Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/en/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down Expand Up @@ -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) |

Expand Down
209 changes: 209 additions & 0 deletions docs/en/api/api-call-flow.md
Original file line number Diff line number Diff line change
@@ -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<br/>(System / Form / AuditLog)
participant Pr as Provider<br/>(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)<br/>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<br/>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<br/>(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<br/>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)
69 changes: 69 additions & 0 deletions docs/en/api/api-streamed-calls.md
Original file line number Diff line number Diff line change
@@ -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<T>`, 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)
Loading