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
refactor(api): call billing education, compliance, account and notification APIs through the generated client (#45136)
yyh4612a807fe17
diff --git a/api/controllers/console/notification.py b/api/controllers/console/notification.pyindex 03ebbc2ba6d..facd47fa05e 100644--- a/api/controllers/console/notification.py+++ b/api/controllers/console/notification.py@@ -1,3 +1,5 @@+from typing import Literal+from flask_restx import Resourcefrom pydantic import BaseModel, Field@@ -22,8 +24,8 @@ class NotificationQuery(BaseModel):class NotificationItemResponse(ResponseModel):- notification_id: str | None = None- frequency: str | None = None+ notification_id: str+ frequency: Literal["once", "every_page_load"]lang: strtitle: strsubtitle: strdiff --git a/api/controllers/console/workspace/account.py b/api/controllers/console/workspace/account.pyindex 253efff4bfb..772b78ff6d7 100644--- a/api/controllers/console/workspace/account.py+++ b/api/controllers/console/workspace/account.py@@ -204,7 +204,7 @@ class AccountIntegrateListResponse(ResponseModel):class EducationVerifyResponse(ResponseModel):- token: str | None = None+ token: strclass EducationActivateResponse(ResponseModel):@@ -212,10 +212,10 @@ class EducationActivateResponse(ResponseModel):class EducationStatusResponse(ResponseModel):- result: bool | None = None- is_student: bool | None = None- expire_at: int | None = None- allow_refresh: bool | None = None+ result: bool+ is_student: bool+ expire_at: int | None+ allow_refresh: bool@field_validator("expire_at", mode="before")@classmethod@@ -224,9 +224,9 @@ class EducationStatusResponse(ResponseModel):class EducationAutocompleteResponse(ResponseModel):- data: list[str] = Field(default_factory=list)- curr_page: int | None = None- has_next: bool | None = None+ data: list[str]+ curr_page: int+ has_next: boolregister_response_schema_models(diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.mdindex f4ed82655fb..2ce595e7631 100644--- a/api/openapi/markdown/console-openapi.md+++ b/api/openapi/markdown/console-openapi.md@@ -25393,9 +25393,9 @@ Rate limit exceeded| Name | Type | Description | Required || ---- | ---- | ----------- | -------- |-| curr_page | integer | | No |-| data | [ string ] | | No |-| has_next | boolean | | No |+| curr_page | integer | | Yes |+| data | [ string ] | | Yes |+| has_next | boolean | | Yes |#### EducationModel@@ -25408,10 +25408,10 @@ Rate limit exceeded| Name | Type | Description | Required || ---- | ---- | ----------- | -------- |-| allow_refresh | boolean | | No |-| expire_at | integer | | No |-| is_student | boolean | | No |-| result | boolean | | No |+| allow_refresh | boolean | | Yes |+| expire_at | integer | | Yes |+| is_student | boolean | | Yes |+| result | boolean | | Yes |#### EducationVerifyLimitError@@ -25425,7 +25425,7 @@ Rate limit exceeded| Name | Type | Description | Required || ---- | ---- | ----------- | -------- |-| token | string | | No |+| token | string | | Yes |#### EmailAlreadyInUseError@@ -31540,9 +31540,9 @@ Only support workflow app.| Name | Type | Description | Required || ---- | ---- | ----------- | -------- || body | string | | Yes |-| frequency | string | | No |+| frequency | string, <br>**Available values:** "every_page_load", "once" | *Enum:* `"every_page_load"`, `"once"` | Yes || lang | string | | Yes |-| notification_id | string | | No |+| notification_id | string | | Yes || subtitle | string | | Yes || title | string | | Yes || title_pic_url | string | | Yes |diff --git a/api/services/account/adapters.py b/api/services/account/adapters.pyindex 3cf720dfb94..364305c70a1 100644--- a/api/services/account/adapters.py+++ b/api/services/account/adapters.py@@ -268,8 +268,8 @@ class RBACWorkspaceMemberAccessSync(WorkspaceMemberAccessSync):class BillingAccountEducationGateway(AccountEducationGateway):@overridedef verify(self, *, account_id: str) -> AccountEducationVerification:- result = BillingService.EducationIdentity.verify(account_id=account_id) or {}- return AccountEducationVerification(token=result.get("token"))+ result = BillingService.EducationIdentity.verify(account_id=account_id)+ return AccountEducationVerification(token=result.token)@overridedef activate(@@ -288,26 +288,26 @@ class BillingAccountEducationGateway(AccountEducationGateway):institution=institution,role=role,)- return AccountEducationActivation(message=result["message"])+ return AccountEducationActivation(message=result.message)@overridedef status(self, account_id: str) -> AccountEducationStatus:- result = BillingService.EducationIdentity.status(account_id) or {}- expire_at = result.get("expire_at")+ result = BillingService.EducationIdentity.status(account_id)+ expire_at = result.expire_atreturn AccountEducationStatus(- result=result.get("result"),- is_student=result.get("is_student"),- expire_at=datetime.fromisoformat(expire_at).astimezone(UTC) if isinstance(expire_at, str) else expire_at,- allow_refresh=result.get("allow_refresh"),+ result=result.result,+ is_student=result.is_student,+ expire_at=datetime.fromisoformat(expire_at).astimezone(UTC) if expire_at else None,+ allow_refresh=result.allow_refresh,)@overridedef autocomplete(self, *, keywords: str, page: int, limit: int) -> AccountEducationAutocomplete:- result = BillingService.EducationIdentity.autocomplete(keywords, page, limit) or {}+ result = BillingService.EducationIdentity.autocomplete(keywords, page, limit)return AccountEducationAutocomplete(- data=tuple(result.get("data") or ()),- curr_page=result.get("curr_page"),- has_next=result.get("has_next"),+ data=tuple(result.data or ()),+ curr_page=result.curr_page,+ has_next=result.has_next,)diff --git a/api/services/billing_client/transport.py b/api/services/billing_client/transport.pyindex ba5fe2406fc..f7c08c930d3 100644--- a/api/services/billing_client/transport.py+++ b/api/services/billing_client/transport.py@@ -42,6 +42,7 @@ ENFORCED_RESPONSE_PATHS: frozenset[str] = frozenset("/subscription/cleanup/whitelist","/model-provider/payment-link","/invoices",+ "/compliance/download","/quota/info","/quota/reserve","/quota/commit",diff --git a/api/services/billing_service.py b/api/services/billing_service.pyindex 660e0a40e03..4a515834950 100644--- a/api/services/billing_service.py+++ b/api/services/billing_service.py@@ -1,94 +1,21 @@-import jsonimport loggingimport osfrom collections.abc import Mapping, Sequence-from typing import Any, Literal, TypedDict+from typing import Literalfrom warnings import deprecated-import httpx-from pydantic import TypeAdapter, ValidationError-from tenacity import retry, retry_if_exception_type, stop_before_delay, wait_fixed-from werkzeug.exceptions import InternalServerError+from pydantic import ValidationError-from core.helper.http_client_pooling import get_pooled_http_clientfrom extensions.ext_redis import redis_client-from services.billing_client import billing+from services.billing_client import billing, saasfrom services.billing_portal_service import BillingPortalLinkfrom services.compliance_download_service import ComplianceDownloadLink-from services.errors.billing import (- BillingUpstreamInvalidResponseError,- BillingUpstreamUnavailableError,-)logger = logging.getLogger(__name__)-_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),- ),-)--EmailFreezeType = Literal["freeze", "email_domain_suspended"]-class _BillingHTTPStatusError(ValueError):- def __init__(self, message: str, status_code: int) -> None:- super().__init__(message)- self.status_code = status_code---class MessageResponseDict(TypedDict):- message: str---class EducationVerifyResponseDict(TypedDict):- token: str---class EducationStatusResponseDict(TypedDict):- result: bool- is_student: bool- expire_at: str- allow_refresh: bool---class EducationAutocompleteResponseDict(TypedDict):- data: list[str]- curr_page: int- has_next: bool---_compliance_download_link_adapter = TypeAdapter(ComplianceDownloadLink)---class LangContentDict(TypedDict):- lang: str- title: str- subtitle: str- body: str- title_pic_url: str---class NotificationDict(TypedDict):- notification_id: str- contents: dict[str, LangContentDict]- frequency: Literal["once", "every_page_load"]---class AccountNotificationDict(TypedDict, total=False):- should_show: bool- notification: NotificationDict- shouldShow: bool- notifications: list[dict]---class DismissNotificationDict(TypedDict):- success: bool--def _quota_meta(meta: Mapping[str, object] | None) -> dict[str, str]:"""The spec types quota metadata as a string map."""return {key: value if isinstance(value, str) else str(value) for key, value in (meta or {}).items()}@@ -231,89 +158,40 @@ class BillingService:return {"url": reply.url}@classmethod- @retry(- wait=wait_fixed(2),- stop=stop_before_delay(10),- retry=retry_if_exception_type(httpx.RequestError),- reraise=True,- )- def _send_request(- cls,- method: Literal["GET", "POST", "DELETE", "PUT"],- endpoint: str,- json=None,- params=None,- base_url: str | None = None,- ) -> Any:- headers = {"Content-Type": "application/json", "Billing-Api-Secret-Key": cls.secret_key}- url = f"{base_url or cls.base_url}{endpoint}"- response = _http_client.request(method, url, json=json, params=params, headers=headers, follow_redirects=True)- if method == "GET" and response.status_code != httpx.codes.OK:- raise _BillingHTTPStatusError(- "Unable to retrieve billing information. Please try again later or contact support.",- response.status_code,- )- if method == "PUT":- if response.status_code == httpx.codes.INTERNAL_SERVER_ERROR:- raise InternalServerError(- "Unable to process billing request. Please try again later or contact support."- )- if response.status_code != httpx.codes.OK:- raise ValueError("Invalid arguments.")- if method == "POST" and response.status_code != httpx.codes.OK:- raise _BillingHTTPStatusError(- f"Unable to send request to {url}. Please try again later or contact support.",- response.status_code,- )- if method == "DELETE" and response.status_code != httpx.codes.OK:- logger.error("billing_service: DELETE response: %s %s", response.status_code, response.text)- raise ValueError(f"Unable to process delete request {url}. Please try again later or contact support.")- return response.json()-- @classmethod- def delete_account(cls, account_id: str) -> MessageResponseDict:- """Delete account."""- params = {"account_id": account_id}- return cls._send_request("DELETE", "/account", params=params)+ def delete_account(cls, account_id: str) -> saas.DeleteAccountReply:+ return saas.account_delete_account(account_id=account_id)@classmethoddef get_email_freeze_type(cls, email: str) -> EmailFreezeType | None:- params = {"email": email}try:- response = cls._send_request("GET", "/account/in-freeze", params=params)- if not response.get("data", False):- return None-- freeze_type = response.get("freeze_type") or response.get("freezeType")- if freeze_type in ("freeze", "email_domain_suspended"):- return freeze_type-- # Keep compatibility with older billing services that only return- # the boolean `data` field.- return "freeze"+ reply = saas.account_check_account_in_freeze(email=email)except Exception:return None+ if not reply.data:+ return None+ match reply.freeze_type:+ case "freeze" | "email_domain_suspended" as freeze_type:+ return freeze_type+ case _:+ # Billing versions that only return the boolean `data` send an empty freeze type.+ return "freeze"@classmethoddef is_email_in_freeze(cls, email: str) -> bool:return cls.get_email_freeze_type(email) is not None@classmethod- def update_account_deletion_feedback(cls, email: str, feedback: str) -> MessageResponseDict:- """Update account deletion feedback."""- json = {"email": email, "feedback": feedback}- return cls._send_request("POST", "/account/delete-feedback", json=json)+ def update_account_deletion_feedback(cls, email: str, feedback: str) -> saas.AddDeleteFeedbackReply:+ return saas.account_add_delete_feedback(body=saas.AddDeleteFeedbackRequest(email=email, feedback=feedback))class EducationIdentity:@classmethod- def verify(cls, account_id: str) -> EducationVerifyResponseDict:- params = {"account_id": account_id}- return BillingService._send_request("GET", "/education/verify", params=params)+ def verify(cls, account_id: str) -> billing.VerifyEducationIdentityReply:+ return billing.education_verify_education_identity(account_id=account_id)@classmethod- def status(cls, account_id: str) -> EducationStatusResponseDict:- params = {"account_id": account_id}- return BillingService._send_request("GET", "/education/status", params=params)+ def status(cls, account_id: str) -> billing.GetEducationIdentityStatusReply:+ return billing.education_get_education_identity_status(account_id=account_id)@classmethoddef activate(@@ -324,19 +202,18 @@ class BillingService:token: str,institution: str,role: str,- ) -> MessageResponseDict:- params = {"account_id": account_id, "curr_tenant_id": tenant_id}- json = {- "institution": institution,- "token": token,- "role": role,- }- return BillingService._send_request("POST", "/education/", json=json, params=params)+ ) -> billing.CreateEducationIdentityReply:+ return billing.education_create_education_identity(+ body=billing.CreateEducationIdentityReq(+ account_id=account_id, curr_tenant_id=tenant_id, institution=institution, role=role, token=token+ )+ )@classmethod- def autocomplete(cls, keywords: str, page: int = 0, limit: int = 20) -> EducationAutocompleteResponseDict:- params = {"keywords": keywords, "page": page, "limit": limit}- return BillingService._send_request("GET", "/education/autocomplete", params=params)+ def autocomplete(+ cls, keywords: str, page: int = 0, limit: int = 20+ ) -> billing.AutocompleteEducationInstitutionReply:+ return billing.education_autocomplete_education_institution(keywords=keywords, page=page, limit=limit)@classmethoddef get_compliance_download_link(@@ -347,30 +224,12 @@ class BillingService:ip: str,device_info: str,) -> ComplianceDownloadLink:- payload = {- "doc_name": doc_name,- "account_id": account_id,- "tenant_id": tenant_id,- "ip_address": ip,- "device_info": device_info,- }- try:- response = cls._send_request("POST", "/compliance/download", json=payload)- result = _compliance_download_link_adapter.validate_python(response)- except _BillingHTTPStatusError as error:- if error.status_code in {httpx.codes.REQUEST_TIMEOUT, httpx.codes.TOO_MANY_REQUESTS} or (- error.status_code >= 500- ):- raise BillingUpstreamUnavailableError from error- raise BillingUpstreamInvalidResponseError from error- except httpx.RequestError as error:- raise BillingUpstreamUnavailableError from error- except (json.JSONDecodeError, UnicodeDecodeError, ValidationError) as error:- raise BillingUpstreamInvalidResponseError from error- except ValueError as error:- raise RuntimeError("Unexpected billing service value error") from error-- return result+ reply = billing.compliance_download_compliance_document(+ body=billing.DownloadComplianceDocumentReq(+ doc_name=doc_name, account_id=account_id, tenant_id=tenant_id, ip_address=ip, device_info=device_info+ )+ )+ return {"url": reply.url}@classmethoddef clean_billing_info_cache(cls, tenant_id: str) -> None:@@ -498,35 +357,13 @@ class BillingService:return [item.tenant_id for item in reply.data or []]@classmethod- def get_account_notification(cls, account_id: str) -> AccountNotificationDict:- """Return the active in-product notification for account_id, if any.-- Calling this endpoint also marks the notification as seen; subsequent- calls will return should_show=false when frequency='once'.-- Response shape (mirrors GetAccountNotificationReply):- {- "should_show": bool,- "notification": { # present only when should_show=true- "notification_id": str,- "contents": { # lang -> LangContent- "en": {"lang": "en", "title": ..., "subtitle": ..., "body": ..., "title_pic_url": ...},- ...- },- "frequency": "once" | "every_page_load"- }- }- """- return cls._send_request("GET", "/notifications/active", params={"account_id": account_id})+ def get_account_notification(cls, account_id: str) -> saas.GetAccountNotificationReply:+ """Return the active in-product notifications; fetching marks `once` notifications as seen."""+ return saas.notification_get_account_notification(account_id=account_id)@classmethod- def dismiss_notification(cls, notification_id: str, account_id: str) -> DismissNotificationDict:- """Mark a notification as dismissed for an account.-- Returns {"success": bool}.- """- return cls._send_request(- "POST",- f"/notifications/{notification_id}/dismiss",- json={"account_id": account_id},+ def dismiss_notification(cls, notification_id: str, account_id: str) -> saas.DismissNotificationReply:+ return saas.notification_dismiss_notification(+ notification_id=notification_id,+ body=saas.DismissNotificationReq(notification_id=notification_id, account_id=account_id),)diff --git a/api/services/entities/account_entities.py b/api/services/entities/account_entities.pyindex abd500a1bec..cbd9f7355c3 100644--- a/api/services/entities/account_entities.py+++ b/api/services/entities/account_entities.py@@ -239,7 +239,7 @@ type AccountChangeEmailTokenData = (@dataclass(frozen=True, slots=True)class AccountEducationVerification:- token: str | None+ token: str@dataclass(frozen=True, slots=True)@@ -249,14 +249,14 @@ class AccountEducationActivation:@dataclass(frozen=True, slots=True)class AccountEducationStatus:- result: bool | None- is_student: bool | None+ result: bool+ is_student: boolexpire_at: datetime | None- allow_refresh: bool | None+ allow_refresh: bool@dataclass(frozen=True, slots=True)class AccountEducationAutocomplete:data: tuple[str, ...]- curr_page: int | None- has_next: bool | None+ curr_page: int+ has_next: booldiff --git a/api/services/entities/notification_entities.py b/api/services/entities/notification_entities.pyindex 6686c5edb99..39ff578f51c 100644--- a/api/services/entities/notification_entities.py+++ b/api/services/entities/notification_entities.py@@ -1,7 +1,9 @@"""Framework-independent notification contracts."""from collections.abc import Mapping-from typing import NamedTuple+from typing import Literal, NamedTuple++type NotificationFrequency = Literal["once", "every_page_load"]class NotificationContent(NamedTuple):@@ -13,8 +15,8 @@ class NotificationContent(NamedTuple):class AccountNotification(NamedTuple):- notification_id: str | None- frequency: str | None+ notification_id: str+ frequency: NotificationFrequencycontents: Mapping[str, NotificationContent]@@ -24,8 +26,8 @@ class AccountNotificationBatch(NamedTuple):class NotificationItem(NamedTuple):- notification_id: str | None- frequency: str | None+ notification_id: str+ frequency: NotificationFrequencylang: strtitle: strsubtitle: strdiff --git a/api/services/notification_gateway.py b/api/services/notification_gateway.pyindex cb7cc5e74d0..7a25bcdddcb 100644--- a/api/services/notification_gateway.py+++ b/api/services/notification_gateway.py@@ -1,8 +1,8 @@"""Billing-backed notification gateway."""-from collections.abc import Mapping-from typing import Any, override+from typing import override+from services.billing_client import saasfrom services.billing_service import BillingServicefrom services.entities.notification_entities import (AccountNotification,@@ -15,11 +15,10 @@ from services.notification_service import NotificationGatewayclass BillingNotificationGateway(NotificationGateway):@overridedef get_active(self, account_id: str) -> AccountNotificationBatch:- payload = BillingService.get_account_notification(account_id)- notifications = tuple(self._map_notification(item) for item in payload.get("notifications") or ())+ reply = BillingService.get_account_notification(account_id)return AccountNotificationBatch(- should_show=bool(payload.get("shouldShow")),- notifications=notifications,+ should_show=bool(reply.should_show),+ notifications=tuple(self._map_notification(item) for item in reply.notifications or ()),)@override@@ -27,22 +26,26 @@ class BillingNotificationGateway(NotificationGateway):BillingService.dismiss_notification(notification_id=notification_id, account_id=account_id)@classmethod- def _map_notification(cls, payload: Mapping[str, Any]) -> AccountNotification:- raw_contents = payload.get("contents") or {}- contents = {language: cls._map_content(content) for language, content in raw_contents.items() if content}+ def _map_notification(cls, payload: saas.NotificationPayload) -> AccountNotification:+ """Accept observed upstream models; omit translations with no non-null fields to allow language fallback."""+ contents = {+ language: cls._map_content(content)+ for language, content in (payload.contents or {}).items()+ if content and content.model_dump(exclude_none=True, warnings=False)+ }return AccountNotification(- notification_id=payload.get("notificationId"),- frequency=payload.get("frequency"),+ notification_id=payload.notification_id,+ frequency=payload.frequency,contents=contents,)@staticmethod- def _map_content(payload: Mapping[str, Any]) -> NotificationContent:+ def _map_content(payload: saas.LangContent) -> NotificationContent:return NotificationContent(# The application service owns the requested-language fallback.- lang=payload.get("lang") or "",- title=payload.get("title") or "",- subtitle=payload.get("subtitle") or "",- body=payload.get("body") or "",- title_pic_url=payload.get("titlePicUrl") or "",+ lang=payload.lang or "",+ title=payload.title or "",+ subtitle=payload.subtitle or "",+ body=payload.body or "",+ title_pic_url=payload.title_pic_url or "",)diff --git a/api/tests/unit_tests/services/account/test_adapters.py b/api/tests/unit_tests/services/account/test_adapters.pyindex 381088f91f8..042fb72e98d 100644--- a/api/tests/unit_tests/services/account/test_adapters.py+++ b/api/tests/unit_tests/services/account/test_adapters.py@@ -27,6 +27,7 @@ from services.account.adapters import (TokenManagerChangeEmailTokenGateway,)from services.account_errors import AccountDeletionRateLimitError+from services.billing_client import billingfrom services.entities.account_activation_entities import InvitationLookup, InvitationTokenfrom services.entities.account_entities import (AccountChangeEmailNewEmailToken,@@ -195,12 +196,9 @@ def test_education_gateway_normalizes_billing_status_timestamp() -> None:with patch("services.account.adapters.BillingService.EducationIdentity.status",- return_value={- "result": True,- "is_student": True,- "expire_at": "2027-01-01T00:00:00+00:00",- "allow_refresh": False,- },+ return_value=billing.GetEducationIdentityStatusReply(+ result=True, is_student=True, expire_at="2027-01-01T00:00:00+00:00", allow_refresh=False+ ),):result = gateway.status("account-1")@@ -217,7 +215,7 @@ def test_education_gateway_activates_with_primitive_account_context() -> None:with patch("services.account.adapters.BillingService.EducationIdentity.activate",- return_value={"message": "success"},+ return_value=billing.CreateEducationIdentityReply(message="success"),) as activate:result = gateway.activate(account_id="account-1",@@ -237,16 +235,30 @@ def test_education_gateway_activates_with_primitive_account_context() -> None:)-def test_education_gateway_normalizes_autocomplete_defaults() -> None:+def test_education_gateway_maps_autocomplete_reply() -> None:gateway = BillingAccountEducationGateway()with patch("services.account.adapters.BillingService.EducationIdentity.autocomplete",- return_value=None,+ return_value=billing.AutocompleteEducationInstitutionReply(+ data=["Example University"], curr_page=0, has_next=True+ ),):result = gateway.autocomplete(keywords="Example", page=0, limit=20)- assert result == AccountEducationAutocomplete(data=(), curr_page=None, has_next=None)+ assert result == AccountEducationAutocomplete(data=("Example University",), curr_page=0, has_next=True)+++def test_education_gateway_reads_empty_expiry_as_none() -> None:+ gateway = BillingAccountEducationGateway()++ with patch(+ "services.account.adapters.BillingService.EducationIdentity.status",+ return_value=billing.GetEducationIdentityStatusReply(+ result=False, is_student=False, expire_at="", allow_refresh=False+ ),+ ):+ assert gateway.status("account-1").expire_at is Nonedef test_billing_email_policy_preserves_suspended_domain_reason() -> None:diff --git a/api/tests/unit_tests/services/billing_client/test_transport.py b/api/tests/unit_tests/services/billing_client/test_transport.pyindex 6d3e7192d74..d1dc1f41dfb 100644--- a/api/tests/unit_tests/services/billing_client/test_transport.py+++ b/api/tests/unit_tests/services/billing_client/test_transport.py@@ -190,3 +190,9 @@ def test_non_object_body_is_an_invalid_response(respond_with: RespondWith, contewith pytest.raises(BillingUpstreamInvalidResponseError):_get(Upstream.BILLING)+++def test_pooled_billing_client_carries_bounded_timeout() -> None:+ """Regression for #39874: a stalled billing proxy must fail fast instead of pinning a worker."""+ assert transport._http_client.timeout.read == 30.0+ assert transport._http_client.timeout.connect == 5.0diff --git a/api/tests/unit_tests/services/test_account_education_service.py b/api/tests/unit_tests/services/test_account_education_service.pyindex 628537f1900..fd32bd0c97d 100644--- a/api/tests/unit_tests/services/test_account_education_service.py+++ b/api/tests/unit_tests/services/test_account_education_service.py@@ -14,6 +14,7 @@ from repositories.account.repository import SQLAlchemyAccountRepositoryfrom services.account.adapters import BillingAccountEducationGatewayfrom services.account_education_service import AccountEducationServicefrom services.account_errors import EducationRateLimitExceededError+from services.billing_client import billingfrom services.billing_service import BillingServicefrom services.entities.account_entities import (AccountEducationActivation,@@ -72,16 +73,16 @@ def test_verify_reads_account_before_billing_gateway_call(_record_commands(commands, events)lookup = mocker.spy(accounts, "get")- def verify(*, account_id: str) -> dict[str, str]:+ def verify(*, account_id: str) -> billing.VerifyEducationIdentityReply:lookup.assert_called_once_with(account_id)events.append("verify")- return {"token": "education-token"}+ return billing.VerifyEducationIdentityReply(token="education-token")- billing = mocker.patch.object(BillingService.EducationIdentity, "verify", side_effect=verify)+ billing_call = mocker.patch.object(BillingService.EducationIdentity, "verify", side_effect=verify)assert service.verify(_context()) == AccountEducationVerification(token="education-token")assert events == ["check", "increment", "verify"]- billing.assert_called_once_with(account_id="account-1")+ billing_call.assert_called_once_with(account_id="account-1")assert all(call.args[1] == "verification:[email protected]" for call in commands.call_args_list)@@ -91,17 +92,16 @@ def test_status_and_autocomplete_delegate_framework_neutral_contracts(status = mocker.patch.object(BillingService.EducationIdentity,"status",- return_value={- "result": True,- "is_student": True,- "expire_at": "2027-01-01T00:00:00+00:00",- "allow_refresh": False,- },+ return_value=billing.GetEducationIdentityStatusReply(+ result=True, is_student=True, expire_at="2027-01-01T00:00:00+00:00", allow_refresh=False+ ),)autocomplete = mocker.patch.object(BillingService.EducationIdentity,"autocomplete",- return_value={"data": ["Example University"], "curr_page": 0, "has_next": False},+ return_value=billing.AutocompleteEducationInstitutionReply(+ data=["Example University"], curr_page=0, has_next=False+ ),)assert service.status(_context()) == AccountEducationStatus(@@ -122,10 +122,12 @@ def test_activate_delegates_account_and_workspace_context(_, commands = redis_transportevents: list[str] = []_record_commands(commands, events)- billing = mocker.patch.object(+ billing_call = mocker.patch.object(BillingService.EducationIdentity,"activate",- side_effect=lambda **_kwargs: events.append("activate") or {"message": "success"},+ side_effect=lambda **_kwargs: (+ events.append("activate") or billing.CreateEducationIdentityReply(message="success")+ ),)result = service.activate(_context(), token="education-token", institution="Dify University", role="Student")@@ -133,7 +135,7 @@ def test_activate_delegates_account_and_workspace_context(assert result == AccountEducationActivation(message="success")assert events == ["check", "increment", "activate"]assert all(call.args[1] == "activation:[email protected]" for call in commands.call_args_list)- billing.assert_called_once_with(+ billing_call.assert_called_once_with(account_id="account-1",tenant_id="workspace-1",token="education-token",diff --git a/api/tests/unit_tests/services/test_billing_service.py b/api/tests/unit_tests/services/test_billing_service.pyindex 836d444a636..d3fedcf55bf 100644--- a/api/tests/unit_tests/services/test_billing_service.py+++ b/api/tests/unit_tests/services/test_billing_service.py@@ -1,32 +1,13 @@-"""Comprehensive unit tests for BillingService.--This test module covers all aspects of the billing service including:-- HTTP request handling with retry logic-- Subscription tier management and billing information retrieval-- Usage calculation and credit management (positive/negative deltas)-- Compliance and education billing-provider requests-- Account management and permission checks-- Cache management for billing data-- Partner integration features--Network, billing-provider, and cache boundaries are mocked.-Tests follow the Arrange-Act-Assert pattern for clarity.-"""--import json-import logging-from types import SimpleNamespace-from unittest.mock import MagicMock, call, patch+"""BillingService delegates to the generated billing and saas clients; HTTP behavior is covered in billing_client."""++from unittest.mock import patchimport httpximport pytest-import tenacity-from werkzeug.exceptions import InternalServerError-from services.billing_client import billing, transport-from services.billing_service import BillingService, _BillingHTTPStatusError+from services.billing_client import billing, saas, transport+from services.billing_service import BillingServicefrom services.errors.billing import (- BillingUpstreamInvalidResponseError,BillingUpstreamUnavailableError,)from tests.helpers import billing_builders as builders@@ -35,303 +16,6 @@ TENANT_ID = "11111111-1111-1111-1111-111111111111"ACCOUNT_ID = "33333333-3333-3333-3333-333333333333"-class TestBillingServiceSendRequest:- """Unit tests for BillingService._send_request method.-- Tests cover:- - Successful GET/PUT/POST/DELETE requests- - Error handling for various HTTP status codes- - Retry logic on network failures- - Request header and parameter validation- """-- @pytest.fixture- def mock_httpx_request(self):- """Mock httpx.request for testing."""- with patch("services.billing_service._http_client.request") as mock_request:- yield mock_request-- @pytest.fixture- def mock_billing_config(self):- """Mock BillingService configuration."""- with (- patch.object(BillingService, "base_url", "https://billing-api.example.com"),- patch.object(BillingService, "secret_key", "test-secret-key"),- ):- yield-- def test_get_request_success(self, mock_httpx_request, mock_billing_config):- """Test successful GET request."""- # Arrange- expected_response = {"result": "success", "data": {"info": "test"}}- mock_response = MagicMock()- mock_response.status_code = httpx.codes.OK- mock_response.json.return_value = expected_response- mock_httpx_request.return_value = mock_response-- # Act- result = BillingService._send_request("GET", "/test", params={"key": "value"})-- # Assert- assert result == expected_response- mock_httpx_request.assert_called_once()- call_args = mock_httpx_request.call_args- assert call_args[0][0] == "GET"- assert call_args[0][1] == "https://billing-api.example.com/test"- assert call_args[1]["params"] == {"key": "value"}- assert call_args[1]["headers"]["Billing-Api-Secret-Key"] == "test-secret-key"- assert call_args[1]["headers"]["Content-Type"] == "application/json"-- def test_send_request_with_base_url_override(self, mock_httpx_request, mock_billing_config):- """Quota APIs can use the new billing service without changing legacy billing calls."""- # Arrange- expected_response = {"result": "success"}- mock_response = MagicMock()- mock_response.status_code = httpx.codes.OK- mock_response.json.return_value = expected_response- mock_httpx_request.return_value = mock_response-- # Act- result = BillingService._send_request("GET", "/quota/balance", base_url="https://quota.example.com")-- # Assert- assert result == expected_response- call_args = mock_httpx_request.call_args- assert call_args[0][1] == "https://quota.example.com/quota/balance"-- @pytest.mark.parametrize(- "status_code", [httpx.codes.NOT_FOUND, httpx.codes.INTERNAL_SERVER_ERROR, httpx.codes.BAD_REQUEST]- )- def test_get_request_non_200_status_code(self, mock_httpx_request, mock_billing_config, status_code):- """Test GET request preserves the upstream status for its public caller."""- # Arrange- mock_response = MagicMock()- mock_response.status_code = status_code- mock_httpx_request.return_value = mock_response-- # Act & Assert- with pytest.raises(_BillingHTTPStatusError) as exc_info:- BillingService._send_request("GET", "/test")- assert exc_info.value.status_code == status_code- assert "Unable to retrieve billing information" in str(exc_info.value)-- def test_put_request_success(self, mock_httpx_request, mock_billing_config):- """Test successful PUT request."""- # Arrange- expected_response = {"result": "success"}- mock_response = MagicMock()- mock_response.status_code = httpx.codes.OK- mock_response.json.return_value = expected_response- mock_httpx_request.return_value = mock_response-- # Act- result = BillingService._send_request("PUT", "/test", json={"key": "value"})-- # Assert- assert result == expected_response- call_args = mock_httpx_request.call_args- assert call_args[0][0] == "PUT"-- def test_put_request_internal_server_error(self, mock_httpx_request, mock_billing_config):- """Test PUT request with INTERNAL_SERVER_ERROR raises InternalServerError."""- # Arrange- mock_response = MagicMock()- mock_response.status_code = httpx.codes.INTERNAL_SERVER_ERROR- mock_httpx_request.return_value = mock_response-- # Act & Assert- with pytest.raises(InternalServerError) as exc_info:- BillingService._send_request("PUT", "/test", json={"key": "value"})- assert exc_info.value.code == 500- assert "Unable to process billing request" in str(exc_info.value.description)-- @pytest.mark.parametrize(- "status_code", [httpx.codes.BAD_REQUEST, httpx.codes.NOT_FOUND, httpx.codes.UNAUTHORIZED, httpx.codes.FORBIDDEN]- )- def test_put_request_non_200_non_500(self, mock_httpx_request, mock_billing_config, status_code):- """Test PUT request with non-200 and non-500 status code raises ValueError."""- # Arrange- mock_response = MagicMock()- mock_response.status_code = status_code- mock_httpx_request.return_value = mock_response-- # Act & Assert- with pytest.raises(ValueError, match="Invalid arguments\\.") as exc_info:- BillingService._send_request("PUT", "/test", json={"key": "value"})- assert "Invalid arguments." in str(exc_info.value)-- @pytest.mark.parametrize("method", ["POST", "DELETE"])- def test_non_get_non_put_request_success(self, mock_httpx_request, mock_billing_config, method):- """Test successful POST/DELETE request."""- # Arrange- expected_response = {"result": "success"}- mock_response = MagicMock()- mock_response.status_code = httpx.codes.OK- mock_response.json.return_value = expected_response- mock_httpx_request.return_value = mock_response-- # Act- result = BillingService._send_request(method, "/test", json={"key": "value"})-- # Assert- assert result == expected_response- call_args = mock_httpx_request.call_args- assert call_args[0][0] == method-- @pytest.mark.parametrize(- "status_code", [httpx.codes.BAD_REQUEST, httpx.codes.INTERNAL_SERVER_ERROR, httpx.codes.NOT_FOUND]- )- def test_post_request_non_200_with_valid_json(self, mock_httpx_request, mock_billing_config, status_code):- """Test POST request with non-200 status code raises ValueError."""- # Arrange- error_response = {"detail": "Error message"}- mock_response = MagicMock()- mock_response.status_code = status_code- mock_response.json.return_value = error_response- mock_httpx_request.return_value = mock_response-- # Act & Assert- with pytest.raises(_BillingHTTPStatusError) as exc_info:- BillingService._send_request("POST", "/test", json={"key": "value"})- assert "Unable to send request to" in str(exc_info.value)- assert exc_info.value.status_code == status_code-- @pytest.mark.parametrize(- "status_code", [httpx.codes.BAD_REQUEST, httpx.codes.INTERNAL_SERVER_ERROR, httpx.codes.NOT_FOUND]- )- def test_delete_request_non_200_with_valid_json(- self, mock_httpx_request, mock_billing_config, status_code, caplog: pytest.LogCaptureFixture- ):- """Test DELETE request with non-200 status code raises ValueError.-- DELETE now checks status code and raises ValueError for non-200 responses.- """- # Arrange- error_response = {"detail": "Error message"}- mock_response = MagicMock()- mock_response.status_code = status_code- mock_response.text = "Error message"- mock_response.json.return_value = error_response- mock_httpx_request.return_value = mock_response-- # Act & Assert- with caplog.at_level(logging.ERROR, logger="services.billing_service"):- with pytest.raises(- ValueError,- match=(- "Unable to process delete request https://billing\\-api\\.example\\.com"- "/test\\. Please try again later or contact support\\."- ),- ) as exc_info:- BillingService._send_request("DELETE", "/test", json={"key": "value"})- assert "Unable to process delete request" in str(exc_info.value)- assert "DELETE response" in caplog.text-- @pytest.mark.parametrize(- "status_code", [httpx.codes.BAD_REQUEST, httpx.codes.INTERNAL_SERVER_ERROR, httpx.codes.NOT_FOUND]- )- def test_post_request_non_200_with_invalid_json(self, mock_httpx_request, mock_billing_config, status_code):- """Test POST request with non-200 status code raises ValueError before JSON parsing."""- # Arrange- mock_response = MagicMock()- mock_response.status_code = status_code- mock_response.text = ""- mock_response.json.side_effect = json.JSONDecodeError("Expecting value", "", 0)- mock_httpx_request.return_value = mock_response-- # Act & Assert- # POST checks status code before calling response.json().- with pytest.raises(_BillingHTTPStatusError) as exc_info:- BillingService._send_request("POST", "/test", json={"key": "value"})- assert "Unable to send request to" in str(exc_info.value)- assert exc_info.value.status_code == status_code-- @pytest.mark.parametrize(- "status_code", [httpx.codes.BAD_REQUEST, httpx.codes.INTERNAL_SERVER_ERROR, httpx.codes.NOT_FOUND]- )- def test_delete_request_non_200_with_invalid_json(- self, mock_httpx_request, mock_billing_config, status_code, caplog: pytest.LogCaptureFixture- ):- """Test DELETE request with non-200 status code raises ValueError before JSON parsing.-- DELETE now checks status code before calling response.json(), so ValueError is raised- when the response cannot be parsed as JSON (e.g., empty response).- """- # Arrange- mock_response = MagicMock()- mock_response.status_code = status_code- mock_response.text = ""- mock_response.json.side_effect = json.JSONDecodeError("Expecting value", "", 0)- mock_httpx_request.return_value = mock_response-- # Act & Assert- with caplog.at_level(logging.ERROR, logger="services.billing_service"):- with pytest.raises(- ValueError,- match=(- "Unable to process delete request https://billing\\-api\\.example\\.com"- "/test\\. Please try again later or contact support\\."- ),- ) as exc_info:- BillingService._send_request("DELETE", "/test", json={"key": "value"})- assert "Unable to process delete request" in str(exc_info.value)- assert "DELETE response" in caplog.text-- @pytest.fixture- def retry_sleep(self, monkeypatch: pytest.MonkeyPatch) -> MagicMock:- """Advance a virtual clock while retaining the production retry policy."""- elapsed = 0.0-- def advance(seconds: float) -> None:- nonlocal elapsed- elapsed += seconds-- sleep = MagicMock(side_effect=advance)- # Replace tenacity's module reference, not the process-wide time module.- monkeypatch.setattr(tenacity, "time", SimpleNamespace(monotonic=lambda: elapsed))- monkeypatch.setattr("services.billing_service.BillingService._send_request.retry.sleep", sleep)- return sleep-- def test_retry_on_request_error(- self, mock_httpx_request: MagicMock, mock_billing_config: None, retry_sleep: MagicMock- ) -> None:- """Test that _send_request retries on httpx.RequestError."""- # Arrange- expected_response = {"result": "success"}- mock_response = MagicMock()- mock_response.status_code = httpx.codes.OK- mock_response.json.return_value = expected_response-- # First call raises RequestError, second succeeds- mock_httpx_request.side_effect = [- httpx.RequestError("Network error"),- mock_response,- ]-- # Act- result = BillingService._send_request("GET", "/test")-- # Assert- assert result == expected_response- assert mock_httpx_request.call_count == 2- retry_sleep.assert_called_once_with(2)-- def test_retry_exhausted_raises_exception(- self, mock_httpx_request: MagicMock, mock_billing_config: None, retry_sleep: MagicMock- ) -> None:- """Test that _send_request raises exception after retries are exhausted."""- # Arrange- mock_httpx_request.side_effect = httpx.RequestError("Network error")-- # Act & Assert- with pytest.raises(httpx.RequestError):- BillingService._send_request("GET", "/test")-- # The next two-second wait would reach the ten-second stop boundary.- assert mock_httpx_request.call_count == 5- assert retry_sleep.call_args_list == [call(2)] * 4--class TestBillingServiceSubscriptionInfo:"""Subscription and usage reads delegate to the generated billing client."""@@ -571,302 +255,139 @@ class TestBillingServiceQuotaOperations:)-class TestBillingServiceComplianceDownload:- """Unit tests for compliance download requests."""-- @pytest.fixture- def mock_send_request(self):- """Mock _send_request method."""- with patch.object(BillingService, "_send_request") as mock:- yield mock-- def test_compliance_download_returns_validated_link(self, mock_send_request):- doc_name = "compliance_report.pdf"- account_id = "account-123"- tenant_id = "tenant-456"- ip = "192.168.1.1"- device_info = "Mozilla/5.0"- expected_response = {"url": "https://example.com/download", "ignored": True}- mock_send_request.return_value = expected_response-- result = BillingService.get_compliance_download_link(doc_name, account_id, tenant_id, ip, device_info)-- assert result == {"url": "https://example.com/download"}- mock_send_request.assert_called_once_with(- "POST",- "/compliance/download",- json={- "doc_name": doc_name,- "account_id": account_id,- "tenant_id": tenant_id,- "ip_address": ip,- "device_info": device_info,- },- )-- @pytest.mark.parametrize(- ("request_error", "error_type"),- [- (_BillingHTTPStatusError("request failed", httpx.codes.BAD_REQUEST), BillingUpstreamInvalidResponseError),- (_BillingHTTPStatusError("request failed", httpx.codes.REQUEST_TIMEOUT), BillingUpstreamUnavailableError),- (_BillingHTTPStatusError("request failed", httpx.codes.TOO_MANY_REQUESTS), BillingUpstreamUnavailableError),- (- _BillingHTTPStatusError("request failed", httpx.codes.INTERNAL_SERVER_ERROR),- BillingUpstreamUnavailableError,- ),- (httpx.RequestError("request failed"), BillingUpstreamUnavailableError),- ],- )- def test_compliance_download_maps_request_failure(- self, mock_send_request, request_error: Exception, error_type: type[Exception]- ) -> None:- mock_send_request.side_effect = request_error-- with pytest.raises(error_type):- BillingService.get_compliance_download_link("SOC2_Type_II", "account-1", "tenant-1", "127.0.0.1", "test")-- def test_compliance_download_rejects_invalid_response(self, mock_send_request) -> None:- mock_send_request.return_value = {}-- with pytest.raises(BillingUpstreamInvalidResponseError):- BillingService.get_compliance_download_link("SOC2_Type_II", "account-1", "tenant-1", "127.0.0.1", "test")---class TestBillingServiceEducationIdentity:- """Unit tests for education identity verification and management.+class TestBillingServiceCacheManagement:+ """Unit tests for billing cache management.Tests cover:- - Education verification status checking- - Institution autocomplete with pagination- - Default parameter handling+ - Billing info cache invalidation+ - Proper Redis key formatting"""@pytest.fixture- def mock_send_request(self):- """Mock _send_request method."""- with patch.object(BillingService, "_send_request") as mock:- yield mock-- def test_education_verify(self, mock_send_request):- account_id = "account-123"- expected_response = {"token": "education-token"}- mock_send_request.return_value = expected_response-- result = BillingService.EducationIdentity.verify(account_id)-- assert result == expected_response- mock_send_request.assert_called_once_with("GET", "/education/verify", params={"account_id": account_id})-- def test_education_activate(self, mock_send_request):- expected_response = {"message": "success"}- mock_send_request.return_value = expected_response-- result = BillingService.EducationIdentity.activate(- account_id="account-123",- tenant_id="tenant-456",- token="verification-token",- institution="MIT",- role="student",- )-- assert result == expected_response- mock_send_request.assert_called_once_with(- "POST",- "/education/",- json={"institution": "MIT", "token": "verification-token", "role": "student"},- params={"account_id": "account-123", "curr_tenant_id": "tenant-456"},- )+ def mock_redis_client(self):+ """Mock Redis client."""+ with patch("services.billing_service.redis_client") as mock_redis:+ yield mock_redis- def test_education_status(self, mock_send_request):- """Test checking education verification status."""+ def test_clean_billing_info_cache(self, mock_redis_client):+ """Test cleaning billing info cache."""# Arrange- account_id = "account-123"- expected_response = {- "result": True,- "is_student": True,- "expire_at": "2027-01-01T00:00:00Z",- "allow_refresh": False,- }- mock_send_request.return_value = expected_response+ tenant_id = "tenant-123"+ expected_key = f"tenant:{tenant_id}:billing_info"# Act- result = BillingService.EducationIdentity.status(account_id)+ BillingService.clean_billing_info_cache(tenant_id)# Assert- assert result == expected_response- mock_send_request.assert_called_once_with("GET", "/education/status", params={"account_id": account_id})-- def test_education_autocomplete(self, mock_send_request):- """Test education institution autocomplete."""- # Arrange- keywords = "Massachusetts"- page = 0- limit = 20- expected_response = {- "data": ["Massachusetts Institute of Technology", "University of Massachusetts"],- "curr_page": 0,- "has_next": False,- }- mock_send_request.return_value = expected_response+ mock_redis_client.delete.assert_called_once_with(expected_key)- # Act- result = BillingService.EducationIdentity.autocomplete(keywords, page, limit)- # Assert- assert result == expected_response- mock_send_request.assert_called_once_with(- "GET", "/education/autocomplete", params={"keywords": keywords, "page": page, "limit": limit}- )+class TestBillingServiceAccountAndEducation:+ """Education, compliance, account and notification calls delegate to the generated clients."""- def test_education_autocomplete_with_defaults(self, mock_send_request):- """Test education institution autocomplete with default parameters."""- # Arrange- keywords = "Stanford"- expected_response = {"data": ["Stanford University"], "curr_page": 0, "has_next": False}- mock_send_request.return_value = expected_response+ def test_compliance_download_returns_the_link(self):+ reply = billing.DownloadComplianceDocumentReply(url="https://billing.example.com/compliance")- # Act- result = BillingService.EducationIdentity.autocomplete(keywords)+ with patch.object(billing, "compliance_download_compliance_document", return_value=reply) as download:+ result = BillingService.get_compliance_download_link("soc2", ACCOUNT_ID, TENANT_ID, "127.0.0.1", "ua")- # Assert- assert result == expected_response- mock_send_request.assert_called_once_with(- "GET", "/education/autocomplete", params={"keywords": keywords, "page": 0, "limit": 20}+ assert result == {"url": "https://billing.example.com/compliance"}+ download.assert_called_once_with(+ body=billing.DownloadComplianceDocumentReq(+ doc_name="soc2", account_id=ACCOUNT_ID, tenant_id=TENANT_ID, ip_address="127.0.0.1", device_info="ua"+ ))+ def test_education_activate_sends_account_context_in_the_body(self):+ reply = billing.CreateEducationIdentityReply(message="success")-class TestBillingServiceAccountManagement:- """Unit tests for account-related billing operations.-- Tests cover:- - Account deletion- - Email freeze status checking- - Account deletion feedback submission- - Tenant owner/admin permission validation- - Error handling for missing tenant joins- """-- @pytest.fixture- def mock_send_request(self):- """Mock _send_request method."""- with patch.object(BillingService, "_send_request") as mock:- yield mock-- def test_delete_account(self, mock_send_request):- """Test account deletion."""- # Arrange- account_id = "account-123"- expected_response = {"message": "Account deleted successfully."}- mock_send_request.return_value = expected_response-- # Act- result = BillingService.delete_account(account_id)-- # Assert- assert result == expected_response- mock_send_request.assert_called_once_with("DELETE", "/account", params={"account_id": account_id})-- def test_is_email_in_freeze_true(self, mock_send_request):- """Test checking if email is frozen (returns True)."""- # Arrange- email = "[email protected]"- mock_send_request.return_value = {"data": True}-- # Act- result = BillingService.is_email_in_freeze(email)-- # Assert- assert result is True- mock_send_request.assert_called_once_with("GET", "/account/in-freeze", params={"email": email})-- def test_get_email_freeze_type_for_suspended_domain(self, mock_send_request):- email = "[email protected]"- mock_send_request.return_value = {"data": True, "freezeType": "email_domain_suspended"}-- result = BillingService.get_email_freeze_type(email)-- assert result == "email_domain_suspended"- mock_send_request.assert_called_once_with("GET", "/account/in-freeze", params={"email": email})-- def test_is_email_in_freeze_false(self, mock_send_request):- """Test checking if email is frozen (returns False)."""- # Arrange- email = "[email protected]"- mock_send_request.return_value = {"data": False}-- # Act- result = BillingService.is_email_in_freeze(email)-- # Assert- assert result is False- mock_send_request.assert_called_once_with("GET", "/account/in-freeze", params={"email": email})+ with patch.object(billing, "education_create_education_identity", return_value=reply) as create:+ result = BillingService.EducationIdentity.activate(+ account_id=ACCOUNT_ID, tenant_id=TENANT_ID, token="token", institution="Dify University", role="Student"+ )- def test_is_email_in_freeze_exception_returns_false(self, mock_send_request):- """Test that is_email_in_freeze returns False on exception."""- # Arrange- email = "[email protected]"- mock_send_request.side_effect = Exception("Network error")+ assert result is reply+ create.assert_called_once_with(+ body=billing.CreateEducationIdentityReq(+ account_id=ACCOUNT_ID,+ curr_tenant_id=TENANT_ID,+ institution="Dify University",+ role="Student",+ token="token",+ )+ )- # Act- result = BillingService.is_email_in_freeze(email)+ def test_education_reads_return_the_generated_replies(self):+ verify = billing.VerifyEducationIdentityReply(token="token")+ status = billing.GetEducationIdentityStatusReply(+ result=True, is_student=True, expire_at="2027-01-01T00:00:00+00:00", allow_refresh=False+ )+ autocomplete = billing.AutocompleteEducationInstitutionReply(+ data=["Dify University"], curr_page=0, has_next=False+ )- # Assert- assert result is False+ with (+ patch.object(billing, "education_verify_education_identity", return_value=verify),+ patch.object(billing, "education_get_education_identity_status", return_value=status),+ patch.object(billing, "education_autocomplete_education_institution", return_value=autocomplete) as search,+ ):+ assert BillingService.EducationIdentity.verify(ACCOUNT_ID) is verify+ assert BillingService.EducationIdentity.status(ACCOUNT_ID) is status+ assert BillingService.EducationIdentity.autocomplete("Dify") is autocomplete- def test_update_account_deletion_feedback(self, mock_send_request):- """Test updating account deletion feedback."""- # Arrange- email = "[email protected]"- feedback = "Service was too expensive"- expected_response = {"message": "Reason added successfully."}- mock_send_request.return_value = expected_response+ search.assert_called_once_with(keywords="Dify", page=0, limit=20)- # Act- result = BillingService.update_account_deletion_feedback(email, feedback)+ def test_delete_account_and_feedback_call_saas(self):+ with (+ patch.object(saas, "account_delete_account", return_value=saas.DeleteAccountReply(message="ok")) as delete,+ patch.object(+ saas, "account_add_delete_feedback", return_value=saas.AddDeleteFeedbackReply(message="ok")+ ) as feedback,+ ):+ BillingService.delete_account(ACCOUNT_ID)+ BillingService.update_account_deletion_feedback("[email protected]", "too expensive")- # Assert- assert result == expected_response- mock_send_request.assert_called_once_with(- "POST", "/account/delete-feedback", json={"email": email, "feedback": feedback}+ delete.assert_called_once_with(account_id=ACCOUNT_ID)+ feedback.assert_called_once_with(+ body=saas.AddDeleteFeedbackRequest(email="[email protected]", feedback="too expensive"))+ @pytest.mark.parametrize(+ ("data", "freeze_type", "expected"),+ [+ (False, "freeze", None),+ (True, "freeze", "freeze"),+ (True, "email_domain_suspended", "email_domain_suspended"),+ (True, "", "freeze"),+ (True, "unexpected", "freeze"),+ ],+ )+ def test_get_email_freeze_type(self, data: bool, freeze_type: str, expected: str | None):+ reply = saas.CheckAccountInFreezeReply.model_construct(data=data, freeze_type=freeze_type)-class TestBillingServiceCacheManagement:- """Unit tests for billing cache management.-- Tests cover:- - Billing info cache invalidation- - Proper Redis key formatting- """-- @pytest.fixture- def mock_redis_client(self):- """Mock Redis client."""- with patch("services.billing_service.redis_client") as mock_redis:- yield mock_redis-- def test_clean_billing_info_cache(self, mock_redis_client):- """Test cleaning billing info cache."""- # Arrange- tenant_id = "tenant-123"- expected_key = f"tenant:{tenant_id}:billing_info"+ with patch.object(saas, "account_check_account_in_freeze", return_value=reply) as check:+ assert BillingService.get_email_freeze_type("[email protected]") == expected+ assert BillingService.is_email_in_freeze("[email protected]") is (expected is not None)- # Act- BillingService.clean_billing_info_cache(tenant_id)+ check.assert_called_with(email="[email protected]")- # Assert- mock_redis_client.delete.assert_called_once_with(expected_key)+ def test_get_email_freeze_type_swallows_billing_errors(self):+ with patch.object(saas, "account_check_account_in_freeze", side_effect=BillingUpstreamUnavailableError("down")):+ assert BillingService.get_email_freeze_type("[email protected]") is None+ def test_notifications_call_saas(self):+ active = saas.GetAccountNotificationReply(should_show=False, notifications=[])+ dismissed = saas.DismissNotificationReply(success=True)-def test_pooled_billing_client_carries_bounded_timeout() -> None:- """Regression for #39874: the pooled billing client must carry a- read/connect timeout so a stalled Stripe / cloud-billing proxy- fails fast instead of pinning a worker. Same shape as the- JinaReader / WaterCrawl hardening that landed in PR #39860 and #39824.- """- import services.billing_service as billing_service_module+ with (+ patch.object(saas, "notification_get_account_notification", return_value=active) as get,+ patch.object(saas, "notification_dismiss_notification", return_value=dismissed) as dismiss,+ ):+ assert BillingService.get_account_notification(ACCOUNT_ID) is active+ assert BillingService.dismiss_notification("notification-1", ACCOUNT_ID) is dismissed- client = billing_service_module._http_client- assert client.timeout is not None- assert client.timeout.read == 30.0- assert client.timeout.connect == 5.0+ get.assert_called_once_with(account_id=ACCOUNT_ID)+ dismiss.assert_called_once_with(+ notification_id="notification-1",+ body=saas.DismissNotificationReq(notification_id="notification-1", account_id=ACCOUNT_ID),+ )diff --git a/api/tests/unit_tests/services/test_compliance_download_service.py b/api/tests/unit_tests/services/test_compliance_download_service.pyindex 653e196d07d..a5042ffac5a 100644--- a/api/tests/unit_tests/services/test_compliance_download_service.py+++ b/api/tests/unit_tests/services/test_compliance_download_service.py@@ -1,12 +1,19 @@from unittest.mock import MagicMock+import httpximport pytestfrom extensions.ext_redis import RedisClientWrapperfrom libs.helper import RateLimiterfrom machinery.context import RequestContext+from services.billing_client import transport+from services.billing_service import BillingServicefrom services.compliance_download_service import ComplianceDownloadService-from services.errors.billing import BillingUpstreamUnavailableError, ComplianceRateLimitExceededError+from services.errors.billing import (+ BillingUpstreamInvalidResponseError,+ BillingUpstreamUnavailableError,+ ComplianceRateLimitExceededError,+)@pytest.fixture@@ -120,3 +127,31 @@ def test_get_link_does_not_increment_after_fetch_failure()assert [call.args[0] for call in commands.call_args_list] == ["ZREMRANGEBYSCORE", "ZCARD"]++[email protected]("payload", [{}, {"url": None}, {"url": 123}])+def test_invalid_billing_response_does_not_consume_download_limit(+ monkeypatch: pytest.MonkeyPatch,+ rate_limiter: RateLimiter,+ request_context: RequestContext,+ redis_transport: tuple[RedisClientWrapper, MagicMock],+ payload: dict[str, object],+) -> None:+ _, commands = redis_transport+ commands.return_value = 0+ service = ComplianceDownloadService(+ fetch_link=BillingService.get_compliance_download_link, rate_limiter=rate_limiter+ )+ monkeypatch.setenv("BILLING_API_URL", "http://billing/v1")+ with httpx.Client(transport=httpx.MockTransport(lambda _: httpx.Response(200, json=payload))) as client:+ monkeypatch.setattr(transport, "_http_client", client)++ with pytest.raises(BillingUpstreamInvalidResponseError):+ service.get_link(+ request_context=request_context,+ document_name="SOC2_Type_II",+ ip_address="127.0.0.1",+ device_info="test-agent",+ )++ assert [call.args[0] for call in commands.call_args_list] == ["ZREMRANGEBYSCORE", "ZCARD"]diff --git a/api/tests/unit_tests/services/test_notification_gateway.py b/api/tests/unit_tests/services/test_notification_gateway.pyindex 9df67e7a325..1b5f5af3645 100644--- a/api/tests/unit_tests/services/test_notification_gateway.py+++ b/api/tests/unit_tests/services/test_notification_gateway.py@@ -1,59 +1,84 @@from unittest.mock import patch-from services.entities.notification_entities import NotificationContent+import httpx+import pytest++from machinery.context import RequestContext+from services.billing_client import saas, transport+from services.entities.notification_entities import NotificationItemfrom services.notification_gateway import BillingNotificationGateway+from services.notification_service import NotificationServicedef test_get_active_maps_billing_proto_json_contract() -> None:- payload = {- "shouldShow": True,- "notifications": [- {- "notificationId": "notification-1",- "frequency": "once",- "contents": {- "en-US": {- "lang": "en-US",- "title": "Title",- "subtitle": "Subtitle",- "body": "Body",- "titlePicUrl": "title.png",- }- },- }- ],- }+ reply = saas.GetAccountNotificationReply.model_validate(+ {+ "shouldShow": True,+ "notifications": [+ {+ "notificationId": "notification-1",+ "frequency": "once",+ "isGlobal": False,+ "contents": {+ "en-US": {+ "lang": "en-US",+ "title": "Title",+ "subtitle": "Subtitle",+ "body": "Body",+ "titlePicUrl": "title.png",+ }+ },+ }+ ],+ }+ )- with patch("services.notification_gateway.BillingService.get_account_notification", return_value=payload):+ with patch("services.notification_gateway.BillingService.get_account_notification", return_value=reply):result = BillingNotificationGateway().get_active("account-1")assert result.should_show is Trueassert result.notifications[0].notification_id == "notification-1"+ assert result.notifications[0].frequency == "once"assert result.notifications[0].contents["en-US"].title_pic_url == "title.png"-def test_get_active_omits_empty_localized_content_so_service_can_fall_back() -> None:- empty_localized_content: dict[str, str] = {}[email protected]("localized_content", [None, {}])+def test_get_active_falls_back_to_english_for_empty_upstream_translation(+ monkeypatch: pytest.MonkeyPatch, localized_content: dict[str, str] | None+) -> None:payload = {"shouldShow": True,"notifications": [{"notificationId": "notification-1","frequency": "once",+ "isGlobal": False,"contents": {- "zh-Hans": empty_localized_content,- "en-US": {"lang": "en-US", "title": "Title"},+ "zh-Hans": localized_content,+ "en-US": {+ "lang": "en-US",+ "title": "Title",+ "subtitle": "Subtitle",+ "body": "Body",+ "titlePicUrl": "title.png",+ },},}],}+ context = RequestContext(+ request_id="request-1", trace_id="trace-1", account_id="account-1", active_workspace_id="workspace-1"+ )+ service = NotificationService(notifications=BillingNotificationGateway())+ monkeypatch.setenv("BILLING_API_URL", "http://billing/v1")+ with httpx.Client(transport=httpx.MockTransport(lambda _: httpx.Response(200, json=payload))) as client:+ monkeypatch.setattr(transport, "_http_client", client)+ result = service.get_active(context, "zh-Hans")- with patch("services.notification_gateway.BillingService.get_account_notification", return_value=payload):- result = BillingNotificationGateway().get_active("account-1")-- assert result.notifications[0].contents == {- "en-US": NotificationContent("en-US", "Title", "", "", ""),- }+ assert result.should_show is True+ assert result.notifications == (+ NotificationItem("notification-1", "once", "en-US", "Title", "Subtitle", "Body", "title.png"),+ )def test_dismiss_delegates_to_billing_service() -> None:diff --git a/packages/contracts/generated/api/console/account/types.gen.ts b/packages/contracts/generated/api/console/account/types.gen.tsindex ec9572013c9..8d6853690a8 100644--- a/packages/contracts/generated/api/console/account/types.gen.ts+++ b/packages/contracts/generated/api/console/account/types.gen.ts@@ -141,10 +141,10 @@ export type EmailCodeAccountDeletionRateLimitExceededError = ErrorResponse & {}export type EducationStatusResponse = {- allow_refresh?: boolean | null- expire_at?: number | null- is_student?: boolean | null- result?: boolean | null+ allow_refresh: boolean+ expire_at: number | null+ is_student: boolean+ result: boolean}export type EducationActivatePayload = {@@ -163,13 +163,13 @@ export type EducationActivateLimitError = ErrorResponse & {}export type EducationAutocompleteResponse = {- curr_page?: number | null- data?: Array<string>- has_next?: boolean | null+ curr_page: number+ data: Array<string>+ has_next: boolean}export type EducationVerifyResponse = {- token?: string | null+ token: string}export type EducationVerifyLimitError = ErrorResponse & {diff --git a/packages/contracts/generated/api/console/account/zod.gen.ts b/packages/contracts/generated/api/console/account/zod.gen.tsindex 9d72af3257c..fbd4e6558e6 100644--- a/packages/contracts/generated/api/console/account/zod.gen.ts+++ b/packages/contracts/generated/api/console/account/zod.gen.ts@@ -265,10 +265,10 @@ export const zEmailCodeAccountDeletionRateLimitExceededError = zErrorResponse.an* EducationStatusResponse*/export const zEducationStatusResponse = z.object({- allow_refresh: z.boolean().nullish(),- expire_at: z.int().nullish(),- is_student: z.boolean().nullish(),- result: z.boolean().nullish(),+ allow_refresh: z.boolean(),+ expire_at: z.int().nullable(),+ is_student: z.boolean(),+ result: z.boolean(),})/**@@ -303,16 +303,16 @@ export const zEducationActivateLimitError = zErrorResponse.and(* EducationAutocompleteResponse*/export const zEducationAutocompleteResponse = z.object({- curr_page: z.int().nullish(),- data: z.array(z.string()).optional(),- has_next: z.boolean().nullish(),+ curr_page: z.int(),+ data: z.array(z.string()),+ has_next: z.boolean(),})/*** EducationVerifyResponse*/export const zEducationVerifyResponse = z.object({- token: z.string().nullish(),+ token: z.string(),})/**diff --git a/packages/contracts/generated/api/console/notification/types.gen.ts b/packages/contracts/generated/api/console/notification/types.gen.tsindex 0b4e9bc3c72..6d856e8b769 100644--- a/packages/contracts/generated/api/console/notification/types.gen.ts+++ b/packages/contracts/generated/api/console/notification/types.gen.ts@@ -29,9 +29,9 @@ export type SimpleResultResponse = {export type NotificationItemResponse = {body: string- frequency?: string | null+ frequency: 'every_page_load' | 'once'lang: string- notification_id?: string | null+ notification_id: stringsubtitle: stringtitle: stringtitle_pic_url: stringdiff --git a/packages/contracts/generated/api/console/notification/zod.gen.ts b/packages/contracts/generated/api/console/notification/zod.gen.tsindex 8c6ce732a3b..de5d8d35083 100644--- a/packages/contracts/generated/api/console/notification/zod.gen.ts+++ b/packages/contracts/generated/api/console/notification/zod.gen.ts@@ -37,9 +37,9 @@ export const zSimpleResultResponse = z.object({*/export const zNotificationItemResponse = z.object({body: z.string(),- frequency: z.string().nullish(),+ frequency: z.enum(['every_page_load', 'once']),lang: z.string(),- notification_id: z.string().nullish(),+ notification_id: z.string(),subtitle: z.string(),title: z.string(),title_pic_url: z.string(),diff --git a/web/app/components/billing/plan/index.tsx b/web/app/components/billing/plan/index.tsxindex f5c4438161b..64b38865796 100644--- a/web/app/components/billing/plan/index.tsx+++ b/web/app/components/billing/plan/index.tsx@@ -23,8 +23,8 @@ type Props = Readonly<{}>const selectEducationPlanStatus = ({ allow_refresh, is_student }: EducationStatusResponse) => ({- isAboutToExpire: allow_refresh ?? false,- isEducationAccount: is_student ?? false,+ isAboutToExpire: allow_refresh,+ isEducationAccount: is_student,})const PlanComp: FC<Props> = ({ loc }) => {diff --git a/web/app/components/billing/pricing/__tests__/content.spec.tsx b/web/app/components/billing/pricing/__tests__/content.spec.tsxindex 6e5da78578d..80bac5f9bf9 100644--- a/web/app/components/billing/pricing/__tests__/content.spec.tsx+++ b/web/app/components/billing/pricing/__tests__/content.spec.tsx@@ -144,6 +144,7 @@ it('preserves a billing interval selected before education eligibility arrives',is_student: true,allow_refresh: true,expire_at: null,+ result: true,}),)expect(screen.getByRole('switch')).not.toBeChecked()@@ -155,6 +156,7 @@ it('shows yearly pricing immediately for a cached eligible education account', (queryClient.setQueryData(consoleQuery.account.education.get.queryOptions().queryKey, {is_student: true,allow_refresh: false,+ result: true,expire_at: null,})show()diff --git a/web/app/components/billing/pricing/content.tsx b/web/app/components/billing/pricing/content.tsxindex aab94d6755f..d85b46aa562 100644--- a/web/app/components/billing/pricing/content.tsx+++ b/web/app/components/billing/pricing/content.tsx@@ -29,7 +29,7 @@ export function PricingContent() {const educationQuery = useQuery(consoleQuery.account.education.get.queryOptions({enabled: educationEnabled,- select: ({ is_student }) => is_student ?? false,+ select: ({ is_student }) => is_student,}),)const canManageBilling = useAtomValue(isCurrentWorkspaceManagerAtom)diff --git a/web/app/education/apply/application-form.tsx b/web/app/education/apply/application-form.tsxindex 87eda8c28fe..60f0a1c6122 100644--- a/web/app/education/apply/application-form.tsx+++ b/web/app/education/apply/application-form.tsx@@ -52,7 +52,7 @@ const EducationApplyPage = ({ plan, token }: EducationApplyPageProps) => {)const { data: isEducationAccount = false } = useQuery(consoleQuery.account.education.get.queryOptions({- select: ({ is_student }) => is_student ?? false,+ select: ({ is_student }) => is_student,}),)const currentWorkspace = useAtomValue(currentWorkspaceAtom)diff --git a/web/app/education/apply/institution-field.tsx b/web/app/education/apply/institution-field.tsxindex 84368015394..ded3cde46a2 100644--- a/web/app/education/apply/institution-field.tsx+++ b/web/app/education/apply/institution-field.tsx@@ -48,8 +48,7 @@ const InstitutionField = ({ value, onValueChange }: InstitutionFieldProps) => {},}),initialPageParam: 0,- getNextPageParam: (lastPage, pages) =>- lastPage.has_next ? (lastPage.curr_page ?? pages.length - 1) + 1 : undefined,+ getNextPageParam: (lastPage) => (lastPage.has_next ? lastPage.curr_page + 1 : undefined),}),enabled: hasSearchQuery && !!debouncedSearchQuery,placeholderData: keepPreviousData,diff --git a/web/app/education/expire-notice/use-expire-notice.ts b/web/app/education/expire-notice/use-expire-notice.tsindex dad184b8746..ba0cfa421f2 100644--- a/web/app/education/expire-notice/use-expire-notice.ts+++ b/web/app/education/expire-notice/use-expire-notice.ts@@ -14,7 +14,7 @@ dayjs.extend(utc)dayjs.extend(timezone)const selectEducationExpireStatus = ({ allow_refresh, expire_at }: EducationStatusResponse) => ({- allowRefresh: allow_refresh ?? false,+ allowRefresh: allow_refresh,expireAt: expire_at ?? null,})diff --git a/web/app/education/verify/verify-flow.tsx b/web/app/education/verify/verify-flow.tsxindex 963bfbb031d..a4429be2eb4 100644--- a/web/app/education/verify/verify-flow.tsx+++ b/web/app/education/verify/verify-flow.tsx@@ -21,8 +21,8 @@ class EducationVerificationRejectedError extends Error {}type EducationVerificationRequest = () => Promise<{ token?: string | null }>const selectEducationStatus = ({ allow_refresh, is_student }: EducationStatusResponse) => ({- allowRefresh: allow_refresh ?? false,- isEducationAccount: is_student ?? false,+ allowRefresh: allow_refresh,+ isEducationAccount: is_student,})const selectEducationPlanEnabled = ({ education }: GetFeaturesResponse) => education.enableddiff --git a/web/service/console/client.spec.ts b/web/service/console/client.spec.tsindex cf7f1c47948..a056d523ed5 100644--- a/web/service/console/client.spec.ts+++ b/web/service/console/client.spec.ts@@ -688,7 +688,7 @@ describe('consoleQuery education defaults', () => {const consoleQuery = await loadConsoleQuery()const queryClient = createQueryClient()const key = consoleQuery.account.education.get.queryKey()- const cached = { is_student: false, allow_refresh: false, expire_at: null }+ const cached = { is_student: false, allow_refresh: false, expire_at: null, result: false }queryClient.setQueryData(key, cached)const unrelatedKey = ['unrelated-account-data']queryClient.setQueryData(unrelatedKey, { name: 'User' })diff --git a/web/test/console/query-data.ts b/web/test/console/query-data.tsindex 020a02668c7..b777df10db8 100644--- a/web/test/console/query-data.ts+++ b/web/test/console/query-data.ts@@ -137,6 +137,7 @@ export const seedEducationStatus = (allow_refresh: false,expire_at: null,is_student: false,+ result: false,...overrides,}queryClient.setQueryData(consoleQuery.account.education.get.queryOptions().queryKey, data)