@cratis/pi 8.4.0 → 8.5.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/harnesses/copilot/instructions/ai-distribution.instructions.md +2 -1
- package/package/corpus/harnesses/copilot/instructions/exit-codes-and-wrappers.instructions.md +1 -1
- package/package/corpus/harnesses/copilot/instructions/scripting.instructions.md +2 -1
- package/package/corpus/hooks/scripts/cratis-cleanup-worktrees.sh +5 -1
- package/package/corpus/hooks/scripts/cratis-guard-secrets.sh +131 -9
- package/package/corpus/rules/ai-distribution.md +2 -1
- package/package/corpus/rules/exit-codes-and-wrappers.md +1 -1
- package/package/corpus/rules/scripting.md +2 -1
- package/package/corpus/skills/cratis-application-growth/references/csharp.md +1 -1
- package/package/corpus/skills/cratis-arc-authorize-request/SKILL.md +3 -3
- package/package/corpus/skills/cratis-arc-authorize-request/references/authproxy.md +28 -3
- package/package/corpus/skills/cratis-arc-authorize-request/references/csharp-query-security.md +3 -3
- package/package/corpus/skills/cratis-arc-authorize-request/references/csharp.md +1 -1
- package/package/corpus/skills/cratis-arc-authorize-request/references/typescript.md +2 -0
- package/package/corpus/skills/cratis-arc-connect-storage/references/csharp.md +1 -0
- package/package/corpus/skills/cratis-arc-connect-storage/references/elixir.md +9 -2
- package/package/corpus/skills/cratis-arc-declare-command/references/csharp-chronicle.md +1 -1
- package/package/corpus/skills/cratis-arc-declare-command/references/csharp-history.md +2 -2
- package/package/corpus/skills/cratis-arc-declare-command/references/csharp.md +7 -7
- package/package/corpus/skills/cratis-arc-declare-operation/references/csharp-abilities.md +2 -2
- package/package/corpus/skills/cratis-arc-declare-operation/references/csharp-recovery.md +6 -4
- package/package/corpus/skills/cratis-arc-declare-operation/references/csharp.md +2 -2
- package/package/corpus/skills/cratis-arc-diagnose-live-query/SKILL.md +1 -1
- package/package/corpus/skills/cratis-arc-diagnose-live-query/references/csharp.md +6 -6
- package/package/corpus/skills/cratis-arc-diagnose-live-query/references/java.md +1 -1
- package/package/corpus/skills/cratis-arc-diagnose-live-query/references/kotlin.md +1 -1
- package/package/corpus/skills/cratis-arc-expose-mcp-operation/references/csharp-diagnose-tool-call.md +9 -7
- package/package/corpus/skills/cratis-arc-expose-mcp-operation/references/csharp.md +3 -1
- package/package/corpus/skills/cratis-arc-expose-query/SKILL.md +1 -1
- package/package/corpus/skills/cratis-arc-expose-query/references/csharp.md +10 -7
- package/package/corpus/skills/cratis-arc-expose-query/references/go.md +2 -2
- package/package/corpus/skills/cratis-arc-expose-query/references/typescript.md +6 -3
- package/package/corpus/skills/cratis-arc-generate-proxies/references/csharp.md +7 -5
- package/package/corpus/skills/cratis-arc-host-application/references/csharp-identity.md +3 -2
- package/package/corpus/skills/cratis-arc-host-application/references/csharp.md +7 -0
- package/package/corpus/skills/cratis-arc-invoke-command/references/csharp-extensions.md +4 -0
- package/package/corpus/skills/cratis-arc-isolate-tenant/SKILL.md +1 -1
- package/package/corpus/skills/cratis-arc-isolate-tenant/references/csharp.md +4 -2
- package/package/corpus/skills/cratis-arc-react-bind-slice/SKILL.md +17 -22
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-commands.md +11 -1
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-host.md +10 -3
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-identity.md +7 -3
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-queries.md +1 -1
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript.md +1 -1
- package/package/corpus/skills/cratis-arc-testing-typescript/references/typescript.md +2 -2
- package/package/corpus/skills/cratis-arc-validation-typescript/SKILL.md +1 -0
- package/package/corpus/skills/cratis-chronicle-cli-operations/SKILL.md +5 -5
- package/package/corpus/skills/cratis-chronicle-cli-operations/references/inspection.md +11 -3
- package/package/corpus/skills/cratis-chronicle-cli-operations/references/project-tooling.md +22 -0
- package/package/corpus/skills/cratis-chronicle-cli-operations/references/recovery-and-comparison.md +17 -3
- package/package/corpus/skills/cratis-chronicle-cli-operations/references/setup-and-target.md +8 -2
- package/package/corpus/skills/cratis-chronicle-connect-application/references/python.md +2 -2
- package/package/corpus/skills/cratis-chronicle-constrain-append/SKILL.md +1 -1
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/SKILL.md +4 -3
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/configuration.md +86 -16
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/kernel-options.md +3 -3
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/network-and-tls.md +14 -6
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/storage.md +33 -1
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/upgrade-and-recovery.md +27 -1
- package/package/corpus/skills/cratis-chronicle-evolve-event/references/csharp.md +2 -2
- package/package/corpus/skills/cratis-chronicle-inspect-observer/SKILL.md +4 -4
- package/package/corpus/skills/cratis-chronicle-inspect-observer/references/csharp.md +8 -7
- package/package/corpus/skills/cratis-chronicle-inspect-observer/references/go.md +2 -2
- package/package/corpus/skills/cratis-chronicle-mcp-inspection/SKILL.md +1 -1
- package/package/corpus/skills/cratis-chronicle-mcp-inspection/references/deployment.md +1 -1
- package/package/corpus/skills/cratis-chronicle-project-view/SKILL.md +1 -1
- package/package/corpus/skills/cratis-chronicle-project-view/references/csharp-fluent.md +1 -1
- package/package/corpus/skills/cratis-chronicle-project-view/references/csharp-model-bound.md +1 -1
- package/package/corpus/skills/cratis-chronicle-project-view/references/csharp-reading.md +2 -0
- package/package/corpus/skills/cratis-chronicle-project-view/references/java.md +1 -1
- package/package/corpus/skills/cratis-chronicle-project-view/references/kotlin.md +3 -3
- package/package/corpus/skills/cratis-chronicle-project-view/references/typescript.md +2 -0
- package/package/corpus/skills/cratis-chronicle-protect-decision/SKILL.md +1 -1
- package/package/corpus/skills/cratis-chronicle-protect-decision/references/csharp-scopes.md +1 -1
- package/package/corpus/skills/cratis-chronicle-protect-decision/references/csharp.md +2 -2
- package/package/corpus/skills/cratis-chronicle-protect-personal-data/SKILL.md +1 -1
- package/package/corpus/skills/cratis-chronicle-protect-personal-data/references/csharp.md +4 -2
- package/package/corpus/skills/cratis-chronicle-publish-contract/SKILL.md +6 -5
- package/package/corpus/skills/cratis-chronicle-publish-contract/references/elixir-integrations.md +3 -3
- package/package/corpus/skills/cratis-chronicle-react-to-fact/SKILL.md +2 -1
- package/package/corpus/skills/cratis-chronicle-react-to-fact/references/csharp-pages.md +1 -1
- package/package/corpus/skills/cratis-chronicle-react-to-fact/references/csharp.md +3 -3
- package/package/corpus/skills/cratis-chronicle-react-to-fact/references/java.md +1 -1
- package/package/corpus/skills/cratis-chronicle-record-event/SKILL.md +2 -2
- package/package/corpus/skills/cratis-chronicle-reduce-state/references/typescript.md +1 -1
- package/package/corpus/skills/cratis-chronicle-web-workbench/SKILL.md +1 -1
- package/package/corpus/skills/cratis-ci-pipeline-performance/SKILL.md +4 -3
- package/package/corpus/skills/cratis-ci-pipeline-performance/references/publish-pipelines.md +19 -4
- package/package/corpus/skills/cratis-code-review/SKILL.md +6 -2
- package/package/corpus/skills/cratis-code-review/references/csharp.md +3 -3
- package/package/corpus/skills/cratis-commits-and-pull-requests/SKILL.md +6 -38
- package/package/corpus/skills/cratis-commits-and-pull-requests/references/pr-description.md +2 -0
- package/package/corpus/skills/cratis-commits-and-pull-requests/references/pr-labels-and-release.md +5 -4
- package/package/corpus/skills/cratis-commits-and-pull-requests/references/workflow-inputs.md +39 -0
- package/package/corpus/skills/cratis-components-submit-form/SKILL.md +6 -6
- package/package/corpus/skills/cratis-components-submit-form/references/typescript-commanddialog.md +21 -1
- package/package/corpus/skills/cratis-components-submit-form/references/typescript.md +2 -2
- package/package/corpus/skills/cratis-fundamentals-concept/references/csharp-serialization.md +2 -1
- package/package/corpus/skills/cratis-fundamentals-concept/references/csharp.md +1 -0
- package/package/corpus/skills/cratis-fundamentals-concept/references/go.md +1 -1
- package/package/corpus/skills/cratis-fundamentals-concept/references/java-json.md +3 -2
- package/package/corpus/skills/cratis-fundamentals-concept/references/kotlin-json.md +3 -2
- package/package/corpus/skills/cratis-fundamentals-concept/references/typescript-serialization.md +8 -2
- package/package/corpus/skills/cratis-fundamentals-name-value/SKILL.md +8 -7
- package/package/corpus/skills/cratis-fundamentals-type-discovery/SKILL.md +3 -3
- package/package/corpus/skills/cratis-fundamentals-type-discovery/references/csharp-diagnostics.md +3 -0
- package/package/corpus/skills/cratis-fundamentals-type-discovery/references/csharp.md +2 -2
- package/package/corpus/skills/cratis-platform-deliver-slice/references/typescript.md +14 -1
- package/package/corpus/skills/cratis-platform-prepare-release-pr/SKILL.md +8 -8
- package/package/corpus/skills/cratis-platform-prepare-release-pr/references/product-release-checks.md +16 -2
- package/package/corpus/skills/cratis-release-notes/SKILL.md +1 -1
- package/package/corpus/skills/cratis-release-notes/references/publish-repair.md +6 -3
- package/package/corpus/skills/cratis-screenplay-accept-model/references/csharp.md +5 -3
- package/package/corpus/skills/cratis-screenplay-accept-model/references/read-the-evidence.md +2 -2
- package/package/corpus/skills/cratis-screenplay-declare-slice/SKILL.md +6 -10
- package/package/corpus/skills/cratis-screenplay-declare-slice/references/commands.md +8 -4
- package/package/corpus/skills/cratis-screenplay-declare-slice/references/projections.md +2 -0
- package/package/corpus/skills/cratis-screenplay-declare-slice/references/structure-and-imports.md +19 -1
- package/package/corpus/skills/cratis-screenplay-edit-workspace/SKILL.md +2 -1
- package/package/corpus/skills/cratis-screenplay-edit-workspace/references/mcp-tools.md +1 -1
- package/package/corpus/skills/cratis-screenplay-handoff-slice/references/csharp.md +13 -1
- package/package/corpus/skills/cratis-screenplay-model-translation/SKILL.md +1 -1
- package/package/corpus/skills/cratis-screenplay-model-translation/references/boundary-diagnostics.md +1 -1
- package/package/corpus/skills/cratis-screenplay-onboard-workspace/SKILL.md +26 -48
- package/package/corpus/skills/cratis-screenplay-onboard-workspace/references/studio.md +5 -0
- package/package/corpus/skills/cratis-screenplay-specify-outcome/SKILL.md +8 -12
- package/package/corpus/skills/cratis-screenplay-specify-outcome/references/running-mcp.md +12 -0
- package/package/corpus/skills/cratis-screenplay-specify-outcome/references/scenarios.md +2 -2
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-command-results.md +1 -1
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-events.md +6 -0
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-integration.md +3 -2
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-reactors.md +15 -2
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-read-models.md +4 -2
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp.md +1 -1
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/typescript.md +4 -2
- package/package/corpus/skills/cratis-stage-render-slice/SKILL.md +6 -0
- package/package/corpus/skills/cratis-stage-render-slice/references/semantic-conformance.md +64 -0
- package/package.json +1 -1
|
@@ -157,15 +157,15 @@ public record ChangeQuantity([property: Key] CartLineId Id, Quantity Quantity)
|
|
|
157
157
|
```
|
|
158
158
|
|
|
159
159
|
- **Command key.** Mark one property with `[Key]` from `System.ComponentModel.DataAnnotations`, or implement `ICanProvideKeyForCommand.GetKey()` for a computed key. A property named `Id` alone is not a key. Only the first `[Key]` property is used. An event-sourced command selects its event source differently (see [Chronicle commands](csharp-chronicle.md)).
|
|
160
|
-
- **Absence.** A nullable parameter receives `null` for a valid key with no record. A non-nullable parameter makes the state required: a missing record refuses the command as invalid before the code runs.
|
|
161
|
-
- **Another key.** `[LookUpBy(nameof(MoveLine.TargetCartId))]` on the parameter (`Cratis.Arc.Commands`) loads that model by the named command property instead of the command key. For state owned by the caller rather than named in the request, use `[LookUpBy<CallerSubject>]` (the caller's `sub` claim). For another claim derive from the abstract `CallerClaim`, e.g. `public sealed class CallerTenant() : CallerClaim("tenant_id");`, and use `[LookUpBy<CallerTenant>]`: the key is the single distinct nonempty value of that exact claim type; an anonymous or system caller, or no value, counts as missing, and several distinct values as ambiguous. For any other source implement
|
|
160
|
+
- **Absence.** A nullable parameter receives `null` for a valid key with no record. A non-nullable parameter makes the state required: a missing record refuses the command as invalid before the code runs. Under Chronicle read protection `On`, a nullable parameter also receives `null` (when neither the parameter nor its read model type is marked `[Unprotected]`), with no read and no guard, when its key comes from a command property that is not an event-source candidate (an `EventSourceId`, a type deriving from `EventSourceId<T>`, or a property carrying Chronicle's `[Key]`) and that value is null, empty or whitespace-only: treat that `null` as "no key supplied" as well as "not found", or reject blank values before invocation. A parameter or read model type marked `[Unprotected]` gets no such shortcut. A malformed non-blank key is still refused. With Chronicle, a public settable non-nullable concept property of the command that arrives `null` is refused as required ("The value is required.") during command validation. Only the first event-source candidate property is exempt, even when `ICanProvideEventSourceId` supplies the event source ID; get-only properties are not checked.
|
|
161
|
+
- **Another key.** `[LookUpBy(nameof(MoveLine.TargetCartId))]` on the parameter (`Cratis.Arc.Commands`) loads that model by the named command property instead of the command key. For state owned by the caller rather than named in the request, use `[LookUpBy<CallerSubject>]` (the caller's `sub` claim). Caller-derived lookups (`[LookUpBy<TKeyProvider>]`) are supported only on a Chronicle read model that is not per-stream. Elsewhere, including Entity Framework Core and MongoDB state, Arc refuses the lookup with `InvalidLookUpBy` when it resolves that parameter; a parameter Arc binds itself, such as `CancellationToken`, silently ignores the attribute. For another claim derive from the abstract `CallerClaim`, e.g. `public sealed class CallerTenant() : CallerClaim("tenant_id");`, and use `[LookUpBy<CallerTenant>]`: the key is the single distinct nonempty value of that exact claim type; an anonymous or system caller, or no value, counts as missing, and several distinct values as ambiguous. For any other source implement `IReadModelKeyProvider` whose `Resolve(ReadModelKeyContext)` returns `ReadModelKeyLookup.Found(key)`, `Missing` or `Ambiguous`. A provider sees only the caller and the target read-model type. Arc shares one instance, so it needs a public parameterless constructor and must be stateless and thread-safe, with no services, dependency injection or IO; if the key needs those, a provider does not fit, so have sign-in issue the key as a claim instead. Never invent a client-supplied property for it. A missing or ambiguous key or a throwing provider refuses the command as unauthorized (`ReadModelKeyResolutionDenied`: `IsAuthorized` false, HTTP 403) before `Handle` runs, never as a validation failure. Arc never falls back to a client key, even for a nullable parameter; the absence rules above apply only once a key is found.
|
|
162
162
|
- To contribute an integration-wide key convention, implement `ICanResolveKeyForCommand.Resolve(object command)`, e.g. `command is MoveLine move ? move.LineId.ToString() : null`. Custom resolvers precede the default; first nonempty key wins.
|
|
163
|
-
- Under effective Chronicle read protection `On`, `[LookUpBy(nameof(line), nameof(CartLine.CartId))] Cart cart` takes its key from the sibling protected `CartLine line` parameter.
|
|
163
|
+
- Under effective Chronicle read protection `On`, `[LookUpBy(nameof(line), nameof(CartLine.CartId))] Cart cart` takes its key from the sibling protected `CartLine line` parameter. Arc reads the source parameter first, whatever the declaration order. When the target is read, both reads guard the command's append. A nullable target is `null`, with no target read and no guard for it, when a nullable source is absent or the source's relationship value is null, empty or whitespace-only. A non-nullable source with no record refuses the command before the target is bound, whatever the target's nullability. The relationship property's type must exactly match the target model's key type (a nullable wrapper is allowed). A cycle, an unknown sibling name, an `[Unprotected]` or per-stream model, or an effective `Off` or `Measure` mode is refused with `InvalidLookUpBy` before Arc acquires arguments for that member. A sibling lookup always needs the Arc source generator's metadata for the relationship property and the target key type, even when `ReadProtection:RequireGeneratedMetadata` is `false`; without it the lookup is refused with `InvalidLookUpBy`. Use `[ProtectedDecision]` on a command that requires guarded decision reads; mark an advisory parameter `[Unprotected("display only")]` only if it cannot affect the decision.
|
|
164
164
|
- Which store loads the parameter is decided by the integration that owns the read model type (Chronicle, Entity Framework Core, MongoDB); nothing is registered per command. Only when writing an integration for another store, implement `ICanResolveReadModelForCommand` (`ReadModelTypes`, `Ownership`, `Resolve(Type readModelType, CommandContext commandContext)` returning `null` when nothing exists for the key) and register it with `services.AddReadModelsForCommand(resolver)`. `ReadModelForCommandOwnership.Declared` claims its types even when another provider resolves them; `Fallback` claims only types nothing else resolves.
|
|
165
165
|
- Never return `null` or a nullable event to express "the record is missing": check the nullable parameter and return a `ValidationResult` failure instead.
|
|
166
166
|
- Sharing the instance is not a lock or a freshness guarantee. Protect a rule that must hold under concurrent writes with a storage constraint, a conditional write, or the Chronicle decision guard (`cratis-chronicle-protect-decision` skill).
|
|
167
167
|
|
|
168
|
-
Failures when the state cannot be loaded.
|
|
168
|
+
Failures when the state cannot be loaded. A refused caller-derived key (`[LookUpBy<TKeyProvider>]`) is not one of them: it is the authorization failure above, and application exception mappers do not change it. By default, of the table rows, the first two are client-input failures (HTTP 400, reason `ValidationResultReason.DependencyUnavailable`, a generic message that does not name the read model type), and the rest are defects in the application and surface as server errors. During command execution an `ICommandExceptionMapper` (`Cratis.Arc.Commands`) can replace these outcomes; a validation-only call does not consult it, and an `IExceptionResponseMapper` does not replace the built-in validation failures.
|
|
169
169
|
|
|
170
170
|
| Failure | Cause | Fix |
|
|
171
171
|
| --- | --- | --- |
|
|
@@ -174,8 +174,8 @@ Failures when the state cannot be loaded. The first two are client-input failure
|
|
|
174
174
|
| `CannotResolveCommandDependency` | A non-nullable `Handle` or `Provide` parameter that is not a registered read model resolved to nothing. | Register the service, or make the parameter nullable. |
|
|
175
175
|
| `CannotResolveValidatorDependency` | The same for a validator constructor parameter. | Register the service, or make the parameter nullable. |
|
|
176
176
|
| `AmbiguousReadModelLookup` | Chronicle read model: several command properties have the model's key type. | Select one with `[LookUpBy(nameof(...))]`. |
|
|
177
|
-
| `InvalidLookUpBy` | `[LookUpBy]` names a missing property, sits on a non-read-model parameter, combines the property and provider forms, or `Provide` supplies a value for a caller-keyed parameter. | Use exactly one lookup form on a read-model parameter and let Arc load it. |
|
|
178
|
-
| `CommandReadModelKeysMissing` | Chronicle read model: the generated key metadata for the command or read model is absent while generated metadata is required. That is the default, and always the case where dynamic code is unavailable. | Enable the Arc source generator in the project that declares the type. Setting `ReadProtection:RequireGeneratedMetadata` to `false` instead falls back to reflection with a warning, only on a runtime that supports dynamic code. |
|
|
177
|
+
| `InvalidLookUpBy` | `[LookUpBy]` names a missing property, sits on a non-read-model parameter, combines the property and provider forms, puts a caller-derived lookup on a resolved parameter other than a non-per-stream Chronicle read model, or `Provide` supplies a value for a caller-keyed parameter. | Use exactly one lookup form on a read-model parameter and let Arc load it. |
|
|
178
|
+
| `CommandReadModelKeysMissing` | Chronicle read model: the generated key metadata for the command or read model is absent while generated metadata is required. That is the default, and always the case where dynamic code is unavailable. | Enable the Arc source generator in the project that declares the type. Setting `ReadProtection:RequireGeneratedMetadata` to `false` instead falls back to reflection with a warning, only on a runtime that supports dynamic code; sibling lookups (`[LookUpBy(nameof(line), …)]`) get no fallback. |
|
|
179
179
|
| `ReadCannotBeProtected` | Chronicle read protection `On`: the parameter's read model has a shape the decision guard cannot cover (a reducer with constructor dependencies or an event filter, joins or children, a key taken from an event property, a key whose read-model schema is neither a string without a format nor a `Guid` with format `guid` or `uuid` (the CLR type alone does not decide this), another event sequence, pinned generation delivery), or the parameter is an `IMongoCollection<T>` of a Chronicle read model. | Apply the fix the message names for that parameter: inject the read model itself, or read a source-keyed model without those features. Mark the parameter `[Unprotected("why")]` only if it cannot affect the decision. Under `Measure` or `On`, analyzer `ARCCHR0024` warns for the refused shapes visible in source; `ARCCHR0026` reports the `IMongoCollection<T>` parameter (a warning under `On`). |
|
|
180
180
|
| `ProtectedReadModelKeyAccessorMissing` | Chronicle read protection: a key is a custom record or class (not a scalar, concept or tuple) that the source generator could not describe, for example a partial or external type. | Before the host starts, call `ProtectedReadModelKeyAccessors.Register<WarehouseKey>(new(nameof(WarehouseKey.Warehouse), key => key.Warehouse), new(nameof(WarehouseKey.Section), key => key.Section))` (`Cratis.Arc.Chronicle.ReadModels`) with every public readable instance property, once per concrete type. Prefer a concept or scalar key. |
|
|
181
181
|
|
|
@@ -261,7 +261,7 @@ public record ScheduleDelivery(CartId CartId, [property: ExplicitOffset] DateTim
|
|
|
261
261
|
| `CorrelationId` | Identifies the execution; also on the result. |
|
|
262
262
|
| `Type`, `Command` | The command type and instance. |
|
|
263
263
|
| `ReceivedAt` | When the command was received. Use it instead of reading the clock. |
|
|
264
|
-
| `AuthorizedPrincipal` |
|
|
264
|
+
| `AuthorizedPrincipal` | Set only when scheme authentication selected an authenticated principal that differs from the original caller; otherwise `null`, even when a scheme selected an equivalent principal. Read the caller from `ICurrentPrincipalAccessor.Current` (`Cratis.Arc.Authorization`), not from this. |
|
|
265
265
|
| `Dependencies` | Resolved `Provide` values and handler arguments; empty during filters. |
|
|
266
266
|
| `Values` | Case-insensitive extension values, shared across the execution. |
|
|
267
267
|
| `GeneratedValues` | Captures of `[GeneratedValue]` parameters. |
|
|
@@ -25,6 +25,6 @@ public record AllocateDispatch(ReservationId Id) : ICommandOperation
|
|
|
25
25
|
}
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
-
Register `builder.Services.AddScoped<IDispatch, Dispatch>();` and supply the host's `IAbilityInvoker` (Arc supplies none). Its `Task<AbilityInvocationResult> Invoke(AbilityInvocation invocation, CancellationToken cancellationToken)` dispatches `System`, `Ability` and `Inputs` to the provider with `IdempotencyKey` and `Causation`. Return `AbilityInvocationResult.ReturnedWith()` (or pass a return value)
|
|
28
|
+
Register `builder.Services.AddScoped<IDispatch, Dispatch>();` and supply the host's `IAbilityInvoker` (Arc supplies none). Its `Task<AbilityInvocationResult> Invoke(AbilityInvocation invocation, CancellationToken cancellationToken)` dispatches `System`, `Ability` and `Inputs` to the provider with `IdempotencyKey` and `Causation`. Return `AbilityInvocationResult.ReturnedWith()` (or pass a return value) when the ability did its work, and `AbilityInvocationResult.FailedWith(reason)` only when it could not. A `failed` outcome makes the adapter throw `AbilityInvocationFailed`, and a thrown invoker exception propagates. Let either escape `Execute` to fail the command; compensation then follows the commit disposition. If either escapes `Compensate`, Arc records a failed compensation; it does not replace the original failure, and Arc still attempts the remaining eligible compensators within the budget. Catching and swallowing it inside `Compensate` records the compensation as completed and hides the failure. `FailedWith` reports that the invocation failed, not that the provider made no change, so keep the reversal safe to run anyway. Report any other declared business outcome as `new AbilityInvocationResult("<outcome>")`: `Invoke` returns it instead of throwing, so have the adapter method return it. The operation can inspect it and act (for example, throw to fail the command); that works at runtime, but Screenplay then cannot extract that phase as `invokes`. Do not use returned data as an operation receipt.
|
|
29
29
|
|
|
30
|
-
`Invoke`
|
|
30
|
+
Call `Invoke` only from an operation's `Execute` or `Compensate`; when no operation phase is running it throws `InvalidCommandOperation`. Its key distinguishes the correlation, operation index/type, phase, system/ability and call ordinal; a retry as another command still needs the business reservation ID. Causation includes `command`, `correlationId`, `operation` and `phase`. To reverse an allocation, expose a separate release ability and call it in `Compensate` with the original ID. For Screenplay discovery keep each statement of a phase a direct (optionally awaited or returned) call on an `ISystemAbilities` parameter using operation inputs; any other statement, such as a branch on a result, leaves that phase unextracted. Test the adapter with a recording invoker to check the input map, causation and distinct execution/reversal keys.
|
|
@@ -14,7 +14,7 @@ public Task Compensate(ISeatHolds holds, CommandOperationFailure failure, Cancel
|
|
|
14
14
|
|
|
15
15
|
Use `failure.InvocationIndex` to identify the entry, `InvocationCompleted` to distinguish returned executions, and `IsFailingInvocation` to identify the failing one. `Source` classifies the original failure (`Planning`, `ResponseHandling`, `Execution`, `Cancellation`, `ScopeCompletion`); `CommitDisposition` and `ExceptionMessages` describe its observed commit facts and errors. Planning failures before entry have nothing to compensate.
|
|
16
16
|
|
|
17
|
-
Recovery has its own token. For example, `builder.Services.Configure<CommandOperationOptions>(o => o.CompensationTimeout = TimeSpan.FromSeconds(12));` changes the shared budget (default 30 seconds; positive, at most 4294967294 ms).
|
|
17
|
+
Recovery has its own token. For example, `builder.Services.Configure<CommandOperationOptions>(o => o.CompensationTimeout = TimeSpan.FromSeconds(12));` changes the shared budget (default 30 seconds; positive, at most 4294967294 ms). The budget is cooperative. Before entering each available callback Arc checks the token; once it has expired, Arc skips that callback and records it as `BudgetExpired`. A callback that already started is awaited to the end, even past expiry. It is recorded as `Failed` if it threw (including an `OperationCanceledException` from honouring the token) or Arc detected a nested command attempt through the same host, and otherwise as `Completed`. Size the budget for the whole reverse chain; passing `CancellationToken.None` to a provider only stops that call observing Arc's budget, and later callbacks are still skipped once it has expired. A thrown compensator is recorded; earlier entries are still attempted within budget. There are no automatic retries. Cleanup errors do not replace the original error.
|
|
18
18
|
|
|
19
19
|
## Pipeline specs
|
|
20
20
|
|
|
@@ -29,13 +29,15 @@ result.ShouldHaveCompensatedOperation<HoldSeat>();
|
|
|
29
29
|
|
|
30
30
|
Assert the provider released **that ID** and the original failure remains. For success, use `result.ShouldHaveExecutedOperation<HoldSeat>()` (completed, not merely entered). For rejected validation or failed preflight use `result.ShouldHaveNoOperationInvocations()`. Scenario methods with the same names assert on its last result; `scenario.Operations` exposes its outcomes. `Validate` alone does not execute operations.
|
|
31
31
|
|
|
32
|
-
`result.Recovery` is a nullable `CommandRecoverySummary`. Inspect its `CommitDisposition` and `Status`: `NotNeeded`, `Completed` (
|
|
32
|
+
`result.Recovery` is a nullable `CommandRecoverySummary`. Inspect its `CommitDisposition` and `Status`: `NotNeeded`, `Completed` (every started entry's compensation recorded as `Completed`), `Incomplete` (at least one recorded otherwise, for example `Failed`, `NotAvailable` or `BudgetExpired`), `Suppressed` (known commit), `Indeterminate` (unknown/mixed). Assert `StartedCount`, `CompletedCount`, `CompensatedCount`, `FailedCompensationCount`, `UncompensatedCount` to distinguish entry, acknowledgement and cleanup. In the lost-acknowledgement test expect one started, zero completed and one compensated. For an uncertain commit after entry, expect `CommandRecoveryStatus.Indeterminate` and no release.
|
|
33
33
|
|
|
34
34
|
Each `result.OperationOutcomes` entry is a `CommandOperationOutcome` with `InvocationIndex`, `OperationType`, `ExecutionCompleted`, `Compensation` (`NotNeeded`, `Completed`, `Failed`, `NotAvailable`, `BudgetExpired`, `Suppressed`) and optional `CompensationFailure`. Test batch failure by recording provider calls: the throwing entry must be released before earlier ones, and unstarted entries never appear. Neither recovery property is an HTTP response field.
|
|
35
35
|
|
|
36
|
+
Arc fills both after every execution scope has completed, so a scope's `Complete` cannot read them. They exist only once Arc has planned the returned operations; if planning fails first (for example a missing `Execute` or `Compensate` dependency), `Recovery` is null and `OperationOutcomes` is empty. An in-process caller of `ICommandPipeline.Execute` gets them on the returned result. For a command received over HTTP, the server-side record is Arc's log: when recovery runs and logging is enabled, Arc attempts an Information entry `Command {CorrelationId} operation recovery: commit {CommitDisposition}, status {RecoveryStatus}, …`, and a Warning for each thrown compensator. That log is best-effort and aggregate, and an HTTP caller can reuse a correlation ID, so use it only for diagnostic correlation. For reliable UI status, execute in process and store `result.Recovery` under an application-owned invocation ID. A record written from inside `Compensate` cannot report `Suppressed`, `Indeterminate`, `NotAvailable` or `BudgetExpired`, because no callback runs in those cases.
|
|
37
|
+
|
|
36
38
|
## Custom execution scope
|
|
37
39
|
|
|
38
|
-
|
|
40
|
+
When a command's `Handle` return type can contain an operation, Arc checks every discovered execution scope before any scope begins: each must implement `ICommandOperationExecutionScope`, and at most one may report `IsCommitParticipant => true`. Otherwise the command fails with `InvalidCommandOperation` before filters, `Handle` or any operation run. Commands whose `Handle` cannot return an operation are not checked. With Chronicle configured, its transactional scope is already the commit participant, so a scope that commits other storage is neither a valid second participant nor an honest nonparticipant: derive that state from the committed events, or move the write out of the command. For a purely observational scope the contract can be as small as:
|
|
39
41
|
|
|
40
42
|
```csharp
|
|
41
43
|
public sealed class ObservationScope : ICommandOperationExecutionScope
|
|
@@ -47,4 +49,4 @@ public sealed class ObservationScope : ICommandOperationExecutionScope
|
|
|
47
49
|
}
|
|
48
50
|
```
|
|
49
51
|
|
|
50
|
-
For storage, set `IsCommitParticipant` to a stable `true
|
|
52
|
+
For the single storage scope, set `IsCommitParticipant` to a stable `true`. `Begin` must leave resources cleanable on partial failure without committing. Report `NotCommitted` while deferred; an early committed, mixed or unknown observation can block entry. `Complete` must respect command failure. Even if completion throws, report actual provider facts; a later scope failure cannot erase a known commit. Keep recovery dependencies usable after completion, obtaining fresh provider resources if necessary without losing tenant context. Test known rejection, confirmed commit followed by failure, and ambiguous commit against the real store.
|
|
@@ -46,6 +46,6 @@ Read [recovery, scope contracts and pipeline specs](csharp-recovery.md) when tes
|
|
|
46
46
|
|
|
47
47
|
## Not supported in this SDK
|
|
48
48
|
|
|
49
|
-
- Execution receipts, nested
|
|
49
|
+
- Execution receipts, nested commands and parallel/detached participation. A command started through the same host's pipeline from inside `Execute` (for example via `ICommandPipeline`) inherits the active command frame, so it is refused and does not run. When Arc's nesting guard records the attempt, the outer command fails after that operation returns even if the operation ignored the child's result. From `Compensate`, the attempt is recorded as a failed compensation. Instead decide the whole flat batch in `Handle`: take the provider's request key from the command as a caller-supplied business identifier that a retry reuses, pass it into the operation, and return the event and response beside the operation as in the return shapes above. A `[GeneratedValue]` `Handle` parameter shares one value between the event, response and operation within one execution, but a resubmission resolves it again and can get a different value, so do not use it alone as the provider's deduplication key. Represent a provider-assigned result in a separate decision.
|
|
50
50
|
- Durable compensation, retry or atomicity across arbitrary provider/database writes — reconcile against provider and storage records, or react idempotently to a committed fact.
|
|
51
|
-
- Client-visible recovery observations —
|
|
51
|
+
- Client-visible recovery observations — store the backend result under an application-owned invocation ID; do not infer a reversal from a failed HTTP call.
|
|
@@ -34,7 +34,7 @@ Python has no Arc application SDK: trace the subscription in the service that ow
|
|
|
34
34
|
| Direct WebSocket | Upgrade the query route to compare socket delivery with direct SSE; capture the handshake separately from the first query result. |
|
|
35
35
|
| WebSocket hub | At `/.cratis/queries/ws`, distinguish an admitted physical connection from a successful `Subscribe` for the intended `queryId` and query name. `Unsubscribe` removes that subscription, not its siblings. |
|
|
36
36
|
| SSE hub | Open `/.cratis/queries/sse`; POST to its `/subscribe` and `/unsubscribe` controls with the issued connection ID and matching ownership credentials. A silent open stream without a subscribe is expected. |
|
|
37
|
-
| Revisions | When the hub advertises subscription revisions, correlate controls and results by connection, query ID and revision
|
|
37
|
+
| Revisions | When the hub advertises subscription revisions, correlate controls and results by connection, query ID and revision. Most hosts block a subscribe at or below the latest revision held for that connection and query ID; Elixir blocks only a lower one, so replaying the cancelling revision reopens the subscription. A blocked subscribe is usually dropped silently but can instead get an `Error`, such as a subscription-limit error. Blocking lasts only while the host keeps the record: some hosts drop a cancelled record after a limited time or count, and then a delayed old subscribe is accepted again. |
|
|
38
38
|
| Transfer mode | Inspect `transferMode`: full results replace state; delta collection delivery needs an initial baseline before later change sets. Check stable item identities before treating remove/add as a missed update. With no preference, inspect the actual result rather than assuming delta-only frames. |
|
|
39
39
|
| Admission and delivery errors | Check authentication, authorization, origin and argument validation at opening. After admission distinguish a suppressed candidate (no delivery), terminal denial and source failure from an allowed empty value. Preserve the result and correlation ID without logging credentials. |
|
|
40
40
|
| Keep-alive | Inspect the advertised interval and idle `Ping` traffic; a ping is not query data. Compare idle disconnect timing with proxy timeouts. |
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# C#: trace a missing delivery run on one subscription
|
|
2
2
|
|
|
3
|
-
Use the application's ASP.NET Core Arc host (`builder.AddCratisArc()`); for sockets put `app.UseWebSockets()` before `app.UseCratisArc()`. Use the generated proxy's
|
|
3
|
+
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.
|
|
4
4
|
|
|
5
5
|
## Establish the baseline
|
|
6
6
|
|
|
@@ -33,18 +33,18 @@ curl -i -X QUERY "$route" -H 'Content-Type: application/json' \
|
|
|
33
33
|
|
|
34
34
|
## Compare the hub subscription
|
|
35
35
|
|
|
36
|
-
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
|
|
36
|
+
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:
|
|
37
37
|
|
|
38
38
|
```json
|
|
39
|
-
{"type":"Subscribe","queryId":"trace","revision":1,"payload":{"queryName":"DeliveryRuns.Open","arguments":{"depot":"North"},"page":0,"pageSize":20,"sortBy":"departure","sortDirection":"asc","transferMode":"delta"}}
|
|
39
|
+
{"type":"Subscribe","queryId":"trace","revision":1,"payload":{"queryName":"Dispatch.DeliveryRuns.Open","arguments":{"depot":"North"},"page":0,"pageSize":20,"sortBy":"departure","sortDirection":"asc","transferMode":"delta"}}
|
|
40
40
|
```
|
|
41
41
|
|
|
42
|
-
Inspect `QueryResult.payload` on `trace` and revision 1. `Error` or `Unauthorized` is not an empty successful result. When finished send `{"type":"Unsubscribe","queryId":"trace","revision":
|
|
42
|
+
Inspect `QueryResult.payload` on `trace` and revision 1. `Error` or `Unauthorized` is not an empty successful result. When finished send `{"type":"Unsubscribe","queryId":"trace","revision":1}`, using the revision you subscribed with. The server ignores a lower unsubscribe revision and accepts an equal or higher one; a higher one also cancels the older work. A subscribe is ignored when its revision is at or below the latest revision the connection still holds for that query ID. A newer active subscription keeps blocking older controls. After an unsubscribe, the connection keeps that record only for a limited time and number of query IDs; once it is dropped and nothing newer has replaced it, a delayed subscribe with an old revision is accepted again. To change arguments, subscribe again on the same `queryId` with a higher revision; it replaces the older subscription. Discard `QueryResult`, `Error` and `Unauthorized` frames whose revision is not current; `Connected`, `Ping` and `Pong` carry no revision, so keep them. After reconnecting, compare connection as well as query ID and revision.
|
|
43
43
|
|
|
44
44
|
For SSE hub, keep `GET /.cratis/queries/sse` open. Use the same owner credentials for both controls. Example POST bodies (`application/json`), substituting `Connected.payload` for `issued-id`:
|
|
45
45
|
|
|
46
|
-
- `/.cratis/queries/sse/subscribe`: `{"connectionId":"issued-id","queryId":"trace","revision":1,"request":{"queryName":"DeliveryRuns.Open","arguments":{"depot":"North"}}}`. Read results on the **open stream**, not the POST response.
|
|
47
|
-
- `/.cratis/queries/sse/unsubscribe`: `{"connectionId":"issued-id","queryId":"trace","revision":
|
|
46
|
+
- `/.cratis/queries/sse/subscribe`: `{"connectionId":"issued-id","queryId":"trace","revision":1,"request":{"queryName":"Dispatch.DeliveryRuns.Open","arguments":{"depot":"North"}}}`. Read results on the **open stream**, not the POST response.
|
|
47
|
+
- `/.cratis/queries/sse/unsubscribe`: `{"connectionId":"issued-id","queryId":"trace","revision":1}`. Siblings remain subscribed. Invalid control fields can give 400; a missing or unowned connection gives 404.
|
|
48
48
|
|
|
49
49
|
On hub subject collections, `full` sends snapshots only; omitted mode sends snapshots plus change sets when identity supports them. `delta` starts with a full baseline, then can send only `changeSet`. Look for a stable case-insensitive `Id` property; without identity the server sends data instead. An ordered delta that would not reproduce the new order also falls back to a snapshot. Replace state on a snapshot; don't apply patches against a previous connection's baseline. Async enumerable streams do not use `transferMode`.
|
|
50
50
|
|
|
@@ -37,7 +37,7 @@ On `/.cratis/queries/ws`, `Connected.payload` is the physical connection ID, not
|
|
|
37
37
|
{"type":"Unsubscribe","queryId":"probe","revision":2}
|
|
38
38
|
```
|
|
39
39
|
|
|
40
|
-
Match `QueryResult`, `Unauthorized` or `Error` by `queryId` and `revision`. When `supportsSubscriptionRevisions` is advertised use increasing positive safe integers for each ID; replaying revision 1 after revision 2
|
|
40
|
+
Match `QueryResult`, `Unauthorized` or `Error` by `queryId` and `revision`. When `supportsSubscriptionRevisions` is advertised use increasing positive safe integers for each ID; replaying revision 1 after revision 2 does not reopen it while the host keeps the cancellation record (up to two minutes and 1024 cancelled IDs per connection); after that, it can. `Ping`/`Pong` carry timestamps, not data; compare idle traffic to `Connected.keepAliveIntervalMs`.
|
|
41
41
|
|
|
42
42
|
For the SSE hub keep GET `/.cratis/queries/sse` open. POST JSON to its `/subscribe` control, e.g. `{"connectionId":"<Connected.payload>","queryId":"probe","revision":1,"request":{"queryName":"Dispatch.DeliveryRun.Active"}}`. POST `{"connectionId":"<Connected.payload>","queryId":"probe","revision":2}` to `/unsubscribe`. Use the connection owner's credentials. For both hubs the subscription request takes string argument values and optional `page`, `pageSize`, `sortBy`, `sortDirection` (not the QUERY-body shape).
|
|
43
43
|
|
|
@@ -31,7 +31,7 @@ curl -NsS -H 'Accept: text/event-stream' "$Q" | tee capture.sse
|
|
|
31
31
|
## Locate a transport or delivery failure
|
|
32
32
|
|
|
33
33
|
- **Direct WebSocket:** upgrade the same route (`ws`/`wss`) with the same arguments. Both direct and hub sockets need `org.springframework.boot:spring-boot-starter-websocket` or `org.springframework:spring-websocket` on the runtime classpath. Look for `Data` with a QueryResult in `data`; distinguish timestamped `Ping`/`Pong` from data. A browser 403 before the upgrade can be an origin mismatch, not a failed query.
|
|
34
|
-
- **WebSocket hub:** upgrade `/.cratis/queries/ws`. `Connected` is physical admission only. Send `{"type":"Subscribe","queryId":"d1","revision":1,"payload":{"queryName":"Dispatch.Delivery.Active","arguments":{},"transferMode":"full"}}` using the actual generated query name. Match `QueryResult`, `Error` or `Unauthorized` by `queryId` and revision. Send `{"type":"Unsubscribe","queryId":"d1","revision":2}`; siblings should stay open. With `supportsSubscriptionRevisions`, replaying revision 1
|
|
34
|
+
- **WebSocket hub:** upgrade `/.cratis/queries/ws`. `Connected` is physical admission only. Send `{"type":"Subscribe","queryId":"d1","revision":1,"payload":{"queryName":"Dispatch.Delivery.Active","arguments":{},"transferMode":"full"}}` using the actual generated query name. Match `QueryResult`, `Error` or `Unauthorized` by `queryId` and revision. Send `{"type":"Unsubscribe","queryId":"d1","revision":2}`; siblings should stay open. With `supportsSubscriptionRevisions`, replaying revision 1 does not resurrect d1 while the host keeps the cancellation record (up to two minutes and 1024 cancelled IDs per connection); after that, it can. Use safe integer revisions.
|
|
35
35
|
- **SSE hub:** GET `/.cratis/queries/sse` as an event stream, keep it open, and take the connection ID from `Connected.payload`. POST JSON `{"connectionId":"<id>","queryId":"d1","revision":1,"request":{"queryName":"Dispatch.Delivery.Active","transferMode":"delta"}}` to `/.cratis/queries/sse/subscribe`; POST `{"connectionId":"<id>","queryId":"d1","revision":2}` to `/.cratis/queries/sse/unsubscribe` as the same owner. Results arrive on the stream, not the control response. Read `keepAliveIntervalMs` on `Connected`; idle heartbeats do not establish delivery.
|
|
36
36
|
- **Collection transfer:** `full` replaces the list; `delta` needs the first delivered full baseline before subsequent change sets. Without a preference expect both snapshot and change set (initially all added). Stable unique keys permit replacements. Missing, null or duplicate keys in explicit delta mode fall back to serialized JSON membership: edits become remove/add, duplicate multiplicity and order-only changes aren't conveyed. Compare in `full` before blaming storage.
|
|
37
37
|
- **Admission versus delivery:** check argument validation, tenant resolution and query authorization even if the anonymous hub handshake succeeded. Register a `GuardObservableQueryEmission` Spring bean to check each candidate; `guard(context)` returns `CompletionStage<ObservableQueryEmissionVerdict>`. For synchronous checks use e.g. `BlockingObservableQueryEmissionGuard { ctx -> policy.verdict(ctx.principal, ctx.tenantId, ctx.data) }`. `ALLOW` delivers unless another guard is more restrictive; `SUPPRESS` stays open and `isFirstEmission` remains true until delivery; `DENY_AND_TERMINATE` or a guard failure fails closed. Capture correlation ID and verdict, not row contents. An `Unauthorized` ends that subscription. Compare the rendered page, source completion, failure and collector cancellation before assuming a transport drop.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Diagnose a tool call
|
|
2
2
|
|
|
3
|
-
Work top to bottom. Steps 3 to 9 follow the order
|
|
3
|
+
Work top to bottom. Steps 3 to 9 follow the order of MCP admission. The capability gate runs before step 3 and can also return 400 `invalid_request`, 401 `unauthorized` or 403 `forbidden`, with no audit record, so a status alone does not tell which layer refused. Refusals are JSON bodies of the form `{"error":"<code>"}`. Do not relax authorization to make a probe pass.
|
|
4
4
|
|
|
5
5
|
1. **Host fails to start.** Fix the first error:
|
|
6
6
|
- Capability hosting is not enabled, or its endpoint group has no port assigned.
|
|
@@ -17,9 +17,11 @@ Work top to bottom. Steps 3 to 9 follow the order in which Arc checks a request,
|
|
|
17
17
|
5. **405 `method_not_allowed`.** A GET or DELETE on the tool path; the response carries `Allow: POST`.
|
|
18
18
|
6. **413 `request_too_large`.** The body exceeds the configured limit.
|
|
19
19
|
7. **400 `invalid_request`.** Invalid JSON, a duplicated member at any depth, or a batch array. Send one JSON-RPC object.
|
|
20
|
-
8. **403 `insufficient_scope`.** The caller holds neither the tool's required set nor any complete alternative set. `WWW-Authenticate` lists the required scopes, plus the metadata location when an OAuth caller can step up. A PAT can only hold scopes on the allowed list: add the scope there and issue a new token.
|
|
21
|
-
9. **403 `forbidden
|
|
22
|
-
|
|
20
|
+
8. **403 `insufficient_scope`.** The caller holds neither the tool's required set nor any complete alternative set. `WWW-Authenticate` lists the required scopes, plus the metadata location when an OAuth caller can step up. A PAT can only hold scopes on the allowed list: add the scope there and issue a new token. A scope with `*` or an `admin` or `approve` segment can never be added, so no PAT can call a tool that requires one.
|
|
21
|
+
9. **403 `{"error":"forbidden"}` without a `WWW-Authenticate` header.** Two layers send this body, and neither gives a tool result or a reason. Check both:
|
|
22
|
+
- The capability gate refused the caller before step 3, for example because the tenant membership check denied the person or the caller's principal kind is not allowed. There is no call audit record.
|
|
23
|
+
- A tool authorizer returned `false` or threw at admission, before the MCP server read the request. The call audit records outcome `not_allowed` for the tool. A cancelled request is not refused this way: the cancellation propagates with no record.
|
|
24
|
+
10. **Tool absent from the list.** List with the actual caller; the host's catalog is not evidence that this caller can see the tool. Causes: the caller lacks the scopes, an authorizer hides it, the availability gate decides it is unavailable, or it was never exposed. Startup warning `5103` names a tool scope that the PAT allowed scopes lack: no PAT can see that tool until the scope is allowed. Scopes with `*` or an `admin` or `approve` segment can never be allowed for a PAT.
|
|
23
25
|
11. **HTTP 200 but the call failed.** Inspect the tool error flag and the outcome; a tool-level refusal is not a successful write.
|
|
24
26
|
- Invalid arguments: an argument is missing, mistyped or not in the input schema.
|
|
25
27
|
- Scope or permission text: the check failed again at dispatch, or the operation's own authorization refused (outcome not authorized).
|
|
@@ -37,8 +39,8 @@ Work top to bottom. Steps 3 to 9 follow the order in which Arc checks a request,
|
|
|
37
39
|
| `failed` | The tool ran and returned a tool error, such as a validation or authorization failure of the operation. |
|
|
38
40
|
| `invalid_arguments` | The arguments did not match the input schema. |
|
|
39
41
|
| `malformed` | A curated tool returned a result that breaks the result rules. |
|
|
40
|
-
| `error` | The tool threw
|
|
42
|
+
| `error` | The tool threw, including a cancellation while the tool ran. |
|
|
41
43
|
| `insufficient_scope` | A verified caller lacked the tool's scopes (the 403 in step 8). |
|
|
42
|
-
| `not_allowed` | A tool authorizer refused a verified caller (the 403 in step 9). |
|
|
44
|
+
| `not_allowed` | A tool authorizer refused a verified caller: at admission (the authorizer 403 in step 9) or at dispatch (a tool error). A capability gate 403 has no record. |
|
|
43
45
|
|
|
44
|
-
The audit covers catalog tools only. Requests rejected before a tool is identified have no record: a refused origin, no accepted credential, a wrong method, an oversized body or a malformed body. Calls to tools registered directly on the MCP server have no record either and need their own audit.
|
|
46
|
+
The audit covers catalog tools only. Requests rejected before a tool is identified have no record: a capability gate refusal, a refused origin, no accepted credential, a wrong method, an oversized body or a malformed body. Calls to tools registered directly on the MCP server have no record either and need their own audit.
|
|
@@ -136,6 +136,8 @@ public record CancelDelivery(Guid DeliveryId)
|
|
|
136
136
|
|
|
137
137
|
For a command the attribute is read from the command type and its `Handle` method; for a query from the read model, the performer type and the query method. Add each such scope to `PatOptions.AllowedScopes`, or startup logs warning `5103` and no PAT can use the tool.
|
|
138
138
|
|
|
139
|
+
`AllowedScopes` can never hold a blank scope, a scope with `*` or a scope with an `admin` or `approve` segment (any letter case; segments split on `:`, `.`, `/` and `-`): adding one throws when PAT support is configured. A blank `[RequiresScope]` fails startup. A tool may require a `*`, `admin` or `approve` scope, but no PAT can then satisfy it; with PAT support installed, startup logs warning `5103` for each scope of a tool that has no required or alternative set fully on the allowed list. Holding every scope is necessary, not sufficient: the operation's own authorization and validation and any tool authorizers still run.
|
|
140
|
+
|
|
139
141
|
## Check the scope boundary
|
|
140
142
|
|
|
141
143
|
Pass the token on standard input so it stays out of the process list and shell history:
|
|
@@ -276,7 +278,7 @@ public class PlanAuthorizer(IPlans plans) : IMcpToolAuthorizer
|
|
|
276
278
|
arc.WithMcp(mcp => mcp.AddToolAuthorizer<PlanAuthorizer>());
|
|
277
279
|
```
|
|
278
280
|
|
|
279
|
-
Authorizers are scoped services. `McpToolAuthorization` carries `Tool`, `Caller`, `Services`, `CancellationToken` and `Operation` (`McpToolOperation.List` or `Call`). They run only for a caller whose scopes already satisfy the tool
|
|
281
|
+
Authorizers are scoped services. `McpToolAuthorization` carries `Tool`, `Caller`, `Services`, `CancellationToken` and `Operation` (`McpToolOperation.List` or `Call`). They run only for a caller whose scopes already satisfy the tool: on `tools/list` for each listed catalog tool, and on a call at admission and again at dispatch if admission allows it. Keep them cheap. All must return `true`. An exception thrown by `IsAllowed` counts as `false`, except an `OperationCanceledException` while the request is cancelled, which propagates with no audit record. For `List`, `false` only hides the tool; hiding does not stop a direct call. For `Call`, admission checks first: `false` refuses the request with HTTP 403 and body `{"error":"forbidden"}`, with no `WWW-Authenticate` challenge and no reason, before the MCP server reads it. If admission allows the call, the dispatcher checks again before it runs the tool; a refusal there is a tool error (`isError: true`), not a 403.
|
|
280
282
|
|
|
281
283
|
## Inspect the catalog
|
|
282
284
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: cratis-arc-expose-query
|
|
3
|
-
description: Use when exposing a read model through Arc as a snapshot or live query, choosing its result shape, or extending query execution. Not for
|
|
3
|
+
description: Use when exposing a read model through Arc as a snapshot or live query, choosing its result shape or read-after-write consistency, or extending query execution. Not for writes, paging an existing query, query specs, or a stalled live subscription.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Expose a read model as a query
|
|
@@ -226,18 +226,19 @@ A filter runs before the query method, for snapshots and once when a subscriptio
|
|
|
226
226
|
| `IQueryFilter` | Last | Cross-cutting validation or preconditions |
|
|
227
227
|
|
|
228
228
|
```csharp
|
|
229
|
+
using Cratis.Arc.Authorization;
|
|
229
230
|
using Cratis.Arc.Queries;
|
|
230
231
|
|
|
231
|
-
public class RequireTenant : IAuthorizationQueryFilter
|
|
232
|
+
public class RequireTenant(ICurrentPrincipalAccessor principals) : IAuthorizationQueryFilter
|
|
232
233
|
{
|
|
233
234
|
public Task<QueryResult> OnPerform(QueryContext context) =>
|
|
234
|
-
Task.FromResult(
|
|
235
|
+
Task.FromResult(principals.Current?.HasClaim(claim => claim.Type == "tenant") == true
|
|
235
236
|
? QueryResult.Success(context.CorrelationId)
|
|
236
237
|
: QueryResult.Unauthorized(context.CorrelationId));
|
|
237
238
|
}
|
|
238
239
|
```
|
|
239
240
|
|
|
240
|
-
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.
|
|
241
|
+
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.
|
|
241
242
|
|
|
242
243
|
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:
|
|
243
244
|
|
|
@@ -284,7 +285,7 @@ public class NormalizeZoneName : IInterceptReadModel<ParkingPermit>
|
|
|
284
285
|
}
|
|
285
286
|
```
|
|
286
287
|
|
|
287
|
-
Return a replacement; items in a collection can be intercepted concurrently. Do not rely on the order of several interceptors for one model. A failing interceptor fails the result; the raw value is never sent.
|
|
288
|
+
Return a replacement; items in a collection can be intercepted concurrently, so injected collaborators must be thread-safe. Do not rely on the order of several interceptors for one model. A failing interceptor fails the result; the raw value is never sent. When the hub diffs snapshots, it compares each intercepted item with the same item in the previous admitted snapshot: the same instance is unchanged; otherwise it uses the type's own `Equals` when the type overrides it (records do), else the serialized JSON. A field that changes on every emission, such as a value derived from the clock, makes the item differ each time, so every change set the hub computes lists it as `replaced`; deliver the stable input (such as a timestamp) and derive the changing value on the client. When an emission after the first is an `ObservedCollection<T>` whose `Changes` is set, the change set comes from the items it names instead; with `Changes` null the hub diffs as above. For an ordered query with `transferMode: "delta"`, the hub sends the full snapshot instead whenever the change set cannot reproduce the new order.
|
|
288
289
|
|
|
289
290
|
Interception runs wherever Arc processes the result: model-bound queries, ordinary controller GET actions Arc wraps, observable snapshots and each live emission.
|
|
290
291
|
|
|
@@ -315,6 +316,8 @@ public class RequireActiveSession(ISessions sessions) : IGuardObservableQueryEmi
|
|
|
315
316
|
| `Suppress` | Withhold this emission; the subscription stays open. A snapshot answers 202 |
|
|
316
317
|
| `DenyAndTerminate` | Send nothing, report unauthorized, end the subscription. A snapshot answers 403 |
|
|
317
318
|
|
|
319
|
+
Several guards: the most restrictive verdict wins (`DenyAndTerminate`, then `Suppress`, then `Allow`); discovery order is not a contract, so keep guards independent. `Suppress` does not move the delta baseline: the next allowed emission is diffed against the last admitted snapshot, so its change set carries the net difference since then. A withheld change that has since been reverted is not sent. When the next allowed emission states its changes (`ObservedCollection<T>` with `Changes` set), its change set holds only the items it names, so a withheld change to another item can be lost; combine `Suppress` with stated changes only where that loss is acceptable.
|
|
320
|
+
|
|
318
321
|
When access depends on mutable state, `StateAwareEmissionGuard<TState>` supplies a fail-closed implementation: override `GetKey(context)`, `Read(key, cancellationToken)` and `Decide(principal, state)`. Missing keys, missing state, read failures and rejection terminate delivery; override `OnDenied` for diagnostics. For a decision tied to the opened subscription, a filter can set `QueryContext.SubscriptionScope`; the guard reads a snapshot via `context.SubscriptionScope`.
|
|
319
322
|
|
|
320
323
|
`ISessions` is the application's own contract. The context carries `QueryName`, `Arguments`, `Principal`, `ServiceProvider`, `IsFirstEmission` and `IsSnapshot`.
|
|
@@ -324,15 +327,15 @@ When access depends on mutable state, `StateAwareEmissionGuard<TState>` supplies
|
|
|
324
327
|
Row narrowing restricts which rows of a read model a caller can get, inside the provider query, so no query on that model can return a row the caller may not see. Derive from `QueryRowNarrowing<TReadModel, TKey>`:
|
|
325
328
|
|
|
326
329
|
```csharp
|
|
327
|
-
public class PermitsInOwnZones(IZoneAccess access) : QueryRowNarrowing<ParkingPermit, ZoneName>
|
|
330
|
+
public class PermitsInOwnZones(IZoneAccess access, ICurrentPrincipalAccessor principals) : QueryRowNarrowing<ParkingPermit, ZoneName>
|
|
328
331
|
{
|
|
329
332
|
protected override Expression<Func<ParkingPermit, ZoneName>> Key => permit => permit.Zone;
|
|
330
333
|
|
|
331
334
|
protected override bool AppliesTo(QueryContext context) =>
|
|
332
|
-
|
|
335
|
+
principals.Current?.IsInRole("inspector") != true;
|
|
333
336
|
|
|
334
337
|
protected override async ValueTask<IEnumerable<ZoneName>> GetAllowedKeys(QueryContext context) =>
|
|
335
|
-
await access.ZonesFor(
|
|
338
|
+
await access.ZonesFor(principals.Current);
|
|
336
339
|
}
|
|
337
340
|
```
|
|
338
341
|
|
|
@@ -56,7 +56,7 @@ Query options (`queries.Register` and `queries.RegisterObservable`):
|
|
|
56
56
|
| `WithValidator[A](v)`, `WithScopedValidator[A](factory, keys...)` | Validation of the bound arguments |
|
|
57
57
|
| `WithoutModelValidation[A]()` | Skips the argument model's declared validation |
|
|
58
58
|
| `WithRenderer[A, Q, R](factory, keys...)` | A renderer for this query only |
|
|
59
|
-
| `WithCollectionIdentity[A, T](extract)` |
|
|
59
|
+
| `WithCollectionIdentity[A, T](extract)` | Overrides the server's item identity only; the JSON still needs a conventional `id` for the JavaScript client to apply replacements |
|
|
60
60
|
| `WithEnumerable[A]()` | Observable only: reject ordinary snapshots even with a current value |
|
|
61
61
|
| `WithExcludeFromDiscovery[A](true)` | Omits from discovery; not an access control |
|
|
62
62
|
| `WithDescriptor[A](metadata.Query{...})` | A complete explicit descriptor, for migrations |
|
|
@@ -135,7 +135,7 @@ Never share caller-specific state across tenants. Treat values as immutable afte
|
|
|
135
135
|
|
|
136
136
|
The performer runs once per subscription, after admission. `waitForFirstResult=true` (text `true`, not `1`) with `waitForFirstResultTimeout=<seconds>` waits for the first value; default wait 30 seconds, capped by `MaximumWait`; 408 when it expires. Transports: `Accept: text/event-stream` or a WebSocket upgrade on the route, and the hub at `/.cratis/queries/ws` or `/.cratis/queries/sse`. `Observable.AllowedOrigins` in the host options lists additional exact origins for WebSocket.
|
|
137
137
|
|
|
138
|
-
See [MongoDB and live hosting](go-live.md) for storage-backed observations, transfer modes and load limits. For delta transfer,
|
|
138
|
+
See [MongoDB and live hosting](go-live.md) for storage-backed observations, transfer modes and load limits. For delta transfer, the server keys each item by its exported `ID` or `Id` field (declared on the item or promoted from an embedded struct), or by the key `WithCollectionIdentity` extracts; the JavaScript client matches change-set items by the JSON `id` property, so that property must hold the same value. `WithCollectionIdentity` changes only the server's key; it does not rename JSON. For a generated observable collection whose item has a conventional `ID`/`Id`, the generator requires exactly one such field (embedded and JSON-hidden ones count), declared directly on the item and serialized as `id` (tag it `json:"id"`, without `omitempty` or `omitzero`); it rejects any other layout. When it emits TypeScript proxies, that `id` must also be a non-nullable scalar (string, number, UUID or enum). Without an `id` property the client can still drop a removed item whose JSON is unchanged, but cannot match replaced items reliably. A collection without a server identity always receives full snapshots, in every transfer mode. For optional change hints emit `queries.ObservedCollection[T]` from an `observable.Source[queries.ObservedCollection[T]]`.
|
|
139
139
|
|
|
140
140
|
## Filters, renderers, interceptors and guards
|
|
141
141
|
|
|
@@ -225,7 +225,9 @@ static allPermits(models: ChronicleReadModels): Observable<ParkingPermit[]> {
|
|
|
225
225
|
| `watch(Type)` / `watchIterable(Type)` | Individual changesets |
|
|
226
226
|
| `getStore()` | The tenant's event store |
|
|
227
227
|
|
|
228
|
-
An append acknowledges persistence, not projection catch-up; an active projection is eventually consistent. Pass `ChronicleReadConsistency.Immediate` to `getById`, `findInstanceById` or `getAll` only for a passive projection, which the kernel computes on demand
|
|
228
|
+
An append acknowledges persistence, not projection catch-up; an active projection is eventually consistent. Pass `ChronicleReadConsistency.Immediate` to `getById`, `findInstanceById` or `getAll` only for a `@passive` model-bound projection, which the kernel computes on demand; for an active projection the read throws. To make a write visible to the next query instead, set `completionTimeoutMs` on a `defineChronicleCommand` definition (which uses only its own value), or on `withChronicle` for events a command returns from `handle()` or applies through a command aggregate, which Arc appends as one batch after the command succeeds. An SDK `eventLog.append(...)` called inside `handle()` bypasses that batch and does not wait. After a successful append the command waits until the event log's observers have caught up to the appended tail. The wait does not name the appended event types, so an observer included in it that does not handle those types can hold it to the timeout; the command then reports an exception although its events are stored. Enable it only where you have confirmed no such observer delays the wait; otherwise let the client tolerate the lag.
|
|
229
|
+
|
|
230
|
+
When the application also uses `withMongoDB`, a projected read model can be read through `MongoCollection.queryPage` and `observe` only if Chronicle writes it where that integration reads. Arc aligns the collection name automatically only when `withChronicle` creates the Chronicle client from a `connectionString`, you pass no `readModelNamingPolicy`, and the model class is listed in `withMongoDB`'s `readModels`. The database must match as well: set `withMongoDB`'s `database` to the event store name, and append each tenant's events to the Chronicle namespace named by its tenant id, as `withChronicle` does (a `defineChronicleCommand` `namespaceForContext` must return the same). With your own Chronicle `client` or your own naming policy, align the collection names yourself (`resolveMongoCollectionName` from `@cratis/arc.mongodb` gives the name Arc reads).
|
|
229
231
|
|
|
230
232
|
## Protected MongoDB results
|
|
231
233
|
|
|
@@ -253,7 +255,8 @@ class TenantGate implements AuthorizationQueryFilter {
|
|
|
253
255
|
@queryPipelineFilter()
|
|
254
256
|
class RequireTerm implements QueryPipelineFilter {
|
|
255
257
|
onPerform(context: QueryContext): QueryResult | void {
|
|
256
|
-
|
|
258
|
+
const name = context.operationName;
|
|
259
|
+
if ((name === 'search' || name?.endsWith('.search')) && !(typeof context.query === 'object' && context.query && 'term' in context.query && context.query.term)) {
|
|
257
260
|
return queryFilterResult(context, { validationResults: [validation('Term is required', ['term'])] });
|
|
258
261
|
}
|
|
259
262
|
}
|
|
@@ -262,7 +265,7 @@ class RequireTerm implements QueryPipelineFilter {
|
|
|
262
265
|
builder.add(TenantGate, RequireTerm);
|
|
263
266
|
```
|
|
264
267
|
|
|
265
|
-
|
|
268
|
+
Arc first checks the query's declared authorization and parses its arguments; authorization filters run next (they see the raw input when parsing failed), then pipeline filters, all before validators and the query method are constructed. Over HTTP (a snapshot or a direct SSE request) a denial answers 403 with no data and a thrown filter answers 500; a subscription through the query hub receives an unauthorized or error frame instead. `operationName` is the namespace-qualified declaration name, or the bare name when the declaration has no namespace, so match both forms (or one exact name); `RequireTerm` may skip a context with no name, but a filter that gates access by name must deny when it is absent. Tokens can be registered instead with `builder.addAuthorizationQueryFilter(token)` and `builder.addQueryPipelineFilter(token)`; a token in both groups fails at `build()`. A thrown filter fails closed. There is no availability filter in this SDK.
|
|
266
269
|
|
|
267
270
|
## Renderers
|
|
268
271
|
|
|
@@ -30,6 +30,7 @@ Names are included by default and restored when skipping would cause conventiona
|
|
|
30
30
|
- **Transport:** `[QueryHttpMethod(QueryHttpMethod.Query)]` selects HTTP QUERY for a model-bound query; `Get` requests GET, `Auto` negotiates. A method overrides its read model. This selects the generated client default, not which verbs the host accepts; callers can use `setHttpMethod`.
|
|
31
31
|
- **Group:** for `[EndpointGroup("staff")]` endpoints set `CratisProxiesEndpointGroup=staff` and use the host port assigned to that group. By default only the default group is generated. Method overrides type, type overrides assembly. Give each generated group its own output tree.
|
|
32
32
|
- **Location:** in TypeScript read `ReserveRoom.sliceLocation`, or use `SliceLocation.ofType(ReserveRoom)` / `SliceLocation.of(command)` from `@cratis/arc/reflection`. The owning namespace after root matching or trimming supplies module / intervening feature segments / slice; short paths fill deepest first. An output folder alias does not become a module.
|
|
33
|
+
- **Backend location:** `CommandContext.SliceLocation` and `QueryContext.SliceLocation` (`SliceLocation` from `Cratis.Arc.Slices`, with `Module`, `Feature` and `Slice`) follow the same rules, with one exception: when a command's `Handle` method or a controller action is inherited, the proxy takes its location from the class that declares the method, while the runtime uses the concrete command or controller type. Declare such methods on the concrete type when both must agree. A multi-segment feature keeps its dots and `ToString()` joins the non-empty parts with `/`. While assembly-info generation is on (the default), the build writes a project's `NamespaceRoot` items and `CratisProxiesSegmentsToSkip` into assembly attributes; the skip count is written only when it is a non-negative whole number. Arc resolves the location from the command or read model type for model-bound endpoints and from the controller type for controller actions. It reads the attributes from the assembly that declares that type and falls back to the entry assembly only when that assembly declares neither. In a class library holding slices, set neither so the host's settings apply, or set exactly the host's roots and skip count. A `CommandContext` you construct resolves its location from the command type; a `QueryContext` you construct carries `SliceLocation.NotSet` until you set `SliceLocation = SliceLocation.For(readModelType)`.
|
|
33
34
|
|
|
34
35
|
## Choose outputs only when needed
|
|
35
36
|
|
|
@@ -41,7 +42,7 @@ These examples are MSBuild property assignments (e.g. `<CratisProxiesFramework>n
|
|
|
41
42
|
- `CratisProxiesUseSourceFileAsOutputFile=true`: group by C# source filename instead of per type when method debug info in an embedded or adjacent portable PDB identifies the document. Unresolved types (often enums) keep separate files.
|
|
42
43
|
- `CratisProxiesUseProxyFileSuffix=true`: write `ReserveRoom.proxy.ts`; update handwritten direct imports. Generated imports and barrels follow the suffix.
|
|
43
44
|
- `CratisProxiesSkipIndexGeneration=true`: skip writing folder `index.ts` exports. Keep handwritten barrels outside the output tree: skipping writes does not prevent cleanup.
|
|
44
|
-
- `CratisProxiesFileHeader=Venue contracts\n{fileName}`: emit comment lines with the generated filename substituted. Unset
|
|
45
|
+
- `CratisProxiesFileHeader=Venue contracts\n{fileName}`: emit comment lines with the generated filename substituted. Unset or empty uses `file_header_template` from `.editorconfig`, read only from `[*]`, `[*.cs]` and `[*.{…}]` lists with an exact `cs` entry such as `[*.{ts,cs}]` (`[*.{ts, cs}]`, path-specific and TypeScript-only sections are ignored); otherwise no custom header. `none` (any case) suppresses the fallback, not tracking metadata. An existing `index.ts` updated in place keeps its comments and gets no new header; only newly created ones get it. Full output deletion removes existing indexes, and orphan-directory cleanup can too. After changing the header, edit the header comment in surviving `index.ts` files by hand; deleting them to get the new header loses any handwritten lines they hold.
|
|
45
46
|
- `CratisProxiesLibraryMode=true`: also collect public concrete types, interfaces and enums from project assemblies even without endpoint references. Open generic definitions are not concrete model roots.
|
|
46
47
|
- `CratisProxiesEmitInterfaces=true`: render plain model shapes rather than decorated classes. Use for data-only contracts, not where query/identity deserialization needs constructors. Command/query clients themselves remain classes.
|
|
47
48
|
- `CratisProxiesFramework=none`: omit React helpers but retain executable Arc client classes; default is React.
|
|
@@ -62,18 +63,18 @@ Add only the needed MSBuild items. `Include` identifies the item; the named meta
|
|
|
62
63
|
</ItemGroup>
|
|
63
64
|
```
|
|
64
65
|
|
|
65
|
-
The longest matching namespace root redirects its subtree; `Folder=""` strips that prefix without replacing it.
|
|
66
|
+
The longest matching namespace root redirects its subtree; `Folder=""` strips that prefix without replacing it. A root's `Namespace` decides both the output folder and the slice location of commands and queries; its `Folder` changes only the output path. Roots never change URLs. A `TypeToTsType` mapping is checked ahead of the built-in mappings wherever a type goes through that lookup; it cannot target one property. Enums and dictionaries are resolved before the lookup, a concept is looked up by its underlying value type rather than its own name, and dictionary keys use only the built-in mappings. An item without `TypeName` or `TsType` is skipped with an "ignoring unusable --type-to-ts entry" warning in the build output. Map only to a compatible wire shape; omit `Package` for inline TypeScript types, supply it for imported names. A `ConceptAs` class hydrates itself. Any other imported class that wraps a scalar needs a `JsonConverter<T>` registered with `JsonSerializer.registerConverter` at client startup (see `cratis-fundamentals-concept`), unless one is already registered: Fundamentals ships converters for its own `Guid`, `DateOnly`, `TimeOnly` and `TimeSpan`. Without a converter, deserialization calls the class's no-argument constructor and ignores the wire value, so the result does not hold the sent value. Assembly mappings reuse exports from a client package rather than emitting copies. Exclusions remove unwanted types/subtrees; compile callers to catch missing dependencies. No special setting is needed for indirect scalar concepts: a record derived via an intermediate `ConceptAs<string>` record maps to the underlying string.
|
|
66
67
|
|
|
67
68
|
## Compare output or inspect validation without publishing
|
|
68
69
|
|
|
69
|
-
Use the packaged executable directly with the same compiled input and generation arguments as the build. In these shell examples `generator` is the absolute path to `Cratis.Arc.ProxyGenerator.Build.dll` from the build task directory; `assembly` and `
|
|
70
|
+
Use the packaged executable directly with the same compiled input and generation arguments as the build. In these shell examples `generator` is the absolute path to `Cratis.Arc.ProxyGenerator.Build.dll` from the build task directory; `assembly`, `out` and `scratch` are absolute paths, `scratch` being a disposable directory. This is not a globally installed CLI.
|
|
70
71
|
|
|
71
72
|
```sh
|
|
72
73
|
dotnet "$generator" "$assembly" "$out" --skip-output-deletion --check
|
|
73
|
-
dotnet "$generator" "$assembly" "$
|
|
74
|
+
dotnet "$generator" "$assembly" "$scratch" --validation-report=json --validation-report-file="$PWD/validation.json"
|
|
74
75
|
```
|
|
75
76
|
|
|
76
|
-
For a drift gate build the input with `-p:CratisProxiesSkip=true` first so the build does not repair the evidence.
|
|
77
|
+
For a drift gate build the input with `-p:CratisProxiesSkip=true` first so the build does not repair the evidence. That build runs no generator, so take the exact arguments from the generator command in a normal-verbosity log (`dotnet build -v:n`) of an earlier generation-enabled build, or of a separate build whose `CratisProxiesOutputPath` is a disposable directory. The build runs the generator from the build task directory, so make any relative paths in the logged command absolute (or replay from that directory). Pass the options the build passes, or the check compares against output the build never writes. `CratisProxiesSegmentsToSkip` is the optional third argument, directly after the output path and before any switch: `dotnet "$generator" "$assembly" "$out" 1 --check`. Everything else is a switch: `--project-directory=<project folder>` for header resolution, plus one for each setting you use, such as `--endpoint-group=<group>` (it changes which endpoints are discovered), `--file-header-base64=<Base64 of CratisProxiesFileHeader>`, `--use-proxy-file-suffix`, `--api-prefix=<prefix>`, `--framework=none` and repeated `--namespace-root=<Namespace>=<Folder>`. The usage text the generator prints without arguments is only a summary and omits some switches. `--check` writes and deletes nothing, including the availability manifest, but it is not a sandbox: it loads the assembly and runs validator constructors, so use only trusted inputs. It prints one `missing: <path>`, `changed: <path>` or `obsolete: <path>` line per finding (relative to the output, `/` separators) and then a summary line; a clean run prints `Proxies are up to date.`. Exit `0` is clean and `2` is drift. Exit `1` is a failure: with fewer than two positional arguments the generator prints its usage text on stdout; other usage, loading and comparison failures it handles print `error: <message>` on stderr. Treat only `2` as stale proxies and any other non-zero exit, whatever its output, as a failed check. Separately use `--validation-report=text` for human inspection or `json` for tooling; a report run still writes proxies to its output tree (and deletes that tree first unless `--skip-output-deletion` is passed), so point it at `scratch`, never at `out`. It also writes the availability manifest, so omit `--availability-manifest` or point it into `scratch`. A `--validation-report-file` inside the proxy output tree is rejected with exit 1, so write it elsewhere. Combining `--check` with a report option is a usage error (exit 1); run them as two invocations. Both ignore `--state-file`. For direct **writing** calls pass `--skip-output-deletion` to avoid wiping the destination and optionally `--state-file=/absolute/path/to/state.json` outside it for incremental generation.
|
|
77
78
|
|
|
78
79
|
Projected literal rules (e.g. required, lengths, comparisons, regex) provide client feedback. Conditional rules, arbitrary predicates and injected-data checks remain server concerns. A clean projection report is not proof the command will execute. After changing a backend contract regenerate rather than patching the client.
|
|
79
80
|
|
|
@@ -89,3 +90,4 @@ Projected literal rules (e.g. required, lengths, comparisons, regex) provide cli
|
|
|
89
90
|
|
|
90
91
|
- Building only the frontend after changing a backend contract: rebuild the configured endpoint project first.
|
|
91
92
|
- Editing generated payloads or routes: correct the contract or generator settings and regenerate.
|
|
93
|
+
- Using two closed instantiations of one generic model, such as `Page<Order>` and `Page<Invoice>`: both generate as `Page` in the generic's folder. Generation fails with "Duplicate type names detected"; with `CratisProxiesUseSourceFileAsOutputFile=true` that check is skipped, but both declarations are combined into one file under the same name `Page`, so the TypeScript does not compile. Declare a non-generic type with its own properties for each shape; deriving from the closed generic still generates the generic.
|
|
@@ -117,7 +117,7 @@ var provider = principal.FindFirst(MicrosoftIdentityPlatformClaims.IdentityProvi
|
|
|
117
117
|
|
|
118
118
|
## Identity details
|
|
119
119
|
|
|
120
|
-
Implement `IProvideIdentityDetails<TDetails>` when the frontend needs more than the principal carries. Arc discovers it;
|
|
120
|
+
Implement `IProvideIdentityDetails<TDetails>` when the frontend needs more than the principal carries. Arc discovers it; Arc's own default provider does not count.
|
|
121
121
|
|
|
122
122
|
```csharp
|
|
123
123
|
using Cratis.Arc.Identity;
|
|
@@ -139,7 +139,8 @@ public class StaffDetailsProvider(IStaffDirectory directory) : IProvideIdentityD
|
|
|
139
139
|
- `Claims` is an `IEnumerable<KeyValuePair<string, string>>`: the key is the claim type and the value the claim value. Read `.Key` and `.Value`; these are not `System.Security.Claims.Claim` objects, so there is no `.Type`. `KeyValuePair` is a struct: `FirstOrDefault(...)` never returns null, so write `.Value`, not `?.Value`, and treat a null `Value` as "claim absent".
|
|
140
140
|
- The type argument declares the shape of the details. When discovery exposes `/.cratis/identity-details/schema`, that endpoint describes the shape. Import the generated TypeScript type instead of declaring a frontend copy. The non-generic `IProvideIdentityDetails` has the same `Provide` method but gives the frontend no generated type.
|
|
141
141
|
- `IdentityDetails(IsUserAuthorized, Details)`: `false` makes `/.cratis/me` answer 403. That gates application entry in the frontend only; it adds no claims and protects no command or query.
|
|
142
|
-
- `/.cratis/me`
|
|
142
|
+
- Arc picks the provider whenever a DI scope first resolves it, not when the host builds. Arc's endpoint mapping does not resolve it. When discovery finds more than one implementation (a referenced project or package can contribute one), the host still starts, but every resolution throws `MultipleIdentityDetailsProvidersFound`, including your own startup code that resolves it from a scope. In requests that means a signed-in `/.cratis/me`, `IIdentityProvider.Get()` for a signed-in caller, and a `/.cratis/identity-details/schema` request that passes discovery access (anonymous callers included only where anonymous discovery is allowed, by default in Development). Anonymous `/.cratis/me` still answers 401 and `Get()` outside a request returns anonymous, so the conflict can go unnoticed until someone signs in or requests the schema. Pin one with `options.IdentityDetailsProvider = typeof(StaffDetailsProvider)` in `AddCratisArc`, or call `builder.Services.AddIdentityProvider<StaffDetailsProvider>()` after `AddCratisArc`; use the latter in a trimmed or NativeAOT host.
|
|
143
|
+
- `/.cratis/me` returns 401 without an authenticated principal. Arc's handlers for `/.cratis/me` (including the 401 and 403 it returns), `/.cratis/users` and `/.cratis/tenants` set `Cache-Control: no-store, private` and add `Cookie` to `Vary`; an existing `Vary: *` is kept. When a response is produced before the handler runs, such as a roster request that authorization refuses, the handler does not add these headers. `/.cratis/me` is specific to the caller; the rosters may be the same for every caller but list development users and tenants. A shared cache such as a CDN or gateway must bypass these routes or honour those headers. One that overrides them risks serving one user's identity to another, or a stale 401 to someone who has just signed in.
|
|
143
144
|
- Without a custom provider, authenticated callers pass with empty details.
|
|
144
145
|
|
|
145
146
|
## Development users and tenants
|
|
@@ -105,6 +105,13 @@ Call these on the `IArcBuilder` passed to `configureBuilder` (`configureArcBuild
|
|
|
105
105
|
|
|
106
106
|
## Compose request services
|
|
107
107
|
|
|
108
|
+
`AddCratisArc` (and `AddCratis`) and `ArcApplication.CreateBuilder` turn on `ValidateScopes` only when the environment name matches `Development` (case-insensitively), and keep `ValidateOnBuild` off. Under any other name (`Staging`, `Production`, `Local`), a singleton that takes a scoped service (tenant storage, the event log) in its constructor is not rejected and keeps the first instance forever. With `ValidateScopes = true`, Microsoft DI rejects that singleton when it is resolved. It does not detect a reference you capture by hand from a child scope. To turn the check on in every environment, set `ValidateScopes = true` and keep `ValidateOnBuild = false`; turning `ValidateOnBuild` on fails `Build()`. Where you set it depends on the host:
|
|
109
|
+
|
|
110
|
+
- `WebApplicationBuilder`: call `builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = false; })` after `AddCratisArc` or `AddCratis`. The last call wins, so a call before them is discarded.
|
|
111
|
+
- `IHostBuilder` with `AddCratisArc`: call `UseDefaultServiceProvider` with the same options on the host builder itself, after `AddCratisArc`.
|
|
112
|
+
- `ArcApplication.CreateBuilder`: call `ConfigureContainer` with a `DefaultServiceProviderFactory` carrying those options. It replaces Arc's defaults whether it comes before or after `AddCratisArc`.
|
|
113
|
+
- `AddCratisArcCore()` on the generic host: Arc does not change the provider options, so the host's own settings apply.
|
|
114
|
+
|
|
108
115
|
Register dependencies on the host (`builder.Services.AddScoped<IDepotDirectory, DepotDirectory>()`), not in a static handler. Use an Arc policy for shared authorization across host types:
|
|
109
116
|
|
|
110
117
|
```csharp
|
|
@@ -8,6 +8,10 @@ Normal callers need only the pipeline. For shared behavior, implement the approp
|
|
|
8
8
|
|
|
9
9
|
Filters implement `Task<CommandResult> OnExecution(CommandContext context)`. For an `IAuthorizationCommandFilter` return `CommandResult.Unauthorized(context.CorrelationId)` on denial, otherwise `CommandResult.Success(context.CorrelationId)`. An `IAvailabilityCommandFilter` runs before other authorization filters: for temporary unavailability return `CommandResult.Retryable(context.CorrelationId, "Station offline")`. Ordinary `ICommandFilter` implementations run after authorization; for a domain rule return a result with `CorrelationId = context.CorrelationId` and `ValidationResults = [ValidationResult.Error("Station closed")]`, not an authorization denial.
|
|
10
10
|
|
|
11
|
+
Filters run after context values are built and before the command's own `Provide()` and `Handle()`. Model-bound execute and validate-only requests run them only if the request gets that far: a missing handler, a principal that cannot be attached, or (on execute) a failing execution scope `Begin` or `BeginAsync` ends the request before any filter runs. Controller actions go through ASP.NET Core MVC filters instead of this chain. So a filter only checks: do not charge quota, count uses or record a successful execution in it. Logging the check itself is fine. An execution scope's `Complete` (below) sees the result so far, and a scope completed after it can still fail the command, so record the outcome no earlier than when `Execute` returns. A successful result is the final verdict, not proof that `Handle()` ran: a command that requires approval can return the approval flow's success without reaching the handler. Nor does it prove durable Chronicle work. A nested pipeline command shares the outer pipeline command's transaction, so a later outer failure discards its pending events (events appended immediately or committed explicitly stay); see the nested Chronicle command note in [the C# reference](csharp.md). A pipeline command executed from a controller action owns its own transaction and commits before `Execute` returns; a later failure of the action does not undo it.
|
|
12
|
+
|
|
13
|
+
Within each group Arc orders filters by the filter type's full name (ordinal comparison), not by registration or a priority setting. Arc merges each filter's result, including a thrown exception, into a running result and stops the chain once that result blocks: an authorization denial, an exception message, or validation findings that block under the effective severity policy. A thrown `IValidationFailure` becomes a finding rather than an exception message, unless it is or wraps an authorization denial, which becomes a denial instead. A nonblocking finding (for example a warning) lets later filters run. A severity policy can also make `Unknown` findings block. So a refusal may not include every filter's findings. Arc's built-in validation runs as two ordinary filters in `Cratis.Arc.Commands.Filters`: `DataAnnotationValidationFilter` and `FluentValidationFilter`. A custom ordinary filter runs before each of them whose full name sorts after its own, which need not be both. Validators for `[GeneratedValue]` handler arguments run only when an execution passes all filters and reaches argument resolution; a validate-only request never runs them.
|
|
14
|
+
|
|
11
15
|
## Execution scopes and returned values
|
|
12
16
|
|
|
13
17
|
Arc discovers execution scopes (`Cratis.Arc.Commands`) and resolves them from the command's service scope. Per invocation it calls `Begin` on every scope, then `BeginAsync` in the same order, runs filters, validation and the handler, then `Complete` in reverse order (also when validation fails or execution throws), and finally `End` in reverse order. A validate-only request runs none of these callbacks.
|
|
@@ -23,7 +23,7 @@ Read `references/<language>.md` for the project's SDK (`.csproj` → csharp, Nod
|
|
|
23
23
|
- **Header name:** change it only to match an existing ingress or client contract; handle ambiguous header values before accepting a tenant.
|
|
24
24
|
- **Query parameter:** select by a named query parameter (normally `tenantId`) when the client contract uses a URL selector; authorize it like a header.
|
|
25
25
|
- **Claim type:** select from a verified principal claim (normally `tenant_id`) when the identity provider assigns the active tenant.
|
|
26
|
-
- **Subdomain and base domain:** select the single label immediately before the configured base domain when tenants have dedicated hosts. Protect the fallback header too: a nonmatching host can select through it.
|
|
26
|
+
- **Subdomain and base domain:** select the single label immediately before the configured base domain when tenants have dedicated hosts. Protect the fallback header too: a nonmatching host can select through it. This Arc resolver is separate from Cratis AuthProxy's own tenant resolution: AuthProxy refuses to start when its own tenant resolutions include the `SubHost` strategy and its session cookie domain is set. Read the AuthProxy reference in `cratis-arc-authorize-request` before sharing a sign-in across hosts.
|
|
27
27
|
- **Fixed ID:** select one configured tenant for a single-tenant deployment, independently of the caller; this is not membership evidence.
|
|
28
28
|
- **Development selector:** use a stable local tenant for development without requiring a caller selection.
|
|
29
29
|
- **Custom resolver:** supply trusted selection logic for an application-specific source; validate its result before use.
|