chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1,451 @@
|
||||
from .account import (
|
||||
Account,
|
||||
AccountIntegrate,
|
||||
AccountStatus,
|
||||
InvitationCode,
|
||||
Tenant,
|
||||
TenantAccountJoin,
|
||||
TenantAccountRole,
|
||||
TenantStatus,
|
||||
)
|
||||
from .agent import (
|
||||
Agent,
|
||||
AgentConfigDraft,
|
||||
AgentConfigDraftType,
|
||||
AgentConfigRevision,
|
||||
AgentConfigRevisionOperation,
|
||||
AgentConfigSnapshot,
|
||||
AgentConfigVersionKind,
|
||||
AgentDebugConversation,
|
||||
AgentHomeSnapshot,
|
||||
AgentIconType,
|
||||
AgentKind,
|
||||
AgentScope,
|
||||
AgentSource,
|
||||
AgentStatus,
|
||||
AgentWorkingResourceStatus,
|
||||
AgentWorkspace,
|
||||
AgentWorkspaceBinding,
|
||||
AgentWorkspaceOwnerType,
|
||||
WorkflowAgentBindingType,
|
||||
WorkflowAgentNodeBinding,
|
||||
)
|
||||
from .agent_sandbox_usage import AgentSandboxExecution, AgentSandboxUsageEvent
|
||||
from .api_based_extension import APIBasedExtension, APIBasedExtensionPoint
|
||||
from .application_trace import ApplicationTraceBatch, ApplicationTraceInvocation, ApplicationTraceRun
|
||||
from .comment import (
|
||||
WorkflowComment,
|
||||
WorkflowCommentMention,
|
||||
WorkflowCommentReply,
|
||||
)
|
||||
from .credential_permission import CredentialPermission
|
||||
from .credential_permission import CredentialType as CredentialPermissionType
|
||||
from .dataset import (
|
||||
AppDatasetJoin,
|
||||
Dataset,
|
||||
DatasetCollectionBinding,
|
||||
DatasetKeywordTable,
|
||||
DatasetPermission,
|
||||
DatasetPermissionEnum,
|
||||
DatasetProcessRule,
|
||||
DatasetQuery,
|
||||
Document,
|
||||
DocumentSegment,
|
||||
Embedding,
|
||||
ExternalKnowledgeApis,
|
||||
ExternalKnowledgeBindings,
|
||||
TidbAuthBinding,
|
||||
Whitelist,
|
||||
)
|
||||
from .enums import (
|
||||
AppTriggerStatus,
|
||||
AppTriggerType,
|
||||
CreatorUserRole,
|
||||
PermissionEnum,
|
||||
WorkflowRunTriggeredFrom,
|
||||
WorkflowTriggerStatus,
|
||||
)
|
||||
from .execution_extra_content import ExecutionExtraContent, HumanInputContent
|
||||
from .human_input import HumanInputForm, HumanInputFormUploadFile, HumanInputFormUploadToken
|
||||
from .human_input_v2 import (
|
||||
ContactSubjectType,
|
||||
HumanInputContactIdentity,
|
||||
HumanInputEmailProvider,
|
||||
HumanInputExternalContactProfile,
|
||||
HumanInputIMBinding,
|
||||
HumanInputIMChannel,
|
||||
HumanInputIMIdentity,
|
||||
HumanInputIMReconciliationChange,
|
||||
HumanInputIMSyncResult,
|
||||
HumanInputIMSyncRun,
|
||||
HumanInputPlatformContactWorkspaceEntry,
|
||||
IMBindingReconciliationSnapshot,
|
||||
IMIdentityRawPayload,
|
||||
IMIdentityReconciliationSnapshot,
|
||||
IMMessageEvent,
|
||||
IMSyncContactSnapshot,
|
||||
IMSyncDirectoryEntryPayload,
|
||||
IMSyncIdentitySnapshot,
|
||||
)
|
||||
from .knowledge_fs import (
|
||||
AppKnowledgeFSSpaceJoin,
|
||||
KnowledgeFSApiCredential,
|
||||
KnowledgeFSApiCredentialStatus,
|
||||
KnowledgeFSAppSpaceJoinStatus,
|
||||
KnowledgeFSAppSpaceJoinType,
|
||||
KnowledgeFSAuthorizationRevision,
|
||||
KnowledgeFSCapabilityIssuanceAudit,
|
||||
KnowledgeFSCapabilityIssuanceReservation,
|
||||
KnowledgeFSCapabilityIssuanceReservationStatus,
|
||||
KnowledgeFSControlSpace,
|
||||
KnowledgeFSControlSpacePermission,
|
||||
KnowledgeFSControlSpacePermissionRole,
|
||||
KnowledgeFSControlSpacePermissionStatus,
|
||||
KnowledgeFSControlSpaceState,
|
||||
KnowledgeFSControlSpaceVisibility,
|
||||
KnowledgeFSExternalAccessPolicy,
|
||||
KnowledgeFSLifecycleOperation,
|
||||
KnowledgeFSLifecycleOutbox,
|
||||
KnowledgeFSLifecycleOutboxStatus,
|
||||
KnowledgeFSSpaceTagBinding,
|
||||
KnowledgeFSStagedUpload,
|
||||
KnowledgeFSStagedUploadStatus,
|
||||
KnowledgeFSUpgradeDocument,
|
||||
KnowledgeFSUpgradeFileLease,
|
||||
KnowledgeFSUpgradeFileLeaseStatus,
|
||||
KnowledgeFSUpgradeItemStatus,
|
||||
KnowledgeFSUpgradeJob,
|
||||
KnowledgeFSUpgradeJobStatus,
|
||||
KnowledgeFSUpgradeSource,
|
||||
KnowledgeFSUpgradeStage,
|
||||
)
|
||||
from .knowledge_fs_cleanup import (
|
||||
KnowledgeFSCleanupAuthorization,
|
||||
KnowledgeFSCleanupAuthorizationStatus,
|
||||
KnowledgeFSCleanupTarget,
|
||||
)
|
||||
from .knowledge_fs_cutover import (
|
||||
KnowledgeFSMigrationIssue,
|
||||
KnowledgeFSMigrationIssueKind,
|
||||
KnowledgeFSMigrationIssueStatus,
|
||||
KnowledgeFSMigrationQuarantine,
|
||||
KnowledgeFSMigrationQuarantineDisposition,
|
||||
KnowledgeFSMigrationQuarantineKind,
|
||||
KnowledgeFSShadowAuthorizationDecision,
|
||||
KnowledgeFSShadowAuthorizationDiff,
|
||||
KnowledgeFSShadowAuthorizationObservation,
|
||||
KnowledgeFSWorkspaceCutoverLedger,
|
||||
KnowledgeFSWorkspaceCutoverPhase,
|
||||
)
|
||||
from .model import (
|
||||
AccountTrialAppRecord,
|
||||
ApiRequest,
|
||||
ApiToken,
|
||||
App,
|
||||
AppAnnotationHitHistory,
|
||||
AppAnnotationSetting,
|
||||
AppMCPServer,
|
||||
AppMode,
|
||||
AppModelConfig,
|
||||
AppStar,
|
||||
Conversation,
|
||||
DatasetApiTokenBinding,
|
||||
DatasetRetrieverResource,
|
||||
DifySetup,
|
||||
EndUser,
|
||||
ExporleBanner,
|
||||
IconType,
|
||||
InstalledApp,
|
||||
Message,
|
||||
MessageAgentThought,
|
||||
MessageAnnotation,
|
||||
MessageChain,
|
||||
MessageFeedback,
|
||||
MessageFile,
|
||||
OperationLog,
|
||||
RecommendedApp,
|
||||
Site,
|
||||
Tag,
|
||||
TagBinding,
|
||||
TenantCreditPool,
|
||||
TraceAppConfig,
|
||||
TrialApp,
|
||||
UploadFile,
|
||||
)
|
||||
from .oauth import DatasourceOauthParamConfig, DatasourceProvider, OAuthAccessToken
|
||||
from .onboarding import AccountStepByStepTourState
|
||||
from .provider import (
|
||||
LoadBalancingModelConfig,
|
||||
Provider,
|
||||
ProviderModel,
|
||||
ProviderModelSetting,
|
||||
ProviderOrder,
|
||||
ProviderQuotaType,
|
||||
ProviderType,
|
||||
TenantDefaultModel,
|
||||
TenantPreferredModelProvider,
|
||||
)
|
||||
from .resource_access_token import (
|
||||
ResourceAccessToken,
|
||||
ResourceAccessTokenRelation,
|
||||
ResourceAccessTokenResourceType,
|
||||
)
|
||||
from .skill import AgentSkillBinding, Skill, SkillDraftFile, SkillFileKind, SkillFileStorage, SkillVersion
|
||||
from .snippet import CustomizedSnippet, SnippetType
|
||||
from .source import DataSourceApiKeyAuthBinding, DataSourceOauthBinding
|
||||
from .task import CeleryTask, CeleryTaskSet
|
||||
from .tools import (
|
||||
ApiToolProvider,
|
||||
BuiltinToolProvider,
|
||||
ToolConversationVariables,
|
||||
ToolFile,
|
||||
ToolLabelBinding,
|
||||
ToolModelInvoke,
|
||||
WorkflowToolProvider,
|
||||
)
|
||||
from .trigger import (
|
||||
AppTrigger,
|
||||
TriggerOAuthSystemClient,
|
||||
TriggerOAuthTenantClient,
|
||||
TriggerSubscription,
|
||||
WorkflowSchedulePlan,
|
||||
)
|
||||
from .web import PinnedConversation, SavedMessage
|
||||
from .workflow import (
|
||||
ConversationVariable,
|
||||
Workflow,
|
||||
WorkflowAppLog,
|
||||
WorkflowAppLogCreatedFrom,
|
||||
WorkflowArchiveLog,
|
||||
WorkflowKind,
|
||||
WorkflowNodeExecutionModel,
|
||||
WorkflowNodeExecutionOffload,
|
||||
WorkflowNodeExecutionTriggeredFrom,
|
||||
WorkflowPause,
|
||||
WorkflowRun,
|
||||
WorkflowRunArchiveBundle,
|
||||
WorkflowType,
|
||||
WorkflowVersionCounter,
|
||||
resolve_workflow_kind,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"APIBasedExtension",
|
||||
"APIBasedExtensionPoint",
|
||||
"Account",
|
||||
"AccountIntegrate",
|
||||
"AccountStatus",
|
||||
"AccountStepByStepTourState",
|
||||
"AccountTrialAppRecord",
|
||||
"Agent",
|
||||
"AgentConfigDraft",
|
||||
"AgentConfigDraftType",
|
||||
"AgentConfigRevision",
|
||||
"AgentConfigRevisionOperation",
|
||||
"AgentConfigSnapshot",
|
||||
"AgentConfigVersionKind",
|
||||
"AgentDebugConversation",
|
||||
"AgentHomeSnapshot",
|
||||
"AgentIconType",
|
||||
"AgentKind",
|
||||
"AgentSandboxExecution",
|
||||
"AgentSandboxUsageEvent",
|
||||
"AgentScope",
|
||||
"AgentSkillBinding",
|
||||
"AgentSource",
|
||||
"AgentStatus",
|
||||
"AgentWorkingResourceStatus",
|
||||
"AgentWorkspace",
|
||||
"AgentWorkspaceBinding",
|
||||
"AgentWorkspaceOwnerType",
|
||||
"ApiRequest",
|
||||
"ApiToken",
|
||||
"ApiToolProvider",
|
||||
"App",
|
||||
"AppAnnotationHitHistory",
|
||||
"AppAnnotationSetting",
|
||||
"AppDatasetJoin",
|
||||
"AppKnowledgeFSSpaceJoin",
|
||||
"AppMCPServer",
|
||||
"AppMode",
|
||||
"AppModelConfig",
|
||||
"AppStar",
|
||||
"AppTrigger",
|
||||
"AppTriggerStatus",
|
||||
"AppTriggerType",
|
||||
"ApplicationTraceBatch",
|
||||
"ApplicationTraceInvocation",
|
||||
"ApplicationTraceRun",
|
||||
"BuiltinToolProvider",
|
||||
"CeleryTask",
|
||||
"CeleryTaskSet",
|
||||
"ContactSubjectType",
|
||||
"Conversation",
|
||||
"ConversationVariable",
|
||||
"CreatorUserRole",
|
||||
"CredentialPermission",
|
||||
"CredentialPermissionType",
|
||||
"CustomizedSnippet",
|
||||
"DataSourceApiKeyAuthBinding",
|
||||
"DataSourceOauthBinding",
|
||||
"Dataset",
|
||||
"DatasetApiTokenBinding",
|
||||
"DatasetCollectionBinding",
|
||||
"DatasetKeywordTable",
|
||||
"DatasetPermission",
|
||||
"DatasetPermissionEnum",
|
||||
"DatasetProcessRule",
|
||||
"DatasetQuery",
|
||||
"DatasetRetrieverResource",
|
||||
"DatasourceOauthParamConfig",
|
||||
"DatasourceProvider",
|
||||
"DifySetup",
|
||||
"Document",
|
||||
"DocumentSegment",
|
||||
"Embedding",
|
||||
"EndUser",
|
||||
"ExecutionExtraContent",
|
||||
"ExporleBanner",
|
||||
"ExternalKnowledgeApis",
|
||||
"ExternalKnowledgeBindings",
|
||||
"HumanInputContactIdentity",
|
||||
"HumanInputContent",
|
||||
"HumanInputEmailProvider",
|
||||
"HumanInputExternalContactProfile",
|
||||
"HumanInputForm",
|
||||
"HumanInputFormUploadFile",
|
||||
"HumanInputFormUploadToken",
|
||||
"HumanInputIMBinding",
|
||||
"HumanInputIMChannel",
|
||||
"HumanInputIMIdentity",
|
||||
"HumanInputIMReconciliationChange",
|
||||
"HumanInputIMSyncResult",
|
||||
"HumanInputIMSyncRun",
|
||||
"HumanInputPlatformContactWorkspaceEntry",
|
||||
"IMBindingReconciliationSnapshot",
|
||||
"IMIdentityRawPayload",
|
||||
"IMIdentityReconciliationSnapshot",
|
||||
"IMMessageEvent",
|
||||
"IMSyncContactSnapshot",
|
||||
"IMSyncDirectoryEntryPayload",
|
||||
"IMSyncIdentitySnapshot",
|
||||
"IconType",
|
||||
"InstalledApp",
|
||||
"InvitationCode",
|
||||
"KnowledgeFSApiCredential",
|
||||
"KnowledgeFSApiCredentialStatus",
|
||||
"KnowledgeFSAppSpaceJoinStatus",
|
||||
"KnowledgeFSAppSpaceJoinType",
|
||||
"KnowledgeFSAuthorizationRevision",
|
||||
"KnowledgeFSCapabilityIssuanceAudit",
|
||||
"KnowledgeFSCapabilityIssuanceReservation",
|
||||
"KnowledgeFSCapabilityIssuanceReservationStatus",
|
||||
"KnowledgeFSCleanupAuthorization",
|
||||
"KnowledgeFSCleanupAuthorizationStatus",
|
||||
"KnowledgeFSCleanupTarget",
|
||||
"KnowledgeFSControlSpace",
|
||||
"KnowledgeFSControlSpacePermission",
|
||||
"KnowledgeFSControlSpacePermissionRole",
|
||||
"KnowledgeFSControlSpacePermissionStatus",
|
||||
"KnowledgeFSControlSpaceState",
|
||||
"KnowledgeFSControlSpaceVisibility",
|
||||
"KnowledgeFSExternalAccessPolicy",
|
||||
"KnowledgeFSLifecycleOperation",
|
||||
"KnowledgeFSLifecycleOutbox",
|
||||
"KnowledgeFSLifecycleOutboxStatus",
|
||||
"KnowledgeFSMigrationIssue",
|
||||
"KnowledgeFSMigrationIssueKind",
|
||||
"KnowledgeFSMigrationIssueStatus",
|
||||
"KnowledgeFSMigrationQuarantine",
|
||||
"KnowledgeFSMigrationQuarantineDisposition",
|
||||
"KnowledgeFSMigrationQuarantineKind",
|
||||
"KnowledgeFSShadowAuthorizationDecision",
|
||||
"KnowledgeFSShadowAuthorizationDiff",
|
||||
"KnowledgeFSShadowAuthorizationObservation",
|
||||
"KnowledgeFSSpaceTagBinding",
|
||||
"KnowledgeFSStagedUpload",
|
||||
"KnowledgeFSStagedUploadStatus",
|
||||
"KnowledgeFSUpgradeDocument",
|
||||
"KnowledgeFSUpgradeFileLease",
|
||||
"KnowledgeFSUpgradeFileLeaseStatus",
|
||||
"KnowledgeFSUpgradeItemStatus",
|
||||
"KnowledgeFSUpgradeJob",
|
||||
"KnowledgeFSUpgradeJobStatus",
|
||||
"KnowledgeFSUpgradeSource",
|
||||
"KnowledgeFSUpgradeStage",
|
||||
"KnowledgeFSWorkspaceCutoverLedger",
|
||||
"KnowledgeFSWorkspaceCutoverPhase",
|
||||
"LoadBalancingModelConfig",
|
||||
"Message",
|
||||
"MessageAgentThought",
|
||||
"MessageAnnotation",
|
||||
"MessageChain",
|
||||
"MessageFeedback",
|
||||
"MessageFile",
|
||||
"OAuthAccessToken",
|
||||
"OperationLog",
|
||||
"PermissionEnum",
|
||||
"PinnedConversation",
|
||||
"Provider",
|
||||
"ProviderModel",
|
||||
"ProviderModelSetting",
|
||||
"ProviderOrder",
|
||||
"ProviderQuotaType",
|
||||
"ProviderType",
|
||||
"RecommendedApp",
|
||||
"ResourceAccessToken",
|
||||
"ResourceAccessTokenRelation",
|
||||
"ResourceAccessTokenResourceType",
|
||||
"SavedMessage",
|
||||
"Site",
|
||||
"Skill",
|
||||
"SkillDraftFile",
|
||||
"SkillFileKind",
|
||||
"SkillFileStorage",
|
||||
"SkillVersion",
|
||||
"SnippetType",
|
||||
"Tag",
|
||||
"TagBinding",
|
||||
"Tenant",
|
||||
"TenantAccountJoin",
|
||||
"TenantAccountRole",
|
||||
"TenantCreditPool",
|
||||
"TenantDefaultModel",
|
||||
"TenantPreferredModelProvider",
|
||||
"TenantStatus",
|
||||
"TidbAuthBinding",
|
||||
"ToolConversationVariables",
|
||||
"ToolFile",
|
||||
"ToolLabelBinding",
|
||||
"ToolModelInvoke",
|
||||
"TraceAppConfig",
|
||||
"TrialApp",
|
||||
"TriggerOAuthSystemClient",
|
||||
"TriggerOAuthTenantClient",
|
||||
"TriggerSubscription",
|
||||
"UploadFile",
|
||||
"Whitelist",
|
||||
"Workflow",
|
||||
"WorkflowAgentBindingType",
|
||||
"WorkflowAgentNodeBinding",
|
||||
"WorkflowAppLog",
|
||||
"WorkflowAppLogCreatedFrom",
|
||||
"WorkflowArchiveLog",
|
||||
"WorkflowComment",
|
||||
"WorkflowCommentMention",
|
||||
"WorkflowCommentReply",
|
||||
"WorkflowKind",
|
||||
"WorkflowNodeExecutionModel",
|
||||
"WorkflowNodeExecutionOffload",
|
||||
"WorkflowNodeExecutionTriggeredFrom",
|
||||
"WorkflowPause",
|
||||
"WorkflowRun",
|
||||
"WorkflowRunArchiveBundle",
|
||||
"WorkflowRunTriggeredFrom",
|
||||
"WorkflowSchedulePlan",
|
||||
"WorkflowToolProvider",
|
||||
"WorkflowTriggerStatus",
|
||||
"WorkflowType",
|
||||
"WorkflowVersionCounter",
|
||||
"resolve_workflow_kind",
|
||||
]
|
||||
@@ -0,0 +1,20 @@
|
||||
"""All these exceptions are not meant to be caught by callers."""
|
||||
|
||||
|
||||
class WorkflowDataError(Exception):
|
||||
"""Base class for all workflow data related exceptions.
|
||||
|
||||
This should be used to indicate issues with workflow data integrity, such as
|
||||
no `graph` configuration, missing `nodes` field in `graph` configuration, or
|
||||
similar issues.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class NodeNotFoundError(WorkflowDataError):
|
||||
"""Raised when a node with the specified ID is not found in the workflow."""
|
||||
|
||||
def __init__(self, node_id: str):
|
||||
super().__init__(f"Node with ID '{node_id}' not found in the workflow.")
|
||||
self.node_id = node_id
|
||||
@@ -0,0 +1,383 @@
|
||||
import enum
|
||||
import json
|
||||
from dataclasses import field
|
||||
from datetime import datetime
|
||||
from typing import TypedDict
|
||||
from uuid import uuid4
|
||||
from warnings import deprecated
|
||||
|
||||
import sqlalchemy as sa
|
||||
from flask_login import UserMixin
|
||||
from sqlalchemy import DateTime, String, func, select
|
||||
from sqlalchemy.orm import Mapped, Session, mapped_column
|
||||
|
||||
from configs import dify_config
|
||||
from enums.account import TenantAccountRole
|
||||
|
||||
from .base import TypeBase
|
||||
from .types import EnumText, LongText, StringUUID
|
||||
|
||||
|
||||
class AccountStatus(enum.StrEnum):
|
||||
PENDING = "pending"
|
||||
UNINITIALIZED = "uninitialized"
|
||||
ACTIVE = "active"
|
||||
BANNED = "banned"
|
||||
CLOSED = "closed"
|
||||
|
||||
|
||||
class Account(UserMixin, TypeBase):
|
||||
__tablename__ = "accounts"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="account_pkey"),
|
||||
sa.Index("account_email_idx", "email"),
|
||||
sa.Index("account_normalized_email_idx", "normalized_email"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
name: Mapped[str] = mapped_column(String(255))
|
||||
email: Mapped[str] = mapped_column(String(255))
|
||||
normalized_email: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
password: Mapped[str | None] = mapped_column(String(255), default=None)
|
||||
password_salt: Mapped[str | None] = mapped_column(String(255), default=None)
|
||||
avatar: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
interface_language: Mapped[str | None] = mapped_column(String(255), default=None)
|
||||
interface_theme: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
timezone: Mapped[str | None] = mapped_column(String(255), default=None)
|
||||
last_login_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
last_login_ip: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
last_active_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, server_default=func.current_timestamp(), nullable=False, init=False
|
||||
)
|
||||
status: Mapped[AccountStatus] = mapped_column(EnumText(AccountStatus, length=16), default=AccountStatus.ACTIVE)
|
||||
initialized_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, server_default=func.current_timestamp(), nullable=False, init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, server_default=func.current_timestamp(), nullable=False, init=False, onupdate=func.current_timestamp()
|
||||
)
|
||||
|
||||
role: TenantAccountRole | None = field(default=None, init=False)
|
||||
_current_tenant: "Tenant | None" = field(default=None, init=False)
|
||||
|
||||
@property
|
||||
def is_password_set(self):
|
||||
return self.password is not None
|
||||
|
||||
@property
|
||||
def current_tenant(self):
|
||||
return self._current_tenant
|
||||
|
||||
def set_current_tenant_with_session(self, tenant: "Tenant", *, session: Session) -> None:
|
||||
"""Set the current tenant and role using the caller-owned session."""
|
||||
tenant_join_query = select(TenantAccountJoin).where(
|
||||
TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == self.id
|
||||
)
|
||||
tenant_join = session.scalar(tenant_join_query)
|
||||
tenant_query = select(Tenant).where(Tenant.id == tenant.id)
|
||||
tenant_reloaded = session.scalars(tenant_query).one()
|
||||
|
||||
if tenant_join:
|
||||
self.role = TenantAccountRole(tenant_join.role)
|
||||
self._current_tenant = tenant_reloaded
|
||||
return
|
||||
self._current_tenant = None
|
||||
|
||||
@property
|
||||
def current_tenant_id(self) -> str | None:
|
||||
return self._current_tenant.id if self._current_tenant else None
|
||||
|
||||
def set_tenant_id_with_session(self, tenant_id: str, *, session: Session) -> None:
|
||||
"""Set the current tenant by id using the caller-owned session."""
|
||||
query = select(Tenant, TenantAccountJoin).where(
|
||||
Tenant.id == tenant_id, TenantAccountJoin.tenant_id == Tenant.id, TenantAccountJoin.account_id == self.id
|
||||
)
|
||||
tenant_account_join = session.execute(query).first()
|
||||
if not tenant_account_join:
|
||||
return
|
||||
tenant, join = tenant_account_join
|
||||
self.role = TenantAccountRole(join.role)
|
||||
self._current_tenant = tenant
|
||||
|
||||
@property
|
||||
def current_role(self):
|
||||
return self.role
|
||||
|
||||
def get_status(self) -> AccountStatus:
|
||||
return self.status
|
||||
|
||||
# check current_user.current_tenant.current_role in ['admin', 'owner']
|
||||
@property
|
||||
def is_admin_or_owner(self):
|
||||
if dify_config.RBAC_ENABLED:
|
||||
return True
|
||||
return TenantAccountRole.is_privileged_role(self.role)
|
||||
|
||||
@property
|
||||
def is_admin(self):
|
||||
if dify_config.RBAC_ENABLED:
|
||||
return True
|
||||
return TenantAccountRole.is_admin_role(self.role)
|
||||
|
||||
@property
|
||||
@deprecated("Use has_edit_permission instead.")
|
||||
def is_editor(self):
|
||||
"""Determines if the account has edit permissions in their current tenant (workspace).
|
||||
|
||||
This property checks if the current role has editing privileges, which includes:
|
||||
- `OWNER`
|
||||
- `ADMIN`
|
||||
- `EDITOR`
|
||||
|
||||
Note: This checks for any role with editing permission, not just the 'EDITOR' role specifically.
|
||||
"""
|
||||
return self.has_edit_permission
|
||||
|
||||
@property
|
||||
def has_edit_permission(self):
|
||||
"""Determines if the account has editing permissions in their current tenant (workspace).
|
||||
|
||||
This property checks if the current role has editing privileges, which includes:
|
||||
- `OWNER`
|
||||
- `ADMIN`
|
||||
- `EDITOR`
|
||||
"""
|
||||
if dify_config.RBAC_ENABLED:
|
||||
return True
|
||||
return TenantAccountRole.is_editing_role(self.role)
|
||||
|
||||
@property
|
||||
def is_dataset_editor(self):
|
||||
if dify_config.RBAC_ENABLED:
|
||||
return True
|
||||
return TenantAccountRole.is_dataset_edit_role(self.role)
|
||||
|
||||
@property
|
||||
def is_dataset_operator(self):
|
||||
if dify_config.RBAC_ENABLED:
|
||||
return True
|
||||
return self.role == TenantAccountRole.DATASET_OPERATOR
|
||||
|
||||
|
||||
class TenantStatus(enum.StrEnum):
|
||||
NORMAL = "normal"
|
||||
ARCHIVE = "archive"
|
||||
|
||||
|
||||
class TenantCustomConfigDict(TypedDict, total=False):
|
||||
remove_webapp_brand: bool
|
||||
replace_webapp_logo: str | None
|
||||
|
||||
|
||||
class Tenant(TypeBase):
|
||||
__tablename__ = "tenants"
|
||||
__table_args__ = (sa.PrimaryKeyConstraint("id", name="tenant_pkey"),)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
name: Mapped[str] = mapped_column(String(255))
|
||||
encrypt_public_key: Mapped[str | None] = mapped_column(LongText, default=None)
|
||||
plan: Mapped[str] = mapped_column(String(255), default="basic")
|
||||
status: Mapped[TenantStatus] = mapped_column(EnumText(TenantStatus, length=255), default=TenantStatus.NORMAL)
|
||||
custom_config: Mapped[str | None] = mapped_column(LongText, default=None)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, server_default=func.current_timestamp(), nullable=False, init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, server_default=func.current_timestamp(), init=False, onupdate=func.current_timestamp()
|
||||
)
|
||||
|
||||
def get_accounts(self, *, session: Session) -> list[Account]:
|
||||
return list(
|
||||
session.scalars(
|
||||
select(Account).where(
|
||||
Account.id == TenantAccountJoin.account_id, TenantAccountJoin.tenant_id == self.id
|
||||
)
|
||||
).all()
|
||||
)
|
||||
|
||||
@property
|
||||
def custom_config_dict(self) -> TenantCustomConfigDict:
|
||||
return json.loads(self.custom_config) if self.custom_config else {}
|
||||
|
||||
@custom_config_dict.setter
|
||||
def custom_config_dict(self, value: TenantCustomConfigDict) -> None:
|
||||
self.custom_config = json.dumps(value)
|
||||
|
||||
|
||||
class TenantAccountJoin(TypeBase):
|
||||
__tablename__ = "tenant_account_joins"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="tenant_account_join_pkey"),
|
||||
sa.Index("tenant_account_join_account_id_idx", "account_id"),
|
||||
sa.Index("tenant_account_join_tenant_id_idx", "tenant_id"),
|
||||
sa.UniqueConstraint("tenant_id", "account_id", name="unique_tenant_account_join"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID)
|
||||
account_id: Mapped[str] = mapped_column(StringUUID)
|
||||
current: Mapped[bool] = mapped_column(sa.Boolean, default=False)
|
||||
role: Mapped[TenantAccountRole] = mapped_column(
|
||||
EnumText(TenantAccountRole, length=16), default=TenantAccountRole.NORMAL
|
||||
)
|
||||
invited_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, server_default=func.current_timestamp(), nullable=False, init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, server_default=func.current_timestamp(), nullable=False, init=False, onupdate=func.current_timestamp()
|
||||
)
|
||||
last_opened_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
|
||||
|
||||
class AccountIntegrate(TypeBase):
|
||||
__tablename__ = "account_integrates"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="account_integrate_pkey"),
|
||||
sa.UniqueConstraint("account_id", "provider", name="unique_account_provider"),
|
||||
sa.UniqueConstraint("provider", "open_id", name="unique_provider_open_id"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
account_id: Mapped[str] = mapped_column(StringUUID)
|
||||
provider: Mapped[str] = mapped_column(String(16))
|
||||
open_id: Mapped[str] = mapped_column(String(255))
|
||||
encrypted_token: Mapped[str] = mapped_column(String(255))
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, server_default=func.current_timestamp(), nullable=False, init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, server_default=func.current_timestamp(), nullable=False, init=False, onupdate=func.current_timestamp()
|
||||
)
|
||||
|
||||
|
||||
class InvitationCodeStatus(enum.StrEnum):
|
||||
UNUSED = "unused"
|
||||
USED = "used"
|
||||
|
||||
|
||||
class InvitationCode(TypeBase):
|
||||
__tablename__ = "invitation_codes"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="invitation_code_pkey"),
|
||||
sa.Index("invitation_codes_batch_idx", "batch"),
|
||||
sa.Index("invitation_codes_code_idx", "code", "status"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(sa.Integer, init=False)
|
||||
batch: Mapped[str] = mapped_column(String(255))
|
||||
code: Mapped[str] = mapped_column(String(32))
|
||||
status: Mapped[InvitationCodeStatus] = mapped_column(
|
||||
EnumText(InvitationCodeStatus, length=16),
|
||||
default=InvitationCodeStatus.UNUSED,
|
||||
)
|
||||
used_at: Mapped[datetime | None] = mapped_column(DateTime, default=None)
|
||||
used_by_tenant_id: Mapped[str | None] = mapped_column(StringUUID, default=None)
|
||||
used_by_account_id: Mapped[str | None] = mapped_column(StringUUID, default=None)
|
||||
deprecated_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, server_default=sa.func.current_timestamp(), nullable=False, init=False
|
||||
)
|
||||
|
||||
|
||||
class TenantPluginInstallPermission(enum.StrEnum):
|
||||
EVERYONE = "everyone"
|
||||
ADMINS = "admins"
|
||||
NOBODY = "noone"
|
||||
|
||||
|
||||
class TenantPluginDebugPermission(enum.StrEnum):
|
||||
EVERYONE = "everyone"
|
||||
ADMINS = "admins"
|
||||
NOBODY = "noone"
|
||||
|
||||
|
||||
class TenantPluginPermission(TypeBase):
|
||||
__tablename__ = "account_plugin_permissions"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="account_plugin_permission_pkey"),
|
||||
sa.UniqueConstraint("tenant_id", name="unique_tenant_plugin"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
install_permission: Mapped[TenantPluginInstallPermission] = mapped_column(
|
||||
EnumText(TenantPluginInstallPermission, length=16),
|
||||
nullable=False,
|
||||
default=TenantPluginInstallPermission.ADMINS,
|
||||
)
|
||||
debug_permission: Mapped[TenantPluginDebugPermission] = mapped_column(
|
||||
EnumText(TenantPluginDebugPermission, length=16),
|
||||
nullable=False,
|
||||
default=TenantPluginDebugPermission.NOBODY,
|
||||
)
|
||||
|
||||
|
||||
class TenantPluginAutoUpgradeCategory(enum.StrEnum):
|
||||
TOOL = "tool"
|
||||
MODEL = "model"
|
||||
EXTENSION = "extension"
|
||||
AGENT_STRATEGY = "agent-strategy"
|
||||
DATASOURCE = "datasource"
|
||||
TRIGGER = "trigger"
|
||||
|
||||
|
||||
class TenantPluginAutoUpgradeStrategySetting(enum.StrEnum):
|
||||
DISABLED = "disabled"
|
||||
FIX_ONLY = "fix_only"
|
||||
LATEST = "latest"
|
||||
|
||||
|
||||
class TenantPluginAutoUpgradeMode(enum.StrEnum):
|
||||
ALL = "all"
|
||||
PARTIAL = "partial"
|
||||
EXCLUDE = "exclude"
|
||||
|
||||
|
||||
class TenantPluginAutoUpgradeStrategy(TypeBase):
|
||||
__tablename__ = "tenant_plugin_auto_upgrade_strategies"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="tenant_plugin_auto_upgrade_strategy_pkey"),
|
||||
sa.UniqueConstraint("tenant_id", "category", name="unique_tenant_plugin_auto_upgrade_strategy"),
|
||||
sa.Index("idx_tenant_plugin_auto_upgrade_strategy_time", "upgrade_time_of_day"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
category: Mapped[TenantPluginAutoUpgradeCategory] = mapped_column(
|
||||
EnumText(TenantPluginAutoUpgradeCategory, length=32),
|
||||
nullable=False,
|
||||
default=TenantPluginAutoUpgradeCategory.TOOL,
|
||||
)
|
||||
strategy_setting: Mapped[TenantPluginAutoUpgradeStrategySetting] = mapped_column(
|
||||
EnumText(TenantPluginAutoUpgradeStrategySetting, length=16),
|
||||
nullable=False,
|
||||
default=TenantPluginAutoUpgradeStrategySetting.FIX_ONLY,
|
||||
)
|
||||
upgrade_mode: Mapped[TenantPluginAutoUpgradeMode] = mapped_column(
|
||||
EnumText(TenantPluginAutoUpgradeMode, length=16),
|
||||
nullable=False,
|
||||
default=TenantPluginAutoUpgradeMode.EXCLUDE,
|
||||
)
|
||||
exclude_plugins: Mapped[list[str]] = mapped_column(sa.JSON, nullable=False, default_factory=list)
|
||||
include_plugins: Mapped[list[str]] = mapped_column(sa.JSON, nullable=False, default_factory=list)
|
||||
upgrade_time_of_day: Mapped[int] = mapped_column(sa.Integer, nullable=False, default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False, onupdate=func.current_timestamp()
|
||||
)
|
||||
@@ -0,0 +1,599 @@
|
||||
import json
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import DateTime, Index, String, UniqueConstraint, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from libs.uuid_utils import uuidv7
|
||||
|
||||
from .agent_config_entities import AgentSoulConfig, WorkflowNodeJobConfig
|
||||
from .base import DefaultFieldsDCMixin, TypeBase
|
||||
from .types import EnumText, JSONModelColumn, LongText, StringUUID
|
||||
|
||||
|
||||
class AgentKind(StrEnum):
|
||||
"""Agent implementation family.
|
||||
|
||||
This leaves room for future non-Dify agent implementations while keeping
|
||||
the current roster/workflow APIs scoped to Dify Agent.
|
||||
"""
|
||||
|
||||
# Native Agent backed by the Dify Agent runtime/protocol.
|
||||
DIFY_AGENT = "dify_agent"
|
||||
|
||||
|
||||
class AgentScope(StrEnum):
|
||||
"""Visibility and lifecycle scope of an Agent record."""
|
||||
|
||||
# Workspace-visible Agent that can be reused from Agent Roster.
|
||||
ROSTER = "roster"
|
||||
# Temporary workflow-local Agent created inside one draft workflow node.
|
||||
WORKFLOW_ONLY = "workflow_only"
|
||||
|
||||
|
||||
class AgentSource(StrEnum):
|
||||
"""Origin that created or imported the Agent."""
|
||||
|
||||
# Created directly as a reusable Agent Roster asset.
|
||||
ROSTER = "roster"
|
||||
# Created from an Agent App composer.
|
||||
AGENT_APP = "agent_app"
|
||||
# Created from a Workflow Agent Composer flow.
|
||||
WORKFLOW = "workflow"
|
||||
# Imported from an external artifact or future CLI/export flow.
|
||||
IMPORTED = "imported"
|
||||
# Created by system bootstrap or managed templates.
|
||||
SYSTEM = "system"
|
||||
|
||||
|
||||
# Source records provenance. Product capability is determined by scope and
|
||||
# backing ownership, so imported resources participate in both supported Agent
|
||||
# surfaces instead of being filtered out by their origin.
|
||||
APP_BACKED_AGENT_SOURCES = (AgentSource.AGENT_APP, AgentSource.IMPORTED)
|
||||
WORKFLOW_ONLY_AGENT_SOURCES = (AgentSource.WORKFLOW, AgentSource.IMPORTED)
|
||||
|
||||
|
||||
class AgentIconType(StrEnum):
|
||||
"""Supported icon storage formats for Agent roster entries."""
|
||||
|
||||
# ``icon`` stores an uploaded image reference.
|
||||
IMAGE = "image"
|
||||
# ``icon`` stores an emoji character.
|
||||
EMOJI = "emoji"
|
||||
# ``icon`` stores an external image URL.
|
||||
LINK = "link"
|
||||
|
||||
|
||||
class AgentStatus(StrEnum):
|
||||
"""Soft lifecycle state for Agent records."""
|
||||
|
||||
# Available for roster lookup, composer use, and workflow binding.
|
||||
ACTIVE = "active"
|
||||
# Hidden from active roster queries while preserving historical bindings.
|
||||
ARCHIVED = "archived"
|
||||
|
||||
|
||||
class AgentConfigRevisionOperation(StrEnum):
|
||||
"""Audit operation recorded for Agent Soul version/revision changes."""
|
||||
|
||||
# Initial version creation for a new Agent.
|
||||
CREATE_VERSION = "create_version"
|
||||
# Saves over the user-facing current version by creating a replacement snapshot.
|
||||
SAVE_CURRENT_VERSION = "save_current_version"
|
||||
# Creates a new semantic version for the same Agent.
|
||||
SAVE_NEW_VERSION = "save_new_version"
|
||||
# Saves composer content into a brand-new roster Agent.
|
||||
SAVE_NEW_AGENT = "save_new_agent"
|
||||
# Promotes a workflow-only Agent into the reusable Agent Roster.
|
||||
SAVE_TO_ROSTER = "save_to_roster"
|
||||
# Switches the Agent's current published config back to an existing version.
|
||||
RESTORE_VERSION = "restore_version"
|
||||
# Publishes the editable Agent Soul draft as a new immutable version.
|
||||
PUBLISH_DRAFT = "publish_draft"
|
||||
# Seeds a new Agent from a portable DSL package.
|
||||
IMPORT_PACKAGE = "import_package"
|
||||
|
||||
|
||||
# Revisions that add an entry to an Agent App's user-facing version history.
|
||||
# Imported Agent Apps also list the version their package seeded.
|
||||
AGENT_APP_VERSION_OPERATIONS = frozenset(
|
||||
{
|
||||
AgentConfigRevisionOperation.PUBLISH_DRAFT,
|
||||
AgentConfigRevisionOperation.SAVE_NEW_VERSION,
|
||||
AgentConfigRevisionOperation.SAVE_TO_ROSTER,
|
||||
AgentConfigRevisionOperation.RESTORE_VERSION,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class AgentConfigDraftType(StrEnum):
|
||||
"""Editable Agent Soul draft workspace type."""
|
||||
|
||||
# Shared Agent Console draft edited by users before publishing.
|
||||
DRAFT = "draft"
|
||||
# Per-editor build draft mutated during debug/build mode.
|
||||
DEBUG_BUILD = "debug_build"
|
||||
|
||||
|
||||
class WorkflowAgentBindingType(StrEnum):
|
||||
"""How a workflow node is bound to an Agent."""
|
||||
|
||||
# Node uses a reusable Agent from the workspace roster.
|
||||
ROSTER_AGENT = "roster_agent"
|
||||
# Node owns a workflow-only Agent that is not visible in the roster.
|
||||
INLINE_AGENT = "inline_agent"
|
||||
|
||||
|
||||
class AgentWorkingResourceStatus(StrEnum):
|
||||
"""Product lifecycle state for a persistent working-environment resource."""
|
||||
|
||||
ACTIVE = "active"
|
||||
RETIRED = "retired"
|
||||
|
||||
|
||||
class AgentWorkspaceOwnerType(StrEnum):
|
||||
"""Product scope that owns a Workspace."""
|
||||
|
||||
WORKFLOW_RUN = "workflow_run"
|
||||
CONVERSATION = "conversation"
|
||||
BUILD_DRAFT = "build_draft"
|
||||
|
||||
|
||||
class AgentConfigVersionKind(StrEnum):
|
||||
SNAPSHOT = "snapshot"
|
||||
DRAFT = "draft"
|
||||
BUILD_DRAFT = "build_draft"
|
||||
|
||||
|
||||
class AgentDefaultFieldsDCMixin(DefaultFieldsDCMixin, kw_only=True):
|
||||
"""Dataclass defaults that retain the established explicit-ID constructor contract for agent models."""
|
||||
|
||||
__abstract__ = True
|
||||
|
||||
id: Mapped[str] = mapped_column( # type: ignore[override]
|
||||
StringUUID,
|
||||
primary_key=True,
|
||||
insert_default=lambda: str(uuidv7()),
|
||||
default_factory=lambda: str(uuidv7()),
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column( # type: ignore[override]
|
||||
DateTime,
|
||||
nullable=False,
|
||||
insert_default=naive_utc_now,
|
||||
default_factory=naive_utc_now,
|
||||
server_default=func.current_timestamp(),
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column( # type: ignore[override]
|
||||
DateTime,
|
||||
nullable=False,
|
||||
insert_default=naive_utc_now,
|
||||
default_factory=naive_utc_now,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
)
|
||||
|
||||
|
||||
class Agent(AgentDefaultFieldsDCMixin, TypeBase, kw_only=True):
|
||||
"""Agent Soul and source lineage; ``AgentWorkspaceBinding.id`` identifies each materialized participant."""
|
||||
|
||||
__tablename__ = "agents"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="agent_pkey"),
|
||||
UniqueConstraint("tenant_id", "roster_unique_name"),
|
||||
Index("agent_tenant_updated_at_idx", "tenant_id", "updated_at"),
|
||||
Index("agent_tenant_scope_idx", "tenant_id", "scope"),
|
||||
Index("agent_tenant_workflow_id_idx", "tenant_id", "workflow_id"),
|
||||
Index("agent_tenant_app_id_idx", "tenant_id", "app_id"),
|
||||
Index("agent_tenant_backing_app_id_idx", "tenant_id", "backing_app_id"),
|
||||
Index("agent_active_config_snapshot_id_idx", "active_config_snapshot_id"),
|
||||
Index(
|
||||
"agent_tenant_invitable_idx",
|
||||
"tenant_id",
|
||||
"scope",
|
||||
"status",
|
||||
"active_config_has_model",
|
||||
"updated_at",
|
||||
),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
description: Mapped[str] = mapped_column(LongText, nullable=False, default="")
|
||||
role: Mapped[str] = mapped_column(String(255), nullable=False, default="")
|
||||
icon_type: Mapped[AgentIconType | None] = mapped_column(
|
||||
EnumText(AgentIconType, length=32), nullable=True, default=None
|
||||
)
|
||||
icon: Mapped[str | None] = mapped_column(
|
||||
String(255),
|
||||
nullable=True,
|
||||
default=None,
|
||||
comment="Icon payload interpreted by icon_type: emoji character, image file id, or external URL.",
|
||||
)
|
||||
icon_background: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
agent_kind: Mapped[AgentKind] = mapped_column(
|
||||
EnumText(AgentKind, length=32), nullable=False, default=AgentKind.DIFY_AGENT
|
||||
)
|
||||
scope: Mapped[AgentScope] = mapped_column(EnumText(AgentScope, length=32), nullable=False)
|
||||
source: Mapped[AgentSource] = mapped_column(EnumText(AgentSource, length=32), nullable=False)
|
||||
app_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
backing_app_id: Mapped[str | None] = mapped_column(
|
||||
StringUUID,
|
||||
nullable=True,
|
||||
default=None,
|
||||
comment=(
|
||||
"Runtime Agent App used for chat/log/monitoring. For workflow-only agents, "
|
||||
"app_id remains the parent workflow app id and this points to the hidden backing app."
|
||||
),
|
||||
)
|
||||
workflow_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
workflow_node_id: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
active_config_snapshot_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
active_config_has_model: Mapped[bool] = mapped_column(
|
||||
sa.Boolean, nullable=False, default=False, server_default=sa.false()
|
||||
)
|
||||
active_config_is_published: Mapped[bool] = mapped_column(
|
||||
sa.Boolean,
|
||||
nullable=False,
|
||||
default=False,
|
||||
server_default=sa.false(),
|
||||
comment=(
|
||||
"Whether the normal shared Agent draft has been published into the active config snapshot. "
|
||||
"User-scoped debug drafts do not affect this flag."
|
||||
),
|
||||
)
|
||||
status: Mapped[AgentStatus] = mapped_column(
|
||||
EnumText(AgentStatus, length=32), nullable=False, default=AgentStatus.ACTIVE
|
||||
)
|
||||
roster_unique_name: Mapped[str | None] = mapped_column(
|
||||
String(255),
|
||||
sa.Computed("CASE WHEN scope = 'roster' AND status = 'active' THEN name ELSE NULL END"),
|
||||
nullable=True,
|
||||
init=False,
|
||||
)
|
||||
created_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
updated_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
archived_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
archived_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
|
||||
|
||||
class AgentHomeSnapshot(TypeBase, kw_only=True):
|
||||
"""Append-only mapping from one Agent-owned Home identity to its backend ref.
|
||||
|
||||
Product tables reference ``id``. ``snapshot_ref`` remains an opaque
|
||||
deployment-specific handle and is only consumed at Dify Agent boundaries.
|
||||
Snapshot bytes and ``snapshot_ref`` are immutable. Lifecycle metadata can
|
||||
transition ACTIVE -> RETIRED; successful physical collection deletes row.
|
||||
"""
|
||||
|
||||
__tablename__ = "agent_home_snapshots"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="agent_home_snapshot_pkey"),
|
||||
Index("agent_home_snapshot_tenant_agent_idx", "tenant_id", "agent_id"),
|
||||
Index("agent_home_snapshot_status_retired_idx", "status", "retired_at"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID,
|
||||
insert_default=lambda: str(uuidv7()),
|
||||
default_factory=lambda: str(uuidv7()),
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
agent_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
snapshot_ref: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
status: Mapped[AgentWorkingResourceStatus] = mapped_column(
|
||||
EnumText(AgentWorkingResourceStatus, length=32),
|
||||
nullable=False,
|
||||
default=AgentWorkingResourceStatus.ACTIVE,
|
||||
server_default=AgentWorkingResourceStatus.ACTIVE.value,
|
||||
)
|
||||
retired_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
insert_default=naive_utc_now,
|
||||
default_factory=naive_utc_now,
|
||||
server_default=func.current_timestamp(),
|
||||
)
|
||||
|
||||
|
||||
class AgentDebugConversation(AgentDefaultFieldsDCMixin, TypeBase, kw_only=True):
|
||||
"""Current console Conversation pointer for one account and draft surface.
|
||||
|
||||
This row owns no Binding or runtime. A Preview Conversation holds its
|
||||
CONVERSATION Binding pointer, while a DEBUG_BUILD AgentConfigDraft holds its
|
||||
BUILD_DRAFT Binding pointer.
|
||||
"""
|
||||
|
||||
__tablename__ = "agent_debug_conversations"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="agent_debug_conversation_pkey"),
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"agent_id",
|
||||
"account_id",
|
||||
"draft_type",
|
||||
name="agent_debug_conversation_agent_account_draft_type_unique",
|
||||
),
|
||||
Index("agent_debug_conversation_conversation_idx", "conversation_id"),
|
||||
Index("agent_debug_conversation_account_idx", "tenant_id", "account_id"),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
agent_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
account_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
draft_type: Mapped[AgentConfigDraftType] = mapped_column(
|
||||
EnumText(AgentConfigDraftType, length=32),
|
||||
nullable=False,
|
||||
default=AgentConfigDraftType.DEBUG_BUILD,
|
||||
server_default=sa.text("'debug_build'"),
|
||||
)
|
||||
conversation_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
|
||||
|
||||
class AgentConfigDraft(AgentDefaultFieldsDCMixin, TypeBase, kw_only=True):
|
||||
"""Editable Agent Soul draft separated from immutable published snapshots.
|
||||
|
||||
A DEBUG_BUILD draft owns its materialized participant through
|
||||
``agent_workspace_binding_id``. Normal drafts leave that pointer unset.
|
||||
"""
|
||||
|
||||
__tablename__ = "agent_config_drafts"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="agent_config_draft_pkey"),
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"agent_id",
|
||||
"draft_type",
|
||||
"draft_owner_key",
|
||||
name="agent_config_draft_agent_type_account_unique",
|
||||
),
|
||||
Index("agent_config_draft_tenant_agent_idx", "tenant_id", "agent_id"),
|
||||
Index("agent_config_draft_base_snapshot_idx", "tenant_id", "base_snapshot_id"),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
agent_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
draft_type: Mapped[AgentConfigDraftType] = mapped_column(EnumText(AgentConfigDraftType, length=32), nullable=False)
|
||||
account_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
draft_owner_key: Mapped[str] = mapped_column(String(255), nullable=False, default="")
|
||||
base_snapshot_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
home_snapshot_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
agent_workspace_binding_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
config_snapshot: Mapped[Any] = mapped_column(JSONModelColumn(AgentSoulConfig), nullable=False)
|
||||
created_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
updated_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
|
||||
@property
|
||||
def config_snapshot_dict(self) -> dict[str, Any]:
|
||||
if not self.config_snapshot:
|
||||
return {}
|
||||
if hasattr(self.config_snapshot, "model_dump"):
|
||||
return self.config_snapshot.model_dump(mode="json")
|
||||
if isinstance(self.config_snapshot, str):
|
||||
return json.loads(self.config_snapshot)
|
||||
return dict(self.config_snapshot)
|
||||
|
||||
|
||||
class AgentConfigSnapshot(AgentDefaultFieldsDCMixin, TypeBase, kw_only=True):
|
||||
"""Immutable Agent Soul snapshot.
|
||||
|
||||
``config_snapshot`` stores ``AgentSoulConfig`` as JSON-backed ``LongText``.
|
||||
It may contain credential or secret references, but must never contain
|
||||
plaintext secrets.
|
||||
"""
|
||||
|
||||
__tablename__ = "agent_config_snapshots"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="agent_config_snapshot_pkey"),
|
||||
UniqueConstraint("agent_id", "version", name="agent_config_snapshot_agent_version_unique"),
|
||||
Index("agent_config_snapshot_tenant_agent_created_at_idx", "tenant_id", "agent_id", "created_at"),
|
||||
Index("agent_config_snapshot_tenant_created_at_idx", "tenant_id", "created_at"),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
agent_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
version: Mapped[int] = mapped_column(sa.Integer, nullable=False)
|
||||
config_snapshot: Mapped[Any] = mapped_column(JSONModelColumn(AgentSoulConfig), nullable=False)
|
||||
home_snapshot_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
summary: Mapped[str | None] = mapped_column(LongText, nullable=True, default=None)
|
||||
version_note: Mapped[str | None] = mapped_column(LongText, nullable=True, default=None)
|
||||
created_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
|
||||
@property
|
||||
def config_snapshot_dict(self) -> dict[str, Any]:
|
||||
if not self.config_snapshot:
|
||||
return {}
|
||||
if hasattr(self.config_snapshot, "model_dump"):
|
||||
return self.config_snapshot.model_dump(mode="json")
|
||||
if isinstance(self.config_snapshot, str):
|
||||
return json.loads(self.config_snapshot)
|
||||
return dict(self.config_snapshot)
|
||||
|
||||
|
||||
class AgentConfigRevision(TypeBase, kw_only=True):
|
||||
"""Audit edge for every Agent Soul save operation.
|
||||
|
||||
Revisions link immutable Agent Soul snapshots instead of duplicating the
|
||||
serialized configuration JSON.
|
||||
"""
|
||||
|
||||
__tablename__ = "agent_config_revisions"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="agent_config_revision_pkey"),
|
||||
UniqueConstraint(
|
||||
"agent_id",
|
||||
"revision",
|
||||
name="agent_config_revision_agent_revision_unique",
|
||||
),
|
||||
Index("agent_config_revision_tenant_agent_created_at_idx", "tenant_id", "agent_id", "created_at"),
|
||||
Index(
|
||||
"agent_config_revision_tenant_current_snapshot_created_at_idx",
|
||||
"tenant_id",
|
||||
"current_snapshot_id",
|
||||
"created_at",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID,
|
||||
primary_key=True,
|
||||
insert_default=lambda: str(uuidv7()),
|
||||
default_factory=lambda: str(uuidv7()),
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
agent_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
previous_snapshot_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
current_snapshot_id: Mapped[str | None] = mapped_column(StringUUID, nullable=False)
|
||||
revision: Mapped[int] = mapped_column(sa.Integer, nullable=False)
|
||||
operation: Mapped[AgentConfigRevisionOperation] = mapped_column(
|
||||
EnumText(AgentConfigRevisionOperation, length=64), nullable=False
|
||||
)
|
||||
summary: Mapped[str | None] = mapped_column(LongText, nullable=True, default=None)
|
||||
version_note: Mapped[str | None] = mapped_column(LongText, nullable=True, default=None)
|
||||
created_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
insert_default=naive_utc_now,
|
||||
default_factory=naive_utc_now,
|
||||
server_default=func.current_timestamp(),
|
||||
)
|
||||
|
||||
|
||||
class WorkflowAgentNodeBinding(AgentDefaultFieldsDCMixin, TypeBase, kw_only=True):
|
||||
"""Binding between one workflow node and one Agent config snapshot.
|
||||
|
||||
``node_job_config`` stores Workflow Node Job JSON only. Agent Soul belongs
|
||||
to ``AgentConfigSnapshot.config_snapshot`` and must not be duplicated here.
|
||||
"""
|
||||
|
||||
__tablename__ = "workflow_agent_node_bindings"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="workflow_agent_node_binding_pkey"),
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"workflow_id",
|
||||
"workflow_version",
|
||||
"node_id",
|
||||
name="workflow_agent_node_binding_node_version_unique",
|
||||
),
|
||||
Index("workflow_agent_node_binding_agent_idx", "tenant_id", "agent_id"),
|
||||
Index("workflow_agent_node_binding_current_snapshot_idx", "tenant_id", "current_snapshot_id"),
|
||||
Index("workflow_agent_node_binding_app_idx", "tenant_id", "app_id"),
|
||||
Index(
|
||||
"workflow_agent_node_binding_workflow_version_idx",
|
||||
"tenant_id",
|
||||
"workflow_id",
|
||||
"workflow_version",
|
||||
),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
workflow_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# Tracks which workflow version (draft or a published version string) this
|
||||
# binding belongs to. Mirrors ``Workflow.version`` and lets us keep separate
|
||||
# rows for the draft workflow and each published copy under the same
|
||||
# workflow_id, restoring the stage 1 §5.3 unique key.
|
||||
workflow_version: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
node_id: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
binding_type: Mapped[WorkflowAgentBindingType] = mapped_column(
|
||||
EnumText(WorkflowAgentBindingType, length=32), nullable=False
|
||||
)
|
||||
agent_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
current_snapshot_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
node_job_config: Mapped[Any] = mapped_column(JSONModelColumn(WorkflowNodeJobConfig), nullable=False)
|
||||
created_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
updated_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
|
||||
@property
|
||||
def node_job_config_dict(self) -> dict[str, Any]:
|
||||
if not self.node_job_config:
|
||||
return {}
|
||||
if hasattr(self.node_job_config, "model_dump"):
|
||||
return self.node_job_config.model_dump(mode="json")
|
||||
if isinstance(self.node_job_config, str):
|
||||
return json.loads(self.node_job_config)
|
||||
return dict(self.node_job_config)
|
||||
|
||||
|
||||
class AgentWorkspace(AgentDefaultFieldsDCMixin, TypeBase, kw_only=True):
|
||||
"""Mutable Workspace owned by one product scope, independent of Agents."""
|
||||
|
||||
__tablename__ = "agent_workspaces"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="agent_workspace_pkey"),
|
||||
Index(
|
||||
"agent_workspace_owner_active_unique",
|
||||
"tenant_id",
|
||||
"owner_type",
|
||||
"owner_id",
|
||||
"owner_scope_key",
|
||||
"active_guard",
|
||||
unique=True,
|
||||
),
|
||||
Index("agent_workspace_tenant_status_idx", "tenant_id", "status"),
|
||||
Index("agent_workspace_tenant_app_status_idx", "tenant_id", "app_id", "status"),
|
||||
Index("agent_workspace_status_retired_idx", "status", "retired_at"),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
owner_type: Mapped[AgentWorkspaceOwnerType] = mapped_column(
|
||||
EnumText(AgentWorkspaceOwnerType, length=32), nullable=False
|
||||
)
|
||||
owner_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
owner_scope_key: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
backend_workspace_ref: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
status: Mapped[AgentWorkingResourceStatus] = mapped_column(
|
||||
EnumText(AgentWorkingResourceStatus, length=32),
|
||||
nullable=False,
|
||||
default=AgentWorkingResourceStatus.ACTIVE,
|
||||
server_default=AgentWorkingResourceStatus.ACTIVE.value,
|
||||
)
|
||||
active_guard: Mapped[int | None] = mapped_column(sa.SmallInteger, nullable=True, default=1, server_default="1")
|
||||
retired_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
|
||||
|
||||
class AgentWorkspaceBinding(AgentDefaultFieldsDCMixin, TypeBase, kw_only=True):
|
||||
"""One materialized Agent participant and session attached to a Workspace.
|
||||
|
||||
All resource IDs are logical associations rather than database foreign
|
||||
keys, so RETIRED rows can outlive their Workspace or base Home Snapshot.
|
||||
``agent_id`` identifies the source Agent Soul; this row's ``id`` identifies
|
||||
the participant and its private Materialized Home.
|
||||
"""
|
||||
|
||||
__tablename__ = "agent_workspace_bindings"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="agent_workspace_binding_pkey"),
|
||||
Index("agent_workspace_binding_workspace_status_idx", "tenant_id", "workspace_id", "status"),
|
||||
Index("agent_workspace_binding_agent_status_idx", "tenant_id", "agent_id", "status"),
|
||||
Index("agent_workspace_binding_status_retired_idx", "status", "retired_at"),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
workspace_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
agent_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
base_home_snapshot_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
agent_config_version_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
agent_config_version_kind: Mapped[AgentConfigVersionKind] = mapped_column(
|
||||
EnumText(AgentConfigVersionKind, length=32), nullable=False
|
||||
)
|
||||
backend_binding_ref: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
session_snapshot: Mapped[str | None] = mapped_column(LongText, nullable=True, default=None)
|
||||
status: Mapped[AgentWorkingResourceStatus] = mapped_column(
|
||||
EnumText(AgentWorkingResourceStatus, length=32),
|
||||
nullable=False,
|
||||
default=AgentWorkingResourceStatus.ACTIVE,
|
||||
server_default=AgentWorkingResourceStatus.ACTIVE.value,
|
||||
)
|
||||
retired_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
pending_form_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
pending_tool_call_id: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,117 @@
|
||||
"""Independent E2B accounting records, retained after business resource deletion.
|
||||
|
||||
All timestamps are explicit naive UTC values, following the API's database
|
||||
convention. These records deliberately have no business-object foreign keys.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
|
||||
from .base import Base, DefaultFieldsMixin
|
||||
from .types import StringUUID
|
||||
|
||||
|
||||
class AgentSandboxUsageEvent(DefaultFieldsMixin, Base):
|
||||
__tablename__ = "agent_sandbox_usage_events"
|
||||
__table_args__ = (
|
||||
sa.UniqueConstraint(
|
||||
"provider", "provider_project_id", "source", "source_event_id", name="sandbox_usage_event_unique"
|
||||
),
|
||||
sa.Index("sandbox_usage_event_sandbox_idx", "provider_project_id", "sandbox_id", "occurred_at"),
|
||||
sa.Index("sandbox_usage_event_allocation_idx", "allocation_id", "received_at"),
|
||||
sa.Index("sandbox_usage_event_owner_idx", "provider_project_id", "binding_id", "event_type"),
|
||||
sa.Index("sandbox_usage_event_pending_idx", "projection_status", "received_at"),
|
||||
sa.Index("sandbox_usage_checkpoint_idx", "provider_project_id", "event_type", "purpose", "occurred_at"),
|
||||
sa.Index("sandbox_usage_diagnostics_idx", "provider_project_id", "projection_status"),
|
||||
sa.Index(
|
||||
"sandbox_usage_execution_idx", "provider_project_id", "provider_execution_id", "projection_error_code"
|
||||
),
|
||||
sa.CheckConstraint("source IN ('application', 'provider')", name="sandbox_usage_event_source_check"),
|
||||
)
|
||||
|
||||
provider: Mapped[str] = mapped_column(sa.String(32), nullable=False, default="e2b")
|
||||
provider_project_id: Mapped[str] = mapped_column(sa.String(128), nullable=False)
|
||||
source: Mapped[str] = mapped_column(sa.String(32), nullable=False)
|
||||
source_event_id: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
||||
event_type: Mapped[str] = mapped_column(sa.String(96), nullable=False)
|
||||
sandbox_id: Mapped[str | None] = mapped_column(sa.String(128))
|
||||
provider_execution_id: Mapped[str | None] = mapped_column(sa.String(128))
|
||||
allocation_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
operation_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
lease_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
attempt: Mapped[int | None] = mapped_column(sa.Integer)
|
||||
tenant_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
app_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
agent_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
binding_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
workspace_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
purpose: Mapped[str | None] = mapped_column(sa.String(32))
|
||||
correlation: Mapped[dict[str, Any]] = mapped_column(sa.JSON, nullable=False, default=dict)
|
||||
occurred_at: Mapped[datetime | None] = mapped_column(sa.DateTime)
|
||||
received_at: Mapped[datetime] = mapped_column(sa.DateTime, nullable=False, default=naive_utc_now)
|
||||
payload: Mapped[dict[str, Any]] = mapped_column(sa.JSON, nullable=False)
|
||||
canonical_hash: Mapped[str] = mapped_column(sa.String(64), nullable=False)
|
||||
payload_versions: Mapped[list[dict[str, Any]]] = mapped_column(sa.JSON, nullable=False, default=list)
|
||||
resolution: Mapped[dict[str, Any]] = mapped_column(sa.JSON, nullable=False, default=dict)
|
||||
projection_status: Mapped[str] = mapped_column(sa.String(32), nullable=False, default="pending")
|
||||
projection_error_code: Mapped[str | None] = mapped_column(sa.String(96))
|
||||
processed_at: Mapped[datetime | None] = mapped_column(sa.DateTime)
|
||||
|
||||
|
||||
class AgentSandboxExecution(DefaultFieldsMixin, Base):
|
||||
"""One provider execution, not one request, lease, or connect call."""
|
||||
|
||||
__tablename__ = "agent_sandbox_executions"
|
||||
__table_args__ = (
|
||||
sa.UniqueConstraint(
|
||||
"provider", "provider_project_id", "provider_execution_id", name="sandbox_execution_unique"
|
||||
),
|
||||
sa.Index("sandbox_execution_project_time_idx", "provider_project_id", "started_at"),
|
||||
sa.Index("sandbox_execution_tenant_time_idx", "tenant_id", "started_at"),
|
||||
sa.Index("sandbox_execution_sandbox_idx", "provider_project_id", "sandbox_id", "started_at"),
|
||||
sa.Index("sandbox_execution_allocation_idx", "allocation_id"),
|
||||
sa.Index("sandbox_execution_reconcile_idx", "quality", "state", "last_reconciled_at"),
|
||||
sa.Index("sandbox_execution_diagnostics_idx", "provider_project_id", "state", "attribution_status"),
|
||||
sa.CheckConstraint("metered_duration_ms IS NULL OR metered_duration_ms >= 0", name="sandbox_duration_check"),
|
||||
sa.CheckConstraint("vcpu_count IS NULL OR vcpu_count > 0", name="sandbox_vcpu_check"),
|
||||
sa.CheckConstraint("memory_mib IS NULL OR memory_mib > 0", name="sandbox_memory_check"),
|
||||
sa.CheckConstraint(
|
||||
"quality <> 'metered' OR (state = 'closed' AND measurement_source = 'provider_execution' "
|
||||
"AND metered_duration_ms IS NOT NULL AND started_at IS NOT NULL "
|
||||
"AND vcpu_count IS NOT NULL AND memory_mib IS NOT NULL)",
|
||||
name="sandbox_metered_check",
|
||||
),
|
||||
)
|
||||
|
||||
provider: Mapped[str] = mapped_column(sa.String(32), nullable=False, default="e2b")
|
||||
provider_project_id: Mapped[str] = mapped_column(sa.String(128), nullable=False)
|
||||
sandbox_id: Mapped[str] = mapped_column(sa.String(128), nullable=False)
|
||||
provider_execution_id: Mapped[str] = mapped_column(sa.String(128), nullable=False)
|
||||
allocation_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
tenant_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
app_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
agent_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
binding_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
workspace_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
attribution_status: Mapped[str] = mapped_column(sa.String(32), nullable=False, default="unresolved")
|
||||
template_id: Mapped[str | None] = mapped_column(sa.String(128))
|
||||
template_build_id: Mapped[str | None] = mapped_column(sa.String(128))
|
||||
vcpu_count: Mapped[int | None] = mapped_column(sa.Integer)
|
||||
memory_mib: Mapped[int | None] = mapped_column(sa.BigInteger)
|
||||
started_at: Mapped[datetime | None] = mapped_column(sa.DateTime)
|
||||
started_at_source: Mapped[str | None] = mapped_column(sa.String(32))
|
||||
started_at_precision_ms: Mapped[int | None] = mapped_column(sa.Integer)
|
||||
terminal_event_at: Mapped[datetime | None] = mapped_column(sa.DateTime)
|
||||
metered_duration_ms: Mapped[int | None] = mapped_column(sa.BigInteger)
|
||||
measurement_source: Mapped[str] = mapped_column(sa.String(32), nullable=False, default="unknown")
|
||||
state: Mapped[str] = mapped_column(sa.String(16), nullable=False, default="unknown")
|
||||
quality: Mapped[str] = mapped_column(sa.String(16), nullable=False, default="pending")
|
||||
close_reason: Mapped[str | None] = mapped_column(sa.String(64))
|
||||
terminal_event_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
last_reconciled_at: Mapped[datetime | None] = mapped_column(sa.DateTime)
|
||||
revision: Mapped[int] = mapped_column(sa.Integer, nullable=False, default=1)
|
||||
@@ -0,0 +1,36 @@
|
||||
import enum
|
||||
from datetime import datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import DateTime, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import TypeBase
|
||||
from .types import LongText, StringUUID
|
||||
|
||||
|
||||
class APIBasedExtensionPoint(enum.StrEnum):
|
||||
APP_EXTERNAL_DATA_TOOL_QUERY = "app.external_data_tool.query"
|
||||
PING = "ping"
|
||||
APP_MODERATION_INPUT = "app.moderation.input"
|
||||
APP_MODERATION_OUTPUT = "app.moderation.output"
|
||||
|
||||
|
||||
class APIBasedExtension(TypeBase):
|
||||
__tablename__ = "api_based_extensions"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="api_based_extension_pkey"),
|
||||
sa.Index("api_based_extension_tenant_idx", "tenant_id"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
api_endpoint: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
api_key: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Durable application tracing envelopes, separate from business execution state.
|
||||
|
||||
Provider configuration snapshots contain the existing workspace-encrypted secret
|
||||
values. They are never serialized by Console endpoints or sent to Agent runs.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from models.base import TypeBase
|
||||
from models.types import StringUUID
|
||||
|
||||
|
||||
class ApplicationTraceRun(TypeBase, kw_only=True):
|
||||
__tablename__ = "application_trace_runs"
|
||||
__table_args__ = (
|
||||
sa.UniqueConstraint("tenant_id", "app_id", "source_kind", "source_id", name="application_trace_source_unique"),
|
||||
sa.Index("application_trace_delivery_idx", "state", "next_attempt_at"),
|
||||
sa.Index("application_trace_retention_idx", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(StringUUID, primary_key=True)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID)
|
||||
source_kind: Mapped[str] = mapped_column(sa.String(16))
|
||||
source_id: Mapped[str] = mapped_column(StringUUID)
|
||||
provider: Mapped[str] = mapped_column(sa.String(32))
|
||||
config_revision: Mapped[str] = mapped_column(sa.String(64))
|
||||
provider_config: Mapped[dict[str, Any]] = mapped_column(sa.JSON)
|
||||
trace_id: Mapped[str] = mapped_column(sa.String(32))
|
||||
root_span_id: Mapped[str] = mapped_column(sa.String(16))
|
||||
session_id: Mapped[str] = mapped_column(sa.String(255))
|
||||
capture_content: Mapped[bool] = mapped_column(sa.Boolean)
|
||||
capture_agent: Mapped[bool] = mapped_column(sa.Boolean, default=True)
|
||||
state: Mapped[str] = mapped_column(sa.String(24), default="collecting")
|
||||
outer_trace: Mapped[dict[str, Any] | None] = mapped_column(sa.JSON, default=None)
|
||||
span_count: Mapped[int] = mapped_column(sa.Integer, default=0)
|
||||
payload_bytes: Mapped[int] = mapped_column(sa.BigInteger, default=0)
|
||||
attempts: Mapped[int] = mapped_column(sa.Integer, default=0)
|
||||
error_code: Mapped[str | None] = mapped_column(sa.String(96), default=None)
|
||||
trace_url: Mapped[str | None] = mapped_column(sa.Text, default=None)
|
||||
provider_trace_id: Mapped[str | None] = mapped_column(sa.String(255), default=None)
|
||||
span_urls: Mapped[dict[str, str]] = mapped_column(sa.JSON, default_factory=dict)
|
||||
export_token: Mapped[str | None] = mapped_column(StringUUID, default=None)
|
||||
export_started_at: Mapped[datetime | None] = mapped_column(sa.DateTime, default=None)
|
||||
export_heartbeat_at: Mapped[datetime | None] = mapped_column(sa.DateTime, default=None)
|
||||
next_attempt_at: Mapped[datetime | None] = mapped_column(sa.DateTime, default=None)
|
||||
accepted_at: Mapped[datetime | None] = mapped_column(sa.DateTime, default=None)
|
||||
terminal_at: Mapped[datetime | None] = mapped_column(sa.DateTime, default=None)
|
||||
created_at: Mapped[datetime] = mapped_column(sa.DateTime, default_factory=naive_utc_now)
|
||||
updated_at: Mapped[datetime] = mapped_column(sa.DateTime, default_factory=naive_utc_now)
|
||||
|
||||
|
||||
class ApplicationTraceInvocation(TypeBase, kw_only=True):
|
||||
__tablename__ = "application_trace_invocations"
|
||||
__table_args__ = (sa.Index("application_trace_invocation_run_idx", "run_id"),)
|
||||
|
||||
id: Mapped[str] = mapped_column(StringUUID, primary_key=True)
|
||||
run_id: Mapped[str] = mapped_column(StringUUID)
|
||||
agent_id: Mapped[str] = mapped_column(StringUUID)
|
||||
parent_span_id: Mapped[str] = mapped_column(sa.String(16))
|
||||
span_id: Mapped[str] = mapped_column(sa.String(16))
|
||||
node_execution_id: Mapped[str | None] = mapped_column(StringUUID)
|
||||
attempt: Mapped[int] = mapped_column(sa.Integer)
|
||||
finalized: Mapped[bool] = mapped_column(sa.Boolean, default=False)
|
||||
created_at: Mapped[datetime] = mapped_column(sa.DateTime, default_factory=naive_utc_now)
|
||||
finalized_at: Mapped[datetime | None] = mapped_column(sa.DateTime, default=None)
|
||||
|
||||
|
||||
class ApplicationTraceBatch(TypeBase, kw_only=True):
|
||||
__tablename__ = "application_trace_batches"
|
||||
__table_args__ = (sa.Index("application_trace_batch_run_idx", "run_id", "created_at"),)
|
||||
|
||||
id: Mapped[str] = mapped_column(StringUUID, primary_key=True)
|
||||
run_id: Mapped[str] = mapped_column(StringUUID)
|
||||
invocation_id: Mapped[str] = mapped_column(StringUUID)
|
||||
payload_hash: Mapped[str] = mapped_column(sa.String(64))
|
||||
spans: Mapped[list[dict[str, Any]]] = mapped_column(sa.JSON)
|
||||
final: Mapped[bool] = mapped_column(sa.Boolean)
|
||||
created_at: Mapped[datetime] = mapped_column(sa.DateTime, default_factory=naive_utc_now)
|
||||
@@ -0,0 +1,107 @@
|
||||
from datetime import datetime
|
||||
from typing import override
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import DateTime, func
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, mapped_column
|
||||
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from libs.uuid_utils import uuidv7
|
||||
|
||||
from .engine import metadata
|
||||
from .types import StringUUID
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
metadata = metadata
|
||||
|
||||
|
||||
class TypeBase(MappedAsDataclass, DeclarativeBase):
|
||||
"""
|
||||
This is for adding type, after all finished, rename to Base.
|
||||
"""
|
||||
|
||||
metadata = metadata
|
||||
|
||||
|
||||
class DefaultFieldsMixin:
|
||||
"""Mixin for models that inherit from Base (non-dataclass)."""
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID,
|
||||
primary_key=True,
|
||||
# NOTE: The default serve as fallback mechanisms.
|
||||
# The application can generate the `id` before saving to optimize
|
||||
# the insertion process (especially for interdependent models)
|
||||
# and reduce database roundtrips.
|
||||
default=lambda: str(uuidv7()),
|
||||
)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
default=naive_utc_now,
|
||||
server_default=func.current_timestamp(),
|
||||
)
|
||||
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
default=naive_utc_now,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
)
|
||||
|
||||
@override
|
||||
def __repr__(self) -> str:
|
||||
return f"<{self.__class__.__name__}(id={self.id})>"
|
||||
|
||||
|
||||
class DefaultFieldsDCMixin(MappedAsDataclass):
|
||||
"""Mixin for models that inherit from TypeBase (MappedAsDataclass)."""
|
||||
|
||||
__abstract__ = True
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID,
|
||||
primary_key=True,
|
||||
insert_default=lambda: str(uuidv7()),
|
||||
default_factory=lambda: str(uuidv7()),
|
||||
init=False,
|
||||
)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
insert_default=naive_utc_now,
|
||||
default_factory=naive_utc_now,
|
||||
init=False,
|
||||
server_default=func.current_timestamp(),
|
||||
)
|
||||
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
insert_default=naive_utc_now,
|
||||
default_factory=naive_utc_now,
|
||||
init=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
)
|
||||
|
||||
@override
|
||||
def __repr__(self) -> str:
|
||||
return f"<{self.__class__.__name__}(id={self.id})>"
|
||||
|
||||
|
||||
def gen_uuidv4_string() -> str:
|
||||
"""gen_uuidv4_string generate a UUIDv4 string.
|
||||
|
||||
NOTE: This function exists only for historical reasons. New models should use uuidv7 for primary key generation.
|
||||
"""
|
||||
return str(uuid4())
|
||||
|
||||
|
||||
def gen_uuidv7_string() -> str:
|
||||
"""Generate a UUIDv7 string."""
|
||||
return str(uuidv7())
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Workflow comment models."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import Index, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from models.base import TypeBase
|
||||
|
||||
from .base import gen_uuidv7_string
|
||||
from .types import StringUUID
|
||||
|
||||
|
||||
class WorkflowComment(TypeBase):
|
||||
"""Workflow comment model for canvas commenting functionality.
|
||||
|
||||
Comments are associated with apps rather than specific workflow versions,
|
||||
since an app has only one draft workflow at a time and comments should persist
|
||||
across workflow version changes.
|
||||
|
||||
Attributes:
|
||||
id: Comment ID
|
||||
tenant_id: Workspace ID
|
||||
app_id: App ID (primary association, comments belong to apps)
|
||||
position_x: X coordinate on canvas
|
||||
position_y: Y coordinate on canvas
|
||||
content: Comment content
|
||||
created_by: Creator account ID
|
||||
created_at: Creation time
|
||||
updated_at: Last update time
|
||||
resolved: Whether comment is resolved
|
||||
resolved_at: Resolution time
|
||||
resolved_by: Resolver account ID
|
||||
"""
|
||||
|
||||
__tablename__ = "workflow_comments"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="workflow_comments_pkey"),
|
||||
Index("workflow_comments_app_idx", "tenant_id", "app_id"),
|
||||
Index("workflow_comments_created_at_idx", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(StringUUID, default_factory=gen_uuidv7_string, init=False)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
position_x: Mapped[float] = mapped_column(sa.Float)
|
||||
position_y: Mapped[float] = mapped_column(sa.Float)
|
||||
content: Mapped[str] = mapped_column(sa.Text, nullable=False)
|
||||
created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
resolved_at: Mapped[datetime | None] = mapped_column(sa.DateTime, default=None)
|
||||
resolved_by: Mapped[str | None] = mapped_column(StringUUID, default=None)
|
||||
|
||||
resolved: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
|
||||
# Relationships
|
||||
replies: Mapped[list[WorkflowCommentReply]] = relationship(
|
||||
lambda: WorkflowCommentReply, back_populates="comment", cascade="all, delete-orphan", init=False
|
||||
)
|
||||
mentions: Mapped[list[WorkflowCommentMention]] = relationship(
|
||||
lambda: WorkflowCommentMention, back_populates="comment", cascade="all, delete-orphan", init=False
|
||||
)
|
||||
|
||||
|
||||
class WorkflowCommentReply(TypeBase):
|
||||
"""Workflow comment reply model.
|
||||
|
||||
Attributes:
|
||||
id: Reply ID
|
||||
comment_id: Parent comment ID
|
||||
content: Reply content
|
||||
created_by: Creator account ID
|
||||
created_at: Creation time
|
||||
"""
|
||||
|
||||
__tablename__ = "workflow_comment_replies"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="workflow_comment_replies_pkey"),
|
||||
Index("comment_replies_comment_idx", "comment_id"),
|
||||
Index("comment_replies_created_at_idx", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(StringUUID, default_factory=gen_uuidv7_string, init=False)
|
||||
comment_id: Mapped[str] = mapped_column(
|
||||
StringUUID, sa.ForeignKey("workflow_comments.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
content: Mapped[str] = mapped_column(sa.Text, nullable=False)
|
||||
created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
# Relationships
|
||||
comment: Mapped[WorkflowComment] = relationship(lambda: WorkflowComment, back_populates="replies", init=False)
|
||||
|
||||
|
||||
class WorkflowCommentMention(TypeBase):
|
||||
"""Workflow comment mention model.
|
||||
|
||||
Mentions are only for internal accounts since end users
|
||||
cannot access workflow canvas and commenting features.
|
||||
|
||||
Attributes:
|
||||
id: Mention ID
|
||||
comment_id: Parent comment ID
|
||||
mentioned_user_id: Mentioned account ID
|
||||
"""
|
||||
|
||||
__tablename__ = "workflow_comment_mentions"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="workflow_comment_mentions_pkey"),
|
||||
Index("comment_mentions_comment_idx", "comment_id"),
|
||||
Index("comment_mentions_reply_idx", "reply_id"),
|
||||
Index("comment_mentions_user_idx", "mentioned_user_id"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(StringUUID, default_factory=gen_uuidv7_string, init=False)
|
||||
comment_id: Mapped[str] = mapped_column(
|
||||
StringUUID, sa.ForeignKey("workflow_comments.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
mentioned_user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
reply_id: Mapped[str | None] = mapped_column(
|
||||
StringUUID, sa.ForeignKey("workflow_comment_replies.id", ondelete="CASCADE"), nullable=True, default=None
|
||||
)
|
||||
|
||||
# Relationships
|
||||
comment: Mapped[WorkflowComment] = relationship(lambda: WorkflowComment, back_populates="mentions", init=False)
|
||||
reply: Mapped[WorkflowCommentReply | None] = relationship(lambda: WorkflowCommentReply, init=False)
|
||||
@@ -0,0 +1,51 @@
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from uuid import uuid4
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import DateTime, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import TypeBase
|
||||
from .types import StringUUID
|
||||
|
||||
|
||||
class CredentialType(StrEnum):
|
||||
"""Discriminator for polymorphic credential permission table."""
|
||||
|
||||
TRIGGER_SUBSCRIPTION = "trigger_subscription"
|
||||
BUILTIN_TOOL_PROVIDER = "builtin_tool_provider"
|
||||
DATASOURCE_PROVIDER = "datasource_provider"
|
||||
PROVIDER_CREDENTIAL = "provider_credential"
|
||||
|
||||
|
||||
class CredentialPermission(TypeBase):
|
||||
"""
|
||||
Polymorphic join table for per-credential partial-member access control.
|
||||
Mirrors DatasetPermission (api/models/dataset.py) but supports all credential types
|
||||
via a credential_type discriminator column.
|
||||
"""
|
||||
|
||||
__tablename__ = "credential_permissions"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="credential_permission_pkey"),
|
||||
sa.Index("idx_credential_permissions_credential", "credential_id", "credential_type"),
|
||||
sa.Index("idx_credential_permissions_account_id", "account_id"),
|
||||
sa.Index("idx_credential_permissions_tenant_id", "tenant_id"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID,
|
||||
insert_default=lambda: str(uuid4()),
|
||||
default_factory=lambda: str(uuid4()),
|
||||
primary_key=True,
|
||||
init=False,
|
||||
)
|
||||
credential_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
credential_type: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
account_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
has_permission: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.true(), default=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,25 @@
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from sqlalchemy import MetaData
|
||||
|
||||
POSTGRES_INDEXES_NAMING_CONVENTION = {
|
||||
"ix": "%(table_name)s_%(column_0_N_name)s_idx",
|
||||
"uq": "%(table_name)s_%(column_0_name)s_key",
|
||||
"ck": "%(table_name)s_%(constraint_name)s_check",
|
||||
"fk": "%(table_name)s_%(column_0_name)s_fkey",
|
||||
"pk": "%(table_name)s_pkey",
|
||||
}
|
||||
|
||||
metadata = MetaData(naming_convention=POSTGRES_INDEXES_NAMING_CONVENTION)
|
||||
|
||||
# ****** IMPORTANT NOTICE ******
|
||||
#
|
||||
# NOTE(QuantumGhost): Avoid directly importing and using `db` in modules outside of the
|
||||
# `controllers` package.
|
||||
#
|
||||
# Instead, import `db` within the `controllers` package and pass it as an argument to
|
||||
# functions or class constructors.
|
||||
#
|
||||
# Directly importing `db` in other modules can make the code more difficult to read, test, and maintain.
|
||||
#
|
||||
# Whenever possible, avoid this pattern in new code.
|
||||
db = SQLAlchemy(metadata=metadata)
|
||||
@@ -0,0 +1,385 @@
|
||||
from enum import StrEnum
|
||||
from typing import override
|
||||
|
||||
from core.trigger.constants import (
|
||||
TRIGGER_PLUGIN_NODE_TYPE,
|
||||
TRIGGER_SCHEDULE_NODE_TYPE,
|
||||
TRIGGER_WEBHOOK_NODE_TYPE,
|
||||
)
|
||||
|
||||
|
||||
class CreatorUserRole(StrEnum):
|
||||
ACCOUNT = "account"
|
||||
END_USER = "end_user"
|
||||
DATASET_API_KEY = "dataset_api_key"
|
||||
|
||||
@classmethod
|
||||
@override
|
||||
def _missing_(cls, value):
|
||||
if value == "end-user":
|
||||
return cls.END_USER
|
||||
else:
|
||||
return super()._missing_(value)
|
||||
|
||||
|
||||
class WorkflowRunTriggeredFrom(StrEnum):
|
||||
DEBUGGING = "debugging"
|
||||
APP_RUN = "app-run" # webapp / service api
|
||||
RAG_PIPELINE_RUN = "rag-pipeline-run"
|
||||
RAG_PIPELINE_DEBUGGING = "rag-pipeline-debugging"
|
||||
WEBHOOK = "webhook"
|
||||
SCHEDULE = "schedule"
|
||||
PLUGIN = "plugin"
|
||||
|
||||
|
||||
class DraftVariableType(StrEnum):
|
||||
# node means that the correspond variable
|
||||
NODE = "node"
|
||||
SYS = "sys"
|
||||
CONVERSATION = "conversation"
|
||||
|
||||
|
||||
class MessageStatus(StrEnum):
|
||||
"""
|
||||
Message Status Enum
|
||||
"""
|
||||
|
||||
NORMAL = "normal"
|
||||
PAUSED = "paused"
|
||||
ERROR = "error"
|
||||
|
||||
|
||||
class ExecutionOffLoadType(StrEnum):
|
||||
INPUTS = "inputs"
|
||||
PROCESS_DATA = "process_data"
|
||||
OUTPUTS = "outputs"
|
||||
|
||||
|
||||
class WorkflowTriggerStatus(StrEnum):
|
||||
"""Workflow Trigger Execution Status"""
|
||||
|
||||
PENDING = "pending"
|
||||
QUEUED = "queued"
|
||||
RUNNING = "running"
|
||||
SUCCEEDED = "succeeded"
|
||||
PAUSED = "paused"
|
||||
FAILED = "failed"
|
||||
RATE_LIMITED = "rate_limited"
|
||||
RETRYING = "retrying"
|
||||
|
||||
|
||||
class AppTriggerStatus(StrEnum):
|
||||
"""App Trigger Status Enum"""
|
||||
|
||||
ENABLED = "enabled"
|
||||
DISABLED = "disabled"
|
||||
UNAUTHORIZED = "unauthorized"
|
||||
RATE_LIMITED = "rate_limited"
|
||||
|
||||
|
||||
class AppTriggerType(StrEnum):
|
||||
"""App Trigger Type Enum"""
|
||||
|
||||
TRIGGER_WEBHOOK = TRIGGER_WEBHOOK_NODE_TYPE
|
||||
TRIGGER_SCHEDULE = TRIGGER_SCHEDULE_NODE_TYPE
|
||||
TRIGGER_PLUGIN = TRIGGER_PLUGIN_NODE_TYPE
|
||||
|
||||
# for backward compatibility
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
class AppStatus(StrEnum):
|
||||
"""App Status Enum"""
|
||||
|
||||
NORMAL = "normal"
|
||||
|
||||
|
||||
class ConversationStatus(StrEnum):
|
||||
"""Conversation Status Enum"""
|
||||
|
||||
NORMAL = "normal"
|
||||
|
||||
|
||||
class DataSourceType(StrEnum):
|
||||
"""Data Source Type for Dataset and Document"""
|
||||
|
||||
UPLOAD_FILE = "upload_file"
|
||||
NOTION_IMPORT = "notion_import"
|
||||
WEBSITE_CRAWL = "website_crawl"
|
||||
LOCAL_FILE = "local_file"
|
||||
ONLINE_DOCUMENT = "online_document"
|
||||
ONLINE_DRIVE = "online_drive"
|
||||
|
||||
|
||||
class ProcessRuleMode(StrEnum):
|
||||
"""Dataset Process Rule Mode"""
|
||||
|
||||
AUTOMATIC = "automatic"
|
||||
CUSTOM = "custom"
|
||||
HIERARCHICAL = "hierarchical"
|
||||
|
||||
|
||||
class IndexingStatus(StrEnum):
|
||||
"""Document Indexing Status"""
|
||||
|
||||
WAITING = "waiting"
|
||||
PARSING = "parsing"
|
||||
CLEANING = "cleaning"
|
||||
SPLITTING = "splitting"
|
||||
INDEXING = "indexing"
|
||||
PAUSED = "paused"
|
||||
COMPLETED = "completed"
|
||||
ERROR = "error"
|
||||
|
||||
|
||||
class DocumentCreatedFrom(StrEnum):
|
||||
"""Document Created From"""
|
||||
|
||||
WEB = "web"
|
||||
API = "api"
|
||||
RAG_PIPELINE = "rag-pipeline"
|
||||
|
||||
|
||||
class ConversationFromSource(StrEnum):
|
||||
"""Conversation / Message from_source"""
|
||||
|
||||
API = "api"
|
||||
CONSOLE = "console"
|
||||
|
||||
|
||||
class FeedbackFromSource(StrEnum):
|
||||
"""MessageFeedback from_source"""
|
||||
|
||||
USER = "user"
|
||||
ADMIN = "admin"
|
||||
|
||||
|
||||
class CustomizeTokenStrategy(StrEnum):
|
||||
"""Site token customization strategy"""
|
||||
|
||||
MUST = "must"
|
||||
ALLOW = "allow"
|
||||
NOT_ALLOW = "not_allow"
|
||||
UUID = "uuid"
|
||||
|
||||
|
||||
class FeedbackRating(StrEnum):
|
||||
"""MessageFeedback rating"""
|
||||
|
||||
LIKE = "like"
|
||||
DISLIKE = "dislike"
|
||||
|
||||
|
||||
class InvokeFrom(StrEnum):
|
||||
"""How a conversation/message was invoked"""
|
||||
|
||||
SERVICE_API = "service-api"
|
||||
WEB_APP = "web-app"
|
||||
TRIGGER = "trigger"
|
||||
EXPLORE = "explore"
|
||||
DEBUGGER = "debugger"
|
||||
PUBLISHED_PIPELINE = "published"
|
||||
VALIDATION = "validation"
|
||||
OPENAPI = "openapi"
|
||||
|
||||
@classmethod
|
||||
def value_of(cls, value: str) -> "InvokeFrom":
|
||||
return cls(value)
|
||||
|
||||
def to_source(self) -> str:
|
||||
source_mapping = {
|
||||
InvokeFrom.WEB_APP: "web_app",
|
||||
InvokeFrom.DEBUGGER: "dev",
|
||||
InvokeFrom.EXPLORE: "explore_app",
|
||||
InvokeFrom.TRIGGER: "trigger",
|
||||
InvokeFrom.SERVICE_API: "api",
|
||||
InvokeFrom.OPENAPI: "openapi",
|
||||
}
|
||||
return source_mapping.get(self, "dev")
|
||||
|
||||
|
||||
class EndUserType(StrEnum):
|
||||
"""Persisted type values for the ``end_users.type`` column."""
|
||||
|
||||
APP_DEPLOY = "app-deploy"
|
||||
BROWSER = "browser"
|
||||
MCP = "mcp"
|
||||
OPENAPI = "openapi"
|
||||
SERVICE_API = "service-api"
|
||||
TRIGGER = "trigger"
|
||||
|
||||
|
||||
DEFAULT_END_USER_SESSION_ID = "DEFAULT-USER"
|
||||
|
||||
|
||||
class DocumentDocType(StrEnum):
|
||||
"""Document doc_type classification"""
|
||||
|
||||
BOOK = "book"
|
||||
WEB_PAGE = "web_page"
|
||||
PAPER = "paper"
|
||||
SOCIAL_MEDIA_POST = "social_media_post"
|
||||
WIKIPEDIA_ENTRY = "wikipedia_entry"
|
||||
PERSONAL_DOCUMENT = "personal_document"
|
||||
BUSINESS_DOCUMENT = "business_document"
|
||||
IM_CHAT_LOG = "im_chat_log"
|
||||
SYNCED_FROM_NOTION = "synced_from_notion"
|
||||
SYNCED_FROM_GITHUB = "synced_from_github"
|
||||
OTHERS = "others"
|
||||
|
||||
|
||||
class TagType(StrEnum):
|
||||
"""Tag type"""
|
||||
|
||||
KNOWLEDGE = "knowledge"
|
||||
APP = "app"
|
||||
SNIPPET = "snippet"
|
||||
SKILL = "skill"
|
||||
|
||||
|
||||
class DatasetMetadataType(StrEnum):
|
||||
"""Dataset metadata value type"""
|
||||
|
||||
STRING = "string"
|
||||
NUMBER = "number"
|
||||
TIME = "time"
|
||||
|
||||
|
||||
class SegmentType(StrEnum):
|
||||
"""Document segment type"""
|
||||
|
||||
AUTOMATIC = "automatic"
|
||||
CUSTOMIZED = "customized"
|
||||
|
||||
|
||||
class SegmentStatus(StrEnum):
|
||||
"""Document segment status"""
|
||||
|
||||
WAITING = "waiting"
|
||||
INDEXING = "indexing"
|
||||
COMPLETED = "completed"
|
||||
ERROR = "error"
|
||||
PAUSED = "paused"
|
||||
RE_SEGMENT = "re_segment"
|
||||
|
||||
|
||||
class DatasetRuntimeMode(StrEnum):
|
||||
"""Dataset runtime mode"""
|
||||
|
||||
GENERAL = "general"
|
||||
RAG_PIPELINE = "rag_pipeline"
|
||||
|
||||
|
||||
class CollectionBindingType(StrEnum):
|
||||
"""Dataset collection binding type"""
|
||||
|
||||
DATASET = "dataset"
|
||||
ANNOTATION = "annotation"
|
||||
|
||||
|
||||
class DatasetQuerySource(StrEnum):
|
||||
"""Dataset query source"""
|
||||
|
||||
HIT_TESTING = "hit_testing"
|
||||
APP = "app"
|
||||
|
||||
|
||||
class TidbAuthBindingStatus(StrEnum):
|
||||
"""TiDB auth binding status"""
|
||||
|
||||
CREATING = "CREATING"
|
||||
ACTIVE = "ACTIVE"
|
||||
FAILED = "FAILED"
|
||||
|
||||
|
||||
class MessageFileBelongsTo(StrEnum):
|
||||
"""MessageFile belongs_to"""
|
||||
|
||||
USER = "user"
|
||||
ASSISTANT = "assistant"
|
||||
|
||||
|
||||
class CredentialSourceType(StrEnum):
|
||||
"""Load balancing credential source type"""
|
||||
|
||||
PROVIDER = "provider"
|
||||
CUSTOM_MODEL = "custom_model"
|
||||
|
||||
|
||||
class PaymentStatus(StrEnum):
|
||||
"""Provider order payment status"""
|
||||
|
||||
WAIT_PAY = "wait_pay"
|
||||
PAID = "paid"
|
||||
FAILED = "failed"
|
||||
REFUNDED = "refunded"
|
||||
|
||||
|
||||
class BannerStatus(StrEnum):
|
||||
"""ExporleBanner status"""
|
||||
|
||||
ENABLED = "enabled"
|
||||
DISABLED = "disabled"
|
||||
|
||||
|
||||
class SummaryStatus(StrEnum):
|
||||
"""Document segment summary status"""
|
||||
|
||||
NOT_STARTED = "not_started"
|
||||
GENERATING = "generating"
|
||||
COMPLETED = "completed"
|
||||
ERROR = "error"
|
||||
TIMEOUT = "timeout"
|
||||
|
||||
|
||||
class MessageChainType(StrEnum):
|
||||
"""Message chain type"""
|
||||
|
||||
SYSTEM = "system"
|
||||
|
||||
|
||||
class PromptType(StrEnum):
|
||||
"""Prompt configuration type"""
|
||||
|
||||
SIMPLE = "simple"
|
||||
ADVANCED = "advanced"
|
||||
|
||||
|
||||
class ProviderQuotaType(StrEnum):
|
||||
PAID = "paid"
|
||||
"""hosted paid quota"""
|
||||
|
||||
FREE = "free"
|
||||
"""third-party free quota"""
|
||||
|
||||
TRIAL = "trial"
|
||||
"""hosted trial quota"""
|
||||
|
||||
@staticmethod
|
||||
def value_of(value: str) -> "ProviderQuotaType":
|
||||
for member in ProviderQuotaType:
|
||||
if member.value == value:
|
||||
return member
|
||||
raise ValueError(f"No matching enum found for value '{value}'")
|
||||
|
||||
|
||||
class ApiTokenType(StrEnum):
|
||||
"""API Token type"""
|
||||
|
||||
APP = "app"
|
||||
DATASET = "dataset"
|
||||
|
||||
|
||||
class ApiTokenBindingResourceType(StrEnum):
|
||||
"""Kind of knowledge base a dataset API key binding row points at."""
|
||||
|
||||
DATASET = "dataset"
|
||||
KNOWLEDGE_FS_SPACE = "knowledge_fs_space"
|
||||
|
||||
|
||||
class PermissionEnum(StrEnum):
|
||||
"""Shared permission levels for resources (datasets, credentials, etc.)"""
|
||||
|
||||
ONLY_ME = "only_me"
|
||||
ALL_TEAM = "all_team_members"
|
||||
PARTIAL_TEAM = "partial_members"
|
||||
@@ -0,0 +1,78 @@
|
||||
from enum import StrEnum, auto
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from .base import Base, DefaultFieldsMixin
|
||||
from .types import EnumText, StringUUID
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .human_input import HumanInputForm
|
||||
|
||||
|
||||
class ExecutionContentType(StrEnum):
|
||||
HUMAN_INPUT = auto()
|
||||
|
||||
|
||||
class ExecutionExtraContent(DefaultFieldsMixin, Base):
|
||||
"""ExecutionExtraContent stores extra contents produced during workflow / chatflow execution."""
|
||||
|
||||
# The `ExecutionExtraContent` uses single table inheritance to model different
|
||||
# kinds of contents produced during message generation.
|
||||
#
|
||||
# See: https://docs.sqlalchemy.org/en/20/orm/inheritance.html#single-table-inheritance
|
||||
|
||||
__tablename__ = "execution_extra_contents"
|
||||
__mapper_args__ = {
|
||||
"polymorphic_abstract": True,
|
||||
"polymorphic_on": "type",
|
||||
"with_polymorphic": "*",
|
||||
}
|
||||
# type records the type of the content. It serves as the `discriminator` for the
|
||||
# single table inheritance.
|
||||
type: Mapped[ExecutionContentType] = mapped_column(
|
||||
EnumText(ExecutionContentType, length=30),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
# `workflow_run_id` records the workflow execution which generates this content, correspond to
|
||||
# `WorkflowRun.id`.
|
||||
workflow_run_id: Mapped[str] = mapped_column(StringUUID, nullable=False, index=True)
|
||||
|
||||
# `message_id` records the messages generated by the execution associated with this `ExecutionExtraContent`.
|
||||
# It references to `Message.id`.
|
||||
#
|
||||
# For workflow execution, this field is `None`.
|
||||
#
|
||||
# For chatflow execution, `message_id`` is not None, and the following condition holds:
|
||||
#
|
||||
# The message referenced by `message_id` has `message.workflow_run_id == execution_extra_content.workflow_run_id`
|
||||
#
|
||||
message_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, index=True)
|
||||
|
||||
|
||||
class HumanInputContent(ExecutionExtraContent):
|
||||
"""HumanInputContent is a concrete class that represents human input content.
|
||||
It should only be initialized with the `new` class method."""
|
||||
|
||||
__mapper_args__ = {
|
||||
"polymorphic_identity": ExecutionContentType.HUMAN_INPUT,
|
||||
}
|
||||
|
||||
# A relation to HumanInputForm table.
|
||||
#
|
||||
# While the form_id column is nullable in database (due to the nature of single table inheritance),
|
||||
# the form_id field should not be null for a given `HumanInputContent` instance.
|
||||
form_id: Mapped[str] = mapped_column(StringUUID, nullable=True)
|
||||
|
||||
@classmethod
|
||||
def new(cls, *, workflow_run_id: str, form_id: str, message_id: str | None) -> "HumanInputContent":
|
||||
return cls(workflow_run_id=workflow_run_id, form_id=form_id, message_id=message_id)
|
||||
|
||||
form: Mapped["HumanInputForm"] = relationship(
|
||||
"HumanInputForm",
|
||||
foreign_keys=[form_id],
|
||||
uselist=False,
|
||||
lazy="raise",
|
||||
primaryjoin="foreign(HumanInputContent.form_id) == HumanInputForm.id",
|
||||
)
|
||||
@@ -0,0 +1,350 @@
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import Annotated, Literal, Self, final
|
||||
|
||||
import sqlalchemy as sa
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from core.workflow.human_input_adapter import DeliveryMethodType, InstantMessageProvider, InstantMessageRecipientType
|
||||
from core.workflow.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus
|
||||
from libs.helper import generate_string
|
||||
|
||||
from .base import Base, DefaultFieldsMixin
|
||||
from .types import EnumText, StringUUID
|
||||
|
||||
_token_length = 22
|
||||
# A 32-character string can store a base64-encoded value with 192 bits of entropy
|
||||
# or a base62-encoded value with over 180 bits of entropy, providing sufficient
|
||||
# uniqueness for most use cases.
|
||||
_token_field_length = 32
|
||||
_email_field_length = 330
|
||||
|
||||
|
||||
def _generate_token() -> str:
|
||||
return generate_string(_token_length)
|
||||
|
||||
|
||||
class HumanInputForm(DefaultFieldsMixin, Base):
|
||||
__tablename__ = "human_input_forms"
|
||||
__table_args__ = (
|
||||
sa.Index(
|
||||
"human_input_forms_workflow_run_id_node_id_idx",
|
||||
"workflow_run_id",
|
||||
"node_id",
|
||||
),
|
||||
sa.Index("human_input_forms_status_expiration_time_idx", "status", "expiration_time"),
|
||||
sa.Index("human_input_forms_status_created_at_idx", "status", "created_at"),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
workflow_run_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
# Chatflow forms retain their conversation for lookup and deletion.
|
||||
conversation_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
form_kind: Mapped[HumanInputFormKind] = mapped_column(
|
||||
EnumText(HumanInputFormKind),
|
||||
nullable=False,
|
||||
default=HumanInputFormKind.RUNTIME,
|
||||
)
|
||||
|
||||
# The human input node the current form corresponds to.
|
||||
node_id: Mapped[str] = mapped_column(sa.String(60), nullable=False)
|
||||
form_definition: Mapped[str] = mapped_column(sa.Text, nullable=False)
|
||||
rendered_content: Mapped[str] = mapped_column(sa.Text, nullable=False)
|
||||
status: Mapped[HumanInputFormStatus] = mapped_column(
|
||||
EnumText(HumanInputFormStatus),
|
||||
nullable=False,
|
||||
default=HumanInputFormStatus.WAITING,
|
||||
)
|
||||
|
||||
expiration_time: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime,
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
# Submission-related fields (nullable until a submission happens).
|
||||
selected_action_id: Mapped[str | None] = mapped_column(sa.String(200), nullable=True)
|
||||
submitted_data: Mapped[str | None] = mapped_column(sa.Text, nullable=True)
|
||||
submitted_at: Mapped[datetime | None] = mapped_column(sa.DateTime, nullable=True)
|
||||
submission_user_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
submission_end_user_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
|
||||
completed_by_recipient_id: Mapped[str | None] = mapped_column(
|
||||
StringUUID,
|
||||
nullable=True,
|
||||
)
|
||||
|
||||
deliveries: Mapped[list["HumanInputDelivery"]] = relationship(
|
||||
"HumanInputDelivery",
|
||||
primaryjoin="HumanInputForm.id == foreign(HumanInputDelivery.form_id)",
|
||||
uselist=True,
|
||||
back_populates="form",
|
||||
lazy="raise",
|
||||
)
|
||||
completed_by_recipient: Mapped["HumanInputFormRecipient | None"] = relationship(
|
||||
"HumanInputFormRecipient",
|
||||
primaryjoin="HumanInputForm.completed_by_recipient_id == foreign(HumanInputFormRecipient.id)",
|
||||
lazy="raise",
|
||||
viewonly=True,
|
||||
)
|
||||
|
||||
|
||||
class HumanInputDelivery(DefaultFieldsMixin, Base):
|
||||
__tablename__ = "human_input_form_deliveries"
|
||||
__table_args__ = (
|
||||
sa.Index(
|
||||
None,
|
||||
"form_id",
|
||||
),
|
||||
)
|
||||
|
||||
form_id: Mapped[str] = mapped_column(
|
||||
StringUUID,
|
||||
nullable=False,
|
||||
)
|
||||
delivery_method_type: Mapped[DeliveryMethodType] = mapped_column(
|
||||
EnumText(DeliveryMethodType),
|
||||
nullable=False,
|
||||
)
|
||||
delivery_config_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
channel_payload: Mapped[str] = mapped_column(sa.Text, nullable=False)
|
||||
|
||||
form: Mapped[HumanInputForm] = relationship(
|
||||
"HumanInputForm",
|
||||
uselist=False,
|
||||
foreign_keys=[form_id],
|
||||
primaryjoin="HumanInputDelivery.form_id == HumanInputForm.id",
|
||||
back_populates="deliveries",
|
||||
lazy="raise",
|
||||
)
|
||||
|
||||
recipients: Mapped[list["HumanInputFormRecipient"]] = relationship(
|
||||
"HumanInputFormRecipient",
|
||||
primaryjoin="HumanInputDelivery.id == foreign(HumanInputFormRecipient.delivery_id)",
|
||||
uselist=True,
|
||||
back_populates="delivery",
|
||||
# Require explicit preloading
|
||||
lazy="raise",
|
||||
)
|
||||
|
||||
|
||||
class ApprovalChannel(StrEnum):
|
||||
"""Where a paused human input form can be approved, surfaced to API callers."""
|
||||
|
||||
EMAIL = "email"
|
||||
IM = "im"
|
||||
WEB_APP = "web_app"
|
||||
CONSOLE = "console"
|
||||
|
||||
|
||||
class RecipientType(StrEnum):
|
||||
# Second value = the approval channel this recipient maps to (surfaced in `approval_channels`).
|
||||
EMAIL_MEMBER = "email_member", ApprovalChannel.EMAIL
|
||||
EMAIL_EXTERNAL = "email_external", ApprovalChannel.EMAIL
|
||||
INSTANT_MESSAGE = "instant_message", ApprovalChannel.IM
|
||||
# STANDALONE_WEB_APP is used by the standalone web app.
|
||||
#
|
||||
# It's not used while running workflows / chatflows containing HumanInput
|
||||
# node inside console.
|
||||
STANDALONE_WEB_APP = "standalone_web_app", ApprovalChannel.WEB_APP
|
||||
# CONSOLE is used while running workflows / chatflows containing HumanInput
|
||||
# node inside console. (E.G. running installed apps or debugging workflows / chatflows)
|
||||
CONSOLE = "console", ApprovalChannel.CONSOLE
|
||||
# BACKSTAGE is used for backstage input inside console.
|
||||
BACKSTAGE = "backstage", ApprovalChannel.CONSOLE
|
||||
|
||||
_approval_channel: ApprovalChannel
|
||||
|
||||
def __new__(cls, value: str, approval_channel: ApprovalChannel) -> "RecipientType":
|
||||
member = str.__new__(cls, value)
|
||||
member._value_ = value
|
||||
member._approval_channel = approval_channel
|
||||
return member
|
||||
|
||||
@property
|
||||
def approval_channel(self) -> ApprovalChannel:
|
||||
return self._approval_channel
|
||||
|
||||
|
||||
@final
|
||||
class EmailMemberRecipientPayload(BaseModel):
|
||||
TYPE: Literal[RecipientType.EMAIL_MEMBER] = RecipientType.EMAIL_MEMBER
|
||||
user_id: str
|
||||
|
||||
# The `email` field here is only used for mail sending.
|
||||
email: str
|
||||
|
||||
|
||||
@final
|
||||
class EmailExternalRecipientPayload(BaseModel):
|
||||
TYPE: Literal[RecipientType.EMAIL_EXTERNAL] = RecipientType.EMAIL_EXTERNAL
|
||||
email: str
|
||||
|
||||
|
||||
@final
|
||||
class InstantMessageRecipientPayload(BaseModel):
|
||||
TYPE: Literal[RecipientType.INSTANT_MESSAGE] = RecipientType.INSTANT_MESSAGE
|
||||
provider: InstantMessageProvider
|
||||
recipient_kind: InstantMessageRecipientType
|
||||
channel_id: str | None = None
|
||||
user_id: str | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_target(self) -> Self:
|
||||
match self.recipient_kind:
|
||||
case InstantMessageRecipientType.CHANNEL:
|
||||
if self.channel_id is None or self.user_id is not None:
|
||||
raise ValueError("channel recipients must include channel_id and must not include user_id")
|
||||
case InstantMessageRecipientType.USER:
|
||||
if self.user_id is None or self.channel_id is not None:
|
||||
raise ValueError("user recipients must include user_id and must not include channel_id")
|
||||
return self
|
||||
|
||||
|
||||
@final
|
||||
class StandaloneWebAppRecipientPayload(BaseModel):
|
||||
TYPE: Literal[RecipientType.STANDALONE_WEB_APP] = RecipientType.STANDALONE_WEB_APP
|
||||
|
||||
|
||||
@final
|
||||
class ConsoleRecipientPayload(BaseModel):
|
||||
TYPE: Literal[RecipientType.CONSOLE] = RecipientType.CONSOLE
|
||||
account_id: str | None = None
|
||||
|
||||
|
||||
@final
|
||||
class BackstageRecipientPayload(BaseModel):
|
||||
TYPE: Literal[RecipientType.BACKSTAGE] = RecipientType.BACKSTAGE
|
||||
account_id: str | None = None
|
||||
|
||||
|
||||
@final
|
||||
class ConsoleDeliveryPayload(BaseModel):
|
||||
type: Literal["console"] = "console"
|
||||
internal: bool = True
|
||||
|
||||
|
||||
RecipientPayload = Annotated[
|
||||
EmailMemberRecipientPayload
|
||||
| EmailExternalRecipientPayload
|
||||
| InstantMessageRecipientPayload
|
||||
| StandaloneWebAppRecipientPayload
|
||||
| ConsoleRecipientPayload
|
||||
| BackstageRecipientPayload,
|
||||
Field(discriminator="TYPE"),
|
||||
]
|
||||
|
||||
|
||||
class HumanInputFormRecipient(DefaultFieldsMixin, Base):
|
||||
__tablename__ = "human_input_form_recipients"
|
||||
__table_args__ = (
|
||||
sa.Index(None, "form_id"),
|
||||
sa.Index(None, "delivery_id"),
|
||||
)
|
||||
|
||||
form_id: Mapped[str] = mapped_column(
|
||||
StringUUID,
|
||||
nullable=False,
|
||||
)
|
||||
delivery_id: Mapped[str] = mapped_column(
|
||||
StringUUID,
|
||||
nullable=False,
|
||||
)
|
||||
recipient_type: Mapped["RecipientType"] = mapped_column(EnumText(RecipientType), nullable=False)
|
||||
recipient_payload: Mapped[str] = mapped_column(sa.Text, nullable=False)
|
||||
|
||||
# Token primarily used for authenticated resume links (email, etc.).
|
||||
access_token: Mapped[str | None] = mapped_column(
|
||||
sa.VARCHAR(_token_field_length),
|
||||
nullable=False,
|
||||
default=_generate_token,
|
||||
unique=True,
|
||||
)
|
||||
|
||||
delivery: Mapped[HumanInputDelivery] = relationship(
|
||||
"HumanInputDelivery",
|
||||
uselist=False,
|
||||
foreign_keys=[delivery_id],
|
||||
back_populates="recipients",
|
||||
primaryjoin="HumanInputFormRecipient.delivery_id == HumanInputDelivery.id",
|
||||
# Require explicit preloading
|
||||
lazy="raise",
|
||||
)
|
||||
|
||||
form: Mapped[HumanInputForm] = relationship(
|
||||
"HumanInputForm",
|
||||
uselist=False,
|
||||
foreign_keys=[form_id],
|
||||
primaryjoin="HumanInputFormRecipient.form_id == HumanInputForm.id",
|
||||
# Require explicit preloading
|
||||
lazy="raise",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def new(
|
||||
cls,
|
||||
form_id: str,
|
||||
delivery_id: str,
|
||||
payload: RecipientPayload,
|
||||
) -> Self:
|
||||
recipient_model = cls(
|
||||
form_id=form_id,
|
||||
delivery_id=delivery_id,
|
||||
recipient_type=payload.TYPE,
|
||||
recipient_payload=payload.model_dump_json(),
|
||||
access_token=_generate_token(),
|
||||
)
|
||||
return recipient_model
|
||||
|
||||
|
||||
class HumanInputFormUploadToken(DefaultFieldsMixin, Base):
|
||||
"""Upload authorization token bound to one human input form recipient.
|
||||
|
||||
HITL upload tokens are intentionally separate from app/service bearer tokens.
|
||||
The token is stored as an opaque random value so upload endpoints can perform
|
||||
a direct lookup without entering the normal Web App authentication chain.
|
||||
Upload ownership is resolved from the form's workflow run initiator instead
|
||||
of being persisted on the token row itself.
|
||||
"""
|
||||
|
||||
__tablename__ = "human_input_form_upload_tokens"
|
||||
__table_args__ = (
|
||||
sa.UniqueConstraint("token", name="human_input_form_upload_tokens_token_key"),
|
||||
sa.Index("human_input_form_upload_tokens_form_id_idx", "form_id"),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
form_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
recipient_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
token: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
||||
|
||||
form: Mapped[HumanInputForm] = relationship(
|
||||
"HumanInputForm",
|
||||
uselist=False,
|
||||
foreign_keys=[form_id],
|
||||
primaryjoin="foreign(HumanInputFormUploadToken.form_id) == HumanInputForm.id",
|
||||
lazy="raise",
|
||||
)
|
||||
|
||||
|
||||
class HumanInputFormUploadFile(DefaultFieldsMixin, Base):
|
||||
"""Association between a human input form and a file uploaded through its token.
|
||||
|
||||
Ownership remains on ``UploadFile`` itself; this table only records the
|
||||
durable form/token/file linkage needed by Human Input flows.
|
||||
"""
|
||||
|
||||
__tablename__ = "human_input_form_upload_files"
|
||||
__table_args__ = (
|
||||
sa.UniqueConstraint("upload_file_id", name="human_input_form_upload_files_upload_file_id_key"),
|
||||
sa.Index("human_input_form_upload_files_form_id_idx", "form_id"),
|
||||
sa.Index("human_input_form_upload_files_upload_token_id_idx", "upload_token_id"),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
form_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
upload_file_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
upload_token_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,130 @@
|
||||
"""Persistent authorization for the irreversible P9 KnowledgeFS cleanup window."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import DateTime, Index, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import DefaultFieldsDCMixin, TypeBase
|
||||
from .types import EnumText, StringUUID
|
||||
|
||||
|
||||
class KnowledgeFSCleanupAuthorizationStatus(StrEnum):
|
||||
REQUESTED = "requested"
|
||||
APPROVED = "approved"
|
||||
STARTED = "started"
|
||||
COMPLETED = "completed"
|
||||
|
||||
|
||||
class KnowledgeFSCleanupTarget(StrEnum):
|
||||
LEGACY_SNAPSHOT_FOREIGN_KEYS = "legacy_snapshot_foreign_keys"
|
||||
LEGACY_ACL_ROUTES = "legacy_acl_routes"
|
||||
LEGACY_ACL_SCHEMA = "legacy_acl_schema"
|
||||
LEGACY_API_KEY_SCHEMA = "legacy_api_key_schema"
|
||||
LEGACY_V1_AUTH = "legacy_v1_auth"
|
||||
RAW_LIST_CREATE_PROXY = "raw_list_create_proxy"
|
||||
|
||||
|
||||
class KnowledgeFSCleanupAuthorization(DefaultFieldsDCMixin, TypeBase):
|
||||
"""Four-eyes approval and immutable evidence for one cleanup start fence."""
|
||||
|
||||
__tablename__ = "knowledge_fs_cleanup_authorizations"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="kfs_cleanup_authorization_pkey"),
|
||||
UniqueConstraint("tenant_id", "ledger_id", "request_id", name="kfs_cleanup_authorization_request_uq"),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tenant_id", "ledger_id"],
|
||||
["knowledge_fs_workspace_cutover_ledgers.tenant_id", "knowledge_fs_workspace_cutover_ledgers.id"],
|
||||
name="kfs_cleanup_authorization_ledger_fk",
|
||||
),
|
||||
Index("kfs_cleanup_authorization_status_idx", "tenant_id", "status", "updated_at"),
|
||||
sa.CheckConstraint("row_version >= 0", name=sa.schema.conv("kfs_cleanup_authorization_version_ck")),
|
||||
sa.CheckConstraint(
|
||||
"readiness_ledger_cas_version >= 0 "
|
||||
"AND (approved_ledger_cas_version IS NULL OR approved_ledger_cas_version >= 0) "
|
||||
"AND (started_ledger_cas_version IS NULL OR started_ledger_cas_version >= 0) "
|
||||
"AND (completed_ledger_cas_version IS NULL OR completed_ledger_cas_version >= 0)",
|
||||
name=sa.schema.conv("kfs_cleanup_authorization_ledger_versions_ck"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"(status = 'requested' "
|
||||
"AND approved_by_account_id IS NULL AND approved_at IS NULL "
|
||||
"AND approval_expires_at IS NULL AND approved_ledger_cas_version IS NULL "
|
||||
"AND started_by_account_id IS NULL AND started_at IS NULL "
|
||||
"AND started_ledger_cas_version IS NULL "
|
||||
"AND completed_by_account_id IS NULL AND completed_at IS NULL "
|
||||
"AND completion_evidence IS NULL AND completed_ledger_cas_version IS NULL) OR "
|
||||
"(status = 'approved' "
|
||||
"AND approved_by_account_id IS NOT NULL AND approved_at IS NOT NULL "
|
||||
"AND approval_expires_at IS NOT NULL AND approved_ledger_cas_version IS NOT NULL "
|
||||
"AND started_by_account_id IS NULL AND started_at IS NULL "
|
||||
"AND started_ledger_cas_version IS NULL "
|
||||
"AND completed_by_account_id IS NULL AND completed_at IS NULL "
|
||||
"AND completion_evidence IS NULL AND completed_ledger_cas_version IS NULL) OR "
|
||||
"(status = 'started' "
|
||||
"AND approved_by_account_id IS NOT NULL AND approved_at IS NOT NULL "
|
||||
"AND approval_expires_at IS NOT NULL AND approved_ledger_cas_version IS NOT NULL "
|
||||
"AND started_by_account_id IS NOT NULL AND started_at IS NOT NULL "
|
||||
"AND started_ledger_cas_version IS NOT NULL "
|
||||
"AND completed_by_account_id IS NULL AND completed_at IS NULL "
|
||||
"AND completion_evidence IS NULL AND completed_ledger_cas_version IS NULL) OR "
|
||||
"(status = 'completed' "
|
||||
"AND approved_by_account_id IS NOT NULL AND approved_at IS NOT NULL "
|
||||
"AND approval_expires_at IS NOT NULL AND approved_ledger_cas_version IS NOT NULL "
|
||||
"AND started_by_account_id IS NOT NULL AND started_at IS NOT NULL "
|
||||
"AND started_ledger_cas_version IS NOT NULL "
|
||||
"AND completed_by_account_id IS NOT NULL AND completed_at IS NOT NULL "
|
||||
"AND completion_evidence IS NOT NULL AND completed_ledger_cas_version IS NOT NULL)",
|
||||
name=sa.schema.conv("kfs_cleanup_authorization_status_fields_ck"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"approval_expires_at IS NULL OR approval_expires_at > approved_at",
|
||||
name=sa.schema.conv("kfs_cleanup_authorization_approval_window_ck"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"completed_at IS NULL OR completed_at >= started_at",
|
||||
name=sa.schema.conv("kfs_cleanup_authorization_completion_time_ck"),
|
||||
),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
ledger_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
request_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
plan_schema_version: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
plan_digest: Mapped[str] = mapped_column(String(71), nullable=False)
|
||||
targets: Mapped[list[str]] = mapped_column(sa.JSON, nullable=False)
|
||||
readiness_evidence: Mapped[dict[str, object]] = mapped_column(sa.JSON, nullable=False)
|
||||
requested_by_account_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
requested_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
readiness_ledger_cas_version: Mapped[int] = mapped_column(sa.BigInteger, nullable=False)
|
||||
status: Mapped[KnowledgeFSCleanupAuthorizationStatus] = mapped_column(
|
||||
EnumText(KnowledgeFSCleanupAuthorizationStatus, length=16),
|
||||
nullable=False,
|
||||
server_default=sa.text("'requested'"),
|
||||
default=KnowledgeFSCleanupAuthorizationStatus.REQUESTED,
|
||||
)
|
||||
approved_by_account_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
approved_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
approval_expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
approved_ledger_cas_version: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True, default=None)
|
||||
started_by_account_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
started_ledger_cas_version: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True, default=None)
|
||||
completed_by_account_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
completed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
completion_evidence: Mapped[dict[str, object] | None] = mapped_column(
|
||||
sa.JSON(none_as_null=True), nullable=True, default=None
|
||||
)
|
||||
completed_ledger_cas_version: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True, default=None)
|
||||
row_version: Mapped[int] = mapped_column(sa.BigInteger, nullable=False, server_default=sa.text("0"), default=0)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"KnowledgeFSCleanupAuthorization",
|
||||
"KnowledgeFSCleanupAuthorizationStatus",
|
||||
"KnowledgeFSCleanupTarget",
|
||||
]
|
||||
@@ -0,0 +1,507 @@
|
||||
"""Workspace-scoped KnowledgeFS migration and cutover persistence.
|
||||
|
||||
The ledger is Dify control-plane state only. It deliberately stores opaque
|
||||
KnowledgeFS identifiers and authorization watermarks without foreign keys or
|
||||
queries to legacy product tables. Cutover feature switches live on one
|
||||
row so the repository can change them with a single CAS statement. Quarantine
|
||||
remediation is separately CAS-versioned and retains immutable operator evidence.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import TypedDict
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import DateTime, Index, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import DefaultFieldsDCMixin, TypeBase
|
||||
from .types import EnumText, LongText, StringUUID
|
||||
|
||||
|
||||
class KnowledgeFSCutoverRevisionWatermark(TypedDict):
|
||||
membership_epoch: int
|
||||
space_acl_epoch: int
|
||||
external_access_epoch: int
|
||||
content_policy_revision: int
|
||||
|
||||
|
||||
class KnowledgeFSCutoverSmokeChecks(TypedDict):
|
||||
authorization: bool
|
||||
list_spaces: bool
|
||||
create_space: bool
|
||||
query: bool
|
||||
upload: bool
|
||||
stream: bool
|
||||
deletion: bool
|
||||
|
||||
|
||||
class KnowledgeFSCutoverSmokeEvidenceReferences(TypedDict):
|
||||
authorization: str
|
||||
list_spaces: str
|
||||
create_space: str
|
||||
query: str
|
||||
upload: str
|
||||
stream: str
|
||||
deletion: str
|
||||
|
||||
|
||||
class KnowledgeFSCutoverSmokeResults(TypedDict):
|
||||
schema_version: str
|
||||
tenant_id: str
|
||||
environment: str
|
||||
operator: str
|
||||
operator_account_id: str
|
||||
observed_at: str
|
||||
checks: KnowledgeFSCutoverSmokeChecks
|
||||
evidence_references: KnowledgeFSCutoverSmokeEvidenceReferences
|
||||
|
||||
|
||||
def knowledge_fs_cutover_smoke_results_passed(value: KnowledgeFSCutoverSmokeResults | None) -> bool:
|
||||
"""Reject incomplete or pre-production JSON evidence instead of treating metadata as booleans."""
|
||||
|
||||
if not isinstance(value, dict):
|
||||
return False
|
||||
checks = value.get("checks")
|
||||
references = value.get("evidence_references")
|
||||
expected = {
|
||||
"authorization",
|
||||
"list_spaces",
|
||||
"create_space",
|
||||
"query",
|
||||
"upload",
|
||||
"stream",
|
||||
"deletion",
|
||||
}
|
||||
return bool(
|
||||
value.get("schema_version") == "knowledge-fs-p8-cutover-smoke/v1"
|
||||
and value.get("environment") == "production"
|
||||
and isinstance(checks, dict)
|
||||
and set(checks) == expected
|
||||
and all(checks.get(name) is True for name in expected)
|
||||
and isinstance(references, dict)
|
||||
and set(references) == expected
|
||||
and all(isinstance(reference := references.get(name), str) and bool(reference) for name in expected)
|
||||
)
|
||||
|
||||
|
||||
class KnowledgeFSWorkspaceCutoverPhase(StrEnum):
|
||||
INVENTORY = "inventory"
|
||||
BACKFILL = "backfill"
|
||||
SHADOW = "shadow"
|
||||
FROZEN = "frozen"
|
||||
CUTOVER = "cutover"
|
||||
OBSERVING = "observing"
|
||||
READY_FOR_CLEANUP = "ready_for_cleanup"
|
||||
|
||||
|
||||
class KnowledgeFSMigrationIssueStatus(StrEnum):
|
||||
OPEN = "open"
|
||||
APPROVED_FAIL_CLOSED = "approved_fail_closed"
|
||||
RESOLVED = "resolved"
|
||||
|
||||
|
||||
class KnowledgeFSMigrationIssueKind(StrEnum):
|
||||
REGISTRATION_CONFLICT = "registration_conflict"
|
||||
UNRESOLVED_SUBJECT = "unresolved_subject"
|
||||
UNKNOWN_EXTERNAL_ACCESS = "unknown_external_access"
|
||||
REVISION_DRIFT = "revision_drift"
|
||||
TASK_QUARANTINE = "task_quarantine"
|
||||
LEGACY_SNAPSHOT_DEPENDENCY = "legacy_snapshot_dependency"
|
||||
LEGACY_FOREIGN_KEY_DEPENDENCY = "legacy_foreign_key_dependency"
|
||||
|
||||
|
||||
class KnowledgeFSMigrationQuarantineKind(StrEnum):
|
||||
CONTROL_SPACE = "control_space"
|
||||
SUBJECT = "subject"
|
||||
TASK = "task"
|
||||
LEGACY_API_KEY = "legacy_api_key"
|
||||
ORPHAN_RESOURCE = "orphan_resource"
|
||||
|
||||
|
||||
class KnowledgeFSMigrationQuarantineDisposition(StrEnum):
|
||||
PENDING = "pending"
|
||||
MIGRATABLE = "migratable"
|
||||
WAIT_FOR_COMPLETION = "wait_for_completion"
|
||||
CANCEL = "cancel"
|
||||
ISOLATE = "isolate"
|
||||
ROTATE_CREDENTIAL = "rotate_credential"
|
||||
RESOLVED = "resolved"
|
||||
|
||||
|
||||
class KnowledgeFSShadowAuthorizationDecision(StrEnum):
|
||||
MATCH = "match"
|
||||
TIGHTENED = "tightened"
|
||||
EXPANDED = "expanded"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
class KnowledgeFSWorkspaceCutoverLedger(DefaultFieldsDCMixin, TypeBase):
|
||||
"""Single-Workspace migration state, watermarks, switches, and time fences."""
|
||||
|
||||
__tablename__ = "knowledge_fs_workspace_cutover_ledgers"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="kfs_workspace_cutover_ledger_pkey"),
|
||||
UniqueConstraint("tenant_id", name="kfs_workspace_cutover_ledger_tenant_uq"),
|
||||
UniqueConstraint("tenant_id", "id", name="kfs_workspace_cutover_ledger_tenant_id_uq"),
|
||||
Index("kfs_workspace_cutover_ledger_phase_updated_idx", "phase", "updated_at"),
|
||||
sa.CheckConstraint("cas_version >= 0", name=sa.schema.conv("kfs_workspace_cutover_cas_version_ck")),
|
||||
sa.CheckConstraint(
|
||||
"source_task_watermark >= 0 AND applied_task_watermark >= 0 "
|
||||
"AND (final_task_watermark IS NULL OR final_task_watermark >= 0)",
|
||||
name=sa.schema.conv("kfs_workspace_cutover_task_watermark_ck"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"cutover_at IS NULL OR freeze_at IS NOT NULL",
|
||||
name=sa.schema.conv("kfs_workspace_cutover_freeze_before_cutover_ck"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"rollback_cutoff_at IS NULL OR cutover_at IS NOT NULL",
|
||||
name=sa.schema.conv("kfs_workspace_cutover_rollback_cutoff_ck"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"shadow_observation_count >= 0",
|
||||
name=sa.schema.conv("kfs_workspace_cutover_shadow_count_ck"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"shadow_window_ended_at IS NULL OR shadow_window_started_at IS NOT NULL",
|
||||
name=sa.schema.conv("kfs_workspace_cutover_shadow_window_ck"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"(shadow_completed_at IS NULL "
|
||||
"AND shadow_evidence_digest IS NULL AND shadow_producer IS NULL "
|
||||
"AND shadow_completed_by_operator IS NULL AND shadow_completed_by_account_id IS NULL "
|
||||
"AND shadow_window_started_at IS NULL AND shadow_window_ended_at IS NULL "
|
||||
"AND shadow_traffic_zero = false AND shadow_traffic_zero_evidence IS NULL "
|
||||
"AND shadow_latest_observed_revision IS NULL) OR "
|
||||
"(shadow_completed_at IS NOT NULL AND shadow_started_at IS NOT NULL "
|
||||
"AND shadow_evidence_digest IS NOT NULL AND shadow_producer IS NOT NULL "
|
||||
"AND shadow_completed_by_operator IS NOT NULL AND shadow_completed_by_account_id IS NOT NULL "
|
||||
"AND ((shadow_traffic_zero = true AND shadow_observation_count = 0 "
|
||||
"AND shadow_traffic_zero_evidence IS NOT NULL AND shadow_window_started_at IS NULL "
|
||||
"AND shadow_window_ended_at IS NULL AND shadow_latest_observed_revision IS NULL) OR "
|
||||
"(shadow_traffic_zero = false AND shadow_observation_count > 0 "
|
||||
"AND shadow_traffic_zero_evidence IS NULL AND shadow_window_started_at IS NOT NULL "
|
||||
"AND shadow_window_ended_at IS NOT NULL AND shadow_latest_observed_revision IS NOT NULL)))",
|
||||
name=sa.schema.conv("kfs_workspace_cutover_shadow_completion_fields_ck"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"(remote_freeze_id IS NULL AND remote_freeze_revision IS NULL "
|
||||
"AND remote_freeze_digest IS NULL AND remote_freeze_task_watermark IS NULL "
|
||||
"AND remote_freeze_control_space_id IS NULL AND remote_freeze_frozen_at IS NULL "
|
||||
"AND remote_freeze_updated_at IS NULL AND remote_freeze_acknowledged_at IS NULL "
|
||||
"AND remote_freeze_applied IS NULL AND remote_freeze_replayed IS NULL) OR "
|
||||
"(remote_freeze_id IS NOT NULL AND remote_freeze_revision BETWEEN 1 AND 9007199254740991 "
|
||||
"AND remote_freeze_digest IS NOT NULL AND remote_freeze_task_watermark >= 0 "
|
||||
"AND remote_freeze_control_space_id IS NOT NULL AND remote_freeze_frozen_at IS NOT NULL "
|
||||
"AND remote_freeze_updated_at IS NOT NULL AND remote_freeze_acknowledged_at IS NOT NULL "
|
||||
"AND ((remote_freeze_applied = true AND remote_freeze_replayed = false) "
|
||||
"OR (remote_freeze_applied = false AND remote_freeze_replayed = true)))",
|
||||
name=sa.schema.conv("kfs_workspace_cutover_remote_freeze_fields_ck"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"remote_freeze_updated_at IS NULL OR remote_freeze_updated_at >= remote_freeze_frozen_at",
|
||||
name=sa.schema.conv("kfs_workspace_cutover_remote_freeze_time_ck"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"(remote_activation_id IS NULL AND remote_activation_revision IS NULL "
|
||||
"AND remote_activation_digest IS NULL AND remote_activation_control_space_id IS NULL "
|
||||
"AND remote_activation_activated_at IS NULL AND remote_activation_updated_at IS NULL "
|
||||
"AND remote_activation_acknowledged_at IS NULL AND remote_activation_applied IS NULL "
|
||||
"AND remote_activation_replayed IS NULL) OR "
|
||||
"(remote_activation_id IS NOT NULL AND remote_activation_revision BETWEEN 1 AND 9007199254740991 "
|
||||
"AND remote_activation_digest IS NOT NULL AND remote_activation_control_space_id IS NOT NULL "
|
||||
"AND remote_activation_activated_at IS NOT NULL AND remote_activation_updated_at IS NOT NULL "
|
||||
"AND remote_activation_acknowledged_at IS NOT NULL "
|
||||
"AND ((remote_activation_applied = true AND remote_activation_replayed = false) "
|
||||
"OR (remote_activation_applied = false AND remote_activation_replayed = true)))",
|
||||
name=sa.schema.conv("kfs_workspace_cutover_remote_activation_fields_ck"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"remote_activation_updated_at IS NULL OR remote_activation_updated_at >= remote_activation_activated_at",
|
||||
name=sa.schema.conv("kfs_workspace_cutover_remote_activation_time_ck"),
|
||||
),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
source_revision_watermark: Mapped[KnowledgeFSCutoverRevisionWatermark] = mapped_column(sa.JSON, nullable=False)
|
||||
applied_revision_watermark: Mapped[KnowledgeFSCutoverRevisionWatermark] = mapped_column(sa.JSON, nullable=False)
|
||||
phase: Mapped[KnowledgeFSWorkspaceCutoverPhase] = mapped_column(
|
||||
EnumText(KnowledgeFSWorkspaceCutoverPhase, length=32),
|
||||
nullable=False,
|
||||
server_default=sa.text("'inventory'"),
|
||||
default=KnowledgeFSWorkspaceCutoverPhase.INVENTORY,
|
||||
)
|
||||
final_revision_watermark: Mapped[KnowledgeFSCutoverRevisionWatermark | None] = mapped_column(
|
||||
sa.JSON, nullable=True, default=None
|
||||
)
|
||||
source_task_watermark: Mapped[int] = mapped_column(
|
||||
sa.BigInteger, nullable=False, server_default=sa.text("0"), default=0
|
||||
)
|
||||
final_task_watermark: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True, default=None)
|
||||
applied_task_watermark: Mapped[int] = mapped_column(
|
||||
sa.BigInteger, nullable=False, server_default=sa.text("0"), default=0
|
||||
)
|
||||
shadow_started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
shadow_completed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
shadow_evidence_digest: Mapped[str | None] = mapped_column(String(71), nullable=True, default=None)
|
||||
shadow_observation_count: Mapped[int] = mapped_column(
|
||||
sa.BigInteger, nullable=False, server_default=sa.text("0"), default=0
|
||||
)
|
||||
shadow_window_started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
shadow_window_ended_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
shadow_traffic_zero: Mapped[bool] = mapped_column(
|
||||
sa.Boolean, nullable=False, server_default=sa.text("false"), default=False
|
||||
)
|
||||
shadow_traffic_zero_evidence: Mapped[dict[str, object] | None] = mapped_column(
|
||||
sa.JSON(none_as_null=True), nullable=True, default=None
|
||||
)
|
||||
shadow_latest_observed_revision: Mapped[KnowledgeFSCutoverRevisionWatermark | None] = mapped_column(
|
||||
sa.JSON(none_as_null=True), nullable=True, default=None
|
||||
)
|
||||
shadow_producer: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
shadow_completed_by_operator: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
shadow_completed_by_account_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
remote_freeze_id: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
remote_freeze_revision: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True, default=None)
|
||||
remote_freeze_digest: Mapped[str | None] = mapped_column(String(71), nullable=True, default=None)
|
||||
remote_freeze_task_watermark: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True, default=None)
|
||||
remote_freeze_control_space_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
remote_freeze_frozen_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
remote_freeze_updated_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
remote_freeze_acknowledged_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
remote_freeze_applied: Mapped[bool | None] = mapped_column(sa.Boolean, nullable=True, default=None)
|
||||
remote_freeze_replayed: Mapped[bool | None] = mapped_column(sa.Boolean, nullable=True, default=None)
|
||||
remote_activation_id: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
remote_activation_revision: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True, default=None)
|
||||
remote_activation_digest: Mapped[str | None] = mapped_column(String(71), nullable=True, default=None)
|
||||
remote_activation_control_space_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
remote_activation_activated_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
remote_activation_updated_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
remote_activation_acknowledged_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
remote_activation_applied: Mapped[bool | None] = mapped_column(sa.Boolean, nullable=True, default=None)
|
||||
remote_activation_replayed: Mapped[bool | None] = mapped_column(sa.Boolean, nullable=True, default=None)
|
||||
freeze_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
cutover_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
rolled_back_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
rollback_cutoff_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
observation_started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
observation_window_ends_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
observation_completed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
maximum_task_expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
irreversible_cleanup_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
product_routes_enabled: Mapped[bool] = mapped_column(
|
||||
sa.Boolean, nullable=False, server_default=sa.text("false"), default=False
|
||||
)
|
||||
capability_v2_enabled: Mapped[bool] = mapped_column(
|
||||
sa.Boolean, nullable=False, server_default=sa.text("false"), default=False
|
||||
)
|
||||
integrated_mode_enabled: Mapped[bool] = mapped_column(
|
||||
sa.Boolean, nullable=False, server_default=sa.text("false"), default=False
|
||||
)
|
||||
legacy_acl_read_only: Mapped[bool] = mapped_column(
|
||||
sa.Boolean, nullable=False, server_default=sa.text("false"), default=False
|
||||
)
|
||||
smoke_results: Mapped[KnowledgeFSCutoverSmokeResults | None] = mapped_column(sa.JSON, nullable=True, default=None)
|
||||
legacy_dependency_report: Mapped[list[dict[str, object]] | None] = mapped_column(
|
||||
sa.JSON, nullable=True, default=None
|
||||
)
|
||||
legacy_dependency_checked_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
legacy_dependency_ready: Mapped[bool] = mapped_column(
|
||||
sa.Boolean, nullable=False, server_default=sa.text("false"), default=False
|
||||
)
|
||||
cas_version: Mapped[int] = mapped_column(sa.BigInteger, nullable=False, server_default=sa.text("0"), default=0)
|
||||
|
||||
|
||||
class KnowledgeFSMigrationIssue(DefaultFieldsDCMixin, TypeBase):
|
||||
"""Auditable blocker; unknown access can only be approved as fail-closed."""
|
||||
|
||||
__tablename__ = "knowledge_fs_migration_issues"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="kfs_migration_issue_pkey"),
|
||||
UniqueConstraint("tenant_id", "ledger_id", "issue_key", name="kfs_migration_issue_key_uq"),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tenant_id", "ledger_id"],
|
||||
["knowledge_fs_workspace_cutover_ledgers.tenant_id", "knowledge_fs_workspace_cutover_ledgers.id"],
|
||||
name="kfs_migration_issue_ledger_fk",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
Index("kfs_migration_issue_gate_idx", "tenant_id", "ledger_id", "status", "kind"),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
ledger_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
issue_key: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
kind: Mapped[KnowledgeFSMigrationIssueKind] = mapped_column(
|
||||
EnumText(KnowledgeFSMigrationIssueKind, length=48), nullable=False
|
||||
)
|
||||
status: Mapped[KnowledgeFSMigrationIssueStatus] = mapped_column(
|
||||
EnumText(KnowledgeFSMigrationIssueStatus, length=32),
|
||||
nullable=False,
|
||||
server_default=sa.text("'open'"),
|
||||
default=KnowledgeFSMigrationIssueStatus.OPEN,
|
||||
)
|
||||
resource_type: Mapped[str | None] = mapped_column(String(64), nullable=True, default=None)
|
||||
resource_id: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
details: Mapped[dict[str, object]] = mapped_column(sa.JSON, nullable=False, default_factory=dict)
|
||||
approved_by_account_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
approved_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
resolved_by_account_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
resolved_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
|
||||
|
||||
class KnowledgeFSMigrationQuarantine(DefaultFieldsDCMixin, TypeBase):
|
||||
"""Fail-closed inventory item whose operator resolution is immutable and CAS-versioned."""
|
||||
|
||||
__tablename__ = "knowledge_fs_migration_quarantine"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="kfs_migration_quarantine_pkey"),
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"ledger_id",
|
||||
"source_kind",
|
||||
"source_id",
|
||||
name="kfs_migration_quarantine_source_uq",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tenant_id", "ledger_id"],
|
||||
["knowledge_fs_workspace_cutover_ledgers.tenant_id", "knowledge_fs_workspace_cutover_ledgers.id"],
|
||||
name="kfs_migration_quarantine_ledger_fk",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
Index("kfs_migration_quarantine_disposition_idx", "tenant_id", "ledger_id", "disposition"),
|
||||
sa.CheckConstraint("row_version >= 0", name=sa.schema.conv("kfs_migration_quarantine_version_ck")),
|
||||
sa.CheckConstraint(
|
||||
"(disposition = 'resolved' "
|
||||
"AND resolved_by_operator IS NOT NULL AND resolved_by_account_id IS NOT NULL "
|
||||
"AND evidence IS NOT NULL AND resolved_at IS NOT NULL) OR "
|
||||
"(disposition <> 'resolved' "
|
||||
"AND resolved_by_operator IS NULL AND resolved_by_account_id IS NULL "
|
||||
"AND evidence IS NULL AND resolved_at IS NULL)",
|
||||
name=sa.schema.conv("kfs_migration_quarantine_resolution_fields_ck"),
|
||||
),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
ledger_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
source_kind: Mapped[KnowledgeFSMigrationQuarantineKind] = mapped_column(
|
||||
EnumText(KnowledgeFSMigrationQuarantineKind, length=32), nullable=False
|
||||
)
|
||||
source_id: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
reason_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
disposition: Mapped[KnowledgeFSMigrationQuarantineDisposition] = mapped_column(
|
||||
EnumText(KnowledgeFSMigrationQuarantineDisposition, length=32), nullable=False
|
||||
)
|
||||
details: Mapped[dict[str, object]] = mapped_column(sa.JSON, nullable=False, default_factory=dict)
|
||||
resolved_by_operator: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
resolved_by_account_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
evidence: Mapped[dict[str, object] | None] = mapped_column(sa.JSON(none_as_null=True), nullable=True, default=None)
|
||||
resolved_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
row_version: Mapped[int] = mapped_column(sa.BigInteger, nullable=False, server_default=sa.text("0"), default=0)
|
||||
|
||||
|
||||
class KnowledgeFSShadowAuthorizationDiff(DefaultFieldsDCMixin, TypeBase):
|
||||
"""Current disposition for a diff key; append-only observations retain its history."""
|
||||
|
||||
__tablename__ = "knowledge_fs_shadow_authorization_diffs"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="kfs_shadow_authorization_diff_pkey"),
|
||||
UniqueConstraint("tenant_id", "ledger_id", "diff_key", name="kfs_shadow_authorization_diff_key_uq"),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tenant_id", "ledger_id"],
|
||||
["knowledge_fs_workspace_cutover_ledgers.tenant_id", "knowledge_fs_workspace_cutover_ledgers.id"],
|
||||
name="kfs_shadow_authorization_diff_ledger_fk",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
Index("kfs_shadow_authorization_diff_gate_idx", "tenant_id", "ledger_id", "status", "decision"),
|
||||
sa.CheckConstraint("row_version >= 0", name=sa.schema.conv("kfs_shadow_authorization_diff_version_ck")),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
ledger_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
diff_key: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
principal: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
dify_allowed: Mapped[bool] = mapped_column(sa.Boolean, nullable=False)
|
||||
decision: Mapped[KnowledgeFSShadowAuthorizationDecision] = mapped_column(
|
||||
EnumText(KnowledgeFSShadowAuthorizationDecision, length=32), nullable=False
|
||||
)
|
||||
reason: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
observed_revision: Mapped[KnowledgeFSCutoverRevisionWatermark] = mapped_column(sa.JSON, nullable=False)
|
||||
status: Mapped[KnowledgeFSMigrationIssueStatus] = mapped_column(
|
||||
EnumText(KnowledgeFSMigrationIssueStatus, length=32), nullable=False
|
||||
)
|
||||
current_evidence_digest: Mapped[str] = mapped_column(String(71), nullable=False)
|
||||
last_observed_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
control_space_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
legacy_allowed: Mapped[bool | None] = mapped_column(sa.Boolean, nullable=True, default=None)
|
||||
approved_by_account_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
approved_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
resolved_by_account_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
resolved_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
row_version: Mapped[int] = mapped_column(sa.BigInteger, nullable=False, server_default=sa.text("0"), default=0)
|
||||
|
||||
|
||||
class KnowledgeFSShadowAuthorizationObservation(DefaultFieldsDCMixin, TypeBase):
|
||||
"""Append-only producer evidence used to derive a shadow diff disposition."""
|
||||
|
||||
__tablename__ = "knowledge_fs_shadow_authorization_observations"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="kfs_shadow_authorization_observation_pkey"),
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"ledger_id",
|
||||
"diff_key",
|
||||
"evidence_digest",
|
||||
name="kfs_shadow_authorization_observation_evidence_uq",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tenant_id", "ledger_id"],
|
||||
["knowledge_fs_workspace_cutover_ledgers.tenant_id", "knowledge_fs_workspace_cutover_ledgers.id"],
|
||||
name="kfs_shadow_authorization_observation_ledger_fk",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
Index(
|
||||
"kfs_shadow_authorization_observation_window_idx",
|
||||
"tenant_id",
|
||||
"ledger_id",
|
||||
"observed_at",
|
||||
),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
ledger_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
diff_key: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
producer: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
principal: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
dify_allowed: Mapped[bool] = mapped_column(sa.Boolean, nullable=False)
|
||||
decision: Mapped[KnowledgeFSShadowAuthorizationDecision] = mapped_column(
|
||||
EnumText(KnowledgeFSShadowAuthorizationDecision, length=32), nullable=False
|
||||
)
|
||||
reason: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
observed_revision: Mapped[KnowledgeFSCutoverRevisionWatermark] = mapped_column(sa.JSON, nullable=False)
|
||||
observed_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
evidence_digest: Mapped[str] = mapped_column(String(71), nullable=False)
|
||||
control_space_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
legacy_allowed: Mapped[bool | None] = mapped_column(sa.Boolean, nullable=True, default=None)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"KnowledgeFSCutoverRevisionWatermark",
|
||||
"KnowledgeFSCutoverSmokeChecks",
|
||||
"KnowledgeFSCutoverSmokeEvidenceReferences",
|
||||
"KnowledgeFSCutoverSmokeResults",
|
||||
"KnowledgeFSMigrationIssue",
|
||||
"KnowledgeFSMigrationIssueKind",
|
||||
"KnowledgeFSMigrationIssueStatus",
|
||||
"KnowledgeFSMigrationQuarantine",
|
||||
"KnowledgeFSMigrationQuarantineDisposition",
|
||||
"KnowledgeFSMigrationQuarantineKind",
|
||||
"KnowledgeFSShadowAuthorizationDecision",
|
||||
"KnowledgeFSShadowAuthorizationDiff",
|
||||
"KnowledgeFSShadowAuthorizationObservation",
|
||||
"KnowledgeFSWorkspaceCutoverLedger",
|
||||
"KnowledgeFSWorkspaceCutoverPhase",
|
||||
"knowledge_fs_cutover_smoke_results_passed",
|
||||
]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,127 @@
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from libs.uuid_utils import uuidv7
|
||||
|
||||
from .base import TypeBase
|
||||
from .enums import PermissionEnum
|
||||
from .types import AdjustedJSON, EnumText, LongText, StringUUID
|
||||
|
||||
|
||||
class DatasourceOauthParamConfig(TypeBase):
|
||||
__tablename__ = "datasource_oauth_params"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="datasource_oauth_config_pkey"),
|
||||
sa.UniqueConstraint("plugin_id", "provider", name="datasource_oauth_config_datasource_id_provider_idx"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuidv7()), default_factory=lambda: str(uuidv7()), init=False
|
||||
)
|
||||
plugin_id: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
||||
provider: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
||||
system_credentials: Mapped[dict[str, Any]] = mapped_column(AdjustedJSON, nullable=False)
|
||||
|
||||
|
||||
class DatasourceProvider(TypeBase):
|
||||
__tablename__ = "datasource_providers"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="datasource_provider_pkey"),
|
||||
sa.UniqueConstraint("tenant_id", "plugin_id", "provider", "name", name="datasource_provider_unique_name"),
|
||||
sa.Index("datasource_provider_auth_type_provider_idx", "tenant_id", "plugin_id", "provider"),
|
||||
)
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuidv7()), default_factory=lambda: str(uuidv7()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
name: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
||||
provider: Mapped[str] = mapped_column(sa.String(128), nullable=False)
|
||||
plugin_id: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
||||
auth_type: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
||||
encrypted_credentials: Mapped[dict[str, Any]] = mapped_column(AdjustedJSON, nullable=False)
|
||||
user_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
avatar_url: Mapped[str] = mapped_column(LongText, nullable=True, default="default")
|
||||
is_default: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
|
||||
expires_at: Mapped[int] = mapped_column(sa.Integer, nullable=False, default=-1)
|
||||
visibility: Mapped[PermissionEnum] = mapped_column(
|
||||
EnumText(PermissionEnum, length=40), nullable=False, default=PermissionEnum.ALL_TEAM
|
||||
)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
|
||||
class DatasourceOauthTenantParamConfig(TypeBase):
|
||||
__tablename__ = "datasource_oauth_tenant_params"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="datasource_oauth_tenant_config_pkey"),
|
||||
sa.UniqueConstraint("tenant_id", "plugin_id", "provider", name="datasource_oauth_tenant_config_unique"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuidv7()), default_factory=lambda: str(uuidv7()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
provider: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
||||
plugin_id: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
||||
client_params: Mapped[dict[str, Any]] = mapped_column(AdjustedJSON, nullable=False, default_factory=dict)
|
||||
enabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
|
||||
class OAuthAccessToken(TypeBase):
|
||||
"""Device-flow bearer. account_id NOT NULL ⇒ dfoa_ (Dify account,
|
||||
subject_issuer = "dify:account" sentinel); account_id NULL +
|
||||
subject_issuer = verified IdP issuer ⇒ dfoe_ (external SSO, EE-only).
|
||||
subject_issuer is non-NULL for all rows the app writes — Postgres
|
||||
treats NULLs as distinct in unique indices, so the partial unique
|
||||
index on (subject_email, subject_issuer, client_id, device_label)
|
||||
WHERE revoked_at IS NULL would otherwise fail to rotate in place.
|
||||
"""
|
||||
|
||||
__tablename__ = "oauth_access_tokens"
|
||||
__table_args__ = (sa.PrimaryKeyConstraint("id", name="oauth_access_tokens_pkey"),)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuidv7()), default_factory=lambda: str(uuidv7()), init=False
|
||||
)
|
||||
# Indexed text columns are bounded VARCHARs so the schema is portable
|
||||
# across PostgreSQL and MySQL (MySQL cannot index TEXT without a prefix
|
||||
# length). 255 chars accommodates RFC-compliant emails and typical
|
||||
# OIDC issuer URLs / device labels.
|
||||
subject_email: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
||||
client_id: Mapped[str] = mapped_column(sa.String(64), nullable=False)
|
||||
device_label: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
||||
prefix: Mapped[str] = mapped_column(sa.String(8), nullable=False)
|
||||
expires_at: Mapped[datetime] = mapped_column(sa.DateTime(timezone=True), nullable=False)
|
||||
subject_issuer: Mapped[str | None] = mapped_column(sa.String(255), nullable=True, default=None)
|
||||
account_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
token_hash: Mapped[str | None] = mapped_column(sa.String(64), nullable=True, default=None)
|
||||
last_used_at: Mapped[datetime | None] = mapped_column(sa.DateTime(timezone=True), nullable=True, default=None)
|
||||
revoked_at: Mapped[datetime | None] = mapped_column(sa.DateTime(timezone=True), nullable=True, default=None)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime(timezone=True), nullable=False, server_default=func.now(), init=False
|
||||
)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Account-level onboarding state models."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import DateTime, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import TypeBase, gen_uuidv7_string
|
||||
from .types import AdjustedJSON, StringUUID
|
||||
|
||||
|
||||
class AccountStepByStepTourState(TypeBase):
|
||||
"""Persistent account-level Step-by-step Tour state.
|
||||
|
||||
The tour is account-owned, with workspace IDs stored only as presentation
|
||||
overrides. The first workspace is the workspace context where an eligible
|
||||
account first asks for tour state; subsequent workspaces are opt-in only.
|
||||
"""
|
||||
|
||||
__tablename__ = "account_step_by_step_tour_states"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="account_step_by_step_tour_state_pkey"),
|
||||
sa.UniqueConstraint("account_id", name="account_step_by_step_tour_state_account_id_key"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID,
|
||||
insert_default=gen_uuidv7_string,
|
||||
default_factory=gen_uuidv7_string,
|
||||
init=False,
|
||||
)
|
||||
account_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
first_workspace_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
skipped: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
|
||||
completed_task_ids: Mapped[list[str]] = mapped_column(AdjustedJSON, nullable=False, default_factory=list)
|
||||
manually_enabled_workspace_ids: Mapped[list[str]] = mapped_column(
|
||||
AdjustedJSON,
|
||||
nullable=False,
|
||||
default_factory=list,
|
||||
)
|
||||
manually_disabled_workspace_ids: Mapped[list[str]] = mapped_column(
|
||||
AdjustedJSON,
|
||||
nullable=False,
|
||||
default_factory=list,
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
server_default=func.current_timestamp(),
|
||||
nullable=False,
|
||||
init=False,
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
server_default=func.current_timestamp(),
|
||||
nullable=False,
|
||||
init=False,
|
||||
onupdate=func.current_timestamp(),
|
||||
)
|
||||
@@ -0,0 +1,366 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from enum import StrEnum, auto
|
||||
from functools import cached_property
|
||||
from typing import override
|
||||
from uuid import uuid4
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import DateTime, String, func, select, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from core.db.session_factory import session_factory
|
||||
from graphon.model_runtime.entities.model_entities import ModelType
|
||||
from libs.uuid_utils import uuidv7
|
||||
|
||||
from .base import TypeBase
|
||||
from .enums import CredentialSourceType, PaymentStatus, PermissionEnum, ProviderQuotaType
|
||||
from .types import EnumText, LongText, StringUUID
|
||||
|
||||
|
||||
class ProviderType(StrEnum):
|
||||
CUSTOM = auto()
|
||||
SYSTEM = auto()
|
||||
|
||||
@staticmethod
|
||||
def value_of(value: str) -> ProviderType:
|
||||
for member in ProviderType:
|
||||
if member.value == value:
|
||||
return member
|
||||
raise ValueError(f"No matching enum found for value '{value}'")
|
||||
|
||||
|
||||
class Provider(TypeBase):
|
||||
"""
|
||||
Provider model representing the API providers and their configurations.
|
||||
"""
|
||||
|
||||
__tablename__ = "providers"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="provider_pkey"),
|
||||
sa.Index("provider_tenant_id_provider_idx", "tenant_id", "provider_name"),
|
||||
sa.UniqueConstraint(
|
||||
"tenant_id", "provider_name", "provider_type", "quota_type", name="unique_provider_name_type_quota"
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID,
|
||||
primary_key=True,
|
||||
insert_default=lambda: str(uuidv7()),
|
||||
default_factory=lambda: str(uuidv7()),
|
||||
init=False,
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
provider_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
provider_type: Mapped[ProviderType] = mapped_column(
|
||||
EnumText(ProviderType, length=40), nullable=False, default=ProviderType.CUSTOM
|
||||
)
|
||||
is_valid: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
|
||||
last_used: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, init=False)
|
||||
credential_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
|
||||
quota_type: Mapped[ProviderQuotaType | None] = mapped_column(
|
||||
EnumText(ProviderQuotaType, length=40), nullable=True, server_default=text("''"), default=None
|
||||
)
|
||||
quota_limit: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True, default=None)
|
||||
quota_used: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True, default=0)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), init=False
|
||||
)
|
||||
|
||||
@override
|
||||
def __repr__(self):
|
||||
return (
|
||||
f"<Provider(id={self.id}, tenant_id={self.tenant_id}, provider_name='{self.provider_name}',"
|
||||
f" provider_type='{self.provider_type}')>"
|
||||
)
|
||||
|
||||
@cached_property
|
||||
def credential(self):
|
||||
if self.credential_id:
|
||||
with session_factory.create_session() as session:
|
||||
return session.scalar(select(ProviderCredential).where(ProviderCredential.id == self.credential_id))
|
||||
|
||||
@property
|
||||
def credential_name(self):
|
||||
credential = self.credential
|
||||
return credential.credential_name if credential else None
|
||||
|
||||
@property
|
||||
def encrypted_config(self):
|
||||
credential = self.credential
|
||||
return credential.encrypted_config if credential else None
|
||||
|
||||
@property
|
||||
def token_is_set(self):
|
||||
"""
|
||||
Returns True if the encrypted_config is not None, indicating that the token is set.
|
||||
"""
|
||||
return self.encrypted_config is not None
|
||||
|
||||
@property
|
||||
def is_enabled(self):
|
||||
"""
|
||||
Returns True if the provider is enabled.
|
||||
"""
|
||||
if self.provider_type == ProviderType.SYSTEM:
|
||||
return self.is_valid
|
||||
else:
|
||||
return self.is_valid and self.token_is_set
|
||||
|
||||
|
||||
class ProviderModel(TypeBase):
|
||||
"""
|
||||
Provider model representing the API provider_models and their configurations.
|
||||
"""
|
||||
|
||||
__tablename__ = "provider_models"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="provider_model_pkey"),
|
||||
sa.Index("provider_model_tenant_id_provider_idx", "tenant_id", "provider_name"),
|
||||
sa.UniqueConstraint(
|
||||
"tenant_id", "provider_name", "model_name", "model_type", name="unique_provider_model_name"
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
provider_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
model_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
model_type: Mapped[ModelType] = mapped_column(EnumText(ModelType, length=40), nullable=False)
|
||||
credential_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
is_valid: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), init=False
|
||||
)
|
||||
|
||||
@cached_property
|
||||
def credential(self):
|
||||
if self.credential_id:
|
||||
with session_factory.create_session() as session:
|
||||
return session.scalar(
|
||||
select(ProviderModelCredential).where(ProviderModelCredential.id == self.credential_id)
|
||||
)
|
||||
|
||||
@property
|
||||
def credential_name(self):
|
||||
credential = self.credential
|
||||
return credential.credential_name if credential else None
|
||||
|
||||
@property
|
||||
def encrypted_config(self):
|
||||
credential = self.credential
|
||||
return credential.encrypted_config if credential else None
|
||||
|
||||
|
||||
class TenantDefaultModel(TypeBase):
|
||||
__tablename__ = "tenant_default_models"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="tenant_default_model_pkey"),
|
||||
sa.Index("tenant_default_model_tenant_id_provider_type_idx", "tenant_id", "provider_name", "model_type"),
|
||||
sa.UniqueConstraint("tenant_id", "model_type", name="unique_tenant_default_model_type"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
provider_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
model_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
model_type: Mapped[ModelType] = mapped_column(EnumText(ModelType, length=40), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), init=False
|
||||
)
|
||||
|
||||
|
||||
class TenantPreferredModelProvider(TypeBase):
|
||||
__tablename__ = "tenant_preferred_model_providers"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="tenant_preferred_model_provider_pkey"),
|
||||
sa.Index("tenant_preferred_model_provider_tenant_provider_idx", "tenant_id", "provider_name"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
provider_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
preferred_provider_type: Mapped[ProviderType] = mapped_column(EnumText(ProviderType, length=40), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), init=False
|
||||
)
|
||||
|
||||
|
||||
class ProviderOrder(TypeBase):
|
||||
__tablename__ = "provider_orders"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="provider_order_pkey"),
|
||||
sa.Index("provider_order_tenant_provider_idx", "tenant_id", "provider_name"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
provider_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
account_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
payment_product_id: Mapped[str] = mapped_column(String(191), nullable=False)
|
||||
payment_id: Mapped[str | None] = mapped_column(String(191))
|
||||
transaction_id: Mapped[str | None] = mapped_column(String(191))
|
||||
quantity: Mapped[int] = mapped_column(sa.Integer, nullable=False, server_default=text("1"))
|
||||
currency: Mapped[str | None] = mapped_column(String(40))
|
||||
total_amount: Mapped[int | None] = mapped_column(sa.Integer)
|
||||
payment_status: Mapped[PaymentStatus] = mapped_column(
|
||||
EnumText(PaymentStatus, length=40), nullable=False, server_default=text("'wait_pay'")
|
||||
)
|
||||
paid_at: Mapped[datetime | None] = mapped_column(DateTime)
|
||||
pay_failed_at: Mapped[datetime | None] = mapped_column(DateTime)
|
||||
refunded_at: Mapped[datetime | None] = mapped_column(DateTime)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), init=False
|
||||
)
|
||||
|
||||
|
||||
class ProviderModelSetting(TypeBase):
|
||||
"""
|
||||
Provider model settings for record the model enabled status and load balancing status.
|
||||
"""
|
||||
|
||||
__tablename__ = "provider_model_settings"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="provider_model_setting_pkey"),
|
||||
sa.Index("provider_model_setting_tenant_provider_model_idx", "tenant_id", "provider_name", "model_type"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
provider_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
model_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
model_type: Mapped[ModelType] = mapped_column(EnumText(ModelType, length=40), nullable=False)
|
||||
enabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=True)
|
||||
load_balancing_enabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), init=False
|
||||
)
|
||||
|
||||
|
||||
class LoadBalancingModelConfig(TypeBase):
|
||||
"""
|
||||
Configurations for load balancing models.
|
||||
"""
|
||||
|
||||
__tablename__ = "load_balancing_model_configs"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="load_balancing_model_config_pkey"),
|
||||
sa.Index("load_balancing_model_config_tenant_provider_model_idx", "tenant_id", "provider_name", "model_type"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
provider_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
model_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
model_type: Mapped[ModelType] = mapped_column(EnumText(ModelType, length=40), nullable=False)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
encrypted_config: Mapped[str | None] = mapped_column(LongText, nullable=True, default=None)
|
||||
credential_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
credential_source_type: Mapped[CredentialSourceType | None] = mapped_column(
|
||||
EnumText(CredentialSourceType, length=40), nullable=True, default=None
|
||||
)
|
||||
enabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), init=False
|
||||
)
|
||||
|
||||
|
||||
class ProviderCredential(TypeBase):
|
||||
"""
|
||||
Provider credential - stores multiple named credentials for each provider
|
||||
"""
|
||||
|
||||
__tablename__ = "provider_credentials"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="provider_credential_pkey"),
|
||||
sa.Index("provider_credential_tenant_provider_idx", "tenant_id", "provider_name"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuidv7()), default_factory=lambda: str(uuidv7()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
provider_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
credential_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
encrypted_config: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
user_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
visibility: Mapped[PermissionEnum] = mapped_column(
|
||||
EnumText(PermissionEnum, length=40), nullable=False, default=PermissionEnum.ALL_TEAM
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), init=False
|
||||
)
|
||||
|
||||
|
||||
class ProviderModelCredential(TypeBase):
|
||||
"""
|
||||
Provider model credential - stores multiple named credentials for each provider model
|
||||
"""
|
||||
|
||||
__tablename__ = "provider_model_credentials"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="provider_model_credential_pkey"),
|
||||
sa.Index(
|
||||
"provider_model_credential_tenant_provider_model_idx",
|
||||
"tenant_id",
|
||||
"provider_name",
|
||||
"model_name",
|
||||
"model_type",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuidv7()), default_factory=lambda: str(uuidv7()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
provider_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
model_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
model_type: Mapped[ModelType] = mapped_column(EnumText(ModelType, length=40), nullable=False)
|
||||
credential_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
encrypted_config: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), init=False
|
||||
)
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Provider ID entities for plugin system."""
|
||||
|
||||
import re
|
||||
from typing import override
|
||||
|
||||
from werkzeug.exceptions import NotFound
|
||||
|
||||
|
||||
class GenericProviderID:
|
||||
organization: str
|
||||
plugin_name: str
|
||||
provider_name: str
|
||||
is_hardcoded: bool
|
||||
|
||||
def to_string(self) -> str:
|
||||
return str(self)
|
||||
|
||||
@override
|
||||
def __str__(self) -> str:
|
||||
return f"{self.organization}/{self.plugin_name}/{self.provider_name}"
|
||||
|
||||
def __init__(self, value: str, is_hardcoded: bool = False) -> None:
|
||||
if not value:
|
||||
raise NotFound("plugin not found, please add plugin")
|
||||
# check if the value is a valid plugin id with format: $organization/$plugin_name/$provider_name
|
||||
if not re.match(r"^[a-z0-9_-]+\/[a-z0-9_-]+\/[a-z0-9_-]+$", value):
|
||||
# check if matches [a-z0-9_-]+, if yes, append with langgenius/$value/$value
|
||||
if re.match(r"^[a-z0-9_-]+$", value):
|
||||
value = f"langgenius/{value}/{value}"
|
||||
else:
|
||||
raise ValueError(f"Invalid plugin id {value}")
|
||||
|
||||
self.organization, self.plugin_name, self.provider_name = value.split("/")
|
||||
self.is_hardcoded = is_hardcoded
|
||||
|
||||
def is_langgenius(self) -> bool:
|
||||
return self.organization == "langgenius"
|
||||
|
||||
@property
|
||||
def plugin_id(self) -> str:
|
||||
return f"{self.organization}/{self.plugin_name}"
|
||||
|
||||
|
||||
class ModelProviderID(GenericProviderID):
|
||||
def __init__(self, value: str, is_hardcoded: bool = False) -> None:
|
||||
super().__init__(value, is_hardcoded)
|
||||
if self.organization == "langgenius" and self.provider_name == "google":
|
||||
self.plugin_name = "gemini"
|
||||
|
||||
|
||||
class ToolProviderID(GenericProviderID):
|
||||
def __init__(self, value: str, is_hardcoded: bool = False) -> None:
|
||||
super().__init__(value, is_hardcoded)
|
||||
if self.organization == "langgenius":
|
||||
if self.provider_name in ["jina", "siliconflow", "stepfun", "gitee_ai"]:
|
||||
self.plugin_name = f"{self.provider_name}_tool"
|
||||
|
||||
|
||||
class DatasourceProviderID(GenericProviderID):
|
||||
def __init__(self, value: str, is_hardcoded: bool = False) -> None:
|
||||
super().__init__(value, is_hardcoded)
|
||||
|
||||
|
||||
class TriggerProviderID(GenericProviderID):
|
||||
def __init__(self, value: str, is_hardcoded: bool = False) -> None:
|
||||
super().__init__(value, is_hardcoded)
|
||||
@@ -0,0 +1,75 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import DateTime, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from constants.resource_access_token import ResourceAccessTokenResourceType
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
|
||||
from .base import Base
|
||||
from .types import EnumText, StringUUID
|
||||
|
||||
|
||||
class ResourceAccessToken(Base):
|
||||
__tablename__ = "resource_access_tokens"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="resource_access_token_pkey"),
|
||||
sa.Index("resource_access_token_tenant_idx", "tenant_id"),
|
||||
sa.Index("resource_access_token_token_idx", "token", unique=True),
|
||||
sa.Index("resource_access_token_track_id_idx", "track_id", unique=True),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(StringUUID, default=lambda: str(uuid4()))
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
track_id: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
token: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
last_used_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
default=naive_utc_now,
|
||||
server_default=func.current_timestamp(),
|
||||
)
|
||||
|
||||
|
||||
class ResourceAccessTokenRelation(Base):
|
||||
__tablename__ = "resource_access_tokens_relation"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="resource_access_token_relation_pkey"),
|
||||
sa.CheckConstraint(
|
||||
"(resource_type = 'app' AND app_id IS NOT NULL AND dataset_id IS NULL) OR "
|
||||
"(resource_type = 'knowledge' AND dataset_id IS NOT NULL AND app_id IS NULL)",
|
||||
name="resource_access_token_relation_resource_check",
|
||||
),
|
||||
sa.Index("resource_access_token_relation_token_idx", "token_id"),
|
||||
sa.Index("resource_access_token_relation_app_idx", "app_id"),
|
||||
sa.Index("resource_access_token_relation_dataset_idx", "dataset_id"),
|
||||
sa.UniqueConstraint("token_id", "resource_type", "app_id", name="resource_access_token_relation_app_unique"),
|
||||
sa.UniqueConstraint(
|
||||
"token_id",
|
||||
"resource_type",
|
||||
"dataset_id",
|
||||
name="resource_access_token_relation_dataset_unique",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(StringUUID, default=lambda: str(uuid4()))
|
||||
token_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
resource_type: Mapped[ResourceAccessTokenResourceType] = mapped_column(
|
||||
EnumText(ResourceAccessTokenResourceType, length=16),
|
||||
nullable=False,
|
||||
)
|
||||
app_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
dataset_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
default=naive_utc_now,
|
||||
server_default=func.current_timestamp(),
|
||||
)
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Workspace-level Skill Management models.
|
||||
|
||||
These tables are the source of truth for reusable workspace Skills. Agent Soul
|
||||
``config_skills`` and Agent Drive skill rows remain per-agent runtime/config
|
||||
assets; they may consume a published Skill snapshot but do not own the Skill's
|
||||
draft, metadata, version history, or Agent binding priority.
|
||||
"""
|
||||
|
||||
from enum import StrEnum
|
||||
|
||||
import sqlalchemy as sa
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy import Index, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from models.base import Base, DefaultFieldsMixin
|
||||
from models.types import EnumText, JSONModelColumn, LongText, StringUUID
|
||||
|
||||
|
||||
class SkillFileKind(StrEnum):
|
||||
"""Draft file entry kind."""
|
||||
|
||||
FILE = "file"
|
||||
DIRECTORY = "directory"
|
||||
|
||||
|
||||
class SkillFileStorage(StrEnum):
|
||||
"""How a draft file's content is stored."""
|
||||
|
||||
TEXT = "text"
|
||||
TOOL_FILE = "tool_file"
|
||||
|
||||
|
||||
class SkillVersionManifestFile(BaseModel):
|
||||
"""One file entry captured in a published Skill snapshot manifest."""
|
||||
|
||||
path: str
|
||||
mime_type: str | None = None
|
||||
size: int
|
||||
hash: str
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class SkillVersionManifest(BaseModel):
|
||||
"""Published Skill snapshot file index."""
|
||||
|
||||
files: list[SkillVersionManifestFile]
|
||||
name: str | None = None
|
||||
display_name: str | None = None
|
||||
description: str | None = None
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class Skill(DefaultFieldsMixin, Base):
|
||||
"""Workspace-level reusable Skill metadata and draft status."""
|
||||
|
||||
__tablename__ = "skills"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="skill_pkey"),
|
||||
UniqueConstraint("tenant_id", "name", name="skill_tenant_name_unique"),
|
||||
Index("skills_tenant_updated_at_idx", "tenant_id", "updated_at"),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
name: Mapped[str] = mapped_column(sa.String(64), nullable=False)
|
||||
display_name: Mapped[str] = mapped_column(sa.String(128), nullable=False)
|
||||
icon: Mapped[str] = mapped_column(sa.String(16), nullable=False, default="📄", server_default="📄")
|
||||
description: Mapped[str] = mapped_column(sa.String(1024), nullable=False, default="", server_default="")
|
||||
name_manually_edited: Mapped[bool] = mapped_column(
|
||||
sa.Boolean,
|
||||
nullable=False,
|
||||
default=False,
|
||||
server_default=sa.false(),
|
||||
)
|
||||
visibility: Mapped[str] = mapped_column(
|
||||
sa.String(32),
|
||||
nullable=False,
|
||||
default="workspace",
|
||||
server_default="workspace",
|
||||
)
|
||||
latest_published_version_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
created_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
updated_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
|
||||
|
||||
class SkillDraftFile(DefaultFieldsMixin, Base):
|
||||
"""One draft file or directory in a workspace Skill."""
|
||||
|
||||
__tablename__ = "skill_draft_files"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="skill_draft_file_pkey"),
|
||||
UniqueConstraint("skill_id", "path", name="skill_draft_file_skill_path_unique"),
|
||||
Index("skill_draft_files_skill_path_idx", "skill_id", "path"),
|
||||
)
|
||||
|
||||
skill_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
path: Mapped[str] = mapped_column(sa.String(512), nullable=False)
|
||||
kind: Mapped[SkillFileKind] = mapped_column(EnumText(SkillFileKind, length=32), nullable=False)
|
||||
storage: Mapped[SkillFileStorage | None] = mapped_column(EnumText(SkillFileStorage, length=32), nullable=True)
|
||||
mime_type: Mapped[str | None] = mapped_column(sa.String(255), nullable=True)
|
||||
content_text: Mapped[str | None] = mapped_column(LongText, nullable=True)
|
||||
tool_file_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
size: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True)
|
||||
hash: Mapped[str | None] = mapped_column(sa.String(255), nullable=True)
|
||||
|
||||
|
||||
class SkillVersion(DefaultFieldsMixin, Base):
|
||||
"""Immutable published Skill snapshot.
|
||||
|
||||
``hash_code`` uniquely identifies a published version for downstream
|
||||
execution audit. It includes Skill identity, version number, and archive
|
||||
content digest instead of being only the archive content hash.
|
||||
"""
|
||||
|
||||
__tablename__ = "skill_versions"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="skill_version_pkey"),
|
||||
UniqueConstraint("skill_id", "version_number", name="skill_version_skill_number_unique"),
|
||||
Index("skill_versions_skill_created_at_idx", "skill_id", "created_at"),
|
||||
)
|
||||
|
||||
skill_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
version_number: Mapped[int] = mapped_column(sa.Integer, nullable=False)
|
||||
version_name: Mapped[str] = mapped_column(sa.String(128), nullable=False, default="", server_default="")
|
||||
publish_note: Mapped[str] = mapped_column(sa.String(1024), nullable=False, default="", server_default="")
|
||||
manifest: Mapped[SkillVersionManifest] = mapped_column(JSONModelColumn(SkillVersionManifest), nullable=False)
|
||||
archive_tool_file_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
hash_code: Mapped[str] = mapped_column(sa.String(255), nullable=False)
|
||||
archive_size: Mapped[int] = mapped_column(sa.BigInteger, nullable=False)
|
||||
published_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
|
||||
|
||||
class AgentSkillBinding(DefaultFieldsMixin, Base):
|
||||
"""Direct Agent-to-workspace-Skill binding.
|
||||
|
||||
``priority`` is retained as an internal ordering column for the current
|
||||
schema constraints. Runtime Skill selection is Agent-driven and must not
|
||||
treat it as a matching priority.
|
||||
"""
|
||||
|
||||
__tablename__ = "agent_skill_bindings"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="agent_skill_binding_pkey"),
|
||||
UniqueConstraint("tenant_id", "agent_id", "skill_id", name="agent_skill_binding_unique"),
|
||||
UniqueConstraint("tenant_id", "agent_id", "priority", name="agent_skill_binding_priority_unique"),
|
||||
Index("agent_skill_bindings_skill_idx", "tenant_id", "skill_id"),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
agent_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
skill_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
priority: Mapped[int] = mapped_column(sa.Integer, nullable=False)
|
||||
created_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
|
||||
|
||||
class AgentSkillBindingSnapshot(DefaultFieldsMixin, Base):
|
||||
"""Published Agent-to-workspace-Skill bindings for one Agent snapshot."""
|
||||
|
||||
__tablename__ = "agent_skill_binding_snapshots"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="agent_skill_binding_snapshot_pkey"),
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"agent_id",
|
||||
"config_snapshot_id",
|
||||
"skill_id",
|
||||
name="agent_skill_binding_snapshot_skill_unique",
|
||||
),
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"agent_id",
|
||||
"config_snapshot_id",
|
||||
"priority",
|
||||
name="agent_skill_binding_snapshot_priority_unique",
|
||||
),
|
||||
Index("agent_skill_binding_snapshots_agent_snapshot_idx", "tenant_id", "agent_id", "config_snapshot_id"),
|
||||
)
|
||||
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
agent_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
config_snapshot_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
skill_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
priority: Mapped[int] = mapped_column(sa.Integer, nullable=False)
|
||||
created_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AgentSkillBinding",
|
||||
"AgentSkillBindingSnapshot",
|
||||
"Skill",
|
||||
"SkillDraftFile",
|
||||
"SkillFileKind",
|
||||
"SkillFileStorage",
|
||||
"SkillVersion",
|
||||
"SkillVersionManifest",
|
||||
"SkillVersionManifestFile",
|
||||
]
|
||||
@@ -0,0 +1,136 @@
|
||||
import json
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import Any, cast
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import DateTime, String, func
|
||||
from sqlalchemy.orm import Mapped, Session, mapped_column
|
||||
|
||||
from libs.uuid_utils import uuidv7
|
||||
|
||||
from .account import Account
|
||||
from .base import TypeBase
|
||||
from .model import Tag, TagBinding
|
||||
from .types import AdjustedJSON, LongText, StringUUID
|
||||
|
||||
|
||||
class SnippetType(StrEnum):
|
||||
"""Snippet Type Enum"""
|
||||
|
||||
NODE = "node"
|
||||
GROUP = "group"
|
||||
|
||||
|
||||
class CustomizedSnippet(TypeBase, kw_only=True):
|
||||
"""
|
||||
Customized Snippet Model
|
||||
|
||||
Stores reusable workflow components (nodes or node groups) that can be
|
||||
shared across applications within a workspace.
|
||||
"""
|
||||
|
||||
__tablename__ = "customized_snippets"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="customized_snippet_pkey"),
|
||||
sa.Index("customized_snippet_tenant_idx", "tenant_id"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID,
|
||||
insert_default=lambda: str(uuidv7()),
|
||||
default_factory=lambda: str(uuidv7()),
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False, default=cast(str, None))
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False, default=cast(str, None))
|
||||
description: Mapped[str | None] = mapped_column(LongText, nullable=True, default=None)
|
||||
type: Mapped[str] = mapped_column(
|
||||
String(50), nullable=False, server_default=sa.text("'node'"), default=cast(str, None)
|
||||
)
|
||||
|
||||
# Workflow reference for published version
|
||||
workflow_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
|
||||
# State flags
|
||||
is_published: Mapped[bool] = mapped_column(
|
||||
sa.Boolean, nullable=False, server_default=sa.false(), default=cast(bool, None)
|
||||
)
|
||||
version: Mapped[int] = mapped_column(
|
||||
sa.Integer, nullable=False, server_default=sa.text("1"), default=cast(int, None)
|
||||
)
|
||||
use_count: Mapped[int] = mapped_column(
|
||||
sa.Integer, nullable=False, server_default=sa.text("0"), default=cast(int, None)
|
||||
)
|
||||
|
||||
# Visual customization
|
||||
icon_info: Mapped[dict[str, Any] | None] = mapped_column(AdjustedJSON, nullable=True, default=None)
|
||||
|
||||
# Snippet configuration (stored as JSON text)
|
||||
input_fields: Mapped[str | None] = mapped_column(LongText, nullable=True, default=None)
|
||||
|
||||
# Audit fields
|
||||
created_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True, default=None)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
def get_graph_dict(self, *, session: Session) -> dict[str, Any]:
|
||||
"""Get graph from associated workflow."""
|
||||
if self.workflow_id:
|
||||
from .workflow import Workflow
|
||||
|
||||
workflow = session.get(Workflow, self.workflow_id)
|
||||
if workflow:
|
||||
return json.loads(workflow.graph) if workflow.graph else {}
|
||||
return {}
|
||||
|
||||
@property
|
||||
def input_fields_list(self) -> list[dict[str, Any]]:
|
||||
"""Parse input_fields JSON to list."""
|
||||
return json.loads(self.input_fields) if self.input_fields else []
|
||||
|
||||
def get_tags(self, *, session: Session) -> Sequence[Tag]:
|
||||
"""Get snippet tags."""
|
||||
tags = session.scalars(
|
||||
sa.select(Tag)
|
||||
.join(TagBinding, Tag.id == TagBinding.tag_id)
|
||||
.where(
|
||||
TagBinding.target_id == self.id,
|
||||
TagBinding.tenant_id == self.tenant_id,
|
||||
Tag.tenant_id == self.tenant_id,
|
||||
Tag.type == "snippet",
|
||||
)
|
||||
).all()
|
||||
|
||||
return tags or []
|
||||
|
||||
def get_created_by_account(self, *, session: Session) -> Account | None:
|
||||
"""Get the account that created this snippet."""
|
||||
if self.created_by:
|
||||
return session.get(Account, self.created_by)
|
||||
return None
|
||||
|
||||
def get_author_name(self, *, session: Session) -> str | None:
|
||||
"""Get the creator account name."""
|
||||
account = self.get_created_by_account(session=session)
|
||||
return account.name if account else None
|
||||
|
||||
def get_updated_by_account(self, *, session: Session) -> Account | None:
|
||||
"""Get the account that last updated this snippet."""
|
||||
if self.updated_by:
|
||||
return session.get(Account, self.updated_by)
|
||||
return None
|
||||
|
||||
@property
|
||||
def version_str(self) -> str:
|
||||
"""Get version as string for API response."""
|
||||
return str(self.version)
|
||||
@@ -0,0 +1,91 @@
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Any, TypedDict
|
||||
from uuid import uuid4
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import DateTime, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import TypeBase
|
||||
from .types import AdjustedJSON, LongText, StringUUID, adjusted_json_index
|
||||
|
||||
|
||||
class DataSourceOauthBinding(TypeBase):
|
||||
__tablename__ = "data_source_oauth_bindings"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="source_binding_pkey"),
|
||||
sa.Index("source_binding_tenant_id_idx", "tenant_id"),
|
||||
adjusted_json_index("source_info_idx", "source_info"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
access_token: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
provider: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
source_info: Mapped[dict[str, Any]] = mapped_column(AdjustedJSON, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
disabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=True, default=False)
|
||||
|
||||
|
||||
class DataSourceApiKeyAuthBindingDict(TypedDict):
|
||||
id: str
|
||||
tenant_id: str
|
||||
category: str
|
||||
provider: str
|
||||
credentials: Any
|
||||
created_at: float
|
||||
updated_at: float
|
||||
disabled: bool
|
||||
|
||||
|
||||
class DataSourceApiKeyAuthBinding(TypeBase):
|
||||
__tablename__ = "data_source_api_key_auth_bindings"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="data_source_api_key_auth_binding_pkey"),
|
||||
sa.Index("data_source_api_key_auth_binding_tenant_id_idx", "tenant_id"),
|
||||
sa.Index("data_source_api_key_auth_binding_provider_idx", "provider"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
category: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
provider: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
credentials: Mapped[str | None] = mapped_column(LongText, nullable=True, default=None) # JSON
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
disabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=True, default=False)
|
||||
|
||||
def to_dict(self) -> DataSourceApiKeyAuthBindingDict:
|
||||
result: DataSourceApiKeyAuthBindingDict = {
|
||||
"id": self.id,
|
||||
"tenant_id": self.tenant_id,
|
||||
"category": self.category,
|
||||
"provider": self.provider,
|
||||
"credentials": json.loads(self.credentials) if self.credentials else None,
|
||||
"created_at": self.created_at.timestamp(),
|
||||
"updated_at": self.updated_at.timestamp(),
|
||||
"disabled": self.disabled,
|
||||
}
|
||||
return result
|
||||
@@ -0,0 +1,53 @@
|
||||
from datetime import datetime
|
||||
|
||||
import sqlalchemy as sa
|
||||
from celery import states
|
||||
from sqlalchemy import DateTime, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
|
||||
from .base import TypeBase
|
||||
from .types import BinaryData, LongText
|
||||
|
||||
|
||||
class CeleryTask(TypeBase):
|
||||
"""Task result/status."""
|
||||
|
||||
__tablename__ = "celery_taskmeta"
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
sa.Integer, sa.Sequence("task_id_sequence"), primary_key=True, autoincrement=True, init=False
|
||||
)
|
||||
task_id: Mapped[str] = mapped_column(String(155), unique=True)
|
||||
status: Mapped[str] = mapped_column(String(50), default=states.PENDING)
|
||||
result: Mapped[bytes | None] = mapped_column(BinaryData, nullable=True, default=None)
|
||||
date_done: Mapped[datetime | None] = mapped_column(
|
||||
DateTime,
|
||||
insert_default=naive_utc_now,
|
||||
default=None,
|
||||
onupdate=naive_utc_now,
|
||||
nullable=True,
|
||||
)
|
||||
traceback: Mapped[str | None] = mapped_column(LongText, nullable=True, default=None)
|
||||
name: Mapped[str | None] = mapped_column(String(155), nullable=True, default=None)
|
||||
args: Mapped[bytes | None] = mapped_column(BinaryData, nullable=True, default=None)
|
||||
kwargs: Mapped[bytes | None] = mapped_column(BinaryData, nullable=True, default=None)
|
||||
worker: Mapped[str | None] = mapped_column(String(155), nullable=True, default=None)
|
||||
retries: Mapped[int | None] = mapped_column(sa.Integer, nullable=True, default=None)
|
||||
queue: Mapped[str | None] = mapped_column(String(155), nullable=True, default=None)
|
||||
|
||||
|
||||
class CeleryTaskSet(TypeBase):
|
||||
"""TaskSet result."""
|
||||
|
||||
__tablename__ = "celery_tasksetmeta"
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
sa.Integer, sa.Sequence("taskset_id_sequence"), autoincrement=True, primary_key=True, init=False
|
||||
)
|
||||
taskset_id: Mapped[str] = mapped_column(String(155), unique=True)
|
||||
result: Mapped[bytes | None] = mapped_column(BinaryData, nullable=True, default=None)
|
||||
date_done: Mapped[datetime | None] = mapped_column(
|
||||
DateTime, insert_default=naive_utc_now, default=None, nullable=True
|
||||
)
|
||||
@@ -0,0 +1,548 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
from uuid import uuid4
|
||||
|
||||
import sqlalchemy as sa
|
||||
from deprecated import deprecated
|
||||
from sqlalchemy import ForeignKey, String, func, select
|
||||
from sqlalchemy.orm import Mapped, Session, mapped_column
|
||||
|
||||
from core.plugin.entities.plugin_daemon import CredentialType
|
||||
from core.tools.entities.common_entities import I18nObject
|
||||
from core.tools.entities.tool_bundle import ApiToolBundle
|
||||
from core.tools.entities.tool_entities import (
|
||||
ApiProviderSchemaType,
|
||||
ToolProviderType,
|
||||
WorkflowToolParameterConfiguration,
|
||||
)
|
||||
|
||||
from .base import TypeBase
|
||||
from .enums import PermissionEnum
|
||||
from .model import Account, App, Tenant
|
||||
from .types import EnumText, LongText, StringUUID
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.entities.mcp_provider import MCPProviderEntity
|
||||
|
||||
|
||||
# system level tool oauth client params (client_id, client_secret, etc.)
|
||||
class ToolOAuthSystemClient(TypeBase):
|
||||
__tablename__ = "tool_oauth_system_clients"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="tool_oauth_system_client_pkey"),
|
||||
sa.UniqueConstraint("plugin_id", "provider", name="tool_oauth_system_client_plugin_id_provider_idx"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
plugin_id: Mapped[str] = mapped_column(String(512), nullable=False)
|
||||
provider: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
# oauth params of the tool provider
|
||||
encrypted_oauth_params: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
|
||||
|
||||
# tenant level tool oauth client params (client_id, client_secret, etc.)
|
||||
class ToolOAuthTenantClient(TypeBase):
|
||||
__tablename__ = "tool_oauth_tenant_clients"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="tool_oauth_tenant_client_pkey"),
|
||||
sa.UniqueConstraint("tenant_id", "plugin_id", "provider", name="unique_tool_oauth_tenant_client"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
# tenant id
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
plugin_id: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
provider: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
enabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.true(), init=False)
|
||||
# oauth params of the tool provider
|
||||
encrypted_oauth_params: Mapped[str] = mapped_column(LongText, nullable=False, init=False)
|
||||
|
||||
@property
|
||||
def oauth_params(self) -> dict[str, Any]:
|
||||
return cast(dict[str, Any], json.loads(self.encrypted_oauth_params or "{}"))
|
||||
|
||||
|
||||
class BuiltinToolProvider(TypeBase):
|
||||
"""
|
||||
This table stores the tool provider information for built-in tools for each tenant.
|
||||
"""
|
||||
|
||||
__tablename__ = "tool_builtin_providers"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="tool_builtin_provider_pkey"),
|
||||
sa.UniqueConstraint("tenant_id", "provider", "name", name="unique_builtin_tool_provider"),
|
||||
)
|
||||
|
||||
# id of the tool provider
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
name: Mapped[str] = mapped_column(
|
||||
String(256),
|
||||
nullable=False,
|
||||
server_default=sa.text("'API KEY 1'"),
|
||||
)
|
||||
# id of the tenant
|
||||
tenant_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
# who created this tool provider
|
||||
user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# name of the tool provider
|
||||
provider: Mapped[str] = mapped_column(String(256), nullable=False)
|
||||
# credential of the tool provider
|
||||
encrypted_credentials: Mapped[str | None] = mapped_column(LongText, nullable=True, default=None)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
is_default: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
|
||||
# credential type, e.g., "api-key", "oauth2"
|
||||
credential_type: Mapped[CredentialType] = mapped_column(
|
||||
EnumText(CredentialType, length=32), nullable=False, default=CredentialType.API_KEY
|
||||
)
|
||||
expires_at: Mapped[int] = mapped_column(sa.BigInteger, nullable=False, default=-1)
|
||||
visibility: Mapped[PermissionEnum] = mapped_column(
|
||||
EnumText(PermissionEnum, length=40), nullable=False, default=PermissionEnum.ALL_TEAM
|
||||
)
|
||||
|
||||
@property
|
||||
def credentials(self) -> dict[str, Any]:
|
||||
if not self.encrypted_credentials:
|
||||
return {}
|
||||
return cast(dict[str, Any], json.loads(self.encrypted_credentials))
|
||||
|
||||
|
||||
class ApiToolProvider(TypeBase):
|
||||
"""
|
||||
The table stores the api providers.
|
||||
"""
|
||||
|
||||
__tablename__ = "tool_api_providers"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="tool_api_provider_pkey"),
|
||||
sa.UniqueConstraint("name", "tenant_id", name="unique_api_tool_provider"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
# name of the api provider
|
||||
name: Mapped[str] = mapped_column(
|
||||
String(255),
|
||||
nullable=False,
|
||||
server_default=sa.text("'API KEY 1'"),
|
||||
)
|
||||
# icon
|
||||
icon: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
# original schema
|
||||
schema: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
schema_type_str: Mapped[ApiProviderSchemaType] = mapped_column(
|
||||
EnumText(ApiProviderSchemaType, length=40), nullable=False
|
||||
)
|
||||
# who created this tool
|
||||
user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# tenant id
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# description of the provider
|
||||
description: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
# json format tools
|
||||
tools_str: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
# json format credentials
|
||||
credentials_str: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
# privacy policy
|
||||
privacy_policy: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
|
||||
# custom_disclaimer
|
||||
custom_disclaimer: Mapped[str] = mapped_column(LongText, default="")
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
@property
|
||||
def schema_type(self) -> ApiProviderSchemaType:
|
||||
return ApiProviderSchemaType.value_of(self.schema_type_str)
|
||||
|
||||
@property
|
||||
def tools(self) -> list[ApiToolBundle]:
|
||||
return [ApiToolBundle.model_validate(tool) for tool in json.loads(self.tools_str)]
|
||||
|
||||
@property
|
||||
def credentials(self) -> dict[str, Any]:
|
||||
return dict[str, Any](json.loads(self.credentials_str))
|
||||
|
||||
def user(self, session: Session) -> Account | None:
|
||||
if not self.user_id:
|
||||
return None
|
||||
return session.scalar(select(Account).where(Account.id == self.user_id))
|
||||
|
||||
def tenant(self, session: Session) -> Tenant | None:
|
||||
return session.scalar(select(Tenant).where(Tenant.id == self.tenant_id))
|
||||
|
||||
|
||||
class ToolLabelBinding(TypeBase):
|
||||
"""
|
||||
The table stores the labels for tools.
|
||||
"""
|
||||
|
||||
__tablename__ = "tool_label_bindings"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="tool_label_bind_pkey"),
|
||||
sa.UniqueConstraint("tool_id", "label_name", name="unique_tool_label_bind"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
# tool id
|
||||
tool_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# tool type
|
||||
tool_type: Mapped[ToolProviderType] = mapped_column(EnumText(ToolProviderType, length=40), nullable=False)
|
||||
# label name
|
||||
label_name: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
|
||||
|
||||
class WorkflowToolProvider(TypeBase):
|
||||
"""
|
||||
The table stores the workflow providers.
|
||||
"""
|
||||
|
||||
__tablename__ = "tool_workflow_providers"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="tool_workflow_provider_pkey"),
|
||||
sa.UniqueConstraint("name", "tenant_id", name="unique_workflow_tool_provider"),
|
||||
sa.UniqueConstraint("tenant_id", "app_id", name="unique_workflow_tool_provider_app_id"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
# name of the workflow provider
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
# label of the workflow provider
|
||||
label: Mapped[str] = mapped_column(String(255), nullable=False, server_default="")
|
||||
# icon
|
||||
icon: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
# app id of the workflow provider
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# version of the workflow provider
|
||||
version: Mapped[str] = mapped_column(String(255), nullable=False, server_default="")
|
||||
# who created this tool
|
||||
user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# tenant id
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# description of the provider
|
||||
description: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
# parameter configuration
|
||||
parameter_configuration: Mapped[str] = mapped_column(LongText, nullable=False, default="[]")
|
||||
# privacy policy
|
||||
privacy_policy: Mapped[str | None] = mapped_column(String(255), nullable=True, server_default="", default=None)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
def user(self, session: Session) -> Account | None:
|
||||
return session.scalar(select(Account).where(Account.id == self.user_id))
|
||||
|
||||
def tenant(self, session: Session) -> Tenant | None:
|
||||
return session.scalar(select(Tenant).where(Tenant.id == self.tenant_id))
|
||||
|
||||
@property
|
||||
def parameter_configurations(self) -> list[WorkflowToolParameterConfiguration]:
|
||||
return [
|
||||
WorkflowToolParameterConfiguration.model_validate(config)
|
||||
for config in json.loads(self.parameter_configuration)
|
||||
]
|
||||
|
||||
def app(self, session: Session) -> App | None:
|
||||
return session.scalar(select(App).where(App.id == self.app_id))
|
||||
|
||||
|
||||
class MCPToolProvider(TypeBase):
|
||||
"""
|
||||
The table stores the mcp providers.
|
||||
"""
|
||||
|
||||
__tablename__ = "tool_mcp_providers"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="tool_mcp_provider_pkey"),
|
||||
sa.UniqueConstraint("tenant_id", "server_url_hash", name="unique_mcp_provider_server_url"),
|
||||
sa.UniqueConstraint("tenant_id", "name", name="unique_mcp_provider_name"),
|
||||
sa.UniqueConstraint("tenant_id", "server_identifier", name="unique_mcp_provider_server_identifier"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
# name of the mcp provider
|
||||
name: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
# server identifier of the mcp provider
|
||||
server_identifier: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# encrypted url of the mcp provider
|
||||
server_url: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
# hash of server_url for uniqueness check
|
||||
server_url_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# icon of the mcp provider
|
||||
icon: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
# tenant id
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# who created this tool
|
||||
user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# encrypted credentials
|
||||
encrypted_credentials: Mapped[str | None] = mapped_column(LongText, nullable=True, default=None)
|
||||
# authed
|
||||
authed: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
|
||||
# tools
|
||||
tools: Mapped[str] = mapped_column(LongText, nullable=False, default="[]")
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
timeout: Mapped[float] = mapped_column(sa.Float, nullable=False, default=30.0)
|
||||
sse_read_timeout: Mapped[float] = mapped_column(sa.Float, nullable=False, default=300.0)
|
||||
# encrypted headers for MCP server requests
|
||||
encrypted_headers: Mapped[str | None] = mapped_column(LongText, nullable=True, default=None)
|
||||
|
||||
# M2 (MCP user-identity forwarding) — which identity-forwarding mechanism
|
||||
# this provider uses. Reserved values:
|
||||
# "off" — no forwarding (default; preserves pre-M2 behaviour).
|
||||
# "idp_token" — forward an SSO access token minted by dify-enterprise.
|
||||
identity_mode: Mapped[str] = mapped_column(sa.String(32), nullable=False, default="off")
|
||||
|
||||
def load_user(self, session: Session) -> Account | None:
|
||||
return session.scalar(select(Account).where(Account.id == self.user_id))
|
||||
|
||||
@property
|
||||
def credentials(self) -> dict[str, Any]:
|
||||
if not self.encrypted_credentials:
|
||||
return {}
|
||||
try:
|
||||
return json.loads(self.encrypted_credentials)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
@property
|
||||
def headers(self) -> dict[str, str]:
|
||||
if self.encrypted_headers is None:
|
||||
return {}
|
||||
try:
|
||||
return json.loads(self.encrypted_headers)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
@property
|
||||
def tool_dict(self) -> list[dict[str, Any]]:
|
||||
try:
|
||||
return json.loads(self.tools) if self.tools else []
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return []
|
||||
|
||||
def to_entity(self) -> MCPProviderEntity:
|
||||
"""Convert to domain entity"""
|
||||
from core.entities.mcp_provider import MCPProviderEntity
|
||||
|
||||
return MCPProviderEntity.from_db_model(self)
|
||||
|
||||
|
||||
class ToolModelInvoke(TypeBase):
|
||||
"""
|
||||
store the invoke logs from tool invoke
|
||||
"""
|
||||
|
||||
__tablename__ = "tool_model_invokes"
|
||||
__table_args__ = (sa.PrimaryKeyConstraint("id", name="tool_model_invoke_pkey"),)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
# who invoke this tool
|
||||
user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# tenant id
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# provider
|
||||
provider: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
# type
|
||||
tool_type: Mapped[ToolProviderType] = mapped_column(EnumText(ToolProviderType, length=40), nullable=False)
|
||||
# tool name
|
||||
tool_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
# invoke parameters
|
||||
model_parameters: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
# prompt messages
|
||||
prompt_messages: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
# invoke response
|
||||
model_response: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
|
||||
prompt_tokens: Mapped[int] = mapped_column(sa.Integer, nullable=False, server_default=sa.text("0"))
|
||||
answer_tokens: Mapped[int] = mapped_column(sa.Integer, nullable=False, server_default=sa.text("0"))
|
||||
answer_unit_price: Mapped[Decimal] = mapped_column(sa.Numeric(10, 4), nullable=False)
|
||||
answer_price_unit: Mapped[Decimal] = mapped_column(
|
||||
sa.Numeric(10, 7), nullable=False, server_default=sa.text("0.001")
|
||||
)
|
||||
provider_response_latency: Mapped[float] = mapped_column(sa.Float, nullable=False, server_default=sa.text("0"))
|
||||
total_price: Mapped[Decimal | None] = mapped_column(sa.Numeric(10, 7))
|
||||
currency: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
|
||||
@deprecated
|
||||
class ToolConversationVariables(TypeBase):
|
||||
"""
|
||||
store the conversation variables from tool invoke
|
||||
"""
|
||||
|
||||
__tablename__ = "tool_conversation_variables"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="tool_conversation_variables_pkey"),
|
||||
# add index for user_id and conversation_id
|
||||
sa.Index("user_id_idx", "user_id"),
|
||||
sa.Index("conversation_id_idx", "conversation_id"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
# conversation user id
|
||||
user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# tenant id
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# conversation id
|
||||
conversation_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# variables pool
|
||||
variables_str: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
@property
|
||||
def variables(self):
|
||||
return json.loads(self.variables_str)
|
||||
|
||||
|
||||
class ToolFile(TypeBase):
|
||||
"""This table stores file metadata generated in workflows,
|
||||
not only files created by agent.
|
||||
"""
|
||||
|
||||
__tablename__ = "tool_files"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="tool_file_pkey"),
|
||||
sa.Index("tool_file_conversation_id_idx", "conversation_id"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
# conversation user id
|
||||
user_id: Mapped[str] = mapped_column(StringUUID)
|
||||
# tenant id
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID)
|
||||
# conversation id
|
||||
conversation_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
# file key
|
||||
file_key: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
# mime type
|
||||
mimetype: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
# original url
|
||||
original_url: Mapped[str | None] = mapped_column(String(2048), nullable=True, default=None)
|
||||
# name
|
||||
name: Mapped[str] = mapped_column(String(255), default="")
|
||||
# size
|
||||
size: Mapped[int] = mapped_column(sa.Integer, default=-1)
|
||||
|
||||
|
||||
@deprecated
|
||||
class DeprecatedPublishedAppTool(TypeBase):
|
||||
"""
|
||||
The table stores the apps published as a tool for each person.
|
||||
"""
|
||||
|
||||
__tablename__ = "tool_published_apps"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="published_app_tool_pkey"),
|
||||
sa.UniqueConstraint("app_id", "user_id", name="unique_published_app_tool"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
# id of the app
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, ForeignKey("apps.id"), nullable=False)
|
||||
|
||||
user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
# who published this tool
|
||||
description: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
# llm_description of the tool, for LLM
|
||||
llm_description: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
# query description, query will be seem as a parameter of the tool,
|
||||
# to describe this parameter to llm, we need this field
|
||||
query_description: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
# query name, the name of the query parameter
|
||||
query_name: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
# name of the tool provider
|
||||
tool_name: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
# author
|
||||
author: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
sa.DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
@property
|
||||
def description_i18n(self) -> I18nObject:
|
||||
return I18nObject.model_validate(json.loads(self.description))
|
||||
@@ -0,0 +1,543 @@
|
||||
import json
|
||||
import time
|
||||
from collections.abc import Mapping
|
||||
from datetime import datetime
|
||||
from functools import cached_property
|
||||
from typing import Any, TypedDict, cast
|
||||
from uuid import uuid4
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import DateTime, Index, Integer, String, UniqueConstraint, func
|
||||
from sqlalchemy.orm import Mapped, Session, mapped_column
|
||||
|
||||
from core.plugin.entities.plugin_daemon import CredentialType
|
||||
from core.trigger.entities.api_entities import TriggerProviderSubscriptionApiEntity
|
||||
from core.trigger.entities.entities import Subscription
|
||||
from core.trigger.utils.endpoint import generate_plugin_trigger_endpoint_url, generate_webhook_trigger_endpoint
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from libs.uuid_utils import uuidv7
|
||||
|
||||
from .base import TypeBase
|
||||
from .enums import AppTriggerStatus, AppTriggerType, CreatorUserRole, PermissionEnum, WorkflowTriggerStatus
|
||||
from .model import Account
|
||||
from .types import EnumText, LongText, StringUUID
|
||||
|
||||
TriggerJsonObject = dict[str, object]
|
||||
TriggerCredentials = dict[str, str]
|
||||
|
||||
|
||||
class WorkflowTriggerLogDict(TypedDict):
|
||||
id: str
|
||||
tenant_id: str
|
||||
app_id: str
|
||||
workflow_id: str
|
||||
workflow_run_id: str | None
|
||||
root_node_id: str | None
|
||||
trigger_metadata: Any
|
||||
trigger_type: str
|
||||
trigger_data: Any
|
||||
inputs: Any
|
||||
outputs: Any
|
||||
status: str
|
||||
error: str | None
|
||||
queue_name: str
|
||||
celery_task_id: str | None
|
||||
retry_count: int
|
||||
elapsed_time: float | None
|
||||
total_tokens: int | None
|
||||
created_by_role: str
|
||||
created_by: str
|
||||
created_at: str | None
|
||||
triggered_at: str | None
|
||||
finished_at: str | None
|
||||
|
||||
|
||||
class WorkflowSchedulePlanDict(TypedDict):
|
||||
id: str
|
||||
app_id: str
|
||||
node_id: str
|
||||
tenant_id: str
|
||||
cron_expression: str
|
||||
timezone: str
|
||||
next_run_at: str | None
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
|
||||
class TriggerSubscription(TypeBase):
|
||||
"""
|
||||
Trigger provider model for managing credentials
|
||||
Supports multiple credential instances per provider
|
||||
"""
|
||||
|
||||
__tablename__ = "trigger_subscriptions"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="trigger_provider_pkey"),
|
||||
Index("idx_trigger_providers_tenant_provider", "tenant_id", "provider_id"),
|
||||
# Primary index for O(1) lookup by endpoint
|
||||
Index("idx_trigger_providers_endpoint", "endpoint_id", unique=True),
|
||||
# Composite index for tenant-specific queries (optional, kept for compatibility)
|
||||
Index("idx_trigger_providers_tenant_endpoint", "tenant_id", "endpoint_id"),
|
||||
UniqueConstraint("tenant_id", "provider_id", "name", name="unique_trigger_provider"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False, comment="Subscription instance name")
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
provider_id: Mapped[str] = mapped_column(
|
||||
String(255), nullable=False, comment="Provider identifier (e.g., plugin_id/provider_name)"
|
||||
)
|
||||
endpoint_id: Mapped[str] = mapped_column(String(255), nullable=False, comment="Subscription endpoint")
|
||||
parameters: Mapped[TriggerJsonObject] = mapped_column(
|
||||
sa.JSON, nullable=False, comment="Subscription parameters JSON"
|
||||
)
|
||||
properties: Mapped[TriggerJsonObject] = mapped_column(
|
||||
sa.JSON, nullable=False, comment="Subscription properties JSON"
|
||||
)
|
||||
|
||||
credentials: Mapped[TriggerCredentials] = mapped_column(
|
||||
sa.JSON, nullable=False, comment="Subscription credentials JSON"
|
||||
)
|
||||
credential_type: Mapped[CredentialType] = mapped_column(
|
||||
EnumText(CredentialType, length=50), nullable=False, comment="oauth or api_key"
|
||||
)
|
||||
credential_expires_at: Mapped[int] = mapped_column(
|
||||
Integer, default=-1, comment="OAuth token expiration timestamp, -1 for never"
|
||||
)
|
||||
expires_at: Mapped[int] = mapped_column(
|
||||
Integer, default=-1, comment="Subscription instance expiration timestamp, -1 for never"
|
||||
)
|
||||
visibility: Mapped[PermissionEnum] = mapped_column(
|
||||
EnumText(PermissionEnum, length=40), nullable=False, default=PermissionEnum.ALL_TEAM
|
||||
)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
def is_credential_expired(self) -> bool:
|
||||
"""Check if credential is expired"""
|
||||
if self.credential_expires_at == -1:
|
||||
return False
|
||||
# Check if token expires in next 3 minutes
|
||||
return (self.credential_expires_at - 180) < int(time.time())
|
||||
|
||||
def to_entity(self) -> Subscription:
|
||||
return Subscription(
|
||||
expires_at=self.expires_at,
|
||||
endpoint=generate_plugin_trigger_endpoint_url(self.endpoint_id),
|
||||
parameters=self.parameters,
|
||||
properties=self.properties,
|
||||
)
|
||||
|
||||
def to_api_entity(self) -> TriggerProviderSubscriptionApiEntity:
|
||||
return TriggerProviderSubscriptionApiEntity(
|
||||
id=self.id,
|
||||
name=self.name,
|
||||
provider=self.provider_id,
|
||||
endpoint=generate_plugin_trigger_endpoint_url(self.endpoint_id),
|
||||
parameters=self.parameters,
|
||||
properties=self.properties,
|
||||
credential_type=self.credential_type,
|
||||
credentials=self.credentials,
|
||||
workflows_in_use=-1,
|
||||
)
|
||||
|
||||
|
||||
# system level trigger oauth client params
|
||||
class TriggerOAuthSystemClient(TypeBase):
|
||||
__tablename__ = "trigger_oauth_system_clients"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="trigger_oauth_system_client_pkey"),
|
||||
sa.UniqueConstraint("plugin_id", "provider", name="trigger_oauth_system_client_plugin_id_provider_idx"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
plugin_id: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
provider: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
# oauth params of the trigger provider
|
||||
encrypted_oauth_params: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
|
||||
# tenant level trigger oauth client params (client_id, client_secret, etc.)
|
||||
class TriggerOAuthTenantClient(TypeBase):
|
||||
__tablename__ = "trigger_oauth_tenant_clients"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="trigger_oauth_tenant_client_pkey"),
|
||||
sa.UniqueConstraint("tenant_id", "plugin_id", "provider", name="unique_trigger_oauth_tenant_client"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
# tenant id
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
plugin_id: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
provider: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
enabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=True)
|
||||
# oauth params of the trigger provider
|
||||
encrypted_oauth_params: Mapped[str] = mapped_column(LongText, nullable=False, default="{}")
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
@property
|
||||
def oauth_params(self) -> Mapping[str, object]:
|
||||
return cast(TriggerJsonObject, json.loads(self.encrypted_oauth_params or "{}"))
|
||||
|
||||
|
||||
class WorkflowTriggerLog(TypeBase):
|
||||
"""
|
||||
Workflow Trigger Log
|
||||
|
||||
Track async trigger workflow runs with re-invocation capability
|
||||
|
||||
Attributes:
|
||||
- id (uuid) Trigger Log ID (used as workflow_trigger_log_id)
|
||||
- tenant_id (uuid) Workspace ID
|
||||
- app_id (uuid) App ID
|
||||
- workflow_id (uuid) Workflow ID
|
||||
- workflow_run_id (uuid) Optional - Associated workflow run ID when execution starts
|
||||
- root_node_id (string) Optional - Custom starting node ID for workflow execution
|
||||
- trigger_metadata (text) Optional - Trigger metadata (JSON)
|
||||
- trigger_type (string) Type of trigger: webhook, schedule, plugin
|
||||
- trigger_data (text) Full trigger data including inputs (JSON)
|
||||
- inputs (text) Input parameters (JSON)
|
||||
- outputs (text) Optional - Output content (JSON)
|
||||
- status (string) Execution status
|
||||
- error (text) Optional - Error message if failed
|
||||
- queue_name (string) Celery queue used
|
||||
- celery_task_id (string) Optional - Celery task ID for tracking
|
||||
- retry_count (int) Number of retry attempts
|
||||
- elapsed_time (float) Optional - Time consumption in seconds
|
||||
- total_tokens (int) Optional - Total tokens used
|
||||
- created_by_role (string) Creator role: account, end_user
|
||||
- created_by (string) Creator ID
|
||||
- created_at (timestamp) Creation time
|
||||
- triggered_at (timestamp) Optional - When actually triggered
|
||||
- finished_at (timestamp) Optional - Completion time
|
||||
"""
|
||||
|
||||
__tablename__ = "workflow_trigger_logs"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="workflow_trigger_log_pkey"),
|
||||
sa.Index("workflow_trigger_log_tenant_app_idx", "tenant_id", "app_id"),
|
||||
sa.Index("workflow_trigger_log_status_idx", "status"),
|
||||
sa.Index("workflow_trigger_log_created_at_idx", "created_at"),
|
||||
sa.Index("workflow_trigger_log_workflow_run_idx", "workflow_run_id"),
|
||||
sa.Index("workflow_trigger_log_workflow_id_idx", "workflow_id"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuidv7()), default_factory=lambda: str(uuidv7()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
workflow_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
workflow_run_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
|
||||
root_node_id: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
trigger_metadata: Mapped[str] = mapped_column(LongText, nullable=False)
|
||||
trigger_type: Mapped[str] = mapped_column(EnumText(AppTriggerType, length=50), nullable=False)
|
||||
trigger_data: Mapped[str] = mapped_column(LongText, nullable=False) # Full TriggerData as JSON
|
||||
inputs: Mapped[str] = mapped_column(LongText, nullable=False) # Just inputs for easy viewing
|
||||
outputs: Mapped[str | None] = mapped_column(LongText, nullable=True)
|
||||
|
||||
status: Mapped[str] = mapped_column(EnumText(WorkflowTriggerStatus, length=50), nullable=False)
|
||||
error: Mapped[str | None] = mapped_column(LongText, nullable=True)
|
||||
|
||||
queue_name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
celery_task_id: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
created_by_role: Mapped[CreatorUserRole] = mapped_column(EnumText(CreatorUserRole, length=255), nullable=False)
|
||||
created_by: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
retry_count: Mapped[int] = mapped_column(sa.Integer, nullable=False, default=0)
|
||||
elapsed_time: Mapped[float | None] = mapped_column(sa.Float, nullable=True, default=None)
|
||||
total_tokens: Mapped[int | None] = mapped_column(sa.Integer, nullable=True, default=None)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
triggered_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
|
||||
def created_by_account(self, session: Session) -> Account | None:
|
||||
created_by_role = CreatorUserRole(self.created_by_role)
|
||||
return session.get(Account, self.created_by) if created_by_role == CreatorUserRole.ACCOUNT else None
|
||||
|
||||
def created_by_end_user(self, session: Session):
|
||||
from .model import EndUser
|
||||
|
||||
created_by_role = CreatorUserRole(self.created_by_role)
|
||||
return session.get(EndUser, self.created_by) if created_by_role == CreatorUserRole.END_USER else None
|
||||
|
||||
def to_dict(self) -> WorkflowTriggerLogDict:
|
||||
"""Convert to dictionary for API responses"""
|
||||
return {
|
||||
"id": self.id,
|
||||
"tenant_id": self.tenant_id,
|
||||
"app_id": self.app_id,
|
||||
"workflow_id": self.workflow_id,
|
||||
"workflow_run_id": self.workflow_run_id,
|
||||
"root_node_id": self.root_node_id,
|
||||
"trigger_metadata": json.loads(self.trigger_metadata) if self.trigger_metadata else None,
|
||||
"trigger_type": self.trigger_type,
|
||||
"trigger_data": json.loads(self.trigger_data),
|
||||
"inputs": json.loads(self.inputs),
|
||||
"outputs": json.loads(self.outputs) if self.outputs else None,
|
||||
"status": self.status,
|
||||
"error": self.error,
|
||||
"queue_name": self.queue_name,
|
||||
"celery_task_id": self.celery_task_id,
|
||||
"retry_count": self.retry_count,
|
||||
"elapsed_time": self.elapsed_time,
|
||||
"total_tokens": self.total_tokens,
|
||||
"created_by_role": self.created_by_role,
|
||||
"created_by": self.created_by,
|
||||
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||
"triggered_at": self.triggered_at.isoformat() if self.triggered_at else None,
|
||||
"finished_at": self.finished_at.isoformat() if self.finished_at else None,
|
||||
}
|
||||
|
||||
|
||||
class WorkflowWebhookTrigger(TypeBase):
|
||||
"""
|
||||
Workflow Webhook Trigger
|
||||
|
||||
Attributes:
|
||||
- id (uuid) Primary key
|
||||
- app_id (uuid) App ID to bind to a specific app
|
||||
- node_id (varchar) Node ID which node in the workflow
|
||||
- tenant_id (uuid) Workspace ID
|
||||
- webhook_id (varchar) Webhook ID for URL: https://api.dify.ai/triggers/webhook/:webhook_id
|
||||
- created_by (varchar) User ID of the creator
|
||||
- created_at (timestamp) Creation time
|
||||
- updated_at (timestamp) Last update time
|
||||
"""
|
||||
|
||||
__tablename__ = "workflow_webhook_triggers"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="workflow_webhook_trigger_pkey"),
|
||||
sa.Index("workflow_webhook_trigger_tenant_idx", "tenant_id"),
|
||||
sa.UniqueConstraint("app_id", "node_id", name="uniq_node"),
|
||||
sa.UniqueConstraint("webhook_id", name="uniq_webhook_id"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuidv7()), default_factory=lambda: str(uuidv7()), init=False
|
||||
)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
node_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
webhook_id: Mapped[str] = mapped_column(String(24), nullable=False)
|
||||
created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
@cached_property
|
||||
def webhook_url(self):
|
||||
"""
|
||||
Generated webhook url
|
||||
"""
|
||||
return generate_webhook_trigger_endpoint(self.webhook_id)
|
||||
|
||||
@cached_property
|
||||
def webhook_debug_url(self):
|
||||
"""
|
||||
Generated debug webhook url
|
||||
"""
|
||||
return generate_webhook_trigger_endpoint(self.webhook_id, True)
|
||||
|
||||
|
||||
class WorkflowPluginTrigger(TypeBase):
|
||||
"""
|
||||
Workflow Plugin Trigger
|
||||
|
||||
Maps plugin triggers to workflow nodes, similar to WorkflowWebhookTrigger
|
||||
|
||||
Attributes:
|
||||
- id (uuid) Primary key
|
||||
- app_id (uuid) App ID to bind to a specific app
|
||||
- node_id (varchar) Node ID which node in the workflow
|
||||
- tenant_id (uuid) Workspace ID
|
||||
- provider_id (varchar) Plugin provider ID
|
||||
- event_name (varchar) trigger name
|
||||
- subscription_id (varchar) Subscription ID
|
||||
- created_at (timestamp) Creation time
|
||||
- updated_at (timestamp) Last update time
|
||||
"""
|
||||
|
||||
__tablename__ = "workflow_plugin_triggers"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="workflow_plugin_trigger_pkey"),
|
||||
sa.Index("workflow_plugin_trigger_tenant_subscription_idx", "tenant_id", "subscription_id", "event_name"),
|
||||
sa.UniqueConstraint("app_id", "node_id", name="uniq_app_node_subscription"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
node_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
provider_id: Mapped[str] = mapped_column(String(512), nullable=False)
|
||||
event_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
subscription_id: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
onupdate=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
|
||||
class AppTrigger(TypeBase):
|
||||
"""
|
||||
App Trigger
|
||||
|
||||
Manages multiple triggers for an app with enable/disable and authorization states.
|
||||
|
||||
Attributes:
|
||||
- id (uuid) Primary key
|
||||
- tenant_id (uuid) Workspace ID
|
||||
- app_id (uuid) App ID
|
||||
- trigger_type (string) Type: webhook, schedule, plugin
|
||||
- title (string) Trigger title
|
||||
|
||||
- status (string) Status: enabled, disabled, unauthorized, error
|
||||
- node_id (string) Required workflow node ID
|
||||
- created_at (timestamp) Creation time
|
||||
- updated_at (timestamp) Last update time
|
||||
"""
|
||||
|
||||
__tablename__ = "app_triggers"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="app_trigger_pkey"),
|
||||
sa.Index("app_trigger_tenant_app_idx", "tenant_id", "app_id"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuidv7()), default_factory=lambda: str(uuidv7()), init=False
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
node_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
trigger_type: Mapped[str] = mapped_column(EnumText(AppTriggerType, length=50), nullable=False)
|
||||
title: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
provider_name: Mapped[str | None] = mapped_column(String(255), nullable=True, default="")
|
||||
status: Mapped[str] = mapped_column(
|
||||
EnumText(AppTriggerStatus, length=50), nullable=False, default=AppTriggerStatus.ENABLED
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
default=naive_utc_now(),
|
||||
onupdate=naive_utc_now(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
|
||||
class WorkflowSchedulePlan(TypeBase):
|
||||
"""
|
||||
Workflow Schedule Configuration
|
||||
|
||||
Store schedule configurations for time-based workflow triggers.
|
||||
Uses cron expressions with timezone support for flexible scheduling.
|
||||
|
||||
Attributes:
|
||||
- id (uuid) Primary key
|
||||
- app_id (uuid) App ID to bind to a specific app
|
||||
- node_id (varchar) Starting node ID for workflow execution
|
||||
- tenant_id (uuid) Workspace ID for multi-tenancy
|
||||
- cron_expression (varchar) Cron expression defining schedule pattern
|
||||
- timezone (varchar) Timezone for cron evaluation (e.g., 'Asia/Shanghai')
|
||||
- next_run_at (timestamp) Next scheduled execution time
|
||||
- created_at (timestamp) Creation timestamp
|
||||
- updated_at (timestamp) Last update timestamp
|
||||
"""
|
||||
|
||||
__tablename__ = "workflow_schedule_plans"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="workflow_schedule_plan_pkey"),
|
||||
sa.UniqueConstraint("app_id", "node_id", name="uniq_app_node"),
|
||||
sa.Index("workflow_schedule_plan_next_idx", "next_run_at"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID,
|
||||
primary_key=True,
|
||||
insert_default=lambda: str(uuidv7()),
|
||||
default_factory=lambda: str(uuidv7()),
|
||||
init=False,
|
||||
)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
node_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
|
||||
# Schedule configuration
|
||||
cron_expression: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
timezone: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
|
||||
# Schedule control
|
||||
next_run_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), init=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), init=False
|
||||
)
|
||||
|
||||
def to_dict(self) -> WorkflowSchedulePlanDict:
|
||||
"""Convert to dictionary representation"""
|
||||
return {
|
||||
"id": self.id,
|
||||
"app_id": self.app_id,
|
||||
"node_id": self.node_id,
|
||||
"tenant_id": self.tenant_id,
|
||||
"cron_expression": self.cron_expression,
|
||||
"timezone": self.timezone,
|
||||
"next_run_at": self.next_run_at.isoformat() if self.next_run_at else None,
|
||||
"created_at": self.created_at.isoformat(),
|
||||
"updated_at": self.updated_at.isoformat(),
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
import enum
|
||||
import json
|
||||
import uuid
|
||||
import warnings
|
||||
from typing import Any, cast, overload, override
|
||||
|
||||
import sqlalchemy as sa
|
||||
from pydantic import BaseModel, TypeAdapter
|
||||
from sqlalchemy import CHAR, TEXT, VARCHAR, LargeBinary, TypeDecorator
|
||||
from sqlalchemy.dialects.mysql import LONGBLOB, LONGTEXT
|
||||
from sqlalchemy.dialects.postgresql import BYTEA, JSONB, UUID
|
||||
from sqlalchemy.engine.interfaces import Dialect
|
||||
from sqlalchemy.sql.type_api import TypeEngine
|
||||
|
||||
from configs import dify_config
|
||||
|
||||
|
||||
class StringUUID(TypeDecorator[uuid.UUID | str | None]):
|
||||
impl = CHAR
|
||||
cache_ok = True
|
||||
|
||||
@override
|
||||
def process_bind_param(self, value: uuid.UUID | str | None, dialect: Dialect) -> str | None:
|
||||
if value is None:
|
||||
return value
|
||||
elif dialect.name in ["postgresql", "mysql"]:
|
||||
return str(value)
|
||||
else:
|
||||
if isinstance(value, uuid.UUID):
|
||||
return value.hex
|
||||
return value
|
||||
|
||||
@override
|
||||
def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
|
||||
if dialect.name == "postgresql":
|
||||
return dialect.type_descriptor(UUID())
|
||||
else:
|
||||
return dialect.type_descriptor(CHAR(36))
|
||||
|
||||
@override
|
||||
def process_result_value(self, value: uuid.UUID | str | None, dialect: Dialect) -> str | None:
|
||||
if value is None:
|
||||
return value
|
||||
return str(value)
|
||||
|
||||
|
||||
class LongText(TypeDecorator[str | None]):
|
||||
impl = TEXT
|
||||
cache_ok = True
|
||||
|
||||
@override
|
||||
def process_bind_param(self, value: str | None, dialect: Dialect) -> str | None:
|
||||
if value is None:
|
||||
return value
|
||||
return value
|
||||
|
||||
@override
|
||||
def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
|
||||
if dialect.name == "postgresql":
|
||||
return dialect.type_descriptor(TEXT())
|
||||
elif dialect.name == "mysql":
|
||||
return dialect.type_descriptor(LONGTEXT())
|
||||
else:
|
||||
return dialect.type_descriptor(TEXT())
|
||||
|
||||
@override
|
||||
def process_result_value(self, value: str | None, dialect: Dialect) -> str | None:
|
||||
if value is None:
|
||||
return value
|
||||
return value
|
||||
|
||||
|
||||
class JSONModelColumn[T: BaseModel](TypeDecorator[T | None]):
|
||||
"""Store coercible Pydantic model input as dialect-adjusted LongText JSON.
|
||||
|
||||
New model-only columns should use ``FrozenPydanticModelColumn``. Existing
|
||||
uses must not be replaced mechanically because they may depend on:
|
||||
|
||||
- historical ``dict`` or JSON string writes;
|
||||
- non-strict validation and coercion;
|
||||
- Pydantic models that are not frozen;
|
||||
- compatibility with dirty or otherwise non-canonical stored data.
|
||||
|
||||
Audit both callers and persisted values before migrating an existing
|
||||
column.
|
||||
"""
|
||||
|
||||
impl = TEXT
|
||||
cache_ok = True
|
||||
|
||||
_model_class: type[T]
|
||||
|
||||
def __init__(self, model_class: type[T]):
|
||||
# Existing persisted columns remain supported until their data and callers are audited.
|
||||
warnings.warn(
|
||||
"JSONModelColumn is a legacy coercing TEXT-backed type. "
|
||||
"Use FrozenPydanticModelColumn for new model-only persistence.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
if not issubclass(model_class, BaseModel):
|
||||
raise TypeError(f"{model_class.__module__}.{model_class.__name__} must be a Pydantic BaseModel subclass")
|
||||
self._model_class = model_class
|
||||
super().__init__()
|
||||
|
||||
@override
|
||||
def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
|
||||
if dialect.name == "postgresql":
|
||||
return dialect.type_descriptor(TEXT())
|
||||
elif dialect.name == "mysql":
|
||||
return dialect.type_descriptor(LONGTEXT())
|
||||
else:
|
||||
return dialect.type_descriptor(TEXT())
|
||||
|
||||
@override
|
||||
def process_bind_param(self, value: T | dict[str, Any] | str | None, dialect: Dialect) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
match value:
|
||||
case _ if isinstance(value, self._model_class):
|
||||
model = value
|
||||
case str():
|
||||
model = self._model_class.model_validate_json(value)
|
||||
case _:
|
||||
model = self._model_class.model_validate(value)
|
||||
return json.dumps(model.model_dump(mode="json"), ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
|
||||
@override
|
||||
def process_result_value(self, value: str | None, dialect: Dialect) -> T | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
return self._model_class.model_validate_json(value)
|
||||
|
||||
|
||||
class BinaryData(TypeDecorator[bytes | None]):
|
||||
impl = LargeBinary
|
||||
cache_ok = True
|
||||
|
||||
@override
|
||||
def process_bind_param(self, value: bytes | None, dialect: Dialect) -> bytes | None:
|
||||
if value is None:
|
||||
return value
|
||||
return value
|
||||
|
||||
@override
|
||||
def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
|
||||
if dialect.name == "postgresql":
|
||||
return dialect.type_descriptor(BYTEA())
|
||||
elif dialect.name == "mysql":
|
||||
return dialect.type_descriptor(LONGBLOB())
|
||||
else:
|
||||
return dialect.type_descriptor(LargeBinary())
|
||||
|
||||
@override
|
||||
def process_result_value(self, value: bytes | None, dialect: Dialect) -> bytes | None:
|
||||
if value is None:
|
||||
return value
|
||||
return value
|
||||
|
||||
|
||||
class AdjustedJSON(TypeDecorator[dict | list | None]):
|
||||
impl = sa.JSON
|
||||
cache_ok = True
|
||||
|
||||
def __init__(self, astext_type=None):
|
||||
self.astext_type = astext_type
|
||||
super().__init__()
|
||||
|
||||
@override
|
||||
def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
|
||||
if dialect.name == "postgresql":
|
||||
if self.astext_type:
|
||||
return dialect.type_descriptor(JSONB(astext_type=self.astext_type))
|
||||
else:
|
||||
return dialect.type_descriptor(JSONB())
|
||||
elif dialect.name == "mysql":
|
||||
return dialect.type_descriptor(sa.JSON())
|
||||
else:
|
||||
return dialect.type_descriptor(sa.JSON())
|
||||
|
||||
@override
|
||||
def process_bind_param(
|
||||
self, value: dict[str, Any] | list[Any] | None, dialect: Dialect
|
||||
) -> dict[str, Any] | list[Any] | None:
|
||||
return value
|
||||
|
||||
@override
|
||||
def process_result_value(
|
||||
self, value: dict[str, Any] | list[Any] | None, dialect: Dialect
|
||||
) -> dict[str, Any] | list[Any] | None:
|
||||
return value
|
||||
|
||||
|
||||
class FrozenPydanticModelColumn[T: BaseModel](TypeDecorator[T]):
|
||||
"""Persist a frozen Pydantic model as JSON in a dialect-adjusted text column.
|
||||
|
||||
Binding serializes the accepted model directly with
|
||||
``model_dump_json(warnings="error")``. Loading validates the stored JSON in
|
||||
strict mode and lets Pydantic validation errors propagate to the caller.
|
||||
Pass a concrete model class for concrete models. For discriminated unions,
|
||||
pass a ``TypeAdapter`` together with every allowed concrete model class.
|
||||
|
||||
The backing type is ``TEXT`` on PostgreSQL and SQLite and ``LONGTEXT`` on
|
||||
MySQL. This is intentional: ``model_dump_json`` already returns JSON text,
|
||||
while passing that string through SQLAlchemy's ``JSON`` type would encode it
|
||||
again and persist a JSON string scalar instead of the model's JSON object.
|
||||
|
||||
SQLAlchemy does not track in-place changes made inside a Pydantic model, so
|
||||
this type only accepts models configured with ``frozen=True``. Persisted
|
||||
values must be updated by constructing a new model and assigning it to the
|
||||
ORM attribute as a whole, for example ``record.payload = PayloadModel(...)``.
|
||||
Otherwise the attribute may not be marked dirty and the change may not be
|
||||
persisted.
|
||||
|
||||
Pydantic freezing is shallow: nested mutable containers such as ``dict`` and
|
||||
``list`` can still be changed in place. Callers must treat nested values as
|
||||
immutable too instead of mutating paths such as
|
||||
``record.payload.root["key"]``. Supporting nested in-place mutation would
|
||||
require SQLAlchemy's Mutable extension or explicit deep change tracking,
|
||||
which this type does not provide.
|
||||
"""
|
||||
|
||||
impl = TEXT
|
||||
cache_ok = True
|
||||
|
||||
_model_type: type[T] | None
|
||||
_adapter: TypeAdapter[T] | None
|
||||
model_types: tuple[type[BaseModel], ...]
|
||||
|
||||
@overload
|
||||
def __init__(
|
||||
self,
|
||||
model_type: type[T],
|
||||
/,
|
||||
) -> None: ...
|
||||
|
||||
@overload
|
||||
def __init__(
|
||||
self,
|
||||
adapter: TypeAdapter[T],
|
||||
/,
|
||||
*,
|
||||
model_types: tuple[type[BaseModel], ...],
|
||||
) -> None: ...
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
schema: type[T] | TypeAdapter[T],
|
||||
/,
|
||||
*,
|
||||
model_types: tuple[type[BaseModel], ...] | None = None,
|
||||
) -> None:
|
||||
if isinstance(schema, TypeAdapter):
|
||||
if model_types is None:
|
||||
raise TypeError("model_types is required when schema is a TypeAdapter")
|
||||
if not model_types:
|
||||
raise ValueError("model_types must not be empty")
|
||||
self._model_type = None
|
||||
self._adapter = schema
|
||||
self.model_types = model_types
|
||||
else:
|
||||
if model_types is not None:
|
||||
raise TypeError("model_types must not be provided for a concrete model")
|
||||
self._model_type = schema
|
||||
self._adapter = None
|
||||
self.model_types = (schema,)
|
||||
|
||||
for allowed_model_type in self.model_types:
|
||||
if not isinstance(allowed_model_type, type) or not issubclass(allowed_model_type, BaseModel):
|
||||
raise TypeError("model_types must contain only Pydantic BaseModel classes")
|
||||
model_name = f"{allowed_model_type.__module__}.{allowed_model_type.__qualname__}"
|
||||
if allowed_model_type.model_config.get("frozen") is not True:
|
||||
raise TypeError(f"{model_name} must configure frozen=True")
|
||||
if allowed_model_type.model_config.get("strict") is not True:
|
||||
raise TypeError(f"{model_name} must configure strict=True")
|
||||
super().__init__()
|
||||
|
||||
@override
|
||||
def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
|
||||
if dialect.name == "mysql":
|
||||
return dialect.type_descriptor(LONGTEXT())
|
||||
return dialect.type_descriptor(TEXT())
|
||||
|
||||
@override
|
||||
def process_bind_param(self, value: object | None, dialect: Dialect) -> str | None:
|
||||
del dialect
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, BaseModel) or not isinstance(value, self.model_types):
|
||||
allowed_model_names = ", ".join(model_type.__name__ for model_type in self.model_types)
|
||||
raise TypeError(f"value must be one of these Pydantic models: {allowed_model_names}")
|
||||
return value.model_dump_json(warnings="error")
|
||||
|
||||
@override
|
||||
def process_result_value(self, value: str | bytes | bytearray | None, dialect: Dialect) -> T | None:
|
||||
del dialect
|
||||
if value is None:
|
||||
return None
|
||||
if self._model_type is not None:
|
||||
return self._model_type.model_validate_json(value, strict=True)
|
||||
if self._adapter is None:
|
||||
raise RuntimeError("Pydantic JSON validator is not configured")
|
||||
return self._adapter.validate_json(value, strict=True)
|
||||
|
||||
|
||||
class EnumText[T: enum.StrEnum](TypeDecorator[T | None]):
|
||||
impl = VARCHAR
|
||||
cache_ok = True
|
||||
|
||||
_length: int
|
||||
_enum_class: type[T]
|
||||
|
||||
def __init__(self, enum_class: type[T], length: int | None = None):
|
||||
self._enum_class = enum_class
|
||||
max_enum_value_len = max(len(e.value) for e in enum_class)
|
||||
if length is not None:
|
||||
if length < max_enum_value_len:
|
||||
raise ValueError("length should be greater than enum value length.")
|
||||
self._length = length
|
||||
else:
|
||||
# leave some rooms for future longer enum values.
|
||||
self._length = max(max_enum_value_len, 20)
|
||||
|
||||
@override
|
||||
def process_bind_param(self, value: T | str | None, dialect: Dialect) -> str | None:
|
||||
if value is None:
|
||||
return value
|
||||
if isinstance(value, self._enum_class):
|
||||
return value.value
|
||||
# Since T is bound to StrEnum which inherits from str, at this point value must be str
|
||||
self._enum_class(value)
|
||||
return value
|
||||
|
||||
@override
|
||||
def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
|
||||
return dialect.type_descriptor(VARCHAR(self._length))
|
||||
|
||||
@override
|
||||
def process_result_value(self, value: str | None, dialect: Dialect) -> T | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
# Type annotation guarantees value is str at this point
|
||||
return self._enum_class(value)
|
||||
except ValueError:
|
||||
value_of = getattr(self._enum_class, "value_of", None)
|
||||
if callable(value_of):
|
||||
return cast(T, value_of(value))
|
||||
raise
|
||||
|
||||
@override
|
||||
def compare_values(self, x: T | None, y: T | None) -> bool:
|
||||
if x is None or y is None:
|
||||
return x is y
|
||||
return x == y
|
||||
|
||||
|
||||
def adjusted_json_index(index_name, column_name):
|
||||
index_name = index_name or f"{column_name}_idx"
|
||||
if dify_config.DB_TYPE == "postgresql":
|
||||
return sa.Index(index_name, column_name, postgresql_using="gin")
|
||||
else:
|
||||
return None
|
||||
@@ -0,0 +1,3 @@
|
||||
from .file_input_compat import build_file_from_input_mapping
|
||||
|
||||
__all__ = ["build_file_from_input_mapping"]
|
||||
@@ -0,0 +1,271 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Mapping
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
from pydantic import JsonValue
|
||||
|
||||
from core.workflow.file_reference import parse_file_reference
|
||||
from graphon.file import File, FileTransferMethod, FileType
|
||||
from graphon.file.constants import FILE_MODEL_IDENTITY, maybe_file_object
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _get_file_access_controller():
|
||||
from core.app.file_access import DatabaseFileAccessController
|
||||
|
||||
return DatabaseFileAccessController()
|
||||
|
||||
|
||||
def resolve_file_record_id(file_mapping: Mapping[str, Any]) -> str | None:
|
||||
reference = file_mapping.get("reference")
|
||||
if isinstance(reference, str) and reference:
|
||||
parsed_reference = parse_file_reference(reference)
|
||||
if parsed_reference is not None:
|
||||
return parsed_reference.record_id
|
||||
|
||||
related_id = file_mapping.get("related_id")
|
||||
if isinstance(related_id, str) and related_id:
|
||||
parsed_reference = parse_file_reference(related_id)
|
||||
if parsed_reference is not None:
|
||||
return parsed_reference.record_id
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def resolve_file_mapping_tenant_id(
|
||||
*,
|
||||
file_mapping: Mapping[str, Any],
|
||||
tenant_resolver: Callable[[], str],
|
||||
) -> str:
|
||||
tenant_id = file_mapping.get("tenant_id")
|
||||
if isinstance(tenant_id, str) and tenant_id:
|
||||
return tenant_id
|
||||
|
||||
return tenant_resolver()
|
||||
|
||||
|
||||
def build_file_from_mapping_without_lookup(*, file_mapping: Mapping[str, Any]) -> File:
|
||||
"""Build a graph `File` directly from serialized metadata."""
|
||||
|
||||
def _coerce_file_type(value: Any) -> FileType:
|
||||
match value:
|
||||
case FileType():
|
||||
return value
|
||||
case str():
|
||||
return FileType.value_of(value)
|
||||
case _:
|
||||
raise ValueError("file type is required in file mapping")
|
||||
|
||||
mapping = dict(file_mapping)
|
||||
transfer_method_value = mapping.get("transfer_method")
|
||||
match transfer_method_value:
|
||||
case FileTransferMethod():
|
||||
transfer_method = transfer_method_value
|
||||
case str():
|
||||
transfer_method = FileTransferMethod.value_of(transfer_method_value)
|
||||
case _:
|
||||
raise ValueError("transfer_method is required in file mapping")
|
||||
|
||||
file_id = mapping.get("file_id")
|
||||
if not isinstance(file_id, str) or not file_id:
|
||||
legacy_id = mapping.get("id")
|
||||
file_id = legacy_id if isinstance(legacy_id, str) and legacy_id else None
|
||||
|
||||
related_id = resolve_file_record_id(mapping)
|
||||
if related_id is None:
|
||||
raw_related_id = mapping.get("related_id")
|
||||
related_id = raw_related_id if isinstance(raw_related_id, str) and raw_related_id else None
|
||||
|
||||
remote_url = mapping.get("remote_url")
|
||||
if not isinstance(remote_url, str) or not remote_url:
|
||||
url = mapping.get("url")
|
||||
remote_url = url if isinstance(url, str) and url else None
|
||||
|
||||
reference = mapping.get("reference")
|
||||
if not isinstance(reference, str) or not reference:
|
||||
reference = None
|
||||
|
||||
filename = mapping.get("filename")
|
||||
if not isinstance(filename, str):
|
||||
filename = None
|
||||
|
||||
extension = mapping.get("extension")
|
||||
if not isinstance(extension, str):
|
||||
extension = None
|
||||
|
||||
mime_type = mapping.get("mime_type")
|
||||
if not isinstance(mime_type, str):
|
||||
mime_type = None
|
||||
|
||||
size = mapping.get("size", -1)
|
||||
if not isinstance(size, int):
|
||||
size = -1
|
||||
|
||||
storage_key = mapping.get("storage_key")
|
||||
if not isinstance(storage_key, str):
|
||||
storage_key = None
|
||||
|
||||
tenant_id = mapping.get("tenant_id")
|
||||
if not isinstance(tenant_id, str):
|
||||
tenant_id = None
|
||||
|
||||
dify_model_identity = mapping.get("dify_model_identity")
|
||||
if not isinstance(dify_model_identity, str):
|
||||
dify_model_identity = FILE_MODEL_IDENTITY
|
||||
|
||||
tool_file_id = mapping.get("tool_file_id")
|
||||
if not isinstance(tool_file_id, str):
|
||||
tool_file_id = None
|
||||
|
||||
upload_file_id = mapping.get("upload_file_id")
|
||||
if not isinstance(upload_file_id, str):
|
||||
upload_file_id = None
|
||||
|
||||
datasource_file_id = mapping.get("datasource_file_id")
|
||||
if not isinstance(datasource_file_id, str):
|
||||
datasource_file_id = None
|
||||
|
||||
return File(
|
||||
file_id=file_id,
|
||||
tenant_id=tenant_id,
|
||||
file_type=_coerce_file_type(mapping.get("file_type", mapping.get("type"))),
|
||||
transfer_method=transfer_method,
|
||||
remote_url=remote_url,
|
||||
reference=reference,
|
||||
related_id=related_id,
|
||||
filename=filename,
|
||||
extension=extension,
|
||||
mime_type=mime_type,
|
||||
size=size,
|
||||
storage_key=storage_key,
|
||||
dify_model_identity=dify_model_identity,
|
||||
url=remote_url,
|
||||
tool_file_id=tool_file_id,
|
||||
upload_file_id=upload_file_id,
|
||||
datasource_file_id=datasource_file_id,
|
||||
)
|
||||
|
||||
|
||||
def rebuild_serialized_graph_files_without_lookup(value: Any) -> Any:
|
||||
"""Recursively rebuild serialized graph file payloads into `File` objects.
|
||||
|
||||
`graphon` no longer accepts legacy serialized file mappings via
|
||||
`model_validate_json()`. Dify keeps this recovery path at the model
|
||||
boundary so historical JSON blobs remain readable without reintroducing
|
||||
global graph patches or test-local coercion.
|
||||
"""
|
||||
match value:
|
||||
case list():
|
||||
return [rebuild_serialized_graph_files_without_lookup(item) for item in value]
|
||||
case dict():
|
||||
if maybe_file_object(value):
|
||||
return build_file_from_mapping_without_lookup(file_mapping=value)
|
||||
return {key: rebuild_serialized_graph_files_without_lookup(item) for key, item in value.items()}
|
||||
case _:
|
||||
return value
|
||||
|
||||
|
||||
def build_file_from_stored_mapping(
|
||||
*,
|
||||
file_mapping: Mapping[str, Any],
|
||||
tenant_id: str,
|
||||
) -> File:
|
||||
"""
|
||||
Canonicalize a persisted file payload against the current tenant context.
|
||||
|
||||
Stored JSON rows can outlive file schema changes, so rebuild storage-backed
|
||||
files through the workflow factory instead of trusting serialized metadata.
|
||||
Pure external ``REMOTE_URL`` payloads without a backing upload row are
|
||||
passed through because there is no server-owned record to rebind.
|
||||
"""
|
||||
|
||||
# NOTE: It's not the best way to implement this, but it's the only way to avoid circular import for now.
|
||||
from factories import file_factory
|
||||
|
||||
mapping = dict(file_mapping)
|
||||
mapping.pop("tenant_id", None)
|
||||
record_id = resolve_file_record_id(mapping)
|
||||
transfer_method = FileTransferMethod.value_of(mapping["transfer_method"])
|
||||
|
||||
match transfer_method:
|
||||
case FileTransferMethod.TOOL_FILE if record_id:
|
||||
mapping["tool_file_id"] = record_id
|
||||
case FileTransferMethod.LOCAL_FILE | FileTransferMethod.REMOTE_URL if record_id:
|
||||
mapping["upload_file_id"] = record_id
|
||||
case FileTransferMethod.DATASOURCE_FILE if record_id:
|
||||
mapping["datasource_file_id"] = record_id
|
||||
case _:
|
||||
pass
|
||||
|
||||
if transfer_method == FileTransferMethod.REMOTE_URL and record_id is None:
|
||||
return build_file_from_mapping_without_lookup(file_mapping=mapping)
|
||||
|
||||
return file_factory.build_from_mapping(
|
||||
mapping=mapping,
|
||||
tenant_id=tenant_id,
|
||||
access_controller=_get_file_access_controller(),
|
||||
)
|
||||
|
||||
|
||||
def build_file_from_input_mapping(
|
||||
*,
|
||||
file_mapping: Mapping[str, Any],
|
||||
tenant_resolver: Callable[[], str],
|
||||
) -> File:
|
||||
"""
|
||||
Rehydrate persisted model input payloads into graph `File` objects.
|
||||
|
||||
This compatibility layer exists because model JSON rows can outlive file payload
|
||||
schema changes. Legacy rows may carry `related_id` and `tenant_id`, while newer
|
||||
rows may only carry `reference`. Keep ownership resolution here, at the model
|
||||
boundary, instead of pushing tenant data back into `graphon.file.File`.
|
||||
"""
|
||||
|
||||
transfer_method = FileTransferMethod.value_of(file_mapping["transfer_method"])
|
||||
record_id = resolve_file_record_id(file_mapping)
|
||||
if transfer_method == FileTransferMethod.REMOTE_URL and record_id is None:
|
||||
return build_file_from_stored_mapping(
|
||||
file_mapping=file_mapping,
|
||||
tenant_id="",
|
||||
)
|
||||
|
||||
tenant_id = resolve_file_mapping_tenant_id(file_mapping=file_mapping, tenant_resolver=tenant_resolver)
|
||||
return build_file_from_stored_mapping(
|
||||
file_mapping=file_mapping,
|
||||
tenant_id=tenant_id,
|
||||
)
|
||||
|
||||
|
||||
def restore_input_files(
|
||||
*,
|
||||
inputs: Mapping[str, JsonValue | File | list[File]],
|
||||
tenant_resolver: Callable[[], str],
|
||||
) -> dict[str, JsonValue | File | list[File]]:
|
||||
"""Restore top-level file inputs, preserving mixed lists and ordinary mappings.
|
||||
|
||||
Resolve the app tenant lazily: legacy files may already carry their tenant,
|
||||
and external remote files do not need an owner lookup.
|
||||
"""
|
||||
restored = dict(inputs)
|
||||
for key, value in inputs.items():
|
||||
match value:
|
||||
case dict() if value.get("dify_model_identity") == FILE_MODEL_IDENTITY:
|
||||
restored[key] = build_file_from_input_mapping(
|
||||
file_mapping=value,
|
||||
tenant_resolver=tenant_resolver,
|
||||
)
|
||||
case list():
|
||||
if all(
|
||||
isinstance(item, dict) and item.get("dify_model_identity") == FILE_MODEL_IDENTITY for item in value
|
||||
):
|
||||
restored[key] = [
|
||||
build_file_from_input_mapping(
|
||||
file_mapping=item,
|
||||
tenant_resolver=tenant_resolver,
|
||||
)
|
||||
for item in value
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
return restored
|
||||
@@ -0,0 +1,65 @@
|
||||
from datetime import datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import DateTime, func, select
|
||||
from sqlalchemy.orm import Mapped, Session, mapped_column
|
||||
|
||||
from .base import TypeBase
|
||||
from .enums import CreatorUserRole
|
||||
from .model import Message
|
||||
from .types import EnumText, StringUUID
|
||||
|
||||
|
||||
class SavedMessage(TypeBase):
|
||||
__tablename__ = "saved_messages"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="saved_message_pkey"),
|
||||
sa.Index("saved_message_message_idx", "app_id", "message_id", "created_by_role", "created_by"),
|
||||
sa.Index("saved_message_message_id_idx", "message_id"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
message_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
created_by_role: Mapped[CreatorUserRole] = mapped_column(
|
||||
EnumText(CreatorUserRole, length=255), nullable=False, server_default=sa.text("'end_user'")
|
||||
)
|
||||
created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
|
||||
def message(self, session: Session) -> Message | None:
|
||||
return session.scalar(select(Message).where(Message.id == self.message_id))
|
||||
|
||||
|
||||
class PinnedConversation(TypeBase):
|
||||
__tablename__ = "pinned_conversations"
|
||||
__table_args__ = (
|
||||
sa.PrimaryKeyConstraint("id", name="pinned_conversation_pkey"),
|
||||
sa.Index("pinned_conversation_conversation_idx", "app_id", "conversation_id", "created_by_role", "created_by"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(
|
||||
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
|
||||
)
|
||||
app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
conversation_id: Mapped[str] = mapped_column(StringUUID)
|
||||
created_by_role: Mapped[CreatorUserRole] = mapped_column(
|
||||
EnumText(CreatorUserRole, length=255),
|
||||
nullable=False,
|
||||
server_default=sa.text("'end_user'"),
|
||||
)
|
||||
created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.current_timestamp(),
|
||||
init=False,
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user