Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
feat(api): generate typed billing and saas client from OpenAPI snapshot (#45126)
yyha54d9c1873db
diff --git a/.github/workflows/style.yml b/.github/workflows/style.ymlindex 381aa9f7fef..53a9811681e 100644--- a/.github/workflows/style.yml+++ b/.github/workflows/style.yml@@ -81,6 +81,10 @@ jobs:if: inputs.run-python-stylerun: uv run --project api --dev python api/dev/lint_response_contracts.py --fail-on-mismatch+ - name: Check Billing Client Is Generated From Snapshot+ if: inputs.run-python-style+ run: uv run --project api --dev python api/dev/generate_billing_client.py --check+- name: Run No New Getattr Guardif: inputs.run-python-stylerun: uv run --project api python scripts/check_no_new_getattr.py --base-rev "${{ inputs.base-rev }}"diff --git a/api/AGENTS.md b/api/AGENTS.mdindex e2a0b77fde7..de2d26613e3 100644--- a/api/AGENTS.md+++ b/api/AGENTS.md@@ -37,6 +37,11 @@ guard rejects new `Base` subclasses. Existing `Base` subclasses may be editedor migrated without adding more legacy inheritance. `make lint` checks localchanges, and CI checks the PR against its target revision.+## Billing And SaaS Calls++- Call billing and saas only through the generated functions in `services/billing_client`; do not hand-write paths or response types.+- To call a new endpoint, add it to `ALLOWED_OPERATIONS` in `dev/generate_billing_client.py` and rerun that script against a dify-saas checkout. Never edit the generated modules or snapshots by hand.+## Typing Best Practises- Treat nullable types (`T | None`) strictly as union types; document the semantic meaning for each branch.diff --git a/api/dev/generate_billing_client.py b/api/dev/generate_billing_client.pynew file mode 100644index 00000000000..6017cfe8835--- /dev/null+++ b/api/dev/generate_billing_client.py@@ -0,0 +1,498 @@+"""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.++ 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+ uv run --project api --dev python api/dev/generate_billing_client.py --check # CI drift check++The dify-saas checkout defaults to `../dify-saas` next to the dify repository; override it with+`DIFY_SAAS_REPO`.++Kratos serializes with protojson `EmitUnpopulated: true`, which the snapshot step records as presence:+- Scalars, enums, lists, and maps are required and non-null.+- Message fields are required but nullable, since unset messages are emitted as null. A message field+ the upstream schema lists in `required` (`google.api.field_behavior = REQUIRED`) is non-null.+- Proto3 `optional` fields (annotated `nullable` in dify-saas) are synthetic oneofs, which protojson+ omits when unset, so they are optional and nullable.+"""++from __future__ import annotations++import argparse+import difflib+import json+import keyword+import logging+import os+import re+import subprocess+import sys+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Literal++import yaml+from pydantic import BaseModel++API_ROOT = Path(__file__).resolve().parents[1]+REPO_ROOT = API_ROOT.parent+CLIENT_DIR = API_ROOT / "services" / "billing_client"+GENERATOR = "api/dev/generate_billing_client.py"++logger = logging.getLogger("generate_billing_client")++type Service = Literal["billing", "saas"]+type UpstreamName = Literal["BILLING", "BILLING_QUOTA", "SAAS"]+type JsonObject = dict[str, Any]++SERVICES: tuple[Service, ...] = ("billing", "saas")+SCHEMA_PREFIXES: dict[Service, str] = {"billing": "dify.saas.api.billing.", "saas": "dify.saas.api.saas."}+# BILLING_API_URL already ends with the API version.+PATH_VERSION_PREFIX = "/v1"+SNAPSHOT_COMMIT_KEY = "x-dify-saas-commit"+HTTP_METHODS = ("get", "post", "put", "delete", "patch")+BASE_MODEL_ATTRIBUTES = frozenset(dir(BaseModel))+++@dataclass(frozen=True)+class AllowedOperation:+ method: str+ path: str+ upstream: UpstreamName+++# Endpoints dify API calls today. Add an entry here, then rerun this script, to call a new one.+ALLOWED_OPERATIONS: dict[Service, tuple[AllowedOperation, ...]] = {+ "billing": (+ AllowedOperation("GET", "/v1/subscription/info", "BILLING"),+ AllowedOperation("GET", "/v1/subscription/vector-space", "BILLING"),+ AllowedOperation("GET", "/v1/subscription/knowledge-rate-limit", "BILLING"),+ AllowedOperation("GET", "/v1/subscription/payment-link", "BILLING"),+ AllowedOperation("POST", "/v1/subscription/plan/batch", "BILLING"),+ AllowedOperation("GET", "/v1/subscription/cleanup/whitelist", "BILLING"),+ AllowedOperation("GET", "/v1/model-provider/payment-link", "BILLING"),+ AllowedOperation("GET", "/v1/invoices", "BILLING"),+ AllowedOperation("GET", "/v1/education/verify", "BILLING"),+ AllowedOperation("GET", "/v1/education/status", "BILLING"),+ AllowedOperation("POST", "/v1/education", "BILLING"),+ AllowedOperation("GET", "/v1/education/autocomplete", "BILLING"),+ AllowedOperation("POST", "/v1/compliance/download", "BILLING"),+ AllowedOperation("GET", "/v1/quota/info", "BILLING_QUOTA"),+ AllowedOperation("POST", "/v1/quota/reserve", "BILLING_QUOTA"),+ AllowedOperation("POST", "/v1/quota/commit", "BILLING_QUOTA"),+ AllowedOperation("POST", "/v1/quota/release", "BILLING_QUOTA"),+ AllowedOperation("GET", "/v1/quota/balance", "BILLING_QUOTA"),+ AllowedOperation("POST", "/v1/quota/consume-capped", "BILLING_QUOTA"),+ ),+ "saas": (+ AllowedOperation("DELETE", "/v1/account", "SAAS"),+ AllowedOperation("GET", "/v1/account/in-freeze", "SAAS"),+ AllowedOperation("POST", "/v1/account/delete-feedback", "SAAS"),+ AllowedOperation("GET", "/v1/notifications/active", "SAAS"),+ AllowedOperation("POST", "/v1/notifications/{notificationId}/dismiss", "SAAS"),+ ),+}+++class GenerationError(Exception):+ pass+++def snapshot_path(service: Service) -> Path:+ return CLIENT_DIR / f"{service}.openapi.json"+++def module_path(service: Service) -> Path:+ return CLIENT_DIR / f"{service}.py"+++# --- snapshot -------------------------------------------------------------------------------------+++def dify_saas_root() -> Path:+ override = os.environ.get("DIFY_SAAS_REPO")+ return Path(override).resolve() if override else (REPO_ROOT.parent / "dify-saas").resolve()+++def _git(root: Path, *args: str) -> str:+ return subprocess.run(["git", "-C", str(root), *args], check=True, capture_output=True, text=True).stdout.strip()+++def dify_saas_commit(root: Path) -> str:+ if _git(root, "status", "--porcelain"):+ logger.warning("dify-saas at %s has uncommitted changes; the snapshot will not match its commit", root)+ branch = _git(root, "rev-parse", "--abbrev-ref", "HEAD")+ if branch != "main":+ logger.warning("dify-saas is on %s, not main", branch)+ try:+ behind = int(_git(root, "rev-list", "--count", "HEAD..origin/main"))+ except subprocess.CalledProcessError:+ logger.warning("dify-saas has no origin/main to compare against")+ else:+ if behind:+ logger.warning("dify-saas is %d commits behind origin/main (as of its last fetch)", behind)+ return _git(root, "rev-parse", "HEAD")+++def _rewrite_refs(node: Any, prefix: str) -> Any:+ if isinstance(node, dict):+ return {+ key: (_strip_ref(value, prefix) if key == "$ref" else _rewrite_refs(value, prefix))+ for key, value in node.items()+ }+ if isinstance(node, list):+ return [_rewrite_refs(item, prefix) for item in node]+ return node+++def _strip_ref(ref: str, prefix: str) -> str:+ head, _, name = ref.rpartition("/")+ return f"{head}/{name.removeprefix(prefix)}"+++def _ref_names(node: Any) -> set[str]:+ if isinstance(node, dict):+ names = {node["$ref"].rpartition("/")[2]} if "$ref" in node else set()+ for value in node.values():+ names |= _ref_names(value)+ return names+ if isinstance(node, list):+ names: set[str] = set()+ for item in node:+ names |= _ref_names(item)+ return names+ return set()+++def _annotate_presence(schema: JsonObject) -> JsonObject:+ properties: dict[str, JsonObject] = schema.get("properties", {})+ always_set = set(schema.get("required", []))+ annotated: dict[str, JsonObject] = {}+ required: list[str] = []+ for name, field in properties.items():+ if "$ref" in field and name not in always_set:+ # OpenAPI 3.0 ignores siblings of $ref, so nullable refs are wrapped in allOf.+ annotated[name] = {"allOf": [{"$ref": field["$ref"]}], "nullable": True}+ else:+ annotated[name] = field+ if "$ref" in field or not field.get("nullable"):+ required.append(name)+ result = {**schema, "properties": annotated}+ if required:+ result["required"] = required+ return result+++def build_snapshot(service: Service, source: JsonObject, commit: str) -> JsonObject:+ prefix = SCHEMA_PREFIXES[service]+ source_paths: dict[str, JsonObject] = source.get("paths", {})+ paths: dict[str, JsonObject] = {}+ for allowed in ALLOWED_OPERATIONS[service]:+ operation = source_paths.get(allowed.path, {}).get(allowed.method.lower())+ if operation is None:+ raise GenerationError(f"{service}: {allowed.method} {allowed.path} is not in the dify-saas spec")+ paths.setdefault(allowed.path, {})[allowed.method.lower()] = _rewrite_refs(operation, prefix)++ source_schemas: dict[str, JsonObject] = {+ name.removeprefix(prefix): _rewrite_refs(schema, prefix)+ for name, schema in source.get("components", {}).get("schemas", {}).items()+ }+ reachable: set[str] = set()+ pending = _ref_names(paths)+ while pending:+ name = pending.pop()+ if name in reachable:+ continue+ if name not in source_schemas:+ raise GenerationError(f"{service}: schema {name} is referenced but not defined")+ reachable.add(name)+ pending |= _ref_names(source_schemas[name])++ return {+ "openapi": source["openapi"],+ "info": source.get("info", {}),+ SNAPSHOT_COMMIT_KEY: commit,+ "paths": paths,+ "components": {"schemas": {name: _annotate_presence(source_schemas[name]) for name in sorted(reachable)}},+ }+++def take_snapshots() -> dict[Service, JsonObject]:+ root = dify_saas_root()+ if not (root / "pkg" / "apis").is_dir():+ raise GenerationError(f"dify-saas checkout not found at {root}; set DIFY_SAAS_REPO")+ commit = dify_saas_commit(root)+ snapshots: dict[Service, JsonObject] = {}+ for service in SERVICES:+ source = yaml.safe_load((root / "pkg" / "apis" / service / "openapi.yaml").read_text())+ snapshots[service] = build_snapshot(service, source, commit)+ return snapshots+++def render_snapshot(snapshot: JsonObject) -> str:+ return json.dumps(snapshot, indent=2, ensure_ascii=False) + "\n"+++def load_snapshot(service: Service) -> JsonObject:+ snapshot: JsonObject = json.loads(snapshot_path(service).read_text())+ operations = {+ (method.upper(), path) for path, item in snapshot["paths"].items() for method in item if method in HTTP_METHODS+ }+ allowed = {(op.method, op.path) for op in ALLOWED_OPERATIONS[service]}+ if operations != allowed:+ raise GenerationError(+ f"{service} snapshot operations differ from ALLOWED_OPERATIONS: "+ f"missing {sorted(allowed - operations)}, unlisted {sorted(operations - allowed)}; rerun the snapshot"+ )+ return snapshot+++# --- generation -----------------------------------------------------------------------------------+++def snake_case(name: str) -> str:+ words = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name)+ words = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", words)+ return re.sub(r"[^0-9a-zA-Z]+", "_", words).strip("_").lower()+++def python_name(name: str) -> str:+ candidate = snake_case(name)+ if not candidate.isidentifier() or keyword.iskeyword(candidate) or candidate in BASE_MODEL_ATTRIBUTES:+ candidate = f"{candidate}_"+ return candidate+++def operation_function_name(operation_id: str, service: Service) -> str:+ tag, _, method = operation_id.partition("_")+ tag = tag.removeprefix(service.capitalize())+ return python_name(f"{tag}_{method}")+++def python_type(schema: JsonObject, context: str) -> str:+ if "allOf" in schema:+ parts = schema["allOf"]+ if len(parts) != 1:+ raise GenerationError(f"{context}: only single-element allOf is supported")+ return python_type(parts[0], context)+ if "$ref" in schema:+ return schema["$ref"].rpartition("/")[2]+ schema_type = schema.get("type")+ if "enum" in schema:+ if schema_type != "string":+ raise GenerationError(f"{context}: only string enums are supported")+ return f"Literal[{', '.join(json.dumps(value) for value in schema['enum'])}]"+ if schema_type == "integer" or (schema_type == "string" and schema.get("format") in {"int64", "uint64"}):+ return "int"+ if schema_type == "string":+ return "str"+ if schema_type == "number":+ return "float"+ if schema_type == "boolean":+ return "bool"+ if schema_type == "array":+ return f"list[{python_type(schema['items'], context)}]"+ if schema_type == "object" and isinstance(schema.get("additionalProperties"), dict):+ return f"dict[str, {python_type(schema['additionalProperties'], context)}]"+ raise GenerationError(f"{context}: unsupported schema {json.dumps(schema)}; give it a named message type")+++def field_type(schema: JsonObject, required: bool, context: str) -> str:+ annotation = python_type(schema, context)+ if schema.get("nullable") or not required:+ annotation = f"{annotation} | None"+ return annotation+++def model_order(schemas: dict[str, JsonObject]) -> list[str]:+ ordered: list[str] = []+ visiting: set[str] = set()++ def visit(name: str) -> None:+ if name in ordered:+ return+ if name in visiting:+ raise GenerationError(f"recursive schema {name} is not supported")+ visiting.add(name)+ for dependency in sorted(_ref_names(schemas[name])):+ visit(dependency)+ visiting.discard(name)+ ordered.append(name)++ for name in sorted(schemas):+ visit(name)+ return ordered+++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")+ required = set(schema.get("required", []))+ lines = [f"class {name}(BillingModel):"]+ properties: dict[str, JsonObject] = schema.get("properties", {})+ for wire_name, field in properties.items():+ attribute = python_name(wire_name)+ annotation = field_type(field, wire_name in required, f"{name}.{wire_name}")+ default = "" if wire_name in required else "None"+ if attribute != wire_name:+ arguments = ", ".join([*([default] if default else []), f"alias={json.dumps(wire_name)}"])+ lines.append(f" {attribute}: {annotation} = Field({arguments})")+ else:+ lines.append(f" {attribute}: {annotation}{f' = {default}' if default else ''}")+ if not properties:+ lines.append(" pass")+ return lines+++def _json_schema_ref(content: JsonObject | None, context: str) -> str:+ schema = (content or {}).get("application/json", {}).get("schema")+ if not schema or "$ref" not in schema:+ raise GenerationError(f"{context}: expected an application/json $ref schema")+ return schema["$ref"].rpartition("/")[2]+++def render_operation(service: Service, allowed: AllowedOperation, operation: JsonObject) -> list[str]:+ context = f"{allowed.method} {allowed.path}"+ function_name = operation_function_name(operation["operationId"], service)+ response = _json_schema_ref(operation.get("responses", {}).get("200", {}).get("content"), context)++ arguments: list[str] = []+ path_params: list[str] = []+ query_params: list[str] = []+ template = allowed.path.removeprefix(PATH_VERSION_PREFIX)+ for parameter in operation.get("parameters", []):+ wire_name = parameter["name"]+ argument = python_name(wire_name)+ annotation = python_type(parameter["schema"], f"{context} {wire_name}")+ arguments.append(f"{argument}: {annotation}")+ if parameter["in"] == "path":+ template = template.replace(f"{{{wire_name}}}", f"{{{argument}}}")+ path_params.append(f"{json.dumps(argument)}: {argument}")+ elif parameter["in"] == "query":+ query_params.append(f"{json.dumps(wire_name)}: {argument}")+ else:+ raise GenerationError(f"{context}: unsupported parameter location {parameter['in']}")+ body = "None"+ if "requestBody" in operation:+ arguments.append(f"body: {_json_schema_ref(operation['requestBody'].get('content'), context)}")+ body = "body"+ if len({argument.partition(":")[0] for argument in arguments}) != len(arguments):+ raise GenerationError(f"{context}: argument names collide")++ signature = f"def {function_name}({'*, ' + ', '.join(arguments) if arguments else ''}) -> {response}:"+ return [+ signature,+ f' """{allowed.method} {allowed.path} ({operation["operationId"]})."""',+ " return request(",+ f" Upstream.{allowed.upstream},",+ f" {json.dumps(allowed.method)},",+ f" {json.dumps(template)},",+ f" response_model={response},",+ f" path_params={{{', '.join(path_params)}}},",+ f" params={{{', '.join(query_params)}}},",+ f" body={body},",+ " )",+ ]+++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)]+ for allowed in ALLOWED_OPERATIONS[service]:+ operation = snapshot["paths"][allowed.path][allowed.method.lower()]+ blocks.append(render_operation(service, allowed, operation))++ body = "\n\n\n".join("\n".join(block) for block in blocks)+ header = [+ f"# Code generated by {GENERATOR} from {service}.openapi.json. DO NOT EDIT.",+ f"# dify-saas commit: {snapshot[SNAPSHOT_COMMIT_KEY]}",+ "",+ "from typing import Literal",+ "",+ "from pydantic import Field",+ "",+ "from services.billing_client.transport import BillingModel, Upstream, request",+ ]+ return format_python("\n".join(header) + "\n\n\n" + body + "\n", module_path(service))+++def format_python(source: str, path: Path) -> str:+ ruff = [sys.executable, "-m", "ruff"]+ fixed = subprocess.run(+ [*ruff, "check", "--fix", "--quiet", "--select", "F401,I", "--stdin-filename", str(path), "-"],+ input=source,+ capture_output=True,+ text=True,+ check=True,+ cwd=API_ROOT,+ ).stdout+ return subprocess.run(+ [*ruff, "format", "--quiet", "--stdin-filename", str(path), "-"],+ input=fixed,+ capture_output=True,+ text=True,+ check=True,+ cwd=API_ROOT,+ ).stdout+++# --- entry point ----------------------------------------------------------------------------------+++def expected_files(snapshots: dict[Service, JsonObject]) -> dict[Path, str]:+ files: dict[Path, str] = {}+ for service, snapshot in snapshots.items():+ files[snapshot_path(service)] = render_snapshot(snapshot)+ files[module_path(service)] = render_module(service, snapshot)+ return files+++def check(files: dict[Path, str]) -> int:+ drifted = 0+ for path, expected in files.items():+ actual = path.read_text() if path.exists() else ""+ if actual != expected:+ drifted += 1+ diff = difflib.unified_diff(+ actual.splitlines(keepends=True),+ expected.splitlines(keepends=True),+ fromfile=str(path.relative_to(REPO_ROOT)),+ tofile="regenerated",+ )+ sys.stderr.writelines(diff)+ if drifted:+ logger.error("billing client is out of date; regenerate with `%s --from-snapshot`", GENERATOR)+ return 1 if drifted else 0+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ mode = parser.add_mutually_exclusive_group()+ mode.add_argument("--from-snapshot", action="store_true", help="generate from the committed snapshots")+ mode.add_argument("--check", action="store_true", help="fail if regenerating the committed snapshots differs")+ args = parser.parse_args()+ logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")++ try:+ if args.check or args.from_snapshot:+ snapshots = {service: load_snapshot(service) for service in SERVICES}+ else:+ snapshots = take_snapshots()+ files = expected_files(snapshots)+ except GenerationError as error:+ sys.stderr.write(f"error: {error}\n")+ return 1++ if args.check:+ return check(files)+ for path, content in files.items():+ path.write_text(content)+ logger.info("wrote %s", path.relative_to(REPO_ROOT))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/api/services/billing_client/__init__.py b/api/services/billing_client/__init__.pynew file mode 100644index 00000000000..cdd74409b78--- /dev/null+++ b/api/services/billing_client/__init__.py@@ -0,0 +1,5 @@+"""Typed client for the billing and saas services.++`billing` and `saas` are generated from the committed OpenAPI snapshots by+`api/dev/generate_billing_client.py`; `transport` is the hand-written HTTP layer they share.+"""diff --git a/api/services/billing_client/billing.openapi.json b/api/services/billing_client/billing.openapi.jsonnew file mode 100644index 00000000000..bbfbbb5f7e0--- /dev/null+++ b/api/services/billing_client/billing.openapi.json@@ -0,0 +1,1420 @@+{+ "openapi": "3.0.3",+ "info": {+ "title": "",+ "version": "0.0.1"+ },+ "x-dify-saas-commit": "a0b548cf3020d490a8b7fad21dfbb66b72fa0ed6",+ "paths": {+ "/v1/subscription/info": {+ "get": {+ "tags": [+ "BillingSubscription"+ ],+ "operationId": "BillingSubscription_GetSubscriptionInfo",+ "parameters": [+ {+ "name": "tenant_id",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "exclude_vector_space",+ "in": "query",+ "schema": {+ "type": "boolean"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetSubscriptionInfoReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/subscription/vector-space": {+ "get": {+ "tags": [+ "BillingSubscription"+ ],+ "operationId": "BillingSubscription_GetSubscriptionVectorSpace",+ "parameters": [+ {+ "name": "tenant_id",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "bypass_cache",+ "in": "query",+ "schema": {+ "type": "boolean"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/VectorSpaceQuota"+ }+ }+ }+ }+ }+ }+ },+ "/v1/subscription/knowledge-rate-limit": {+ "get": {+ "tags": [+ "BillingSubscription"+ ],+ "operationId": "BillingSubscription_GetKnowledgeRateLimit",+ "parameters": [+ {+ "name": "tenant_id",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetKnowledgeRateLimitReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/subscription/payment-link": {+ "get": {+ "tags": [+ "BillingSubscription"+ ],+ "operationId": "BillingSubscription_GetSubscriptionPaymentLink",+ "parameters": [+ {+ "name": "plan",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "interval",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "prefilled_email",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "tenant_id",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetSubscriptionPaymentLinkReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/subscription/plan/batch": {+ "post": {+ "tags": [+ "BillingSubscription"+ ],+ "operationId": "BillingSubscription_BatchGetSubscriptionPlan",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/BatchGetSubscriptionPlanReq"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/BatchGetSubscriptionPlanReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/subscription/cleanup/whitelist": {+ "get": {+ "tags": [+ "BillingSubscription"+ ],+ "operationId": "BillingSubscription_ListSubscriptionCleanupWhitelist",+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ListSubscriptionCleanupWhitelistReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/model-provider/payment-link": {+ "get": {+ "tags": [+ "BillingModelProvider"+ ],+ "operationId": "BillingModelProvider_GetModelProviderPaymentLink",+ "parameters": [+ {+ "name": "provider_name",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "tenant_id",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "account_id",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "prefilled_email",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetModelProviderPaymentLinkReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/invoices": {+ "get": {+ "tags": [+ "BillingInvoice"+ ],+ "operationId": "BillingInvoice_GetInvoices",+ "parameters": [+ {+ "name": "prefilled_email",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "tenant_id",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetInvoicesReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/education/verify": {+ "get": {+ "tags": [+ "BillingEducation"+ ],+ "operationId": "BillingEducation_VerifyEducationIdentity",+ "parameters": [+ {+ "name": "account_id",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/VerifyEducationIdentityReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/education/status": {+ "get": {+ "tags": [+ "BillingEducation"+ ],+ "operationId": "BillingEducation_GetEducationIdentityStatus",+ "parameters": [+ {+ "name": "account_id",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetEducationIdentityStatusReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/education": {+ "post": {+ "tags": [+ "BillingEducation"+ ],+ "operationId": "BillingEducation_CreateEducationIdentity",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateEducationIdentityReq"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateEducationIdentityReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/education/autocomplete": {+ "get": {+ "tags": [+ "BillingEducation"+ ],+ "operationId": "BillingEducation_AutocompleteEducationInstitution",+ "parameters": [+ {+ "name": "keywords",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "page",+ "in": "query",+ "schema": {+ "type": "integer",+ "format": "int32"+ }+ },+ {+ "name": "limit",+ "in": "query",+ "schema": {+ "type": "integer",+ "format": "int32"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AutocompleteEducationInstitutionReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/compliance/download": {+ "post": {+ "tags": [+ "BillingCompliance"+ ],+ "operationId": "BillingCompliance_DownloadComplianceDocument",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DownloadComplianceDocumentReq"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DownloadComplianceDocumentReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/quota/info": {+ "get": {+ "tags": [+ "BillingQuota"+ ],+ "description": "GetQuotaInfo returns aggregated quota info for all billing features of a tenant.",+ "operationId": "BillingQuota_GetQuotaInfo",+ "parameters": [+ {+ "name": "tenant_id",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QuotaGetInfoReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/quota/reserve": {+ "post": {+ "tags": [+ "BillingQuota"+ ],+ "description": "Reserve pre-allocates quota before task execution.",+ "operationId": "BillingQuota_Reserve",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QuotaReserveReq"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QuotaReserveReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/quota/commit": {+ "post": {+ "tags": [+ "BillingQuota"+ ],+ "description": "Commit finalizes the reservation with actual cost.",+ "operationId": "BillingQuota_Commit",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QuotaCommitReq"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QuotaCommitReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/quota/release": {+ "post": {+ "tags": [+ "BillingQuota"+ ],+ "description": "Release cancels a reservation and returns quota.",+ "operationId": "BillingQuota_Release",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QuotaReleaseReq"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QuotaReleaseReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/quota/balance": {+ "get": {+ "tags": [+ "BillingQuota"+ ],+ "description": "GetBalance returns current available and reserved quota for a single feature.",+ "operationId": "BillingQuota_GetBalance",+ "parameters": [+ {+ "name": "tenant_id",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "feature_key",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "bucket",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QuotaGetBalanceReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/quota/consume-capped": {+ "post": {+ "tags": [+ "BillingQuota"+ ],+ "description": "ConsumeCapped atomically consumes up to the available quota.",+ "operationId": "BillingQuota_ConsumeCapped",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QuotaConsumeCappedReq"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QuotaConsumeCappedReply"+ }+ }+ }+ }+ }+ }+ }+ },+ "components": {+ "schemas": {+ "AutocompleteEducationInstitutionReply": {+ "type": "object",+ "properties": {+ "data": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "curr_page": {+ "type": "integer",+ "format": "int32"+ },+ "has_next": {+ "type": "boolean"+ }+ },+ "required": [+ "data",+ "curr_page",+ "has_next"+ ]+ },+ "BatchGetSubscriptionPlanReply": {+ "type": "object",+ "properties": {+ "data": {+ "type": "object",+ "additionalProperties": {+ "$ref": "#/components/schemas/SubscriptionPlanItem"+ }+ }+ },+ "description": "Batch get subscription plan reply",+ "required": [+ "data"+ ]+ },+ "BatchGetSubscriptionPlanReq": {+ "type": "object",+ "properties": {+ "tenant_ids": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "description": "Batch get subscription plan request",+ "required": [+ "tenant_ids"+ ]+ },+ "BillingSubscriptionPlan": {+ "type": "object",+ "properties": {+ "plan": {+ "enum": [+ "sandbox",+ "professional",+ "team"+ ],+ "type": "string"+ },+ "interval": {+ "enum": [+ "",+ "month",+ "year"+ ],+ "type": "string"+ },+ "education": {+ "type": "boolean"+ },+ "status": {+ "type": "string"+ },+ "cancel_at_period_end": {+ "type": "boolean"+ },+ "paid_period_end": {+ "type": "string",+ "format": "int64"+ }+ },+ "description": "Subscription plan and billing cycle info",+ "required": [+ "plan",+ "interval",+ "education",+ "status",+ "cancel_at_period_end",+ "paid_period_end"+ ]+ },+ "CreateEducationIdentityReply": {+ "type": "object",+ "properties": {+ "message": {+ "type": "string"+ }+ },+ "required": [+ "message"+ ]+ },+ "CreateEducationIdentityReq": {+ "type": "object",+ "properties": {+ "account_id": {+ "type": "string"+ },+ "curr_tenant_id": {+ "type": "string"+ },+ "institution": {+ "type": "string"+ },+ "role": {+ "type": "string"+ },+ "token": {+ "type": "string"+ }+ },+ "required": [+ "account_id",+ "curr_tenant_id",+ "institution",+ "role",+ "token"+ ]+ },+ "DownloadComplianceDocumentReply": {+ "type": "object",+ "properties": {+ "url": {+ "type": "string"+ }+ },+ "required": [+ "url"+ ]+ },+ "DownloadComplianceDocumentReq": {+ "type": "object",+ "properties": {+ "doc_name": {+ "type": "string"+ },+ "account_id": {+ "type": "string"+ },+ "tenant_id": {+ "type": "string"+ },+ "ip_address": {+ "type": "string"+ },+ "device_info": {+ "type": "string"+ }+ },+ "required": [+ "doc_name",+ "account_id",+ "tenant_id",+ "ip_address",+ "device_info"+ ]+ },+ "GetEducationIdentityStatusReply": {+ "type": "object",+ "properties": {+ "result": {+ "type": "boolean"+ },+ "is_student": {+ "type": "boolean"+ },+ "expire_at": {+ "type": "string"+ },+ "allow_refresh": {+ "type": "boolean"+ }+ },+ "required": [+ "result",+ "is_student",+ "expire_at",+ "allow_refresh"+ ]+ },+ "GetInvoicesReply": {+ "type": "object",+ "properties": {+ "url": {+ "type": "string"+ }+ },+ "required": [+ "url"+ ]+ },+ "GetKnowledgeRateLimitReply": {+ "type": "object",+ "properties": {+ "subscription_plan": {+ "enum": [+ "sandbox",+ "professional",+ "team"+ ],+ "type": "string"+ },+ "limit": {+ "type": "integer",+ "format": "int32"+ }+ },+ "required": [+ "subscription_plan",+ "limit"+ ]+ },+ "GetModelProviderPaymentLinkReply": {+ "type": "object",+ "properties": {+ "url": {+ "type": "string"+ }+ },+ "required": [+ "url"+ ]+ },+ "GetSubscriptionInfoReply": {+ "required": [+ "enabled",+ "subscription",+ "members",+ "apps",+ "vector_space",+ "knowledge_rate_limit",+ "documents_upload_quota",+ "annotation_quota_limit",+ "docs_processing",+ "can_replace_logo",+ "model_load_balancing_enabled",+ "knowledge_pipeline_publish_enabled",+ "next_credit_reset_date"+ ],+ "type": "object",+ "properties": {+ "enabled": {+ "type": "boolean"+ },+ "subscription": {+ "$ref": "#/components/schemas/BillingSubscriptionPlan"+ },+ "members": {+ "$ref": "#/components/schemas/SubscriptionQuota"+ },+ "apps": {+ "$ref": "#/components/schemas/SubscriptionQuota"+ },+ "vector_space": {+ "allOf": [+ {+ "$ref": "#/components/schemas/VectorSpaceQuota"+ }+ ],+ "nullable": true+ },+ "knowledge_rate_limit": {+ "$ref": "#/components/schemas/KnowledgeRateLimit"+ },+ "documents_upload_quota": {+ "$ref": "#/components/schemas/SubscriptionQuota"+ },+ "annotation_quota_limit": {+ "$ref": "#/components/schemas/SubscriptionQuota"+ },+ "docs_processing": {+ "enum": [+ "standard",+ "priority",+ "top-priority"+ ],+ "type": "string"+ },+ "can_replace_logo": {+ "type": "boolean"+ },+ "model_load_balancing_enabled": {+ "type": "boolean"+ },+ "knowledge_pipeline_publish_enabled": {+ "type": "boolean"+ },+ "next_credit_reset_date": {+ "type": "string",+ "format": "int64"+ }+ },+ "description": "Get subscription info reply"+ },+ "GetSubscriptionPaymentLinkReply": {+ "type": "object",+ "properties": {+ "url": {+ "type": "string"+ }+ },+ "description": "Get subscription payment link reply",+ "required": [+ "url"+ ]+ },+ "KnowledgeRateLimit": {+ "type": "object",+ "properties": {+ "size": {+ "type": "string",+ "format": "int64"+ },+ "limit": {+ "type": "string",+ "format": "int64"+ }+ },+ "description": "Knowledge rate limit (requests per minute)\n NOTE: size is retained for structural consistency but is not consumed by dify.\n Implementation should populate 0 for paid users.",+ "required": [+ "size",+ "limit"+ ]+ },+ "ListSubscriptionCleanupWhitelistReply": {+ "type": "object",+ "properties": {+ "data": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/SubscriptionCleanupWhitelist"+ }+ }+ },+ "description": "List subscription cleanup whitelist reply",+ "required": [+ "data"+ ]+ },+ "QuotaCommitReply": {+ "type": "object",+ "properties": {+ "available": {+ "type": "string",+ "format": "int64"+ },+ "reserved": {+ "type": "string",+ "format": "int64"+ },+ "refunded": {+ "type": "string",+ "format": "int64"+ }+ },+ "required": [+ "available",+ "reserved",+ "refunded"+ ]+ },+ "QuotaCommitReq": {+ "type": "object",+ "properties": {+ "tenant_id": {+ "type": "string"+ },+ "feature_key": {+ "type": "string"+ },+ "reservation_id": {+ "type": "string"+ },+ "actual_amount": {+ "type": "string",+ "format": "int64"+ },+ "meta": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ },+ "bucket": {+ "type": "string"+ }+ },+ "required": [+ "tenant_id",+ "feature_key",+ "reservation_id",+ "actual_amount",+ "meta",+ "bucket"+ ]+ },+ "QuotaConsumeCappedReply": {+ "type": "object",+ "properties": {+ "deducted": {+ "type": "string",+ "format": "int64"+ },+ "available": {+ "type": "string",+ "format": "int64"+ },+ "reserved": {+ "type": "string",+ "format": "int64"+ },+ "quota": {+ "type": "string",+ "format": "int64"+ },+ "usage": {+ "type": "string",+ "format": "int64"+ }+ },+ "required": [+ "deducted",+ "available",+ "reserved",+ "quota",+ "usage"+ ]+ },+ "QuotaConsumeCappedReq": {+ "type": "object",+ "properties": {+ "tenant_id": {+ "type": "string"+ },+ "feature_key": {+ "type": "string"+ },+ "request_id": {+ "type": "string"+ },+ "amount": {+ "type": "string",+ "format": "int64"+ },+ "meta": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ },+ "bucket": {+ "type": "string"+ }+ },+ "required": [+ "tenant_id",+ "feature_key",+ "request_id",+ "amount",+ "meta",+ "bucket"+ ]+ },+ "QuotaFeatureInfo": {+ "type": "object",+ "properties": {+ "usage": {+ "type": "string",+ "format": "int64"+ },+ "limit": {+ "type": "string",+ "format": "int64"+ },+ "reset_date": {+ "type": "string",+ "format": "int64"+ }+ },+ "description": "Per-feature quota detail",+ "required": [+ "usage",+ "limit",+ "reset_date"+ ]+ },+ "QuotaGetBalanceReply": {+ "type": "object",+ "properties": {+ "available": {+ "type": "string",+ "format": "int64"+ },+ "reserved": {+ "type": "string",+ "format": "int64"+ },+ "quota": {+ "type": "string",+ "format": "int64"+ },+ "usage": {+ "type": "string",+ "format": "int64"+ },+ "exhausted_at": {+ "type": "string",+ "format": "int64"+ }+ },+ "required": [+ "available",+ "reserved",+ "quota",+ "usage",+ "exhausted_at"+ ]+ },+ "QuotaGetInfoReply": {+ "required": [+ "trigger_event",+ "api_rate_limit"+ ],+ "type": "object",+ "properties": {+ "trigger_event": {+ "$ref": "#/components/schemas/QuotaFeatureInfo"+ },+ "api_rate_limit": {+ "$ref": "#/components/schemas/QuotaFeatureInfo"+ }+ }+ },+ "QuotaReleaseReply": {+ "type": "object",+ "properties": {+ "available": {+ "type": "string",+ "format": "int64"+ },+ "reserved": {+ "type": "string",+ "format": "int64"+ },+ "released": {+ "type": "string",+ "format": "int64"+ }+ },+ "required": [+ "available",+ "reserved",+ "released"+ ]+ },+ "QuotaReleaseReq": {+ "type": "object",+ "properties": {+ "tenant_id": {+ "type": "string"+ },+ "feature_key": {+ "type": "string"+ },+ "reservation_id": {+ "type": "string"+ },+ "bucket": {+ "type": "string"+ }+ },+ "required": [+ "tenant_id",+ "feature_key",+ "reservation_id",+ "bucket"+ ]+ },+ "QuotaReserveReply": {+ "type": "object",+ "properties": {+ "reservation_id": {+ "type": "string"+ },+ "available": {+ "type": "string",+ "format": "int64"+ },+ "reserved": {+ "type": "string",+ "format": "int64"+ }+ },+ "required": [+ "reservation_id",+ "available",+ "reserved"+ ]+ },+ "QuotaReserveReq": {+ "type": "object",+ "properties": {+ "tenant_id": {+ "type": "string"+ },+ "feature_key": {+ "type": "string"+ },+ "request_id": {+ "type": "string"+ },+ "amount": {+ "type": "string",+ "format": "int64"+ },+ "meta": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ },+ "description": "Optional metadata (model name, trace_id, etc.)"+ },+ "bucket": {+ "type": "string"+ }+ },+ "required": [+ "tenant_id",+ "feature_key",+ "request_id",+ "amount",+ "meta",+ "bucket"+ ]+ },+ "SubscriptionCleanupWhitelist": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "tenant_id": {+ "type": "string"+ },+ "contact": {+ "type": "string"+ },+ "expired_at": {+ "type": "string",+ "format": "date-time"+ },+ "created_at": {+ "type": "string",+ "format": "date-time"+ },+ "updated_at": {+ "type": "string",+ "format": "date-time"+ }+ },+ "description": "Single whitelist item",+ "required": [+ "id",+ "tenant_id",+ "contact",+ "expired_at",+ "created_at",+ "updated_at"+ ]+ },+ "SubscriptionPlanItem": {+ "type": "object",+ "properties": {+ "plan": {+ "enum": [+ "sandbox",+ "professional",+ "team"+ ],+ "type": "string"+ },+ "expiration_date": {+ "type": "string",+ "format": "int64"+ }+ },+ "description": "Subscription plan item",+ "required": [+ "plan",+ "expiration_date"+ ]+ },+ "SubscriptionQuota": {+ "type": "object",+ "properties": {+ "size": {+ "type": "string",+ "format": "int64"+ },+ "limit": {+ "type": "string",+ "format": "int64"+ }+ },+ "description": "Generic usage quota (size = current usage, limit = max allowed)",+ "required": [+ "size",+ "limit"+ ]+ },+ "VectorSpaceQuota": {+ "type": "object",+ "properties": {+ "size": {+ "type": "number",+ "format": "double"+ },+ "limit": {+ "type": "string",+ "format": "int64"+ },+ "usage_unknown": {+ "nullable": true,+ "type": "boolean"+ }+ },+ "description": "Vector space quota (size is double because dataset sizes are fractional MB)",+ "required": [+ "size",+ "limit"+ ]+ },+ "VerifyEducationIdentityReply": {+ "type": "object",+ "properties": {+ "token": {+ "type": "string"+ }+ },+ "required": [+ "token"+ ]+ }+ }+ }+}diff --git a/api/services/billing_client/billing.py b/api/services/billing_client/billing.pynew file mode 100644index 00000000000..57b7b783e7c--- /dev/null+++ b/api/services/billing_client/billing.py@@ -0,0 +1,468 @@+# Code generated by api/dev/generate_billing_client.py from billing.openapi.json. DO NOT EDIT.+# dify-saas commit: a0b548cf3020d490a8b7fad21dfbb66b72fa0ed6++from typing import Literal++from services.billing_client.transport import BillingModel, Upstream, request+++class AutocompleteEducationInstitutionReply(BillingModel):+ data: list[str]+ curr_page: int+ has_next: bool+++class SubscriptionPlanItem(BillingModel):+ plan: Literal["sandbox", "professional", "team"]+ expiration_date: int+++class BatchGetSubscriptionPlanReply(BillingModel):+ data: dict[str, SubscriptionPlanItem]+++class BatchGetSubscriptionPlanReq(BillingModel):+ tenant_ids: list[str]+++class BillingSubscriptionPlan(BillingModel):+ plan: Literal["sandbox", "professional", "team"]+ interval: Literal["", "month", "year"]+ education: bool+ status: str+ cancel_at_period_end: bool+ paid_period_end: int+++class CreateEducationIdentityReply(BillingModel):+ message: str+++class CreateEducationIdentityReq(BillingModel):+ account_id: str+ curr_tenant_id: str+ institution: str+ role: str+ token: str+++class DownloadComplianceDocumentReply(BillingModel):+ url: str+++class DownloadComplianceDocumentReq(BillingModel):+ doc_name: str+ account_id: str+ tenant_id: str+ ip_address: str+ device_info: str+++class GetEducationIdentityStatusReply(BillingModel):+ result: bool+ is_student: bool+ expire_at: str+ allow_refresh: bool+++class GetInvoicesReply(BillingModel):+ url: str+++class GetKnowledgeRateLimitReply(BillingModel):+ subscription_plan: Literal["sandbox", "professional", "team"]+ limit: int+++class GetModelProviderPaymentLinkReply(BillingModel):+ url: str+++class KnowledgeRateLimit(BillingModel):+ size: int+ limit: int+++class SubscriptionQuota(BillingModel):+ size: int+ limit: int+++class VectorSpaceQuota(BillingModel):+ size: float+ limit: int+ usage_unknown: bool | None = None+++class GetSubscriptionInfoReply(BillingModel):+ enabled: bool+ subscription: BillingSubscriptionPlan+ members: SubscriptionQuota+ apps: SubscriptionQuota+ vector_space: VectorSpaceQuota | None+ knowledge_rate_limit: KnowledgeRateLimit+ documents_upload_quota: SubscriptionQuota+ annotation_quota_limit: SubscriptionQuota+ docs_processing: Literal["standard", "priority", "top-priority"]+ can_replace_logo: bool+ model_load_balancing_enabled: bool+ knowledge_pipeline_publish_enabled: bool+ next_credit_reset_date: int+++class GetSubscriptionPaymentLinkReply(BillingModel):+ url: str+++class SubscriptionCleanupWhitelist(BillingModel):+ id: str+ tenant_id: str+ contact: str+ expired_at: str+ created_at: str+ updated_at: str+++class ListSubscriptionCleanupWhitelistReply(BillingModel):+ data: list[SubscriptionCleanupWhitelist]+++class QuotaCommitReply(BillingModel):+ available: int+ reserved: int+ refunded: int+++class QuotaCommitReq(BillingModel):+ tenant_id: str+ feature_key: str+ reservation_id: str+ actual_amount: int+ meta: dict[str, str]+ bucket: str+++class QuotaConsumeCappedReply(BillingModel):+ deducted: int+ available: int+ reserved: int+ quota: int+ usage: int+++class QuotaConsumeCappedReq(BillingModel):+ tenant_id: str+ feature_key: str+ request_id: str+ amount: int+ meta: dict[str, str]+ bucket: str+++class QuotaFeatureInfo(BillingModel):+ usage: int+ limit: int+ reset_date: int+++class QuotaGetBalanceReply(BillingModel):+ available: int+ reserved: int+ quota: int+ usage: int+ exhausted_at: int+++class QuotaGetInfoReply(BillingModel):+ trigger_event: QuotaFeatureInfo+ api_rate_limit: QuotaFeatureInfo+++class QuotaReleaseReply(BillingModel):+ available: int+ reserved: int+ released: int+++class QuotaReleaseReq(BillingModel):+ tenant_id: str+ feature_key: str+ reservation_id: str+ bucket: str+++class QuotaReserveReply(BillingModel):+ reservation_id: str+ available: int+ reserved: int+++class QuotaReserveReq(BillingModel):+ tenant_id: str+ feature_key: str+ request_id: str+ amount: int+ meta: dict[str, str]+ bucket: str+++class VerifyEducationIdentityReply(BillingModel):+ token: str+++def subscription_get_subscription_info(*, tenant_id: str, exclude_vector_space: bool) -> GetSubscriptionInfoReply:+ """GET /v1/subscription/info (BillingSubscription_GetSubscriptionInfo)."""+ return request(+ Upstream.BILLING,+ "GET",+ "/subscription/info",+ response_model=GetSubscriptionInfoReply,+ path_params={},+ params={"tenant_id": tenant_id, "exclude_vector_space": exclude_vector_space},+ body=None,+ )+++def subscription_get_subscription_vector_space(*, tenant_id: str, bypass_cache: bool) -> VectorSpaceQuota:+ """GET /v1/subscription/vector-space (BillingSubscription_GetSubscriptionVectorSpace)."""+ return request(+ Upstream.BILLING,+ "GET",+ "/subscription/vector-space",+ response_model=VectorSpaceQuota,+ path_params={},+ params={"tenant_id": tenant_id, "bypass_cache": bypass_cache},+ body=None,+ )+++def subscription_get_knowledge_rate_limit(*, tenant_id: str) -> GetKnowledgeRateLimitReply:+ """GET /v1/subscription/knowledge-rate-limit (BillingSubscription_GetKnowledgeRateLimit)."""+ return request(+ Upstream.BILLING,+ "GET",+ "/subscription/knowledge-rate-limit",+ response_model=GetKnowledgeRateLimitReply,+ path_params={},+ params={"tenant_id": tenant_id},+ body=None,+ )+++def subscription_get_subscription_payment_link(+ *, plan: str, interval: str, prefilled_email: str, tenant_id: str+) -> GetSubscriptionPaymentLinkReply:+ """GET /v1/subscription/payment-link (BillingSubscription_GetSubscriptionPaymentLink)."""+ return request(+ Upstream.BILLING,+ "GET",+ "/subscription/payment-link",+ response_model=GetSubscriptionPaymentLinkReply,+ path_params={},+ params={"plan": plan, "interval": interval, "prefilled_email": prefilled_email, "tenant_id": tenant_id},+ body=None,+ )+++def subscription_batch_get_subscription_plan(*, body: BatchGetSubscriptionPlanReq) -> BatchGetSubscriptionPlanReply:+ """POST /v1/subscription/plan/batch (BillingSubscription_BatchGetSubscriptionPlan)."""+ return request(+ Upstream.BILLING,+ "POST",+ "/subscription/plan/batch",+ response_model=BatchGetSubscriptionPlanReply,+ path_params={},+ params={},+ body=body,+ )+++def subscription_list_subscription_cleanup_whitelist() -> ListSubscriptionCleanupWhitelistReply:+ """GET /v1/subscription/cleanup/whitelist (BillingSubscription_ListSubscriptionCleanupWhitelist)."""+ return request(+ Upstream.BILLING,+ "GET",+ "/subscription/cleanup/whitelist",+ response_model=ListSubscriptionCleanupWhitelistReply,+ path_params={},+ params={},+ body=None,+ )+++def model_provider_get_model_provider_payment_link(+ *, provider_name: str, tenant_id: str, account_id: str, prefilled_email: str+) -> GetModelProviderPaymentLinkReply:+ """GET /v1/model-provider/payment-link (BillingModelProvider_GetModelProviderPaymentLink)."""+ return request(+ Upstream.BILLING,+ "GET",+ "/model-provider/payment-link",+ response_model=GetModelProviderPaymentLinkReply,+ path_params={},+ params={+ "provider_name": provider_name,+ "tenant_id": tenant_id,+ "account_id": account_id,+ "prefilled_email": prefilled_email,+ },+ body=None,+ )+++def invoice_get_invoices(*, prefilled_email: str, tenant_id: str) -> GetInvoicesReply:+ """GET /v1/invoices (BillingInvoice_GetInvoices)."""+ return request(+ Upstream.BILLING,+ "GET",+ "/invoices",+ response_model=GetInvoicesReply,+ path_params={},+ params={"prefilled_email": prefilled_email, "tenant_id": tenant_id},+ body=None,+ )+++def education_verify_education_identity(*, account_id: str) -> VerifyEducationIdentityReply:+ """GET /v1/education/verify (BillingEducation_VerifyEducationIdentity)."""+ return request(+ Upstream.BILLING,+ "GET",+ "/education/verify",+ response_model=VerifyEducationIdentityReply,+ path_params={},+ params={"account_id": account_id},+ body=None,+ )+++def education_get_education_identity_status(*, account_id: str) -> GetEducationIdentityStatusReply:+ """GET /v1/education/status (BillingEducation_GetEducationIdentityStatus)."""+ return request(+ Upstream.BILLING,+ "GET",+ "/education/status",+ response_model=GetEducationIdentityStatusReply,+ path_params={},+ params={"account_id": account_id},+ body=None,+ )+++def education_create_education_identity(*, body: CreateEducationIdentityReq) -> CreateEducationIdentityReply:+ """POST /v1/education (BillingEducation_CreateEducationIdentity)."""+ return request(+ Upstream.BILLING,+ "POST",+ "/education",+ response_model=CreateEducationIdentityReply,+ path_params={},+ params={},+ body=body,+ )+++def education_autocomplete_education_institution(+ *, keywords: str, page: int, limit: int+) -> AutocompleteEducationInstitutionReply:+ """GET /v1/education/autocomplete (BillingEducation_AutocompleteEducationInstitution)."""+ return request(+ Upstream.BILLING,+ "GET",+ "/education/autocomplete",+ response_model=AutocompleteEducationInstitutionReply,+ path_params={},+ params={"keywords": keywords, "page": page, "limit": limit},+ body=None,+ )+++def compliance_download_compliance_document(*, body: DownloadComplianceDocumentReq) -> DownloadComplianceDocumentReply:+ """POST /v1/compliance/download (BillingCompliance_DownloadComplianceDocument)."""+ return request(+ Upstream.BILLING,+ "POST",+ "/compliance/download",+ response_model=DownloadComplianceDocumentReply,+ path_params={},+ params={},+ body=body,+ )+++def quota_get_quota_info(*, tenant_id: str) -> QuotaGetInfoReply:+ """GET /v1/quota/info (BillingQuota_GetQuotaInfo)."""+ return request(+ Upstream.BILLING_QUOTA,+ "GET",+ "/quota/info",+ response_model=QuotaGetInfoReply,+ path_params={},+ params={"tenant_id": tenant_id},+ body=None,+ )+++def quota_reserve(*, body: QuotaReserveReq) -> QuotaReserveReply:+ """POST /v1/quota/reserve (BillingQuota_Reserve)."""+ return request(+ Upstream.BILLING_QUOTA,+ "POST",+ "/quota/reserve",+ response_model=QuotaReserveReply,+ path_params={},+ params={},+ body=body,+ )+++def quota_commit(*, body: QuotaCommitReq) -> QuotaCommitReply:+ """POST /v1/quota/commit (BillingQuota_Commit)."""+ return request(+ Upstream.BILLING_QUOTA,+ "POST",+ "/quota/commit",+ response_model=QuotaCommitReply,+ path_params={},+ params={},+ body=body,+ )+++def quota_release(*, body: QuotaReleaseReq) -> QuotaReleaseReply:+ """POST /v1/quota/release (BillingQuota_Release)."""+ return request(+ Upstream.BILLING_QUOTA,+ "POST",+ "/quota/release",+ response_model=QuotaReleaseReply,+ path_params={},+ params={},+ body=body,+ )+++def quota_get_balance(*, tenant_id: str, feature_key: str, bucket: str) -> QuotaGetBalanceReply:+ """GET /v1/quota/balance (BillingQuota_GetBalance)."""+ return request(+ Upstream.BILLING_QUOTA,+ "GET",+ "/quota/balance",+ response_model=QuotaGetBalanceReply,+ path_params={},+ params={"tenant_id": tenant_id, "feature_key": feature_key, "bucket": bucket},+ body=None,+ )+++def quota_consume_capped(*, body: QuotaConsumeCappedReq) -> QuotaConsumeCappedReply:+ """POST /v1/quota/consume-capped (BillingQuota_ConsumeCapped)."""+ return request(+ Upstream.BILLING_QUOTA,+ "POST",+ "/quota/consume-capped",+ response_model=QuotaConsumeCappedReply,+ path_params={},+ params={},+ body=body,+ )diff --git a/api/services/billing_client/saas.openapi.json b/api/services/billing_client/saas.openapi.jsonnew file mode 100644index 00000000000..f3d43ac714c--- /dev/null+++ b/api/services/billing_client/saas.openapi.json@@ -0,0 +1,340 @@+{+ "openapi": "3.0.3",+ "info": {+ "title": "",+ "version": "0.0.1"+ },+ "x-dify-saas-commit": "a0b548cf3020d490a8b7fad21dfbb66b72fa0ed6",+ "paths": {+ "/v1/account": {+ "delete": {+ "tags": [+ "Account"+ ],+ "description": "删除账户",+ "operationId": "Account_DeleteAccount",+ "parameters": [+ {+ "name": "accountId",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DeleteAccountReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/account/in-freeze": {+ "get": {+ "tags": [+ "Account"+ ],+ "description": "检查邮箱是否在冻结期",+ "operationId": "Account_CheckAccountInFreeze",+ "parameters": [+ {+ "name": "email",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CheckAccountInFreezeReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/account/delete-feedback": {+ "post": {+ "tags": [+ "Account"+ ],+ "description": "添加删除反馈",+ "operationId": "Account_AddDeleteFeedback",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AddDeleteFeedbackRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AddDeleteFeedbackReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/notifications/active": {+ "get": {+ "tags": [+ "SaasNotification"+ ],+ "operationId": "SaasNotification_GetAccountNotification",+ "parameters": [+ {+ "name": "accountId",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetAccountNotificationReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/notifications/{notificationId}/dismiss": {+ "post": {+ "tags": [+ "SaasNotification"+ ],+ "operationId": "SaasNotification_DismissNotification",+ "parameters": [+ {+ "name": "notificationId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DismissNotificationReq"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DismissNotificationReply"+ }+ }+ }+ }+ }+ }+ }+ },+ "components": {+ "schemas": {+ "AddDeleteFeedbackReply": {+ "type": "object",+ "properties": {+ "message": {+ "type": "string"+ }+ },+ "required": [+ "message"+ ]+ },+ "AddDeleteFeedbackRequest": {+ "type": "object",+ "properties": {+ "email": {+ "type": "string"+ },+ "feedback": {+ "type": "string"+ }+ },+ "description": "AddDeleteFeedback",+ "required": [+ "email",+ "feedback"+ ]+ },+ "CheckAccountInFreezeReply": {+ "type": "object",+ "properties": {+ "data": {+ "type": "boolean",+ "description": "Keep the boolean data field for compatibility with dify-api clients."+ },+ "freezeType": {+ "enum": [+ "",+ "freeze",+ "email_domain_suspended"+ ],+ "type": "string"+ }+ },+ "required": [+ "data",+ "freezeType"+ ]+ },+ "DeleteAccountReply": {+ "type": "object",+ "properties": {+ "message": {+ "type": "string"+ }+ },+ "required": [+ "message"+ ]+ },+ "DismissNotificationReply": {+ "type": "object",+ "properties": {+ "success": {+ "type": "boolean"+ }+ },+ "required": [+ "success"+ ]+ },+ "DismissNotificationReq": {+ "type": "object",+ "properties": {+ "notificationId": {+ "type": "string"+ },+ "accountId": {+ "type": "string"+ }+ },+ "required": [+ "notificationId",+ "accountId"+ ]+ },+ "GetAccountNotificationReply": {+ "type": "object",+ "properties": {+ "shouldShow": {+ "type": "boolean",+ "description": "true when at least one notification is present."+ },+ "notifications": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/NotificationPayload"+ },+ "description": "All eligible notifications for this account, ordered newest first."+ }+ },+ "required": [+ "shouldShow",+ "notifications"+ ]+ },+ "LangContent": {+ "type": "object",+ "properties": {+ "lang": {+ "type": "string",+ "description": "Language tag: \"zh\" | \"en\" | \"jp\""+ },+ "title": {+ "type": "string"+ },+ "subtitle": {+ "type": "string"+ },+ "body": {+ "type": "string"+ },+ "titlePicUrl": {+ "type": "string"+ }+ },+ "description": "LangContent carries the notification content for a single language.\n The fields here mirror biz.LangContent; both must be kept in sync.",+ "required": [+ "lang",+ "title",+ "subtitle",+ "body",+ "titlePicUrl"+ ]+ },+ "NotificationPayload": {+ "type": "object",+ "properties": {+ "notificationId": {+ "type": "string"+ },+ "contents": {+ "type": "object",+ "additionalProperties": {+ "$ref": "#/components/schemas/LangContent"+ },+ "description": "All available language variants keyed by lang tag (\"zh\", \"en\", \"jp\").\n Frontend picks the appropriate language from this map."+ },+ "frequency": {+ "enum": [+ "once",+ "every_page_load"+ ],+ "type": "string",+ "description": "\"once\" | \"every_page_load\" — frontend uses this to decide re-display logic."+ },+ "isGlobal": {+ "type": "boolean"+ }+ },+ "required": [+ "notificationId",+ "contents",+ "frequency",+ "isGlobal"+ ]+ }+ }+ }+}diff --git a/api/services/billing_client/saas.py b/api/services/billing_client/saas.pynew file mode 100644index 00000000000..2a4ba1c58a2--- /dev/null+++ b/api/services/billing_client/saas.py@@ -0,0 +1,122 @@+# Code generated by api/dev/generate_billing_client.py from saas.openapi.json. DO NOT EDIT.+# dify-saas commit: a0b548cf3020d490a8b7fad21dfbb66b72fa0ed6++from typing import Literal++from pydantic import Field++from services.billing_client.transport import BillingModel, Upstream, request+++class AddDeleteFeedbackReply(BillingModel):+ message: str+++class AddDeleteFeedbackRequest(BillingModel):+ email: str+ feedback: str+++class CheckAccountInFreezeReply(BillingModel):+ data: bool+ freeze_type: Literal["", "freeze", "email_domain_suspended"] = Field(alias="freezeType")+++class DeleteAccountReply(BillingModel):+ message: str+++class DismissNotificationReply(BillingModel):+ success: bool+++class DismissNotificationReq(BillingModel):+ notification_id: str = Field(alias="notificationId")+ account_id: str = Field(alias="accountId")+++class LangContent(BillingModel):+ lang: str+ title: str+ subtitle: str+ body: str+ title_pic_url: str = Field(alias="titlePicUrl")+++class NotificationPayload(BillingModel):+ notification_id: str = Field(alias="notificationId")+ contents: dict[str, LangContent]+ frequency: Literal["once", "every_page_load"]+ is_global: bool = Field(alias="isGlobal")+++class GetAccountNotificationReply(BillingModel):+ should_show: bool = Field(alias="shouldShow")+ notifications: list[NotificationPayload]+++def account_delete_account(*, account_id: str) -> DeleteAccountReply:+ """DELETE /v1/account (Account_DeleteAccount)."""+ return request(+ Upstream.SAAS,+ "DELETE",+ "/account",+ response_model=DeleteAccountReply,+ path_params={},+ params={"accountId": account_id},+ body=None,+ )+++def account_check_account_in_freeze(*, email: str) -> CheckAccountInFreezeReply:+ """GET /v1/account/in-freeze (Account_CheckAccountInFreeze)."""+ return request(+ Upstream.SAAS,+ "GET",+ "/account/in-freeze",+ response_model=CheckAccountInFreezeReply,+ path_params={},+ params={"email": email},+ body=None,+ )+++def account_add_delete_feedback(*, body: AddDeleteFeedbackRequest) -> AddDeleteFeedbackReply:+ """POST /v1/account/delete-feedback (Account_AddDeleteFeedback)."""+ return request(+ Upstream.SAAS,+ "POST",+ "/account/delete-feedback",+ response_model=AddDeleteFeedbackReply,+ path_params={},+ params={},+ body=body,+ )+++def notification_get_account_notification(*, account_id: str) -> GetAccountNotificationReply:+ """GET /v1/notifications/active (SaasNotification_GetAccountNotification)."""+ return request(+ Upstream.SAAS,+ "GET",+ "/notifications/active",+ response_model=GetAccountNotificationReply,+ path_params={},+ params={"accountId": account_id},+ body=None,+ )+++def notification_dismiss_notification(+ *, notification_id: str, body: DismissNotificationReq+) -> DismissNotificationReply:+ """POST /v1/notifications/{notificationId}/dismiss (SaasNotification_DismissNotification)."""+ return request(+ Upstream.SAAS,+ "POST",+ "/notifications/{notification_id}/dismiss",+ response_model=DismissNotificationReply,+ path_params={"notification_id": notification_id},+ params={},+ body=body,+ )diff --git a/api/services/billing_client/transport.py b/api/services/billing_client/transport.pynew file mode 100644index 00000000000..d62a339496b--- /dev/null+++ b/api/services/billing_client/transport.py@@ -0,0 +1,96 @@+"""HTTP transport shared by the generated billing and saas operations.++Reuses the pooled client, auth header, and connection retry of `services.billing_service`.+Network failures, timeouts, throttling, and 5xx raise `BillingUpstreamUnavailableError`;+any other non-200 status or a body that fails model validation raises+`BillingUpstreamInvalidResponseError`.+"""++import os+from collections.abc import Mapping+from enum import StrEnum+from typing import Literal+from urllib.parse import quote++import httpx+from pydantic import BaseModel, ConfigDict, ValidationError+from tenacity import retry, retry_if_exception_type, stop_before_delay, wait_fixed++from core.helper.http_client_pooling import get_pooled_http_client+from services.errors.billing import BillingUpstreamInvalidResponseError, BillingUpstreamUnavailableError++type HTTPMethod = Literal["GET", "POST", "PUT", "DELETE"]+type QueryValue = str | int | float | bool | list[str]++_http_client: httpx.Client = get_pooled_http_client(+ "billing:default",+ lambda: httpx.Client(+ timeout=httpx.Timeout(30.0, connect=5.0),+ limits=httpx.Limits(max_keepalive_connections=50, max_connections=100),+ ),+)++_UNAVAILABLE_STATUSES = frozenset({httpx.codes.REQUEST_TIMEOUT, httpx.codes.TOO_MANY_REQUESTS})+++class Upstream(StrEnum):+ BILLING = "billing"+ BILLING_QUOTA = "billing_quota"+ SAAS = "saas"+++class BillingModel(BaseModel):+ """Base for generated models; unknown upstream fields are ignored and int64 strings coerce to int."""++ model_config = ConfigDict(extra="ignore", validate_by_name=True, validate_by_alias=True, serialize_by_alias=True)+++def _base_url(upstream: Upstream) -> str:+ billing_url = os.environ.get("BILLING_API_URL", "BILLING_API_URL")+ if upstream == Upstream.BILLING_QUOTA:+ return os.environ.get("BILLING_QUOTA_API_URL") or billing_url+ return billing_url+++@retry(+ wait=wait_fixed(2),+ stop=stop_before_delay(10),+ retry=retry_if_exception_type(httpx.RequestError),+ reraise=True,+)+def _send(method: HTTPMethod, url: str, *, params: Mapping[str, QueryValue], json: object | None) -> httpx.Response:+ headers = {+ "Content-Type": "application/json",+ "Billing-Api-Secret-Key": os.environ.get("BILLING_API_SECRET_KEY", "BILLING_API_SECRET_KEY"),+ }+ return _http_client.request(method, url, params=params, json=json, headers=headers, follow_redirects=True)+++def request[ResponseT: BillingModel](+ upstream: Upstream,+ method: HTTPMethod,+ path: str,+ *,+ response_model: type[ResponseT],+ path_params: Mapping[str, str],+ params: Mapping[str, QueryValue],+ body: BillingModel | None,+) -> ResponseT:+ resolved_path = path.format_map({name: quote(value, safe="") for name, value in path_params.items()})+ url = f"{_base_url(upstream)}{resolved_path}"+ json = body.model_dump(mode="json") if body is not None else None+ try:+ response = _send(method, url, params=params, json=json)+ except httpx.RequestError as error:+ raise BillingUpstreamUnavailableError(f"{method} {path} failed") from error++ if response.status_code != httpx.codes.OK:+ message = f"{method} {path} returned {response.status_code}"+ if response.status_code in _UNAVAILABLE_STATUSES or response.status_code >= 500:+ raise BillingUpstreamUnavailableError(message)+ raise BillingUpstreamInvalidResponseError(message)++ try:+ return response_model.model_validate_json(response.content)+ except ValidationError as error:+ raise BillingUpstreamInvalidResponseError(f"{method} {path} returned an invalid body") from errordiff --git a/api/tests/unit_tests/dev/test_generate_billing_client.py b/api/tests/unit_tests/dev/test_generate_billing_client.pynew file mode 100644index 00000000000..f85ebbe6cfe--- /dev/null+++ b/api/tests/unit_tests/dev/test_generate_billing_client.py@@ -0,0 +1,119 @@+import pytest++from dev import generate_billing_client as generator++PREFIX = "#/components/schemas/dify.saas.api.billing."+++def _source_spec() -> generator.JsonObject:+ reply = {"$ref": f"{PREFIX}GetSubscriptionInfoReply"}+ return {+ "openapi": "3.0.3",+ "info": {"title": "", "version": "0.0.1"},+ "paths": {+ "/v1/subscription/info": {+ "get": {+ "operationId": "BillingSubscription_GetSubscriptionInfo",+ "responses": {"200": {"content": {"application/json": {"schema": reply}}}},+ }+ },+ "/v1/coupons/stripe": {+ "get": {+ "operationId": "BillingCoupon_ListStripeCoupons",+ "responses": {+ "200": {"content": {"application/json": {"schema": {"$ref": f"{PREFIX}ListCouponsReply"}}}}+ },+ }+ },+ },+ "components": {+ "schemas": {+ "dify.saas.api.billing.GetSubscriptionInfoReply": {+ "type": "object",+ "properties": {+ "plan": {"type": "string", "enum": ["sandbox", "team"]},+ "paid_period_end": {"type": "string", "format": "int64"},+ "members": {"$ref": f"{PREFIX}Quota"},+ "usage_unknown": {"type": "boolean", "nullable": True},+ "tags": {"type": "array", "items": {"type": "string"}},+ },+ },+ "dify.saas.api.billing.Quota": {"type": "object", "properties": {"limit": {"type": "integer"}}},+ "dify.saas.api.billing.ListCouponsReply": {+ "type": "object",+ "properties": {"coupon_id": {"type": "string"}},+ },+ }+ },+ }+++def subscription_info_only(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setitem(+ generator.ALLOWED_OPERATIONS,+ "billing",+ (generator.AllowedOperation("GET", "/v1/subscription/info", "BILLING"),),+ )++[email protected]("subscription_info_only")+def test_snapshot_keeps_only_allowlisted_operations_and_reachable_schemas() -> None:+ snapshot = generator.build_snapshot("billing", _source_spec(), "abc123")++ assert snapshot[generator.SNAPSHOT_COMMIT_KEY] == "abc123"+ assert list(snapshot["paths"]) == ["/v1/subscription/info"]+ assert sorted(snapshot["components"]["schemas"]) == ["GetSubscriptionInfoReply", "Quota"]+ assert "coupon" not in generator.render_snapshot(snapshot).lower()++[email protected]("subscription_info_only")+def test_snapshot_marks_presence_from_protojson_rules() -> None:+ schema = generator.build_snapshot("billing", _source_spec(), "abc123")["components"]["schemas"][+ "GetSubscriptionInfoReply"+ ]++ # Proto3 optional fields are omitted when unset, so only they stay out of required.+ assert schema["required"] == ["plan", "paid_period_end", "members", "tags"]+ assert schema["properties"]["members"] == {"allOf": [{"$ref": "#/components/schemas/Quota"}], "nullable": True}+ assert "nullable" not in schema["properties"]["plan"]++[email protected]("subscription_info_only")+def test_rendered_module_types_fields_and_operations() -> None:+ snapshot = generator.build_snapshot("billing", _source_spec(), "abc123")++ source = generator.render_module("billing", snapshot)++ assert 'plan: Literal["sandbox", "team"]' in source+ assert "paid_period_end: int\n" in source+ assert "members: Quota | None\n" in source+ assert "usage_unknown: bool | None = None\n" in source+ assert "def subscription_get_subscription_info() -> GetSubscriptionInfoReply:" in source+ assert '"/subscription/info",' in source++[email protected]("subscription_info_only")+def test_upstream_required_message_field_is_non_null() -> None:+ source = _source_spec()+ source["components"]["schemas"]["dify.saas.api.billing.GetSubscriptionInfoReply"]["required"] = ["members"]++ snapshot = generator.build_snapshot("billing", source, "abc123")+ schema = snapshot["components"]["schemas"]["GetSubscriptionInfoReply"]++ assert schema["properties"]["members"] == {"$ref": "#/components/schemas/Quota"}+ assert schema["required"] == ["plan", "paid_period_end", "members", "tags"]+ assert "members: Quota\n" in generator.render_module("billing", snapshot)++[email protected]("subscription_info_only")+def test_snapshot_rejects_allowlisted_operation_missing_from_spec() -> None:+ source = _source_spec()+ del source["paths"]["/v1/subscription/info"]++ with pytest.raises(generator.GenerationError, match="not in the dify-saas spec"):+ generator.build_snapshot("billing", source, "abc123")+++def test_committed_client_matches_snapshots() -> None:+ assert generator.check(generator.expected_files({s: generator.load_snapshot(s) for s in generator.SERVICES})) == 0diff --git a/api/tests/unit_tests/services/billing_client/__init__.py b/api/tests/unit_tests/services/billing_client/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/api/tests/unit_tests/services/billing_client/conftest.py b/api/tests/unit_tests/services/billing_client/conftest.pynew file mode 100644index 00000000000..d72a59e2be7--- /dev/null+++ b/api/tests/unit_tests/services/billing_client/conftest.py@@ -0,0 +1,31 @@+from collections.abc import Callable++import httpx+import pytest++from services.billing_client import transport++type RespondWith = Callable[[httpx.Response], list[httpx.Request]]++[email protected](autouse=True)+def billing_env(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("BILLING_API_URL", "http://billing/v1")+ monkeypatch.setenv("BILLING_QUOTA_API_URL", "http://quota/v1")+ monkeypatch.setenv("BILLING_API_SECRET_KEY", "secret")+++def respond_with(monkeypatch: pytest.MonkeyPatch) -> RespondWith:+ """Route the pooled billing client to a MockTransport that answers every request with `response`."""+ requests: list[httpx.Request] = []++ def install(response: httpx.Response) -> list[httpx.Request]:+ def handler(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ return response++ monkeypatch.setattr(transport, "_http_client", httpx.Client(transport=httpx.MockTransport(handler)))+ return requests++ return installdiff --git a/api/tests/unit_tests/services/billing_client/test_billing.py b/api/tests/unit_tests/services/billing_client/test_billing.pynew file mode 100644index 00000000000..6fb0b5aa82e--- /dev/null+++ b/api/tests/unit_tests/services/billing_client/test_billing.py@@ -0,0 +1,59 @@+import httpx+import pytest++from services.billing_client import billing+from services.errors.billing import BillingUpstreamInvalidResponseError+from tests.unit_tests.services.billing_client.conftest import RespondWith+++def test_response_coerces_int64_strings_and_ignores_unknown_fields(respond_with: RespondWith) -> None:+ requests = respond_with(+ httpx.Response(+ 200,+ json={+ "available": "9007199254740993",+ "reserved": 0,+ "quota": "5",+ "usage": 1,+ "exhausted_at": "0",+ "added_later": True,+ },+ )+ )++ balance = billing.quota_get_balance(tenant_id="t1", feature_key="api_rate_limit", bucket="")++ assert balance.available == 9007199254740993+ assert balance.quota == 5+ assert str(requests[0].url) == "http://quota/v1/quota/balance?tenant_id=t1&feature_key=api_rate_limit&bucket="+ assert requests[0].headers["Billing-Api-Secret-Key"] == "secret"+++def test_request_body_is_serialized_from_the_model(respond_with: RespondWith) -> None:+ requests = respond_with(httpx.Response(200, json={"reservation_id": "r1", "available": "1", "reserved": "1"}))+ body = billing.QuotaReserveReq(+ tenant_id="t1", feature_key="trigger_event", request_id="req", amount=2, meta={}, bucket=""+ )++ billing.quota_reserve(body=body)++ assert requests[0].method == "POST"+ assert str(requests[0].url) == "http://quota/v1/quota/reserve"+ assert body.model_validate_json(requests[0].content) == body+++def test_missing_required_field_is_an_invalid_response(respond_with: RespondWith) -> None:+ respond_with(httpx.Response(200, json={"available": "1"}))++ with pytest.raises(BillingUpstreamInvalidResponseError):+ billing.quota_get_balance(tenant_id="t1", feature_key="api_rate_limit", bucket="")+++def test_omitted_optional_field_parses_as_none(respond_with: RespondWith) -> None:+ respond_with(httpx.Response(200, json={"size": 1.25, "limit": "50"}))++ quota = billing.subscription_get_subscription_vector_space(tenant_id="t1", bypass_cache=False)++ assert quota.size == 1.25+ assert quota.limit == 50+ assert quota.usage_unknown is Nonediff --git a/api/tests/unit_tests/services/billing_client/test_saas.py b/api/tests/unit_tests/services/billing_client/test_saas.pynew file mode 100644index 00000000000..123a1443539--- /dev/null+++ b/api/tests/unit_tests/services/billing_client/test_saas.py@@ -0,0 +1,17 @@+import httpx++from services.billing_client import saas+from tests.unit_tests.services.billing_client.conftest import RespondWith+++def test_path_params_are_percent_encoded_and_body_uses_wire_names(respond_with: RespondWith) -> None:+ requests = respond_with(httpx.Response(200, json={"success": True}))++ reply = saas.notification_dismiss_notification(+ notification_id="a/b c", body=saas.DismissNotificationReq(notification_id="a/b c", account_id="acc")+ )++ assert reply.success is True+ assert str(requests[0].url) == "http://billing/v1/notifications/a%2Fb%20c/dismiss"+ assert requests[0].url.raw_path == b"/v1/notifications/a%2Fb%20c/dismiss"+ assert b'"accountId"' in requests[0].contentdiff --git a/api/tests/unit_tests/services/billing_client/test_transport.py b/api/tests/unit_tests/services/billing_client/test_transport.pynew file mode 100644index 00000000000..1e8e1ae39e2--- /dev/null+++ b/api/tests/unit_tests/services/billing_client/test_transport.py@@ -0,0 +1,87 @@+import httpx+import pytest+import tenacity++from services.billing_client import transport+from services.billing_client.transport import BillingModel, Upstream+from services.errors.billing import BillingUpstreamInvalidResponseError, BillingUpstreamUnavailableError+from tests.unit_tests.services.billing_client.conftest import RespondWith+++class _Reply(BillingModel):+ ok: bool+++class _VirtualClock:+ """Advance tenacity's clock instead of sleeping, keeping the production retry policy."""++ def __init__(self) -> None:+ self.elapsed = 0.0+ self.sleeps: list[float] = []++ def monotonic(self) -> float:+ return self.elapsed++ def sleep(self, seconds: float) -> None:+ self.sleeps.append(seconds)+ self.elapsed += seconds+++def _get(upstream: Upstream) -> _Reply:+ return transport.request(upstream, "GET", "/probe", response_model=_Reply, path_params={}, params={}, body=None)+++ ("status", "error"),+ [+ (400, BillingUpstreamInvalidResponseError),+ (408, BillingUpstreamUnavailableError),+ (429, BillingUpstreamUnavailableError),+ (503, BillingUpstreamUnavailableError),+ ],+)+def test_non_ok_status_maps_to_upstream_errors(respond_with: RespondWith, status: int, error: type[Exception]) -> None:+ respond_with(httpx.Response(status, json={}))++ with pytest.raises(error):+ _get(Upstream.BILLING)+++def test_request_error_is_retried_then_unavailable(monkeypatch: pytest.MonkeyPatch) -> None:+ attempts: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ attempts.append(request)+ raise httpx.ConnectError("connection refused", request=request)++ clock = _VirtualClock()+ # Replace tenacity's module reference, not the process-wide time module.+ monkeypatch.setattr(tenacity, "time", clock)+ monkeypatch.setattr("services.billing_client.transport._send.retry.sleep", clock.sleep)+ monkeypatch.setattr(transport, "_http_client", httpx.Client(transport=httpx.MockTransport(handler)))++ with pytest.raises(BillingUpstreamUnavailableError):+ _get(Upstream.BILLING)++ # The next two-second wait would reach the ten-second stop boundary.+ assert len(attempts) == 5+ assert clock.sleeps == [2, 2, 2, 2]+++ ("upstream", "quota_url", "expected"),+ [+ (Upstream.BILLING, "http://quota/v1", "http://billing/v1/probe"),+ (Upstream.SAAS, "http://quota/v1", "http://billing/v1/probe"),+ (Upstream.BILLING_QUOTA, "http://quota/v1", "http://quota/v1/probe"),+ (Upstream.BILLING_QUOTA, "", "http://billing/v1/probe"),+ ],+)+def test_upstream_selects_base_url(+ monkeypatch: pytest.MonkeyPatch, respond_with: RespondWith, upstream: Upstream, quota_url: str, expected: str+) -> None:+ monkeypatch.setenv("BILLING_QUOTA_API_URL", quota_url)+ requests = respond_with(httpx.Response(200, json={"ok": True}))++ assert _get(upstream).ok is True+ assert str(requests[0].url) == expecteddiff --git a/api/tests/unit_tests/services/test_conversation_query_service.py b/api/tests/unit_tests/services/test_conversation_query_service.pyindex 2e5e9b2a49c..758eb5d7e73 100644--- a/api/tests/unit_tests/services/test_conversation_query_service.py+++ b/api/tests/unit_tests/services/test_conversation_query_service.py@@ -17,7 +17,7 @@ from pydantic import JsonValuefrom sqlalchemy import Connection, Engine, event, selectfrom sqlalchemy.orm import Session, SessionTransaction, sessionmaker-from core.helper.http_client_pooling import close_all_pooled_clients+from core.helper import http_client_poolingfrom core.tools.signature import verify_tool_file_signaturefrom core.workflow.file_reference import build_file_reference, resolve_file_record_idfrom extensions.storage.storage_type import StorageType@@ -376,7 +376,7 @@ def test_console_invalid_file_metadata_fails_after_connection_release(@pytest.fixture-def _file_configuration(config_overrides: Callable[..., None]) -> Iterator[None]:+def _file_configuration(config_overrides: Callable[..., None], monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:config_overrides(FILES_URL="https://files.example.test",SECRET_KEY="conversation-detail-file-test",@@ -384,9 +384,11 @@ def _file_configuration(config_overrides: Callable[..., None]) -> Iterator[None]SSRF_PROXY_HTTPS_URL="",SSRF_PROXY_ALL_URL="",)- close_all_pooled_clients()+ # A private pool picks up the overrides without closing clients other modules hold at import time.+ http_pool = http_client_pooling.HttpClientPoolFactory()+ monkeypatch.setattr(http_client_pooling, "_factory", http_pool)yield- close_all_pooled_clients()+ http_pool.close_all()@dataclass(frozen=True)