From fa4eeb5ba806551539c0bace10575011c390a6df Mon Sep 17 00:00:00 2001 From: jeff377 Date: Thu, 3 Dec 2026 14:19:33 +0800 Subject: [PATCH] docs: sequence diagrams of an API call and of a streamed call Adds two user documents, in English with their Traditional Chinese translations, that follow one call through what Polhem adds on top of Polhem.JsonRpc: the session key issued at sign-in under RSA and handed to the payload filter through IApiEncryptionKeyProvider and PolhemPayloadPolicy, the object factory, method policy and access filter that run before a business object method, and how the body codec is chosen. The transport, dispatcher and payload envelope are left to Polhem.JsonRpc's request-flow and streaming documents, which both link to. The streamed-call document explains that business objects do not stream (PolhemMethodPolicy, since #644) and what a caller that asks for a stream gets from a Polhem server. Both are listed under Concepts in the docs index. --- docs/en/README.md | 4 +- docs/en/api/api-call-flow.md | 209 +++++++++++++++++++++++++++ docs/en/api/api-streamed-calls.md | 69 +++++++++ docs/zh-TW/README.md | 6 +- docs/zh-TW/api/api-call-flow.md | 187 ++++++++++++++++++++++++ docs/zh-TW/api/api-streamed-calls.md | 64 ++++++++ 6 files changed, 536 insertions(+), 3 deletions(-) create mode 100644 docs/en/api/api-call-flow.md create mode 100644 docs/en/api/api-streamed-calls.md create mode 100644 docs/zh-TW/api/api-call-flow.md create mode 100644 docs/zh-TW/api/api-streamed-calls.md diff --git a/docs/en/README.md b/docs/en/README.md index 9b670344..49dabdf2 100644 --- a/docs/en/README.md +++ b/docs/en/README.md @@ -39,6 +39,8 @@ Why the framework is built the way it is. |----------|------|-------------| | [FormSchema-Driven Database Access](definitions/formschema-data-access.md) | Concept | How Polhem.Db generates SQL dynamically from a FormSchema, and why it is not an ORM | | [API ↔ BO Contract Design](api/api-bo-contract-design.md) | Concept | Three-tier API contract separation (Contracts / API Type / BO Type) and the naming conventions that drive it | +| [How an API Call Is Processed](api/api-call-flow.md) | Concept | One call from the client connector to the business object and back: the session key exchanged at sign-in, the checks before a method runs, and how MessagePack bodies are chosen | +| [How a Streamed Call Is Processed](api/api-streamed-calls.md) | Concept | Why business objects do not stream, and what a caller that asks for a stream gets | | [Project Dependency Map](architecture/dependency-map.md) | Concept | How the `src/` projects depend on each other, and the rules that keep the graph acyclic | | [Caching](guides/caching.md) | Concept | How definition and database-backed caches work: the read path, the invalidation signals, and the notification-table mechanism for cross-process / multi-node deployments | @@ -101,7 +103,7 @@ The same documents, grouped by subject. A document appearing under several topic | **Multi-tenancy** | [Tenant Customization](definitions/customization.md) · [Definition Files Overview](definitions/definition-files-overview.md) · [Development Cookbook](guides/development-cookbook.md) · [Caching](guides/caching.md) | | **Caching & performance** | [Caching](guides/caching.md) · [Development Cookbook](guides/development-cookbook.md) · [Development Constraints](architecture/development-constraints.md) | | **Client heads & platforms** | [Platform Support](getting-started/platform-support.md) · [List Query Conditions](guides/list-query-conditions.md) · [JSON-RPC Frontend Integration](api/jsonrpc-frontend-integration.md) · [Development Cookbook](guides/development-cookbook.md) | -| **API & frontend** | [Contract Design](api/api-bo-contract-design.md) · [API Method Reference](api/api-method-reference.md) · [JSON-RPC Frontend Integration](api/jsonrpc-frontend-integration.md) · [Permission & Authorization](security/permission-authorization.md) · [API Key Management](security/api-key-management.md) | +| **API & frontend** | [Contract Design](api/api-bo-contract-design.md) · [API Call Flow](api/api-call-flow.md) · [Streamed Calls](api/api-streamed-calls.md) · [API Method Reference](api/api-method-reference.md) · [JSON-RPC Frontend Integration](api/jsonrpc-frontend-integration.md) · [Permission & Authorization](security/permission-authorization.md) · [API Key Management](security/api-key-management.md) | | **Types & time** | [Temporal Types](database/temporal-types.md) · [Time Zones](database/datetime-timezone.md) | | **Quality & conventions** | [Analyzer Rules](reference/analyzer-rules.md) · [Development Constraints](architecture/development-constraints.md) · [Naming Conventions](database/database-naming-conventions.md) | diff --git a/docs/en/api/api-call-flow.md b/docs/en/api/api-call-flow.md new file mode 100644 index 00000000..7bfd6bde --- /dev/null +++ b/docs/en/api/api-call-flow.md @@ -0,0 +1,209 @@ +# How an API Call Is Processed + +[繁體中文](../../zh-TW/api/api-call-flow.md) · [← Docs Index](../README.md) + +What the Polhem framework does with one API call, from a connector method on the client to the business object method +on the server and back. Polhem builds its API on the Polhem.JsonRpc packages: the transport, the dispatcher, the filter +pipeline and the payload envelope are theirs, and are described in Polhem.JsonRpc's +[How a call is processed](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/request-flow.md). This document +covers only what Polhem adds on top: who is calling, how the session key is exchanged and reaches the envelope, which +checks run before a business object method, and how MessagePack bodies are chosen. Streamed calls are in +[api-streamed-calls.md](api-streamed-calls.md). + +Settings and their defaults are documented on the types that hold them; the reasons behind each step are in the ADRs +linked from each section. + +## Overview + +```mermaid +sequenceDiagram + participant App as Application + participant Con as ApiConnector
(System / Form / AuditLog) + participant Pr as Provider
(Remote or Local) + participant D as JsonRpcDispatcher + participant BO as Business object + + App->>Con: e.g. FormApiConnector.ExecuteAsync(action, value) + Con->>Pr: ProgId.Action, value sealed in the payload envelope + Pr->>D: HTTP POST, or in-process + D->>D: Who is calling, may they call this method + D->>BO: Action(args) + BO-->>D: Result + D-->>Pr: JSON-RPC response, result sealed in the same format + Pr-->>Con: Response + Con-->>App: Typed response, or an exception +``` + +- **Every call carries the payload envelope.** In Polhem.JsonRpc the payload packages are optional; the Polhem client + always goes through `PayloadConnector`, and the server always runs `PolhemPayloadFilter`. A `Plain` call still has an + envelope; its value is ordinary JSON. +- **Two providers, one path.** The remote provider sends through `HttpTransport` to the endpoint a host maps with + `MapJsonRpc`. The local provider (`PolhemApiClient.CreateLocal`) reaches the dispatcher of the same process through + `InProcessTransport`, so the HTTP checks below do not run; everything else is the same. +- **One request per HTTP call.** The server options built by `PolhemJsonRpc.CreateServerOptions` refuse batches; the + reason is on that method. + +## Signing in: the session key + +An `Encrypted` call needs a key that both ends hold and nobody else does. Polhem issues one per session at sign-in and +hands it to the client under RSA. + +```mermaid +sequenceDiagram + participant SC as SystemApiConnector + participant BO as SystemBusinessObject + participant KP as IApiEncryptionKeyProvider + participant S as Session store + + SC->>SC: Generate an RSA key pair + SC->>BO: System.Login (Encoded)
user id, password, client public key + BO->>BO: Check lockout, authenticate + BO->>KP: GenerateKeyForLogin(new access token) + KP-->>BO: Session key + BO->>S: Save the session seed, cache SessionInfo with the key + BO->>BO: Encrypt the key with the client public key + BO-->>SC: Access token, encrypted key, time zone + SC->>SC: Decrypt the key with the private key
Session.SignIn(token, key, zone) +``` + +- **Before signing in**, `SystemApiConnector.InitializeAsync` reads the server's configuration with a `Plain` call and + adopts its compressor and encryptor. Both ends must use the same ones, because the envelope does not name them; what + the client refuses to adopt from that unauthenticated answer is on `InitializeAsync`. +- **The sign-in itself is `Encoded`**, because no key exists yet. The key travels encrypted with the client's public key. +- **The key provider is the deployment's choice**, named by `BackendComponents.ApiEncryptionKeyProvider`. The providers + that ship with the framework, and which one is the default, are listed in the + [Polhem.Business README](../../../src/Polhem.Business/README.md#authentication--security). A provider that keeps the + key only inside the session cannot rebuild a session from its seed; see `SupportsSessionRebuild` on + [`IApiEncryptionKeyProvider`](../../../src/Polhem.Definition/Security/IApiEncryptionKeyProvider.cs). +- **A browser client has no session key.** .NET cannot generate RSA keys on browser-wasm, so the client sends no public + key and gets no key back. Its `Encrypted` calls are sent as `Encoded`, and methods that require `Encrypted` refuse + them. +- **Encryption is not a replacement for TLS.** Nothing authenticates the client's public key or the configuration + answer, so over plain HTTP an intermediary can substitute either + ([ADR-014](../../../maintainers/adr/adr-014-jsonrpc-plain-public-default.md)). + +## Each call: the key reaches the envelope + +After sign-in, every connector of the client calls with the same credentials. On the server, Polhem answers the +questions the payload filter of Polhem.JsonRpc asks through `IPayloadServerPolicy`. + +```mermaid +sequenceDiagram + participant Con as ApiConnector + participant PC as PayloadConnector + participant PF as PayloadFilter
(in PolhemPayloadFilter) + participant Pol as PolhemPayloadPolicy + participant KP as IApiEncryptionKeyProvider + + Con->>PC: Format, codec, session key, next sequence number + PC->>PF: Request sealed with the session key + PF->>Pol: GetKeyAsync + Pol->>KP: GetKey(access token of this call) + KP-->>PF: Session key + PF->>Pol: Replay scope, unique sequence required, payload type + Pol-->>PF: Access token, ApiAccessControl's ReplayProtection, ActionPayloadType + PF->>PF: Open the request (Polhem.JsonRpc) +``` + +- **The client reads the credentials once per call**, so the token it sends and the key it seals with always belong to + the same sign-in, even when another thread signs in meanwhile. +- **The format can be lowered on the client.** A local client outside debug mode sends `Plain`, and an `Encrypted` call + without a session key is sent as `Encoded`; the rules are on `ApiConnector`. The server decides whether the format it + receives is enough, as described below. +- **Sequence numbers come from the session**, so all connectors of one session share them. The server checks them only + for a method that declares `ReplayProtection = UniqueSequence`, only when the host requires the wire frame, and only + for a signed-in remote call: see [Replay protection](api-method-reference.md#replay-protection) and + [ADR-042](../../../maintainers/adr/adr-042-api-replay-protection.md). +- **The parameter type comes from the method**, not from the type name the caller wrote on the envelope. + `ActionPayloadType` explains why. + +How the envelope is sealed and opened (gzip, the frame, AES-CBC with an HMAC bound to the direction and the method) is +Polhem.JsonRpc's: see [The payload envelope](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/request-flow.md#the-payload-envelope). + +## Server: who is calling, and what they may call + +Polhem plugs into the dispatcher at the object factory, the method policy, the two filters, the parameter binder and +the exception mapper. They run in this order: + +```mermaid +sequenceDiagram + participant D as JsonRpcDispatcher + participant OF as PolhemObjectFactory + participant AF as PolhemAccessFilter + participant PF as PolhemPayloadFilter + participant B as PolhemParameterBinder + participant BO as Business object + + D->>OF: CreateObject(ProgId) + OF->>OF: HTTP only: check X-Api-Key and Authorization + OF-->>D: Business object for this access token + D->>D: Find the action (PolhemMethodPolicy) + D->>AF: Run the filters + AF->>AF: ApiAccessValidator: requirement, protection level vs format + AF->>PF: next + PF->>PF: Open the envelope + PF->>B: Bind + B->>BO: Action(args) + BO-->>PF: Result + PF->>PF: ApiOutputConverter, then seal the result + PF-->>AF: Done + AF->>AF: Record a slow call +``` + +- **Who is calling.** A call over HTTP is checked before any business object exists: the `X-Api-Key` header by + `IApiKeyValidator` ([API Key Management](../security/api-key-management.md)), then the request by + `IApiAuthorizationValidator`, which also reads the access token from the `Authorization` header. A request without + the header is an anonymous call. An in-process call brings its access token in the transport and is not checked here. +- **Which methods exist.** `PolhemMethodPolicy` publishes a method only when it takes one parameter and + [`ApiAccessControlAttribute`](../../../src/Polhem.Definition/Attributes/ApiAccessControlAttribute.cs) covers it (on + the method, the method it overrides, or the class). Any other method is answered as one that does not exist. The + analyzer rule POLHEM3001 reports an uncovered public method at build time ([Analyzer Rules](../reference/analyzer-rules.md)). +- **Whether this caller may call it.** `PolhemAccessFilter` reads only the `format` of the envelope and checks it + against the attribute: an `Authenticated` method needs a live access token, and the format must reach the method's + [`ApiProtectionLevel`](../../../src/Polhem.Definition/Security/ApiProtectionLevel.cs). A `LocalOnly` method refuses + every remote call. A local call skips the protection level, but one that carries an expired token is still refused. + Each framework method's settings are in the [API Method Reference](api-method-reference.md). +- **The access filter runs first**, so a call that is refused costs no decryption or deserialization. A host that + assembles its own server options must keep this order; a host that adds filters through `AddJsonRpcServer` gets them + after the framework's. +- **Arguments and results are converted.** The binder reads the opened value into the wire request type and converts it + to the business-layer argument; `ApiOutputConverter` turns the result into the wire response type before it is + sealed. The three tiers are in [API ↔ BO Contract Design](api-bo-contract-design.md). +- **Errors.** `PolhemExceptionMapper` turns an exception into the error the client receives, through the error contract + that the client reads to rebuild the exception + ([ADR-043](../../../maintainers/adr/adr-043-error-contract-single-registry.md)). Which roles and records a signed-in + user may reach is decided inside the business object: see [Permission & Authorization](../security/permission-authorization.md). + +## MessagePack bodies + +An `Encoded` or `Encrypted` body is serialized by a codec, and each request names its codec in the envelope. The server +answers in the codec the request used. + +```mermaid +flowchart LR + F{"format"} -->|Plain| J["Value as ordinary JSON
no codec"] + F -->|Encoded / Encrypted| C{"codec in the envelope"} + C -->|none named| M["messagepack"] + C -->|messagepack| M + C -->|json| JS["json"] +``` + +- **The .NET client** uses MessagePack unless `ApiConnector.PayloadCodec` names another codec, per connector. + MessagePack is what the framework's formatters and wire contracts are written for + ([ADR-004](../../../maintainers/adr/adr-004-messagepack-payload.md), + [ADR-030](../../../maintainers/adr/adr-030-messagepack-name-based-keys.md), + [ADR-037](../../../maintainers/adr/adr-037-wire-explicit-registration.md)). +- **A client in another language** names `json` and needs no MessagePack: + [JSON-RPC Frontend Integration](jsonrpc-frontend-integration.md). +- **A request that names no codec is read as MessagePack**, because clients that predate codec negotiation send none + ([ADR-044](../../../maintainers/adr/adr-044-payload-codec-negotiation.md)). +- **The codec changes only the serialization step.** Compression, encryption and the frame are the same for every + codec. `PolhemPayload` builds the options both ends use; its remarks say which of them must not be changed. + +## See also + +- [How a streamed call is processed](api-streamed-calls.md) +- [End-to-End Development Cookbook](../guides/development-cookbook.md#request-processing-pipeline): the whole request + pipeline in one diagram +- Polhem.JsonRpc: [How a call is processed](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/request-flow.md) + and [security.md](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/security.md) diff --git a/docs/en/api/api-streamed-calls.md b/docs/en/api/api-streamed-calls.md new file mode 100644 index 00000000..26ed0147 --- /dev/null +++ b/docs/en/api/api-streamed-calls.md @@ -0,0 +1,69 @@ +# How a Streamed Call Is Processed + +[繁體中文](../../zh-TW/api/api-streamed-calls.md) · [← Docs Index](../README.md) + +Polhem.JsonRpc can answer a call with a stream: the method sends items as server-sent events before its response +([How a streamed call is processed](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/streaming.md)). +**Polhem business objects do not stream.** This document explains why, and what a caller that asks for a stream gets +from a Polhem server. Read [How an API call is processed](api-call-flow.md) first: a streamed call to Polhem takes the +same path up to the point where it differs. + +## Why business objects do not stream + +`PolhemMethodPolicy` publishes only methods that take one parameter. A streaming method takes a second one, its +`IJsonRpcStream`, so it is not published, whatever `ApiAccessControlAttribute` it carries. + +The reason is the wire type. `PolhemPayloadFilter` converts a method's return value into its wire response type with +`ApiOutputConverter` before the envelope is sealed. The items of a stream are written while the method runs and never +pass through that step, so they would leave in their business-layer type. The change is recorded in the +[1.17.0 release notes](../changelogs/1.17.0.md#business-objects-do-not-publish-streaming-methods). + +## What a caller asking for a stream gets + +A caller asks for a stream by naming `text/event-stream` in `Accept`. The HTTP endpoint then takes the streaming path, +but the stream starts only right before a streaming method runs. With Polhem that never happens, so the call is +answered with ordinary JSON. + +```mermaid +sequenceDiagram + participant Cli as Client + participant H as JsonRpcHttpHandler + participant D as JsonRpcDispatcher + participant OF as PolhemObjectFactory + participant F as Polhem filters + + Cli->>H: POST, Accept: application/json, text/event-stream + H->>D: DispatchStreamingAsync + D->>OF: CreateObject: API key and authorization checks + D->>D: Find the action (PolhemMethodPolicy) + alt A method that is published + D->>F: Access check, envelope, call + F-->>D: Result + D-->>H: Final response + H-->>Cli: 200, application/json + else A streaming method, or no such method + D-->>H: -32601 Method not found + H-->>Cli: application/json + end +``` + +- **The checks are the same.** The API key, the access token and the access filter run before anything streams, as + for every call. +- **A streaming method is answered as one that does not exist**, the same as any method the policy does not publish. +- **A published method answers once**, and a client reading the stream sees a call with no items. +- **An `Encrypted` result is bound to the streaming path.** The payload filter of Polhem.JsonRpc seals the result of a + call that arrived through the streaming path as the end of a stream with no items, so it opens only with the + streaming opener of `PayloadConnector.InvokeStreamingAsync`, not as an ordinary result. See + [Encrypted streams](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/streaming.md#encrypted-streams). + +## The framework's clients + +`PolhemApiClient` and its connectors make only ordinary calls. The remote provider's `HttpTransport` does not name +`text/event-stream` on an ordinary call, and the local provider calls the dispatcher in process, so none of the above +applies to them. A client in another language that calls Polhem sends ordinary requests as well +([JSON-RPC Frontend Integration](jsonrpc-frontend-integration.md)). + +## See also + +- [How an API call is processed](api-call-flow.md) +- Polhem.JsonRpc: [How a streamed call is processed](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/streaming.md) diff --git a/docs/zh-TW/README.md b/docs/zh-TW/README.md index b842c5e8..d83e8613 100644 --- a/docs/zh-TW/README.md +++ b/docs/zh-TW/README.md @@ -1,4 +1,4 @@ - + # Polhem 文件 [English](../en/README.md) @@ -40,6 +40,8 @@ |------|------|------| | [FormSchema 驅動的資料庫存取](definitions/formschema-data-access.md) | 概念 | Polhem.Db 如何以 FormSchema 為單位動態產生 SQL,以及它為何不是 ORM | | [API ↔ BO 契約設計](api/api-bo-contract-design.md) | 概念 | API 契約三層分離(Contracts / API Type / BO Type)與驅動它的命名慣例 | +| [一次 API 呼叫的處理流程](api/api-call-flow.md) | 概念 | 一次呼叫從用戶端 connector 到 business object 再回來:登入時交換的 session 金鑰、方法執行前的檢查,以及 MessagePack 本體怎麼選 | +| [一次串流呼叫的處理流程](api/api-streamed-calls.md) | 概念 | business object 為什麼不做串流,以及要求串流的呼叫者會拿到什麼 | | [專案相依性全景圖](architecture/dependency-map.md) | 概念 | `src/` 專案之間的相依關係,以及維持相依圖無環的規則 | | [快取機制](guides/caching.md) | 概念 | 定義快取與資料庫相依快取如何運作:讀取路徑、失效信號,以及跨 process / 多節點的通知表機制 | @@ -102,7 +104,7 @@ | **多租戶** | [租戶客製化](definitions/customization.md) · [定義檔全景](definitions/definition-files-overview.md) · [開發指引](guides/development-cookbook.md) · [快取機制](guides/caching.md) | | **快取與效能** | [快取機制](guides/caching.md) · [開發指引](guides/development-cookbook.md) · [開發限制與反模式](architecture/development-constraints.md) | | **用戶端 head 與平台** | [平台支援](getting-started/platform-support.md) · [清單查詢條件](guides/list-query-conditions.md) · [JSON-RPC 前端整合](api/jsonrpc-frontend-integration.md) · [開發指引](guides/development-cookbook.md) | -| **API 與前端** | [契約設計](api/api-bo-contract-design.md) · [API 方法參考](api/api-method-reference.md) · [JSON-RPC 前端整合](api/jsonrpc-frontend-integration.md) · [權限與授權](security/permission-authorization.md) · [API 金鑰管理](security/api-key-management.md) | +| **API 與前端** | [契約設計](api/api-bo-contract-design.md) · [API 呼叫流程](api/api-call-flow.md) · [串流呼叫](api/api-streamed-calls.md) · [API 方法參考](api/api-method-reference.md) · [JSON-RPC 前端整合](api/jsonrpc-frontend-integration.md) · [權限與授權](security/permission-authorization.md) · [API 金鑰管理](security/api-key-management.md) | | **型別與時間** | [時間型別總覽](database/temporal-types.md) · [時區處理](database/datetime-timezone.md) | | **品質與規範** | [Analyzer 規則](reference/analyzer-rules.md) · [開發限制與反模式](architecture/development-constraints.md) · [命名規範](database/database-naming-conventions.md) | diff --git a/docs/zh-TW/api/api-call-flow.md b/docs/zh-TW/api/api-call-flow.md new file mode 100644 index 00000000..e73e5da1 --- /dev/null +++ b/docs/zh-TW/api/api-call-flow.md @@ -0,0 +1,187 @@ + +# 一次 API 呼叫的處理流程 + +[English](../../en/api/api-call-flow.md) · [← 文件索引](../README.md) + +Polhem 框架怎麼處理一次 API 呼叫:從用戶端的 connector 方法,到伺服器上的 business object 方法,再回到用戶端。Polhem 的 API +建立在 Polhem.JsonRpc 套件之上:傳輸、dispatcher、filter 管線與 payload 外殼都屬於它們,寫在 Polhem.JsonRpc 的 +[一次呼叫的處理流程](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/request-flow.zh-TW.md)。本文只寫 Polhem +在上面加了什麼:呼叫者是誰、session 金鑰怎麼交換並進到外殼、business object 方法之前跑哪些檢查,以及 MessagePack 本體怎麼選。 +串流呼叫見 [api-streamed-calls.md](api-streamed-calls.md)。 + +設定值與預設值寫在持有它們的型別上;各步驟背後的理由記在各節連結的 ADR(英文)。 + +## 總覽 + +```mermaid +sequenceDiagram + participant App as 應用程式 + participant Con as ApiConnector
(System / Form / AuditLog) + participant Pr as Provider
(Remote 或 Local) + participant D as JsonRpcDispatcher + participant BO as Business object + + App->>Con: 例如 FormApiConnector.ExecuteAsync(action, value) + Con->>Pr: ProgId.Action,value 封進 payload 外殼 + Pr->>D: HTTP POST,或同一程序內呼叫 + D->>D: 呼叫者是誰、能不能呼叫這個方法 + D->>BO: Action(args) + BO-->>D: 結果 + D-->>Pr: JSON-RPC response,結果以同一格式封裝 + Pr-->>Con: 回應 + Con-->>App: 具型別的回應,或例外 +``` + +- **每次呼叫都帶 payload 外殼。** 在 Polhem.JsonRpc 裡 payload 套件是選用的;Polhem 的用戶端一律經過 `PayloadConnector`, + 伺服器一律執行 `PolhemPayloadFilter`。`Plain` 呼叫一樣有外殼,只是值是一般 JSON。 +- **兩種 provider,同一條路徑。** remote provider 透過 `HttpTransport` 送到 host 以 `MapJsonRpc` 對映的端點。local provider + (`PolhemApiClient.CreateLocal`)透過 `InProcessTransport` 直接進入同一程序的 dispatcher,所以下面的 HTTP 檢查不會執行, + 其餘都相同。 +- **一次 HTTP 呼叫只有一個請求。** `PolhemJsonRpc.CreateServerOptions` 建出的伺服器選項拒絕 batch,理由寫在該方法上。 + +## 登入:session 金鑰 + +`Encrypted` 呼叫需要一把兩端都有、其他人都沒有的金鑰。Polhem 在登入時為每個 session 發一把,以 RSA 交給用戶端。 + +```mermaid +sequenceDiagram + participant SC as SystemApiConnector + participant BO as SystemBusinessObject + participant KP as IApiEncryptionKeyProvider + participant S as Session 儲存 + + SC->>SC: 產生 RSA 金鑰對 + SC->>BO: System.Login(Encoded)
帳號、密碼、用戶端公鑰 + BO->>BO: 檢查鎖定、驗證帳密 + BO->>KP: GenerateKeyForLogin(新的 access token) + KP-->>BO: Session 金鑰 + BO->>S: 寫入 session seed,快取含金鑰的 SessionInfo + BO->>BO: 以用戶端公鑰加密金鑰 + BO-->>SC: Access token、加密後的金鑰、時區 + SC->>SC: 以私鑰解出金鑰
Session.SignIn(token, key, zone) +``` + +- **登入之前**,`SystemApiConnector.InitializeAsync` 以 `Plain` 呼叫讀取伺服器設定,採用其中的壓縮器與加密器。外殼不會寫出 + 這兩者,所以兩端必須一致;這份未經驗證的回答裡哪些部分用戶端不採用,寫在 `InitializeAsync` 上。 +- **登入本身是 `Encoded`**,因為這時還沒有金鑰。金鑰以用戶端的公鑰加密後傳回。 +- **金鑰提供者由部署決定**,由 `BackendComponents.ApiEncryptionKeyProvider` 指名。框架內附的提供者與預設是哪一個,列在 + [Polhem.Business README](../../../src/Polhem.Business/README.zh-TW.md#驗證與安全)。只把金鑰存在 session 裡的提供者,無法從 + seed 重建 session;見 [`IApiEncryptionKeyProvider`](../../../src/Polhem.Definition/Security/IApiEncryptionKeyProvider.cs) + 的 `SupportsSessionRebuild`。 +- **瀏覽器用戶端沒有 session 金鑰。** .NET 在 browser-wasm 上無法產生 RSA 金鑰,所以用戶端不送公鑰、也拿不到金鑰。它的 + `Encrypted` 呼叫會改以 `Encoded` 送出,要求 `Encrypted` 的方法會拒絕。 +- **加密不能取代 TLS。** 用戶端的公鑰與設定的回答都沒有經過驗證,在純 HTTP 上,中間人可以替換其中任何一個 + ([ADR-014](../../../maintainers/adr/adr-014-jsonrpc-plain-public-default.md))。 + +## 每次呼叫:金鑰進到外殼 + +登入之後,同一個用戶端的每個 connector 都用同一份憑證呼叫。在伺服器上,Polhem.JsonRpc 的 payload filter 透過 +`IPayloadServerPolicy` 提出的問題,由 Polhem 回答。 + +```mermaid +sequenceDiagram + participant Con as ApiConnector + participant PC as PayloadConnector + participant PF as PayloadFilter
(在 PolhemPayloadFilter 內) + participant Pol as PolhemPayloadPolicy + participant KP as IApiEncryptionKeyProvider + + Con->>PC: 格式、codec、session 金鑰、下一個序號 + PC->>PF: 以 session 金鑰封裝的請求 + PF->>Pol: GetKeyAsync + Pol->>KP: GetKey(這次呼叫的 access token) + KP-->>PF: Session 金鑰 + PF->>Pol: 重放範圍、是否要求唯一序號、payload 型別 + Pol-->>PF: Access token、ApiAccessControl 的 ReplayProtection、ActionPayloadType + PF->>PF: 打開請求(Polhem.JsonRpc) +``` + +- **用戶端每次呼叫只讀一次憑證**,所以送出的 token 與封裝用的金鑰一定屬於同一次登入,即使另一個執行緒同時重新登入也一樣。 +- **格式可能在用戶端被調低。** 非 debug 模式的 local 用戶端一律送 `Plain`;沒有 session 金鑰時,`Encrypted` 呼叫改以 + `Encoded` 送出。規則寫在 `ApiConnector` 上。收到的格式夠不夠,由伺服器決定,見下一節。 +- **序號來自 session**,同一個 session 的所有 connector 共用。伺服器只在方法宣告 `ReplayProtection = UniqueSequence`、 + host 要求 wire frame、而且是已登入的遠端呼叫時才檢查:見[重放防護](api-method-reference.md#重放防護)與 + [ADR-042](../../../maintainers/adr/adr-042-api-replay-protection.md)。 +- **參數型別由方法決定**,不採用呼叫者寫在外殼上的型別名稱。理由寫在 `ActionPayloadType` 上。 + +外殼怎麼封裝與打開(gzip、frame、AES-CBC 以及綁定方向與 method 的 HMAC)屬於 Polhem.JsonRpc:見 +[payload 外殼](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/request-flow.zh-TW.md#payload-外殼)。 + +## 伺服器:呼叫者是誰、能呼叫什麼 + +Polhem 掛在 dispatcher 的 object factory、method policy、兩個 filter、parameter binder 與 exception mapper 上,依下列順序執行: + +```mermaid +sequenceDiagram + participant D as JsonRpcDispatcher + participant OF as PolhemObjectFactory + participant AF as PolhemAccessFilter + participant PF as PolhemPayloadFilter + participant B as PolhemParameterBinder + participant BO as Business object + + D->>OF: CreateObject(ProgId) + OF->>OF: 僅限 HTTP:檢查 X-Api-Key 與 Authorization + OF-->>D: 這個 access token 的 business object + D->>D: 找 action(PolhemMethodPolicy) + D->>AF: 執行 filter + AF->>AF: ApiAccessValidator:存取需求、保護等級對照格式 + AF->>PF: next + PF->>PF: 打開外殼 + PF->>B: 綁定參數 + B->>BO: Action(args) + BO-->>PF: 結果 + PF->>PF: ApiOutputConverter,再封裝結果 + PF-->>AF: 完成 + AF->>AF: 記錄慢速呼叫 +``` + +- **呼叫者是誰。** 經 HTTP 的呼叫在 business object 建立之前就先檢查:`X-Api-Key` header 由 `IApiKeyValidator` 檢查 + ([API 金鑰管理](../security/api-key-management.md)),接著整個請求由 `IApiAuthorizationValidator` 檢查,它也從 + `Authorization` header 讀出 access token。沒有這個 header 的請求是匿名呼叫。同一程序內的呼叫由 transport 帶入 access + token,這裡不檢查。 +- **哪些方法存在。** `PolhemMethodPolicy` 只公開接受一個參數、而且受 + [`ApiAccessControlAttribute`](../../../src/Polhem.Definition/Attributes/ApiAccessControlAttribute.cs) 涵蓋(標在方法、 + 它覆寫的方法或類別上)的方法。其他方法一律當作不存在回答。analyzer 規則 POLHEM3001 會在建置時報出沒有涵蓋的公開方法 + ([Analyzer 規則](../reference/analyzer-rules.md))。 +- **這個呼叫者能不能呼叫。** `PolhemAccessFilter` 只讀外殼的 `format`,拿它對照 attribute:`Authenticated` 方法需要有效的 + access token,格式也必須達到方法的 [`ApiProtectionLevel`](../../../src/Polhem.Definition/Security/ApiProtectionLevel.cs)。 + `LocalOnly` 方法拒絕所有遠端呼叫。local 呼叫略過保護等級,但帶著過期 token 的仍會被拒絕。框架各方法的設定見 + [API 方法參考](api-method-reference.md)。 +- **存取 filter 先執行**,所以被拒絕的呼叫不會花任何解密與反序列化的成本。自行組伺服器選項的 host 必須保持這個順序;透過 + `AddJsonRpcServer` 加入的 filter 排在框架的之後。 +- **參數與結果會轉換。** binder 把打開的值讀成 wire 請求型別,再轉成 business 層的參數;`ApiOutputConverter` 在封裝之前把結果 + 轉成 wire 回應型別。三層的分工見 [API ↔ BO 契約設計](api-bo-contract-design.md)。 +- **錯誤。** `PolhemExceptionMapper` 透過錯誤契約,把例外轉成用戶端收到的錯誤;用戶端讀同一份契約重建例外 + ([ADR-043](../../../maintainers/adr/adr-043-error-contract-single-registry.md))。已登入的使用者能碰到哪些角色與資料, + 在 business object 內決定:見[權限與授權](../security/permission-authorization.md)。 + +## MessagePack 本體 + +`Encoded` 或 `Encrypted` 的本體由 codec 序列化,每個請求在外殼裡寫明自己的 codec,伺服器以請求用的 codec 回答。 + +```mermaid +flowchart LR + F{"format"} -->|Plain| J["值為一般 JSON
不用 codec"] + F -->|Encoded / Encrypted| C{"外殼裡的 codec"} + C -->|沒有寫| M["messagepack"] + C -->|messagepack| M + C -->|json| JS["json"] +``` + +- **.NET 用戶端**用 MessagePack,除非 `ApiConnector.PayloadCodec` 指名其他 codec,每個 connector 各自設定。框架的 formatter + 與 wire 契約是為 MessagePack 寫的([ADR-004](../../../maintainers/adr/adr-004-messagepack-payload.md)、 + [ADR-030](../../../maintainers/adr/adr-030-messagepack-name-based-keys.md)、 + [ADR-037](../../../maintainers/adr/adr-037-wire-explicit-registration.md))。 +- **其他語言的用戶端**指名 `json`,不需要 MessagePack:[JSON-RPC 前端整合](jsonrpc-frontend-integration.md)。 +- **沒有寫 codec 的請求以 MessagePack 讀取**,因為在 codec 協商之前的用戶端都不寫 + ([ADR-044](../../../maintainers/adr/adr-044-payload-codec-negotiation.md))。 +- **codec 只改變序列化那一步。** 壓縮、加密與 frame 對每種 codec 都一樣。兩端使用的選項由 `PolhemPayload` 組出,哪些不能改 + 寫在它的 remarks。 + +## 延伸閱讀 + +- [一次串流呼叫的處理流程](api-streamed-calls.md) +- [端到端開發手冊](../guides/development-cookbook.md#請求處理管線):以一張圖畫出整條請求管線 +- Polhem.JsonRpc:[一次呼叫的處理流程](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/request-flow.zh-TW.md) + 與 [security.zh-TW.md](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/security.zh-TW.md) diff --git a/docs/zh-TW/api/api-streamed-calls.md b/docs/zh-TW/api/api-streamed-calls.md new file mode 100644 index 00000000..f17c5cee --- /dev/null +++ b/docs/zh-TW/api/api-streamed-calls.md @@ -0,0 +1,64 @@ + +# 一次串流呼叫的處理流程 + +[English](../../en/api/api-streamed-calls.md) · [← 文件索引](../README.md) + +Polhem.JsonRpc 可以用串流回答一次呼叫:方法在回應之前,以 server-sent events 送出多個項目 +([一次串流呼叫的處理流程](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/streaming.zh-TW.md))。 +**Polhem 的 business object 不做串流。** 本文說明原因,以及要求串流的呼叫者從 Polhem 伺服器會拿到什麼。請先讀 +[一次 API 呼叫的處理流程](api-call-flow.md):串流呼叫在分歧點之前走的是同一條路徑。 + +## business object 為什麼不做串流 + +`PolhemMethodPolicy` 只公開接受一個參數的方法。串流方法還有第二個參數,也就是它的 `IJsonRpcStream`,所以不論標了什麼 +`ApiAccessControlAttribute`,都不會公開。 + +原因在 wire 型別。`PolhemPayloadFilter` 在封裝外殼之前,以 `ApiOutputConverter` 把方法的回傳值轉成 wire 回應型別。串流的 +項目是在方法執行中寫出的,不會經過這一步,會以 business 層的型別送出去。這項變更記在 +[1.17.0 版本說明](../changelogs/1.17.0.md#business-object-不公開串流方法)。 + +## 要求串流的呼叫者會拿到什麼 + +呼叫者在 `Accept` 寫明 `text/event-stream`,就是要求串流。HTTP 端點這時會走串流路徑,但串流要到串流方法即將執行時才開始。 +在 Polhem 上這永遠不會發生,所以呼叫以一般 JSON 回答。 + +```mermaid +sequenceDiagram + participant Cli as 用戶端 + participant H as JsonRpcHttpHandler + participant D as JsonRpcDispatcher + participant OF as PolhemObjectFactory + participant F as Polhem 的 filter + + Cli->>H: POST,Accept: application/json, text/event-stream + H->>D: DispatchStreamingAsync + D->>OF: CreateObject:API 金鑰與授權檢查 + D->>D: 找 action(PolhemMethodPolicy) + alt 有公開的方法 + D->>F: 存取檢查、外殼、呼叫 + F-->>D: 結果 + D-->>H: 最終回應 + H-->>Cli: 200,application/json + else 串流方法,或沒有這個方法 + D-->>H: -32601 Method not found + H-->>Cli: application/json + end +``` + +- **檢查都一樣。** API 金鑰、access token 與存取 filter 都在任何串流開始之前執行,與每次呼叫相同。 +- **串流方法被當作不存在回答**,與任何 policy 不公開的方法相同。 +- **有公開的方法只回答一次**,讀串流的用戶端看到的是一次沒有項目的呼叫。 +- **`Encrypted` 的結果綁定串流路徑。** 經串流路徑進來的呼叫,Polhem.JsonRpc 的 payload filter 會把結果封裝成「沒有項目的串流 + 結尾」,所以只能以 `PayloadConnector.InvokeStreamingAsync` 的串流開啟方式打開,不能當作一般結果打開。見 + [加密的串流](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/streaming.zh-TW.md#加密的串流)。 + +## 框架的用戶端 + +`PolhemApiClient` 與它的 connector 只發一般呼叫。remote provider 的 `HttpTransport` 在一般呼叫上不寫 +`text/event-stream`,local provider 則在同一程序內呼叫 dispatcher,所以上述情形都不適用於它們。以其他語言呼叫 Polhem 的 +用戶端也一樣送一般請求([JSON-RPC 前端整合](jsonrpc-frontend-integration.md))。 + +## 延伸閱讀 + +- [一次 API 呼叫的處理流程](api-call-flow.md) +- Polhem.JsonRpc:[一次串流呼叫的處理流程](https://github.com/polhem-dev/polhem-jsonrpc/blob/main/docs/streaming.zh-TW.md)