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
Whitespace-only changes.
@@ -0,0 +1 @@
|
||||
"""Domain-specific dependency composition for application services."""
|
||||
@@ -0,0 +1,360 @@
|
||||
"""Compose the account domain using shared account and workspace persistence."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from functools import partial
|
||||
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from configs import dify_config
|
||||
from constants.languages import languages
|
||||
from enums import DeploymentEdition
|
||||
from extensions.ext_redis import RedisClientWrapper
|
||||
from libs.datetime_utils import naive_utc_now, utc_now
|
||||
from libs.helper import RateLimiter
|
||||
from libs.oauth import GitHubOAuth, GoogleOAuth
|
||||
from libs.oauth_bearer import invalidate_oauth_token_cache
|
||||
from repositories.account.repository import SQLAlchemyAccountRepository
|
||||
from repositories.account_activation_repository import SQLAlchemyAccountActivationRepository
|
||||
from repositories.account_integration_repository import SQLAlchemyAccountIntegrationRepository
|
||||
from repositories.oauth_access_token_repository import SQLAlchemyOAuthAccessTokenRepository
|
||||
from repositories.workspace.workspace_repository import WorkspaceRepository
|
||||
from services.account.adapters import (
|
||||
AccountIdentityGateway,
|
||||
BillingAccountActivationEligibility,
|
||||
BillingAccountDeletionFeedbackGateway,
|
||||
BillingAccountEducationGateway,
|
||||
BillingAccountEmailPolicyGateway,
|
||||
BillingWorkspaceMembershipCache,
|
||||
CeleryAccountDeletionScheduler,
|
||||
CeleryAccountDeletionVerificationNotifier,
|
||||
CeleryChangeEmailNotificationGateway,
|
||||
DeploymentAccountLifecyclePolicy,
|
||||
DeploymentWorkspaceInvitePolicy,
|
||||
EnterpriseAccountDeletionSyncGateway,
|
||||
RateLimiterChangeEmailSendLimiter,
|
||||
RBACWorkspaceMemberAccessSync,
|
||||
RedisChangeEmailSecurityGateway,
|
||||
RedisInvitationTokenStore,
|
||||
SecureChangeEmailCodeGenerator,
|
||||
TokenManagerAccountDeletionVerificationGateway,
|
||||
TokenManagerChangeEmailTokenGateway,
|
||||
)
|
||||
from services.account.email_registration_adapters import (
|
||||
AccountLifecycleRegistrationGateway,
|
||||
BillingAccountRegistrationPolicyGateway,
|
||||
CeleryEmailRegistrationNotificationGateway,
|
||||
RateLimiterEmailRegistrationSendLimiter,
|
||||
RedisEmailRegistrationSecurityGateway,
|
||||
SecureEmailRegistrationCodeGenerator,
|
||||
TokenManagerEmailRegistrationTokenGateway,
|
||||
)
|
||||
from services.account.email_registration_service import AccountEmailRegistrationService
|
||||
from services.account.forgot_password_adapters import (
|
||||
CeleryForgotPasswordNotificationGateway,
|
||||
RateLimiterForgotPasswordSendLimiter,
|
||||
RedisForgotPasswordSecurityGateway,
|
||||
RedisForgotPasswordTokenGateway,
|
||||
SecureForgotPasswordCodeGenerator,
|
||||
SystemFeatureServiceForgotPasswordRegistrationPolicy,
|
||||
)
|
||||
from services.account.forgot_password_service import AccountForgotPasswordService
|
||||
from services.account.login_adapters import (
|
||||
AccountActivationConsoleAuthInvitationGateway,
|
||||
DeploymentConsoleAuthPolicyGateway,
|
||||
LoggingConsoleAuthAuditGateway,
|
||||
RedisAccountSessionGateway,
|
||||
RedisConsoleAuthSecurityGateway,
|
||||
RedisEmailCodeGateway,
|
||||
RedisResetPasswordEmailGateway,
|
||||
SQLAlchemyAccountRefreshPreparationGateway,
|
||||
TurnstileHumanVerificationGateway,
|
||||
)
|
||||
from services.account.login_service import ConsoleAuthenticationService
|
||||
from services.account.oauth_adapters import (
|
||||
AccountActivationOAuthInvitationGateway,
|
||||
AccountLifecycleOAuthRegistrationGateway,
|
||||
AccountLifecycleOAuthSessionGateway,
|
||||
DeploymentOAuthPolicyGateway,
|
||||
DifyOAuthProviderGateway,
|
||||
RedisOAuthAccountClaimLock,
|
||||
WorkspaceProvisioningOAuthGateway,
|
||||
)
|
||||
from services.account.oauth_service import AccountOAuthService, OAuthProviderGateway
|
||||
from services.account.service import AccountService
|
||||
from services.account_access_service import AccountAccessService
|
||||
from services.account_activation_service import (
|
||||
AccountActivationRepository,
|
||||
AccountActivationService,
|
||||
InvitationTokenStore,
|
||||
)
|
||||
from services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGateway
|
||||
from services.account_avatar_service import AccountAvatarService
|
||||
from services.account_change_email_service import AccountChangeEmailService
|
||||
from services.account_deletion_feedback_service import AccountDeletionFeedbackService
|
||||
from services.account_deletion_service import AccountDeletionService
|
||||
from services.account_education_service import AccountEducationService
|
||||
from services.account_initialization_service import AccountInitializationService
|
||||
from services.account_integration_service import AccountIntegrationService
|
||||
from services.account_password_hasher import DefaultAccountPasswordHasher
|
||||
from services.account_password_service import AccountPasswordService
|
||||
from services.account_profile_service import AccountProfileService
|
||||
from services.workspace.provisioning_service import WorkspaceProvisioningService
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AccountServices:
|
||||
access: AccountAccessService
|
||||
activation: AccountActivationService
|
||||
authentication: ConsoleAuthenticationService
|
||||
avatar: AccountAvatarService
|
||||
change_email: AccountChangeEmailService
|
||||
email_registration: AccountEmailRegistrationService
|
||||
deletion: AccountDeletionService
|
||||
deletion_feedback: AccountDeletionFeedbackService
|
||||
education: AccountEducationService
|
||||
forgot_password: AccountForgotPasswordService
|
||||
initialization: AccountInitializationService
|
||||
integrations: AccountIntegrationService
|
||||
oauth: AccountOAuthService
|
||||
password: AccountPasswordService
|
||||
profile: AccountProfileService
|
||||
lifecycle: AccountService
|
||||
identity: AccountIdentityGateway
|
||||
|
||||
|
||||
def _build_account_oauth_service(
|
||||
*,
|
||||
deployment_edition: DeploymentEdition,
|
||||
redis: RedisClientWrapper,
|
||||
accounts: SQLAlchemyAccountRepository,
|
||||
integrations: SQLAlchemyAccountIntegrationRepository,
|
||||
memberships: WorkspaceRepository,
|
||||
lifecycle: AccountService,
|
||||
workspace_provisioning: WorkspaceProvisioningService,
|
||||
invitation_tokens: InvitationTokenStore,
|
||||
activation_accounts: AccountActivationRepository,
|
||||
) -> AccountOAuthService:
|
||||
providers: dict[str, OAuthProviderGateway] = {}
|
||||
if dify_config.GITHUB_CLIENT_ID and dify_config.GITHUB_CLIENT_SECRET:
|
||||
providers["github"] = DifyOAuthProviderGateway(
|
||||
provider_name="github",
|
||||
client=GitHubOAuth(
|
||||
client_id=dify_config.GITHUB_CLIENT_ID,
|
||||
client_secret=dify_config.GITHUB_CLIENT_SECRET,
|
||||
redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/github",
|
||||
),
|
||||
)
|
||||
if dify_config.GOOGLE_CLIENT_ID and dify_config.GOOGLE_CLIENT_SECRET:
|
||||
providers["google"] = DifyOAuthProviderGateway(
|
||||
provider_name="google",
|
||||
client=GoogleOAuth(
|
||||
client_id=dify_config.GOOGLE_CLIENT_ID,
|
||||
client_secret=dify_config.GOOGLE_CLIENT_SECRET,
|
||||
redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/google",
|
||||
),
|
||||
)
|
||||
|
||||
policy = DeploymentOAuthPolicyGateway(
|
||||
billing_enabled=deployment_edition == DeploymentEdition.CLOUD,
|
||||
)
|
||||
return AccountOAuthService(
|
||||
providers=providers,
|
||||
accounts=accounts,
|
||||
integrations=integrations,
|
||||
memberships=memberships,
|
||||
invitations=AccountActivationOAuthInvitationGateway(tokens=invitation_tokens, accounts=activation_accounts),
|
||||
account_claims=RedisOAuthAccountClaimLock(client=redis),
|
||||
registration=AccountLifecycleOAuthRegistrationGateway(accounts=lifecycle),
|
||||
workspaces=WorkspaceProvisioningOAuthGateway(workspaces=workspace_provisioning),
|
||||
sessions=AccountLifecycleOAuthSessionGateway(accounts=lifecycle),
|
||||
registration_policy=policy,
|
||||
workspace_policy=policy,
|
||||
supported_languages=languages,
|
||||
now=naive_utc_now,
|
||||
)
|
||||
|
||||
|
||||
def build_account_services(
|
||||
*,
|
||||
database_client: sessionmaker[Session],
|
||||
deployment_edition: DeploymentEdition,
|
||||
redis: RedisClientWrapper,
|
||||
accounts: SQLAlchemyAccountRepository,
|
||||
integrations: SQLAlchemyAccountIntegrationRepository,
|
||||
workspace_repository: WorkspaceRepository,
|
||||
workspace_provisioning: WorkspaceProvisioningService,
|
||||
passwords: DefaultAccountPasswordHasher,
|
||||
invitation_tokens: RedisInvitationTokenStore,
|
||||
activation_accounts: SQLAlchemyAccountActivationRepository,
|
||||
) -> AccountServices:
|
||||
lifecycle = AccountService(
|
||||
security=RedisConsoleAuthSecurityGateway(redis=redis),
|
||||
accounts=accounts,
|
||||
policies=DeploymentAccountLifecyclePolicy(),
|
||||
passwords=passwords,
|
||||
workspaces=workspace_provisioning,
|
||||
sessions=RedisAccountSessionGateway(redis=redis),
|
||||
now=naive_utc_now,
|
||||
)
|
||||
activation = AccountActivationService(
|
||||
tokens=invitation_tokens,
|
||||
accounts=activation_accounts,
|
||||
workspace_policy=DeploymentWorkspaceInvitePolicy(),
|
||||
eligibility=BillingAccountActivationEligibility(
|
||||
enabled=deployment_edition == DeploymentEdition.CLOUD,
|
||||
),
|
||||
membership_cache=BillingWorkspaceMembershipCache(
|
||||
enabled=deployment_edition == DeploymentEdition.CLOUD,
|
||||
),
|
||||
member_access_sync=RBACWorkspaceMemberAccessSync(
|
||||
enabled=dify_config.RBAC_ENABLED,
|
||||
),
|
||||
)
|
||||
return AccountServices(
|
||||
lifecycle=lifecycle,
|
||||
activation=activation,
|
||||
identity=AccountIdentityGateway(accounts=accounts, redis=redis),
|
||||
access=AccountAccessService(
|
||||
accounts=accounts,
|
||||
workspaces=workspace_repository,
|
||||
sessions=SQLAlchemyOAuthAccessTokenRepository(session_factory=database_client),
|
||||
invalidate_token_cache=partial(invalidate_oauth_token_cache, redis),
|
||||
now=utc_now,
|
||||
),
|
||||
authentication=ConsoleAuthenticationService(
|
||||
accounts=accounts,
|
||||
workspaces=workspace_repository,
|
||||
invitations=AccountActivationConsoleAuthInvitationGateway(
|
||||
tokens=invitation_tokens,
|
||||
accounts=activation_accounts,
|
||||
activation=activation,
|
||||
),
|
||||
policies=DeploymentConsoleAuthPolicyGateway(
|
||||
billing_enabled=deployment_edition == DeploymentEdition.CLOUD,
|
||||
),
|
||||
security=RedisConsoleAuthSecurityGateway(redis=redis),
|
||||
passwords=passwords,
|
||||
human_verification=TurnstileHumanVerificationGateway(),
|
||||
sessions=RedisAccountSessionGateway(redis=redis),
|
||||
refresh_preparation=SQLAlchemyAccountRefreshPreparationGateway(accounts=accounts),
|
||||
account_provisioning=workspace_provisioning,
|
||||
workspace_provisioning=workspace_provisioning,
|
||||
email_codes=RedisEmailCodeGateway(redis=redis),
|
||||
reset_password_emails=RedisResetPasswordEmailGateway(redis=redis),
|
||||
audit=LoggingConsoleAuthAuditGateway(),
|
||||
now=naive_utc_now,
|
||||
turnstile_enabled=deployment_edition == DeploymentEdition.CLOUD,
|
||||
turnstile_verify_required=(
|
||||
deployment_edition == DeploymentEdition.CLOUD and dify_config.TURNSTILE_EMAIL_CODE_VERIFY_REQUIRED
|
||||
),
|
||||
),
|
||||
avatar=AccountAvatarService(
|
||||
files=SQLAlchemyAccountAvatarFileGateway(session_factory=database_client),
|
||||
),
|
||||
change_email=AccountChangeEmailService(
|
||||
accounts=accounts,
|
||||
tokens=TokenManagerChangeEmailTokenGateway(),
|
||||
codes=SecureChangeEmailCodeGenerator(),
|
||||
notifications=CeleryChangeEmailNotificationGateway(),
|
||||
send_limits=RateLimiterChangeEmailSendLimiter(redis=redis),
|
||||
security=RedisChangeEmailSecurityGateway(
|
||||
redis=redis,
|
||||
email_send_ip_limit_per_minute=dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE,
|
||||
verification_failure_limit=5,
|
||||
verification_lockout_duration=dify_config.CHANGE_EMAIL_LOCKOUT_DURATION,
|
||||
),
|
||||
email_policy=BillingAccountEmailPolicyGateway(
|
||||
billing_enabled=deployment_edition == DeploymentEdition.CLOUD,
|
||||
),
|
||||
),
|
||||
email_registration=AccountEmailRegistrationService(
|
||||
accounts=accounts,
|
||||
tokens=TokenManagerEmailRegistrationTokenGateway(),
|
||||
codes=SecureEmailRegistrationCodeGenerator(),
|
||||
notifications=CeleryEmailRegistrationNotificationGateway(),
|
||||
send_limits=RateLimiterEmailRegistrationSendLimiter(
|
||||
rate_limiter=RateLimiter(
|
||||
prefix="email_register_rate_limit",
|
||||
max_attempts=1,
|
||||
time_window=60,
|
||||
redis_client=redis,
|
||||
)
|
||||
),
|
||||
security=RedisEmailRegistrationSecurityGateway(
|
||||
redis=redis,
|
||||
login_security=RedisConsoleAuthSecurityGateway(redis=redis),
|
||||
verification_failure_limit=5,
|
||||
verification_lockout_duration=dify_config.EMAIL_REGISTER_LOCKOUT_DURATION,
|
||||
),
|
||||
account_policy=BillingAccountRegistrationPolicyGateway(
|
||||
enabled=deployment_edition == DeploymentEdition.CLOUD,
|
||||
),
|
||||
registration=AccountLifecycleRegistrationGateway(accounts=lifecycle),
|
||||
),
|
||||
deletion=AccountDeletionService(
|
||||
accounts=accounts,
|
||||
memberships=workspace_repository,
|
||||
verification=TokenManagerAccountDeletionVerificationGateway(),
|
||||
notifications=CeleryAccountDeletionVerificationNotifier(redis=redis),
|
||||
synchronization=EnterpriseAccountDeletionSyncGateway(),
|
||||
scheduler=CeleryAccountDeletionScheduler(),
|
||||
),
|
||||
deletion_feedback=AccountDeletionFeedbackService(
|
||||
feedback=BillingAccountDeletionFeedbackGateway(),
|
||||
),
|
||||
education=AccountEducationService(
|
||||
accounts=accounts,
|
||||
education=BillingAccountEducationGateway(),
|
||||
verification_rate_limiter=RateLimiter(
|
||||
prefix="edu_verification_rate_limit",
|
||||
max_attempts=10,
|
||||
time_window=60,
|
||||
redis_client=redis,
|
||||
),
|
||||
activation_rate_limiter=RateLimiter(
|
||||
prefix="edu_activation_rate_limit",
|
||||
max_attempts=10,
|
||||
time_window=60,
|
||||
redis_client=redis,
|
||||
),
|
||||
),
|
||||
forgot_password=AccountForgotPasswordService(
|
||||
accounts=accounts,
|
||||
passwords=passwords,
|
||||
tokens=RedisForgotPasswordTokenGateway(
|
||||
redis=redis,
|
||||
expiry_seconds=dify_config.RESET_PASSWORD_TOKEN_EXPIRY_MINUTES * 60,
|
||||
),
|
||||
codes=SecureForgotPasswordCodeGenerator(),
|
||||
notifications=CeleryForgotPasswordNotificationGateway(),
|
||||
send_limits=RateLimiterForgotPasswordSendLimiter(redis=redis),
|
||||
security=RedisForgotPasswordSecurityGateway(
|
||||
redis=redis,
|
||||
email_send_ip_limit_per_minute=dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE,
|
||||
verification_lockout_duration=dify_config.FORGOT_PASSWORD_LOCKOUT_DURATION,
|
||||
),
|
||||
registration=SystemFeatureServiceForgotPasswordRegistrationPolicy(),
|
||||
),
|
||||
initialization=AccountInitializationService(
|
||||
accounts=accounts,
|
||||
invitation_required=deployment_edition == DeploymentEdition.CLOUD,
|
||||
now=naive_utc_now,
|
||||
),
|
||||
integrations=AccountIntegrationService(integrations=integrations),
|
||||
oauth=_build_account_oauth_service(
|
||||
deployment_edition=deployment_edition,
|
||||
redis=redis,
|
||||
accounts=accounts,
|
||||
integrations=integrations,
|
||||
memberships=workspace_repository,
|
||||
lifecycle=lifecycle,
|
||||
workspace_provisioning=workspace_provisioning,
|
||||
invitation_tokens=invitation_tokens,
|
||||
activation_accounts=activation_accounts,
|
||||
),
|
||||
password=AccountPasswordService(
|
||||
accounts=accounts,
|
||||
passwords=passwords,
|
||||
),
|
||||
profile=AccountProfileService(accounts=accounts),
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Composition of the Agent App console use cases."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from configs import dify_config
|
||||
from repositories.app.agent_app_repository import AgentAppRepository
|
||||
from repositories.app.agent_sandbox_repository import AgentSandboxRepository
|
||||
from services.app.agent_app_feature_gateway import AgentAppFeatureValidator
|
||||
from services.app.agent_app_sandbox_service import AgentAppSandboxService
|
||||
from services.app.agent_app_service import AgentAppAccessService, AgentAppFeatureConfigService
|
||||
from services.app.agent_sandbox_file_gateway import AgentSandboxFileGateway, create_sandbox_client
|
||||
from services.file_request_service import FileRequestService
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AgentAppServices:
|
||||
access: AgentAppAccessService
|
||||
features: AgentAppFeatureConfigService
|
||||
sandbox: AgentAppSandboxService
|
||||
|
||||
|
||||
def build_agent_app_services(*, database_client: sessionmaker[Session]) -> AgentAppServices:
|
||||
apps = AgentAppRepository(session_factory=database_client)
|
||||
return AgentAppServices(
|
||||
access=AgentAppAccessService(references=apps),
|
||||
features=AgentAppFeatureConfigService(features=apps, validator=AgentAppFeatureValidator()),
|
||||
sandbox=AgentAppSandboxService(
|
||||
bindings=AgentSandboxRepository(session_factory=database_client, apps=apps),
|
||||
files=AgentSandboxFileGateway(
|
||||
client_factory=create_sandbox_client,
|
||||
file_requests=FileRequestService(),
|
||||
files_url=dify_config.FILES_URL,
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Composition of App use cases."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from configs import dify_config
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from repositories.account.repository import SQLAlchemyAccountRepository
|
||||
from repositories.app.api_key_repository import AppApiKeyRepository
|
||||
from repositories.app.console_repository import ConsoleAppRepository
|
||||
from repositories.app.dsl_import_repository import DslImportRepository
|
||||
from repositories.app.enterprise_app_repository import EnterpriseAppRepository
|
||||
from repositories.app.export_repository import AppExportRepository
|
||||
from repositories.factory import DifyAPIRepositoryFactory
|
||||
from repositories.trigger.app_repository import SQLAlchemyAppTriggerRepository
|
||||
from repositories.workspace.workspace_repository import WorkspaceRepository
|
||||
from services.agent.roster_package_exporter import RosterAgentPackageExporter
|
||||
from services.agent.roster_package_importer import RosterAgentPackageImporter
|
||||
from services.api_token_service import ApiTokenCache
|
||||
from services.app.api_key_service import AppApiKeyService
|
||||
from services.app.console_gateway import AppLifecycleGateway, AppTransferGateway, EnterpriseConsoleAppAccess
|
||||
from services.app.console_service import ConsoleAppService
|
||||
from services.app.creators_platform_gateway import CreatorsPlatformGateway
|
||||
from services.app.discovery_gateway import EnterpriseAppDiscoveryAccess
|
||||
from services.app.enterprise_app_service import EnterpriseAppService
|
||||
from services.app.export_service import AppExportService
|
||||
from services.app.import_service import AppImportService
|
||||
from services.app.query_service import AppDiscoveryService
|
||||
from services.app_dsl_service import AppDslService
|
||||
from services.app_package_service import AppPackageService
|
||||
from services.app_tracing_config_service import AppTracingConfigService
|
||||
from services.oauth_server_service import OAuthServerService
|
||||
from services.rbac.members import MemberService
|
||||
from services.recommended_app_package_service import RecommendedAppPackageService
|
||||
from services.trigger.app_trigger_store import AppTriggerStore
|
||||
from services.workflow.dsl_import import DslImportService
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AppServices:
|
||||
imports: AppImportService
|
||||
exports: AppExportService
|
||||
dsl_imports: DslImportService
|
||||
discovery: AppDiscoveryService
|
||||
console: ConsoleAppService
|
||||
enterprise: EnterpriseAppService
|
||||
triggers: AppTriggerStore
|
||||
|
||||
|
||||
def build_app_services(
|
||||
*,
|
||||
database_client: sessionmaker[Session],
|
||||
oauth: OAuthServerService,
|
||||
recommended_packages: RecommendedAppPackageService,
|
||||
repository: ConsoleAppRepository,
|
||||
rbac_members: MemberService,
|
||||
tracing_configs: AppTracingConfigService,
|
||||
) -> AppServices:
|
||||
transfers = AppTransferGateway(
|
||||
session_factory=database_client,
|
||||
dsl_factory=AppDslService,
|
||||
packages=AppPackageService(),
|
||||
agent_packages=RosterAgentPackageExporter(),
|
||||
agent_importer=RosterAgentPackageImporter(),
|
||||
recommended_packages=recommended_packages,
|
||||
)
|
||||
return AppServices(
|
||||
imports=AppImportService(accounts=SQLAlchemyAccountRepository(database_client), definitions=transfers),
|
||||
exports=AppExportService(
|
||||
apps=AppExportRepository(session_factory=database_client), serialize=AppDslService.serialize_export_data
|
||||
),
|
||||
dsl_imports=DslImportService(store=DslImportRepository(session_factory=database_client)),
|
||||
discovery=AppDiscoveryService(
|
||||
apps=repository,
|
||||
workspaces=WorkspaceRepository(database_client),
|
||||
access=EnterpriseAppDiscoveryAccess(),
|
||||
),
|
||||
console=ConsoleAppService(
|
||||
apps=repository,
|
||||
access=EnterpriseConsoleAppAccess(members=rbac_members),
|
||||
transfers=transfers,
|
||||
creators=CreatorsPlatformGateway(oauth=oauth),
|
||||
tracing=tracing_configs,
|
||||
lifecycle=AppLifecycleGateway(session_factory=database_client),
|
||||
),
|
||||
enterprise=EnterpriseAppService(
|
||||
apps=EnterpriseAppRepository(
|
||||
session_factory=database_client,
|
||||
app_web_url=dify_config.APP_WEB_URL,
|
||||
service_api_url=dify_config.SERVICE_API_URL,
|
||||
),
|
||||
workflow_runs=DifyAPIRepositoryFactory.create_api_workflow_run_repository(session_maker=database_client),
|
||||
now=naive_utc_now,
|
||||
),
|
||||
triggers=SQLAlchemyAppTriggerRepository(session_factory=database_client),
|
||||
)
|
||||
|
||||
|
||||
def build_app_api_key_service(*, database_client: sessionmaker[Session]) -> AppApiKeyService:
|
||||
return AppApiKeyService(
|
||||
keys=AppApiKeyRepository(session_factory=database_client),
|
||||
cache=ApiTokenCache,
|
||||
)
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Composition root for data-source services and shared credential gateways."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from configs import dify_config
|
||||
from core.datasource.datasource_manager import DatasourceManager
|
||||
from core.helper.ssrf_proxy import ssrf_proxy
|
||||
from core.plugin.impl.datasource import PluginDatasourceManager
|
||||
from core.plugin.impl.oauth import OAuthHandler
|
||||
from extensions.ext_redis import redis_client
|
||||
from repositories.data_source.api_key_auth_repository import SQLAlchemyDataSourceApiKeyAuthBindingRepository
|
||||
from repositories.data_source.credential_repository import SQLAlchemyDatasourceCredentialRepository
|
||||
from repositories.data_source.oauth_binding_repository import SQLAlchemyDataSourceOAuthBindingRepository
|
||||
from repositories.knowledge.dataset_repository import SQLAlchemyDatasetRepository
|
||||
from repositories.knowledge.document_repository import SQLAlchemyDocumentRepository
|
||||
from services.credentials.redis_refresh_lock import RedisCredentialRefreshLock
|
||||
from services.data_source.auth.api_key_gateways import (
|
||||
ProviderApiKeyAuthCredentialValidator,
|
||||
TenantApiKeyAuthCredentialEncryptor,
|
||||
)
|
||||
from services.data_source.auth.api_key_service import DataSourceApiKeyAuthService
|
||||
from services.data_source.binding_application_service import DataSourceBindingApplicationService
|
||||
from services.data_source.credential_adapters import (
|
||||
OAuthDatasourceCredentialRefresher,
|
||||
PluginDatasourceCredentialCodec,
|
||||
PluginDatasourceOAuthClientResolver,
|
||||
)
|
||||
from services.data_source.credential_gateway import (
|
||||
ActorAwareDatasourceCredentialGateway,
|
||||
TrustedStoredDatasourceCredentialGateway,
|
||||
)
|
||||
from services.data_source.notion_import_adapters import PluginNotionSourceGateway
|
||||
from services.data_source.notion_import_application_service import NotionImportApplicationService
|
||||
from services.data_source.notion_oauth_gateway import NotionDataSourceGateway
|
||||
from services.data_source.oauth_service import DataSourceOAuthService, InvalidDataSourceOAuthProviderError
|
||||
from services.data_source.provider_service import DatasourceProviderService
|
||||
from services.data_source.website_service import WebsiteService
|
||||
from services.knowledge.dataset_access import DatasetAccessService
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DataSourceServices:
|
||||
providers: DatasourceProviderService
|
||||
api_key_auth: DataSourceApiKeyAuthService
|
||||
oauth: Mapping[str, DataSourceOAuthService]
|
||||
bindings: DataSourceBindingApplicationService
|
||||
notion_imports: NotionImportApplicationService
|
||||
|
||||
def resolve_oauth(self, provider: str) -> DataSourceOAuthService:
|
||||
service = self.oauth.get(provider)
|
||||
if service is None:
|
||||
raise InvalidDataSourceOAuthProviderError("Invalid provider")
|
||||
return service
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DataSourceCredentials:
|
||||
providers: DatasourceProviderService
|
||||
actor: ActorAwareDatasourceCredentialGateway
|
||||
stored: TrustedStoredDatasourceCredentialGateway
|
||||
|
||||
|
||||
def build_data_source_credentials(*, database_client: sessionmaker[Session]) -> DataSourceCredentials:
|
||||
credentials = SQLAlchemyDatasourceCredentialRepository(session_factory=database_client)
|
||||
provider_manager = PluginDatasourceManager()
|
||||
codec = PluginDatasourceCredentialCodec(provider_manager=provider_manager)
|
||||
refresher = OAuthDatasourceCredentialRefresher(
|
||||
oauth_clients=PluginDatasourceOAuthClientResolver(configs=credentials, provider_manager=provider_manager),
|
||||
oauth_handler=OAuthHandler(),
|
||||
)
|
||||
refresh_lock = RedisCredentialRefreshLock(client=redis_client)
|
||||
return DataSourceCredentials(
|
||||
providers=DatasourceProviderService(
|
||||
credentials=credentials,
|
||||
codec=codec,
|
||||
refresher=refresher,
|
||||
refresh_lock=refresh_lock,
|
||||
provider_manager=provider_manager,
|
||||
),
|
||||
actor=ActorAwareDatasourceCredentialGateway(
|
||||
credentials=credentials, codec=codec, refresher=refresher, refresh_lock=refresh_lock
|
||||
),
|
||||
stored=TrustedStoredDatasourceCredentialGateway(
|
||||
credentials=credentials, codec=codec, refresher=refresher, refresh_lock=refresh_lock
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def build_data_source_services(
|
||||
*,
|
||||
database_client: sessionmaker[Session],
|
||||
dataset_access: DatasetAccessService,
|
||||
datasets: SQLAlchemyDatasetRepository,
|
||||
documents: SQLAlchemyDocumentRepository,
|
||||
actor_credentials: ActorAwareDatasourceCredentialGateway,
|
||||
providers: DatasourceProviderService,
|
||||
) -> DataSourceServices:
|
||||
oauth_bindings = SQLAlchemyDataSourceOAuthBindingRepository(session_factory=database_client)
|
||||
notion_gateway = NotionDataSourceGateway(
|
||||
client_id=dify_config.NOTION_CLIENT_ID or "",
|
||||
client_secret=dify_config.NOTION_CLIENT_SECRET or "",
|
||||
redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/data-source/callback/notion",
|
||||
http_client=ssrf_proxy,
|
||||
)
|
||||
return DataSourceServices(
|
||||
providers=providers,
|
||||
api_key_auth=DataSourceApiKeyAuthService(
|
||||
bindings=SQLAlchemyDataSourceApiKeyAuthBindingRepository(session_factory=database_client),
|
||||
validator=ProviderApiKeyAuthCredentialValidator(),
|
||||
encryptor=TenantApiKeyAuthCredentialEncryptor(),
|
||||
),
|
||||
oauth={
|
||||
"notion": DataSourceOAuthService(
|
||||
provider_name="notion",
|
||||
provider_gateway=notion_gateway,
|
||||
bindings=oauth_bindings,
|
||||
is_internal_provider=dify_config.NOTION_INTEGRATION_TYPE == "internal",
|
||||
internal_access_token=dify_config.NOTION_INTERNAL_SECRET,
|
||||
)
|
||||
},
|
||||
bindings=DataSourceBindingApplicationService(bindings=oauth_bindings),
|
||||
notion_imports=NotionImportApplicationService(
|
||||
dataset_access=dataset_access,
|
||||
datasets=datasets,
|
||||
documents=documents,
|
||||
source=PluginNotionSourceGateway(
|
||||
credentials=actor_credentials, runtime_loader=DatasourceManager.get_datasource_runtime
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def build_website_service(*, database_client: sessionmaker[Session]) -> WebsiteService:
|
||||
return WebsiteService(providers=build_data_source_credentials(database_client=database_client).providers)
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Shared dataset dependencies for knowledge and data-source use cases."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from configs import dify_config
|
||||
from repositories.knowledge.dataset_repository import SQLAlchemyDatasetRepository
|
||||
from repositories.knowledge.document_repository import SQLAlchemyDocumentRepository
|
||||
from services.knowledge.dataset_access import DatasetAccessService, WorkspaceRoleReader
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DatasetDependencies:
|
||||
datasets: SQLAlchemyDatasetRepository
|
||||
documents: SQLAlchemyDocumentRepository
|
||||
access: DatasetAccessService
|
||||
|
||||
|
||||
def build_dataset_dependencies(
|
||||
*, database_client: sessionmaker[Session], workspace_roles: WorkspaceRoleReader
|
||||
) -> DatasetDependencies:
|
||||
datasets = SQLAlchemyDatasetRepository(session_factory=database_client)
|
||||
return DatasetDependencies(
|
||||
datasets=datasets,
|
||||
documents=SQLAlchemyDocumentRepository(session_factory=database_client),
|
||||
access=DatasetAccessService(
|
||||
datasets=datasets,
|
||||
workspace_roles=workspace_roles,
|
||||
legacy_permissions_enabled=not dify_config.RBAC_ENABLED,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Composition of Installed App use cases."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from repositories.installed_app_repository import SQLAlchemyInstalledAppRepository
|
||||
from services.conversation_command_service import ConversationCommandService
|
||||
from services.conversation_name_service import ConversationNameService
|
||||
from services.conversation_query_service import ConversationQueryService
|
||||
from services.installed_app_access_service import InstalledAppAccessService
|
||||
from services.installed_app_conversation_service import InstalledAppConversationService
|
||||
from services.installed_app_generation_adapters import AppGenerateServiceRuntime
|
||||
from services.installed_app_generation_service import InstalledAppGenerationService
|
||||
from services.installed_app_service import InstalledAppService, WorkspaceRoleLookup
|
||||
from services.webapp_access_query_service import WebAppAccessQueryService
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class InstalledAppServices:
|
||||
access: InstalledAppAccessService
|
||||
management: InstalledAppService
|
||||
generation: InstalledAppGenerationService
|
||||
conversations: InstalledAppConversationService
|
||||
|
||||
|
||||
def build_installed_app_services(
|
||||
*,
|
||||
database_client: sessionmaker[Session],
|
||||
conversation_queries: ConversationQueryService,
|
||||
conversation_names: ConversationNameService,
|
||||
conversation_commands: ConversationCommandService,
|
||||
webapp_access: WebAppAccessQueryService,
|
||||
get_workspace_role: WorkspaceRoleLookup,
|
||||
webapp_auth_enabled: bool,
|
||||
) -> InstalledAppServices:
|
||||
installed_apps = SQLAlchemyInstalledAppRepository(session_factory=database_client)
|
||||
access = InstalledAppAccessService(
|
||||
installed_apps=installed_apps,
|
||||
is_user_allowed=webapp_access.is_user_allowed,
|
||||
get_access_modes=webapp_access.batch_get_access_modes,
|
||||
get_user_permissions=webapp_access.batch_get_user_permissions,
|
||||
)
|
||||
return InstalledAppServices(
|
||||
access=access,
|
||||
management=InstalledAppService(
|
||||
installed_apps=installed_apps,
|
||||
get_workspace_role=get_workspace_role,
|
||||
get_visible_app_ids=access.get_visible_app_ids if webapp_auth_enabled else None,
|
||||
),
|
||||
generation=InstalledAppGenerationService(
|
||||
usage=installed_apps,
|
||||
runtime=AppGenerateServiceRuntime(session_factory=database_client),
|
||||
),
|
||||
conversations=InstalledAppConversationService(
|
||||
queries=conversation_queries,
|
||||
names=conversation_names,
|
||||
commands=conversation_commands,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Composition root for dataset-controller application services."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from configs import dify_config
|
||||
from core.app.apps.pipeline.pipeline_generator import PipelineGenerator
|
||||
from core.rag.extractor.entity.datasource_type import DatasourceType
|
||||
from libs.helper import generate_text_hash
|
||||
from repositories.app.console_repository import ConsoleAppRepository
|
||||
from repositories.knowledge.dataset_api_key_repository import DatasetApiKeyRepository
|
||||
from repositories.knowledge.dataset_repository import SQLAlchemyDatasetRepository
|
||||
from repositories.knowledge.document_repository import SQLAlchemyDocumentRepository
|
||||
from repositories.knowledge.metadata_repository import SQLAlchemyMetadataRepository
|
||||
from repositories.knowledge.segment_repository import SQLAlchemySegmentRepository
|
||||
from repositories.knowledge.upload_file_repository import SQLAlchemyKnowledgeUploadRepository
|
||||
from services.api_token_service import ApiTokenCache, get_effective_token_last_used_at
|
||||
from services.data_source.credential_gateway import (
|
||||
ActorAwareDatasourceCredentialGateway,
|
||||
TrustedStoredDatasourceCredentialGateway,
|
||||
)
|
||||
from services.data_source.provider_service import DatasourceProviderService
|
||||
from services.knowledge.api_key_service import DatasetApiKeyService
|
||||
from services.knowledge.dataset_access import DatasetAccessService
|
||||
from services.knowledge.dataset_service import DocumentService
|
||||
from services.knowledge.datasets.adapters import SQLAlchemyDatasetOperations
|
||||
from services.knowledge.datasets.application import DatasetApplicationService
|
||||
from services.knowledge.datasets.upgrades import KnowledgeUpgradeApplicationService
|
||||
from services.knowledge.document_sync import DocumentSyncApplicationService
|
||||
from services.knowledge.document_sync_adapters import CeleryDocumentSyncDispatcher
|
||||
from services.knowledge.documents.adapters import SQLAlchemyDocumentOperations
|
||||
from services.knowledge.documents.application import DatasetDocumentApplicationService
|
||||
from services.knowledge.external.adapters import SQLAlchemyExternalKnowledgeOperations
|
||||
from services.knowledge.external.application import ExternalKnowledgeApplicationService
|
||||
from services.knowledge.indexing.adapters.estimate import IndexingEstimateAdapter, SQLAlchemyProcessRuleReader
|
||||
from services.knowledge.indexing.adapters.sources import (
|
||||
CompositeStoredSourceResolver,
|
||||
FileSourceAdapter,
|
||||
NotionSourceResolver,
|
||||
WebsiteSourceAdapter,
|
||||
)
|
||||
from services.knowledge.indexing.estimate import IndexingEstimateApplicationService
|
||||
from services.knowledge.metadata.application import MetadataService
|
||||
from services.knowledge.segments.adapters import (
|
||||
CelerySegmentBatchImportDispatcher,
|
||||
ModelManagerSegmentGuard,
|
||||
RedisSegmentClient,
|
||||
RedisSegmentIndexingState,
|
||||
)
|
||||
from services.knowledge.segments.application import DatasetSegmentApplicationService
|
||||
from services.knowledge.segments.indexing import SegmentIndexingGateway
|
||||
from services.knowledge_fs.feature_service import get_knowledge_fs_features
|
||||
from services.rbac.members import MemberService
|
||||
from services.tag_application_service import TagTargetQuery
|
||||
from services.workflow_run_agg import WorkflowRunAgg
|
||||
from tasks.batch_create_segment_to_index_task import batch_create_segment_to_index_task
|
||||
from tasks.delete_segment_from_index_task import delete_segment_from_index_task
|
||||
from tasks.disable_segments_from_index_task import disable_segments_from_index_task
|
||||
from tasks.document_indexing_sync_task import document_indexing_sync_task
|
||||
from tasks.enable_segments_to_index_task import enable_segments_to_index_task
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class KnowledgeServices:
|
||||
metadata: MetadataService
|
||||
datasets: DatasetApplicationService
|
||||
external: ExternalKnowledgeApplicationService
|
||||
documents: DatasetDocumentApplicationService
|
||||
document_sync: DocumentSyncApplicationService
|
||||
indexing_estimates: IndexingEstimateApplicationService
|
||||
segments: DatasetSegmentApplicationService
|
||||
pipeline_generator: PipelineGenerator
|
||||
upgrades: KnowledgeUpgradeApplicationService
|
||||
|
||||
|
||||
def build_dataset_api_key_service(
|
||||
*, database_client: sessionmaker[Session], dataset_access: DatasetAccessService
|
||||
) -> DatasetApiKeyService:
|
||||
return DatasetApiKeyService(
|
||||
keys=DatasetApiKeyRepository(session_factory=database_client),
|
||||
cache=ApiTokenCache,
|
||||
access=dataset_access,
|
||||
last_used_at=get_effective_token_last_used_at,
|
||||
rbac_enabled=lambda: dify_config.RBAC_ENABLED,
|
||||
)
|
||||
|
||||
|
||||
def build_knowledge_services(
|
||||
*,
|
||||
database_client: sessionmaker[Session],
|
||||
dataset_access: DatasetAccessService,
|
||||
datasets: SQLAlchemyDatasetRepository,
|
||||
documents: SQLAlchemyDocumentRepository,
|
||||
actor_credentials: ActorAwareDatasourceCredentialGateway,
|
||||
stored_credentials: TrustedStoredDatasourceCredentialGateway,
|
||||
providers: DatasourceProviderService,
|
||||
redis: RedisSegmentClient,
|
||||
tags: TagTargetQuery,
|
||||
rbac_members: MemberService,
|
||||
) -> KnowledgeServices:
|
||||
"""Build the dataset-controller knowledge use cases."""
|
||||
|
||||
uploads = SQLAlchemyKnowledgeUploadRepository(session_factory=database_client)
|
||||
notion_sources = NotionSourceResolver(
|
||||
actor_credentials=actor_credentials,
|
||||
stored_credentials=stored_credentials,
|
||||
)
|
||||
file_sources = FileSourceAdapter(uploads=uploads)
|
||||
website_sources = WebsiteSourceAdapter()
|
||||
stored_sources = CompositeStoredSourceResolver(
|
||||
adapters={
|
||||
DatasourceType.FILE.value: file_sources,
|
||||
DatasourceType.NOTION.value: notion_sources,
|
||||
DatasourceType.WEBSITE.value: website_sources,
|
||||
}
|
||||
)
|
||||
segments = SQLAlchemySegmentRepository(session_factory=database_client)
|
||||
segment_index = SegmentIndexingGateway(
|
||||
segments=segments,
|
||||
uploads=uploads,
|
||||
redis=redis,
|
||||
new_session=database_client,
|
||||
delete_task=delete_segment_from_index_task.delay,
|
||||
enable_task=enable_segments_to_index_task.delay,
|
||||
disable_task=disable_segments_from_index_task.delay,
|
||||
)
|
||||
dataset_operations = SQLAlchemyDatasetOperations(
|
||||
session_factory=database_client,
|
||||
tags=tags,
|
||||
app_queries=ConsoleAppRepository(session_factory=database_client),
|
||||
members=rbac_members,
|
||||
)
|
||||
return KnowledgeServices(
|
||||
metadata=MetadataService(
|
||||
store=SQLAlchemyMetadataRepository(session_factory=database_client), dataset_access=dataset_access
|
||||
),
|
||||
datasets=DatasetApplicationService(
|
||||
dataset_access=dataset_access,
|
||||
operations=dataset_operations,
|
||||
rbac_enabled=dify_config.RBAC_ENABLED,
|
||||
service_api_url=dify_config.SERVICE_API_URL,
|
||||
vector_store=dify_config.VECTOR_STORE,
|
||||
tidb_fulltext=dify_config.TIDB_VECTOR_ENABLE_FULLTEXT_SEARCH,
|
||||
),
|
||||
external=ExternalKnowledgeApplicationService(
|
||||
dataset_access=dataset_access,
|
||||
operations=SQLAlchemyExternalKnowledgeOperations(session_factory=database_client, members=rbac_members),
|
||||
),
|
||||
documents=DatasetDocumentApplicationService(
|
||||
dataset_access=dataset_access,
|
||||
operations=SQLAlchemyDocumentOperations(session_factory=database_client),
|
||||
metadata_schema=DocumentService.DOCUMENT_METADATA_SCHEMA,
|
||||
),
|
||||
pipeline_generator=PipelineGenerator(
|
||||
execution_driver=WorkflowRunAgg.run, documents=documents, datasource_providers=providers
|
||||
),
|
||||
upgrades=KnowledgeUpgradeApplicationService(
|
||||
session_factory=database_client,
|
||||
dataset_access=dataset_access,
|
||||
datasets=dataset_operations,
|
||||
rbac_enabled=dify_config.RBAC_ENABLED,
|
||||
feature_enabled=lambda: get_knowledge_fs_features().enabled,
|
||||
),
|
||||
document_sync=DocumentSyncApplicationService(
|
||||
dataset_access=dataset_access,
|
||||
documents=documents,
|
||||
dispatcher=CeleryDocumentSyncDispatcher(delay=document_indexing_sync_task.delay),
|
||||
),
|
||||
indexing_estimates=IndexingEstimateApplicationService(
|
||||
dataset_access=dataset_access,
|
||||
datasets=datasets,
|
||||
documents=documents,
|
||||
files=file_sources,
|
||||
websites=website_sources,
|
||||
stored_sources=stored_sources,
|
||||
notion=notion_sources,
|
||||
process_rules=SQLAlchemyProcessRuleReader(session_factory=database_client),
|
||||
runner=IndexingEstimateAdapter(session_factory=database_client),
|
||||
),
|
||||
segments=DatasetSegmentApplicationService(
|
||||
dataset_access=dataset_access,
|
||||
scopes=datasets,
|
||||
store=segments,
|
||||
index=segment_index,
|
||||
limits=dify_config,
|
||||
text_hash=generate_text_hash,
|
||||
uploads=uploads,
|
||||
model_guard=ModelManagerSegmentGuard(),
|
||||
indexing_state=RedisSegmentIndexingState(redis),
|
||||
batch_dispatcher=CelerySegmentBatchImportDispatcher(delay=batch_create_segment_to_index_task.delay),
|
||||
job_id_factory=lambda: str(uuid4()),
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Compose RBAC use cases with the existing workspace, app and dataset repositories."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from repositories.app.console_repository import ConsoleAppRepository
|
||||
from repositories.knowledge.dataset_repository import SQLAlchemyDatasetRepository
|
||||
from repositories.workspace.workspace_repository import WorkspaceRepository
|
||||
from services.enterprise import rbac_service as enterprise
|
||||
from services.rbac.gateways import (
|
||||
CeleryAccessInitializer,
|
||||
DeploymentRBACSettings,
|
||||
EnterpriseResourceAccessClients,
|
||||
)
|
||||
from services.rbac.members import MemberService
|
||||
from services.rbac.policies import PolicyService
|
||||
from services.rbac.resource_queries import ResourceQueryService
|
||||
from services.rbac.resources import ResourceAccessService
|
||||
from services.rbac.roles import RoleService
|
||||
from services.workspace.member_service import WorkspaceMemberService
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RBACServices:
|
||||
roles: RoleService
|
||||
policies: PolicyService
|
||||
members: MemberService
|
||||
resources: ResourceAccessService
|
||||
queries: ResourceQueryService
|
||||
|
||||
|
||||
def build_rbac_services(
|
||||
*,
|
||||
workspaces: WorkspaceRepository,
|
||||
workspace_members: WorkspaceMemberService,
|
||||
apps: ConsoleAppRepository,
|
||||
datasets: SQLAlchemyDatasetRepository,
|
||||
) -> RBACServices:
|
||||
settings = DeploymentRBACSettings()
|
||||
return RBACServices(
|
||||
queries=ResourceQueryService(apps=apps, datasets=datasets),
|
||||
roles=RoleService(
|
||||
roles=enterprise.RBACService.KnowledgeFSRoles, catalog=enterprise.RBACService.Catalog, settings=settings
|
||||
),
|
||||
policies=PolicyService(
|
||||
policies=enterprise.RBACService.AccessPolicies, bindings=enterprise.RBACService.AccessPolicyBindings
|
||||
),
|
||||
members=MemberService(
|
||||
members=workspaces,
|
||||
workspace_roles=workspace_members,
|
||||
roles=enterprise.RBACService.KnowledgeFSMemberRoles,
|
||||
permissions=enterprise.RBACService.MyPermissions,
|
||||
apps=enterprise.RBACService.AppPermissions,
|
||||
datasets=enterprise.RBACService.DatasetPermissions,
|
||||
settings=settings,
|
||||
),
|
||||
resources=ResourceAccessService(
|
||||
clients=EnterpriseResourceAccessClients(
|
||||
apps=enterprise._APP_ACCESS,
|
||||
datasets=enterprise._DATASET_ACCESS,
|
||||
agents=enterprise._AGENT_ACCESS,
|
||||
workspace_apps=enterprise._WORKSPACE_APP_ACCESS,
|
||||
workspace_datasets=enterprise._WORKSPACE_DATASET_ACCESS,
|
||||
workspace_agents=enterprise._WORKSPACE_AGENT_ACCESS,
|
||||
catalogs=enterprise.RBACService.Catalog,
|
||||
),
|
||||
members=workspaces,
|
||||
apps=apps,
|
||||
datasets=datasets,
|
||||
initializer=CeleryAccessInitializer(),
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Compose the resource access token service at the application boundary."""
|
||||
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from repositories.resource_access_token_repository import (
|
||||
ResourceAccessTokenCleanupRepository,
|
||||
ResourceAccessTokenRepository,
|
||||
)
|
||||
from services.resource_access_token_service import ResourceAccessTokenCleanupService, ResourceAccessTokenService
|
||||
|
||||
|
||||
def build_resource_access_token_service(*, database_client: sessionmaker[Session]) -> ResourceAccessTokenService:
|
||||
return ResourceAccessTokenService(tokens=ResourceAccessTokenRepository(session_factory=database_client))
|
||||
|
||||
|
||||
def build_resource_access_token_cleanup_service(*, session: Session) -> ResourceAccessTokenCleanupService:
|
||||
"""Bind cleanup to an existing transaction without taking ownership of its lifetime."""
|
||||
return ResourceAccessTokenCleanupService(tokens=ResourceAccessTokenCleanupRepository(session=session))
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Compose provider-scoped tool credential resolution for workflow execution."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
|
||||
from configs import dify_config
|
||||
from core.db.session_factory import get_session_maker
|
||||
from core.plugin.entities.plugin_daemon import CredentialType
|
||||
from core.tools.builtin_tool.provider import BuiltinToolProviderController
|
||||
from core.tools.plugin_tool.provider import PluginToolProviderController
|
||||
from extensions.ext_redis import redis_client
|
||||
from models.provider_ids import ToolProviderID
|
||||
from repositories.credentials.query_repository import CredentialQueryRepository
|
||||
from services.credentials.redis_refresh_lock import RedisCredentialRefreshLock
|
||||
from services.credentials.tool_runtime import ToolCredentialService
|
||||
from services.credentials.tool_runtime_adapters import ProviderToolCredentialRuntime
|
||||
|
||||
|
||||
def resolve_tool_credentials(
|
||||
*, controller: BuiltinToolProviderController, provider_id: str, workspace_id: str, credential_id: str | None
|
||||
) -> tuple[Mapping[str, object], CredentialType]:
|
||||
if isinstance(controller, PluginToolProviderController):
|
||||
provider = ToolProviderID(provider_id)
|
||||
providers = (str(provider), provider.provider_name)
|
||||
else:
|
||||
providers = (provider_id,)
|
||||
runtime = ProviderToolCredentialRuntime(
|
||||
controller=controller, provider_id=provider_id, console_api_url=dify_config.CONSOLE_API_URL
|
||||
)
|
||||
service = ToolCredentialService(
|
||||
credentials=CredentialQueryRepository(session_factory=get_session_maker()),
|
||||
runtime=runtime,
|
||||
refresh_lock=RedisCredentialRefreshLock(client=redis_client),
|
||||
providers=providers,
|
||||
)
|
||||
return runtime.resolve(service=service, workspace_id=workspace_id, credential_id=credential_id)
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Composition of the trace pipeline, Agent trace collection, and tracing provider configurations."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from configs import dify_config
|
||||
from enterprise.telemetry.exporter import is_enterprise_telemetry_enabled
|
||||
from repositories.app.tracing_config_repository import SQLAlchemyAppTracingConfigRepository
|
||||
from repositories.application_trace_repository import ApplicationTraceRepository
|
||||
from repositories.factory import DifyAPIRepositoryFactory
|
||||
from repositories.trace_record_repository import TraceRecordRepository
|
||||
from services.tracing.adapters import (
|
||||
CeleryExportRetryQueue,
|
||||
CeleryTraceEmitter,
|
||||
WorkspaceTracingSecretCipher,
|
||||
schedule_agent_trace_export,
|
||||
send_to_enterprise_telemetry,
|
||||
)
|
||||
from services.tracing.canonical import CanonicalTraceBuilder
|
||||
from services.tracing.collection import AgentTraceSettings
|
||||
from services.tracing.delivery import TraceDeliveryService
|
||||
from services.tracing.egress import SSRFEgress
|
||||
from services.tracing.provider_configs import ProviderConfigGateway, TraceProviderCapabilitiesQuery
|
||||
from services.tracing.providers import ProviderConfigCodec
|
||||
from services.tracing.registry import EntryPointTraceProviderCatalog
|
||||
from services.tracing.runtime_bridge import RuntimeApplicationTracingHooks
|
||||
from services.tracing.scopes import TraceScopes
|
||||
from services.tracing.service import ApplicationTracingService
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TracingServices:
|
||||
scopes: TraceScopes
|
||||
delivery: TraceDeliveryService
|
||||
agent_traces: ApplicationTracingService
|
||||
hooks: RuntimeApplicationTracingHooks | None
|
||||
"""``None`` when the deployment does not collect Agent traces."""
|
||||
provider_configs: ProviderConfigGateway
|
||||
provider_capabilities: TraceProviderCapabilitiesQuery
|
||||
|
||||
|
||||
def build_tracing_services(*, database_client: sessionmaker[Session]) -> TracingServices:
|
||||
egress = SSRFEgress()
|
||||
providers = EntryPointTraceProviderCatalog()
|
||||
codec = ProviderConfigCodec(WorkspaceTracingSecretCipher())
|
||||
builder = CanonicalTraceBuilder()
|
||||
configs = SQLAlchemyAppTracingConfigRepository(session_factory=database_client)
|
||||
enterprise_telemetry = is_enterprise_telemetry_enabled()
|
||||
workflow_runs = DifyAPIRepositoryFactory.create_api_workflow_run_repository(database_client)
|
||||
node_executions = DifyAPIRepositoryFactory.create_api_workflow_node_execution_repository(database_client)
|
||||
agent_settings = AgentTraceSettings(
|
||||
enabled=dify_config.OPS_AGENT_TRACE_ENABLED,
|
||||
max_spans=dify_config.OPS_AGENT_TRACE_MAX_SPANS,
|
||||
max_bytes=dify_config.OPS_AGENT_TRACE_MAX_BYTES,
|
||||
collection_timeout_seconds=dify_config.OPS_AGENT_TRACE_COLLECTION_TIMEOUT,
|
||||
export_lease_seconds=dify_config.OPS_AGENT_TRACE_EXPORT_LEASE_SECONDS,
|
||||
max_export_attempts=dify_config.OPS_AGENT_TRACE_MAX_ATTEMPTS,
|
||||
retention_days=dify_config.OPS_AGENT_TRACE_RETENTION_DAYS,
|
||||
)
|
||||
agent_trace_runs = ApplicationTraceRepository(database_client)
|
||||
agent_traces = ApplicationTracingService(
|
||||
runs=agent_trace_runs,
|
||||
run_query=agent_trace_runs,
|
||||
sources=agent_trace_runs,
|
||||
# App, workspace, and credential names are enterprise telemetry dimensions only.
|
||||
records=TraceRecordRepository(
|
||||
database_client,
|
||||
workflow_runs=workflow_runs,
|
||||
node_executions=node_executions,
|
||||
files_url=dify_config.FILES_URL,
|
||||
enterprise_details=False,
|
||||
),
|
||||
builder=builder,
|
||||
providers=providers,
|
||||
codec=codec,
|
||||
egress=egress,
|
||||
schedule_export=schedule_agent_trace_export,
|
||||
settings=agent_settings,
|
||||
)
|
||||
return TracingServices(
|
||||
scopes=TraceScopes(
|
||||
emitter=CeleryTraceEmitter(), policies=configs, enterprise_enabled=is_enterprise_telemetry_enabled
|
||||
),
|
||||
delivery=TraceDeliveryService(
|
||||
records=TraceRecordRepository(
|
||||
database_client,
|
||||
workflow_runs=workflow_runs,
|
||||
node_executions=node_executions,
|
||||
files_url=dify_config.FILES_URL,
|
||||
enterprise_details=enterprise_telemetry,
|
||||
),
|
||||
destinations=configs,
|
||||
providers=providers,
|
||||
codec=codec,
|
||||
builder=builder,
|
||||
egress=egress,
|
||||
retries=CeleryExportRetryQueue(),
|
||||
enterprise_sink=send_to_enterprise_telemetry if enterprise_telemetry else None,
|
||||
collector=agent_traces if agent_settings.enabled else None,
|
||||
max_export_attempts=dify_config.OPS_TRACE_EXPORT_MAX_ATTEMPTS,
|
||||
),
|
||||
agent_traces=agent_traces,
|
||||
hooks=RuntimeApplicationTracingHooks(agent_traces) if agent_settings.enabled else None,
|
||||
provider_configs=ProviderConfigGateway(providers=providers, codec=codec, egress=egress),
|
||||
provider_capabilities=TraceProviderCapabilitiesQuery(
|
||||
providers=providers, api_collection_enabled=agent_settings.enabled
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Composition of Trial App use cases."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from repositories.trial_app_repository import TrialAppRepository
|
||||
from services.trial_app_access_service import TrialAppAccessService
|
||||
from services.trial_app_generation_adapters import AppGenerateServiceRuntime
|
||||
from services.trial_app_generation_service import TrialAppGenerationService
|
||||
from services.trial_app_usage import TrialAppUsageRecorder
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TrialAppServices:
|
||||
access: TrialAppAccessService
|
||||
generation: TrialAppGenerationService
|
||||
usage: TrialAppUsageRecorder
|
||||
|
||||
|
||||
def build_trial_app_services(
|
||||
*, database_client: sessionmaker[Session], trial_apps: TrialAppRepository
|
||||
) -> TrialAppServices:
|
||||
return TrialAppServices(
|
||||
access=TrialAppAccessService(apps=trial_apps),
|
||||
generation=TrialAppGenerationService(
|
||||
runtime=AppGenerateServiceRuntime(session_factory=database_client), usage=trial_apps
|
||||
),
|
||||
usage=trial_apps,
|
||||
)
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Compose workspace use cases with the shared account and workspace repositories."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from extensions.ext_redis import RedisClientWrapper
|
||||
from repositories.account.repository import SQLAlchemyAccountRepository
|
||||
from repositories.app.console_repository import ConsoleAppRepository
|
||||
from repositories.knowledge.dataset_repository import SQLAlchemyDatasetRepository
|
||||
from repositories.workspace.resource_cleanup_repository import WorkspaceResourceCleanupRepository
|
||||
from repositories.workspace.workspace_repository import WorkspaceRepository
|
||||
from services.account.adapters import RedisInvitationTokenStore
|
||||
from services.file_service import FileService
|
||||
from services.workspace.gateways import (
|
||||
DeploymentWorkspaceCreationPolicy,
|
||||
DeploymentWorkspaceFeatureGateway,
|
||||
DeploymentWorkspaceMemberAccessGateway,
|
||||
DeploymentWorkspaceMemberRoleResolver,
|
||||
DeploymentWorkspacePlanGateway,
|
||||
WorkspaceFileGateway,
|
||||
WorkspaceIdentityGateway,
|
||||
WorkspaceInvitationGateway,
|
||||
WorkspaceOwnerTransferGateway,
|
||||
WorkspaceProvisioningEffectsGateway,
|
||||
)
|
||||
from services.workspace.member_service import (
|
||||
InvitedAccountRegistration,
|
||||
WorkspaceInvitationService,
|
||||
WorkspaceMemberQueryService,
|
||||
WorkspaceMemberService,
|
||||
WorkspaceOwnerTransferService,
|
||||
)
|
||||
from services.workspace.provisioning_service import WorkspaceProvisioningService
|
||||
from services.workspace.resource_cleanup_service import WorkspaceResourceCleanupService
|
||||
from services.workspace.service import WorkspaceQueryService, WorkspaceService
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class WorkspaceServices:
|
||||
queries: WorkspaceQueryService
|
||||
management: WorkspaceService
|
||||
provisioning: WorkspaceProvisioningService
|
||||
members: WorkspaceMemberService
|
||||
member_queries: WorkspaceMemberQueryService
|
||||
owner_transfer: WorkspaceOwnerTransferService
|
||||
invitations: WorkspaceInvitationService
|
||||
identity: WorkspaceIdentityGateway
|
||||
resource_cleanup: WorkspaceResourceCleanupService
|
||||
|
||||
|
||||
def build_workspace_membership_services(
|
||||
*,
|
||||
workspaces: WorkspaceRepository,
|
||||
accounts: SQLAlchemyAccountRepository,
|
||||
) -> tuple[WorkspaceMemberService, WorkspaceProvisioningService]:
|
||||
"""Build the workspace prerequisites shared by account registration and invitations."""
|
||||
members = WorkspaceMemberService(
|
||||
workspaces=workspaces,
|
||||
accounts=accounts,
|
||||
access=DeploymentWorkspaceMemberAccessGateway(),
|
||||
)
|
||||
provisioning = WorkspaceProvisioningService(
|
||||
owners=accounts,
|
||||
provisioning=workspaces,
|
||||
effects=WorkspaceProvisioningEffectsGateway(),
|
||||
policies=DeploymentWorkspaceCreationPolicy(),
|
||||
memberships=workspaces,
|
||||
members=members,
|
||||
)
|
||||
return members, provisioning
|
||||
|
||||
|
||||
def build_workspace_services(
|
||||
*,
|
||||
database_client: sessionmaker[Session],
|
||||
workspaces: WorkspaceRepository,
|
||||
accounts: SQLAlchemyAccountRepository,
|
||||
files: FileService,
|
||||
redis: RedisClientWrapper,
|
||||
members: WorkspaceMemberService,
|
||||
provisioning: WorkspaceProvisioningService,
|
||||
registration: InvitedAccountRegistration,
|
||||
invitation_tokens: RedisInvitationTokenStore,
|
||||
) -> WorkspaceServices:
|
||||
return WorkspaceServices(
|
||||
queries=WorkspaceQueryService(workspaces=workspaces, plans=DeploymentWorkspacePlanGateway()),
|
||||
management=WorkspaceService(
|
||||
workspaces=workspaces,
|
||||
features=DeploymentWorkspaceFeatureGateway(),
|
||||
logos=WorkspaceFileGateway(files=files),
|
||||
),
|
||||
provisioning=provisioning,
|
||||
members=members,
|
||||
member_queries=WorkspaceMemberQueryService(
|
||||
members=workspaces,
|
||||
roles=DeploymentWorkspaceMemberRoleResolver(),
|
||||
),
|
||||
owner_transfer=WorkspaceOwnerTransferService(
|
||||
accounts=accounts,
|
||||
workspaces=workspaces,
|
||||
members=members,
|
||||
challenges=WorkspaceOwnerTransferGateway(redis=redis),
|
||||
),
|
||||
invitations=WorkspaceInvitationService(
|
||||
accounts=registration,
|
||||
workspaces=workspaces,
|
||||
members=members,
|
||||
invitations=WorkspaceInvitationGateway(tokens=invitation_tokens, redis=redis),
|
||||
),
|
||||
identity=WorkspaceIdentityGateway(workspaces=workspaces),
|
||||
resource_cleanup=WorkspaceResourceCleanupService(
|
||||
session_factory=database_client,
|
||||
apps=ConsoleAppRepository(session_factory=database_client),
|
||||
datasets=SQLAlchemyDatasetRepository(session_factory=database_client),
|
||||
agent_resources=WorkspaceResourceCleanupRepository(session_factory=database_client),
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,70 @@
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
|
||||
from flask import Response
|
||||
|
||||
from configs import dify_config
|
||||
from controllers.console.admin import admin_required
|
||||
from dify_app import DifyApp
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
@app.after_request
|
||||
def after_request(response):
|
||||
"""Add Version headers to the response."""
|
||||
response.headers.add("X-Version", dify_config.project.version)
|
||||
response.headers.add("X-Env", dify_config.DEPLOY_ENV)
|
||||
return response
|
||||
|
||||
@app.route("/health")
|
||||
def health():
|
||||
return Response(
|
||||
json.dumps({"pid": os.getpid(), "status": "ok", "version": dify_config.project.version}),
|
||||
status=200,
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
@app.route("/threads")
|
||||
@admin_required
|
||||
def threads():
|
||||
num_threads = threading.active_count()
|
||||
threads = threading.enumerate()
|
||||
|
||||
thread_list = []
|
||||
for thread in threads:
|
||||
thread_name = thread.name
|
||||
thread_id = thread.ident
|
||||
is_alive = thread.is_alive()
|
||||
|
||||
thread_list.append(
|
||||
{
|
||||
"name": thread_name,
|
||||
"id": thread_id,
|
||||
"is_alive": is_alive,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"pid": os.getpid(),
|
||||
"thread_num": num_threads,
|
||||
"threads": thread_list,
|
||||
}
|
||||
|
||||
@app.route("/db-pool-stat")
|
||||
@admin_required
|
||||
def pool_stat():
|
||||
from extensions.ext_database import db
|
||||
|
||||
engine = db.engine
|
||||
# TODO: Fix the type error
|
||||
# FIXME maybe its sqlalchemy issue
|
||||
return {
|
||||
"pid": os.getpid(),
|
||||
"pool_size": engine.pool.size(), # type: ignore
|
||||
"checked_in_connections": engine.pool.checkedin(), # type: ignore
|
||||
"checked_out_connections": engine.pool.checkedout(), # type: ignore
|
||||
"overflow_connections": engine.pool.overflow(), # type: ignore
|
||||
"connection_timeout": engine.pool.timeout(), # type: ignore
|
||||
"recycle_time": db.engine.pool._recycle, # type: ignore
|
||||
}
|
||||
@@ -0,0 +1,897 @@
|
||||
"""Composition root for application services used by transport adapters."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from typing import cast
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
from flask import Flask, current_app
|
||||
from pydantic import ValidationError
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from configs import dify_config
|
||||
from constants.dsl_version import CURRENT_APP_DSL_VERSION
|
||||
from core.db.session_factory import get_session_maker
|
||||
from core.schemas.schema_manager import SchemaManager
|
||||
from core.tools.tool_file_manager import ToolFileManager
|
||||
from core.tools.tool_manager import ToolManager
|
||||
from enums import DeploymentEdition, WebAppAccessMode
|
||||
from extensions.application_services.account import AccountServices, build_account_services
|
||||
from extensions.application_services.agent import AgentAppServices, build_agent_app_services
|
||||
from extensions.application_services.app import AppServices, build_app_api_key_service, build_app_services
|
||||
from extensions.application_services.data_sources import (
|
||||
DataSourceServices,
|
||||
build_data_source_credentials,
|
||||
build_data_source_services,
|
||||
)
|
||||
from extensions.application_services.datasets import build_dataset_dependencies
|
||||
from extensions.application_services.installed_app import InstalledAppServices, build_installed_app_services
|
||||
from extensions.application_services.knowledge import (
|
||||
KnowledgeServices,
|
||||
build_dataset_api_key_service,
|
||||
build_knowledge_services,
|
||||
)
|
||||
from extensions.application_services.rbac import RBACServices, build_rbac_services
|
||||
from extensions.application_services.resource_access_token import build_resource_access_token_service
|
||||
from extensions.application_services.tracing import TracingServices, build_tracing_services
|
||||
from extensions.application_services.trial_app import TrialAppServices, build_trial_app_services
|
||||
from extensions.application_services.workspace import (
|
||||
WorkspaceServices,
|
||||
build_workspace_membership_services,
|
||||
build_workspace_services,
|
||||
)
|
||||
from extensions.ext_redis import RedisClientWrapper, redis_client
|
||||
from extensions.ext_storage import storage
|
||||
from extensions.tracing import bind_tracing
|
||||
from libs.helper import RateLimiter
|
||||
from libs.passport import PassportService
|
||||
from models.model import EndUser
|
||||
from models.utils.file_input_compat import restore_input_files
|
||||
from repositories.account.repository import SQLAlchemyAccountRepository
|
||||
from repositories.account_activation_repository import SQLAlchemyAccountActivationRepository
|
||||
from repositories.account_integration_repository import SQLAlchemyAccountIntegrationRepository
|
||||
from repositories.annotation_import_job_repository import RedisAnnotationImportJobRepository
|
||||
from repositories.annotation_reply_job_repository import RedisAnnotationReplyJobRepository
|
||||
from repositories.annotation_repository import AnnotationRepository
|
||||
from repositories.api_based_extension_repository import APIBasedExtensionRepository
|
||||
from repositories.app.agent_app_repository import AgentAppRepository
|
||||
from repositories.app.console_repository import ConsoleAppRepository
|
||||
from repositories.app.mcp_server_repository import AppMCPServerRepository
|
||||
from repositories.app.site_command_repository import AppSiteCommandRepository
|
||||
from repositories.app.tracing_config_repository import SQLAlchemyAppTracingConfigRepository
|
||||
from repositories.app.workflow_comment_repository import WorkflowCommentRepository
|
||||
from repositories.app_definition_query_repository import AppDefinitionQueryRepository
|
||||
from repositories.app_preview_query_repository import AppPreviewQueryRepository
|
||||
from repositories.app_scoped_end_user_repository import AppScopedEndUserRepo
|
||||
from repositories.app_statistic_query_repository import AppStatisticQueryRepository
|
||||
from repositories.conversation_repository import ConversationRepository
|
||||
from repositories.conversation_variable_repository import ConversationVariableRepository
|
||||
from repositories.credentials.query_repository import CredentialQueryRepository
|
||||
from repositories.explore_banner_query_repository import ExploreBannerQueryRepository
|
||||
from repositories.factory import DifyAPIRepositoryFactory
|
||||
from repositories.file_grant_repository import FileGrantRepository
|
||||
from repositories.human_input_file_upload_repository import SQLAlchemyHumanInputFileUploadRepository
|
||||
from repositories.installation_state_repository import InstallationStateRepository
|
||||
from repositories.message_file_preview_repository import MessageFilePreviewQueryRepository
|
||||
from repositories.message_repository import MessageRepository
|
||||
from repositories.network_access_group_repository import SQLAlchemyNetworkAccessGroupAppRepository
|
||||
from repositories.oauth_device_token_repository import SQLAlchemyOAuthDeviceTokenRepository
|
||||
from repositories.oauth_server_repository import RedisOAuthServerTokenRepository, SQLAlchemyOAuthServerRepository
|
||||
from repositories.plugin_file_upload_repository import SQLAlchemyPluginFileUploadOwnerRepository
|
||||
from repositories.recommended_app_catalog_repository import DatabaseRecommendedAppCatalogRepository
|
||||
from repositories.saved_message_repository import SQLAlchemySavedMessageRepository
|
||||
from repositories.sqlalchemy_api_workflow_run_repository import DifyAPISQLAlchemyWorkflowRunRepository
|
||||
from repositories.sqlalchemy_execution_extra_content_repository import SQLAlchemyExecutionExtraContentRepository
|
||||
from repositories.step_by_step_tour_repository import SQLAlchemyStepByStepTourStateRepository
|
||||
from repositories.tag_repository import TagRepository
|
||||
from repositories.trial_app_repository import TrialAppRepository
|
||||
from repositories.upload_file_delivery_repository import UploadFileDeliveryQueryRepository
|
||||
from repositories.web_passport_repository import WebPassportRepository
|
||||
from repositories.webapp_access_query_repository import WebAppAccessQueryRepository
|
||||
from repositories.workflow_app_log_query_repository import WorkflowAppLogQueryRepository
|
||||
from repositories.workflow_run_archive_repository import WorkflowRunArchiveBundleQueryRepository
|
||||
from repositories.workspace.workspace_repository import WorkspaceRepository
|
||||
from services.account.adapters import (
|
||||
InstallationTelemetryGateway,
|
||||
RedisInvitationTokenStore,
|
||||
)
|
||||
from services.account.forgot_password_adapters import RedisForgotPasswordSecurityGateway
|
||||
from services.account.forgot_password_service import (
|
||||
FORGOT_PASSWORD_SEND_RATE_LIMIT_MAX_ATTEMPTS,
|
||||
FORGOT_PASSWORD_SEND_RATE_LIMIT_PREFIX,
|
||||
FORGOT_PASSWORD_SEND_RATE_LIMIT_WINDOW_SECONDS,
|
||||
)
|
||||
from services.account.login_adapters import RedisConsoleAuthSecurityGateway
|
||||
from services.account.service import AccountSetupProvisioner
|
||||
from services.account_password_hasher import DefaultAccountPasswordHasher
|
||||
from services.agent.roster_package_exporter import RosterAgentPackageExporter
|
||||
from services.agent_tracing_config_service import AgentTracingConfigService
|
||||
from services.annotation_command_service import AnnotationCommandService
|
||||
from services.annotation_import_service import AnnotationImportLimits, AnnotationImportQuota, AnnotationImportService
|
||||
from services.annotation_query import AnnotationQuery
|
||||
from services.annotation_reply_service import AnnotationReplyService
|
||||
from services.api_based_extension_adapters import APIBasedExtensionPingProbe, WorkspaceTokenCipher
|
||||
from services.api_based_extension_application_service import APIBasedExtensionApplicationService
|
||||
from services.app.advanced_prompt_template_service import AdvancedPromptTemplateService
|
||||
from services.app.api_key_service import AppApiKeyService
|
||||
from services.app.mcp_server_service import AppMCPServerService
|
||||
from services.app.workflow_comment_mention_gateway import CeleryWorkflowCommentMentionNotifier
|
||||
from services.app.workflow_comment_service import WorkflowCommentService
|
||||
from services.app_audio_adapters import AppAudioRuntime
|
||||
from services.app_audio_service import AppAudio
|
||||
from services.app_definition_query_service import AppDefinitionQueryService
|
||||
from services.app_preview_details_adapters import AppPreviewDetailsRuntime
|
||||
from services.app_preview_details_service import AppPreviewDetails
|
||||
from services.app_preview_query_service import AppPreviewQueryService
|
||||
from services.app_scoped_end_user_query_service import AppScopedEndUserQueryService
|
||||
from services.app_scoped_end_user_service import AppScopedEndUserService
|
||||
from services.app_site_service import AppSiteService
|
||||
from services.app_statistic_query import AppStatisticQuery
|
||||
from services.app_task_service import AppTaskControlService
|
||||
from services.app_tracing_config_service import AppTracingConfigService
|
||||
from services.billing_portal_service import BillingPortalService
|
||||
from services.billing_service import BillingService
|
||||
from services.compliance_download_service import ComplianceDownloadService
|
||||
from services.conversation_command_service import ConversationCommandService
|
||||
from services.conversation_name_generator import DefaultModelConversationNameGenerator
|
||||
from services.conversation_name_service import ConversationNameService
|
||||
from services.conversation_query_service import ConversationQueryService
|
||||
from services.conversation_service import ConversationService
|
||||
from services.conversation_variable_command_service import ConversationVariableCommandService
|
||||
from services.conversation_variable_query import ConversationVariableQuery
|
||||
from services.credentials.query import CredentialQuery
|
||||
from services.enterprise.enterprise_service import EnterpriseService
|
||||
from services.entities.file_grant_entities import FileGrantLimits
|
||||
from services.errors.enterprise import EnterpriseServiceError
|
||||
from services.explore_banner_query_service import ExploreBannerQueryService
|
||||
from services.feature_query_service import FeatureQueryService
|
||||
from services.feature_service import FeatureService
|
||||
from services.feature_service_gateway import FeatureServiceGateway
|
||||
from services.file_grant_gateways import FileGrantFileGateway, FileGrantRemoteFileGateway, FileGrantTokenGateway
|
||||
from services.file_grant_service import FileGrantService
|
||||
from services.file_service import FileService
|
||||
from services.human_input_file_upload_service import HumanInputFileUploadService
|
||||
from services.init_validation_service import InitValidationService
|
||||
from services.inner_mail_service import InnerMailService
|
||||
from services.knowledge.api_key_service import DatasetApiKeyService
|
||||
from services.knowledge_fs.builtin_tool.knowledge_fs.knowledge_fs import KnowledgeFSProvider
|
||||
from services.knowledge_fs.feature_service import get_knowledge_fs_features
|
||||
from services.knowledge_fs.workflow_runtime import build_knowledge_fs_node_dependencies
|
||||
from services.message_feedback_service import MessageFeedbackService
|
||||
from services.message_file_preview_service import MessageFilePreviewService
|
||||
from services.message_more_like_this_generator import MessageMoreLikeThisGenerator
|
||||
from services.message_more_like_this_service import MessageMoreLikeThisService
|
||||
from services.message_query_adapters import ExecutionExtraContentReader, MessageFileResolver
|
||||
from services.message_query_service import MessageQueryService
|
||||
from services.message_suggested_questions_generator import SuggestedQuestionsGenerator
|
||||
from services.message_suggested_questions_queries import SuggestedQuestionsQuery
|
||||
from services.message_suggested_questions_service import MessageSuggestedQuestions, MessageSuggestedQuestionsService
|
||||
from services.network_access_group_gateway import (
|
||||
BillingNetworkAccessGroupEntitlementGateway,
|
||||
NetworkAccessGroupGateway,
|
||||
)
|
||||
from services.network_access_group_service import NetworkAccessGroupService
|
||||
from services.notification_gateway import BillingNotificationGateway
|
||||
from services.notification_service import NotificationService
|
||||
from services.oauth_device_adapters import (
|
||||
DifyConfigOAuthDeviceSettings,
|
||||
EnterpriseOAuthDeviceSSOGateway,
|
||||
EnvironmentOAuthDeviceTokenTTLPolicy,
|
||||
OAuthDeviceTokenIssuanceGateway,
|
||||
RedisExternalApprovalLimiter,
|
||||
)
|
||||
from services.oauth_device_application_service import (
|
||||
DeviceWorkspaceQuery,
|
||||
OAuthDeviceAccountQuery,
|
||||
OAuthDeviceApplicationService,
|
||||
)
|
||||
from services.oauth_device_flow import DeviceFlowRedis
|
||||
from services.oauth_server_service import OAUTH_ACCESS_TOKEN_EXPIRES_IN, OAuthServerService
|
||||
from services.plugin_file_upload_gateway import ToolFilePluginUploadGateway
|
||||
from services.plugin_file_upload_service import PluginFileUploadService
|
||||
from services.recommended_app_catalog_gateway import (
|
||||
BuiltinRecommendedAppCatalogGateway,
|
||||
RecommendedAppCatalogRouter,
|
||||
RemoteRecommendedAppCatalogGateway,
|
||||
)
|
||||
from services.recommended_app_package_service import RecommendedAppPackageService
|
||||
from services.recommended_app_query_service import RecommendedAppQueryService
|
||||
from services.remote_file_service import RemoteFileService
|
||||
from services.resource_access_token_service import ResourceAccessTokenService
|
||||
from services.retention.workflow_run.archive_download_adapters import (
|
||||
dispatch_workflow_run_archive_deletion_task,
|
||||
dispatch_workflow_run_archive_download_task,
|
||||
sign_workflow_run_archive_download_url,
|
||||
)
|
||||
from services.retention.workflow_run.archive_download_task_cache import WorkflowRunArchiveDownloadTaskCache
|
||||
from services.retention.workflow_run.archive_log_service import WorkflowRunArchiveService
|
||||
from services.saved_message_service import SavedMessageService
|
||||
from services.schema_definition_service import SchemaDefinitionService
|
||||
from services.setup_adapters import RedisSetupLock
|
||||
from services.setup_service import SetupService
|
||||
from services.step_by_step_tour_service import StepByStepTourService
|
||||
from services.system_feature_service import SystemFeatureService
|
||||
from services.tag_application_service import TagApplicationService
|
||||
from services.tool_file_download_service import ToolFileDownloadService
|
||||
from services.tracing.adapters import StoredPolicyTraceScopes
|
||||
from services.upload_file_delivery_service import UploadFileDeliveryService
|
||||
from services.web_app_runtime_query_service import WebAppRuntimeQueryService
|
||||
from services.web_authentication_adapters import (
|
||||
AccountWebAuthenticationSecurityGateway,
|
||||
LoggingWebAuthenticationAuditGateway,
|
||||
PassportWebAppSessionGateway,
|
||||
TokenManagerWebAuthenticationGateway,
|
||||
)
|
||||
from services.web_authentication_service import WebAuthenticationService
|
||||
from services.web_passport_gateways import (
|
||||
DeploymentWebPassportAuthGateway,
|
||||
PassportTokenGateway,
|
||||
)
|
||||
from services.web_passport_service import WebPassportService
|
||||
from services.webapp_access_adapters import EnterpriseWebAppAccessPolicyGateway
|
||||
from services.webapp_access_query_service import WebAppAccessQueryService, WebAppAccessUnavailableError
|
||||
from services.workflow_app_log_query_service import WorkflowAppLogQueryService
|
||||
from services.workflow_run_service import WorkflowRunService
|
||||
from services.workflow_statistic_query_service import WorkflowStatisticQueryService
|
||||
from tasks.annotation.add_annotation_to_index_task import add_annotation_to_index_task
|
||||
from tasks.annotation.batch_import_annotations_task import batch_import_annotations_task
|
||||
from tasks.annotation.delete_annotation_index_task import delete_annotation_index_task
|
||||
from tasks.annotation.disable_annotation_reply_task import disable_annotation_reply_task
|
||||
from tasks.annotation.enable_annotation_reply_task import enable_annotation_reply_task
|
||||
from tasks.annotation.update_annotation_to_index_task import update_annotation_to_index_task
|
||||
from tasks.mail_inner_task import enqueue_inner_mail
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_EXTENSION_KEY = "application_services"
|
||||
|
||||
|
||||
# TODO: Normalize EnterpriseService.WebAppAuth result/error contracts in the SDK,
|
||||
# migrate its callers, then inject its batch methods directly and remove these wrappers.
|
||||
# Define SDK errors for timeouts, transport failures, upstream status and invalid
|
||||
# responses before adding finer HTTP mappings; these wrappers report unavailability.
|
||||
# Validate required fields and real booleans there, replacing legacy permission
|
||||
# truthiness conversion. Missing fields currently become False, {} or a default mode.
|
||||
# Replace response-shape ValueError/KeyError/AttributeError with typed SDK errors;
|
||||
# ordinary ValueError can still reach the global 400 invalid_param handler. The
|
||||
# lost field information cannot be recovered by translating exceptions here.
|
||||
def _batch_get_enterprise_webapp_access_modes(*, app_ids: Sequence[str]) -> Mapping[str, WebAppAccessMode]:
|
||||
try:
|
||||
settings = EnterpriseService.WebAppAuth.batch_get_app_access_mode_by_id(list(app_ids))
|
||||
except (EnterpriseServiceError, httpx.RequestError, json.JSONDecodeError, UnicodeDecodeError, ValidationError) as e:
|
||||
raise WebAppAccessUnavailableError from e
|
||||
access_modes: dict[str, WebAppAccessMode] = {}
|
||||
for app_id, setting in settings.items():
|
||||
try:
|
||||
access_mode = WebAppAccessMode(setting.access_mode)
|
||||
except ValueError:
|
||||
logger.warning("Skipping invalid web app access mode %r for app %s", setting.access_mode, app_id)
|
||||
continue
|
||||
access_modes[app_id] = access_mode
|
||||
return access_modes
|
||||
|
||||
|
||||
def _batch_get_enterprise_webapp_user_permissions(*, user_id: str, app_ids: Sequence[str]) -> Mapping[str, bool]:
|
||||
try:
|
||||
permissions = EnterpriseService.WebAppAuth.batch_is_user_allowed_to_access_webapps(
|
||||
user_id=user_id, app_ids=list(app_ids)
|
||||
)
|
||||
except (EnterpriseServiceError, httpx.RequestError, json.JSONDecodeError, UnicodeDecodeError) as e:
|
||||
raise WebAppAccessUnavailableError from e
|
||||
return {app_id: bool(allowed) for app_id, allowed in permissions.items()}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AppScopedEndUserServices:
|
||||
commands: AppScopedEndUserService[EndUser]
|
||||
queries: AppScopedEndUserQueryService
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ApplicationServices:
|
||||
annotation_commands: AnnotationCommandService
|
||||
annotation_imports: AnnotationImportService
|
||||
annotation_queries: AnnotationQuery
|
||||
annotation_reply: AnnotationReplyService
|
||||
rbac: RBACServices
|
||||
agent_apps: AgentAppServices
|
||||
advanced_prompt_templates: AdvancedPromptTemplateService
|
||||
api_based_extensions: APIBasedExtensionApplicationService
|
||||
credential_queries: CredentialQuery
|
||||
accounts: AccountServices
|
||||
app_api_keys: AppApiKeyService
|
||||
dataset_api_keys: DatasetApiKeyService
|
||||
resource_access_tokens: ResourceAccessTokenService
|
||||
apps: AppServices
|
||||
app_definitions: AppDefinitionQueryService
|
||||
app_mcp_servers: AppMCPServerService
|
||||
app_preview_details: AppPreviewDetails
|
||||
app_previews: AppPreviewQueryService
|
||||
app_sites: AppSiteService
|
||||
conversation_variables: ConversationVariableQuery
|
||||
conversation_variable_commands: ConversationVariableCommandService
|
||||
app_statistics: AppStatisticQuery
|
||||
app_tracing_configs: AppTracingConfigService
|
||||
agent_tracing_configs: AgentTracingConfigService
|
||||
billing_portal: BillingPortalService
|
||||
compliance_downloads: ComplianceDownloadService
|
||||
conversation_names: ConversationNameService
|
||||
conversation_commands: ConversationCommandService
|
||||
conversation_queries: ConversationQueryService
|
||||
data_sources: DataSourceServices
|
||||
knowledge: KnowledgeServices
|
||||
app_scoped_end_users: AppScopedEndUserServices
|
||||
webapp_access: WebAppAccessQueryService
|
||||
web_authentication: WebAuthenticationService
|
||||
web_app_runtime: WebAppRuntimeQueryService
|
||||
explore_banner_queries: ExploreBannerQueryService
|
||||
schema_definitions: SchemaDefinitionService
|
||||
setup: SetupService
|
||||
feature_queries: FeatureQueryService
|
||||
file_grants: FileGrantService
|
||||
files: FileService
|
||||
human_input_file_uploads: HumanInputFileUploadService
|
||||
message_feedbacks: MessageFeedbackService
|
||||
message_queries: MessageQueryService
|
||||
message_file_previews: MessageFilePreviewService
|
||||
message_suggested_questions: MessageSuggestedQuestions
|
||||
message_more_like_this: MessageMoreLikeThisService
|
||||
plugin_file_uploads: PluginFileUploadService
|
||||
tool_file_downloads: ToolFileDownloadService
|
||||
upload_file_delivery: UploadFileDeliveryService
|
||||
oauth_server: OAuthServerService
|
||||
oauth_device: OAuthDeviceApplicationService
|
||||
init_validation: InitValidationService
|
||||
installed_apps: InstalledAppServices
|
||||
notifications: NotificationService
|
||||
network_access_groups: NetworkAccessGroupService
|
||||
step_by_step_tour: StepByStepTourService
|
||||
recommended_app_queries: RecommendedAppQueryService
|
||||
recommended_app_packages: RecommendedAppPackageService
|
||||
remote_files: RemoteFileService
|
||||
saved_messages: SavedMessageService
|
||||
app_tasks: AppTaskControlService
|
||||
app_audio: AppAudio
|
||||
trial_apps: TrialAppServices
|
||||
workflow_run_archives: WorkflowRunArchiveService
|
||||
workflow_runs: WorkflowRunService
|
||||
workspaces: WorkspaceServices
|
||||
workflow_app_logs: WorkflowAppLogQueryService
|
||||
workflow_comments: WorkflowCommentService
|
||||
inner_mail: InnerMailService
|
||||
web_passport: WebPassportService
|
||||
tags: TagApplicationService
|
||||
workflow_statistics: WorkflowStatisticQueryService
|
||||
tracing: TracingServices
|
||||
|
||||
|
||||
def _build_oauth_server_service(
|
||||
*,
|
||||
database_client: sessionmaker[Session],
|
||||
redis: RedisClientWrapper,
|
||||
) -> OAuthServerService:
|
||||
return OAuthServerService(
|
||||
repository=SQLAlchemyOAuthServerRepository(session_factory=database_client),
|
||||
tokens=RedisOAuthServerTokenRepository(redis=redis),
|
||||
access_token_expires_in=OAUTH_ACCESS_TOKEN_EXPIRES_IN,
|
||||
)
|
||||
|
||||
|
||||
def _build_oauth_device_service(
|
||||
*,
|
||||
database_client: sessionmaker[Session],
|
||||
redis: RedisClientWrapper,
|
||||
accounts: OAuthDeviceAccountQuery,
|
||||
workspaces: DeviceWorkspaceQuery,
|
||||
) -> OAuthDeviceApplicationService:
|
||||
token_repository = SQLAlchemyOAuthDeviceTokenRepository(session_factory=database_client, redis=redis)
|
||||
return OAuthDeviceApplicationService(
|
||||
store=DeviceFlowRedis(redis),
|
||||
accounts=accounts,
|
||||
workspaces=workspaces,
|
||||
tokens=OAuthDeviceTokenIssuanceGateway(
|
||||
tokens=token_repository,
|
||||
ttl_policy=EnvironmentOAuthDeviceTokenTTLPolicy(),
|
||||
),
|
||||
sessions=token_repository,
|
||||
sso=EnterpriseOAuthDeviceSSOGateway(
|
||||
redis=redis,
|
||||
enterprise_service=EnterpriseService(),
|
||||
),
|
||||
external_approval_limiter=RedisExternalApprovalLimiter(redis=redis),
|
||||
settings=DifyConfigOAuthDeviceSettings(),
|
||||
)
|
||||
|
||||
|
||||
def _build_file_grant_service(*, database_client: sessionmaker[Session]) -> FileGrantService:
|
||||
repository = FileGrantRepository(session_factory=database_client)
|
||||
return FileGrantService(
|
||||
repository=repository,
|
||||
files=FileGrantFileGateway(
|
||||
load_end_user=repository.get_end_user,
|
||||
subject_exists=repository.subject_exists,
|
||||
file_service=FileService(session_factory=database_client),
|
||||
tool_files=ToolFileManager(),
|
||||
storage=storage,
|
||||
),
|
||||
remote_files=FileGrantRemoteFileGateway(),
|
||||
tokens=FileGrantTokenGateway(
|
||||
secret_key=dify_config.SECRET_KEY,
|
||||
external_files_url=dify_config.FILES_URL,
|
||||
internal_files_url=dify_config.INTERNAL_FILES_URL or dify_config.FILES_URL,
|
||||
content_token_ttl_seconds=dify_config.FILES_ACCESS_TIMEOUT,
|
||||
now=lambda: int(time.time()),
|
||||
),
|
||||
limits=FileGrantLimits(
|
||||
file_size_limit=dify_config.UPLOAD_FILE_SIZE_LIMIT,
|
||||
image_file_size_limit=dify_config.UPLOAD_IMAGE_FILE_SIZE_LIMIT,
|
||||
audio_file_size_limit=dify_config.UPLOAD_AUDIO_FILE_SIZE_LIMIT,
|
||||
video_file_size_limit=dify_config.UPLOAD_VIDEO_FILE_SIZE_LIMIT,
|
||||
workflow_file_upload_limit=dify_config.WORKFLOW_FILE_UPLOAD_LIMIT,
|
||||
batch_count_limit=dify_config.UPLOAD_FILE_BATCH_LIMIT,
|
||||
),
|
||||
now=lambda: int(time.time()),
|
||||
)
|
||||
|
||||
|
||||
def _get_annotation_import_quota(*, tenant_id: str) -> AnnotationImportQuota | None:
|
||||
if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:
|
||||
return None
|
||||
quota = FeatureService.get_features(tenant_id, exclude_vector_space=True).annotation_quota_limit
|
||||
return AnnotationImportQuota(limit=quota.limit, size=quota.size)
|
||||
|
||||
|
||||
def build_application_services(
|
||||
*,
|
||||
database_client: sessionmaker[Session],
|
||||
deployment_edition: DeploymentEdition,
|
||||
initialization_password: str,
|
||||
redis: RedisClientWrapper,
|
||||
) -> ApplicationServices:
|
||||
installation_state = InstallationStateRepository(session_factory=database_client)
|
||||
app_definition_repository = AppDefinitionQueryRepository(session_factory=database_client)
|
||||
app_definitions = AppDefinitionQueryService(
|
||||
definitions=app_definition_repository,
|
||||
builtin_icon_url_prefix=(
|
||||
dify_config.CONSOLE_API_URL + "/console/api/workspaces/current/tool-provider/builtin/"
|
||||
),
|
||||
)
|
||||
webapp_auth_enabled = SystemFeatureService.is_webapp_auth_enabled(deployment_edition=deployment_edition)
|
||||
webapp_access_repository = WebAppAccessQueryRepository(session_factory=database_client)
|
||||
webapp_access = WebAppAccessQueryService(
|
||||
access=webapp_access_repository,
|
||||
policy=EnterpriseWebAppAccessPolicyGateway(webapp_auth=EnterpriseService.WebAppAuth),
|
||||
webapp_auth_enabled=webapp_auth_enabled,
|
||||
get_access_modes=_batch_get_enterprise_webapp_access_modes,
|
||||
get_user_permissions=_batch_get_enterprise_webapp_user_permissions,
|
||||
)
|
||||
app_preview_repository = AppPreviewQueryRepository(session_factory=database_client)
|
||||
feature_gateway = FeatureServiceGateway()
|
||||
accounts = SQLAlchemyAccountRepository(session_factory=database_client)
|
||||
integrations = SQLAlchemyAccountIntegrationRepository(session_factory=database_client)
|
||||
trial_app_enabled = SystemFeatureService.is_trial_app_enabled()
|
||||
trial_apps = TrialAppRepository(session_factory=database_client)
|
||||
database_catalog = DatabaseRecommendedAppCatalogRepository(session_factory=database_client, redis=redis)
|
||||
builtin_catalog = BuiltinRecommendedAppCatalogGateway()
|
||||
remote_catalog = RemoteRecommendedAppCatalogGateway()
|
||||
recommended_app_catalog = RecommendedAppCatalogRouter(
|
||||
remote=remote_catalog,
|
||||
database=database_catalog,
|
||||
builtin=builtin_catalog,
|
||||
)
|
||||
workspace_repository = WorkspaceRepository(session_factory=database_client)
|
||||
workspace_members, workspace_provisioning = build_workspace_membership_services(
|
||||
workspaces=workspace_repository,
|
||||
accounts=accounts,
|
||||
)
|
||||
recommended_app_queries = RecommendedAppQueryService(
|
||||
catalog=recommended_app_catalog,
|
||||
trial_apps=trial_apps,
|
||||
trial_enabled=trial_app_enabled,
|
||||
)
|
||||
recommended_app_packages = RecommendedAppPackageService(
|
||||
sources=database_catalog, exporter=RosterAgentPackageExporter()
|
||||
)
|
||||
dataset_dependencies = build_dataset_dependencies(
|
||||
database_client=database_client,
|
||||
workspace_roles=workspace_repository,
|
||||
)
|
||||
datasource_credentials = build_data_source_credentials(database_client=database_client)
|
||||
data_sources = build_data_source_services(
|
||||
database_client=database_client,
|
||||
dataset_access=dataset_dependencies.access,
|
||||
datasets=dataset_dependencies.datasets,
|
||||
documents=dataset_dependencies.documents,
|
||||
actor_credentials=datasource_credentials.actor,
|
||||
providers=datasource_credentials.providers,
|
||||
)
|
||||
oauth_server = _build_oauth_server_service(database_client=database_client, redis=redis)
|
||||
console_apps = ConsoleAppRepository(session_factory=database_client)
|
||||
rbac = build_rbac_services(
|
||||
workspaces=workspace_repository,
|
||||
workspace_members=workspace_members,
|
||||
apps=console_apps,
|
||||
datasets=dataset_dependencies.datasets,
|
||||
)
|
||||
tracing = build_tracing_services(database_client=database_client)
|
||||
tracing_configs = AppTracingConfigService(
|
||||
configs=SQLAlchemyAppTracingConfigRepository(session_factory=database_client),
|
||||
provider=tracing.provider_configs,
|
||||
)
|
||||
apps = build_app_services(
|
||||
database_client=database_client,
|
||||
oauth=oauth_server,
|
||||
recommended_packages=recommended_app_packages,
|
||||
repository=console_apps,
|
||||
rbac_members=rbac.members,
|
||||
tracing_configs=tracing_configs,
|
||||
)
|
||||
tags = TagApplicationService(tags=TagRepository(session_factory=database_client))
|
||||
knowledge = build_knowledge_services(
|
||||
database_client=database_client,
|
||||
dataset_access=dataset_dependencies.access,
|
||||
datasets=dataset_dependencies.datasets,
|
||||
documents=dataset_dependencies.documents,
|
||||
actor_credentials=datasource_credentials.actor,
|
||||
stored_credentials=datasource_credentials.stored,
|
||||
providers=datasource_credentials.providers,
|
||||
redis=redis,
|
||||
tags=tags,
|
||||
rbac_members=rbac.members,
|
||||
)
|
||||
app_scoped_end_user_repository = AppScopedEndUserRepo(session_factory=database_client)
|
||||
file_service = FileService(session_factory=database_client)
|
||||
remote_file_service = RemoteFileService(files=file_service)
|
||||
passwords = DefaultAccountPasswordHasher()
|
||||
web_authentication_tokens = TokenManagerWebAuthenticationGateway(
|
||||
reset_password_rate_limiter=RateLimiter(
|
||||
prefix=FORGOT_PASSWORD_SEND_RATE_LIMIT_PREFIX,
|
||||
max_attempts=FORGOT_PASSWORD_SEND_RATE_LIMIT_MAX_ATTEMPTS,
|
||||
time_window=FORGOT_PASSWORD_SEND_RATE_LIMIT_WINDOW_SECONDS,
|
||||
redis_client=redis,
|
||||
),
|
||||
access_token_expire_minutes=dify_config.ACCESS_TOKEN_EXPIRE_MINUTES,
|
||||
)
|
||||
invitation_tokens = RedisInvitationTokenStore(redis=redis)
|
||||
activation_accounts = SQLAlchemyAccountActivationRepository(session_factory=database_client)
|
||||
workflow_run_repository = DifyAPISQLAlchemyWorkflowRunRepository(session_maker=database_client)
|
||||
workflow_node_execution_repository = DifyAPIRepositoryFactory.create_api_workflow_node_execution_repository(
|
||||
session_maker=database_client
|
||||
)
|
||||
account_services = build_account_services(
|
||||
database_client=database_client,
|
||||
deployment_edition=deployment_edition,
|
||||
redis=redis,
|
||||
accounts=accounts,
|
||||
integrations=integrations,
|
||||
workspace_repository=workspace_repository,
|
||||
workspace_provisioning=workspace_provisioning,
|
||||
passwords=passwords,
|
||||
invitation_tokens=invitation_tokens,
|
||||
activation_accounts=activation_accounts,
|
||||
)
|
||||
workspace_services = build_workspace_services(
|
||||
database_client=database_client,
|
||||
workspaces=workspace_repository,
|
||||
accounts=accounts,
|
||||
files=file_service,
|
||||
redis=redis,
|
||||
members=workspace_members,
|
||||
provisioning=workspace_provisioning,
|
||||
registration=account_services.lifecycle,
|
||||
invitation_tokens=invitation_tokens,
|
||||
)
|
||||
conversations = ConversationRepository(session_factory=database_client)
|
||||
conversation_names = ConversationNameService(
|
||||
conversations=conversations,
|
||||
generate_name=DefaultModelConversationNameGenerator(trace_scopes=tracing.scopes),
|
||||
)
|
||||
conversation_commands = ConversationCommandService(
|
||||
conversations=conversations, enqueue_delete_cleanup=ConversationService.enqueue_delete_cleanup
|
||||
)
|
||||
message_files = MessageFileResolver()
|
||||
conversation_queries = ConversationQueryService(
|
||||
conversations=conversations, restore_inputs=restore_input_files, files=message_files
|
||||
)
|
||||
conversation_variables = ConversationVariableRepository(session_factory=database_client)
|
||||
annotations = AnnotationRepository(session_factory=database_client)
|
||||
messages = MessageRepository(session_factory=database_client)
|
||||
suggested_questions = SuggestedQuestionsQuery(
|
||||
session_factory=database_client,
|
||||
repository=messages,
|
||||
)
|
||||
|
||||
return ApplicationServices(
|
||||
annotation_commands=AnnotationCommandService(
|
||||
annotations=annotations,
|
||||
add_index=add_annotation_to_index_task.delay,
|
||||
update_index=update_annotation_to_index_task.delay,
|
||||
delete_index=delete_annotation_index_task.delay,
|
||||
),
|
||||
annotation_queries=annotations,
|
||||
annotation_imports=AnnotationImportService(
|
||||
apps=annotations,
|
||||
jobs=RedisAnnotationImportJobRepository(redis=redis),
|
||||
publish=batch_import_annotations_task.delay,
|
||||
quota=_get_annotation_import_quota,
|
||||
limits=AnnotationImportLimits(
|
||||
min_records=dify_config.ANNOTATION_IMPORT_MIN_RECORDS,
|
||||
max_records=dify_config.ANNOTATION_IMPORT_MAX_RECORDS,
|
||||
requests_per_minute=dify_config.ANNOTATION_IMPORT_RATE_LIMIT_PER_MINUTE,
|
||||
requests_per_hour=dify_config.ANNOTATION_IMPORT_RATE_LIMIT_PER_HOUR,
|
||||
max_concurrent=dify_config.ANNOTATION_IMPORT_MAX_CONCURRENT,
|
||||
),
|
||||
),
|
||||
annotation_reply=AnnotationReplyService(
|
||||
apps=annotations,
|
||||
jobs=RedisAnnotationReplyJobRepository(redis=redis),
|
||||
enable_task=enable_annotation_reply_task.delay,
|
||||
disable_task=disable_annotation_reply_task.delay,
|
||||
),
|
||||
rbac=rbac,
|
||||
conversation_names=conversation_names,
|
||||
conversation_commands=conversation_commands,
|
||||
conversation_queries=conversation_queries,
|
||||
accounts=account_services,
|
||||
apps=apps,
|
||||
credential_queries=CredentialQueryRepository(session_factory=database_client),
|
||||
agent_apps=build_agent_app_services(database_client=database_client),
|
||||
advanced_prompt_templates=AdvancedPromptTemplateService(),
|
||||
app_definitions=app_definitions,
|
||||
app_mcp_servers=AppMCPServerService(
|
||||
servers=AppMCPServerRepository(session_factory=database_client),
|
||||
),
|
||||
app_preview_details=AppPreviewDetailsRuntime(details=app_preview_repository),
|
||||
app_previews=AppPreviewQueryService(
|
||||
apps=app_preview_repository,
|
||||
is_previewable=recommended_app_queries.is_previewable,
|
||||
),
|
||||
app_sites=AppSiteService(
|
||||
sites=AppSiteCommandRepository(session_factory=database_client),
|
||||
),
|
||||
conversation_variables=conversation_variables,
|
||||
conversation_variable_commands=ConversationVariableCommandService(variables=conversation_variables),
|
||||
app_api_keys=build_app_api_key_service(database_client=database_client),
|
||||
dataset_api_keys=build_dataset_api_key_service(
|
||||
database_client=database_client,
|
||||
dataset_access=dataset_dependencies.access,
|
||||
),
|
||||
resource_access_tokens=build_resource_access_token_service(database_client=database_client),
|
||||
app_statistics=AppStatisticQueryRepository(session_factory=database_client),
|
||||
app_tracing_configs=tracing_configs,
|
||||
agent_tracing_configs=AgentTracingConfigService(
|
||||
owners=AgentAppRepository(session_factory=database_client),
|
||||
settings=apps.console,
|
||||
configs=tracing_configs,
|
||||
),
|
||||
billing_portal=BillingPortalService(
|
||||
accounts=accounts,
|
||||
get_subscription=BillingService.get_subscription,
|
||||
get_invoices=BillingService.get_invoices,
|
||||
),
|
||||
compliance_downloads=ComplianceDownloadService(
|
||||
fetch_link=BillingService.get_compliance_download_link,
|
||||
rate_limiter=RateLimiter(
|
||||
prefix="compliance_download_rate_limiter",
|
||||
max_attempts=4,
|
||||
time_window=60,
|
||||
redis_client=redis,
|
||||
),
|
||||
),
|
||||
data_sources=data_sources,
|
||||
knowledge=knowledge,
|
||||
app_scoped_end_users=AppScopedEndUserServices(
|
||||
commands=AppScopedEndUserService(end_users=app_scoped_end_user_repository),
|
||||
queries=AppScopedEndUserQueryService(end_users=app_scoped_end_user_repository),
|
||||
),
|
||||
webapp_access=webapp_access,
|
||||
web_authentication=WebAuthenticationService(
|
||||
accounts=accounts,
|
||||
passwords=passwords,
|
||||
tokens=web_authentication_tokens,
|
||||
security=AccountWebAuthenticationSecurityGateway(
|
||||
password_security=RedisForgotPasswordSecurityGateway(
|
||||
redis=redis,
|
||||
email_send_ip_limit_per_minute=dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE,
|
||||
verification_lockout_duration=dify_config.FORGOT_PASSWORD_LOCKOUT_DURATION,
|
||||
),
|
||||
login_security=RedisConsoleAuthSecurityGateway(redis=redis),
|
||||
),
|
||||
app_access=webapp_access,
|
||||
app_sessions=PassportWebAppSessionGateway(
|
||||
sessions=webapp_access_repository,
|
||||
app_access=webapp_access,
|
||||
),
|
||||
audit=LoggingWebAuthenticationAuditGateway(logger=logging.getLogger("controllers.web.login")),
|
||||
private_app_access_enabled=deployment_edition == DeploymentEdition.ENTERPRISE,
|
||||
),
|
||||
installed_apps=build_installed_app_services(
|
||||
conversation_queries=conversation_queries,
|
||||
conversation_names=conversation_names,
|
||||
conversation_commands=conversation_commands,
|
||||
database_client=database_client,
|
||||
webapp_access=webapp_access,
|
||||
get_workspace_role=workspace_repository.get_account_role,
|
||||
webapp_auth_enabled=webapp_auth_enabled,
|
||||
),
|
||||
web_app_runtime=WebAppRuntimeQueryService(
|
||||
runtime=app_definition_repository,
|
||||
file_service=file_service,
|
||||
workspace_features=feature_gateway.get_workspace_features,
|
||||
files_url=dify_config.FILES_URL,
|
||||
deployment_edition=deployment_edition,
|
||||
),
|
||||
explore_banner_queries=ExploreBannerQueryService(
|
||||
banners=ExploreBannerQueryRepository(session_factory=database_client),
|
||||
enabled=SystemFeatureService.is_explore_banner_enabled(),
|
||||
),
|
||||
schema_definitions=SchemaDefinitionService(source_factory=SchemaManager),
|
||||
setup=SetupService(
|
||||
state=installation_state,
|
||||
accounts=AccountSetupProvisioner(
|
||||
accounts=account_services.lifecycle,
|
||||
workspaces=workspace_services.provisioning,
|
||||
installation=installation_state,
|
||||
telemetry=InstallationTelemetryGateway(session_factory=database_client),
|
||||
),
|
||||
lock=RedisSetupLock(client=redis),
|
||||
setup_required=deployment_edition != DeploymentEdition.CLOUD,
|
||||
),
|
||||
feature_queries=FeatureQueryService(
|
||||
features=feature_gateway,
|
||||
app_dsl_version=CURRENT_APP_DSL_VERSION,
|
||||
),
|
||||
file_grants=_build_file_grant_service(database_client=database_client),
|
||||
files=file_service,
|
||||
human_input_file_uploads=HumanInputFileUploadService(
|
||||
uploads=SQLAlchemyHumanInputFileUploadRepository(session_factory=database_client),
|
||||
workflow_run_repository=DifyAPIRepositoryFactory.create_api_workflow_run_repository(
|
||||
session_maker=database_client,
|
||||
),
|
||||
files=file_service,
|
||||
remote_files=remote_file_service,
|
||||
),
|
||||
message_feedbacks=MessageFeedbackService(repository=messages),
|
||||
message_queries=MessageQueryService(
|
||||
messages=messages,
|
||||
files=message_files,
|
||||
extra_contents=ExecutionExtraContentReader(
|
||||
repository=SQLAlchemyExecutionExtraContentRepository(session_maker=database_client),
|
||||
session_factory=database_client,
|
||||
),
|
||||
),
|
||||
message_file_previews=MessageFilePreviewService(
|
||||
files=MessageFilePreviewQueryRepository(session_factory=database_client),
|
||||
storage=storage,
|
||||
),
|
||||
message_more_like_this=MessageMoreLikeThisService(
|
||||
repository=messages,
|
||||
generator=MessageMoreLikeThisGenerator(session_factory=database_client),
|
||||
),
|
||||
message_suggested_questions=MessageSuggestedQuestionsService(
|
||||
queries=suggested_questions,
|
||||
generator=SuggestedQuestionsGenerator(trace_scopes=tracing.scopes),
|
||||
),
|
||||
plugin_file_uploads=PluginFileUploadService(
|
||||
owners=SQLAlchemyPluginFileUploadOwnerRepository(session_factory=database_client),
|
||||
files=ToolFilePluginUploadGateway(tool_files=ToolFileManager()),
|
||||
),
|
||||
tool_file_downloads=ToolFileDownloadService(tool_files=ToolFileManager()),
|
||||
upload_file_delivery=UploadFileDeliveryService(
|
||||
files=UploadFileDeliveryQueryRepository(session_factory=database_client),
|
||||
storage=storage,
|
||||
),
|
||||
oauth_server=oauth_server,
|
||||
oauth_device=_build_oauth_device_service(
|
||||
database_client=database_client,
|
||||
redis=redis,
|
||||
accounts=accounts,
|
||||
workspaces=workspace_repository,
|
||||
),
|
||||
init_validation=InitValidationService(
|
||||
state=installation_state,
|
||||
validation_required=(deployment_edition != DeploymentEdition.CLOUD and bool(initialization_password)),
|
||||
expected_password=initialization_password,
|
||||
),
|
||||
notifications=NotificationService(
|
||||
notifications=BillingNotificationGateway(),
|
||||
),
|
||||
network_access_groups=NetworkAccessGroupService(
|
||||
control_plane=NetworkAccessGroupGateway(),
|
||||
apps=SQLAlchemyNetworkAccessGroupAppRepository(session_factory=database_client),
|
||||
memberships=workspace_repository,
|
||||
entitlement=BillingNetworkAccessGroupEntitlementGateway(),
|
||||
),
|
||||
step_by_step_tour=StepByStepTourService(
|
||||
accounts=accounts,
|
||||
states=SQLAlchemyStepByStepTourStateRepository(session_factory=database_client),
|
||||
enabled=dify_config.ENABLE_STEP_BY_STEP_TOUR,
|
||||
rollout_started_at=dify_config.STEP_BY_STEP_TOUR_ROLLOUT_STARTED_AT,
|
||||
),
|
||||
recommended_app_queries=recommended_app_queries,
|
||||
recommended_app_packages=recommended_app_packages,
|
||||
remote_files=remote_file_service,
|
||||
saved_messages=SavedMessageService(
|
||||
saved_messages=SQLAlchemySavedMessageRepository(session_factory=database_client),
|
||||
),
|
||||
app_tasks=AppTaskControlService(redis_client=redis),
|
||||
app_audio=AppAudioRuntime(session_factory=database_client),
|
||||
trial_apps=build_trial_app_services(database_client=database_client, trial_apps=trial_apps),
|
||||
workflow_run_archives=WorkflowRunArchiveService(
|
||||
bundles=WorkflowRunArchiveBundleQueryRepository(session_factory=database_client),
|
||||
tasks=WorkflowRunArchiveDownloadTaskCache(redis=redis),
|
||||
dispatcher=dispatch_workflow_run_archive_download_task,
|
||||
sign_download_url=sign_workflow_run_archive_download_url,
|
||||
deletion_dispatcher=dispatch_workflow_run_archive_deletion_task,
|
||||
),
|
||||
workflow_runs=WorkflowRunService(
|
||||
workflow_runs=workflow_run_repository,
|
||||
node_executions=workflow_node_execution_repository,
|
||||
session_factory=database_client,
|
||||
),
|
||||
workspaces=workspace_services,
|
||||
workflow_app_logs=WorkflowAppLogQueryService(
|
||||
logs=WorkflowAppLogQueryRepository(session_factory=database_client),
|
||||
),
|
||||
workflow_comments=WorkflowCommentService(
|
||||
comments=WorkflowCommentRepository(session_factory=database_client),
|
||||
notifier=CeleryWorkflowCommentMentionNotifier(),
|
||||
console_web_url=dify_config.CONSOLE_WEB_URL,
|
||||
),
|
||||
inner_mail=InnerMailService(dispatch=enqueue_inner_mail),
|
||||
web_passport=WebPassportService(
|
||||
passports=WebPassportRepository(
|
||||
session_factory=database_client,
|
||||
generate_session_id=lambda: str(uuid4()),
|
||||
),
|
||||
auth=DeploymentWebPassportAuthGateway(
|
||||
webapp_auth_enabled=SystemFeatureService.is_webapp_auth_enabled(deployment_edition=deployment_edition),
|
||||
get_app_access_mode=EnterpriseService.WebAppAuth.get_app_access_mode_by_id,
|
||||
),
|
||||
tokens=PassportTokenGateway(passport=PassportService()),
|
||||
now=lambda: datetime.now(UTC),
|
||||
access_token_expire_minutes=dify_config.ACCESS_TOKEN_EXPIRE_MINUTES,
|
||||
),
|
||||
api_based_extensions=APIBasedExtensionApplicationService(
|
||||
extensions=APIBasedExtensionRepository(session_factory=database_client),
|
||||
secrets=WorkspaceTokenCipher(),
|
||||
probe=APIBasedExtensionPingProbe(),
|
||||
),
|
||||
tags=tags,
|
||||
workflow_statistics=WorkflowStatisticQueryService(
|
||||
workflow_runs=DifyAPIRepositoryFactory.create_api_workflow_run_repository(
|
||||
session_maker=database_client,
|
||||
),
|
||||
),
|
||||
tracing=tracing,
|
||||
)
|
||||
|
||||
|
||||
def init_app(app: Flask) -> None:
|
||||
from extensions.application_services.tools import resolve_tool_credentials
|
||||
from extensions.ext_login import bind_account_loader
|
||||
|
||||
app.extensions["knowledge_fs_node_dependencies"] = build_knowledge_fs_node_dependencies
|
||||
# The Agent Knowledge Base tool cannot run without KnowledgeFS, so keep it out of tool lists when disabled.
|
||||
if get_knowledge_fs_features().enabled:
|
||||
ToolManager.register_hardcoded_provider_class(KnowledgeFSProvider)
|
||||
ToolManager.configure_credential_resolver(resolve_tool_credentials)
|
||||
services = build_application_services(
|
||||
database_client=get_session_maker(),
|
||||
deployment_edition=dify_config.DEPLOYMENT_EDITION,
|
||||
initialization_password=dify_config.INIT_PASSWORD,
|
||||
redis=redis_client,
|
||||
)
|
||||
app.extensions[_EXTENSION_KEY] = services
|
||||
bind_tracing(app, scopes=StoredPolicyTraceScopes(services.tracing.scopes), hooks=services.tracing.hooks)
|
||||
bind_account_loader(app, services.accounts.identity.load_user)
|
||||
|
||||
|
||||
def application_services() -> ApplicationServices:
|
||||
"""Return the application services bound to the current Flask app."""
|
||||
return cast(ApplicationServices, current_app.extensions[_EXTENSION_KEY])
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Register API blueprints with their browser-facing CORS policies."""
|
||||
|
||||
from configs import dify_config
|
||||
from configs.deploy import IMEventTransportMode
|
||||
from constants import (
|
||||
HEADER_NAME_APP_CODE,
|
||||
HEADER_NAME_CATALOG,
|
||||
HEADER_NAME_CSRF_TOKEN,
|
||||
HEADER_NAME_IDEMPOTENCY_KEY,
|
||||
HEADER_NAME_PASSPORT,
|
||||
HEADER_NAME_REQUEST_ID,
|
||||
)
|
||||
from dify_app import DifyApp
|
||||
|
||||
BASE_CORS_HEADERS: tuple[str, ...] = ("Content-Type", HEADER_NAME_APP_CODE, HEADER_NAME_PASSPORT)
|
||||
SERVICE_API_HEADERS: tuple[str, ...] = (*BASE_CORS_HEADERS, "Authorization")
|
||||
AUTHENTICATED_HEADERS: tuple[str, ...] = (
|
||||
*SERVICE_API_HEADERS,
|
||||
HEADER_NAME_CSRF_TOKEN,
|
||||
HEADER_NAME_IDEMPOTENCY_KEY,
|
||||
HEADER_NAME_REQUEST_ID,
|
||||
"X-Trace-ID",
|
||||
)
|
||||
FILES_HEADERS: tuple[str, ...] = (*BASE_CORS_HEADERS, HEADER_NAME_CSRF_TOKEN)
|
||||
EMBED_HEADERS: tuple[str, ...] = ("Content-Type", HEADER_NAME_APP_CODE)
|
||||
EXPOSED_HEADERS: tuple[str, ...] = ("X-Version", "X-Env", "X-Trace-Id", "Content-Disposition", HEADER_NAME_CATALOG)
|
||||
OPENAPI_HEADERS: tuple[str, ...] = ("Authorization", "Content-Type", HEADER_NAME_CSRF_TOKEN, HEADER_NAME_CATALOG)
|
||||
OPENAPI_MAX_AGE_SECONDS: int = 600
|
||||
|
||||
|
||||
def _apply_cors_once(bp, /, **cors_kwargs):
|
||||
"""Make CORS idempotent so blueprints can be reused across multiple app instances."""
|
||||
|
||||
if getattr(bp, "_dify_cors_applied", False):
|
||||
return
|
||||
|
||||
from flask_cors import CORS
|
||||
|
||||
CORS(bp, **cors_kwargs)
|
||||
bp._dify_cors_applied = True
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
# register blueprint routers
|
||||
|
||||
from services.human_input_v2.im_webhook_runtime import configure_im_webhook_runtime
|
||||
|
||||
configure_im_webhook_runtime(app)
|
||||
if dify_config.HUMAN_INPUT_IM_EVENT_TRANSPORT_MODE is IMEventTransportMode.WEBHOOK:
|
||||
from controllers.web.human_input_v2_im_webhook import bp as im_provider_webhook_bp
|
||||
|
||||
app.register_blueprint(im_provider_webhook_bp)
|
||||
|
||||
from controllers.console import bp as console_app_bp
|
||||
from controllers.files import bp as files_bp
|
||||
from controllers.inner_api import bp as inner_api_bp
|
||||
from controllers.mcp import bp as mcp_bp
|
||||
from controllers.openapi import bp as openapi_bp
|
||||
from controllers.service_api import bp as service_api_bp
|
||||
from controllers.trigger import bp as trigger_bp
|
||||
from controllers.web import bp as web_bp
|
||||
|
||||
_apply_cors_once(
|
||||
service_api_bp,
|
||||
allow_headers=list(SERVICE_API_HEADERS),
|
||||
methods=["GET", "PUT", "POST", "DELETE", "OPTIONS", "PATCH"],
|
||||
expose_headers=list(EXPOSED_HEADERS),
|
||||
)
|
||||
app.register_blueprint(service_api_bp)
|
||||
|
||||
if dify_config.OPENAPI_ENABLED:
|
||||
# User-scoped programmatic API. Default empty allowlist = same-origin
|
||||
# only; expand via OPENAPI_CORS_ALLOW_ORIGINS for third-party
|
||||
# integrations. supports_credentials so cookie-authed approve/deny
|
||||
# work; cross-origin OPTIONS without an allowed origin will fail
|
||||
# the same as on the console blueprint.
|
||||
_apply_cors_once(
|
||||
openapi_bp,
|
||||
resources={r"/*": {"origins": dify_config.OPENAPI_CORS_ALLOW_ORIGINS}},
|
||||
supports_credentials=True,
|
||||
allow_headers=list(OPENAPI_HEADERS),
|
||||
methods=["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
|
||||
expose_headers=list(EXPOSED_HEADERS),
|
||||
max_age=OPENAPI_MAX_AGE_SECONDS,
|
||||
)
|
||||
app.register_blueprint(openapi_bp)
|
||||
|
||||
_apply_cors_once(
|
||||
web_bp,
|
||||
resources={
|
||||
# Embedded bot endpoints (unauthenticated, cross-origin safe)
|
||||
r"^/chat-messages$": {
|
||||
"origins": dify_config.WEB_API_CORS_ALLOW_ORIGINS,
|
||||
"supports_credentials": False,
|
||||
"allow_headers": list(EMBED_HEADERS),
|
||||
"methods": ["GET", "POST", "OPTIONS"],
|
||||
},
|
||||
r"^/chat-messages/.*": {
|
||||
"origins": dify_config.WEB_API_CORS_ALLOW_ORIGINS,
|
||||
"supports_credentials": False,
|
||||
"allow_headers": list(EMBED_HEADERS),
|
||||
"methods": ["GET", "POST", "OPTIONS"],
|
||||
},
|
||||
# Default web application endpoints (authenticated)
|
||||
r"/*": {
|
||||
"origins": dify_config.WEB_API_CORS_ALLOW_ORIGINS,
|
||||
"supports_credentials": True,
|
||||
"allow_headers": list(AUTHENTICATED_HEADERS),
|
||||
"methods": ["GET", "PUT", "POST", "DELETE", "OPTIONS", "PATCH"],
|
||||
},
|
||||
},
|
||||
expose_headers=list(EXPOSED_HEADERS),
|
||||
)
|
||||
app.register_blueprint(web_bp)
|
||||
|
||||
_apply_cors_once(
|
||||
console_app_bp,
|
||||
resources={r"/*": {"origins": dify_config.CONSOLE_CORS_ALLOW_ORIGINS}},
|
||||
supports_credentials=True,
|
||||
allow_headers=list(AUTHENTICATED_HEADERS),
|
||||
methods=["GET", "PUT", "POST", "DELETE", "OPTIONS", "PATCH"],
|
||||
expose_headers=list(EXPOSED_HEADERS),
|
||||
)
|
||||
app.register_blueprint(console_app_bp)
|
||||
|
||||
_apply_cors_once(
|
||||
files_bp,
|
||||
allow_headers=list(FILES_HEADERS),
|
||||
methods=["GET", "PUT", "POST", "DELETE", "OPTIONS", "PATCH"],
|
||||
expose_headers=list(EXPOSED_HEADERS),
|
||||
)
|
||||
app.register_blueprint(files_bp)
|
||||
|
||||
app.register_blueprint(inner_api_bp)
|
||||
app.register_blueprint(mcp_bp)
|
||||
|
||||
# Register trigger blueprint with CORS for webhook calls
|
||||
_apply_cors_once(
|
||||
trigger_bp,
|
||||
allow_headers=["Content-Type", "Authorization", "X-App-Code"],
|
||||
methods=["GET", "PUT", "POST", "DELETE", "OPTIONS", "PATCH", "HEAD"],
|
||||
expose_headers=list(EXPOSED_HEADERS),
|
||||
)
|
||||
app.register_blueprint(trigger_bp)
|
||||
@@ -0,0 +1,407 @@
|
||||
import logging
|
||||
import ssl
|
||||
from datetime import timedelta
|
||||
from typing import Any, NotRequired
|
||||
|
||||
import pytz # type: ignore[import-untyped]
|
||||
from celery import Celery, Task
|
||||
from celery.schedules import crontab
|
||||
from celery.signals import beat_init
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from configs import dify_config
|
||||
from dify_app import DifyApp
|
||||
from enums import DeploymentEdition
|
||||
from extensions.redis_names import normalize_redis_key_prefix
|
||||
from extensions.workflow_warm_shutdown import setup_workflow_warm_shutdown_handler
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _CelerySentinelKwargsDict(TypedDict):
|
||||
socket_timeout: float | None
|
||||
password: str | None
|
||||
|
||||
|
||||
class CelerySentinelTransportDict(TypedDict, total=False):
|
||||
master_name: str | None
|
||||
sentinel_kwargs: _CelerySentinelKwargsDict
|
||||
global_keyprefix: str
|
||||
visibility_timeout: int
|
||||
|
||||
|
||||
class CelerySSLOptionsDict(TypedDict):
|
||||
ssl_cert_reqs: int
|
||||
ssl_ca_certs: str | None
|
||||
ssl_certfile: str | None
|
||||
ssl_keyfile: str | None
|
||||
|
||||
|
||||
class CeleryBeatScheduleEntry(TypedDict):
|
||||
task: str
|
||||
schedule: crontab | timedelta
|
||||
kwargs: NotRequired[dict[str, str]]
|
||||
options: NotRequired[dict[str, Any]]
|
||||
|
||||
|
||||
def _enqueue_initial_community_telemetry_heartbeat(sender: Any, **_: Any) -> None:
|
||||
task_name = "community_telemetry.send_heartbeat"
|
||||
if "community_telemetry_heartbeat" not in sender.app.conf.beat_schedule:
|
||||
return
|
||||
|
||||
task = sender.app.tasks.get(task_name)
|
||||
if task is not None:
|
||||
task.apply_async()
|
||||
|
||||
|
||||
beat_init.connect(_enqueue_initial_community_telemetry_heartbeat, weak=False)
|
||||
|
||||
|
||||
def get_celery_ssl_options() -> CelerySSLOptionsDict | None:
|
||||
"""Get SSL configuration for Celery broker/backend connections."""
|
||||
# Only apply SSL if we're using Redis as broker/backend
|
||||
if not dify_config.BROKER_USE_SSL:
|
||||
return None
|
||||
|
||||
# Check if Celery is actually using Redis
|
||||
broker_is_redis = dify_config.CELERY_BROKER_URL and (
|
||||
dify_config.CELERY_BROKER_URL.startswith("redis://") or dify_config.CELERY_BROKER_URL.startswith("rediss://")
|
||||
)
|
||||
|
||||
if not broker_is_redis:
|
||||
return None
|
||||
|
||||
# Map certificate requirement strings to SSL constants
|
||||
cert_reqs_map = {
|
||||
"CERT_NONE": ssl.CERT_NONE,
|
||||
"CERT_OPTIONAL": ssl.CERT_OPTIONAL,
|
||||
"CERT_REQUIRED": ssl.CERT_REQUIRED,
|
||||
}
|
||||
|
||||
ssl_cert_reqs = cert_reqs_map.get(dify_config.REDIS_SSL_CERT_REQS, ssl.CERT_NONE)
|
||||
|
||||
return CelerySSLOptionsDict(
|
||||
ssl_cert_reqs=ssl_cert_reqs,
|
||||
ssl_ca_certs=dify_config.REDIS_SSL_CA_CERTS,
|
||||
ssl_certfile=dify_config.REDIS_SSL_CERTFILE,
|
||||
ssl_keyfile=dify_config.REDIS_SSL_KEYFILE,
|
||||
)
|
||||
|
||||
|
||||
def get_celery_broker_transport_options() -> CelerySentinelTransportDict | dict[str, Any]:
|
||||
"""Get broker transport options (e.g. Redis Sentinel) for Celery connections."""
|
||||
transport_options: CelerySentinelTransportDict | dict[str, Any]
|
||||
if dify_config.CELERY_USE_SENTINEL:
|
||||
transport_options = CelerySentinelTransportDict(
|
||||
master_name=dify_config.CELERY_SENTINEL_MASTER_NAME,
|
||||
sentinel_kwargs=_CelerySentinelKwargsDict(
|
||||
socket_timeout=dify_config.CELERY_SENTINEL_SOCKET_TIMEOUT,
|
||||
password=dify_config.CELERY_SENTINEL_PASSWORD,
|
||||
),
|
||||
)
|
||||
else:
|
||||
transport_options = {}
|
||||
|
||||
global_keyprefix = get_celery_redis_global_keyprefix()
|
||||
if global_keyprefix:
|
||||
transport_options["global_keyprefix"] = global_keyprefix
|
||||
|
||||
visibility = dify_config.CELERY_BROKER_VISIBILITY_TIMEOUT
|
||||
if isinstance(visibility, int) and not isinstance(visibility, bool):
|
||||
transport_options["visibility_timeout"] = visibility
|
||||
if dify_config.KNOWLEDGE_FS_BACKGROUND_WORKER_ENABLED is True:
|
||||
broker = dify_config.CELERY_BROKER_URL or ""
|
||||
if not broker:
|
||||
raise ValueError("KnowledgeFS workers require an explicit CELERY_BROKER_URL")
|
||||
if broker.startswith(("redis://", "rediss://", "sentinel://")) and (
|
||||
not isinstance(visibility, int)
|
||||
or visibility <= dify_config.KNOWLEDGE_FS_BACKGROUND_TASK_TIMEOUT_SECONDS + 30
|
||||
):
|
||||
raise ValueError("KnowledgeFS workers require CELERY_BROKER_VISIBILITY_TIMEOUT above their hard task limit")
|
||||
|
||||
return transport_options
|
||||
|
||||
|
||||
def get_celery_redis_global_keyprefix() -> str | None:
|
||||
"""Return the Redis transport prefix for Celery when namespace isolation is enabled."""
|
||||
normalized_prefix = normalize_redis_key_prefix(dify_config.REDIS_KEY_PREFIX)
|
||||
if not normalized_prefix:
|
||||
return None
|
||||
return f"{normalized_prefix}:"
|
||||
|
||||
|
||||
def init_app(app: DifyApp) -> Celery:
|
||||
class FlaskTask(Task):
|
||||
def __call__(self, *args: object, **kwargs: object) -> object:
|
||||
from core.logging.context import init_request_context
|
||||
|
||||
with app.app_context():
|
||||
# Initialize logging context for this task (similar to before_request in Flask)
|
||||
init_request_context()
|
||||
return self.run(*args, **kwargs)
|
||||
|
||||
broker_transport_options = get_celery_broker_transport_options()
|
||||
|
||||
celery_app = Celery(
|
||||
app.name,
|
||||
task_cls=FlaskTask,
|
||||
broker=dify_config.CELERY_BROKER_URL,
|
||||
backend=dify_config.CELERY_BACKEND,
|
||||
)
|
||||
|
||||
celery_app.conf.update(
|
||||
result_backend=dify_config.CELERY_RESULT_BACKEND,
|
||||
broker_transport_options=broker_transport_options,
|
||||
broker_connection_retry_on_startup=True,
|
||||
worker_log_format=dify_config.LOG_FORMAT,
|
||||
worker_task_log_format=dify_config.LOG_FORMAT,
|
||||
worker_hijack_root_logger=False,
|
||||
timezone=pytz.timezone(dify_config.LOG_TZ or "UTC"),
|
||||
task_ignore_result=True,
|
||||
task_annotations=dify_config.CELERY_TASK_ANNOTATIONS,
|
||||
task_routes={
|
||||
"tasks.trace_delivery_task.*": {"queue": dify_config.OPS_TRACE_QUEUE},
|
||||
"tasks.application_trace_task.*": {"queue": dify_config.OPS_TRACE_QUEUE},
|
||||
"schedule.collect_agent_sandbox_usage.collect_agent_sandbox_usage": {"queue": dify_config.OPS_TRACE_QUEUE},
|
||||
},
|
||||
)
|
||||
|
||||
if dify_config.CELERY_BACKEND == "redis":
|
||||
celery_app.conf.update(
|
||||
result_backend_transport_options=broker_transport_options,
|
||||
)
|
||||
|
||||
if "visibility_timeout" in broker_transport_options:
|
||||
celery_app.conf.visibility_timeout = broker_transport_options["visibility_timeout"]
|
||||
|
||||
# Apply SSL configuration if enabled
|
||||
ssl_options = get_celery_ssl_options()
|
||||
if ssl_options:
|
||||
celery_app.conf.update(
|
||||
broker_use_ssl=ssl_options,
|
||||
# Also apply SSL to the backend if it's Redis
|
||||
redis_backend_use_ssl=ssl_options if dify_config.CELERY_BACKEND == "redis" else None,
|
||||
)
|
||||
|
||||
if dify_config.LOG_FILE:
|
||||
celery_app.conf.update(
|
||||
worker_logfile=dify_config.LOG_FILE,
|
||||
)
|
||||
|
||||
celery_app.set_default()
|
||||
app.extensions["celery"] = celery_app
|
||||
setup_workflow_warm_shutdown_handler()
|
||||
|
||||
imports = [
|
||||
"schedule.collect_agent_sandbox_usage", # optional background provider accounting
|
||||
"tasks.async_workflow_tasks", # trigger workers
|
||||
"tasks.collect_agent_resources_task", # retired Agent resource collection
|
||||
"tasks.trigger_processing_tasks", # async trigger processing
|
||||
"tasks.generate_summary_index_task", # summary index generation
|
||||
"tasks.regenerate_summary_index_task", # summary index regeneration
|
||||
"tasks.rag_pipeline.rag_pipeline_run_task", # regular RAG pipeline execution
|
||||
"tasks.rag_pipeline.priority_rag_pipeline_run_task", # priority RAG pipeline execution
|
||||
"tasks.initialize_created_app_rbac_access_task", # app access initialization
|
||||
"tasks.install_default_plugins_task", # tenant default plugin installation
|
||||
"tasks.refresh_billing_vector_space_task", # billing vector-space cache refresh
|
||||
"tasks.workflow_run_archive_download_tasks", # workflow-run archive download preparation
|
||||
"tasks.im_message_inbox_tasks", # durable IM callback processing
|
||||
"tasks.human_input_im_card_tasks", # post-submission IM card updates
|
||||
"tasks.im_contact_sync_tasks", # durable IM Contact directory synchronization
|
||||
"tasks.knowledge_fs_initial_source_preview_tasks", # datasource previews use the standard dataset queue
|
||||
"tasks.knowledge_fs_agent_investigation_tasks",
|
||||
"tasks.knowledge_fs_failed_retrieval_tasks", # best-effort Workflow quality capture uses dataset workers
|
||||
"tasks.knowledge_fs_upgrade_tasks", # legacy Dataset upgrades use a dedicated queue and worker
|
||||
"tasks.knowledge_fs_background_tasks", # local-engine tasks on dedicated prefork queues
|
||||
"tasks.workflow_run_archive_deletion_tasks", # permanent monthly archive deletion
|
||||
"tasks.trace_delivery_task", # trace delivery and provider export retries
|
||||
"tasks.ops_trace_task", # retired endpoint; old workers must drain pre-upgrade tasks
|
||||
]
|
||||
day = dify_config.CELERY_BEAT_SCHEDULER_TIME
|
||||
|
||||
# if you add a new task, please add the switch to CeleryScheduleTasksConfig
|
||||
beat_schedule: dict[str, CeleryBeatScheduleEntry] = {}
|
||||
if dify_config.KNOWLEDGE_FS_BACKGROUND_WORKER_ENABLED is True:
|
||||
from services.knowledge_fs.background_contract import OPERATION_QUEUES, OPERATION_TASK
|
||||
|
||||
interval = dify_config.KNOWLEDGE_FS_BACKGROUND_POLL_INTERVAL_SECONDS
|
||||
for operation, queue in OPERATION_QUEUES.items():
|
||||
beat_schedule[f"knowledge_fs_background_{operation}"] = {
|
||||
"task": OPERATION_TASK,
|
||||
"schedule": timedelta(seconds=interval),
|
||||
"kwargs": {"operation": operation},
|
||||
# These are recoverable database sweeps, not document messages. Expired wakeups
|
||||
# must not replay a backlog of timer ticks after an extended worker outage.
|
||||
"options": {"queue": queue, "expires": max(30, interval * 2)},
|
||||
}
|
||||
from services.knowledge_fs.lifecycle_readiness import get_configured_knowledge_fs_lifecycle_worker_readiness
|
||||
|
||||
if get_configured_knowledge_fs_lifecycle_worker_readiness().ready:
|
||||
imports.extend(
|
||||
[
|
||||
"tasks.knowledge_fs_initial_source_tasks",
|
||||
"tasks.knowledge_fs_lifecycle_tasks",
|
||||
"tasks.knowledge_fs_source_import_tasks",
|
||||
]
|
||||
)
|
||||
beat_schedule["knowledge_fs_lifecycle_worker"] = {
|
||||
"task": "tasks.knowledge_fs_lifecycle_tasks.run_knowledge_fs_lifecycle_worker",
|
||||
"schedule": timedelta(seconds=dify_config.KNOWLEDGE_FS_LIFECYCLE_POLL_INTERVAL_SECONDS),
|
||||
}
|
||||
beat_schedule["knowledge_fs_staged_upload_cleanup"] = {
|
||||
"task": "tasks.knowledge_fs_lifecycle_tasks.cleanup_knowledge_fs_staged_uploads",
|
||||
"schedule": timedelta(seconds=dify_config.KNOWLEDGE_FS_LIFECYCLE_POLL_INTERVAL_SECONDS),
|
||||
}
|
||||
beat_schedule["knowledge_fs_upgrade_recovery"] = {
|
||||
"task": "tasks.knowledge_fs_upgrade_tasks.recover_stalled_knowledge_fs_upgrades",
|
||||
"schedule": timedelta(seconds=60),
|
||||
"options": {"expires": 60},
|
||||
}
|
||||
beat_schedule["knowledge_fs_upgrade_file_cleanup"] = {
|
||||
"task": "tasks.knowledge_fs_upgrade_tasks.cleanup_deferred_knowledge_fs_upgrade_files",
|
||||
"schedule": timedelta(seconds=dify_config.KNOWLEDGE_FS_LIFECYCLE_POLL_INTERVAL_SECONDS),
|
||||
}
|
||||
if dify_config.ENABLE_TRACE_PAYLOAD_SWEEP_TASK:
|
||||
beat_schedule["sweep_trace_payloads"] = {
|
||||
"task": "tasks.trace_delivery_task.sweep_trace_payloads",
|
||||
"schedule": crontab(minute="30", hour="3"),
|
||||
}
|
||||
if dify_config.OPS_AGENT_TRACE_ENABLED:
|
||||
imports.append("tasks.application_trace_task")
|
||||
if dify_config.OPS_AGENT_TRACE_ENABLED and dify_config.ENABLE_APPLICATION_TRACE_RECONCILE_TASK:
|
||||
beat_schedule["reconcile_application_traces"] = {
|
||||
"task": "tasks.application_trace_task.reconcile_application_traces",
|
||||
"schedule": timedelta(seconds=30),
|
||||
"options": {"expires": 25},
|
||||
}
|
||||
if dify_config.AGENT_SANDBOX_METERING_ENABLED:
|
||||
try:
|
||||
interval = int(dify_config.AGENT_SANDBOX_METERING_INTERVAL_SECONDS)
|
||||
if interval < 1:
|
||||
raise ValueError("collection interval must be positive")
|
||||
collection_schedule = timedelta(seconds=interval)
|
||||
except (ValueError, OverflowError):
|
||||
logger.warning("Skipping sandbox usage schedule: interval must be a valid positive number of seconds")
|
||||
else:
|
||||
beat_schedule["collect_agent_sandbox_usage"] = {
|
||||
"task": "schedule.collect_agent_sandbox_usage.collect_agent_sandbox_usage",
|
||||
"schedule": collection_schedule,
|
||||
"options": {"expires": interval},
|
||||
}
|
||||
if dify_config.ENABLE_CONVERSATION_CLEANUP_TASK:
|
||||
imports.append("tasks.delete_conversation_task")
|
||||
beat_schedule["conversation_cleanup_sweeper"] = {
|
||||
"task": "tasks.delete_conversation_task.sweep_deleted_conversations",
|
||||
"schedule": timedelta(minutes=dify_config.CONVERSATION_CLEANUP_TASK_INTERVAL),
|
||||
}
|
||||
if dify_config.ENABLE_CLEAN_EMBEDDING_CACHE_TASK:
|
||||
imports.append("schedule.clean_embedding_cache_task")
|
||||
beat_schedule["clean_embedding_cache_task"] = {
|
||||
"task": "schedule.clean_embedding_cache_task.clean_embedding_cache_task",
|
||||
"schedule": crontab(minute="0", hour="2", day_of_month=f"*/{day}"),
|
||||
}
|
||||
if dify_config.ENABLE_CLEAN_UNUSED_DATASETS_TASK:
|
||||
imports.append("schedule.clean_unused_datasets_task")
|
||||
beat_schedule["clean_unused_datasets_task"] = {
|
||||
"task": "schedule.clean_unused_datasets_task.clean_unused_datasets_task",
|
||||
"schedule": crontab(minute="0", hour="3", day_of_month=f"*/{day}"),
|
||||
}
|
||||
if dify_config.ENABLE_CREATE_TIDB_SERVERLESS_TASK:
|
||||
imports.append("schedule.create_tidb_serverless_task")
|
||||
beat_schedule["create_tidb_serverless_task"] = {
|
||||
"task": "schedule.create_tidb_serverless_task.create_tidb_serverless_task",
|
||||
"schedule": crontab(minute="0", hour="*"),
|
||||
}
|
||||
if dify_config.ENABLE_UPDATE_TIDB_SERVERLESS_STATUS_TASK:
|
||||
imports.append("schedule.update_tidb_serverless_status_task")
|
||||
beat_schedule["update_tidb_serverless_status_task"] = {
|
||||
"task": "schedule.update_tidb_serverless_status_task.update_tidb_serverless_status_task",
|
||||
"schedule": timedelta(minutes=10),
|
||||
}
|
||||
if dify_config.ENABLE_CLEAN_MESSAGES:
|
||||
imports.append("schedule.clean_messages")
|
||||
beat_schedule["clean_messages"] = {
|
||||
"task": "schedule.clean_messages.clean_messages",
|
||||
"schedule": crontab(minute="0", hour="4", day_of_month=f"*/{day}"),
|
||||
}
|
||||
if dify_config.ENABLE_MAIL_CLEAN_DOCUMENT_NOTIFY_TASK:
|
||||
imports.append("schedule.mail_clean_document_notify_task")
|
||||
beat_schedule["mail_clean_document_notify_task"] = {
|
||||
"task": "schedule.mail_clean_document_notify_task.mail_clean_document_notify_task",
|
||||
"schedule": crontab(minute="0", hour="10", day_of_week="1"),
|
||||
}
|
||||
if dify_config.ENABLE_DATASETS_QUEUE_MONITOR:
|
||||
imports.append("schedule.queue_monitor_task")
|
||||
beat_schedule["datasets-queue-monitor"] = {
|
||||
"task": "schedule.queue_monitor_task.queue_monitor_task",
|
||||
"schedule": timedelta(minutes=dify_config.QUEUE_MONITOR_INTERVAL or 30),
|
||||
}
|
||||
if dify_config.ENABLE_HUMAN_INPUT_TIMEOUT_TASK:
|
||||
imports.append("tasks.human_input_timeout_tasks")
|
||||
beat_schedule["human_input_form_timeout"] = {
|
||||
"task": "human_input_form_timeout.check_and_resume",
|
||||
"schedule": timedelta(minutes=dify_config.HUMAN_INPUT_TIMEOUT_TASK_INTERVAL),
|
||||
}
|
||||
if dify_config.ENABLE_CHECK_UPGRADABLE_PLUGIN_TASK and dify_config.MARKETPLACE_ENABLED:
|
||||
imports.extend(("schedule.check_upgradable_plugin_task", "tasks.process_tenant_plugin_autoupgrade_check_task"))
|
||||
beat_schedule["check_upgradable_plugin_task"] = {
|
||||
"task": "schedule.check_upgradable_plugin_task.check_upgradable_plugin_task",
|
||||
"schedule": crontab(minute="*/15"),
|
||||
}
|
||||
if dify_config.WORKFLOW_LOG_CLEANUP_ENABLED:
|
||||
# 2:00 AM every day
|
||||
imports.append("schedule.clean_workflow_runlogs_precise")
|
||||
beat_schedule["clean_workflow_runlogs_precise"] = {
|
||||
"task": "schedule.clean_workflow_runlogs_precise.clean_workflow_runlogs_precise",
|
||||
"schedule": crontab(minute="0", hour="2"),
|
||||
}
|
||||
if dify_config.ENABLE_WORKFLOW_RUN_CLEANUP_TASK:
|
||||
# for saas only
|
||||
imports.append("schedule.clean_workflow_runs_task")
|
||||
beat_schedule["clean_workflow_runs_task"] = {
|
||||
"task": "schedule.clean_workflow_runs_task.clean_workflow_runs_task",
|
||||
"schedule": crontab(minute="0", hour="0"),
|
||||
}
|
||||
if dify_config.ENABLE_CLEAN_OAUTH_ACCESS_TOKENS_TASK:
|
||||
imports.append("schedule.clean_oauth_access_tokens_task")
|
||||
beat_schedule["clean_oauth_access_tokens_task"] = {
|
||||
"task": "schedule.clean_oauth_access_tokens_task.clean_oauth_access_tokens_task",
|
||||
"schedule": crontab(minute="0", hour="5", day_of_month=f"*/{day}"),
|
||||
}
|
||||
if dify_config.ENABLE_WORKFLOW_SCHEDULE_POLLER_TASK:
|
||||
imports.append("schedule.workflow_schedule_task")
|
||||
beat_schedule["workflow_schedule_task"] = {
|
||||
"task": "schedule.workflow_schedule_task.poll_workflow_schedules",
|
||||
"schedule": timedelta(minutes=dify_config.WORKFLOW_SCHEDULE_POLLER_INTERVAL),
|
||||
}
|
||||
if dify_config.ENABLE_TRIGGER_PROVIDER_REFRESH_TASK:
|
||||
imports.append("schedule.trigger_provider_refresh_task")
|
||||
beat_schedule["trigger_provider_refresh"] = {
|
||||
"task": "schedule.trigger_provider_refresh_task.trigger_provider_refresh",
|
||||
"schedule": timedelta(minutes=dify_config.TRIGGER_PROVIDER_REFRESH_INTERVAL),
|
||||
}
|
||||
|
||||
if dify_config.ENABLE_API_TOKEN_LAST_USED_UPDATE_TASK:
|
||||
imports.append("schedule.update_api_token_last_used_task")
|
||||
beat_schedule["batch_update_api_token_last_used"] = {
|
||||
"task": "schedule.update_api_token_last_used_task.batch_update_api_token_last_used",
|
||||
"schedule": timedelta(minutes=dify_config.API_TOKEN_LAST_USED_UPDATE_INTERVAL),
|
||||
}
|
||||
|
||||
if (
|
||||
dify_config.DEPLOYMENT_EDITION == DeploymentEdition.COMMUNITY
|
||||
and not dify_config.DISABLE_TELEMETRY
|
||||
and not dify_config.DO_NOT_TRACK
|
||||
and not dify_config.CI
|
||||
):
|
||||
imports.append("tasks.community_telemetry_task")
|
||||
beat_schedule["community_telemetry_heartbeat"] = {
|
||||
"task": "community_telemetry.send_heartbeat",
|
||||
"schedule": timedelta(minutes=dify_config.TELEMETRY_HEARTBEAT_INTERVAL_MINUTES),
|
||||
}
|
||||
|
||||
if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE and dify_config.ENTERPRISE_TELEMETRY_ENABLED:
|
||||
imports.append("tasks.enterprise_telemetry_task")
|
||||
celery_app.conf.update(beat_schedule=beat_schedule, imports=imports)
|
||||
|
||||
return celery_app
|
||||
@@ -0,0 +1,9 @@
|
||||
from core.extension.extension import Extension
|
||||
from dify_app import DifyApp
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
code_based_extension.init()
|
||||
|
||||
|
||||
code_based_extension = Extension()
|
||||
@@ -0,0 +1,97 @@
|
||||
from dify_app import DifyApp
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
from commands import (
|
||||
add_qdrant_index,
|
||||
archive_workflow_runs,
|
||||
archive_workflow_runs_plan,
|
||||
backfill_plugin_auto_upgrade,
|
||||
backfill_workflow_run_archive_bundles,
|
||||
clean_expired_messages,
|
||||
clean_workflow_runs,
|
||||
cleanup_orphaned_draft_variables,
|
||||
clear_free_plan_tenant_expired_logs,
|
||||
clear_orphaned_file_records,
|
||||
convert_to_agent_apps,
|
||||
create_tenant,
|
||||
data_migrate,
|
||||
delete_archived_workflow_runs,
|
||||
export_app_messages,
|
||||
export_migration_data,
|
||||
export_migration_data_template,
|
||||
extract_plugins,
|
||||
extract_unique_plugins,
|
||||
file_usage,
|
||||
fix_app_site_missing,
|
||||
import_migration_data,
|
||||
install_plugins,
|
||||
install_rag_pipeline_plugins,
|
||||
knowledge_fs_control_space,
|
||||
migrate_agent_permissions_to_rbac,
|
||||
migrate_data_for_plugin,
|
||||
migrate_dataset_permissions_to_rbac,
|
||||
migrate_member_roles_to_rbac,
|
||||
migrate_oss,
|
||||
migration_data_wizard,
|
||||
old_metadata_migration,
|
||||
remove_orphaned_files_on_storage,
|
||||
reset_email,
|
||||
reset_encrypt_key_pair,
|
||||
reset_password,
|
||||
restore_workflow_runs,
|
||||
setup_datasource_oauth_client,
|
||||
setup_system_tool_oauth_client,
|
||||
setup_system_trigger_oauth_client,
|
||||
transform_datasource_credentials,
|
||||
upgrade_db,
|
||||
vdb_migrate,
|
||||
)
|
||||
|
||||
cmds_to_register = [
|
||||
reset_password,
|
||||
reset_email,
|
||||
reset_encrypt_key_pair,
|
||||
vdb_migrate,
|
||||
convert_to_agent_apps,
|
||||
add_qdrant_index,
|
||||
create_tenant,
|
||||
data_migrate,
|
||||
upgrade_db,
|
||||
fix_app_site_missing,
|
||||
migrate_data_for_plugin,
|
||||
migrate_dataset_permissions_to_rbac,
|
||||
migrate_member_roles_to_rbac,
|
||||
migrate_agent_permissions_to_rbac,
|
||||
backfill_plugin_auto_upgrade,
|
||||
extract_plugins,
|
||||
extract_unique_plugins,
|
||||
install_plugins,
|
||||
old_metadata_migration,
|
||||
clear_free_plan_tenant_expired_logs,
|
||||
clear_orphaned_file_records,
|
||||
remove_orphaned_files_on_storage,
|
||||
file_usage,
|
||||
setup_system_tool_oauth_client,
|
||||
setup_system_trigger_oauth_client,
|
||||
cleanup_orphaned_draft_variables,
|
||||
migrate_oss,
|
||||
setup_datasource_oauth_client,
|
||||
transform_datasource_credentials,
|
||||
install_rag_pipeline_plugins,
|
||||
archive_workflow_runs_plan,
|
||||
archive_workflow_runs,
|
||||
backfill_workflow_run_archive_bundles,
|
||||
delete_archived_workflow_runs,
|
||||
restore_workflow_runs,
|
||||
clean_workflow_runs,
|
||||
clean_expired_messages,
|
||||
export_app_messages,
|
||||
export_migration_data,
|
||||
export_migration_data_template,
|
||||
import_migration_data,
|
||||
migration_data_wizard,
|
||||
knowledge_fs_control_space,
|
||||
]
|
||||
for cmd in cmds_to_register:
|
||||
app.cli.add_command(cmd)
|
||||
@@ -0,0 +1,13 @@
|
||||
from configs import dify_config
|
||||
from dify_app import DifyApp
|
||||
|
||||
|
||||
def is_enabled() -> bool:
|
||||
return dify_config.API_COMPRESSION_ENABLED
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
from flask_compress import Compress
|
||||
|
||||
compress = Compress()
|
||||
compress.init_app(app)
|
||||
@@ -0,0 +1,62 @@
|
||||
import logging
|
||||
|
||||
import gevent
|
||||
from sqlalchemy import event
|
||||
from sqlalchemy.pool import Pool
|
||||
|
||||
from dify_app import DifyApp
|
||||
from models.engine import db
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Global flag to avoid duplicate registration of event listener
|
||||
_gevent_compatibility_setup: bool = False
|
||||
|
||||
|
||||
def _safe_rollback(connection):
|
||||
"""Safely rollback database connection.
|
||||
|
||||
Args:
|
||||
connection: Database connection object
|
||||
"""
|
||||
try:
|
||||
connection.rollback()
|
||||
except Exception: # pylint: disable=broad-exception-caught
|
||||
logger.exception("Failed to rollback connection")
|
||||
|
||||
|
||||
def _setup_gevent_compatibility():
|
||||
global _gevent_compatibility_setup # pylint: disable=global-statement
|
||||
|
||||
# Avoid duplicate registration
|
||||
if _gevent_compatibility_setup:
|
||||
return
|
||||
|
||||
@event.listens_for(Pool, "reset")
|
||||
def _safe_reset(dbapi_connection, connection_record, reset_state):
|
||||
if reset_state.terminate_only:
|
||||
return
|
||||
|
||||
# Safe rollback for connection
|
||||
try:
|
||||
hub = gevent.get_hub()
|
||||
if hasattr(hub, "loop") and getattr(hub.loop, "in_callback", False):
|
||||
gevent.spawn_later(0, lambda: _safe_rollback(dbapi_connection))
|
||||
else:
|
||||
_safe_rollback(dbapi_connection)
|
||||
except (AttributeError, ImportError):
|
||||
_safe_rollback(dbapi_connection)
|
||||
|
||||
_gevent_compatibility_setup = True
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
db.init_app(app)
|
||||
_setup_gevent_compatibility()
|
||||
|
||||
# Eagerly build the engine so pool_size/max_overflow/etc. come from config
|
||||
try:
|
||||
with app.app_context():
|
||||
_ = db.engine # triggers engine creation with the configured options
|
||||
except Exception:
|
||||
logger.exception("Failed to initialize SQLAlchemy engine during app startup")
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Flask extension for enterprise telemetry lifecycle management.
|
||||
|
||||
Initializes the EnterpriseExporter singleton during ``create_app()``
|
||||
(single-threaded), registers blinker event handlers, and hooks atexit
|
||||
for graceful shutdown.
|
||||
|
||||
Skipped entirely outside the Enterprise edition or when ``ENTERPRISE_TELEMETRY_ENABLED``
|
||||
is false (``is_enabled()`` gate).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from configs import dify_config
|
||||
from enums import DeploymentEdition
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from dify_app import DifyApp
|
||||
from enterprise.telemetry.exporter import EnterpriseExporter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_exporter: EnterpriseExporter | None = None
|
||||
|
||||
|
||||
def is_enabled() -> bool:
|
||||
return bool(
|
||||
dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE and dify_config.ENTERPRISE_TELEMETRY_ENABLED
|
||||
)
|
||||
|
||||
|
||||
def init_app(app: DifyApp) -> None:
|
||||
global _exporter
|
||||
|
||||
if not is_enabled():
|
||||
return
|
||||
|
||||
from enterprise.telemetry.exporter import EnterpriseExporter
|
||||
|
||||
_exporter = EnterpriseExporter(dify_config)
|
||||
atexit.register(_exporter.shutdown)
|
||||
|
||||
# Import to trigger @signal.connect decorator registration
|
||||
import enterprise.telemetry.event_handlers # noqa: F401 # type: ignore[reportUnusedImport]
|
||||
|
||||
logger.info("Enterprise telemetry initialized")
|
||||
|
||||
|
||||
def get_enterprise_exporter() -> EnterpriseExporter | None:
|
||||
return _exporter
|
||||
@@ -0,0 +1,54 @@
|
||||
from typing import Protocol, cast
|
||||
|
||||
from fastopenapi.routers import FlaskRouter
|
||||
from flask_cors import CORS
|
||||
|
||||
from configs import dify_config
|
||||
from controllers.fastopenapi import console_router
|
||||
from dify_app import DifyApp
|
||||
from extensions.ext_blueprints import AUTHENTICATED_HEADERS, EXPOSED_HEADERS
|
||||
|
||||
DOCS_PREFIX = "/fastopenapi"
|
||||
|
||||
|
||||
class SupportsIncludeRouter(Protocol):
|
||||
def include_router(self, router: object, *, prefix: str = "") -> None: ...
|
||||
|
||||
|
||||
def init_app(app: DifyApp) -> None:
|
||||
docs_enabled = dify_config.SWAGGER_UI_ENABLED
|
||||
docs_url = f"{DOCS_PREFIX}/docs" if docs_enabled else None
|
||||
redoc_url = f"{DOCS_PREFIX}/redoc" if docs_enabled else None
|
||||
openapi_url = f"{DOCS_PREFIX}/openapi.json" if docs_enabled else None
|
||||
|
||||
router = FlaskRouter(
|
||||
app=app,
|
||||
docs_url=docs_url,
|
||||
redoc_url=redoc_url,
|
||||
openapi_url=openapi_url,
|
||||
openapi_version="3.1.0",
|
||||
title="Dify API (FastOpenAPI PoC)",
|
||||
version="1.0",
|
||||
description="FastOpenAPI proof of concept for Dify API",
|
||||
)
|
||||
|
||||
# Ensure route decorators are evaluated.
|
||||
import controllers.console.init_validate as init_validate_module
|
||||
import controllers.console.system as system_module
|
||||
from controllers.console import remote_files, setup
|
||||
|
||||
_ = init_validate_module
|
||||
_ = system_module
|
||||
_ = remote_files
|
||||
_ = setup
|
||||
|
||||
cast(SupportsIncludeRouter, router).include_router(console_router, prefix="/console/api")
|
||||
CORS(
|
||||
app,
|
||||
resources={r"/console/api/.*": {"origins": dify_config.CONSOLE_CORS_ALLOW_ORIGINS}},
|
||||
supports_credentials=True,
|
||||
allow_headers=list(AUTHENTICATED_HEADERS),
|
||||
methods=["GET", "PUT", "POST", "DELETE", "OPTIONS", "PATCH"],
|
||||
expose_headers=list(EXPOSED_HEADERS),
|
||||
)
|
||||
app.extensions["fastopenapi"] = router
|
||||
@@ -0,0 +1,8 @@
|
||||
from core.hosting_configuration import HostingConfiguration
|
||||
from dify_app import DifyApp
|
||||
|
||||
hosting_configuration = HostingConfiguration()
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
hosting_configuration.init_app(app)
|
||||
@@ -0,0 +1,5 @@
|
||||
from dify_app import DifyApp
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
from events import event_handlers # noqa: F401
|
||||
@@ -0,0 +1,50 @@
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from configs import dify_config
|
||||
from dify_app import DifyApp
|
||||
from libs.key_providers.base import BaseKeyProvider
|
||||
from libs.key_providers.key_provider_type import KeyProviderType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class KeyProviderManager:
|
||||
_provider: BaseKeyProvider | None = None
|
||||
|
||||
def init_app(self, app: Flask):
|
||||
with app.app_context():
|
||||
self._provider = self._build_provider()
|
||||
|
||||
@property
|
||||
def provider(self) -> BaseKeyProvider:
|
||||
if self._provider is None:
|
||||
self._provider = self._build_provider()
|
||||
return self._provider
|
||||
|
||||
def _build_provider(self) -> BaseKeyProvider:
|
||||
provider_factory = self.get_provider_factory(dify_config.KEY_PROVIDER_TYPE)
|
||||
return provider_factory()
|
||||
|
||||
@staticmethod
|
||||
def get_provider_factory(provider_type: str) -> Callable[[], BaseKeyProvider]:
|
||||
match provider_type:
|
||||
case KeyProviderType.LOCAL:
|
||||
from libs.key_providers.rsa_key_provider import RSAKeyProvider
|
||||
|
||||
return RSAKeyProvider
|
||||
case KeyProviderType.AZURE_KEYVAULT:
|
||||
from libs.key_providers.azure_keyvault_key_provider import AzureKeyVaultKeyProvider
|
||||
|
||||
return AzureKeyVaultKeyProvider
|
||||
case _:
|
||||
raise ValueError(f"unsupported key provider type {provider_type}")
|
||||
|
||||
|
||||
key_provider_manager = KeyProviderManager()
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
key_provider_manager.init_app(app)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Production assembly for KnowledgeFS database-backed metrics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from core.db.session_factory import session_factory
|
||||
from repositories.sqlalchemy_knowledge_fs_control_space_state_metrics import (
|
||||
SQLAlchemyKnowledgeFSControlSpaceStateCountReader,
|
||||
)
|
||||
from services.knowledge_fs.observability import get_knowledge_fs_operational_metrics
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def init_app(app: Flask) -> None:
|
||||
del app
|
||||
try:
|
||||
reader = SQLAlchemyKnowledgeFSControlSpaceStateCountReader(session_factory.get_session_maker())
|
||||
get_knowledge_fs_operational_metrics().register_control_space_state_gauge(reader)
|
||||
except Exception:
|
||||
logger.exception("KnowledgeFS operational metric registration failed; continuing application startup")
|
||||
@@ -0,0 +1,147 @@
|
||||
"""Logging extension for Dify Flask application."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from typing import override
|
||||
|
||||
from configs import dify_config
|
||||
from dify_app import DifyApp
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
"""Initialize logging with support for text or JSON format."""
|
||||
log_handlers: list[logging.Handler] = []
|
||||
|
||||
# File handler
|
||||
log_file = dify_config.LOG_FILE
|
||||
if log_file:
|
||||
log_dir = os.path.dirname(log_file)
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
log_handlers.append(
|
||||
RotatingFileHandler(
|
||||
filename=log_file,
|
||||
maxBytes=dify_config.LOG_FILE_MAX_SIZE * 1024 * 1024,
|
||||
backupCount=dify_config.LOG_FILE_BACKUP_COUNT,
|
||||
)
|
||||
)
|
||||
|
||||
# Console handler
|
||||
sh = logging.StreamHandler(sys.stdout)
|
||||
log_handlers.append(sh)
|
||||
|
||||
# Apply filters to all handlers
|
||||
from core.logging.filters import IdentityContextFilter, TraceContextFilter
|
||||
|
||||
for handler in log_handlers:
|
||||
handler.addFilter(TraceContextFilter())
|
||||
handler.addFilter(IdentityContextFilter())
|
||||
|
||||
# Configure formatter based on format type
|
||||
formatter = _create_formatter()
|
||||
for handler in log_handlers:
|
||||
handler.setFormatter(formatter)
|
||||
|
||||
# Configure root logger
|
||||
logging.basicConfig(
|
||||
level=dify_config.LOG_LEVEL,
|
||||
handlers=log_handlers,
|
||||
force=True,
|
||||
)
|
||||
|
||||
# Disable propagation for noisy loggers to avoid duplicate logs
|
||||
logging.getLogger("sqlalchemy.engine").propagate = False
|
||||
|
||||
# Apply timezone if specified (only for text format)
|
||||
if dify_config.LOG_OUTPUT_FORMAT == "text":
|
||||
_apply_timezone(log_handlers)
|
||||
|
||||
|
||||
def _create_formatter() -> logging.Formatter:
|
||||
"""Create appropriate formatter based on configuration."""
|
||||
if dify_config.LOG_OUTPUT_FORMAT == "json":
|
||||
from core.logging.structured_formatter import StructuredJSONFormatter
|
||||
|
||||
return StructuredJSONFormatter()
|
||||
else:
|
||||
# Text format - use existing pattern with backward compatible formatter
|
||||
return _TextFormatter(
|
||||
fmt=dify_config.LOG_FORMAT,
|
||||
datefmt=dify_config.LOG_DATEFORMAT,
|
||||
)
|
||||
|
||||
|
||||
def _apply_timezone(handlers: list[logging.Handler]):
|
||||
"""Apply timezone conversion to text formatters."""
|
||||
log_tz = dify_config.LOG_TZ
|
||||
if log_tz:
|
||||
from datetime import datetime
|
||||
|
||||
import pytz
|
||||
|
||||
timezone = pytz.timezone(log_tz)
|
||||
|
||||
def time_converter(seconds):
|
||||
return datetime.fromtimestamp(seconds, tz=timezone).timetuple()
|
||||
|
||||
for handler in handlers:
|
||||
if handler.formatter:
|
||||
handler.formatter.converter = time_converter # type: ignore[attr-defined]
|
||||
|
||||
|
||||
class _TextFormatter(logging.Formatter):
|
||||
"""Text formatter that ensures trace_id and req_id are always present."""
|
||||
|
||||
@override
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
if not hasattr(record, "req_id"):
|
||||
record.req_id = ""
|
||||
if not hasattr(record, "trace_id"):
|
||||
record.trace_id = ""
|
||||
if not hasattr(record, "span_id"):
|
||||
record.span_id = ""
|
||||
return super().format(record)
|
||||
|
||||
|
||||
def get_request_id() -> str:
|
||||
"""Get request ID for current request context.
|
||||
|
||||
Deprecated: Use core.logging.context.get_request_id() directly.
|
||||
"""
|
||||
from core.logging.context import get_request_id as _get_request_id
|
||||
|
||||
return _get_request_id()
|
||||
|
||||
|
||||
# Backward compatibility aliases
|
||||
class RequestIdFilter(logging.Filter):
|
||||
"""Deprecated: Use TraceContextFilter from core.logging.filters instead."""
|
||||
|
||||
@override
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
from core.logging.context import get_request_id as _get_request_id
|
||||
from core.logging.context import get_trace_id as _get_trace_id
|
||||
|
||||
record.req_id = _get_request_id()
|
||||
record.trace_id = _get_trace_id()
|
||||
return True
|
||||
|
||||
|
||||
class RequestIdFormatter(logging.Formatter):
|
||||
"""Deprecated: Use _TextFormatter instead."""
|
||||
|
||||
@override
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
if not hasattr(record, "req_id"):
|
||||
record.req_id = ""
|
||||
if not hasattr(record, "trace_id"):
|
||||
record.trace_id = ""
|
||||
return super().format(record)
|
||||
|
||||
|
||||
def apply_request_id_formatter():
|
||||
"""Deprecated: Formatter is now applied in init_app."""
|
||||
for handler in logging.root.handlers:
|
||||
if handler.formatter:
|
||||
handler.formatter = RequestIdFormatter(dify_config.LOG_FORMAT, dify_config.LOG_DATEFORMAT)
|
||||
@@ -0,0 +1,209 @@
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from typing import assert_never, cast, override
|
||||
|
||||
import flask_login
|
||||
from flask import Flask, Request, Response, current_app, request
|
||||
from flask_login import user_loaded_from_request, user_logged_in
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
from werkzeug.exceptions import NotFound, Unauthorized
|
||||
|
||||
from configs import dify_config
|
||||
from constants import HEADER_NAME_APP_CODE
|
||||
from core.db.session_factory import session_factory
|
||||
from core.logging.context import set_identity_context
|
||||
from dify_app import DifyApp
|
||||
from libs.passport import PassportService
|
||||
from libs.token import (
|
||||
extract_access_token,
|
||||
extract_console_cookie_token,
|
||||
extract_webapp_passport,
|
||||
is_admin_api_key_request,
|
||||
)
|
||||
from models import Account, Tenant, TenantAccountJoin
|
||||
from models.enums import EndUserType
|
||||
from models.model import AppMCPServer, EndUser
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
type LoginUser = Account | EndUser
|
||||
type AccountLoader = Callable[[str], Account | None]
|
||||
|
||||
|
||||
def bind_account_loader(app: Flask, loader: AccountLoader) -> None:
|
||||
app.extensions["account_identity_loader"] = loader
|
||||
|
||||
|
||||
def load_account(account_id: str) -> Account | None:
|
||||
return cast(AccountLoader, current_app.extensions["account_identity_loader"])(account_id)
|
||||
|
||||
|
||||
class DifyLoginManager(flask_login.LoginManager):
|
||||
"""Project-specific Flask-Login manager with a stable unauthorized contract.
|
||||
|
||||
Dify registers `unauthorized_handler` below to always return a JSON `Response`.
|
||||
Overriding this method lets callers rely on that narrower return type instead of
|
||||
Flask-Login's broader callback contract.
|
||||
"""
|
||||
|
||||
@override
|
||||
def unauthorized(self) -> Response:
|
||||
"""Return the registered unauthorized handler result as a Flask `Response`."""
|
||||
return cast(Response, super().unauthorized())
|
||||
|
||||
def load_user_from_request_context(self) -> None:
|
||||
"""Populate Flask-Login's request-local user cache for the current request."""
|
||||
self._load_user()
|
||||
|
||||
|
||||
login_manager = DifyLoginManager()
|
||||
|
||||
|
||||
# Flask-Login configuration
|
||||
@login_manager.request_loader
|
||||
def load_user_from_request(request_from_flask_login: Request) -> LoginUser | None:
|
||||
"""Load user based on the request."""
|
||||
with session_factory.create_session() as session:
|
||||
return _load_user_from_request(request_from_flask_login, session)
|
||||
|
||||
|
||||
def _load_user_from_request(request_from_flask_login: Request, session: Session) -> LoginUser | None:
|
||||
"""Load user based on the request using an explicit database session."""
|
||||
del request_from_flask_login
|
||||
|
||||
# Skip authentication for documentation endpoints
|
||||
if dify_config.SWAGGER_UI_ENABLED and request.path.endswith((dify_config.SWAGGER_UI_PATH, "/swagger.json")):
|
||||
return None
|
||||
|
||||
auth_token = extract_access_token(request)
|
||||
|
||||
# Check for admin API key authentication first
|
||||
if is_admin_api_key_request(request):
|
||||
workspace_id = request.headers.get("X-WORKSPACE-ID")
|
||||
if workspace_id:
|
||||
tenant_account_join = session.execute(
|
||||
select(Tenant, TenantAccountJoin).where(
|
||||
Tenant.id == workspace_id,
|
||||
TenantAccountJoin.tenant_id == Tenant.id,
|
||||
TenantAccountJoin.role == "owner",
|
||||
)
|
||||
).one_or_none()
|
||||
if tenant_account_join:
|
||||
tenant, ta = tenant_account_join
|
||||
account = session.scalar(select(Account).where(Account.id == ta.account_id))
|
||||
if account:
|
||||
account.set_current_tenant_with_session(tenant, session=session)
|
||||
return account
|
||||
|
||||
if request.blueprint in {"console", "inner_api"}:
|
||||
if not auth_token:
|
||||
raise Unauthorized("Invalid Authorization token.")
|
||||
decoded = PassportService().verify(auth_token)
|
||||
user_id = decoded.get("user_id")
|
||||
source = decoded.get("token_source")
|
||||
if source:
|
||||
raise Unauthorized("Invalid Authorization token.")
|
||||
if not user_id:
|
||||
raise Unauthorized("Invalid Authorization token.")
|
||||
|
||||
logged_in_account = load_account(user_id)
|
||||
return logged_in_account
|
||||
elif request.blueprint == "openapi":
|
||||
# Account-branch device-flow approval routes (approve / deny /
|
||||
# approval-context) sit under @login_required and authenticate via
|
||||
# the console session cookie. Cookie-only on purpose — bearer
|
||||
# tokens (dfoa_/dfoe_) live on the Authorization header and are
|
||||
# validated by AppPipeline, not flask-login.
|
||||
cookie_token = extract_console_cookie_token(request)
|
||||
if not cookie_token:
|
||||
return None
|
||||
try:
|
||||
decoded = PassportService().verify(cookie_token)
|
||||
except Exception:
|
||||
return None
|
||||
user_id = decoded.get("user_id")
|
||||
source = decoded.get("token_source")
|
||||
if source or not user_id:
|
||||
return None
|
||||
return load_account(user_id)
|
||||
elif request.blueprint == "web":
|
||||
app_code = request.headers.get(HEADER_NAME_APP_CODE)
|
||||
webapp_token = extract_webapp_passport(app_code, request) if app_code else None
|
||||
|
||||
if webapp_token:
|
||||
decoded = PassportService().verify(webapp_token)
|
||||
end_user_id = decoded.get("end_user_id")
|
||||
if not end_user_id:
|
||||
raise Unauthorized("Invalid Authorization token.")
|
||||
end_user = session.scalar(select(EndUser).where(EndUser.id == end_user_id))
|
||||
if not end_user:
|
||||
raise NotFound("End user not found.")
|
||||
return end_user
|
||||
else:
|
||||
if not auth_token:
|
||||
raise Unauthorized("Invalid Authorization token.")
|
||||
decoded = PassportService().verify(auth_token)
|
||||
end_user_id = decoded.get("end_user_id")
|
||||
if end_user_id:
|
||||
end_user = session.scalar(select(EndUser).where(EndUser.id == end_user_id))
|
||||
if not end_user:
|
||||
raise NotFound("End user not found.")
|
||||
return end_user
|
||||
else:
|
||||
raise Unauthorized("Invalid Authorization token for web API.")
|
||||
elif request.blueprint == "mcp":
|
||||
server_code = request.view_args.get("server_code") if request.view_args else None
|
||||
if not server_code:
|
||||
raise Unauthorized("Invalid Authorization token.")
|
||||
app_mcp_server = session.scalar(select(AppMCPServer).where(AppMCPServer.server_code == server_code).limit(1))
|
||||
if not app_mcp_server:
|
||||
raise NotFound("App MCP server not found.")
|
||||
end_user = session.scalar(
|
||||
select(EndUser).where(EndUser.session_id == app_mcp_server.id, EndUser.type == EndUserType.MCP).limit(1)
|
||||
)
|
||||
if not end_user:
|
||||
raise NotFound("End user not found.")
|
||||
return end_user
|
||||
|
||||
return None
|
||||
|
||||
|
||||
@user_logged_in.connect
|
||||
@user_loaded_from_request.connect
|
||||
def on_user_logged_in(_sender: object, user: LoginUser) -> None:
|
||||
"""Snapshot authenticated identity into the side-effect-free logging context.
|
||||
|
||||
Note: AccountIdentityGateway.load_user will populate user.current_tenant_id
|
||||
through the load_user method, which calls account.set_tenant_id_with_session().
|
||||
"""
|
||||
set_identity_context()
|
||||
try:
|
||||
match user:
|
||||
case Account():
|
||||
set_identity_context(tenant_id=user.current_tenant_id, user_id=user.id, user_type="account")
|
||||
case EndUser():
|
||||
set_identity_context(tenant_id=user.tenant_id, user_id=user.id, user_type=user.type or "end_user")
|
||||
case _ as unreachable:
|
||||
assert_never(unreachable)
|
||||
except Exception:
|
||||
# Logging enrichment must never make authentication fail.
|
||||
logger.exception("Failed to set logging identity context")
|
||||
return
|
||||
|
||||
|
||||
@login_manager.unauthorized_handler
|
||||
def unauthorized_handler() -> Response:
|
||||
"""Handle unauthorized requests."""
|
||||
# Keep this as a concrete `Response`; `DifyLoginManager.unauthorized()` narrows
|
||||
# Flask-Login's callback contract based on this override.
|
||||
return Response(
|
||||
json.dumps({"code": "unauthorized", "message": "Unauthorized.", "status": 401}),
|
||||
status=401,
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
|
||||
def init_app(app: DifyApp) -> None:
|
||||
login_manager.init_app(app)
|
||||
@@ -0,0 +1,94 @@
|
||||
"""
|
||||
Logstore extension for Dify application.
|
||||
|
||||
This extension initializes the logstore (Aliyun SLS) on application startup,
|
||||
creating necessary projects, logstores, and indexes if they don't exist.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from configs import dify_config
|
||||
from dify_app import DifyApp
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def is_enabled() -> bool:
|
||||
"""
|
||||
Check if logstore extension is enabled.
|
||||
|
||||
Logstore is considered enabled when:
|
||||
1. All required Aliyun SLS environment variables are set
|
||||
2. At least one repository configuration points to a logstore implementation
|
||||
|
||||
Returns:
|
||||
True if logstore should be initialized, False otherwise
|
||||
"""
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
# Check if Aliyun SLS connection parameters are configured
|
||||
required_vars = [
|
||||
"ALIYUN_SLS_ACCESS_KEY_ID",
|
||||
"ALIYUN_SLS_ACCESS_KEY_SECRET",
|
||||
"ALIYUN_SLS_ENDPOINT",
|
||||
"ALIYUN_SLS_REGION",
|
||||
"ALIYUN_SLS_PROJECT_NAME",
|
||||
]
|
||||
|
||||
sls_vars_set = all(os.environ.get(var) for var in required_vars)
|
||||
|
||||
if not sls_vars_set:
|
||||
return False
|
||||
|
||||
# Check if any repository configuration points to logstore implementation
|
||||
repository_configs = [
|
||||
dify_config.CORE_WORKFLOW_EXECUTION_REPOSITORY,
|
||||
dify_config.CORE_WORKFLOW_NODE_EXECUTION_REPOSITORY,
|
||||
dify_config.API_WORKFLOW_NODE_EXECUTION_REPOSITORY,
|
||||
dify_config.API_WORKFLOW_RUN_REPOSITORY,
|
||||
]
|
||||
|
||||
uses_logstore = any("logstore" in config.lower() for config in repository_configs)
|
||||
|
||||
if not uses_logstore:
|
||||
return False
|
||||
|
||||
logger.info("Logstore extension enabled: SLS variables set and repository configured to use logstore")
|
||||
return True
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
"""
|
||||
Initialize logstore on application startup.
|
||||
If initialization fails, the application continues running without logstore features.
|
||||
|
||||
Args:
|
||||
app: The Dify application instance
|
||||
"""
|
||||
try:
|
||||
from extensions.logstore.aliyun_logstore import AliyunLogStore
|
||||
|
||||
logger.info("Initializing Aliyun SLS Logstore...")
|
||||
|
||||
# Create logstore client and initialize resources
|
||||
logstore_client = AliyunLogStore()
|
||||
logstore_client.init_project_logstore()
|
||||
|
||||
app.extensions["logstore"] = logstore_client
|
||||
|
||||
logger.info("Logstore initialized successfully")
|
||||
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Logstore initialization failed. Configuration: endpoint=%s, region=%s, project=%s, timeout=%ss. "
|
||||
"Application will continue but logstore features will NOT work.",
|
||||
os.environ.get("ALIYUN_SLS_ENDPOINT"),
|
||||
os.environ.get("ALIYUN_SLS_REGION"),
|
||||
os.environ.get("ALIYUN_SLS_PROJECT_NAME"),
|
||||
os.environ.get("ALIYUN_SLS_CHECK_CONNECTIVITY_TIMEOUT", "30"),
|
||||
)
|
||||
# Don't raise - allow application to continue even if logstore setup fails
|
||||
@@ -0,0 +1,107 @@
|
||||
import logging
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from configs import dify_config
|
||||
from dify_app import DifyApp
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Mail:
|
||||
def __init__(self):
|
||||
self._client = None
|
||||
self._default_send_from = None
|
||||
|
||||
def is_inited(self) -> bool:
|
||||
return self._client is not None
|
||||
|
||||
def init_app(self, app: Flask):
|
||||
mail_type = dify_config.MAIL_TYPE
|
||||
if not mail_type:
|
||||
logger.warning("MAIL_TYPE is not set")
|
||||
return
|
||||
|
||||
if dify_config.MAIL_DEFAULT_SEND_FROM:
|
||||
self._default_send_from = dify_config.MAIL_DEFAULT_SEND_FROM
|
||||
|
||||
match mail_type:
|
||||
case "resend":
|
||||
import resend
|
||||
|
||||
api_key = dify_config.RESEND_API_KEY
|
||||
if not api_key:
|
||||
raise ValueError("RESEND_API_KEY is not set")
|
||||
|
||||
api_url = dify_config.RESEND_API_URL
|
||||
if api_url:
|
||||
resend.api_url = api_url
|
||||
|
||||
resend.api_key = api_key
|
||||
self._client = resend.Emails
|
||||
case "smtp":
|
||||
from libs.smtp import SMTPClient
|
||||
|
||||
if not dify_config.SMTP_SERVER or not dify_config.SMTP_PORT:
|
||||
raise ValueError("SMTP_SERVER and SMTP_PORT are required for smtp mail type")
|
||||
if not dify_config.SMTP_USE_TLS and dify_config.SMTP_OPPORTUNISTIC_TLS:
|
||||
raise ValueError("SMTP_OPPORTUNISTIC_TLS is not supported without enabling SMTP_USE_TLS")
|
||||
self._client = SMTPClient(
|
||||
server=dify_config.SMTP_SERVER,
|
||||
port=dify_config.SMTP_PORT,
|
||||
username=dify_config.SMTP_USERNAME or "",
|
||||
password=dify_config.SMTP_PASSWORD or "",
|
||||
_from=dify_config.MAIL_DEFAULT_SEND_FROM or "",
|
||||
use_tls=dify_config.SMTP_USE_TLS,
|
||||
opportunistic_tls=dify_config.SMTP_OPPORTUNISTIC_TLS,
|
||||
)
|
||||
case "sendgrid":
|
||||
from libs.sendgrid import SendGridClient
|
||||
|
||||
if not dify_config.SENDGRID_API_KEY:
|
||||
raise ValueError("SENDGRID_API_KEY is required for SendGrid mail type")
|
||||
|
||||
self._client = SendGridClient(
|
||||
sendgrid_api_key=dify_config.SENDGRID_API_KEY, _from=dify_config.MAIL_DEFAULT_SEND_FROM or ""
|
||||
)
|
||||
case _:
|
||||
raise ValueError(f"Unsupported mail type {mail_type}")
|
||||
|
||||
def send(self, to: str, subject: str, html: str, from_: str = ""):
|
||||
if not self._client:
|
||||
raise ValueError("Mail client is not initialized")
|
||||
|
||||
if not from_ and self._default_send_from:
|
||||
from_ = self._default_send_from
|
||||
|
||||
if not from_:
|
||||
raise ValueError("mail from is not set")
|
||||
|
||||
if not to:
|
||||
raise ValueError("mail to is not set")
|
||||
|
||||
if not subject:
|
||||
raise ValueError("mail subject is not set")
|
||||
|
||||
if not html:
|
||||
raise ValueError("mail html is not set")
|
||||
|
||||
self._client.send(
|
||||
{
|
||||
"from": from_,
|
||||
"to": to,
|
||||
"subject": subject,
|
||||
"html": html,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def is_enabled() -> bool:
|
||||
return dify_config.MAIL_TYPE is not None and dify_config.MAIL_TYPE != ""
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
mail.init_app(app)
|
||||
|
||||
|
||||
mail = Mail()
|
||||
@@ -0,0 +1,9 @@
|
||||
from dify_app import DifyApp
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
import flask_migrate
|
||||
|
||||
from extensions.ext_database import db
|
||||
|
||||
flask_migrate.Migrate(app, db)
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Bind the bearer authenticator at startup. Must run after ext_database
|
||||
and ext_redis (needs both factories).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from configs import dify_config
|
||||
from dify_app import DifyApp
|
||||
from extensions.ext_database import db
|
||||
from extensions.ext_redis import redis_client
|
||||
from libs.oauth_bearer import build_and_bind
|
||||
|
||||
|
||||
def is_enabled() -> bool:
|
||||
return dify_config.ENABLE_OAUTH_BEARER
|
||||
|
||||
|
||||
def init_app(app: DifyApp) -> None:
|
||||
# scoped_session isn't a context manager; request teardown closes it.
|
||||
def session_factory():
|
||||
return db.session
|
||||
|
||||
build_and_bind(session_factory=session_factory, redis_client=redis_client)
|
||||
@@ -0,0 +1,8 @@
|
||||
from flask_orjson import OrjsonProvider
|
||||
|
||||
from dify_app import DifyApp
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
"""Initialize Flask-Orjson extension for faster JSON serialization"""
|
||||
app.json = OrjsonProvider(app)
|
||||
@@ -0,0 +1,143 @@
|
||||
import atexit
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import socket
|
||||
|
||||
from configs import dify_config
|
||||
from dify_app import DifyApp
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter as GRPCMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter as GRPCSpanExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter as HTTPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter as HTTPSpanExporter
|
||||
from opentelemetry.metrics import set_meter_provider
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import ConsoleMetricExporter, PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import (
|
||||
BatchSpanProcessor,
|
||||
ConsoleSpanExporter,
|
||||
)
|
||||
from opentelemetry.sdk.trace.sampling import ParentBasedTraceIdRatio
|
||||
from opentelemetry.semconv._incubating.attributes.deployment_attributes import ( # type: ignore[import-untyped]
|
||||
DEPLOYMENT_ENVIRONMENT_NAME,
|
||||
)
|
||||
from opentelemetry.semconv._incubating.attributes.host_attributes import ( # type: ignore[import-untyped]
|
||||
HOST_ARCH,
|
||||
HOST_ID,
|
||||
HOST_NAME,
|
||||
)
|
||||
from opentelemetry.semconv._incubating.attributes.os_attributes import ( # type: ignore[import-untyped]
|
||||
OS_DESCRIPTION,
|
||||
OS_TYPE,
|
||||
OS_VERSION,
|
||||
)
|
||||
from opentelemetry.semconv._incubating.attributes.process_attributes import ( # type: ignore[import-untyped]
|
||||
PROCESS_PID,
|
||||
)
|
||||
from opentelemetry.semconv.attributes.service_attributes import ( # type: ignore[import-untyped]
|
||||
SERVICE_NAME,
|
||||
SERVICE_VERSION,
|
||||
)
|
||||
from opentelemetry.trace import set_tracer_provider
|
||||
|
||||
from extensions.otel.instrumentation import init_instruments
|
||||
from extensions.otel.runtime import setup_context_propagation, shutdown_tracer
|
||||
|
||||
setup_context_propagation()
|
||||
# Initialize OpenTelemetry
|
||||
# Follow Semantic Conventions 1.32.0 to define resource attributes
|
||||
resource = Resource(
|
||||
attributes={
|
||||
SERVICE_NAME: dify_config.APPLICATION_NAME,
|
||||
SERVICE_VERSION: f"dify-{dify_config.project.version}-{dify_config.COMMIT_SHA}",
|
||||
PROCESS_PID: os.getpid(),
|
||||
DEPLOYMENT_ENVIRONMENT_NAME: f"{dify_config.DEPLOY_ENV}-{dify_config.DEPLOYMENT_EDITION.value}",
|
||||
HOST_NAME: socket.gethostname(),
|
||||
HOST_ARCH: platform.machine(),
|
||||
"custom.deployment.git_commit": dify_config.COMMIT_SHA,
|
||||
HOST_ID: platform.node(),
|
||||
OS_TYPE: platform.system().lower(),
|
||||
OS_DESCRIPTION: platform.platform(),
|
||||
OS_VERSION: platform.version(),
|
||||
}
|
||||
)
|
||||
sampler = ParentBasedTraceIdRatio(dify_config.OTEL_SAMPLING_RATE)
|
||||
provider = TracerProvider(resource=resource, sampler=sampler)
|
||||
|
||||
set_tracer_provider(provider)
|
||||
exporter: GRPCSpanExporter | HTTPSpanExporter | ConsoleSpanExporter
|
||||
metric_exporter: GRPCMetricExporter | HTTPMetricExporter | ConsoleMetricExporter
|
||||
protocol = (dify_config.OTEL_EXPORTER_OTLP_PROTOCOL or "").lower()
|
||||
if dify_config.OTEL_EXPORTER_TYPE == "otlp":
|
||||
if protocol == "grpc":
|
||||
# Auto-detect TLS: https:// uses secure, everything else is insecure
|
||||
endpoint = dify_config.OTLP_BASE_ENDPOINT
|
||||
insecure = not endpoint.startswith("https://")
|
||||
|
||||
# Header field names must consist of lowercase letters, check RFC7540
|
||||
grpc_headers = (
|
||||
(("authorization", f"Bearer {dify_config.OTLP_API_KEY}"),) if dify_config.OTLP_API_KEY else ()
|
||||
)
|
||||
|
||||
exporter = GRPCSpanExporter(
|
||||
endpoint=endpoint,
|
||||
headers=grpc_headers,
|
||||
insecure=insecure,
|
||||
)
|
||||
metric_exporter = GRPCMetricExporter(
|
||||
endpoint=endpoint,
|
||||
headers=grpc_headers,
|
||||
insecure=insecure,
|
||||
)
|
||||
else:
|
||||
headers = {"Authorization": f"Bearer {dify_config.OTLP_API_KEY}"} if dify_config.OTLP_API_KEY else None
|
||||
|
||||
trace_endpoint = dify_config.OTLP_TRACE_ENDPOINT
|
||||
if not trace_endpoint:
|
||||
trace_endpoint = dify_config.OTLP_BASE_ENDPOINT + "/v1/traces"
|
||||
exporter = HTTPSpanExporter(
|
||||
endpoint=trace_endpoint,
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
metric_endpoint = dify_config.OTLP_METRIC_ENDPOINT
|
||||
if not metric_endpoint:
|
||||
metric_endpoint = dify_config.OTLP_BASE_ENDPOINT + "/v1/metrics"
|
||||
metric_exporter = HTTPMetricExporter(
|
||||
endpoint=metric_endpoint,
|
||||
headers=headers,
|
||||
)
|
||||
else:
|
||||
exporter = ConsoleSpanExporter()
|
||||
metric_exporter = ConsoleMetricExporter()
|
||||
|
||||
provider.add_span_processor(
|
||||
BatchSpanProcessor(
|
||||
exporter,
|
||||
max_queue_size=dify_config.OTEL_MAX_QUEUE_SIZE,
|
||||
schedule_delay_millis=dify_config.OTEL_BATCH_EXPORT_SCHEDULE_DELAY,
|
||||
max_export_batch_size=dify_config.OTEL_MAX_EXPORT_BATCH_SIZE,
|
||||
export_timeout_millis=dify_config.OTEL_BATCH_EXPORT_TIMEOUT,
|
||||
)
|
||||
)
|
||||
reader = PeriodicExportingMetricReader(
|
||||
metric_exporter,
|
||||
export_interval_millis=dify_config.OTEL_METRIC_EXPORT_INTERVAL,
|
||||
export_timeout_millis=dify_config.OTEL_METRIC_EXPORT_TIMEOUT,
|
||||
)
|
||||
set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader]))
|
||||
|
||||
init_instruments(app)
|
||||
|
||||
atexit.register(shutdown_tracer)
|
||||
|
||||
|
||||
def is_enabled():
|
||||
return dify_config.ENABLE_OTEL
|
||||
@@ -0,0 +1,9 @@
|
||||
from configs import dify_config
|
||||
from dify_app import DifyApp
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
if dify_config.RESPECT_XFORWARD_HEADERS_ENABLED:
|
||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||
|
||||
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_port=1) # type: ignore[method-assign]
|
||||
@@ -0,0 +1,592 @@
|
||||
import functools
|
||||
import logging
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
from collections.abc import Callable
|
||||
from datetime import timedelta
|
||||
from typing import Any, Protocol, cast, runtime_checkable
|
||||
|
||||
import redis
|
||||
from redis import RedisError
|
||||
from redis.backoff import ExponentialWithJitterBackoff # type: ignore
|
||||
from redis.cache import CacheConfig
|
||||
from redis.client import PubSub
|
||||
from redis.cluster import ClusterNode, RedisCluster
|
||||
from redis.connection import Connection, SSLConnection
|
||||
from redis.exceptions import ConnectionError, TimeoutError
|
||||
from redis.retry import Retry
|
||||
from redis.sentinel import Sentinel
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from configs import dify_config
|
||||
from dify_app import DifyApp
|
||||
from extensions.redis_names import (
|
||||
normalize_redis_key_prefix,
|
||||
serialize_redis_name,
|
||||
serialize_redis_name_arg,
|
||||
serialize_redis_name_args,
|
||||
)
|
||||
from libs.broadcast_channel.channel import BroadcastChannel as BroadcastChannelProtocol
|
||||
from libs.broadcast_channel.redis.pubsub_channel import BroadcastChannel as RedisBroadcastChannel
|
||||
from libs.broadcast_channel.redis.sharded_channel import ShardedRedisBroadcastChannel
|
||||
from libs.broadcast_channel.redis.streams_channel import StreamsBroadcastChannel
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_normalize_redis_key_prefix = normalize_redis_key_prefix
|
||||
_serialize_redis_name = serialize_redis_name
|
||||
_serialize_redis_name_arg = serialize_redis_name_arg
|
||||
_serialize_redis_name_args = serialize_redis_name_args
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class _ScriptRegistrar(Protocol):
|
||||
def register_script(self, script: str) -> Callable[..., Any]: ...
|
||||
|
||||
|
||||
_INCR_IF_EXISTS_LUA = """
|
||||
-- Exactly 1 key and no arguments.
|
||||
-- KEYS[1]: Existing integer counter key, including the deployment prefix.
|
||||
-- Returns the incremented integer, or nil (Lua false) if the key is missing.
|
||||
-- INCR preserves TTL; checking existence atomically avoids recreating an
|
||||
-- expired/deleted counter without an expiry.
|
||||
if redis.call('EXISTS', KEYS[1]) == 0 then return false end
|
||||
return redis.call('INCR', KEYS[1])
|
||||
"""
|
||||
|
||||
|
||||
class RedisClientWrapper:
|
||||
"""
|
||||
A wrapper class for the Redis client that addresses the issue where the global
|
||||
`redis_client` variable cannot be updated when a new Redis instance is returned
|
||||
by Sentinel.
|
||||
|
||||
This class allows for deferred initialization of the Redis client, enabling the
|
||||
client to be re-initialized with a new instance when necessary. This is particularly
|
||||
useful in scenarios where the Redis instance may change dynamically, such as during
|
||||
a failover in a Sentinel-managed Redis setup.
|
||||
|
||||
Attributes:
|
||||
_client: The actual Redis client instance. It remains None until
|
||||
initialized with the `initialize` method.
|
||||
|
||||
Methods:
|
||||
initialize(client): Initializes the Redis client if it hasn't been initialized already.
|
||||
__getattr__(item): Delegates attribute access to the Redis client, raising an error
|
||||
if the client is not initialized.
|
||||
"""
|
||||
|
||||
_client: redis.Redis | RedisCluster | None
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._client = None
|
||||
|
||||
def initialize(self, client: redis.Redis | RedisCluster) -> None:
|
||||
if self._client is None:
|
||||
self._client = client
|
||||
|
||||
def _require_client(self) -> redis.Redis | RedisCluster:
|
||||
if self._client is None:
|
||||
raise RuntimeError("Redis client is not initialized. Call init_app first.")
|
||||
return self._client
|
||||
|
||||
def _get_prefix(self) -> str:
|
||||
return dify_config.REDIS_KEY_PREFIX
|
||||
|
||||
def get(self, name: str | bytes) -> Any:
|
||||
return self._require_client().get(_serialize_redis_name_arg(name, self._get_prefix()))
|
||||
|
||||
def set(
|
||||
self,
|
||||
name: str | bytes,
|
||||
value: Any,
|
||||
ex: int | None = None,
|
||||
px: int | None = None,
|
||||
nx: bool = False,
|
||||
xx: bool = False,
|
||||
keepttl: bool = False,
|
||||
get: bool = False,
|
||||
exat: int | None = None,
|
||||
pxat: int | None = None,
|
||||
) -> Any:
|
||||
return self._require_client().set(
|
||||
_serialize_redis_name_arg(name, self._get_prefix()),
|
||||
value,
|
||||
ex=ex,
|
||||
px=px,
|
||||
nx=nx,
|
||||
xx=xx,
|
||||
keepttl=keepttl,
|
||||
get=get,
|
||||
exat=exat,
|
||||
pxat=pxat,
|
||||
)
|
||||
|
||||
def setex(self, name: str | bytes, time: int | timedelta, value: Any) -> Any:
|
||||
return self._require_client().setex(_serialize_redis_name_arg(name, self._get_prefix()), time, value)
|
||||
|
||||
def setnx(self, name: str | bytes, value: Any) -> Any:
|
||||
return self._require_client().setnx(_serialize_redis_name_arg(name, self._get_prefix()), value)
|
||||
|
||||
def delete(self, *names: str | bytes) -> Any:
|
||||
return self._require_client().delete(*_serialize_redis_name_args(names, self._get_prefix()))
|
||||
|
||||
def incr(self, name: str | bytes, amount: int = 1) -> Any:
|
||||
return self._require_client().incr(_serialize_redis_name_arg(name, self._get_prefix()), amount)
|
||||
|
||||
def expire(
|
||||
self,
|
||||
name: str | bytes,
|
||||
time: int | timedelta,
|
||||
nx: bool = False,
|
||||
xx: bool = False,
|
||||
gt: bool = False,
|
||||
lt: bool = False,
|
||||
) -> Any:
|
||||
return self._require_client().expire(
|
||||
_serialize_redis_name_arg(name, self._get_prefix()),
|
||||
time,
|
||||
nx=nx,
|
||||
xx=xx,
|
||||
gt=gt,
|
||||
lt=lt,
|
||||
)
|
||||
|
||||
def exists(self, *names: str | bytes) -> Any:
|
||||
return self._require_client().exists(*_serialize_redis_name_args(names, self._get_prefix()))
|
||||
|
||||
def ttl(self, name: str | bytes) -> Any:
|
||||
return self._require_client().ttl(_serialize_redis_name_arg(name, self._get_prefix()))
|
||||
|
||||
def pttl(self, name: str | bytes) -> Any:
|
||||
return self._require_client().pttl(_serialize_redis_name_arg(name, self._get_prefix()))
|
||||
|
||||
def getdel(self, name: str | bytes) -> Any:
|
||||
return self._require_client().getdel(_serialize_redis_name_arg(name, self._get_prefix()))
|
||||
|
||||
def lock(
|
||||
self,
|
||||
name: str,
|
||||
timeout: float | None = None,
|
||||
sleep: float = 0.1,
|
||||
blocking: bool = True,
|
||||
blocking_timeout: float | None = None,
|
||||
thread_local: bool = True,
|
||||
) -> Any:
|
||||
return self._require_client().lock(
|
||||
_serialize_redis_name(name, self._get_prefix()),
|
||||
timeout=timeout,
|
||||
sleep=sleep,
|
||||
blocking=blocking,
|
||||
blocking_timeout=blocking_timeout,
|
||||
thread_local=thread_local,
|
||||
)
|
||||
|
||||
def hset(self, name: str | bytes, *args: Any, **kwargs: Any) -> Any:
|
||||
return self._require_client().hset(_serialize_redis_name_arg(name, self._get_prefix()), *args, **kwargs)
|
||||
|
||||
def incr_if_exists(self, name: str) -> int | None:
|
||||
"""Increment an existing integer counter, preserving TTL; return None if absent."""
|
||||
count = self.eval(_INCR_IF_EXISTS_LUA, 1, _serialize_redis_name(name, self._get_prefix()))
|
||||
if count is not None and not isinstance(count, int):
|
||||
raise ValueError("Invalid Redis counter response")
|
||||
return count
|
||||
|
||||
def hgetall(self, name: str | bytes) -> Any:
|
||||
return self._require_client().hgetall(_serialize_redis_name_arg(name, self._get_prefix()))
|
||||
|
||||
def hkeys(self, name: str | bytes) -> Any:
|
||||
return self._require_client().hkeys(_serialize_redis_name_arg(name, self._get_prefix()))
|
||||
|
||||
def hexists(self, name: str | bytes, key: str | bytes) -> Any:
|
||||
return self._require_client().hexists(_serialize_redis_name_arg(name, self._get_prefix()), key)
|
||||
|
||||
def hdel(self, name: str | bytes, *keys: str | bytes) -> Any:
|
||||
return self._require_client().hdel(_serialize_redis_name_arg(name, self._get_prefix()), *keys)
|
||||
|
||||
def hlen(self, name: str | bytes) -> Any:
|
||||
return self._require_client().hlen(_serialize_redis_name_arg(name, self._get_prefix()))
|
||||
|
||||
def zadd(
|
||||
self,
|
||||
name: str | bytes,
|
||||
mapping: dict[str | bytes | int | float, float | int | str | bytes],
|
||||
nx: bool = False,
|
||||
xx: bool = False,
|
||||
ch: bool = False,
|
||||
incr: bool = False,
|
||||
gt: bool = False,
|
||||
lt: bool = False,
|
||||
) -> Any:
|
||||
return self._require_client().zadd(
|
||||
_serialize_redis_name_arg(name, self._get_prefix()),
|
||||
cast(Any, mapping),
|
||||
nx=nx,
|
||||
xx=xx,
|
||||
ch=ch,
|
||||
incr=incr,
|
||||
gt=gt,
|
||||
lt=lt,
|
||||
)
|
||||
|
||||
def zrem(self, name: str | bytes, *values: str | bytes | int | float) -> Any:
|
||||
return self._require_client().zrem(_serialize_redis_name_arg(name, self._get_prefix()), *values)
|
||||
|
||||
def zremrangebyscore(self, name: str | bytes, min: float | str, max: float | str) -> Any:
|
||||
return self._require_client().zremrangebyscore(_serialize_redis_name_arg(name, self._get_prefix()), min, max)
|
||||
|
||||
def zcard(self, name: str | bytes) -> Any:
|
||||
return self._require_client().zcard(_serialize_redis_name_arg(name, self._get_prefix()))
|
||||
|
||||
def pubsub(self) -> PubSub:
|
||||
return self._require_client().pubsub()
|
||||
|
||||
def eval(self, script: str, numkeys: int, *args: str | int) -> Any:
|
||||
# Lua callers supply physical names, matching the historically delegated API.
|
||||
# Redis script responses are dynamically shaped at this SDK boundary.
|
||||
return self._require_client().execute_command("EVAL", script, numkeys, *args)
|
||||
|
||||
def pipeline(self, transaction: bool = True, shard_hint: str | None = None) -> Any:
|
||||
return self._require_client().pipeline(transaction=transaction, shard_hint=shard_hint)
|
||||
|
||||
def register_script(self, script: str) -> Callable[..., Any]:
|
||||
"""Register a Lua script whose key arguments use logical Redis names."""
|
||||
client = self._require_client()
|
||||
if not isinstance(client, _ScriptRegistrar):
|
||||
raise RuntimeError("Redis client does not support Lua script registration")
|
||||
registered_script = client.register_script(script)
|
||||
|
||||
def execute(
|
||||
keys: list[str | bytes] | tuple[str | bytes, ...] | None = None,
|
||||
args: list[Any] | tuple[Any, ...] | None = None,
|
||||
client: RedisClientWrapper | redis.Redis | RedisCluster | None = None,
|
||||
) -> Any:
|
||||
redis_keys = _serialize_redis_name_args(tuple(keys or ()), self._get_prefix())
|
||||
execution_client = client._require_client() if isinstance(client, RedisClientWrapper) else client
|
||||
return registered_script(
|
||||
keys=redis_keys,
|
||||
args=args,
|
||||
client=execution_client or self._require_client(),
|
||||
)
|
||||
|
||||
return execute
|
||||
|
||||
def __getattr__(self, item: str) -> Any:
|
||||
return getattr(self._require_client(), item)
|
||||
|
||||
|
||||
redis_client: RedisClientWrapper = RedisClientWrapper()
|
||||
_pubsub_redis_client: redis.Redis | RedisCluster | None = None
|
||||
|
||||
|
||||
class RedisSSLParamsDict(TypedDict):
|
||||
ssl_cert_reqs: int
|
||||
ssl_ca_certs: str | None
|
||||
ssl_certfile: str | None
|
||||
ssl_keyfile: str | None
|
||||
|
||||
|
||||
class RedisHealthParamsDict(TypedDict):
|
||||
retry: Retry
|
||||
socket_timeout: float | None
|
||||
socket_connect_timeout: float | None
|
||||
health_check_interval: int | None
|
||||
socket_keepalive: bool
|
||||
socket_keepalive_options: dict[int, int]
|
||||
|
||||
|
||||
class RedisClusterHealthParamsDict(TypedDict):
|
||||
retry: Retry
|
||||
socket_timeout: float | None
|
||||
socket_connect_timeout: float | None
|
||||
socket_keepalive: bool
|
||||
socket_keepalive_options: dict[int, int]
|
||||
|
||||
|
||||
class RedisBaseParamsDict(TypedDict):
|
||||
username: str | None
|
||||
password: str | None
|
||||
db: int
|
||||
encoding: str
|
||||
encoding_errors: str
|
||||
decode_responses: bool
|
||||
protocol: int
|
||||
cache_config: CacheConfig | None
|
||||
retry: Retry
|
||||
socket_timeout: float | None
|
||||
socket_connect_timeout: float | None
|
||||
health_check_interval: int | None
|
||||
socket_keepalive: bool
|
||||
socket_keepalive_options: dict[int, int]
|
||||
|
||||
|
||||
def _get_ssl_configuration() -> tuple[type[Connection | SSLConnection], dict[str, Any]]:
|
||||
"""Get SSL configuration for Redis connection."""
|
||||
if not dify_config.REDIS_USE_SSL:
|
||||
return Connection, {}
|
||||
|
||||
cert_reqs_map = {
|
||||
"CERT_NONE": ssl.CERT_NONE,
|
||||
"CERT_OPTIONAL": ssl.CERT_OPTIONAL,
|
||||
"CERT_REQUIRED": ssl.CERT_REQUIRED,
|
||||
}
|
||||
ssl_cert_reqs = cert_reqs_map.get(dify_config.REDIS_SSL_CERT_REQS, ssl.CERT_NONE)
|
||||
|
||||
ssl_kwargs = {
|
||||
"ssl_cert_reqs": ssl_cert_reqs,
|
||||
"ssl_ca_certs": dify_config.REDIS_SSL_CA_CERTS,
|
||||
"ssl_certfile": dify_config.REDIS_SSL_CERTFILE,
|
||||
"ssl_keyfile": dify_config.REDIS_SSL_KEYFILE,
|
||||
}
|
||||
|
||||
return SSLConnection, ssl_kwargs
|
||||
|
||||
|
||||
def _get_cache_configuration() -> CacheConfig | None:
|
||||
"""Get client-side cache configuration if enabled."""
|
||||
if not dify_config.REDIS_ENABLE_CLIENT_SIDE_CACHE:
|
||||
return None
|
||||
|
||||
resp_protocol = dify_config.REDIS_SERIALIZATION_PROTOCOL
|
||||
if resp_protocol < 3:
|
||||
raise ValueError("Client side cache is only supported in RESP3")
|
||||
|
||||
return CacheConfig()
|
||||
|
||||
|
||||
def _get_retry_policy() -> Retry:
|
||||
"""Build the shared retry policy for Redis connections."""
|
||||
return Retry(
|
||||
backoff=ExponentialWithJitterBackoff(
|
||||
base=dify_config.REDIS_RETRY_BACKOFF_BASE,
|
||||
cap=dify_config.REDIS_RETRY_BACKOFF_CAP,
|
||||
),
|
||||
retries=dify_config.REDIS_RETRY_RETRIES,
|
||||
supported_errors=(
|
||||
ConnectionError,
|
||||
TimeoutError,
|
||||
BrokenPipeError,
|
||||
OSError,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _get_connection_health_params() -> RedisHealthParamsDict:
|
||||
"""Get connection health and retry parameters for standalone and Sentinel Redis clients."""
|
||||
socket_keepalive_options: dict[int, int] = {}
|
||||
if sys.platform == "linux":
|
||||
socket_keepalive_options[socket.TCP_KEEPIDLE] = dify_config.REDIS_KEEPALIVE_IDLE
|
||||
socket_keepalive_options[socket.TCP_KEEPINTVL] = dify_config.REDIS_KEEPALIVE_INTERVAL
|
||||
socket_keepalive_options[socket.TCP_KEEPCNT] = dify_config.REDIS_KEEPALIVE_COUNT
|
||||
elif sys.platform == "darwin":
|
||||
socket_keepalive_options[socket.TCP_KEEPALIVE] = dify_config.REDIS_KEEPALIVE_IDLE
|
||||
|
||||
return RedisHealthParamsDict(
|
||||
retry=_get_retry_policy(),
|
||||
socket_timeout=dify_config.REDIS_SOCKET_TIMEOUT,
|
||||
socket_connect_timeout=dify_config.REDIS_SOCKET_CONNECT_TIMEOUT,
|
||||
health_check_interval=dify_config.REDIS_HEALTH_CHECK_INTERVAL,
|
||||
socket_keepalive=dify_config.REDIS_KEEPALIVE,
|
||||
socket_keepalive_options=socket_keepalive_options,
|
||||
)
|
||||
|
||||
|
||||
def _get_cluster_connection_health_params() -> RedisClusterHealthParamsDict:
|
||||
"""Get retry and timeout parameters for Redis Cluster clients.
|
||||
|
||||
RedisCluster does not support ``health_check_interval`` as a constructor
|
||||
keyword (it is silently stripped by ``cleanup_kwargs``), so it is excluded
|
||||
here. Only ``retry``, ``socket_timeout``, and ``socket_connect_timeout``
|
||||
are passed through.
|
||||
"""
|
||||
health_params = _get_connection_health_params()
|
||||
result: RedisClusterHealthParamsDict = {
|
||||
"retry": health_params["retry"],
|
||||
"socket_timeout": health_params["socket_timeout"],
|
||||
"socket_connect_timeout": health_params["socket_connect_timeout"],
|
||||
"socket_keepalive": health_params["socket_keepalive"],
|
||||
"socket_keepalive_options": health_params["socket_keepalive_options"],
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def _get_base_redis_params() -> RedisBaseParamsDict:
|
||||
"""Get base Redis connection parameters including retry and health policy."""
|
||||
return RedisBaseParamsDict(
|
||||
username=dify_config.REDIS_USERNAME,
|
||||
password=dify_config.REDIS_PASSWORD or None,
|
||||
db=dify_config.REDIS_DB,
|
||||
encoding="utf-8",
|
||||
encoding_errors="strict",
|
||||
decode_responses=False,
|
||||
protocol=dify_config.REDIS_SERIALIZATION_PROTOCOL,
|
||||
cache_config=_get_cache_configuration(),
|
||||
**_get_connection_health_params(),
|
||||
)
|
||||
|
||||
|
||||
def _parse_redis_nodes(value: str) -> list[tuple[str, int]]:
|
||||
nodes = []
|
||||
for raw_node in value.split(","):
|
||||
host, separator, port = raw_node.strip().rpartition(":")
|
||||
if not separator or not host or not port:
|
||||
raise ValueError(f"Invalid Redis node: {raw_node}")
|
||||
if host.startswith("[") and host.endswith("]"):
|
||||
host = host[1:-1]
|
||||
nodes.append((host, int(port)))
|
||||
return nodes
|
||||
|
||||
|
||||
def _create_sentinel_client(redis_params: RedisBaseParamsDict) -> redis.Redis | RedisCluster:
|
||||
"""Create Redis client using Sentinel configuration."""
|
||||
if not dify_config.REDIS_SENTINELS:
|
||||
raise ValueError("REDIS_SENTINELS must be set when REDIS_USE_SENTINEL is True")
|
||||
|
||||
if not dify_config.REDIS_SENTINEL_SERVICE_NAME:
|
||||
raise ValueError("REDIS_SENTINEL_SERVICE_NAME must be set when REDIS_USE_SENTINEL is True")
|
||||
|
||||
sentinel_hosts = _parse_redis_nodes(dify_config.REDIS_SENTINELS)
|
||||
|
||||
health_params = _get_connection_health_params()
|
||||
|
||||
sentinel_kwargs = {
|
||||
"socket_timeout": dify_config.REDIS_SENTINEL_SOCKET_TIMEOUT,
|
||||
"username": dify_config.REDIS_SENTINEL_USERNAME,
|
||||
"password": dify_config.REDIS_SENTINEL_PASSWORD,
|
||||
"socket_keepalive": health_params["socket_keepalive"],
|
||||
"socket_keepalive_options": health_params["socket_keepalive_options"],
|
||||
}
|
||||
|
||||
if dify_config.REDIS_MAX_CONNECTIONS:
|
||||
sentinel_kwargs["max_connections"] = dify_config.REDIS_MAX_CONNECTIONS
|
||||
|
||||
sentinel = Sentinel(
|
||||
sentinel_hosts,
|
||||
sentinel_kwargs=sentinel_kwargs,
|
||||
)
|
||||
|
||||
params: dict[str, Any] = {**redis_params}
|
||||
master: redis.Redis = sentinel.master_for(dify_config.REDIS_SENTINEL_SERVICE_NAME, **params)
|
||||
return master
|
||||
|
||||
|
||||
def _create_cluster_client() -> redis.Redis | RedisCluster:
|
||||
"""Create Redis cluster client."""
|
||||
if not dify_config.REDIS_CLUSTERS:
|
||||
raise ValueError("REDIS_CLUSTERS must be set when REDIS_USE_CLUSTERS is True")
|
||||
|
||||
nodes = [ClusterNode(host=host, port=port) for host, port in _parse_redis_nodes(dify_config.REDIS_CLUSTERS)]
|
||||
|
||||
cluster_kwargs: dict[str, Any] = {
|
||||
"startup_nodes": nodes,
|
||||
"password": dify_config.REDIS_CLUSTERS_PASSWORD,
|
||||
"protocol": dify_config.REDIS_SERIALIZATION_PROTOCOL,
|
||||
"cache_config": _get_cache_configuration(),
|
||||
**_get_cluster_connection_health_params(),
|
||||
}
|
||||
if dify_config.REDIS_MAX_CONNECTIONS:
|
||||
cluster_kwargs["max_connections"] = dify_config.REDIS_MAX_CONNECTIONS
|
||||
cluster: RedisCluster = RedisCluster(**cluster_kwargs)
|
||||
return cluster
|
||||
|
||||
|
||||
def _create_standalone_client(redis_params: RedisBaseParamsDict) -> redis.Redis | RedisCluster:
|
||||
"""Create standalone Redis client."""
|
||||
connection_class, ssl_kwargs = _get_ssl_configuration()
|
||||
|
||||
params: dict[str, Any] = {
|
||||
**redis_params,
|
||||
"host": dify_config.REDIS_HOST,
|
||||
"port": dify_config.REDIS_PORT,
|
||||
"connection_class": connection_class,
|
||||
}
|
||||
|
||||
if dify_config.REDIS_MAX_CONNECTIONS:
|
||||
params["max_connections"] = dify_config.REDIS_MAX_CONNECTIONS
|
||||
|
||||
if ssl_kwargs:
|
||||
params.update(ssl_kwargs)
|
||||
|
||||
pool = redis.ConnectionPool(**params)
|
||||
client: redis.Redis = redis.Redis(connection_pool=pool)
|
||||
return client
|
||||
|
||||
|
||||
def _create_pubsub_client(pubsub_url: str, use_clusters: bool) -> redis.Redis | RedisCluster:
|
||||
max_conns = dify_config.REDIS_MAX_CONNECTIONS
|
||||
|
||||
if use_clusters:
|
||||
health_params = _get_cluster_connection_health_params()
|
||||
kwargs: dict[str, Any] = {**health_params}
|
||||
if max_conns:
|
||||
kwargs["max_connections"] = max_conns
|
||||
return RedisCluster.from_url(pubsub_url, **kwargs)
|
||||
|
||||
standalone_health_params: dict[str, Any] = dict(_get_connection_health_params())
|
||||
kwargs = {**standalone_health_params}
|
||||
if max_conns:
|
||||
kwargs["max_connections"] = max_conns
|
||||
return redis.Redis.from_url(pubsub_url, **kwargs)
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
"""Initialize Redis client and attach it to the app."""
|
||||
global redis_client
|
||||
|
||||
# Determine Redis mode and create appropriate client
|
||||
if dify_config.REDIS_USE_SENTINEL:
|
||||
redis_params = _get_base_redis_params()
|
||||
client = _create_sentinel_client(redis_params)
|
||||
elif dify_config.REDIS_USE_CLUSTERS:
|
||||
client = _create_cluster_client()
|
||||
else:
|
||||
redis_params = _get_base_redis_params()
|
||||
client = _create_standalone_client(redis_params)
|
||||
|
||||
# Initialize the wrapper and attach to app
|
||||
redis_client.initialize(client)
|
||||
app.extensions["redis"] = redis_client
|
||||
|
||||
global _pubsub_redis_client
|
||||
_pubsub_redis_client = client
|
||||
if dify_config.normalized_pubsub_redis_url:
|
||||
_pubsub_redis_client = _create_pubsub_client(
|
||||
dify_config.normalized_pubsub_redis_url, dify_config.PUBSUB_REDIS_USE_CLUSTERS
|
||||
)
|
||||
|
||||
|
||||
def get_pubsub_broadcast_channel() -> BroadcastChannelProtocol:
|
||||
assert _pubsub_redis_client is not None, "PubSub redis Client should be initialized here."
|
||||
if dify_config.PUBSUB_REDIS_CHANNEL_TYPE == "sharded":
|
||||
return ShardedRedisBroadcastChannel(_pubsub_redis_client)
|
||||
if dify_config.PUBSUB_REDIS_CHANNEL_TYPE == "streams":
|
||||
return StreamsBroadcastChannel(
|
||||
_pubsub_redis_client,
|
||||
retention_seconds=dify_config.PUBSUB_STREAMS_RETENTION_SECONDS,
|
||||
)
|
||||
return RedisBroadcastChannel(_pubsub_redis_client)
|
||||
|
||||
|
||||
def redis_fallback[T](default_return: T | None = None): # type: ignore
|
||||
"""
|
||||
decorator to handle Redis operation exceptions and return a default value when Redis is unavailable.
|
||||
|
||||
Args:
|
||||
default_return: The value to return when a Redis operation fails. Defaults to None.
|
||||
"""
|
||||
|
||||
def decorator[**P, R](func: Callable[P, R]) -> Callable[P, R | T | None]:
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | T | None:
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except RedisError as e:
|
||||
func_name = getattr(func, "__name__", "Unknown")
|
||||
logger.warning("Redis operation failed in %s: %s", func_name, str(e), exc_info=True)
|
||||
return default_return
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
@@ -0,0 +1,109 @@
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
|
||||
import flask
|
||||
import werkzeug.http
|
||||
from flask import Flask, g
|
||||
from flask.signals import request_finished, request_started
|
||||
|
||||
from configs import dify_config
|
||||
from core.helper.trace_id_helper import get_trace_id_from_otel_context
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _is_content_type_json(content_type: str) -> bool:
|
||||
if not content_type:
|
||||
return False
|
||||
content_type_no_option, _ = werkzeug.http.parse_options_header(content_type)
|
||||
return content_type_no_option.lower() == "application/json"
|
||||
|
||||
|
||||
def _log_request_started(_sender, **_extra):
|
||||
"""Log the start of a request."""
|
||||
# Record start time for access logging
|
||||
g.__request_started_ts = time.perf_counter()
|
||||
|
||||
if not logger.isEnabledFor(logging.DEBUG):
|
||||
return
|
||||
|
||||
request = flask.request
|
||||
if not (_is_content_type_json(request.content_type) and request.data):
|
||||
logger.debug("Received Request %s -> %s", request.method, request.path)
|
||||
return
|
||||
try:
|
||||
json_data = json.loads(request.data)
|
||||
except (TypeError, ValueError):
|
||||
logger.exception("Failed to parse JSON request")
|
||||
return
|
||||
formatted_json = json.dumps(json_data, ensure_ascii=False, indent=2)
|
||||
logger.debug(
|
||||
"Received Request %s -> %s, Request Body:\n%s",
|
||||
request.method,
|
||||
request.path,
|
||||
formatted_json,
|
||||
)
|
||||
|
||||
|
||||
def _log_request_finished(_sender, response, **_extra):
|
||||
"""Log the end of a request.
|
||||
|
||||
Safe to call with or without an active Flask request context.
|
||||
"""
|
||||
if response is None:
|
||||
return
|
||||
|
||||
# Always emit a compact access line at INFO with trace_id so it can be grepped
|
||||
has_ctx = flask.has_request_context()
|
||||
start_ts = getattr(g, "__request_started_ts", None) if has_ctx else None
|
||||
duration_ms = None
|
||||
if start_ts is not None:
|
||||
duration_ms = round((time.perf_counter() - start_ts) * 1000, 3)
|
||||
|
||||
# Request attributes are available only when a request context exists
|
||||
if has_ctx:
|
||||
req_method = flask.request.method
|
||||
req_path = flask.request.path
|
||||
else:
|
||||
req_method = "-"
|
||||
req_path = "-"
|
||||
|
||||
trace_id = get_trace_id_from_otel_context() or response.headers.get("X-Trace-Id") or ""
|
||||
logger.info(
|
||||
"%s %s %s %s %s",
|
||||
req_method,
|
||||
req_path,
|
||||
getattr(response, "status_code", "-"),
|
||||
duration_ms if duration_ms is not None else "-",
|
||||
trace_id,
|
||||
)
|
||||
|
||||
if not logger.isEnabledFor(logging.DEBUG):
|
||||
return
|
||||
|
||||
if not _is_content_type_json(response.content_type):
|
||||
logger.debug("Response %s %s", response.status, response.content_type)
|
||||
return
|
||||
|
||||
response_data = response.get_data(as_text=True)
|
||||
try:
|
||||
json_data = json.loads(response_data)
|
||||
except (TypeError, ValueError):
|
||||
logger.exception("Failed to parse JSON response")
|
||||
return
|
||||
formatted_json = json.dumps(json_data, ensure_ascii=False, indent=2)
|
||||
logger.debug(
|
||||
"Response %s %s, Response Body:\n%s",
|
||||
response.status,
|
||||
response.content_type,
|
||||
formatted_json,
|
||||
)
|
||||
|
||||
|
||||
def init_app(app: Flask):
|
||||
"""Initialize the request logging extension."""
|
||||
if not dify_config.ENABLE_REQUEST_LOGGING:
|
||||
return
|
||||
request_started.connect(_log_request_started, app)
|
||||
request_finished.connect(_log_request_finished, app)
|
||||
@@ -0,0 +1,38 @@
|
||||
from configs import dify_config
|
||||
from dify_app import DifyApp
|
||||
from enums import DeploymentEdition
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
if dify_config.SENTRY_DSN:
|
||||
import sentry_sdk
|
||||
from sentry_sdk.integrations.celery import CeleryIntegration
|
||||
from sentry_sdk.integrations.flask import FlaskIntegration
|
||||
from sentry_sdk.integrations.logging import ignore_logger
|
||||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
from graphon.model_runtime.errors.invoke import InvokeRateLimitError
|
||||
|
||||
sentry_sdk.init(
|
||||
dsn=dify_config.SENTRY_DSN,
|
||||
integrations=[FlaskIntegration(), CeleryIntegration()],
|
||||
ignore_errors=[
|
||||
HTTPException,
|
||||
ValueError,
|
||||
FileNotFoundError,
|
||||
InvokeRateLimitError,
|
||||
],
|
||||
traces_sample_rate=dify_config.SENTRY_TRACES_SAMPLE_RATE,
|
||||
profiles_sample_rate=dify_config.SENTRY_PROFILES_SAMPLE_RATE,
|
||||
environment=dify_config.DEPLOY_ENV,
|
||||
release=f"dify-{dify_config.project.version}-{dify_config.COMMIT_SHA}",
|
||||
)
|
||||
|
||||
if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:
|
||||
# Cloud only. `opentelemetry.context.detach()` catches its own failures and reports
|
||||
# them through `logger.exception`, so a double-detach surfaces as an error event
|
||||
# rather than as a raised exception. Under gevent this can fire about once per
|
||||
# workflow run, which is enough volume to crowd real errors out of the issue stream.
|
||||
# Self-hosted deployments rarely see enough of it to be worth silencing, and the
|
||||
# records still reach the normal logging handlers either way.
|
||||
ignore_logger("opentelemetry.context")
|
||||
@@ -0,0 +1,9 @@
|
||||
from flask import Flask
|
||||
|
||||
from core.db.session_factory import configure_session_factory
|
||||
from extensions.ext_database import db
|
||||
|
||||
|
||||
def init_app(app: Flask):
|
||||
with app.app_context():
|
||||
configure_session_factory(db.engine)
|
||||
@@ -0,0 +1,13 @@
|
||||
from configs import dify_config
|
||||
from configs.secret_key import resolve_secret_key
|
||||
from dify_app import DifyApp
|
||||
|
||||
|
||||
def init_app(app: DifyApp) -> None:
|
||||
"""Resolve SECRET_KEY after config loading and before session/login setup."""
|
||||
secret_key = dify_config.SECRET_KEY
|
||||
if not secret_key:
|
||||
secret_key = resolve_secret_key(secret_key)
|
||||
dify_config.SECRET_KEY = secret_key
|
||||
app.config["SECRET_KEY"] = secret_key
|
||||
app.secret_key = secret_key
|
||||
@@ -0,0 +1,78 @@
|
||||
import ssl
|
||||
from typing import Any, cast
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import socketio # type: ignore[reportMissingTypeStubs]
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.redis_names import serialize_redis_name
|
||||
|
||||
SOCKETIO_REDIS_CHANNEL = "socketio"
|
||||
|
||||
|
||||
def _get_ssl_cert_reqs() -> ssl.VerifyMode:
|
||||
cert_reqs_map = {
|
||||
"CERT_NONE": ssl.CERT_NONE,
|
||||
"CERT_OPTIONAL": ssl.CERT_OPTIONAL,
|
||||
"CERT_REQUIRED": ssl.CERT_REQUIRED,
|
||||
}
|
||||
return cert_reqs_map.get(dify_config.REDIS_SSL_CERT_REQS, ssl.CERT_NONE)
|
||||
|
||||
|
||||
def _build_redis_options(redis_url: str) -> dict[str, Any]:
|
||||
"""Build Redis options for Socket.IO's cross-process pub/sub manager.
|
||||
|
||||
Note: ``socket_timeout`` is intentionally omitted. The RedisManager runs a
|
||||
blocking ``pubsub.listen()`` loop that idles indefinitely between messages;
|
||||
applying a read timeout there causes a reconnect storm (issue #39423).
|
||||
``socket_connect_timeout`` still guards connection establishment.
|
||||
"""
|
||||
options: dict[str, Any] = {
|
||||
"socket_connect_timeout": dify_config.REDIS_SOCKET_CONNECT_TIMEOUT,
|
||||
"health_check_interval": dify_config.REDIS_HEALTH_CHECK_INTERVAL,
|
||||
"protocol": dify_config.REDIS_SERIALIZATION_PROTOCOL,
|
||||
}
|
||||
|
||||
if dify_config.REDIS_MAX_CONNECTIONS:
|
||||
options["max_connections"] = dify_config.REDIS_MAX_CONNECTIONS
|
||||
|
||||
if urlparse(redis_url).scheme == "rediss":
|
||||
options.update(
|
||||
{
|
||||
"ssl_cert_reqs": _get_ssl_cert_reqs(),
|
||||
"ssl_ca_certs": dify_config.REDIS_SSL_CA_CERTS,
|
||||
"ssl_certfile": dify_config.REDIS_SSL_CERTFILE,
|
||||
"ssl_keyfile": dify_config.REDIS_SSL_KEYFILE,
|
||||
}
|
||||
)
|
||||
|
||||
return options
|
||||
|
||||
|
||||
def create_socketio_client_manager() -> Any:
|
||||
"""
|
||||
Create the Socket.IO manager used to fan out room events across API workers.
|
||||
|
||||
Workflow collaboration relies on room broadcasts and direct emits to a collaborator's sid. The default in-memory
|
||||
manager only reaches clients attached to the current process, so horizontal websocket workers must share a Redis
|
||||
pub/sub channel. The channel name follows Dify's Redis key prefix to keep independent deployments isolated.
|
||||
"""
|
||||
redis_url = dify_config.normalized_pubsub_redis_url
|
||||
return socketio.RedisManager(
|
||||
redis_url,
|
||||
channel=serialize_redis_name(SOCKETIO_REDIS_CHANNEL),
|
||||
redis_options=_build_redis_options(redis_url),
|
||||
)
|
||||
|
||||
|
||||
# TODO: FIXME(chariri) - Casting to any because app_factory attaches the
|
||||
# current app as the `app` attribute on this - Bad.
|
||||
sio = cast(
|
||||
Any,
|
||||
socketio.Server(
|
||||
async_mode="gevent",
|
||||
client_manager=create_socketio_client_manager(),
|
||||
cors_allowed_origins=dify_config.CONSOLE_CORS_ALLOW_ORIGINS,
|
||||
max_http_buffer_size=dify_config.WEBSOCKET_MAX_HTTP_BUFFER_SIZE,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,146 @@
|
||||
import logging
|
||||
from collections.abc import Callable, Generator
|
||||
from typing import Literal, overload
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from configs import dify_config
|
||||
from dify_app import DifyApp
|
||||
from extensions.storage.base_storage import BaseStorage
|
||||
from extensions.storage.storage_type import StorageType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Storage:
|
||||
def init_app(self, app: Flask):
|
||||
storage_factory = self.get_storage_factory(dify_config.STORAGE_TYPE)
|
||||
with app.app_context():
|
||||
self.storage_runner = storage_factory()
|
||||
|
||||
@staticmethod
|
||||
def get_storage_factory(storage_type: str) -> Callable[[], BaseStorage]:
|
||||
match storage_type:
|
||||
case StorageType.S3:
|
||||
from extensions.storage.aws_s3_storage import AwsS3Storage
|
||||
|
||||
return AwsS3Storage
|
||||
case StorageType.OPENDAL:
|
||||
from extensions.storage.opendal_storage import OpenDALStorage
|
||||
|
||||
return lambda: OpenDALStorage(dify_config.OPENDAL_SCHEME)
|
||||
case StorageType.LOCAL:
|
||||
from extensions.storage.opendal_storage import OpenDALStorage
|
||||
|
||||
return lambda: OpenDALStorage(scheme="fs", root=dify_config.STORAGE_LOCAL_PATH)
|
||||
case StorageType.AZURE_BLOB:
|
||||
from extensions.storage.azure_blob_storage import AzureBlobStorage
|
||||
|
||||
return AzureBlobStorage
|
||||
case StorageType.ALIYUN_OSS:
|
||||
from extensions.storage.aliyun_oss_storage import AliyunOssStorage
|
||||
|
||||
return AliyunOssStorage
|
||||
case StorageType.GOOGLE_STORAGE:
|
||||
from extensions.storage.google_cloud_storage import GoogleCloudStorage
|
||||
|
||||
return GoogleCloudStorage
|
||||
case StorageType.TENCENT_COS:
|
||||
from extensions.storage.tencent_cos_storage import TencentCosStorage
|
||||
|
||||
return TencentCosStorage
|
||||
case StorageType.OCI_STORAGE:
|
||||
from extensions.storage.oracle_oci_storage import OracleOCIStorage
|
||||
|
||||
return OracleOCIStorage
|
||||
case StorageType.HUAWEI_OBS:
|
||||
from extensions.storage.huawei_obs_storage import HuaweiObsStorage
|
||||
|
||||
return HuaweiObsStorage
|
||||
case StorageType.BAIDU_OBS:
|
||||
from extensions.storage.baidu_obs_storage import BaiduObsStorage
|
||||
|
||||
return BaiduObsStorage
|
||||
case StorageType.VOLCENGINE_TOS:
|
||||
from extensions.storage.volcengine_tos_storage import VolcengineTosStorage
|
||||
|
||||
return VolcengineTosStorage
|
||||
case StorageType.SUPABASE:
|
||||
from extensions.storage.supabase_storage import SupabaseStorage
|
||||
|
||||
return SupabaseStorage
|
||||
case StorageType.CLICKZETTA_VOLUME:
|
||||
from extensions.storage.clickzetta_volume.clickzetta_volume_storage import (
|
||||
ClickZettaVolumeConfig,
|
||||
ClickZettaVolumeStorage,
|
||||
)
|
||||
|
||||
def create_clickzetta_volume_storage():
|
||||
# ClickZettaVolumeConfig will automatically read from environment variables
|
||||
# and fallback to CLICKZETTA_* config if CLICKZETTA_VOLUME_* is not set
|
||||
volume_config = ClickZettaVolumeConfig()
|
||||
return ClickZettaVolumeStorage(volume_config)
|
||||
|
||||
return create_clickzetta_volume_storage
|
||||
case _:
|
||||
raise ValueError(f"unsupported storage type {storage_type}")
|
||||
|
||||
def save(self, filename: str, data: bytes):
|
||||
self.storage_runner.save(filename, data)
|
||||
|
||||
@overload
|
||||
def load(self, filename: str, /, *, stream: Literal[False] = False) -> bytes: ...
|
||||
|
||||
@overload
|
||||
def load(self, filename: str, /, *, stream: Literal[True]) -> Generator: ...
|
||||
|
||||
# Keep a bool fallback overload for callers that forward a runtime bool flag.
|
||||
@overload
|
||||
def load(self, filename: str, /, *, stream: bool = False) -> bytes | Generator: ...
|
||||
|
||||
def load(self, filename: str, /, *, stream: bool = False) -> bytes | Generator:
|
||||
if stream:
|
||||
return self.load_stream(filename)
|
||||
else:
|
||||
return self.load_once(filename)
|
||||
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
return self.storage_runner.load_once(filename)
|
||||
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
return self.storage_runner.load_stream(filename)
|
||||
|
||||
def download(self, filename, target_filepath):
|
||||
self.storage_runner.download(filename, target_filepath)
|
||||
|
||||
def exists(self, filename):
|
||||
return self.storage_runner.exists(filename)
|
||||
|
||||
def delete(self, filename: str):
|
||||
return self.storage_runner.delete(filename)
|
||||
|
||||
def generate_presigned_url(
|
||||
self,
|
||||
filename: str,
|
||||
*,
|
||||
expires_in: int,
|
||||
content_type: str | None = None,
|
||||
) -> str:
|
||||
return self.storage_runner.generate_presigned_url(
|
||||
filename,
|
||||
expires_in=expires_in,
|
||||
content_type=content_type,
|
||||
)
|
||||
|
||||
def scan(self, path: str, files: bool = True, directories: bool = False) -> list[str]:
|
||||
return self.storage_runner.scan(path, files=files, directories=directories)
|
||||
|
||||
|
||||
storage = Storage()
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
storage.init_app(app)
|
||||
from core.app.workflow import file_runtime
|
||||
|
||||
file_runtime.init_app(app)
|
||||
@@ -0,0 +1,11 @@
|
||||
import os
|
||||
import time
|
||||
|
||||
from dify_app import DifyApp
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
os.environ["TZ"] = "UTC"
|
||||
# windows platform not support tzset
|
||||
if hasattr(time, "tzset"):
|
||||
time.tzset()
|
||||
@@ -0,0 +1,7 @@
|
||||
from dify_app import DifyApp
|
||||
|
||||
|
||||
def init_app(app: DifyApp):
|
||||
import warnings
|
||||
|
||||
warnings.simplefilter("ignore", ResourceWarning)
|
||||
Whitespace-only changes.
@@ -0,0 +1,928 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
import sqlalchemy as sa
|
||||
from aliyun.log import ( # type: ignore[import-untyped]
|
||||
GetLogsRequest,
|
||||
IndexConfig,
|
||||
IndexKeyConfig,
|
||||
IndexLineConfig,
|
||||
LogClient,
|
||||
LogItem,
|
||||
PutLogsRequest,
|
||||
)
|
||||
from aliyun.log.auth import AUTH_VERSION_4 # type: ignore[import-untyped]
|
||||
from aliyun.log.logexception import LogException # type: ignore[import-untyped]
|
||||
from dotenv import load_dotenv
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.logstore.aliyun_logstore_pg import AliyunLogStorePG
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AliyunLogStore:
|
||||
"""
|
||||
Singleton class for Aliyun SLS LogStore operations.
|
||||
|
||||
Ensures only one instance exists to prevent multiple PG connection pools.
|
||||
"""
|
||||
|
||||
_instance: AliyunLogStore | None = None
|
||||
_initialized: bool = False
|
||||
|
||||
# Track delayed PG connection for newly created projects
|
||||
_pg_connection_timer: threading.Timer | None = None
|
||||
_pg_connection_delay: int = 90 # delay seconds
|
||||
|
||||
# Default tokenizer for text/json fields and full-text index
|
||||
# Common delimiters: comma, space, quotes, punctuation, operators, brackets, special chars
|
||||
DEFAULT_TOKEN_LIST = [
|
||||
",",
|
||||
" ",
|
||||
'"',
|
||||
'"',
|
||||
";",
|
||||
"=",
|
||||
"(",
|
||||
")",
|
||||
"[",
|
||||
"]",
|
||||
"{",
|
||||
"}",
|
||||
"?",
|
||||
"@",
|
||||
"&",
|
||||
"<",
|
||||
">",
|
||||
"/",
|
||||
":",
|
||||
"\n",
|
||||
"\t",
|
||||
]
|
||||
|
||||
def __new__(cls) -> AliyunLogStore:
|
||||
"""Implement singleton pattern."""
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
return cls._instance
|
||||
|
||||
project_des = "dify"
|
||||
|
||||
workflow_execution_logstore = "workflow_execution"
|
||||
|
||||
workflow_node_execution_logstore = "workflow_node_execution"
|
||||
|
||||
@staticmethod
|
||||
def _sqlalchemy_type_to_logstore_type(column: Any) -> str:
|
||||
"""
|
||||
Map SQLAlchemy column type to Aliyun LogStore index type.
|
||||
|
||||
Args:
|
||||
column: SQLAlchemy column object
|
||||
|
||||
Returns:
|
||||
LogStore index type: 'text', 'long', 'double', or 'json'
|
||||
"""
|
||||
column_type = column.type
|
||||
|
||||
# Integer types -> long
|
||||
if isinstance(column_type, (sa.Integer, sa.BigInteger, sa.SmallInteger)):
|
||||
return "long"
|
||||
|
||||
# Float types -> double
|
||||
if isinstance(column_type, (sa.Float, sa.Numeric)):
|
||||
return "double"
|
||||
|
||||
# String and Text types -> text
|
||||
if isinstance(column_type, (sa.String, sa.Text)):
|
||||
return "text"
|
||||
|
||||
# DateTime -> text (stored as ISO format string in logstore)
|
||||
if isinstance(column_type, sa.DateTime):
|
||||
return "text"
|
||||
|
||||
# Boolean -> long (stored as 0/1)
|
||||
if isinstance(column_type, sa.Boolean):
|
||||
return "long"
|
||||
|
||||
# JSON -> json
|
||||
if isinstance(column_type, sa.JSON):
|
||||
return "json"
|
||||
|
||||
# Default to text for unknown types
|
||||
return "text"
|
||||
|
||||
@staticmethod
|
||||
def _generate_index_keys_from_model(model_class: type[DeclarativeBase]) -> dict[str, IndexKeyConfig]:
|
||||
"""
|
||||
Automatically generate LogStore field index configuration from SQLAlchemy model.
|
||||
|
||||
This method introspects the SQLAlchemy model's column definitions and creates
|
||||
corresponding LogStore index configurations. When the PG schema is updated via
|
||||
Flask-Migrate, this method will automatically pick up the new fields on next startup.
|
||||
|
||||
Args:
|
||||
model_class: SQLAlchemy model class (e.g., WorkflowRun, WorkflowNodeExecutionModel)
|
||||
|
||||
Returns:
|
||||
Dictionary mapping field names to IndexKeyConfig objects
|
||||
"""
|
||||
index_keys = {}
|
||||
|
||||
# Iterate over all mapped columns in the model
|
||||
if hasattr(model_class, "__mapper__"):
|
||||
for column_name, column_property in model_class.__mapper__.columns.items():
|
||||
# Skip relationship properties and other non-column attributes
|
||||
if not hasattr(column_property, "type"):
|
||||
continue
|
||||
|
||||
# Map SQLAlchemy type to LogStore type
|
||||
logstore_type = AliyunLogStore._sqlalchemy_type_to_logstore_type(column_property)
|
||||
|
||||
# Create index configuration
|
||||
# - text fields: case_insensitive for better search, with tokenizer and Chinese support
|
||||
# - all fields: doc_value=True for analytics
|
||||
if logstore_type == "text":
|
||||
index_keys[column_name] = IndexKeyConfig(
|
||||
index_type="text",
|
||||
case_sensitive=False,
|
||||
doc_value=True,
|
||||
token_list=AliyunLogStore.DEFAULT_TOKEN_LIST,
|
||||
chinese=True,
|
||||
)
|
||||
else:
|
||||
index_keys[column_name] = IndexKeyConfig(index_type=logstore_type, doc_value=True)
|
||||
|
||||
# Add log_version field (not in PG model, but used in logstore for versioning)
|
||||
index_keys["log_version"] = IndexKeyConfig(index_type="long", doc_value=True)
|
||||
|
||||
return index_keys
|
||||
|
||||
def __init__(self) -> None:
|
||||
# Skip initialization if already initialized (singleton pattern)
|
||||
if self.__class__._initialized:
|
||||
return
|
||||
|
||||
load_dotenv()
|
||||
|
||||
self.access_key_id: str = os.environ.get("ALIYUN_SLS_ACCESS_KEY_ID", "")
|
||||
self.access_key_secret: str = os.environ.get("ALIYUN_SLS_ACCESS_KEY_SECRET", "")
|
||||
self.endpoint: str = os.environ.get("ALIYUN_SLS_ENDPOINT", "")
|
||||
self.region: str = os.environ.get("ALIYUN_SLS_REGION", "")
|
||||
self.project_name: str = os.environ.get("ALIYUN_SLS_PROJECT_NAME", "")
|
||||
self.logstore_ttl: int = int(os.environ.get("ALIYUN_SLS_LOGSTORE_TTL", 365))
|
||||
self.log_enabled: bool = (
|
||||
os.environ.get("SQLALCHEMY_ECHO", "false").lower() == "true"
|
||||
or os.environ.get("LOGSTORE_SQL_ECHO", "false").lower() == "true"
|
||||
)
|
||||
self.pg_mode_enabled: bool = os.environ.get("LOGSTORE_PG_MODE_ENABLED", "true").lower() == "true"
|
||||
|
||||
# Get timeout configuration
|
||||
check_timeout = int(os.environ.get("ALIYUN_SLS_CHECK_CONNECTIVITY_TIMEOUT", 30))
|
||||
|
||||
# Pre-check endpoint connectivity to prevent indefinite hangs
|
||||
self._check_endpoint_connectivity(self.endpoint, check_timeout)
|
||||
|
||||
# Initialize SDK client
|
||||
self.client = LogClient(
|
||||
self.endpoint, self.access_key_id, self.access_key_secret, auth_version=AUTH_VERSION_4, region=self.region
|
||||
)
|
||||
|
||||
# Append Dify identification to the existing user agent
|
||||
original_user_agent = self.client._user_agent
|
||||
dify_version = dify_config.project.version
|
||||
enhanced_user_agent = f"Dify,Dify-{dify_version},{original_user_agent}"
|
||||
self.client.set_user_agent(enhanced_user_agent)
|
||||
|
||||
# PG client will be initialized in init_project_logstore
|
||||
self._pg_client: AliyunLogStorePG | None = None
|
||||
self._use_pg_protocol: bool = False
|
||||
|
||||
self.__class__._initialized = True
|
||||
|
||||
@staticmethod
|
||||
def _check_endpoint_connectivity(endpoint: str, timeout: int) -> None:
|
||||
"""
|
||||
Check if the SLS endpoint is reachable before creating LogClient.
|
||||
Prevents indefinite hangs when the endpoint is unreachable.
|
||||
|
||||
Args:
|
||||
endpoint: SLS endpoint URL
|
||||
timeout: Connection timeout in seconds
|
||||
|
||||
Raises:
|
||||
ConnectionError: If endpoint is not reachable
|
||||
"""
|
||||
# Parse endpoint URL to extract hostname and port
|
||||
from urllib.parse import urlparse
|
||||
|
||||
parsed_url = urlparse(endpoint if "://" in endpoint else f"http://{endpoint}")
|
||||
hostname = parsed_url.hostname
|
||||
port = parsed_url.port or (443 if parsed_url.scheme == "https" else 80)
|
||||
|
||||
if not hostname:
|
||||
raise ConnectionError(f"Invalid endpoint URL: {endpoint}")
|
||||
|
||||
sock = None
|
||||
try:
|
||||
# Create socket and set timeout
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(timeout)
|
||||
sock.connect((hostname, port))
|
||||
except Exception as e:
|
||||
# Catch all exceptions and provide clear error message
|
||||
error_type = type(e).__name__
|
||||
raise ConnectionError(
|
||||
f"Cannot connect to {hostname}:{port} (timeout={timeout}s): [{error_type}] {e}"
|
||||
) from e
|
||||
finally:
|
||||
# Ensure socket is properly closed
|
||||
if sock:
|
||||
# Ignore errors during cleanup
|
||||
with contextlib.suppress(Exception):
|
||||
sock.close()
|
||||
|
||||
@property
|
||||
def supports_pg_protocol(self) -> bool:
|
||||
"""Check if PG protocol is supported and enabled."""
|
||||
return self._use_pg_protocol
|
||||
|
||||
def _attempt_pg_connection_init(self) -> bool:
|
||||
"""
|
||||
Attempt to initialize PG connection.
|
||||
|
||||
This method tries to establish PG connection and performs necessary checks.
|
||||
It's used both for immediate connection (existing projects) and delayed connection (new projects).
|
||||
|
||||
Returns:
|
||||
True if PG connection was successfully established, False otherwise.
|
||||
"""
|
||||
if not self.pg_mode_enabled or not self._pg_client:
|
||||
return False
|
||||
|
||||
try:
|
||||
self._use_pg_protocol = self._pg_client.init_connection()
|
||||
if self._use_pg_protocol:
|
||||
logger.info("Using PG protocol for project %s", self.project_name)
|
||||
# Check if scan_index is enabled for all logstores
|
||||
self._check_and_disable_pg_if_scan_index_disabled()
|
||||
return True
|
||||
else:
|
||||
logger.info("Using SDK mode for project %s", self.project_name)
|
||||
return False
|
||||
except Exception:
|
||||
logger.info("Using SDK mode for project %s", self.project_name)
|
||||
logger.debug("PG connection details", exc_info=True)
|
||||
self._use_pg_protocol = False
|
||||
return False
|
||||
|
||||
def _delayed_pg_connection_init(self) -> None:
|
||||
"""
|
||||
Delayed initialization of PG connection for newly created projects.
|
||||
|
||||
This method is called by a background timer 3 minutes after project creation.
|
||||
"""
|
||||
# Double check conditions in case state changed
|
||||
if self._use_pg_protocol:
|
||||
return
|
||||
|
||||
self._attempt_pg_connection_init()
|
||||
self.__class__._pg_connection_timer = None
|
||||
|
||||
def init_project_logstore(self):
|
||||
"""
|
||||
Initialize project, logstore, index, and PG connection.
|
||||
|
||||
This method should be called once during application startup to ensure
|
||||
all required resources exist and connections are established.
|
||||
"""
|
||||
# Step 1: Ensure project and logstore exist
|
||||
project_is_new = False
|
||||
if not self.is_project_exist():
|
||||
self.create_project()
|
||||
project_is_new = True
|
||||
|
||||
self.create_logstore_if_not_exist()
|
||||
|
||||
# Step 2: Initialize PG client and connection (if enabled)
|
||||
if not self.pg_mode_enabled:
|
||||
logger.info("PG mode is disabled. Will use SDK mode.")
|
||||
return
|
||||
|
||||
# Create PG client if not already created
|
||||
if self._pg_client is None:
|
||||
logger.info("Initializing PG client for project %s...", self.project_name)
|
||||
self._pg_client = AliyunLogStorePG(
|
||||
self.access_key_id, self.access_key_secret, self.endpoint, self.project_name
|
||||
)
|
||||
|
||||
# Step 3: Establish PG connection based on project status
|
||||
if project_is_new:
|
||||
# For newly created projects, schedule delayed PG connection
|
||||
self._use_pg_protocol = False
|
||||
logger.info("Using SDK mode for project %s (newly created)", self.project_name)
|
||||
if self.__class__._pg_connection_timer is not None:
|
||||
self.__class__._pg_connection_timer.cancel()
|
||||
self.__class__._pg_connection_timer = threading.Timer(
|
||||
self.__class__._pg_connection_delay,
|
||||
self._delayed_pg_connection_init,
|
||||
)
|
||||
self.__class__._pg_connection_timer.daemon = True # Don't block app shutdown
|
||||
self.__class__._pg_connection_timer.start()
|
||||
else:
|
||||
# For existing projects, attempt PG connection immediately
|
||||
self._attempt_pg_connection_init()
|
||||
|
||||
def _check_and_disable_pg_if_scan_index_disabled(self) -> None:
|
||||
"""
|
||||
Check if scan_index is enabled for all logstores.
|
||||
If any logstore has scan_index=false, disable PG protocol.
|
||||
|
||||
This is necessary because PG protocol requires scan_index to be enabled.
|
||||
"""
|
||||
logstore_name_list = [
|
||||
AliyunLogStore.workflow_execution_logstore,
|
||||
AliyunLogStore.workflow_node_execution_logstore,
|
||||
]
|
||||
|
||||
for logstore_name in logstore_name_list:
|
||||
existing_config = self.get_existing_index_config(logstore_name)
|
||||
if existing_config and not existing_config.scan_index:
|
||||
logger.info(
|
||||
"Logstore %s requires scan_index enabled, using SDK mode for project %s",
|
||||
logstore_name,
|
||||
self.project_name,
|
||||
)
|
||||
self._use_pg_protocol = False
|
||||
# Close PG connection if it was initialized
|
||||
if self._pg_client:
|
||||
self._pg_client.close()
|
||||
self._pg_client = None
|
||||
return
|
||||
|
||||
def is_project_exist(self) -> bool:
|
||||
try:
|
||||
self.client.get_project(self.project_name)
|
||||
return True
|
||||
except Exception as e:
|
||||
if e.args[0] == "ProjectNotExist":
|
||||
return False
|
||||
else:
|
||||
raise e
|
||||
|
||||
def create_project(self):
|
||||
try:
|
||||
self.client.create_project(self.project_name, AliyunLogStore.project_des)
|
||||
logger.info("Project %s created successfully", self.project_name)
|
||||
except LogException as e:
|
||||
logger.exception(
|
||||
"Failed to create project %s: errorCode=%s, errorMessage=%s, requestId=%s",
|
||||
self.project_name,
|
||||
e.get_error_code(),
|
||||
e.get_error_message(),
|
||||
e.get_request_id(),
|
||||
)
|
||||
raise
|
||||
|
||||
def is_logstore_exist(self, logstore_name: str) -> bool:
|
||||
try:
|
||||
_ = self.client.get_logstore(self.project_name, logstore_name)
|
||||
return True
|
||||
except Exception as e:
|
||||
if e.args[0] == "LogStoreNotExist":
|
||||
return False
|
||||
else:
|
||||
raise e
|
||||
|
||||
def create_logstore_if_not_exist(self) -> None:
|
||||
logstore_name_list = [
|
||||
AliyunLogStore.workflow_execution_logstore,
|
||||
AliyunLogStore.workflow_node_execution_logstore,
|
||||
]
|
||||
|
||||
for logstore_name in logstore_name_list:
|
||||
if not self.is_logstore_exist(logstore_name):
|
||||
try:
|
||||
self.client.create_logstore(
|
||||
project_name=self.project_name, logstore_name=logstore_name, ttl=self.logstore_ttl
|
||||
)
|
||||
logger.info("logstore %s created successfully", logstore_name)
|
||||
except LogException as e:
|
||||
logger.exception(
|
||||
"Failed to create logstore %s: errorCode=%s, errorMessage=%s, requestId=%s",
|
||||
logstore_name,
|
||||
e.get_error_code(),
|
||||
e.get_error_message(),
|
||||
e.get_request_id(),
|
||||
)
|
||||
raise
|
||||
|
||||
# Ensure index contains all Dify-required fields
|
||||
# This intelligently merges with existing config, preserving custom indexes
|
||||
self.ensure_index_config(logstore_name)
|
||||
|
||||
def is_index_exist(self, logstore_name: str) -> bool:
|
||||
try:
|
||||
_ = self.client.get_index_config(self.project_name, logstore_name)
|
||||
return True
|
||||
except Exception as e:
|
||||
if e.args[0] == "IndexConfigNotExist":
|
||||
return False
|
||||
else:
|
||||
raise e
|
||||
|
||||
def get_existing_index_config(self, logstore_name: str) -> IndexConfig | None:
|
||||
"""
|
||||
Get existing index configuration from logstore.
|
||||
|
||||
Args:
|
||||
logstore_name: Name of the logstore
|
||||
|
||||
Returns:
|
||||
IndexConfig object if index exists, None otherwise
|
||||
"""
|
||||
try:
|
||||
response = self.client.get_index_config(self.project_name, logstore_name)
|
||||
return response.get_index_config()
|
||||
except Exception as e:
|
||||
if e.args[0] == "IndexConfigNotExist":
|
||||
return None
|
||||
else:
|
||||
logger.exception("Failed to get index config for logstore %s", logstore_name)
|
||||
raise e
|
||||
|
||||
def _get_workflow_execution_index_keys(self) -> dict[str, IndexKeyConfig]:
|
||||
"""
|
||||
Get field index configuration for workflow_execution logstore.
|
||||
|
||||
This method automatically generates index configuration from the WorkflowRun SQLAlchemy model.
|
||||
When the PG schema is updated via Flask-Migrate, the index configuration will be automatically
|
||||
updated on next application startup.
|
||||
"""
|
||||
from models.workflow import WorkflowRun
|
||||
|
||||
index_keys = self._generate_index_keys_from_model(WorkflowRun)
|
||||
|
||||
# Add custom fields that are in logstore but not in PG model
|
||||
# These fields are added by the repository layer
|
||||
index_keys["error_message"] = IndexKeyConfig(
|
||||
index_type="text",
|
||||
case_sensitive=False,
|
||||
doc_value=True,
|
||||
token_list=self.DEFAULT_TOKEN_LIST,
|
||||
chinese=True,
|
||||
) # Maps to 'error' in PG
|
||||
index_keys["started_at"] = IndexKeyConfig(
|
||||
index_type="text",
|
||||
case_sensitive=False,
|
||||
doc_value=True,
|
||||
token_list=self.DEFAULT_TOKEN_LIST,
|
||||
chinese=True,
|
||||
) # Maps to 'created_at' in PG
|
||||
|
||||
logger.info("Generated %d index keys for workflow_execution from WorkflowRun model", len(index_keys))
|
||||
return index_keys
|
||||
|
||||
def _get_workflow_node_execution_index_keys(self) -> dict[str, IndexKeyConfig]:
|
||||
"""
|
||||
Get field index configuration for workflow_node_execution logstore.
|
||||
|
||||
This method automatically generates index configuration from the WorkflowNodeExecutionModel.
|
||||
When the PG schema is updated via Flask-Migrate, the index configuration will be automatically
|
||||
updated on next application startup.
|
||||
"""
|
||||
from models.workflow import WorkflowNodeExecutionModel
|
||||
|
||||
index_keys = self._generate_index_keys_from_model(WorkflowNodeExecutionModel)
|
||||
|
||||
logger.debug(
|
||||
"Generated %d index keys for workflow_node_execution from WorkflowNodeExecutionModel", len(index_keys)
|
||||
)
|
||||
return index_keys
|
||||
|
||||
def _get_index_config(self, logstore_name: str) -> IndexConfig:
|
||||
"""
|
||||
Get index configuration for the specified logstore.
|
||||
|
||||
Args:
|
||||
logstore_name: Name of the logstore
|
||||
|
||||
Returns:
|
||||
IndexConfig object with line and field indexes
|
||||
"""
|
||||
# Create full-text index (line config) with tokenizer
|
||||
line_config = IndexLineConfig(token_list=self.DEFAULT_TOKEN_LIST, case_sensitive=False, chinese=True)
|
||||
|
||||
# Get field index configuration based on logstore name
|
||||
field_keys = {}
|
||||
if logstore_name == AliyunLogStore.workflow_execution_logstore:
|
||||
field_keys = self._get_workflow_execution_index_keys()
|
||||
elif logstore_name == AliyunLogStore.workflow_node_execution_logstore:
|
||||
field_keys = self._get_workflow_node_execution_index_keys()
|
||||
|
||||
# key_config_list should be a dict, not a list
|
||||
# Create index config with both line and field indexes
|
||||
return IndexConfig(line_config=line_config, key_config_list=field_keys, scan_index=True)
|
||||
|
||||
def create_index(self, logstore_name: str) -> None:
|
||||
"""
|
||||
Create index for the specified logstore with both full-text and field indexes.
|
||||
Field indexes are automatically generated from the corresponding SQLAlchemy model.
|
||||
"""
|
||||
index_config = self._get_index_config(logstore_name)
|
||||
|
||||
try:
|
||||
self.client.create_index(self.project_name, logstore_name, index_config)
|
||||
logger.info(
|
||||
"index for %s created successfully with %d field indexes",
|
||||
logstore_name,
|
||||
len(index_config.key_config_list or {}),
|
||||
)
|
||||
except LogException as e:
|
||||
logger.exception(
|
||||
"Failed to create index for logstore %s: errorCode=%s, errorMessage=%s, requestId=%s",
|
||||
logstore_name,
|
||||
e.get_error_code(),
|
||||
e.get_error_message(),
|
||||
e.get_request_id(),
|
||||
)
|
||||
raise
|
||||
|
||||
def _merge_index_configs(
|
||||
self, existing_config: IndexConfig, required_keys: dict[str, IndexKeyConfig], logstore_name: str
|
||||
) -> tuple[IndexConfig, bool]:
|
||||
"""
|
||||
Intelligently merge existing index config with Dify's required field indexes.
|
||||
|
||||
This method:
|
||||
1. Preserves all existing field indexes in logstore (including custom fields)
|
||||
2. Adds missing Dify-required fields
|
||||
3. Updates fields where type doesn't match (with json/text compatibility)
|
||||
4. Corrects case mismatches (e.g., if Dify needs 'status' but logstore has 'Status')
|
||||
|
||||
Type compatibility rules:
|
||||
- json and text types are considered compatible (users can manually choose either)
|
||||
- All other type mismatches will be corrected to match Dify requirements
|
||||
|
||||
Note: Logstore is case-sensitive and doesn't allow duplicate fields with different cases.
|
||||
Case mismatch means: existing field name differs from required name only in case.
|
||||
|
||||
Args:
|
||||
existing_config: Current index configuration from logstore
|
||||
required_keys: Dify's required field index configurations
|
||||
logstore_name: Name of the logstore (for logging)
|
||||
|
||||
Returns:
|
||||
Tuple of (merged_config, needs_update)
|
||||
"""
|
||||
# key_config_list is already a dict in the SDK
|
||||
# Make a copy to avoid modifying the original
|
||||
existing_keys = dict(existing_config.key_config_list) if existing_config.key_config_list else {}
|
||||
|
||||
# Track changes
|
||||
needs_update = False
|
||||
case_corrections = [] # Fields that need case correction (e.g., 'Status' -> 'status')
|
||||
missing_fields = []
|
||||
type_mismatches = []
|
||||
|
||||
# First pass: Check for and resolve case mismatches with required fields
|
||||
# Note: Logstore itself doesn't allow duplicate fields with different cases,
|
||||
# so we only need to check if the existing case matches the required case
|
||||
for required_name in required_keys:
|
||||
lower_name = required_name.lower()
|
||||
# Find key that matches case-insensitively but not exactly
|
||||
wrong_case_key = None
|
||||
for existing_key in existing_keys:
|
||||
if existing_key.lower() == lower_name and existing_key != required_name:
|
||||
wrong_case_key = existing_key
|
||||
break
|
||||
|
||||
if wrong_case_key:
|
||||
# Field exists but with wrong case (e.g., 'Status' when we need 'status')
|
||||
# Remove the wrong-case key, will be added back with correct case later
|
||||
case_corrections.append((wrong_case_key, required_name))
|
||||
del existing_keys[wrong_case_key]
|
||||
needs_update = True
|
||||
|
||||
# Second pass: Check each required field
|
||||
for required_name, required_config in required_keys.items():
|
||||
# Check for exact match (case-sensitive)
|
||||
if required_name in existing_keys:
|
||||
existing_type = existing_keys[required_name].index_type
|
||||
required_type = required_config.index_type
|
||||
|
||||
# Check if type matches
|
||||
# Special case: json and text are interchangeable for JSON content fields
|
||||
# Allow users to manually configure text instead of json (or vice versa) without forcing updates
|
||||
is_compatible = existing_type == required_type or ({existing_type, required_type} == {"json", "text"})
|
||||
|
||||
if not is_compatible:
|
||||
type_mismatches.append((required_name, existing_type, required_type))
|
||||
# Update with correct type
|
||||
existing_keys[required_name] = required_config
|
||||
needs_update = True
|
||||
# else: field exists with compatible type, no action needed
|
||||
else:
|
||||
# Field doesn't exist (may have been removed in first pass due to case conflict)
|
||||
missing_fields.append(required_name)
|
||||
existing_keys[required_name] = required_config
|
||||
needs_update = True
|
||||
|
||||
# Log changes
|
||||
if missing_fields:
|
||||
logger.info(
|
||||
"Logstore %s: Adding %d missing Dify-required fields: %s",
|
||||
logstore_name,
|
||||
len(missing_fields),
|
||||
", ".join(missing_fields[:10]) + ("..." if len(missing_fields) > 10 else ""),
|
||||
)
|
||||
|
||||
if type_mismatches:
|
||||
logger.info(
|
||||
"Logstore %s: Fixing %d type mismatches: %s",
|
||||
logstore_name,
|
||||
len(type_mismatches),
|
||||
", ".join([f"{name}({old}->{new})" for name, old, new in type_mismatches[:5]])
|
||||
+ ("..." if len(type_mismatches) > 5 else ""),
|
||||
)
|
||||
|
||||
if case_corrections:
|
||||
logger.info(
|
||||
"Logstore %s: Correcting %d field name cases: %s",
|
||||
logstore_name,
|
||||
len(case_corrections),
|
||||
", ".join([f"'{old}' -> '{new}'" for old, new in case_corrections[:5]])
|
||||
+ ("..." if len(case_corrections) > 5 else ""),
|
||||
)
|
||||
|
||||
# Create merged config
|
||||
# key_config_list should be a dict, not a list
|
||||
# Preserve the original scan_index value - don't force it to True
|
||||
merged_config = IndexConfig(
|
||||
line_config=existing_config.line_config
|
||||
or IndexLineConfig(token_list=self.DEFAULT_TOKEN_LIST, case_sensitive=False, chinese=True),
|
||||
key_config_list=existing_keys,
|
||||
scan_index=existing_config.scan_index,
|
||||
)
|
||||
|
||||
return merged_config, needs_update
|
||||
|
||||
def ensure_index_config(self, logstore_name: str) -> None:
|
||||
"""
|
||||
Ensure index configuration includes all Dify-required fields.
|
||||
|
||||
This method intelligently manages index configuration:
|
||||
1. If index doesn't exist, create it with Dify's required fields
|
||||
2. If index exists:
|
||||
- Check if all Dify-required fields are present
|
||||
- Check if field types match requirements
|
||||
- Only update if fields are missing or types are incorrect
|
||||
- Preserve any additional custom index configurations
|
||||
|
||||
This approach allows users to add their own custom indexes without being overwritten.
|
||||
"""
|
||||
# Get Dify's required field indexes
|
||||
required_keys = {}
|
||||
if logstore_name == AliyunLogStore.workflow_execution_logstore:
|
||||
required_keys = self._get_workflow_execution_index_keys()
|
||||
elif logstore_name == AliyunLogStore.workflow_node_execution_logstore:
|
||||
required_keys = self._get_workflow_node_execution_index_keys()
|
||||
|
||||
# Check if index exists
|
||||
existing_config = self.get_existing_index_config(logstore_name)
|
||||
|
||||
if existing_config is None:
|
||||
# Index doesn't exist, create it
|
||||
logger.info(
|
||||
"Logstore %s: Index doesn't exist, creating with %d required fields",
|
||||
logstore_name,
|
||||
len(required_keys),
|
||||
)
|
||||
self.create_index(logstore_name)
|
||||
else:
|
||||
merged_config, needs_update = self._merge_index_configs(existing_config, required_keys, logstore_name)
|
||||
|
||||
if needs_update:
|
||||
logger.info("Logstore %s: Updating index to include Dify-required fields", logstore_name)
|
||||
try:
|
||||
self.client.update_index(self.project_name, logstore_name, merged_config)
|
||||
logger.info(
|
||||
"Logstore %s: Index updated successfully, now has %d total field indexes",
|
||||
logstore_name,
|
||||
len(merged_config.key_config_list or {}),
|
||||
)
|
||||
except LogException as e:
|
||||
logger.exception(
|
||||
"Failed to update index for logstore %s: errorCode=%s, errorMessage=%s, requestId=%s",
|
||||
logstore_name,
|
||||
e.get_error_code(),
|
||||
e.get_error_message(),
|
||||
e.get_request_id(),
|
||||
)
|
||||
raise
|
||||
else:
|
||||
logger.info(
|
||||
"Logstore %s: Index already contains all %d Dify-required fields with correct types, "
|
||||
"no update needed",
|
||||
logstore_name,
|
||||
len(required_keys),
|
||||
)
|
||||
|
||||
def put_log(self, logstore: str, contents: Sequence[tuple[str, str]]) -> None:
|
||||
# Route to PG or SDK based on protocol availability
|
||||
if self._use_pg_protocol and self._pg_client:
|
||||
self._pg_client.put_log(logstore, contents, self.log_enabled)
|
||||
else:
|
||||
log_item = LogItem(contents=contents)
|
||||
request = PutLogsRequest(project=self.project_name, logstore=logstore, logitems=[log_item])
|
||||
|
||||
if self.log_enabled:
|
||||
logger.info(
|
||||
"[LogStore-SDK] PUT_LOG | logstore=%s | project=%s | items_count=%d",
|
||||
logstore,
|
||||
self.project_name,
|
||||
len(contents),
|
||||
)
|
||||
|
||||
try:
|
||||
self.client.put_logs(request)
|
||||
except LogException as e:
|
||||
logger.exception(
|
||||
"Failed to put logs to logstore %s: errorCode=%s, errorMessage=%s, requestId=%s",
|
||||
logstore,
|
||||
e.get_error_code(),
|
||||
e.get_error_message(),
|
||||
e.get_request_id(),
|
||||
)
|
||||
raise
|
||||
|
||||
def get_logs(
|
||||
self,
|
||||
logstore: str,
|
||||
from_time: int,
|
||||
to_time: int,
|
||||
topic: str = "",
|
||||
query: str = "",
|
||||
line: int = 100,
|
||||
offset: int = 0,
|
||||
reverse: bool = True,
|
||||
) -> list[dict]:
|
||||
request = GetLogsRequest(
|
||||
project=self.project_name,
|
||||
logstore=logstore,
|
||||
fromTime=from_time,
|
||||
toTime=to_time,
|
||||
topic=topic,
|
||||
query=query,
|
||||
line=line,
|
||||
offset=offset,
|
||||
reverse=reverse,
|
||||
)
|
||||
|
||||
if self.log_enabled:
|
||||
logger.info(
|
||||
"[LogStore] GET_LOGS | logstore=%s | project=%s | query=%s | "
|
||||
"from_time=%d | to_time=%d | line=%d | offset=%d | reverse=%s",
|
||||
logstore,
|
||||
self.project_name,
|
||||
query,
|
||||
from_time,
|
||||
to_time,
|
||||
line,
|
||||
offset,
|
||||
reverse,
|
||||
)
|
||||
|
||||
try:
|
||||
response = self.client.get_logs(request)
|
||||
result = []
|
||||
logs = response.get_logs() if response else []
|
||||
for log in logs:
|
||||
result.append(log.get_contents())
|
||||
|
||||
if self.log_enabled:
|
||||
logger.info(
|
||||
"[LogStore] GET_LOGS RESULT | logstore=%s | returned_count=%d",
|
||||
logstore,
|
||||
len(result),
|
||||
)
|
||||
|
||||
return result
|
||||
except LogException as e:
|
||||
logger.exception(
|
||||
"Failed to get logs from logstore %s with query '%s': errorCode=%s, errorMessage=%s, requestId=%s",
|
||||
logstore,
|
||||
query,
|
||||
e.get_error_code(),
|
||||
e.get_error_message(),
|
||||
e.get_request_id(),
|
||||
)
|
||||
raise
|
||||
|
||||
def execute_sql(
|
||||
self,
|
||||
sql: str,
|
||||
logstore: str | None = None,
|
||||
query: str = "*",
|
||||
from_time: int | None = None,
|
||||
to_time: int | None = None,
|
||||
power_sql: bool = False,
|
||||
) -> list[dict]:
|
||||
"""
|
||||
Execute SQL query for aggregation and analysis.
|
||||
|
||||
Args:
|
||||
sql: SQL query string (SELECT statement)
|
||||
logstore: Name of the logstore (required)
|
||||
query: Search/filter query for SDK mode (default: "*" for all logs).
|
||||
Only used in SDK mode. PG mode ignores this parameter.
|
||||
from_time: Start time (Unix timestamp) - only used in SDK mode
|
||||
to_time: End time (Unix timestamp) - only used in SDK mode
|
||||
power_sql: Whether to use enhanced SQL mode (default: False)
|
||||
|
||||
Returns:
|
||||
List of result rows as dictionaries
|
||||
|
||||
Note:
|
||||
- PG mode: Only executes the SQL directly
|
||||
- SDK mode: Combines query and sql as "query | sql"
|
||||
"""
|
||||
# Logstore is required
|
||||
if not logstore:
|
||||
raise ValueError("logstore parameter is required for execute_sql")
|
||||
|
||||
# Route to PG or SDK based on protocol availability
|
||||
if self._use_pg_protocol and self._pg_client:
|
||||
# PG mode: execute SQL directly (ignore query parameter)
|
||||
return self._pg_client.execute_sql(sql, logstore, self.log_enabled)
|
||||
else:
|
||||
# SDK mode: combine query and sql as "query | sql"
|
||||
full_query = f"{query} | {sql}"
|
||||
|
||||
# Provide default time range if not specified
|
||||
if from_time is None:
|
||||
from_time = 0
|
||||
|
||||
if to_time is None:
|
||||
to_time = int(time.time()) # now
|
||||
|
||||
request = GetLogsRequest(
|
||||
project=self.project_name,
|
||||
logstore=logstore,
|
||||
fromTime=from_time,
|
||||
toTime=to_time,
|
||||
query=full_query,
|
||||
)
|
||||
|
||||
if self.log_enabled:
|
||||
logger.info(
|
||||
"[LogStore-SDK] EXECUTE_SQL | logstore=%s | project=%s | from_time=%d | to_time=%d | full_query=%s",
|
||||
logstore,
|
||||
self.project_name,
|
||||
from_time,
|
||||
to_time,
|
||||
full_query,
|
||||
)
|
||||
|
||||
try:
|
||||
response = self.client.get_logs(request)
|
||||
|
||||
result = []
|
||||
logs = response.get_logs() if response else []
|
||||
for log in logs:
|
||||
result.append(log.get_contents())
|
||||
|
||||
if self.log_enabled:
|
||||
logger.info(
|
||||
"[LogStore-SDK] EXECUTE_SQL RESULT | logstore=%s | returned_count=%d",
|
||||
logstore,
|
||||
len(result),
|
||||
)
|
||||
|
||||
return result
|
||||
except LogException as e:
|
||||
logger.exception(
|
||||
"Failed to execute SQL, logstore %s: errorCode=%s, errorMessage=%s, requestId=%s, full_query=%s",
|
||||
logstore,
|
||||
e.get_error_code(),
|
||||
e.get_error_message(),
|
||||
e.get_request_id(),
|
||||
full_query,
|
||||
)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
aliyun_logstore = AliyunLogStore()
|
||||
# aliyun_logstore.init_project_logstore()
|
||||
aliyun_logstore.put_log(AliyunLogStore.workflow_execution_logstore, [("key1", "value1")])
|
||||
@@ -0,0 +1,272 @@
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
from collections.abc import Sequence
|
||||
from contextlib import contextmanager
|
||||
from typing import Any
|
||||
|
||||
import psycopg2
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
from configs import dify_config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AliyunLogStorePG:
|
||||
"""PostgreSQL protocol support for Aliyun SLS LogStore using SQLAlchemy connection pool."""
|
||||
|
||||
def __init__(self, access_key_id: str, access_key_secret: str, endpoint: str, project_name: str):
|
||||
"""
|
||||
Initialize PG connection for SLS.
|
||||
|
||||
Args:
|
||||
access_key_id: Aliyun access key ID
|
||||
access_key_secret: Aliyun access key secret
|
||||
endpoint: SLS endpoint
|
||||
project_name: SLS project name
|
||||
"""
|
||||
self._access_key_id = access_key_id
|
||||
self._access_key_secret = access_key_secret
|
||||
self._endpoint = endpoint
|
||||
self.project_name = project_name
|
||||
self._engine: Any = None # SQLAlchemy Engine
|
||||
self._use_pg_protocol = False
|
||||
|
||||
def _check_port_connectivity(self, host: str, port: int, timeout: float = 2.0) -> bool:
|
||||
"""Fast TCP port check to avoid long waits on unsupported regions."""
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(timeout)
|
||||
result = sock.connect_ex((host, port))
|
||||
sock.close()
|
||||
return result == 0
|
||||
except Exception:
|
||||
logger.debug("Port connectivity check failed for %s:%d", host, port, exc_info=True)
|
||||
return False
|
||||
|
||||
def init_connection(self) -> bool:
|
||||
"""Initialize SQLAlchemy connection pool with pool_recycle and TCP keepalive support."""
|
||||
try:
|
||||
pg_host = self._endpoint.replace("http://", "").replace("https://", "")
|
||||
|
||||
# Pool configuration
|
||||
pool_size = int(os.environ.get("ALIYUN_SLS_PG_POOL_SIZE", 5))
|
||||
max_overflow = int(os.environ.get("ALIYUN_SLS_PG_MAX_OVERFLOW", 5))
|
||||
pool_recycle = int(os.environ.get("ALIYUN_SLS_PG_POOL_RECYCLE", 3600))
|
||||
pool_pre_ping = os.environ.get("ALIYUN_SLS_PG_POOL_PRE_PING", "false").lower() == "true"
|
||||
|
||||
logger.debug("Check PG protocol connection to SLS: host=%s, project=%s", pg_host, self.project_name)
|
||||
|
||||
# Fast port check to avoid long waits
|
||||
if not self._check_port_connectivity(pg_host, 5432, timeout=1.0):
|
||||
logger.debug("Using SDK mode for host=%s", pg_host)
|
||||
return False
|
||||
|
||||
# Build connection URL
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
username = quote_plus(self._access_key_id)
|
||||
password = quote_plus(self._access_key_secret)
|
||||
database_url = (
|
||||
f"postgresql+psycopg2://{username}:{password}@{pg_host}:5432/{self.project_name}?sslmode=require"
|
||||
)
|
||||
|
||||
# Create SQLAlchemy engine with connection pool
|
||||
self._engine = create_engine(
|
||||
database_url,
|
||||
pool_size=pool_size,
|
||||
max_overflow=max_overflow,
|
||||
pool_recycle=pool_recycle,
|
||||
pool_pre_ping=pool_pre_ping,
|
||||
pool_timeout=30,
|
||||
connect_args={
|
||||
"connect_timeout": 5,
|
||||
"application_name": f"Dify-{dify_config.project.version}-fixautocommit",
|
||||
"keepalives": 1,
|
||||
"keepalives_idle": 60,
|
||||
"keepalives_interval": 10,
|
||||
"keepalives_count": 5,
|
||||
},
|
||||
)
|
||||
|
||||
self._use_pg_protocol = True
|
||||
logger.info(
|
||||
"PG protocol initialized for SLS project=%s (pool_size=%d, pool_recycle=%ds)",
|
||||
self.project_name,
|
||||
pool_size,
|
||||
pool_recycle,
|
||||
)
|
||||
return True
|
||||
|
||||
except Exception:
|
||||
self._use_pg_protocol = False
|
||||
if self._engine:
|
||||
try:
|
||||
self._engine.dispose()
|
||||
except Exception:
|
||||
logger.debug("Failed to dispose engine during cleanup, ignoring")
|
||||
self._engine = None
|
||||
|
||||
logger.debug("Using SDK mode for region", exc_info=True)
|
||||
return False
|
||||
|
||||
@contextmanager
|
||||
def _get_connection(self):
|
||||
"""Get connection from SQLAlchemy pool. Pool handles recycle, invalidation, and keepalive automatically."""
|
||||
if not self._engine:
|
||||
raise RuntimeError("SQLAlchemy engine is not initialized")
|
||||
|
||||
connection = self._engine.raw_connection()
|
||||
try:
|
||||
connection.autocommit = True # SLS PG protocol does not support transactions
|
||||
yield connection
|
||||
except Exception:
|
||||
raise
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def close(self) -> None:
|
||||
"""Dispose SQLAlchemy engine and close all connections."""
|
||||
if self._engine:
|
||||
try:
|
||||
self._engine.dispose()
|
||||
logger.info("SQLAlchemy engine disposed")
|
||||
except Exception:
|
||||
logger.exception("Failed to dispose engine")
|
||||
|
||||
def _is_retriable_error(self, error: Exception) -> bool:
|
||||
"""Check if error is retriable (connection-related issues)."""
|
||||
# Check for psycopg2 connection errors directly
|
||||
if isinstance(error, (psycopg2.OperationalError, psycopg2.InterfaceError)):
|
||||
return True
|
||||
|
||||
error_msg = str(error).lower()
|
||||
retriable_patterns = [
|
||||
"connection",
|
||||
"timeout",
|
||||
"closed",
|
||||
"broken pipe",
|
||||
"reset by peer",
|
||||
"no route to host",
|
||||
"network",
|
||||
"operational error",
|
||||
"interface error",
|
||||
]
|
||||
return any(pattern in error_msg for pattern in retriable_patterns)
|
||||
|
||||
def put_log(self, logstore: str, contents: Sequence[tuple[str, str]], log_enabled: bool = False) -> None:
|
||||
"""Write log to SLS using INSERT with automatic retry (3 attempts with exponential backoff)."""
|
||||
if not contents:
|
||||
return
|
||||
|
||||
fields = [field_name for field_name, _ in contents]
|
||||
values = [value for _, value in contents]
|
||||
field_list = ", ".join([f'"{field}"' for field in fields])
|
||||
|
||||
if log_enabled:
|
||||
logger.info(
|
||||
"[LogStore-PG] PUT_LOG | logstore=%s | project=%s | items_count=%d",
|
||||
logstore,
|
||||
self.project_name,
|
||||
len(contents),
|
||||
)
|
||||
|
||||
max_retries = 3
|
||||
retry_delay = 0.1
|
||||
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
with self._get_connection() as conn:
|
||||
with conn.cursor() as cursor:
|
||||
placeholders = ", ".join(["%s"] * len(fields))
|
||||
values_literal = cursor.mogrify(f"({placeholders})", values).decode("utf-8")
|
||||
insert_sql = f'INSERT INTO "{logstore}" ({field_list}) VALUES {values_literal}'
|
||||
cursor.execute(insert_sql)
|
||||
return
|
||||
|
||||
except psycopg2.Error as e:
|
||||
if not self._is_retriable_error(e):
|
||||
logger.exception("Failed to put logs to logstore %s (non-retriable error)", logstore)
|
||||
raise
|
||||
|
||||
if attempt < max_retries - 1:
|
||||
logger.warning(
|
||||
"Failed to put logs to logstore %s (attempt %d/%d): %s. Retrying...",
|
||||
logstore,
|
||||
attempt + 1,
|
||||
max_retries,
|
||||
str(e),
|
||||
)
|
||||
time.sleep(retry_delay)
|
||||
retry_delay *= 2
|
||||
else:
|
||||
logger.exception("Failed to put logs to logstore %s after %d attempts", logstore, max_retries)
|
||||
raise
|
||||
|
||||
def execute_sql(self, sql: str, logstore: str, log_enabled: bool = False) -> list[dict[str, Any]]:
|
||||
"""Execute SQL query with automatic retry (3 attempts with exponential backoff)."""
|
||||
if log_enabled:
|
||||
logger.info(
|
||||
"[LogStore-PG] EXECUTE_SQL | logstore=%s | project=%s | sql=%s",
|
||||
logstore,
|
||||
self.project_name,
|
||||
sql,
|
||||
)
|
||||
|
||||
max_retries = 3
|
||||
retry_delay = 0.1
|
||||
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
with self._get_connection() as conn:
|
||||
with conn.cursor() as cursor:
|
||||
cursor.execute(sql)
|
||||
columns = [desc[0] for desc in cursor.description]
|
||||
|
||||
result = []
|
||||
for row in cursor.fetchall():
|
||||
row_dict = {}
|
||||
for col, val in zip(columns, row, strict=False):
|
||||
row_dict[col] = "" if val is None else str(val)
|
||||
result.append(row_dict)
|
||||
|
||||
if log_enabled:
|
||||
logger.info(
|
||||
"[LogStore-PG] EXECUTE_SQL RESULT | logstore=%s | returned_count=%d",
|
||||
logstore,
|
||||
len(result),
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
except psycopg2.Error as e:
|
||||
if not self._is_retriable_error(e):
|
||||
logger.exception(
|
||||
"Failed to execute SQL on logstore %s (non-retriable error): sql=%s",
|
||||
logstore,
|
||||
sql,
|
||||
)
|
||||
raise
|
||||
|
||||
if attempt < max_retries - 1:
|
||||
logger.warning(
|
||||
"Failed to execute SQL on logstore %s (attempt %d/%d): %s. Retrying...",
|
||||
logstore,
|
||||
attempt + 1,
|
||||
max_retries,
|
||||
str(e),
|
||||
)
|
||||
time.sleep(retry_delay)
|
||||
retry_delay *= 2
|
||||
else:
|
||||
logger.exception(
|
||||
"Failed to execute SQL on logstore %s after %d attempts: sql=%s",
|
||||
logstore,
|
||||
max_retries,
|
||||
sql,
|
||||
)
|
||||
raise
|
||||
|
||||
return []
|
||||
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
LogStore repository utilities.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def safe_float(value: Any, default: float = 0.0) -> float:
|
||||
"""
|
||||
Safely convert a value to float, handling 'null' strings and None.
|
||||
"""
|
||||
if value is None or value in {"null", ""}:
|
||||
return default
|
||||
try:
|
||||
return float(value)
|
||||
except (ValueError, TypeError):
|
||||
return default
|
||||
|
||||
|
||||
def safe_int(value: Any, default: int = 0) -> int:
|
||||
"""
|
||||
Safely convert a value to int, handling 'null' strings and None.
|
||||
"""
|
||||
if value is None or value in {"null", ""}:
|
||||
return default
|
||||
try:
|
||||
return int(float(value))
|
||||
except (ValueError, TypeError):
|
||||
return default
|
||||
+386
@@ -0,0 +1,386 @@
|
||||
"""
|
||||
LogStore implementation of DifyAPIWorkflowNodeExecutionRepository.
|
||||
|
||||
This module provides the LogStore-based implementation for service-layer
|
||||
WorkflowNodeExecutionModel operations using Aliyun SLS LogStore.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Mapping, Sequence
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any, override
|
||||
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from extensions.logstore.aliyun_logstore import AliyunLogStore
|
||||
from extensions.logstore.repositories import safe_float, safe_int
|
||||
from extensions.logstore.sql_escape import escape_identifier, escape_logstore_query_value
|
||||
from graphon.enums import BuiltinNodeTypes, WorkflowNodeExecutionStatus
|
||||
from libs.datetime_utils import ensure_naive_utc, naive_utc_now
|
||||
from models.enums import CreatorUserRole
|
||||
from models.workflow import WorkflowNodeExecutionModel, WorkflowNodeExecutionTriggeredFrom
|
||||
from repositories.api_workflow_node_execution_repository import (
|
||||
DifyAPIWorkflowNodeExecutionRepository,
|
||||
WorkflowNodeExecutionPayloads,
|
||||
WorkflowNodeExecutionSnapshot,
|
||||
)
|
||||
from repositories.sqlalchemy_api_workflow_node_execution_repository import (
|
||||
DifyAPISQLAlchemyWorkflowNodeExecutionRepository,
|
||||
)
|
||||
from repositories.workflow_run_control import apply_workflow_stop_to_node, get_stopped_workflow_run
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _dict_to_workflow_node_execution_model(data: dict[str, Any]) -> WorkflowNodeExecutionModel:
|
||||
"""
|
||||
Convert LogStore result dictionary to WorkflowNodeExecutionModel instance.
|
||||
|
||||
Args:
|
||||
data: Dictionary from LogStore query result
|
||||
|
||||
Returns:
|
||||
WorkflowNodeExecutionModel instance (detached from session)
|
||||
|
||||
Note:
|
||||
The returned model is not attached to any SQLAlchemy session.
|
||||
Relationship fields (like offload_data) are not loaded from LogStore.
|
||||
"""
|
||||
logger.debug("_dict_to_workflow_node_execution_model: data keys=%s", list(data.keys())[:5])
|
||||
# Create model instance without session
|
||||
model = WorkflowNodeExecutionModel()
|
||||
|
||||
# Map all required fields with validation
|
||||
# Critical fields - must not be None
|
||||
model.id = data.get("id") or ""
|
||||
model.tenant_id = data.get("tenant_id") or ""
|
||||
model.app_id = data.get("app_id") or ""
|
||||
model.workflow_id = data.get("workflow_id") or ""
|
||||
model.triggered_from_workflow_id = data.get("triggered_from_workflow_id") or None
|
||||
model.triggered_from_node_execution_id = data.get("triggered_from_node_execution_id") or None
|
||||
triggered_from_val = data.get("triggered_from")
|
||||
try:
|
||||
model.triggered_from = (
|
||||
WorkflowNodeExecutionTriggeredFrom(str(triggered_from_val))
|
||||
if triggered_from_val
|
||||
else WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN
|
||||
)
|
||||
except ValueError:
|
||||
logger.warning("Invalid triggered_from value: %s, falling back to WORKFLOW_RUN", triggered_from_val)
|
||||
model.triggered_from = WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN
|
||||
model.node_id = data.get("node_id") or ""
|
||||
model.node_type = data.get("node_type") or ""
|
||||
model.status = WorkflowNodeExecutionStatus(data.get("status") or "running")
|
||||
model.title = data.get("title") or ""
|
||||
created_by_role_val = data.get("created_by_role")
|
||||
try:
|
||||
model.created_by_role = (
|
||||
CreatorUserRole(str(created_by_role_val)) if created_by_role_val else CreatorUserRole.ACCOUNT
|
||||
)
|
||||
except ValueError:
|
||||
logger.warning("Invalid created_by_role value: %s, falling back to ACCOUNT", created_by_role_val)
|
||||
model.created_by_role = CreatorUserRole.ACCOUNT
|
||||
model.created_by = data.get("created_by") or ""
|
||||
|
||||
model.index = safe_int(data.get("index", 0))
|
||||
model.elapsed_time = safe_float(data.get("elapsed_time", 0))
|
||||
|
||||
# Optional fields
|
||||
model.workflow_run_id = data.get("workflow_run_id")
|
||||
model.predecessor_node_id = data.get("predecessor_node_id")
|
||||
model.node_execution_id = data.get("node_execution_id")
|
||||
model.inputs = data.get("inputs")
|
||||
model.process_data = data.get("process_data")
|
||||
model.outputs = data.get("outputs")
|
||||
model.error = data.get("error")
|
||||
model.execution_metadata = data.get("execution_metadata")
|
||||
|
||||
# Handle datetime fields
|
||||
# Every branch must yield naive UTC, matching what the database path stores.
|
||||
created_at = data.get("created_at")
|
||||
match created_at:
|
||||
case None:
|
||||
# Provide default created_at if missing
|
||||
model.created_at = naive_utc_now()
|
||||
case str():
|
||||
model.created_at = ensure_naive_utc(datetime.fromisoformat(created_at))
|
||||
case int() | float():
|
||||
model.created_at = datetime.fromtimestamp(created_at, tz=UTC).replace(tzinfo=None)
|
||||
case _:
|
||||
model.created_at = ensure_naive_utc(created_at)
|
||||
|
||||
finished_at = data.get("finished_at")
|
||||
match finished_at:
|
||||
case None | "":
|
||||
...
|
||||
case str():
|
||||
model.finished_at = ensure_naive_utc(datetime.fromisoformat(finished_at))
|
||||
case int() | float():
|
||||
model.finished_at = datetime.fromtimestamp(finished_at, tz=UTC).replace(tzinfo=None)
|
||||
case _:
|
||||
model.finished_at = ensure_naive_utc(finished_at)
|
||||
|
||||
return model
|
||||
|
||||
|
||||
class LogstoreAPIWorkflowNodeExecutionRepository(DifyAPIWorkflowNodeExecutionRepository):
|
||||
"""
|
||||
LogStore implementation of DifyAPIWorkflowNodeExecutionRepository.
|
||||
|
||||
Provides service-layer database operations for WorkflowNodeExecutionModel
|
||||
using LogStore SQL queries with optimized deduplication strategies.
|
||||
"""
|
||||
|
||||
def __init__(self, session_maker: sessionmaker | None = None):
|
||||
"""
|
||||
Initialize the repository with LogStore client.
|
||||
|
||||
Args:
|
||||
session_maker: SQLAlchemy sessionmaker for synchronous Agent caller records.
|
||||
"""
|
||||
logger.debug("LogstoreAPIWorkflowNodeExecutionRepository.__init__: initializing")
|
||||
self.logstore_client = AliyunLogStore()
|
||||
self._session_maker = session_maker
|
||||
|
||||
def _apply_stopped_run(
|
||||
self, executions: Sequence[WorkflowNodeExecutionModel], tenant_id: str, workflow_run_id: str
|
||||
) -> None:
|
||||
if self._session_maker is None:
|
||||
return
|
||||
with self._session_maker() as session:
|
||||
stopped = get_stopped_workflow_run(session, tenant_id=tenant_id, workflow_run_id=workflow_run_id)
|
||||
for execution in executions:
|
||||
apply_workflow_stop_to_node(execution, stopped)
|
||||
|
||||
@override
|
||||
def delete_executions_by_app(self, tenant_id: str, app_id: str, batch_size: int = 1000) -> int:
|
||||
"""Delete SQL caller records; append-only Logstore traces retain their configured TTL."""
|
||||
if self._session_maker is None:
|
||||
raise ValueError("session_maker is required to delete SQL workflow caller records")
|
||||
return DifyAPISQLAlchemyWorkflowNodeExecutionRepository(self._session_maker).delete_executions_by_app(
|
||||
tenant_id=tenant_id, app_id=app_id, batch_size=batch_size
|
||||
)
|
||||
|
||||
@override
|
||||
def load_full_inputs(self, execution: WorkflowNodeExecutionModel) -> Mapping[str, Any] | None:
|
||||
return execution.inputs_dict
|
||||
|
||||
@override
|
||||
def load_full_outputs(self, execution: WorkflowNodeExecutionModel) -> Mapping[str, Any] | None:
|
||||
return execution.outputs_dict
|
||||
|
||||
@override
|
||||
def load_full_process_data(self, execution: WorkflowNodeExecutionModel) -> Mapping[str, Any] | None:
|
||||
"""Return complete Process Data already stored inline by LogStore."""
|
||||
return execution.process_data_dict
|
||||
|
||||
@override
|
||||
def load_full_payloads(
|
||||
self, executions: Sequence[WorkflowNodeExecutionModel]
|
||||
) -> Mapping[str, WorkflowNodeExecutionPayloads]:
|
||||
return {
|
||||
execution.id: WorkflowNodeExecutionPayloads(
|
||||
inputs=execution.inputs_dict,
|
||||
process_data=execution.process_data_dict,
|
||||
outputs=execution.outputs_dict,
|
||||
)
|
||||
for execution in executions
|
||||
}
|
||||
|
||||
@override
|
||||
def get_node_last_execution(
|
||||
self,
|
||||
tenant_id: str,
|
||||
app_id: str,
|
||||
workflow_id: str,
|
||||
node_id: str,
|
||||
) -> WorkflowNodeExecutionModel | None:
|
||||
"""Return the most recent visible, non-paused execution after selecting each latest version."""
|
||||
filter_values = {"tenant_id": tenant_id, "app_id": app_id, "workflow_id": workflow_id, "node_id": node_id}
|
||||
sql_filters = " AND ".join(f"{key} = '{escape_identifier(value)}'" for key, value in filter_values.items())
|
||||
search_query = " and ".join(
|
||||
f"{key}: {escape_logstore_query_value(value)}" for key, value in filter_values.items()
|
||||
)
|
||||
results = self.logstore_client.execute_sql(
|
||||
sql=f"""
|
||||
SELECT * FROM (
|
||||
SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY log_version DESC) AS rn
|
||||
FROM "{AliyunLogStore.workflow_node_execution_logstore}"
|
||||
WHERE {sql_filters} AND __time__ > 0
|
||||
) AS executions WHERE rn = 1
|
||||
AND (triggered_from IS NULL
|
||||
OR triggered_from != '{WorkflowNodeExecutionTriggeredFrom.WORKFLOW_TOOL.value}')
|
||||
AND (status IS NULL OR status != '{WorkflowNodeExecutionStatus.PAUSED.value}')
|
||||
ORDER BY created_at DESC LIMIT 1
|
||||
""",
|
||||
logstore=AliyunLogStore.workflow_node_execution_logstore,
|
||||
query=search_query,
|
||||
)
|
||||
return _dict_to_workflow_node_execution_model(results[0]) if results else None
|
||||
|
||||
@override
|
||||
def get_executions_by_workflow_run(
|
||||
self, tenant_id: str, app_id: str, workflow_run_id: str
|
||||
) -> Sequence[WorkflowNodeExecutionModel]:
|
||||
"""Return visible terminal trace records, newest index first."""
|
||||
executions = self._get_run_executions(tenant_id, app_id, workflow_run_id)
|
||||
return sorted(
|
||||
(execution for execution in executions if execution.status != WorkflowNodeExecutionStatus.PAUSED),
|
||||
key=lambda execution: execution.index,
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
@override
|
||||
def get_execution_snapshots_by_workflow_run(
|
||||
self, tenant_id: str, app_id: str, workflow_id: str, triggered_from: str, workflow_run_id: str
|
||||
) -> Sequence[WorkflowNodeExecutionSnapshot]:
|
||||
return [
|
||||
WorkflowNodeExecutionSnapshot.from_execution(execution)
|
||||
for execution in self._get_run_executions(
|
||||
tenant_id, app_id, workflow_run_id, workflow_id=workflow_id, triggered_from=triggered_from
|
||||
)
|
||||
]
|
||||
|
||||
def _get_run_executions(
|
||||
self,
|
||||
tenant_id: str,
|
||||
app_id: str,
|
||||
workflow_run_id: str,
|
||||
*,
|
||||
workflow_id: str | None = None,
|
||||
triggered_from: str | None = None,
|
||||
) -> list[WorkflowNodeExecutionModel]:
|
||||
"""Read latest versions through the shared SQL/SDK adapter; snapshots omit payloads."""
|
||||
filter_values = {"tenant_id": tenant_id, "app_id": app_id, "workflow_run_id": workflow_run_id}
|
||||
if workflow_id is not None:
|
||||
filter_values["workflow_id"] = workflow_id
|
||||
sql_filters = " AND ".join(f"{key} = '{escape_identifier(value)}'" for key, value in filter_values.items())
|
||||
search_query = " and ".join(
|
||||
f"{key}: {escape_logstore_query_value(value)}" for key, value in filter_values.items()
|
||||
)
|
||||
trigger_filter = (
|
||||
f"triggered_from = '{escape_identifier(triggered_from)}'"
|
||||
if triggered_from is not None
|
||||
else f"(triggered_from IS NULL OR triggered_from != '{WorkflowNodeExecutionTriggeredFrom.WORKFLOW_TOOL}')"
|
||||
)
|
||||
columns = (
|
||||
'id, node_execution_id, node_id, node_type, title, "index", status, elapsed_time, '
|
||||
"created_at, finished_at, execution_metadata"
|
||||
if workflow_id is not None
|
||||
else "*"
|
||||
)
|
||||
executions: list[WorkflowNodeExecutionModel] = []
|
||||
offset = 0
|
||||
to_time = int(time.time())
|
||||
while True:
|
||||
page = self.logstore_client.execute_sql(
|
||||
sql=f"""
|
||||
SELECT {columns} FROM (
|
||||
SELECT {columns}, ROW_NUMBER() OVER (PARTITION BY id ORDER BY log_version DESC) AS rn
|
||||
FROM "{AliyunLogStore.workflow_node_execution_logstore}"
|
||||
WHERE {sql_filters} AND {trigger_filter} AND __time__ > 0
|
||||
) AS executions WHERE rn = 1 ORDER BY created_at, "index", id LIMIT 1000 OFFSET {offset}
|
||||
""",
|
||||
logstore=AliyunLogStore.workflow_node_execution_logstore,
|
||||
query=search_query,
|
||||
to_time=to_time,
|
||||
)
|
||||
for row in page:
|
||||
execution = _dict_to_workflow_node_execution_model(row)
|
||||
if workflow_id is not None and row.get("elapsed_time") is None:
|
||||
execution.elapsed_time = (
|
||||
(execution.finished_at - execution.created_at).total_seconds() if execution.finished_at else 0.0
|
||||
)
|
||||
executions.append(execution)
|
||||
if len(page) < 1000:
|
||||
self._apply_stopped_run(executions, tenant_id, workflow_run_id)
|
||||
return executions
|
||||
offset += len(page)
|
||||
|
||||
@override
|
||||
def get_workflow_tool_executions(
|
||||
self,
|
||||
tenant_id: str,
|
||||
workflow_run_id: str,
|
||||
parent_node_execution_id: str,
|
||||
) -> Sequence[WorkflowNodeExecutionModel]:
|
||||
sql_filters = (
|
||||
f"tenant_id = '{escape_identifier(tenant_id)}' "
|
||||
f"AND workflow_run_id = '{escape_identifier(workflow_run_id)}' AND __time__ > 0"
|
||||
)
|
||||
search_query = (
|
||||
f"tenant_id: {escape_logstore_query_value(tenant_id)} "
|
||||
f"and workflow_run_id: {escape_logstore_query_value(workflow_run_id)}"
|
||||
)
|
||||
requested_id = escape_identifier(parent_node_execution_id)
|
||||
to_time = int(time.time())
|
||||
parents = self.logstore_client.execute_sql(
|
||||
sql=f"""
|
||||
SELECT id, node_execution_id, workflow_id FROM "{AliyunLogStore.workflow_node_execution_logstore}"
|
||||
WHERE {sql_filters} AND node_type = '{BuiltinNodeTypes.TOOL}'
|
||||
AND (id = '{requested_id}' OR node_execution_id = '{requested_id}')
|
||||
ORDER BY log_version DESC LIMIT 1
|
||||
""",
|
||||
logstore=AliyunLogStore.workflow_node_execution_logstore,
|
||||
query=search_query,
|
||||
to_time=to_time,
|
||||
)
|
||||
if not parents:
|
||||
return []
|
||||
parent_execution_id = escape_identifier(parents[0].get("node_execution_id") or parents[0]["id"])
|
||||
parent_workflow_id = escape_identifier(parents[0]["workflow_id"])
|
||||
children: list[WorkflowNodeExecutionModel] = []
|
||||
offset = 0
|
||||
while True:
|
||||
page = self.logstore_client.execute_sql(
|
||||
sql=f"""
|
||||
SELECT * FROM (
|
||||
SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY log_version DESC) AS rn
|
||||
FROM "{AliyunLogStore.workflow_node_execution_logstore}"
|
||||
WHERE {sql_filters}
|
||||
AND triggered_from = '{WorkflowNodeExecutionTriggeredFrom.WORKFLOW_TOOL.value}'
|
||||
AND triggered_from_node_execution_id = '{parent_execution_id}'
|
||||
AND triggered_from_workflow_id = '{parent_workflow_id}'
|
||||
) AS executions WHERE rn = 1
|
||||
ORDER BY created_at, "index", id LIMIT 1000 OFFSET {offset}
|
||||
""",
|
||||
logstore=AliyunLogStore.workflow_node_execution_logstore,
|
||||
query=search_query,
|
||||
to_time=to_time,
|
||||
)
|
||||
children.extend(_dict_to_workflow_node_execution_model(row) for row in page)
|
||||
if len(page) < 1000:
|
||||
self._apply_stopped_run(children, tenant_id, workflow_run_id)
|
||||
return children
|
||||
offset += len(page)
|
||||
|
||||
@override
|
||||
def get_execution_by_id(
|
||||
self,
|
||||
execution_id: str,
|
||||
tenant_id: str | None = None,
|
||||
) -> WorkflowNodeExecutionModel | None:
|
||||
"""Return the latest version of an execution, optionally scoped to its tenant."""
|
||||
filter_values = {"id": execution_id}
|
||||
if tenant_id:
|
||||
filter_values["tenant_id"] = tenant_id
|
||||
sql_filters = " AND ".join(f"{key} = '{escape_identifier(value)}'" for key, value in filter_values.items())
|
||||
search_query = " and ".join(
|
||||
f"{key}: {escape_logstore_query_value(value)}" for key, value in filter_values.items()
|
||||
)
|
||||
results = self.logstore_client.execute_sql(
|
||||
sql=f"""
|
||||
SELECT * FROM "{AliyunLogStore.workflow_node_execution_logstore}"
|
||||
WHERE {sql_filters} AND __time__ > 0
|
||||
ORDER BY log_version DESC LIMIT 1
|
||||
""",
|
||||
logstore=AliyunLogStore.workflow_node_execution_logstore,
|
||||
query=search_query,
|
||||
)
|
||||
if not results:
|
||||
return None
|
||||
execution = _dict_to_workflow_node_execution_model(results[0])
|
||||
if execution.workflow_run_id:
|
||||
self._apply_stopped_run([execution], execution.tenant_id, execution.workflow_run_id)
|
||||
return execution
|
||||
+1052
File diff suppressed because it is too large.
Load diff
+221
@@ -0,0 +1,221 @@
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import override
|
||||
|
||||
from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from configs import dify_config
|
||||
from core.repositories.factory import WorkflowExecutionRepository
|
||||
from core.repositories.sqlalchemy_workflow_execution_repository import SQLAlchemyWorkflowExecutionRepository
|
||||
from extensions.logstore.aliyun_logstore import AliyunLogStore
|
||||
from graphon.entities import WorkflowExecution
|
||||
from graphon.enums import WorkflowExecutionStatus
|
||||
from graphon.workflow_type_encoder import WorkflowRuntimeTypeConverter
|
||||
from models import (
|
||||
Account,
|
||||
CreatorUserRole,
|
||||
EndUser,
|
||||
)
|
||||
from models.enums import WorkflowRunTriggeredFrom
|
||||
from repositories.entities.workflow_execution import WorkflowExecution as TimedWorkflowExecution
|
||||
from repositories.workflow_run_control import get_stopped_workflow_run
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class LogstoreWorkflowExecutionRepository(WorkflowExecutionRepository):
|
||||
def __init__(
|
||||
self,
|
||||
session_factory: sessionmaker | Engine,
|
||||
tenant_id: str,
|
||||
user: Account | EndUser,
|
||||
app_id: str | None,
|
||||
triggered_from: WorkflowRunTriggeredFrom | None,
|
||||
):
|
||||
"""
|
||||
Initialize the repository with a SQLAlchemy sessionmaker or engine and context information.
|
||||
|
||||
Args:
|
||||
session_factory: SQLAlchemy sessionmaker or engine for creating sessions
|
||||
tenant_id: Tenant that owns the workflow execution
|
||||
user: Account or EndUser used for creator attribution
|
||||
app_id: App ID for filtering by application (can be None)
|
||||
triggered_from: Source of the execution trigger (DEBUGGING or APP_RUN)
|
||||
"""
|
||||
logger.debug(
|
||||
"LogstoreWorkflowExecutionRepository.__init__: app_id=%s, triggered_from=%s", app_id, triggered_from
|
||||
)
|
||||
# Initialize LogStore client
|
||||
# Note: Project/logstore/index initialization is done at app startup via ext_logstore
|
||||
self.logstore_client = AliyunLogStore()
|
||||
|
||||
if not tenant_id:
|
||||
raise ValueError("tenant_id is required")
|
||||
self._tenant_id = tenant_id
|
||||
|
||||
# Store app context
|
||||
self._app_id = app_id
|
||||
|
||||
# Extract user context
|
||||
self._triggered_from = triggered_from
|
||||
self._creator_user_id = user.id
|
||||
|
||||
# Determine user role based on user type
|
||||
self._creator_user_role = CreatorUserRole.ACCOUNT if isinstance(user, Account) else CreatorUserRole.END_USER
|
||||
|
||||
# Initialize SQL repository for dual-write support
|
||||
self.sql_repository = SQLAlchemyWorkflowExecutionRepository(
|
||||
session_factory=session_factory,
|
||||
tenant_id=tenant_id,
|
||||
user=user,
|
||||
app_id=app_id,
|
||||
triggered_from=triggered_from,
|
||||
)
|
||||
|
||||
self._enable_dual_write = dify_config.LOGSTORE_DUAL_WRITE_ENABLED
|
||||
self._session_factory = (
|
||||
sessionmaker(bind=session_factory) if isinstance(session_factory, Engine) else session_factory
|
||||
)
|
||||
|
||||
# Control flag for whether to write the `graph` field to LogStore.
|
||||
# If LOGSTORE_ENABLE_PUT_GRAPH_FIELD is "true", write the full `graph` field;
|
||||
# otherwise write an empty {} instead. Defaults to writing the `graph` field.
|
||||
self._enable_put_graph_field = dify_config.LOGSTORE_ENABLE_PUT_GRAPH_FIELD
|
||||
|
||||
def _to_logstore_model(self, domain_model: WorkflowExecution, *, log_version: int) -> list[tuple[str, str]]:
|
||||
"""
|
||||
Convert a domain model to a logstore model (List[Tuple[str, str]]).
|
||||
|
||||
Args:
|
||||
domain_model: The domain model to convert
|
||||
|
||||
Returns:
|
||||
The logstore model as a list of key-value tuples
|
||||
"""
|
||||
logger.debug(
|
||||
"_to_logstore_model: id=%s, workflow_id=%s, status=%s",
|
||||
domain_model.id_,
|
||||
domain_model.workflow_id,
|
||||
domain_model.status.value,
|
||||
)
|
||||
# Use values from constructor if provided
|
||||
if not self._triggered_from:
|
||||
raise ValueError("triggered_from is required in repository constructor")
|
||||
if not self._creator_user_id:
|
||||
raise ValueError("created_by is required in repository constructor")
|
||||
if not self._creator_user_role:
|
||||
raise ValueError("created_by_role is required in repository constructor")
|
||||
|
||||
version = str(log_version)
|
||||
|
||||
# Use WorkflowRuntimeTypeConverter to handle complex types (Segment, File, etc.)
|
||||
json_converter = WorkflowRuntimeTypeConverter()
|
||||
|
||||
logstore_model = [
|
||||
("id", domain_model.id_),
|
||||
("log_version", version), # Add log_version field for append-only writes
|
||||
("tenant_id", self._tenant_id),
|
||||
("app_id", self._app_id or ""),
|
||||
("workflow_id", domain_model.workflow_id),
|
||||
(
|
||||
"triggered_from",
|
||||
self._triggered_from.value if hasattr(self._triggered_from, "value") else str(self._triggered_from),
|
||||
),
|
||||
("type", domain_model.workflow_type.value),
|
||||
("version", domain_model.workflow_version),
|
||||
(
|
||||
"graph",
|
||||
json.dumps(json_converter.to_json_encodable(domain_model.graph), ensure_ascii=False)
|
||||
if domain_model.graph and self._enable_put_graph_field
|
||||
else "{}",
|
||||
),
|
||||
(
|
||||
"inputs",
|
||||
json.dumps(json_converter.to_json_encodable(domain_model.inputs), ensure_ascii=False)
|
||||
if domain_model.inputs
|
||||
else "{}",
|
||||
),
|
||||
(
|
||||
"outputs",
|
||||
json.dumps(json_converter.to_json_encodable(domain_model.outputs), ensure_ascii=False)
|
||||
if domain_model.outputs
|
||||
else "{}",
|
||||
),
|
||||
("status", domain_model.status.value),
|
||||
("error_message", domain_model.error_message or ""),
|
||||
("total_tokens", str(domain_model.total_tokens)),
|
||||
("total_steps", str(domain_model.total_steps)),
|
||||
("exceptions_count", str(domain_model.exceptions_count)),
|
||||
("elapsed_time", str(domain_model.elapsed_time)),
|
||||
(
|
||||
"created_by_role",
|
||||
self._creator_user_role.value
|
||||
if hasattr(self._creator_user_role, "value")
|
||||
else str(self._creator_user_role),
|
||||
),
|
||||
("created_by", self._creator_user_id),
|
||||
("started_at", domain_model.started_at.isoformat() if domain_model.started_at else ""),
|
||||
("finished_at", domain_model.finished_at.isoformat() if domain_model.finished_at else ""),
|
||||
]
|
||||
|
||||
return logstore_model
|
||||
|
||||
@override
|
||||
def save_synchronously(self, execution: WorkflowExecution) -> None:
|
||||
# Cancellation and pause/resume need a durable SQL owner even when
|
||||
# optional SQL history dual-write is disabled. Never swallow this write.
|
||||
self.sql_repository.save(execution)
|
||||
self.save(execution)
|
||||
|
||||
@override
|
||||
def save(self, execution: WorkflowExecution) -> None:
|
||||
"""
|
||||
Save or update a WorkflowExecution domain entity to the logstore.
|
||||
|
||||
This method serves as a domain-to-logstore adapter that:
|
||||
1. Converts the domain entity to its logstore representation
|
||||
2. Persists the logstore model using Aliyun SLS
|
||||
3. Maintains proper multi-tenancy by including tenant context during conversion
|
||||
4. Optionally writes to SQL database for dual-write support (controlled by LOGSTORE_DUAL_WRITE_ENABLED)
|
||||
|
||||
Args:
|
||||
execution: The WorkflowExecution domain entity to persist
|
||||
"""
|
||||
logger.debug(
|
||||
"save: id=%s, workflow_id=%s, status=%s", execution.id_, execution.workflow_id, execution.status.value
|
||||
)
|
||||
# Capture ordering before reading control state. A concurrent stop's
|
||||
# terminal record sorts after this snapshot even if its upload finishes first.
|
||||
version = time.time_ns()
|
||||
with self._session_factory() as session:
|
||||
stopped = get_stopped_workflow_run(session, tenant_id=self._tenant_id, workflow_run_id=execution.id_)
|
||||
if stopped is not None:
|
||||
execution = TimedWorkflowExecution.model_validate(
|
||||
{
|
||||
**execution.model_dump(),
|
||||
"status": WorkflowExecutionStatus.STOPPED,
|
||||
"error_message": stopped.error,
|
||||
"outputs": stopped.outputs_dict,
|
||||
"finished_at": stopped.finished_at,
|
||||
"accumulated_elapsed_time": stopped.elapsed_time,
|
||||
}
|
||||
)
|
||||
try:
|
||||
logstore_model = self._to_logstore_model(execution, log_version=version)
|
||||
self.logstore_client.put_log(AliyunLogStore.workflow_execution_logstore, logstore_model)
|
||||
|
||||
logger.debug("Saved workflow execution to logstore: id=%s", execution.id_)
|
||||
except Exception:
|
||||
logger.exception("Failed to save workflow execution to logstore: id=%s", execution.id_)
|
||||
raise
|
||||
|
||||
# Dual-write to SQL database if enabled (for safe migration)
|
||||
if self._enable_dual_write:
|
||||
try:
|
||||
self.sql_repository.save(execution)
|
||||
logger.debug("Dual-write: saved workflow execution to SQL database: id=%s", execution.id_)
|
||||
except Exception:
|
||||
logger.exception("Failed to dual-write workflow execution to SQL database: id=%s", execution.id_)
|
||||
# Don't raise - LogStore write succeeded, SQL is just a backup
|
||||
+497
@@ -0,0 +1,497 @@
|
||||
"""
|
||||
LogStore implementation of the WorkflowNodeExecutionRepository.
|
||||
|
||||
This module provides a LogStore-based repository for WorkflowNodeExecution entities,
|
||||
using Aliyun SLS LogStore with append-only writes and version control.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime
|
||||
from typing import Any, override
|
||||
|
||||
from pydantic import TypeAdapter
|
||||
from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from configs import dify_config
|
||||
from core.repositories import SQLAlchemyWorkflowNodeExecutionRepository
|
||||
from core.repositories.factory import OrderConfig, WorkflowNodeExecutionRepository
|
||||
from core.workflow.node_execution import WorkflowNodeExecution as DifyWorkflowNodeExecution
|
||||
from extensions.logstore.aliyun_logstore import AliyunLogStore
|
||||
from extensions.logstore.repositories import safe_float, safe_int
|
||||
from extensions.logstore.sql_escape import escape_identifier
|
||||
from graphon.entities import WorkflowNodeExecution
|
||||
from graphon.enums import WorkflowNodeExecutionMetadataKey, WorkflowNodeExecutionStatus
|
||||
from graphon.model_runtime.utils.encoders import jsonable_encoder
|
||||
from graphon.workflow_type_encoder import WorkflowRuntimeTypeConverter
|
||||
from models import (
|
||||
Account,
|
||||
CreatorUserRole,
|
||||
EndUser,
|
||||
WorkflowNodeExecutionTriggeredFrom,
|
||||
)
|
||||
from repositories.workflow_run_control import apply_workflow_stop_to_node, get_stopped_workflow_run
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_JSON_DICT_ADAPTER: TypeAdapter[dict[str, Any]] = TypeAdapter(dict[str, Any])
|
||||
|
||||
|
||||
def _dict_to_workflow_node_execution(data: dict[str, Any]) -> WorkflowNodeExecution:
|
||||
"""
|
||||
Convert LogStore result dictionary to WorkflowNodeExecution domain model.
|
||||
|
||||
Args:
|
||||
data: Dictionary from LogStore query result
|
||||
|
||||
Returns:
|
||||
WorkflowNodeExecution domain model instance
|
||||
"""
|
||||
logger.debug("_dict_to_workflow_node_execution: data keys=%s", list(data.keys())[:5])
|
||||
# Parse JSON fields
|
||||
inputs = _JSON_DICT_ADAPTER.validate_json(data.get("inputs") or "{}")
|
||||
process_data = _JSON_DICT_ADAPTER.validate_json(data.get("process_data") or "{}")
|
||||
outputs = _JSON_DICT_ADAPTER.validate_json(data.get("outputs") or "{}")
|
||||
metadata = _JSON_DICT_ADAPTER.validate_json(data.get("execution_metadata") or "{}")
|
||||
|
||||
# Convert metadata to domain enum keys
|
||||
domain_metadata = {}
|
||||
for k, v in metadata.items():
|
||||
try:
|
||||
domain_metadata[WorkflowNodeExecutionMetadataKey(k)] = v
|
||||
except ValueError:
|
||||
# Skip invalid metadata keys
|
||||
continue
|
||||
|
||||
# Convert status to domain enum
|
||||
status = WorkflowNodeExecutionStatus(data.get("status", "running"))
|
||||
|
||||
# Parse datetime fields
|
||||
created_at = datetime.fromisoformat(data.get("created_at", "")) if data.get("created_at") else datetime.now()
|
||||
finished_at = datetime.fromisoformat(data.get("finished_at", "")) if data.get("finished_at") else None
|
||||
|
||||
return DifyWorkflowNodeExecution(
|
||||
id=data.get("id", ""),
|
||||
node_execution_id=data.get("node_execution_id"),
|
||||
workflow_id=data.get("workflow_id", ""),
|
||||
triggered_from_workflow_id=data.get("triggered_from_workflow_id") or None,
|
||||
triggered_from_node_execution_id=data.get("triggered_from_node_execution_id") or None,
|
||||
workflow_execution_id=data.get("workflow_run_id"),
|
||||
index=safe_int(data.get("index", 0)),
|
||||
predecessor_node_id=data.get("predecessor_node_id"),
|
||||
node_id=data.get("node_id", ""),
|
||||
node_type=data.get("node_type", "start"),
|
||||
title=data.get("title", ""),
|
||||
inputs=inputs,
|
||||
process_data=process_data,
|
||||
outputs=outputs,
|
||||
status=status,
|
||||
error=data.get("error"),
|
||||
elapsed_time=safe_float(data.get("elapsed_time", 0.0)),
|
||||
metadata=domain_metadata,
|
||||
created_at=created_at,
|
||||
finished_at=finished_at,
|
||||
)
|
||||
|
||||
|
||||
class LogstoreWorkflowNodeExecutionRepository(WorkflowNodeExecutionRepository):
|
||||
"""
|
||||
LogStore implementation of the WorkflowNodeExecutionRepository interface.
|
||||
|
||||
This implementation uses Aliyun SLS LogStore with an append-only write strategy:
|
||||
- Each save() operation appends a new record with a version timestamp
|
||||
- Updates are simulated by writing new records with higher version numbers
|
||||
- Queries retrieve the latest version using finished_at IS NOT NULL filter
|
||||
- Multi-tenancy is maintained through tenant_id filtering
|
||||
|
||||
Version Strategy:
|
||||
version = time.time_ns() # Nanosecond timestamp for unique ordering
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
session_factory: sessionmaker | Engine,
|
||||
tenant_id: str,
|
||||
user: Account | EndUser,
|
||||
app_id: str | None,
|
||||
triggered_from: WorkflowNodeExecutionTriggeredFrom | None,
|
||||
):
|
||||
"""
|
||||
Initialize the repository with a SQLAlchemy sessionmaker or engine and context information.
|
||||
|
||||
Args:
|
||||
session_factory: SQLAlchemy sessionmaker or engine for creating sessions
|
||||
tenant_id: Tenant that owns the workflow node execution
|
||||
user: Account or EndUser used for creator attribution
|
||||
app_id: App ID for filtering by application (can be None)
|
||||
triggered_from: Source of the execution trigger (SINGLE_STEP or WORKFLOW_RUN)
|
||||
"""
|
||||
logger.debug(
|
||||
"LogstoreWorkflowNodeExecutionRepository.__init__: app_id=%s, triggered_from=%s", app_id, triggered_from
|
||||
)
|
||||
# Initialize LogStore client
|
||||
self.logstore_client = AliyunLogStore()
|
||||
|
||||
if not tenant_id:
|
||||
raise ValueError("tenant_id is required")
|
||||
self._tenant_id = tenant_id
|
||||
|
||||
# Store app context
|
||||
self._app_id = app_id
|
||||
|
||||
# Extract user context
|
||||
self._triggered_from = triggered_from
|
||||
self._creator_user_id = user.id
|
||||
self._user = user
|
||||
self._session_factory = (
|
||||
sessionmaker(bind=session_factory) if isinstance(session_factory, Engine) else session_factory
|
||||
)
|
||||
|
||||
# Determine user role based on user type
|
||||
self._creator_user_role = CreatorUserRole.ACCOUNT if isinstance(user, Account) else CreatorUserRole.END_USER
|
||||
|
||||
# Initialize SQL repository for dual-write support
|
||||
self.sql_repository = SQLAlchemyWorkflowNodeExecutionRepository(
|
||||
session_factory=session_factory,
|
||||
tenant_id=tenant_id,
|
||||
user=user,
|
||||
app_id=app_id,
|
||||
triggered_from=triggered_from,
|
||||
)
|
||||
|
||||
# Keep the migration switch on the typed application config so callers
|
||||
# and tests share the same validated source.
|
||||
self._enable_dual_write = dify_config.LOGSTORE_DUAL_WRITE_ENABLED
|
||||
|
||||
@override
|
||||
def for_workflow_tool(self, app_id: str) -> "LogstoreWorkflowNodeExecutionRepository":
|
||||
return LogstoreWorkflowNodeExecutionRepository(
|
||||
session_factory=self._session_factory,
|
||||
tenant_id=self._tenant_id,
|
||||
user=self._user,
|
||||
app_id=app_id,
|
||||
triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_TOOL,
|
||||
)
|
||||
|
||||
def _to_logstore_model(self, domain_model: WorkflowNodeExecution, *, log_version: int) -> Sequence[tuple[str, str]]:
|
||||
logger.debug(
|
||||
"_to_logstore_model: id=%s, node_id=%s, status=%s",
|
||||
domain_model.id,
|
||||
domain_model.node_id,
|
||||
domain_model.status.value,
|
||||
)
|
||||
if not self._triggered_from:
|
||||
raise ValueError("triggered_from is required in repository constructor")
|
||||
if not self._creator_user_id:
|
||||
raise ValueError("created_by is required in repository constructor")
|
||||
if not self._creator_user_role:
|
||||
raise ValueError("created_by_role is required in repository constructor")
|
||||
|
||||
version = str(log_version)
|
||||
|
||||
json_converter = WorkflowRuntimeTypeConverter()
|
||||
triggered_from_workflow_id = triggered_from_node_execution_id = None
|
||||
if isinstance(domain_model, DifyWorkflowNodeExecution):
|
||||
triggered_from_workflow_id = domain_model.triggered_from_workflow_id
|
||||
triggered_from_node_execution_id = domain_model.triggered_from_node_execution_id
|
||||
|
||||
logstore_model = [
|
||||
("id", domain_model.id),
|
||||
("log_version", version), # Add log_version field for append-only writes
|
||||
("tenant_id", self._tenant_id),
|
||||
("app_id", self._app_id or ""),
|
||||
("workflow_id", domain_model.workflow_id),
|
||||
("triggered_from_workflow_id", triggered_from_workflow_id or ""),
|
||||
("triggered_from_node_execution_id", triggered_from_node_execution_id or ""),
|
||||
(
|
||||
"triggered_from",
|
||||
self._triggered_from.value if hasattr(self._triggered_from, "value") else str(self._triggered_from),
|
||||
),
|
||||
("workflow_run_id", domain_model.workflow_execution_id or ""),
|
||||
("index", str(domain_model.index)),
|
||||
("predecessor_node_id", domain_model.predecessor_node_id or ""),
|
||||
("node_execution_id", domain_model.node_execution_id or ""),
|
||||
("node_id", domain_model.node_id),
|
||||
("node_type", domain_model.node_type),
|
||||
("title", domain_model.title),
|
||||
(
|
||||
"inputs",
|
||||
json.dumps(json_converter.to_json_encodable(domain_model.inputs), ensure_ascii=False)
|
||||
if domain_model.inputs
|
||||
else "{}",
|
||||
),
|
||||
(
|
||||
"process_data",
|
||||
json.dumps(json_converter.to_json_encodable(domain_model.process_data), ensure_ascii=False)
|
||||
if domain_model.process_data
|
||||
else "{}",
|
||||
),
|
||||
(
|
||||
"outputs",
|
||||
json.dumps(json_converter.to_json_encodable(domain_model.outputs), ensure_ascii=False)
|
||||
if domain_model.outputs
|
||||
else "{}",
|
||||
),
|
||||
("status", domain_model.status.value),
|
||||
("error", domain_model.error or ""),
|
||||
("elapsed_time", str(domain_model.elapsed_time)),
|
||||
(
|
||||
"execution_metadata",
|
||||
json.dumps(jsonable_encoder(domain_model.metadata), ensure_ascii=False)
|
||||
if domain_model.metadata
|
||||
else "{}",
|
||||
),
|
||||
("created_at", domain_model.created_at.isoformat() if domain_model.created_at else ""),
|
||||
("created_by_role", self._creator_user_role.value),
|
||||
("created_by", self._creator_user_id),
|
||||
("finished_at", domain_model.finished_at.isoformat() if domain_model.finished_at else ""),
|
||||
]
|
||||
|
||||
return logstore_model
|
||||
|
||||
@override
|
||||
def save(self, execution: WorkflowNodeExecution) -> None:
|
||||
"""
|
||||
Save or update a NodeExecution domain entity to LogStore.
|
||||
|
||||
This method serves as a domain-to-logstore adapter that:
|
||||
1. Converts the domain entity to its logstore representation
|
||||
2. Appends a new record with a log_version timestamp
|
||||
3. Maintains proper multi-tenancy by including tenant context during conversion
|
||||
4. Optionally writes to SQL database for dual-write support (controlled by LOGSTORE_DUAL_WRITE_ENABLED)
|
||||
|
||||
Each save operation creates a new record. Updates are simulated by writing
|
||||
new records with higher log_version numbers.
|
||||
|
||||
Args:
|
||||
execution: The NodeExecution domain entity to persist
|
||||
"""
|
||||
logger.debug(
|
||||
"save: id=%s, node_execution_id=%s, status=%s",
|
||||
execution.id,
|
||||
execution.node_execution_id,
|
||||
execution.status.value,
|
||||
)
|
||||
execution, version = self._prepare_controlled_write(execution)
|
||||
try:
|
||||
logstore_model = self._to_logstore_model(execution, log_version=version)
|
||||
self.logstore_client.put_log(AliyunLogStore.workflow_node_execution_logstore, logstore_model)
|
||||
|
||||
logger.debug(
|
||||
"Saved node execution to LogStore: id=%s, node_execution_id=%s, status=%s",
|
||||
execution.id,
|
||||
execution.node_execution_id,
|
||||
execution.status.value,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Failed to save node execution to LogStore: id=%s, node_execution_id=%s",
|
||||
execution.id,
|
||||
execution.node_execution_id,
|
||||
)
|
||||
raise
|
||||
|
||||
# Dual-write to SQL database if enabled (for safe migration)
|
||||
if self._enable_dual_write:
|
||||
try:
|
||||
self.sql_repository.save(execution)
|
||||
logger.debug("Dual-write: saved node execution to SQL database: id=%s", execution.id)
|
||||
except Exception:
|
||||
logger.exception("Failed to dual-write node execution to SQL database: id=%s", execution.id)
|
||||
# Don't raise - LogStore write succeeded, SQL is just a backup
|
||||
|
||||
def _prepare_controlled_write(self, execution: WorkflowNodeExecution) -> tuple[WorkflowNodeExecution, int]:
|
||||
# Assign ordering before checking SQL so an in-flight pause cannot sort
|
||||
# after a stop that commits while the LogStore upload is pending.
|
||||
version = time.time_ns()
|
||||
if execution.status in (
|
||||
WorkflowNodeExecutionStatus.RUNNING,
|
||||
WorkflowNodeExecutionStatus.PAUSED,
|
||||
WorkflowNodeExecutionStatus.RETRY,
|
||||
):
|
||||
execution = execution.model_copy()
|
||||
with self._session_factory() as session:
|
||||
apply_workflow_stop_to_node(
|
||||
execution,
|
||||
get_stopped_workflow_run(
|
||||
session, tenant_id=self._tenant_id, workflow_run_id=execution.workflow_execution_id
|
||||
),
|
||||
)
|
||||
return execution, version
|
||||
|
||||
@override
|
||||
def save_many(self, executions: Sequence[WorkflowNodeExecution]) -> None:
|
||||
"""Append each record through the existing writer and batch the SQL backup."""
|
||||
if not executions:
|
||||
return
|
||||
controlled_executions = []
|
||||
for execution in executions:
|
||||
execution, version = self._prepare_controlled_write(execution)
|
||||
controlled_executions.append(execution)
|
||||
self.logstore_client.put_log(
|
||||
AliyunLogStore.workflow_node_execution_logstore, self._to_logstore_model(execution, log_version=version)
|
||||
)
|
||||
if self._enable_dual_write:
|
||||
try:
|
||||
self.sql_repository.save_many(controlled_executions)
|
||||
except Exception:
|
||||
logger.exception("Failed to dual-write workflow node execution batch: %s", [e.id for e in executions])
|
||||
|
||||
@override
|
||||
def save_synchronously(self, execution: WorkflowNodeExecution) -> None:
|
||||
"""Create the SQL caller row required by Agent v2 participant ownership."""
|
||||
|
||||
self.sql_repository.save_synchronously(execution)
|
||||
|
||||
@override
|
||||
def save_execution_data(self, execution: WorkflowNodeExecution) -> None:
|
||||
"""
|
||||
Save or update the inputs, process_data, or outputs associated with a specific
|
||||
node_execution record.
|
||||
|
||||
For LogStore implementation, this is a no-op for the LogStore write because save()
|
||||
already writes all fields including inputs, process_data, and outputs. The caller
|
||||
typically calls save() first to persist status/metadata, then calls save_execution_data()
|
||||
to persist data fields. Since LogStore writes complete records atomically, we don't
|
||||
need a separate write here to avoid duplicate records.
|
||||
|
||||
However, if dual-write is enabled, we still need to call the SQL repository's
|
||||
save_execution_data() method to properly update the SQL database.
|
||||
|
||||
Args:
|
||||
execution: The NodeExecution instance with data to save
|
||||
"""
|
||||
logger.debug(
|
||||
"save_execution_data: no-op for LogStore (data already saved by save()): id=%s, node_execution_id=%s",
|
||||
execution.id,
|
||||
execution.node_execution_id,
|
||||
)
|
||||
# No-op for LogStore: save() already writes all fields including inputs, process_data, and outputs
|
||||
# Calling save() again would create a duplicate record in the append-only LogStore
|
||||
|
||||
# Dual-write to SQL database if enabled (for safe migration)
|
||||
if self._enable_dual_write:
|
||||
try:
|
||||
self.sql_repository.save_execution_data(execution)
|
||||
logger.debug("Dual-write: saved node execution data to SQL database: id=%s", execution.id)
|
||||
except Exception:
|
||||
logger.exception("Failed to dual-write node execution data to SQL database: id=%s", execution.id)
|
||||
# Don't raise - LogStore write succeeded, SQL is just a backup
|
||||
|
||||
@override
|
||||
def get_by_workflow_execution(
|
||||
self,
|
||||
workflow_execution_id: str,
|
||||
order_config: OrderConfig | None = None,
|
||||
*,
|
||||
include_paused: bool = False,
|
||||
) -> Sequence[WorkflowNodeExecution]:
|
||||
"""
|
||||
Retrieve all node executions for a workflow execution.
|
||||
Paused nodes are always included; include_paused accepts the shared resume-read contract.
|
||||
Uses LogStore SQL query with window function to get the latest version of each node execution.
|
||||
This ensures we only get the most recent version of each node execution record.
|
||||
Args:
|
||||
workflow_execution_id: The workflow execution identifier
|
||||
order_config: Optional configuration for ordering results
|
||||
order_config.order_by: List of fields to order by (e.g., ["index", "created_at"])
|
||||
order_config.order_direction: Direction to order ("asc" or "desc")
|
||||
|
||||
Returns:
|
||||
A list of workflow node execution instances
|
||||
|
||||
Note:
|
||||
This method uses ROW_NUMBER() window function partitioned by node_execution_id
|
||||
to get the latest version (highest log_version) of each node execution.
|
||||
"""
|
||||
logger.debug(
|
||||
"get_by_workflow_execution: workflow_execution_id=%s, order_config=%s",
|
||||
workflow_execution_id,
|
||||
order_config,
|
||||
)
|
||||
# Build SQL query with deduplication using window function
|
||||
# ROW_NUMBER() OVER (PARTITION BY node_execution_id ORDER BY log_version DESC)
|
||||
# ensures we get the latest version of each node execution
|
||||
|
||||
# Escape parameters to prevent SQL injection
|
||||
escaped_workflow_execution_id = escape_identifier(workflow_execution_id)
|
||||
escaped_tenant_id = escape_identifier(self._tenant_id)
|
||||
# Legacy root records may omit their origin; exclude only new hidden tool records.
|
||||
tool_origin = WorkflowNodeExecutionTriggeredFrom.WORKFLOW_TOOL.value
|
||||
origin_filter = (
|
||||
f"triggered_from='{tool_origin}'"
|
||||
if self._triggered_from == WorkflowNodeExecutionTriggeredFrom.WORKFLOW_TOOL
|
||||
else f"(triggered_from IS NULL OR triggered_from!='{tool_origin}')"
|
||||
)
|
||||
|
||||
# Build ORDER BY clause for outer query
|
||||
order_clause = ""
|
||||
if order_config and order_config.order_by:
|
||||
order_fields = []
|
||||
for field in order_config.order_by:
|
||||
# Map domain field names to logstore field names if needed
|
||||
field_name = field
|
||||
if order_config.order_direction == "desc":
|
||||
order_fields.append(f"{field_name} DESC")
|
||||
else:
|
||||
order_fields.append(f"{field_name} ASC")
|
||||
if order_fields:
|
||||
order_clause = "ORDER BY " + ", ".join(order_fields)
|
||||
|
||||
# Build app_id filter for subquery
|
||||
app_id_filter = ""
|
||||
if self._app_id:
|
||||
escaped_app_id = escape_identifier(self._app_id)
|
||||
app_id_filter = f" AND app_id='{escaped_app_id}'"
|
||||
|
||||
# Use window function to get latest version of each node execution
|
||||
sql = f"""
|
||||
SELECT * FROM (
|
||||
SELECT *, ROW_NUMBER() OVER (PARTITION BY node_execution_id ORDER BY log_version DESC) AS rn
|
||||
FROM {AliyunLogStore.workflow_node_execution_logstore}
|
||||
WHERE workflow_run_id='{escaped_workflow_execution_id}'
|
||||
AND tenant_id='{escaped_tenant_id}'
|
||||
AND {origin_filter}
|
||||
{app_id_filter}
|
||||
) t
|
||||
WHERE rn = 1
|
||||
"""
|
||||
|
||||
if order_clause:
|
||||
sql += f" {order_clause}"
|
||||
|
||||
try:
|
||||
# Execute SQL query
|
||||
results = self.logstore_client.execute_sql(
|
||||
sql=sql,
|
||||
query="*",
|
||||
logstore=AliyunLogStore.workflow_node_execution_logstore,
|
||||
)
|
||||
|
||||
# Convert LogStore results to WorkflowNodeExecution domain models
|
||||
executions = []
|
||||
for row in results:
|
||||
try:
|
||||
execution = _dict_to_workflow_node_execution(row)
|
||||
executions.append(execution)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to convert row to WorkflowNodeExecution: %s, row=%s", e, row)
|
||||
continue
|
||||
|
||||
with self._session_factory() as session:
|
||||
stopped = get_stopped_workflow_run(
|
||||
session, tenant_id=self._tenant_id, workflow_run_id=workflow_execution_id
|
||||
)
|
||||
for execution in executions:
|
||||
apply_workflow_stop_to_node(execution, stopped)
|
||||
return executions
|
||||
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Failed to retrieve node executions from LogStore: workflow_execution_id=%s",
|
||||
workflow_execution_id,
|
||||
)
|
||||
raise
|
||||
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
SQL Escape Utility for LogStore Queries
|
||||
|
||||
This module provides escaping utilities to prevent injection attacks in LogStore queries.
|
||||
|
||||
LogStore supports two query modes:
|
||||
1. PG Protocol Mode: Uses SQL syntax with single quotes for strings
|
||||
2. SDK Mode: Uses LogStore query syntax (key: value) with double quotes
|
||||
|
||||
Key Security Concerns:
|
||||
- Prevent tenant A from accessing tenant B's data via injection
|
||||
- SLS queries are read-only, so we focus on data access control
|
||||
- Different escaping strategies for SQL vs LogStore query syntax
|
||||
"""
|
||||
|
||||
|
||||
def escape_sql_string(value: str) -> str:
|
||||
"""
|
||||
Escape a string value for safe use in SQL queries.
|
||||
|
||||
This function escapes single quotes by doubling them, which is the standard
|
||||
SQL escaping method. This prevents SQL injection by ensuring that user input
|
||||
cannot break out of string literals.
|
||||
|
||||
Args:
|
||||
value: The string value to escape
|
||||
|
||||
Returns:
|
||||
Escaped string safe for use in SQL queries
|
||||
|
||||
Examples:
|
||||
>>> escape_sql_string("normal_value")
|
||||
"normal_value"
|
||||
>>> escape_sql_string("value' OR '1'='1")
|
||||
"value'' OR ''1''=''1"
|
||||
>>> escape_sql_string("tenant's_id")
|
||||
"tenant''s_id"
|
||||
|
||||
Security:
|
||||
- Prevents breaking out of string literals
|
||||
- Stops injection attacks like: ' OR '1'='1
|
||||
- Protects against cross-tenant data access
|
||||
"""
|
||||
if not value:
|
||||
return value
|
||||
|
||||
# Escape single quotes by doubling them (standard SQL escaping)
|
||||
# This prevents breaking out of string literals in SQL queries
|
||||
return value.replace("'", "''")
|
||||
|
||||
|
||||
def escape_identifier(value: str) -> str:
|
||||
"""
|
||||
Escape an identifier (tenant_id, app_id, run_id, etc.) for safe SQL use.
|
||||
|
||||
This function is for PG protocol mode (SQL syntax).
|
||||
For SDK mode, use escape_logstore_query_value() instead.
|
||||
|
||||
Args:
|
||||
value: The identifier value to escape
|
||||
|
||||
Returns:
|
||||
Escaped identifier safe for use in SQL queries
|
||||
|
||||
Examples:
|
||||
>>> escape_identifier("550e8400-e29b-41d4-a716-446655440000")
|
||||
"550e8400-e29b-41d4-a716-446655440000"
|
||||
>>> escape_identifier("tenant_id' OR '1'='1")
|
||||
"tenant_id'' OR ''1''=''1"
|
||||
|
||||
Security:
|
||||
- Prevents SQL injection via identifiers
|
||||
- Stops cross-tenant access attempts
|
||||
- Works for UUIDs, alphanumeric IDs, and similar identifiers
|
||||
"""
|
||||
# For identifiers, use the same escaping as strings
|
||||
# This is simple and effective for preventing injection
|
||||
return escape_sql_string(value)
|
||||
|
||||
|
||||
def escape_logstore_query_value(value: str) -> str:
|
||||
"""
|
||||
Escape value for LogStore query syntax (SDK mode).
|
||||
|
||||
LogStore query syntax rules:
|
||||
1. Keywords (and/or/not) are case-insensitive
|
||||
2. Single quotes are ordinary characters (no special meaning)
|
||||
3. Double quotes wrap values: key:"value"
|
||||
4. Backslash is the escape character:
|
||||
- \" for double quote inside value
|
||||
- \\ for backslash itself
|
||||
5. Parentheses can change query structure
|
||||
|
||||
To prevent injection:
|
||||
- Wrap value in double quotes to treat special chars as literals
|
||||
- Escape backslashes and double quotes using backslash
|
||||
|
||||
Args:
|
||||
value: The value to escape for LogStore query syntax
|
||||
|
||||
Returns:
|
||||
Quoted and escaped value safe for LogStore query syntax (includes the quotes)
|
||||
|
||||
Examples:
|
||||
>>> escape_logstore_query_value("normal_value")
|
||||
'"normal_value"'
|
||||
>>> escape_logstore_query_value("value or field:evil")
|
||||
'"value or field:evil"' # 'or' and ':' are now literals
|
||||
>>> escape_logstore_query_value('value"test')
|
||||
'"value\\"test"' # Internal double quote escaped
|
||||
>>> escape_logstore_query_value('value\\test')
|
||||
'"value\\\\test"' # Backslash escaped
|
||||
|
||||
Security:
|
||||
- Prevents injection via and/or/not keywords
|
||||
- Prevents injection via colons (:)
|
||||
- Prevents injection via parentheses
|
||||
- Protects against cross-tenant data access
|
||||
|
||||
Note:
|
||||
Escape order is critical: backslash first, then double quotes.
|
||||
Otherwise, we'd double-escape the escape character itself.
|
||||
"""
|
||||
if not value:
|
||||
return '""'
|
||||
|
||||
# IMPORTANT: Escape backslashes FIRST, then double quotes
|
||||
# This prevents double-escaping (e.g., " -> \" -> \\" incorrectly)
|
||||
escaped = value.replace("\\", "\\\\") # \ -> \\
|
||||
escaped = escaped.replace('"', '\\"') # " -> \"
|
||||
|
||||
# Wrap in double quotes to treat as literal string
|
||||
# This prevents and/or/not/:/() from being interpreted as operators
|
||||
return f'"{escaped}"'
|
||||
@@ -0,0 +1,13 @@
|
||||
from extensions.otel.context import propagate_context
|
||||
from extensions.otel.decorators.base import trace_span
|
||||
from extensions.otel.decorators.handler import SpanHandler
|
||||
from extensions.otel.decorators.handlers.generate_handler import AppGenerateHandler
|
||||
from extensions.otel.decorators.handlers.workflow_app_runner_handler import WorkflowAppRunnerHandler
|
||||
|
||||
__all__ = [
|
||||
"AppGenerateHandler",
|
||||
"SpanHandler",
|
||||
"WorkflowAppRunnerHandler",
|
||||
"propagate_context",
|
||||
"trace_span",
|
||||
]
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
Celery SQL comment context for OpenTelemetry SQLCommenter.
|
||||
|
||||
Injects Celery-specific metadata (framework, task_name, traceparent, celery_retries,
|
||||
routing_key) into SQL comments for queries executed by Celery workers. This improves
|
||||
trace-to-SQL correlation and debugging in production.
|
||||
|
||||
Uses the OpenTelemetry context key SQLCOMMENTER_ORM_TAGS_AND_VALUES, which is read
|
||||
by opentelemetry.instrumentation.sqlcommenter_utils._add_framework_tags() when the
|
||||
SQLAlchemy instrumentor appends comments to SQL statements.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Any, TypedDict
|
||||
|
||||
from celery.app.task import Task
|
||||
from celery.signals import task_postrun, task_prerun
|
||||
from opentelemetry import context
|
||||
from opentelemetry.instrumentation.celery import CeleryInstrumentor
|
||||
from opentelemetry.metrics import MeterProvider
|
||||
from opentelemetry.trace import TracerProvider
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_TRACE_PROPAGATOR = TraceContextTextMapPropagator()
|
||||
|
||||
_SQLCOMMENTER_CONTEXT_KEY = "SQLCOMMENTER_ORM_TAGS_AND_VALUES"
|
||||
_TOKEN_ATTR = "_dify_sqlcommenter_context_token"
|
||||
|
||||
|
||||
class CelerySqlcommenterTagsDict(TypedDict, total=False):
|
||||
framework: str
|
||||
task_name: str
|
||||
traceparent: str
|
||||
celery_retries: int
|
||||
routing_key: str
|
||||
|
||||
|
||||
def _build_celery_sqlcommenter_tags(task: Any) -> CelerySqlcommenterTagsDict:
|
||||
"""Build SQL commenter tags from the current Celery task and OpenTelemetry context."""
|
||||
tags: CelerySqlcommenterTagsDict = {}
|
||||
|
||||
try:
|
||||
tags["framework"] = f"celery:{_get_celery_version()}"
|
||||
except Exception:
|
||||
tags["framework"] = "celery:unknown"
|
||||
|
||||
if task and getattr(task, "name", None):
|
||||
tags["task_name"] = str(task.name)
|
||||
|
||||
traceparent = _get_traceparent()
|
||||
if traceparent:
|
||||
tags["traceparent"] = traceparent
|
||||
|
||||
if task and hasattr(task, "request"):
|
||||
request = task.request
|
||||
retries = getattr(request, "retries", None)
|
||||
if retries is not None and retries > 0:
|
||||
tags["celery_retries"] = int(retries)
|
||||
|
||||
delivery_info = getattr(request, "delivery_info", None) or {}
|
||||
if isinstance(delivery_info, dict):
|
||||
routing_key = delivery_info.get("routing_key")
|
||||
if routing_key:
|
||||
tags["routing_key"] = str(routing_key)
|
||||
|
||||
return tags
|
||||
|
||||
|
||||
def _get_celery_version() -> str:
|
||||
import celery
|
||||
|
||||
return getattr(celery, "__version__", "unknown")
|
||||
|
||||
|
||||
def _get_traceparent() -> str | None:
|
||||
"""Extract traceparent from the current OpenTelemetry context."""
|
||||
carrier: dict[str, str] = {}
|
||||
_TRACE_PROPAGATOR.inject(carrier)
|
||||
return carrier.get("traceparent")
|
||||
|
||||
|
||||
def _on_task_prerun(*args: object, **kwargs: object) -> None:
|
||||
task = kwargs.get("task")
|
||||
if not isinstance(task, Task):
|
||||
return
|
||||
|
||||
tags = _build_celery_sqlcommenter_tags(task)
|
||||
if not tags:
|
||||
return
|
||||
|
||||
current = context.get_current()
|
||||
new_ctx = context.set_value(_SQLCOMMENTER_CONTEXT_KEY, tags, current)
|
||||
token = context.attach(new_ctx)
|
||||
# Celery reuses one Task instance across concurrent invocations. Its request
|
||||
# is execution-local, so another invocation cannot overwrite this token.
|
||||
setattr(task.request, _TOKEN_ATTR, token)
|
||||
|
||||
|
||||
def _on_task_postrun(*args: object, **kwargs: object) -> None:
|
||||
task = kwargs.get("task")
|
||||
if not isinstance(task, Task):
|
||||
return
|
||||
|
||||
request = task.request
|
||||
token = getattr(request, _TOKEN_ATTR, None)
|
||||
if token is None:
|
||||
return
|
||||
|
||||
delattr(request, _TOKEN_ATTR)
|
||||
context.detach(token)
|
||||
|
||||
|
||||
def setup_celery_sqlcommenter(*, tracer_provider: TracerProvider, meter_provider: MeterProvider) -> None:
|
||||
"""
|
||||
Install Celery instrumentation with SQL comments inside its activation scope.
|
||||
|
||||
Celery invokes signal receivers in registration order. The SQL context must
|
||||
attach after OTel's task span is active, then detach before OTel restores its
|
||||
parent. Registering both handlers after instrument() would restore an ended
|
||||
task span during postrun instead of leaving the caller's context intact.
|
||||
"""
|
||||
instrumentor = CeleryInstrumentor()
|
||||
if instrumentor.is_instrumented_by_opentelemetry:
|
||||
# Auto-instrumentation may already own the signal order and providers.
|
||||
# Keep its spans intact rather than add a context we cannot unwind first.
|
||||
logger.warning("Celery is already instrumented; skipping SQL commenter signal registration")
|
||||
return
|
||||
|
||||
task_postrun.connect(_on_task_postrun, weak=False)
|
||||
instrumentor.instrument(tracer_provider=tracer_provider, meter_provider=meter_provider)
|
||||
task_prerun.connect(_on_task_prerun, weak=False)
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Utilities for propagating OpenTelemetry context across execution boundaries."""
|
||||
|
||||
import contextvars
|
||||
import functools
|
||||
from collections.abc import Callable
|
||||
|
||||
from opentelemetry import context as otel_context
|
||||
|
||||
|
||||
def propagate_context[**P, R](func: Callable[P, R]) -> Callable[P, R]:
|
||||
"""Capture the current context and attach it whenever ``func`` executes."""
|
||||
captured_context = otel_context.get_current()
|
||||
captured_contextvars = contextvars.copy_context()
|
||||
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
||||
token = otel_context.attach(captured_context)
|
||||
try:
|
||||
return captured_contextvars.run(func, *args, **kwargs)
|
||||
finally:
|
||||
otel_context.detach(token)
|
||||
|
||||
return wrapper
|
||||
Whitespace-only changes.
@@ -0,0 +1,44 @@
|
||||
import functools
|
||||
from collections.abc import Callable
|
||||
from typing import cast
|
||||
|
||||
from opentelemetry.trace import get_tracer
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.otel.decorators.handler import SpanHandler
|
||||
from extensions.otel.runtime import is_instrument_flag_enabled
|
||||
|
||||
_HANDLER_INSTANCES: dict[type[SpanHandler], SpanHandler] = {SpanHandler: SpanHandler()}
|
||||
|
||||
|
||||
def _get_handler_instance(handler_class: type[SpanHandler]) -> SpanHandler:
|
||||
"""Get or create a singleton instance of the handler class."""
|
||||
if handler_class not in _HANDLER_INSTANCES:
|
||||
_HANDLER_INSTANCES[handler_class] = handler_class()
|
||||
return _HANDLER_INSTANCES[handler_class]
|
||||
|
||||
|
||||
def trace_span[**P, R](handler_class: type[SpanHandler] | None = None) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
||||
"""
|
||||
Decorator that traces a function with an OpenTelemetry span.
|
||||
|
||||
The decorator uses the provided handler class to create a singleton handler instance
|
||||
and delegates the wrapper implementation to that handler.
|
||||
|
||||
:param handler_class: Optional handler class to use for this span. If None, uses the default SpanHandler.
|
||||
"""
|
||||
|
||||
def decorator(func: Callable[P, R]) -> Callable[P, R]:
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
||||
if not (dify_config.ENABLE_OTEL or is_instrument_flag_enabled()):
|
||||
return func(*args, **kwargs)
|
||||
|
||||
handler = _get_handler_instance(handler_class or SpanHandler)
|
||||
tracer = get_tracer(__name__)
|
||||
|
||||
return handler.wrapper(tracer, func, *args, **kwargs)
|
||||
|
||||
return cast(Callable[P, R], wrapper)
|
||||
|
||||
return decorator
|
||||
@@ -0,0 +1,95 @@
|
||||
import inspect
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode, Tracer
|
||||
|
||||
|
||||
class SpanHandler:
|
||||
"""
|
||||
Base class for all span handlers.
|
||||
|
||||
Each instrumentation point provides a handler implementation that fully controls
|
||||
how spans are created, annotated, and finalized through the wrapper method.
|
||||
|
||||
This class provides a default implementation that creates a basic span and handles
|
||||
exceptions. Handlers can override the wrapper method to customize behavior.
|
||||
"""
|
||||
|
||||
_signature_cache: dict[Callable[..., object], inspect.Signature] = {}
|
||||
|
||||
def _build_span_name[**P, R](self, wrapped: Callable[P, R]) -> str:
|
||||
"""
|
||||
Build the span name from the wrapped function.
|
||||
|
||||
Handlers can override this method to customize span name generation.
|
||||
|
||||
:param wrapped: The original function being traced
|
||||
:return: The span name
|
||||
"""
|
||||
return f"{wrapped.__module__}.{wrapped.__qualname__}"
|
||||
|
||||
def _extract_arguments[**P, R](
|
||||
self,
|
||||
wrapped: Callable[P, R],
|
||||
*args: P.args,
|
||||
**kwargs: P.kwargs,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
Extract function arguments using inspect.signature.
|
||||
|
||||
Returns a dictionary of bound arguments, or None if extraction fails.
|
||||
Handlers can use this to safely extract parameters from args/kwargs.
|
||||
|
||||
The function signature is cached to improve performance on repeated calls.
|
||||
|
||||
:param wrapped: The function being traced
|
||||
:param args: Positional arguments
|
||||
:param kwargs: Keyword arguments
|
||||
:return: Dictionary of bound arguments, or None if extraction fails
|
||||
"""
|
||||
try:
|
||||
if wrapped not in self._signature_cache:
|
||||
self._signature_cache[wrapped] = inspect.signature(wrapped)
|
||||
|
||||
sig = self._signature_cache[wrapped]
|
||||
bound = sig.bind(*args, **kwargs)
|
||||
bound.apply_defaults()
|
||||
return bound.arguments
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def wrapper[**P, R](
|
||||
self,
|
||||
tracer: Tracer,
|
||||
wrapped: Callable[P, R],
|
||||
*args: P.args,
|
||||
**kwargs: P.kwargs,
|
||||
) -> R:
|
||||
"""
|
||||
Fully control the wrapper behavior.
|
||||
|
||||
Default implementation creates a basic span and handles exceptions.
|
||||
Handlers can override this method to provide complete control over:
|
||||
- Span creation and configuration
|
||||
- Attribute extraction
|
||||
- Function invocation
|
||||
- Exception handling
|
||||
- Status setting
|
||||
|
||||
:param tracer: OpenTelemetry tracer instance
|
||||
:param wrapped: The original function being traced
|
||||
:param args: Positional arguments (including self/cls if applicable)
|
||||
:param kwargs: Keyword arguments
|
||||
:return: Result of calling wrapped function
|
||||
"""
|
||||
span_name = self._build_span_name(wrapped)
|
||||
with tracer.start_as_current_span(span_name, kind=SpanKind.INTERNAL) as span:
|
||||
try:
|
||||
result = wrapped(*args, **kwargs)
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
return result
|
||||
except Exception as exc:
|
||||
span.record_exception(exc)
|
||||
span.set_status(Status(StatusCode.ERROR, str(exc)))
|
||||
raise
|
||||
@@ -0,0 +1,65 @@
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from typing import override
|
||||
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode, Tracer
|
||||
from opentelemetry.util.types import AttributeValue
|
||||
|
||||
from extensions.otel.decorators.handler import SpanHandler
|
||||
from extensions.otel.semconv import DifySpanAttributes, GenAIAttributes
|
||||
from models.model import Account
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AppGenerateHandler(SpanHandler):
|
||||
"""Span handler for ``AppGenerateService.generate``."""
|
||||
|
||||
@override
|
||||
def wrapper[**P, R](
|
||||
self,
|
||||
tracer: Tracer,
|
||||
wrapped: Callable[P, R],
|
||||
*args: P.args,
|
||||
**kwargs: P.kwargs,
|
||||
) -> R:
|
||||
try:
|
||||
arguments = self._extract_arguments(wrapped, *args, **kwargs)
|
||||
if not arguments:
|
||||
return wrapped(*args, **kwargs)
|
||||
|
||||
app_model = arguments.get("app_model")
|
||||
user = arguments.get("user")
|
||||
args_dict = arguments.get("args", {})
|
||||
streaming = arguments.get("streaming", True)
|
||||
|
||||
if not app_model or not user or not isinstance(args_dict, dict):
|
||||
return wrapped(*args, **kwargs)
|
||||
app_id = getattr(app_model, "id", None) or "unknown"
|
||||
tenant_id = getattr(app_model, "tenant_id", None) or "unknown"
|
||||
user_id = getattr(user, "id", None) or "unknown"
|
||||
workflow_id = args_dict.get("workflow_id") or "unknown"
|
||||
|
||||
attributes: dict[str, AttributeValue] = {
|
||||
DifySpanAttributes.APP_ID: app_id,
|
||||
DifySpanAttributes.TENANT_ID: tenant_id,
|
||||
GenAIAttributes.USER_ID: user_id,
|
||||
DifySpanAttributes.USER_TYPE: "Account" if isinstance(user, Account) else "EndUser",
|
||||
DifySpanAttributes.STREAMING: streaming,
|
||||
DifySpanAttributes.WORKFLOW_ID: workflow_id,
|
||||
}
|
||||
|
||||
span_name = self._build_span_name(wrapped)
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to prepare span attributes for AppGenerateService.generate: %s", exc, exc_info=True)
|
||||
return wrapped(*args, **kwargs)
|
||||
|
||||
with tracer.start_as_current_span(span_name, kind=SpanKind.INTERNAL, attributes=attributes) as span:
|
||||
try:
|
||||
result = wrapped(*args, **kwargs)
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
return result
|
||||
except Exception as exc:
|
||||
span.record_exception(exc)
|
||||
span.set_status(Status(StatusCode.ERROR, str(exc)))
|
||||
raise
|
||||
@@ -0,0 +1,66 @@
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from typing import override
|
||||
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode, Tracer
|
||||
from opentelemetry.util.types import AttributeValue
|
||||
|
||||
from extensions.otel.decorators.handler import SpanHandler
|
||||
from extensions.otel.semconv import DifySpanAttributes, GenAIAttributes
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class WorkflowAppRunnerHandler(SpanHandler):
|
||||
"""Trace the workflow driver's full execution, including graph preparation."""
|
||||
|
||||
@override
|
||||
def wrapper[**P, R](
|
||||
self,
|
||||
tracer: Tracer,
|
||||
wrapped: Callable[P, R],
|
||||
*args: P.args,
|
||||
**kwargs: P.kwargs,
|
||||
) -> R:
|
||||
try:
|
||||
arguments = self._extract_arguments(wrapped, *args, **kwargs)
|
||||
if not arguments:
|
||||
return wrapped(*args, **kwargs)
|
||||
|
||||
runner = arguments.get("runner")
|
||||
if runner is None or not hasattr(runner, "application_generate_entity"):
|
||||
return wrapped(*args, **kwargs)
|
||||
|
||||
entity = runner.application_generate_entity
|
||||
app_config = getattr(entity, "app_config", None)
|
||||
if app_config is None:
|
||||
return wrapped(*args, **kwargs)
|
||||
|
||||
user_id: AttributeValue = getattr(entity, "user_id", None) or "unknown"
|
||||
app_id: AttributeValue = getattr(app_config, "app_id", None) or "unknown"
|
||||
tenant_id: AttributeValue = getattr(app_config, "tenant_id", None) or "unknown"
|
||||
workflow_id: AttributeValue = getattr(app_config, "workflow_id", None) or "unknown"
|
||||
streaming = getattr(entity, "stream", True)
|
||||
|
||||
attributes: dict[str, AttributeValue] = {
|
||||
DifySpanAttributes.APP_ID: app_id,
|
||||
DifySpanAttributes.TENANT_ID: tenant_id,
|
||||
GenAIAttributes.USER_ID: user_id,
|
||||
DifySpanAttributes.STREAMING: streaming,
|
||||
DifySpanAttributes.WORKFLOW_ID: workflow_id,
|
||||
}
|
||||
|
||||
span_name = self._build_span_name(wrapped)
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to prepare workflow execution span attributes: %s", exc, exc_info=True)
|
||||
return wrapped(*args, **kwargs)
|
||||
|
||||
with tracer.start_as_current_span(span_name, kind=SpanKind.INTERNAL, attributes=attributes) as span:
|
||||
try:
|
||||
result = wrapped(*args, **kwargs)
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
return result
|
||||
except Exception as exc:
|
||||
span.record_exception(exc)
|
||||
span.set_status(Status(StatusCode.ERROR, str(exc)))
|
||||
raise
|
||||
@@ -0,0 +1,164 @@
|
||||
import contextlib
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from typing import Protocol, cast, override
|
||||
|
||||
import flask
|
||||
from opentelemetry.instrumentation.celery import CeleryInstrumentor
|
||||
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
|
||||
from opentelemetry.instrumentation.redis import RedisInstrumentor
|
||||
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
|
||||
from opentelemetry.metrics import get_meter, get_meter_provider
|
||||
from opentelemetry.semconv.attributes.http_attributes import ( # type: ignore[import-untyped]
|
||||
HTTP_REQUEST_METHOD,
|
||||
HTTP_ROUTE,
|
||||
)
|
||||
from opentelemetry.trace import Span, get_tracer_provider
|
||||
from opentelemetry.trace.status import StatusCode
|
||||
|
||||
from configs import dify_config
|
||||
from dify_app import DifyApp
|
||||
from extensions.otel.runtime import is_celery_worker
|
||||
from extensions.otel.workflow_collaboration import init_workflow_collaboration_metrics
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SupportsInstrument(Protocol):
|
||||
def instrument(self, **kwargs: object) -> None: ...
|
||||
|
||||
|
||||
class SupportsFlaskInstrumentor(Protocol):
|
||||
def instrument_app(
|
||||
self, app: DifyApp, response_hook: Callable[[Span, str, list], None] | None = None, **kwargs: object
|
||||
) -> None: ...
|
||||
|
||||
|
||||
# Some OpenTelemetry instrumentor constructors are typed loosely enough that
|
||||
# pyrefly infers `NoneType`. Narrow the instances to just the methods we use
|
||||
# while leaving runtime behavior unchanged.
|
||||
def _new_celery_instrumentor() -> SupportsInstrument:
|
||||
return cast(SupportsInstrument, CeleryInstrumentor())
|
||||
|
||||
|
||||
def _new_httpx_instrumentor() -> SupportsInstrument:
|
||||
return cast(SupportsInstrument, HTTPXClientInstrumentor())
|
||||
|
||||
|
||||
def _new_redis_instrumentor() -> SupportsInstrument:
|
||||
return cast(SupportsInstrument, RedisInstrumentor())
|
||||
|
||||
|
||||
def _new_sqlalchemy_instrumentor() -> SupportsInstrument:
|
||||
return cast(SupportsInstrument, SQLAlchemyInstrumentor())
|
||||
|
||||
|
||||
class ExceptionLoggingHandler(logging.Handler):
|
||||
"""
|
||||
Handler that records exceptions to the current OpenTelemetry span.
|
||||
|
||||
Unlike creating a new span, this records exceptions on the existing span
|
||||
to maintain trace context consistency throughout the request lifecycle.
|
||||
"""
|
||||
|
||||
@override
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
with contextlib.suppress(Exception):
|
||||
if not record.exc_info:
|
||||
return
|
||||
|
||||
from opentelemetry.trace import get_current_span
|
||||
|
||||
span = get_current_span()
|
||||
if not span or not span.is_recording():
|
||||
return
|
||||
|
||||
# Record exception on the current span instead of creating a new one
|
||||
span.set_status(StatusCode.ERROR, record.getMessage())
|
||||
|
||||
# Add log context as span events/attributes
|
||||
span.add_event(
|
||||
"log.exception",
|
||||
attributes={
|
||||
"log.level": record.levelname,
|
||||
"log.message": record.getMessage(),
|
||||
"log.logger": record.name,
|
||||
"log.file.path": record.pathname,
|
||||
"log.file.line": record.lineno,
|
||||
},
|
||||
)
|
||||
|
||||
if record.exc_info[1]:
|
||||
span.record_exception(record.exc_info[1])
|
||||
if record.exc_info[0]:
|
||||
span.set_attribute("exception.type", record.exc_info[0].__name__)
|
||||
|
||||
|
||||
def instrument_exception_logging() -> None:
|
||||
exception_handler = ExceptionLoggingHandler()
|
||||
logging.getLogger().addHandler(exception_handler)
|
||||
|
||||
|
||||
def init_flask_instrumentor(app: DifyApp) -> None:
|
||||
meter = get_meter("http_metrics", version=dify_config.project.version)
|
||||
_http_response_counter = meter.create_counter(
|
||||
"http.server.response.count",
|
||||
description="Total number of HTTP responses by status code, method and target",
|
||||
unit="{response}",
|
||||
)
|
||||
|
||||
def response_hook(span: Span, status: str, response_headers: list) -> None:
|
||||
if span and span.is_recording():
|
||||
try:
|
||||
if status.startswith("2"):
|
||||
span.set_status(StatusCode.OK)
|
||||
else:
|
||||
span.set_status(StatusCode.ERROR, status)
|
||||
|
||||
status = status.split(" ")[0]
|
||||
status_code = int(status)
|
||||
status_class = f"{status_code // 100}xx"
|
||||
attributes: dict[str, str | int] = {"status_code": status_code, "status_class": status_class}
|
||||
request = flask.request
|
||||
if request and request.url_rule:
|
||||
attributes[HTTP_ROUTE] = str(request.url_rule.rule)
|
||||
if request and request.method:
|
||||
attributes[HTTP_REQUEST_METHOD] = str(request.method)
|
||||
_http_response_counter.add(1, attributes)
|
||||
except Exception:
|
||||
logger.exception("Error setting status and attributes")
|
||||
|
||||
from opentelemetry.instrumentation.flask import FlaskInstrumentor
|
||||
|
||||
instrumentor = cast(SupportsFlaskInstrumentor, FlaskInstrumentor())
|
||||
if dify_config.DEBUG:
|
||||
logger.info("Initializing Flask instrumentor")
|
||||
instrumentor.instrument_app(app, response_hook=response_hook)
|
||||
|
||||
|
||||
def init_sqlalchemy_instrumentor(app: DifyApp) -> None:
|
||||
with app.app_context():
|
||||
engines = list(app.extensions["sqlalchemy"].engines.values())
|
||||
_new_sqlalchemy_instrumentor().instrument(enable_commenter=True, engines=engines)
|
||||
|
||||
|
||||
def init_redis_instrumentor() -> None:
|
||||
_new_redis_instrumentor().instrument()
|
||||
|
||||
|
||||
def init_httpx_instrumentor() -> None:
|
||||
_new_httpx_instrumentor().instrument()
|
||||
|
||||
|
||||
def init_instruments(app: DifyApp) -> None:
|
||||
if not is_celery_worker():
|
||||
init_flask_instrumentor(app)
|
||||
init_workflow_collaboration_metrics(app)
|
||||
_new_celery_instrumentor().instrument(
|
||||
tracer_provider=get_tracer_provider(), meter_provider=get_meter_provider()
|
||||
)
|
||||
|
||||
instrument_exception_logging()
|
||||
init_sqlalchemy_instrumentor(app)
|
||||
init_redis_instrumentor()
|
||||
init_httpx_instrumentor()
|
||||
@@ -0,0 +1,21 @@
|
||||
"""
|
||||
OpenTelemetry node parsers for workflow nodes.
|
||||
|
||||
This module provides parsers that extract node-specific metadata and set
|
||||
OpenTelemetry span attributes according to semantic conventions.
|
||||
"""
|
||||
|
||||
from extensions.otel.parser.base import DefaultNodeOTelParser, NodeOTelParser, safe_json_dumps, should_include_content
|
||||
from extensions.otel.parser.llm import LLMNodeOTelParser
|
||||
from extensions.otel.parser.retrieval import RetrievalNodeOTelParser
|
||||
from extensions.otel.parser.tool import ToolNodeOTelParser
|
||||
|
||||
__all__ = [
|
||||
"DefaultNodeOTelParser",
|
||||
"LLMNodeOTelParser",
|
||||
"NodeOTelParser",
|
||||
"RetrievalNodeOTelParser",
|
||||
"ToolNodeOTelParser",
|
||||
"safe_json_dumps",
|
||||
"should_include_content",
|
||||
]
|
||||
@@ -0,0 +1,133 @@
|
||||
"""
|
||||
Base parser interface and utilities for OpenTelemetry node parsers.
|
||||
|
||||
Content gating: ``should_include_content()`` controls whether content-bearing
|
||||
span attributes (inputs, outputs, prompts, completions, documents) are written.
|
||||
Gate is only active in the Enterprise edition when
|
||||
``ENTERPRISE_INCLUDE_CONTENT=False``; CE behaviour is unchanged.
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import Any, Protocol
|
||||
|
||||
from opentelemetry.trace import Span
|
||||
from opentelemetry.trace.status import Status, StatusCode
|
||||
from pydantic import BaseModel
|
||||
|
||||
from configs import dify_config
|
||||
from enums import DeploymentEdition
|
||||
from extensions.otel.semconv.gen_ai import ChainAttributes, GenAIAttributes
|
||||
from graphon.engine_events import NodeEvent
|
||||
from graphon.enums import BuiltinNodeTypes
|
||||
from graphon.file import File
|
||||
from graphon.nodes.base.node import Node
|
||||
from graphon.variables import Segment
|
||||
|
||||
|
||||
def should_include_content() -> bool:
|
||||
"""Return True if content should be written to spans.
|
||||
|
||||
Community and Cloud editions: always True — no behaviour change.
|
||||
"""
|
||||
if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.ENTERPRISE:
|
||||
return True
|
||||
return dify_config.ENTERPRISE_INCLUDE_CONTENT
|
||||
|
||||
|
||||
def safe_json_dumps(obj: Any, ensure_ascii: bool = False) -> str:
|
||||
"""
|
||||
Safely serialize objects to JSON, handling non-serializable types.
|
||||
|
||||
Handles:
|
||||
- Segment types (ArrayFileSegment, FileSegment, etc.) - converts to their value
|
||||
- File objects - converts to dict using to_dict()
|
||||
- BaseModel objects - converts using model_dump()
|
||||
- Other types - falls back to str() representation
|
||||
|
||||
Args:
|
||||
obj: Object to serialize
|
||||
ensure_ascii: Whether to ensure ASCII encoding
|
||||
|
||||
Returns:
|
||||
JSON string representation of the object
|
||||
"""
|
||||
|
||||
def _convert_value(value: Any) -> Any:
|
||||
"""Recursively convert non-serializable values."""
|
||||
match value:
|
||||
case None:
|
||||
return None
|
||||
case bool() | int() | float() | str():
|
||||
return value
|
||||
case Segment():
|
||||
# Convert Segment to its underlying value
|
||||
return _convert_value(value.value)
|
||||
case File():
|
||||
# Convert File to dict
|
||||
return value.to_dict()
|
||||
case BaseModel():
|
||||
# Convert Pydantic model to dict
|
||||
return _convert_value(value.model_dump(mode="json"))
|
||||
case dict():
|
||||
return {k: _convert_value(v) for k, v in value.items()}
|
||||
case list() | tuple():
|
||||
return [_convert_value(item) for item in value]
|
||||
case _:
|
||||
# Fallback to string representation for unknown types
|
||||
return str(value)
|
||||
|
||||
try:
|
||||
converted = _convert_value(obj)
|
||||
return json.dumps(converted, ensure_ascii=ensure_ascii)
|
||||
except (TypeError, ValueError) as e:
|
||||
# If conversion still fails, return error message as string
|
||||
return json.dumps(
|
||||
{"error": f"Failed to serialize: {type(obj).__name__}", "message": str(e)}, ensure_ascii=ensure_ascii
|
||||
)
|
||||
|
||||
|
||||
class NodeOTelParser(Protocol):
|
||||
"""Parser interface for node-specific OpenTelemetry enrichment."""
|
||||
|
||||
def parse(
|
||||
self, *, node: Node, span: "Span", error: Exception | None, result_event: NodeEvent | None = None
|
||||
) -> None: ...
|
||||
|
||||
|
||||
class DefaultNodeOTelParser:
|
||||
"""Fallback parser used when no node-specific parser is registered."""
|
||||
|
||||
def parse(
|
||||
self, *, node: Node, span: "Span", error: Exception | None, result_event: NodeEvent | None = None
|
||||
) -> None:
|
||||
span.set_attribute("node.id", node.id)
|
||||
if node.execution_id:
|
||||
span.set_attribute("node.execution_id", node.execution_id)
|
||||
span.set_attribute("node.type", node.node_type)
|
||||
|
||||
span.set_attribute(GenAIAttributes.FRAMEWORK, "dify")
|
||||
|
||||
match node.node_type:
|
||||
case BuiltinNodeTypes.LLM:
|
||||
span.set_attribute(GenAIAttributes.SPAN_KIND, "LLM")
|
||||
case BuiltinNodeTypes.KNOWLEDGE_RETRIEVAL:
|
||||
span.set_attribute(GenAIAttributes.SPAN_KIND, "RETRIEVER")
|
||||
case BuiltinNodeTypes.TOOL:
|
||||
span.set_attribute(GenAIAttributes.SPAN_KIND, "TOOL")
|
||||
case _:
|
||||
span.set_attribute(GenAIAttributes.SPAN_KIND, "TASK")
|
||||
|
||||
# Extract inputs and outputs from result_event
|
||||
if result_event and result_event.node_run_result:
|
||||
node_run_result = result_event.node_run_result
|
||||
if should_include_content():
|
||||
if node_run_result.inputs:
|
||||
span.set_attribute(ChainAttributes.INPUT_VALUE, safe_json_dumps(node_run_result.inputs))
|
||||
if node_run_result.outputs:
|
||||
span.set_attribute(ChainAttributes.OUTPUT_VALUE, safe_json_dumps(node_run_result.outputs))
|
||||
|
||||
if error:
|
||||
span.record_exception(error)
|
||||
span.set_status(Status(StatusCode.ERROR, str(error)))
|
||||
else:
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
@@ -0,0 +1,155 @@
|
||||
"""
|
||||
Parser for LLM nodes that captures LLM-specific metadata.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
from opentelemetry.trace import Span
|
||||
|
||||
from extensions.otel.parser.base import DefaultNodeOTelParser, safe_json_dumps
|
||||
from extensions.otel.semconv.gen_ai import LLMAttributes
|
||||
from graphon.engine_events import NodeEvent
|
||||
from graphon.nodes.base.node import Node
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _format_input_messages(process_data: Mapping[str, Any]) -> str:
|
||||
"""
|
||||
Format input messages from process_data for LLM spans.
|
||||
|
||||
Args:
|
||||
process_data: Process data containing prompts
|
||||
|
||||
Returns:
|
||||
JSON string of formatted input messages
|
||||
"""
|
||||
try:
|
||||
if not isinstance(process_data, dict):
|
||||
return safe_json_dumps([])
|
||||
|
||||
prompts = process_data.get("prompts", [])
|
||||
if not prompts:
|
||||
return safe_json_dumps([])
|
||||
|
||||
valid_roles = {"system", "user", "assistant", "tool"}
|
||||
input_messages = []
|
||||
for prompt in prompts:
|
||||
if not isinstance(prompt, dict):
|
||||
continue
|
||||
|
||||
role = prompt.get("role", "")
|
||||
text = prompt.get("text", "")
|
||||
|
||||
if not role or role not in valid_roles:
|
||||
continue
|
||||
|
||||
if text:
|
||||
message = {"role": role, "parts": [{"type": "text", "content": text}]}
|
||||
input_messages.append(message)
|
||||
|
||||
return safe_json_dumps(input_messages)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to format input messages: %s", e, exc_info=True)
|
||||
return safe_json_dumps([])
|
||||
|
||||
|
||||
def _format_output_messages(outputs: Mapping[str, Any]) -> str:
|
||||
"""
|
||||
Format output messages from outputs for LLM spans.
|
||||
|
||||
Args:
|
||||
outputs: Output data containing text and finish_reason
|
||||
|
||||
Returns:
|
||||
JSON string of formatted output messages
|
||||
"""
|
||||
try:
|
||||
if not isinstance(outputs, dict):
|
||||
return safe_json_dumps([])
|
||||
|
||||
text = outputs.get("text", "")
|
||||
finish_reason = outputs.get("finish_reason", "")
|
||||
|
||||
if not text:
|
||||
return safe_json_dumps([])
|
||||
|
||||
valid_finish_reasons = {"stop", "length", "content_filter", "tool_call", "error"}
|
||||
if finish_reason not in valid_finish_reasons:
|
||||
finish_reason = "stop"
|
||||
|
||||
output_message = {
|
||||
"role": "assistant",
|
||||
"parts": [{"type": "text", "content": text}],
|
||||
"finish_reason": finish_reason,
|
||||
}
|
||||
|
||||
return safe_json_dumps([output_message])
|
||||
except Exception as e:
|
||||
logger.warning("Failed to format output messages: %s", e, exc_info=True)
|
||||
return safe_json_dumps([])
|
||||
|
||||
|
||||
class LLMNodeOTelParser:
|
||||
"""Parser for LLM nodes that captures LLM-specific metadata."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._delegate = DefaultNodeOTelParser()
|
||||
|
||||
def parse(
|
||||
self, *, node: Node, span: "Span", error: Exception | None, result_event: NodeEvent | None = None
|
||||
) -> None:
|
||||
self._delegate.parse(node=node, span=span, error=error, result_event=result_event)
|
||||
|
||||
if not result_event or not result_event.node_run_result:
|
||||
return
|
||||
|
||||
node_run_result = result_event.node_run_result
|
||||
process_data = node_run_result.process_data or {}
|
||||
outputs = node_run_result.outputs or {}
|
||||
|
||||
# Extract usage data (from process_data or outputs)
|
||||
usage_data = process_data.get("usage") or outputs.get("usage") or {}
|
||||
|
||||
# Model and provider information
|
||||
model_name = process_data.get("model_name") or ""
|
||||
model_provider = process_data.get("model_provider") or ""
|
||||
|
||||
if model_name:
|
||||
span.set_attribute(LLMAttributes.REQUEST_MODEL, model_name)
|
||||
if model_provider:
|
||||
span.set_attribute(LLMAttributes.PROVIDER_NAME, model_provider)
|
||||
|
||||
# Token usage
|
||||
if usage_data:
|
||||
prompt_tokens = usage_data.get("prompt_tokens", 0)
|
||||
completion_tokens = usage_data.get("completion_tokens", 0)
|
||||
total_tokens = usage_data.get("total_tokens", 0)
|
||||
|
||||
span.set_attribute(LLMAttributes.USAGE_INPUT_TOKENS, prompt_tokens)
|
||||
span.set_attribute(LLMAttributes.USAGE_OUTPUT_TOKENS, completion_tokens)
|
||||
span.set_attribute(LLMAttributes.USAGE_TOTAL_TOKENS, total_tokens)
|
||||
|
||||
# Prompts and completion
|
||||
prompts = process_data.get("prompts", [])
|
||||
if prompts:
|
||||
prompts_json = safe_json_dumps(prompts)
|
||||
span.set_attribute(LLMAttributes.PROMPT, prompts_json)
|
||||
|
||||
text_output = str(outputs.get("text", ""))
|
||||
if text_output:
|
||||
span.set_attribute(LLMAttributes.COMPLETION, text_output)
|
||||
|
||||
# Finish reason
|
||||
finish_reason = outputs.get("finish_reason") or ""
|
||||
if finish_reason:
|
||||
span.set_attribute(LLMAttributes.RESPONSE_FINISH_REASON, finish_reason)
|
||||
|
||||
# Structured input/output messages
|
||||
gen_ai_input_message = _format_input_messages(process_data)
|
||||
gen_ai_output_message = _format_output_messages(outputs)
|
||||
|
||||
span.set_attribute(LLMAttributes.INPUT_MESSAGE, gen_ai_input_message)
|
||||
span.set_attribute(LLMAttributes.OUTPUT_MESSAGE, gen_ai_output_message)
|
||||
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
Parser for knowledge retrieval nodes that captures retrieval-specific metadata.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from opentelemetry.trace import Span
|
||||
|
||||
from extensions.otel.parser.base import DefaultNodeOTelParser, safe_json_dumps
|
||||
from extensions.otel.semconv.gen_ai import RetrieverAttributes
|
||||
from graphon.engine_events import NodeEvent
|
||||
from graphon.nodes.base.node import Node
|
||||
from graphon.variables import Segment
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _format_retrieval_documents(retrieval_documents: list[Any]) -> list:
|
||||
"""
|
||||
Format retrieval documents for semantic conventions.
|
||||
|
||||
Args:
|
||||
retrieval_documents: List of retrieval document dictionaries
|
||||
|
||||
Returns:
|
||||
List of formatted semantic documents
|
||||
"""
|
||||
try:
|
||||
if not isinstance(retrieval_documents, list):
|
||||
return []
|
||||
|
||||
semantic_documents = []
|
||||
for doc in retrieval_documents:
|
||||
if not isinstance(doc, dict):
|
||||
continue
|
||||
|
||||
metadata = doc.get("metadata", {})
|
||||
content = doc.get("content", "")
|
||||
title = doc.get("title", "")
|
||||
score = metadata.get("score", 0.0)
|
||||
document_id = metadata.get("document_id", "")
|
||||
|
||||
semantic_metadata = {}
|
||||
if title:
|
||||
semantic_metadata["title"] = title
|
||||
if metadata.get("source"):
|
||||
semantic_metadata["source"] = metadata["source"]
|
||||
elif metadata.get("_source"):
|
||||
semantic_metadata["source"] = metadata["_source"]
|
||||
if metadata.get("doc_metadata"):
|
||||
doc_metadata = metadata["doc_metadata"]
|
||||
if isinstance(doc_metadata, dict):
|
||||
semantic_metadata.update(doc_metadata)
|
||||
|
||||
semantic_doc = {
|
||||
"document": {"content": content, "metadata": semantic_metadata, "score": score, "id": document_id}
|
||||
}
|
||||
semantic_documents.append(semantic_doc)
|
||||
|
||||
return semantic_documents
|
||||
except Exception as e:
|
||||
logger.warning("Failed to format retrieval documents: %s", e, exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
class RetrievalNodeOTelParser:
|
||||
"""Parser for knowledge retrieval nodes that captures retrieval-specific metadata."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._delegate = DefaultNodeOTelParser()
|
||||
|
||||
def parse(
|
||||
self, *, node: Node, span: "Span", error: Exception | None, result_event: NodeEvent | None = None
|
||||
) -> None:
|
||||
self._delegate.parse(node=node, span=span, error=error, result_event=result_event)
|
||||
|
||||
if not result_event or not result_event.node_run_result:
|
||||
return
|
||||
|
||||
node_run_result = result_event.node_run_result
|
||||
inputs = node_run_result.inputs or {}
|
||||
outputs = node_run_result.outputs or {}
|
||||
|
||||
# Extract query from inputs
|
||||
query = str(inputs.get("query", "")) if inputs else ""
|
||||
if query:
|
||||
span.set_attribute(RetrieverAttributes.QUERY, query)
|
||||
|
||||
# Extract and format retrieval documents from outputs
|
||||
result_value = outputs.get("result") if outputs else None
|
||||
retrieval_documents: list[Any] = []
|
||||
if result_value:
|
||||
value_to_check = result_value
|
||||
if isinstance(result_value, Segment):
|
||||
value_to_check = result_value.value
|
||||
|
||||
if isinstance(value_to_check, (list, Sequence)):
|
||||
retrieval_documents = list(value_to_check)
|
||||
|
||||
if retrieval_documents:
|
||||
semantic_retrieval_documents = _format_retrieval_documents(retrieval_documents)
|
||||
semantic_retrieval_documents_json = safe_json_dumps(semantic_retrieval_documents)
|
||||
span.set_attribute(RetrieverAttributes.DOCUMENT, semantic_retrieval_documents_json)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
Parser for tool nodes that captures tool-specific metadata.
|
||||
"""
|
||||
|
||||
from opentelemetry.trace import Span
|
||||
|
||||
from extensions.otel.parser.base import DefaultNodeOTelParser, safe_json_dumps
|
||||
from extensions.otel.semconv.gen_ai import ToolAttributes
|
||||
from graphon.engine_events import NodeEvent
|
||||
from graphon.enums import WorkflowNodeExecutionMetadataKey
|
||||
from graphon.nodes.base.node import Node
|
||||
from graphon.nodes.tool.entities import ToolNodeData
|
||||
|
||||
|
||||
class ToolNodeOTelParser:
|
||||
"""Parser for tool nodes that captures tool-specific metadata."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._delegate = DefaultNodeOTelParser()
|
||||
|
||||
def parse(
|
||||
self, *, node: Node, span: "Span", error: Exception | None, result_event: NodeEvent | None = None
|
||||
) -> None:
|
||||
self._delegate.parse(node=node, span=span, error=error, result_event=result_event)
|
||||
|
||||
tool_data = getattr(node, "_node_data", None)
|
||||
if not isinstance(tool_data, ToolNodeData):
|
||||
return
|
||||
|
||||
span.set_attribute(ToolAttributes.TOOL_NAME, node.title)
|
||||
span.set_attribute(ToolAttributes.TOOL_TYPE, tool_data.provider_type.value)
|
||||
|
||||
# Extract tool info from metadata (consistent with aliyun_trace)
|
||||
tool_info = {}
|
||||
if result_event and result_event.node_run_result:
|
||||
node_run_result = result_event.node_run_result
|
||||
if node_run_result.metadata:
|
||||
tool_info = node_run_result.metadata.get(WorkflowNodeExecutionMetadataKey.TOOL_INFO, {})
|
||||
|
||||
if tool_info:
|
||||
span.set_attribute(ToolAttributes.TOOL_DESCRIPTION, safe_json_dumps(tool_info))
|
||||
|
||||
if result_event and result_event.node_run_result and result_event.node_run_result.inputs:
|
||||
span.set_attribute(ToolAttributes.TOOL_CALL_ARGUMENTS, safe_json_dumps(result_event.node_run_result.inputs))
|
||||
|
||||
if result_event and result_event.node_run_result and result_event.node_run_result.outputs:
|
||||
span.set_attribute(ToolAttributes.TOOL_CALL_RESULT, safe_json_dumps(result_event.node_run_result.outputs))
|
||||
@@ -0,0 +1,109 @@
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
from celery.signals import worker_init
|
||||
from flask_login import user_loaded_from_request, user_logged_in
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry.propagate import set_global_textmap
|
||||
from opentelemetry.propagators.b3 import B3MultiFormat
|
||||
from opentelemetry.propagators.composite import CompositePropagator
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.otel.semconv import DifySpanAttributes, GenAIAttributes
|
||||
from libs.helper import extract_tenant_id
|
||||
from models import Account, EndUser
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def setup_context_propagation() -> None:
|
||||
set_global_textmap(
|
||||
CompositePropagator(
|
||||
[
|
||||
TraceContextTextMapPropagator(),
|
||||
B3MultiFormat(),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def shutdown_tracer() -> None:
|
||||
flush_telemetry()
|
||||
|
||||
|
||||
def flush_telemetry() -> None:
|
||||
"""
|
||||
Best-effort flush for telemetry providers.
|
||||
|
||||
This is mainly used by short-lived command processes (e.g. Kubernetes CronJob)
|
||||
so counters/histograms are exported before the process exits.
|
||||
"""
|
||||
provider = trace.get_tracer_provider()
|
||||
if hasattr(provider, "force_flush"):
|
||||
try:
|
||||
provider.force_flush()
|
||||
except Exception:
|
||||
logger.exception("otel: failed to flush trace provider")
|
||||
|
||||
metric_provider = metrics.get_meter_provider()
|
||||
if hasattr(metric_provider, "force_flush"):
|
||||
try:
|
||||
metric_provider.force_flush()
|
||||
except Exception:
|
||||
logger.exception("otel: failed to flush metric provider")
|
||||
|
||||
|
||||
def is_celery_worker():
|
||||
return "celery" in sys.argv[0].lower()
|
||||
|
||||
|
||||
@user_logged_in.connect
|
||||
@user_loaded_from_request.connect
|
||||
def on_user_loaded(_sender: object, user: Account | EndUser | None) -> None:
|
||||
if dify_config.ENABLE_OTEL and user:
|
||||
try:
|
||||
if not trace.get_current_span().is_recording():
|
||||
return
|
||||
set_identity_span_attributes(tenant_id=extract_tenant_id(user), user_id=user.id)
|
||||
except Exception:
|
||||
logger.exception("Error setting tenant and user attributes")
|
||||
|
||||
|
||||
def set_identity_span_attributes(*, tenant_id: str | None, user_id: str) -> None:
|
||||
"""Enrich the recording span; a missing workspace (None) skips enrichment."""
|
||||
if not dify_config.ENABLE_OTEL:
|
||||
return
|
||||
try:
|
||||
current_span = trace.get_current_span()
|
||||
if not current_span.is_recording() or not tenant_id:
|
||||
return
|
||||
current_span.set_attributes({DifySpanAttributes.TENANT_ID: tenant_id, GenAIAttributes.USER_ID: user_id})
|
||||
except Exception:
|
||||
logger.exception("Error setting tenant and user attributes")
|
||||
|
||||
|
||||
@worker_init.connect(weak=False)
|
||||
def init_celery_worker(*args: object, **kwargs: object):
|
||||
if dify_config.ENABLE_OTEL:
|
||||
from opentelemetry.metrics import get_meter_provider
|
||||
from opentelemetry.trace import get_tracer_provider
|
||||
|
||||
from extensions.otel.celery_sqlcommenter import setup_celery_sqlcommenter
|
||||
|
||||
tracer_provider = get_tracer_provider()
|
||||
metric_provider = get_meter_provider()
|
||||
if dify_config.DEBUG:
|
||||
logger.info("Initializing OpenTelemetry for Celery worker")
|
||||
setup_celery_sqlcommenter(tracer_provider=tracer_provider, meter_provider=metric_provider)
|
||||
|
||||
|
||||
def is_instrument_flag_enabled() -> bool:
|
||||
"""
|
||||
Check if external instrumentation is enabled via environment variable.
|
||||
|
||||
Third-party non-invasive instrumentation agents set this flag to coordinate
|
||||
with Dify's manual OpenTelemetry instrumentation.
|
||||
"""
|
||||
return os.getenv("ENABLE_OTEL_FOR_INSTRUMENT", "").strip().lower() == "true"
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Semantic convention shortcuts for Dify-specific spans."""
|
||||
|
||||
from .dify import DifySpanAttributes
|
||||
from .gen_ai import ChainAttributes, GenAIAttributes, LLMAttributes, RetrieverAttributes, ToolAttributes
|
||||
|
||||
__all__ = [
|
||||
"ChainAttributes",
|
||||
"DifySpanAttributes",
|
||||
"GenAIAttributes",
|
||||
"LLMAttributes",
|
||||
"RetrieverAttributes",
|
||||
"ToolAttributes",
|
||||
]
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Dify-specific semantic convention definitions."""
|
||||
|
||||
|
||||
class DifySpanAttributes:
|
||||
"""Attribute names for Dify-specific spans."""
|
||||
|
||||
APP_ID = "dify.app_id"
|
||||
"""Application identifier."""
|
||||
|
||||
TENANT_ID = "dify.tenant_id"
|
||||
"""Tenant identifier."""
|
||||
|
||||
USER_TYPE = "dify.user_type"
|
||||
"""User type, e.g. Account, EndUser."""
|
||||
|
||||
STREAMING = "dify.streaming"
|
||||
"""Whether streaming response is enabled."""
|
||||
|
||||
WORKFLOW_ID = "dify.workflow_id"
|
||||
"""Workflow identifier."""
|
||||
|
||||
WORKFLOW_ABORT_REASON = "dify.workflow.abort.reason"
|
||||
"""Reason recorded when a workflow run is aborted."""
|
||||
|
||||
INVOKE_FROM = "dify.invoke_from"
|
||||
"""Invocation source, e.g. SERVICE_API, WEB_APP, DEBUGGER."""
|
||||
|
||||
INVOKED_BY = "dify.invoked_by"
|
||||
"""Invoked by, e.g. end_user, account, user."""
|
||||
|
||||
USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"
|
||||
"""Number of input tokens (prompt tokens) used."""
|
||||
|
||||
USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"
|
||||
"""Number of output tokens (completion tokens) generated."""
|
||||
|
||||
USAGE_TOTAL_TOKENS = "gen_ai.usage.total_tokens"
|
||||
"""Total number of tokens used."""
|
||||
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
GenAI semantic conventions.
|
||||
"""
|
||||
|
||||
|
||||
class GenAIAttributes:
|
||||
"""Common GenAI attribute keys."""
|
||||
|
||||
USER_ID = "gen_ai.user.id"
|
||||
"""Identifier of the end user in the application layer."""
|
||||
|
||||
FRAMEWORK = "gen_ai.framework"
|
||||
"""Framework type. Fixed to 'dify' in this project."""
|
||||
|
||||
SPAN_KIND = "gen_ai.span.kind"
|
||||
"""Operation type. Extended specification, not in OTel standard."""
|
||||
|
||||
|
||||
class ChainAttributes:
|
||||
"""Chain operation attribute keys."""
|
||||
|
||||
OPERATION_NAME = "gen_ai.operation.name"
|
||||
"""Secondary operation type, e.g. WORKFLOW, TASK."""
|
||||
|
||||
INPUT_VALUE = "input.value"
|
||||
"""Input content."""
|
||||
|
||||
OUTPUT_VALUE = "output.value"
|
||||
"""Output content."""
|
||||
|
||||
TIME_TO_FIRST_TOKEN = "gen_ai.user.time_to_first_token"
|
||||
"""Time to first token in nanoseconds from receiving the request to first token return."""
|
||||
|
||||
|
||||
class RetrieverAttributes:
|
||||
"""Retriever operation attribute keys."""
|
||||
|
||||
QUERY = "retrieval.query"
|
||||
"""Retrieval query string."""
|
||||
|
||||
DOCUMENT = "retrieval.document"
|
||||
"""Retrieved document list as JSON array."""
|
||||
|
||||
|
||||
class ToolAttributes:
|
||||
"""Tool operation attribute keys."""
|
||||
|
||||
TOOL_CALL_ID = "gen_ai.tool.call.id"
|
||||
"""Tool call identifier."""
|
||||
|
||||
TOOL_DESCRIPTION = "gen_ai.tool.description"
|
||||
"""Tool description."""
|
||||
|
||||
TOOL_NAME = "gen_ai.tool.name"
|
||||
"""Tool name."""
|
||||
|
||||
TOOL_TYPE = "gen_ai.tool.type"
|
||||
"""Tool type. Examples: function, extension, datastore."""
|
||||
|
||||
TOOL_CALL_ARGUMENTS = "gen_ai.tool.call.arguments"
|
||||
"""Tool invocation arguments."""
|
||||
|
||||
TOOL_CALL_RESULT = "gen_ai.tool.call.result"
|
||||
"""Tool invocation result."""
|
||||
|
||||
|
||||
class LLMAttributes:
|
||||
"""LLM operation attribute keys."""
|
||||
|
||||
REQUEST_MODEL = "gen_ai.request.model"
|
||||
"""Model identifier."""
|
||||
|
||||
PROVIDER_NAME = "gen_ai.provider.name"
|
||||
"""Provider name."""
|
||||
|
||||
USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"
|
||||
"""Number of input tokens."""
|
||||
|
||||
USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"
|
||||
"""Number of output tokens."""
|
||||
|
||||
USAGE_TOTAL_TOKENS = "gen_ai.usage.total_tokens"
|
||||
"""Total number of tokens."""
|
||||
|
||||
PROMPT = "gen_ai.prompt"
|
||||
"""Prompt text."""
|
||||
|
||||
COMPLETION = "gen_ai.completion"
|
||||
"""Completion text."""
|
||||
|
||||
RESPONSE_FINISH_REASON = "gen_ai.response.finish_reason"
|
||||
"""Finish reason for the response."""
|
||||
|
||||
INPUT_MESSAGE = "gen_ai.input.messages"
|
||||
"""Input messages in structured format."""
|
||||
|
||||
OUTPUT_MESSAGE = "gen_ai.output.messages"
|
||||
"""Output messages in structured format."""
|
||||
@@ -0,0 +1,271 @@
|
||||
"""Worker-local Socket.IO load metrics without persistence or per-message network I/O.
|
||||
|
||||
Lifecycle updates run on the Socket.IO gevent hub and never yield. Observable callbacks
|
||||
only read immutable numeric snapshots, including when the SDK collects on a native thread.
|
||||
Room counts describe local membership, not globally distinct rooms or distinct people.
|
||||
No room, socket, tenant, user, payload, or exception values become metric attributes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Callable, Iterable, Mapping, Sequence
|
||||
from functools import wraps
|
||||
from time import perf_counter
|
||||
from typing import Literal, NamedTuple, Protocol, runtime_checkable
|
||||
|
||||
from flask import Flask
|
||||
from opentelemetry.metrics import CallbackOptions, Meter, Observation, get_meter
|
||||
|
||||
from configs import dify_config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
type SocketEvent = Literal["connect", "user_connect", "disconnect", "collaboration_event", "graph_event"]
|
||||
type Outcome = Literal["success", "rejected", "error"]
|
||||
|
||||
_EVENT_TYPES = frozenset(
|
||||
{
|
||||
"mouse_move",
|
||||
"vars_and_features_update",
|
||||
"sync_request",
|
||||
"workflow_update",
|
||||
"comments_update",
|
||||
"node_panel_presence",
|
||||
"graph_view_state",
|
||||
"graph_resync_request",
|
||||
}
|
||||
)
|
||||
_SIZE_RANGES = ("1", "2-5", "6-10", "11-20", "21+")
|
||||
_WORKER_ATTRIBUTES = {"aggregation_scope": "worker"}
|
||||
_EXTENSION_KEY = "workflow_collaboration_metrics"
|
||||
|
||||
|
||||
class _SocketManager(Protocol):
|
||||
def is_connected(self, sid: str, namespace: str) -> bool: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class _SocketIO(Protocol):
|
||||
@property
|
||||
def app(self) -> Flask: ...
|
||||
|
||||
@property
|
||||
def manager(self) -> _SocketManager: ...
|
||||
|
||||
def rooms(self, sid: str, namespace: str) -> list[str]: ...
|
||||
|
||||
|
||||
class _Snapshot(NamedTuple):
|
||||
connections: int
|
||||
rooms: int
|
||||
size_ranges: tuple[int, ...]
|
||||
|
||||
|
||||
def _size_range(size: int) -> str:
|
||||
"""Given a positive local room size, return one bounded attribute value without I/O."""
|
||||
if size == 1:
|
||||
return "1"
|
||||
if size <= 5:
|
||||
return "2-5"
|
||||
if size <= 10:
|
||||
return "6-10"
|
||||
if size <= 20:
|
||||
return "11-20"
|
||||
return "21+"
|
||||
|
||||
|
||||
class WorkflowCollaborationMetrics:
|
||||
"""Own one worker's instruments and an idempotent mirror of accepted socket membership.
|
||||
|
||||
Writers must run in Socket.IO handlers on the gevent hub; they perform no I/O or
|
||||
yielding operations. SDK collection never traverses the mutable membership maps.
|
||||
Unknown/late joins cannot recreate disconnected sessions, and duplicate lifecycle
|
||||
notifications cannot inflate counts. Instrument failures are isolated by the decorator.
|
||||
"""
|
||||
|
||||
def __init__(self, meter: Meter | None = None) -> None:
|
||||
"""Register instruments with the supplied/default meter and start with zero load."""
|
||||
self._connections: dict[str, frozenset[str]] = {}
|
||||
self._room_sizes: dict[str, int] = {}
|
||||
self._size_counts = dict.fromkeys(_SIZE_RANGES, 0)
|
||||
self._snapshot = _Snapshot(0, 0, (0,) * len(_SIZE_RANGES))
|
||||
meter = meter if meter is not None else get_meter("dify.collaboration")
|
||||
meter.create_observable_gauge(
|
||||
"dify.collaboration.connections",
|
||||
callbacks=(self._observe_connections,),
|
||||
description="Authenticated Socket.IO sessions connected to this worker; not distinct users",
|
||||
unit="{connection}",
|
||||
)
|
||||
meter.create_observable_gauge(
|
||||
"dify.collaboration.rooms",
|
||||
callbacks=(self._observe_rooms,),
|
||||
description="Workflow rooms with local members; summing workers does not give globally distinct rooms",
|
||||
unit="{room}",
|
||||
)
|
||||
meter.create_observable_gauge(
|
||||
"dify.collaboration.room_sessions",
|
||||
callbacks=(self._observe_room_sessions,),
|
||||
description="Current local room count by local session-count range; not a join-weighted histogram",
|
||||
unit="{room}",
|
||||
)
|
||||
self._events = meter.create_counter(
|
||||
"dify.collaboration.events", description="Completed Socket.IO handlers by event and outcome", unit="{event}"
|
||||
)
|
||||
self._duration = meter.create_histogram(
|
||||
"dify.collaboration.event_duration",
|
||||
description="Socket.IO handler wall time, including dependency waits; not peer delivery or client ACK time",
|
||||
unit="s",
|
||||
explicit_bucket_boundaries_advisory=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 15, 30),
|
||||
)
|
||||
|
||||
def _observe_connections(self, _: CallbackOptions) -> Iterable[Observation]:
|
||||
"""Return a numeric snapshot for any collector thread without accessing live sockets."""
|
||||
return (Observation(self._snapshot.connections, attributes=_WORKER_ATTRIBUTES),)
|
||||
|
||||
def _observe_rooms(self, _: CallbackOptions) -> Iterable[Observation]:
|
||||
"""Return the local room snapshot, including zero after the last member leaves."""
|
||||
return (Observation(self._snapshot.rooms, attributes=_WORKER_ATTRIBUTES),)
|
||||
|
||||
def _observe_room_sessions(self, _: CallbackOptions) -> Iterable[Observation]:
|
||||
"""Return all fixed range counts from one snapshot without exposing room identifiers."""
|
||||
snapshot = self._snapshot
|
||||
return tuple(
|
||||
Observation(count, attributes={**_WORKER_ATTRIBUTES, "size_range": size_range})
|
||||
for size_range, count in zip(_SIZE_RANGES, snapshot.size_ranges, strict=True)
|
||||
)
|
||||
|
||||
def _publish_snapshot(self) -> None:
|
||||
"""After a lifecycle update, atomically replace the collector's immutable numeric view."""
|
||||
self._snapshot = _Snapshot(len(self._connections), len(self._room_sizes), tuple(self._size_counts.values()))
|
||||
|
||||
def _change_room_size(self, room: str, delta: Literal[-1, 1]) -> None:
|
||||
"""Apply one known member addition/removal and keep current room buckets consistent."""
|
||||
previous = self._room_sizes.get(room, 0)
|
||||
if previous:
|
||||
self._size_counts[_size_range(previous)] -= 1
|
||||
current = previous + delta
|
||||
if current:
|
||||
self._room_sizes[room] = current
|
||||
self._size_counts[_size_range(current)] += 1
|
||||
else:
|
||||
del self._room_sizes[room]
|
||||
|
||||
def connected(self, sid: str) -> None:
|
||||
"""Register a live, authenticated SID once; a duplicate preserves existing memberships."""
|
||||
if sid not in self._connections:
|
||||
self._connections[sid] = frozenset()
|
||||
self._publish_snapshot()
|
||||
|
||||
def update_rooms(self, sid: str, rooms: Sequence[str]) -> None:
|
||||
"""Mirror actual rooms for a registered SID; ignore late joins and exclude its private room."""
|
||||
previous = self._connections.get(sid)
|
||||
if previous is None:
|
||||
return
|
||||
current = frozenset(room for room in rooms if room != sid)
|
||||
for room in previous - current:
|
||||
self._change_room_size(room, -1)
|
||||
for room in current - previous:
|
||||
self._change_room_size(room, 1)
|
||||
self._connections[sid] = current
|
||||
self._publish_snapshot()
|
||||
|
||||
def disconnected(self, sid: str) -> None:
|
||||
"""Remove a SID and all local memberships, tolerating duplicate or rejected disconnects."""
|
||||
previous = self._connections.pop(sid, None)
|
||||
if previous is not None:
|
||||
for room in previous:
|
||||
self._change_room_size(room, -1)
|
||||
self._publish_snapshot()
|
||||
|
||||
def record_event(self, event: SocketEvent, event_type: str, outcome: Outcome, duration_seconds: float) -> None:
|
||||
"""Record one completed handler with bounded labels; propagate SDK failures to the isolation boundary."""
|
||||
bounded_type = event_type if event_type in _EVENT_TYPES else "other"
|
||||
attributes = {
|
||||
"event": event,
|
||||
"event_type": bounded_type if event == "collaboration_event" else "none",
|
||||
"outcome": outcome,
|
||||
}
|
||||
self._events.add(1, attributes=attributes)
|
||||
self._duration.record(duration_seconds, attributes=attributes)
|
||||
|
||||
|
||||
def init_workflow_collaboration_metrics(app: Flask) -> None:
|
||||
"""Bind metrics during enabled OTel startup, after the provider and before serving events.
|
||||
|
||||
The application owns one instance; repeated startup calls preserve its state.
|
||||
Registration failure leaves instrumentation absent and business handlers usable.
|
||||
"""
|
||||
if _EXTENSION_KEY not in app.extensions:
|
||||
try:
|
||||
app.extensions[_EXTENSION_KEY] = WorkflowCollaborationMetrics()
|
||||
except Exception:
|
||||
logger.exception("Failed to initialize workflow collaboration metrics")
|
||||
|
||||
|
||||
def _outcome(result: object) -> Outcome:
|
||||
"""Classify existing handler results without modifying their body, status, or identity."""
|
||||
if result is False:
|
||||
return "rejected"
|
||||
if isinstance(result, tuple) and len(result) == 2 and isinstance(result[1], int):
|
||||
if result[1] >= 500:
|
||||
return "error"
|
||||
if result[1] >= 400:
|
||||
return "rejected"
|
||||
return "success"
|
||||
|
||||
|
||||
def observe_workflow_event[**P, R](
|
||||
event: SocketEvent, socketio: _SocketIO
|
||||
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
||||
"""Observe an existing synchronous Socket.IO handler without changing returns or exceptions.
|
||||
|
||||
The caller supplies the event and Socket.IO server bound to its initialized app.
|
||||
Disabled or unavailable instrumentation calls the handler directly. Otherwise capture
|
||||
membership in the handler thread, even when a join partially succeeds or Redis cleanup
|
||||
fails, without additional Redis/SQL queries. Telemetry failures never alter authentication,
|
||||
room membership, ACK payloads, or the handler's exception.
|
||||
"""
|
||||
|
||||
def decorate(handler: Callable[P, R]) -> Callable[P, R]:
|
||||
"""Preserve the handler signature and metadata while observing its completion."""
|
||||
|
||||
@wraps(handler)
|
||||
def observed(*args: P.args, **kwargs: P.kwargs) -> R:
|
||||
"""Run the original handler once and isolate all metric-side failures in finally."""
|
||||
if not dify_config.ENABLE_OTEL:
|
||||
return handler(*args, **kwargs)
|
||||
metrics = socketio.app.extensions.get(_EXTENSION_KEY)
|
||||
if not isinstance(metrics, WorkflowCollaborationMetrics):
|
||||
return handler(*args, **kwargs)
|
||||
|
||||
started = perf_counter()
|
||||
outcome: Outcome = "error"
|
||||
try:
|
||||
result = handler(*args, **kwargs)
|
||||
outcome = _outcome(result)
|
||||
return result
|
||||
finally:
|
||||
duration = perf_counter() - started
|
||||
try:
|
||||
sid = args[0] if args else kwargs.get("sid")
|
||||
try:
|
||||
if isinstance(sid, str):
|
||||
if event == "connect" and outcome == "success" and socketio.manager.is_connected(sid, "/"):
|
||||
metrics.connected(sid)
|
||||
elif event == "user_connect":
|
||||
metrics.update_rooms(sid, socketio.rooms(sid, "/"))
|
||||
elif event == "disconnect":
|
||||
metrics.disconnected(sid)
|
||||
finally:
|
||||
data = args[1] if len(args) > 1 else kwargs.get("data")
|
||||
event_type = data.get("type") if isinstance(data, Mapping) else None
|
||||
metrics.record_event(
|
||||
event, event_type if isinstance(event_type, str) else "other", outcome, duration
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("Failed to record workflow collaboration metrics", exc_info=True)
|
||||
|
||||
return observed
|
||||
|
||||
return decorate
|
||||
@@ -0,0 +1,32 @@
|
||||
from configs import dify_config
|
||||
|
||||
|
||||
def normalize_redis_key_prefix(prefix: str | None) -> str:
|
||||
"""Normalize the configured Redis key prefix for consistent runtime use."""
|
||||
if prefix is None:
|
||||
return ""
|
||||
return prefix.strip()
|
||||
|
||||
|
||||
def get_redis_key_prefix() -> str:
|
||||
"""Read and normalize the current Redis key prefix from config."""
|
||||
return normalize_redis_key_prefix(dify_config.REDIS_KEY_PREFIX)
|
||||
|
||||
|
||||
def serialize_redis_name(name: str, prefix: str | None = None) -> str:
|
||||
"""Convert a logical Redis name into the physical name used in Redis."""
|
||||
normalized_prefix = get_redis_key_prefix() if prefix is None else normalize_redis_key_prefix(prefix)
|
||||
if not normalized_prefix:
|
||||
return name
|
||||
return f"{normalized_prefix}:{name}"
|
||||
|
||||
|
||||
def serialize_redis_name_arg(name: str | bytes, prefix: str | None = None) -> str | bytes:
|
||||
"""Prefix string Redis names while preserving bytes inputs unchanged."""
|
||||
if isinstance(name, bytes):
|
||||
return name
|
||||
return serialize_redis_name(name, prefix)
|
||||
|
||||
|
||||
def serialize_redis_name_args(names: tuple[str | bytes, ...], prefix: str | None = None) -> tuple[str | bytes, ...]:
|
||||
return tuple(serialize_redis_name_arg(name, prefix) for name in names)
|
||||
@@ -0,0 +1,71 @@
|
||||
import posixpath
|
||||
from collections.abc import Generator
|
||||
from typing import override
|
||||
|
||||
import oss2 as aliyun_s3
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.storage.base_storage import BaseStorage
|
||||
|
||||
|
||||
class AliyunOssStorage(BaseStorage):
|
||||
"""Implementation for Aliyun OSS storage."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.bucket_name = dify_config.ALIYUN_OSS_BUCKET_NAME
|
||||
self.folder = dify_config.ALIYUN_OSS_PATH
|
||||
oss_auth_method = aliyun_s3.Auth
|
||||
region = None
|
||||
if dify_config.ALIYUN_OSS_AUTH_VERSION == "v4":
|
||||
oss_auth_method = aliyun_s3.AuthV4
|
||||
region = dify_config.ALIYUN_OSS_REGION
|
||||
oss_auth = oss_auth_method(dify_config.ALIYUN_OSS_ACCESS_KEY, dify_config.ALIYUN_OSS_SECRET_KEY)
|
||||
self.client = aliyun_s3.Bucket(
|
||||
oss_auth,
|
||||
dify_config.ALIYUN_OSS_ENDPOINT,
|
||||
self.bucket_name,
|
||||
connect_timeout=30,
|
||||
region=region,
|
||||
cloudbox_id=dify_config.ALIYUN_CLOUDBOX_ID,
|
||||
)
|
||||
|
||||
@override
|
||||
def save(self, filename, data):
|
||||
self.client.put_object(self.__wrapper_folder_filename(filename), data)
|
||||
|
||||
@override
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
obj = self.client.get_object(self.__wrapper_folder_filename(filename))
|
||||
data = obj.read()
|
||||
if not isinstance(data, bytes):
|
||||
return b""
|
||||
return data
|
||||
|
||||
@override
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
obj = self.client.get_object(self.__wrapper_folder_filename(filename))
|
||||
while chunk := obj.read(4096):
|
||||
yield chunk
|
||||
|
||||
@override
|
||||
def download(self, filename: str, target_filepath):
|
||||
self.client.get_object_to_file(self.__wrapper_folder_filename(filename), target_filepath)
|
||||
|
||||
@override
|
||||
def exists(self, filename: str):
|
||||
return self.client.object_exists(self.__wrapper_folder_filename(filename))
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
self.client.delete_object(self.__wrapper_folder_filename(filename))
|
||||
|
||||
@override
|
||||
def scan(self, path: str, files: bool = True, directories: bool = False) -> list[str]:
|
||||
prefix = self.__wrapper_folder_filename(path)
|
||||
folder_prefix = self.folder.rstrip("/") + "/" if self.folder else ""
|
||||
keys = (obj.key.removeprefix(folder_prefix) for obj in aliyun_s3.ObjectIterator(self.client, prefix=prefix))
|
||||
return self._filter_scan_keys(keys, files, directories)
|
||||
|
||||
def __wrapper_folder_filename(self, filename: str) -> str:
|
||||
return posixpath.join(self.folder, filename) if self.folder else filename
|
||||
@@ -0,0 +1,142 @@
|
||||
import logging
|
||||
from collections.abc import Generator
|
||||
from typing import override
|
||||
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.storage.base_storage import BaseStorage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AwsS3Storage(BaseStorage):
|
||||
"""Implementation for Amazon Web Services S3 storage."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.bucket_name = dify_config.S3_BUCKET_NAME
|
||||
if dify_config.S3_USE_AWS_MANAGED_IAM:
|
||||
logger.info("Using AWS managed IAM role for S3")
|
||||
|
||||
session = boto3.Session()
|
||||
region_name = dify_config.S3_REGION
|
||||
self.client = session.client(service_name="s3", region_name=region_name)
|
||||
else:
|
||||
logger.info("Using ak and sk for S3")
|
||||
|
||||
self.client = boto3.client(
|
||||
"s3",
|
||||
aws_secret_access_key=dify_config.S3_SECRET_KEY,
|
||||
aws_access_key_id=dify_config.S3_ACCESS_KEY,
|
||||
endpoint_url=dify_config.S3_ENDPOINT,
|
||||
region_name=dify_config.S3_REGION,
|
||||
config=Config(s3={"addressing_style": dify_config.S3_ADDRESS_STYLE}),
|
||||
)
|
||||
# create bucket
|
||||
try:
|
||||
self.client.head_bucket(Bucket=self.bucket_name)
|
||||
except ClientError as e:
|
||||
# if bucket not exists, create it
|
||||
if e.response.get("Error", {}).get("Code") == "404":
|
||||
self.client.create_bucket(Bucket=self.bucket_name)
|
||||
# if bucket is not accessible, pass, maybe the bucket is existing but not accessible
|
||||
elif e.response.get("Error", {}).get("Code") == "403":
|
||||
pass
|
||||
else:
|
||||
# other error, raise exception
|
||||
raise
|
||||
|
||||
@override
|
||||
def save(self, filename, data):
|
||||
self.client.put_object(Bucket=self.bucket_name, Key=filename, Body=data)
|
||||
|
||||
@override
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
try:
|
||||
data: bytes = self.client.get_object(Bucket=self.bucket_name, Key=filename)["Body"].read()
|
||||
except ClientError as ex:
|
||||
if ex.response.get("Error", {}).get("Code") == "NoSuchKey":
|
||||
raise FileNotFoundError("File not found") from ex
|
||||
else:
|
||||
raise
|
||||
return data
|
||||
|
||||
@override
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
try:
|
||||
response = self.client.get_object(Bucket=self.bucket_name, Key=filename)
|
||||
yield from response["Body"].iter_chunks()
|
||||
except ClientError as ex:
|
||||
if ex.response.get("Error", {}).get("Code") == "NoSuchKey":
|
||||
raise FileNotFoundError("file not found") from ex
|
||||
elif "reached max retries" in str(ex):
|
||||
raise ValueError("please do not request the same file too frequently") from ex
|
||||
else:
|
||||
raise
|
||||
|
||||
@override
|
||||
def download(self, filename, target_filepath):
|
||||
self.client.download_file(self.bucket_name, filename, target_filepath)
|
||||
|
||||
@override
|
||||
def exists(self, filename):
|
||||
try:
|
||||
self.client.head_object(Bucket=self.bucket_name, Key=filename)
|
||||
return True
|
||||
except ClientError:
|
||||
return False
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
self.client.delete_object(Bucket=self.bucket_name, Key=filename)
|
||||
|
||||
@override
|
||||
def generate_presigned_url(
|
||||
self,
|
||||
filename: str,
|
||||
*,
|
||||
expires_in: int,
|
||||
content_type: str | None = None,
|
||||
) -> str:
|
||||
params = {"Bucket": self.bucket_name, "Key": filename}
|
||||
if content_type:
|
||||
params["ResponseContentType"] = content_type
|
||||
|
||||
return self.client.generate_presigned_url(
|
||||
"get_object",
|
||||
Params=params,
|
||||
ExpiresIn=expires_in,
|
||||
)
|
||||
|
||||
@override
|
||||
def scan(self, path: str, files: bool = True, directories: bool = False) -> list[str]:
|
||||
"""Recursively list keys below a portable storage directory."""
|
||||
if not files and not directories:
|
||||
raise ValueError("At least one of files or directories must be True")
|
||||
|
||||
normalized_path = path.strip("/")
|
||||
prefix = f"{normalized_path}/" if normalized_path else ""
|
||||
results: set[str] = set()
|
||||
paginator = self.client.get_paginator("list_objects_v2")
|
||||
for page in paginator.paginate(Bucket=self.bucket_name, Prefix=prefix):
|
||||
for item in page.get("Contents", []):
|
||||
key = item.get("Key")
|
||||
if not isinstance(key, str) or not key.startswith(prefix):
|
||||
continue
|
||||
if key.endswith("/"):
|
||||
if directories:
|
||||
results.add(key)
|
||||
continue
|
||||
|
||||
if files:
|
||||
results.add(key)
|
||||
if directories:
|
||||
current = prefix
|
||||
for segment in key[len(prefix) :].split("/")[:-1]:
|
||||
current = f"{current}{segment}/"
|
||||
results.add(current)
|
||||
|
||||
return sorted(results)
|
||||
@@ -0,0 +1,120 @@
|
||||
from collections.abc import Generator
|
||||
from datetime import timedelta
|
||||
from typing import override
|
||||
|
||||
from azure.identity import ChainedTokenCredential, DefaultAzureCredential
|
||||
from azure.storage.blob import AccountSasPermissions, BlobServiceClient, ResourceTypes, generate_account_sas
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.ext_redis import redis_client
|
||||
from extensions.storage.base_storage import BaseStorage
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
|
||||
|
||||
class AzureBlobStorage(BaseStorage):
|
||||
"""Implementation for Azure Blob storage."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.bucket_name = dify_config.AZURE_BLOB_CONTAINER_NAME
|
||||
self.account_url = dify_config.AZURE_BLOB_ACCOUNT_URL
|
||||
self.account_name = dify_config.AZURE_BLOB_ACCOUNT_NAME
|
||||
self.account_key = dify_config.AZURE_BLOB_ACCOUNT_KEY
|
||||
|
||||
self.credential: ChainedTokenCredential | None = None
|
||||
if self.account_key == "managedidentity":
|
||||
self.credential = DefaultAzureCredential()
|
||||
else:
|
||||
self.credential = None
|
||||
|
||||
@override
|
||||
def save(self, filename, data):
|
||||
if not self.bucket_name:
|
||||
return
|
||||
|
||||
client = self._sync_client()
|
||||
blob_container = client.get_container_client(container=self.bucket_name)
|
||||
blob_container.upload_blob(filename, data)
|
||||
|
||||
@override
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
if not self.bucket_name:
|
||||
raise FileNotFoundError("Azure bucket name is not configured.")
|
||||
|
||||
client = self._sync_client()
|
||||
blob = client.get_container_client(container=self.bucket_name)
|
||||
blob = blob.get_blob_client(blob=filename)
|
||||
data = blob.download_blob().readall()
|
||||
if not isinstance(data, bytes):
|
||||
raise TypeError(f"Expected bytes from blob.readall(), got {type(data).__name__}")
|
||||
return data
|
||||
|
||||
@override
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
if not self.bucket_name:
|
||||
raise FileNotFoundError("Azure bucket name is not configured.")
|
||||
|
||||
client = self._sync_client()
|
||||
blob = client.get_blob_client(container=self.bucket_name, blob=filename)
|
||||
blob_data = blob.download_blob()
|
||||
yield from blob_data.chunks()
|
||||
|
||||
@override
|
||||
def download(self, filename, target_filepath):
|
||||
if not self.bucket_name:
|
||||
return
|
||||
|
||||
client = self._sync_client()
|
||||
|
||||
blob = client.get_blob_client(container=self.bucket_name, blob=filename)
|
||||
with open(target_filepath, "wb") as my_blob:
|
||||
blob_data = blob.download_blob()
|
||||
blob_data.readinto(my_blob)
|
||||
|
||||
@override
|
||||
def exists(self, filename):
|
||||
if not self.bucket_name:
|
||||
return False
|
||||
|
||||
client = self._sync_client()
|
||||
|
||||
blob = client.get_blob_client(container=self.bucket_name, blob=filename)
|
||||
return blob.exists()
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
if not self.bucket_name:
|
||||
return
|
||||
|
||||
client = self._sync_client()
|
||||
|
||||
blob_container = client.get_container_client(container=self.bucket_name)
|
||||
blob_container.delete_blob(filename)
|
||||
|
||||
@override
|
||||
def scan(self, path: str, files: bool = True, directories: bool = False) -> list[str]:
|
||||
if not self.bucket_name:
|
||||
raise ValueError("Azure bucket name is not configured.")
|
||||
container = self._sync_client().get_container_client(container=self.bucket_name)
|
||||
# ItemPaged follows continuation tokens automatically.
|
||||
keys = (blob.name for blob in container.list_blobs(name_starts_with=path))
|
||||
return self._filter_scan_keys(keys, files, directories)
|
||||
|
||||
def _sync_client(self):
|
||||
if self.account_key == "managedidentity":
|
||||
return BlobServiceClient(account_url=self.account_url, credential=self.credential) # type: ignore
|
||||
|
||||
cache_key = f"azure_blob_sas_token_{self.account_name}_{self.account_key}"
|
||||
cache_result = redis_client.get(cache_key)
|
||||
if cache_result is not None:
|
||||
sas_token = cache_result.decode("utf-8")
|
||||
else:
|
||||
sas_token = generate_account_sas(
|
||||
account_name=self.account_name or "",
|
||||
account_key=self.account_key or "",
|
||||
resource_types=ResourceTypes(service=True, container=True, object=True),
|
||||
permission=AccountSasPermissions(read=True, write=True, delete=True, list=True, add=True, create=True),
|
||||
expiry=naive_utc_now() + timedelta(hours=1),
|
||||
)
|
||||
redis_client.set(cache_key, sas_token, ex=3000)
|
||||
return BlobServiceClient(account_url=self.account_url or "", credential=sas_token)
|
||||
@@ -0,0 +1,76 @@
|
||||
import base64
|
||||
import hashlib
|
||||
from collections.abc import Generator
|
||||
from typing import override
|
||||
|
||||
from baidubce.auth.bce_credentials import BceCredentials
|
||||
from baidubce.bce_client_configuration import BceClientConfiguration
|
||||
from baidubce.services.bos.bos_client import BosClient
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.storage.base_storage import BaseStorage
|
||||
|
||||
|
||||
class BaiduObsStorage(BaseStorage):
|
||||
"""Implementation for Baidu OBS storage."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.bucket_name = dify_config.BAIDU_OBS_BUCKET_NAME
|
||||
client_config = BceClientConfiguration(
|
||||
credentials=BceCredentials(
|
||||
access_key_id=dify_config.BAIDU_OBS_ACCESS_KEY,
|
||||
secret_access_key=dify_config.BAIDU_OBS_SECRET_KEY,
|
||||
),
|
||||
endpoint=dify_config.BAIDU_OBS_ENDPOINT,
|
||||
)
|
||||
|
||||
self.client = BosClient(config=client_config)
|
||||
|
||||
@override
|
||||
def save(self, filename, data):
|
||||
md5 = hashlib.md5()
|
||||
md5.update(data)
|
||||
content_md5 = base64.standard_b64encode(md5.digest())
|
||||
self.client.put_object(
|
||||
bucket_name=self.bucket_name, key=filename, data=data, content_length=len(data), content_md5=content_md5
|
||||
)
|
||||
|
||||
@override
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
response = self.client.get_object(bucket_name=self.bucket_name, key=filename)
|
||||
data: bytes = response.data.read()
|
||||
return data
|
||||
|
||||
@override
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
response = self.client.get_object(bucket_name=self.bucket_name, key=filename).data
|
||||
while chunk := response.read(4096):
|
||||
yield chunk
|
||||
|
||||
@override
|
||||
def download(self, filename, target_filepath):
|
||||
self.client.get_object_to_file(bucket_name=self.bucket_name, key=filename, file_name=target_filepath)
|
||||
|
||||
@override
|
||||
def exists(self, filename):
|
||||
res = self.client.get_object_meta_data(bucket_name=self.bucket_name, key=filename)
|
||||
return res is not None
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
self.client.delete_object(bucket_name=self.bucket_name, key=filename)
|
||||
|
||||
@override
|
||||
def scan(self, path: str, files: bool = True, directories: bool = False) -> list[str]:
|
||||
keys: list[str] = []
|
||||
marker = ""
|
||||
while True:
|
||||
page = self.client.list_objects(bucket_name=self.bucket_name, prefix=path, marker=marker, max_keys=1000)
|
||||
keys.extend(obj.key for obj in page.contents)
|
||||
if not page.is_truncated:
|
||||
break
|
||||
if not page.next_marker or page.next_marker == marker:
|
||||
raise RuntimeError("BOS object listing did not advance its pagination marker")
|
||||
marker = page.next_marker
|
||||
return self._filter_scan_keys(keys, files, directories)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Abstract interface for file storage implementations."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Generator, Iterable
|
||||
|
||||
|
||||
class BaseStorage(ABC):
|
||||
"""Interface for file storage."""
|
||||
|
||||
@abstractmethod
|
||||
def save(self, filename: str, data: bytes):
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def download(self, filename: str, target_filepath: str) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def exists(self, filename: str) -> bool:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def delete(self, filename: str):
|
||||
raise NotImplementedError
|
||||
|
||||
def generate_presigned_url(
|
||||
self,
|
||||
filename: str,
|
||||
*,
|
||||
expires_in: int,
|
||||
content_type: str | None = None,
|
||||
) -> str:
|
||||
"""Generate a temporary direct-download URL when the backend supports it."""
|
||||
raise NotImplementedError("This storage backend doesn't support presigned URLs")
|
||||
|
||||
def scan(self, path, files=True, directories=False) -> list[str]:
|
||||
"""
|
||||
Scan files and directories in the given path.
|
||||
This method is implemented only in some storage backends.
|
||||
If a storage backend doesn't support scanning, it will raise NotImplementedError.
|
||||
"""
|
||||
raise NotImplementedError("This storage backend doesn't support scanning")
|
||||
|
||||
@staticmethod
|
||||
def _filter_scan_keys(keys: Iterable[str], files: bool, directories: bool) -> list[str]:
|
||||
"""Filter recursive object listings; directory entries end with '/'."""
|
||||
if not files and not directories:
|
||||
raise ValueError("At least one of files or directories must be True")
|
||||
return [key for key in keys if (key.endswith("/") and directories) or (not key.endswith("/") and files)]
|
||||
@@ -0,0 +1,5 @@
|
||||
"""ClickZetta Volume storage implementation."""
|
||||
|
||||
from .clickzetta_volume_storage import ClickZettaVolumeStorage
|
||||
|
||||
__all__ = ["ClickZettaVolumeStorage"]
|
||||
@@ -0,0 +1,543 @@
|
||||
"""ClickZetta Volume Storage Implementation
|
||||
|
||||
This module provides storage backend using ClickZetta Volume functionality.
|
||||
Supports Table Volume, User Volume, and External Volume types.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
from collections.abc import Generator
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from typing import Any, override
|
||||
|
||||
import clickzetta
|
||||
from pydantic import BaseModel, model_validator
|
||||
|
||||
from extensions.storage.base_storage import BaseStorage
|
||||
|
||||
from .volume_permissions import VolumePermissionManager, check_volume_permission
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ClickZettaVolumeConfig(BaseModel):
|
||||
"""Configuration for ClickZetta Volume storage."""
|
||||
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
instance: str = ""
|
||||
service: str = "api.clickzetta.com"
|
||||
workspace: str = "quick_start"
|
||||
vcluster: str = "default_ap"
|
||||
schema_name: str = "dify"
|
||||
volume_type: str = "table" # table|user|external
|
||||
volume_name: str | None = None # For external volumes
|
||||
table_prefix: str = "dataset_" # Prefix for table volume names
|
||||
dify_prefix: str = "dify_km" # Directory prefix for User Volume
|
||||
permission_check: bool = True # Enable/disable permission checking
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def validate_config(cls, values: dict[str, Any]):
|
||||
"""Validate the configuration values.
|
||||
|
||||
This method will first try to use CLICKZETTA_VOLUME_* environment variables,
|
||||
then fall back to CLICKZETTA_* environment variables (for vector DB config).
|
||||
"""
|
||||
|
||||
# Helper function to get environment variable with fallback
|
||||
def get_env_with_fallback(volume_key: str, fallback_key: str, default: str | None = None) -> str:
|
||||
# First try CLICKZETTA_VOLUME_* specific config
|
||||
volume_value = values.get(volume_key.lower().replace("clickzetta_volume_", ""))
|
||||
if volume_value:
|
||||
return str(volume_value)
|
||||
|
||||
# Then try environment variables
|
||||
volume_env = os.getenv(volume_key)
|
||||
if volume_env:
|
||||
return volume_env
|
||||
|
||||
# Fall back to existing CLICKZETTA_* config
|
||||
fallback_env = os.getenv(fallback_key)
|
||||
if fallback_env:
|
||||
return fallback_env
|
||||
|
||||
return default or ""
|
||||
|
||||
# Apply environment variables with fallback to existing CLICKZETTA_* config
|
||||
values.setdefault("username", get_env_with_fallback("CLICKZETTA_VOLUME_USERNAME", "CLICKZETTA_USERNAME"))
|
||||
values.setdefault("password", get_env_with_fallback("CLICKZETTA_VOLUME_PASSWORD", "CLICKZETTA_PASSWORD"))
|
||||
values.setdefault("instance", get_env_with_fallback("CLICKZETTA_VOLUME_INSTANCE", "CLICKZETTA_INSTANCE"))
|
||||
values.setdefault(
|
||||
"service", get_env_with_fallback("CLICKZETTA_VOLUME_SERVICE", "CLICKZETTA_SERVICE", "api.clickzetta.com")
|
||||
)
|
||||
values.setdefault(
|
||||
"workspace", get_env_with_fallback("CLICKZETTA_VOLUME_WORKSPACE", "CLICKZETTA_WORKSPACE", "quick_start")
|
||||
)
|
||||
values.setdefault(
|
||||
"vcluster", get_env_with_fallback("CLICKZETTA_VOLUME_VCLUSTER", "CLICKZETTA_VCLUSTER", "default_ap")
|
||||
)
|
||||
values.setdefault("schema_name", get_env_with_fallback("CLICKZETTA_VOLUME_SCHEMA", "CLICKZETTA_SCHEMA", "dify"))
|
||||
|
||||
# Volume-specific configurations (no fallback to vector DB config)
|
||||
values.setdefault("volume_type", os.getenv("CLICKZETTA_VOLUME_TYPE", "table"))
|
||||
values.setdefault("volume_name", os.getenv("CLICKZETTA_VOLUME_NAME"))
|
||||
values.setdefault("table_prefix", os.getenv("CLICKZETTA_VOLUME_TABLE_PREFIX", "dataset_"))
|
||||
values.setdefault("dify_prefix", os.getenv("CLICKZETTA_VOLUME_DIFY_PREFIX", "dify_km"))
|
||||
# Temporarily disable permission check feature, set directly to false
|
||||
values.setdefault("permission_check", False)
|
||||
|
||||
# Validate required fields
|
||||
if not values.get("username"):
|
||||
raise ValueError("CLICKZETTA_VOLUME_USERNAME or CLICKZETTA_USERNAME is required")
|
||||
if not values.get("password"):
|
||||
raise ValueError("CLICKZETTA_VOLUME_PASSWORD or CLICKZETTA_PASSWORD is required")
|
||||
if not values.get("instance"):
|
||||
raise ValueError("CLICKZETTA_VOLUME_INSTANCE or CLICKZETTA_INSTANCE is required")
|
||||
|
||||
# Validate volume type
|
||||
volume_type = values["volume_type"]
|
||||
if volume_type not in ["table", "user", "external"]:
|
||||
raise ValueError("CLICKZETTA_VOLUME_TYPE must be one of: table, user, external")
|
||||
|
||||
if volume_type == "external" and not values.get("volume_name"):
|
||||
raise ValueError("CLICKZETTA_VOLUME_NAME is required for external volume type")
|
||||
|
||||
return values
|
||||
|
||||
|
||||
class ClickZettaVolumeStorage(BaseStorage):
|
||||
"""ClickZetta Volume storage implementation."""
|
||||
|
||||
def __init__(self, config: ClickZettaVolumeConfig):
|
||||
"""Initialize ClickZetta Volume storage.
|
||||
|
||||
Args:
|
||||
config: ClickZetta Volume configuration
|
||||
"""
|
||||
self._config = config
|
||||
self._connection = None
|
||||
self._permission_manager: VolumePermissionManager | None = None
|
||||
self._init_connection()
|
||||
self._init_permission_manager()
|
||||
|
||||
logger.info("ClickZetta Volume storage initialized with type: %s", config.volume_type)
|
||||
|
||||
def _init_connection(self):
|
||||
"""Initialize ClickZetta connection."""
|
||||
try:
|
||||
self._connection = clickzetta.connect(
|
||||
username=self._config.username,
|
||||
password=self._config.password,
|
||||
instance=self._config.instance,
|
||||
service=self._config.service,
|
||||
workspace=self._config.workspace,
|
||||
vcluster=self._config.vcluster,
|
||||
schema=self._config.schema_name,
|
||||
)
|
||||
logger.debug("ClickZetta connection established")
|
||||
except Exception:
|
||||
logger.exception("Failed to connect to ClickZetta")
|
||||
raise
|
||||
|
||||
def _init_permission_manager(self):
|
||||
"""Initialize permission manager."""
|
||||
try:
|
||||
self._permission_manager = VolumePermissionManager(
|
||||
self._connection, self._config.volume_type, self._config.volume_name
|
||||
)
|
||||
logger.debug("Permission manager initialized")
|
||||
except Exception:
|
||||
logger.exception("Failed to initialize permission manager")
|
||||
raise
|
||||
|
||||
def _get_volume_path(self, filename: str, dataset_id: str | None = None) -> str:
|
||||
"""Get the appropriate volume path based on volume type."""
|
||||
if self._config.volume_type == "user":
|
||||
# Add dify prefix for User Volume to organize files
|
||||
return f"{self._config.dify_prefix}/{filename}"
|
||||
elif self._config.volume_type == "table":
|
||||
# Check if this should use User Volume (special directories)
|
||||
if dataset_id in ["upload_files", "temp", "cache", "tools", "website_files", "privkeys"]:
|
||||
# Use User Volume with dify prefix for special directories
|
||||
return f"{self._config.dify_prefix}/{filename}"
|
||||
|
||||
if dataset_id:
|
||||
return f"{self._config.table_prefix}{dataset_id}/{filename}"
|
||||
else:
|
||||
# Extract dataset_id from filename if not provided
|
||||
# Format: dataset_id/filename
|
||||
if "/" in filename:
|
||||
return filename
|
||||
else:
|
||||
raise ValueError("dataset_id is required for table volume or filename must include dataset_id/")
|
||||
elif self._config.volume_type == "external":
|
||||
return filename
|
||||
else:
|
||||
raise ValueError(f"Unsupported volume type: {self._config.volume_type}")
|
||||
|
||||
def _get_volume_sql_prefix(self, dataset_id: str | None = None) -> str:
|
||||
"""Get SQL prefix for volume operations."""
|
||||
if self._config.volume_type == "user":
|
||||
return "USER VOLUME"
|
||||
elif self._config.volume_type == "table":
|
||||
# For Dify's current file storage pattern, most files are stored in
|
||||
# paths like "upload_files/tenant_id/uuid.ext", "tools/tenant_id/uuid.ext"
|
||||
# These should use USER VOLUME for better compatibility
|
||||
if dataset_id in ["upload_files", "temp", "cache", "tools", "website_files", "privkeys"]:
|
||||
return "USER VOLUME"
|
||||
|
||||
# Only use TABLE VOLUME for actual dataset-specific paths
|
||||
# like "dataset_12345/file.pdf" or paths with dataset_ prefix
|
||||
# Default table name for generic operations
|
||||
table_name = f"{self._config.table_prefix}{dataset_id}" if dataset_id else "default_dataset"
|
||||
return f"TABLE VOLUME {table_name}"
|
||||
elif self._config.volume_type == "external":
|
||||
return f"VOLUME {self._config.volume_name}"
|
||||
else:
|
||||
raise ValueError(f"Unsupported volume type: {self._config.volume_type}")
|
||||
|
||||
def _execute_sql(self, sql: str, fetch: bool = False):
|
||||
"""Execute SQL command."""
|
||||
try:
|
||||
if self._connection is None:
|
||||
raise RuntimeError("Connection not initialized")
|
||||
with self._connection.cursor() as cursor:
|
||||
cursor.execute(sql)
|
||||
if fetch:
|
||||
return cursor.fetchall()
|
||||
return None
|
||||
except Exception:
|
||||
logger.exception("SQL execution failed: %s", sql)
|
||||
raise
|
||||
|
||||
def _ensure_table_volume_exists(self, dataset_id: str):
|
||||
"""Ensure table volume exists for the given dataset_id."""
|
||||
if self._config.volume_type != "table" or not dataset_id:
|
||||
return
|
||||
|
||||
# Skip for upload_files and other special directories that use USER VOLUME
|
||||
if dataset_id in ["upload_files", "temp", "cache", "tools", "website_files", "privkeys"]:
|
||||
return
|
||||
|
||||
table_name = f"{self._config.table_prefix}{dataset_id}"
|
||||
|
||||
try:
|
||||
# Check if table exists
|
||||
check_sql = f"SHOW TABLES LIKE '{table_name}'"
|
||||
result = self._execute_sql(check_sql, fetch=True)
|
||||
|
||||
if not result:
|
||||
# Create table with volume
|
||||
create_sql = f"""
|
||||
CREATE TABLE {table_name} (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
filename VARCHAR(255) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
INDEX idx_filename (filename)
|
||||
) WITH VOLUME
|
||||
"""
|
||||
self._execute_sql(create_sql)
|
||||
logger.info("Created table volume: %s", table_name)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning("Failed to create table volume %s: %s", table_name, e)
|
||||
# Don't raise exception, let the operation continue
|
||||
# The table might exist but not be visible due to permissions
|
||||
|
||||
@override
|
||||
def save(self, filename: str, data: bytes):
|
||||
"""Save data to ClickZetta Volume.
|
||||
|
||||
Args:
|
||||
filename: File path in volume
|
||||
data: File content as bytes
|
||||
"""
|
||||
# Extract dataset_id from filename if present
|
||||
dataset_id = None
|
||||
if "/" in filename and self._config.volume_type == "table":
|
||||
parts = filename.split("/", 1)
|
||||
if parts[0].startswith(self._config.table_prefix):
|
||||
dataset_id = parts[0][len(self._config.table_prefix) :]
|
||||
filename = parts[1]
|
||||
else:
|
||||
dataset_id = parts[0]
|
||||
filename = parts[1]
|
||||
|
||||
# Ensure table volume exists (for table volumes)
|
||||
if dataset_id:
|
||||
self._ensure_table_volume_exists(dataset_id)
|
||||
|
||||
# Check permissions (if enabled)
|
||||
if self._config.permission_check:
|
||||
# Skip permission check for special directories that use USER VOLUME
|
||||
if dataset_id not in ["upload_files", "temp", "cache", "tools", "website_files", "privkeys"]:
|
||||
if self._permission_manager is not None:
|
||||
check_volume_permission(self._permission_manager, "save", dataset_id)
|
||||
|
||||
# Write data to temporary file
|
||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||
temp_file.write(data)
|
||||
temp_file_path = temp_file.name
|
||||
|
||||
try:
|
||||
# Upload to volume
|
||||
volume_prefix = self._get_volume_sql_prefix(dataset_id)
|
||||
|
||||
# Get the actual volume path (may include dify_km prefix)
|
||||
volume_path = self._get_volume_path(filename, dataset_id)
|
||||
|
||||
# For User Volume, use the full path with dify_km prefix
|
||||
if volume_prefix == "USER VOLUME":
|
||||
sql = f"PUT '{temp_file_path}' TO {volume_prefix} FILE '{volume_path}'"
|
||||
else:
|
||||
sql = f"PUT '{temp_file_path}' TO {volume_prefix} FILE '{filename}'"
|
||||
|
||||
self._execute_sql(sql)
|
||||
logger.debug("File %s saved to ClickZetta Volume at path %s", filename, volume_path)
|
||||
finally:
|
||||
# Clean up temporary file
|
||||
Path(temp_file_path).unlink(missing_ok=True)
|
||||
|
||||
@override
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
"""Load file content from ClickZetta Volume.
|
||||
|
||||
Args:
|
||||
filename: File path in volume
|
||||
|
||||
Returns:
|
||||
File content as bytes
|
||||
"""
|
||||
# Extract dataset_id from filename if present
|
||||
dataset_id = None
|
||||
if "/" in filename and self._config.volume_type == "table":
|
||||
parts = filename.split("/", 1)
|
||||
if parts[0].startswith(self._config.table_prefix):
|
||||
dataset_id = parts[0][len(self._config.table_prefix) :]
|
||||
filename = parts[1]
|
||||
else:
|
||||
dataset_id = parts[0]
|
||||
filename = parts[1]
|
||||
|
||||
# Check permissions (if enabled)
|
||||
if self._config.permission_check:
|
||||
# Skip permission check for special directories that use USER VOLUME
|
||||
if dataset_id not in ["upload_files", "temp", "cache", "tools", "website_files", "privkeys"]:
|
||||
if self._permission_manager is not None:
|
||||
check_volume_permission(self._permission_manager, "load_once", dataset_id)
|
||||
|
||||
# Download to temporary directory
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
volume_prefix = self._get_volume_sql_prefix(dataset_id)
|
||||
|
||||
# Get the actual volume path (may include dify_km prefix)
|
||||
volume_path = self._get_volume_path(filename, dataset_id)
|
||||
|
||||
# For User Volume, use the full path with dify_km prefix
|
||||
if volume_prefix == "USER VOLUME":
|
||||
sql = f"GET {volume_prefix} FILE '{volume_path}' TO '{temp_dir}'"
|
||||
else:
|
||||
sql = f"GET {volume_prefix} FILE '{filename}' TO '{temp_dir}'"
|
||||
|
||||
self._execute_sql(sql)
|
||||
|
||||
# Find the downloaded file (may be in subdirectories)
|
||||
downloaded_file = None
|
||||
for root, _, files in os.walk(temp_dir):
|
||||
for file in files:
|
||||
if file == filename or file == os.path.basename(filename):
|
||||
downloaded_file = Path(root) / file
|
||||
break
|
||||
if downloaded_file:
|
||||
break
|
||||
|
||||
if not downloaded_file or not downloaded_file.exists():
|
||||
raise FileNotFoundError(f"Downloaded file not found: {filename}")
|
||||
|
||||
content = downloaded_file.read_bytes()
|
||||
|
||||
logger.debug("File %s loaded from ClickZetta Volume", filename)
|
||||
return content
|
||||
|
||||
@override
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
"""Load file as stream from ClickZetta Volume.
|
||||
|
||||
Args:
|
||||
filename: File path in volume
|
||||
|
||||
Yields:
|
||||
File content chunks
|
||||
"""
|
||||
content = self.load_once(filename)
|
||||
batch_size = 4096
|
||||
stream = BytesIO(content)
|
||||
|
||||
while chunk := stream.read(batch_size):
|
||||
yield chunk
|
||||
|
||||
logger.debug("File %s loaded as stream from ClickZetta Volume", filename)
|
||||
|
||||
@override
|
||||
def download(self, filename: str, target_filepath: str):
|
||||
"""Download file from ClickZetta Volume to local path.
|
||||
|
||||
Args:
|
||||
filename: File path in volume
|
||||
target_filepath: Local target file path
|
||||
"""
|
||||
content = self.load_once(filename)
|
||||
|
||||
Path(target_filepath).write_bytes(content)
|
||||
|
||||
logger.debug("File %s downloaded from ClickZetta Volume to %s", filename, target_filepath)
|
||||
|
||||
@override
|
||||
def exists(self, filename: str) -> bool:
|
||||
"""Check if file exists in ClickZetta Volume.
|
||||
|
||||
Args:
|
||||
filename: File path in volume
|
||||
|
||||
Returns:
|
||||
True if file exists, False otherwise
|
||||
"""
|
||||
try:
|
||||
# Extract dataset_id from filename if present
|
||||
dataset_id = None
|
||||
if "/" in filename and self._config.volume_type == "table":
|
||||
parts = filename.split("/", 1)
|
||||
if parts[0].startswith(self._config.table_prefix):
|
||||
dataset_id = parts[0][len(self._config.table_prefix) :]
|
||||
filename = parts[1]
|
||||
else:
|
||||
dataset_id = parts[0]
|
||||
filename = parts[1]
|
||||
|
||||
volume_prefix = self._get_volume_sql_prefix(dataset_id)
|
||||
|
||||
# Get the actual volume path (may include dify_km prefix)
|
||||
volume_path = self._get_volume_path(filename, dataset_id)
|
||||
|
||||
# For User Volume, use the full path with dify_km prefix
|
||||
if volume_prefix == "USER VOLUME":
|
||||
sql = f"LIST {volume_prefix} REGEXP = '^{volume_path}$'"
|
||||
else:
|
||||
sql = f"LIST {volume_prefix} REGEXP = '^{filename}$'"
|
||||
|
||||
rows = self._execute_sql(sql, fetch=True)
|
||||
|
||||
exists = len(rows) > 0 if rows else False
|
||||
logger.debug("File %s exists check: %s", filename, exists)
|
||||
return exists
|
||||
except Exception as e:
|
||||
logger.warning("Error checking file existence for %s: %s", filename, e)
|
||||
# Deletion relies on this result. A failed query is not proof that
|
||||
# the file is absent; retain references so callers can retry.
|
||||
raise
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
"""Delete file from ClickZetta Volume.
|
||||
|
||||
Args:
|
||||
filename: File path in volume
|
||||
"""
|
||||
if not self.exists(filename):
|
||||
logger.debug("File %s not found, skip delete", filename)
|
||||
return
|
||||
|
||||
# Extract dataset_id from filename if present
|
||||
dataset_id = None
|
||||
if "/" in filename and self._config.volume_type == "table":
|
||||
parts = filename.split("/", 1)
|
||||
if parts[0].startswith(self._config.table_prefix):
|
||||
dataset_id = parts[0][len(self._config.table_prefix) :]
|
||||
filename = parts[1]
|
||||
else:
|
||||
dataset_id = parts[0]
|
||||
filename = parts[1]
|
||||
|
||||
volume_prefix = self._get_volume_sql_prefix(dataset_id)
|
||||
|
||||
# Get the actual volume path (may include dify_km prefix)
|
||||
volume_path = self._get_volume_path(filename, dataset_id)
|
||||
|
||||
# For User Volume, use the full path with dify_km prefix
|
||||
if volume_prefix == "USER VOLUME":
|
||||
sql = f"REMOVE {volume_prefix} FILE '{volume_path}'"
|
||||
else:
|
||||
sql = f"REMOVE {volume_prefix} FILE '{filename}'"
|
||||
|
||||
self._execute_sql(sql)
|
||||
|
||||
logger.debug("File %s deleted from ClickZetta Volume", filename)
|
||||
|
||||
@override
|
||||
def scan(self, path: str, files: bool = True, directories: bool = False) -> list[str]:
|
||||
"""Scan files and directories in ClickZetta Volume.
|
||||
|
||||
Args:
|
||||
path: Path prefix to scan, or a bare dataset_id for a table-volume root
|
||||
files: Include files in results
|
||||
directories: Include directories in results
|
||||
|
||||
Returns:
|
||||
List of file/directory paths
|
||||
"""
|
||||
if not files and not directories:
|
||||
raise ValueError("At least one of files or directories must be True")
|
||||
requested_path = path
|
||||
try:
|
||||
# Match save/load/delete: the first path component selects the
|
||||
# table (or special USER VOLUME), and the remainder is its file path.
|
||||
dataset_id = None
|
||||
logical_root = ""
|
||||
if self._config.volume_type == "table":
|
||||
root, separator, relative_path = path.partition("/")
|
||||
dataset_id = root.removeprefix(self._config.table_prefix)
|
||||
path = relative_path
|
||||
if separator:
|
||||
logical_root = root + "/"
|
||||
|
||||
volume_prefix = self._get_volume_sql_prefix(dataset_id)
|
||||
|
||||
# For User Volume, add dify prefix to path
|
||||
if volume_prefix == "USER VOLUME":
|
||||
if path:
|
||||
scan_path = f"{self._config.dify_prefix}/{path}"
|
||||
sql = f"LIST {volume_prefix} SUBDIRECTORY '{scan_path}'"
|
||||
else:
|
||||
sql = f"LIST {volume_prefix} SUBDIRECTORY '{self._config.dify_prefix}'"
|
||||
else:
|
||||
sql = f"LIST {volume_prefix} SUBDIRECTORY '{path}'" if path else f"LIST {volume_prefix}"
|
||||
|
||||
rows = self._execute_sql(sql, fetch=True)
|
||||
|
||||
result = []
|
||||
if rows:
|
||||
for row in rows:
|
||||
file_path = row[0] # relative_path column
|
||||
|
||||
# For User Volume, remove dify prefix from results
|
||||
dify_prefix_with_slash = f"{self._config.dify_prefix}/"
|
||||
if volume_prefix == "USER VOLUME" and file_path.startswith(dify_prefix_with_slash):
|
||||
file_path = file_path[len(dify_prefix_with_slash) :] # Remove prefix
|
||||
|
||||
file_path = logical_root + file_path
|
||||
if logical_root and not file_path.startswith(requested_path):
|
||||
continue
|
||||
|
||||
if files and not file_path.endswith("/") or directories and file_path.endswith("/"):
|
||||
result.append(file_path)
|
||||
|
||||
logger.debug("Scanned %d items in path %s", len(result), path)
|
||||
return result
|
||||
|
||||
except Exception:
|
||||
logger.exception("Error scanning path %s", requested_path)
|
||||
raise
|
||||
@@ -0,0 +1,542 @@
|
||||
"""ClickZetta Volume file lifecycle management
|
||||
|
||||
This module provides file lifecycle management features including version control,
|
||||
automatic cleanup, backup and restore.
|
||||
Supports complete lifecycle management for knowledge base files.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import operator
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime
|
||||
from enum import StrEnum, auto
|
||||
from typing import Any, TypedDict
|
||||
|
||||
from pydantic import TypeAdapter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_metadata_adapter: TypeAdapter[dict[str, Any]] = TypeAdapter(dict[str, Any])
|
||||
|
||||
|
||||
class StorageStatisticsDict(TypedDict):
|
||||
total_files: int
|
||||
active_files: int
|
||||
archived_files: int
|
||||
deleted_files: int
|
||||
total_size: int
|
||||
versions_count: int
|
||||
oldest_file: str | None
|
||||
newest_file: str | None
|
||||
|
||||
|
||||
class FileStatus(StrEnum):
|
||||
"""File status enumeration"""
|
||||
|
||||
ACTIVE = auto() # Active status
|
||||
ARCHIVED = auto() # Archived
|
||||
DELETED = auto() # Deleted (soft delete)
|
||||
BACKUP = auto() # Backup file
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileMetadata:
|
||||
"""File metadata"""
|
||||
|
||||
filename: str
|
||||
size: int | None
|
||||
created_at: datetime
|
||||
modified_at: datetime
|
||||
version: int | None
|
||||
status: FileStatus
|
||||
checksum: str | None = None
|
||||
tags: dict[str, str] | None = None
|
||||
parent_version: int | None = None
|
||||
|
||||
def to_dict(self):
|
||||
"""Convert to dictionary format"""
|
||||
data = asdict(self)
|
||||
data["created_at"] = self.created_at.isoformat()
|
||||
data["modified_at"] = self.modified_at.isoformat()
|
||||
data["status"] = self.status.value
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> FileMetadata:
|
||||
"""Create instance from dictionary"""
|
||||
data = data.copy()
|
||||
data["created_at"] = datetime.fromisoformat(data["created_at"])
|
||||
data["modified_at"] = datetime.fromisoformat(data["modified_at"])
|
||||
data["status"] = FileStatus(data["status"])
|
||||
return cls(**data)
|
||||
|
||||
|
||||
class FileLifecycleManager:
|
||||
"""File lifecycle manager"""
|
||||
|
||||
def __init__(self, storage, dataset_id: str | None = None):
|
||||
"""Initialize lifecycle manager
|
||||
|
||||
Args:
|
||||
storage: ClickZetta Volume storage instance
|
||||
dataset_id: Dataset ID (for Table Volume)
|
||||
"""
|
||||
self._storage = storage
|
||||
self._dataset_id = dataset_id
|
||||
self._metadata_file = ".dify_file_metadata.json"
|
||||
self._version_prefix = ".versions/"
|
||||
self._backup_prefix = ".backups/"
|
||||
self._deleted_prefix = ".deleted/"
|
||||
|
||||
# Get permission manager (if exists)
|
||||
self._permission_manager: Any | None = getattr(storage, "_permission_manager", None)
|
||||
|
||||
def save_with_lifecycle(self, filename: str, data: bytes, tags: dict[str, str] | None = None) -> FileMetadata:
|
||||
"""Save file and manage lifecycle
|
||||
|
||||
Args:
|
||||
filename: File name
|
||||
data: File content
|
||||
tags: File tags
|
||||
|
||||
Returns:
|
||||
File metadata
|
||||
"""
|
||||
# Permission check
|
||||
if not self._check_permission(filename, "save"):
|
||||
from .volume_permissions import VolumePermissionError
|
||||
|
||||
raise VolumePermissionError(
|
||||
f"Permission denied for lifecycle save operation on file: {filename}",
|
||||
operation="save",
|
||||
volume_type=getattr(self._storage, "_config", {}).get("volume_type", "unknown"),
|
||||
dataset_id=self._dataset_id,
|
||||
)
|
||||
|
||||
try:
|
||||
# 1. Check if old version exists
|
||||
metadata_dict = self._load_metadata()
|
||||
current_metadata = metadata_dict.get(filename)
|
||||
|
||||
# 2. If old version exists, create version backup
|
||||
if current_metadata:
|
||||
self._create_version_backup(filename, current_metadata)
|
||||
|
||||
# 3. Calculate file information
|
||||
now = datetime.now()
|
||||
checksum = self._calculate_checksum(data)
|
||||
new_version = (current_metadata["version"] + 1) if current_metadata else 1
|
||||
|
||||
# 4. Save new file
|
||||
self._storage.save(filename, data)
|
||||
|
||||
# 5. Create metadata
|
||||
created_at = now
|
||||
parent_version = None
|
||||
|
||||
if current_metadata:
|
||||
# If created_at is string, convert to datetime
|
||||
if isinstance(current_metadata["created_at"], str):
|
||||
created_at = datetime.fromisoformat(current_metadata["created_at"])
|
||||
else:
|
||||
created_at = current_metadata["created_at"]
|
||||
parent_version = current_metadata["version"]
|
||||
|
||||
file_metadata = FileMetadata(
|
||||
filename=filename,
|
||||
size=len(data),
|
||||
created_at=created_at,
|
||||
modified_at=now,
|
||||
version=new_version,
|
||||
status=FileStatus.ACTIVE,
|
||||
checksum=checksum,
|
||||
tags=tags or {},
|
||||
parent_version=parent_version,
|
||||
)
|
||||
|
||||
# 6. Update metadata
|
||||
metadata_dict[filename] = file_metadata.to_dict()
|
||||
self._save_metadata(metadata_dict)
|
||||
|
||||
logger.info("File %s saved with lifecycle management, version %s", filename, new_version)
|
||||
return file_metadata
|
||||
|
||||
except Exception:
|
||||
logger.exception("Failed to save file with lifecycle")
|
||||
raise
|
||||
|
||||
def get_file_metadata(self, filename: str) -> FileMetadata | None:
|
||||
"""Get file metadata
|
||||
|
||||
Args:
|
||||
filename: File name
|
||||
|
||||
Returns:
|
||||
File metadata, returns None if not exists
|
||||
"""
|
||||
try:
|
||||
metadata_dict = self._load_metadata()
|
||||
if filename in metadata_dict:
|
||||
return FileMetadata.from_dict(metadata_dict[filename])
|
||||
return None
|
||||
except Exception:
|
||||
logger.exception("Failed to get file metadata for %s", filename)
|
||||
return None
|
||||
|
||||
def list_file_versions(self, filename: str) -> list[FileMetadata]:
|
||||
"""List all versions of a file
|
||||
|
||||
Args:
|
||||
filename: File name
|
||||
|
||||
Returns:
|
||||
File version list, sorted by version number
|
||||
"""
|
||||
try:
|
||||
versions = []
|
||||
|
||||
# Get current version
|
||||
current_metadata = self.get_file_metadata(filename)
|
||||
if current_metadata:
|
||||
versions.append(current_metadata)
|
||||
|
||||
# Get historical versions
|
||||
try:
|
||||
version_files = self._storage.scan(self._dataset_id or "", files=True)
|
||||
for file_path in version_files:
|
||||
if file_path.startswith(f"{self._version_prefix}{filename}.v"):
|
||||
# Parse version number
|
||||
version_str = file_path.split(".v")[-1].split(".")[0]
|
||||
try:
|
||||
_ = int(version_str)
|
||||
# Simplified processing here, should actually read metadata from version file
|
||||
# Temporarily create basic metadata information
|
||||
except ValueError:
|
||||
continue
|
||||
except Exception:
|
||||
# If cannot scan version files, only return current version
|
||||
logger.exception("Failed to scan version files for %s", filename)
|
||||
|
||||
return sorted(versions, key=lambda x: x.version or 0, reverse=True)
|
||||
|
||||
except Exception:
|
||||
logger.exception("Failed to list file versions for %s", filename)
|
||||
return []
|
||||
|
||||
def restore_version(self, filename: str, version: int) -> bool:
|
||||
"""Restore file to specified version
|
||||
|
||||
Args:
|
||||
filename: File name
|
||||
version: Version number to restore
|
||||
|
||||
Returns:
|
||||
Whether restore succeeded
|
||||
"""
|
||||
try:
|
||||
version_filename = f"{self._version_prefix}{filename}.v{version}"
|
||||
|
||||
# Check if version file exists
|
||||
if not self._storage.exists(version_filename):
|
||||
logger.warning("Version %s of %s not found", version, filename)
|
||||
return False
|
||||
|
||||
# Read version file content
|
||||
version_data = self._storage.load_once(version_filename)
|
||||
|
||||
# Save current version as backup
|
||||
current_metadata = self.get_file_metadata(filename)
|
||||
if current_metadata:
|
||||
self._create_version_backup(filename, current_metadata.to_dict())
|
||||
|
||||
# Restore file
|
||||
self.save_with_lifecycle(filename, version_data, {"restored_from": str(version)})
|
||||
return True
|
||||
|
||||
except Exception:
|
||||
logger.exception("Failed to restore %s to version %s", filename, version)
|
||||
return False
|
||||
|
||||
def archive_file(self, filename: str) -> bool:
|
||||
"""Archive file
|
||||
|
||||
Args:
|
||||
filename: File name
|
||||
|
||||
Returns:
|
||||
Whether archive succeeded
|
||||
"""
|
||||
# Permission check
|
||||
if not self._check_permission(filename, "archive"):
|
||||
logger.warning("Permission denied for archive operation on file: %s", filename)
|
||||
return False
|
||||
|
||||
try:
|
||||
# Update file status to archived
|
||||
metadata_dict = self._load_metadata()
|
||||
if filename not in metadata_dict:
|
||||
logger.warning("File %s not found in metadata", filename)
|
||||
return False
|
||||
|
||||
metadata_dict[filename]["status"] = FileStatus.ARCHIVED
|
||||
metadata_dict[filename]["modified_at"] = datetime.now().isoformat()
|
||||
|
||||
self._save_metadata(metadata_dict)
|
||||
|
||||
logger.info("File %s archived successfully", filename)
|
||||
return True
|
||||
|
||||
except Exception:
|
||||
logger.exception("Failed to archive file %s", filename)
|
||||
return False
|
||||
|
||||
def soft_delete_file(self, filename: str) -> bool:
|
||||
"""Soft delete file (move to deleted directory)
|
||||
|
||||
Args:
|
||||
filename: File name
|
||||
|
||||
Returns:
|
||||
Whether delete succeeded
|
||||
"""
|
||||
# Permission check
|
||||
if not self._check_permission(filename, "delete"):
|
||||
logger.warning("Permission denied for soft delete operation on file: %s", filename)
|
||||
return False
|
||||
|
||||
try:
|
||||
# Check if file exists
|
||||
if not self._storage.exists(filename):
|
||||
logger.warning("File %s not found", filename)
|
||||
return False
|
||||
|
||||
# Read file content
|
||||
file_data = self._storage.load_once(filename)
|
||||
|
||||
# Move to deleted directory
|
||||
deleted_filename = f"{self._deleted_prefix}{filename}.{datetime.now().strftime('%Y%m%d_%H%M%S')}"
|
||||
self._storage.save(deleted_filename, file_data)
|
||||
|
||||
# Delete original file
|
||||
self._storage.delete(filename)
|
||||
|
||||
# Update metadata
|
||||
metadata_dict = self._load_metadata()
|
||||
if filename in metadata_dict:
|
||||
metadata_dict[filename]["status"] = FileStatus.DELETED
|
||||
metadata_dict[filename]["modified_at"] = datetime.now().isoformat()
|
||||
self._save_metadata(metadata_dict)
|
||||
|
||||
logger.info("File %s soft deleted successfully", filename)
|
||||
return True
|
||||
|
||||
except Exception:
|
||||
logger.exception("Failed to soft delete file %s", filename)
|
||||
return False
|
||||
|
||||
def cleanup_old_versions(self, max_versions: int = 5, max_age_days: int = 30) -> int:
|
||||
"""Cleanup old version files
|
||||
|
||||
Args:
|
||||
max_versions: Maximum number of versions to keep
|
||||
max_age_days: Maximum retention days for version files
|
||||
|
||||
Returns:
|
||||
Number of files cleaned
|
||||
"""
|
||||
try:
|
||||
cleaned_count = 0
|
||||
|
||||
# Get all version files
|
||||
try:
|
||||
all_files = self._storage.scan(self._dataset_id or "", files=True)
|
||||
version_files = [f for f in all_files if f.startswith(self._version_prefix)]
|
||||
|
||||
# Group by file
|
||||
file_versions: dict[str, list[tuple[int, str]]] = {}
|
||||
for version_file in version_files:
|
||||
# Parse filename and version
|
||||
parts = version_file[len(self._version_prefix) :].split(".v")
|
||||
if len(parts) >= 2:
|
||||
base_filename = parts[0]
|
||||
version_part = parts[1].split(".")[0]
|
||||
try:
|
||||
version_num = int(version_part)
|
||||
if base_filename not in file_versions:
|
||||
file_versions[base_filename] = []
|
||||
file_versions[base_filename].append((version_num, version_file))
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
# Cleanup old versions for each file
|
||||
for _base_filename, versions in file_versions.items():
|
||||
# Sort by version number
|
||||
versions.sort(key=operator.itemgetter(0), reverse=True)
|
||||
|
||||
# Keep the newest max_versions versions, delete the rest
|
||||
if len(versions) > max_versions:
|
||||
to_delete = versions[max_versions:]
|
||||
for _version_num, version_file in to_delete:
|
||||
self._storage.delete(version_file)
|
||||
cleaned_count += 1
|
||||
logger.debug("Cleaned old version: %s", version_file)
|
||||
|
||||
logger.info("Cleaned %d old version files", cleaned_count)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning("Could not scan for version files: %s", e)
|
||||
|
||||
return cleaned_count
|
||||
|
||||
except Exception:
|
||||
logger.exception("Failed to cleanup old versions")
|
||||
return 0
|
||||
|
||||
def get_storage_statistics(self) -> StorageStatisticsDict:
|
||||
"""Get storage statistics
|
||||
|
||||
Returns:
|
||||
Storage statistics dictionary
|
||||
"""
|
||||
try:
|
||||
metadata_dict = self._load_metadata()
|
||||
|
||||
stats = StorageStatisticsDict(
|
||||
total_files=len(metadata_dict),
|
||||
active_files=0,
|
||||
archived_files=0,
|
||||
deleted_files=0,
|
||||
total_size=0,
|
||||
versions_count=0,
|
||||
oldest_file=None,
|
||||
newest_file=None,
|
||||
)
|
||||
|
||||
oldest_date = None
|
||||
newest_date = None
|
||||
|
||||
for filename, metadata in metadata_dict.items():
|
||||
file_meta = FileMetadata.from_dict(metadata)
|
||||
|
||||
# Count file status
|
||||
if file_meta.status == FileStatus.ACTIVE:
|
||||
stats["active_files"] = (stats["active_files"] or 0) + 1
|
||||
elif file_meta.status == FileStatus.ARCHIVED:
|
||||
stats["archived_files"] = (stats["archived_files"] or 0) + 1
|
||||
elif file_meta.status == FileStatus.DELETED:
|
||||
stats["deleted_files"] = (stats["deleted_files"] or 0) + 1
|
||||
|
||||
# Count size
|
||||
stats["total_size"] = (stats["total_size"] or 0) + (file_meta.size or 0)
|
||||
|
||||
# Count versions
|
||||
stats["versions_count"] = (stats["versions_count"] or 0) + (file_meta.version or 0)
|
||||
|
||||
# Find newest and oldest files
|
||||
if oldest_date is None or file_meta.created_at < oldest_date:
|
||||
oldest_date = file_meta.created_at
|
||||
stats["oldest_file"] = filename
|
||||
|
||||
if newest_date is None or file_meta.modified_at > newest_date:
|
||||
newest_date = file_meta.modified_at
|
||||
stats["newest_file"] = filename
|
||||
|
||||
return stats
|
||||
|
||||
except Exception:
|
||||
logger.exception("Failed to get storage statistics")
|
||||
return StorageStatisticsDict(
|
||||
total_files=0,
|
||||
active_files=0,
|
||||
archived_files=0,
|
||||
deleted_files=0,
|
||||
total_size=0,
|
||||
versions_count=0,
|
||||
oldest_file=None,
|
||||
newest_file=None,
|
||||
)
|
||||
|
||||
def _create_version_backup(self, filename: str, metadata: dict[str, Any]):
|
||||
"""Create version backup"""
|
||||
try:
|
||||
# Read current file content
|
||||
current_data = self._storage.load_once(filename)
|
||||
|
||||
# Save as version file
|
||||
version_filename = f"{self._version_prefix}{filename}.v{metadata['version']}"
|
||||
self._storage.save(version_filename, current_data)
|
||||
|
||||
logger.debug("Created version backup: %s", version_filename)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning("Failed to create version backup for %s: %s", filename, e)
|
||||
|
||||
def _load_metadata(self) -> dict[str, Any]:
|
||||
"""Load metadata file"""
|
||||
try:
|
||||
if self._storage.exists(self._metadata_file):
|
||||
metadata_content = self._storage.load_once(self._metadata_file)
|
||||
result = _metadata_adapter.validate_json(metadata_content)
|
||||
return result or {}
|
||||
else:
|
||||
return {}
|
||||
except Exception as e:
|
||||
logger.warning("Failed to load metadata: %s", e)
|
||||
return {}
|
||||
|
||||
def _save_metadata(self, metadata_dict: dict[str, Any]):
|
||||
"""Save metadata file"""
|
||||
try:
|
||||
metadata_content = json.dumps(metadata_dict, indent=2, ensure_ascii=False)
|
||||
self._storage.save(self._metadata_file, metadata_content.encode("utf-8"))
|
||||
logger.debug("Metadata saved successfully")
|
||||
except Exception:
|
||||
logger.exception("Failed to save metadata")
|
||||
raise
|
||||
|
||||
def _calculate_checksum(self, data: bytes) -> str:
|
||||
"""Calculate file checksum"""
|
||||
import hashlib
|
||||
|
||||
return hashlib.md5(data).hexdigest()
|
||||
|
||||
def _check_permission(self, filename: str, operation: str) -> bool:
|
||||
"""Check file operation permission
|
||||
|
||||
Args:
|
||||
filename: File name
|
||||
operation: Operation type
|
||||
|
||||
Returns:
|
||||
True if permission granted, False otherwise
|
||||
"""
|
||||
# If no permission manager, allow by default
|
||||
if not self._permission_manager:
|
||||
return True
|
||||
|
||||
try:
|
||||
# Map operation type to permission
|
||||
operation_mapping = {
|
||||
"save": "save",
|
||||
"load": "load_once",
|
||||
"delete": "delete",
|
||||
"archive": "delete", # Archive requires delete permission
|
||||
"restore": "save", # Restore requires write permission
|
||||
"cleanup": "delete", # Cleanup requires delete permission
|
||||
"read": "load_once",
|
||||
"write": "save",
|
||||
}
|
||||
|
||||
mapped_operation = operation_mapping.get(operation, operation)
|
||||
|
||||
# Check permission
|
||||
result = self._permission_manager.validate_operation(mapped_operation, self._dataset_id)
|
||||
return bool(result)
|
||||
|
||||
except Exception:
|
||||
logger.exception("Permission check failed for %s operation %s", filename, operation)
|
||||
# Safe default: deny access when permission check fails
|
||||
return False
|
||||
@@ -0,0 +1,646 @@
|
||||
"""ClickZetta Volume permission management mechanism
|
||||
|
||||
This module provides Volume permission checking, validation and management features.
|
||||
According to ClickZetta's permission model, different Volume types have different permission requirements.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from enum import StrEnum
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class VolumePermission(StrEnum):
|
||||
"""Volume permission type enumeration"""
|
||||
|
||||
READ = "SELECT" # Corresponds to ClickZetta's SELECT permission
|
||||
WRITE = "INSERT,UPDATE,DELETE" # Corresponds to ClickZetta's write permissions
|
||||
LIST = "SELECT" # Listing files requires SELECT permission
|
||||
DELETE = "INSERT,UPDATE,DELETE" # Deleting files requires write permissions
|
||||
USAGE = "USAGE" # Basic permission required for External Volume
|
||||
|
||||
|
||||
class VolumePermissionManager:
|
||||
"""Volume permission manager"""
|
||||
|
||||
def __init__(self, connection_or_config, volume_type: str | None = None, volume_name: str | None = None):
|
||||
"""Initialize permission manager
|
||||
|
||||
Args:
|
||||
connection_or_config: ClickZetta connection object or configuration dictionary
|
||||
volume_type: Volume type (user|table|external)
|
||||
volume_name: Volume name (for external volume)
|
||||
"""
|
||||
# Support two initialization methods: connection object or configuration dictionary
|
||||
if isinstance(connection_or_config, dict):
|
||||
# Create connection from configuration dictionary
|
||||
import clickzetta
|
||||
|
||||
config = connection_or_config
|
||||
self._connection = clickzetta.connect(
|
||||
username=config.get("username"),
|
||||
password=config.get("password"),
|
||||
instance=config.get("instance"),
|
||||
service=config.get("service"),
|
||||
workspace=config.get("workspace"),
|
||||
vcluster=config.get("vcluster"),
|
||||
schema=config.get("schema") or config.get("database"),
|
||||
)
|
||||
self._volume_type = config.get("volume_type", volume_type)
|
||||
self._volume_name = config.get("volume_name", volume_name)
|
||||
else:
|
||||
# Use connection object directly
|
||||
self._connection = connection_or_config
|
||||
self._volume_type = volume_type
|
||||
self._volume_name = volume_name
|
||||
|
||||
if not self._connection:
|
||||
raise ValueError("Valid connection or config is required")
|
||||
if not self._volume_type:
|
||||
raise ValueError("volume_type is required")
|
||||
|
||||
self._permission_cache: dict[str, set[str]] = {}
|
||||
self._current_username = None # Will get current username from connection
|
||||
|
||||
def check_permission(self, operation: VolumePermission, dataset_id: str | None = None) -> bool:
|
||||
"""Check if user has permission to perform specific operation
|
||||
|
||||
Args:
|
||||
operation: Type of operation to perform
|
||||
dataset_id: Dataset ID (for table volume)
|
||||
|
||||
Returns:
|
||||
True if user has permission, False otherwise
|
||||
"""
|
||||
try:
|
||||
if self._volume_type == "user":
|
||||
return self._check_user_volume_permission(operation)
|
||||
elif self._volume_type == "table":
|
||||
return self._check_table_volume_permission(operation, dataset_id)
|
||||
elif self._volume_type == "external":
|
||||
return self._check_external_volume_permission(operation)
|
||||
else:
|
||||
logger.warning("Unknown volume type: %s", self._volume_type)
|
||||
return False
|
||||
|
||||
except Exception:
|
||||
logger.exception("Permission check failed")
|
||||
return False
|
||||
|
||||
def _check_user_volume_permission(self, operation: VolumePermission) -> bool:
|
||||
"""Check User Volume permission
|
||||
|
||||
User Volume permission rules:
|
||||
- User has full permissions on their own User Volume
|
||||
- As long as user can connect to ClickZetta, they have basic User Volume permissions by default
|
||||
- Focus more on connection authentication rather than complex permission checking
|
||||
"""
|
||||
try:
|
||||
# Get current username
|
||||
current_user = self._get_current_username()
|
||||
|
||||
# Check basic connection status
|
||||
with self._connection.cursor() as cursor:
|
||||
# Simple connection test, if query can be executed user has basic permissions
|
||||
cursor.execute("SELECT 1")
|
||||
result = cursor.fetchone()
|
||||
|
||||
if result:
|
||||
logger.debug(
|
||||
"User Volume permission check for %s, operation %s: granted (basic connection verified)",
|
||||
current_user,
|
||||
operation.name,
|
||||
)
|
||||
return True
|
||||
else:
|
||||
logger.warning(
|
||||
"User Volume permission check failed: cannot verify basic connection for %s", current_user
|
||||
)
|
||||
return False
|
||||
|
||||
except Exception:
|
||||
logger.exception("User Volume permission check failed")
|
||||
# For User Volume, if permission check fails, it might be a configuration issue,
|
||||
# provide friendlier error message
|
||||
logger.info("User Volume permission check failed, but permission checking is disabled in this version")
|
||||
return False
|
||||
|
||||
def _check_table_volume_permission(self, operation: VolumePermission, dataset_id: str | None) -> bool:
|
||||
"""Check Table Volume permission
|
||||
|
||||
Table Volume permission rules:
|
||||
- Table Volume permissions inherit from corresponding table permissions
|
||||
- SELECT permission -> can READ/LIST files
|
||||
- INSERT,UPDATE,DELETE permissions -> can WRITE/DELETE files
|
||||
"""
|
||||
if not dataset_id:
|
||||
logger.warning("dataset_id is required for table volume permission check")
|
||||
return False
|
||||
|
||||
table_name = f"dataset_{dataset_id}" if not dataset_id.startswith("dataset_") else dataset_id
|
||||
|
||||
try:
|
||||
# Check table permissions
|
||||
permissions = self._get_table_permissions(table_name)
|
||||
required_permissions = set(operation.value.split(","))
|
||||
|
||||
# Check if has all required permissions
|
||||
has_permission = required_permissions.issubset(permissions)
|
||||
|
||||
logger.debug(
|
||||
"Table Volume permission check for %s, operation %s: required=%s, has=%s, granted=%s",
|
||||
table_name,
|
||||
operation.name,
|
||||
required_permissions,
|
||||
permissions,
|
||||
has_permission,
|
||||
)
|
||||
|
||||
return has_permission
|
||||
|
||||
except Exception:
|
||||
logger.exception("Table volume permission check failed for %s", table_name)
|
||||
return False
|
||||
|
||||
def _check_external_volume_permission(self, operation: VolumePermission) -> bool:
|
||||
"""Check External Volume permission
|
||||
|
||||
External Volume permission rules:
|
||||
- Try to get permissions for External Volume
|
||||
- If permission check fails, perform fallback verification
|
||||
- For development environment, provide more lenient permission checking
|
||||
"""
|
||||
if not self._volume_name:
|
||||
logger.warning("volume_name is required for external volume permission check")
|
||||
return False
|
||||
|
||||
try:
|
||||
# Check External Volume permissions
|
||||
permissions = self._get_external_volume_permissions(self._volume_name)
|
||||
|
||||
# External Volume permission mapping: determine required permissions based on operation type
|
||||
required_permissions = set()
|
||||
|
||||
if operation in [VolumePermission.READ, VolumePermission.LIST]:
|
||||
required_permissions.add("read")
|
||||
elif operation in [VolumePermission.WRITE, VolumePermission.DELETE]:
|
||||
required_permissions.add("write")
|
||||
|
||||
# Check if has all required permissions
|
||||
has_permission = required_permissions.issubset(permissions)
|
||||
|
||||
logger.debug(
|
||||
"External Volume permission check for %s, operation %s: required=%s, has=%s, granted=%s",
|
||||
self._volume_name,
|
||||
operation.name,
|
||||
required_permissions,
|
||||
permissions,
|
||||
has_permission,
|
||||
)
|
||||
|
||||
# If permission check fails, try fallback verification
|
||||
if not has_permission:
|
||||
logger.info("Direct permission check failed for %s, trying fallback verification", self._volume_name)
|
||||
|
||||
# Fallback verification: try listing Volume to verify basic access permissions
|
||||
try:
|
||||
with self._connection.cursor() as cursor:
|
||||
cursor.execute("SHOW VOLUMES")
|
||||
volumes = cursor.fetchall()
|
||||
for volume in volumes:
|
||||
if len(volume) > 0 and volume[0] == self._volume_name:
|
||||
logger.info("Fallback verification successful for %s", self._volume_name)
|
||||
return True
|
||||
except Exception as fallback_e:
|
||||
logger.warning("Fallback verification failed for %s: %s", self._volume_name, fallback_e)
|
||||
|
||||
return has_permission
|
||||
|
||||
except Exception:
|
||||
logger.exception("External volume permission check failed for %s", self._volume_name)
|
||||
logger.info("External Volume permission check failed, but permission checking is disabled in this version")
|
||||
return False
|
||||
|
||||
def _get_table_permissions(self, table_name: str) -> set[str]:
|
||||
"""Get user permissions for specified table
|
||||
|
||||
Args:
|
||||
table_name: Table name
|
||||
|
||||
Returns:
|
||||
Set of user permissions for this table
|
||||
"""
|
||||
cache_key = f"table:{table_name}"
|
||||
|
||||
if cache_key in self._permission_cache:
|
||||
return self._permission_cache[cache_key]
|
||||
|
||||
permissions = set()
|
||||
|
||||
try:
|
||||
with self._connection.cursor() as cursor:
|
||||
# Use correct ClickZetta syntax to check current user permissions
|
||||
cursor.execute("SHOW GRANTS")
|
||||
grants = cursor.fetchall()
|
||||
|
||||
# Parse permission results, find permissions for this table
|
||||
for grant in grants:
|
||||
if len(grant) >= 3: # Typical format: (privilege, object_type, object_name, ...)
|
||||
privilege = grant[0].upper()
|
||||
object_type = grant[1].upper() if len(grant) > 1 else ""
|
||||
object_name = grant[2] if len(grant) > 2 else ""
|
||||
|
||||
# Check if it's permission for this table
|
||||
if (
|
||||
object_type == "TABLE"
|
||||
and object_name == table_name
|
||||
or object_type == "SCHEMA"
|
||||
and object_name in table_name
|
||||
):
|
||||
if privilege in ["SELECT", "INSERT", "UPDATE", "DELETE", "ALL"]:
|
||||
if privilege == "ALL":
|
||||
permissions.update(["SELECT", "INSERT", "UPDATE", "DELETE"])
|
||||
else:
|
||||
permissions.add(privilege)
|
||||
|
||||
# If no explicit permissions found, try executing a simple query to verify permissions
|
||||
if not permissions:
|
||||
try:
|
||||
cursor.execute(f"SELECT COUNT(*) FROM {table_name} LIMIT 1")
|
||||
permissions.add("SELECT")
|
||||
except Exception:
|
||||
logger.debug("Cannot query table %s, no SELECT permission", table_name)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning("Could not check table permissions for %s: %s", table_name, e)
|
||||
# Safe default: deny access when permission check fails
|
||||
pass
|
||||
|
||||
# Cache permission information
|
||||
self._permission_cache[cache_key] = permissions
|
||||
return permissions
|
||||
|
||||
def _get_current_username(self) -> str:
|
||||
"""Get current username"""
|
||||
if self._current_username:
|
||||
return self._current_username
|
||||
|
||||
try:
|
||||
with self._connection.cursor() as cursor:
|
||||
cursor.execute("SELECT CURRENT_USER()")
|
||||
result = cursor.fetchone()
|
||||
if result:
|
||||
self._current_username = result[0]
|
||||
return str(self._current_username)
|
||||
except Exception:
|
||||
logger.exception("Failed to get current username")
|
||||
|
||||
return "unknown"
|
||||
|
||||
def _get_user_permissions(self, username: str) -> set[str]:
|
||||
"""Get user's basic permission set"""
|
||||
cache_key = f"user_permissions:{username}"
|
||||
|
||||
if cache_key in self._permission_cache:
|
||||
return self._permission_cache[cache_key]
|
||||
|
||||
permissions = set()
|
||||
|
||||
try:
|
||||
with self._connection.cursor() as cursor:
|
||||
# Use correct ClickZetta syntax to check current user permissions
|
||||
cursor.execute("SHOW GRANTS")
|
||||
grants = cursor.fetchall()
|
||||
|
||||
# Parse permission results, find user's basic permissions
|
||||
for grant in grants:
|
||||
if len(grant) >= 3: # Typical format: (privilege, object_type, object_name, ...)
|
||||
privilege = grant[0].upper()
|
||||
_ = grant[1].upper() if len(grant) > 1 else ""
|
||||
|
||||
# Collect all relevant permissions
|
||||
if privilege in ["SELECT", "INSERT", "UPDATE", "DELETE", "ALL"]:
|
||||
if privilege == "ALL":
|
||||
permissions.update(["SELECT", "INSERT", "UPDATE", "DELETE"])
|
||||
else:
|
||||
permissions.add(privilege)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning("Could not check user permissions for %s: %s", username, e)
|
||||
# Safe default: deny access when permission check fails
|
||||
pass
|
||||
|
||||
# Cache permission information
|
||||
self._permission_cache[cache_key] = permissions
|
||||
return permissions
|
||||
|
||||
def _get_external_volume_permissions(self, volume_name: str) -> set[str]:
|
||||
"""Get user permissions for specified External Volume
|
||||
|
||||
Args:
|
||||
volume_name: External Volume name
|
||||
|
||||
Returns:
|
||||
Set of user permissions for this Volume
|
||||
"""
|
||||
cache_key = f"external_volume:{volume_name}"
|
||||
|
||||
if cache_key in self._permission_cache:
|
||||
return self._permission_cache[cache_key]
|
||||
|
||||
permissions = set()
|
||||
|
||||
try:
|
||||
with self._connection.cursor() as cursor:
|
||||
# Use correct ClickZetta syntax to check Volume permissions
|
||||
logger.info("Checking permissions for volume: %s", volume_name)
|
||||
cursor.execute(f"SHOW GRANTS ON VOLUME {volume_name}")
|
||||
grants = cursor.fetchall()
|
||||
|
||||
logger.info("Raw grants result for %s: %s", volume_name, grants)
|
||||
|
||||
# Parse permission results
|
||||
# Format: (granted_type, privilege, conditions, granted_on, object_name, granted_to,
|
||||
# grantee_name, grantor_name, grant_option, granted_time)
|
||||
for grant in grants:
|
||||
logger.info("Processing grant: %s", grant)
|
||||
if len(grant) >= 5:
|
||||
granted_type = grant[0]
|
||||
privilege = grant[1].upper()
|
||||
granted_on = grant[3]
|
||||
object_name = grant[4]
|
||||
|
||||
logger.info(
|
||||
"Grant details - type: %s, privilege: %s, granted_on: %s, object_name: %s",
|
||||
granted_type,
|
||||
privilege,
|
||||
granted_on,
|
||||
object_name,
|
||||
)
|
||||
|
||||
# Check if it's permission for this Volume or hierarchical permission
|
||||
if (
|
||||
granted_type == "PRIVILEGE" and granted_on == "VOLUME" and object_name.endswith(volume_name)
|
||||
) or (granted_type == "OBJECT_HIERARCHY" and granted_on == "VOLUME"):
|
||||
logger.info("Matching grant found for %s", volume_name)
|
||||
|
||||
if "READ" in privilege:
|
||||
permissions.add("read")
|
||||
logger.info("Added READ permission for %s", volume_name)
|
||||
if "WRITE" in privilege:
|
||||
permissions.add("write")
|
||||
logger.info("Added WRITE permission for %s", volume_name)
|
||||
if "ALTER" in privilege:
|
||||
permissions.add("alter")
|
||||
logger.info("Added ALTER permission for %s", volume_name)
|
||||
if privilege == "ALL":
|
||||
permissions.update(["read", "write", "alter"])
|
||||
logger.info("Added ALL permissions for %s", volume_name)
|
||||
|
||||
logger.info("Final permissions for %s: %s", volume_name, permissions)
|
||||
|
||||
# If no explicit permissions found, try viewing Volume list to verify basic permissions
|
||||
if not permissions:
|
||||
try:
|
||||
cursor.execute("SHOW VOLUMES")
|
||||
volumes = cursor.fetchall()
|
||||
for volume in volumes:
|
||||
if len(volume) > 0 and volume[0] == volume_name:
|
||||
permissions.add("read") # At least has read permission
|
||||
logger.debug("Volume %s found in SHOW VOLUMES, assuming read permission", volume_name)
|
||||
break
|
||||
except Exception:
|
||||
logger.debug("Cannot access volume %s, no basic permission", volume_name)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning("Could not check external volume permissions for %s: %s", volume_name, e)
|
||||
# When permission check fails, try basic Volume access verification
|
||||
try:
|
||||
with self._connection.cursor() as cursor:
|
||||
cursor.execute("SHOW VOLUMES")
|
||||
volumes = cursor.fetchall()
|
||||
for volume in volumes:
|
||||
if len(volume) > 0 and volume[0] == volume_name:
|
||||
logger.info("Basic volume access verified for %s", volume_name)
|
||||
permissions.add("read")
|
||||
permissions.add("write") # Assume has write permission
|
||||
break
|
||||
except Exception as basic_e:
|
||||
logger.warning("Basic volume access check failed for %s: %s", volume_name, basic_e)
|
||||
# Last fallback: assume basic permissions
|
||||
permissions.add("read")
|
||||
|
||||
# Cache permission information
|
||||
self._permission_cache[cache_key] = permissions
|
||||
return permissions
|
||||
|
||||
def clear_permission_cache(self):
|
||||
"""Clear permission cache"""
|
||||
self._permission_cache.clear()
|
||||
logger.debug("Permission cache cleared")
|
||||
|
||||
@property
|
||||
def volume_type(self) -> str | None:
|
||||
"""Get the volume type."""
|
||||
return self._volume_type
|
||||
|
||||
def get_permission_summary(self, dataset_id: str | None = None) -> dict[str, bool]:
|
||||
"""Get permission summary
|
||||
|
||||
Args:
|
||||
dataset_id: Dataset ID (for table volume)
|
||||
|
||||
Returns:
|
||||
Permission summary dictionary
|
||||
"""
|
||||
summary = {}
|
||||
|
||||
for operation in VolumePermission:
|
||||
summary[operation.name.lower()] = self.check_permission(operation, dataset_id)
|
||||
|
||||
return summary
|
||||
|
||||
def check_inherited_permission(self, file_path: str, operation: VolumePermission) -> bool:
|
||||
"""Check permission inheritance for file path
|
||||
|
||||
Args:
|
||||
file_path: File path
|
||||
operation: Operation to perform
|
||||
|
||||
Returns:
|
||||
True if user has permission, False otherwise
|
||||
"""
|
||||
try:
|
||||
# Parse file path
|
||||
path_parts = file_path.strip("/").split("/")
|
||||
|
||||
if not path_parts:
|
||||
logger.warning("Invalid file path for permission inheritance check")
|
||||
return False
|
||||
|
||||
# For Table Volume, first layer is dataset_id
|
||||
if self._volume_type == "table":
|
||||
if len(path_parts) < 1:
|
||||
return False
|
||||
|
||||
dataset_id = path_parts[0]
|
||||
|
||||
# Check permissions for dataset
|
||||
has_dataset_permission = self.check_permission(operation, dataset_id)
|
||||
|
||||
if not has_dataset_permission:
|
||||
logger.debug("Permission denied for dataset %s", dataset_id)
|
||||
return False
|
||||
|
||||
# Check path traversal attack
|
||||
if self._contains_path_traversal(file_path):
|
||||
logger.warning("Path traversal attack detected: %s", file_path)
|
||||
return False
|
||||
|
||||
# Check if accessing sensitive directory
|
||||
if self._is_sensitive_path(file_path):
|
||||
logger.warning("Access to sensitive path denied: %s", file_path)
|
||||
return False
|
||||
|
||||
logger.debug("Permission inherited for path %s", file_path)
|
||||
return True
|
||||
|
||||
elif self._volume_type == "user":
|
||||
# User Volume permission inheritance
|
||||
current_user = self._get_current_username()
|
||||
|
||||
# Check if attempting to access other user's directory
|
||||
if len(path_parts) > 1 and path_parts[0] != current_user:
|
||||
logger.warning("User %s attempted to access %s's directory", current_user, path_parts[0])
|
||||
return False
|
||||
|
||||
# Check basic permissions
|
||||
return self.check_permission(operation)
|
||||
|
||||
elif self._volume_type == "external":
|
||||
# External Volume permission inheritance
|
||||
# Check permissions for External Volume
|
||||
return self.check_permission(operation)
|
||||
|
||||
else:
|
||||
logger.warning("Unknown volume type for permission inheritance: %s", self._volume_type)
|
||||
return False
|
||||
|
||||
except Exception:
|
||||
logger.exception("Permission inheritance check failed")
|
||||
return False
|
||||
|
||||
def _contains_path_traversal(self, file_path: str) -> bool:
|
||||
"""Check if path contains path traversal attack"""
|
||||
# Check common path traversal patterns
|
||||
traversal_patterns = [
|
||||
"../",
|
||||
"..\\",
|
||||
"..%2f",
|
||||
"..%2F",
|
||||
"..%5c",
|
||||
"..%5C",
|
||||
"%2e%2e%2f",
|
||||
"%2e%2e%5c",
|
||||
"....//",
|
||||
"....\\\\",
|
||||
]
|
||||
|
||||
file_path_lower = file_path.lower()
|
||||
|
||||
for pattern in traversal_patterns:
|
||||
if pattern in file_path_lower:
|
||||
return True
|
||||
|
||||
# Check absolute path
|
||||
if file_path.startswith("/") or file_path.startswith("\\"):
|
||||
return True
|
||||
|
||||
# Check Windows drive path
|
||||
return bool(len(file_path) >= 2 and file_path[1] == ":")
|
||||
|
||||
def _is_sensitive_path(self, file_path: str) -> bool:
|
||||
"""Check if path is sensitive path"""
|
||||
sensitive_patterns = [
|
||||
"passwd",
|
||||
"shadow",
|
||||
"hosts",
|
||||
"config",
|
||||
"secrets",
|
||||
"private",
|
||||
"key",
|
||||
"certificate",
|
||||
"cert",
|
||||
"ssl",
|
||||
"database",
|
||||
"backup",
|
||||
"dump",
|
||||
"log",
|
||||
"tmp",
|
||||
]
|
||||
|
||||
file_path_lower = file_path.lower()
|
||||
|
||||
return any(pattern in file_path_lower for pattern in sensitive_patterns)
|
||||
|
||||
def validate_operation(self, operation: str, dataset_id: str | None = None) -> bool:
|
||||
"""Validate operation permission
|
||||
|
||||
Args:
|
||||
operation: Operation name (save|load|exists|delete|scan)
|
||||
dataset_id: Dataset ID
|
||||
|
||||
Returns:
|
||||
True if operation is allowed, False otherwise
|
||||
"""
|
||||
operation_mapping = {
|
||||
"save": VolumePermission.WRITE,
|
||||
"load": VolumePermission.READ,
|
||||
"load_once": VolumePermission.READ,
|
||||
"load_stream": VolumePermission.READ,
|
||||
"download": VolumePermission.READ,
|
||||
"exists": VolumePermission.READ,
|
||||
"delete": VolumePermission.DELETE,
|
||||
"scan": VolumePermission.LIST,
|
||||
}
|
||||
|
||||
if operation not in operation_mapping:
|
||||
logger.warning("Unknown operation: %s", operation)
|
||||
return False
|
||||
|
||||
volume_permission = operation_mapping[operation]
|
||||
return self.check_permission(volume_permission, dataset_id)
|
||||
|
||||
|
||||
class VolumePermissionError(Exception):
|
||||
"""Volume permission error exception"""
|
||||
|
||||
def __init__(self, message: str, operation: str, volume_type: str, dataset_id: str | None = None):
|
||||
self.operation = operation
|
||||
self.volume_type = volume_type
|
||||
self.dataset_id = dataset_id
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
def check_volume_permission(permission_manager: VolumePermissionManager, operation: str, dataset_id: str | None = None):
|
||||
"""Permission check decorator function
|
||||
|
||||
Args:
|
||||
permission_manager: Permission manager
|
||||
operation: Operation name
|
||||
dataset_id: Dataset ID
|
||||
|
||||
Raises:
|
||||
VolumePermissionError: If no permission
|
||||
"""
|
||||
if not permission_manager.validate_operation(operation, dataset_id):
|
||||
error_message = f"Permission denied for operation '{operation}' on {permission_manager.volume_type} volume"
|
||||
if dataset_id:
|
||||
error_message += f" (dataset: {dataset_id})"
|
||||
|
||||
raise VolumePermissionError(
|
||||
error_message,
|
||||
operation=operation,
|
||||
volume_type=permission_manager.volume_type or "unknown",
|
||||
dataset_id=dataset_id,
|
||||
)
|
||||
@@ -0,0 +1,80 @@
|
||||
import base64
|
||||
import io
|
||||
from collections.abc import Generator
|
||||
from typing import Any, override
|
||||
|
||||
from google.cloud import storage as google_cloud_storage # type: ignore
|
||||
from pydantic import TypeAdapter
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.storage.base_storage import BaseStorage
|
||||
|
||||
_service_account_adapter: TypeAdapter[dict[str, Any]] = TypeAdapter(dict[str, Any])
|
||||
|
||||
|
||||
class GoogleCloudStorage(BaseStorage):
|
||||
"""Implementation for Google Cloud storage."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self.bucket_name = dify_config.GOOGLE_STORAGE_BUCKET_NAME
|
||||
service_account_json_str = dify_config.GOOGLE_STORAGE_SERVICE_ACCOUNT_JSON_BASE64
|
||||
# if service_account_json_str is empty, use Application Default Credentials
|
||||
if service_account_json_str:
|
||||
service_account_json = base64.b64decode(service_account_json_str).decode("utf-8")
|
||||
# convert str to object
|
||||
service_account_obj = _service_account_adapter.validate_json(service_account_json)
|
||||
self.client = google_cloud_storage.Client.from_service_account_info(service_account_obj)
|
||||
else:
|
||||
self.client = google_cloud_storage.Client()
|
||||
|
||||
@override
|
||||
def save(self, filename, data):
|
||||
bucket = self.client.get_bucket(self.bucket_name)
|
||||
blob = bucket.blob(filename)
|
||||
with io.BytesIO(data) as stream:
|
||||
blob.upload_from_file(stream)
|
||||
|
||||
@override
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
bucket = self.client.get_bucket(self.bucket_name)
|
||||
blob = bucket.get_blob(filename)
|
||||
if blob is None:
|
||||
raise FileNotFoundError("File not found")
|
||||
data: bytes = blob.download_as_bytes()
|
||||
return data
|
||||
|
||||
@override
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
bucket = self.client.get_bucket(self.bucket_name)
|
||||
blob = bucket.get_blob(filename)
|
||||
if blob is None:
|
||||
raise FileNotFoundError("File not found")
|
||||
with blob.open(mode="rb") as blob_stream:
|
||||
while chunk := blob_stream.read(4096):
|
||||
yield chunk
|
||||
|
||||
@override
|
||||
def download(self, filename, target_filepath):
|
||||
bucket = self.client.get_bucket(self.bucket_name)
|
||||
blob = bucket.get_blob(filename)
|
||||
if blob is None:
|
||||
raise FileNotFoundError("File not found")
|
||||
blob.download_to_filename(target_filepath)
|
||||
|
||||
@override
|
||||
def exists(self, filename):
|
||||
bucket = self.client.get_bucket(self.bucket_name)
|
||||
blob = bucket.blob(filename)
|
||||
return blob.exists()
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
bucket = self.client.get_bucket(self.bucket_name)
|
||||
bucket.delete_blob(filename)
|
||||
|
||||
@override
|
||||
def scan(self, path: str, files: bool = True, directories: bool = False) -> list[str]:
|
||||
keys = (blob.name for blob in self.client.list_blobs(self.bucket_name, prefix=path))
|
||||
return self._filter_scan_keys(keys, files, directories)
|
||||
@@ -0,0 +1,83 @@
|
||||
from collections.abc import Generator
|
||||
from typing import Any, override
|
||||
|
||||
from obs import ObsClient
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.storage.base_storage import BaseStorage
|
||||
|
||||
|
||||
class HuaweiObsStorage(BaseStorage):
|
||||
"""Implementation for Huawei OBS storage."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self.bucket_name = dify_config.HUAWEI_OBS_BUCKET_NAME
|
||||
self.client = ObsClient(
|
||||
access_key_id=dify_config.HUAWEI_OBS_ACCESS_KEY,
|
||||
secret_access_key=dify_config.HUAWEI_OBS_SECRET_KEY,
|
||||
server=dify_config.HUAWEI_OBS_SERVER,
|
||||
path_style=dify_config.HUAWEI_OBS_PATH_STYLE,
|
||||
)
|
||||
|
||||
@override
|
||||
def save(self, filename, data):
|
||||
self.client.putObject(bucketName=self.bucket_name, objectKey=filename, content=data)
|
||||
|
||||
@override
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
# TODO: Huawei SDK lacks proper typing
|
||||
data: bytes = self.client.getObject(bucketName=self.bucket_name, objectKey=filename).body.response.read() # type: ignore
|
||||
return data
|
||||
|
||||
@override
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
# TODO: Huawei SDK lacks proper typing
|
||||
response = self.client.getObject(bucketName=self.bucket_name, objectKey=filename).body.response # type: ignore
|
||||
while chunk := response.read(4096):
|
||||
yield chunk
|
||||
|
||||
@override
|
||||
def download(self, filename, target_filepath):
|
||||
self.client.getObject(bucketName=self.bucket_name, objectKey=filename, downloadPath=target_filepath)
|
||||
|
||||
@override
|
||||
def exists(self, filename):
|
||||
res = self._get_meta(filename)
|
||||
return res is not None
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
response: Any = self.client.deleteObject(bucketName=self.bucket_name, objectKey=filename)
|
||||
if response.status == 404 and response.errorCode == "NoSuchKey":
|
||||
raise FileNotFoundError(filename)
|
||||
if response.status >= 300:
|
||||
raise RuntimeError(f"OBS object deletion failed: status={response.status}, code={response.errorCode}")
|
||||
|
||||
@override
|
||||
def scan(self, path: str, files: bool = True, directories: bool = False) -> list[str]:
|
||||
keys: list[str] = []
|
||||
marker = ""
|
||||
while True:
|
||||
# The SDK's decorator annotations do not describe its response model.
|
||||
response: Any = self.client.listObjects(
|
||||
bucketName=self.bucket_name, prefix=path, marker=marker, max_keys=1000
|
||||
)
|
||||
if response.status >= 300:
|
||||
raise RuntimeError(f"OBS object listing failed: status={response.status}, code={response.errorCode}")
|
||||
page = response.body
|
||||
keys.extend(obj.key for obj in page.contents or [])
|
||||
if not page.is_truncated:
|
||||
break
|
||||
if not page.next_marker or page.next_marker == marker:
|
||||
raise RuntimeError("OBS object listing did not advance its pagination marker")
|
||||
marker = page.next_marker
|
||||
return self._filter_scan_keys(keys, files, directories)
|
||||
|
||||
def _get_meta(self, filename):
|
||||
res = self.client.getObjectMetadata(bucketName=self.bucket_name, objectKey=filename)
|
||||
if res and res.status and res.status < 300:
|
||||
return res
|
||||
else:
|
||||
return None
|
||||
@@ -0,0 +1,110 @@
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
from typing import Any, override
|
||||
|
||||
import opendal
|
||||
from dotenv import dotenv_values
|
||||
from opendal import Operator
|
||||
|
||||
from extensions.storage.base_storage import BaseStorage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _get_opendal_kwargs(*, scheme: str, env_file_path: str = ".env", prefix: str = "OPENDAL_"):
|
||||
kwargs = {}
|
||||
config_prefix = prefix + scheme.upper() + "_"
|
||||
for key, value in os.environ.items():
|
||||
if key.startswith(config_prefix):
|
||||
kwargs[key[len(config_prefix) :].lower()] = value
|
||||
|
||||
file_env_vars: dict[str, Any] = dotenv_values(env_file_path) or {}
|
||||
for key, value in file_env_vars.items():
|
||||
if key.startswith(config_prefix) and key[len(config_prefix) :].lower() not in kwargs and value:
|
||||
kwargs[key[len(config_prefix) :].lower()] = value
|
||||
|
||||
return kwargs
|
||||
|
||||
|
||||
class OpenDALStorage(BaseStorage):
|
||||
def __init__(self, scheme: str, **kwargs):
|
||||
kwargs = kwargs or _get_opendal_kwargs(scheme=scheme)
|
||||
|
||||
if scheme == "fs":
|
||||
root = kwargs.setdefault("root", "storage")
|
||||
Path(root).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
retry_layer = opendal.layers.RetryLayer(max_times=3, factor=2.0, jitter=True)
|
||||
self.op = Operator(scheme=scheme, **kwargs).layer(retry_layer)
|
||||
logger.debug("opendal operator created with scheme %s", scheme)
|
||||
logger.debug("added retry layer to opendal operator")
|
||||
|
||||
@override
|
||||
def save(self, filename: str, data: bytes):
|
||||
self.op.write(path=filename, bs=data)
|
||||
logger.debug("file %s saved", filename)
|
||||
|
||||
@override
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
if not self.exists(filename):
|
||||
raise FileNotFoundError("File not found")
|
||||
|
||||
content: bytes = self.op.read(path=filename)
|
||||
logger.debug("file %s loaded", filename)
|
||||
return content
|
||||
|
||||
@override
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
if not self.exists(filename):
|
||||
raise FileNotFoundError("File not found")
|
||||
|
||||
batch_size = 4096
|
||||
with self.op.open(
|
||||
path=filename,
|
||||
mode="rb",
|
||||
chunck=batch_size,
|
||||
) as file:
|
||||
while chunk := file.read(batch_size):
|
||||
yield chunk
|
||||
logger.debug("file %s loaded as stream", filename)
|
||||
|
||||
@override
|
||||
def download(self, filename: str, target_filepath: str):
|
||||
if not self.exists(filename):
|
||||
raise FileNotFoundError("File not found")
|
||||
|
||||
Path(target_filepath).write_bytes(self.op.read(path=filename))
|
||||
logger.debug("file %s downloaded to %s", filename, target_filepath)
|
||||
|
||||
@override
|
||||
def exists(self, filename: str) -> bool:
|
||||
return self.op.exists(path=filename)
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
if self.exists(filename):
|
||||
self.op.delete(path=filename)
|
||||
logger.debug("file %s deleted", filename)
|
||||
return
|
||||
logger.debug("file %s not found, skip delete", filename)
|
||||
|
||||
@override
|
||||
def scan(self, path: str, files: bool = True, directories: bool = False) -> list[str]:
|
||||
if not self.exists(path):
|
||||
raise FileNotFoundError("Path not found")
|
||||
|
||||
# Use the new OpenDAL 0.46.0+ API with recursive listing
|
||||
lister = self.op.list(path, recursive=True)
|
||||
if files and directories:
|
||||
logger.debug("files and directories on %s scanned", path)
|
||||
return [entry.path for entry in lister]
|
||||
if files:
|
||||
logger.debug("files on %s scanned", path)
|
||||
return [entry.path for entry in lister if not entry.metadata.is_dir]
|
||||
elif directories:
|
||||
logger.debug("directories on %s scanned", path)
|
||||
return [entry.path for entry in lister if entry.metadata.is_dir]
|
||||
else:
|
||||
raise ValueError("At least one of files or directories must be True")
|
||||
@@ -0,0 +1,72 @@
|
||||
from collections.abc import Generator
|
||||
from typing import override
|
||||
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.storage.base_storage import BaseStorage
|
||||
|
||||
|
||||
class OracleOCIStorage(BaseStorage):
|
||||
"""Implementation for Oracle OCI storage."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self.bucket_name = dify_config.OCI_BUCKET_NAME
|
||||
self.client = boto3.client(
|
||||
"s3",
|
||||
aws_secret_access_key=dify_config.OCI_SECRET_KEY,
|
||||
aws_access_key_id=dify_config.OCI_ACCESS_KEY,
|
||||
endpoint_url=dify_config.OCI_ENDPOINT,
|
||||
region_name=dify_config.OCI_REGION,
|
||||
)
|
||||
|
||||
@override
|
||||
def save(self, filename, data):
|
||||
self.client.put_object(Bucket=self.bucket_name, Key=filename, Body=data)
|
||||
|
||||
@override
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
try:
|
||||
data: bytes = self.client.get_object(Bucket=self.bucket_name, Key=filename)["Body"].read()
|
||||
except ClientError as ex:
|
||||
if ex.response.get("Error", {}).get("Code") == "NoSuchKey":
|
||||
raise FileNotFoundError("File not found") from ex
|
||||
else:
|
||||
raise
|
||||
return data
|
||||
|
||||
@override
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
try:
|
||||
response = self.client.get_object(Bucket=self.bucket_name, Key=filename)
|
||||
yield from response["Body"].iter_chunks()
|
||||
except ClientError as ex:
|
||||
if ex.response.get("Error", {}).get("Code") == "NoSuchKey":
|
||||
raise FileNotFoundError("File not found") from ex
|
||||
else:
|
||||
raise
|
||||
|
||||
@override
|
||||
def download(self, filename, target_filepath):
|
||||
self.client.download_file(self.bucket_name, filename, target_filepath)
|
||||
|
||||
@override
|
||||
def exists(self, filename):
|
||||
try:
|
||||
self.client.head_object(Bucket=self.bucket_name, Key=filename)
|
||||
return True
|
||||
except ClientError:
|
||||
return False
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
self.client.delete_object(Bucket=self.bucket_name, Key=filename)
|
||||
|
||||
@override
|
||||
def scan(self, path: str, files: bool = True, directories: bool = False) -> list[str]:
|
||||
pages = self.client.get_paginator("list_objects_v2").paginate(Bucket=self.bucket_name, Prefix=path)
|
||||
keys = (obj["Key"] for page in pages for obj in page.get("Contents", []))
|
||||
return self._filter_scan_keys(keys, files, directories)
|
||||
@@ -0,0 +1,17 @@
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class StorageType(StrEnum):
|
||||
ALIYUN_OSS = "aliyun-oss"
|
||||
AZURE_BLOB = "azure-blob"
|
||||
BAIDU_OBS = "baidu-obs"
|
||||
CLICKZETTA_VOLUME = "clickzetta-volume"
|
||||
GOOGLE_STORAGE = "google-storage"
|
||||
HUAWEI_OBS = "huawei-obs"
|
||||
LOCAL = "local"
|
||||
OCI_STORAGE = "oci-storage"
|
||||
OPENDAL = "opendal"
|
||||
S3 = "s3"
|
||||
TENCENT_COS = "tencent-cos"
|
||||
VOLCENGINE_TOS = "volcengine-tos"
|
||||
SUPABASE = "supabase"
|
||||
@@ -0,0 +1,99 @@
|
||||
import io
|
||||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
from typing import override
|
||||
|
||||
from supabase import Client
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.storage.base_storage import BaseStorage
|
||||
|
||||
|
||||
class SupabaseStorage(BaseStorage):
|
||||
"""Implementation for supabase obs storage."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
if dify_config.SUPABASE_URL is None:
|
||||
raise ValueError("SUPABASE_URL is not set")
|
||||
if dify_config.SUPABASE_API_KEY is None:
|
||||
raise ValueError("SUPABASE_API_KEY is not set")
|
||||
if dify_config.SUPABASE_BUCKET_NAME is None:
|
||||
raise ValueError("SUPABASE_BUCKET_NAME is not set")
|
||||
|
||||
self.bucket_name = dify_config.SUPABASE_BUCKET_NAME
|
||||
self.client = Client(supabase_url=dify_config.SUPABASE_URL, supabase_key=dify_config.SUPABASE_API_KEY)
|
||||
self.create_bucket(id=dify_config.SUPABASE_BUCKET_NAME, bucket_name=dify_config.SUPABASE_BUCKET_NAME)
|
||||
|
||||
def create_bucket(self, id, bucket_name):
|
||||
if not self.bucket_exists():
|
||||
self.client.storage.create_bucket(id=id, name=bucket_name)
|
||||
|
||||
@override
|
||||
def save(self, filename, data):
|
||||
self.client.storage.from_(self.bucket_name).upload(filename, data)
|
||||
|
||||
@override
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
content: bytes = self.client.storage.from_(self.bucket_name).download(filename)
|
||||
return content
|
||||
|
||||
@override
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
result = self.client.storage.from_(self.bucket_name).download(filename)
|
||||
byte_stream = io.BytesIO(result)
|
||||
while chunk := byte_stream.read(4096): # Read in chunks of 4KB
|
||||
yield chunk
|
||||
|
||||
@override
|
||||
def download(self, filename, target_filepath):
|
||||
result = self.client.storage.from_(self.bucket_name).download(filename)
|
||||
Path(target_filepath).write_bytes(result)
|
||||
|
||||
@override
|
||||
def exists(self, filename):
|
||||
result = self.client.storage.from_(self.bucket_name).list(path=filename)
|
||||
return len(result) > 0
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
self.client.storage.from_(self.bucket_name).remove([filename])
|
||||
|
||||
@override
|
||||
def scan(self, path: str, files: bool = True, directories: bool = False) -> list[str]:
|
||||
bucket = self.client.storage.from_(self.bucket_name)
|
||||
# Supabase lists only immediate children, with offset pagination.
|
||||
root = path.rstrip("/") if path.endswith("/") else path.rpartition("/")[0]
|
||||
pending = [root]
|
||||
keys: list[str] = []
|
||||
page_size = 100
|
||||
while pending:
|
||||
folder = pending.pop()
|
||||
offset = 0
|
||||
while True:
|
||||
page = bucket.list(
|
||||
path=folder,
|
||||
options={
|
||||
"limit": page_size,
|
||||
"offset": offset,
|
||||
"sortBy": {"column": "name", "order": "asc"},
|
||||
},
|
||||
)
|
||||
for entry in page:
|
||||
key = f"{folder}/{entry['name']}" if folder else entry["name"]
|
||||
if entry.get("id") is None:
|
||||
directory_key = key + "/"
|
||||
if directory_key.startswith(path) or path.startswith(directory_key):
|
||||
pending.append(key)
|
||||
if directory_key.startswith(path):
|
||||
keys.append(directory_key)
|
||||
elif key.startswith(path):
|
||||
keys.append(key)
|
||||
if len(page) < page_size:
|
||||
break
|
||||
offset += page_size
|
||||
return self._filter_scan_keys(keys, files, directories)
|
||||
|
||||
def bucket_exists(self):
|
||||
buckets = self.client.storage.list_buckets()
|
||||
return any(bucket.name == self.bucket_name for bucket in buckets)
|
||||
@@ -0,0 +1,73 @@
|
||||
from collections.abc import Generator
|
||||
from typing import override
|
||||
|
||||
from qcloud_cos import CosConfig, CosS3Client
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.storage.base_storage import BaseStorage
|
||||
|
||||
|
||||
class TencentCosStorage(BaseStorage):
|
||||
"""Implementation for Tencent Cloud COS storage."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self.bucket_name = dify_config.TENCENT_COS_BUCKET_NAME
|
||||
if dify_config.TENCENT_COS_CUSTOM_DOMAIN:
|
||||
config = CosConfig(
|
||||
Domain=dify_config.TENCENT_COS_CUSTOM_DOMAIN,
|
||||
SecretId=dify_config.TENCENT_COS_SECRET_ID,
|
||||
SecretKey=dify_config.TENCENT_COS_SECRET_KEY,
|
||||
Scheme=dify_config.TENCENT_COS_SCHEME,
|
||||
)
|
||||
else:
|
||||
config = CosConfig(
|
||||
Region=dify_config.TENCENT_COS_REGION,
|
||||
SecretId=dify_config.TENCENT_COS_SECRET_ID,
|
||||
SecretKey=dify_config.TENCENT_COS_SECRET_KEY,
|
||||
Scheme=dify_config.TENCENT_COS_SCHEME,
|
||||
)
|
||||
self.client = CosS3Client(config)
|
||||
|
||||
@override
|
||||
def save(self, filename, data):
|
||||
self.client.put_object(Bucket=self.bucket_name, Body=data, Key=filename)
|
||||
|
||||
@override
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
data: bytes = self.client.get_object(Bucket=self.bucket_name, Key=filename)["Body"].get_raw_stream().read()
|
||||
return data
|
||||
|
||||
@override
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
response = self.client.get_object(Bucket=self.bucket_name, Key=filename)
|
||||
yield from response["Body"].get_stream(chunk_size=4096)
|
||||
|
||||
@override
|
||||
def download(self, filename, target_filepath):
|
||||
response = self.client.get_object(Bucket=self.bucket_name, Key=filename)
|
||||
response["Body"].get_stream_to_file(target_filepath)
|
||||
|
||||
@override
|
||||
def exists(self, filename):
|
||||
return self.client.object_exists(Bucket=self.bucket_name, Key=filename)
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
self.client.delete_object(Bucket=self.bucket_name, Key=filename)
|
||||
|
||||
@override
|
||||
def scan(self, path: str, files: bool = True, directories: bool = False) -> list[str]:
|
||||
keys: list[str] = []
|
||||
marker = ""
|
||||
while True:
|
||||
page = self.client.list_objects(Bucket=self.bucket_name, Prefix=path, Marker=marker, MaxKeys=1000)
|
||||
keys.extend(obj["Key"] for obj in page.get("Contents", []))
|
||||
if str(page.get("IsTruncated", "false")).lower() != "true":
|
||||
break
|
||||
next_marker = page.get("NextMarker")
|
||||
if not next_marker or next_marker == marker:
|
||||
raise RuntimeError("COS object listing did not advance its pagination marker")
|
||||
marker = next_marker
|
||||
return self._filter_scan_keys(keys, files, directories)
|
||||
@@ -0,0 +1,87 @@
|
||||
from collections.abc import Generator
|
||||
from typing import override
|
||||
|
||||
import tos
|
||||
|
||||
from configs import dify_config
|
||||
from extensions.storage.base_storage import BaseStorage
|
||||
|
||||
|
||||
class VolcengineTosStorage(BaseStorage):
|
||||
"""Implementation for Volcengine TOS storage."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
if not dify_config.VOLCENGINE_TOS_ACCESS_KEY:
|
||||
raise ValueError("VOLCENGINE_TOS_ACCESS_KEY is not set")
|
||||
if not dify_config.VOLCENGINE_TOS_SECRET_KEY:
|
||||
raise ValueError("VOLCENGINE_TOS_SECRET_KEY is not set")
|
||||
if not dify_config.VOLCENGINE_TOS_ENDPOINT:
|
||||
raise ValueError("VOLCENGINE_TOS_ENDPOINT is not set")
|
||||
if not dify_config.VOLCENGINE_TOS_REGION:
|
||||
raise ValueError("VOLCENGINE_TOS_REGION is not set")
|
||||
self.bucket_name = dify_config.VOLCENGINE_TOS_BUCKET_NAME
|
||||
self.client = tos.TosClientV2(
|
||||
ak=dify_config.VOLCENGINE_TOS_ACCESS_KEY,
|
||||
sk=dify_config.VOLCENGINE_TOS_SECRET_KEY,
|
||||
endpoint=dify_config.VOLCENGINE_TOS_ENDPOINT,
|
||||
region=dify_config.VOLCENGINE_TOS_REGION,
|
||||
)
|
||||
|
||||
@override
|
||||
def save(self, filename, data):
|
||||
if not self.bucket_name:
|
||||
raise ValueError("VOLCENGINE_TOS_BUCKET_NAME is not set")
|
||||
self.client.put_object(bucket=self.bucket_name, key=filename, content=data)
|
||||
|
||||
@override
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
if not self.bucket_name:
|
||||
raise FileNotFoundError("VOLCENGINE_TOS_BUCKET_NAME is not set")
|
||||
data = self.client.get_object(bucket=self.bucket_name, key=filename).read()
|
||||
if not isinstance(data, bytes):
|
||||
raise TypeError(f"Expected bytes, got {type(data).__name__}")
|
||||
return data
|
||||
|
||||
@override
|
||||
def load_stream(self, filename: str) -> Generator:
|
||||
if not self.bucket_name:
|
||||
raise FileNotFoundError("VOLCENGINE_TOS_BUCKET_NAME is not set")
|
||||
response = self.client.get_object(bucket=self.bucket_name, key=filename)
|
||||
while chunk := response.read(4096):
|
||||
yield chunk
|
||||
|
||||
@override
|
||||
def download(self, filename, target_filepath):
|
||||
if not self.bucket_name:
|
||||
raise ValueError("VOLCENGINE_TOS_BUCKET_NAME is not set")
|
||||
self.client.get_object_to_file(bucket=self.bucket_name, key=filename, file_path=target_filepath)
|
||||
|
||||
@override
|
||||
def exists(self, filename):
|
||||
if not self.bucket_name:
|
||||
return False
|
||||
res = self.client.head_object(bucket=self.bucket_name, key=filename)
|
||||
return res.status_code == 200
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
if not self.bucket_name:
|
||||
return
|
||||
self.client.delete_object(bucket=self.bucket_name, key=filename)
|
||||
|
||||
@override
|
||||
def scan(self, path: str, files: bool = True, directories: bool = False) -> list[str]:
|
||||
if not self.bucket_name:
|
||||
raise ValueError("VOLCENGINE_TOS_BUCKET_NAME is not set")
|
||||
keys: list[str] = []
|
||||
marker = ""
|
||||
while True:
|
||||
page = self.client.list_objects(bucket=self.bucket_name, prefix=path, marker=marker, max_keys=1000)
|
||||
keys.extend(obj.key for obj in page.contents)
|
||||
if not page.is_truncated:
|
||||
break
|
||||
if not page.next_marker or page.next_marker == marker:
|
||||
raise RuntimeError("TOS object listing did not advance its pagination marker")
|
||||
marker = page.next_marker
|
||||
return self._filter_scan_keys(keys, files, directories)
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Execution-side access to the trace pipeline, bound to one Flask application.
|
||||
|
||||
Legacy producers in the execution kernel import only these accessors; the
|
||||
composition root binds the services they reach. Every accessor fails open:
|
||||
tracing never breaks the operation that is being traced.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from collections.abc import Mapping
|
||||
from typing import TYPE_CHECKING, Any, Literal, Protocol, runtime_checkable
|
||||
|
||||
from dify_trace_sdk.emitter import TraceScope
|
||||
from dify_trace_sdk.events import TraceCorrelation
|
||||
from flask import Flask, current_app, has_app_context
|
||||
|
||||
from core.helper.trace_id_helper import ParentTraceContext
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from dify_agent.layers.execution_context import ApplicationTracingContext
|
||||
|
||||
from core.app.apps.agent_app.runtime_request_builder import AgentAppRuntimeBuildContext
|
||||
from core.app.entities.app_invoke_entities import AdvancedChatAppGenerateEntity, WorkflowAppGenerateEntity
|
||||
from core.workflow.nodes.agent_v2.runtime_request_builder import WorkflowAgentRuntimeBuildContext
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_SCOPES_KEY = "trace_scopes"
|
||||
_HOOKS_KEY = "application_tracing_hooks"
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ExecutionTraceScopes(Protocol):
|
||||
"""Trace scopes for legacy producers, which hold the app's stored tracing policy as its raw column value."""
|
||||
|
||||
def for_execution(
|
||||
self,
|
||||
*,
|
||||
tenant_id: str,
|
||||
app_id: str | None,
|
||||
app_tracing: str | None,
|
||||
user_id: str | None,
|
||||
correlation: TraceCorrelation,
|
||||
) -> TraceScope | None: ...
|
||||
|
||||
def for_app(
|
||||
self, *, tenant_id: str, app_id: str | None, user_id: str | None, correlation: TraceCorrelation
|
||||
) -> TraceScope | None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ApplicationTracingHooks(Protocol):
|
||||
"""Agent trace collection lifecycle; it never replaces the trace pipeline."""
|
||||
|
||||
def prepare_agent_app(self, context: "AgentAppRuntimeBuildContext") -> "ApplicationTracingContext | None": ...
|
||||
|
||||
def prepare_workflow_agent(
|
||||
self, context: "WorkflowAgentRuntimeBuildContext", conversation_id: str | None
|
||||
) -> "ApplicationTracingContext | None": ...
|
||||
|
||||
def freeze_workflow_run(
|
||||
self,
|
||||
entity: "AdvancedChatAppGenerateEntity | WorkflowAppGenerateEntity",
|
||||
*,
|
||||
workflow_id: str,
|
||||
workflow_run_id: str,
|
||||
conversation_id: object,
|
||||
graph_data: object,
|
||||
) -> None: ...
|
||||
|
||||
def capture_agent_app_terminal(
|
||||
self,
|
||||
*,
|
||||
tenant_id: str,
|
||||
app_id: str,
|
||||
message_id: str,
|
||||
outcome: Literal["succeeded", "failed", "cancelled"],
|
||||
output: str | None,
|
||||
) -> None: ...
|
||||
|
||||
|
||||
def bind_tracing(app: Flask, *, scopes: ExecutionTraceScopes, hooks: ApplicationTracingHooks | None) -> None:
|
||||
"""``hooks`` is ``None`` when this deployment does not collect Agent traces."""
|
||||
app.extensions[_SCOPES_KEY] = scopes
|
||||
app.extensions[_HOOKS_KEY] = hooks
|
||||
|
||||
|
||||
def _scopes() -> ExecutionTraceScopes | None:
|
||||
if not has_app_context():
|
||||
return None
|
||||
scopes = current_app.extensions.get(_SCOPES_KEY)
|
||||
return scopes if isinstance(scopes, ExecutionTraceScopes) else None
|
||||
|
||||
|
||||
def correlation_from_extras(extras: Mapping[str, Any]) -> TraceCorrelation:
|
||||
"""The caller-supplied correlation an execution carries in its ``extras``."""
|
||||
parent = extras.get("parent_trace_context")
|
||||
if isinstance(parent, Mapping):
|
||||
try:
|
||||
parent = ParentTraceContext.model_validate(parent)
|
||||
except ValueError:
|
||||
parent = None
|
||||
external_trace_id, session_id = extras.get("external_trace_id"), extras.get("trace_session_id")
|
||||
return TraceCorrelation(
|
||||
external_trace_id=external_trace_id if isinstance(external_trace_id, str) and external_trace_id else None,
|
||||
session_id=session_id if isinstance(session_id, str) and session_id else None,
|
||||
parent_workflow_run_id=parent.parent_workflow_run_id if isinstance(parent, ParentTraceContext) else None,
|
||||
parent_node_execution_id=parent.parent_node_execution_id if isinstance(parent, ParentTraceContext) else None,
|
||||
)
|
||||
|
||||
|
||||
def create_trace_scope(
|
||||
*, tenant_id: str, app_id: str | None, app_tracing: str | None, user_id: str | None, extras: Mapping[str, Any]
|
||||
) -> TraceScope | None:
|
||||
"""The scope for an execution whose app row is loaded; ``None`` when nothing consumes its events."""
|
||||
scopes = _scopes()
|
||||
if scopes is None:
|
||||
return None
|
||||
try:
|
||||
return scopes.for_execution(
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
app_tracing=app_tracing,
|
||||
user_id=user_id,
|
||||
correlation=correlation_from_extras(extras),
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("Tracing scope unavailable: app_id=%s", app_id, exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
def create_trace_scope_for_app(
|
||||
*, tenant_id: str, app_id: str | None, user_id: str | None, extras: Mapping[str, Any]
|
||||
) -> TraceScope | None:
|
||||
"""The scope for a caller that does not hold the app row."""
|
||||
scopes = _scopes()
|
||||
if scopes is None:
|
||||
return None
|
||||
try:
|
||||
return scopes.for_app(
|
||||
tenant_id=tenant_id, app_id=app_id, user_id=user_id, correlation=correlation_from_extras(extras)
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("Tracing scope unavailable: app_id=%s", app_id, exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
def application_tracing_hooks() -> ApplicationTracingHooks | None:
|
||||
"""The Agent collection hooks; ``None`` when Agent tracing is off or no application is bound here.
|
||||
|
||||
Agent runs started without hooks are reported as not collected instead of failing.
|
||||
"""
|
||||
if not has_app_context():
|
||||
return None
|
||||
hooks = current_app.extensions.get(_HOOKS_KEY)
|
||||
return hooks if isinstance(hooks, ApplicationTracingHooks) else None
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Abort active workflow runs during Celery warm shutdown."""
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from typing import Any
|
||||
|
||||
from celery.signals import worker_shutdown, worker_shutting_down
|
||||
|
||||
from core.app.apps.workflow.active_workflow_tasks import (
|
||||
get_active_workflow_task_count,
|
||||
reset_active_workflow_tasks,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
WORKFLOW_WARM_SHUTDOWN_ABORT_REASON = "Workflow stopped because the worker is shutting down."
|
||||
_WORKER_SHUTTING_DOWN_DISPATCH_UID = "dify.workflow_warm_shutdown.shutting_down"
|
||||
_WORKER_SHUTDOWN_DISPATCH_UID = "dify.workflow_warm_shutdown.shutdown"
|
||||
_celery_warm_shutdown_started = threading.Event()
|
||||
|
||||
|
||||
def _is_warm_shutdown(how: Any) -> bool:
|
||||
return str(how).strip().lower() == "warm"
|
||||
|
||||
|
||||
def celery_warm_shutdown_started() -> bool:
|
||||
"""Return whether the current worker process started Celery warm shutdown."""
|
||||
return _celery_warm_shutdown_started.is_set()
|
||||
|
||||
|
||||
def mark_celery_warm_shutdown_started() -> None:
|
||||
"""Mark the current worker process as being in Celery warm shutdown."""
|
||||
_celery_warm_shutdown_started.set()
|
||||
|
||||
|
||||
def _on_worker_shutting_down(*args: object, **kwargs: object) -> None:
|
||||
"""Mark warm shutdown and log the active workflow run count."""
|
||||
how = kwargs.get("how")
|
||||
if not _is_warm_shutdown(how):
|
||||
logger.debug("Skip workflow abort during non-warm Celery shutdown: how=%s", how)
|
||||
return
|
||||
|
||||
mark_celery_warm_shutdown_started()
|
||||
abort_count = get_active_workflow_task_count()
|
||||
if abort_count == 0:
|
||||
logger.info("No active workflow runs found during Celery warm shutdown")
|
||||
return
|
||||
|
||||
logger.info(
|
||||
"Marked Celery warm shutdown for %s active workflow run(s)",
|
||||
abort_count,
|
||||
)
|
||||
|
||||
|
||||
def _on_worker_shutdown(*args: object, **kwargs: object) -> None:
|
||||
"""Log whether tracked workflow tasks ended before Celery worker shutdown."""
|
||||
remaining_run_count = get_active_workflow_task_count()
|
||||
if remaining_run_count:
|
||||
logger.warning(
|
||||
"Celery worker is shutting down with %s workflow run(s) still active after warm shutdown wait",
|
||||
remaining_run_count,
|
||||
)
|
||||
return
|
||||
|
||||
logger.info("Celery worker shutdown reached after all tracked workflow runs ended")
|
||||
|
||||
|
||||
def setup_workflow_warm_shutdown_handler() -> None:
|
||||
"""Connect Celery worker shutdown handlers for workflow abort and logging."""
|
||||
reset_active_workflow_tasks()
|
||||
worker_shutting_down.connect(
|
||||
_on_worker_shutting_down,
|
||||
weak=False,
|
||||
dispatch_uid=_WORKER_SHUTTING_DOWN_DISPATCH_UID,
|
||||
)
|
||||
worker_shutdown.connect(
|
||||
_on_worker_shutdown,
|
||||
weak=False,
|
||||
dispatch_uid=_WORKER_SHUTDOWN_DISPATCH_UID,
|
||||
)
|
||||
Reference in new issue
Block a user