@cratis/pi 8.15.0 → 8.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package/corpus/skills/cratis-arc-authorize-request/references/authproxy.md +3 -0
- package/package/corpus/skills/cratis-arc-authorize-request/references/csharp.md +21 -0
- package/package/corpus/skills/cratis-arc-diagnose-live-query/references/csharp.md +19 -6
- package/package/corpus/skills/cratis-arc-expose-query/references/csharp.md +12 -2
- package/package/corpus/skills/cratis-arc-generate-proxies/SKILL.md +1 -1
- package/package/corpus/skills/cratis-arc-host-application/SKILL.md +1 -1
- package/package/corpus/skills/cratis-arc-host-application/references/csharp.md +27 -0
- package/package/corpus/skills/cratis-arc-localize-application/SKILL.md +3 -2
- package/package/corpus/skills/cratis-arc-localize-application/references/csharp.md +1 -1
- package/package/corpus/skills/cratis-arc-localize-application/references/typescript-tooling.md +3 -0
- package/package/corpus/skills/cratis-arc-localize-application/references/typescript.md +32 -0
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-localization.md +26 -2
- package/package/corpus/skills/cratis-arc-react-separate-view-model/SKILL.md +1 -1
- package/package/corpus/skills/cratis-arc-react-separate-view-model/references/typescript.md +31 -1
- package/package/corpus/skills/cratis-arc-storage-typescript/SKILL.md +1 -1
- package/package/corpus/skills/cratis-arc-storage-typescript/references/typescript-drizzle.md +2 -0
- package/package/corpus/skills/cratis-authproxy-configure/SKILL.md +3 -2
- package/package/corpus/skills/cratis-authproxy-configure/references/admission.md +6 -4
- package/package/corpus/skills/cratis-authproxy-configure/references/services-and-routing.md +12 -1
- package/package/corpus/skills/cratis-authproxy-configure/references/sessions-and-logout.md +47 -7
- package/package/corpus/skills/cratis-chronicle-cli-operations/SKILL.md +1 -1
- package/package/corpus/skills/cratis-chronicle-connect-application/references/csharp-patterns.md +3 -1
- package/package/corpus/skills/cratis-chronicle-connect-application/references/elixir-patterns.md +2 -1
- package/package/corpus/skills/cratis-chronicle-connect-application/references/go-patterns.md +3 -1
- package/package/corpus/skills/cratis-chronicle-connect-application/references/go.md +3 -3
- package/package/corpus/skills/cratis-chronicle-connect-application/references/java.md +40 -2
- package/package/corpus/skills/cratis-chronicle-connect-application/references/kotlin-patterns.md +3 -2
- package/package/corpus/skills/cratis-chronicle-connect-application/references/kotlin.md +2 -2
- package/package/corpus/skills/cratis-chronicle-connect-application/references/typescript-patterns.md +2 -1
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/upgrade-and-recovery.md +14 -0
- package/package/corpus/skills/cratis-chronicle-project-view/SKILL.md +11 -10
- package/package/corpus/skills/cratis-chronicle-project-view/references/join-precedence.md +38 -0
- package/package/corpus/skills/cratis-chronicle-project-view/references/typescript.md +1 -1
- package/package/corpus/skills/cratis-chronicle-protect-decision/references/csharp.md +11 -2
- package/package/corpus/skills/cratis-chronicle-react-to-fact/SKILL.md +17 -1
- package/package/corpus/skills/cratis-chronicle-record-event/references/go.md +11 -0
- package/package/corpus/skills/cratis-chronicle-select-client/references/python.md +8 -1
- package/package/corpus/skills/cratis-code-review/SKILL.md +5 -0
- package/package/corpus/skills/cratis-components-submit-form/SKILL.md +1 -1
- package/package/corpus/skills/cratis-components-submit-form/references/typescript-commanddialog.md +1 -0
- package/package/corpus/skills/cratis-platform-deliver-slice/SKILL.md +3 -0
- package/package/corpus/skills/cratis-platform-deliver-slice/references/csharp.md +9 -3
- package/package/corpus/skills/cratis-platform-start-application/SKILL.md +1 -1
- package/package/corpus/skills/cratis-platform-start-application/references/csharp.md +5 -0
- package/package/corpus/skills/cratis-platform-upgrade-application/SKILL.md +2 -2
- package/package/corpus/skills/cratis-platform-upgrade-application/references/csharp.md +1 -0
- package/package/corpus/skills/cratis-platform-upgrade-application/references/typescript.md +1 -1
- package/package/corpus/skills/cratis-screenplay-declare-slice/SKILL.md +2 -2
- package/package/corpus/skills/cratis-screenplay-declare-slice/references/commands.md +9 -0
- package/package/corpus/skills/cratis-screenplay-declare-slice/references/read-identity.md +1 -1
- package/package/corpus/skills/cratis-screenplay-declare-slice/references/structure-and-imports.md +1 -1
- package/package/corpus/skills/cratis-screenplay-model-automation/SKILL.md +8 -10
- package/package/corpus/skills/cratis-screenplay-model-interaction/SKILL.md +9 -8
- package/package/corpus/skills/cratis-screenplay-model-interaction/references/csharp-host-api.md +12 -1
- package/package/corpus/skills/cratis-screenplay-model-interaction/references/csharp.md +1 -0
- package/package/corpus/skills/cratis-screenplay-model-interaction/references/localized-strings.md +2 -0
- package/package/corpus/skills/cratis-screenplay-model-interaction/references/shell-and-data.md +21 -0
- package/package/corpus/skills/cratis-specifications-exercise-backend/SKILL.md +1 -1
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-command-results.md +9 -2
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-events.md +9 -1
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-query-scenario.md +2 -2
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-reactors.md +1 -0
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-read-models.md +13 -1
- package/package/profile-catalog.json +2 -0
- package/package.json +1 -1
|
@@ -29,9 +29,12 @@ This reference covers what the application may rely on and which paths a service
|
|
|
29
29
|
| --- | --- | --- |
|
|
30
30
|
| A person in a browser | Nothing; this is the default | The signed-in principal and tenant. |
|
|
31
31
|
| A program with an access token from an authorization server (CLI, MCP client, another service) | A `BearerRoutes` entry with `Issuers` | The principal built from the validated token, without the token's role claims, and the tenant from the token's tenant claim. |
|
|
32
|
+
| A program you run (importer, scanner, job), with a client id and secret the application stores | `ClientCredentials` on the service; the program gets a token at `POST /.cratis/token`. Set it up with `cratis-authproxy-configure`. | A principal the proxy authenticated, and the tenant the application named for that client. |
|
|
32
33
|
| A program with a personal access token | A `BearerRoutes` entry with `PersonalAccessTokens` | The unverified token in `Authorization`; no principal and no tenant. |
|
|
33
34
|
| Anyone, without an account (health, public content, public metadata, a signed link, a signed webhook) | An `AnonymousPaths` entry | No identity at all. |
|
|
34
35
|
|
|
36
|
+
For a caller you run yourself (your own importer, scanner or webhook sender), default to client credentials: the proxy authenticates it and the application receives a caller it can trust. Use an `AnonymousPaths` entry only when a third party signs requests its own way and cannot fetch a token. Avoid an anonymous path guarded by an API key the application checks itself.
|
|
37
|
+
|
|
35
38
|
```json
|
|
36
39
|
{
|
|
37
40
|
"Cratis": {
|
|
@@ -62,6 +62,27 @@ public sealed class OwnsShift(IShiftStore shifts) : StateAwareAuthorizationPolic
|
|
|
62
62
|
|
|
63
63
|
For a decision without a keyed read, implement `IAuthorizationPolicy.IsAuthorized(AuthorizationPolicyContext context, CancellationToken cancellationToken)` returning `ValueTask<bool>`, e.g. `ValueTask.FromResult(context.Principal.HasClaim("training", "dispatch"))`. `Target` identifies the type or query method; `Resource` is the executing `CommandContext` or `QueryContext`. `ReceivedAt` is fixed for this operation. Use `ValuesAs<ShiftFacts>()` for typed provided values, `ProvidedValues` for the container or `Values` for dynamic lookup. Keep providers, execution-scope setup and policy evaluation free of irreversible effects. For an authorization refusal decided inside a command, return `AuthorizationResult.Failure("Shift access denied")` before effects; do not use a validation error for lack of permission.
|
|
64
64
|
|
|
65
|
+
**Rules about when a request arrived** (office hours, a cut-off, weekdays). Default: decide on `context.ReceivedAt`.
|
|
66
|
+
|
|
67
|
+
```csharp
|
|
68
|
+
public class WeekdayAdmission : IAuthorizationPolicy
|
|
69
|
+
{
|
|
70
|
+
public ValueTask<bool> IsAuthorized(AuthorizationPolicyContext context, CancellationToken cancellationToken)
|
|
71
|
+
{
|
|
72
|
+
if (context.ReceivedAt == default) return ValueTask.FromResult(false); // no receipt: deny
|
|
73
|
+
var weekday = context.ReceivedAt.UtcDateTime.DayOfWeek;
|
|
74
|
+
return ValueTask.FromResult(weekday != DayOfWeek.Saturday && weekday != DayOfWeek.Sunday);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
- `ReceivedAt` is a `DateTimeOffset`, equal to `Resource.ReceivedAt`. It stays the same when evaluation is delayed or repeated, so a slow lookup cannot move a request across a boundary.
|
|
80
|
+
- It is the moment Arc received the operation, taken before binding at a model-bound endpoint. It is not network arrival time. In an MVC controller it is taken after MVC binding.
|
|
81
|
+
- Each hub subscribe operation gets its own receipt, not the connection's. The policy admits that new subscription only; it never ends a stream that is already open. Use a delivery guard for that.
|
|
82
|
+
- A context built by hand has a default `ReceivedAt`. Deny it, as above.
|
|
83
|
+
- In a spec set `ReceivedAt` on the context. In a host-level test register a controllable `TimeProvider`; it takes precedence over Arc's whether registered before or after `AddCratisArcCore()`.
|
|
84
|
+
- Avoid `DateTimeOffset.UtcNow` or `TimeProvider.GetUtcNow()` inside the policy, above all after an `await`, and keeping the receipt as per-user state.
|
|
85
|
+
|
|
65
86
|
Policies normally require sign-in. Only for intentional guest evaluation, pass `evaluatesAnonymous: true` in the registration. For a native ASP.NET policy register it with the host and opt in separately with `builder.Services.AddArcAnonymousAspNetAuthorizationPolicy("guest-preview");`. Every stacked requirement must be an opted-in policy without roles or schemes; the policy still decides. Unknown or duplicate policy names are configuration errors.
|
|
66
87
|
|
|
67
88
|
On ASP.NET Core a policy registered with the host, e.g. `builder.Services.AddAuthorizationBuilder().AddPolicy("owns-shift", policy => policy.RequireClaim("training", "dispatch"));`, is evaluated for the same `Policy` name. Its handlers receive Arc's `CommandContext` or `QueryContext` as the resource, not an MVC resource. Register a name either with Arc or with ASP.NET Core, never both: a name found in both or in neither is a configuration error.
|
|
@@ -2,15 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
## Contents
|
|
4
4
|
|
|
5
|
-
-
|
|
6
|
-
-
|
|
7
|
-
-
|
|
8
|
-
-
|
|
9
|
-
|
|
10
|
-
Use the application's ASP.NET Core Arc host (`builder.AddCratisArc()`); for sockets put `app.UseWebSockets()` before `app.UseCratisArc()`. Use the generated proxy's route for HTTP probes. For hub controls use the query name the server registered (see below); the proxy's `queryName` is only a starting point, and neither is inferred from the URL. Names below are illustrative. Use a test caller, authorized tenant and non-sensitive data; keep real credentials out of transcripts.
|
|
5
|
+
- Establish the baseline
|
|
6
|
+
- Find the first missing identity
|
|
7
|
+
- When the source is EF Core
|
|
8
|
+
- Compare the hub subscription
|
|
9
|
+
- Distinguish idle, overload and access failures
|
|
11
10
|
|
|
12
11
|
## Establish the baseline
|
|
13
12
|
|
|
13
|
+
Use the application's ASP.NET Core Arc host (`builder.AddCratisArc()`); for sockets put `app.UseWebSockets()` before `app.UseCratisArc()`. Use the generated proxy's route for HTTP probes. For hub controls use the query name the server registered (see below); the proxy's `queryName` is only a starting point, and neither is inferred from the URL. Names below are illustrative. Use a test caller, authorized tenant and non-sensitive data; keep real credentials out of transcripts.
|
|
14
|
+
|
|
14
15
|
Set `route` to the absolute query URL without query parameters. Configure curl with the same credentials and tenant selection as the caller. A snapshot and a subscription are different requests:
|
|
15
16
|
|
|
16
17
|
```sh
|
|
@@ -38,6 +39,18 @@ curl -i -X QUERY "$route" -H 'Content-Type: application/json' \
|
|
|
38
39
|
4. If the source emits, check caller restrictions and `IGuardObservableQueryEmission.Guard(context)`: `Allow` delivers, `Suppress` skips this candidate, `DenyAndTerminate` ends delivery as a denial, `Unavailable` ends it as a temporary failure of the check (see the last section). With several guards the caller sees one combined verdict: `DenyAndTerminate` overrides `Unavailable`, which overrides `Suppress`, which overrides `Allow`, so check every registered guard, not only the one you suspect. A throwing guard fails closed as a denial. Distinguish this from a query rejected at opening (arguments, authentication or authorization). Record correlation ID and outcome, not credentials. After an identity/tenant change, establish a fresh subscription.
|
|
39
40
|
5. Inspect whole SSE `data:` events, not individual chunks. From the skill directory run `node scripts/check-frames.mjs < capture.sse` after stopping capture. It skips not-ready events and requires two successful frames; independently confirm the second contains the test ID. If direct SSE works, follow the actual hub frames before changing the source. For a direct socket comparison, open the same query URL and arguments with `wss:` (or `ws:` for HTTP) using a WebSocket client with the same scope; verify both upgrade and a later result.
|
|
40
41
|
|
|
42
|
+
## When the source is EF Core
|
|
43
|
+
|
|
44
|
+
An EF Core `Observe()` source re-queries when it is notified; it has no change stream to watch, and nothing polls in place of a missing notifier. Match the symptom before changing the query:
|
|
45
|
+
|
|
46
|
+
| Symptom | Cause | Check |
|
|
47
|
+
| --- | --- | --- |
|
|
48
|
+
| A write from another process, or raw or bulk SQL, never arrives | Only `SaveChanges` on a context with Arc's interceptor is seen in process. Everything else needs the provider's notifier: `LISTEN/NOTIFY` on PostgreSQL, `SqlDependency` on SQL Server, none on SQLite. | The log for a notifier that failed to start (observation then continues in-process only), the PostgreSQL trigger, SQL Server Service Broker and its query-notification permissions. |
|
|
49
|
+
| Intermediate states are missing | A notification re-runs the query and emits the current result. It is not a change log. | Expected. Model the states as data if every one matters. |
|
|
50
|
+
| Callbacks, connections or listeners remain after clients leave or the host stops | A disconnect disposes that client's subscription only. Only completing the subject releases the observation. | Who owns the subject and where it is completed; see `cratis-arc-expose-query`. |
|
|
51
|
+
| Every client loses the stream when one leaves | The shared subject was completed on a single disconnect. | Complete it only when the observation itself ends. |
|
|
52
|
+
| A change to an included relationship does not refresh | The observation follows the root table. | Observe the related set too and re-evaluate on either. |
|
|
53
|
+
|
|
41
54
|
## Compare the hub subscription
|
|
42
55
|
|
|
43
56
|
Open `/.cratis/queries/ws` by WebSocket. `Connected.payload` is the physical connection ID, **not** a subscription. For a revision-capable connection (`supportsSubscriptionRevisions`), a pair of client controls looks like this. Set `queryName` to the exact name the server registered for the query, never the HTTP route. For a model-bound query this is usually the read model's full type name (namespace included), then `.` and the method name; generated query metadata can register a different name. For a controller action it is the full type name of the concrete controller that serves the action, then `.` and the method name. The generated proxy's `queryName` usually matches, but not always. For an action inherited from a base controller, the proxy uses the base class name: that name never selects the derived controller's action, and selects the base controller's own action only if that is registered separately. Use the concrete controller's name instead:
|
|
@@ -169,7 +169,7 @@ An ordinary controller GET that Arc wraps (no `[AspNetResult]`) turns a returned
|
|
|
169
169
|
|
|
170
170
|
## Observable sources
|
|
171
171
|
|
|
172
|
-
An observable query returns `ISubject<T>` or `ISubject<IEnumerable<T>>`. Prefer a provider source: it emits the current result, re-emits on change, and stops watching when the subscriber leaves.
|
|
172
|
+
An observable query returns `ISubject<T>` or `ISubject<IEnumerable<T>>`. Prefer a provider source: it emits the current result, re-emits on change, and on MongoDB stops watching when the subscriber leaves. An EF Core observation needs an owned lifetime (below).
|
|
173
173
|
|
|
174
174
|
| Source | Emits | Notes |
|
|
175
175
|
| --- | --- | --- |
|
|
@@ -187,6 +187,16 @@ An observable query returns `ISubject<T>` or `ISubject<IEnumerable<T>>`. Prefer
|
|
|
187
187
|
|
|
188
188
|
MongoDB observation needs change streams: a replica set or sharded cluster. A standalone server fails with `MongoDBChangeStreamsNotSupported`. With the EF integration (`arc.WithEntityFrameworkCore()`), use `db.Permits.Observe(p => p.Zone == zone)`; its collection overload also accepts `ignoreQueryContext: true`. For an independently configured EF context, register `services.AddEntityFrameworkCoreObservation()` and call `options.AddObservation(serviceProvider)` on its options builder. EF Core observation refreshes on `SaveChanges` through an Arc-registered context, plus `LISTEN/NOTIFY` on PostgreSQL and `SqlDependency` on SQL Server; SQLite sees only in-process writes.
|
|
189
189
|
|
|
190
|
+
**An EF Core observation outlives its subscribers.** The subject owns change callbacks and a database notifier, and only completing the subject releases them. This differs from MongoDB observation, whose subject follows subscriber disposal.
|
|
191
|
+
|
|
192
|
+
- A client disconnect disposes that client's subscription only. Arc never completes the EF subject, so a query method that returns `db.Permits.Observe(...)` directly keeps its callbacks and notifier after the client has gone. A plain GET snapshot, also with `waitForFirstResult=true`, changes nothing about that.
|
|
193
|
+
- Default: give the observation an application-owned producer lifetime. A component the application owns creates the subject, keeps it, hands it to the query method and calls `OnCompleted()` on it when the observation is finished, at the latest on shutdown. Disposing an Rx subscription does not stop the observation.
|
|
194
|
+
- Never complete a shared subject because one client left: that ends the stream for every other client.
|
|
195
|
+
- Completion starts the cleanup; it does not wait for the notifier to be disposed. A later query failure reaches subscribers through `OnError` and ends the observation too.
|
|
196
|
+
- Test a disconnect, several concurrent clients and shutdown before releasing the query.
|
|
197
|
+
|
|
198
|
+
**A notification triggers a re-query; it is not a change log.** Each one re-runs the query and emits the current result, so intermediate states can be skipped, and a subscriber that joins later gets the current result, never the history. Nothing polls in place of a missing notifier. A write that bypasses `SaveChanges` on a context with Arc's interceptor (raw or bulk SQL, another process) is seen only through the provider's database notifier, which SQLite does not have. A notifier that fails to start is logged and the observation continues with in-process writes only, so prove an external write against a test database before relying on one. A change to an included relationship does not by itself refresh the root observation.
|
|
199
|
+
|
|
190
200
|
A plain GET on an observable route is a snapshot. When the subject exposes no readable `Value` property the snapshot answers 202 with `isReady: false`; add `waitForFirstResult=true` to wait, and `waitForFirstResultTimeout=<seconds>` to bound the wait (default 30 seconds; 408 when it expires). An application-owned `BehaviorSubject<T>` has a current value and answers 200.
|
|
191
201
|
|
|
192
202
|
Always add `waitForFirstResult=true` to a plain GET on a MongoDB `Observe()` query. Without it the request answers 202, never an empty collection, and can leave the database watcher that `Observe()` started running, because nothing subscribes to the subject or disposes it. With it Arc subscribes, returns the first result that the emission guards allow and disposes the subscription. A suppressed emission is skipped and the wait continues until an allowed emission, a terminal verdict (403 or 503), the timeout (408), or the source failing or completing before any allowed result (500). This waiting applies to an observable subject; an `IAsyncEnumerable<T>` snapshot runs to completion instead, leaves out suppressed items and answers 200 with the allowed ones, even when that is none.
|
|
@@ -257,7 +267,7 @@ public class RequireTenant(ICurrentPrincipalAccessor principals) : IAuthorizatio
|
|
|
257
267
|
|
|
258
268
|
Read the caller through an injected `ICurrentPrincipalAccessor` (`Cratis.Arc.Authorization`). Do not use `QueryContext.AuthorizedPrincipal`: it is set only when scheme authentication selected a different principal and is otherwise `null`, so a check on it denies ordinary callers. Return `QueryResult.Success(...)` to continue, `QueryResult.Unauthorized(...)` to deny (403), and `QueryResult.WithValidationError(correlationId, member, message)` to reject input (400). Built-in filters already cover availability, the query's `[Authorize]`/`[Roles]`/`[AllowAnonymous]` declarations, DataAnnotations on parameters, and FluentValidation validators.
|
|
259
269
|
|
|
260
|
-
With the availability integration configured, `[Available<PermitServiceOnline>]` gates the read model using an application `AvailabilityBlock`, not an authorization policy. For admission require a policy with `[Authorize(Policy = "permit-read")]`, opt a deliberately public query out with `[AllowAnonymous]`, or restrict the query with `[Roles("PermitInspector")]` from `Cratis.Arc.Authorization`. For local validation put `[StringLength(40)]` on `string text`. For a whole-argument rule on `Search(string text, IMongoCollection<ParkingPermit> collection)`, put this model and validator in the read model assembly:
|
|
270
|
+
With the availability integration configured, `[Available<PermitServiceOnline>]` gates the read model using an application `AvailabilityBlock`, not an authorization policy. For admission require a policy with `[Authorize(Policy = "permit-read")]`, opt a deliberately public query out with `[AllowAnonymous]`, or restrict the query with `[Roles("PermitInspector")]` from `Cratis.Arc.Authorization`. Admission is decided once per operation: each hub subscribe is its own operation with its own receipt time, and a policy admits that new subscription only, never ending a stream that is already open. Time-based admission rules: `cratis-arc-authorize-request`; ending an open stream: Emission guards below. For local validation put `[StringLength(40)]` on `string text`. For a whole-argument rule on `Search(string text, IMongoCollection<ParkingPermit> collection)`, put this model and validator in the read model assembly:
|
|
261
271
|
|
|
262
272
|
```csharp
|
|
263
273
|
public record ParkingPermitSearchParameters(string Text);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: cratis-arc-generate-proxies
|
|
3
|
-
description: Use when generating or updating typed clients from Arc backend operations, configuring generator inputs or diagnosing stale files and route mismatches. Not for consuming a generated hook in a view (use cratis-arc-react-bind-slice).
|
|
3
|
+
description: Use when generating or updating typed clients from Arc backend operations, configuring generator inputs (output path, file naming, the client validation mode that lets the server word or localize validation messages) or diagnosing stale files and route mismatches. Not for consuming a generated hook in a view (use cratis-arc-react-bind-slice) or authoring the validation rules themselves (use cratis-arc-validate-command).
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Generate the typed client
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: cratis-arc-host-application
|
|
3
|
-
description: Use when creating, configuring or starting an Arc application host - choosing the bootstrap, setting host options, wiring authentication and identity details, serving a frontend, giving a known application exception a public failure status, stable error code and optional Retry-After instead of the default 500, gating product parts with feature availability (audiences, and audience or suspension sources that every replica shares) - and when verifying that the host serves a registered endpoint. Not for
|
|
3
|
+
description: Use when creating, configuring or starting an Arc application host - choosing the bootstrap (including adding Chronicle to an existing Arc host through the `Cratis` package), setting host options, wiring authentication and identity details, serving a frontend, giving a known application exception a public failure status, stable error code and optional Retry-After instead of the default 500, gating product parts with feature availability (audiences, and audience or suspension sources that every replica shares) - and when verifying that the host serves a registered endpoint. Not for a Chronicle client's connection string, TLS or readiness (use cratis-chronicle-connect-application), protecting one operation (use cratis-arc-authorize-request), selecting a tenant (use cratis-arc-isolate-tenant) or adding services or configuration to a Stage-rendered application, whose host and settings files are generated (use cratis-stage-render-slice).
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Host an Arc application
|
|
@@ -49,6 +49,26 @@ app.Run();
|
|
|
49
49
|
|
|
50
50
|
`AddCratis` takes `configureArcOptions`, `configureArcBuilder`, `configureChronicleOptions` and `configureChronicleBuilder`. It authenticates nobody until `TrustForwardedIdentityHeaders` is enabled or another scheme is registered; see [authentication and identity](csharp-identity.md).
|
|
51
51
|
|
|
52
|
+
### Add Chronicle to an existing Arc host
|
|
53
|
+
|
|
54
|
+
Default: reference the `Cratis` package in the ASP.NET Core host and replace `AddCratisArc()` / `UseCratisArc()` with `AddCratis()` / `UseCratis()`, moving the existing callbacks to `configureArcOptions` and `configureArcBuilder`.
|
|
55
|
+
|
|
56
|
+
- **Exception, the host brings its own authentication:** keep the `Cratis` package reference and split the registration, which leaves out the Microsoft Identity Platform header scheme. `UseCratis()` calls both activations, so a split host calls both itself:
|
|
57
|
+
|
|
58
|
+
```csharp
|
|
59
|
+
builder.AddCratisArc(configureBuilder: arc =>
|
|
60
|
+
Microsoft.AspNetCore.Builder.ArcBuilderExtensions.WithChronicle(arc));
|
|
61
|
+
|
|
62
|
+
var app = builder.Build();
|
|
63
|
+
app.UseCratisArc();
|
|
64
|
+
app.UseCratisChronicle();
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The explicit static call selects the ASP.NET Core `WithChronicle`; the generic-host one has the same name.
|
|
68
|
+
- **Avoid** referencing only `Cratis.Arc.Chronicle` in an ASP.NET Core host: it supplies the generic-host integration, not the ASP.NET Core extensions above. Avoid registering the Chronicle client beside `AddCratisArc()` without `WithChronicle`: Arc then does not know about Chronicle, and `ARCCHR0005` reports it when the project uses Chronicle types.
|
|
69
|
+
- **Registration starts no kernel.** Run a compatible Chronicle kernel and configure connection, event store and namespace (`cratis-chronicle-connect-application`). The existing read-model storage registration (`Cratis.Arc.MongoDB` or Entity Framework Core) stays, and sharing a host does not align it with Chronicle's sink: database, collection or table naming, key mapping and serialization must match for an existing query to read what a projection writes.
|
|
70
|
+
- **Existing rows are not history.** Adding a projection does not turn stored rows into events: decide how they become events (import initial facts, backfill, or cut over to a new model) and stop the old direct writes before the projection runs. Moving a decision onto events is `cratis-chronicle-protect-decision`.
|
|
71
|
+
|
|
52
72
|
For trusted in-process commands and queries without a listener, reference `Cratis.Arc.Core` and use `Host.CreateDefaultBuilder(args).AddCratisArcCore().Build()` (`using Cratis.Arc;`). Do not pass `configureBuilder` on that overload: it throws. Register dependencies through the generic host instead.
|
|
53
73
|
|
|
54
74
|
See [host configuration](csharp-configuration.md) for route contracts, validation, tenancy, observables and operational settings. For a capability port, read [verified callers](csharp-callers.md).
|
|
@@ -183,6 +203,13 @@ if (app.Environment.IsDevelopment())
|
|
|
183
203
|
|
|
184
204
|
`MapCratisEventModel(assemblies)` returns a route group, so `.RequireAuthorization()` puts the whole viewer behind the host's policy. Opt out of automatic mapping with `builder.Services.AddCratisEventModelViewer(options => options.Enabled = false)`.
|
|
185
205
|
|
|
206
|
+
Whether the build contains the documents and whether the host serves them are two separate decisions; a viewer outside Development needs both.
|
|
207
|
+
|
|
208
|
+
- **Documents.** A direct reference to `Cratis.Arc.Screenplay.Embedded` generates them in every configuration. The `Cratis` package leaves them out of a Release build: set `<CratisEmbeddedScreenplayEnabled>true</CratisEmbeddedScreenplayEnabled>` in the application project to ship them. Setting it to `false` keeps them out; removing the mapping does not remove documents already embedded.
|
|
209
|
+
- **Serving.** Automatic mapping covers only a Debug build running in Development. Default for a shared environment such as staging: ship the Release build with the documents enabled, and map the viewer explicitly for that environment behind a policy, `app.MapCratisEventModel().RequireAuthorization("Developers")`. The host must have authentication and that policy registered; the group covers the viewer, its assets and every document query.
|
|
210
|
+
- **Exception, keep `UseCratis()` mapping it:** `AddCratisEventModelViewer(options => { options.Enabled = true; options.RequireAuthorization = true; options.AuthorizationPolicy = "Developers"; })`. `Enabled = true` alone serves the viewer in any build and environment, adds no authorization and generates no documents.
|
|
211
|
+
- **Avoid** running a promoted image as Development or shipping a Debug build to get the viewer. It reveals commands, events, read models and feature boundaries, and is unauthenticated by default.
|
|
212
|
+
|
|
186
213
|
## Declare availability
|
|
187
214
|
|
|
188
215
|
When a part is offered only to some tenants, users or system callers (a package, staged rollout, preview or incident switch), register `arc.WithAvailability()`. Read [availability](csharp-availability.md) for audience and suspension sources, typed gate declarations, asking whether one part is available for given input (`IUnavailableParts.Get(PartQuestion)`), and building or evaluating the availability manifest file. Availability is not authorization; `cratis-screenplay-availability` teaches the declaration language.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: cratis-arc-localize-application
|
|
3
|
-
description: Use when an Arc application with a React frontend must show screens, refusals and widget text in more than one language, add a language, add a language switcher
|
|
3
|
+
description: Use when an Arc application with a React frontend must show screens, refusals and widget text in more than one language, add a language, add a language switcher, hand translation files to a translation service, or find out why a language shows English or another visitor's language (a refused or missing catalog pack after a package upgrade, server-rendered pages, validation messages the server should word). Not for the backend culture settings alone (use cratis-arc-host-application), a single-language literal-tree setup (use cratis-arc-react-bind-slice), restyling Components (use cratis-components-theme-application) or version pairing and upgrade order (use cratis-platform-upgrade-application).
|
|
4
4
|
compatibility: Needs an Arc backend and an Arc React frontend. The optional localization tooling needs a Node.js version its package supports.
|
|
5
5
|
---
|
|
6
6
|
|
|
@@ -21,7 +21,8 @@ Read `references/<language>.md` for the project's SDK (`.csproj` → csharp, Nod
|
|
|
21
21
|
3. **Mount once.** Create one locale store with one catalog registry, pass it to `<Arc locale>` at the root and register every feature the root can show; loaders are lazy per language, not per route. Done when the network panel requests no language outside the selected one, its parents, the default and English.
|
|
22
22
|
4. **Add a language.** Add one translated file per feature, sparse overrides for platform text, and an optional pack for platform text. Omit untranslated keys so they fall back to English. Done when `cratis-l10n check` (or your own check) passes and the screen shows the language.
|
|
23
23
|
5. **Add the switcher and verify on an open route.** Never reload to switch. Done when the switch checks pass, including a late refusal and an unsaved draft.
|
|
24
|
-
6. **
|
|
24
|
+
6. **Server-rendered pages only:** create one locale store per request from the request's headers and hydrate the browser store from its snapshot. Never share one store between requests. See Server rendering in `typescript.md`.
|
|
25
|
+
7. **Optional: generate loaders and types** with the `cratis-l10n` tool, hand translation files to a translation service and diagnose a missing pack. Hand-written wiring is equally valid.
|
|
25
26
|
|
|
26
27
|
## Rules
|
|
27
28
|
|
|
@@ -41,7 +41,7 @@ The selection sets `CultureInfo.CurrentUICulture` for the request only. Formatti
|
|
|
41
41
|
## Refusals
|
|
42
42
|
|
|
43
43
|
- The server keeps sending a stable `reason`, `reasonDetail` and English `message`. The client maps these to its catalog. There is no server catalog package; the client supplies the text.
|
|
44
|
-
-
|
|
44
|
+
- For translated rule messages to reach the UI, run those rules on the server. See "Server-worded validation messages" in `typescript.md` for the proxy setup.
|
|
45
45
|
- For an application-specific message, resolve the resource inside a lambda so it is read at validation time, after the culture is known: `.WithMessage(_ => ValidationMessages.NameRequired)`. FluentValidation's built-in messages already follow the UI culture.
|
|
46
46
|
- Give each application-specific refusal a stable `reasonDetail` (see `cratis-arc-validate-command`) and a frontend catalog ID. Never make the client branch on message text.
|
|
47
47
|
|
package/package/corpus/skills/cratis-arc-localize-application/references/typescript-tooling.md
CHANGED
|
@@ -74,6 +74,9 @@ A pack is optional and never downloaded, so a missing one is not an error: the l
|
|
|
74
74
|
3. `build` reports a missing pack as an English fallback. Read its warnings.
|
|
75
75
|
4. Use `packLoaders.arc` in the Arc registry and `packLoaders.components` in a separate Components registry, whose `registry.load(tag)` result is passed as `value.catalog` (see `typescript.md`). For a Components pack the generator compares the pack's same-minor `coreRange` with the installed `@cratis/components` at build time; it warns and omits the loader when the range excludes it or the version cannot be determined, so rerun `build` after updating either package. The generated Components loader needs an Arc release that includes the fix for Cratis/Arc#4079; on an older Arc, and in hosts that do not use the generated loaders, register the pack directly: `{ nb: () => import('@cratis/components.locale.nb') }`.
|
|
76
76
|
5. A pack is refused, with an error reported, when it is malformed, when its manifest locale is invalid, or when its same-minor range excludes your installed core version. A different English template revision only warns and the pack still loads. Pass `onDiagnostic` to read the reports, and upgrade the pack and the library together.
|
|
77
|
+
- The only accepted range is one minor line, written `>=x.y.0 <x.(y+1).0`. A wider or differently written range is refused exactly like a wrong one, so never edit or widen `coreRange` to make a pack load.
|
|
78
|
+
- After an upgrade that leaves the pack behind: install the pack released for the new minor line, or stay on the previous minor until it exists. Until then put the platform IDs you need (`arc.*`, `components.*`) in `locales/<tag>/overrides.json`; an application file beats a pack for the same ID and needs no range.
|
|
79
|
+
- There is no option that loads an incompatible pack and no per-pack fallback callback; `onDiagnostic` only reports.
|
|
77
80
|
6. The tag must be in `localization.json`. A pack for an unlisted language is never loaded.
|
|
78
81
|
7. If the pack cannot be installed, put the texts you need in `locales/<tag>/overrides.json`.
|
|
79
82
|
|
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
- Components text
|
|
11
11
|
- Regional format
|
|
12
12
|
- Register by hand
|
|
13
|
+
- Server rendering
|
|
14
|
+
- Server-worded validation messages
|
|
13
15
|
- Related references
|
|
14
16
|
|
|
15
17
|
## Prerequisites
|
|
@@ -146,6 +148,36 @@ const registry = createCatalogRegistry({
|
|
|
146
148
|
|
|
147
149
|
A bare dictionary is the application's English. A tag map holds loaders; a pack loader returns `{ messages, manifest }`, and Arc refuses a pack whose manifest range does not include its core version (it reports it and continues in English). Pass `onDiagnostic` to receive those reports instead of the console. Your bundler must support literal dynamic JSON imports.
|
|
148
150
|
|
|
151
|
+
## Server rendering
|
|
152
|
+
|
|
153
|
+
Default: create one locale store per request and create the browser store from the server's snapshot. Keep the module-level store of Step 3 for a browser-only application.
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
const options = { supported: policy.languages, defaultLocale: policy.default, catalogRegistry: registry, cookie: true };
|
|
157
|
+
|
|
158
|
+
// Server, once per request, before rendering <Arc locale={serverLocale}>.
|
|
159
|
+
const serverLocale = createLocale({ ...options, request: { cookieHeader, acceptLanguage } });
|
|
160
|
+
await serverLocale.ready;
|
|
161
|
+
const snapshot = JSON.stringify(serverLocale.getServerSnapshot());
|
|
162
|
+
|
|
163
|
+
// Browser, before hydrating <Arc locale={clientLocale}>.
|
|
164
|
+
const clientLocale = createLocale({ ...options, hydration: JSON.parse(snapshot) });
|
|
165
|
+
await clientLocale.ready;
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
- **`request`** takes the request's raw `Cookie` and `Accept-Language` header values. With `cookie: true` the ASP.NET Core culture cookie is tried first, then `Accept-Language`; `initialLocale` (a signed-in profile's language) beats both. A switch in the browser writes the cookie, so the next request renders the chosen language.
|
|
169
|
+
- **`hydration`** makes the browser's first render match the server's markup. Afterwards a supported application or saved choice takes over. Move the snapshot with the framework's safe hydration-data mechanism, and use the same languages and catalogs on both sides.
|
|
170
|
+
- **Why one store per request.** A server render reads the store's server snapshot. It is fixed to the language the store was created with; `setLocale()` and `setLanguage()` never change it. A module-level store therefore renders its creation-time language for every visitor, and switching it per request only moves the one shared current language, which other visitors' in-flight requests then send to the backend.
|
|
171
|
+
- **Request-owned queries and commands** created outside the root: bind the request's store with `instance.setRequestDefaults({ locale: serverLocale })`.
|
|
172
|
+
- Send a page that varies by the cookie with `Cache-Control: no-store, private` and a matching `Vary`.
|
|
173
|
+
- Avoid a module-level store on a server, switching a shared store per request, and `Globals.locale` on a server.
|
|
174
|
+
|
|
175
|
+
Done when two requests with different languages, rendered at the same time, each return markup and backend text in their own language, and the browser hydrates without a mismatch warning.
|
|
176
|
+
|
|
177
|
+
## Server-worded validation messages
|
|
178
|
+
|
|
179
|
+
A rule message the server translates reaches the screen only when the rule runs on the server. Generated proxies carry a copy of each projectable rule; a blocking copy stops the request in the browser and shows the wording fixed at build time. In a C# backend project set `<CratisProxiesClientValidation>server</CratisProxiesClientValidation>` (a direct generator call takes `--client-validation=server`; the default is `mirrored`), remove the application's own imports of the generated validator classes, then rebuild so the proxies are regenerated. Required-property and route checks still run in the browser. Never translate by matching the English text.
|
|
180
|
+
|
|
149
181
|
## Related references
|
|
150
182
|
|
|
151
183
|
Open `typescript-switcher.md` for the switcher and checks, and `typescript-tooling.md` for `cratis-l10n`, translation-service file masks and a missing pack.
|
package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-localization.md
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
- What Arc does with the language
|
|
7
7
|
- Validation text
|
|
8
8
|
- Outside React
|
|
9
|
+
- Server rendering
|
|
9
10
|
- Avoid
|
|
10
11
|
|
|
11
12
|
For several languages, multi-file catalogs, optional packs, a language switcher or the `cratis-l10n` tool, use `cratis-arc-localize-application`; this page keeps the literal-tree path (`defineTranslations`).
|
|
@@ -66,13 +67,36 @@ For a ready-made selector and Components controls in the same language, mount `A
|
|
|
66
67
|
|
|
67
68
|
- With a locale on the host, `CommandForm` shows Arc-owned failures (such as a missing required field) in English or Norwegian Bokmål. Messages authored in a rule pass through unchanged; without a locale the original messages are shown.
|
|
68
69
|
- To change the wording, supply `formatValidationResult` on the form or in `CommandFormDefaults`. Decide by `reason` and `reasonDetail`, never by message text. For your own display, `formatValidationResult(result, locale, { fieldTitle, fieldName })` from `@cratis/arc/localization` returns the platform text for those failures and the original message for every other.
|
|
69
|
-
- **Rule messages translated by the server
|
|
70
|
+
- **Rule messages translated by the server.** For translated rule messages to reach the UI, run those rules on the server. See "Server-worded validation messages" in the `cratis-arc-localize-application` skill's `references/typescript.md` for the proxy setup.
|
|
70
71
|
|
|
71
72
|
## Outside React
|
|
72
73
|
|
|
73
74
|
- A command or query instance used without the host: `instance.setRequestDefaults({ locale })`. The call replaces the process-wide defaults for that instance, so include `httpHeadersCallback` when the application has one.
|
|
74
75
|
- A browser application without React: set `Globals.locale = locale` (from `@cratis/arc`) once at startup.
|
|
75
|
-
-
|
|
76
|
+
- A query or command instance that belongs to one server request: bind that request's store with `instance.setRequestDefaults({ locale })`.
|
|
77
|
+
|
|
78
|
+
## Server rendering
|
|
79
|
+
|
|
80
|
+
Default: one store per request, and the browser store created from what the server rendered.
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
const options = { supported: ['en', 'nb'], defaultLocale: 'en', cookie: true };
|
|
84
|
+
|
|
85
|
+
// Server, once per request, before rendering <Arc locale={serverLocale}>.
|
|
86
|
+
const serverLocale = createLocale({ ...options, request: { cookieHeader, acceptLanguage } });
|
|
87
|
+
await serverLocale.ready;
|
|
88
|
+
const snapshot = JSON.stringify(serverLocale.getServerSnapshot());
|
|
89
|
+
|
|
90
|
+
// Browser, before hydrating <Arc locale={clientLocale}>.
|
|
91
|
+
const clientLocale = createLocale({ ...options, hydration: JSON.parse(snapshot) });
|
|
92
|
+
await clientLocale.ready;
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
- **`request`** takes the request's raw `Cookie` and `Accept-Language` header values. With `cookie: true` the ASP.NET Core culture cookie is tried first, then `Accept-Language`; `initialLocale` (a signed-in profile's language) beats both.
|
|
96
|
+
- **`hydration`** makes the browser's first render match the server's markup. Afterwards a supported application or saved choice takes over. Move the snapshot with the framework's safe hydration-data mechanism and use the same languages and catalogs on both sides.
|
|
97
|
+
- **Why one store per request.** A server render reads the store's server snapshot. It is fixed to the language the store was created with; `setLocale()` never changes it. A module-level store therefore renders its creation-time language for every visitor, and switching it per request only moves the one shared current language, which other visitors' in-flight requests then send.
|
|
98
|
+
- Send a page that varies by the cookie with `Cache-Control: no-store, private` and a matching `Vary`.
|
|
99
|
+
- Avoid a module-level store on a server, calling `setLocale()` per request, and `Globals.locale` on a server.
|
|
76
100
|
|
|
77
101
|
## Avoid
|
|
78
102
|
|
|
@@ -50,7 +50,7 @@ A **pure module** (plain functions over plain data, with its own specs) is the l
|
|
|
50
50
|
2. **View model.** In a module without markup, write a class that extends nothing, marked with tsyringe's `injectable` decorator when it has constructor parameters. Give every field an initial value, expose derived state as getters and user actions as methods, and take generated proxies and collaborators as constructor parameters. See View model and view.
|
|
51
51
|
3. **Bind.** Export the component `withViewModel` returns for the view-model class and a render function. Read view-model state inside that render and wire events to view-model methods. Never construct the view model yourself.
|
|
52
52
|
4. **Inputs.** Take initial values through the `props`, `params` and `queryParams` decorators; implement `IHandleProps` and `IHandleParams` for values that change while mounted. Route and query-string values are strings: parse and validate them. See Props and Route and query parameters.
|
|
53
|
-
5. **Server calls.** Call `execute()` on injected commands and `perform(args)` on injected snapshot queries that need no custom headers or scope tracking. Otherwise create the command with its generated hook in the view and pass it in, or take the query from `IQueryProvider`. Read a live collection with its generated hook in the view and pass the data to the view model. See Queries and commands in a view model.
|
|
53
|
+
5. **Server calls.** Call `execute()` on injected commands and `perform(args)` on injected snapshot queries that need no custom headers or scope tracking. Otherwise create the command with its generated hook in the view and pass it in, or take the query from `IQueryProvider`. Read a live collection with its generated hook in the view and pass the data to the view model. See Queries and commands in a view model; it also covers a query called repeatedly (which request is cancelled, and when an older answer can still arrive) and what a raw subscription delivers when an argument is missing or rejected.
|
|
54
54
|
6. **Cleanup.** Keep every subscription and timer handle in a field and release it in `detached()` (`IViewModelDetached`). See Lifecycle and cleanup.
|
|
55
55
|
7. **Lint and specs.** Enable the Arc ESLint plugin's recommended config, and specify the view model by constructing it directly with fakes. See Lint and specs.
|
|
56
56
|
|
|
@@ -233,6 +233,29 @@ export const RoomEditor = withViewModel(RoomEditorViewModel, ({ viewModel }) =>
|
|
|
233
233
|
});
|
|
234
234
|
```
|
|
235
235
|
|
|
236
|
+
**Calling a snapshot query repeatedly** (search as you type, a loader that reruns). Default: keep one query instance for the search (here an injected `_roomSearch` snapshot query) and number each attempt, so only the latest attempt may write state:
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
private _attempt = 0;
|
|
240
|
+
|
|
241
|
+
async search(term: string) {
|
|
242
|
+
const attempt = ++this._attempt;
|
|
243
|
+
try {
|
|
244
|
+
const result = await this._roomSearch.perform({ term });
|
|
245
|
+
if (attempt !== this._attempt) return; // a newer attempt owns the result
|
|
246
|
+
if (result.isSuccess) this.rooms = result.data;
|
|
247
|
+
} catch (error) {
|
|
248
|
+
if ((error as { name?: string })?.name !== 'AbortError') throw error; // superseded: discard, never show
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
- A `perform()` that passes the client checks aborts the previous request **on the same instance** before it sends its own. Two instances never cancel each other.
|
|
254
|
+
- The superseded call rejects with `AbortError` instead of returning a result. That is cancellation, not a failure. Cancel yourself with `query.abortController?.abort()`.
|
|
255
|
+
- A call stopped in the browser (a generated rule rejects it, or a required argument is missing) sends nothing and aborts nothing, so the earlier request can still arrive. The attempt number is what stops it from overwriting the newer state.
|
|
256
|
+
- Avoid a new query instance per keystroke, showing `AbortError` as an error, and comparing the returned data with the typed term instead of the attempt number.
|
|
257
|
+
- This applies to snapshot queries. An observable query's `perform()` has no abort; end a subscription with `unsubscribe()`.
|
|
258
|
+
|
|
236
259
|
Do not register an injected command with an injected `ICommandScope`, or notify an injected `IQueryScope`, from the constructor: the scopes are captured once when the view model is created, and a scope component that mounts together with the view still provides an inert placeholder at that moment. To keep an injected command in the view model, expose it (`constructor(readonly closeRoom: CloseRoom) {}`), then register it from the view against the current scope and remove it on cleanup:
|
|
237
260
|
|
|
238
261
|
```tsx
|
|
@@ -274,7 +297,14 @@ export class OccupancyViewModel implements IViewModelDetached {
|
|
|
274
297
|
}
|
|
275
298
|
```
|
|
276
299
|
|
|
277
|
-
Prefer the ordinary `.use()` hook for displaying a collection. A raw subscriber receives the initial snapshot but can then receive `changeSet` with empty `data`; assigning `result.data` loses the list. If presentation logic needs its own ongoing subscription, inject the proxy, subscribe in the constructor for fixed arguments as above, and unsubscribe in `detached()` (there is no `attached()` callback). For
|
|
300
|
+
Prefer the ordinary `.use()` hook for displaying a collection. A raw subscriber receives the initial snapshot but can then receive `changeSet` with empty `data`; assigning `result.data` loses the list. If presentation logic needs its own ongoing subscription, inject the proxy, subscribe in the constructor for fixed arguments as above, and unsubscribe in `detached()` (there is no `attached()` callback). For a collection, either maintain a snapshot by applying `added`, `replaced` and `removed` and accepting full snapshots when sent, or require full snapshots (`observableQueryTransferMode={ObservableQueryTransferMode.Full}` on `Arc`, enum from `@cratis/arc`, configured application-wide before subscribing).
|
|
301
|
+
|
|
302
|
+
Raw `subscribe()` with arguments that change or can be rejected:
|
|
303
|
+
|
|
304
|
+
- **Wait for required arguments.** With a required argument missing (absent, `undefined`, `null` or an empty string), `subscribe()` opens no connection and delivers one result that is ready, valid and successful with the query's empty default data. It looks exactly like "no data". Check the argument yourself before subscribing and show a placeholder until it exists.
|
|
305
|
+
- **A rejection ends the subscription.** When a generated client rule rejects the arguments, the callback gets an invalid result and no connection opens. When the server rejects a model-bound observable query, the callback gets one result with `isValid === false` and that subscription ends; it is not a failed connection and it never resumes. Show `validationResults`, then call `subscribe()` again with corrected arguments.
|
|
306
|
+
- **Replacing.** `subscribe()` on the same instance disconnects its previous connection, also when the new arguments are rejected. Keep the newest subscription and call its `unsubscribe()` (or the query's `dispose()`) in `detached()`.
|
|
307
|
+
- Avoid treating the empty fallback as an empty dataset, and waiting for a rejected subscription to deliver again.
|
|
278
308
|
|
|
279
309
|
## Props
|
|
280
310
|
|
|
@@ -64,7 +64,7 @@ Read `references/<language>.md` for the project's SDK (`.csproj` → csharp, Nod
|
|
|
64
64
|
- Column codecs — convert driver values in both directions: dialect-specific GUIDs, string/number/GUID concepts, date-only, time-only, duration, or validated JSON. MySQL string concepts can specify a varchar length (1–65535).
|
|
65
65
|
- Column builders — apply a codec through the PostgreSQL, MySQL or SQLite column builder matching the table dialect.
|
|
66
66
|
- `observation` — omit for ordinary reads; enable in-process notifications for local announced writes, or PostgreSQL notifications for changes from other writers.
|
|
67
|
-
- `notifyChanged` — announce changed tables or registered models to local observers after writes.
|
|
67
|
+
- `notifyChanged` — announce changed tables or registered models to local observers after writes. In-process mode only: with PostgreSQL notifications it publishes nothing and the database trigger is the only source.
|
|
68
68
|
- `observe`, `observePage`, `observeById` — subscribe to replacement lists, counted pages or a single row. A list is bounded by `maxPageSize` and a larger result fails; use a page for large lists.
|
|
69
69
|
- `current`, `close` — fetch a lazy observation’s current value or release its sessions.
|
|
70
70
|
- `listener` — supply a dedicated PostgreSQL listener for the same tenant database as the reader; it is a factory called with tenant and context, and the context provides cancellation. The node-postgres adapter accepts a fresh, unconnected, dedicated client or a factory for one.
|
package/package/corpus/skills/cratis-arc-storage-typescript/references/typescript-drizzle.md
CHANGED
|
@@ -143,6 +143,8 @@ observation: {
|
|
|
143
143
|
- Route the listener and the reader to the same tenant database.
|
|
144
144
|
- Install the trigger in an application migration, once per observed base table. `postgresqlChangeTrigger(table)` returns the SQL for a table declared with `pgSchema`. For a plain `pgTable` pass the schema it lives in: `postgresqlChangeTrigger(table, { schema: 'public' })`. Aliased tables are rejected.
|
|
145
145
|
- Arc never installs the trigger at runtime, and notifications do not replay changes made during a disconnect.
|
|
146
|
+
- The database trigger is the only invalidation source in this mode. `notifyChanged` still validates its target but publishes nothing locally, so a write to a table without the trigger never reaches an observer.
|
|
147
|
+
- There is no fallback to in-process observation. A missing, disabled or incompatible trigger fails the observation; while the listener is disconnected Arc pauses reads, keeps each subscriber's last snapshot and reconnects.
|
|
146
148
|
- To use another driver implement `PostgreSQLListenerConnection`: `connect()`, `query(text, values?)` resolving `{ rows }`, `onNotification((channel, payload) => ...)`, `onDisconnect(error => ...)` and `close()`.
|
|
147
149
|
|
|
148
150
|
## Failures
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: cratis-authproxy-configure
|
|
3
|
-
description: "Use when putting Cratis AuthProxy in front of an application or changing its configuration: sign-in providers, who is admitted (required claims, GitHub organization or team membership), tenant resolution and switching (including the endpoint that lists a person's tenants), machine clients that get tokens from the proxy (client credentials, `/.cratis/token`), sessions and sign-out, routing to services, running it in production or under Aspire. Not for authorizing a command or query (`cratis-arc-authorize-request`) or reading identity in the backend (`cratis-arc-host-application`)."
|
|
3
|
+
description: "Use when putting Cratis AuthProxy in front of an application or changing its configuration: sign-in providers, who is admitted (required claims, GitHub organization or team membership), tenant resolution and switching (including the endpoint that lists a person's tenants), machine clients that get tokens from the proxy (client credentials, `/.cratis/token`), sessions and sign-out, how soon removed access takes effect, telling the backend when a person signs in or returns (sign-in callback, last active), routing to services, running it in production or under Aspire. Not for authorizing a command or query (`cratis-arc-authorize-request`) or reading identity in the backend (`cratis-arc-host-application`)."
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Configure Cratis AuthProxy: the ingress that signs people in
|
|
@@ -96,6 +96,7 @@ One application, one sign-in provider, one tenant. Run the `cratis/authproxy` im
|
|
|
96
96
|
| A person switches between tenants | `Selection` strategy and `/.cratis/select-tenant` | [tenant-resolution.md](references/tenant-resolution.md) |
|
|
97
97
|
| The application serves the list of a person's tenants | `GET` endpoint, signed in the `Selection` options, `5xx` on failure | [tenant-resolution.md](references/tenant-resolution.md) |
|
|
98
98
|
| Add a sign-out link | Navigate to `/.cratis/logout` | [sessions-and-logout.md](references/sessions-and-logout.md) |
|
|
99
|
+
| The backend must know when a person signs in or comes back (last active, first-use work) | `SignInCallback` on the service | [sessions-and-logout.md](references/sessions-and-logout.md) |
|
|
99
100
|
| A sensitive page needs a recent sign-in | `FreshAuthentication` on the path | [sessions-and-logout.md](references/sessions-and-logout.md) |
|
|
100
101
|
| Several applications behind one sign-in | Route by host, path prefix or header | [services-and-routing.md](references/services-and-routing.md) |
|
|
101
102
|
| A webhook or public page without sign-in | `AnonymousPaths` on the service | `cratis-arc-authorize-request` |
|
|
@@ -115,7 +116,7 @@ One application, one sign-in provider, one tenant. Run the `cratis/authproxy` im
|
|
|
115
116
|
| [references/sign-in-providers.md](references/sign-in-providers.md) | Adding or changing a sign-in provider, registering callbacks, or offering sign-in by e-mail code. |
|
|
116
117
|
| [references/admission.md](references/admission.md) | Deciding who gets past the proxy: required claims, admitting only a GitHub organization or team, the `/.cratis/me` verdict, what a refused person sees. |
|
|
117
118
|
| [references/tenant-resolution.md](references/tenant-resolution.md) | Choosing how the tenant is resolved, verifying it exists, serving or securing the endpoint that lists a person's tenants, handling its outages and removed tenant access, or building a tenant switcher. |
|
|
118
|
-
| [references/sessions-and-logout.md](references/sessions-and-logout.md) | Setting session lifetime, adding sign-out, requiring a recent sign-in, or handling a `401` in the frontend. |
|
|
119
|
+
| [references/sessions-and-logout.md](references/sessions-and-logout.md) | Setting session lifetime, adding sign-out, requiring a recent sign-in, receiving the sign-in callback (payload, headers, delivery guarantees), or handling a `401` in the frontend. |
|
|
119
120
|
| [references/services-and-routing.md](references/services-and-routing.md) | Routing several services, limiting forwarded paths, reading the forwarded headers, or keeping long-lived connections open. Also any machine client: client credentials, `/.cratis/token`, the verification endpoint, refresh tokens. |
|
|
120
121
|
| [references/operations.md](references/operations.md) | Deploying: key ring, ingress, health probes, TLS to the backend, custom pages, telemetry. |
|
|
121
122
|
| [references/aspire.md](references/aspire.md) | Wiring the proxy in an Aspire AppHost. |
|
|
@@ -49,7 +49,7 @@ These gates decide who reaches the application at all. Each command and query st
|
|
|
49
49
|
|
|
50
50
|
## GitHub organizations and teams
|
|
51
51
|
|
|
52
|
-
Add the `read:org` scope to the GitHub provider. The proxy then reads the person's organizations and teams during sign-in and adds them as claims:
|
|
52
|
+
Add the `read:org` scope to the GitHub provider (`write:org` or `admin:org` also work; `read:org` is the least). The proxy then reads the person's organizations and teams during sign-in and adds them as claims:
|
|
53
53
|
|
|
54
54
|
| Claim | Value | Example |
|
|
55
55
|
|---|---|---|
|
|
@@ -58,7 +58,7 @@ Add the `read:org` scope to the GitHub provider. The proxy then reads the person
|
|
|
58
58
|
|
|
59
59
|
Without the scope the claims are absent and every requirement on them refuses.
|
|
60
60
|
|
|
61
|
-
Admit
|
|
61
|
+
Admit members of one organization who are on a given team with the scope on the provider and two requirements:
|
|
62
62
|
|
|
63
63
|
```json
|
|
64
64
|
{
|
|
@@ -80,6 +80,7 @@ Admit one team of one organization with the scope on the provider and one requir
|
|
|
80
80
|
},
|
|
81
81
|
"Authorization": {
|
|
82
82
|
"RequiredClaims": [
|
|
83
|
+
{ "Claim": "urn:github:organization", "AnyOf": [ "Acme" ] },
|
|
83
84
|
{ "Claim": "urn:github:team", "AnyOf": [ "Acme/operations" ] }
|
|
84
85
|
]
|
|
85
86
|
}
|
|
@@ -90,10 +91,11 @@ Admit one team of one organization with the scope on the provider and one requir
|
|
|
90
91
|
|
|
91
92
|
Supply `ClientSecret` from a secret store. See [sign-in-providers.md](sign-in-providers.md) for the provider itself.
|
|
92
93
|
|
|
93
|
-
- **Team value.** Write `organization/team-slug`. The slug is the last segment of the team's URL, not its display name.
|
|
94
|
+
- **Team value.** Write `organization/team-slug`. The slug is the last segment of the team's URL, not its display name.
|
|
95
|
+
- **The organization entry is optional next to a team entry.** A team value already names its organization, so only a member of that organization's team can match it. Keep the organization entry as the default: it states the intent and still holds if the team entry is later removed. A team entry alone admits the same people.
|
|
94
96
|
- **Several teams.** List them in one `AnyOf` to admit a member of any of them. Separate entries in `RequiredClaims` must all be satisfied.
|
|
95
97
|
- **`Type` must be `GitHub`.** It is what makes the proxy read memberships. `ClaimMappings` cannot produce them: GitHub's user endpoint returns nothing about membership.
|
|
96
|
-
- **Read at sign-in, not per request.** The claims live in the session. A person removed from the team keeps access until the session ends, at most `Session:Lifetime` (12 hours by default).
|
|
98
|
+
- **Read at sign-in, not per request.** The claims live in the session. A person removed from the team keeps access until the session ends, at most `Session:Lifetime` (12 hours by default) while `Session:SlidingExpiration` is off, which is the default. With it on, activity extends the session, so an active person keeps the old memberships. Keep it off and shorten `Lifetime` when removal must take effect sooner.
|
|
97
99
|
- **A failed read refuses.** When GitHub cannot be reached during sign-in the claims are absent, and the requirement refuses the person. Signing in again reads them again.
|
|
98
100
|
- **Organization approval.** GitHub lists only organizations that let the OAuth app see them. An organization that restricts third-party applications must approve the app, or its members are refused.
|
|
99
101
|
- **Limits.** The proxy reads up to 500 organizations and 500 teams per person.
|
|
@@ -154,7 +154,18 @@ The service needs a `Backend`. The application stores and verifies the secrets;
|
|
|
154
154
|
]
|
|
155
155
|
```
|
|
156
156
|
|
|
157
|
-
|
|
157
|
+
Default: return the tenant's own id (its key under `Tenants`), and list that same id in the tenant's `SourceIdentifiers`.
|
|
158
|
+
|
|
159
|
+
```json
|
|
160
|
+
"Tenants": { "tenant-a": { "SourceIdentifiers": [ "tenant-a" ] } }
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
- Answer with `Content-Type: application/json`. A body of any other type is ignored and the token carries no tenant.
|
|
164
|
+
- The `Claim` strategy looks the value up in `SourceIdentifiers`; a tenant's id is not matched unless it is listed there.
|
|
165
|
+
- On routes that enforce credential binding, AuthProxy also compares the tenant value the verification endpoint returned with the resolved tenant ID, ignoring case. A returned value that resolves only through an alias (a `SourceIdentifiers` entry that differs from the tenant ID) is refused with `403`. So is a credential bound to a different tenant than the one the request addresses by host, route or a `Specified` strategy.
|
|
166
|
+
- Decide the tenant from the stored client record. Never take it from a header or body value the client sent.
|
|
167
|
+
|
|
168
|
+
See [tenant-resolution.md](tenant-resolution.md).
|
|
158
169
|
|
|
159
170
|
**More than one replica.** The tokens are protected with the proxy's key ring. Without a shared, persisted key ring a token issued by one replica is refused by another, and every restart invalidates every token. See [operations.md](operations.md).
|
|
160
171
|
|
|
@@ -101,21 +101,61 @@ A valid session does not prove the person signed in recently. Declare how old th
|
|
|
101
101
|
|
|
102
102
|
## Tell the backend when someone signs in
|
|
103
103
|
|
|
104
|
-
`Services:<name>:SignInCallback` has the proxy call the service's backend, in the background, without delaying the browser:
|
|
104
|
+
Use it for "last active", "returning user" and work started on first use. `Services:<name>:SignInCallback` has the proxy call the service's backend, in the background, without delaying the browser:
|
|
105
105
|
|
|
106
106
|
```json
|
|
107
|
-
"SignInCallback": { "Path": "/internal/sign-in", "
|
|
107
|
+
"SignInCallback": { "Path": "/internal/sign-in", "Secret": "<from a secret store>" }
|
|
108
108
|
```
|
|
109
109
|
|
|
110
|
+
| Setting | Default | Meaning |
|
|
111
|
+
|---|---|---|
|
|
112
|
+
| `Path` | required | A path on the service's `Backend`, starting with one `/`, without host or query. A service without a backend cannot receive the callback. |
|
|
113
|
+
| `Interval` | `12:00:00` | The least time between two `Returned` callbacks for the same person and service. |
|
|
114
|
+
| `Timeout` | `00:00:05` | How long the proxy waits for the answer. At most one minute. |
|
|
115
|
+
| `Secret` | empty | Sent in a header so the receiver can tell the proxy from any other caller on its network. |
|
|
116
|
+
|
|
110
117
|
| Kind | When |
|
|
111
118
|
|---|---|
|
|
112
|
-
| `SignedIn` | A sign-in at a provider completes. |
|
|
119
|
+
| `SignedIn` | A sign-in at a provider completes for the service. |
|
|
113
120
|
| `Returned` | An existing browser session makes a request to the service and no callback was sent for that person and service within `Interval`. A `SignedIn` starts the interval, so the request that follows a sign-in is not a `Returned`. |
|
|
114
121
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
122
|
+
Bearer and machine callers, unauthenticated requests and refused requests never produce a callback. When sign-in completes on a shared callback host that matches no service, no `SignedIn` is sent; the person's first request to the service reports `Returned` instead.
|
|
123
|
+
|
|
124
|
+
**The call.** One `POST` to `Path` with `Content-Type: application/json`. Any `2xx` counts as accepted and the response body is ignored.
|
|
125
|
+
|
|
126
|
+
```json
|
|
127
|
+
{
|
|
128
|
+
"kind": "SignedIn",
|
|
129
|
+
"subject": "134365",
|
|
130
|
+
"name": "Ada Lovelace",
|
|
131
|
+
"email": "ada@example.com",
|
|
132
|
+
"identityProvider": "github",
|
|
133
|
+
"tenant": "acme",
|
|
134
|
+
"occurred": "2026-11-03T09:00:00+00:00"
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
- `tenant` is left out when no tenant resolved. `name` and `email` are empty strings when the provider gave none. The other fields are always present.
|
|
139
|
+
- `x-cratis-sign-in-callback` carries the kind. It is not a credential.
|
|
140
|
+
- `x-cratis-sign-in-callback-secret` carries `Secret`, only when one is configured.
|
|
141
|
+
- The person's identity headers (`x-ms-client-principal` and its `-id` and `-name`), the tenant headers (when a tenant resolved) and the service headers are sent as on a forwarded request. `subject` is the principal ID. Compare it with the decoded `x-ms-client-principal-id` value, not with the raw header: an ID that is not printable US-ASCII travels in that header in RFC 8187 form (`UTF-8''` followed by percent-encoded UTF-8).
|
|
142
|
+
|
|
143
|
+
**Delivery is best-effort.** A failed, timed-out or refused callback is logged and not retried, a full queue drops callbacks, and a restart loses the queued ones. Each proxy instance tracks `Interval` in memory, so several instances or a restart can send the same `Returned` again. A callback can also arrive after the person's request, or never.
|
|
144
|
+
|
|
145
|
+
Default receiver:
|
|
146
|
+
|
|
147
|
+
1. Reject a missing or wrong `x-cratis-sign-in-callback-secret` first, compared in constant time. Also keep the backend reachable from the proxy only.
|
|
148
|
+
2. Store `occurred` per person (and tenant) only when it is later than the stored value, so a late or repeated callback never moves activity backwards.
|
|
149
|
+
3. Answer `2xx` quickly and do slow work elsewhere.
|
|
150
|
+
4. Work that must happen exactly once per person (a welcome message, creating a profile) goes through the application's normal authenticated path, guarded so a second attempt does nothing. The callback only makes it happen sooner; a lost callback must not leave it undone.
|
|
151
|
+
|
|
152
|
+
Avoid:
|
|
153
|
+
|
|
154
|
+
- Using the callback as a gate. It is a notification: admission stays with [required claims and `/.cratis/me`](admission.md).
|
|
155
|
+
- Making a request wait for, or depend on, its callback.
|
|
156
|
+
- Trusting the `x-cratis-sign-in-callback` header alone as proof of the sender.
|
|
157
|
+
- A per-request "last seen" write in application middleware as a substitute.
|
|
158
|
+
- Expecting `Interval` to be exact, or counting callbacks as a count of sign-ins.
|
|
119
159
|
|
|
120
160
|
## Anti-patterns
|
|
121
161
|
|