Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
feat(api): type billing error reasons per proto service (#45203)
yyh4c521a3c0a1f
diff --git a/api/controllers/console/billing/billing.py b/api/controllers/console/billing/billing.pyindex 3600a3e7f03..43982171624 100644--- a/api/controllers/console/billing/billing.py+++ b/api/controllers/console/billing/billing.py@@ -53,7 +53,7 @@ register_response_schema_models()-def _billing_portal_error(error: billing.UpstreamError) -> BaseHTTPException:+def _subscription_portal_error(error: billing.BillingSubscriptionUpstreamError) -> BaseHTTPException:match error.reason:case (""@@ -75,59 +75,30 @@ def _billing_portal_error(error: billing.UpstreamError) -> BaseHTTPException:| "INVALID_KNOWLEDGE_RATE_LIMIT_REQUEST"| "TENANT_IDS_COUNT_TOO_LARGE"| "DOCUMENT_USAGE_UNAVAILABLE"- | "EDUCATION_VERIFY_FAILED"- | "EDUCATION_CREATE_FAILED"- | "EDUCATION_STATUS_FAILED"+ ):+ return to_billing_request_error(error)+ case UnknownErrorReason() | None:+ return to_billing_request_error(error)+ case unreachable:+ assert_never(unreachable)+++def _invoice_portal_error(error: billing.BillingInvoiceUpstreamError) -> BaseHTTPException:+ match error.reason:+ case (+ ""+ | "CODEC"+ | "VALIDATOR"+ | "UNKNOWN"+ | "INVALID_SECRET_KEY"+ | "REQUEST_IN_PROGRESS"+ | "MISSING_TENANT_ID"+ | "INVALID_TENANT_ID"+ | "MISSING_ACCOUNT_ID"+ | "INVALID_ACCOUNT_ID"+ | "MISSING_PREFILLED_EMAIL"| "INVALID_INVOICE_REQUEST"| "CREATE_INVOICE_PORTAL_FAILED"- | "INVALID_COMPLIANCE_DOWNLOAD_REQUEST"- | "MISSING_DOC_NAME"- | "MISSING_IP_ADDRESS"- | "MISSING_DEVICE_INFO"- | "COMPLIANCE_DOCUMENT_NOT_FOUND"- | "COMPLIANCE_DOWNLOAD_FORBIDDEN"- | "COMPLIANCE_DOWNLOAD_FAILED"- | "INVALID_MODEL_PROVIDER_PAYMENT_LINK_REQUEST"- | "MISSING_PROVIDER_NAME"- | "INVALID_MODEL_PROVIDER"- | "CREATE_MODEL_PROVIDER_PAYMENT_LINK_FAILED"- | "BILLING_COUPON_AMOUNT_OFF_INVALID"- | "BILLING_COUPON_CURRENCY_INVALID"- | "BILLING_COUPON_DISCOUNT_TYPE_INVALID"- | "BILLING_COUPON_DURATION_MISMATCH"- | "BILLING_COUPON_DURATION_MONTHS_INVALID"- | "BILLING_COUPON_DURATION_MONTHS_MISMATCH"- | "BILLING_COUPON_DURATION_UNSUPPORTED"- | "BILLING_COUPON_EXPIRES_AFTER_COUPON"- | "BILLING_COUPON_EXPIRES_AT_INVALID"- | "BILLING_COUPON_ID_EMPTY"- | "BILLING_COUPON_NOT_FOUND"- | "BILLING_COUPON_PERCENT_OFF_INVALID"- | "BILLING_COUPON_PRODUCT_NOT_FOUND"- | "BILLING_COUPON_PRODUCT_PRICE_NOT_CONFIGURED"- | "BILLING_COUPON_PRODUCT_SCOPE_INVALID"- | "BILLING_COUPON_PRODUCT_SCOPE_MISMATCH"- | "BILLING_COUPON_PRODUCT_SERVICE_NOT_CONFIGURED"- | "BILLING_COUPON_PROMOTION_CODE_INVALID"- | "BILLING_COUPON_QUANTITY_INVALID"- | "BILLING_COUPON_QUANTITY_TOO_LARGE"- | "BILLING_COUPON_STRIPE_NOT_CONFIGURED"- | "BILLING_COUPON_TASK_ID_REQUIRED"- | "BILLING_COUPON_TASK_NOT_CONFIGURED"- | "BILLING_COUPON_TASK_NOT_FOUND"- | "BILLING_COUPON_TASK_PUBLISHER_NOT_CONFIGURED"- | "BILLING_COUPON_TASK_REPO_NOT_CONFIGURED"- | "BILLING_COUPON_TICKET_ID_REQUIRED"- | "BILLING_COUPON_USAGE_REPO_NOT_CONFIGURED"- | "BILLING_REFUND_AMOUNT_INVALID"- | "BILLING_REFUND_INVOICE_MISMATCH"- | "BILLING_REFUND_INVOICE_NOT_FOUND"- | "BILLING_REFUND_MODE_INVALID"- | "BILLING_REFUND_NOT_REFUNDABLE"- | "BILLING_REFUND_PAYMENT_NOT_FOUND"- | "BILLING_REFUND_STRIPE_STATUS_NOT_FOUND"- | "BILLING_REFUND_SUBSCRIPTION_NOT_FOUND"- | "BILLING_REFUND_TICKET_ID_REQUIRED"):return to_billing_request_error(error)case UnknownErrorReason() | None:@@ -169,8 +140,8 @@ class Subscription(Resource):plan=req_data.plan,interval=req_data.interval,)- except billing.UpstreamError as error:- raise _billing_portal_error(error) from error+ except billing.BillingSubscriptionUpstreamError as error:+ raise _subscription_portal_error(error) from errorreturn dump_response(BillingSubscriptionResponse, data)@@ -196,6 +167,6 @@ class Invoices(Resource):def get(self, request_context: RequestContext):try:data = application_services().billing_portal.get_invoices(request_context)- except billing.UpstreamError as error:- raise _billing_portal_error(error) from error+ except billing.BillingInvoiceUpstreamError as error:+ raise _invoice_portal_error(error) from errorreturn dump_response(BillingInvoiceResponse, data)diff --git a/api/controllers/console/billing/compliance.py b/api/controllers/console/billing/compliance.pyindex 223fb1931db..611aa9c4c0c 100644--- a/api/controllers/console/billing/compliance.py+++ b/api/controllers/console/billing/compliance.py@@ -55,7 +55,7 @@ register_response_schema_models()-def _compliance_download_error(error: billing.UpstreamError) -> BaseHTTPException:+def _compliance_download_error(error: billing.BillingComplianceUpstreamError) -> BaseHTTPException:match error.reason:case "COMPLIANCE_DOCUMENT_NOT_FOUND":return ComplianceDocumentNotFoundError()@@ -74,65 +74,11 @@ def _compliance_download_error(error: billing.UpstreamError) -> BaseHTTPExceptio| "MISSING_ACCOUNT_ID"| "INVALID_ACCOUNT_ID"| "MISSING_PREFILLED_EMAIL"- | "INVALID_PAYMENT_LINK_REQUEST"- | "MISSING_PLAN"- | "MISSING_INTERVAL"- | "INVALID_PLAN_INTERVAL"- | "CREATE_SUBSCRIPTION_PAYMENT_LINK_FAILED"- | "INVALID_KNOWLEDGE_RATE_LIMIT_REQUEST"- | "TENANT_IDS_COUNT_TOO_LARGE"- | "DOCUMENT_USAGE_UNAVAILABLE"- | "EDUCATION_VERIFY_FAILED"- | "EDUCATION_CREATE_FAILED"- | "EDUCATION_STATUS_FAILED"- | "INVALID_INVOICE_REQUEST"- | "CREATE_INVOICE_PORTAL_FAILED"| "INVALID_COMPLIANCE_DOWNLOAD_REQUEST"| "MISSING_DOC_NAME"| "MISSING_IP_ADDRESS"| "MISSING_DEVICE_INFO"| "COMPLIANCE_DOWNLOAD_FAILED"- | "INVALID_MODEL_PROVIDER_PAYMENT_LINK_REQUEST"- | "MISSING_PROVIDER_NAME"- | "INVALID_MODEL_PROVIDER"- | "CREATE_MODEL_PROVIDER_PAYMENT_LINK_FAILED"- | "BILLING_COUPON_AMOUNT_OFF_INVALID"- | "BILLING_COUPON_CURRENCY_INVALID"- | "BILLING_COUPON_DISCOUNT_TYPE_INVALID"- | "BILLING_COUPON_DURATION_MISMATCH"- | "BILLING_COUPON_DURATION_MONTHS_INVALID"- | "BILLING_COUPON_DURATION_MONTHS_MISMATCH"- | "BILLING_COUPON_DURATION_UNSUPPORTED"- | "BILLING_COUPON_EXPIRES_AFTER_COUPON"- | "BILLING_COUPON_EXPIRES_AT_INVALID"- | "BILLING_COUPON_ID_EMPTY"- | "BILLING_COUPON_NOT_FOUND"- | "BILLING_COUPON_PERCENT_OFF_INVALID"- | "BILLING_COUPON_PRODUCT_NOT_FOUND"- | "BILLING_COUPON_PRODUCT_PRICE_NOT_CONFIGURED"- | "BILLING_COUPON_PRODUCT_SCOPE_INVALID"- | "BILLING_COUPON_PRODUCT_SCOPE_MISMATCH"- | "BILLING_COUPON_PRODUCT_SERVICE_NOT_CONFIGURED"- | "BILLING_COUPON_PROMOTION_CODE_INVALID"- | "BILLING_COUPON_QUANTITY_INVALID"- | "BILLING_COUPON_QUANTITY_TOO_LARGE"- | "BILLING_COUPON_STRIPE_NOT_CONFIGURED"- | "BILLING_COUPON_TASK_ID_REQUIRED"- | "BILLING_COUPON_TASK_NOT_CONFIGURED"- | "BILLING_COUPON_TASK_NOT_FOUND"- | "BILLING_COUPON_TASK_PUBLISHER_NOT_CONFIGURED"- | "BILLING_COUPON_TASK_REPO_NOT_CONFIGURED"- | "BILLING_COUPON_TICKET_ID_REQUIRED"- | "BILLING_COUPON_USAGE_REPO_NOT_CONFIGURED"- | "BILLING_REFUND_AMOUNT_INVALID"- | "BILLING_REFUND_INVOICE_MISMATCH"- | "BILLING_REFUND_INVOICE_NOT_FOUND"- | "BILLING_REFUND_MODE_INVALID"- | "BILLING_REFUND_NOT_REFUNDABLE"- | "BILLING_REFUND_PAYMENT_NOT_FOUND"- | "BILLING_REFUND_STRIPE_STATUS_NOT_FOUND"- | "BILLING_REFUND_SUBSCRIPTION_NOT_FOUND"- | "BILLING_REFUND_TICKET_ID_REQUIRED"):return to_billing_request_error(error)case UnknownErrorReason() | None:@@ -189,6 +135,6 @@ class ComplianceApi(Resource):)except ComplianceRateLimitExceededError as error:raise ComplianceRateLimitError() from error- except billing.UpstreamError as error:+ except billing.BillingComplianceUpstreamError as error:raise _compliance_download_error(error) from errorreturn dump_response(ComplianceDownloadResponse, data)diff --git a/api/dev/generate_billing_client.py b/api/dev/generate_billing_client.pyindex d7b7c08f350..a7012b167e3 100644--- a/api/dev/generate_billing_client.py+++ b/api/dev/generate_billing_client.py@@ -1,9 +1,14 @@"""Snapshot the billing and saas OpenAPI specs and generate the typed client in `services/billing_client`.The snapshot is the generation input, so CI can regenerate and diff without the private dify-saas-checkout. Only operations on `ALLOWED_OPERATIONS`, the schemas they reach, and each service's-`ERROR_SCHEMAS` are snapshotted: dify is public, and every other dify-saas endpoint stays out of-this repository.+checkout. Only operations on `ALLOWED_OPERATIONS`, the schemas they reach, the `Error` body, and the+`<Service>ErrorReason` of each proto service they belong to are snapshotted: dify is public, and every+other dify-saas endpoint stays out of this repository.++The proto service is the operationId prefix before the underscore (`BillingEducation` for+`BillingEducation_VerifyEducationIdentity`). Each one gets its own reason Literal, error classes, and+`ServiceErrors`, so a caller catching `BillingEducationUpstreamError` only matches the reasons that+service can return.uv run --project api --dev python api/dev/generate_billing_client.py # snapshot + generateuv run --project api --dev python api/dev/generate_billing_client.py --from-snapshot # generate only@@ -57,7 +62,9 @@ SNAPSHOT_COMMIT_KEY = "x-dify-saas-commit"HTTP_METHODS = ("get", "post", "put", "delete", "patch")LINE_LENGTH = 120BASE_MODEL_ATTRIBUTES = frozenset(dir(BaseModel))-ERROR_SCHEMAS = ("Error", "ErrorReason")+ERROR_SCHEMA = "Error"+ERROR_REASON_SUFFIX = "ErrorReason"+ERROR_CLASS_SUFFIXES = ("UpstreamError", "UpstreamUnavailableError", "UpstreamInvalidResponseError")@dataclass(frozen=True)@@ -201,6 +208,17 @@ def _annotate_presence(schema: JsonObject) -> JsonObject:return result+def proto_service(operation_id: str) -> str:+ prefix, separator, method = operation_id.partition("_")+ if not separator or not prefix or not method:+ raise GenerationError(f"operationId {operation_id!r} has no `<Service>_` prefix")+ return prefix+++def error_reason_schema(proto: str) -> str:+ return f"{proto}{ERROR_REASON_SUFFIX}"++def build_snapshot(service: Service, source: JsonObject, commit: str) -> JsonObject:prefix = SCHEMA_PREFIXES[service]source_paths: dict[str, JsonObject] = source.get("paths", {})@@ -215,11 +233,20 @@ def build_snapshot(service: Service, source: JsonObject, commit: str) -> JsonObjname.removeprefix(prefix): _rewrite_refs(schema, prefix)for name, schema in source.get("components", {}).get("schemas", {}).items()}- for name in ERROR_SCHEMAS:- if name not in source_schemas:- raise GenerationError(f"{service}: error schema {prefix}{name} is not in the dify-saas spec")+ error_schemas = {ERROR_SCHEMA}+ for allowed in ALLOWED_OPERATIONS[service]:+ operation_id = paths[allowed.path][allowed.method.lower()].get("operationId", "")+ reason_schema = error_reason_schema(proto_service(operation_id))+ if reason_schema not in source_schemas:+ raise GenerationError(+ f"{service}: {allowed.method} {allowed.path} ({operation_id}) has no "+ f"{prefix}{reason_schema} schema in the dify-saas spec"+ )+ error_schemas.add(reason_schema)+ if ERROR_SCHEMA not in source_schemas:+ raise GenerationError(f"{service}: error schema {prefix}{ERROR_SCHEMA} is not in the dify-saas spec")reachable: set[str] = set()- pending = _ref_names(paths) | set(ERROR_SCHEMAS)+ pending = _ref_names(paths) | error_schemaswhile pending:name = pending.pop()if name in reachable:@@ -351,7 +378,7 @@ def check_error_body(schema: JsonObject) -> None:properties: dict[str, JsonObject] = schema.get("properties", {})expected = {"code": {"type": "integer", "format": "int32"},- "reason": {"$ref": "#/components/schemas/ErrorReason"},+ "reason": {"type": "string"},"message": {"type": "string"},"metadata": {"type": "object", "additionalProperties": {"type": "string"}},}@@ -363,7 +390,7 @@ def check_error_body(schema: JsonObject) -> None:def render_schema(name: str, schema: JsonObject) -> list[str]:- if name == "Error":+ if name == ERROR_SCHEMA:check_error_body(schema)return []if "enum" in schema:@@ -438,7 +465,7 @@ def render_operation(service: Service, allowed: AllowedOperation, operation: Jsof" {json.dumps(allowed.method)},",f" {json.dumps(template)},",f" response_model={response},",- " errors=ERRORS,",+ f" errors={service_errors_name(proto_service(operation['operationId']))},",f" path_params={{{', '.join(path_params)}}},",f" params={{{', '.join(query_params)}}},",f" body={body},",@@ -446,42 +473,74 @@ def render_operation(service: Service, allowed: AllowedOperation, operation: Jso]-def render_errors(service: Service) -> list[str]:- return f'''def _is_error_reason(value: str) -> TypeIs[ErrorReason]:- return value in get_args(ErrorReason.__value__)+def service_errors_name(proto: str) -> str:+ return f"{snake_case(proto).upper()}_ERRORS"+++def proto_services(service: Service, snapshot: JsonObject) -> list[str]:+ protos: list[str] = []+ for allowed in ALLOWED_OPERATIONS[service]:+ proto = proto_service(snapshot["paths"][allowed.path][allowed.method.lower()]["operationId"])+ if proto not in protos:+ protos.append(proto)+ return protos+++def check_error_schemas(service: Service, protos: list[str], schemas: dict[str, JsonObject]) -> None:+ expected = {error_reason_schema(proto) for proto in protos}+ actual = {name for name in schemas if name.endswith(ERROR_REASON_SUFFIX)}+ if actual != expected:+ raise GenerationError(+ f"{service} snapshot reason schemas differ from its operations' services: "+ f"missing {sorted(expected - actual)}, unused {sorted(actual - expected)}; rerun the snapshot"+ )+ generated = {f"{proto}{suffix}" for proto in protos for suffix in ERROR_CLASS_SUFFIXES}+ if collisions := sorted(generated & set(schemas)):+ raise GenerationError(f"{service}: generated error classes collide with schemas {collisions}")+++def render_errors(proto: str) -> list[str]:+ reason = error_reason_schema(proto)+ guard = f"_is_{snake_case(proto)}_error_reason"+ return f'''def {guard}(value: str) -> TypeIs[{reason}]:+ return value in get_args({reason}.__value__)-class UpstreamError(BillingUpstreamError):- """A failed {service} call, with its reason typed by this module's `ErrorReason`."""+class {proto}UpstreamError(BillingUpstreamError):+ """A failed {proto} call, with its reason typed by `{reason}`."""def __init__(self,*args: object,status_code: int | None = None,body: UpstreamErrorBody | None = None,- reason: ErrorReason | UnknownErrorReason | None = None,+ reason: {reason} | UnknownErrorReason | None = None,) -> None:super().__init__(*args, status_code=status_code, body=body)self.reason = reason-class UpstreamUnavailableError(UpstreamError, BillingUpstreamUnavailableError):+class {proto}UpstreamUnavailableError({proto}UpstreamError, BillingUpstreamUnavailableError):pass-class UpstreamInvalidResponseError(UpstreamError, BillingUpstreamInvalidResponseError):+class {proto}UpstreamInvalidResponseError({proto}UpstreamError, BillingUpstreamInvalidResponseError):pass-ERRORS = ServiceErrors(- is_reason=_is_error_reason, unavailable=UpstreamUnavailableError, invalid_response=UpstreamInvalidResponseError+{service_errors_name(proto)} = ServiceErrors(+ is_reason={guard},+ unavailable={proto}UpstreamUnavailableError,+ invalid_response={proto}UpstreamInvalidResponseError,)'''.splitlines()def render_module(service: Service, snapshot: JsonObject) -> str:schemas: dict[str, JsonObject] = snapshot["components"]["schemas"]+ protos = proto_services(service, snapshot)+ check_error_schemas(service, protos, schemas)blocks = [block for name in model_order(schemas) if (block := render_schema(name, schemas[name]))]- blocks.append(render_errors(service))+ blocks.extend(render_errors(proto) for proto in protos)for allowed in ALLOWED_OPERATIONS[service]:operation = snapshot["paths"][allowed.path][allowed.method.lower()]blocks.append(render_operation(service, allowed, operation))diff --git a/api/services/account/adapters.py b/api/services/account/adapters.pyindex b9469f88f90..c7775860887 100644--- a/api/services/account/adapters.py+++ b/api/services/account/adapters.py@@ -276,7 +276,7 @@ class RBACWorkspaceMemberAccessSync(WorkspaceMemberAccessSync):)-def _education_error(error: billing.UpstreamError) -> AccountApplicationError | None:+def _education_error(error: billing.BillingEducationUpstreamError) -> AccountApplicationError | None:"""The account error for a billing failure, or None to leave it to the generic billing errors."""match error.reason:case "EDUCATION_VERIFY_FAILED":@@ -296,65 +296,7 @@ def _education_error(error: billing.UpstreamError) -> AccountApplicationError || "MISSING_ACCOUNT_ID"| "INVALID_ACCOUNT_ID"| "MISSING_PREFILLED_EMAIL"- | "INVALID_PAYMENT_LINK_REQUEST"- | "MISSING_PLAN"- | "MISSING_INTERVAL"- | "INVALID_PLAN_INTERVAL"- | "CREATE_SUBSCRIPTION_PAYMENT_LINK_FAILED"- | "INVALID_KNOWLEDGE_RATE_LIMIT_REQUEST"- | "TENANT_IDS_COUNT_TOO_LARGE"- | "DOCUMENT_USAGE_UNAVAILABLE"| "EDUCATION_STATUS_FAILED"- | "INVALID_INVOICE_REQUEST"- | "CREATE_INVOICE_PORTAL_FAILED"- | "INVALID_COMPLIANCE_DOWNLOAD_REQUEST"- | "MISSING_DOC_NAME"- | "MISSING_IP_ADDRESS"- | "MISSING_DEVICE_INFO"- | "COMPLIANCE_DOCUMENT_NOT_FOUND"- | "COMPLIANCE_DOWNLOAD_FORBIDDEN"- | "COMPLIANCE_DOWNLOAD_FAILED"- | "INVALID_MODEL_PROVIDER_PAYMENT_LINK_REQUEST"- | "MISSING_PROVIDER_NAME"- | "INVALID_MODEL_PROVIDER"- | "CREATE_MODEL_PROVIDER_PAYMENT_LINK_FAILED"- | "BILLING_COUPON_AMOUNT_OFF_INVALID"- | "BILLING_COUPON_CURRENCY_INVALID"- | "BILLING_COUPON_DISCOUNT_TYPE_INVALID"- | "BILLING_COUPON_DURATION_MISMATCH"- | "BILLING_COUPON_DURATION_MONTHS_INVALID"- | "BILLING_COUPON_DURATION_MONTHS_MISMATCH"- | "BILLING_COUPON_DURATION_UNSUPPORTED"- | "BILLING_COUPON_EXPIRES_AFTER_COUPON"- | "BILLING_COUPON_EXPIRES_AT_INVALID"- | "BILLING_COUPON_ID_EMPTY"- | "BILLING_COUPON_NOT_FOUND"- | "BILLING_COUPON_PERCENT_OFF_INVALID"- | "BILLING_COUPON_PRODUCT_NOT_FOUND"- | "BILLING_COUPON_PRODUCT_PRICE_NOT_CONFIGURED"- | "BILLING_COUPON_PRODUCT_SCOPE_INVALID"- | "BILLING_COUPON_PRODUCT_SCOPE_MISMATCH"- | "BILLING_COUPON_PRODUCT_SERVICE_NOT_CONFIGURED"- | "BILLING_COUPON_PROMOTION_CODE_INVALID"- | "BILLING_COUPON_QUANTITY_INVALID"- | "BILLING_COUPON_QUANTITY_TOO_LARGE"- | "BILLING_COUPON_STRIPE_NOT_CONFIGURED"- | "BILLING_COUPON_TASK_ID_REQUIRED"- | "BILLING_COUPON_TASK_NOT_CONFIGURED"- | "BILLING_COUPON_TASK_NOT_FOUND"- | "BILLING_COUPON_TASK_PUBLISHER_NOT_CONFIGURED"- | "BILLING_COUPON_TASK_REPO_NOT_CONFIGURED"- | "BILLING_COUPON_TICKET_ID_REQUIRED"- | "BILLING_COUPON_USAGE_REPO_NOT_CONFIGURED"- | "BILLING_REFUND_AMOUNT_INVALID"- | "BILLING_REFUND_INVOICE_MISMATCH"- | "BILLING_REFUND_INVOICE_NOT_FOUND"- | "BILLING_REFUND_MODE_INVALID"- | "BILLING_REFUND_NOT_REFUNDABLE"- | "BILLING_REFUND_PAYMENT_NOT_FOUND"- | "BILLING_REFUND_STRIPE_STATUS_NOT_FOUND"- | "BILLING_REFUND_SUBSCRIPTION_NOT_FOUND"- | "BILLING_REFUND_TICKET_ID_REQUIRED"):return Nonecase UnknownErrorReason() | None:@@ -367,7 +309,7 @@ def _education_error(error: billing.UpstreamError) -> AccountApplicationError |def _education_errors() -> Generator[None]:try:yield- except billing.UpstreamError as error:+ except billing.BillingEducationUpstreamError as error:mapped = _education_error(error)if mapped is None:raisediff --git a/api/services/billing_client/billing.openapi.json b/api/services/billing_client/billing.openapi.jsonindex 891791ccddb..91f7e01dddf 100644--- a/api/services/billing_client/billing.openapi.json+++ b/api/services/billing_client/billing.openapi.json@@ -4,7 +4,7 @@"title": "","version": "0.0.1"},- "x-dify-saas-commit": "04f8d88cc15c5f62f14f8843a54f3e2e7e09ee5a",+ "x-dify-saas-commit": "2d358b5a0555440b30d8601f5e786a15e28a2345","paths": {"/v1/subscription/info": {"get": {@@ -710,6 +710,138 @@"tenant_ids"]},+ "BillingComplianceErrorReason": {+ "enum": [+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "REQUEST_IN_PROGRESS",+ "MISSING_TENANT_ID",+ "INVALID_TENANT_ID",+ "MISSING_ACCOUNT_ID",+ "INVALID_ACCOUNT_ID",+ "MISSING_PREFILLED_EMAIL",+ "INVALID_COMPLIANCE_DOWNLOAD_REQUEST",+ "MISSING_DOC_NAME",+ "MISSING_IP_ADDRESS",+ "MISSING_DEVICE_INFO",+ "COMPLIANCE_DOCUMENT_NOT_FOUND",+ "COMPLIANCE_DOWNLOAD_FORBIDDEN",+ "COMPLIANCE_DOWNLOAD_FAILED"+ ],+ "type": "string",+ "description": "Reasons returned by the BillingCompliance service: values of the proto enums dify.saas.api.billing.CommonErrorReason and dify.saas.api.billing.BillingComplianceErrorReason, plus the reasons emitted by Kratos itself: CODEC and VALIDATOR (400), UNKNOWN (500, recovered panic) and an empty string (500, unclassified error).",+ "properties": {}+ },+ "BillingEducationErrorReason": {+ "enum": [+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "REQUEST_IN_PROGRESS",+ "MISSING_TENANT_ID",+ "INVALID_TENANT_ID",+ "MISSING_ACCOUNT_ID",+ "INVALID_ACCOUNT_ID",+ "MISSING_PREFILLED_EMAIL",+ "EDUCATION_VERIFY_FAILED",+ "EDUCATION_CREATE_FAILED",+ "EDUCATION_STATUS_FAILED"+ ],+ "type": "string",+ "description": "Reasons returned by the BillingEducation service: values of the proto enums dify.saas.api.billing.CommonErrorReason and dify.saas.api.billing.BillingEducationErrorReason, plus the reasons emitted by Kratos itself: CODEC and VALIDATOR (400), UNKNOWN (500, recovered panic) and an empty string (500, unclassified error).",+ "properties": {}+ },+ "BillingInvoiceErrorReason": {+ "enum": [+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "REQUEST_IN_PROGRESS",+ "MISSING_TENANT_ID",+ "INVALID_TENANT_ID",+ "MISSING_ACCOUNT_ID",+ "INVALID_ACCOUNT_ID",+ "MISSING_PREFILLED_EMAIL",+ "INVALID_INVOICE_REQUEST",+ "CREATE_INVOICE_PORTAL_FAILED"+ ],+ "type": "string",+ "description": "Reasons returned by the BillingInvoice service: values of the proto enums dify.saas.api.billing.CommonErrorReason and dify.saas.api.billing.BillingInvoiceErrorReason, plus the reasons emitted by Kratos itself: CODEC and VALIDATOR (400), UNKNOWN (500, recovered panic) and an empty string (500, unclassified error).",+ "properties": {}+ },+ "BillingModelProviderErrorReason": {+ "enum": [+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "REQUEST_IN_PROGRESS",+ "MISSING_TENANT_ID",+ "INVALID_TENANT_ID",+ "MISSING_ACCOUNT_ID",+ "INVALID_ACCOUNT_ID",+ "MISSING_PREFILLED_EMAIL",+ "INVALID_MODEL_PROVIDER_PAYMENT_LINK_REQUEST",+ "MISSING_PROVIDER_NAME",+ "INVALID_MODEL_PROVIDER",+ "CREATE_MODEL_PROVIDER_PAYMENT_LINK_FAILED"+ ],+ "type": "string",+ "description": "Reasons returned by the BillingModelProvider service: values of the proto enums dify.saas.api.billing.CommonErrorReason and dify.saas.api.billing.BillingModelProviderErrorReason, plus the reasons emitted by Kratos itself: CODEC and VALIDATOR (400), UNKNOWN (500, recovered panic) and an empty string (500, unclassified error).",+ "properties": {}+ },+ "BillingQuotaErrorReason": {+ "enum": [+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "REQUEST_IN_PROGRESS",+ "MISSING_TENANT_ID",+ "INVALID_TENANT_ID",+ "MISSING_ACCOUNT_ID",+ "INVALID_ACCOUNT_ID",+ "MISSING_PREFILLED_EMAIL"+ ],+ "type": "string",+ "description": "Reasons returned by the BillingQuota service: values of the proto enum dify.saas.api.billing.CommonErrorReason, plus the reasons emitted by Kratos itself: CODEC and VALIDATOR (400), UNKNOWN (500, recovered panic) and an empty string (500, unclassified error).",+ "properties": {}+ },+ "BillingSubscriptionErrorReason": {+ "enum": [+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "REQUEST_IN_PROGRESS",+ "MISSING_TENANT_ID",+ "INVALID_TENANT_ID",+ "MISSING_ACCOUNT_ID",+ "INVALID_ACCOUNT_ID",+ "MISSING_PREFILLED_EMAIL",+ "INVALID_PAYMENT_LINK_REQUEST",+ "MISSING_PLAN",+ "MISSING_INTERVAL",+ "INVALID_PLAN_INTERVAL",+ "CREATE_SUBSCRIPTION_PAYMENT_LINK_FAILED",+ "INVALID_KNOWLEDGE_RATE_LIMIT_REQUEST",+ "TENANT_IDS_COUNT_TOO_LARGE",+ "DOCUMENT_USAGE_UNAVAILABLE"+ ],+ "type": "string",+ "description": "Reasons returned by the BillingSubscription service: values of the proto enums dify.saas.api.billing.CommonErrorReason and dify.saas.api.billing.BillingSubscriptionErrorReason, plus the reasons emitted by Kratos itself: CODEC and VALIDATOR (400), UNKNOWN (500, recovered panic) and an empty string (500, unclassified error).",+ "properties": {}+ },"BillingSubscriptionPlan": {"type": "object","properties": {@@ -844,7 +976,8 @@"format": "int32"},"reason": {- "$ref": "#/components/schemas/ErrorReason"+ "type": "string",+ "description": "Error reason. The possible values for an operation are listed in the dify.saas.api.billing.<Service>ErrorReason schema of its service, where <Service> is the operationId prefix before the underscore."},"message": {"type": "string"@@ -858,85 +991,6 @@},"description": "Error body returned with every non-2xx response."},- "ErrorReason": {- "enum": [- "",- "CODEC",- "VALIDATOR",- "UNKNOWN",- "INVALID_SECRET_KEY",- "REQUEST_IN_PROGRESS",- "MISSING_TENANT_ID",- "INVALID_TENANT_ID",- "MISSING_ACCOUNT_ID",- "INVALID_ACCOUNT_ID",- "MISSING_PREFILLED_EMAIL",- "INVALID_PAYMENT_LINK_REQUEST",- "MISSING_PLAN",- "MISSING_INTERVAL",- "INVALID_PLAN_INTERVAL",- "CREATE_SUBSCRIPTION_PAYMENT_LINK_FAILED",- "INVALID_KNOWLEDGE_RATE_LIMIT_REQUEST",- "TENANT_IDS_COUNT_TOO_LARGE",- "DOCUMENT_USAGE_UNAVAILABLE",- "EDUCATION_VERIFY_FAILED",- "EDUCATION_CREATE_FAILED",- "EDUCATION_STATUS_FAILED",- "INVALID_INVOICE_REQUEST",- "CREATE_INVOICE_PORTAL_FAILED",- "INVALID_COMPLIANCE_DOWNLOAD_REQUEST",- "MISSING_DOC_NAME",- "MISSING_IP_ADDRESS",- "MISSING_DEVICE_INFO",- "COMPLIANCE_DOCUMENT_NOT_FOUND",- "COMPLIANCE_DOWNLOAD_FORBIDDEN",- "COMPLIANCE_DOWNLOAD_FAILED",- "INVALID_MODEL_PROVIDER_PAYMENT_LINK_REQUEST",- "MISSING_PROVIDER_NAME",- "INVALID_MODEL_PROVIDER",- "CREATE_MODEL_PROVIDER_PAYMENT_LINK_FAILED",- "BILLING_COUPON_AMOUNT_OFF_INVALID",- "BILLING_COUPON_CURRENCY_INVALID",- "BILLING_COUPON_DISCOUNT_TYPE_INVALID",- "BILLING_COUPON_DURATION_MISMATCH",- "BILLING_COUPON_DURATION_MONTHS_INVALID",- "BILLING_COUPON_DURATION_MONTHS_MISMATCH",- "BILLING_COUPON_DURATION_UNSUPPORTED",- "BILLING_COUPON_EXPIRES_AFTER_COUPON",- "BILLING_COUPON_EXPIRES_AT_INVALID",- "BILLING_COUPON_ID_EMPTY",- "BILLING_COUPON_NOT_FOUND",- "BILLING_COUPON_PERCENT_OFF_INVALID",- "BILLING_COUPON_PRODUCT_NOT_FOUND",- "BILLING_COUPON_PRODUCT_PRICE_NOT_CONFIGURED",- "BILLING_COUPON_PRODUCT_SCOPE_INVALID",- "BILLING_COUPON_PRODUCT_SCOPE_MISMATCH",- "BILLING_COUPON_PRODUCT_SERVICE_NOT_CONFIGURED",- "BILLING_COUPON_PROMOTION_CODE_INVALID",- "BILLING_COUPON_QUANTITY_INVALID",- "BILLING_COUPON_QUANTITY_TOO_LARGE",- "BILLING_COUPON_STRIPE_NOT_CONFIGURED",- "BILLING_COUPON_TASK_ID_REQUIRED",- "BILLING_COUPON_TASK_NOT_CONFIGURED",- "BILLING_COUPON_TASK_NOT_FOUND",- "BILLING_COUPON_TASK_PUBLISHER_NOT_CONFIGURED",- "BILLING_COUPON_TASK_REPO_NOT_CONFIGURED",- "BILLING_COUPON_TICKET_ID_REQUIRED",- "BILLING_COUPON_USAGE_REPO_NOT_CONFIGURED",- "BILLING_REFUND_AMOUNT_INVALID",- "BILLING_REFUND_INVOICE_MISMATCH",- "BILLING_REFUND_INVOICE_NOT_FOUND",- "BILLING_REFUND_MODE_INVALID",- "BILLING_REFUND_NOT_REFUNDABLE",- "BILLING_REFUND_PAYMENT_NOT_FOUND",- "BILLING_REFUND_STRIPE_STATUS_NOT_FOUND",- "BILLING_REFUND_SUBSCRIPTION_NOT_FOUND",- "BILLING_REFUND_TICKET_ID_REQUIRED"- ],- "type": "string",- "description": "Values of dify.saas.api.billing.ErrorReason, plus the reasons emitted by Kratos itself: CODEC and VALIDATOR (400), UNKNOWN (500, recovered panic) and an empty string (500, unclassified error).",- "properties": {}- },"GetEducationIdentityStatusReply": {"type": "object","properties": {diff --git a/api/services/billing_client/billing.py b/api/services/billing_client/billing.pyindex 4c3689b6f70..bdf0dfc2575 100644--- a/api/services/billing_client/billing.py+++ b/api/services/billing_client/billing.py@@ -1,5 +1,5 @@# Code generated by api/dev/generate_billing_client.py from billing.openapi.json. DO NOT EDIT.-# dify-saas commit: 04f8d88cc15c5f62f14f8843a54f3e2e7e09ee5a+# dify-saas commit: 2d358b5a0555440b30d8601f5e786a15e28a2345from datetime import datetimefrom typing import Literal, TypeIs, get_args@@ -33,6 +33,120 @@ class BatchGetSubscriptionPlanReq(BillingModel):tenant_ids: list[str]+type BillingComplianceErrorReason = Literal[+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "REQUEST_IN_PROGRESS",+ "MISSING_TENANT_ID",+ "INVALID_TENANT_ID",+ "MISSING_ACCOUNT_ID",+ "INVALID_ACCOUNT_ID",+ "MISSING_PREFILLED_EMAIL",+ "INVALID_COMPLIANCE_DOWNLOAD_REQUEST",+ "MISSING_DOC_NAME",+ "MISSING_IP_ADDRESS",+ "MISSING_DEVICE_INFO",+ "COMPLIANCE_DOCUMENT_NOT_FOUND",+ "COMPLIANCE_DOWNLOAD_FORBIDDEN",+ "COMPLIANCE_DOWNLOAD_FAILED",+]+++type BillingEducationErrorReason = Literal[+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "REQUEST_IN_PROGRESS",+ "MISSING_TENANT_ID",+ "INVALID_TENANT_ID",+ "MISSING_ACCOUNT_ID",+ "INVALID_ACCOUNT_ID",+ "MISSING_PREFILLED_EMAIL",+ "EDUCATION_VERIFY_FAILED",+ "EDUCATION_CREATE_FAILED",+ "EDUCATION_STATUS_FAILED",+]+++type BillingInvoiceErrorReason = Literal[+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "REQUEST_IN_PROGRESS",+ "MISSING_TENANT_ID",+ "INVALID_TENANT_ID",+ "MISSING_ACCOUNT_ID",+ "INVALID_ACCOUNT_ID",+ "MISSING_PREFILLED_EMAIL",+ "INVALID_INVOICE_REQUEST",+ "CREATE_INVOICE_PORTAL_FAILED",+]+++type BillingModelProviderErrorReason = Literal[+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "REQUEST_IN_PROGRESS",+ "MISSING_TENANT_ID",+ "INVALID_TENANT_ID",+ "MISSING_ACCOUNT_ID",+ "INVALID_ACCOUNT_ID",+ "MISSING_PREFILLED_EMAIL",+ "INVALID_MODEL_PROVIDER_PAYMENT_LINK_REQUEST",+ "MISSING_PROVIDER_NAME",+ "INVALID_MODEL_PROVIDER",+ "CREATE_MODEL_PROVIDER_PAYMENT_LINK_FAILED",+]+++type BillingQuotaErrorReason = Literal[+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "REQUEST_IN_PROGRESS",+ "MISSING_TENANT_ID",+ "INVALID_TENANT_ID",+ "MISSING_ACCOUNT_ID",+ "INVALID_ACCOUNT_ID",+ "MISSING_PREFILLED_EMAIL",+]+++type BillingSubscriptionErrorReason = Literal[+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "REQUEST_IN_PROGRESS",+ "MISSING_TENANT_ID",+ "INVALID_TENANT_ID",+ "MISSING_ACCOUNT_ID",+ "INVALID_ACCOUNT_ID",+ "MISSING_PREFILLED_EMAIL",+ "INVALID_PAYMENT_LINK_REQUEST",+ "MISSING_PLAN",+ "MISSING_INTERVAL",+ "INVALID_PLAN_INTERVAL",+ "CREATE_SUBSCRIPTION_PAYMENT_LINK_FAILED",+ "INVALID_KNOWLEDGE_RATE_LIMIT_REQUEST",+ "TENANT_IDS_COUNT_TOO_LARGE",+ "DOCUMENT_USAGE_UNAVAILABLE",+]++class BillingSubscriptionPlan(BillingModel):plan: Literal["sandbox", "professional", "team"]interval: Literal["", "month", "year"]@@ -66,82 +180,6 @@ class DownloadComplianceDocumentReq(BillingModel):device_info: str-type ErrorReason = Literal[- "",- "CODEC",- "VALIDATOR",- "UNKNOWN",- "INVALID_SECRET_KEY",- "REQUEST_IN_PROGRESS",- "MISSING_TENANT_ID",- "INVALID_TENANT_ID",- "MISSING_ACCOUNT_ID",- "INVALID_ACCOUNT_ID",- "MISSING_PREFILLED_EMAIL",- "INVALID_PAYMENT_LINK_REQUEST",- "MISSING_PLAN",- "MISSING_INTERVAL",- "INVALID_PLAN_INTERVAL",- "CREATE_SUBSCRIPTION_PAYMENT_LINK_FAILED",- "INVALID_KNOWLEDGE_RATE_LIMIT_REQUEST",- "TENANT_IDS_COUNT_TOO_LARGE",- "DOCUMENT_USAGE_UNAVAILABLE",- "EDUCATION_VERIFY_FAILED",- "EDUCATION_CREATE_FAILED",- "EDUCATION_STATUS_FAILED",- "INVALID_INVOICE_REQUEST",- "CREATE_INVOICE_PORTAL_FAILED",- "INVALID_COMPLIANCE_DOWNLOAD_REQUEST",- "MISSING_DOC_NAME",- "MISSING_IP_ADDRESS",- "MISSING_DEVICE_INFO",- "COMPLIANCE_DOCUMENT_NOT_FOUND",- "COMPLIANCE_DOWNLOAD_FORBIDDEN",- "COMPLIANCE_DOWNLOAD_FAILED",- "INVALID_MODEL_PROVIDER_PAYMENT_LINK_REQUEST",- "MISSING_PROVIDER_NAME",- "INVALID_MODEL_PROVIDER",- "CREATE_MODEL_PROVIDER_PAYMENT_LINK_FAILED",- "BILLING_COUPON_AMOUNT_OFF_INVALID",- "BILLING_COUPON_CURRENCY_INVALID",- "BILLING_COUPON_DISCOUNT_TYPE_INVALID",- "BILLING_COUPON_DURATION_MISMATCH",- "BILLING_COUPON_DURATION_MONTHS_INVALID",- "BILLING_COUPON_DURATION_MONTHS_MISMATCH",- "BILLING_COUPON_DURATION_UNSUPPORTED",- "BILLING_COUPON_EXPIRES_AFTER_COUPON",- "BILLING_COUPON_EXPIRES_AT_INVALID",- "BILLING_COUPON_ID_EMPTY",- "BILLING_COUPON_NOT_FOUND",- "BILLING_COUPON_PERCENT_OFF_INVALID",- "BILLING_COUPON_PRODUCT_NOT_FOUND",- "BILLING_COUPON_PRODUCT_PRICE_NOT_CONFIGURED",- "BILLING_COUPON_PRODUCT_SCOPE_INVALID",- "BILLING_COUPON_PRODUCT_SCOPE_MISMATCH",- "BILLING_COUPON_PRODUCT_SERVICE_NOT_CONFIGURED",- "BILLING_COUPON_PROMOTION_CODE_INVALID",- "BILLING_COUPON_QUANTITY_INVALID",- "BILLING_COUPON_QUANTITY_TOO_LARGE",- "BILLING_COUPON_STRIPE_NOT_CONFIGURED",- "BILLING_COUPON_TASK_ID_REQUIRED",- "BILLING_COUPON_TASK_NOT_CONFIGURED",- "BILLING_COUPON_TASK_NOT_FOUND",- "BILLING_COUPON_TASK_PUBLISHER_NOT_CONFIGURED",- "BILLING_COUPON_TASK_REPO_NOT_CONFIGURED",- "BILLING_COUPON_TICKET_ID_REQUIRED",- "BILLING_COUPON_USAGE_REPO_NOT_CONFIGURED",- "BILLING_REFUND_AMOUNT_INVALID",- "BILLING_REFUND_INVOICE_MISMATCH",- "BILLING_REFUND_INVOICE_NOT_FOUND",- "BILLING_REFUND_MODE_INVALID",- "BILLING_REFUND_NOT_REFUNDABLE",- "BILLING_REFUND_PAYMENT_NOT_FOUND",- "BILLING_REFUND_STRIPE_STATUS_NOT_FOUND",- "BILLING_REFUND_SUBSCRIPTION_NOT_FOUND",- "BILLING_REFUND_TICKET_ID_REQUIRED",-]--class GetEducationIdentityStatusReply(BillingModel):result: boolis_student: bool@@ -295,34 +333,207 @@ class VerifyEducationIdentityReply(BillingModel):status: Literal["eligible", "not_eligible"]-def _is_error_reason(value: str) -> TypeIs[ErrorReason]:- return value in get_args(ErrorReason.__value__)+def _is_billing_subscription_error_reason(value: str) -> TypeIs[BillingSubscriptionErrorReason]:+ return value in get_args(BillingSubscriptionErrorReason.__value__)+++class BillingSubscriptionUpstreamError(BillingUpstreamError):+ """A failed BillingSubscription call, with its reason typed by `BillingSubscriptionErrorReason`."""++ def __init__(+ self,+ *args: object,+ status_code: int | None = None,+ body: UpstreamErrorBody | None = None,+ reason: BillingSubscriptionErrorReason | UnknownErrorReason | None = None,+ ) -> None:+ super().__init__(*args, status_code=status_code, body=body)+ self.reason = reason+++class BillingSubscriptionUpstreamUnavailableError(BillingSubscriptionUpstreamError, BillingUpstreamUnavailableError):+ pass+++class BillingSubscriptionUpstreamInvalidResponseError(+ BillingSubscriptionUpstreamError, BillingUpstreamInvalidResponseError+):+ pass+++BILLING_SUBSCRIPTION_ERRORS = ServiceErrors(+ is_reason=_is_billing_subscription_error_reason,+ unavailable=BillingSubscriptionUpstreamUnavailableError,+ invalid_response=BillingSubscriptionUpstreamInvalidResponseError,+)+++def _is_billing_model_provider_error_reason(value: str) -> TypeIs[BillingModelProviderErrorReason]:+ return value in get_args(BillingModelProviderErrorReason.__value__)+++class BillingModelProviderUpstreamError(BillingUpstreamError):+ """A failed BillingModelProvider call, with its reason typed by `BillingModelProviderErrorReason`."""++ def __init__(+ self,+ *args: object,+ status_code: int | None = None,+ body: UpstreamErrorBody | None = None,+ reason: BillingModelProviderErrorReason | UnknownErrorReason | None = None,+ ) -> None:+ super().__init__(*args, status_code=status_code, body=body)+ self.reason = reason+++class BillingModelProviderUpstreamUnavailableError(BillingModelProviderUpstreamError, BillingUpstreamUnavailableError):+ pass+++class BillingModelProviderUpstreamInvalidResponseError(+ BillingModelProviderUpstreamError, BillingUpstreamInvalidResponseError+):+ pass+++BILLING_MODEL_PROVIDER_ERRORS = ServiceErrors(+ is_reason=_is_billing_model_provider_error_reason,+ unavailable=BillingModelProviderUpstreamUnavailableError,+ invalid_response=BillingModelProviderUpstreamInvalidResponseError,+)+++def _is_billing_invoice_error_reason(value: str) -> TypeIs[BillingInvoiceErrorReason]:+ return value in get_args(BillingInvoiceErrorReason.__value__)+++class BillingInvoiceUpstreamError(BillingUpstreamError):+ """A failed BillingInvoice call, with its reason typed by `BillingInvoiceErrorReason`."""++ def __init__(+ self,+ *args: object,+ status_code: int | None = None,+ body: UpstreamErrorBody | None = None,+ reason: BillingInvoiceErrorReason | UnknownErrorReason | None = None,+ ) -> None:+ super().__init__(*args, status_code=status_code, body=body)+ self.reason = reason+++class BillingInvoiceUpstreamUnavailableError(BillingInvoiceUpstreamError, BillingUpstreamUnavailableError):+ pass+++class BillingInvoiceUpstreamInvalidResponseError(BillingInvoiceUpstreamError, BillingUpstreamInvalidResponseError):+ pass+++BILLING_INVOICE_ERRORS = ServiceErrors(+ is_reason=_is_billing_invoice_error_reason,+ unavailable=BillingInvoiceUpstreamUnavailableError,+ invalid_response=BillingInvoiceUpstreamInvalidResponseError,+)+++def _is_billing_education_error_reason(value: str) -> TypeIs[BillingEducationErrorReason]:+ return value in get_args(BillingEducationErrorReason.__value__)+++class BillingEducationUpstreamError(BillingUpstreamError):+ """A failed BillingEducation call, with its reason typed by `BillingEducationErrorReason`."""++ def __init__(+ self,+ *args: object,+ status_code: int | None = None,+ body: UpstreamErrorBody | None = None,+ reason: BillingEducationErrorReason | UnknownErrorReason | None = None,+ ) -> None:+ super().__init__(*args, status_code=status_code, body=body)+ self.reason = reason+++class BillingEducationUpstreamUnavailableError(BillingEducationUpstreamError, BillingUpstreamUnavailableError):+ pass+++class BillingEducationUpstreamInvalidResponseError(BillingEducationUpstreamError, BillingUpstreamInvalidResponseError):+ pass+++BILLING_EDUCATION_ERRORS = ServiceErrors(+ is_reason=_is_billing_education_error_reason,+ unavailable=BillingEducationUpstreamUnavailableError,+ invalid_response=BillingEducationUpstreamInvalidResponseError,+)+++def _is_billing_compliance_error_reason(value: str) -> TypeIs[BillingComplianceErrorReason]:+ return value in get_args(BillingComplianceErrorReason.__value__)+++class BillingComplianceUpstreamError(BillingUpstreamError):+ """A failed BillingCompliance call, with its reason typed by `BillingComplianceErrorReason`."""++ def __init__(+ self,+ *args: object,+ status_code: int | None = None,+ body: UpstreamErrorBody | None = None,+ reason: BillingComplianceErrorReason | UnknownErrorReason | None = None,+ ) -> None:+ super().__init__(*args, status_code=status_code, body=body)+ self.reason = reason+++class BillingComplianceUpstreamUnavailableError(BillingComplianceUpstreamError, BillingUpstreamUnavailableError):+ pass+++class BillingComplianceUpstreamInvalidResponseError(+ BillingComplianceUpstreamError, BillingUpstreamInvalidResponseError+):+ pass+++BILLING_COMPLIANCE_ERRORS = ServiceErrors(+ is_reason=_is_billing_compliance_error_reason,+ unavailable=BillingComplianceUpstreamUnavailableError,+ invalid_response=BillingComplianceUpstreamInvalidResponseError,+)+++def _is_billing_quota_error_reason(value: str) -> TypeIs[BillingQuotaErrorReason]:+ return value in get_args(BillingQuotaErrorReason.__value__)-class UpstreamError(BillingUpstreamError):- """A failed billing call, with its reason typed by this module's `ErrorReason`."""+class BillingQuotaUpstreamError(BillingUpstreamError):+ """A failed BillingQuota call, with its reason typed by `BillingQuotaErrorReason`."""def __init__(self,*args: object,status_code: int | None = None,body: UpstreamErrorBody | None = None,- reason: ErrorReason | UnknownErrorReason | None = None,+ reason: BillingQuotaErrorReason | UnknownErrorReason | None = None,) -> None:super().__init__(*args, status_code=status_code, body=body)self.reason = reason-class UpstreamUnavailableError(UpstreamError, BillingUpstreamUnavailableError):+class BillingQuotaUpstreamUnavailableError(BillingQuotaUpstreamError, BillingUpstreamUnavailableError):pass-class UpstreamInvalidResponseError(UpstreamError, BillingUpstreamInvalidResponseError):+class BillingQuotaUpstreamInvalidResponseError(BillingQuotaUpstreamError, BillingUpstreamInvalidResponseError):pass-ERRORS = ServiceErrors(- is_reason=_is_error_reason, unavailable=UpstreamUnavailableError, invalid_response=UpstreamInvalidResponseError+BILLING_QUOTA_ERRORS = ServiceErrors(+ is_reason=_is_billing_quota_error_reason,+ unavailable=BillingQuotaUpstreamUnavailableError,+ invalid_response=BillingQuotaUpstreamInvalidResponseError,)@@ -333,7 +544,7 @@ def subscription_get_subscription_info(*, tenant_id: str, exclude_vector_space:"GET","/subscription/info",response_model=GetSubscriptionInfoReply,- errors=ERRORS,+ errors=BILLING_SUBSCRIPTION_ERRORS,path_params={},params={"tenant_id": tenant_id, "exclude_vector_space": exclude_vector_space},body=None,@@ -347,7 +558,7 @@ def subscription_get_subscription_vector_space(*, tenant_id: str, bypass_cache:"GET","/subscription/vector-space",response_model=VectorSpaceQuota,- errors=ERRORS,+ errors=BILLING_SUBSCRIPTION_ERRORS,path_params={},params={"tenant_id": tenant_id, "bypass_cache": bypass_cache},body=None,@@ -361,7 +572,7 @@ def subscription_get_knowledge_rate_limit(*, tenant_id: str) -> GetKnowledgeRate"GET","/subscription/knowledge-rate-limit",response_model=GetKnowledgeRateLimitReply,- errors=ERRORS,+ errors=BILLING_SUBSCRIPTION_ERRORS,path_params={},params={"tenant_id": tenant_id},body=None,@@ -377,7 +588,7 @@ def subscription_get_subscription_payment_link("GET","/subscription/payment-link",response_model=GetSubscriptionPaymentLinkReply,- errors=ERRORS,+ errors=BILLING_SUBSCRIPTION_ERRORS,path_params={},params={"plan": plan, "interval": interval, "prefilled_email": prefilled_email, "tenant_id": tenant_id},body=None,@@ -391,7 +602,7 @@ def subscription_batch_get_subscription_plan(*, body: BatchGetSubscriptionPlanRe"POST","/subscription/plan/batch",response_model=BatchGetSubscriptionPlanReply,- errors=ERRORS,+ errors=BILLING_SUBSCRIPTION_ERRORS,path_params={},params={},body=body,@@ -405,7 +616,7 @@ def subscription_list_subscription_cleanup_whitelist() -> ListSubscriptionCleanu"GET","/subscription/cleanup/whitelist",response_model=ListSubscriptionCleanupWhitelistReply,- errors=ERRORS,+ errors=BILLING_SUBSCRIPTION_ERRORS,path_params={},params={},body=None,@@ -421,7 +632,7 @@ def model_provider_get_model_provider_payment_link("GET","/model-provider/payment-link",response_model=GetModelProviderPaymentLinkReply,- errors=ERRORS,+ errors=BILLING_MODEL_PROVIDER_ERRORS,path_params={},params={"provider_name": provider_name,@@ -440,7 +651,7 @@ def invoice_get_invoices(*, prefilled_email: str, tenant_id: str) -> GetInvoices"GET","/invoices",response_model=GetInvoicesReply,- errors=ERRORS,+ errors=BILLING_INVOICE_ERRORS,path_params={},params={"prefilled_email": prefilled_email, "tenant_id": tenant_id},body=None,@@ -454,7 +665,7 @@ def education_verify_education_identity(*, account_id: str) -> VerifyEducationId"GET","/education/verify",response_model=VerifyEducationIdentityReply,- errors=ERRORS,+ errors=BILLING_EDUCATION_ERRORS,path_params={},params={"account_id": account_id},body=None,@@ -468,7 +679,7 @@ def education_get_education_identity_status(*, account_id: str) -> GetEducationI"GET","/education/status",response_model=GetEducationIdentityStatusReply,- errors=ERRORS,+ errors=BILLING_EDUCATION_ERRORS,path_params={},params={"account_id": account_id},body=None,@@ -482,7 +693,7 @@ def education_create_education_identity(*, body: CreateEducationIdentityReq) ->"POST","/education",response_model=CreateEducationIdentityReply,- errors=ERRORS,+ errors=BILLING_EDUCATION_ERRORS,path_params={},params={},body=body,@@ -498,7 +709,7 @@ def education_autocomplete_education_institution("GET","/education/autocomplete",response_model=AutocompleteEducationInstitutionReply,- errors=ERRORS,+ errors=BILLING_EDUCATION_ERRORS,path_params={},params={"keywords": keywords, "page": page, "limit": limit},body=None,@@ -512,7 +723,7 @@ def compliance_download_compliance_document(*, body: DownloadComplianceDocumentR"POST","/compliance/download",response_model=DownloadComplianceDocumentReply,- errors=ERRORS,+ errors=BILLING_COMPLIANCE_ERRORS,path_params={},params={},body=body,@@ -526,7 +737,7 @@ def quota_get_quota_info(*, tenant_id: str) -> QuotaGetInfoReply:"GET","/quota/info",response_model=QuotaGetInfoReply,- errors=ERRORS,+ errors=BILLING_QUOTA_ERRORS,path_params={},params={"tenant_id": tenant_id},body=None,@@ -540,7 +751,7 @@ def quota_reserve(*, body: QuotaReserveReq) -> QuotaReserveReply:"POST","/quota/reserve",response_model=QuotaReserveReply,- errors=ERRORS,+ errors=BILLING_QUOTA_ERRORS,path_params={},params={},body=body,@@ -554,7 +765,7 @@ def quota_commit(*, body: QuotaCommitReq) -> QuotaCommitReply:"POST","/quota/commit",response_model=QuotaCommitReply,- errors=ERRORS,+ errors=BILLING_QUOTA_ERRORS,path_params={},params={},body=body,@@ -568,7 +779,7 @@ def quota_release(*, body: QuotaReleaseReq) -> QuotaReleaseReply:"POST","/quota/release",response_model=QuotaReleaseReply,- errors=ERRORS,+ errors=BILLING_QUOTA_ERRORS,path_params={},params={},body=body,@@ -582,7 +793,7 @@ def quota_get_balance(*, tenant_id: str, feature_key: str, bucket: str) -> Quota"GET","/quota/balance",response_model=QuotaGetBalanceReply,- errors=ERRORS,+ errors=BILLING_QUOTA_ERRORS,path_params={},params={"tenant_id": tenant_id, "feature_key": feature_key, "bucket": bucket},body=None,@@ -596,7 +807,7 @@ def quota_consume_capped(*, body: QuotaConsumeCappedReq) -> QuotaConsumeCappedRe"POST","/quota/consume-capped",response_model=QuotaConsumeCappedReply,- errors=ERRORS,+ errors=BILLING_QUOTA_ERRORS,path_params={},params={},body=body,diff --git a/api/services/billing_client/saas.openapi.json b/api/services/billing_client/saas.openapi.jsonindex 0bd32e50654..83abcdc387b 100644--- a/api/services/billing_client/saas.openapi.json+++ b/api/services/billing_client/saas.openapi.json@@ -4,7 +4,7 @@"title": "","version": "0.0.1"},- "x-dify-saas-commit": "04f8d88cc15c5f62f14f8843a54f3e2e7e09ee5a",+ "x-dify-saas-commit": "2d358b5a0555440b30d8601f5e786a15e28a2345","paths": {"/v1/account": {"delete": {@@ -591,6 +591,18 @@},"components": {"schemas": {+ "AccountErrorReason": {+ "enum": [+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY"+ ],+ "type": "string",+ "description": "Reasons returned by the Account service: values of the proto enum dify.saas.api.saas.CommonErrorReason, plus the reasons emitted by Kratos itself: CODEC and VALIDATOR (400), UNKNOWN (500, recovered panic) and an empty string (500, unclassified error).",+ "properties": {}+ },"AddDeleteFeedbackReply": {"type": "object","properties": {@@ -801,7 +813,8 @@"format": "int32"},"reason": {- "$ref": "#/components/schemas/ErrorReason"+ "type": "string",+ "description": "Error reason. The possible values for an operation are listed in the dify.saas.api.saas.<Service>ErrorReason schema of its service, where <Service> is the operationId prefix before the underscore."},"message": {"type": "string"@@ -815,32 +828,6 @@},"description": "Error body returned with every non-2xx response."},- "ErrorReason": {- "enum": [- "",- "CODEC",- "VALIDATOR",- "UNKNOWN",- "INVALID_SECRET_KEY",- "INVALID_ARGUMENT",- "INTERNAL_ERROR",- "INVALID_NETWORK_ACCESS_INPUT",- "TENANT_NOT_FOUND",- "NETWORK_ACCESS_GROUP_NOT_FOUND",- "APP_NOT_FOUND",- "NETWORK_ACCESS_APP_STILL_EXISTS",- "TENANT_ARCHIVED",- "NETWORK_ACCESS_FORBIDDEN",- "NETWORK_ACCESS_NOT_ENTITLED",- "NETWORK_ACCESS_VERSION_CONFLICT",- "NETWORK_ACCESS_GROUP_NAME_CONFLICT",- "NETWORK_ACCESS_GROUP_BOUND",- "NETWORK_ACCESS_CACHE_UNAVAILABLE"- ],- "type": "string",- "description": "Values of dify.saas.api.saas.ErrorReason, plus the reasons emitted by Kratos itself: CODEC and VALIDATOR (400), UNKNOWN (500, recovered panic) and an empty string (500, unclassified error).",- "properties": {}- },"GetAccountNotificationReply": {"type": "object","properties": {@@ -1154,6 +1141,44 @@"accessPoints"]},+ "SaasNetworkAccessPolicyErrorReason": {+ "enum": [+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "INVALID_ARGUMENT",+ "INTERNAL_ERROR",+ "INVALID_NETWORK_ACCESS_INPUT",+ "TENANT_NOT_FOUND",+ "NETWORK_ACCESS_GROUP_NOT_FOUND",+ "APP_NOT_FOUND",+ "NETWORK_ACCESS_APP_STILL_EXISTS",+ "TENANT_ARCHIVED",+ "NETWORK_ACCESS_FORBIDDEN",+ "NETWORK_ACCESS_NOT_ENTITLED",+ "NETWORK_ACCESS_VERSION_CONFLICT",+ "NETWORK_ACCESS_GROUP_NAME_CONFLICT",+ "NETWORK_ACCESS_GROUP_BOUND",+ "NETWORK_ACCESS_CACHE_UNAVAILABLE"+ ],+ "type": "string",+ "description": "Reasons returned by the SaasNetworkAccessPolicy service: values of the proto enums dify.saas.api.saas.CommonErrorReason and dify.saas.api.saas.SaasNetworkAccessPolicyErrorReason, plus the reasons emitted by Kratos itself: CODEC and VALIDATOR (400), UNKNOWN (500, recovered panic) and an empty string (500, unclassified error).",+ "properties": {}+ },+ "SaasNotificationErrorReason": {+ "enum": [+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY"+ ],+ "type": "string",+ "description": "Reasons returned by the SaasNotification service: values of the proto enum dify.saas.api.saas.CommonErrorReason, plus the reasons emitted by Kratos itself: CODEC and VALIDATOR (400), UNKNOWN (500, recovered panic) and an empty string (500, unclassified error).",+ "properties": {}+ },"TenantUtmReply": {"type": "object","properties": {@@ -1239,6 +1264,18 @@"expectedVersion","actorAccountId"]+ },+ "UtmErrorReason": {+ "enum": [+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY"+ ],+ "type": "string",+ "description": "Reasons returned by the Utm service: values of the proto enum dify.saas.api.saas.CommonErrorReason, plus the reasons emitted by Kratos itself: CODEC and VALIDATOR (400), UNKNOWN (500, recovered panic) and an empty string (500, unclassified error).",+ "properties": {}}}}diff --git a/api/services/billing_client/saas.py b/api/services/billing_client/saas.pyindex 4e66ca4b3b5..0895898d50c 100644--- a/api/services/billing_client/saas.py+++ b/api/services/billing_client/saas.py@@ -1,5 +1,5 @@# Code generated by api/dev/generate_billing_client.py from saas.openapi.json. DO NOT EDIT.-# dify-saas commit: 04f8d88cc15c5f62f14f8843a54f3e2e7e09ee5a+# dify-saas commit: 2d358b5a0555440b30d8601f5e786a15e28a2345from datetime import datetimefrom typing import Literal, TypeIs, get_args@@ -15,6 +15,8 @@ from services.errors.billing import (UpstreamErrorBody,)+type AccountErrorReason = Literal["", "CODEC", "VALIDATOR", "UNKNOWN", "INVALID_SECRET_KEY"]+class AddDeleteFeedbackReply(BillingModel):message: str@@ -73,29 +75,6 @@ class DismissNotificationReq(BillingModel):account_id: str = Field(alias="accountId")-type ErrorReason = Literal[- "",- "CODEC",- "VALIDATOR",- "UNKNOWN",- "INVALID_SECRET_KEY",- "INVALID_ARGUMENT",- "INTERNAL_ERROR",- "INVALID_NETWORK_ACCESS_INPUT",- "TENANT_NOT_FOUND",- "NETWORK_ACCESS_GROUP_NOT_FOUND",- "APP_NOT_FOUND",- "NETWORK_ACCESS_APP_STILL_EXISTS",- "TENANT_ARCHIVED",- "NETWORK_ACCESS_FORBIDDEN",- "NETWORK_ACCESS_NOT_ENTITLED",- "NETWORK_ACCESS_VERSION_CONFLICT",- "NETWORK_ACCESS_GROUP_NAME_CONFLICT",- "NETWORK_ACCESS_GROUP_BOUND",- "NETWORK_ACCESS_CACHE_UNAVAILABLE",-]--class LangContent(BillingModel):lang: strtitle: str@@ -172,6 +151,32 @@ class PutAppNetworkAccessGroupRequest(BillingModel):access_points: list[str] = Field(alias="accessPoints")+type SaasNetworkAccessPolicyErrorReason = Literal[+ "",+ "CODEC",+ "VALIDATOR",+ "UNKNOWN",+ "INVALID_SECRET_KEY",+ "INVALID_ARGUMENT",+ "INTERNAL_ERROR",+ "INVALID_NETWORK_ACCESS_INPUT",+ "TENANT_NOT_FOUND",+ "NETWORK_ACCESS_GROUP_NOT_FOUND",+ "APP_NOT_FOUND",+ "NETWORK_ACCESS_APP_STILL_EXISTS",+ "TENANT_ARCHIVED",+ "NETWORK_ACCESS_FORBIDDEN",+ "NETWORK_ACCESS_NOT_ENTITLED",+ "NETWORK_ACCESS_VERSION_CONFLICT",+ "NETWORK_ACCESS_GROUP_NAME_CONFLICT",+ "NETWORK_ACCESS_GROUP_BOUND",+ "NETWORK_ACCESS_CACHE_UNAVAILABLE",+]+++type SaasNotificationErrorReason = Literal["", "CODEC", "VALIDATOR", "UNKNOWN", "INVALID_SECRET_KEY"]++class TenantUtmReply(BillingModel):result: str@@ -196,34 +201,142 @@ class UpdateNetworkAccessGroupRequest(BillingModel):actor_account_id: str = Field(alias="actorAccountId")-def _is_error_reason(value: str) -> TypeIs[ErrorReason]:- return value in get_args(ErrorReason.__value__)+type UtmErrorReason = Literal["", "CODEC", "VALIDATOR", "UNKNOWN", "INVALID_SECRET_KEY"]+++def _is_account_error_reason(value: str) -> TypeIs[AccountErrorReason]:+ return value in get_args(AccountErrorReason.__value__)+++class AccountUpstreamError(BillingUpstreamError):+ """A failed Account call, with its reason typed by `AccountErrorReason`."""++ def __init__(+ self,+ *args: object,+ status_code: int | None = None,+ body: UpstreamErrorBody | None = None,+ reason: AccountErrorReason | UnknownErrorReason | None = None,+ ) -> None:+ super().__init__(*args, status_code=status_code, body=body)+ self.reason = reason+++class AccountUpstreamUnavailableError(AccountUpstreamError, BillingUpstreamUnavailableError):+ pass+++class AccountUpstreamInvalidResponseError(AccountUpstreamError, BillingUpstreamInvalidResponseError):+ pass+++ACCOUNT_ERRORS = ServiceErrors(+ is_reason=_is_account_error_reason,+ unavailable=AccountUpstreamUnavailableError,+ invalid_response=AccountUpstreamInvalidResponseError,+)+++def _is_saas_notification_error_reason(value: str) -> TypeIs[SaasNotificationErrorReason]:+ return value in get_args(SaasNotificationErrorReason.__value__)+++class SaasNotificationUpstreamError(BillingUpstreamError):+ """A failed SaasNotification call, with its reason typed by `SaasNotificationErrorReason`."""++ def __init__(+ self,+ *args: object,+ status_code: int | None = None,+ body: UpstreamErrorBody | None = None,+ reason: SaasNotificationErrorReason | UnknownErrorReason | None = None,+ ) -> None:+ super().__init__(*args, status_code=status_code, body=body)+ self.reason = reason+++class SaasNotificationUpstreamUnavailableError(SaasNotificationUpstreamError, BillingUpstreamUnavailableError):+ pass+++class SaasNotificationUpstreamInvalidResponseError(SaasNotificationUpstreamError, BillingUpstreamInvalidResponseError):+ pass+++SAAS_NOTIFICATION_ERRORS = ServiceErrors(+ is_reason=_is_saas_notification_error_reason,+ unavailable=SaasNotificationUpstreamUnavailableError,+ invalid_response=SaasNotificationUpstreamInvalidResponseError,+)+++def _is_utm_error_reason(value: str) -> TypeIs[UtmErrorReason]:+ return value in get_args(UtmErrorReason.__value__)+++class UtmUpstreamError(BillingUpstreamError):+ """A failed Utm call, with its reason typed by `UtmErrorReason`."""++ def __init__(+ self,+ *args: object,+ status_code: int | None = None,+ body: UpstreamErrorBody | None = None,+ reason: UtmErrorReason | UnknownErrorReason | None = None,+ ) -> None:+ super().__init__(*args, status_code=status_code, body=body)+ self.reason = reason+++class UtmUpstreamUnavailableError(UtmUpstreamError, BillingUpstreamUnavailableError):+ pass+++class UtmUpstreamInvalidResponseError(UtmUpstreamError, BillingUpstreamInvalidResponseError):+ pass+++UTM_ERRORS = ServiceErrors(+ is_reason=_is_utm_error_reason,+ unavailable=UtmUpstreamUnavailableError,+ invalid_response=UtmUpstreamInvalidResponseError,+)+++def _is_saas_network_access_policy_error_reason(value: str) -> TypeIs[SaasNetworkAccessPolicyErrorReason]:+ return value in get_args(SaasNetworkAccessPolicyErrorReason.__value__)-class UpstreamError(BillingUpstreamError):- """A failed saas call, with its reason typed by this module's `ErrorReason`."""+class SaasNetworkAccessPolicyUpstreamError(BillingUpstreamError):+ """A failed SaasNetworkAccessPolicy call, with its reason typed by `SaasNetworkAccessPolicyErrorReason`."""def __init__(self,*args: object,status_code: int | None = None,body: UpstreamErrorBody | None = None,- reason: ErrorReason | UnknownErrorReason | None = None,+ reason: SaasNetworkAccessPolicyErrorReason | UnknownErrorReason | None = None,) -> None:super().__init__(*args, status_code=status_code, body=body)self.reason = reason-class UpstreamUnavailableError(UpstreamError, BillingUpstreamUnavailableError):+class SaasNetworkAccessPolicyUpstreamUnavailableError(+ SaasNetworkAccessPolicyUpstreamError, BillingUpstreamUnavailableError+):pass-class UpstreamInvalidResponseError(UpstreamError, BillingUpstreamInvalidResponseError):+class SaasNetworkAccessPolicyUpstreamInvalidResponseError(+ SaasNetworkAccessPolicyUpstreamError, BillingUpstreamInvalidResponseError+):pass-ERRORS = ServiceErrors(- is_reason=_is_error_reason, unavailable=UpstreamUnavailableError, invalid_response=UpstreamInvalidResponseError+SAAS_NETWORK_ACCESS_POLICY_ERRORS = ServiceErrors(+ is_reason=_is_saas_network_access_policy_error_reason,+ unavailable=SaasNetworkAccessPolicyUpstreamUnavailableError,+ invalid_response=SaasNetworkAccessPolicyUpstreamInvalidResponseError,)@@ -234,7 +347,7 @@ def account_delete_account(*, account_id: str) -> DeleteAccountReply:"DELETE","/account",response_model=DeleteAccountReply,- errors=ERRORS,+ errors=ACCOUNT_ERRORS,path_params={},params={"accountId": account_id},body=None,@@ -248,7 +361,7 @@ def account_check_account_in_freeze(*, email: str) -> CheckAccountInFreezeReply:"GET","/account/in-freeze",response_model=CheckAccountInFreezeReply,- errors=ERRORS,+ errors=ACCOUNT_ERRORS,path_params={},params={"email": email},body=None,@@ -262,7 +375,7 @@ def account_add_delete_feedback(*, body: AddDeleteFeedbackRequest) -> AddDeleteF"POST","/account/delete-feedback",response_model=AddDeleteFeedbackReply,- errors=ERRORS,+ errors=ACCOUNT_ERRORS,path_params={},params={},body=body,@@ -276,7 +389,7 @@ def notification_get_account_notification(*, account_id: str) -> GetAccountNotif"GET","/notifications/active",response_model=GetAccountNotificationReply,- errors=ERRORS,+ errors=SAAS_NOTIFICATION_ERRORS,path_params={},params={"accountId": account_id},body=None,@@ -292,7 +405,7 @@ def notification_dismiss_notification("POST","/notifications/{notification_id}/dismiss",response_model=DismissNotificationReply,- errors=ERRORS,+ errors=SAAS_NOTIFICATION_ERRORS,path_params={"notification_id": notification_id},params={},body=body,@@ -306,7 +419,7 @@ def utm_record_tenant_utm(*, body: TenantUtmRequest) -> TenantUtmReply:"POST","/tenant_utms",response_model=TenantUtmReply,- errors=ERRORS,+ errors=UTM_ERRORS,path_params={},params={},body=body,@@ -322,7 +435,7 @@ def network_access_policy_list_network_access_groups("GET","/tenants/{tenant_id}/network-access-groups",response_model=ListNetworkAccessGroupsReply,- errors=ERRORS,+ errors=SAAS_NETWORK_ACCESS_POLICY_ERRORS,path_params={"tenant_id": tenant_id},params={"actorAccountId": actor_account_id},body=None,@@ -338,7 +451,7 @@ def network_access_policy_create_network_access_group("POST","/tenants/{tenant_id}/network-access-groups",response_model=NetworkAccessGroupReply,- errors=ERRORS,+ errors=SAAS_NETWORK_ACCESS_POLICY_ERRORS,path_params={"tenant_id": tenant_id},params={},body=body,@@ -354,7 +467,7 @@ def network_access_policy_get_network_access_group("GET","/tenants/{tenant_id}/network-access-groups/{group_id}",response_model=NetworkAccessGroupReply,- errors=ERRORS,+ errors=SAAS_NETWORK_ACCESS_POLICY_ERRORS,path_params={"tenant_id": tenant_id, "group_id": group_id},params={"actorAccountId": actor_account_id},body=None,@@ -370,7 +483,7 @@ def network_access_policy_update_network_access_group("PUT","/tenants/{tenant_id}/network-access-groups/{group_id}",response_model=NetworkAccessGroupReply,- errors=ERRORS,+ errors=SAAS_NETWORK_ACCESS_POLICY_ERRORS,path_params={"tenant_id": tenant_id, "group_id": group_id},params={},body=body,@@ -389,7 +502,7 @@ def network_access_policy_delete_network_access_group("DELETE","/tenants/{tenant_id}/network-access-groups/{group_id}",response_model=DeleteNetworkAccessGroupReply,- errors=ERRORS,+ errors=SAAS_NETWORK_ACCESS_POLICY_ERRORS,path_params={"tenant_id": tenant_id, "group_id": group_id},params={"expectedVersion": expected_version, "actorAccountId": actor_account_id},body=None,@@ -408,7 +521,7 @@ def network_access_policy_get_app_network_access_group("GET","/tenants/{tenant_id}/apps/{app_id}/network-access-group",response_model=GetAppNetworkAccessGroupReply,- errors=ERRORS,+ errors=SAAS_NETWORK_ACCESS_POLICY_ERRORS,path_params={"tenant_id": tenant_id, "app_id": app_id},params={"actorAccountId": actor_account_id},body=None,@@ -427,7 +540,7 @@ def network_access_policy_put_app_network_access_group("PUT","/tenants/{tenant_id}/apps/{app_id}/network-access-group",response_model=PutAppNetworkAccessGroupReply,- errors=ERRORS,+ errors=SAAS_NETWORK_ACCESS_POLICY_ERRORS,path_params={"tenant_id": tenant_id, "app_id": app_id},params={},body=body,@@ -446,7 +559,7 @@ def network_access_policy_get_app_network_access_group_status("GET","/tenants/{tenant_id}/apps/{app_id}/network-access-group/status",response_model=GetAppNetworkAccessGroupStatusReply,- errors=ERRORS,+ errors=SAAS_NETWORK_ACCESS_POLICY_ERRORS,path_params={"tenant_id": tenant_id, "app_id": app_id},params={"actorAccountId": actor_account_id},body=None,@@ -465,7 +578,7 @@ def network_access_policy_cleanup_app_network_access_group_binding("DELETE","/tenants/{tenant_id}/apps/{app_id}/network-access-group-binding",response_model=CleanupAppNetworkAccessGroupBindingReply,- errors=ERRORS,+ errors=SAAS_NETWORK_ACCESS_POLICY_ERRORS,path_params={"tenant_id": tenant_id, "app_id": app_id},params={},body=None,diff --git a/api/services/billing_client/transport.py b/api/services/billing_client/transport.pyindex e1296e189ec..f914bb9daca 100644--- a/api/services/billing_client/transport.py+++ b/api/services/billing_client/transport.py@@ -2,15 +2,16 @@This is the only module that reads the billing URLs and secret, and only the generated modulescall `request`; ruff's banned-api rule (TID251) rejects both anywhere else.-Network failures, timeouts, throttling, and 5xx raise the service's `UpstreamUnavailableError`-(a `BillingUpstreamUnavailableError`); any other non-200 status or an enforced response that-fails model validation raises its `UpstreamInvalidResponseError` (a-`BillingUpstreamInvalidResponseError`). Each generated module passes its own error types in-`ServiceErrors`. For a non-200 status, the error carries the status code, the parsed Kratos-error body, and its reason typed by the service's generated `ErrorReason`. A reason outside it-is kept as `UnknownErrorReason` and logged with `logger.error` (reported to Sentry): the service-shipped a reason before this client was regenerated. Callers map reasons to their own errors;-this module branches on none.+Each generated operation passes the `ServiceErrors` of its proto service. Network failures,+timeouts, throttling, and 5xx raise that service's `<Service>UpstreamUnavailableError` (a+`BillingUpstreamUnavailableError`); any other non-200 status or an enforced response that fails+model validation raises its `<Service>UpstreamInvalidResponseError` (a+`BillingUpstreamInvalidResponseError`). For a non-200 status, the error carries the status code,+the parsed Kratos error body, and its reason typed by the service's `<Service>ErrorReason`. A+reason outside it is kept as `UnknownErrorReason` and logged with `logger.error` (reported to+Sentry): either the billing service shipped a reason before this client was regenerated, or it+returned a reason outside the declared set of that service. Callers map reasons to their own+errors; this module branches on none.Response validation is observed before it is enforced. For a path not in`ENFORCED_RESPONSE_PATHS`, a body that fails validation is logged with `logger.exception`@@ -194,7 +195,8 @@ def _error_details(if is_reason(reason):return body, reasonlogger.error(- "Unknown %s error reason %s from %s %s; regenerate the billing client",+ "Unknown %s error reason %s from %s %s: regenerate the billing client, "+ "or the billing service returned a reason outside this service's declared set",upstream,_NON_REASON_CHARACTERS.sub("", reason)[:64],method,diff --git a/api/services/errors/billing.py b/api/services/errors/billing.pyindex 0f6420cc459..2619bd04d22 100644--- a/api/services/errors/billing.py+++ b/api/services/errors/billing.py@@ -45,9 +45,9 @@ class UnknownErrorReason:class BillingUpstreamError(BillingError):"""A billing or saas call failed.- `status_code` and `body` are set when the upstream answered with a non-200 status. Each- generated service module subclasses this with a `reason` typed by its own `ErrorReason`;- catch that subclass to read the reason.+ `status_code` and `body` are set when the upstream answered with a non-200 status. The+ generated modules subclass this per proto service with a `reason` typed by that service's+ `<Service>ErrorReason`; catch that subclass to read the reason."""def __init__(self, *args: object, status_code: int | None = None, body: UpstreamErrorBody | None = None) -> None:diff --git a/api/services/network_access_group_gateway.py b/api/services/network_access_group_gateway.pyindex 6def0216980..f8734b4ab3c 100644--- a/api/services/network_access_group_gateway.py+++ b/api/services/network_access_group_gateway.py@@ -38,7 +38,7 @@ from services.network_access_group_service import ()-def _control_plane_error(exc: saas.UpstreamError) -> NetworkAccessGroupError:+def _control_plane_error(exc: saas.SaasNetworkAccessPolicyUpstreamError) -> NetworkAccessGroupError:match exc.reason:case "VALIDATOR" | "INVALID_ARGUMENT" | "INVALID_NETWORK_ACCESS_INPUT":return NetworkAccessGroupInvalidInputError()@@ -79,7 +79,7 @@ def _upstream_errors() -> Generator[None]:"""Map saas failures to the service's errors by their Kratos reason."""try:yield- except saas.UpstreamError as exc:+ except saas.SaasNetworkAccessPolicyUpstreamError as exc:if exc.status_code is None and not isinstance(exc, BillingUpstreamUnavailableError):raise NetworkAccessGroupInvalidResponseError from excraise _control_plane_error(exc) from excdiff --git a/api/tests/unit_tests/controllers/console/billing/test_billing.py b/api/tests/unit_tests/controllers/console/billing/test_billing.pyindex a8303797f72..f4db86464e1 100644--- a/api/tests/unit_tests/controllers/console/billing/test_billing.py+++ b/api/tests/unit_tests/controllers/console/billing/test_billing.py@@ -94,7 +94,7 @@ class TestBillingPortal:) -> None:resource = Invoices()method = unwrap(resource.get)- billing_portal.get_invoices.side_effect = billing.UpstreamUnavailableError+ billing_portal.get_invoices.side_effect = billing.BillingInvoiceUpstreamUnavailableErrorwith app.test_request_context("/billing/invoices"):with pytest.raises(BillingUnavailableError) as exc_info:@@ -115,7 +115,7 @@ class TestBillingPortal:resource = Subscription()method = unwrap(resource.get)query = SubscriptionQuery(plan=CloudPlan.PROFESSIONAL, interval="month")- billing_portal.get_subscription.side_effect = billing.UpstreamInvalidResponseError+ billing_portal.get_subscription.side_effect = billing.BillingSubscriptionUpstreamInvalidResponseErrorwith app.test_request_context("/billing/subscription"):with pytest.raises(BillingOperationFailedError) as exc_info:@@ -130,20 +130,34 @@ class TestBillingPortal:@pytest.mark.parametrize(("error", "expected"),[- (billing.UpstreamInvalidResponseError(status_code=400, reason="MISSING_PLAN"), BillingOperationFailedError),(- billing.UpstreamUnavailableError(status_code=500, reason="CREATE_SUBSCRIPTION_PAYMENT_LINK_FAILED"),+ billing.BillingSubscriptionUpstreamInvalidResponseError(status_code=400, reason="MISSING_PLAN"),+ BillingOperationFailedError,+ ),+ (+ billing.BillingSubscriptionUpstreamUnavailableError(+ status_code=500, reason="CREATE_SUBSCRIPTION_PAYMENT_LINK_FAILED"+ ),+ BillingUnavailableError,+ ),+ (+ billing.BillingSubscriptionUpstreamUnavailableError(status_code=429, reason="REQUEST_IN_PROGRESS"),BillingUnavailableError,),- (billing.UpstreamUnavailableError(status_code=429, reason="REQUEST_IN_PROGRESS"), BillingUnavailableError),(- billing.UpstreamInvalidResponseError(status_code=409, reason=UnknownErrorReason("PLAN_SHIPPED_LATER")),+ billing.BillingSubscriptionUpstreamInvalidResponseError(+ status_code=409, reason=UnknownErrorReason("PLAN_SHIPPED_LATER")+ ),BillingOperationFailedError,),(- billing.UpstreamUnavailableError(status_code=503, reason=UnknownErrorReason("PLAN_SHIPPED_LATER")),+ billing.BillingSubscriptionUpstreamUnavailableError(+ status_code=503, reason=UnknownErrorReason("PLAN_SHIPPED_LATER")+ ),BillingUnavailableError,),+ (billing.BillingSubscriptionUpstreamInvalidResponseError(status_code=400), BillingOperationFailedError),+ (billing.BillingSubscriptionUpstreamUnavailableError(), BillingUnavailableError),],)def test_get_subscription_maps_every_reason_to_a_generic_billing_error(@@ -151,7 +165,7 @@ class TestBillingPortal:app: Flask,request_context: RequestContext,billing_portal: MagicMock,- error: billing.UpstreamError,+ error: billing.BillingSubscriptionUpstreamError,expected: type[Exception],) -> None:resource = Subscription()@@ -163,3 +177,39 @@ class TestBillingPortal:)assert exc_info.value.__cause__ is error++ @pytest.mark.parametrize(+ ("error", "expected"),+ [+ (+ billing.BillingInvoiceUpstreamInvalidResponseError(status_code=400, reason="INVALID_INVOICE_REQUEST"),+ BillingOperationFailedError,+ ),+ (+ billing.BillingInvoiceUpstreamUnavailableError(status_code=500, reason="CREATE_INVOICE_PORTAL_FAILED"),+ BillingUnavailableError,+ ),+ (+ billing.BillingInvoiceUpstreamInvalidResponseError(+ status_code=409, reason=UnknownErrorReason("INVOICE_SHIPPED_LATER")+ ),+ BillingOperationFailedError,+ ),+ (billing.BillingInvoiceUpstreamUnavailableError(status_code=502), BillingUnavailableError),+ ],+ )+ def test_get_invoices_maps_every_reason_to_a_generic_billing_error(+ self,+ app: Flask,+ request_context: RequestContext,+ billing_portal: MagicMock,+ error: billing.BillingInvoiceUpstreamError,+ expected: type[Exception],+ ) -> None:+ resource = Invoices()+ billing_portal.get_invoices.side_effect = error++ with app.test_request_context("/billing/invoices"), pytest.raises(expected) as exc_info:+ unwrap(resource.get)(resource, request_context)++ assert exc_info.value.__cause__ is errordiff --git a/api/tests/unit_tests/controllers/console/billing/test_compliance.py b/api/tests/unit_tests/controllers/console/billing/test_compliance.pyindex 1fe8571ae82..9ed3bf874e0 100644--- a/api/tests/unit_tests/controllers/console/billing/test_compliance.py+++ b/api/tests/unit_tests/controllers/console/billing/test_compliance.py@@ -103,51 +103,57 @@ def test_get_compliance_download_translates_rate_limit(("error", "expected_code", "expected_status"),[(- billing.UpstreamInvalidResponseError(status_code=404, reason="COMPLIANCE_DOCUMENT_NOT_FOUND"),+ billing.BillingComplianceUpstreamInvalidResponseError(+ status_code=404, reason="COMPLIANCE_DOCUMENT_NOT_FOUND"+ ),"compliance_document_not_found",404,),(- billing.UpstreamInvalidResponseError(status_code=403, reason="COMPLIANCE_DOWNLOAD_FORBIDDEN"),+ billing.BillingComplianceUpstreamInvalidResponseError(+ status_code=403, reason="COMPLIANCE_DOWNLOAD_FORBIDDEN"+ ),"compliance_download_forbidden",403,),(- billing.UpstreamUnavailableError(status_code=429, reason="REQUEST_IN_PROGRESS"),+ billing.BillingComplianceUpstreamUnavailableError(status_code=429, reason="REQUEST_IN_PROGRESS"),"billing_request_in_progress",429,),(- billing.UpstreamUnavailableError(status_code=500, reason="COMPLIANCE_DOWNLOAD_FAILED"),+ billing.BillingComplianceUpstreamUnavailableError(status_code=500, reason="COMPLIANCE_DOWNLOAD_FAILED"),"billing_unavailable",503,),(- billing.UpstreamInvalidResponseError(status_code=400, reason="MISSING_DOC_NAME"),+ billing.BillingComplianceUpstreamInvalidResponseError(status_code=400, reason="MISSING_DOC_NAME"),"billing_operation_failed",502,),(- billing.UpstreamInvalidResponseError(+ billing.BillingComplianceUpstreamInvalidResponseError(status_code=403, reason=UnknownErrorReason("COMPLIANCE_SHIPPED_LATER")),"billing_operation_failed",502,),(- billing.UpstreamUnavailableError(status_code=503, reason=UnknownErrorReason("COMPLIANCE_SHIPPED_LATER")),+ billing.BillingComplianceUpstreamUnavailableError(+ status_code=503, reason=UnknownErrorReason("COMPLIANCE_SHIPPED_LATER")+ ),"billing_unavailable",503,),- (billing.UpstreamInvalidResponseError(status_code=404), "billing_operation_failed", 502),- (billing.UpstreamUnavailableError(), "billing_unavailable", 503),+ (billing.BillingComplianceUpstreamInvalidResponseError(status_code=404), "billing_operation_failed", 502),+ (billing.BillingComplianceUpstreamUnavailableError(), "billing_unavailable", 503),],)def test_get_compliance_download_maps_billing_reason(app: Flask,request_context: RequestContext,compliance_downloads: MagicMock,- error: billing.UpstreamError,+ error: billing.BillingComplianceUpstreamError,expected_code: str,expected_status: int,) -> None:diff --git a/api/tests/unit_tests/controllers/console/workspace/test_account.py b/api/tests/unit_tests/controllers/console/workspace/test_account.pyindex 3e4ffd5db63..eb5d01c42d1 100644--- a/api/tests/unit_tests/controllers/console/workspace/test_account.py+++ b/api/tests/unit_tests/controllers/console/workspace/test_account.py@@ -325,9 +325,15 @@ class TestWorkspaceAccountCases:[(account_errors.EducationVerificationFailedError(), "education_verify_failed", 400),(account_errors.EducationRequestInProgressError(), "billing_request_in_progress", 429),- (billing.UpstreamUnavailableError(status_code=500, reason=""), "billing_unavailable", 503),(- billing.UpstreamInvalidResponseError(status_code=400, reason=UnknownErrorReason("SHIPPED_LATER")),+ billing.BillingEducationUpstreamUnavailableError(status_code=500, reason=""),+ "billing_unavailable",+ 503,+ ),+ (+ billing.BillingEducationUpstreamInvalidResponseError(+ status_code=400, reason=UnknownErrorReason("SHIPPED_LATER")+ ),"billing_operation_failed",502,),diff --git a/api/tests/unit_tests/dev/test_generate_billing_client.py b/api/tests/unit_tests/dev/test_generate_billing_client.pyindex 1fc9aa2db01..a18be7a844a 100644--- a/api/tests/unit_tests/dev/test_generate_billing_client.py+++ b/api/tests/unit_tests/dev/test_generate_billing_client.py@@ -49,13 +49,17 @@ def _source_spec() -> generator.JsonObject:"type": "object","properties": {"code": {"type": "integer", "description": "HTTP status code.", "format": "int32"},- "reason": {"$ref": f"{PREFIX}ErrorReason"},+ "reason": {"type": "string", "description": "See <Service>ErrorReason."},"message": {"type": "string"},"metadata": {"type": "object", "additionalProperties": {"type": "string"}},},},- "dify.saas.api.billing.ErrorReason": {- "enum": ["", "CODEC", "REQUEST_IN_PROGRESS"],+ "dify.saas.api.billing.BillingSubscriptionErrorReason": {+ "enum": ["", "CODEC", "MISSING_PLAN"],+ "type": "string",+ },+ "dify.saas.api.billing.BillingCouponErrorReason": {+ "enum": ["", "CODEC", "BILLING_COUPON_NOT_FOUND"],"type": "string",},}@@ -78,7 +82,12 @@ def test_snapshot_keeps_only_allowlisted_operations_and_reachable_schemas() -> Nassert snapshot[generator.SNAPSHOT_COMMIT_KEY] == "abc123"assert list(snapshot["paths"]) == ["/v1/subscription/info"]- assert sorted(snapshot["components"]["schemas"]) == ["Error", "ErrorReason", "GetSubscriptionInfoReply", "Quota"]+ assert sorted(snapshot["components"]["schemas"]) == [+ "BillingSubscriptionErrorReason",+ "Error",+ "GetSubscriptionInfoReply",+ "Quota",+ ]assert "coupon" not in generator.render_snapshot(snapshot).lower()@@ -107,11 +116,42 @@ def test_rendered_module_types_fields_and_operations() -> None:assert "renewed_at: datetime\n" in sourceassert "def subscription_get_subscription_info() -> GetSubscriptionInfoReply:" in sourceassert '"/subscription/info",' in source- assert 'type ErrorReason = Literal["", "CODEC", "REQUEST_IN_PROGRESS"]' in source- assert "errors=ERRORS," in source- assert "class UpstreamError(BillingUpstreamError):" in source- assert "reason: ErrorReason | UnknownErrorReason | None = None," in source+ assert 'type BillingSubscriptionErrorReason = Literal["", "CODEC", "MISSING_PLAN"]' in source+ assert "def _is_billing_subscription_error_reason(value: str) -> TypeIs[BillingSubscriptionErrorReason]:" in source+ assert "errors=BILLING_SUBSCRIPTION_ERRORS," in source+ assert "class BillingSubscriptionUpstreamError(BillingUpstreamError):" in source+ assert "reason: BillingSubscriptionErrorReason | UnknownErrorReason | None = None," in source+ assert (+ "class BillingSubscriptionUpstreamUnavailableError(BillingSubscriptionUpstreamError, "+ "BillingUpstreamUnavailableError):"+ ) in source+ assert "BILLING_SUBSCRIPTION_ERRORS = ServiceErrors(" in source+ assert "Coupon" not in sourceassert "class Error(" not in source+ assert "ErrorReason =" not in source.replace("BillingSubscriptionErrorReason =", "")+++def test_rendered_module_gives_each_service_its_own_errors(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setitem(+ generator.ALLOWED_OPERATIONS,+ "billing",+ (+ generator.AllowedOperation("GET", "/v1/subscription/info", "BILLING"),+ generator.AllowedOperation("GET", "/v1/coupons/stripe", "BILLING"),+ ),+ )+ snapshot = generator.build_snapshot("billing", _source_spec(), "abc123")++ source = generator.render_module("billing", snapshot)++ assert {"BillingCouponErrorReason", "BillingSubscriptionErrorReason"} <= set(snapshot["components"]["schemas"])+ subscription, coupon = (+ source.partition(f"def {name}(")[2].partition("\n\n\n")[0]+ for name in ("subscription_get_subscription_info", "coupon_list_stripe_coupons")+ )+ assert "errors=BILLING_SUBSCRIPTION_ERRORS," in subscription+ assert "errors=BILLING_COUPON_ERRORS," in coupon+ assert "class BillingCouponUpstreamError(BillingUpstreamError):" in sourcedef test_long_operation_docstring_is_wrapped() -> None:@@ -150,15 +190,51 @@ def test_snapshot_rejects_allowlisted_operation_missing_from_spec() -> None:@pytest.mark.usefixtures("subscription_info_only")[email protected]("name", ["Error", "ErrorReason"])-def test_snapshot_rejects_spec_without_error_schema(name: str) -> None:+def test_snapshot_rejects_spec_without_error_schema() -> None:+ source = _source_spec()+ del source["components"]["schemas"]["dify.saas.api.billing.Error"]++ with pytest.raises(generator.GenerationError, match="error schema dify.saas.api.billing.Error "):+ generator.build_snapshot("billing", source, "abc123")++[email protected]("subscription_info_only")+def test_snapshot_rejects_operation_without_its_service_reason_schema() -> None:source = _source_spec()- del source["components"]["schemas"][f"dify.saas.api.billing.{name}"]+ del source["components"]["schemas"]["dify.saas.api.billing.BillingSubscriptionErrorReason"]- with pytest.raises(generator.GenerationError, match=f"error schema dify.saas.api.billing.{name}"):+ with pytest.raises(+ generator.GenerationError,+ match=r"BillingSubscription_GetSubscriptionInfo\) has no dify.saas.api.billing.BillingSubscriptionErrorReason",+ ):generator.build_snapshot("billing", source, "abc123")[email protected]("subscription_info_only")[email protected]("operation_id", ["GetSubscriptionInfo", "_GetSubscriptionInfo", "BillingSubscription_", ""])+def test_snapshot_rejects_operation_id_without_service_prefix(operation_id: str) -> None:+ source = _source_spec()+ source["paths"]["/v1/subscription/info"]["get"]["operationId"] = operation_id++ with pytest.raises(generator.GenerationError, match="has no `<Service>_` prefix"):+ generator.build_snapshot("billing", source, "abc123")++[email protected]("subscription_info_only")+def test_rendering_rejects_snapshot_whose_reason_schemas_drift_from_its_operations() -> None:+ snapshot = generator.build_snapshot("billing", _source_spec(), "abc123")+ schemas = snapshot["components"]["schemas"]+ schemas["BillingCouponErrorReason"] = {"enum": [""], "type": "string"}++ with pytest.raises(generator.GenerationError, match=r"unused \['BillingCouponErrorReason'\]"):+ generator.render_module("billing", snapshot)++ del schemas["BillingCouponErrorReason"], schemas["BillingSubscriptionErrorReason"]++ with pytest.raises(generator.GenerationError, match=r"missing \['BillingSubscriptionErrorReason'\]"):+ generator.render_module("billing", snapshot)++@pytest.mark.usefixtures("subscription_info_only")def test_rendering_rejects_error_body_that_drifts_from_the_transport() -> None:source = _source_spec()@@ -169,16 +245,35 @@ def test_rendering_rejects_error_body_that_drifts_from_the_transport() -> None:generator.render_module("billing", snapshot)-def test_committed_snapshots_keep_each_service_reasons_apart() -> None:- billing_reasons, saas_reasons = (- generator.load_snapshot(service)["components"]["schemas"]["ErrorReason"]["enum"]+def test_committed_snapshots_keep_only_the_reasons_of_called_services() -> None:+ reason_schemas = {+ service: {+ name: schema["enum"]+ for name, schema in generator.load_snapshot(service)["components"]["schemas"].items()+ if name.endswith("ErrorReason")+ }for service in generator.SERVICES- )+ }- assert "REQUEST_IN_PROGRESS" in billing_reasons- assert "REQUEST_IN_PROGRESS" not in saas_reasons- assert "NETWORK_ACCESS_VERSION_CONFLICT" in saas_reasons- assert "NETWORK_ACCESS_VERSION_CONFLICT" not in billing_reasons+ assert sorted(reason_schemas["billing"]) == [+ "BillingComplianceErrorReason",+ "BillingEducationErrorReason",+ "BillingInvoiceErrorReason",+ "BillingModelProviderErrorReason",+ "BillingQuotaErrorReason",+ "BillingSubscriptionErrorReason",+ ]+ assert sorted(reason_schemas["saas"]) == [+ "AccountErrorReason",+ "SaasNetworkAccessPolicyErrorReason",+ "SaasNotificationErrorReason",+ "UtmErrorReason",+ ]+ education = reason_schemas["billing"]["BillingEducationErrorReason"]+ assert "EDUCATION_VERIFY_FAILED" in education+ assert "COMPLIANCE_DOCUMENT_NOT_FOUND" not in education+ assert "NETWORK_ACCESS_VERSION_CONFLICT" in reason_schemas["saas"]["SaasNetworkAccessPolicyErrorReason"]+ assert "NETWORK_ACCESS_VERSION_CONFLICT" not in reason_schemas["saas"]["AccountErrorReason"]def test_committed_client_matches_snapshots() -> None:diff --git a/api/tests/unit_tests/services/account/test_adapters.py b/api/tests/unit_tests/services/account/test_adapters.pyindex bd17fe3fcbe..fee49421b7c 100644--- a/api/tests/unit_tests/services/account/test_adapters.py+++ b/api/tests/unit_tests/services/account/test_adapters.py@@ -558,8 +558,10 @@ def test_identity_rejects_banned_and_missing_accounts(account_domain: AccountDom("REQUEST_IN_PROGRESS", EducationRequestInProgressError),],)-def test_education_gateway_maps_billing_reason(reason: billing.ErrorReason, expected: type[Exception]) -> None:- error = billing.UpstreamInvalidResponseError(status_code=400, reason=reason)+def test_education_gateway_maps_billing_reason(+ reason: billing.BillingEducationErrorReason, expected: type[Exception]+) -> None:+ error = billing.BillingEducationUpstreamInvalidResponseError(status_code=400, reason=reason)with (patch("services.account.adapters.BillingService.EducationIdentity.verify", side_effect=error),@@ -573,15 +575,17 @@ def test_education_gateway_maps_billing_reason(reason: billing.ErrorReason, expe@pytest.mark.parametrize("error",[- billing.UpstreamInvalidResponseError(status_code=400, reason="EDUCATION_STATUS_FAILED"),- billing.UpstreamUnavailableError(status_code=500, reason=""),- billing.UpstreamInvalidResponseError(status_code=400, reason=UnknownErrorReason("EDUCATION_SHIPPED_LATER")),- billing.UpstreamUnavailableError(status_code=502),- billing.UpstreamUnavailableError(),+ billing.BillingEducationUpstreamInvalidResponseError(status_code=400, reason="EDUCATION_STATUS_FAILED"),+ billing.BillingEducationUpstreamUnavailableError(status_code=500, reason=""),+ billing.BillingEducationUpstreamInvalidResponseError(+ status_code=400, reason=UnknownErrorReason("EDUCATION_SHIPPED_LATER")+ ),+ billing.BillingEducationUpstreamUnavailableError(status_code=502),+ billing.BillingEducationUpstreamUnavailableError(),],)def test_education_gateway_leaves_generic_reasons_to_billing_errors(- error: billing.UpstreamError,+ error: billing.BillingEducationUpstreamError,) -> None:with (patch("services.account.adapters.BillingService.EducationIdentity.status", side_effect=error),diff --git a/api/tests/unit_tests/services/billing_client/test_transport.py b/api/tests/unit_tests/services/billing_client/test_transport.pyindex 38ef2012104..6f36401ee18 100644--- a/api/tests/unit_tests/services/billing_client/test_transport.py+++ b/api/tests/unit_tests/services/billing_client/test_transport.py@@ -1,8 +1,7 @@import inspectimport logging-import typesfrom collections.abc import Callable-from typing import assert_type, get_args+from typing import TypeAliasType, assert_type, get_argsimport httpximport pytest@@ -41,7 +40,14 @@ class _VirtualClock:def _get(upstream: Upstream) -> _Reply:return transport.request(- upstream, "GET", "/probe", response_model=_Reply, errors=saas.ERRORS, path_params={}, params={}, body=None+ upstream,+ "GET",+ "/probe",+ response_model=_Reply,+ errors=saas.SAAS_NETWORK_ACCESS_POLICY_ERRORS,+ path_params={},+ params={},+ body=None,)@@ -65,7 +71,7 @@ def test_non_ok_status_maps_to_upstream_errors(respond_with: RespondWith, statusassert isinstance(exc_info.value, BillingUpstreamError)assert exc_info.value.status_code == statusassert exc_info.value.body == UpstreamErrorBody(code=status, message="over")- assert isinstance(exc_info.value, saas.UpstreamError)+ assert isinstance(exc_info.value, saas.SaasNetworkAccessPolicyUpstreamError)assert exc_info.value.reason == "NETWORK_ACCESS_VERSION_CONFLICT"@@ -89,7 +95,7 @@ def test_error_body_keeps_well_typed_fields() -> None:respond_with(httpx.Response(409, content=content))- with pytest.raises(saas.UpstreamInvalidResponseError) as exc_info:+ with pytest.raises(saas.SaasNetworkAccessPolicyUpstreamInvalidResponseError) as exc_info:_get(Upstream.BILLING)assert exc_info.value.body == body@@ -107,13 +113,15 @@ def test_unknown_reason_is_kept_apart_and_reported(with caplog.at_level(logging.ERROR, logger=transport.__name__), pytest.raises(error) as exc_info:_get(Upstream.SAAS)- assert isinstance(exc_info.value, saas.UpstreamError)+ assert isinstance(exc_info.value, saas.SaasNetworkAccessPolicyUpstreamError)assert exc_info.value.reason == UnknownErrorReason("SHIPPED_LATER")assert exc_info.value.body == UpstreamErrorBody(code=status, message="new")[record] = caplog.recordsassert record.levelno == logging.ERRORassert (- record.getMessage() == "Unknown saas error reason SHIPPED_LATER from GET /probe; regenerate the billing client"+ record.getMessage()+ == "Unknown saas error reason SHIPPED_LATER from GET /probe: regenerate the billing client, "+ "or the billing service returned a reason outside this service's declared set")@@ -123,7 +131,10 @@ def test_unknown_reason_is_logged_without_foreign_characters(reason = "SHIPPED_LATER\nERROR forged entry <script>" + "X" * 100respond_with(httpx.Response(409, json={"code": 409, "reason": reason}))- with caplog.at_level(logging.ERROR, logger=transport.__name__), pytest.raises(saas.UpstreamError) as exc_info:+ with (+ caplog.at_level(logging.ERROR, logger=transport.__name__),+ pytest.raises(saas.SaasNetworkAccessPolicyUpstreamError) as exc_info,+ ):_get(Upstream.SAAS)assert exc_info.value.reason == UnknownErrorReason(reason)@@ -133,38 +144,79 @@ def test_unknown_reason_is_logged_without_foreign_characters(@pytest.mark.parametrize(- ("call", "own", "other"),+ ("call", "own", "others"),[- (lambda: billing.subscription_get_subscription_info(tenant_id="t", exclude_vector_space=False), billing, saas),- (lambda: saas.account_check_account_in_freeze(email="[email protected]"), saas, billing),+ (+ lambda: billing.subscription_get_subscription_info(tenant_id="t", exclude_vector_space=False),+ billing.BillingSubscriptionUpstreamUnavailableError,+ (billing.BillingQuotaUpstreamError, saas.AccountUpstreamError),+ ),+ (+ lambda: billing.quota_get_quota_info(tenant_id="t"),+ billing.BillingQuotaUpstreamUnavailableError,+ (billing.BillingSubscriptionUpstreamError, saas.AccountUpstreamError),+ ),+ (+ lambda: saas.account_check_account_in_freeze(email="[email protected]"),+ saas.AccountUpstreamUnavailableError,+ (saas.SaasNetworkAccessPolicyUpstreamError, billing.BillingSubscriptionUpstreamError),+ ),],)def test_generated_operation_raises_its_own_service_errors(- respond_with: RespondWith, call: Callable[[], object], own: types.ModuleType, other: types.ModuleType+ respond_with: RespondWith,+ call: Callable[[], object],+ own: type[BillingUpstreamError],+ others: tuple[type[BillingUpstreamError], ...],) -> None:respond_with(httpx.Response(503, json={"code": 503, "reason": ""}))with pytest.raises(BillingUpstreamUnavailableError) as exc_info:call()- assert isinstance(exc_info.value, own.UpstreamUnavailableError)- assert not isinstance(exc_info.value, other.UpstreamError)- assert exc_info.value.reason == ""+ assert type(exc_info.value) is own+ assert not isinstance(exc_info.value, others)-def test_service_errors_type_their_own_reason() -> None:- def read(saas_error: saas.UpstreamError, billing_error: billing.UpstreamError) -> None:- assert_type(saas_error.reason, saas.ErrorReason | UnknownErrorReason | None)- assert_type(billing_error.reason, billing.ErrorReason | UnknownErrorReason | None)+def test_reason_from_another_service_is_unknown(respond_with: RespondWith) -> None:+ respond_with(httpx.Response(409, json={"code": 409, "reason": "COMPLIANCE_DOCUMENT_NOT_FOUND"}))- read(saas.UpstreamUnavailableError(reason="APP_NOT_FOUND"), billing.UpstreamInvalidResponseError(reason=""))+ with pytest.raises(billing.BillingEducationUpstreamInvalidResponseError) as exc_info:+ billing.education_get_education_identity_status(account_id="a")++ assert exc_info.value.reason == UnknownErrorReason("COMPLIANCE_DOCUMENT_NOT_FOUND")+++def test_service_errors_type_their_own_reason() -> None:+ def read(+ network_access: saas.SaasNetworkAccessPolicyUpstreamError, education: billing.BillingEducationUpstreamError+ ) -> None:+ assert_type(network_access.reason, saas.SaasNetworkAccessPolicyErrorReason | UnknownErrorReason | None)+ assert_type(education.reason, billing.BillingEducationErrorReason | UnknownErrorReason | None)++ read(+ saas.SaasNetworkAccessPolicyUpstreamUnavailableError(reason="APP_NOT_FOUND"),+ billing.BillingEducationUpstreamInvalidResponseError(reason="EDUCATION_VERIFY_FAILED"),+ )+ read(+ saas.SaasNetworkAccessPolicyUpstreamError(),+ billing.BillingComplianceUpstreamError(), # pyrefly: ignore[bad-argument-type]+ )+ billing.BillingEducationUpstreamError(reason="COMPLIANCE_DOCUMENT_NOT_FOUND") # pyrefly: ignore[bad-argument-type]assert not hasattr(BillingUpstreamError(), "reason")def test_transport_branches_on_no_specific_reason() -> None:source = inspect.getsource(transport)- reasons = set(get_args(billing.ErrorReason.__value__)) | set(get_args(saas.ErrorReason.__value__))-+ reason_types = [+ value+ for module in (billing, saas)+ for name, value in vars(module).items()+ if name.endswith("ErrorReason") and isinstance(value, TypeAliasType)+ ]+ reasons = {reason for reason_type in reason_types for reason in get_args(reason_type.__value__)}++ assert len(reason_types) == 10assert [reason for reason in reasons if reason and reason in source] == []@@ -266,7 +318,7 @@ def test_invalid_body_is_reported_and_kept_raw_while_observed("GET","/probe",response_model=billing.GetSubscriptionInfoReply,- errors=billing.ERRORS,+ errors=billing.BILLING_SUBSCRIPTION_ERRORS,path_params={},params={},body=None,@@ -308,7 +360,7 @@ def test_migrated_reads_reject_missing_required_fields("GET",path,response_model=response_model,- errors=billing.ERRORS,+ errors=billing.BILLING_SUBSCRIPTION_ERRORS,path_params={},params={},body=None,@@ -337,7 +389,7 @@ def test_quota_responses_reject_missing_required_fields(method,path,response_model=response_model,- errors=billing.ERRORS,+ errors=billing.BILLING_QUOTA_ERRORS,path_params={},params={},body=None,diff --git a/api/tests/unit_tests/services/test_network_access_group_gateway.py b/api/tests/unit_tests/services/test_network_access_group_gateway.pyindex 8685acb2ca1..934eca02918 100644--- a/api/tests/unit_tests/services/test_network_access_group_gateway.py+++ b/api/tests/unit_tests/services/test_network_access_group_gateway.py@@ -268,7 +268,7 @@ def test_known_reason_maps_to_service_error(NetworkAccessGroupGateway().get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID)assert type(exc_info.value) is expected- assert isinstance(exc_info.value.__cause__, saas.UpstreamError)+ assert isinstance(exc_info.value.__cause__, saas.SaasNetworkAccessPolicyUpstreamError)@pytest.mark.parametrize(@@ -306,7 +306,7 @@ def test_unknown_reason_falls_back_to_status_and_is_reported(assert exc_info.value.unavailable is unavailablecause = exc_info.value.__cause__- assert isinstance(cause, saas.UpstreamError)+ assert isinstance(cause, saas.SaasNetworkAccessPolicyUpstreamError)assert cause.reason == UnknownErrorReason("NETWORK_ACCESS_SHIPPED_LATER")[record] = [record for record in caplog.records if record.name == transport.__name__]assert record.levelname == "ERROR"@@ -335,7 +335,7 @@ def test_reply_without_reason_falls_back_to_status(assert exc_info.value.unavailable is unavailablecause = exc_info.value.__cause__- assert isinstance(cause, saas.UpstreamError)+ assert isinstance(cause, saas.SaasNetworkAccessPolicyUpstreamError)assert cause.reason is None@@ -344,7 +344,7 @@ def test_unreachable_upstream_maps_to_unavailable() -> None:patch.object(saas,"network_access_policy_list_network_access_groups",- side_effect=saas.UpstreamUnavailableError("GET failed"),+ side_effect=saas.SaasNetworkAccessPolicyUpstreamUnavailableError("GET failed"),),pytest.raises(NetworkAccessGroupUpstreamError) as exc_info,):