Skip to content

armgit / dify

Public Imported from GitHub
0

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.

feat(api): map billing error reasons to typed console errors (#45170)

yyh3ae91474174b
diff --git a/api/controllers/console/billing/billing.py b/api/controllers/console/billing/billing.py
index b28a6df44a9..3600a3e7f03 100644
--- a/api/controllers/console/billing/billing.py
+++ b/api/controllers/console/billing/billing.py
@@ -1,4 +1,4 @@
-from typing import Literal
+from typing import Literal, assert_never
from flask_restx import Resource
from pydantic import BaseModel, Field
@@ -18,11 +18,13 @@ from controllers.console.wraps import model_validate
from enums import CloudPlan, DeploymentEdition
from extensions.ext_application_services import application_services
from fields.base import ResponseModel
+from libs.exception import BaseHTTPException
from libs.external_api import error_responses
from libs.helper import dump_response
from machinery.context import RequestContext
from models.account import TenantAccountRole
-from services.errors.billing import BillingError
+from services.billing_client import billing
+from services.errors.billing import UnknownErrorReason
_BILLING_PORTAL_ALLOWED_ROLES = frozenset({TenantAccountRole.OWNER, TenantAccountRole.ADMIN})
@@ -51,6 +53,89 @@ register_response_schema_models(
)
+def _billing_portal_error(error: billing.UpstreamError) -> 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_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"
+ ):
+ return to_billing_request_error(error)
+ case UnknownErrorReason() | None:
+ return to_billing_request_error(error)
+ case unreachable:
+ assert_never(unreachable)
+
+
@console_ns.route("/billing/subscription")
class Subscription(Resource):
@error_responses(BillingOperationFailedError, BillingUnavailableError)
@@ -84,8 +169,8 @@ class Subscription(Resource):
plan=req_data.plan,
interval=req_data.interval,
)
- except BillingError as error:
- raise to_billing_request_error(error) from error
+ except billing.UpstreamError as error:
+ raise _billing_portal_error(error) from error
return dump_response(BillingSubscriptionResponse, data)
@@ -111,6 +196,6 @@ class Invoices(Resource):
def get(self, request_context: RequestContext):
try:
data = application_services().billing_portal.get_invoices(request_context)
- except BillingError as error:
- raise to_billing_request_error(error) from error
+ except billing.UpstreamError as error:
+ raise _billing_portal_error(error) from error
return dump_response(BillingInvoiceResponse, data)
diff --git a/api/controllers/console/billing/compliance.py b/api/controllers/console/billing/compliance.py
index e595cff3cd4..223fb1931db 100644
--- a/api/controllers/console/billing/compliance.py
+++ b/api/controllers/console/billing/compliance.py
@@ -1,3 +1,5 @@
+from typing import assert_never
+
from flask import request
from flask_restx import Resource
from pydantic import BaseModel, Field
@@ -11,9 +13,12 @@ from controllers.console import console_ns
from controllers.console.billing.error import (
BillingOperationFailedError,
BillingOperationFailedErrorResponse,
+ BillingRequestInProgressError,
BillingUnavailableError,
BillingUnavailableErrorResponse,
BillingUnprocessableEntityErrorResponse,
+ ComplianceDocumentNotFoundError,
+ ComplianceDownloadForbiddenError,
ComplianceRateLimitError,
ComplianceRateLimitErrorResponse,
to_billing_request_error,
@@ -23,10 +28,12 @@ from controllers.console.wraps import model_validate
from enums import DeploymentEdition
from extensions.ext_application_services import application_services
from fields.base import ResponseModel
+from libs.exception import BaseHTTPException
from libs.external_api import error_responses
from libs.helper import dump_response, extract_remote_ip
from machinery.context import RequestContext
-from services.errors.billing import BillingError, ComplianceRateLimitExceededError
+from services.billing_client import billing
+from services.errors.billing import ComplianceRateLimitExceededError, UnknownErrorReason
class ComplianceDownloadQuery(BaseModel):
@@ -48,9 +55,102 @@ register_response_schema_models(
)
+def _compliance_download_error(error: billing.UpstreamError) -> BaseHTTPException:
+ match error.reason:
+ case "COMPLIANCE_DOCUMENT_NOT_FOUND":
+ return ComplianceDocumentNotFoundError()
+ case "COMPLIANCE_DOWNLOAD_FORBIDDEN":
+ return ComplianceDownloadForbiddenError()
+ case "REQUEST_IN_PROGRESS":
+ return BillingRequestInProgressError()
+ case (
+ ""
+ | "CODEC"
+ | "VALIDATOR"
+ | "UNKNOWN"
+ | "INVALID_SECRET_KEY"
+ | "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_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:
+ return to_billing_request_error(error)
+ case unreachable:
+ assert_never(unreachable)
+
+
@console_ns.route("/compliance/download")
class ComplianceApi(Resource):
- @error_responses(BillingOperationFailedError, BillingUnavailableError, ComplianceRateLimitError)
+ @error_responses(
+ BillingOperationFailedError,
+ BillingRequestInProgressError,
+ BillingUnavailableError,
+ ComplianceDocumentNotFoundError,
+ ComplianceDownloadForbiddenError,
+ ComplianceRateLimitError,
+ )
@console_ns.doc(params=query_params_from_model(ComplianceDownloadQuery))
@console_ns.doc("download_compliance_document")
@console_ns.doc(description="Get compliance document download link")
@@ -89,6 +189,6 @@ class ComplianceApi(Resource):
)
except ComplianceRateLimitExceededError as error:
raise ComplianceRateLimitError() from error
- except BillingError as error:
- raise to_billing_request_error(error) from error
+ except billing.UpstreamError as error:
+ raise _compliance_download_error(error) from error
return dump_response(ComplianceDownloadResponse, data)
diff --git a/api/controllers/console/billing/error.py b/api/controllers/console/billing/error.py
index bc81d042a04..66a78ef6601 100644
--- a/api/controllers/console/billing/error.py
+++ b/api/controllers/console/billing/error.py
@@ -39,6 +39,24 @@ class ComplianceRateLimitError(BaseHTTPException):
code = 429
+class ComplianceDocumentNotFoundError(BaseHTTPException):
+ error_code = "compliance_document_not_found"
+ description = "The compliance document was not found."
+ code = 404
+
+
+class ComplianceDownloadForbiddenError(BaseHTTPException):
+ error_code = "compliance_download_forbidden"
+ description = "Your current plan does not allow downloading this compliance document."
+ code = 403
+
+
+class BillingRequestInProgressError(BaseHTTPException):
+ error_code = "billing_request_in_progress"
+ description = "A previous request is still being processed. Please try again shortly."
+ code = 429
+
+
class BillingOperationFailedError(BaseHTTPException):
error_code = "billing_operation_failed"
description = "We couldn't complete this request. Please try again. If the problem persists, contact support."
diff --git a/api/controllers/console/error.py b/api/controllers/console/error.py
index af97cb6f3e9..68beb0abc1a 100644
--- a/api/controllers/console/error.py
+++ b/api/controllers/console/error.py
@@ -1,6 +1,12 @@
from libs.exception import BaseHTTPException
+class PaidPlanRequiredError(BaseHTTPException):
+ error_code = "paid_plan_required"
+ description = "This feature requires a paid plan."
+ code = 403
+
+
class AlreadySetupError(BaseHTTPException):
error_code = "already_setup"
description = "Dify has been successfully installed. Please refresh the page or return to the dashboard homepage."
@@ -121,6 +127,18 @@ class EducationActivateLimitError(BaseHTTPException):
code = 429
+class EducationVerifyFailedError(BaseHTTPException):
+ error_code = "education_verify_failed"
+ description = "We couldn't verify your education status."
+ code = 400
+
+
+class EducationActivateFailedError(BaseHTTPException):
+ error_code = "education_activate_failed"
+ description = "We couldn't activate your education discount."
+ code = 400
+
+
class ApiKeyLimitExceededHTTPError(BaseHTTPException):
error_code = "max_keys_exceeded"
description = "The API key limit has been reached."
diff --git a/api/controllers/console/workflow_run_archive.py b/api/controllers/console/workflow_run_archive.py
index 1edd5fe21d8..d336c1ed23d 100644
--- a/api/controllers/console/workflow_run_archive.py
+++ b/api/controllers/console/workflow_run_archive.py
@@ -9,6 +9,7 @@ from pydantic import BaseModel, Field, ValidationError
from controllers.common.fields import RedirectResponse
from controllers.common.schema import register_response_schema_models, register_schema_models
from controllers.console import console_ns
+from controllers.console.error import PaidPlanRequiredError
from controllers.console.flask_admission import console_account_admission
from controllers.console.wraps import (
cloud_edition_billing_paid_plan_required,
@@ -17,6 +18,7 @@ from controllers.console.wraps import (
from enums import DeploymentEdition
from extensions.ext_application_services import application_services
from fields.base import ResponseModel
+from libs.external_api import error_responses
from libs.helper import dump_response
from machinery.context import RequestContext
from models.account import TenantAccountRole
@@ -107,6 +109,7 @@ register_response_schema_models(
@console_ns.route("/workflow-run-archives")
class WorkflowRunArchivesApi(Resource):
+ @error_responses(PaidPlanRequiredError)
@console_ns.doc("list_workflow_run_archives")
@console_ns.doc(description="List monthly workflow-run archive metadata for the current workspace")
@console_ns.response(200, "Success", console_ns.models[WorkflowRunArchiveListResponse.__name__])
@@ -122,6 +125,7 @@ class WorkflowRunArchivesApi(Resource):
@console_ns.route("/workflow-run-archives/<int:year>/<int:month>")
class WorkflowRunArchiveMonthApi(Resource):
+ @error_responses(PaidPlanRequiredError)
@console_ns.doc("delete_workflow_run_archive")
@console_ns.doc(description="Permanently delete this workspace's monthly archive files and archive index")
@console_ns.doc(
@@ -154,6 +158,7 @@ class WorkflowRunArchiveMonthApi(Resource):
@console_ns.route("/workflow-run-archives/downloads")
class WorkflowRunArchiveDownloadsApi(Resource):
+ @error_responses(PaidPlanRequiredError)
@console_ns.doc("create_workflow_run_archive_download")
@console_ns.doc(description="Create or return a temporary workflow-run archive download task")
@console_ns.expect(console_ns.models[WorkflowRunArchiveDownloadPayload.__name__])
@@ -179,6 +184,7 @@ class WorkflowRunArchiveDownloadsApi(Resource):
@console_ns.route("/workflow-run-archives/downloads/<string:download_id>")
class WorkflowRunArchiveDownloadApi(Resource):
+ @error_responses(PaidPlanRequiredError)
@console_ns.doc("get_workflow_run_archive_download")
@console_ns.doc(description="Get a temporary workflow-run archive download task")
@console_ns.response(200, "Success", console_ns.models[WorkflowRunArchiveDownloadTaskResponse.__name__])
@@ -197,6 +203,7 @@ class WorkflowRunArchiveDownloadApi(Resource):
@console_ns.route("/workflow-run-archives/downloads/<string:download_id>/file")
class WorkflowRunArchiveDownloadFileApi(Resource):
+ @error_responses(PaidPlanRequiredError)
@console_ns.doc("download_workflow_run_archive_file")
@console_ns.doc(description="Redirect to a prepared workflow-run archive ZIP file")
@console_ns.response(
diff --git a/api/controllers/console/workspace/account.py b/api/controllers/console/workspace/account.py
index 4da163c1976..566ee1f42ee 100644
--- a/api/controllers/console/workspace/account.py
+++ b/api/controllers/console/workspace/account.py
@@ -28,10 +28,18 @@ from controllers.console.auth.error import (
InvalidEmailError,
InvalidTokenError,
)
+from controllers.console.billing.error import (
+ BillingOperationFailedError,
+ BillingRequestInProgressError,
+ BillingUnavailableError,
+ to_billing_request_error,
+)
from controllers.console.error import (
AccountInFreezeError,
AccountNotFound,
+ EducationActivateFailedError,
EducationActivateLimitError,
+ EducationVerifyFailedError,
EducationVerifyLimitError,
EmailDomainSuspendedError,
EmailSendIpLimitError,
@@ -50,12 +58,14 @@ from controllers.console.wraps import model_validate, setup_required
from extensions.ext_application_services import application_services
from fields.base import ResponseModel
from fields.member_fields import AccountResponse
+from libs.exception import BaseHTTPException
from libs.external_api import error_responses
from libs.helper import EmailStr, dump_response, extract_remote_ip, timezone, to_timestamp
from machinery.context import RequestContext
from services import account_errors
from services.account_education_service import EDUCATION_EDITIONS
from services.entities.account_entities import AccountProfileChanges
+from services.errors.billing import BillingUpstreamError
class AccountInitPayload(BaseModel):
@@ -425,9 +435,39 @@ class AccountDeleteUpdateFeedbackApi(Resource):
return SimpleResultResponse(result="success").model_dump(mode="json")
+_EDUCATION_BILLING_ERRORS = (
+ account_errors.EducationVerificationFailedError,
+ account_errors.EducationActivationFailedError,
+ account_errors.EducationRequestInProgressError,
+ BillingUpstreamError,
+)
+
+
+def _education_billing_error(
+ error: account_errors.EducationVerificationFailedError
+ | account_errors.EducationActivationFailedError
+ | account_errors.EducationRequestInProgressError
+ | BillingUpstreamError,
+) -> BaseHTTPException:
+ if isinstance(error, account_errors.EducationVerificationFailedError):
+ return EducationVerifyFailedError()
+ if isinstance(error, account_errors.EducationActivationFailedError):
+ return EducationActivateFailedError()
+ if isinstance(error, account_errors.EducationRequestInProgressError):
+ return BillingRequestInProgressError()
+ return to_billing_request_error(error)
+
+
@console_ns.route("/account/education/verify")
class EducationVerifyApi(Resource):
- @error_responses(AccountNotFound, EducationVerifyLimitError)
+ @error_responses(
+ AccountNotFound,
+ BillingOperationFailedError,
+ BillingRequestInProgressError,
+ BillingUnavailableError,
+ EducationVerifyFailedError,
+ EducationVerifyLimitError,
+ )
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[EducationVerifyResponse.__name__])
@console_account_admission(editions=EDUCATION_EDITIONS)
def get(self, request_context: RequestContext):
@@ -437,12 +477,21 @@ class EducationVerifyApi(Resource):
raise AccountNotFound() from error
except account_errors.EducationRateLimitExceededError as error:
raise EducationVerifyLimitError() from error
+ except _EDUCATION_BILLING_ERRORS as error:
+ raise _education_billing_error(error) from error
return dump_response(EducationVerifyResponse, verification)
@console_ns.route("/account/education")
class EducationApi(Resource):
- @error_responses(AccountNotFound, EducationActivateLimitError)
+ @error_responses(
+ AccountNotFound,
+ BillingOperationFailedError,
+ BillingRequestInProgressError,
+ BillingUnavailableError,
+ EducationActivateFailedError,
+ EducationActivateLimitError,
+ )
@console_ns.expect(console_ns.models[EducationActivatePayload.__name__])
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[EducationActivateResponse.__name__])
@console_account_admission(editions=EDUCATION_EDITIONS)
@@ -459,30 +508,39 @@ class EducationApi(Resource):
raise AccountNotFound() from error
except account_errors.EducationRateLimitExceededError as error:
raise EducationActivateLimitError() from error
+ except _EDUCATION_BILLING_ERRORS as error:
+ raise _education_billing_error(error) from error
return dump_response(EducationActivateResponse, activation)
+ @error_responses(BillingOperationFailedError, BillingRequestInProgressError, BillingUnavailableError)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[EducationStatusResponse.__name__])
@console_account_admission(editions=EDUCATION_EDITIONS)
def get(self, request_context: RequestContext):
- return dump_response(EducationStatusResponse, application_services().accounts.education.status(request_context))
+ try:
+ status = application_services().accounts.education.status(request_context)
+ except _EDUCATION_BILLING_ERRORS as error:
+ raise _education_billing_error(error) from error
+ return dump_response(EducationStatusResponse, status)
@console_ns.route("/account/education/autocomplete")
class EducationAutoCompleteApi(Resource):
+ @error_responses(BillingOperationFailedError, BillingUnavailableError)
@console_ns.doc(params=query_params_from_model(EducationAutocompleteQuery))
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[EducationAutocompleteResponse.__name__])
@console_account_admission(editions=EDUCATION_EDITIONS)
@model_validate(EducationAutocompleteQuery)
def get(self, args: EducationAutocompleteQuery, request_context: RequestContext):
- return dump_response(
- EducationAutocompleteResponse,
- application_services().accounts.education.autocomplete(
+ try:
+ institutions = application_services().accounts.education.autocomplete(
request_context,
keywords=args.keywords,
page=args.page,
limit=args.limit,
- ),
- )
+ )
+ except _EDUCATION_BILLING_ERRORS as error:
+ raise _education_billing_error(error) from error
+ return dump_response(EducationAutocompleteResponse, institutions)
@console_ns.route("/account/change-email")
diff --git a/api/controllers/console/workspace/error.py b/api/controllers/console/workspace/error.py
index 1ea8a4a7194..7f46df990db 100644
--- a/api/controllers/console/workspace/error.py
+++ b/api/controllers/console/workspace/error.py
@@ -103,3 +103,63 @@ class MemberRoleAlreadyAssignedError(BaseHTTPException):
error_code = "role_already_assigned"
description = "Role already assigned."
code = 400
+
+
+class NetworkAccessInvalidInputError(BaseHTTPException):
+ error_code = "network_access_invalid_input"
+ description = "Invalid network access group request."
+ code = 400
+
+
+class NetworkAccessForbiddenError(BaseHTTPException):
+ error_code = "network_access_forbidden"
+ description = "Network access groups are not available for this workspace."
+ code = 403
+
+
+class NetworkAccessNotEntitledError(BaseHTTPException):
+ error_code = "network_access_not_entitled"
+ description = "Network access groups are not available for this workspace."
+ code = 403
+
+
+class NetworkAccessGroupNotFoundError(BaseHTTPException):
+ error_code = "network_access_group_not_found"
+ description = "Network access group was not found."
+ code = 404
+
+
+class NetworkAccessVersionConflictError(BaseHTTPException):
+ error_code = "network_access_version_conflict"
+ description = "The network access resource changed. Refresh it and try again."
+ code = 409
+
+
+class NetworkAccessGroupNameConflictError(BaseHTTPException):
+ error_code = "network_access_group_name_conflict"
+ description = "An IP policy with this name already exists."
+ code = 409
+
+
+class NetworkAccessGroupBoundError(BaseHTTPException):
+ error_code = "network_access_group_bound"
+ description = "This IP policy is still used by one or more apps."
+ code = 409
+
+
+class NetworkAccessRoleDeniedError(BaseHTTPException):
+ error_code = "network_access_role_denied"
+ description = "Your workspace role does not allow this network access operation."
+ code = 403
+
+
+class NetworkAccessUnsupportedAppModeError(BaseHTTPException):
+ error_code = "network_access_unsupported_app_mode"
+ description = "Network access control is not supported for this app mode."
+ code = 400
+
+
+class NetworkAccessUnsupportedAccessPointsError(BaseHTTPException):
+ error_code = "network_access_unsupported_access_points"
+ description = "Some access points are not supported for this app."
+ code = 400
diff --git a/api/controllers/console/workspace/network_access_group.py b/api/controllers/console/workspace/network_access_group.py
index 5e0279661f2..054d98de8fa 100644
--- a/api/controllers/console/workspace/network_access_group.py
+++ b/api/controllers/console/workspace/network_access_group.py
@@ -5,14 +5,17 @@ from uuid import UUID
from flask import Response, after_this_request, request
from flask_restx import Resource
from pydantic import AliasChoices, BaseModel, Field, ValidationError, model_validator
-from werkzeug.exceptions import BadGateway, BadRequest, Conflict, Forbidden, NotFound, ServiceUnavailable
+from werkzeug.exceptions import BadGateway, ServiceUnavailable
from configs import dify_config
from controllers.common.rbac import RBACCheck, Workspace
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console import console_ns
from controllers.console.app.error import AppNotFoundError
+from controllers.console.billing.error import BillingOperationFailedError, BillingUnavailableError
+from controllers.console.error import PaidPlanRequiredError
from controllers.console.flask_admission import console_account_admission
+from controllers.console.workspace import error as console_errors
from controllers.console.wraps import RBACPermission, cloud_edition_billing_paid_plan_required, model_validate
from core.network_access.client_ip import NetworkAccessClientIPUnavailableError, resolve_network_access_client_ip
from enums import DeploymentEdition
@@ -24,13 +27,20 @@ from machinery.context import RequestContext
from services.network_access_group_service import (
NetworkAccessGroupAccessDeniedError,
NetworkAccessGroupAppNotFoundError,
+ NetworkAccessGroupBoundError,
NetworkAccessGroupEntitlementUnavailableError,
NetworkAccessGroupError,
+ NetworkAccessGroupForbiddenError,
+ NetworkAccessGroupInvalidInputError,
NetworkAccessGroupInvalidPolicyError,
NetworkAccessGroupInvalidResponseError,
+ NetworkAccessGroupNameConflictError,
+ NetworkAccessGroupNotEntitledError,
+ NetworkAccessGroupNotFoundError,
NetworkAccessGroupUnsupportedAccessPointsError,
NetworkAccessGroupUnsupportedAppModeError,
NetworkAccessGroupUpstreamError,
+ NetworkAccessGroupVersionConflictError,
NetworkAccessPoint,
)
@@ -200,44 +210,48 @@ register_response_schema_models(
)
-def _translate_upstream_error(exc: NetworkAccessGroupUpstreamError) -> Exception:
- if exc.reason == "INVALID_SECRET_KEY":
- return ServiceUnavailable("Network access group service authentication failed.")
- if exc.status_code in (400, 422):
- return BadRequest("Invalid network access group request.")
- if exc.status_code == 401:
- return ServiceUnavailable("Network access group service authentication failed.")
- if exc.status_code == 403:
- return Forbidden("Network access groups are not available for this workspace.")
- if exc.status_code == 404:
- return NotFound("Network access group was not found.")
- if exc.status_code == 409:
- message_by_reason = {
- "NETWORK_ACCESS_VERSION_CONFLICT": "The network access resource changed. Refresh it and try again.",
- "NETWORK_ACCESS_GROUP_NAME_CONFLICT": "An IP policy with this name already exists.",
- "NETWORK_ACCESS_GROUP_LIMIT": "This workspace has reached the network access group limit.",
- }
- return Conflict(message_by_reason.get(exc.reason or "", "The network access resource is in conflict."))
- if exc.status_code >= 500:
- return ServiceUnavailable("Network access group service is unavailable.")
- return BadGateway("Unexpected response from the network access group service.")
+_CONTROL_PLANE_ERRORS = (
+ BillingOperationFailedError,
+ BillingUnavailableError,
+ console_errors.NetworkAccessForbiddenError,
+ console_errors.NetworkAccessNotEntitledError,
+ console_errors.NetworkAccessRoleDeniedError,
+)
def _translate_service_error(exc: NetworkAccessGroupError) -> Exception:
if isinstance(exc, NetworkAccessGroupInvalidResponseError):
return BadGateway("Invalid response from the network access group service.")
if isinstance(exc, NetworkAccessGroupUpstreamError):
- return _translate_upstream_error(exc)
+ return BillingUnavailableError() if exc.unavailable else BillingOperationFailedError()
+ if isinstance(exc, NetworkAccessGroupInvalidInputError):
+ return console_errors.NetworkAccessInvalidInputError()
+ if isinstance(exc, NetworkAccessGroupForbiddenError):
+ return console_errors.NetworkAccessForbiddenError()
+ if isinstance(exc, NetworkAccessGroupNotEntitledError):
+ return console_errors.NetworkAccessNotEntitledError()
+ if isinstance(exc, NetworkAccessGroupNotFoundError):
+ return console_errors.NetworkAccessGroupNotFoundError()
+ if isinstance(exc, NetworkAccessGroupVersionConflictError):
+ return console_errors.NetworkAccessVersionConflictError()
+ if isinstance(exc, NetworkAccessGroupNameConflictError):
+ return console_errors.NetworkAccessGroupNameConflictError()
+ if isinstance(exc, NetworkAccessGroupBoundError):
+ return console_errors.NetworkAccessGroupBoundError()
if isinstance(exc, NetworkAccessGroupAccessDeniedError):
- return Forbidden("Your workspace role does not allow this network access operation.")
+ return console_errors.NetworkAccessRoleDeniedError()
if isinstance(exc, NetworkAccessGroupEntitlementUnavailableError):
return ServiceUnavailable("Billing entitlement is temporarily unavailable.")
if isinstance(exc, NetworkAccessGroupAppNotFoundError):
return AppNotFoundError()
if isinstance(exc, NetworkAccessGroupUnsupportedAppModeError):
- return BadRequest(f"Network access control is not supported for app mode '{exc.app_mode}'.")
+ return console_errors.NetworkAccessUnsupportedAppModeError(
+ f"Network access control is not supported for app mode '{exc.app_mode}'."
+ )
if isinstance(exc, NetworkAccessGroupUnsupportedAccessPointsError):
- return BadRequest(f"Unsupported access points for this app: {', '.join(exc.access_points)}.")
+ return console_errors.NetworkAccessUnsupportedAccessPointsError(
+ f"Unsupported access points for this app: {', '.join(exc.access_points)}."
+ )
if isinstance(exc, NetworkAccessGroupInvalidPolicyError):
return ServiceUnavailable("Network access policy cannot be evaluated.")
raise TypeError(f"Unsupported network access group error: {type(exc).__name__}")
@@ -261,6 +275,7 @@ def _resolve_current_network_access_client_ip() -> str:
@console_ns.route("/workspaces/current/network-access-groups")
class CurrentWorkspaceNetworkAccessGroupsApi(Resource):
+ @error_responses(*_CONTROL_PLANE_ERRORS)
@console_ns.response(
200,
"Workspace network access groups retrieved successfully",
@@ -277,6 +292,12 @@ class CurrentWorkspaceNetworkAccessGroupsApi(Resource):
raise _translate_service_error(exc) from exc
return _serialize_response(NetworkAccessGroupListResponse, payload)
+ @error_responses(
+ *_CONTROL_PLANE_ERRORS,
+ console_errors.NetworkAccessGroupNameConflictError,
+ console_errors.NetworkAccessInvalidInputError,
+ PaidPlanRequiredError,
+ )
@console_ns.expect(console_ns.models[NetworkAccessGroupCreatePayload.__name__])
@console_ns.response(
201,
@@ -308,6 +329,7 @@ class CurrentWorkspaceNetworkAccessGroupsApi(Resource):
@console_ns.route("/workspaces/current/network-access-groups/<uuid:group_id>")
class CurrentWorkspaceNetworkAccessGroupApi(Resource):
+ @error_responses(*_CONTROL_PLANE_ERRORS, console_errors.NetworkAccessGroupNotFoundError)
@console_ns.response(
200,
"Workspace network access group retrieved successfully",
@@ -324,6 +346,14 @@ class CurrentWorkspaceNetworkAccessGroupApi(Resource):
raise _translate_service_error(exc) from exc
return _serialize_response(NetworkAccessGroupMutationResponse, {"group": payload})
+ @error_responses(
+ *_CONTROL_PLANE_ERRORS,
+ console_errors.NetworkAccessGroupNameConflictError,
+ console_errors.NetworkAccessGroupNotFoundError,
+ console_errors.NetworkAccessInvalidInputError,
+ console_errors.NetworkAccessVersionConflictError,
+ PaidPlanRequiredError,
+ )
@console_ns.expect(console_ns.models[NetworkAccessGroupUpdatePayload.__name__])
@console_ns.response(
200,
@@ -355,6 +385,13 @@ class CurrentWorkspaceNetworkAccessGroupApi(Resource):
raise _translate_service_error(exc) from exc
return _serialize_response(NetworkAccessGroupMutationResponse, {"group": payload})
+ @error_responses(
+ *_CONTROL_PLANE_ERRORS,
+ console_errors.NetworkAccessGroupBoundError,
+ console_errors.NetworkAccessGroupNotFoundError,
+ console_errors.NetworkAccessVersionConflictError,
+ PaidPlanRequiredError,
+ )
@console_ns.doc(params=query_params_from_model(NetworkAccessGroupDeleteQuery))
@console_ns.response(
200,
@@ -386,6 +423,7 @@ class CurrentWorkspaceNetworkAccessGroupApi(Resource):
@console_ns.route("/workspaces/current/network-access-groups/current-ip")
class CurrentWorkspaceNetworkAccessGroupCurrentIPApi(Resource):
+ @error_responses(console_errors.NetworkAccessRoleDeniedError)
@console_ns.response(
200,
"Trusted current client IP retrieved without requiring an existing network access group",
@@ -414,6 +452,7 @@ class CurrentWorkspaceNetworkAccessGroupCurrentIPApi(Resource):
@console_ns.route("/workspaces/current/network-access-groups/<uuid:group_id>/check-current-ip")
class CurrentWorkspaceNetworkAccessGroupCurrentIPCheckApi(Resource):
+ @error_responses(*_CONTROL_PLANE_ERRORS, console_errors.NetworkAccessGroupNotFoundError)
@console_ns.response(
200,
"Current client IP checked against the workspace network access group",
@@ -441,7 +480,7 @@ class CurrentWorkspaceNetworkAccessGroupCurrentIPCheckApi(Resource):
@console_ns.route("/apps/<uuid:app_id>/network-access-group")
class AppNetworkAccessGroupApi(Resource):
- @error_responses(AppNotFoundError)
+ @error_responses(AppNotFoundError, *_CONTROL_PLANE_ERRORS, console_errors.NetworkAccessUnsupportedAppModeError)
@console_ns.response(
200,
"App network access group binding retrieved successfully",
@@ -458,7 +497,16 @@ class AppNetworkAccessGroupApi(Resource):
raise _translate_service_error(exc) from exc
return _serialize_response(AppNetworkAccessGroupResponse, payload)
- @error_responses(AppNotFoundError)
+ @error_responses(
+ AppNotFoundError,
+ *_CONTROL_PLANE_ERRORS,
+ console_errors.NetworkAccessGroupNotFoundError,
+ console_errors.NetworkAccessInvalidInputError,
+ console_errors.NetworkAccessUnsupportedAccessPointsError,
+ console_errors.NetworkAccessUnsupportedAppModeError,
+ console_errors.NetworkAccessVersionConflictError,
+ PaidPlanRequiredError,
+ )
@console_ns.expect(console_ns.models[AppNetworkAccessGroupUpdatePayload.__name__])
@console_ns.response(
200,
@@ -490,7 +538,7 @@ class AppNetworkAccessGroupApi(Resource):
@console_ns.route("/apps/<uuid:app_id>/network-access-group/status")
class AppNetworkAccessGroupStatusApi(Resource):
- @error_responses(AppNotFoundError)
+ @error_responses(AppNotFoundError, *_CONTROL_PLANE_ERRORS, console_errors.NetworkAccessUnsupportedAppModeError)
@console_ns.response(
200,
"App network access control entry status retrieved successfully",
diff --git a/api/controllers/console/wraps.py b/api/controllers/console/wraps.py
index ca890de7dbf..e00803cdfd0 100644
--- a/api/controllers/console/wraps.py
+++ b/api/controllers/console/wraps.py
@@ -14,6 +14,7 @@ from configs import dify_config
from controllers.common.rbac import RBACPermission, RBACResourceScope
from controllers.common.wraps import rbac_permission_required
from controllers.console.auth.error import AuthenticationFailedError, EmailCodeError
+from controllers.console.error import PaidPlanRequiredError
from controllers.console.workspace.error import AccountNotInitializedError
from enums import CloudPlan, DeploymentEdition
from extensions.ext_application_services import application_services
@@ -182,7 +183,7 @@ def cloud_edition_billing_paid_plan_required[**P, R](view: Callable[P, R]) -> Ca
def decorated(*args: P.args, **kwargs: P.kwargs):
_, current_tenant_id = current_account_with_tenant()
if not is_cloud_edition_billing_paid_plan(current_tenant_id):
- abort(403, "This feature requires a paid plan.")
+ raise PaidPlanRequiredError()
return view(*args, **kwargs)
return decorated
diff --git a/api/dev/generate_billing_client.py b/api/dev/generate_billing_client.py
index 427e3f434bd..d7b7c08f350 100644
--- a/api/dev/generate_billing_client.py
+++ b/api/dev/generate_billing_client.py
@@ -1,8 +1,9 @@
"""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` and the schemas they reach 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, and each service's
+`ERROR_SCHEMAS` are snapshotted: dify is public, and every other dify-saas endpoint stays out of
+this repository.
uv run --project api --dev python api/dev/generate_billing_client.py # snapshot + generate
uv run --project api --dev python api/dev/generate_billing_client.py --from-snapshot # generate only
@@ -56,6 +57,7 @@ SNAPSHOT_COMMIT_KEY = "x-dify-saas-commit"
HTTP_METHODS = ("get", "post", "put", "delete", "patch")
LINE_LENGTH = 120
BASE_MODEL_ATTRIBUTES = frozenset(dir(BaseModel))
+ERROR_SCHEMAS = ("Error", "ErrorReason")
@dataclass(frozen=True)
@@ -213,8 +215,11 @@ def build_snapshot(service: Service, source: JsonObject, commit: str) -> JsonObj
name.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")
reachable: set[str] = set()
- pending = _ref_names(paths)
+ pending = _ref_names(paths) | set(ERROR_SCHEMAS)
while pending:
name = pending.pop()
if name in reachable:
@@ -342,6 +347,30 @@ def model_order(schemas: dict[str, JsonObject]) -> list[str]:
return ordered
+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"},
+ "message": {"type": "string"},
+ "metadata": {"type": "object", "additionalProperties": {"type": "string"}},
+ }
+ actual = {
+ name: {key: value for key, value in field.items() if key != "description"} for name, field in properties.items()
+ }
+ if actual != expected:
+ raise GenerationError(f"Error is now {json.dumps(actual)}; update UpstreamErrorBody and the transport")
+
+
+def render_schema(name: str, schema: JsonObject) -> list[str]:
+ if name == "Error":
+ check_error_body(schema)
+ return []
+ if "enum" in schema:
+ return [f"type {name} = {python_type(schema, name)}"]
+ return render_model(name, schema)
+
+
def render_model(name: str, schema: JsonObject) -> list[str]:
if schema.get("type") != "object":
raise GenerationError(f"schema {name}: only object schemas can be top-level models")
@@ -409,6 +438,7 @@ def render_operation(service: Service, allowed: AllowedOperation, operation: Jso
f" {json.dumps(allowed.method)},",
f" {json.dumps(template)},",
f" response_model={response},",
+ " errors=ERRORS,",
f" path_params={{{', '.join(path_params)}}},",
f" params={{{', '.join(query_params)}}},",
f" body={body},",
@@ -416,9 +446,42 @@ 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__)
+
+
+class UpstreamError(BillingUpstreamError):
+ """A failed {service} call, with its reason typed by this module's `ErrorReason`."""
+
+ def __init__(
+ self,
+ *args: object,
+ status_code: int | None = None,
+ body: UpstreamErrorBody | None = None,
+ reason: ErrorReason | UnknownErrorReason | None = None,
+ ) -> None:
+ super().__init__(*args, status_code=status_code, body=body)
+ self.reason = reason
+
+
+class UpstreamUnavailableError(UpstreamError, BillingUpstreamUnavailableError):
+ pass
+
+
+class UpstreamInvalidResponseError(UpstreamError, BillingUpstreamInvalidResponseError):
+ pass
+
+
+ERRORS = ServiceErrors(
+ is_reason=_is_error_reason, unavailable=UpstreamUnavailableError, invalid_response=UpstreamInvalidResponseError
+)'''.splitlines()
+
+
def render_module(service: Service, snapshot: JsonObject) -> str:
schemas: dict[str, JsonObject] = snapshot["components"]["schemas"]
- blocks = [render_model(name, schemas[name]) for name in model_order(schemas)]
+ blocks = [block for name in model_order(schemas) if (block := render_schema(name, schemas[name]))]
+ blocks.append(render_errors(service))
for allowed in ALLOWED_OPERATIONS[service]:
operation = snapshot["paths"][allowed.path][allowed.method.lower()]
blocks.append(render_operation(service, allowed, operation))
@@ -429,11 +492,18 @@ def render_module(service: Service, snapshot: JsonObject) -> str:
f"# dify-saas commit: {snapshot[SNAPSHOT_COMMIT_KEY]}",
"",
"from datetime import datetime",
- "from typing import Literal",
+ "from typing import Literal, TypeIs, get_args",
"",
"from pydantic import Field",
"",
- "from services.billing_client.transport import BillingModel, Upstream, request",
+ "from services.billing_client.transport import BillingModel, ServiceErrors, Upstream, request",
+ "from services.errors.billing import (",
+ " BillingUpstreamError,",
+ " BillingUpstreamInvalidResponseError,",
+ " BillingUpstreamUnavailableError,",
+ " UnknownErrorReason,",
+ " UpstreamErrorBody,",
+ ")",
]
return format_python("\n".join(header) + "\n\n\n" + body + "\n", module_path(service))
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index 14515e8b59f..f7a1a956b08 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -135,6 +135,9 @@ Get account avatar url
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | **application/json**: [EducationStatusResponse](#educationstatusresponse)<br> |
+| 429 | Too Many Requests | **application/json**: [BillingRequestInProgressError](#billingrequestinprogresserror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 503 | Service Unavailable | **application/json**: [BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [POST] /account/education
@@ -149,8 +152,10 @@ Get account avatar url
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | **application/json**: [EducationActivateResponse](#educationactivateresponse)<br> |
-| 400 | Bad Request | **application/json**: [AccountNotFoundError](#accountnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
-| 429 | Too Many Requests | **application/json**: [EducationActivateLimitError](#educationactivatelimiterror)<br>[ErrorResponse](#errorresponse)<br> |
+| 400 | Bad Request | **application/json**: [AccountNotFoundError](#accountnotfounderror)<br>[EducationActivateFailedError](#educationactivatefailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 429 | Too Many Requests | **application/json**: [BillingRequestInProgressError](#billingrequestinprogresserror)<br>[EducationActivateLimitError](#educationactivatelimiterror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 503 | Service Unavailable | **application/json**: [BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [GET] /account/education/autocomplete
@@ -167,6 +172,8 @@ Get account avatar url
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | **application/json**: [EducationAutocompleteResponse](#educationautocompleteresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 503 | Service Unavailable | **application/json**: [BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [GET] /account/education/verify
@@ -175,8 +182,10 @@ Get account avatar url
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | **application/json**: [EducationVerifyResponse](#educationverifyresponse)<br> |
-| 400 | Bad Request | **application/json**: [AccountNotFoundError](#accountnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
-| 429 | Too Many Requests | **application/json**: [EducationVerifyLimitError](#educationverifylimiterror)<br>[ErrorResponse](#errorresponse)<br> |
+| 400 | Bad Request | **application/json**: [AccountNotFoundError](#accountnotfounderror)<br>[EducationVerifyFailedError](#educationverifyfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 429 | Too Many Requests | **application/json**: [BillingRequestInProgressError](#billingrequestinprogresserror)<br>[EducationVerifyLimitError](#educationverifylimiterror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 503 | Service Unavailable | **application/json**: [BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [POST] /account/init
@@ -3320,7 +3329,11 @@ Check if app name is available
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | App network access group binding retrieved successfully | **application/json**: [AppNetworkAccessGroupResponse](#appnetworkaccessgroupresponse)<br> |
+| 400 | Bad Request | **application/json**: [NetworkAccessUnsupportedAppModeError](#networkaccessunsupportedappmodeerror)<br>[ErrorResponse](#errorresponse)<br> |
+| 403 | Forbidden | **application/json**: [NetworkAccessForbiddenError](#networkaccessforbiddenerror)<br>[NetworkAccessNotEntitledError](#networkaccessnotentitlederror)<br>[NetworkAccessRoleDeniedError](#networkaccessroledeniederror)<br>[ErrorResponse](#errorresponse)<br> |
| 404 | Not Found | **application/json**: [AppNotFoundError](#appnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 503 | Service Unavailable | **application/json**: [BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [PUT] /apps/{app_id}/network-access-group
@@ -3341,7 +3354,12 @@ Check if app name is available
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | App network access group binding updated successfully | **application/json**: [AppNetworkAccessGroupMutationResponse](#appnetworkaccessgroupmutationresponse)<br> |
-| 404 | Not Found | **application/json**: [AppNotFoundError](#appnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
+| 400 | Bad Request | **application/json**: [NetworkAccessInvalidInputError](#networkaccessinvalidinputerror)<br>[NetworkAccessUnsupportedAccessPointsError](#networkaccessunsupportedaccesspointserror)<br>[NetworkAccessUnsupportedAppModeError](#networkaccessunsupportedappmodeerror)<br>[ErrorResponse](#errorresponse)<br> |
+| 403 | Forbidden | **application/json**: [NetworkAccessForbiddenError](#networkaccessforbiddenerror)<br>[NetworkAccessNotEntitledError](#networkaccessnotentitlederror)<br>[NetworkAccessRoleDeniedError](#networkaccessroledeniederror)<br>[PaidPlanRequiredError](#paidplanrequirederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 404 | Not Found | **application/json**: [AppNotFoundError](#appnotfounderror)<br>[NetworkAccessGroupNotFoundError](#networkaccessgroupnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
+| 409 | Conflict | **application/json**: [NetworkAccessVersionConflictError](#networkaccessversionconflicterror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 503 | Service Unavailable | **application/json**: [BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [GET] /apps/{app_id}/network-access-group/status
@@ -3356,7 +3374,11 @@ Check if app name is available
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | App network access control entry status retrieved successfully | **application/json**: [AppNetworkAccessGroupStatusResponse](#appnetworkaccessgroupstatusresponse)<br> |
+| 400 | Bad Request | **application/json**: [NetworkAccessUnsupportedAppModeError](#networkaccessunsupportedappmodeerror)<br>[ErrorResponse](#errorresponse)<br> |
+| 403 | Forbidden | **application/json**: [NetworkAccessForbiddenError](#networkaccessforbiddenerror)<br>[NetworkAccessNotEntitledError](#networkaccessnotentitlederror)<br>[NetworkAccessRoleDeniedError](#networkaccessroledeniederror)<br>[ErrorResponse](#errorresponse)<br> |
| 404 | Not Found | **application/json**: [AppNotFoundError](#appnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 503 | Service Unavailable | **application/json**: [BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [POST] /apps/{app_id}/publish-to-creators-platform
@@ -5879,8 +5901,10 @@ Get compliance document download link
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | **application/json**: [ComplianceDownloadResponse](#compliancedownloadresponse)<br> |
+| 403 | Forbidden | **application/json**: [ComplianceDownloadForbiddenError](#compliancedownloadforbiddenerror)<br>[ErrorResponse](#errorresponse)<br> |
+| 404 | Not Found | **application/json**: [ComplianceDocumentNotFoundError](#compliancedocumentnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
| 422 | Invalid compliance download query | **application/json**: [BillingUnprocessableEntityErrorResponse](#billingunprocessableentityerrorresponse)<br>[ErrorResponse](#errorresponse)<br> |
-| 429 | Compliance download rate limit exceeded | **application/json**: [ComplianceRateLimitErrorResponse](#complianceratelimiterrorresponse)<br>[ComplianceRateLimitError](#complianceratelimiterror)<br>[ErrorResponse](#errorresponse)<br> |
+| 429 | Compliance download rate limit exceeded | **application/json**: [ComplianceRateLimitErrorResponse](#complianceratelimiterrorresponse)<br>[BillingRequestInProgressError](#billingrequestinprogresserror)<br>[ComplianceRateLimitError](#complianceratelimiterror)<br>[ErrorResponse](#errorresponse)<br> |
| 502 | Compliance download failed | **application/json**: [BillingOperationFailedErrorResponse](#billingoperationfailederrorresponse)<br>[BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
| 503 | Billing unavailable | **application/json**: [BillingUnavailableErrorResponse](#billingunavailableerrorresponse)<br>[BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
@@ -14100,6 +14124,7 @@ List monthly workflow-run archive metadata for the current workspace
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | **application/json**: [WorkflowRunArchiveListResponse](#workflowrunarchivelistresponse)<br> |
+| 403 | Forbidden | **application/json**: [PaidPlanRequiredError](#paidplanrequirederror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [POST] /workflow-run-archives/downloads
@@ -14116,6 +14141,7 @@ Create or return a temporary workflow-run archive download task
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 202 | Download task accepted | **application/json**: [WorkflowRunArchiveDownloadTaskResponse](#workflowrunarchivedownloadtaskresponse)<br> |
+| 403 | Forbidden | **application/json**: [PaidPlanRequiredError](#paidplanrequirederror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [GET] /workflow-run-archives/downloads/{download_id}
@@ -14132,6 +14158,7 @@ Get a temporary workflow-run archive download task
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | **application/json**: [WorkflowRunArchiveDownloadTaskResponse](#workflowrunarchivedownloadtaskresponse)<br> |
+| 403 | Forbidden | **application/json**: [PaidPlanRequiredError](#paidplanrequirederror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [GET] /workflow-run-archives/downloads/{download_id}/file
@@ -14148,6 +14175,7 @@ Redirect to a prepared workflow-run archive ZIP file
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 302 | Redirect to pre-signed archive storage URL | **application/json**: [RedirectResponse](#redirectresponse)<br> |
+| 403 | Forbidden | **application/json**: [PaidPlanRequiredError](#paidplanrequirederror)<br>[ErrorResponse](#errorresponse)<br> |
| 409 | Download task is not ready | **application/json**: [ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
@@ -14166,6 +14194,7 @@ Permanently delete this workspace's monthly archive files and archive index
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 202 | Archive deletion accepted | **application/json**: [WorkflowRunArchiveDeletionTaskResponse](#workflowrunarchivedeletiontaskresponse)<br> |
+| 403 | Forbidden | **application/json**: [PaidPlanRequiredError](#paidplanrequirederror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [GET] /workflow/{workflow_run_id}/events
@@ -15839,6 +15868,9 @@ Migrate node data from HITLv1 to HITLv2. A missing legacy version defaults to "1
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Workspace network access groups retrieved successfully | **application/json**: [NetworkAccessGroupListResponse](#networkaccessgrouplistresponse)<br> |
+| 403 | Forbidden | **application/json**: [NetworkAccessForbiddenError](#networkaccessforbiddenerror)<br>[NetworkAccessNotEntitledError](#networkaccessnotentitlederror)<br>[NetworkAccessRoleDeniedError](#networkaccessroledeniederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 503 | Service Unavailable | **application/json**: [BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [POST] /workspaces/current/network-access-groups
@@ -15853,6 +15885,11 @@ Migrate node data from HITLv1 to HITLv2. A missing legacy version defaults to "1
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Workspace network access group created successfully | **application/json**: [NetworkAccessGroupMutationResponse](#networkaccessgroupmutationresponse)<br> |
+| 400 | Bad Request | **application/json**: [NetworkAccessInvalidInputError](#networkaccessinvalidinputerror)<br>[ErrorResponse](#errorresponse)<br> |
+| 403 | Forbidden | **application/json**: [NetworkAccessForbiddenError](#networkaccessforbiddenerror)<br>[NetworkAccessNotEntitledError](#networkaccessnotentitlederror)<br>[NetworkAccessRoleDeniedError](#networkaccessroledeniederror)<br>[PaidPlanRequiredError](#paidplanrequirederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 409 | Conflict | **application/json**: [NetworkAccessGroupNameConflictError](#networkaccessgroupnameconflicterror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 503 | Service Unavailable | **application/json**: [BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [GET] /workspaces/current/network-access-groups/current-ip
@@ -15861,7 +15898,7 @@ Migrate node data from HITLv1 to HITLv2. A missing legacy version defaults to "1
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Trusted current client IP retrieved without requiring an existing network access group | **application/json**: [NetworkAccessGroupCurrentIPResponse](#networkaccessgroupcurrentipresponse)<br> |
-| 403 | The workspace role does not allow network access policy reads | **application/json**: [ErrorResponse](#errorresponse)<br> |
+| 403 | The workspace role does not allow network access policy reads | **application/json**: [NetworkAccessRoleDeniedError](#networkaccessroledeniederror)<br>[ErrorResponse](#errorresponse)<br> |
| 503 | A trusted current client IP is unavailable | **application/json**: [ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
@@ -15878,6 +15915,11 @@ Migrate node data from HITLv1 to HITLv2. A missing legacy version defaults to "1
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Workspace network access group deleted successfully | **application/json**: [NetworkAccessGroupDeleteResponse](#networkaccessgroupdeleteresponse)<br> |
+| 403 | Forbidden | **application/json**: [NetworkAccessForbiddenError](#networkaccessforbiddenerror)<br>[NetworkAccessNotEntitledError](#networkaccessnotentitlederror)<br>[NetworkAccessRoleDeniedError](#networkaccessroledeniederror)<br>[PaidPlanRequiredError](#paidplanrequirederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 404 | Not Found | **application/json**: [NetworkAccessGroupNotFoundError](#networkaccessgroupnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
+| 409 | Conflict | **application/json**: [NetworkAccessGroupBoundError](#networkaccessgroupbounderror)<br>[NetworkAccessVersionConflictError](#networkaccessversionconflicterror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 503 | Service Unavailable | **application/json**: [BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [GET] /workspaces/current/network-access-groups/{group_id}
@@ -15892,6 +15934,10 @@ Migrate node data from HITLv1 to HITLv2. A missing legacy version defaults to "1
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Workspace network access group retrieved successfully | **application/json**: [NetworkAccessGroupMutationResponse](#networkaccessgroupmutationresponse)<br> |
+| 403 | Forbidden | **application/json**: [NetworkAccessForbiddenError](#networkaccessforbiddenerror)<br>[NetworkAccessNotEntitledError](#networkaccessnotentitlederror)<br>[NetworkAccessRoleDeniedError](#networkaccessroledeniederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 404 | Not Found | **application/json**: [NetworkAccessGroupNotFoundError](#networkaccessgroupnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 503 | Service Unavailable | **application/json**: [BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [PUT] /workspaces/current/network-access-groups/{group_id}
@@ -15912,6 +15958,12 @@ Migrate node data from HITLv1 to HITLv2. A missing legacy version defaults to "1
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Workspace network access group updated successfully | **application/json**: [NetworkAccessGroupMutationResponse](#networkaccessgroupmutationresponse)<br> |
+| 400 | Bad Request | **application/json**: [NetworkAccessInvalidInputError](#networkaccessinvalidinputerror)<br>[ErrorResponse](#errorresponse)<br> |
+| 403 | Forbidden | **application/json**: [NetworkAccessForbiddenError](#networkaccessforbiddenerror)<br>[NetworkAccessNotEntitledError](#networkaccessnotentitlederror)<br>[NetworkAccessRoleDeniedError](#networkaccessroledeniederror)<br>[PaidPlanRequiredError](#paidplanrequirederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 404 | Not Found | **application/json**: [NetworkAccessGroupNotFoundError](#networkaccessgroupnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
+| 409 | Conflict | **application/json**: [NetworkAccessGroupNameConflictError](#networkaccessgroupnameconflicterror)<br>[NetworkAccessVersionConflictError](#networkaccessversionconflicterror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 503 | Service Unavailable | **application/json**: [BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [GET] /workspaces/current/network-access-groups/{group_id}/check-current-ip
@@ -15926,6 +15978,10 @@ Migrate node data from HITLv1 to HITLv2. A missing legacy version defaults to "1
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Current client IP checked against the workspace network access group | **application/json**: [NetworkAccessGroupCurrentIPCheckResponse](#networkaccessgroupcurrentipcheckresponse)<br> |
+| 403 | Forbidden | **application/json**: [NetworkAccessForbiddenError](#networkaccessforbiddenerror)<br>[NetworkAccessNotEntitledError](#networkaccessnotentitlederror)<br>[NetworkAccessRoleDeniedError](#networkaccessroledeniederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 404 | Not Found | **application/json**: [NetworkAccessGroupNotFoundError](#networkaccessgroupnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [BillingOperationFailedError](#billingoperationfailederror)<br>[ErrorResponse](#errorresponse)<br> |
+| 503 | Service Unavailable | **application/json**: [BillingUnavailableError](#billingunavailableerror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [GET] /workspaces/current/permission
@@ -22932,6 +22988,14 @@ We couldn't complete this request. Please try again. If the problem persists, co
| message | string | | Yes |
| status | integer | | Yes |
+#### BillingRequestInProgressError
+
+A previous request is still being processed. Please try again shortly.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| BillingRequestInProgressError | | A previous request is still being processed. Please try again shortly. | |
+
#### BillingSubscriptionResponse
| Name | Type | Description | Required |
@@ -23410,6 +23474,22 @@ Completion request failed.
| ---- | ---- | ----------- | -------- |
| CompletionRequestError | | Completion request failed. | |
+#### ComplianceDocumentNotFoundError
+
+The compliance document was not found.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| ComplianceDocumentNotFoundError | | The compliance document was not found. | |
+
+#### ComplianceDownloadForbiddenError
+
+Your current plan does not allow downloading this compliance document.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| ComplianceDownloadForbiddenError | | Your current plan does not allow downloading this compliance document. | |
+
#### ComplianceDownloadQuery
| Name | Type | Description | Required |
@@ -25359,6 +25439,14 @@ Portable DSL reference that could not be restored in the target workspace.
| selector | [ string ] | | Yes |
| type | string, <br>**Default:** dynamic_email | | No |
+#### EducationActivateFailedError
+
+We couldn't activate your education discount.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| EducationActivateFailedError | | We couldn't activate your education discount. | |
+
#### EducationActivateLimitError
Rate limit exceeded
@@ -25420,6 +25508,14 @@ Rate limit exceeded
| status | string | | Yes |
| token | string | | Yes |
+#### EducationVerifyFailedError
+
+We couldn't verify your education status.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| EducationVerifyFailedError | | We couldn't verify your education status. | |
+
#### EducationVerifyLimitError
Rate limit exceeded
@@ -31247,6 +31343,14 @@ Need to add ids.
| ---- | ---- | ----------- | -------- |
| NeedAddIdsError | | Need to add ids. | |
+#### NetworkAccessForbiddenError
+
+Network access groups are not available for this workspace.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| NetworkAccessForbiddenError | | Network access groups are not available for this workspace. | |
+
#### NetworkAccessGroupAppResponse
| Name | Type | Description | Required |
@@ -31259,6 +31363,14 @@ Need to add ids.
| mode | string | | Yes |
| name | string | | Yes |
+#### NetworkAccessGroupBoundError
+
+This IP policy is still used by one or more apps.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| NetworkAccessGroupBoundError | | This IP policy is still used by one or more apps. | |
+
#### NetworkAccessGroupCreatePayload
| Name | Type | Description | Required |
@@ -31301,6 +31413,22 @@ Need to add ids.
| ---- | ---- | ----------- | -------- |
| group | [NetworkAccessGroupResponse](#networkaccessgroupresponse) | | Yes |
+#### NetworkAccessGroupNameConflictError
+
+An IP policy with this name already exists.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| NetworkAccessGroupNameConflictError | | An IP policy with this name already exists. | |
+
+#### NetworkAccessGroupNotFoundError
+
+Network access group was not found.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| NetworkAccessGroupNotFoundError | | Network access group was not found. | |
+
#### NetworkAccessGroupResponse
| Name | Type | Description | Required |
@@ -31328,6 +31456,54 @@ Need to add ids.
| expected_version | integer | | Yes |
| name | string | | Yes |
+#### NetworkAccessInvalidInputError
+
+Invalid network access group request.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| NetworkAccessInvalidInputError | | Invalid network access group request. | |
+
+#### NetworkAccessNotEntitledError
+
+Network access groups are not available for this workspace.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| NetworkAccessNotEntitledError | | Network access groups are not available for this workspace. | |
+
+#### NetworkAccessRoleDeniedError
+
+Your workspace role does not allow this network access operation.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| NetworkAccessRoleDeniedError | | Your workspace role does not allow this network access operation. | |
+
+#### NetworkAccessUnsupportedAccessPointsError
+
+Some access points are not supported for this app.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| NetworkAccessUnsupportedAccessPointsError | | Some access points are not supported for this app. | |
+
+#### NetworkAccessUnsupportedAppModeError
+
+Network access control is not supported for this app mode.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| NetworkAccessUnsupportedAppModeError | | Network access control is not supported for this app mode. | |
+
+#### NetworkAccessVersionConflictError
+
+The network access resource changed. Refresh it and try again.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| NetworkAccessVersionConflictError | | The network access resource changed. Refresh it and try again. | |
+
#### NewAppResponse
| Name | Type | Description | Required |
@@ -31896,6 +32072,14 @@ Too many owner transfer emails have been sent. Please try again in {minutes} min
| limit | integer, <br>**Default:** 20 | | No |
| page | integer, <br>**Default:** 1 | | No |
+#### PaidPlanRequiredError
+
+This feature requires a paid plan.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| PaidPlanRequiredError | | This feature requires a paid plan. | |
+
#### ParagraphInput
Resolved multiline text input.
diff --git a/api/services/account/adapters.py b/api/services/account/adapters.py
index 8780e7afe0b..b9469f88f90 100644
--- a/api/services/account/adapters.py
+++ b/api/services/account/adapters.py
@@ -3,7 +3,8 @@
import logging
import secrets
import uuid
-from collections.abc import Sequence
+from collections.abc import Generator, Sequence
+from contextlib import contextmanager
from datetime import timedelta
from hashlib import sha256
from typing import assert_never, override
@@ -40,7 +41,13 @@ from services.account_change_email_ports import (
)
from services.account_deletion_feedback_service import AccountDeletionFeedbackGateway
from services.account_education_service import AccountEducationGateway
-from services.account_errors import AccountDeletionRateLimitError
+from services.account_errors import (
+ AccountApplicationError,
+ AccountDeletionRateLimitError,
+ EducationActivationFailedError,
+ EducationRequestInProgressError,
+ EducationVerificationFailedError,
+)
from services.account_ports import (
AccountDeletionScheduler,
AccountDeletionSyncGateway,
@@ -48,6 +55,7 @@ from services.account_ports import (
AccountDeletionVerificationNotifier,
)
from services.account_security_gateway import RedisAccountEmailSecurityGateway
+from services.billing_client import billing
from services.billing_service import BillingService
from services.enterprise.account_deletion_sync import sync_account_deletion_memberships
from services.enterprise.enterprise_service import try_join_default_workspace
@@ -74,6 +82,7 @@ from services.entities.auth_entities import (
ChangeEmailOldEmailVerifiedToken,
ChangeEmailTokenData,
)
+from services.errors.billing import UnknownErrorReason
from services.telemetry_service import CommunityTelemetryService
from tasks.delete_account_task import delete_account_task
from tasks.mail_account_deletion_task import send_account_deletion_verification_code
@@ -267,10 +276,109 @@ class RBACWorkspaceMemberAccessSync(WorkspaceMemberAccessSync):
)
+def _education_error(error: billing.UpstreamError) -> 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":
+ return EducationVerificationFailedError()
+ case "EDUCATION_CREATE_FAILED":
+ return EducationActivationFailedError()
+ case "REQUEST_IN_PROGRESS":
+ return EducationRequestInProgressError()
+ case (
+ ""
+ | "CODEC"
+ | "VALIDATOR"
+ | "UNKNOWN"
+ | "INVALID_SECRET_KEY"
+ | "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_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 None
+ case UnknownErrorReason() | None:
+ return None
+ case unreachable:
+ assert_never(unreachable)
+
+
+@contextmanager
+def _education_errors() -> Generator[None]:
+ try:
+ yield
+ except billing.UpstreamError as error:
+ mapped = _education_error(error)
+ if mapped is None:
+ raise
+ raise mapped from error
+
+
class BillingAccountEducationGateway(AccountEducationGateway):
@override
def verify(self, *, account_id: str) -> AccountEducationVerification:
- result = BillingService.EducationIdentity.verify(account_id=account_id)
+ with _education_errors():
+ result = BillingService.EducationIdentity.verify(account_id=account_id)
match result.status:
case "eligible":
return AccountEducationEligible(token=result.token)
@@ -289,18 +397,20 @@ class BillingAccountEducationGateway(AccountEducationGateway):
institution: str,
role: str,
) -> AccountEducationActivation:
- result = BillingService.EducationIdentity.activate(
- account_id=account_id,
- tenant_id=tenant_id,
- token=token,
- institution=institution,
- role=role,
- )
+ with _education_errors():
+ result = BillingService.EducationIdentity.activate(
+ account_id=account_id,
+ tenant_id=tenant_id,
+ token=token,
+ institution=institution,
+ role=role,
+ )
return AccountEducationActivation(message=result.message)
@override
def status(self, account_id: str) -> AccountEducationStatus:
- result = BillingService.EducationIdentity.status(account_id)
+ with _education_errors():
+ result = BillingService.EducationIdentity.status(account_id)
return AccountEducationStatus(
result=result.result,
is_student=result.is_student,
@@ -310,7 +420,8 @@ class BillingAccountEducationGateway(AccountEducationGateway):
@override
def autocomplete(self, *, keywords: str, page: int, limit: int) -> AccountEducationAutocomplete:
- result = BillingService.EducationIdentity.autocomplete(keywords, page, limit)
+ with _education_errors():
+ result = BillingService.EducationIdentity.autocomplete(keywords, page, limit)
return AccountEducationAutocomplete(
data=tuple(result.data or ()),
curr_page=result.curr_page,
diff --git a/api/services/account_errors.py b/api/services/account_errors.py
index 0535bfd7305..88e13bdc127 100644
--- a/api/services/account_errors.py
+++ b/api/services/account_errors.py
@@ -260,6 +260,18 @@ class EducationRateLimitExceededError(AccountApplicationError):
"""Too many education verification or activation requests were made."""
+class EducationVerificationFailedError(AccountApplicationError):
+ """The billing service could not verify the account's education identity."""
+
+
+class EducationActivationFailedError(AccountApplicationError):
+ """The billing service could not create the account's education identity."""
+
+
+class EducationRequestInProgressError(AccountApplicationError):
+ """An earlier education request for the account is still being processed."""
+
+
class LoginRateLimitError(AccountApplicationError):
"""Too many failed password-login attempts were made for the address."""
diff --git a/api/services/billing_client/billing.openapi.json b/api/services/billing_client/billing.openapi.json
index 4386c5085c4..891791ccddb 100644
--- a/api/services/billing_client/billing.openapi.json
+++ b/api/services/billing_client/billing.openapi.json
@@ -829,6 +829,114 @@
"device_info"
]
},
+ "Error": {
+ "required": [
+ "code",
+ "reason",
+ "message",
+ "metadata"
+ ],
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "description": "HTTP status code.",
+ "format": "int32"
+ },
+ "reason": {
+ "$ref": "#/components/schemas/ErrorReason"
+ },
+ "message": {
+ "type": "string"
+ },
+ "metadata": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ }
+ },
+ "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.py
index 20d1c755273..4c3689b6f70 100644
--- a/api/services/billing_client/billing.py
+++ b/api/services/billing_client/billing.py
@@ -2,9 +2,16 @@
# dify-saas commit: 04f8d88cc15c5f62f14f8843a54f3e2e7e09ee5a
from datetime import datetime
-from typing import Literal
+from typing import Literal, TypeIs, get_args
-from services.billing_client.transport import BillingModel, Upstream, request
+from services.billing_client.transport import BillingModel, ServiceErrors, Upstream, request
+from services.errors.billing import (
+ BillingUpstreamError,
+ BillingUpstreamInvalidResponseError,
+ BillingUpstreamUnavailableError,
+ UnknownErrorReason,
+ UpstreamErrorBody,
+)
class AutocompleteEducationInstitutionReply(BillingModel):
@@ -59,6 +66,82 @@ 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: bool
is_student: bool
@@ -212,6 +295,37 @@ class VerifyEducationIdentityReply(BillingModel):
status: Literal["eligible", "not_eligible"]
+def _is_error_reason(value: str) -> TypeIs[ErrorReason]:
+ return value in get_args(ErrorReason.__value__)
+
+
+class UpstreamError(BillingUpstreamError):
+ """A failed billing call, with its reason typed by this module's `ErrorReason`."""
+
+ def __init__(
+ self,
+ *args: object,
+ status_code: int | None = None,
+ body: UpstreamErrorBody | None = None,
+ reason: ErrorReason | UnknownErrorReason | None = None,
+ ) -> None:
+ super().__init__(*args, status_code=status_code, body=body)
+ self.reason = reason
+
+
+class UpstreamUnavailableError(UpstreamError, BillingUpstreamUnavailableError):
+ pass
+
+
+class UpstreamInvalidResponseError(UpstreamError, BillingUpstreamInvalidResponseError):
+ pass
+
+
+ERRORS = ServiceErrors(
+ is_reason=_is_error_reason, unavailable=UpstreamUnavailableError, invalid_response=UpstreamInvalidResponseError
+)
+
+
def subscription_get_subscription_info(*, tenant_id: str, exclude_vector_space: bool) -> GetSubscriptionInfoReply:
"""GET /v1/subscription/info (BillingSubscription_GetSubscriptionInfo)."""
return request(
@@ -219,6 +333,7 @@ def subscription_get_subscription_info(*, tenant_id: str, exclude_vector_space:
"GET",
"/subscription/info",
response_model=GetSubscriptionInfoReply,
+ errors=ERRORS,
path_params={},
params={"tenant_id": tenant_id, "exclude_vector_space": exclude_vector_space},
body=None,
@@ -232,6 +347,7 @@ def subscription_get_subscription_vector_space(*, tenant_id: str, bypass_cache:
"GET",
"/subscription/vector-space",
response_model=VectorSpaceQuota,
+ errors=ERRORS,
path_params={},
params={"tenant_id": tenant_id, "bypass_cache": bypass_cache},
body=None,
@@ -245,6 +361,7 @@ def subscription_get_knowledge_rate_limit(*, tenant_id: str) -> GetKnowledgeRate
"GET",
"/subscription/knowledge-rate-limit",
response_model=GetKnowledgeRateLimitReply,
+ errors=ERRORS,
path_params={},
params={"tenant_id": tenant_id},
body=None,
@@ -260,6 +377,7 @@ def subscription_get_subscription_payment_link(
"GET",
"/subscription/payment-link",
response_model=GetSubscriptionPaymentLinkReply,
+ errors=ERRORS,
path_params={},
params={"plan": plan, "interval": interval, "prefilled_email": prefilled_email, "tenant_id": tenant_id},
body=None,
@@ -273,6 +391,7 @@ def subscription_batch_get_subscription_plan(*, body: BatchGetSubscriptionPlanRe
"POST",
"/subscription/plan/batch",
response_model=BatchGetSubscriptionPlanReply,
+ errors=ERRORS,
path_params={},
params={},
body=body,
@@ -286,6 +405,7 @@ def subscription_list_subscription_cleanup_whitelist() -> ListSubscriptionCleanu
"GET",
"/subscription/cleanup/whitelist",
response_model=ListSubscriptionCleanupWhitelistReply,
+ errors=ERRORS,
path_params={},
params={},
body=None,
@@ -301,6 +421,7 @@ def model_provider_get_model_provider_payment_link(
"GET",
"/model-provider/payment-link",
response_model=GetModelProviderPaymentLinkReply,
+ errors=ERRORS,
path_params={},
params={
"provider_name": provider_name,
@@ -319,6 +440,7 @@ def invoice_get_invoices(*, prefilled_email: str, tenant_id: str) -> GetInvoices
"GET",
"/invoices",
response_model=GetInvoicesReply,
+ errors=ERRORS,
path_params={},
params={"prefilled_email": prefilled_email, "tenant_id": tenant_id},
body=None,
@@ -332,6 +454,7 @@ def education_verify_education_identity(*, account_id: str) -> VerifyEducationId
"GET",
"/education/verify",
response_model=VerifyEducationIdentityReply,
+ errors=ERRORS,
path_params={},
params={"account_id": account_id},
body=None,
@@ -345,6 +468,7 @@ def education_get_education_identity_status(*, account_id: str) -> GetEducationI
"GET",
"/education/status",
response_model=GetEducationIdentityStatusReply,
+ errors=ERRORS,
path_params={},
params={"account_id": account_id},
body=None,
@@ -358,6 +482,7 @@ def education_create_education_identity(*, body: CreateEducationIdentityReq) ->
"POST",
"/education",
response_model=CreateEducationIdentityReply,
+ errors=ERRORS,
path_params={},
params={},
body=body,
@@ -373,6 +498,7 @@ def education_autocomplete_education_institution(
"GET",
"/education/autocomplete",
response_model=AutocompleteEducationInstitutionReply,
+ errors=ERRORS,
path_params={},
params={"keywords": keywords, "page": page, "limit": limit},
body=None,
@@ -386,6 +512,7 @@ def compliance_download_compliance_document(*, body: DownloadComplianceDocumentR
"POST",
"/compliance/download",
response_model=DownloadComplianceDocumentReply,
+ errors=ERRORS,
path_params={},
params={},
body=body,
@@ -399,6 +526,7 @@ def quota_get_quota_info(*, tenant_id: str) -> QuotaGetInfoReply:
"GET",
"/quota/info",
response_model=QuotaGetInfoReply,
+ errors=ERRORS,
path_params={},
params={"tenant_id": tenant_id},
body=None,
@@ -412,6 +540,7 @@ def quota_reserve(*, body: QuotaReserveReq) -> QuotaReserveReply:
"POST",
"/quota/reserve",
response_model=QuotaReserveReply,
+ errors=ERRORS,
path_params={},
params={},
body=body,
@@ -425,6 +554,7 @@ def quota_commit(*, body: QuotaCommitReq) -> QuotaCommitReply:
"POST",
"/quota/commit",
response_model=QuotaCommitReply,
+ errors=ERRORS,
path_params={},
params={},
body=body,
@@ -438,6 +568,7 @@ def quota_release(*, body: QuotaReleaseReq) -> QuotaReleaseReply:
"POST",
"/quota/release",
response_model=QuotaReleaseReply,
+ errors=ERRORS,
path_params={},
params={},
body=body,
@@ -451,6 +582,7 @@ def quota_get_balance(*, tenant_id: str, feature_key: str, bucket: str) -> Quota
"GET",
"/quota/balance",
response_model=QuotaGetBalanceReply,
+ errors=ERRORS,
path_params={},
params={"tenant_id": tenant_id, "feature_key": feature_key, "bucket": bucket},
body=None,
@@ -464,6 +596,7 @@ def quota_consume_capped(*, body: QuotaConsumeCappedReq) -> QuotaConsumeCappedRe
"POST",
"/quota/consume-capped",
response_model=QuotaConsumeCappedReply,
+ errors=ERRORS,
path_params={},
params={},
body=body,
diff --git a/api/services/billing_client/saas.openapi.json b/api/services/billing_client/saas.openapi.json
index 1fe53165268..0bd32e50654 100644
--- a/api/services/billing_client/saas.openapi.json
+++ b/api/services/billing_client/saas.openapi.json
@@ -786,6 +786,61 @@
"accountId"
]
},
+ "Error": {
+ "required": [
+ "code",
+ "reason",
+ "message",
+ "metadata"
+ ],
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "description": "HTTP status code.",
+ "format": "int32"
+ },
+ "reason": {
+ "$ref": "#/components/schemas/ErrorReason"
+ },
+ "message": {
+ "type": "string"
+ },
+ "metadata": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ }
+ },
+ "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": {
diff --git a/api/services/billing_client/saas.py b/api/services/billing_client/saas.py
index cb836378245..4e66ca4b3b5 100644
--- a/api/services/billing_client/saas.py
+++ b/api/services/billing_client/saas.py
@@ -2,11 +2,18 @@
# dify-saas commit: 04f8d88cc15c5f62f14f8843a54f3e2e7e09ee5a
from datetime import datetime
-from typing import Literal
+from typing import Literal, TypeIs, get_args
from pydantic import Field
-from services.billing_client.transport import BillingModel, Upstream, request
+from services.billing_client.transport import BillingModel, ServiceErrors, Upstream, request
+from services.errors.billing import (
+ BillingUpstreamError,
+ BillingUpstreamInvalidResponseError,
+ BillingUpstreamUnavailableError,
+ UnknownErrorReason,
+ UpstreamErrorBody,
+)
class AddDeleteFeedbackReply(BillingModel):
@@ -66,6 +73,29 @@ 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: str
title: str
@@ -166,6 +196,37 @@ 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__)
+
+
+class UpstreamError(BillingUpstreamError):
+ """A failed saas call, with its reason typed by this module's `ErrorReason`."""
+
+ def __init__(
+ self,
+ *args: object,
+ status_code: int | None = None,
+ body: UpstreamErrorBody | None = None,
+ reason: ErrorReason | UnknownErrorReason | None = None,
+ ) -> None:
+ super().__init__(*args, status_code=status_code, body=body)
+ self.reason = reason
+
+
+class UpstreamUnavailableError(UpstreamError, BillingUpstreamUnavailableError):
+ pass
+
+
+class UpstreamInvalidResponseError(UpstreamError, BillingUpstreamInvalidResponseError):
+ pass
+
+
+ERRORS = ServiceErrors(
+ is_reason=_is_error_reason, unavailable=UpstreamUnavailableError, invalid_response=UpstreamInvalidResponseError
+)
+
+
def account_delete_account(*, account_id: str) -> DeleteAccountReply:
"""DELETE /v1/account (Account_DeleteAccount)."""
return request(
@@ -173,6 +234,7 @@ def account_delete_account(*, account_id: str) -> DeleteAccountReply:
"DELETE",
"/account",
response_model=DeleteAccountReply,
+ errors=ERRORS,
path_params={},
params={"accountId": account_id},
body=None,
@@ -186,6 +248,7 @@ def account_check_account_in_freeze(*, email: str) -> CheckAccountInFreezeReply:
"GET",
"/account/in-freeze",
response_model=CheckAccountInFreezeReply,
+ errors=ERRORS,
path_params={},
params={"email": email},
body=None,
@@ -199,6 +262,7 @@ def account_add_delete_feedback(*, body: AddDeleteFeedbackRequest) -> AddDeleteF
"POST",
"/account/delete-feedback",
response_model=AddDeleteFeedbackReply,
+ errors=ERRORS,
path_params={},
params={},
body=body,
@@ -212,6 +276,7 @@ def notification_get_account_notification(*, account_id: str) -> GetAccountNotif
"GET",
"/notifications/active",
response_model=GetAccountNotificationReply,
+ errors=ERRORS,
path_params={},
params={"accountId": account_id},
body=None,
@@ -227,6 +292,7 @@ def notification_dismiss_notification(
"POST",
"/notifications/{notification_id}/dismiss",
response_model=DismissNotificationReply,
+ errors=ERRORS,
path_params={"notification_id": notification_id},
params={},
body=body,
@@ -240,6 +306,7 @@ def utm_record_tenant_utm(*, body: TenantUtmRequest) -> TenantUtmReply:
"POST",
"/tenant_utms",
response_model=TenantUtmReply,
+ errors=ERRORS,
path_params={},
params={},
body=body,
@@ -255,6 +322,7 @@ def network_access_policy_list_network_access_groups(
"GET",
"/tenants/{tenant_id}/network-access-groups",
response_model=ListNetworkAccessGroupsReply,
+ errors=ERRORS,
path_params={"tenant_id": tenant_id},
params={"actorAccountId": actor_account_id},
body=None,
@@ -270,6 +338,7 @@ def network_access_policy_create_network_access_group(
"POST",
"/tenants/{tenant_id}/network-access-groups",
response_model=NetworkAccessGroupReply,
+ errors=ERRORS,
path_params={"tenant_id": tenant_id},
params={},
body=body,
@@ -285,6 +354,7 @@ def network_access_policy_get_network_access_group(
"GET",
"/tenants/{tenant_id}/network-access-groups/{group_id}",
response_model=NetworkAccessGroupReply,
+ errors=ERRORS,
path_params={"tenant_id": tenant_id, "group_id": group_id},
params={"actorAccountId": actor_account_id},
body=None,
@@ -300,6 +370,7 @@ def network_access_policy_update_network_access_group(
"PUT",
"/tenants/{tenant_id}/network-access-groups/{group_id}",
response_model=NetworkAccessGroupReply,
+ errors=ERRORS,
path_params={"tenant_id": tenant_id, "group_id": group_id},
params={},
body=body,
@@ -318,6 +389,7 @@ def network_access_policy_delete_network_access_group(
"DELETE",
"/tenants/{tenant_id}/network-access-groups/{group_id}",
response_model=DeleteNetworkAccessGroupReply,
+ errors=ERRORS,
path_params={"tenant_id": tenant_id, "group_id": group_id},
params={"expectedVersion": expected_version, "actorAccountId": actor_account_id},
body=None,
@@ -336,6 +408,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,
path_params={"tenant_id": tenant_id, "app_id": app_id},
params={"actorAccountId": actor_account_id},
body=None,
@@ -354,6 +427,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,
path_params={"tenant_id": tenant_id, "app_id": app_id},
params={},
body=body,
@@ -372,6 +446,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,
path_params={"tenant_id": tenant_id, "app_id": app_id},
params={"actorAccountId": actor_account_id},
body=None,
@@ -390,6 +465,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,
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.py
index e429fd061e3..e1296e189ec 100644
--- a/api/services/billing_client/transport.py
+++ b/api/services/billing_client/transport.py
@@ -2,10 +2,15 @@
This is the only module that reads the billing URLs and secret, and only the generated modules
call `request`; ruff's banned-api rule (TID251) rejects both anywhere else.
-Network failures, timeouts, throttling, and 5xx raise `BillingUpstreamUnavailableError`;
-any other non-200 status or an enforced response that fails model validation raises
-`BillingUpstreamInvalidResponseError`. For a non-200 status, the error carries the status
-code and the parsed Kratos error body, so callers can branch on its `reason`.
+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.
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`
@@ -18,8 +23,10 @@ each item before returning it.
import json
import logging
+import re
import types
-from collections.abc import Mapping
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass
from enum import StrEnum
from functools import cache
from typing import Any, Literal, Union, get_args, get_origin
@@ -34,6 +41,7 @@ from core.helper.http_client_pooling import get_pooled_http_client
from services.errors.billing import (
BillingUpstreamInvalidResponseError,
BillingUpstreamUnavailableError,
+ UnknownErrorReason,
UpstreamErrorBody,
)
@@ -79,6 +87,7 @@ _http_client: httpx.Client = get_pooled_http_client(
)
_UNAVAILABLE_STATUSES = frozenset({httpx.codes.REQUEST_TIMEOUT, httpx.codes.TOO_MANY_REQUESTS})
+_NON_REASON_CHARACTERS = re.compile(r"[^A-Z0-9_]")
class Upstream(StrEnum):
@@ -88,6 +97,15 @@ class Upstream(StrEnum):
NETWORK_ACCESS = "network_access"
+@dataclass(frozen=True)
+class ServiceErrors:
+ """The reason guard and error types of one generated service module, which raises through them."""
+
+ is_reason: Callable[[str], bool]
+ unavailable: Callable[..., BillingUpstreamUnavailableError]
+ invalid_response: Callable[..., BillingUpstreamInvalidResponseError]
+
+
class BillingModel(BaseModel):
"""Base for generated models; unknown upstream fields are ignored and int64 strings coerce to int."""
@@ -123,6 +141,7 @@ def request[ResponseT: BillingModel](
path: str,
*,
response_model: type[ResponseT],
+ errors: ServiceErrors,
path_params: Mapping[str, str],
params: Mapping[str, QueryValue],
body: BillingModel | None,
@@ -133,34 +152,55 @@ def request[ResponseT: BillingModel](
try:
response = _send(method, url, params=params, json=request_json)
except httpx.RequestError as error:
- raise BillingUpstreamUnavailableError(f"{method} {path} failed") from error
+ raise errors.unavailable(f"{method} {path} failed") from error
if response.status_code != httpx.codes.OK:
message = f"{method} {path} returned {response.status_code}"
- status_code, error_body = response.status_code, _error_body(response)
- if status_code in _UNAVAILABLE_STATUSES or status_code >= 500:
- raise BillingUpstreamUnavailableError(message, status_code=status_code, body=error_body)
- raise BillingUpstreamInvalidResponseError(message, status_code=status_code, body=error_body)
+ status_code = response.status_code
+ error_body, reason = _error_details(response, errors.is_reason, upstream, method, path)
+ error_type = (
+ errors.unavailable
+ if status_code in _UNAVAILABLE_STATUSES or status_code >= 500
+ else errors.invalid_response
+ )
+ raise error_type(message, status_code=status_code, body=error_body, reason=reason)
invalid_body = f"{method} {path} returned an invalid body"
try:
payload = json.loads(response.content)
except ValueError as error:
- raise BillingUpstreamInvalidResponseError(invalid_body) from error
+ raise errors.invalid_response(invalid_body) from error
try:
return response_model.model_validate(payload)
except ValidationError as error:
if path in ENFORCED_RESPONSE_PATHS or not isinstance(payload, dict):
- raise BillingUpstreamInvalidResponseError(invalid_body) from error
+ raise errors.invalid_response(invalid_body) from error
logger.exception("Billing response failed validation: %s %s", method, path)
return _salvage_model(response_model, payload)
-def _error_body(response: httpx.Response) -> UpstreamErrorBody | None:
+def _error_details(
+ response: httpx.Response, is_reason: Callable[[str], bool], upstream: Upstream, method: HTTPMethod, path: str
+) -> tuple[UpstreamErrorBody | None, str | UnknownErrorReason | None]:
try:
- return UpstreamErrorBody.model_validate_json(response.content)
- except ValidationError:
- return None
+ payload = json.loads(response.content)
+ except ValueError:
+ return None, None
+ if not isinstance(payload, dict):
+ return None, None
+ body, reason = UpstreamErrorBody.model_validate(payload), payload.get("reason")
+ if not isinstance(reason, str):
+ return body, None
+ if is_reason(reason):
+ return body, reason
+ logger.error(
+ "Unknown %s error reason %s from %s %s; regenerate the billing client",
+ upstream,
+ _NON_REASON_CHARACTERS.sub("", reason)[:64],
+ method,
+ path,
+ )
+ return body, UnknownErrorReason(reason)
def _salvage_model[ModelT: BillingModel](model: type[ModelT], payload: Mapping[str, Any]) -> ModelT:
diff --git a/api/services/errors/billing.py b/api/services/errors/billing.py
index f1e214407cf..0f6420cc459 100644
--- a/api/services/errors/billing.py
+++ b/api/services/errors/billing.py
@@ -1,3 +1,4 @@
+from dataclasses import dataclass
from typing import Annotated, Any
from pydantic import BaseModel, ConfigDict, ValidationError, ValidatorFunctionWrapHandler, WrapValidator
@@ -22,20 +23,31 @@ type _Lenient[T] = Annotated[T | None, WrapValidator(_none_on_error)]
class UpstreamErrorBody(BaseModel):
- """Kratos error body of a non-200 reply. A field of an unexpected type reads as None instead of failing the rest."""
+ """Kratos error body of a non-200 reply, without its reason.
+
+ A field of an unexpected type reads as None instead of failing the rest.
+ """
model_config = ConfigDict(extra="ignore", frozen=True)
code: _Lenient[int] = None
- reason: _Lenient[str] = None
message: _Lenient[str] = None
metadata: _Lenient[dict[str, str]] = None
+@dataclass(frozen=True)
+class UnknownErrorReason:
+ """A reason missing from the snapshot the billing client was generated from."""
+
+ value: str
+
+
class BillingUpstreamError(BillingError):
"""A billing or saas call failed.
- `status_code` and `body` are set when the upstream answered with a non-200 status.
+ `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.
"""
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.py
index be2c63ba4b2..6def0216980 100644
--- a/api/services/network_access_group_gateway.py
+++ b/api/services/network_access_group_gateway.py
@@ -2,9 +2,7 @@
from collections.abc import Generator
from contextlib import contextmanager
-from typing import override
-
-import httpx
+from typing import assert_never, override
from enums import CloudPlan
from services.billing_client import saas
@@ -17,28 +15,74 @@ from services.entities.network_access_group_entities import (
NetworkAccessGroup,
NetworkAccessGroupList,
)
-from services.errors.billing import BillingError, BillingUpstreamError, BillingUpstreamUnavailableError
+from services.errors.billing import (
+ BillingError,
+ BillingUpstreamUnavailableError,
+ UnknownErrorReason,
+)
from services.network_access_group_service import (
+ NetworkAccessGroupAppNotFoundError,
+ NetworkAccessGroupBoundError,
NetworkAccessGroupControlPlane,
NetworkAccessGroupEntitlement,
NetworkAccessGroupEntitlementUnavailableError,
+ NetworkAccessGroupError,
+ NetworkAccessGroupForbiddenError,
+ NetworkAccessGroupInvalidInputError,
NetworkAccessGroupInvalidResponseError,
+ NetworkAccessGroupNameConflictError,
+ NetworkAccessGroupNotEntitledError,
+ NetworkAccessGroupNotFoundError,
NetworkAccessGroupUpstreamError,
+ NetworkAccessGroupVersionConflictError,
)
+def _control_plane_error(exc: saas.UpstreamError) -> NetworkAccessGroupError:
+ match exc.reason:
+ case "VALIDATOR" | "INVALID_ARGUMENT" | "INVALID_NETWORK_ACCESS_INPUT":
+ return NetworkAccessGroupInvalidInputError()
+ case "NETWORK_ACCESS_FORBIDDEN" | "TENANT_ARCHIVED":
+ return NetworkAccessGroupForbiddenError()
+ case "NETWORK_ACCESS_NOT_ENTITLED":
+ return NetworkAccessGroupNotEntitledError()
+ case "NETWORK_ACCESS_GROUP_NOT_FOUND":
+ return NetworkAccessGroupNotFoundError()
+ case "APP_NOT_FOUND":
+ return NetworkAccessGroupAppNotFoundError()
+ case "NETWORK_ACCESS_VERSION_CONFLICT":
+ return NetworkAccessGroupVersionConflictError()
+ case "NETWORK_ACCESS_GROUP_NAME_CONFLICT":
+ return NetworkAccessGroupNameConflictError()
+ case "NETWORK_ACCESS_GROUP_BOUND":
+ return NetworkAccessGroupBoundError()
+ case "INVALID_SECRET_KEY":
+ return NetworkAccessGroupUpstreamError(unavailable=True)
+ case (
+ ""
+ | "CODEC"
+ | "UNKNOWN"
+ | "INTERNAL_ERROR"
+ | "TENANT_NOT_FOUND"
+ | "NETWORK_ACCESS_APP_STILL_EXISTS"
+ | "NETWORK_ACCESS_CACHE_UNAVAILABLE"
+ ):
+ return NetworkAccessGroupUpstreamError(unavailable=isinstance(exc, BillingUpstreamUnavailableError))
+ case UnknownErrorReason() | None:
+ return NetworkAccessGroupUpstreamError(unavailable=isinstance(exc, BillingUpstreamUnavailableError))
+ case unreachable:
+ assert_never(unreachable)
+
+
@contextmanager
def _upstream_errors() -> Generator[None]:
- """Map saas failures to the service's errors, keeping the upstream status and Kratos reason."""
+ """Map saas failures to the service's errors by their Kratos reason."""
try:
yield
- except BillingUpstreamError as exc:
- if exc.status_code is not None:
- reason = exc.body.reason if exc.body is not None else None
- raise NetworkAccessGroupUpstreamError(exc.status_code, reason) from exc
- if isinstance(exc, BillingUpstreamUnavailableError):
- raise NetworkAccessGroupUpstreamError(httpx.codes.SERVICE_UNAVAILABLE) from exc
- raise NetworkAccessGroupInvalidResponseError from exc
+ except saas.UpstreamError as exc:
+ if exc.status_code is None and not isinstance(exc, BillingUpstreamUnavailableError):
+ raise NetworkAccessGroupInvalidResponseError from exc
+ raise _control_plane_error(exc) from exc
_MAX_INT64 = 2**63 - 1
diff --git a/api/services/network_access_group_service.py b/api/services/network_access_group_service.py
index 13b4e8b4717..af66dc0e1b3 100644
--- a/api/services/network_access_group_service.py
+++ b/api/services/network_access_group_service.py
@@ -42,12 +42,43 @@ class NetworkAccessGroupError(Exception):
class NetworkAccessGroupUpstreamError(NetworkAccessGroupError):
- """Failure returned by the network-access control plane."""
+ """The network-access control plane failed without a reason the use cases handle."""
+
+ def __init__(self, *, unavailable: bool) -> None:
+ self.unavailable = unavailable
+ super().__init__(
+ "network access group control plane is unavailable"
+ if unavailable
+ else "network access group control plane request failed"
+ )
+
+
+class NetworkAccessGroupInvalidInputError(NetworkAccessGroupError):
+ """The control plane rejected the requested policy or binding."""
+
+
+class NetworkAccessGroupForbiddenError(NetworkAccessGroupError):
+ """The control plane refused the workspace or actor."""
+
+
+class NetworkAccessGroupNotEntitledError(NetworkAccessGroupError):
+ """The workspace plan does not include network access control."""
+
+
+class NetworkAccessGroupNotFoundError(NetworkAccessGroupError):
+ """The network access group does not exist in the workspace."""
+
+
+class NetworkAccessGroupVersionConflictError(NetworkAccessGroupError):
+ """The resource changed since the version the caller read."""
+
+
+class NetworkAccessGroupNameConflictError(NetworkAccessGroupError):
+ """Another network access group in the workspace has the requested name."""
+
- def __init__(self, status_code: int, reason: str | None = None) -> None:
- self.status_code = status_code
- self.reason = reason
- super().__init__(f"network access group upstream returned HTTP {status_code}")
+class NetworkAccessGroupBoundError(NetworkAccessGroupError):
+ """The network access group is still bound to at least one app."""
class NetworkAccessGroupAccessDeniedError(NetworkAccessGroupError):
diff --git a/api/tests/unit_tests/controllers/console/billing/test_billing.py b/api/tests/unit_tests/controllers/console/billing/test_billing.py
index e562a33067d..a8303797f72 100644
--- a/api/tests/unit_tests/controllers/console/billing/test_billing.py
+++ b/api/tests/unit_tests/controllers/console/billing/test_billing.py
@@ -15,8 +15,7 @@ from enums import CloudPlan
from machinery.context import RequestContext
from services.billing_client import billing
from services.errors.billing import (
- BillingUpstreamInvalidResponseError,
- BillingUpstreamUnavailableError,
+ UnknownErrorReason,
)
@@ -95,7 +94,7 @@ class TestBillingPortal:
) -> None:
resource = Invoices()
method = unwrap(resource.get)
- billing_portal.get_invoices.side_effect = BillingUpstreamUnavailableError
+ billing_portal.get_invoices.side_effect = billing.UpstreamUnavailableError
with app.test_request_context("/billing/invoices"):
with pytest.raises(BillingUnavailableError) as exc_info:
@@ -116,7 +115,7 @@ class TestBillingPortal:
resource = Subscription()
method = unwrap(resource.get)
query = SubscriptionQuery(plan=CloudPlan.PROFESSIONAL, interval="month")
- billing_portal.get_subscription.side_effect = BillingUpstreamInvalidResponseError
+ billing_portal.get_subscription.side_effect = billing.UpstreamInvalidResponseError
with app.test_request_context("/billing/subscription"):
with pytest.raises(BillingOperationFailedError) as exc_info:
@@ -127,3 +126,40 @@ class TestBillingPortal:
"message": "We couldn't complete this request. Please try again. If the problem persists, contact support.",
"status": 502,
}
+
+ @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"),
+ BillingUnavailableError,
+ ),
+ (billing.UpstreamUnavailableError(status_code=429, reason="REQUEST_IN_PROGRESS"), BillingUnavailableError),
+ (
+ billing.UpstreamInvalidResponseError(status_code=409, reason=UnknownErrorReason("PLAN_SHIPPED_LATER")),
+ BillingOperationFailedError,
+ ),
+ (
+ billing.UpstreamUnavailableError(status_code=503, reason=UnknownErrorReason("PLAN_SHIPPED_LATER")),
+ BillingUnavailableError,
+ ),
+ ],
+ )
+ def test_get_subscription_maps_every_reason_to_a_generic_billing_error(
+ self,
+ app: Flask,
+ request_context: RequestContext,
+ billing_portal: MagicMock,
+ error: billing.UpstreamError,
+ expected: type[Exception],
+ ) -> None:
+ resource = Subscription()
+ billing_portal.get_subscription.side_effect = error
+
+ with app.test_request_context("/billing/subscription"), pytest.raises(expected) as exc_info:
+ unwrap(resource.get)(
+ resource, SubscriptionQuery(plan=CloudPlan.PROFESSIONAL, interval="month"), request_context
+ )
+
+ assert exc_info.value.__cause__ is error
diff --git a/api/tests/unit_tests/controllers/console/billing/test_compliance.py b/api/tests/unit_tests/controllers/console/billing/test_compliance.py
index 167df938eb1..1fe8571ae82 100644
--- a/api/tests/unit_tests/controllers/console/billing/test_compliance.py
+++ b/api/tests/unit_tests/controllers/console/billing/test_compliance.py
@@ -8,9 +8,13 @@ from flask import Flask
from controllers.console.billing.compliance import ComplianceApi, ComplianceDownloadQuery
from controllers.console.billing.error import ComplianceRateLimitError
+from libs.exception import BaseHTTPException
from machinery.context import RequestContext
from services.billing_client import billing
-from services.errors.billing import ComplianceRateLimitExceededError
+from services.errors.billing import (
+ ComplianceRateLimitExceededError,
+ UnknownErrorReason,
+)
@pytest.fixture
@@ -93,3 +97,70 @@ def test_get_compliance_download_translates_rate_limit(
"message": "Rate limit exceeded for downloading compliance report.",
"status": 429,
}
+
+
+ ("error", "expected_code", "expected_status"),
+ [
+ (
+ billing.UpstreamInvalidResponseError(status_code=404, reason="COMPLIANCE_DOCUMENT_NOT_FOUND"),
+ "compliance_document_not_found",
+ 404,
+ ),
+ (
+ billing.UpstreamInvalidResponseError(status_code=403, reason="COMPLIANCE_DOWNLOAD_FORBIDDEN"),
+ "compliance_download_forbidden",
+ 403,
+ ),
+ (
+ billing.UpstreamUnavailableError(status_code=429, reason="REQUEST_IN_PROGRESS"),
+ "billing_request_in_progress",
+ 429,
+ ),
+ (
+ billing.UpstreamUnavailableError(status_code=500, reason="COMPLIANCE_DOWNLOAD_FAILED"),
+ "billing_unavailable",
+ 503,
+ ),
+ (
+ billing.UpstreamInvalidResponseError(status_code=400, reason="MISSING_DOC_NAME"),
+ "billing_operation_failed",
+ 502,
+ ),
+ (
+ billing.UpstreamInvalidResponseError(
+ status_code=403, reason=UnknownErrorReason("COMPLIANCE_SHIPPED_LATER")
+ ),
+ "billing_operation_failed",
+ 502,
+ ),
+ (
+ billing.UpstreamUnavailableError(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),
+ ],
+)
+def test_get_compliance_download_maps_billing_reason(
+ app: Flask,
+ request_context: RequestContext,
+ compliance_downloads: MagicMock,
+ error: billing.UpstreamError,
+ expected_code: str,
+ expected_status: int,
+) -> None:
+ resource = ComplianceApi()
+ compliance_downloads.get_link.side_effect = error
+
+ with (
+ app.test_request_context("/compliance/download"),
+ patch("controllers.console.billing.compliance.extract_remote_ip", return_value="127.0.0.1"),
+ pytest.raises(BaseHTTPException) as exc_info,
+ ):
+ unwrap(resource.get)(resource, ComplianceDownloadQuery(doc_name="SOC2_Type_II"), request_context)
+
+ assert exc_info.value.error_code == expected_code
+ assert exc_info.value.code == expected_status
+ assert exc_info.value.__cause__ is error
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_account.py b/api/tests/unit_tests/controllers/console/workspace/test_account.py
index c80753fd53d..3e4ffd5db63 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_account.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_account.py
@@ -2,7 +2,7 @@ import inspect
from collections.abc import Iterator
from datetime import datetime
from types import SimpleNamespace
-from unittest.mock import MagicMock, PropertyMock, patch
+from unittest.mock import MagicMock, PropertyMock, create_autospec, patch
from uuid import NAMESPACE_URL, uuid5
import pytest
@@ -21,6 +21,7 @@ from controllers.console.auth.error import (
)
from controllers.console.error import (
AccountInFreezeError,
+ EducationActivateFailedError,
EducationActivateLimitError,
EducationVerifyLimitError,
EmailDomainSuspendedError,
@@ -61,6 +62,7 @@ from controllers.console.workspace.error import (
)
from extensions.application_services.account import AccountServices
from extensions.ext_application_services import ApplicationServices
+from libs.exception import BaseHTTPException
from libs.login import AccountWithTenant
from machinery.context import RequestContext
from models import Account, Tenant, TenantAccountJoin
@@ -68,6 +70,7 @@ from models import AccountStatus as _workspace_account_AccountStatus
from models.account import AccountStatus as _accounts_AccountStatus
from models.account import TenantAccountRole
from services import account_errors
+from services.account_education_service import AccountEducationService
from services.account_email import normalize_email
from services.account_errors import (
AccountAlreadyInitializedError,
@@ -82,6 +85,7 @@ from services.account_errors import (
InvalidChangeEmailCodeError,
MissingInvitationCodeError,
)
+from services.billing_client import billing
from services.entities.account_entities import (
AccountEducationActivation,
AccountEducationEligible,
@@ -99,6 +103,9 @@ from services.entities.auth_entities import (
ChangeEmailPhase,
ChangeEmailTokenBase,
)
+from services.errors.billing import (
+ UnknownErrorReason,
+)
from tests.helpers.unit.config_override import config_overrides_context
@@ -313,6 +320,73 @@ class TestWorkspaceAccountCases:
api, EducationActivatePayload.model_validate(request.get_json() or {}), request_context
)
+ @pytest.mark.parametrize(
+ ("error", "expected_code", "expected_status"),
+ [
+ (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_operation_failed",
+ 502,
+ ),
+ ],
+ )
+ def test_verify_maps_billing_errors(
+ self, app: Flask, error: Exception, expected_code: str, expected_status: int
+ ) -> None:
+ education = create_autospec(AccountEducationService, instance=True)
+ education.verify.side_effect = error
+ request_context = RequestContext(
+ request_id="request-1",
+ trace_id=None,
+ account_id="account-1",
+ active_workspace_id="workspace-1",
+ )
+
+ api = EducationVerifyApi()
+ with (
+ app.test_request_context("/account/education/verify", method="GET"),
+ patch(
+ "controllers.console.workspace.account.application_services",
+ **{"return_value.accounts.education": education},
+ ),
+ pytest.raises(BaseHTTPException) as exc_info,
+ ):
+ inspect.unwrap(api.get)(api, request_context)
+
+ assert exc_info.value.error_code == expected_code
+ assert exc_info.value.code == expected_status
+ assert exc_info.value.__cause__ is error
+
+ def test_post_maps_activation_failure(self, app: Flask) -> None:
+ education = create_autospec(AccountEducationService, instance=True)
+ education.activate.side_effect = account_errors.EducationActivationFailedError
+ request_context = RequestContext(
+ request_id="request-1",
+ trace_id=None,
+ account_id="account-1",
+ active_workspace_id="workspace-1",
+ )
+
+ with (
+ app.test_request_context(
+ "/account/education",
+ method="POST",
+ json={"token": "education-token", "institution": "Dify University", "role": "Student"},
+ ),
+ patch(
+ "controllers.console.workspace.account.application_services",
+ **{"return_value.accounts.education": education},
+ ),
+ ):
+ api = EducationApi()
+ with pytest.raises(EducationActivateFailedError):
+ inspect.unwrap(api.post)(
+ api, EducationActivatePayload.model_validate(request.get_json() or {}), request_context
+ )
+
class TestChangeEmailControllers:
def test_send_delegates_parsed_request_to_application_service(self, app: Flask) -> None:
change_email = MagicMock()
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_network_access_group.py b/api/tests/unit_tests/controllers/console/workspace/test_network_access_group.py
index a8eaf273cb4..4ed487d82f9 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_network_access_group.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_network_access_group.py
@@ -12,10 +12,11 @@ from flask import Flask, Response
from pydantic import ValidationError
from pytest_mock import MockerFixture
from sqlalchemy.orm import sessionmaker
-from werkzeug.exceptions import BadGateway, BadRequest, Conflict, Forbidden, HTTPException, NotFound, ServiceUnavailable
+from werkzeug.exceptions import BadGateway, HTTPException, NotFound, ServiceUnavailable
from werkzeug.test import TestResponse
from controllers.console.app.error import AppNotFoundError
+from controllers.console.workspace import error as console_errors
from controllers.console.workspace.network_access_group import (
AppNetworkAccessGroupApi,
AppNetworkAccessGroupStatusApi,
@@ -29,13 +30,13 @@ from controllers.console.workspace.network_access_group import (
NetworkAccessGroupDeleteQuery,
NetworkAccessGroupUpdatePayload,
_translate_service_error,
- _translate_upstream_error,
)
from controllers.console.wraps import validate_request
from core.network_access.client_ip import NetworkAccessClientIPUnavailableError
from enums import DeploymentEdition
from extensions.ext_application_services import ApplicationServices
from extensions.ext_login import DifyLoginManager
+from libs.exception import BaseHTTPException
from libs.login import AccountWithTenant
from machinery.context import RequestContext
from models.account import Account, AccountStatus
@@ -56,14 +57,21 @@ from services.network_access_group_service import (
NetworkAccessGroupAccessDeniedError,
NetworkAccessGroupAppNotFoundError,
NetworkAccessGroupAppRecord,
+ NetworkAccessGroupBoundError,
NetworkAccessGroupEntitlementUnavailableError,
NetworkAccessGroupError,
+ NetworkAccessGroupForbiddenError,
+ NetworkAccessGroupInvalidInputError,
NetworkAccessGroupInvalidPolicyError,
NetworkAccessGroupInvalidResponseError,
+ NetworkAccessGroupNameConflictError,
+ NetworkAccessGroupNotEntitledError,
+ NetworkAccessGroupNotFoundError,
NetworkAccessGroupService,
NetworkAccessGroupUnsupportedAccessPointsError,
NetworkAccessGroupUnsupportedAppModeError,
NetworkAccessGroupUpstreamError,
+ NetworkAccessGroupVersionConflictError,
)
from tests.helpers.unit.config_override import config_overrides_context
@@ -398,11 +406,13 @@ def test_app_status_rejects_disallowed_roles_before_upstream_read(
assert requests == []
[email protected]("upstream_status", [403, 404])
[email protected](("upstream_status", "reason"), [(403, "NETWORK_ACCESS_NOT_ENTITLED"), (404, "APP_NOT_FOUND")])
def test_app_status_does_not_fall_back_to_full_binding_after_upstream_error(
- account_application_services: ApplicationServices, upstream_status: int
+ account_application_services: ApplicationServices, upstream_status: int, reason: str
) -> None:
- response, requests = _typed_status_http_response(account_application_services, {}, upstream_status=upstream_status)
+ response, requests = _typed_status_http_response(
+ account_application_services, {"code": upstream_status, "reason": reason}, upstream_status=upstream_status
+ )
assert response.status_code == upstream_status
assert len(requests) == 1
@@ -436,34 +446,31 @@ def test_app_status_rejects_malformed_scopes(
@pytest.mark.parametrize(
- ("status_code", "expected_exception"),
+ ("service_error", "expected_code", "expected_status"),
[
- (400, BadRequest),
- (401, ServiceUnavailable),
- (403, Forbidden),
- (404, NotFound),
- (409, Conflict),
- (500, ServiceUnavailable),
- (418, BadGateway),
+ (NetworkAccessGroupUpstreamError(unavailable=True), "billing_unavailable", 503),
+ (NetworkAccessGroupUpstreamError(unavailable=False), "billing_operation_failed", 502),
+ (NetworkAccessGroupInvalidInputError(), "network_access_invalid_input", 400),
+ (NetworkAccessGroupForbiddenError(), "network_access_forbidden", 403),
+ (NetworkAccessGroupNotEntitledError(), "network_access_not_entitled", 403),
+ (NetworkAccessGroupNotFoundError(), "network_access_group_not_found", 404),
+ (NetworkAccessGroupVersionConflictError(), "network_access_version_conflict", 409),
+ (NetworkAccessGroupNameConflictError(), "network_access_group_name_conflict", 409),
+ (NetworkAccessGroupBoundError(), "network_access_group_bound", 409),
+ (NetworkAccessGroupAppNotFoundError(), "app_not_found", 404),
+ (NetworkAccessGroupAccessDeniedError(), "network_access_role_denied", 403),
+ (NetworkAccessGroupUnsupportedAppModeError("channel"), "network_access_unsupported_app_mode", 400),
+ (NetworkAccessGroupUnsupportedAccessPointsError(["trigger"]), "network_access_unsupported_access_points", 400),
],
)
-def test_upstream_error_mapping(status_code: int, expected_exception: type[HTTPException]) -> None:
- assert isinstance(_translate_upstream_error(NetworkAccessGroupUpstreamError(status_code)), expected_exception)
-
+def test_control_plane_error_maps_to_console_error_code(
+ service_error: NetworkAccessGroupError, expected_code: str, expected_status: int
+) -> None:
+ error = _translate_service_error(service_error)
- ("reason", "expected_message"),
- [
- ("NETWORK_ACCESS_VERSION_CONFLICT", "changed"),
- ("NETWORK_ACCESS_GROUP_NAME_CONFLICT", "An IP policy with this name already exists."),
- ("NETWORK_ACCESS_GROUP_LIMIT", "reached"),
- ],
-)
-def test_conflict_error_mapping_preserves_safe_actionable_reason(reason: str, expected_message: str) -> None:
- error = _translate_upstream_error(NetworkAccessGroupUpstreamError(409, reason))
- assert isinstance(error, Conflict)
- assert error.description is not None
- assert expected_message in error.description
+ assert isinstance(error, BaseHTTPException)
+ assert error.error_code == expected_code
+ assert error.code == expected_status
@pytest.mark.parametrize("mutation", ["create", "update"])
@@ -471,7 +478,7 @@ def test_duplicate_policy_name_mutations_preserve_conflict_and_public_message(
account_application_services: ApplicationServices, mocker: MockerFixture, mutation: str
) -> None:
service = account_application_services.network_access_groups
- upstream_error = NetworkAccessGroupUpstreamError(409, "NETWORK_ACCESS_GROUP_NAME_CONFLICT")
+ upstream_error = NetworkAccessGroupNameConflictError()
mock_create_group = mocker.patch.object(service, "create_group", side_effect=upstream_error)
mock_update_group = mocker.patch.object(service, "update_group", side_effect=upstream_error)
@@ -494,32 +501,35 @@ def test_duplicate_policy_name_mutations_preserve_conflict_and_public_message(
group_id=UUID(GROUP_ID),
)
- with _application_services(account_application_services), pytest.raises(Conflict) as exc_info:
+ with (
+ _application_services(account_application_services),
+ pytest.raises(console_errors.NetworkAccessGroupNameConflictError) as exc_info,
+ ):
invoke_mutation()
assert exc_info.value.code == 409
assert exc_info.value.description == "An IP policy with this name already exists."
assert exc_info.value.__cause__ is upstream_error
- assert upstream_error.reason == "NETWORK_ACCESS_GROUP_NAME_CONFLICT"
assert mock_create_group.call_count == (1 if mutation == "create" else 0)
assert mock_update_group.call_count == (1 if mutation == "update" else 0)
-def test_internal_secret_error_is_not_reported_as_tenant_input_failure() -> None:
- assert isinstance(
- _translate_upstream_error(NetworkAccessGroupUpstreamError(400, "INVALID_SECRET_KEY")),
- ServiceUnavailable,
- )
-
-
@pytest.mark.parametrize(
("service_error", "expected_exception", "expected_message"),
[
- (NetworkAccessGroupAccessDeniedError(), Forbidden, "workspace role"),
+ (NetworkAccessGroupAccessDeniedError(), console_errors.NetworkAccessRoleDeniedError, "workspace role"),
(NetworkAccessGroupEntitlementUnavailableError(), ServiceUnavailable, "temporarily unavailable"),
(NetworkAccessGroupAppNotFoundError(), AppNotFoundError, "not found"),
- (NetworkAccessGroupUnsupportedAppModeError("channel"), BadRequest, "channel"),
- (NetworkAccessGroupUnsupportedAccessPointsError(["trigger"]), BadRequest, "trigger"),
+ (
+ NetworkAccessGroupUnsupportedAppModeError("channel"),
+ console_errors.NetworkAccessUnsupportedAppModeError,
+ "channel",
+ ),
+ (
+ NetworkAccessGroupUnsupportedAccessPointsError(["trigger"]),
+ console_errors.NetworkAccessUnsupportedAccessPointsError,
+ "trigger",
+ ),
(NetworkAccessGroupInvalidPolicyError(), ServiceUnavailable, "cannot be evaluated"),
(NetworkAccessGroupInvalidResponseError(), BadGateway, "invalid response"),
],
@@ -601,7 +611,10 @@ def test_controller_maps_service_error_before_serialization(
service = account_application_services.network_access_groups
mocker.patch.object(service, "list_groups", side_effect=NetworkAccessGroupAccessDeniedError)
- with _application_services(account_application_services), pytest.raises(Forbidden, match="workspace role"):
+ with (
+ _application_services(account_application_services),
+ pytest.raises(console_errors.NetworkAccessRoleDeniedError, match="workspace role"),
+ ):
unwrap(CurrentWorkspaceNetworkAccessGroupsApi().get)(
CurrentWorkspaceNetworkAccessGroupsApi(),
request_context=_request_context(),
@@ -897,7 +910,7 @@ def test_current_ip_read_maps_role_denial_without_resolving_ip(
"controllers.console.workspace.network_access_group.resolve_network_access_client_ip"
) as resolve_client_ip,
):
- with pytest.raises(Forbidden, match="workspace role") as exc_info:
+ with pytest.raises(console_errors.NetworkAccessRoleDeniedError, match="workspace role") as exc_info:
unwrap(api.get)(api, request_context=_request_context())
response = app.process_response(app.make_response(exc_info.value.get_response()))
diff --git a/api/tests/unit_tests/controllers/service_api/test___init__.py b/api/tests/unit_tests/controllers/service_api/test___init__.py
index 8f08bb8618a..26d6358f0d3 100644
--- a/api/tests/unit_tests/controllers/service_api/test___init__.py
+++ b/api/tests/unit_tests/controllers/service_api/test___init__.py
@@ -827,6 +827,99 @@ def test_console_member_invite_documents_bad_request_response(openapi_json: Open
}
+def test_console_billing_reason_errors_are_documented(openapi_json: OpenAPIJSONLoader) -> None:
+ from controllers.console import bp as console_bp
+
+ payload = json.loads(openapi_json(console_bp, "/console/api/openapi.json", True))
+ control_plane = {
+ "403": {"NetworkAccessForbiddenError", "NetworkAccessNotEntitledError", "NetworkAccessRoleDeniedError"},
+ "502": {"BillingOperationFailedError"},
+ "503": {"BillingUnavailableError"},
+ }
+ expected = {
+ ("/compliance/download", "get"): {
+ "403": {"ComplianceDownloadForbiddenError"},
+ "404": {"ComplianceDocumentNotFoundError"},
+ "429": {"BillingRequestInProgressError"},
+ },
+ ("/account/education/verify", "get"): {
+ "400": {"EducationVerifyFailedError"},
+ "429": {"BillingRequestInProgressError"},
+ "502": {"BillingOperationFailedError"},
+ "503": {"BillingUnavailableError"},
+ },
+ ("/account/education", "post"): {
+ "400": {"EducationActivateFailedError"},
+ "429": {"BillingRequestInProgressError"},
+ "502": {"BillingOperationFailedError"},
+ "503": {"BillingUnavailableError"},
+ },
+ ("/account/education", "get"): {
+ "429": {"BillingRequestInProgressError"},
+ "502": {"BillingOperationFailedError"},
+ "503": {"BillingUnavailableError"},
+ },
+ ("/workspaces/current/network-access-groups", "get"): control_plane,
+ ("/workspaces/current/network-access-groups", "post"): {
+ **control_plane,
+ "403": {*control_plane["403"], "PaidPlanRequiredError"},
+ "400": {"NetworkAccessInvalidInputError"},
+ "409": {"NetworkAccessGroupNameConflictError"},
+ },
+ ("/workspaces/current/network-access-groups/{group_id}", "put"): {
+ **control_plane,
+ "400": {"NetworkAccessInvalidInputError"},
+ "404": {"NetworkAccessGroupNotFoundError"},
+ "409": {"NetworkAccessGroupNameConflictError", "NetworkAccessVersionConflictError"},
+ },
+ ("/workspaces/current/network-access-groups/{group_id}", "delete"): {
+ **control_plane,
+ "404": {"NetworkAccessGroupNotFoundError"},
+ "409": {"NetworkAccessGroupBoundError", "NetworkAccessVersionConflictError"},
+ },
+ ("/apps/{app_id}/network-access-group", "put"): {
+ **control_plane,
+ "400": {
+ "NetworkAccessInvalidInputError",
+ "NetworkAccessUnsupportedAccessPointsError",
+ "NetworkAccessUnsupportedAppModeError",
+ },
+ "404": {"AppNotFoundError", "NetworkAccessGroupNotFoundError"},
+ "409": {"NetworkAccessVersionConflictError"},
+ },
+ }
+
+ for (path, method), responses in expected.items():
+ operation = payload["paths"][path][method]
+ for status, components in responses.items():
+ schema = operation["responses"][status]["content"]["application/json"]["schema"]
+ documented = {option["$ref"].rpartition("/")[2] for option in schema["anyOf"]}
+ assert components <= documented, (path, method, status)
+
+ expected_codes = {
+ "BillingRequestInProgressError": ("billing_request_in_progress", 429),
+ "ComplianceDocumentNotFoundError": ("compliance_document_not_found", 404),
+ "ComplianceDownloadForbiddenError": ("compliance_download_forbidden", 403),
+ "EducationVerifyFailedError": ("education_verify_failed", 400),
+ "EducationActivateFailedError": ("education_activate_failed", 400),
+ "NetworkAccessInvalidInputError": ("network_access_invalid_input", 400),
+ "NetworkAccessForbiddenError": ("network_access_forbidden", 403),
+ "NetworkAccessNotEntitledError": ("network_access_not_entitled", 403),
+ "NetworkAccessGroupNotFoundError": ("network_access_group_not_found", 404),
+ "NetworkAccessVersionConflictError": ("network_access_version_conflict", 409),
+ "NetworkAccessGroupNameConflictError": ("network_access_group_name_conflict", 409),
+ "NetworkAccessGroupBoundError": ("network_access_group_bound", 409),
+ "NetworkAccessRoleDeniedError": ("network_access_role_denied", 403),
+ "NetworkAccessUnsupportedAppModeError": ("network_access_unsupported_app_mode", 400),
+ "NetworkAccessUnsupportedAccessPointsError": ("network_access_unsupported_access_points", 400),
+ "PaidPlanRequiredError": ("paid_plan_required", 403),
+ }
+ for component, (code, status) in expected_codes.items():
+ properties = payload["components"]["schemas"][component]["allOf"][1]["properties"]
+ assert properties["code"]["const"] == code
+ assert properties["status"]["const"] == status
+
+
def test_console_billing_routes_document_error_responses(openapi_json: OpenAPIJSONLoader):
from controllers.console import bp as console_bp
diff --git a/api/tests/unit_tests/dev/test_generate_billing_client.py b/api/tests/unit_tests/dev/test_generate_billing_client.py
index f34651b69ac..1fc9aa2db01 100644
--- a/api/tests/unit_tests/dev/test_generate_billing_client.py
+++ b/api/tests/unit_tests/dev/test_generate_billing_client.py
@@ -44,6 +44,20 @@ def _source_spec() -> generator.JsonObject:
"type": "object",
"properties": {"coupon_id": {"type": "string"}},
},
+ "dify.saas.api.billing.Error": {
+ "required": ["code", "reason", "message", "metadata"],
+ "type": "object",
+ "properties": {
+ "code": {"type": "integer", "description": "HTTP status code.", "format": "int32"},
+ "reason": {"$ref": f"{PREFIX}ErrorReason"},
+ "message": {"type": "string"},
+ "metadata": {"type": "object", "additionalProperties": {"type": "string"}},
+ },
+ },
+ "dify.saas.api.billing.ErrorReason": {
+ "enum": ["", "CODEC", "REQUEST_IN_PROGRESS"],
+ "type": "string",
+ },
}
},
}
@@ -64,7 +78,7 @@ def test_snapshot_keeps_only_allowlisted_operations_and_reachable_schemas() -> N
assert snapshot[generator.SNAPSHOT_COMMIT_KEY] == "abc123"
assert list(snapshot["paths"]) == ["/v1/subscription/info"]
- assert sorted(snapshot["components"]["schemas"]) == ["GetSubscriptionInfoReply", "Quota"]
+ assert sorted(snapshot["components"]["schemas"]) == ["Error", "ErrorReason", "GetSubscriptionInfoReply", "Quota"]
assert "coupon" not in generator.render_snapshot(snapshot).lower()
@@ -93,6 +107,11 @@ def test_rendered_module_types_fields_and_operations() -> None:
assert "renewed_at: datetime\n" in source
assert "def subscription_get_subscription_info() -> GetSubscriptionInfoReply:" in source
assert '"/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 "class Error(" not in source
def test_long_operation_docstring_is_wrapped() -> None:
@@ -130,5 +149,37 @@ def test_snapshot_rejects_allowlisted_operation_missing_from_spec() -> None:
generator.build_snapshot("billing", source, "abc123")
[email protected]("subscription_info_only")
[email protected]("name", ["Error", "ErrorReason"])
+def test_snapshot_rejects_spec_without_error_schema(name: str) -> None:
+ source = _source_spec()
+ del source["components"]["schemas"][f"dify.saas.api.billing.{name}"]
+
+ with pytest.raises(generator.GenerationError, match=f"error schema dify.saas.api.billing.{name}"):
+ generator.build_snapshot("billing", source, "abc123")
+
+
[email protected]("subscription_info_only")
+def test_rendering_rejects_error_body_that_drifts_from_the_transport() -> None:
+ source = _source_spec()
+ source["components"]["schemas"]["dify.saas.api.billing.Error"]["properties"]["details"] = {"type": "string"}
+ snapshot = generator.build_snapshot("billing", source, "abc123")
+
+ with pytest.raises(generator.GenerationError, match="update UpstreamErrorBody"):
+ 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"]
+ 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
+
+
def test_committed_client_matches_snapshots() -> None:
assert generator.check(generator.expected_files({s: generator.load_snapshot(s) for s in generator.SERVICES})) == 0
diff --git a/api/tests/unit_tests/services/account/test_adapters.py b/api/tests/unit_tests/services/account/test_adapters.py
index c2b9b7858d1..bd17fe3fcbe 100644
--- a/api/tests/unit_tests/services/account/test_adapters.py
+++ b/api/tests/unit_tests/services/account/test_adapters.py
@@ -28,7 +28,12 @@ from services.account.adapters import (
TokenManagerAccountDeletionVerificationGateway,
TokenManagerChangeEmailTokenGateway,
)
-from services.account_errors import AccountDeletionRateLimitError
+from services.account_errors import (
+ AccountDeletionRateLimitError,
+ EducationActivationFailedError,
+ EducationRequestInProgressError,
+ EducationVerificationFailedError,
+)
from services.billing_client import billing, transport
from services.entities.account_activation_entities import InvitationLookup, InvitationToken
from services.entities.account_entities import (
@@ -40,7 +45,11 @@ from services.entities.account_entities import (
AccountEducationStatus,
AccountEducationVerification,
)
-from services.errors.billing import BillingUpstreamInvalidResponseError
+from services.errors.billing import (
+ BillingUpstreamError,
+ BillingUpstreamInvalidResponseError,
+ UnknownErrorReason,
+)
from tests.helpers.unit.account_domain import AccountDomain
@@ -539,3 +548,45 @@ def test_identity_rejects_banned_and_missing_accounts(account_domain: AccountDom
with pytest.raises(Unauthorized, match="banned"):
gateway.load_user(account.id)
assert gateway.load_user("missing") is None
+
+
+ ("reason", "expected"),
+ [
+ ("EDUCATION_VERIFY_FAILED", EducationVerificationFailedError),
+ ("EDUCATION_CREATE_FAILED", EducationActivationFailedError),
+ ("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)
+
+ with (
+ patch("services.account.adapters.BillingService.EducationIdentity.verify", side_effect=error),
+ pytest.raises(expected) as exc_info,
+ ):
+ BillingAccountEducationGateway().verify(account_id="account-1")
+
+ assert exc_info.value.__cause__ is error
+
+
+ "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(),
+ ],
+)
+def test_education_gateway_leaves_generic_reasons_to_billing_errors(
+ error: billing.UpstreamError,
+) -> None:
+ with (
+ patch("services.account.adapters.BillingService.EducationIdentity.status", side_effect=error),
+ pytest.raises(BillingUpstreamError) as exc_info,
+ ):
+ BillingAccountEducationGateway().status("account-1")
+
+ assert exc_info.value is error
diff --git a/api/tests/unit_tests/services/billing_client/test_transport.py b/api/tests/unit_tests/services/billing_client/test_transport.py
index 0e3a4026789..38ef2012104 100644
--- a/api/tests/unit_tests/services/billing_client/test_transport.py
+++ b/api/tests/unit_tests/services/billing_client/test_transport.py
@@ -1,16 +1,20 @@
+import inspect
import logging
+import types
from collections.abc import Callable
+from typing import assert_type, get_args
import httpx
import pytest
import tenacity
-from services.billing_client import billing, transport
+from services.billing_client import billing, saas, transport
from services.billing_client.transport import BillingModel, Upstream
from services.errors.billing import (
BillingUpstreamError,
BillingUpstreamInvalidResponseError,
BillingUpstreamUnavailableError,
+ UnknownErrorReason,
UpstreamErrorBody,
)
from tests.unit_tests.services.billing_client.conftest import RespondWith
@@ -36,7 +40,9 @@ class _VirtualClock:
def _get(upstream: Upstream) -> _Reply:
- return transport.request(upstream, "GET", "/probe", response_model=_Reply, path_params={}, params={}, body=None)
+ return transport.request(
+ upstream, "GET", "/probe", response_model=_Reply, errors=saas.ERRORS, path_params={}, params={}, body=None
+ )
@pytest.mark.parametrize(
@@ -49,33 +55,117 @@ def _get(upstream: Upstream) -> _Reply:
],
)
def test_non_ok_status_maps_to_upstream_errors(respond_with: RespondWith, status: int, error: type[Exception]) -> None:
- respond_with(httpx.Response(status, json={"code": status, "reason": "QUOTA_EXCEEDED", "message": "over"}))
+ respond_with(
+ httpx.Response(status, json={"code": status, "reason": "NETWORK_ACCESS_VERSION_CONFLICT", "message": "over"})
+ )
with pytest.raises(error) as exc_info:
_get(Upstream.BILLING)
assert isinstance(exc_info.value, BillingUpstreamError)
assert exc_info.value.status_code == status
- assert exc_info.value.body == UpstreamErrorBody(code=status, reason="QUOTA_EXCEEDED", message="over")
+ assert exc_info.value.body == UpstreamErrorBody(code=status, message="over")
+ assert isinstance(exc_info.value, saas.UpstreamError)
+ assert exc_info.value.reason == "NETWORK_ACCESS_VERSION_CONFLICT"
@pytest.mark.parametrize(
- ("content", "body"),
+ ("content", "body", "reason"),
[
- (b"upstream crashed", None),
- (b"[]", None),
- (b'{"code": "x", "reason": "CONFLICT", "metadata": {"k": 1}}', UpstreamErrorBody(reason="CONFLICT")),
+ (b"upstream crashed", None, None),
+ (b"[]", None, None),
+ (
+ b'{"code": "x", "reason": "NETWORK_ACCESS_GROUP_NAME_CONFLICT", "metadata": {"k": 1}}',
+ UpstreamErrorBody(),
+ "NETWORK_ACCESS_GROUP_NAME_CONFLICT",
+ ),
+ (b'{"code": 409, "reason": 409, "message": "taken"}', UpstreamErrorBody(code=409, message="taken"), None),
+ (b'{"code": 409, "message": "taken"}', UpstreamErrorBody(code=409, message="taken"), None),
+ (b'{"reason": ""}', UpstreamErrorBody(), ""),
],
)
def test_error_body_keeps_well_typed_fields(
- respond_with: RespondWith, content: bytes, body: UpstreamErrorBody | None
+ respond_with: RespondWith, content: bytes, body: UpstreamErrorBody | None, reason: str | None
) -> None:
respond_with(httpx.Response(409, content=content))
- with pytest.raises(BillingUpstreamInvalidResponseError) as exc_info:
+ with pytest.raises(saas.UpstreamInvalidResponseError) as exc_info:
_get(Upstream.BILLING)
assert exc_info.value.body == body
+ assert exc_info.value.reason == reason
+
+
+ ("status", "error"), [(409, BillingUpstreamInvalidResponseError), (503, BillingUpstreamUnavailableError)]
+)
+def test_unknown_reason_is_kept_apart_and_reported(
+ respond_with: RespondWith, caplog: pytest.LogCaptureFixture, status: int, error: type[Exception]
+) -> None:
+ respond_with(httpx.Response(status, json={"code": status, "reason": "SHIPPED_LATER", "message": "new"}))
+
+ 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 exc_info.value.reason == UnknownErrorReason("SHIPPED_LATER")
+ assert exc_info.value.body == UpstreamErrorBody(code=status, message="new")
+ [record] = caplog.records
+ assert record.levelno == logging.ERROR
+ assert (
+ record.getMessage() == "Unknown saas error reason SHIPPED_LATER from GET /probe; regenerate the billing client"
+ )
+
+
+def test_unknown_reason_is_logged_without_foreign_characters(
+ respond_with: RespondWith, caplog: pytest.LogCaptureFixture
+) -> None:
+ reason = "SHIPPED_LATER\nERROR forged entry <script>" + "X" * 100
+ respond_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:
+ _get(Upstream.SAAS)
+
+ assert exc_info.value.reason == UnknownErrorReason(reason)
+ [record] = caplog.records
+ logged = record.getMessage().removeprefix("Unknown saas error reason ").partition(" ")[0]
+ assert logged == ("SHIPPED_LATERERROR" + "X" * 100)[:64]
+
+
+ ("call", "own", "other"),
+ [
+ (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),
+ ],
+)
+def test_generated_operation_raises_its_own_service_errors(
+ respond_with: RespondWith, call: Callable[[], object], own: types.ModuleType, other: types.ModuleType
+) -> 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 == ""
+
+
+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)
+
+ read(saas.UpstreamUnavailableError(reason="APP_NOT_FOUND"), billing.UpstreamInvalidResponseError(reason=""))
+ 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__))
+
+ assert [reason for reason in reasons if reason and reason in source] == []
def test_unreachable_upstream_has_no_status(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -176,6 +266,7 @@ def test_invalid_body_is_reported_and_kept_raw_while_observed(
"GET",
"/probe",
response_model=billing.GetSubscriptionInfoReply,
+ errors=billing.ERRORS,
path_params={},
params={},
body=None,
@@ -213,7 +304,14 @@ def test_migrated_reads_reject_missing_required_fields(
with pytest.raises(BillingUpstreamInvalidResponseError):
transport.request(
- Upstream.BILLING, "GET", path, response_model=response_model, path_params={}, params={}, body=None
+ Upstream.BILLING,
+ "GET",
+ path,
+ response_model=response_model,
+ errors=billing.ERRORS,
+ path_params={},
+ params={},
+ body=None,
)
@@ -235,7 +333,14 @@ def test_quota_responses_reject_missing_required_fields(
with pytest.raises(BillingUpstreamInvalidResponseError):
transport.request(
- Upstream.BILLING_QUOTA, method, path, response_model=response_model, path_params={}, params={}, body=None
+ Upstream.BILLING_QUOTA,
+ method,
+ path,
+ response_model=response_model,
+ errors=billing.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.py
index 29d8d073e7b..8685acb2ca1 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
@@ -9,15 +9,28 @@ import pytest
from enums import CloudPlan
from services.billing_client import saas, transport
from services.billing_client.transport import BillingModel
-from services.errors.billing import BillingUpstreamInvalidResponseError, BillingUpstreamUnavailableError
+from services.errors.billing import (
+ BillingUpstreamInvalidResponseError,
+ BillingUpstreamUnavailableError,
+ UnknownErrorReason,
+)
from services.network_access_group_gateway import (
BillingNetworkAccessGroupEntitlementGateway,
NetworkAccessGroupGateway,
)
from services.network_access_group_service import (
+ NetworkAccessGroupAppNotFoundError,
+ NetworkAccessGroupBoundError,
NetworkAccessGroupEntitlementUnavailableError,
+ NetworkAccessGroupError,
+ NetworkAccessGroupForbiddenError,
+ NetworkAccessGroupInvalidInputError,
NetworkAccessGroupInvalidResponseError,
+ NetworkAccessGroupNameConflictError,
+ NetworkAccessGroupNotEntitledError,
+ NetworkAccessGroupNotFoundError,
NetworkAccessGroupUpstreamError,
+ NetworkAccessGroupVersionConflictError,
)
from tests.helpers import billing_builders as builders
@@ -230,52 +243,114 @@ def test_snake_case_proto_names_are_accepted(respond: Respond) -> None:
assert NetworkAccessGroupGateway().get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID).app_ids == (APP_ID,)
[email protected]("status_code", [400, 403, 404, 409, 500, 503])
-def test_error_status_is_preserved(respond: Respond, status_code: int) -> None:
- respond(httpx.Response(status_code))
+ ("status_code", "reason", "expected"),
+ [
+ (400, "VALIDATOR", NetworkAccessGroupInvalidInputError),
+ (400, "INVALID_ARGUMENT", NetworkAccessGroupInvalidInputError),
+ (400, "INVALID_NETWORK_ACCESS_INPUT", NetworkAccessGroupInvalidInputError),
+ (403, "NETWORK_ACCESS_FORBIDDEN", NetworkAccessGroupForbiddenError),
+ (403, "TENANT_ARCHIVED", NetworkAccessGroupForbiddenError),
+ (403, "NETWORK_ACCESS_NOT_ENTITLED", NetworkAccessGroupNotEntitledError),
+ (404, "NETWORK_ACCESS_GROUP_NOT_FOUND", NetworkAccessGroupNotFoundError),
+ (404, "APP_NOT_FOUND", NetworkAccessGroupAppNotFoundError),
+ (409, "NETWORK_ACCESS_VERSION_CONFLICT", NetworkAccessGroupVersionConflictError),
+ (409, "NETWORK_ACCESS_GROUP_NAME_CONFLICT", NetworkAccessGroupNameConflictError),
+ (409, "NETWORK_ACCESS_GROUP_BOUND", NetworkAccessGroupBoundError),
+ ],
+)
+def test_known_reason_maps_to_service_error(
+ respond: Respond, status_code: int, reason: str, expected: type[NetworkAccessGroupError]
+) -> None:
+ respond(httpx.Response(status_code, json={"code": status_code, "reason": reason, "message": "internal"}))
+
+ with pytest.raises(NetworkAccessGroupError) as exc_info:
+ NetworkAccessGroupGateway().get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID)
+
+ assert type(exc_info.value) is expected
+ assert isinstance(exc_info.value.__cause__, saas.UpstreamError)
+
+
+ ("status_code", "reason", "unavailable"),
+ [
+ (400, "INVALID_SECRET_KEY", True),
+ (400, "CODEC", False),
+ (404, "TENANT_NOT_FOUND", False),
+ (409, "NETWORK_ACCESS_APP_STILL_EXISTS", False),
+ (500, "", True),
+ (500, "UNKNOWN", True),
+ (500, "INTERNAL_ERROR", True),
+ (503, "NETWORK_ACCESS_CACHE_UNAVAILABLE", True),
+ ],
+)
+def test_generic_reason_maps_to_upstream_error(
+ respond: Respond, status_code: int, reason: str, unavailable: bool
+) -> None:
+ respond(httpx.Response(status_code, json={"code": status_code, "reason": reason, "message": "internal"}))
+
+ with pytest.raises(NetworkAccessGroupUpstreamError) as exc_info:
+ NetworkAccessGroupGateway().get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID)
+
+ assert exc_info.value.unavailable is unavailable
+
+
[email protected](("status_code", "unavailable"), [(400, False), (409, False), (429, True), (503, True)])
+def test_unknown_reason_falls_back_to_status_and_is_reported(
+ respond: Respond, caplog: pytest.LogCaptureFixture, status_code: int, unavailable: bool
+) -> None:
+ respond(httpx.Response(status_code, json={"code": status_code, "reason": "NETWORK_ACCESS_SHIPPED_LATER"}))
with pytest.raises(NetworkAccessGroupUpstreamError) as exc_info:
NetworkAccessGroupGateway().get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID)
- assert exc_info.value.status_code == status_code
- assert exc_info.value.reason is None
+ assert exc_info.value.unavailable is unavailable
+ cause = exc_info.value.__cause__
+ assert isinstance(cause, saas.UpstreamError)
+ assert cause.reason == UnknownErrorReason("NETWORK_ACCESS_SHIPPED_LATER")
+ [record] = [record for record in caplog.records if record.name == transport.__name__]
+ assert record.levelname == "ERROR"
+ assert "network_access" in record.getMessage()
+ assert "NETWORK_ACCESS_SHIPPED_LATER" in record.getMessage()
+ assert "/tenants/{tenant_id}/network-access-groups/{group_id}" in record.getMessage()
@pytest.mark.parametrize(
- ("body", "reason"),
+ ("response", "unavailable"),
[
- (
- {"code": 409, "reason": "NETWORK_ACCESS_VERSION_CONFLICT", "message": "internal"},
- "NETWORK_ACCESS_VERSION_CONFLICT",
- ),
- ({"code": "not-a-code", "reason": "NETWORK_ACCESS_GROUP_NAME_CONFLICT"}, "NETWORK_ACCESS_GROUP_NAME_CONFLICT"),
- ({"reason": 409}, None),
- (["NETWORK_ACCESS_VERSION_CONFLICT"], None),
+ (httpx.Response(404), False),
+ (httpx.Response(409, json={"code": 409, "reason": 409}), False),
+ (httpx.Response(409, json=["NETWORK_ACCESS_VERSION_CONFLICT"]), False),
+ (httpx.Response(409, content=b"{"), False),
+ (httpx.Response(502, content=b"<html>bad gateway</html>"), True),
],
)
-def test_error_reason_is_preserved_when_it_is_a_string(respond: Respond, body: object, reason: str | None) -> None:
- respond(httpx.Response(httpx.codes.CONFLICT, json=body))
+def test_reply_without_reason_falls_back_to_status(
+ respond: Respond, response: httpx.Response, unavailable: bool
+) -> None:
+ respond(response)
with pytest.raises(NetworkAccessGroupUpstreamError) as exc_info:
NetworkAccessGroupGateway().delete_group(TENANT_ID, GROUP_ID, expected_version=1, actor_account_id=ACCOUNT_ID)
- assert exc_info.value.status_code == httpx.codes.CONFLICT
- assert exc_info.value.reason == reason
+ assert exc_info.value.unavailable is unavailable
+ cause = exc_info.value.__cause__
+ assert isinstance(cause, saas.UpstreamError)
+ assert cause.reason is None
-def test_unreachable_upstream_maps_to_service_unavailable() -> None:
+def test_unreachable_upstream_maps_to_unavailable() -> None:
with (
patch.object(
saas,
"network_access_policy_list_network_access_groups",
- side_effect=BillingUpstreamUnavailableError("GET failed"),
+ side_effect=saas.UpstreamUnavailableError("GET failed"),
),
pytest.raises(NetworkAccessGroupUpstreamError) as exc_info,
):
NetworkAccessGroupGateway().list_groups(TENANT_ID, ACCOUNT_ID)
- assert exc_info.value.status_code == httpx.codes.SERVICE_UNAVAILABLE
- assert exc_info.value.reason is None
+ assert exc_info.value.unavailable is True
@pytest.mark.parametrize("body", [b"{", b"\xff", b"", b"[]"])
diff --git a/api/tests/unit_tests/services/test_network_access_group_service.py b/api/tests/unit_tests/services/test_network_access_group_service.py
index 26e32da620b..8d7dd8b105d 100644
--- a/api/tests/unit_tests/services/test_network_access_group_service.py
+++ b/api/tests/unit_tests/services/test_network_access_group_service.py
@@ -24,10 +24,10 @@ from services.network_access_group_service import (
NetworkAccessGroupControlPlane,
NetworkAccessGroupEntitlement,
NetworkAccessGroupInvalidPolicyError,
+ NetworkAccessGroupNotFoundError,
NetworkAccessGroupService,
NetworkAccessGroupUnsupportedAccessPointsError,
NetworkAccessGroupUnsupportedAppModeError,
- NetworkAccessGroupUpstreamError,
WorkspaceMembershipRoleQuery,
)
@@ -792,9 +792,9 @@ def test_current_ip_check_rejects_role_before_policy_or_ip_lookup(role: str | No
def test_current_ip_check_does_not_read_ip_when_tenant_scoped_policy_lookup_fails() -> None:
harness = _harness(role="admin")
- harness.control_plane.get_group.side_effect = NetworkAccessGroupUpstreamError(404)
+ harness.control_plane.get_group.side_effect = NetworkAccessGroupNotFoundError
- with pytest.raises(NetworkAccessGroupUpstreamError):
+ with pytest.raises(NetworkAccessGroupNotFoundError):
harness.service.check_current_ip(_context(), group_id=GROUP_ID, client_ip_supplier=_unexpected_client_ip_read)
diff --git a/api/tests/unit_tests/tasks/test_remove_app_and_related_data_task.py b/api/tests/unit_tests/tasks/test_remove_app_and_related_data_task.py
index 54e340b52a3..889958198ee 100644
--- a/api/tests/unit_tests/tasks/test_remove_app_and_related_data_task.py
+++ b/api/tests/unit_tests/tasks/test_remove_app_and_related_data_task.py
@@ -187,7 +187,7 @@ def test_independent_binding_cleanup_task_retries_with_exponential_backoff(
mocker: MockerFixture,
account_application_services: ApplicationServices,
) -> None:
- upstream_error = NetworkAccessGroupUpstreamError(409, "NETWORK_ACCESS_APP_STILL_EXISTS")
+ upstream_error = NetworkAccessGroupUpstreamError(unavailable=False)
retry_error = RuntimeError("retry scheduled")
mocker.patch.object(
account_application_services.network_access_groups, "cleanup_app_binding", side_effect=upstream_error
diff --git a/packages/contracts/generated/api/console/account/errors.gen.ts b/packages/contracts/generated/api/console/account/errors.gen.ts
index 5245a8d4feb..cb2511347b3 100644
--- a/packages/contracts/generated/api/console/account/errors.gen.ts
+++ b/packages/contracts/generated/api/console/account/errors.gen.ts
@@ -106,6 +106,38 @@ const zEmailCodeAccountDeletionRateLimitExceededError = /* @__PURE__ */ (() =>
}),
))()
+const zBillingRequestInProgressError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_request_in_progress'),
+ status: z.literal(429),
+ }),
+ ))()
+
+const zBillingOperationFailedError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_operation_failed'),
+ status: z.literal(502),
+ }),
+ ))()
+
+const zBillingUnavailableError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_unavailable'),
+ status: z.literal(503),
+ }),
+ ))()
+
+const zEducationActivateFailedError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('education_activate_failed'),
+ status: z.literal(400),
+ }),
+ ))()
+
const zEducationActivateLimitError = /* @__PURE__ */ (() =>
zErrorResponse.and(
z.object({
@@ -114,6 +146,14 @@ const zEducationActivateLimitError = /* @__PURE__ */ (() =>
}),
))()
+const zEducationVerifyFailedError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('education_verify_failed'),
+ status: z.literal(400),
+ }),
+ ))()
+
const zEducationVerifyLimitError = /* @__PURE__ */ (() =>
zErrorResponse.and(
z.object({
@@ -203,13 +243,32 @@ export const post6Errors = {
invalid_account_deletion_code: { status: 400, data: zInvalidAccountDeletionCodeError },
}
+export const get3Errors = {
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+}
+
export const get4Errors = {
account_not_found: { status: 400, data: zAccountNotFoundError },
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_request_in_progress: { status: 429, data: zBillingRequestInProgressError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ education_verify_failed: { status: 400, data: zEducationVerifyFailedError },
education_verify_limit: { status: 429, data: zEducationVerifyLimitError },
}
+export const get5Errors = {
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_request_in_progress: { status: 429, data: zBillingRequestInProgressError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+}
+
export const post7Errors = {
account_not_found: { status: 400, data: zAccountNotFoundError },
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_request_in_progress: { status: 429, data: zBillingRequestInProgressError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ education_activate_failed: { status: 400, data: zEducationActivateFailedError },
education_activate_limit: { status: 429, data: zEducationActivateLimitError },
}
diff --git a/packages/contracts/generated/api/console/account/orpc.gen.ts b/packages/contracts/generated/api/console/account/orpc.gen.ts
index 2810d0fa53e..37280ccbd3b 100644
--- a/packages/contracts/generated/api/console/account/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/account/orpc.gen.ts
@@ -6,8 +6,13 @@ import {
zAccountAlreadyInitedError,
zAccountInFreezeError,
zAccountNotFoundError,
+ zBillingOperationFailedError,
+ zBillingRequestInProgressError,
+ zBillingUnavailableError,
zCurrentPasswordIncorrectError,
+ zEducationActivateFailedError,
zEducationActivateLimitError,
+ zEducationVerifyFailedError,
zEducationVerifyLimitError,
zEmailAlreadyInUseError,
zEmailChangeLimitError,
@@ -228,6 +233,10 @@ export const get3 = oc
})
.input(z.object({ query: zGetAccountEducationAutocompleteQuery }))
.output(zGetAccountEducationAutocompleteResponse)
+ .errors({
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ })
export const autocomplete = {
get: get3,
@@ -244,6 +253,10 @@ export const get4 = oc
.output(zGetAccountEducationVerifyResponse)
.errors({
account_not_found: { status: 400, data: zAccountNotFoundError },
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_request_in_progress: { status: 429, data: zBillingRequestInProgressError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ education_verify_failed: { status: 400, data: zEducationVerifyFailedError },
education_verify_limit: { status: 429, data: zEducationVerifyLimitError },
})
@@ -260,6 +273,11 @@ export const get5 = oc
tags: ['console'],
})
.output(zGetAccountEducationResponse)
+ .errors({
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_request_in_progress: { status: 429, data: zBillingRequestInProgressError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ })
export const post7 = oc
.route({
@@ -273,6 +291,10 @@ export const post7 = oc
.output(zPostAccountEducationResponse)
.errors({
account_not_found: { status: 400, data: zAccountNotFoundError },
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_request_in_progress: { status: 429, data: zBillingRequestInProgressError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ education_activate_failed: { status: 400, data: zEducationActivateFailedError },
education_activate_limit: { status: 429, data: zEducationActivateLimitError },
})
diff --git a/packages/contracts/generated/api/console/account/types.gen.ts b/packages/contracts/generated/api/console/account/types.gen.ts
index d640b59cf58..c6b7ef7afbb 100644
--- a/packages/contracts/generated/api/console/account/types.gen.ts
+++ b/packages/contracts/generated/api/console/account/types.gen.ts
@@ -147,6 +147,21 @@ export type EducationStatusResponse = {
result: boolean
}
+export type BillingRequestInProgressError = ErrorResponse & {
+ code: 'billing_request_in_progress'
+ status: 429
+}
+
+export type BillingOperationFailedError = ErrorResponse & {
+ code: 'billing_operation_failed'
+ status: 502
+}
+
+export type BillingUnavailableError = ErrorResponse & {
+ code: 'billing_unavailable'
+ status: 503
+}
+
export type EducationActivatePayload = {
institution: string
role: string
@@ -157,6 +172,11 @@ export type EducationActivateResponse = {
message: string
}
+export type EducationActivateFailedError = ErrorResponse & {
+ code: 'education_activate_failed'
+ status: 400
+}
+
export type EducationActivateLimitError = ErrorResponse & {
code: 'education_activate_limit'
status: 429
@@ -176,6 +196,11 @@ export type EducationVerifyResponse =
status: 'not_eligible'
} & EducationVerifyNotEligibleResponse)
+export type EducationVerifyFailedError = ErrorResponse & {
+ code: 'education_verify_failed'
+ status: 400
+}
+
export type EducationVerifyLimitError = ErrorResponse & {
code: 'education_verify_limit'
status: 429
@@ -449,6 +474,9 @@ export type GetAccountEducationData = {
}
export type GetAccountEducationErrors = {
+ 429: BillingRequestInProgressError | ErrorResponse
+ 502: BillingOperationFailedError | ErrorResponse
+ 503: BillingUnavailableError | ErrorResponse
default: ErrorResponse
}
@@ -469,8 +497,10 @@ export type PostAccountEducationData = {
}
export type PostAccountEducationErrors = {
- 400: AccountNotFoundError | ErrorResponse
- 429: EducationActivateLimitError | ErrorResponse
+ 400: AccountNotFoundError | EducationActivateFailedError | ErrorResponse
+ 429: BillingRequestInProgressError | EducationActivateLimitError | ErrorResponse
+ 502: BillingOperationFailedError | ErrorResponse
+ 503: BillingUnavailableError | ErrorResponse
default: ErrorResponse
}
@@ -495,6 +525,8 @@ export type GetAccountEducationAutocompleteData = {
}
export type GetAccountEducationAutocompleteErrors = {
+ 502: BillingOperationFailedError | ErrorResponse
+ 503: BillingUnavailableError | ErrorResponse
default: ErrorResponse
}
@@ -516,8 +548,10 @@ export type GetAccountEducationVerifyData = {
}
export type GetAccountEducationVerifyErrors = {
- 400: AccountNotFoundError | ErrorResponse
- 429: EducationVerifyLimitError | ErrorResponse
+ 400: AccountNotFoundError | EducationVerifyFailedError | ErrorResponse
+ 429: BillingRequestInProgressError | EducationVerifyLimitError | ErrorResponse
+ 502: BillingOperationFailedError | ErrorResponse
+ 503: BillingUnavailableError | ErrorResponse
default: ErrorResponse
}
diff --git a/packages/contracts/generated/api/console/account/zod.gen.ts b/packages/contracts/generated/api/console/account/zod.gen.ts
index 8629ed80134..f36c8ce2254 100644
--- a/packages/contracts/generated/api/console/account/zod.gen.ts
+++ b/packages/contracts/generated/api/console/account/zod.gen.ts
@@ -271,6 +271,42 @@ export const zEducationStatusResponse = z.object({
result: z.boolean(),
})
+/**
+ * BillingRequestInProgressError
+ *
+ * A previous request is still being processed. Please try again shortly.
+ */
+export const zBillingRequestInProgressError = zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_request_in_progress'),
+ status: z.literal(429),
+ }),
+)
+
+/**
+ * BillingOperationFailedError
+ *
+ * We couldn't complete this request. Please try again. If the problem persists, contact support.
+ */
+export const zBillingOperationFailedError = zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_operation_failed'),
+ status: z.literal(502),
+ }),
+)
+
+/**
+ * BillingUnavailableError
+ *
+ * This operation is temporarily unavailable. Please try again later.
+ */
+export const zBillingUnavailableError = zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_unavailable'),
+ status: z.literal(503),
+ }),
+)
+
/**
* EducationActivatePayload
*/
@@ -287,6 +323,18 @@ export const zEducationActivateResponse = z.object({
message: z.string(),
})
+/**
+ * EducationActivateFailedError
+ *
+ * We couldn't activate your education discount.
+ */
+export const zEducationActivateFailedError = zErrorResponse.and(
+ z.object({
+ code: z.literal('education_activate_failed'),
+ status: z.literal(400),
+ }),
+)
+
/**
* EducationActivateLimitError
*
@@ -308,6 +356,18 @@ export const zEducationAutocompleteResponse = z.object({
has_next: z.boolean(),
})
+/**
+ * EducationVerifyFailedError
+ *
+ * We couldn't verify your education status.
+ */
+export const zEducationVerifyFailedError = zErrorResponse.and(
+ z.object({
+ code: z.literal('education_verify_failed'),
+ status: z.literal(400),
+ }),
+)
+
/**
* EducationVerifyLimitError
*
diff --git a/packages/contracts/generated/api/console/apps/errors.gen.ts b/packages/contracts/generated/api/console/apps/errors.gen.ts
index f82577bbc7c..fe263698edf 100644
--- a/packages/contracts/generated/api/console/apps/errors.gen.ts
+++ b/packages/contracts/generated/api/console/apps/errors.gen.ts
@@ -234,6 +234,94 @@ const zMessageFeedbackRatingRequiredError = /* @__PURE__ */ (() =>
}),
))()
+const zNetworkAccessUnsupportedAppModeError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_unsupported_app_mode'),
+ status: z.literal(400),
+ }),
+ ))()
+
+const zNetworkAccessForbiddenError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_forbidden'),
+ status: z.literal(403),
+ }),
+ ))()
+
+const zNetworkAccessNotEntitledError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_not_entitled'),
+ status: z.literal(403),
+ }),
+ ))()
+
+const zNetworkAccessRoleDeniedError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_role_denied'),
+ status: z.literal(403),
+ }),
+ ))()
+
+const zBillingOperationFailedError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_operation_failed'),
+ status: z.literal(502),
+ }),
+ ))()
+
+const zBillingUnavailableError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_unavailable'),
+ status: z.literal(503),
+ }),
+ ))()
+
+const zNetworkAccessInvalidInputError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_invalid_input'),
+ status: z.literal(400),
+ }),
+ ))()
+
+const zNetworkAccessUnsupportedAccessPointsError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_unsupported_access_points'),
+ status: z.literal(400),
+ }),
+ ))()
+
+const zPaidPlanRequiredError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('paid_plan_required'),
+ status: z.literal(403),
+ }),
+ ))()
+
+const zNetworkAccessGroupNotFoundError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_group_not_found'),
+ status: z.literal(404),
+ }),
+ ))()
+
+const zNetworkAccessVersionConflictError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_version_conflict'),
+ status: z.literal(409),
+ }),
+ ))()
+
const zProviderNotSupportTextToSpeechError = /* @__PURE__ */ (() =>
zErrorResponse.and(
z.object({
@@ -724,11 +812,43 @@ export const get32Errors = {
export const post27Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const get33Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const get33Errors = {
+ app_not_found: { status: 404, data: zAppNotFoundError },
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ network_access_unsupported_app_mode: { status: 400, data: zNetworkAccessUnsupportedAppModeError },
+}
-export const get34Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const get34Errors = {
+ app_not_found: { status: 404, data: zAppNotFoundError },
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ network_access_unsupported_app_mode: { status: 400, data: zNetworkAccessUnsupportedAppModeError },
+}
-export const putErrors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const putErrors = {
+ app_not_found: { status: 404, data: zAppNotFoundError },
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_group_not_found: { status: 404, data: zNetworkAccessGroupNotFoundError },
+ network_access_invalid_input: { status: 400, data: zNetworkAccessInvalidInputError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ network_access_unsupported_access_points: {
+ status: 400,
+ data: zNetworkAccessUnsupportedAccessPointsError,
+ },
+ network_access_unsupported_app_mode: { status: 400, data: zNetworkAccessUnsupportedAppModeError },
+ network_access_version_conflict: { status: 409, data: zNetworkAccessVersionConflictError },
+ paid_plan_required: { status: 403, data: zPaidPlanRequiredError },
+}
export const post30Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
diff --git a/packages/contracts/generated/api/console/apps/orpc.gen.ts b/packages/contracts/generated/api/console/apps/orpc.gen.ts
index a1ff3255300..f11cbfde52c 100644
--- a/packages/contracts/generated/api/console/apps/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/apps/orpc.gen.ts
@@ -17,6 +17,8 @@ import {
zAppUnavailableError,
zAudioTooLargeError,
zBadRequestError,
+ zBillingOperationFailedError,
+ zBillingUnavailableError,
zBindingFileDownloadUnavailableError,
zCompletionRequestError,
zConversationNotFoundError,
@@ -30,11 +32,20 @@ import {
zMaxKeysExceededError,
zMessageFeedbackRatingRequiredError,
zModelCurrentlyNotSupportError,
+ zNetworkAccessForbiddenError,
+ zNetworkAccessGroupNotFoundError,
+ zNetworkAccessInvalidInputError,
+ zNetworkAccessNotEntitledError,
+ zNetworkAccessRoleDeniedError,
+ zNetworkAccessUnsupportedAccessPointsError,
+ zNetworkAccessUnsupportedAppModeError,
+ zNetworkAccessVersionConflictError,
zNoActiveBindingError,
zNoAudioUploadedError,
zNoFileUploadedError,
zNodeNotInWorkflowRunError,
zNodeOutputNotDeclaredError,
+ zPaidPlanRequiredError,
zPlaintextSecretNotAllowedError,
zProviderNotInitializeError,
zProviderNotSupportSpeechToTextError,
@@ -2265,7 +2276,18 @@ export const get33 = oc
})
.input(z.object({ params: zGetAppsByAppIdNetworkAccessGroupStatusPath }))
.output(zGetAppsByAppIdNetworkAccessGroupStatusResponse)
- .errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
+ .errors({
+ app_not_found: { status: 404, data: zAppNotFoundError },
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ network_access_unsupported_app_mode: {
+ status: 400,
+ data: zNetworkAccessUnsupportedAppModeError,
+ },
+ })
export const status2 = {
get: get33,
@@ -2281,7 +2303,18 @@ export const get34 = oc
})
.input(z.object({ params: zGetAppsByAppIdNetworkAccessGroupPath }))
.output(zGetAppsByAppIdNetworkAccessGroupResponse)
- .errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
+ .errors({
+ app_not_found: { status: 404, data: zAppNotFoundError },
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ network_access_unsupported_app_mode: {
+ status: 400,
+ data: zNetworkAccessUnsupportedAppModeError,
+ },
+ })
export const put = oc
.route({
@@ -2298,7 +2331,26 @@ export const put = oc
}),
)
.output(zPutAppsByAppIdNetworkAccessGroupResponse)
- .errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
+ .errors({
+ app_not_found: { status: 404, data: zAppNotFoundError },
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_group_not_found: { status: 404, data: zNetworkAccessGroupNotFoundError },
+ network_access_invalid_input: { status: 400, data: zNetworkAccessInvalidInputError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ network_access_unsupported_access_points: {
+ status: 400,
+ data: zNetworkAccessUnsupportedAccessPointsError,
+ },
+ network_access_unsupported_app_mode: {
+ status: 400,
+ data: zNetworkAccessUnsupportedAppModeError,
+ },
+ network_access_version_conflict: { status: 409, data: zNetworkAccessVersionConflictError },
+ paid_plan_required: { status: 403, data: zPaidPlanRequiredError },
+ })
export const networkAccessGroup = {
get: get34,
diff --git a/packages/contracts/generated/api/console/apps/types.gen.ts b/packages/contracts/generated/api/console/apps/types.gen.ts
index 9b7dd626171..c1fcd054d58 100644
--- a/packages/contracts/generated/api/console/apps/types.gen.ts
+++ b/packages/contracts/generated/api/console/apps/types.gen.ts
@@ -740,6 +740,36 @@ export type AppNetworkAccessGroupResponse = {
tenant_id: string
}
+export type NetworkAccessUnsupportedAppModeError = ErrorResponse & {
+ code: 'network_access_unsupported_app_mode'
+ status: 400
+}
+
+export type NetworkAccessForbiddenError = ErrorResponse & {
+ code: 'network_access_forbidden'
+ status: 403
+}
+
+export type NetworkAccessNotEntitledError = ErrorResponse & {
+ code: 'network_access_not_entitled'
+ status: 403
+}
+
+export type NetworkAccessRoleDeniedError = ErrorResponse & {
+ code: 'network_access_role_denied'
+ status: 403
+}
+
+export type BillingOperationFailedError = ErrorResponse & {
+ code: 'billing_operation_failed'
+ status: 502
+}
+
+export type BillingUnavailableError = ErrorResponse & {
+ code: 'billing_unavailable'
+ status: 503
+}
+
export type AppNetworkAccessGroupUpdatePayload = {
access_points: Array<'mcp' | 'service_api' | 'trigger' | 'webapp'>
enabled: boolean
@@ -753,6 +783,31 @@ export type AppNetworkAccessGroupMutationResponse = {
effective_enabled: boolean
}
+export type NetworkAccessInvalidInputError = ErrorResponse & {
+ code: 'network_access_invalid_input'
+ status: 400
+}
+
+export type NetworkAccessUnsupportedAccessPointsError = ErrorResponse & {
+ code: 'network_access_unsupported_access_points'
+ status: 400
+}
+
+export type PaidPlanRequiredError = ErrorResponse & {
+ code: 'paid_plan_required'
+ status: 403
+}
+
+export type NetworkAccessGroupNotFoundError = ErrorResponse & {
+ code: 'network_access_group_not_found'
+ status: 404
+}
+
+export type NetworkAccessVersionConflictError = ErrorResponse & {
+ code: 'network_access_version_conflict'
+ status: 409
+}
+
export type AppNetworkAccessGroupStatusResponse = {
available_count: number
configured: boolean
@@ -6716,7 +6771,15 @@ export type GetAppsByAppIdNetworkAccessGroupData = {
}
export type GetAppsByAppIdNetworkAccessGroupErrors = {
+ 400: NetworkAccessUnsupportedAppModeError | ErrorResponse
+ 403:
+ | NetworkAccessForbiddenError
+ | NetworkAccessNotEntitledError
+ | NetworkAccessRoleDeniedError
+ | ErrorResponse
404: AppNotFoundError | ErrorResponse
+ 502: BillingOperationFailedError | ErrorResponse
+ 503: BillingUnavailableError | ErrorResponse
default: ErrorResponse
}
@@ -6740,7 +6803,21 @@ export type PutAppsByAppIdNetworkAccessGroupData = {
}
export type PutAppsByAppIdNetworkAccessGroupErrors = {
- 404: AppNotFoundError | ErrorResponse
+ 400:
+ | NetworkAccessInvalidInputError
+ | NetworkAccessUnsupportedAccessPointsError
+ | NetworkAccessUnsupportedAppModeError
+ | ErrorResponse
+ 403:
+ | NetworkAccessForbiddenError
+ | NetworkAccessNotEntitledError
+ | NetworkAccessRoleDeniedError
+ | PaidPlanRequiredError
+ | ErrorResponse
+ 404: AppNotFoundError | NetworkAccessGroupNotFoundError | ErrorResponse
+ 409: NetworkAccessVersionConflictError | ErrorResponse
+ 502: BillingOperationFailedError | ErrorResponse
+ 503: BillingUnavailableError | ErrorResponse
default: ErrorResponse
}
@@ -6764,7 +6841,15 @@ export type GetAppsByAppIdNetworkAccessGroupStatusData = {
}
export type GetAppsByAppIdNetworkAccessGroupStatusErrors = {
+ 400: NetworkAccessUnsupportedAppModeError | ErrorResponse
+ 403:
+ | NetworkAccessForbiddenError
+ | NetworkAccessNotEntitledError
+ | NetworkAccessRoleDeniedError
+ | ErrorResponse
404: AppNotFoundError | ErrorResponse
+ 502: BillingOperationFailedError | ErrorResponse
+ 503: BillingUnavailableError | ErrorResponse
default: ErrorResponse
}
diff --git a/packages/contracts/generated/api/console/apps/zod.gen.ts b/packages/contracts/generated/api/console/apps/zod.gen.ts
index 5f7e5186894..88a054a43e8 100644
--- a/packages/contracts/generated/api/console/apps/zod.gen.ts
+++ b/packages/contracts/generated/api/console/apps/zod.gen.ts
@@ -676,6 +676,78 @@ export const zAppNamePayload = z.object({
name: z.string().min(1),
})
+/**
+ * NetworkAccessUnsupportedAppModeError
+ *
+ * Network access control is not supported for this app mode.
+ */
+export const zNetworkAccessUnsupportedAppModeError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_unsupported_app_mode'),
+ status: z.literal(400),
+ }),
+)
+
+/**
+ * NetworkAccessForbiddenError
+ *
+ * Network access groups are not available for this workspace.
+ */
+export const zNetworkAccessForbiddenError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_forbidden'),
+ status: z.literal(403),
+ }),
+)
+
+/**
+ * NetworkAccessNotEntitledError
+ *
+ * Network access groups are not available for this workspace.
+ */
+export const zNetworkAccessNotEntitledError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_not_entitled'),
+ status: z.literal(403),
+ }),
+)
+
+/**
+ * NetworkAccessRoleDeniedError
+ *
+ * Your workspace role does not allow this network access operation.
+ */
+export const zNetworkAccessRoleDeniedError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_role_denied'),
+ status: z.literal(403),
+ }),
+)
+
+/**
+ * BillingOperationFailedError
+ *
+ * We couldn't complete this request. Please try again. If the problem persists, contact support.
+ */
+export const zBillingOperationFailedError = zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_operation_failed'),
+ status: z.literal(502),
+ }),
+)
+
+/**
+ * BillingUnavailableError
+ *
+ * This operation is temporarily unavailable. Please try again later.
+ */
+export const zBillingUnavailableError = zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_unavailable'),
+ status: z.literal(503),
+ }),
+)
+
/**
* AppNetworkAccessGroupUpdatePayload
*/
@@ -686,6 +758,66 @@ export const zAppNetworkAccessGroupUpdatePayload = z.object({
group_id: z.uuid().nullable(),
})
+/**
+ * NetworkAccessInvalidInputError
+ *
+ * Invalid network access group request.
+ */
+export const zNetworkAccessInvalidInputError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_invalid_input'),
+ status: z.literal(400),
+ }),
+)
+
+/**
+ * NetworkAccessUnsupportedAccessPointsError
+ *
+ * Some access points are not supported for this app.
+ */
+export const zNetworkAccessUnsupportedAccessPointsError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_unsupported_access_points'),
+ status: z.literal(400),
+ }),
+)
+
+/**
+ * PaidPlanRequiredError
+ *
+ * This feature requires a paid plan.
+ */
+export const zPaidPlanRequiredError = zErrorResponse.and(
+ z.object({
+ code: z.literal('paid_plan_required'),
+ status: z.literal(403),
+ }),
+)
+
+/**
+ * NetworkAccessGroupNotFoundError
+ *
+ * Network access group was not found.
+ */
+export const zNetworkAccessGroupNotFoundError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_group_not_found'),
+ status: z.literal(404),
+ }),
+)
+
+/**
+ * NetworkAccessVersionConflictError
+ *
+ * The network access resource changed. Refresh it and try again.
+ */
+export const zNetworkAccessVersionConflictError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_version_conflict'),
+ status: z.literal(409),
+ }),
+)
+
/**
* AppNetworkAccessGroupStatusResponse
*/
diff --git a/packages/contracts/generated/api/console/compliance/errors.gen.ts b/packages/contracts/generated/api/console/compliance/errors.gen.ts
index bee33fd3c25..2002088eaf7 100644
--- a/packages/contracts/generated/api/console/compliance/errors.gen.ts
+++ b/packages/contracts/generated/api/console/compliance/errors.gen.ts
@@ -10,6 +10,30 @@ const zErrorResponse = /* @__PURE__ */ (() =>
status: z.int(),
}))()
+const zComplianceDownloadForbiddenError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('compliance_download_forbidden'),
+ status: z.literal(403),
+ }),
+ ))()
+
+const zComplianceDocumentNotFoundError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('compliance_document_not_found'),
+ status: z.literal(404),
+ }),
+ ))()
+
+const zBillingRequestInProgressError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_request_in_progress'),
+ status: z.literal(429),
+ }),
+ ))()
+
const zComplianceRateLimitError = /* @__PURE__ */ (() =>
zErrorResponse.and(
z.object({
@@ -36,6 +60,9 @@ const zBillingUnavailableError = /* @__PURE__ */ (() =>
export const getErrors = {
billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_request_in_progress: { status: 429, data: zBillingRequestInProgressError },
billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ compliance_document_not_found: { status: 404, data: zComplianceDocumentNotFoundError },
+ compliance_download_forbidden: { status: 403, data: zComplianceDownloadForbiddenError },
compliance_rate_limit: { status: 429, data: zComplianceRateLimitError },
}
diff --git a/packages/contracts/generated/api/console/compliance/orpc.gen.ts b/packages/contracts/generated/api/console/compliance/orpc.gen.ts
index 4b2225b0c99..1c38b978887 100644
--- a/packages/contracts/generated/api/console/compliance/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/compliance/orpc.gen.ts
@@ -4,7 +4,10 @@ import { oc } from '@orpc/contract'
import * as z from 'zod'
import {
zBillingOperationFailedError,
+ zBillingRequestInProgressError,
zBillingUnavailableError,
+ zComplianceDocumentNotFoundError,
+ zComplianceDownloadForbiddenError,
zComplianceRateLimitError,
} from './zod.gen.ts'
import { zGetComplianceDownloadQuery, zGetComplianceDownloadResponse } from './zod.gen.ts'
@@ -25,7 +28,10 @@ export const get = oc
.output(zGetComplianceDownloadResponse)
.errors({
billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_request_in_progress: { status: 429, data: zBillingRequestInProgressError },
billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ compliance_document_not_found: { status: 404, data: zComplianceDocumentNotFoundError },
+ compliance_download_forbidden: { status: 403, data: zComplianceDownloadForbiddenError },
compliance_rate_limit: { status: 429, data: zComplianceRateLimitError },
})
diff --git a/packages/contracts/generated/api/console/compliance/types.gen.ts b/packages/contracts/generated/api/console/compliance/types.gen.ts
index e7e752efb46..d8cd05e5975 100644
--- a/packages/contracts/generated/api/console/compliance/types.gen.ts
+++ b/packages/contracts/generated/api/console/compliance/types.gen.ts
@@ -8,10 +8,9 @@ export type ComplianceDownloadResponse = {
url: string
}
-export type BillingUnprocessableEntityErrorResponse = {
- code: 'unprocessable_entity'
- message: string
- status: 422
+export type ComplianceDownloadForbiddenError = ErrorResponse & {
+ code: 'compliance_download_forbidden'
+ status: 403
}
export type ErrorResponse = {
@@ -24,12 +23,28 @@ export type ErrorResponse = {
status: number
}
+export type ComplianceDocumentNotFoundError = ErrorResponse & {
+ code: 'compliance_document_not_found'
+ status: 404
+}
+
+export type BillingUnprocessableEntityErrorResponse = {
+ code: 'unprocessable_entity'
+ message: string
+ status: 422
+}
+
export type ComplianceRateLimitErrorResponse = {
code: 'compliance_rate_limit'
message: string
status: 429
}
+export type BillingRequestInProgressError = ErrorResponse & {
+ code: 'billing_request_in_progress'
+ status: 429
+}
+
export type ComplianceRateLimitError = ErrorResponse & {
code: 'compliance_rate_limit'
status: 429
@@ -67,8 +82,14 @@ export type GetComplianceDownloadData = {
}
export type GetComplianceDownloadErrors = {
+ 403: ComplianceDownloadForbiddenError | ErrorResponse
+ 404: ComplianceDocumentNotFoundError | ErrorResponse
422: BillingUnprocessableEntityErrorResponse | ErrorResponse
- 429: ComplianceRateLimitErrorResponse | ComplianceRateLimitError | ErrorResponse
+ 429:
+ | ComplianceRateLimitErrorResponse
+ | BillingRequestInProgressError
+ | ComplianceRateLimitError
+ | ErrorResponse
502: BillingOperationFailedErrorResponse | BillingOperationFailedError | ErrorResponse
503: BillingUnavailableErrorResponse | BillingUnavailableError | ErrorResponse
default: ErrorResponse
diff --git a/packages/contracts/generated/api/console/compliance/zod.gen.ts b/packages/contracts/generated/api/console/compliance/zod.gen.ts
index d5eac237d3c..009ebd4f9ff 100644
--- a/packages/contracts/generated/api/console/compliance/zod.gen.ts
+++ b/packages/contracts/generated/api/console/compliance/zod.gen.ts
@@ -9,15 +9,6 @@ export const zComplianceDownloadResponse = z.object({
url: z.string(),
})
-/**
- * BillingUnprocessableEntityErrorResponse
- */
-export const zBillingUnprocessableEntityErrorResponse = z.object({
- code: z.literal('unprocessable_entity'),
- message: z.string(),
- status: z.literal(422),
-})
-
/**
* ErrorResponse
*
@@ -34,6 +25,39 @@ export const zErrorResponse = z.object({
status: z.int(),
})
+/**
+ * ComplianceDownloadForbiddenError
+ *
+ * Your current plan does not allow downloading this compliance document.
+ */
+export const zComplianceDownloadForbiddenError = zErrorResponse.and(
+ z.object({
+ code: z.literal('compliance_download_forbidden'),
+ status: z.literal(403),
+ }),
+)
+
+/**
+ * ComplianceDocumentNotFoundError
+ *
+ * The compliance document was not found.
+ */
+export const zComplianceDocumentNotFoundError = zErrorResponse.and(
+ z.object({
+ code: z.literal('compliance_document_not_found'),
+ status: z.literal(404),
+ }),
+)
+
+/**
+ * BillingUnprocessableEntityErrorResponse
+ */
+export const zBillingUnprocessableEntityErrorResponse = z.object({
+ code: z.literal('unprocessable_entity'),
+ message: z.string(),
+ status: z.literal(422),
+})
+
/**
* ComplianceRateLimitErrorResponse
*/
@@ -43,6 +67,18 @@ export const zComplianceRateLimitErrorResponse = z.object({
status: z.literal(429),
})
+/**
+ * BillingRequestInProgressError
+ *
+ * A previous request is still being processed. Please try again shortly.
+ */
+export const zBillingRequestInProgressError = zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_request_in_progress'),
+ status: z.literal(429),
+ }),
+)
+
/**
* ComplianceRateLimitError
*
diff --git a/packages/contracts/generated/api/console/errors.gen.ts b/packages/contracts/generated/api/console/errors.gen.ts
index 93c5935f12a..a76961cb811 100644
--- a/packages/contracts/generated/api/console/errors.gen.ts
+++ b/packages/contracts/generated/api/console/errors.gen.ts
@@ -5,6 +5,7 @@ export { delete11Errors as 'DELETE /apps/{app_id}/workflows/draft/nodes/{node_id
export { delete11Errors as 'DELETE /knowledge-fs/spaces/{control_space_id}/sources/{source_id}' } from './knowledge-fs/errors.gen.ts'
export { delete12Errors as 'DELETE /apps/{app_id}/workflows/draft/variables/{variable_id}' } from './apps/errors.gen.ts'
export { delete12Errors as 'DELETE /knowledge-fs/spaces/{control_space_id}' } from './knowledge-fs/errors.gen.ts'
+export { delete12Errors as 'DELETE /workspaces/current/network-access-groups/{group_id}' } from './workspaces/errors.gen.ts'
export { delete13Errors as 'DELETE /apps/{app_id}/workflows/draft/variables' } from './apps/errors.gen.ts'
export { delete13Errors as 'DELETE /knowledge-fs/uploads/{upload_id}' } from './knowledge-fs/errors.gen.ts'
export { delete14Errors as 'DELETE /apps/{app_id}/workflows/{workflow_id}' } from './apps/errors.gen.ts'
@@ -39,6 +40,7 @@ export { delete9Errors as 'DELETE /knowledge-fs/spaces/{control_space_id}/metada
export { delete_Errors as 'DELETE /apps/{app_id}/agent/config/files/{name}' } from './apps/errors.gen.ts'
export { delete_Errors as 'DELETE /installed-apps/{installed_app_id}/conversations/{c_id}' } from './installed-apps/errors.gen.ts'
export { delete_Errors as 'DELETE /knowledge-fs/source-provider-preview/jobs/{job_id}' } from './knowledge-fs/errors.gen.ts'
+export { delete_Errors as 'DELETE /workflow-run-archives/{year}/{month}' } from './workflow-run-archives/errors.gen.ts'
export { get101Errors as 'GET /workspaces/current/summary' } from './workspaces/errors.gen.ts'
export { get10Errors as 'GET /agent/{agent_id}/config/files/{name}/preview' } from './agent/errors.gen.ts'
export { get10Errors as 'GET /apps/{app_id}/agent/config/skills/{name}/download' } from './apps/errors.gen.ts'
@@ -131,6 +133,7 @@ export { get2Errors as 'GET /form/human_input/{form_token}' } from './form/error
export { get2Errors as 'GET /installed-apps/{installed_app_id}/messages/{message_id}/more-like-this' } from './installed-apps/errors.gen.ts'
export { get2Errors as 'GET /notion/pre-import/pages' } from './notion/errors.gen.ts'
export { get2Errors as 'GET /trial-apps/{app_id}/agent/config/files/{name}/download' } from './trial-apps/errors.gen.ts'
+export { get2Errors as 'GET /workflow-run-archives' } from './workflow-run-archives/errors.gen.ts'
export { get30Errors as 'GET /agent/{agent_id}/trace-capabilities' } from './agent/errors.gen.ts'
export { get30Errors as 'GET /apps/{app_id}/conversation-variables' } from './apps/errors.gen.ts'
export { get30Errors as 'GET /knowledge-fs/spaces/{control_space_id}/permissions' } from './knowledge-fs/errors.gen.ts'
@@ -150,15 +153,20 @@ export { get34Errors as 'GET /knowledge-fs/spaces/{control_space_id}/quality/rep
export { get35Errors as 'GET /agent/{agent_id}' } from './agent/errors.gen.ts'
export { get35Errors as 'GET /apps/{app_id}/server' } from './apps/errors.gen.ts'
export { get35Errors as 'GET /knowledge-fs/spaces/{control_space_id}/quality/replay-runs' } from './knowledge-fs/errors.gen.ts'
+export { get35Errors as 'GET /workspaces/current/network-access-groups/current-ip' } from './workspaces/errors.gen.ts'
export { get36Errors as 'GET /agent' } from './agent/errors.gen.ts'
export { get36Errors as 'GET /apps/{app_id}/statistics/average-response-time' } from './apps/errors.gen.ts'
export { get36Errors as 'GET /knowledge-fs/spaces/{control_space_id}/research-tasks/{task_id}/partials' } from './knowledge-fs/errors.gen.ts'
+export { get36Errors as 'GET /workspaces/current/network-access-groups/{group_id}/check-current-ip' } from './workspaces/errors.gen.ts'
export { get37Errors as 'GET /apps/{app_id}/statistics/average-session-interactions' } from './apps/errors.gen.ts'
export { get37Errors as 'GET /knowledge-fs/spaces/{control_space_id}/research-tasks/{task_id}' } from './knowledge-fs/errors.gen.ts'
+export { get37Errors as 'GET /workspaces/current/network-access-groups/{group_id}' } from './workspaces/errors.gen.ts'
export { get38Errors as 'GET /apps/{app_id}/statistics/daily-conversations' } from './apps/errors.gen.ts'
export { get38Errors as 'GET /knowledge-fs/spaces/{control_space_id}/research-tasks' } from './knowledge-fs/errors.gen.ts'
+export { get38Errors as 'GET /workspaces/current/network-access-groups' } from './workspaces/errors.gen.ts'
export { get39Errors as 'GET /apps/{app_id}/statistics/daily-end-users' } from './apps/errors.gen.ts'
export { get39Errors as 'GET /knowledge-fs/spaces/{control_space_id}/settings/migrations/{migration_id}' } from './knowledge-fs/errors.gen.ts'
+export { get3Errors as 'GET /account/education/autocomplete' } from './account/errors.gen.ts'
export { get3Errors as 'GET /installed-apps/{installed_app_id}/messages/{message_id}/suggested-questions' } from './installed-apps/errors.gen.ts'
export { get3Errors as 'GET /knowledge-fs/research-tasks/{task_id}/events' } from './knowledge-fs/errors.gen.ts'
export { get3Errors as 'GET /trial-apps/{app_id}/agent/config/files/{name}/preview' } from './trial-apps/errors.gen.ts'
@@ -217,6 +225,7 @@ export { get57Errors as 'GET /apps/{app_id}/workflow-runs' } from './apps/errors
export { get57Errors as 'GET /knowledge-fs/spaces' } from './knowledge-fs/errors.gen.ts'
export { get58Errors as 'GET /apps/{app_id}/workflow/comments/mention-users' } from './apps/errors.gen.ts'
export { get59Errors as 'GET /apps/{app_id}/workflow/comments/{comment_id}' } from './apps/errors.gen.ts'
+export { get5Errors as 'GET /account/education' } from './account/errors.gen.ts'
export { get5Errors as 'GET /agent/{agent_id}/chat-messages/{message_id}/suggested-questions' } from './agent/errors.gen.ts'
export { get5Errors as 'GET /apps/{app_id}/advanced-chat/workflow-runs' } from './apps/errors.gen.ts'
export { get5Errors as 'GET /datasets/external-knowledge-api/{external_knowledge_api_id}' } from './datasets/errors.gen.ts'
@@ -288,6 +297,7 @@ export { getErrors as 'GET /installed-apps/{installed_app_id}/conversations' } f
export { getErrors as 'GET /remote-files/{url}' } from './remote-files/errors.gen.ts'
export { getErrors as 'GET /trial-apps/{app_id}/agent-composer' } from './trial-apps/errors.gen.ts'
export { getErrors as 'GET /website/crawl/status/{job_id}' } from './website/errors.gen.ts'
+export { getErrors as 'GET /workflow-run-archives/downloads/{download_id}' } from './workflow-run-archives/errors.gen.ts'
export { patch2Errors as 'PATCH /apps/{app_id}/workflows/draft/variables/{variable_id}' } from './apps/errors.gen.ts'
export { patch2Errors as 'PATCH /datasets/{dataset_id}/documents/status/{action}/batch' } from './datasets/errors.gen.ts'
export { patch2Errors as 'PATCH /installed-apps/{installed_app_id}/conversations/{c_id}/unpin' } from './installed-apps/errors.gen.ts'
@@ -419,6 +429,7 @@ export { post37Errors as 'POST /apps/{app_id}/trace' } from './apps/errors.gen.t
export { post37Errors as 'POST /knowledge-fs/spaces/{control_space_id}/upload-sessions/{upload_session_id}/parts/{part_number}/presign' } from './knowledge-fs/errors.gen.ts'
export { post38Errors as 'POST /apps/{app_id}/trace-config' } from './apps/errors.gen.ts'
export { post38Errors as 'POST /knowledge-fs/spaces/{control_space_id}/upload-sessions/{upload_session_id}/small-file' } from './knowledge-fs/errors.gen.ts'
+export { post38Errors as 'POST /workspaces/current/network-access-groups' } from './workspaces/errors.gen.ts'
export { post39Errors as 'POST /apps/{app_id}/trace-runs/{source_kind}/{source_id}/retry' } from './apps/errors.gen.ts'
export { post39Errors as 'POST /knowledge-fs/spaces/{control_space_id}/upload-sessions' } from './knowledge-fs/errors.gen.ts'
export { post3Errors as 'POST /account/change-email/validity' } from './account/errors.gen.ts'
@@ -548,6 +559,7 @@ export { postErrors as 'POST /rule-generate' } from './rule-generate/errors.gen.
export { postErrors as 'POST /rule-structured-output-generate' } from './rule-structured-output-generate/errors.gen.ts'
export { postErrors as 'POST /trial-apps/{app_id}/audio-to-text' } from './trial-apps/errors.gen.ts'
export { postErrors as 'POST /website/crawl' } from './website/errors.gen.ts'
+export { postErrors as 'POST /workflow-run-archives/downloads' } from './workflow-run-archives/errors.gen.ts'
export { put24Errors as 'PUT /workspaces/current/skills/{skill_id}/files' } from './workspaces/errors.gen.ts'
export { put2Errors as 'PUT /agent/{agent_id}/composer' } from './agent/errors.gen.ts'
export { put2Errors as 'PUT /apps/{app_id}/server' } from './apps/errors.gen.ts'
@@ -561,6 +573,7 @@ export { put5Errors as 'PUT /apps/{app_id}/workflows/draft/nodes/{node_id}/agent
export { put5Errors as 'PUT /knowledge-fs/spaces/{control_space_id}/tags' } from './knowledge-fs/errors.gen.ts'
export { put6Errors as 'PUT /apps/{app_id}/workflows/draft/variables/{variable_id}/reset' } from './apps/errors.gen.ts'
export { put6Errors as 'PUT /workspaces/current/members/{member_id}/update-role' } from './workspaces/errors.gen.ts'
+export { put9Errors as 'PUT /workspaces/current/network-access-groups/{group_id}' } from './workspaces/errors.gen.ts'
export { putErrors as 'PUT /agent/{agent_id}/build-draft' } from './agent/errors.gen.ts'
export { putErrors as 'PUT /apps/{app_id}/network-access-group' } from './apps/errors.gen.ts'
export { putErrors as 'PUT /knowledge-fs/spaces/{control_space_id}/app-bindings' } from './knowledge-fs/errors.gen.ts'
diff --git a/packages/contracts/generated/api/console/workflow-run-archives/errors.gen.ts b/packages/contracts/generated/api/console/workflow-run-archives/errors.gen.ts
new file mode 100644
index 00000000000..d4dbc81d6d6
--- /dev/null
+++ b/packages/contracts/generated/api/console/workflow-run-archives/errors.gen.ts
@@ -0,0 +1,27 @@
+// This file is auto-generated by scripts/add-orpc-error-maps.ts
+import * as z from 'zod'
+
+const zErrorResponse = /* @__PURE__ */ (() =>
+ z.object({
+ code: z.string(),
+ details: z.record(z.string(), z.unknown()).optional(),
+ message: z.string(),
+ params: z.string().optional(),
+ status: z.int(),
+ }))()
+
+const zPaidPlanRequiredError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('paid_plan_required'),
+ status: z.literal(403),
+ }),
+ ))()
+
+export const getErrors = { paid_plan_required: { status: 403, data: zPaidPlanRequiredError } }
+
+export const postErrors = { paid_plan_required: { status: 403, data: zPaidPlanRequiredError } }
+
+export const delete_Errors = { paid_plan_required: { status: 403, data: zPaidPlanRequiredError } }
+
+export const get2Errors = { paid_plan_required: { status: 403, data: zPaidPlanRequiredError } }
diff --git a/packages/contracts/generated/api/console/workflow-run-archives/orpc.gen.ts b/packages/contracts/generated/api/console/workflow-run-archives/orpc.gen.ts
index 5bfa2820b7b..8a1b16489e8 100644
--- a/packages/contracts/generated/api/console/workflow-run-archives/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/workflow-run-archives/orpc.gen.ts
@@ -2,6 +2,7 @@
import { oc } from '@orpc/contract'
import * as z from 'zod'
+import { zPaidPlanRequiredError } from './zod.gen.ts'
import {
zDeleteWorkflowRunArchivesByYearByMonthPath,
zDeleteWorkflowRunArchivesByYearByMonthResponse,
@@ -26,6 +27,7 @@ export const get = oc
})
.input(z.object({ params: zGetWorkflowRunArchivesDownloadsByDownloadIdPath }))
.output(zGetWorkflowRunArchivesDownloadsByDownloadIdResponse)
+ .errors({ paid_plan_required: { status: 403, data: zPaidPlanRequiredError } })
export const byDownloadId = {
get,
@@ -46,6 +48,7 @@ export const post = oc
})
.input(z.object({ body: zPostWorkflowRunArchivesDownloadsBody }))
.output(zPostWorkflowRunArchivesDownloadsResponse)
+ .errors({ paid_plan_required: { status: 403, data: zPaidPlanRequiredError } })
export const downloads = {
post,
@@ -67,6 +70,7 @@ export const delete_ = oc
})
.input(z.object({ params: zDeleteWorkflowRunArchivesByYearByMonthPath }))
.output(zDeleteWorkflowRunArchivesByYearByMonthResponse)
+ .errors({ paid_plan_required: { status: 403, data: zPaidPlanRequiredError } })
export const byMonth = {
delete: delete_,
@@ -89,6 +93,7 @@ export const get2 = oc
tags: ['console'],
})
.output(zGetWorkflowRunArchivesResponse)
+ .errors({ paid_plan_required: { status: 403, data: zPaidPlanRequiredError } })
export const workflowRunArchives = {
get: get2,
diff --git a/packages/contracts/generated/api/console/workflow-run-archives/types.gen.ts b/packages/contracts/generated/api/console/workflow-run-archives/types.gen.ts
index 23dd7c3547a..58416b5f5ea 100644
--- a/packages/contracts/generated/api/console/workflow-run-archives/types.gen.ts
+++ b/packages/contracts/generated/api/console/workflow-run-archives/types.gen.ts
@@ -9,6 +9,11 @@ export type WorkflowRunArchiveListResponse = {
summary: WorkflowRunArchiveSummaryResponse
}
+export type PaidPlanRequiredError = ErrorResponse & {
+ code: 'paid_plan_required'
+ status: 403
+}
+
export type ErrorResponse = {
code: string
details?: {
@@ -79,6 +84,7 @@ export type GetWorkflowRunArchivesData = {
}
export type GetWorkflowRunArchivesErrors = {
+ 403: PaidPlanRequiredError | ErrorResponse
default: ErrorResponse
}
@@ -100,6 +106,7 @@ export type PostWorkflowRunArchivesDownloadsData = {
}
export type PostWorkflowRunArchivesDownloadsErrors = {
+ 403: PaidPlanRequiredError | ErrorResponse
default: ErrorResponse
}
@@ -123,6 +130,7 @@ export type GetWorkflowRunArchivesDownloadsByDownloadIdData = {
}
export type GetWorkflowRunArchivesDownloadsByDownloadIdErrors = {
+ 403: PaidPlanRequiredError | ErrorResponse
default: ErrorResponse
}
@@ -147,6 +155,7 @@ export type DeleteWorkflowRunArchivesByYearByMonthData = {
}
export type DeleteWorkflowRunArchivesByYearByMonthErrors = {
+ 403: PaidPlanRequiredError | ErrorResponse
default: ErrorResponse
}
diff --git a/packages/contracts/generated/api/console/workflow-run-archives/zod.gen.ts b/packages/contracts/generated/api/console/workflow-run-archives/zod.gen.ts
index a910bc9febd..e387b83a658 100644
--- a/packages/contracts/generated/api/console/workflow-run-archives/zod.gen.ts
+++ b/packages/contracts/generated/api/console/workflow-run-archives/zod.gen.ts
@@ -18,6 +18,18 @@ export const zErrorResponse = z.object({
status: z.int(),
})
+/**
+ * PaidPlanRequiredError
+ *
+ * This feature requires a paid plan.
+ */
+export const zPaidPlanRequiredError = zErrorResponse.and(
+ z.object({
+ code: z.literal('paid_plan_required'),
+ status: z.literal(403),
+ }),
+)
+
/**
* WorkflowRunArchiveDownloadPayload
*
diff --git a/packages/contracts/generated/api/console/workspaces/errors.gen.ts b/packages/contracts/generated/api/console/workspaces/errors.gen.ts
index 9e108d3ec6c..80e86480a82 100644
--- a/packages/contracts/generated/api/console/workspaces/errors.gen.ts
+++ b/packages/contracts/generated/api/console/workspaces/errors.gen.ts
@@ -138,6 +138,94 @@ const zRoleAlreadyAssignedError = /* @__PURE__ */ (() =>
}),
))()
+const zNetworkAccessForbiddenError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_forbidden'),
+ status: z.literal(403),
+ }),
+ ))()
+
+const zNetworkAccessNotEntitledError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_not_entitled'),
+ status: z.literal(403),
+ }),
+ ))()
+
+const zNetworkAccessRoleDeniedError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_role_denied'),
+ status: z.literal(403),
+ }),
+ ))()
+
+const zBillingOperationFailedError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_operation_failed'),
+ status: z.literal(502),
+ }),
+ ))()
+
+const zBillingUnavailableError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_unavailable'),
+ status: z.literal(503),
+ }),
+ ))()
+
+const zNetworkAccessInvalidInputError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_invalid_input'),
+ status: z.literal(400),
+ }),
+ ))()
+
+const zPaidPlanRequiredError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('paid_plan_required'),
+ status: z.literal(403),
+ }),
+ ))()
+
+const zNetworkAccessGroupNameConflictError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_group_name_conflict'),
+ status: z.literal(409),
+ }),
+ ))()
+
+const zNetworkAccessGroupNotFoundError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_group_not_found'),
+ status: z.literal(404),
+ }),
+ ))()
+
+const zNetworkAccessGroupBoundError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_group_bound'),
+ status: z.literal(409),
+ }),
+ ))()
+
+const zNetworkAccessVersionConflictError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_version_conflict'),
+ status: z.literal(409),
+ }),
+ ))()
+
const zPluginError = /* @__PURE__ */ (() =>
zErrorResponse.and(
z.object({
@@ -253,6 +341,72 @@ export const delete8Errors = {
member_not_found: { status: 404, data: zMemberNotFoundError },
}
+export const get35Errors = {
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+}
+
+export const get36Errors = {
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_group_not_found: { status: 404, data: zNetworkAccessGroupNotFoundError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+}
+
+export const delete12Errors = {
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_group_bound: { status: 409, data: zNetworkAccessGroupBoundError },
+ network_access_group_not_found: { status: 404, data: zNetworkAccessGroupNotFoundError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ network_access_version_conflict: { status: 409, data: zNetworkAccessVersionConflictError },
+ paid_plan_required: { status: 403, data: zPaidPlanRequiredError },
+}
+
+export const get37Errors = {
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_group_not_found: { status: 404, data: zNetworkAccessGroupNotFoundError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+}
+
+export const put9Errors = {
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_group_name_conflict: { status: 409, data: zNetworkAccessGroupNameConflictError },
+ network_access_group_not_found: { status: 404, data: zNetworkAccessGroupNotFoundError },
+ network_access_invalid_input: { status: 400, data: zNetworkAccessInvalidInputError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ network_access_version_conflict: { status: 409, data: zNetworkAccessVersionConflictError },
+ paid_plan_required: { status: 403, data: zPaidPlanRequiredError },
+}
+
+export const get38Errors = {
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+}
+
+export const post38Errors = {
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_group_name_conflict: { status: 409, data: zNetworkAccessGroupNameConflictError },
+ network_access_invalid_input: { status: 400, data: zNetworkAccessInvalidInputError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ paid_plan_required: { status: 403, data: zPaidPlanRequiredError },
+}
+
export const get40Errors = { plugin_error: { status: 400, data: zPluginError } }
export const get42Errors = { plugin_error: { status: 400, data: zPluginError } }
diff --git a/packages/contracts/generated/api/console/workspaces/orpc.gen.ts b/packages/contracts/generated/api/console/workspaces/orpc.gen.ts
index 7b02b27bf37..77ccaed5749 100644
--- a/packages/contracts/generated/api/console/workspaces/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/workspaces/orpc.gen.ts
@@ -4,6 +4,8 @@ import { oc } from '@orpc/contract'
import * as z from 'zod'
import {
zAccountNotLinkTenantError,
+ zBillingOperationFailedError,
+ zBillingUnavailableError,
zCannotOperateSelfError,
zCannotTransferOwnerToSelfError,
zCurrentWorkspaceArchivedError,
@@ -20,10 +22,19 @@ import {
zLimitExceededError,
zMemberNotFoundError,
zMemberNotInTenantError,
+ zNetworkAccessForbiddenError,
+ zNetworkAccessGroupBoundError,
+ zNetworkAccessGroupNameConflictError,
+ zNetworkAccessGroupNotFoundError,
+ zNetworkAccessInvalidInputError,
+ zNetworkAccessNotEntitledError,
+ zNetworkAccessRoleDeniedError,
+ zNetworkAccessVersionConflictError,
zNoFileUploadedError,
zNotOwnerError,
zOwnerTransferLimitError,
zOwnerTransferRateLimitExceededError,
+ zPaidPlanRequiredError,
zPluginError,
zRoleAlreadyAssignedError,
zTooManyFilesError,
@@ -2536,6 +2547,7 @@ export const get35 = oc
tags: ['console'],
})
.output(zGetWorkspacesCurrentNetworkAccessGroupsCurrentIpResponse)
+ .errors({ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError } })
export const currentIp = {
get: get35,
@@ -2551,6 +2563,14 @@ export const get36 = oc
})
.input(z.object({ params: zGetWorkspacesCurrentNetworkAccessGroupsByGroupIdCheckCurrentIpPath }))
.output(zGetWorkspacesCurrentNetworkAccessGroupsByGroupIdCheckCurrentIpResponse)
+ .errors({
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_group_not_found: { status: 404, data: zNetworkAccessGroupNotFoundError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ })
export const checkCurrentIp = {
get: get36,
@@ -2571,6 +2591,17 @@ export const delete12 = oc
}),
)
.output(zDeleteWorkspacesCurrentNetworkAccessGroupsByGroupIdResponse)
+ .errors({
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_group_bound: { status: 409, data: zNetworkAccessGroupBoundError },
+ network_access_group_not_found: { status: 404, data: zNetworkAccessGroupNotFoundError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ network_access_version_conflict: { status: 409, data: zNetworkAccessVersionConflictError },
+ paid_plan_required: { status: 403, data: zPaidPlanRequiredError },
+ })
export const get37 = oc
.route({
@@ -2582,6 +2613,14 @@ export const get37 = oc
})
.input(z.object({ params: zGetWorkspacesCurrentNetworkAccessGroupsByGroupIdPath }))
.output(zGetWorkspacesCurrentNetworkAccessGroupsByGroupIdResponse)
+ .errors({
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_group_not_found: { status: 404, data: zNetworkAccessGroupNotFoundError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ })
export const put9 = oc
.route({
@@ -2598,6 +2637,18 @@ export const put9 = oc
}),
)
.output(zPutWorkspacesCurrentNetworkAccessGroupsByGroupIdResponse)
+ .errors({
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_group_name_conflict: { status: 409, data: zNetworkAccessGroupNameConflictError },
+ network_access_group_not_found: { status: 404, data: zNetworkAccessGroupNotFoundError },
+ network_access_invalid_input: { status: 400, data: zNetworkAccessInvalidInputError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ network_access_version_conflict: { status: 409, data: zNetworkAccessVersionConflictError },
+ paid_plan_required: { status: 403, data: zPaidPlanRequiredError },
+ })
export const byGroupId = {
delete: delete12,
@@ -2615,6 +2666,13 @@ export const get38 = oc
tags: ['console'],
})
.output(zGetWorkspacesCurrentNetworkAccessGroupsResponse)
+ .errors({
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ })
export const post38 = oc
.route({
@@ -2627,6 +2685,16 @@ export const post38 = oc
})
.input(z.object({ body: zPostWorkspacesCurrentNetworkAccessGroupsBody }))
.output(zPostWorkspacesCurrentNetworkAccessGroupsResponse)
+ .errors({
+ billing_operation_failed: { status: 502, data: zBillingOperationFailedError },
+ billing_unavailable: { status: 503, data: zBillingUnavailableError },
+ network_access_forbidden: { status: 403, data: zNetworkAccessForbiddenError },
+ network_access_group_name_conflict: { status: 409, data: zNetworkAccessGroupNameConflictError },
+ network_access_invalid_input: { status: 400, data: zNetworkAccessInvalidInputError },
+ network_access_not_entitled: { status: 403, data: zNetworkAccessNotEntitledError },
+ network_access_role_denied: { status: 403, data: zNetworkAccessRoleDeniedError },
+ paid_plan_required: { status: 403, data: zPaidPlanRequiredError },
+ })
export const networkAccessGroups = {
get: get38,
diff --git a/packages/contracts/generated/api/console/workspaces/types.gen.ts b/packages/contracts/generated/api/console/workspaces/types.gen.ts
index 792a2f9d2a3..8ea605024ba 100644
--- a/packages/contracts/generated/api/console/workspaces/types.gen.ts
+++ b/packages/contracts/generated/api/console/workspaces/types.gen.ts
@@ -676,6 +676,31 @@ export type NetworkAccessGroupListResponse = {
tenant_id: string
}
+export type NetworkAccessForbiddenError = ErrorResponse & {
+ code: 'network_access_forbidden'
+ status: 403
+}
+
+export type NetworkAccessNotEntitledError = ErrorResponse & {
+ code: 'network_access_not_entitled'
+ status: 403
+}
+
+export type NetworkAccessRoleDeniedError = ErrorResponse & {
+ code: 'network_access_role_denied'
+ status: 403
+}
+
+export type BillingOperationFailedError = ErrorResponse & {
+ code: 'billing_operation_failed'
+ status: 502
+}
+
+export type BillingUnavailableError = ErrorResponse & {
+ code: 'billing_unavailable'
+ status: 503
+}
+
export type NetworkAccessGroupCreatePayload = {
allowed_cidrs: Array<string>
description?: string
@@ -686,6 +711,21 @@ export type NetworkAccessGroupMutationResponse = {
group: NetworkAccessGroupResponse
}
+export type NetworkAccessInvalidInputError = ErrorResponse & {
+ code: 'network_access_invalid_input'
+ status: 400
+}
+
+export type PaidPlanRequiredError = ErrorResponse & {
+ code: 'paid_plan_required'
+ status: 403
+}
+
+export type NetworkAccessGroupNameConflictError = ErrorResponse & {
+ code: 'network_access_group_name_conflict'
+ status: 409
+}
+
export type NetworkAccessGroupCurrentIpResponse = {
client_ip: string
}
@@ -694,6 +734,21 @@ export type NetworkAccessGroupDeleteResponse = {
deleted: boolean
}
+export type NetworkAccessGroupNotFoundError = ErrorResponse & {
+ code: 'network_access_group_not_found'
+ status: 404
+}
+
+export type NetworkAccessGroupBoundError = ErrorResponse & {
+ code: 'network_access_group_bound'
+ status: 409
+}
+
+export type NetworkAccessVersionConflictError = ErrorResponse & {
+ code: 'network_access_version_conflict'
+ status: 409
+}
+
export type NetworkAccessGroupUpdatePayload = {
allowed_cidrs: Array<string>
description?: string
@@ -6453,6 +6508,13 @@ export type GetWorkspacesCurrentNetworkAccessGroupsData = {
}
export type GetWorkspacesCurrentNetworkAccessGroupsErrors = {
+ 403:
+ | NetworkAccessForbiddenError
+ | NetworkAccessNotEntitledError
+ | NetworkAccessRoleDeniedError
+ | ErrorResponse
+ 502: BillingOperationFailedError | ErrorResponse
+ 503: BillingUnavailableError | ErrorResponse
default: ErrorResponse
}
@@ -6474,6 +6536,16 @@ export type PostWorkspacesCurrentNetworkAccessGroupsData = {
}
export type PostWorkspacesCurrentNetworkAccessGroupsErrors = {
+ 400: NetworkAccessInvalidInputError | ErrorResponse
+ 403:
+ | NetworkAccessForbiddenError
+ | NetworkAccessNotEntitledError
+ | NetworkAccessRoleDeniedError
+ | PaidPlanRequiredError
+ | ErrorResponse
+ 409: NetworkAccessGroupNameConflictError | ErrorResponse
+ 502: BillingOperationFailedError | ErrorResponse
+ 503: BillingUnavailableError | ErrorResponse
default: ErrorResponse
}
@@ -6495,7 +6567,7 @@ export type GetWorkspacesCurrentNetworkAccessGroupsCurrentIpData = {
}
export type GetWorkspacesCurrentNetworkAccessGroupsCurrentIpErrors = {
- 403: ErrorResponse
+ 403: NetworkAccessRoleDeniedError | ErrorResponse
503: ErrorResponse
default: ErrorResponse
}
@@ -6522,6 +6594,16 @@ export type DeleteWorkspacesCurrentNetworkAccessGroupsByGroupIdData = {
}
export type DeleteWorkspacesCurrentNetworkAccessGroupsByGroupIdErrors = {
+ 403:
+ | NetworkAccessForbiddenError
+ | NetworkAccessNotEntitledError
+ | NetworkAccessRoleDeniedError
+ | PaidPlanRequiredError
+ | ErrorResponse
+ 404: NetworkAccessGroupNotFoundError | ErrorResponse
+ 409: NetworkAccessGroupBoundError | NetworkAccessVersionConflictError | ErrorResponse
+ 502: BillingOperationFailedError | ErrorResponse
+ 503: BillingUnavailableError | ErrorResponse
default: ErrorResponse
}
@@ -6545,6 +6627,14 @@ export type GetWorkspacesCurrentNetworkAccessGroupsByGroupIdData = {
}
export type GetWorkspacesCurrentNetworkAccessGroupsByGroupIdErrors = {
+ 403:
+ | NetworkAccessForbiddenError
+ | NetworkAccessNotEntitledError
+ | NetworkAccessRoleDeniedError
+ | ErrorResponse
+ 404: NetworkAccessGroupNotFoundError | ErrorResponse
+ 502: BillingOperationFailedError | ErrorResponse
+ 503: BillingUnavailableError | ErrorResponse
default: ErrorResponse
}
@@ -6568,6 +6658,17 @@ export type PutWorkspacesCurrentNetworkAccessGroupsByGroupIdData = {
}
export type PutWorkspacesCurrentNetworkAccessGroupsByGroupIdErrors = {
+ 400: NetworkAccessInvalidInputError | ErrorResponse
+ 403:
+ | NetworkAccessForbiddenError
+ | NetworkAccessNotEntitledError
+ | NetworkAccessRoleDeniedError
+ | PaidPlanRequiredError
+ | ErrorResponse
+ 404: NetworkAccessGroupNotFoundError | ErrorResponse
+ 409: NetworkAccessGroupNameConflictError | NetworkAccessVersionConflictError | ErrorResponse
+ 502: BillingOperationFailedError | ErrorResponse
+ 503: BillingUnavailableError | ErrorResponse
default: ErrorResponse
}
@@ -6591,6 +6692,14 @@ export type GetWorkspacesCurrentNetworkAccessGroupsByGroupIdCheckCurrentIpData =
}
export type GetWorkspacesCurrentNetworkAccessGroupsByGroupIdCheckCurrentIpErrors = {
+ 403:
+ | NetworkAccessForbiddenError
+ | NetworkAccessNotEntitledError
+ | NetworkAccessRoleDeniedError
+ | ErrorResponse
+ 404: NetworkAccessGroupNotFoundError | ErrorResponse
+ 502: BillingOperationFailedError | ErrorResponse
+ 503: BillingUnavailableError | ErrorResponse
default: ErrorResponse
}
diff --git a/packages/contracts/generated/api/console/workspaces/zod.gen.ts b/packages/contracts/generated/api/console/workspaces/zod.gen.ts
index 627fb4f0034..19385f3b103 100644
--- a/packages/contracts/generated/api/console/workspaces/zod.gen.ts
+++ b/packages/contracts/generated/api/console/workspaces/zod.gen.ts
@@ -544,6 +544,66 @@ export const zParserPreferredProviderType = z.object({
preferred_provider_type: z.enum(['custom', 'system']),
})
+/**
+ * NetworkAccessForbiddenError
+ *
+ * Network access groups are not available for this workspace.
+ */
+export const zNetworkAccessForbiddenError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_forbidden'),
+ status: z.literal(403),
+ }),
+)
+
+/**
+ * NetworkAccessNotEntitledError
+ *
+ * Network access groups are not available for this workspace.
+ */
+export const zNetworkAccessNotEntitledError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_not_entitled'),
+ status: z.literal(403),
+ }),
+)
+
+/**
+ * NetworkAccessRoleDeniedError
+ *
+ * Your workspace role does not allow this network access operation.
+ */
+export const zNetworkAccessRoleDeniedError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_role_denied'),
+ status: z.literal(403),
+ }),
+)
+
+/**
+ * BillingOperationFailedError
+ *
+ * We couldn't complete this request. Please try again. If the problem persists, contact support.
+ */
+export const zBillingOperationFailedError = zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_operation_failed'),
+ status: z.literal(502),
+ }),
+)
+
+/**
+ * BillingUnavailableError
+ *
+ * This operation is temporarily unavailable. Please try again later.
+ */
+export const zBillingUnavailableError = zErrorResponse.and(
+ z.object({
+ code: z.literal('billing_unavailable'),
+ status: z.literal(503),
+ }),
+)
+
/**
* NetworkAccessGroupCreatePayload
*/
@@ -553,6 +613,42 @@ export const zNetworkAccessGroupCreatePayload = z.object({
name: z.string().min(1).max(100),
})
+/**
+ * NetworkAccessInvalidInputError
+ *
+ * Invalid network access group request.
+ */
+export const zNetworkAccessInvalidInputError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_invalid_input'),
+ status: z.literal(400),
+ }),
+)
+
+/**
+ * PaidPlanRequiredError
+ *
+ * This feature requires a paid plan.
+ */
+export const zPaidPlanRequiredError = zErrorResponse.and(
+ z.object({
+ code: z.literal('paid_plan_required'),
+ status: z.literal(403),
+ }),
+)
+
+/**
+ * NetworkAccessGroupNameConflictError
+ *
+ * An IP policy with this name already exists.
+ */
+export const zNetworkAccessGroupNameConflictError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_group_name_conflict'),
+ status: z.literal(409),
+ }),
+)
+
/**
* NetworkAccessGroupCurrentIPResponse
*/
@@ -567,6 +663,42 @@ export const zNetworkAccessGroupDeleteResponse = z.object({
deleted: z.boolean(),
})
+/**
+ * NetworkAccessGroupNotFoundError
+ *
+ * Network access group was not found.
+ */
+export const zNetworkAccessGroupNotFoundError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_group_not_found'),
+ status: z.literal(404),
+ }),
+)
+
+/**
+ * NetworkAccessGroupBoundError
+ *
+ * This IP policy is still used by one or more apps.
+ */
+export const zNetworkAccessGroupBoundError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_group_bound'),
+ status: z.literal(409),
+ }),
+)
+
+/**
+ * NetworkAccessVersionConflictError
+ *
+ * The network access resource changed. Refresh it and try again.
+ */
+export const zNetworkAccessVersionConflictError = zErrorResponse.and(
+ z.object({
+ code: z.literal('network_access_version_conflict'),
+ status: z.literal(409),
+ }),
+)
+
/**
* NetworkAccessGroupUpdatePayload
*/
diff --git a/web/app/components/header/account-setting/ip-policies-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/ip-policies-page/__tests__/index.spec.tsx
index 5550fb03a10..fb358fda3a7 100644
--- a/web/app/components/header/account-setting/ip-policies-page/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/ip-policies-page/__tests__/index.spec.tsx
@@ -230,7 +230,10 @@ describe('IpPoliciesPage', () => {
return Response.json({ tenant_id: 'workspace-1', entitled: true, groups: [remote] })
putBodies.push(JSON.parse(await request.clone().text()))
if (requests.filter((item) => item.method === 'PUT').length === 1)
- return Response.json({ code: 'network_access_conflict' }, { status: 409 })
+ return Response.json(
+ { code: 'network_access_version_conflict', message: 'Changed', status: 409 },
+ { status: 409 },
+ )
return Response.json({ group: remote, entitled: true })
})
renderWithConsoleQuery(
@@ -280,7 +283,10 @@ describe('IpPoliciesPage', () => {
if (request.method === 'PUT') {
saves += 1
return saves === 1
- ? Response.json({ code: 'network_access_conflict' }, { status: 409 })
+ ? Response.json(
+ { code: 'network_access_version_conflict', message: 'Changed', status: 409 },
+ { status: 409 },
+ )
: Response.json({ group, entitled: true })
}
return Response.json({
@@ -391,7 +397,10 @@ describe('IpPoliciesPage', () => {
? Response.json({ message: 'Unavailable' }, { status: 500 })
: Response.json({ tenant_id: 'workspace-1', entitled: true, groups: [remote] })
}
- return Response.json({ code: 'network_access_conflict' }, { status: 409 })
+ return Response.json(
+ { code: 'network_access_version_conflict', message: 'Changed', status: 409 },
+ { status: 409 },
+ )
})
renderWithConsoleQuery(
<NuqsTestingAdapter>
@@ -427,7 +436,10 @@ describe('IpPoliciesPage', () => {
if (request.url.endsWith('/current-ip')) return Response.json({ client_ip: '203.0.113.42' })
return request.method === 'GET'
? reload
- : Response.json({ code: 'network_access_conflict' }, { status: 409 })
+ : Response.json(
+ { code: 'network_access_version_conflict', message: 'Changed', status: 409 },
+ { status: 409 },
+ )
})
renderWithConsoleQuery(
<NuqsTestingAdapter>
diff --git a/web/app/components/header/account-setting/ip-policies-page/index.tsx b/web/app/components/header/account-setting/ip-policies-page/index.tsx
index aac57642dbb..c3a6656ca4d 100644
--- a/web/app/components/header/account-setting/ip-policies-page/index.tsx
+++ b/web/app/components/header/account-setting/ip-policies-page/index.tsx
@@ -11,6 +11,7 @@ import {
ScrollAreaThumb,
ScrollAreaViewport,
} from '@langgenius/dify-ui/scroll-area'
+import { isDefinedError } from '@orpc/client'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import Image from 'next/image'
@@ -24,7 +25,6 @@ import {
} from '@/app/components/billing/pricing/query-params'
import { currentWorkspaceAtom } from '@/context/workspace-state'
import { getIpPolicyFailReason, trackNetworkAccessEvent } from '@/features/network-access/analytics'
-import { getNetworkAccessErrorStatus } from '@/features/network-access/errors'
import {
canManageNetworkAccessPoliciesAtom,
canReadNetworkAccessAtom,
@@ -311,11 +311,11 @@ export default function IpPoliciesPage() {
entry_count: payload.allowed_cidrs.length,
validation_error_types: [...dialogState.analytics.validationErrors],
}
- const trackFailure = async (error: unknown) => {
+ const trackFailure = (error: unknown) => {
trackNetworkAccessEvent('ip_policy_save', {
...analytics,
result: 'failed',
- fail_reason: await getIpPolicyFailReason(error),
+ fail_reason: getIpPolicyFailReason(error),
})
}
if (selectedGroup) {
@@ -335,7 +335,11 @@ export default function IpPoliciesPage() {
if (dialogSessionRef.current === session) openDialog(null)
},
onError: (error) => {
- if (getNetworkAccessErrorStatus(error) !== 409) return
+ if (
+ !isDefinedError(error) ||
+ error.code !== 'network_access_version_conflict'
+ )
+ return
void refreshGroupsAfterConflict(selectedGroup.id, session)
},
},
diff --git a/web/features/network-access/__tests__/analytics.spec.ts b/web/features/network-access/__tests__/analytics.spec.ts
index 41f5e803310..dbf40b04a1d 100644
--- a/web/features/network-access/__tests__/analytics.spec.ts
+++ b/web/features/network-access/__tests__/analytics.spec.ts
@@ -1,3 +1,4 @@
+import { ORPCError } from '@orpc/client'
import { trackEvent } from '@/app/components/base/amplitude'
import {
getAccessControlFailReason,
@@ -40,38 +41,47 @@ it('only forwards allowlisted properties and excludes application context from S
})
it.each([
- [403, 'This feature requires a paid plan.', 'plan', 'permission'],
- [403, 'Network access groups are not available for this workspace.', 'plan', 'permission'],
- [
- 403,
- 'Your workspace role does not allow this network access operation.',
- 'permission',
- 'permission',
- ],
- [401, 'Unauthorized', 'permission', 'permission'],
- [503, 'Unavailable', 'network', 'network'],
- [409, 'This workspace has reached the network access group limit.', 'other', 'limit_exceeded'],
- [409, 'The network access resource changed. Refresh it and try again.', 'other', 'other'],
- [409, 'A network access group with this name already exists.', 'other', 'other'],
- [400, 'Invalid request', 'other', 'other'],
-])(
- 'classifies HTTP %i failures without forwarding error text',
- async (status, message, accessReason, policyReason) => {
- const error = Response.json({ message }, { status })
- expect(await getAccessControlFailReason(error)).toBe(accessReason)
- expect(await getIpPolicyFailReason(error)).toBe(policyReason)
- expect(error.bodyUsed).toBe(false)
- },
-)
+ ['paid_plan_required', 403, 'plan', 'permission'],
+ ['network_access_not_entitled', 403, 'plan', 'permission'],
+ ['network_access_forbidden', 403, 'permission', 'permission'],
+ ['network_access_role_denied', 403, 'permission', 'permission'],
+ ['billing_unavailable', 503, 'network', 'network'],
+ ['billing_operation_failed', 502, 'network', 'network'],
+ ['network_access_group_name_conflict', 409, 'other', 'name_conflict'],
+ ['network_access_version_conflict', 409, 'other', 'other'],
+ ['network_access_invalid_input', 400, 'other', 'other'],
+])('classifies the %s error code', (code, status, accessReason, policyReason) => {
+ const error = new ORPCError(code, { defined: true, status, message: 'Backend text' })
+ expect(getAccessControlFailReason(error)).toBe(accessReason)
+ expect(getIpPolicyFailReason(error)).toBe(policyReason)
+})
+
+it('ignores a plan or conflict code the contract does not define for the call', () => {
+ const plan = new ORPCError('paid_plan_required', { status: 403 })
+ const conflict = new ORPCError('network_access_group_name_conflict', { status: 409 })
+ expect(getAccessControlFailReason(plan)).toBe('permission')
+ expect(getIpPolicyFailReason(conflict)).toBe('other')
+})
+
+it.each([
+ [401, 'permission'],
+ [403, 'permission'],
+ [503, 'network'],
+ [400, 'other'],
+])('falls back to the HTTP %i status for undocumented errors', (status, reason) => {
+ const error = Response.json({ message: 'This feature requires a paid plan.' }, { status })
+ expect(getAccessControlFailReason(error)).toBe(reason)
+ expect(getIpPolicyFailReason(error)).toBe(reason)
+})
-it('recognizes fetch failures without labelling arbitrary exceptions as network errors', async () => {
- expect(await getAccessControlFailReason(new TypeError('Failed to fetch'))).toBe('network')
- expect(await getIpPolicyFailReason(new Error('Unexpected failure'))).toBe('other')
+it('recognizes fetch failures without labelling arbitrary exceptions as network errors', () => {
+ expect(getAccessControlFailReason(new TypeError('Failed to fetch'))).toBe('network')
+ expect(getIpPolicyFailReason(new Error('Unexpected failure'))).toBe('other')
})
it('still classifies the status when an error response body has already been consumed', async () => {
const response = Response.json({ message: 'Unavailable' }, { status: 503 })
await response.json()
- expect(await getAccessControlFailReason(response)).toBe('network')
- expect(await getIpPolicyFailReason(response)).toBe('network')
+ expect(getAccessControlFailReason(response)).toBe('network')
+ expect(getIpPolicyFailReason(response)).toBe('network')
})
diff --git a/web/features/network-access/analytics.ts b/web/features/network-access/analytics.ts
index e5d59c065f5..260d4c0f95c 100644
--- a/web/features/network-access/analytics.ts
+++ b/web/features/network-access/analytics.ts
@@ -2,6 +2,12 @@ import type {
AppMode,
AppNetworkAccessGroupResponse,
} from '@dify/contracts/api/console/apps/types.gen'
+import type {
+ NetworkAccessGroupNameConflictError,
+ NetworkAccessNotEntitledError,
+ PaidPlanRequiredError,
+} from '@dify/contracts/api/console/workspaces/types.gen'
+import { isDefinedError, ORPCError } from '@orpc/client'
import { trackEvent } from '@/app/components/base/amplitude'
type NetworkAccessPoint = AppNetworkAccessGroupResponse['available_access_points'][number]
@@ -69,7 +75,7 @@ type IpPolicySaveProperties = IpPolicyFormContext & {
}
type AccessControlFailReason = 'network' | 'permission' | 'plan' | 'other'
-type IpPolicyFailReason = 'limit_exceeded' | 'network' | 'permission' | 'other'
+type IpPolicyFailReason = 'name_conflict' | 'network' | 'permission' | 'other'
type SaveResult<Reason> = { result: 'success' } | { result: 'failed'; fail_reason: Reason }
type NetworkAccessEvents = {
access_control_entry_click: AccessControlAnalyticsContext & {
@@ -147,32 +153,15 @@ export function getProtectedAccessPoints(points: readonly NetworkAccessPoint[])
return points.map((point) => ACCESS_POINTS[point])
}
-async function readFailure(
- error: unknown,
-): Promise<{ status?: number; message?: string; code?: string }> {
- if (typeof error !== 'object' || error === null) return {}
- const response =
- error instanceof Response
- ? error
- : 'response' in error && error.response instanceof Response
- ? error.response
- : undefined
- if (response) {
- try {
- const data: unknown = await response.clone().json()
- return { ...(await readFailure(data)), status: response.status }
- } catch {
- return { status: response.status }
- }
- }
- return {
- status: 'status' in error && typeof error.status === 'number' ? error.status : undefined,
- message: 'message' in error && typeof error.message === 'string' ? error.message : undefined,
- code: 'code' in error && typeof error.code === 'string' ? error.code : undefined,
- }
+function readStatus(error: unknown) {
+ if (typeof error !== 'object' || error === null) return undefined
+ if (error instanceof Response) return error.status
+ if ('response' in error && error.response instanceof Response) return error.response.status
+ return 'status' in error && typeof error.status === 'number' ? error.status : undefined
}
-function isNetworkFailure(error: unknown, status?: number) {
+function isNetworkFailure(error: unknown) {
+ const status = readStatus(error)
return (
(status !== undefined && [408, 502, 503, 504].includes(status)) ||
(status === undefined &&
@@ -181,26 +170,31 @@ function isNetworkFailure(error: unknown, status?: number) {
)
}
-export async function getAccessControlFailReason(error: unknown): Promise<AccessControlFailReason> {
- const { status, message } = await readFailure(error)
- if (
- status === 403 &&
- (message === 'This feature requires a paid plan.' ||
- message === 'Network access groups are not available for this workspace.')
+type DefinedFailureCode = (
+ | NetworkAccessGroupNameConflictError
+ | NetworkAccessNotEntitledError
+ | PaidPlanRequiredError
+)['code']
+
+function hasDefinedCode(error: unknown, ...codes: DefinedFailureCode[]) {
+ return (
+ error instanceof ORPCError && isDefinedError(error) && codes.some((code) => code === error.code)
)
- return 'plan'
- if (status === 401 || status === 403) return 'permission'
- return isNetworkFailure(error, status) ? 'network' : 'other'
}
-export async function getIpPolicyFailReason(error: unknown): Promise<IpPolicyFailReason> {
- const { status, message, code } = await readFailure(error)
- if (
- status === 409 &&
- (code === 'NETWORK_ACCESS_GROUP_LIMIT' ||
- message === 'This workspace has reached the network access group limit.')
- )
- return 'limit_exceeded'
- if (status === 401 || status === 403) return 'permission'
- return isNetworkFailure(error, status) ? 'network' : 'other'
+function isPermissionFailure(error: unknown) {
+ const status = readStatus(error)
+ return status === 401 || status === 403
+}
+
+export function getAccessControlFailReason(error: unknown): AccessControlFailReason {
+ if (hasDefinedCode(error, 'paid_plan_required', 'network_access_not_entitled')) return 'plan'
+ if (isPermissionFailure(error)) return 'permission'
+ return isNetworkFailure(error) ? 'network' : 'other'
+}
+
+export function getIpPolicyFailReason(error: unknown): IpPolicyFailReason {
+ if (hasDefinedCode(error, 'network_access_group_name_conflict')) return 'name_conflict'
+ if (isPermissionFailure(error)) return 'permission'
+ return isNetworkFailure(error) ? 'network' : 'other'
}
diff --git a/web/features/network-access/app-binding/__tests__/index.spec.tsx b/web/features/network-access/app-binding/__tests__/index.spec.tsx
index 510832a6470..41ce6602734 100644
--- a/web/features/network-access/app-binding/__tests__/index.spec.tsx
+++ b/web/features/network-access/app-binding/__tests__/index.spec.tsx
@@ -1410,17 +1410,17 @@ const lockoutWarning = "Your IP (203.0.113.42) isn't in this policy. You may los
describe('trusted IP checks before saving', () => {
it.each([
- [403, 'This feature requires a paid plan.', 'plan'],
- [403, 'Forbidden', 'permission'],
- [503, 'Unavailable', 'network'],
- [409, 'The network access resource changed. Refresh it and try again.', 'other'],
+ [403, 'paid_plan_required', 'plan'],
+ [403, 'forbidden', 'permission'],
+ [503, 'billing_unavailable', 'network'],
+ [409, 'network_access_version_conflict', 'other'],
] as const)(
- 'reports one failed save for the submitted draft after HTTP %s',
- async (status, message, failReason) => {
+ 'reports one failed save for the submitted draft after HTTP %s %s',
+ async (status, code, failReason) => {
const user = userEvent.setup()
const server = setupBindingServer()
server.check.allowed = true
- server.put = async () => Response.json({ message }, { status })
+ server.put = async () => Response.json({ code, message: 'Backend text', status }, { status })
renderEntry({ plan: 'professional', groups: server.groups })
await openSelectedConfig(user)
await waitFor(() => expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled())
@@ -1751,7 +1751,11 @@ describe('immediate pause and resume', () => {
).toEqual(['turn_off_attempted', 'turn_off_confirmed'])
if (status === 409)
server.binding = createBinding({ version: 3, access_points: ['webapp', 'mcp'] })
- await act(async () => finish(Response.json({ message: 'Unable to pause' }, { status })))
+ const body =
+ status === 409
+ ? { code: 'network_access_version_conflict', message: 'Unable to pause', status }
+ : { message: 'Unable to pause' }
+ await act(async () => finish(Response.json(body, { status })))
await waitFor(() => expect(toggle).not.toHaveAttribute('aria-disabled', 'true'))
expect(toggle).toBeChecked()
expect(within(getChip()).getByText('2 of 3')).toBeInTheDocument()
diff --git a/web/features/network-access/app-binding/__tests__/network-access.spec.ts b/web/features/network-access/app-binding/__tests__/network-access.spec.ts
index d20febeba7a..5295b75fb66 100644
--- a/web/features/network-access/app-binding/__tests__/network-access.spec.ts
+++ b/web/features/network-access/app-binding/__tests__/network-access.spec.ts
@@ -1,5 +1,4 @@
import { ACCESS_POINT_ORDER } from '@/app/components/app/deploy/utils/access-point'
-import { getNetworkAccessErrorStatus } from '@/features/network-access/errors'
import {
accessPointsFromScopes,
draftFromBinding,
@@ -17,11 +16,6 @@ describe('network access mappers', () => {
expect(toUiAccessPoint('service_api')).toBe('serviceApi')
})
- it('reads HTTP status from Response and nested response objects', () => {
- expect(getNetworkAccessErrorStatus(new Response(null, { status: 409 }))).toBe(409)
- expect(getNetworkAccessErrorStatus({ response: { status: 409 } })).toBe(409)
- })
-
it('builds scopes from selected API access points', () => {
expect(scopesFromAccessPoints(['webapp', 'mcp'])).toEqual({
webApp: true,
diff --git a/web/features/network-access/app-binding/index.tsx b/web/features/network-access/app-binding/index.tsx
index 69166f251b7..a418fdd8d2e 100644
--- a/web/features/network-access/app-binding/index.tsx
+++ b/web/features/network-access/app-binding/index.tsx
@@ -17,6 +17,7 @@ import {
} from '@langgenius/dify-ui/alert-dialog'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
+import { isDefinedError } from '@orpc/client'
import { skipToken, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { useQueryState } from 'nuqs'
@@ -36,7 +37,6 @@ import {
getProtectedAccessPoints,
trackNetworkAccessEvent,
} from '@/features/network-access/analytics'
-import { getNetworkAccessErrorStatus } from '@/features/network-access/errors'
import {
canManageNetworkAccessPoliciesAtom,
canReadNetworkAccessAtom,
@@ -179,14 +179,7 @@ function AccessControlSession({
)
const saveCheck = useMutation(checkCurrentIp.mutationOptions({ context: { silent: true } }))
- const bindingErrorStatus = getNetworkAccessErrorStatus(bindingQuery.error)
- const hideForUnsupportedApp =
- canFetchNetworkAccess &&
- Boolean(appId) &&
- (bindingErrorStatus === 400 || bindingErrorStatus === 403 || bindingErrorStatus === 404)
-
if (!canFetchNetworkAccess) return null
- if (hideForUnsupportedApp) return null
if (groupsQuery.isPending || bindingQuery.isPending) return null
if (groupsQuery.isError || bindingQuery.isError || !groupsQuery.data || !bindingQuery.data)
return null
@@ -365,7 +358,7 @@ function AccessControlSession({
onSuccess?.()
},
onError: (error) => {
- if (getNetworkAccessErrorStatus(error) !== 409) return
+ if (!isDefinedError(error) || error.code !== 'network_access_version_conflict') return
void queryClient.invalidateQueries({
queryKey: consoleQuery.apps.byAppId.networkAccessGroup.get.queryKey({
input: { params: { app_id: appId } },
@@ -382,12 +375,12 @@ function AccessControlSession({
if (analytics)
trackNetworkAccessEvent('access_control_save', { ...analytics, result: 'success' })
},
- async (error: unknown) => {
+ (error: unknown) => {
if (analytics)
trackNetworkAccessEvent('access_control_save', {
...analytics,
result: 'failed',
- fail_reason: await getAccessControlFailReason(error),
+ fail_reason: getAccessControlFailReason(error),
})
},
)
@@ -663,11 +656,11 @@ function AccessControlSession({
result: 'success',
policy_id: data.group.id,
}),
- async (error: unknown) =>
+ (error: unknown) =>
trackNetworkAccessEvent('ip_policy_save', {
...analytics,
result: 'failed',
- fail_reason: await getIpPolicyFailReason(error),
+ fail_reason: getIpPolicyFailReason(error),
}),
)
}}
diff --git a/web/features/network-access/errors.ts b/web/features/network-access/errors.ts
deleted file mode 100644
index 912d7f294cd..00000000000
--- a/web/features/network-access/errors.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-export function getNetworkAccessErrorStatus(error: unknown): number | undefined {
- if (error instanceof Response) return error.status
- if (typeof error === 'object' && error !== null) {
- if ('status' in error && typeof error.status === 'number') return error.status
- if (
- 'response' in error &&
- typeof error.response === 'object' &&
- error.response !== null &&
- 'status' in error.response &&
- typeof error.response.status === 'number'
- )
- return error.response.status
- }
-}