@cratis/pi 8.5.0 → 8.6.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/glossary.instructions.md +5 -3
- package/package/corpus/harnesses/copilot/instructions/react.instructions.md +3 -1
- package/package/corpus/harnesses/copilot/instructions/reactors.instructions.md +3 -1
- package/package/corpus/harnesses/copilot/instructions/specs.csharp.instructions.md +6 -3
- package/package/corpus/harnesses/copilot/instructions/vertical-slices.instructions.md +5 -2
- package/package/corpus/rules/glossary.md +5 -3
- package/package/corpus/rules/react.md +3 -1
- package/package/corpus/rules/reactors.md +3 -1
- package/package/corpus/rules/specs.csharp.md +6 -3
- package/package/corpus/rules/vertical-slices.md +5 -2
- package/package/corpus/skills/cratis-application-growth/SKILL.md +1 -2
- package/package/corpus/skills/cratis-application-growth/references/csharp.md +0 -2
- package/package/corpus/skills/cratis-application-growth/references/move-and-untangle.md +1 -2
- package/package/corpus/skills/cratis-application-growth/references/rename-window.md +1 -3
- package/package/corpus/skills/cratis-application-growth/references/service-and-delivery.md +3 -2
- package/package/corpus/skills/cratis-application-growth/references/stages.md +2 -2
- package/package/corpus/skills/cratis-arc-authorize-request/SKILL.md +2 -2
- package/package/corpus/skills/cratis-arc-authorize-request/references/authproxy.md +19 -0
- package/package/corpus/skills/cratis-arc-authorize-request/references/csharp-query-security.md +15 -0
- package/package/corpus/skills/cratis-arc-authorize-request/references/csharp.md +12 -3
- package/package/corpus/skills/cratis-arc-declare-command/SKILL.md +2 -0
- package/package/corpus/skills/cratis-arc-declare-command/references/csharp-chronicle.md +46 -7
- package/package/corpus/skills/cratis-arc-declare-command/references/csharp-controller.md +3 -1
- package/package/corpus/skills/cratis-arc-declare-command/references/csharp-history.md +4 -1
- package/package/corpus/skills/cratis-arc-declare-command/references/csharp.md +31 -4
- package/package/corpus/skills/cratis-arc-declare-command/references/go.md +1 -1
- package/package/corpus/skills/cratis-arc-diagnose-live-query/references/csharp.md +24 -2
- package/package/corpus/skills/cratis-arc-expose-mcp-operation/references/csharp.md +49 -0
- package/package/corpus/skills/cratis-arc-expose-query/SKILL.md +3 -1
- package/package/corpus/skills/cratis-arc-expose-query/references/csharp.md +27 -4
- package/package/corpus/skills/cratis-arc-generate-proxies/SKILL.md +1 -0
- package/package/corpus/skills/cratis-arc-generate-proxies/references/csharp.md +49 -2
- package/package/corpus/skills/cratis-arc-generate-proxies/references/typescript.md +9 -0
- package/package/corpus/skills/cratis-arc-host-application/SKILL.md +1 -1
- package/package/corpus/skills/cratis-arc-host-application/references/csharp-configuration.md +54 -0
- package/package/corpus/skills/cratis-arc-host-application/references/csharp-deployment.md +98 -0
- package/package/corpus/skills/cratis-arc-host-application/references/csharp-http.md +9 -1
- package/package/corpus/skills/cratis-arc-host-application/references/csharp-identity.md +84 -2
- package/package/corpus/skills/cratis-arc-host-application/references/csharp.md +2 -0
- package/package/corpus/skills/cratis-arc-invoke-command/references/csharp.md +2 -1
- package/package/corpus/skills/cratis-arc-isolate-tenant/SKILL.md +18 -1
- package/package/corpus/skills/cratis-arc-page-query/references/csharp.md +2 -0
- package/package/corpus/skills/cratis-arc-react-bind-slice/SKILL.md +18 -16
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-commands.md +8 -3
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-host.md +84 -16
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-identity.md +22 -2
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-instant-feedback.md +81 -0
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-localization.md +80 -0
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-navigation.md +103 -0
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-queries.md +40 -1
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-structure.md +117 -0
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript.md +7 -3
- package/package/corpus/skills/cratis-arc-react-separate-view-model/SKILL.md +3 -3
- package/package/corpus/skills/cratis-arc-react-separate-view-model/references/typescript.md +27 -6
- package/package/corpus/skills/cratis-arc-validate-command/references/csharp-rules.md +23 -2
- package/package/corpus/skills/cratis-arc-validate-command/references/csharp.md +28 -2
- package/package/corpus/skills/cratis-authproxy-configure/SKILL.md +136 -0
- package/package/corpus/skills/cratis-authproxy-configure/references/admission.md +125 -0
- package/package/corpus/skills/cratis-authproxy-configure/references/aspire.md +154 -0
- package/package/corpus/skills/cratis-authproxy-configure/references/operations.md +122 -0
- package/package/corpus/skills/cratis-authproxy-configure/references/services-and-routing.md +114 -0
- package/package/corpus/skills/cratis-authproxy-configure/references/sessions-and-logout.md +126 -0
- package/package/corpus/skills/cratis-authproxy-configure/references/sign-in-providers.md +116 -0
- package/package/corpus/skills/cratis-authproxy-configure/references/tenant-resolution.md +135 -0
- package/package/corpus/skills/cratis-choreography-run-workflow/SKILL.md +117 -0
- package/package/corpus/skills/cratis-choreography-run-workflow/references/csharp-chronicle.md +164 -0
- package/package/corpus/skills/cratis-choreography-run-workflow/references/csharp.md +354 -0
- package/package/corpus/skills/cratis-chronicle-cli-operations/SKILL.md +2 -2
- package/package/corpus/skills/cratis-chronicle-cli-operations/references/project-tooling.md +28 -0
- package/package/corpus/skills/cratis-chronicle-connect-application/references/csharp-services.md +13 -2
- package/package/corpus/skills/cratis-chronicle-connect-application/references/csharp.md +12 -0
- package/package/corpus/skills/cratis-chronicle-connect-application/references/kotlin.md +2 -0
- package/package/corpus/skills/cratis-chronicle-connect-application/references/typescript.md +10 -1
- package/package/corpus/skills/cratis-chronicle-constrain-append/SKILL.md +8 -1
- package/package/corpus/skills/cratis-chronicle-constrain-append/references/csharp.md +35 -3
- package/package/corpus/skills/cratis-chronicle-constrain-append/references/go.md +1 -1
- package/package/corpus/skills/cratis-chronicle-constrain-append/references/operations.md +70 -0
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/SKILL.md +2 -0
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/configuration.md +27 -0
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/container-and-kubernetes.md +293 -0
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/kernel-options.md +13 -6
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/network-and-tls.md +45 -0
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/storage.md +91 -1
- package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/upgrade-and-recovery.md +9 -0
- package/package/corpus/skills/cratis-chronicle-evolve-event/SKILL.md +12 -0
- package/package/corpus/skills/cratis-chronicle-inspect-observer/SKILL.md +11 -1
- package/package/corpus/skills/cratis-chronicle-inspect-observer/references/csharp.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 +14 -3
- package/package/corpus/skills/cratis-chronicle-project-view/references/csharp-model-bound.md +3 -0
- package/package/corpus/skills/cratis-chronicle-project-view/references/csharp-reading.md +3 -2
- package/package/corpus/skills/cratis-chronicle-project-view/references/csharp.md +23 -0
- package/package/corpus/skills/cratis-chronicle-project-view/references/elixir.md +1 -0
- package/package/corpus/skills/cratis-chronicle-project-view/references/go.md +2 -1
- package/package/corpus/skills/cratis-chronicle-project-view/references/java.md +2 -0
- package/package/corpus/skills/cratis-chronicle-project-view/references/kotlin.md +1 -0
- package/package/corpus/skills/cratis-chronicle-project-view/references/typescript.md +1 -1
- package/package/corpus/skills/cratis-chronicle-protect-decision/SKILL.md +2 -0
- package/package/corpus/skills/cratis-chronicle-protect-decision/references/csharp-scopes.md +40 -3
- package/package/corpus/skills/cratis-chronicle-protect-decision/references/csharp.md +20 -2
- package/package/corpus/skills/cratis-chronicle-protect-decision/references/elixir.md +7 -0
- package/package/corpus/skills/cratis-chronicle-protect-decision/references/go.md +9 -1
- package/package/corpus/skills/cratis-chronicle-protect-decision/references/java.md +8 -0
- package/package/corpus/skills/cratis-chronicle-protect-decision/references/kotlin.md +9 -0
- package/package/corpus/skills/cratis-chronicle-protect-decision/references/typescript.md +7 -0
- package/package/corpus/skills/cratis-chronicle-protect-personal-data/references/csharp.md +24 -1
- package/package/corpus/skills/cratis-chronicle-publish-contract/SKILL.md +1 -1
- package/package/corpus/skills/cratis-chronicle-publish-contract/references/csharp.md +41 -0
- package/package/corpus/skills/cratis-chronicle-publish-contract/references/webhook-signature-wire-format.md +82 -0
- package/package/corpus/skills/cratis-chronicle-react-to-fact/SKILL.md +17 -0
- package/package/corpus/skills/cratis-chronicle-react-to-fact/references/csharp-outputs.md +3 -1
- package/package/corpus/skills/cratis-chronicle-react-to-fact/references/csharp.md +35 -2
- package/package/corpus/skills/cratis-chronicle-react-to-fact/references/elixir.md +11 -0
- package/package/corpus/skills/cratis-chronicle-react-to-fact/references/java.md +1 -0
- package/package/corpus/skills/cratis-chronicle-react-to-fact/references/kotlin.md +1 -0
- package/package/corpus/skills/cratis-chronicle-record-event/SKILL.md +1 -1
- package/package/corpus/skills/cratis-chronicle-record-event/references/csharp-coordination.md +31 -2
- package/package/corpus/skills/cratis-chronicle-record-event/references/csharp-history.md +21 -4
- package/package/corpus/skills/cratis-chronicle-record-event/references/csharp.md +20 -2
- package/package/corpus/skills/cratis-chronicle-record-event/references/go.md +1 -1
- package/package/corpus/skills/cratis-chronicle-record-event/references/java.md +1 -1
- package/package/corpus/skills/cratis-chronicle-record-event/references/kotlin.md +3 -0
- package/package/corpus/skills/cratis-chronicle-reduce-state/SKILL.md +2 -1
- package/package/corpus/skills/cratis-chronicle-reduce-state/references/csharp.md +3 -1
- package/package/corpus/skills/cratis-chronicle-reduce-state/references/java.md +10 -1
- package/package/corpus/skills/cratis-chronicle-reduce-state/references/kotlin.md +10 -1
- package/package/corpus/skills/cratis-chronicle-reduce-state/references/typescript.md +27 -5
- package/package/corpus/skills/cratis-chronicle-select-client/SKILL.md +18 -0
- package/package/corpus/skills/cratis-chronicle-select-client/references/elixir.md +21 -1
- package/package/corpus/skills/cratis-chronicle-select-client/references/go.md +13 -0
- package/package/corpus/skills/cratis-chronicle-select-client/references/java.md +15 -0
- package/package/corpus/skills/cratis-chronicle-select-client/references/kotlin.md +15 -0
- package/package/corpus/skills/cratis-chronicle-select-client/references/typescript.md +16 -0
- package/package/corpus/skills/cratis-code-review/references/csharp-diagnostics.md +28 -2
- package/package/corpus/skills/cratis-code-review/references/csharp.md +1 -1
- package/package/corpus/skills/cratis-components-accessibility/SKILL.md +6 -8
- package/package/corpus/skills/cratis-components-accessibility/references/typescript.md +32 -14
- package/package/corpus/skills/cratis-components-build-canvas/SKILL.md +4 -3
- package/package/corpus/skills/cratis-components-build-canvas/references/typescript-props.md +1 -1
- package/package/corpus/skills/cratis-components-build-canvas/references/typescript.md +4 -2
- package/package/corpus/skills/cratis-components-choose-control/SKILL.md +13 -7
- package/package/corpus/skills/cratis-components-choose-control/references/from-primereact.md +116 -0
- package/package/corpus/skills/cratis-components-choose-control/references/menu.md +90 -0
- package/package/corpus/skills/cratis-components-choose-control/references/typescript-composition.md +48 -0
- package/package/corpus/skills/cratis-components-choose-control/references/typescript.md +2 -2
- package/package/corpus/skills/cratis-components-compose-toolbar/SKILL.md +2 -1
- package/package/corpus/skills/cratis-components-compose-toolbar/references/floating-toolbar.md +146 -0
- package/package/corpus/skills/cratis-components-diagnose-screen/SKILL.md +102 -0
- package/package/corpus/skills/cratis-components-display-list/SKILL.md +10 -10
- package/package/corpus/skills/cratis-components-display-list/references/typescript-custom-panel.md +74 -0
- package/package/corpus/skills/cratis-components-display-list/references/typescript-datatables.md +2 -7
- package/package/corpus/skills/cratis-components-display-list/references/typescript.md +3 -2
- package/package/corpus/skills/cratis-components-submit-form/references/typescript-commandform.md +72 -2
- package/package/corpus/skills/cratis-components-submit-form/references/typescript.md +5 -3
- package/package/corpus/skills/cratis-components-theme-application/SKILL.md +17 -15
- package/package/corpus/skills/cratis-components-theme-application/references/localization.md +166 -0
- package/package/corpus/skills/cratis-components-theme-application/references/typescript.md +18 -14
- package/package/corpus/skills/cratis-components-theme-application/references/upgrade-from-previous-major.md +141 -0
- package/package/corpus/skills/cratis-engineering-csharp-conventions/SKILL.md +2 -0
- package/package/corpus/skills/cratis-engineering-csharp-conventions/references/csharp-domain-philosophy.md +31 -3
- package/package/corpus/skills/cratis-engineering-csharp-conventions/references/csharp-fundamentals-helpers.md +119 -0
- package/package/corpus/skills/cratis-engineering-csharp-conventions/references/csharp.md +4 -0
- package/package/corpus/skills/cratis-fundamentals-concept/references/csharp-serialization.md +70 -0
- package/package/corpus/skills/cratis-fundamentals-concept/references/csharp.md +8 -0
- package/package/corpus/skills/cratis-fundamentals-concept/references/go.md +1 -0
- package/package/corpus/skills/cratis-fundamentals-concept/references/typescript-serialization.md +33 -0
- package/package/corpus/skills/cratis-fundamentals-name-value/references/csharp.md +2 -1
- package/package/corpus/skills/cratis-fundamentals-type-discovery/references/csharp-diagnostics.md +5 -0
- package/package/corpus/skills/cratis-fundamentals-type-discovery/references/go-dependency-injection.md +3 -0
- package/package/corpus/skills/cratis-modeling-design-event-model/SKILL.md +6 -4
- package/package/corpus/skills/cratis-modeling-design-event-model/references/command-inventory.md +7 -1
- package/package/corpus/skills/cratis-modeling-design-event-model/references/model-first.md +13 -1
- package/package/corpus/skills/cratis-modeling-design-event-model/references/review-one-slice.md +6 -0
- package/package/corpus/skills/cratis-multi-service-local-orchestration/SKILL.md +6 -6
- package/package/corpus/skills/cratis-multi-service-local-orchestration/references/csharp-aspire.md +116 -28
- package/package/corpus/skills/cratis-multi-service-local-orchestration/references/docker-compose.md +2 -2
- package/package/corpus/skills/cratis-observability/references/chronicle-kernel-export.md +46 -0
- package/package/corpus/skills/cratis-orleans-jobs/SKILL.md +4 -2
- package/package/corpus/skills/cratis-platform-build-application/SKILL.md +8 -0
- package/package/corpus/skills/cratis-platform-build-application/references/cratis-identity.md +71 -0
- package/package/corpus/skills/cratis-platform-build-application/references/studio-repository.md +96 -0
- package/package/corpus/skills/cratis-platform-deliver-slice/SKILL.md +14 -8
- package/package/corpus/skills/cratis-platform-deliver-slice/references/csharp.md +167 -3
- package/package/corpus/skills/cratis-platform-deliver-slice/references/eventual-consistency.md +150 -0
- package/package/corpus/skills/cratis-platform-diagnose-slice/SKILL.md +1 -1
- package/package/corpus/skills/cratis-platform-start-application/SKILL.md +21 -0
- package/package/corpus/skills/cratis-platform-start-application/references/csharp.md +77 -3
- package/package/corpus/skills/cratis-platform-upgrade-application/SKILL.md +118 -0
- package/package/corpus/skills/cratis-platform-upgrade-application/references/csharp.md +117 -0
- package/package/corpus/skills/cratis-platform-upgrade-application/references/java.md +53 -0
- package/package/corpus/skills/cratis-platform-upgrade-application/references/kotlin.md +53 -0
- package/package/corpus/skills/cratis-platform-upgrade-application/references/typescript.md +71 -0
- package/package/corpus/skills/cratis-screenplay-accept-model/references/csharp.md +29 -0
- package/package/corpus/skills/cratis-screenplay-accept-model/references/read-the-evidence.md +82 -1
- package/package/corpus/skills/cratis-screenplay-declare-slice/SKILL.md +1 -1
- package/package/corpus/skills/cratis-screenplay-declare-slice/references/structure-and-imports.md +10 -0
- package/package/corpus/skills/cratis-screenplay-onboard-workspace/SKILL.md +5 -4
- package/package/corpus/skills/cratis-screenplay-onboard-workspace/references/cli.md +19 -2
- package/package/corpus/skills/cratis-screenplay-onboard-workspace/references/smallest-model.md +87 -0
- package/package/corpus/skills/cratis-screenplay-onboard-workspace/references/typescript.md +13 -0
- package/package/corpus/skills/cratis-screenplay-onboard-workspace/references/workspace-mcp.md +5 -0
- package/package/corpus/skills/cratis-specifications-exercise-backend/SKILL.md +2 -0
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-colocated.md +101 -0
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-command-results.md +3 -1
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-decision-reads.md +1 -0
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-events.md +1 -0
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-integration.md +4 -2
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-reactors.md +3 -3
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp.md +34 -1
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/elixir.md +2 -0
- package/package/corpus/skills/cratis-specifications-isolate-behavior/SKILL.md +1 -1
- package/package/corpus/skills/cratis-specifications-isolate-behavior/references/csharp-running.md +10 -3
- package/package/corpus/skills/cratis-specifications-test-application-ui/references/typescript.md +22 -4
- package/package/corpus/skills/cratis-specifications-test-typescript-behavior/SKILL.md +2 -1
- package/package/corpus/skills/cratis-specifications-test-typescript-behavior/references/typescript.md +40 -0
- package/package/profile-catalog.json +15 -0
- package/package.json +1 -1
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Attach the predicate used by an explicit decision
|
|
2
2
|
|
|
3
|
+
## Contents
|
|
4
|
+
|
|
5
|
+
- Build the scope from the position the decision used
|
|
6
|
+
- Read the result
|
|
7
|
+
- Inspect a scope and a position
|
|
8
|
+
- Refusals before sending
|
|
9
|
+
- Derive a scope only for writes without an earlier decision
|
|
10
|
+
|
|
11
|
+
## Build the scope from the position the decision used
|
|
12
|
+
|
|
3
13
|
Prefer the decision token: it captures both the fold's position and its filters. When you own a different, equally consistent read, import `Cratis.Chronicle.EventSequences.Concurrency` and build its predicate. Here `observed` is the position used by that read, **not** a tail fetched after deciding.
|
|
4
14
|
|
|
5
15
|
```csharp
|
|
@@ -26,10 +36,37 @@ Import `Cratis.Chronicle.Events` for `GetEventType()`.
|
|
|
26
36
|
- For several operations on one source, import `Cratis.Chronicle.EventSequences.Operations` and use `await eventStore.EventLog.ForEventSourceId(source, s => s.WithConcurrencyScope(scope).Append(new SeatReserved())).Perform();`. The configuration overload, e.g. `WithConcurrencyScope(b => b.WithEventSourceId(source).ExpectingNoMatchingEvent())`, builds the scope inline.
|
|
27
37
|
- For a mixed batch use `await eventStore.EventLog.AppendMany(events, concurrencyScopes: new Dictionary<EventSourceId, ConcurrencyScope> { [source] = scope, [other] = otherScope });`. Match the label to the scope's explicit source ID. An independent guard (a label without appended events) must identify its own protected history explicitly. For multiple predicates under one label pass the ordered `IEnumerable<KeyValuePair<EventSourceId, ConcurrencyScope>>` overload with `correlationId` and `tags`. With no explicit scope for a label, the client resolves each distinct route (declared dimensions, stream type, stream ID and source type) through the strategy. A route can resolve to no checked guard, for example an empty matching history under default settings. Equal resolved predicates share the earliest expected position, even when they come from different routes; different predicates keep separate guards, and the client never widens them into a whole-source check. In a batch without idempotency keys, several guards under one label, derived or explicit, need a kernel that advertises scope conjunctions. Otherwise the client throws `IncompatibleConcurrencyScopesForEventSource` before sending, and nothing is appended. Upgrade the kernel, or deliberately pass one explicit scope that covers the whole decision and accept broader conflicts. A batch in which any event carries an idempotency key refuses several distinct guards under one label even on a capable kernel, and writes nothing. It also checks only labels that still have new events to write, so it drops independent guards and guards on labels whose events were already appended. Do not use idempotency keys when the decision depends on such a guard. Do not split the batch: separate appends no longer protect the decision atomically. Do not overwrite a guard in a dictionary. Inspect `AppendManyResult.ConcurrencyViolations` (single append: `AppendResult.ConcurrencyViolation`) separately from constraint violations and unknown outcomes.
|
|
28
38
|
|
|
39
|
+
## Read the result
|
|
40
|
+
|
|
41
|
+
Check `HasConcurrencyViolations` on every append. A single append exposes `ConcurrencyViolation`; a batch exposes `ConcurrencyViolations`.
|
|
42
|
+
|
|
43
|
+
- A `ConcurrencyViolation` carries `EventSourceId`, `ExpectedEventSequenceNumber` and `ActualEventSequenceNumber`. When the kernel reports them it also carries `ConflictingEventTypeId` and `ConflictingEventSequenceNumber` (the first matching event after the expected position; both stay empty when that event could not be looked up), `Scope` (the predicate and expected position that failed) and `ScopeIndex`. All four are optional diagnostics and can be absent; a single-scope append can omit `Scope` and `ScopeIndex`. `ScopeIndex` counts the scopes the client sent after merging duplicates and resolving derived ones, not the list you passed: identify the failed guard by `Scope`. A violation caused by revised or redacted history rather than by a new event has equal expected and actual positions and no conflicting event. Log the violation, then read again and make a new decision; never resend the stale events.
|
|
44
|
+
- `ConcurrencyCheckPerformed` on a single append is true only when its scope was actually compared against the event store. It is false for `ConcurrencyScope.None`, when no scope was supplied or resolved, for an unchecked first append into a scope, and for an incomplete scope that was skipped. A success with false proves nothing about contention. Assert true in contention tests and whenever correctness depends on the guard running.
|
|
45
|
+
- On a batch the flag is true only when every scope sent was checked. False can therefore mean that some scopes were checked and others skipped: make every scope checkable rather than reading false as "nothing ran". A batch carrying idempotency keys is different. It first drops the guards on read-only labels and on labels already appended. It then reports true when, on any append attempt it made, every remaining scope was checkable; one unchecked remaining scope keeps that attempt false. An attempt that failed its check and wrote nothing still counts. True there proves neither that events were written nor that every dependency was checked.
|
|
46
|
+
|
|
47
|
+
## Inspect a scope and a position
|
|
48
|
+
|
|
49
|
+
- `scope.ExpectsNoMatchingEvent` is true when the scope asserts absence, which is what `.ExpectingNoMatchingEvent()` builds.
|
|
50
|
+
- `scope.IsIncomplete` is true when the scope is neither `NotSet` nor `None` and carries neither a position nor an absence expectation. An incomplete explicit scope that narrows history is treated as expecting absence unless `SkipIncompleteExplicitScopes` is on; one with no narrowing at all is sent unchecked.
|
|
51
|
+
- `EventSequenceNumber.First` is position zero, a real position. A tail lookup over empty matching history returns `EventSequenceNumber.Unavailable` (`IsUnavailable`); `IsActualValue` is true only for a real position. Express absence with `.ExpectingNoMatchingEvent()`, never with `First` or `Unavailable`.
|
|
52
|
+
|
|
53
|
+
## Refusals before sending
|
|
54
|
+
|
|
55
|
+
The client throws these while building or validating the append. Nothing is sent and nothing is appended. Fix the scope; do not drop a guard to make the append pass.
|
|
56
|
+
|
|
57
|
+
| Exception | Cause | Fix |
|
|
58
|
+
| --- | --- | --- |
|
|
59
|
+
| `ConcurrencyScopeLabelMustBeSpecified` | An event target or a scope label is unspecified, empty or whitespace | Give every event and every scope a real source ID |
|
|
60
|
+
| `ConcurrencyScopeEventSourceIdDoesNotMatchLabel` | A scope narrows by a source ID other than the label it is passed under | Label the scope with the source ID it narrows by |
|
|
61
|
+
| `IndependentConcurrencyScopeMustBeExplicit` | A label without appended events has a scope that is `NotSet` or incomplete | Give that scope a position or `.ExpectingNoMatchingEvent()` |
|
|
62
|
+
| `DuplicateConcurrencyScopeForEventSourceId` | One label carries contradictory scopes: the same predicate with two different positions, or `None` or `NotSet` mixed with another scope | Keep one scope per predicate; do not mix unchecked and checked scopes under a label |
|
|
63
|
+
| `IncompatibleConcurrencyScopesForEventSource` | Several distinct guards under one label on a kernel that does not advertise scope conjunctions | Upgrade the kernel, or pass one explicit scope that covers the whole decision; do not split the batch |
|
|
64
|
+
| `ConcurrencyScopeStreamDoesNotMatchAppend` | A definition-linked scope (`ForEventSource<T>(stream: ...)`) names another stream of the same definition than the single append is routed to | Guard the append's own stream. To guard another stream of the same source as well, use the ordered `AppendMany` overload and pass that stream's scope under the append's source label, not under a separate label. Pass the write-side scope explicitly beside it: an explicit scope for a label replaces the derived one |
|
|
65
|
+
|
|
29
66
|
## Derive a scope only for writes without an earlier decision
|
|
30
67
|
|
|
31
68
|
`ConcurrencyOptions.DefaultStrategy` defaults to `typeof(OptimisticConcurrencyStrategy)`. The strategy's `GetScope(source, eventTypes: watched)` reads the tail with the same filters it puts on the predicate. Its `GetScope(dimensions, source, ...)` overload applies the definition's concurrency dimensions, so a guard need not be per source. `[EventStream("Stream", Concurrency = ConcurrencyDimensions.EventSourceId | ConcurrencyDimensions.EventStreamType | ConcurrencyDimensions.EventStreamId)]` replaces the `[EventSource(..., Concurrency = ...)]` dimensions for appends through that stream; include `EventSourceId` when the rule is per instance. A strategy evaluated at append time cannot protect an earlier read.
|
|
32
69
|
|
|
33
|
-
- Set `options.ConcurrencyOptions.CheckFirstAppendIntoAScope = true` to have the optimistic strategy expect absence on an empty filtered tail. By default it skips the first check. An explicit absence expectation does not depend on this option.
|
|
34
|
-
- For a custom strategy set `DefaultStrategy = typeof(MyStrategy)` implementing `IConcurrencyScopeStrategy
|
|
35
|
-
- Keep `SkipIncompleteExplicitScopes` false: a narrowed explicit scope missing a position otherwise becomes unchecked rather than expecting absence. Keep `AllowRouteScopeStreamMismatch` false: a definition-linked explicit scope must match a single append's stream.
|
|
70
|
+
- Set `options.ConcurrencyOptions.CheckFirstAppendIntoAScope = true` to have the optimistic strategy expect absence on an empty filtered tail. By default it skips the first check. Do not design on an unchecked first append: turn the option on, or pass `ConcurrencyScope.None` where an unchecked write is intended. An explicit absence expectation does not depend on this option.
|
|
71
|
+
- For a custom strategy set `DefaultStrategy = typeof(MyStrategy)` implementing `IConcurrencyScopeStrategy` (assigning any other type throws `TypeIsNotAConcurrencyStrategy` at configuration); do not substitute custom strategy guards for enforced read protection. Return `ConcurrencyScope.None` only when an unchecked write is intended.
|
|
72
|
+
- Keep `SkipIncompleteExplicitScopes` false: a narrowed explicit scope missing a position otherwise becomes unchecked rather than expecting absence. Keep `AllowRouteScopeStreamMismatch` false: a definition-linked explicit scope must match a single append's stream. Instead of weakening route validation, pass a dependency on another source as a labelled independent condition, and one on another stream of the same source under that source's label in the ordered batch overload.
|
|
@@ -59,6 +59,7 @@ public class ReserveSeatValidator : CommandValidator<ReserveSeat>
|
|
|
59
59
|
|
|
60
60
|
- Inject the decision model into the command path; an earlier display read does not guard a later append.
|
|
61
61
|
- Treat a concurrency refusal as a stale decision; read and decide again rather than resending the event.
|
|
62
|
+
- Treat a passing validate-only call (`{url}/validate`) as form feedback. Under `On` it runs the validators against fresh reads, except for advisory ones; under `Off` or `Measure`, and for advisory reads, a validator can see stored state that lags. Either way nothing is guarded or written, so it does not promise that executing the command commits.
|
|
62
63
|
|
|
63
64
|
## Check the capacity rule
|
|
64
65
|
|
|
@@ -116,7 +117,12 @@ The full pattern, other routes and failures are in the `cratis-arc-declare-comma
|
|
|
116
117
|
|
|
117
118
|
## Failures that mean the command is wired wrong
|
|
118
119
|
|
|
119
|
-
|
|
120
|
+
Tell the two kinds of refusal apart first:
|
|
121
|
+
|
|
122
|
+
- **A stale or incomplete read** arrives as `ReadChanged` (a guarded read was no longer current at commit: a competing write, or a revision or redaction of the sequence's history) or `ReadIncomplete` (the fold did not reach a consistent position, with or without a competing write; Chronicle attempts it up to three times). Both are a `400` validation result with reason `concurrencyViolation`. `ReadIncomplete` always carries its name as detail; `ReadChanged` carries it only under `On`. Nothing was written and the command is never re-run for you: keep the input, read fresh state and resubmit deliberately.
|
|
123
|
+
- **A wiring defect** is every failure in the table below. It is thrown as an exception and, with the default HTTP mapping, surfaces as a server error (`500`) that no retry fixes. An exception response mapping can change the status, not the cause. Change the code; never catch and retry it.
|
|
124
|
+
|
|
125
|
+
The failures below are code defects, not competing writes. Most are raised under `On`; a row says so where another mode applies.
|
|
120
126
|
|
|
121
127
|
| Failure | Cause | Fix |
|
|
122
128
|
| --- | --- | --- |
|
|
@@ -125,9 +131,21 @@ Under `On` these are code defects, not competing writes. Fix the command; never
|
|
|
125
131
|
| `ReadOfSourceWithStagedEvents` | A source was read after events for it were staged; the read cannot see them | Decide once in the outer command and pass the value down |
|
|
126
132
|
| `ReadAfterProtectedCommit` | A read ran after an aggregate `Commit()` | Read before committing; return the commit result last |
|
|
127
133
|
| `ReadAndAggregateOnSameSource` | A protected read model and an aggregate use the same event source ID label at runtime, even if their stream or source types differ. Under `On`, analyzer `ARCCHR0033` warns earlier, but only when an automatically injected aggregate and read-model parameter statically resolve to the same key; the runtime check is authoritative | Decide from the aggregate's state, or mark a read that does not decide `[Unprotected("why")]`. A protected read of a different event source ID may stay beside the aggregate |
|
|
128
|
-
| `DecisionReadConflictsWithConcurrencyScope` |
|
|
134
|
+
| `DecisionReadConflictsWithConcurrencyScope` | Without enforcement (`Off` or `Measure`), one source has both a decision read and an explicit concurrency scope. Under `On` a scope that covers the read is accepted instead (see "Which scope guards the append?") | Remove the explicit scope, or do not decision-read that source |
|
|
129
135
|
| `DeclaredRoutingNotCoveredByExplicitScope` | An explicit scope is narrower than the concurrency the event source declares | Widen the scope or remove the declared concurrency |
|
|
130
136
|
| `DecisionReadRequiresUnitOfWork` | A decision read ran with no ambient unit of work | Read inside the command or an owned unit |
|
|
137
|
+
| `ProtectedUnitOfWorkRequiresOwner` | Command code called `Commit()`, `Rollback()` or `Dispose()` on the unit of work. Arc owns the command's unit and is the only one allowed to complete it, so that a decision cannot be committed half-guarded | Return the events from `Handle` and let Arc commit; never complete the unit yourself |
|
|
138
|
+
| `ReadModelInjectedOutsideDecision` | Under `On`, a read model was resolved through dependency injection anywhere other than `Handle` or a validator constructor, for example in a command filter or a service. A declared per-stream model and a type marked `[Unprotected]` are not refused there | Take the model as a parameter of `Handle` or of the `CommandValidator<T>` constructor and move the rule there. If it is only context, mark the read-model type `[Unprotected("why")]` |
|
|
139
|
+
| `ReadModelStreamNotOnCommandRoute` | A per-stream model parameter whose declared source or stream is not the command's route, or the command has no explicit stream ID. Refused in every mode, not only `On` | Route the command to the model's source and stream with an explicit stream ID, or read another stream explicitly through `IDecisionReads` directly in `Handle`, with a reasoned `ARCCHR0040` suppression as described under the lookup keys above |
|
|
140
|
+
| `ConcurrentNestedCommandsUnderReadProtection` | A nested command started while another nested command of the same outer command was still running, and one of the commands involved has read protection `On` | Await nested commands one after another |
|
|
141
|
+
| `NestedEarlyCompletionUnderReadProtection` | A nested command committed the outer command's unit (an aggregate `Commit()`) | Commit in the outer command |
|
|
142
|
+
| `CommandCannotBeBothProtectedAndUnprotected` | `[ProtectedDecision]` and `[Unprotected]` on one command | Keep one |
|
|
143
|
+
| `ConflictingReadProtection` | `[ReadProtection]` with `On` or `Measure` and `[Unprotected]` on one command | Keep one |
|
|
144
|
+
| `ConflictingContributionsOnLabel`, `ConflictingExplicitScopes` | Two explicit or aggregate guards on one event source contradict each other: the same predicate with two expectations, or a no-check scope mixed with a checked one | Reconcile them into one expectation per predicate, or remove the no-check scope. Guards with distinct predicates may share a source; do not drop an independent guard |
|
|
145
|
+
| `ReservedConcurrencyScopeLabel` | A scope label starts with `$read-protection/` | Use another label |
|
|
146
|
+
| `ReadProtectionRequiresTheDefaultConcurrencyStrategy` | A custom concurrency strategy is configured and the commit appends an event to a source that a protected read also guards. A protected read of a source the commit does not write to does not trigger it | Use the default strategy for commits that write to a source they read under protection |
|
|
147
|
+
| `ReadDependencyTargetMismatch` | A guard belongs to another event store, namespace or event sequence than the unit that commits | Read and write in the same store, namespace and sequence |
|
|
148
|
+
| `SourceLessReadNotSupported` | A read with no event source | Read a source-keyed model |
|
|
131
149
|
|
|
132
150
|
## Related skills
|
|
133
151
|
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Read and stage the Elixir decision in the same process
|
|
2
2
|
|
|
3
|
+
## Contents
|
|
4
|
+
|
|
5
|
+
- Admission and stream reads
|
|
6
|
+
- Detached evidence and ownership
|
|
7
|
+
- Explicit append predicates
|
|
8
|
+
- Not supported in this SDK
|
|
9
|
+
|
|
3
10
|
Start the configured `Cratis.Chronicle.Client` against the target store, with the event modules registered and `read_models: [Bay]`. Names are illustrative. Let `Bay` project `BayAssigned` and remove the instance on `BayReleased`, both keyed by bay source ID. Use a binary ID and the same client, namespace and event log throughout.
|
|
4
11
|
|
|
5
12
|
```elixir
|
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
# Guard a decision in Go
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
## Contents
|
|
4
|
+
|
|
5
|
+
- Guard a decision made from source history
|
|
6
|
+
- Model reads on a preflight-admitted deployment only
|
|
7
|
+
- Arc command decisions
|
|
8
|
+
- Diagnose refusal versus conflict
|
|
9
|
+
- Not supported in this SDK
|
|
10
|
+
|
|
11
|
+
The Go client's model-based decision reader requires a successful preflight with an exact server **and** protocol match, and a model shape that passes admission. The match is an allowlist of exact versions, not a minimum: a newer kernel is refused as well. A read can fail in three distinct ways. Model shape admission runs first, locally and without contacting the server: an inadmissible model returns a `*readmodels.DecisionReadRefused` carrying the model and a reason. An admitted model then needs the connection: a failed preflight returns its own compatibility or transport error. When preflight succeeds but the server and protocol pair is not on the allowlist, the error wraps `chronicle.ErrUnsupported`. Match each with `errors.As` or `errors.Is`; do not treat them as one condition. The current kernel is outside that allowlist. Send the intent to a compatible writer that both decides and commits, or use an explicit history-based guard if it covers every fact. `WithSkipCompatibilityCheck` does not enable model reads. An Arc command reads through the same reader, so the same admission applies there. Names below are illustrative; SDK subpackages are under `github.com/cratis/chronicle.go` (root import `chronicle`).
|
|
4
12
|
|
|
5
13
|
## Guard a decision made from source history
|
|
6
14
|
|
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Guard the Java append with the history actually read
|
|
2
2
|
|
|
3
|
+
## Contents
|
|
4
|
+
|
|
5
|
+
- One bay, two events that determine occupancy
|
|
6
|
+
- Select only dimensions the decision actually used
|
|
7
|
+
- Share a guard or check several sources atomically
|
|
8
|
+
- Routing-derived guards are for writes without earlier decision evidence
|
|
9
|
+
- Not supported in this SDK
|
|
10
|
+
|
|
3
11
|
Use the Chronicle JVM client with a connected `EventStore` in the intended namespace. Register the `@EventType` classes before reading or appending. Use the blocking facade from `io.cratis.chronicle.java` in the command owner. It does not turn a read-model lookup into a protected read. `BlockingEventStore.getEventLog()` already returns a `BlockingEventSequence`; wrap only a suspending store's log yourself. The static bridges below take the suspending sequence, so pass `log.unwrap()` when you hold the blocking one.
|
|
4
12
|
|
|
5
13
|
## One bay, two events that determine occupancy
|
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Guard an append with the history used by a Kotlin decision
|
|
2
2
|
|
|
3
|
+
## Contents
|
|
4
|
+
|
|
5
|
+
- Default: read, decide, append with an explicit predicate
|
|
6
|
+
- Several events or dependencies
|
|
7
|
+
- Routing-derived checks
|
|
8
|
+
- Staging a guarded append in a unit of work
|
|
9
|
+
- Inspecting the result
|
|
10
|
+
- Not supported in this SDK
|
|
11
|
+
|
|
3
12
|
Use the connected store's `eventLog` (or the same `IEventSequence` for both operations) from a suspending command. Register the event types in that store. Names are illustrative.
|
|
4
13
|
|
|
5
14
|
## Default: read, decide, append with an explicit predicate
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Guard the history used by a Node command
|
|
2
2
|
|
|
3
|
+
## Contents
|
|
4
|
+
|
|
5
|
+
- Read, decide and append
|
|
6
|
+
- Guard more than one dependency
|
|
7
|
+
- Choose a policy only for writes without explicit evidence
|
|
8
|
+
- Not supported in this SDK
|
|
9
|
+
|
|
3
10
|
## Read, decide and append
|
|
4
11
|
|
|
5
12
|
Use `@cratis/chronicle` on the server. Obtain the event log from the command's configured client, store and namespace. The example assumes registered `@eventType()` classes `BayClaimed` and `BayReleased`; these are the only events that change occupancy, and each is routed to the affected bay. Names are illustrative.
|
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Protect technician contact details in C#
|
|
2
2
|
|
|
3
|
+
## Contents
|
|
4
|
+
|
|
5
|
+
- Classify the event and its destination
|
|
6
|
+
- Supply policy when annotations are unavailable
|
|
7
|
+
- Query after authorization
|
|
8
|
+
- Erase and verify under the provisioning fence
|
|
9
|
+
- Not supported in this SDK
|
|
10
|
+
|
|
3
11
|
Use the `Cratis.Chronicle` client with an `IEventStore` bound to the intended store and namespace. Register events and projections through normal client discovery. The examples use opaque IDs; never put a contact number in a route, reason, schema annotation or log.
|
|
4
12
|
|
|
5
13
|
## Classify the event and its destination
|
|
@@ -29,6 +37,7 @@ Here an order owns the history, but the technician owns the contact data. `[Subj
|
|
|
29
37
|
|
|
30
38
|
- Mark a class (concept or value object) only if every use is personal. Otherwise mark just the personal property or constructor parameter. Mark destinations separately, including reducer result types. Inspect both registered schemas and test a synthetic value at rest and after release.
|
|
31
39
|
- Marking a nested member protects that member. Marking a collection property (e.g. `[PII] string[] ContactNumbers`) protects the whole collection, precluding element indexing; erasure empties it. To retain other members, mark the personal members of a concrete item type instead.
|
|
40
|
+
- Edge case, dictionaries and polymorphic values: protection follows the members the registered schema declares and classifies, so prefer a concrete value object with declared members for personal data. A dictionary is protected in one of two ways: classifying the dictionary property itself protects the whole dictionary as one value, with no separate classification of its entries, while an unclassified dictionary property protects individual entry values only if the registered schema classifies the value type (for example a `[PII]` concept as the value). A polymorphic value may lack the declared members needed to classify its personal fields, and a schema reference that cannot be resolved contributes no classification of its own: only a classification declared on the referring property still applies. Inspect the registered schema before relying on any of these.
|
|
32
41
|
- Details default to empty and document purpose, not key selection. Nonempty resolved `[ComplianceDetails]` takes precedence; otherwise the first nonempty PII details on the property, matching parameter, declaring type or property type win, in that order.
|
|
33
42
|
- `[PII(SpecialCategory = SpecialCategory.Health)]` classifies Article 9 data. Alternatives are `RacialOrEthnicOrigin`, `PoliticalOpinions`, `ReligiousOrPhilosophicalBeliefs`, `TradeUnionMembership`, `Genetic`, `Biometric`, `SexLifeOrSexualOrientation`; default `None`. `[PII(Criminal = true)]` classifies conviction/offense data; `[PII(OperationalSecret = true)]` classifies personal data that is also a secret. Both flags default to false. These flags are not emitted as schema metadata and add no protection layer.
|
|
34
43
|
- For a **non-personal** secret use `[Encrypted]` (`Cratis.Chronicle.ProtectedValues`, like `EncryptionScope`) on a property, parameter or class instead. Its default `EncryptionScope.Subject` uses a separate non-erasable-by-PII key; `[Encrypted(EncryptionScope.Namespace, details: "Authenticate the dispatch integration")]` shares a key within the store namespace; `EncryptionScope.Global` shares across the installation. Details default to empty. Never combine with PII on the same value.
|
|
@@ -78,10 +87,24 @@ var history = await eventStore.EventLog.GetFromSequenceNumberWithErasedPropertie
|
|
|
78
87
|
var erasedPaths = history.SelectMany(entry => entry.Context.ErasedProperties);
|
|
79
88
|
```
|
|
80
89
|
|
|
81
|
-
Check the expected field paths on the affected event and query the view afresh; confirm the control still releases. The read optionally takes `filterEventTypes` as well as `eventSourceId`; omit the source only when the wider read is intended. Erasure fences new provisioning, removes the key, evicts cached keys and removes associated uniqueness claims across registered non-system stores in the namespace for an application store. Discovery and permission must cover the targets.
|
|
90
|
+
Check the expected field paths on the affected event and query the view afresh; confirm the control still releases. The read optionally takes `filterEventTypes` as well as `eventSourceId`; omit the source only when the wider read is intended. Erasure fences new provisioning, removes the key, evicts cached keys and removes associated uniqueness claims across registered non-system stores in the namespace for an application store. Discovery and permission must cover the targets. `DeleteEncryptionKeyFor` throws when any erasure step fails. A call that returns means the configured key storage completed its erasure operations without a reported failure; it is not by itself proof of a confirmed erasure, because a storage backend without fencing guarantees (a standalone MongoDB server, for example) erases without the confirmation step. Where confirmation matters, run key storage on a backend that provides it (a MongoDB replica set) and verify the result as described here. The kernel collects the failures of an erasure that started but did not complete in every event store as `EncryptionKeyErasureIncomplete`; the call can also fail before any deletion, when permission or coverage of the target stores is not established, or with a single refusal outside that collection. Treat every failed call as an unconfirmed erasure, whatever its cause: resolve the cause and repeat the same call. Do not report document deletion or coverage of forwarded copies, other namespaces or recoverable backups.
|
|
91
|
+
|
|
92
|
+
After erasure the stored event remains in the log and is still returned by reads. Each protection boundary whose key was erased comes back as the JSON default of its schema type:
|
|
93
|
+
|
|
94
|
+
| Protection boundary | Released JSON |
|
|
95
|
+
| --- | --- |
|
|
96
|
+
| String | empty string |
|
|
97
|
+
| Non-nullable number or boolean | `0` or `false` |
|
|
98
|
+
| Nullable number or boolean | `null` |
|
|
99
|
+
| Collection protected as a whole | empty collection |
|
|
100
|
+
| Object protected as a whole | empty object |
|
|
101
|
+
|
|
102
|
+
The boundary is where the classification sits, not the C# type. A value object classified on its members keeps its outer shape, and each classified member follows its own row; only a container protected as one value is emptied. These are JSON defaults, not typed values, so a typed read of an erased event can throw, and not only for containers: a scalar whose C# type has no representation for the default fails too. A protected `Guid`, date or other formatted value is a JSON string and comes back as `""`, which the .NET deserializer rejects, and an emptied object or collection may not fit its C# type. The erased-properties read materializes typed `Content` the same way, so it can throw on the same event. Prefer `string` or string-backed concepts for protected members, and test a typed read of an erased event for every protected member type. An ordinary read cannot tell these from genuine values, so never treat a `0`, `false` or empty value on a protected member as a business fact. Where the difference matters, use the erased-properties read above.
|
|
82
103
|
|
|
83
104
|
`ErasedProperties` is also available directly on each returned `AppendedEvent`. Paths use JSON/schema names, dotted members and bracketed indices, such as `profile.name` or `contacts[0].email`; a protected whole container reports only its boundary (`contacts`). Dictionary keys are not escaped, so a path such as `contacts.work.email` can mean a literal `work.email` key rather than nested members; do not treat paths as unambiguous field addresses, and treat them as potentially sensitive because they can contain dictionary keys. `Content` still holds the released defaults with no markers. The paths describe the current `Content` only, never `OriginalContent`. On a server without this read the call throws an `RpcException` (`StatusCode.Unimplemented`) instead of returning an empty list.
|
|
84
105
|
|
|
106
|
+
While the subject is fenced, appending a protected personal value for it is refused; the kernel names this refusal `EncryptionKeyErased`. No replacement key is created and nothing is stored blank. Both failure names are kernel names used in the product documentation; the C# client has no exception types for them and kernel logs are not promised to carry them, so do not catch by type or match on message text. A fence refusal normally returns an unsuccessful result (`IsSuccess` false, the kernel's message in `Errors`), but an unsuccessful result or an exception does not by itself prove a refusal. `result.Errors.Contains(AppendError.AppendOutcomeUnknown)`, a timeout or a dropped connection means the append may have committed, and it may still be executing after the caller has given up. Reading the event source's events for the attempt's correlation ID can confirm a commit, but a read that finds nothing is not proof that nothing was or will be written, so retrying on a negative read alone can duplicate the event. Make the attempt repeatable instead: append with `EventLog.AppendOnce(eventSourceId, @event, idempotencyKey, ...)`, keep the `IdempotencyKey` chosen for the original attempt, and retry with that same key. A repeat of an append that did commit writes nothing and reports it through `result.Outcome` (`AppendOutcome.AlreadyAppended`; `result.WasAlreadyAppended`). `AppendOnce` throws `IdempotentAppendsNotSupported` before sending anything when the key cannot be honored. The refusal message contains the subject identifier, so keep it out of user-facing responses.
|
|
107
|
+
|
|
85
108
|
Only after independent approval for **future** personal data: `await eventStore.PII.AllowNewEncryptionKeyFor(technicianId.ToString());`. Never do this automatically on refusal to provision. A new key cannot release earlier ciphertext.
|
|
86
109
|
|
|
87
110
|
To redact event content instead, use `await eventStore.EventLog.Redact(sequenceNumber, reason);` or `await eventStore.EventLog.Redact(orderId, reason, typeof(TechnicianAssigned));`. Omitting the type filter on the latter targets the entire source. Redaction removes event content and retained causation property values, not the subject's key. The stored event keeps its position and becomes an `EventRedacted` marker (`Cratis.Chronicle.Events`). To clear derived state, add an `EventRedacted` handler to the reducer or reactor that already handles the original event type; a reducer returns `null` to remove the model. Then verify the removal. The marker, what it keeps and the observer rules are in the history reference of `cratis-chronicle-record-event`.
|
|
@@ -58,7 +58,7 @@ Use webhooks, external services and HTTP captures only when the other side is no
|
|
|
58
58
|
- The status code selects the recovery: 5xx, 408, 429 and connection failures are retried with backoff; 429 or 503 with `Retry-After` defers the partition without spending a retry; 410 parks the partition until an operator acts; any other 4xx pauses the whole webhook as a configuration problem. A receiver that is warming up answers 503 with `Retry-After`, never 400 or 404.
|
|
59
59
|
- One observer ID is served either by a webhook or by connected clients, never both. Registration is refused while a client serves that ID in any namespace; some SDKs report the refusal only as a warning.
|
|
60
60
|
- Registration replaces the whole definition. Header values and credentials are never returned on read, so never register a definition that was read back.
|
|
61
|
-
- Signing is off by default. With signing on, the receiver verifies each request against the event store's public signing keys, on the raw body, and accepts every key the store currently lists so that a key rotation does not reject deliveries. Signing does not replace authorization.
|
|
61
|
+
- Signing is off by default. With signing on, the receiver verifies each request against the event store's public signing keys, on the raw body, and accepts every key the store currently lists so that a key rotation does not reject deliveries. Signing does not replace authorization. A receiver that is not .NET verifies by hand: read [webhook signature wire format](references/webhook-signature-wire-format.md) for the headers, signed message, key format and rotation.
|
|
62
62
|
- A webhook is replayable unless registered otherwise; a replay sends stored events again under the same sequence numbers.
|
|
63
63
|
- Events are released from personal-data protection before delivery: the receiver gets plaintext, and erasing a subject later does not reach what the receiver stored.
|
|
64
64
|
|
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Publish a parcel clearance with C#
|
|
2
2
|
|
|
3
|
+
## Contents
|
|
4
|
+
|
|
5
|
+
- Declare and publish the contract
|
|
6
|
+
- Receive and verify
|
|
7
|
+
- Publish only changes to state
|
|
8
|
+
- Manage a filtered route explicitly
|
|
9
|
+
- Consumers that are not Chronicle stores
|
|
10
|
+
- Not supported in this SDK
|
|
11
|
+
|
|
3
12
|
Names are illustrative. Use `Cratis.Chronicle` in both services; in ASP.NET Core use the Chronicle ASP.NET Core integration (`builder.AddCratisChronicle(...)` before building, `app.UseCratisChronicle()` after). Configure the producer for `dispatch` and consumer for `tracking` on the same kernel, with a matching namespace. Use the scoped `IEventStore` of each host. Share the public record, not the producer's internal events. Examples use `Cratis.Chronicle`, `.Events`, `.EventSequences`, `.Reactors`, `.Projections`, `.Reducers`, `.Registrations`, `.Observation` and `.Sinks` under that namespace.
|
|
4
13
|
|
|
5
14
|
## Declare and publish the contract
|
|
@@ -16,6 +25,38 @@ public record ParcelInspected(string Lane, string InternalNote);
|
|
|
16
25
|
|
|
17
26
|
Verify visibility and origin in the Workbench Event Types view. `[EventStore]` makes the shared type public in both stores. For a contracts-only assembly, `[assembly: EventStore("dispatch")]` supplies the default origin; a type declaration overrides it. Keep private records out of that assembly. Without origin or `[Public]`, .NET registers the type private. Use `[Public]` alone when visibility, not origin-based routing, is wanted. For plain types configure `options.ExplicitArtifacts.RegisterEventType<ParcelCleared>(e => e.WithId("parcel-cleared").ForEventStore("dispatch"))` before creating the store; `e.Public()` or `e.Private()` sets visibility explicitly. Do not contradict attribute declarations. Foreign ownership alone is not eligibility for an event-target publisher in the receiving store.
|
|
18
27
|
|
|
28
|
+
Lay the contracts project out by producing slice, one event per file: `<Service>.Contracts/<Slice>/<Event>.cs`, here `Dispatch.Contracts/Clearance/ParcelCleared.cs` in namespace `Dispatch.Contracts.Clearance`. The project references `Cratis.Chronicle` and nothing of the service; the producer and every consumer reference it. Give contract events scalar fields (`string`, `Guid`, `DateTimeOffset`) rather than the producer's concept types, so the contract carries none of its domain model. Declare the store name once, as a constant the assembly attribute and the producer's `options.EventStore` both use. These are three separate files.
|
|
29
|
+
|
|
30
|
+
`Dispatch.Contracts/DispatchEventStore.cs`:
|
|
31
|
+
|
|
32
|
+
```csharp
|
|
33
|
+
[assembly: EventStore(Dispatch.Contracts.DispatchEventStore.Name)]
|
|
34
|
+
|
|
35
|
+
namespace Dispatch.Contracts;
|
|
36
|
+
|
|
37
|
+
public static class DispatchEventStore
|
|
38
|
+
{
|
|
39
|
+
public const string Name = "dispatch";
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`Dispatch.Contracts/Clearance/ParcelCleared.cs`:
|
|
44
|
+
|
|
45
|
+
```csharp
|
|
46
|
+
namespace Dispatch.Contracts.Clearance;
|
|
47
|
+
|
|
48
|
+
[EventType("parcel-cleared")]
|
|
49
|
+
public record ParcelCleared(string Lane);
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The Dispatch service's `Program.cs`:
|
|
53
|
+
|
|
54
|
+
```csharp
|
|
55
|
+
builder.AddCratisChronicle(options => options.EventStore = Dispatch.Contracts.DispatchEventStore.Name);
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
In this layout remove the type-level `[EventStore("dispatch")]` shown on `ParcelCleared` in the first example: it would override the assembly default and repeat the store name as a second literal.
|
|
59
|
+
|
|
19
60
|
Record the inspection on `producer.EventLog`. Publish once per clearance, not once per distinct lane. Persist a unique publication ID per occurrence before attempting the append; reuse it and identical inputs on retry.
|
|
20
61
|
|
|
21
62
|
```csharp
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# Webhook signature wire format
|
|
2
|
+
|
|
3
|
+
Use this when the receiver of a signed webhook is not a .NET process, so it must verify deliveries itself. A .NET receiver uses the client's `WebhookSignatureVerifier` instead (C# integrations, `references/csharp-integrations.md`), which covers the signed message and the steps under [Verify a delivery](#verify-a-delivery). A .NET receiver still loads and refreshes the keys, answers the request and handles repeats itself. The verifier keeps the keys it was created with, so create a new one from every refreshed key set.
|
|
4
|
+
|
|
5
|
+
## Contents
|
|
6
|
+
|
|
7
|
+
- [What a signed request carries](#what-a-signed-request-carries)
|
|
8
|
+
- [The signed message](#the-signed-message)
|
|
9
|
+
- [Get the public keys](#get-the-public-keys)
|
|
10
|
+
- [Verify a delivery](#verify-a-delivery)
|
|
11
|
+
- [Key rotation](#key-rotation)
|
|
12
|
+
- [Repeats and replays](#repeats-and-replays)
|
|
13
|
+
- [Anti-patterns](#anti-patterns)
|
|
14
|
+
|
|
15
|
+
## What a signed request carries
|
|
16
|
+
|
|
17
|
+
The kernel generates these headers only for a webhook registered with Ed25519 signing, and there it replaces any custom header of the same name. An unsigned webhook gets none from the kernel, but its custom headers may use these names, so their presence alone proves nothing.
|
|
18
|
+
|
|
19
|
+
| Header | Contents |
|
|
20
|
+
| --- | --- |
|
|
21
|
+
| `webhook-id` | Identifier of the delivery. It stays the same when the kernel retries the same delivery. Treat it as opaque. |
|
|
22
|
+
| `webhook-timestamp` | Time of signing in Unix seconds, as decimal digits. |
|
|
23
|
+
| `webhook-signature` | One or more signatures separated by a space, each written `v1a,<base64>`. |
|
|
24
|
+
| `Cratis-Key-Id` | Id of a signing key. A hint for noticing an unknown key; never base the accept or reject decision on it. |
|
|
25
|
+
|
|
26
|
+
The framing follows Standard Webhooks with its asymmetric `v1a` signature version.
|
|
27
|
+
|
|
28
|
+
## The signed message
|
|
29
|
+
|
|
30
|
+
- Message bytes: the UTF-8 bytes of `<webhook-id>.<webhook-timestamp>.` followed by the request body exactly as received. The header values are used as sent, joined by dots.
|
|
31
|
+
- Algorithm: Ed25519 (RFC 8032). Each signature is 64 bytes, Base64-encoded after the `v1a,` prefix.
|
|
32
|
+
- The body is JSON, but the signature covers its bytes. Read the raw body before any JSON parser touches it; a body that was parsed and serialized again fails verification as soon as one byte differs.
|
|
33
|
+
|
|
34
|
+
## Get the public keys
|
|
35
|
+
|
|
36
|
+
The keys belong to the **event store**, not to one webhook: every signed webhook of a store is verified with the same keys.
|
|
37
|
+
|
|
38
|
+
- Each public key is the text `whpk_` followed by the Base64 of the 32-byte Ed25519 public key. Remove the prefix and Base64-decode to get the key.
|
|
39
|
+
- Read them from the kernel with the `GetWebhookSigningKeys` operation of the `Webhooks` gRPC service, passing the event store name. Each entry has `KeyId`, `Algorithm`, `PublicKey`, `Status` (`Active` or `Overlap`), `CreatedAt` and `OverlapEndsAt`. Private keys are never returned.
|
|
40
|
+
- A receiver that cannot reach the kernel gets the keys as configuration from an operator who can: each `whpk_...` string with its status and `OverlapEndsAt`. A bare key string carries no expiry, so the receiver would trust it indefinitely. The operator supplies the complete updated set at every rotation, before the overlap ends.
|
|
41
|
+
- Load the keys when the receiver starts and keep them in memory. The kernel does not push keys to receivers, so the receiver replaces its set on its own schedule, as described under [Key rotation](#key-rotation).
|
|
42
|
+
|
|
43
|
+
## Verify a delivery
|
|
44
|
+
|
|
45
|
+
1. Reject the request when `webhook-id`, `webhook-timestamp` or `webhook-signature` is missing or empty, when `webhook-id` contains a dot, or when `webhook-id` is not well-formed text that encodes to UTF-8 without loss. Never substitute a replacement character for a malformed sequence or an unpaired surrogate; reject instead.
|
|
46
|
+
2. Reject it when `webhook-timestamp` is not canonical decimal seconds: ASCII digits `0`-`9` only, with no sign, no spaces and no leading zeros, and a value within the signed 64-bit range (at most `9223372036854775807`). Parse it so that a longer run of digits is rejected, not wrapped or truncated. Reject it also when it is more than five minutes from the receiver's clock in either direction. Keep the clock synchronized.
|
|
47
|
+
3. Build the message from the two header values and the raw body, as above, encoding strictly as UTF-8.
|
|
48
|
+
4. Reject the request when `webhook-signature` is longer than 4096 characters. Otherwise split it on spaces and keep the entries that start with `v1a,`; ignore entries of any other version. Reject the request when no `v1a` entry is left. Base64-decode the rest of each entry and skip an entry that is not valid Base64 of exactly 64 bytes. Reject the request when no signature remains.
|
|
49
|
+
5. Accept the request when **any** of those signatures verifies under **any** usable key: an active key, or an overlap key whose `OverlapEndsAt` is still in the future. Otherwise reject it and do not process the body.
|
|
50
|
+
|
|
51
|
+
The kernel takes only a `2xx` answer as an acknowledgement. Choose the answer by cause:
|
|
52
|
+
|
|
53
|
+
| Situation | Answer | What the kernel does |
|
|
54
|
+
| --- | --- | --- |
|
|
55
|
+
| The request fails any of steps 1 to 5 with the receiver's keys current | `401` | Treats a final `401` as a configuration problem and pauses the whole webhook |
|
|
56
|
+
| The receiver cannot decide yet: it has no keys loaded, or the refresh a failed verification calls for cannot reach the key source | `503` with `Retry-After` | Defers the partition until the time given and sends again, without spending a retry or pausing the webhook |
|
|
57
|
+
| The request verifies and is handled, or verifies and its `webhook-id` was already handled | `2xx` | Moves on to the next batch |
|
|
58
|
+
|
|
59
|
+
When the webhook authenticates with OAuth or a managed identity, the kernel answers a `401` by refreshing its token and sending the batch once more; the answer to that second request decides, so a resend the receiver accepts does not pause the webhook. Do the failure-triggered refresh described under [Key rotation](#key-rotation) before answering `401`, not after.
|
|
60
|
+
|
|
61
|
+
## Key rotation
|
|
62
|
+
|
|
63
|
+
- The kernel signs every delivery once per usable key: the active key and every overlap key whose overlap has not ended. `webhook-signature` carries one signature for each. An earlier overlap stays open through a later rotation, so there can be more than two. A receiver holding any of those keys accepts the delivery, provided the header passes step 4; that is why step 5 tries every signature against every key. Each entry is 92 characters, so 44 signatures fit in the 4096-character limit and a header carrying more is rejected whole. Let overlaps end before rotating again, so the count stays far below that.
|
|
64
|
+
- A replaced key is listed with status `Overlap` and its own `OverlapEndsAt`. Stop trusting each overlap key once its own time has passed; after that it is no longer listed.
|
|
65
|
+
- Replace the key set proactively; do not wait for a failure. A key the receiver loaded as `Active` keeps verifying all through its overlap, so a receiver that refreshes only on failure never learns that the key was replaced or when it expires, and goes on trusting it. Read the keys again on a fixed interval well shorter than the overlap the operator allows at rotation. A receiver that cannot reach the kernel gets the same from its operator: the complete new set at every rotation, before the overlap ends.
|
|
66
|
+
- Replace the whole set each time, never merge into the old one: keep exactly the keys listed, with the status and `OverlapEndsAt` now listed, and drop every key that is no longer listed.
|
|
67
|
+
- As a fallback, when verification fails and `Cratis-Key-Id` names a key the receiver does not hold, read the keys again at once and verify once more. If it still fails, reject. Never accept a delivery because its key id is unknown.
|
|
68
|
+
|
|
69
|
+
## Repeats and replays
|
|
70
|
+
|
|
71
|
+
- The timestamp tolerance limits how long a captured request stays usable; it does not make a request single use. Record the `webhook-id` of every delivery that verified and was handled. Verify a repeat like any other request; when it verifies and its `webhook-id` is recorded, answer `2xx` without applying its effect again. Any other answer makes the kernel send it again or pause the webhook. Never answer `2xx` to, or record the id of, a request that failed verification.
|
|
72
|
+
- A replay of the webhook from Chronicle is a new delivery with a new `webhook-id` carrying the same events under the same sequence numbers. So `webhook-id` stops a re-sent request, while the effect itself stays keyed on the event, as described under **Webhook** in `SKILL.md`.
|
|
73
|
+
|
|
74
|
+
## Anti-patterns
|
|
75
|
+
|
|
76
|
+
- Verifying a re-serialized body, or a body a framework already decoded and re-encoded.
|
|
77
|
+
- Picking the key by `Cratis-Key-Id` and verifying only against it, or skipping verification when the id is unknown.
|
|
78
|
+
- Failing the request on a signature entry of an unknown version instead of ignoring that entry.
|
|
79
|
+
- Refreshing keys only when verification fails: a replaced key stays trusted after its overlap has ended.
|
|
80
|
+
- Answering `401` while the keys cannot be loaded, or anything but `2xx` to a verified repeat.
|
|
81
|
+
- Hard-coding one public key with no way to add a second: the next rotation rejects every delivery once the overlap ends.
|
|
82
|
+
- Treating a valid signature as authorization. Signing proves origin and integrity; keep the receiver's authentication as well.
|
|
@@ -46,7 +46,9 @@ Use the project's reference for the supported form of each operation.
|
|
|
46
46
|
- Start at tail — skip existing facts only on first registration in a namespace. It never moves an observer that already has a saved position and does not suppress explicit replay. Both kernel and client must support it; a kernel that predates it ignores the request and the new subscription catches up from the beginning, so upgrade the kernel first, then the client. Changing the subscription's identity makes a new observer that starts at the tail again, skipping anything the old one had not handled.
|
|
47
47
|
- Replay exclusion — disable replay for the whole observer or skip selected handlers when replay must not repeat their effects.
|
|
48
48
|
- Replay override — substitute a replay handler for the ordinary handler of that type, or bind a replay-only event type; ordinary handlers otherwise run unless excluded.
|
|
49
|
+
- Handler changes — deploying changed handler code does not reprocess history: the reactor continues from its saved position. Adding or removing a handled event type does not replay either on a kernel with default settings; the kernel recommends a replay instead of starting one. The development kernel image is the exception: it requests a replay when the reactor's set of handled event types changes, never for a code-only change, and a reactor with replay disabled is still not replayed. Request an explicit replay when earlier events must be handled again, and only when the handlers are replay-safe.
|
|
49
50
|
- Replay lifecycle — receive begin/end notifications for the replay or a partition when rebuilding auxiliary state.
|
|
51
|
+
- Retry schedule — a failed partition is retried automatically with exponentially growing delays, and recovery is requested again when the reactor subscribes again, for example after a deployment. After deploying the fix, check whether the partition recovered before requesting anything; an accepted retry is not proof of recovery. Retries are bounded by default; a maximum of zero retry attempts means unlimited retries. A partition that used up its attempts is quarantined and automatic retries stop. Once the cause is fixed, an operator retry of a connected reactor's exhausted partition is still accepted, but it keeps the spent budget, so one more failure quarantines the partition again; clearing its quarantine starts a fresh budget. For the retry budget and quarantine see `cratis-chronicle-inspect-observer`.
|
|
50
52
|
- Delivery identity — use the stable delivery identity plus a distinct label per external operation; a delivery attempt number is not a receipt key.
|
|
51
53
|
- Derived fact — return a registered event when success should append a fact, or complete without a result for no append.
|
|
52
54
|
- Targeted output — explicitly route an output to another source instead of inheriting the trigger's source.
|
|
@@ -71,3 +73,18 @@ Use the project's reference for the supported form of each operation.
|
|
|
71
73
|
- Retired reactor — a reactor whose code is deleted, renamed or moved without a pinned identity stays registered as a disconnected observer with its position. Remove it only when no service needs it; removal covers every namespace, and registering it again starts from the beginning.
|
|
72
74
|
- Two versions connected at once — when instances of two application versions register the same observer with different event types, the last registration wins and the other version stops receiving. Only when the last connected instance of the winner leaves does a superseded version take over: connected standbys are tried newest first, and one that cannot take over is skipped. This automatic hand-over neither lifts a quarantine nor reactivates a retired observer (a redeploy or restart that subscribes the reactor again does end its observer quarantine), and events of types only the departed version handled are not replayed to the new one. Serving both type sets at once is not supported: keep the overlap short or put new handling in a separate reactor with its own ID. The hand-over is not exactly-once, so keep effects keyed on delivery identity.
|
|
73
75
|
- Read-model reactor — observe additions, modifications or removals when the change to a view is the trigger. Use materialized change detection for stored snapshots when needed. Delivery is best-effort, not a durable event subscription: a failing handler is logged or reported and never retried, with no failed partition to recover and no exactly-once delivery. Changes made while disconnected are not guaranteed to arrive, a change can arrive again after reconnecting, and snapshot comparison can merge intermediate states. Never trigger once-only external effects (payments, messages) from a view change; react to the domain event with an event reactor and make the external call idempotent.
|
|
76
|
+
|
|
77
|
+
## Multi-step processes (sagas and process managers)
|
|
78
|
+
|
|
79
|
+
Cratis has no saga or process-manager building block. Build a multi-step process from facts, reactors and read models, chosen by its shape:
|
|
80
|
+
|
|
81
|
+
| Shape of the process | Use |
|
|
82
|
+
| --- | --- |
|
|
83
|
+
| Short and linear, no waiting (default) | A chain of reactors: each reactor handles one fact and returns the next event, or the next command where your language reference shows a command integration; without one a returned command is not executed. Add a work-list read model (`cratis-chronicle-project-view`): the opening fact adds the item, and only a completion or cancellation fact removes it. |
|
|
84
|
+
| Steps that also need guarded ordering and an explicit closure | Still facts, reactors and a work-list read model. Add a process stream: one stream per run, a stream decision guards the step order against competing appends (`cratis-chronicle-protect-decision`) and completing the stream refuses later appends (`cratis-arc-declare-command`, `references/csharp-chronicle.md`). It gives only those two guarantees; it does not drive the steps. |
|
|
85
|
+
| Waits for a person, another fact or a deadline | The same chain with a work-list item that stays open while the process waits. The wait is not code: the next step is a reactor for the fact that ends the wait, such as the approval, the answer or the recorded expiry. A reactor never waits itself. |
|
|
86
|
+
| One entity's lifecycle | A status on the entity's read model, built from its facts (`cratis-chronicle-project-view`). Commands decide from the entity's facts, not from that status. |
|
|
87
|
+
|
|
88
|
+
**No rollback across steps.** Each step commits on its own, and nothing spans a reactor's returned events and commands, several returned commands, or several steps. A failed step is redelivered, so first make each step safe to repeat and let a transient failure retry. Compensate only when the domain decides to reverse completed work: record that decision as a fact and issue a compensating command for each completed step it reverses. Chronicle does not prevent a duplicate compensation, so make each one safe to repeat. Keep the item on the work list until a completion or cancellation fact removes it. Never delete or redact events to undo a step.
|
|
89
|
+
|
|
90
|
+
**Order.** Each handler method sees its events in order within one event source. Two methods of the same reactor are not ordered relative to each other, even for the same event source: a batch method and a per-event method each keep only their own order. When two effects must happen in a set order, handle them in one method. Order does not hold across event sources or between observers: a reactor can handle a fact before a projection has stored it, and the reverse. When logic needs the facts of two entities in order, put them on one event source or carry the needed data on the later event. Limiting partition concurrency protects a downstream system; it does not create a global order. With several instances of a service connected, keep the kernel's default fan-out, which keeps each event source on one instance while the set of connected instances is unchanged. Scaling or a reconnect can move an event source to another instance, so do not hold per-source state in instance memory.
|
|
@@ -12,6 +12,8 @@ public IEnumerable<object> Dispatched(ParcelDispatched fact) =>
|
|
|
12
12
|
|
|
13
13
|
For bare results implement on the reactor `ICanProvideEventSourceId`, `ICanProvideSubject` or `ICanProvideEventStreamId` with `GetEventSourceId()`, `GetSubject()` or `GetEventStreamId()` respectively; use reactor `[EventStreamId]`, `[EventStreamType]`, `[EventSourceType]` metadata where appropriate. An explicit wrapper takes precedence; set its `Subject`, `EventSourceType`, `EventStreamType`, `EventStreamId` and tags deliberately. Keep order stable: Chronicle derives automatic append keys by delivery and output position. `[Reactor("dispatch-log", effectEpoch: 1)]` (also available with an event sequence) deliberately changes automatic output identity (and named keys from `IdempotencyKeyFor`, but not `delivery.Id`); inspect `delivery.EffectEpoch`. Do not bump it to retry a failed delivery.
|
|
14
14
|
|
|
15
|
+
The derived keys are what stop a repeated delivery from appending a returned event again, and they need a kernel that supports idempotent appends. A kernel without that support appends returned events **without** derived keys and the client logs one warning per reactor, so a redelivery can append a copy: upgrade the kernel; do not replace returned events with manual appends. An `IdempotencyKey` you set yourself on an `EventForEventSourceId` is kept and never silently dropped: on such a kernel the return fails with `IdempotentAppendsNotSupported` and nothing is appended.
|
|
16
|
+
|
|
15
17
|
When several outputs depend on independently observed state, return `EventsWithConcurrencyScopes` with the ordered targeted events and the observed concurrency conditions. For example, given `depotOutput`, `parcelOutput` and scopes obtained at decision time:
|
|
16
18
|
|
|
17
19
|
```csharp
|
|
@@ -34,6 +36,6 @@ public CommandInvocation Dispatched(ParcelDispatched fact) =>
|
|
|
34
36
|
|
|
35
37
|
Use `Cratis.Arc.Chronicle.Reactors`. Match the exact constraint name. Selectors include `ByValidation`, `ByConstraint(name)`, `ByAnyConstraint`, `ByAuthorization` and `Any` (validation and constraints, not authorization). First match wins. A handled refusal stops later commands; earlier appends remain committed. Only acknowledge when no outcome fact is required. Concurrency and infrastructure failures aren't refusals. Preserve the actor for consequential commands.
|
|
36
38
|
|
|
37
|
-
The integration also executes a bare returned command (e.g. `public ReserveLoadingBay Dispatched(ParcelDispatched fact) => new(fact.DepotId);`), an enumerable of commands and/or invocations in order, and an enumerable mixing registered events with commands:
|
|
39
|
+
The integration also executes a bare returned command (e.g. `public ReserveLoadingBay Dispatched(ParcelDispatched fact) => new(fact.DepotId);`), an enumerable of commands and/or invocations in order, and an enumerable mixing registered events with commands: all events are appended first as one batch, then the commands run in order; interleaving them in the collection does not interleave execution. If the append fails, no command runs. Without a matching refusal branch an unsuccessful command fails the delivery and stops later commands. Nothing spans the two groups: the event batch and the commands that already succeeded stay committed, and recovery redelivers the triggering event and runs the returned commands again from the first one, including those that already succeeded, stopping again at the first unsuccessful command. `[OnceOnly]` does not prevent that, so keep each returned command safe to repeat. To run a reactor's returned commands as the system with declared roles, see `[ExecuteCommandsAsSystem]` in `cratis-arc-authorize-request`. That attribute covers **returned** commands only. Prefer returning the command: a handler that calls `ICommandPipeline.Execute` itself runs with no principal unless it opens its own system scope, and must state what replay does (`ARCCHR0006`): `[OnceOnly]` when skipping the handler on replay is right, otherwise a `[Replay]` handler for the same event type.
|
|
38
40
|
|
|
39
41
|
A returned value that no side-effect handler claims (for example a custom type without a registered `IReactorSideEffectHandler`) fails the delivery with `UnhandledReactorReturnValue`. Return a supported type or register the handler.
|
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Handle a committed event in C#
|
|
2
2
|
|
|
3
|
+
## Contents
|
|
4
|
+
|
|
5
|
+
- One handler per event type
|
|
6
|
+
- Configure the subscription
|
|
7
|
+
- Event context
|
|
8
|
+
- Register without discovery
|
|
9
|
+
- Replay and returned work
|
|
10
|
+
- Common mistakes
|
|
11
|
+
|
|
3
12
|
Reference `Cratis.Chronicle` in the connected backend. Write handlers as public instance methods on a concrete `IReactor` in a discovered assembly, with a registered event type as the first parameter. Names below are illustrative. Register application dependencies such as `services.AddScoped<ICarrier, Carrier>();` in the host; Chronicle discovers the reactor, not the carrier's receipt protocol.
|
|
4
13
|
|
|
5
14
|
```csharp
|
|
@@ -44,9 +53,33 @@ The client binds one handler per event type, and separately one `[Replay]` handl
|
|
|
44
53
|
- Never combine `[EventStore]`/`FromEventStore` with an explicit sequence; registration refuses it.
|
|
45
54
|
- `options.EventGenerationDelivery = EventGenerationDelivery.Pinned` requests the declared generation rather than compatibility delivery; this is a client option, not a handler attribute.
|
|
46
55
|
- `[Tag("shipping", "operations")]` or `[Tags("shipping", "operations")]` labels the reactor for inspection. Repeat `[FilterEventsByTag("urgent")]` with different values for an any-tag input filter. `[EventSourceType("parcel")]` and `[EventStreamType("dispatch")]` further restrict delivery by append metadata; these restrictions intersect. To filter by a declared route instead, `[FromEventSource<Parcel>("Dispatch")]` (`Cratis.Chronicle.EventSources`) sets both from an `IEventSource` definition and one stream it declares; explicit `[EventSourceType]`/`[EventStreamType]` may only repeat those values. An unregistered source or undeclared stream fails registration. `[EventStreamId("notifications")]` routes outputs, not inputs.
|
|
47
|
-
- Prefer constructor injection for infrastructure. Handler parameters can also receive services, `EventContext` (e.g. `context.EventSourceId`, `context.SequenceNumber
|
|
56
|
+
- Prefer constructor injection for infrastructure. Handler parameters can also receive services, `EventContext` (e.g. `context.EventSourceId`, `context.SequenceNumber`; all members under Event context below), `ReactorDelivery`, or related read models. By default every read-model parameter is loaded with the event's `EventSourceId` as its key, so `Task Notify(ParcelDispatched fact, Depot depot)` looks `Depot` up by the parcel's source ID. The lookup uses only that key value: for a model keyed by something else you get whatever is stored under that value; a materialized model returns null when its sink has no row for it. A stream-scoped model (`[EventStream<TSource>("stream")]`) refuses key-only lookup, so read it with `IReadModels.GetInstanceById<T>(eventSourceId, eventStreamId)` instead of a parameter. To use another key implement `ICanResolveReadModelKey` on the reactor. `Resolve` runs for each read-model parameter and receives the fact and context but not the parameter type, so handle every event the reactor observes: `public ReadModelKey Resolve(object fact, EventContext context) => fact switch { ParcelDispatched dispatched => dispatched.DepotId, _ => (ReadModelKey)context.EventSourceId };`. All read-model parameters of one handler get the same key; read a differently keyed model with `IReadModels.GetInstanceById<T>(key)`. A materialized read model is read from its sink and may not yet include the event being handled; don't treat it as part of the triggering fact. Avoid mutable fields across events.
|
|
48
57
|
- For tracing, implement `IReactorMiddleware.BeforeInvoke(EventContext, object)` and `AfterInvoke(EventContext, object)` returning `Task`; override the overloads with leading `ReactorId` when tagging spans by observer. Middleware surrounds individual invocations, not a cross-partition transaction.
|
|
49
58
|
|
|
59
|
+
## Event context
|
|
60
|
+
|
|
61
|
+
`EventContext` (`Cratis.Chronicle.Events`) describes the delivered event. Take it as a handler parameter and read these values from it; do not copy them into the event payload.
|
|
62
|
+
|
|
63
|
+
| Member | Carries |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| `EventType` | The event type: its `Id` and the `Generation` of the payload the handler receives. Under compatibility delivery this is the generation the handler declares, which can differ from the one the event was appended in. |
|
|
66
|
+
| `AppendedGeneration` | The generation the event was appended in, whichever generation is delivered; `null` when unknown. |
|
|
67
|
+
| `EventSourceType`, `EventSourceId` | The type and identity of the event source. |
|
|
68
|
+
| `EventSource` | The name of the event source definition the event was appended through; `EventSourceName.NotSet` when it was appended without one. |
|
|
69
|
+
| `EventStreamType`, `EventStreamId` | The stream within the event source. |
|
|
70
|
+
| `SequenceNumber` | The event's position in its event sequence. |
|
|
71
|
+
| `Occurred` | When the event occurred (`DateTimeOffset`). |
|
|
72
|
+
| `EventStore`, `Namespace` | The event store and namespace the event belongs to. |
|
|
73
|
+
| `CorrelationId` | The correlation the event was appended under. Not a delivery receipt: use `ReactorDelivery`. |
|
|
74
|
+
| `Causation` | The chain of causes that led to the event. |
|
|
75
|
+
| `CausedBy` | The identity that caused the event. |
|
|
76
|
+
| `Tags`, `NamedTags` | The plain tags and the named tags on the event. |
|
|
77
|
+
| `Subject`, `SubjectIsEventSourceId` | The compliance subject, which defaults to the event source ID when the event was appended without an explicit subject. `SubjectIsEventSourceId` is `true` when the two are equal. |
|
|
78
|
+
| `CompensationFor` | The sequence number of the event this one compensates for; `null` when it is not a compensation. |
|
|
79
|
+
| `Hash` | A hash Chronicle stored for the event. It does not change with the delivered generation, so do not compare it with a hash of the payload the handler receives. |
|
|
80
|
+
| `ErasedProperties` | Always empty in a reactor delivery: only an explicit erased-path read of an event sequence fills it. Do not use it in a handler to decide whether content was erased. |
|
|
81
|
+
| `ObservationState` | Delivery state set by Chronicle. Do not branch on it; use `[Replay]` and `[OnceOnly]` (see Replay and returned work). |
|
|
82
|
+
|
|
50
83
|
## Register without discovery
|
|
51
84
|
|
|
52
85
|
For explicitly selected artifacts use `options.ExplicitArtifacts.RegisterReactor<CarrierNotice>()` (or the `Type` overload). Discovery never finds a class that does not implement `IReactor` by its method signatures; nominate it this way or register it in manual startup with `Register(typeof(CarrierNotice))` below. In manual startup `await reactors.Discover(); await reactors.Register();` discovers then registers all; `Register<CarrierNotice>()` or `Register(typeof(CarrierNotice))` registers one. Do not repeat the host's automatic registration.
|
|
@@ -64,7 +97,7 @@ For runtime schemas use `await reactors.Register(id, b => b.WithEventType(eventT
|
|
|
64
97
|
|
|
65
98
|
## Replay and returned work
|
|
66
99
|
|
|
67
|
-
`[OnceOnly]` on the reactor excludes the whole observer from replay; on a method it skips that method during replay. Neither prevents retry. To substitute replay behavior, add e.g. `[Replay] public Task Rebuild(ParcelDispatched fact) => cache.Restore(fact);`. A replay method may also bind a type without a live handler. Otherwise ordinary replayable handlers run. For lifecycle callbacks implement `ICanBeNotifiedWhenReplay` (`Task BeginReplay()`, `Task EndReplay()`) or `ICanBeNotifiedWhenPartitionReplayed` (`Task BeginReplayPartition(Partition partition)`, `Task EndReplayPartition(Partition partition)`).
|
|
100
|
+
`[OnceOnly]` on the reactor excludes the whole observer from replay; on a method it skips that method during replay. Neither prevents retry. To substitute replay behavior, add e.g. `[Replay] public Task Rebuild(ParcelDispatched fact) => cache.Restore(fact);`. A replay method may also bind a type without a live handler. Otherwise ordinary replayable handlers run. For lifecycle callbacks implement `ICanBeNotifiedWhenReplay` (`Task BeginReplay()`, `Task EndReplay()`) or `ICanBeNotifiedWhenPartitionReplayed` (`Task BeginReplayPartition(Partition partition)`, `Task EndReplayPartition(Partition partition)`). Only reactor classes receive these: a reactor defined with the builder or registered with a delegate gets none. Each notification runs in its own dependency scope. By default it also gets a new reactor instance, so a field set in `BeginReplay` is visible neither to the handlers nor to `EndReplay`; a reactor registered in the container as a singleton is the same instance each time. Do not rely on reactor fields either way: keep such state in a singleton service, or in storage outside the process when it must survive a restart or span instances.
|
|
68
101
|
|
|
69
102
|
See [Returned events and command outcomes](csharp-outputs.md) for derived facts, routing, guarded appends and custom return values. If the activation is not domain history, [record an occurrence](csharp-occurrences.md) instead. See [Pages and recovery](csharp-pages.md) for batch processing, capacity, waits, repair, starting and awaiting a replay, and view-change reactions.
|
|
70
103
|
|
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# React to a committed fact in Elixir
|
|
2
2
|
|
|
3
|
+
## Contents
|
|
4
|
+
|
|
5
|
+
- Register a typed handler
|
|
6
|
+
- Select delivery and replay behavior
|
|
7
|
+
- Return derived events
|
|
8
|
+
- Work in pages
|
|
9
|
+
- Inspect and recover
|
|
10
|
+
- React to a change in a view instead
|
|
11
|
+
- Not supported in this SDK
|
|
12
|
+
|
|
3
13
|
## Register a typed handler
|
|
4
14
|
|
|
5
15
|
Names are illustrative. In the Mix service using `:cratis_chronicle`, define the input contract and a reactor module:
|
|
@@ -31,6 +41,7 @@ Add `{Cratis.Chronicle.Client, connection_string: endpoint, event_store: "shippi
|
|
|
31
41
|
- Compatibility delivery upgrades to the handled generation. Set `generation_delivery: :pinned` to bind to the declared generation; do not handle multiple generations of the same type ID in that reactor. Overrides client `event_generation_delivery:`. `ctx.appended_generation` is zero when unknown.
|
|
32
42
|
- Read routing and provenance from context: e.g. `ctx.event_source_id`, `ctx.sequence_number`, `ctx.event_stream_id`, `ctx.event_store`, `ctx.namespace`, `ctx.subject`, `ctx.tags`, `ctx.correlation_id`, `ctx.caused_by` and `ctx.causation`. Do not use correlation ID as a delivery receipt.
|
|
33
43
|
- `middleware: [Shipping.Trace]` wraps per-event handlers, not batch functions. Implement `@behaviour Cratis.Chronicle.Middleware` and `def call(event, ctx, next), do: next.(event, ctx)` around the tracing work; return the downstream result. Global `config :cratis_chronicle, middleware: [Service.Trace]` wraps reactor-local middleware.
|
|
44
|
+
- A handler must answer each delivered batch within the kernel's subscriber timeout, `observers.subscriberTimeout`: configured as 30 seconds unless the kernel sets another value, and 5 seconds on the development kernel image. That is not a guaranteed window: live delivery is also capped at five seconds below the kernel's cluster response timeout, so a live batch can time out sooner than the configured value. When the wait elapses the batch is recorded as a failed partition and retried with backoff, while the handler may still finish its work, so the effect can repeat. Keep handlers fast, keep effects idempotent, and move slow work out of the handler. The option is described in `cratis-chronicle-deploy-kernel`, `references/kernel-options.md`.
|
|
34
45
|
|
|
35
46
|
## Return derived events
|
|
36
47
|
|
|
@@ -118,6 +118,7 @@ Registration rejects a mis-shaped reactor; fix the class instead of catching.
|
|
|
118
118
|
|
|
119
119
|
## Not supported in this SDK
|
|
120
120
|
|
|
121
|
+
- No `@EventLog` or `@EventStore` annotation: a reactor without an explicit sequence already reads the event log, and a source store is never inferred. `@ContextKey` can be applied but nothing reads it, so it changes no key.
|
|
121
122
|
- No reactor generation pin, automatic source-store inbox selection, output-stream annotation, dynamic typed builder or raw delegate subscription. Register compatible typed handlers, select the local sequence explicitly, and wrap routed outputs.
|
|
122
123
|
- No per-event activation option or dedicated model-key annotation. Keep services stateless; resolve a different key explicitly.
|
|
123
124
|
- No built-in receiver delivery key, effect epoch, guarded multi-target reactor return, general custom result interpreter or occurrence/receipt reactor contract. Use receiver-owned receipts; send decisions requiring concurrency checks to the owning write path instead of returning commands or unguarded facts.
|
|
@@ -110,6 +110,7 @@ Registration rejects a mis-shaped reactor; fix the class instead of catching.
|
|
|
110
110
|
|
|
111
111
|
## Not supported in this SDK
|
|
112
112
|
|
|
113
|
+
- No `@EventLog` or `@EventStore` annotation: a reactor without an explicit sequence already reads the event log, and a source store is never inferred. `@ContextKey` can be applied but nothing reads it, so it changes no key.
|
|
113
114
|
- No generation-pinning reactor option, automatic external-store selection, dynamic callback builder or raw delegate registration: register compatible typed methods on the intended sequence; cancel the registration job to stop listening.
|
|
114
115
|
- No per-event activation switch, per-reactor page limits or partition parallelism setting: keep instances stateless and bound downstream work. No dedicated readiness await: inspect observer state with a timeout.
|
|
115
116
|
- No built-in receiver delivery key, automatic output epoch, guarded multi-target reactor return or custom return interpreter: deduplicate at the receiver, version effects deliberately, and move guarded decisions into an explicit write workflow. For operational work without a fact use an application-owned durable queue with receipts rather than returning an arbitrary object.
|