@cratis/pi 7.48.3 → 7.48.4
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/agents/backend-developer.md +1 -1
- package/package/corpus/agents/slice-implementer.md +2 -2
- package/package/corpus/harnesses/copilot/instructions/application-profile.instructions.md +3 -3
- package/package/corpus/harnesses/copilot/instructions/csharp.instructions.md +3 -1
- package/package/corpus/harnesses/copilot/instructions/glossary.instructions.md +3 -3
- package/package/corpus/harnesses/copilot/instructions/vertical-slices.instructions.md +6 -3
- package/package/corpus/prompts/add-projection.prompt.md +2 -1
- package/package/corpus/prompts/add-reducer.prompt.md +6 -4
- package/package/corpus/rules/application-profile.md +3 -3
- package/package/corpus/rules/csharp.md +3 -1
- package/package/corpus/rules/glossary.md +3 -3
- package/package/corpus/rules/vertical-slices.md +6 -3
- package/package/corpus/skills/cratis-chronicle-client-dotnet/SKILL.md +16 -33
- package/package/corpus/skills/cratis-chronicle-client-dotnet/references/discovery.md +92 -7
- package/package/corpus/skills/cratis-chronicle-projection/SKILL.md +18 -10
- package/package/corpus/skills/cratis-chronicle-read-model/SKILL.md +46 -18
- package/package/corpus/skills/cratis-chronicle-read-model-specifications/SKILL.md +32 -14
- package/package/corpus/skills/cratis-chronicle-reducer/SKILL.md +194 -38
- package/package.json +1 -1
|
@@ -110,7 +110,7 @@ public record ProjectRegistered(ProjectName Name);
|
|
|
110
110
|
|
|
111
111
|
- Record decorated with `[ReadModel]`; query methods are **static** methods on the record; custom paths use `[Path("...")]`.
|
|
112
112
|
- **AutoMap is on by default — NEVER call `.AutoMap()`.** Matching property names map automatically; diverge with `[SetFrom<T>]` / `.Set().To()` only for genuine name differences. Re-enable `.AutoMap()` only inside a `.NoAutoMap()` scope.
|
|
113
|
-
-
|
|
113
|
+
- Start with model-bound attributes for clear mappings; use fluent `IProjectionFor<T>` when mappings need structure; choose reducer code when prior-state branches, calculations or guards read better as code. Default new .NET reducers to static `Reduce` on the model; use `IReducerFor<T>` for DI/replay instance behavior/separation and nominated plain classes only when their assembly cannot reference Chronicle. Follow **cratis-chronicle-read-model** and **cratis-chronicle-reducer** for signatures, Arc query discovery and ownership; preserve admission/ordering guards when converting. Other SDK and Stage contracts are unchanged.
|
|
114
114
|
- Projections consume **events**, never other read models.
|
|
115
115
|
- Identity concepts derive from `EventSourceId<T>` (not `ConceptAs<Guid>`).
|
|
116
116
|
|
|
@@ -54,7 +54,7 @@ Read the skill before writing the artifact it covers; the rules alone are not th
|
|
|
54
54
|
| Slice type | Before writing code | Specifications |
|
|
55
55
|
|---|---|---|
|
|
56
56
|
| State Change | `cratis-arc-command`, `cratis-arc-command-validation`, `cratis-fundamentals-concept`; `cratis-chronicle-event-constraints` for uniqueness | `cratis-application-slice-specifications`; `cratis-chronicle-event-specifications` for constraints |
|
|
57
|
-
| State View | `cratis-chronicle-read-model`, `cratis-chronicle-projection` (`cratis-chronicle-reducer`
|
|
57
|
+
| State View | `cratis-chronicle-read-model`, `cratis-chronicle-projection` (`cratis-chronicle-reducer` when transitions read better as code) | `cratis-chronicle-read-model-specifications` |
|
|
58
58
|
| Automation | `cratis-chronicle-reactor`; `cratis-arc-command-execution` or `cratis-arc-command-operation`; `cratis-engineering-effect-boundaries` for any outside call | Plain calls for pure reactor decisions; `ReactorScenario` for invocation/side effects (`cratis-specifications-csharp`), plus the invoked command's specs |
|
|
59
59
|
| Translation | by the actual construct and trigger, not the label: a `capture` is an ingestion adapter (`cratis-engineering-effect-boundaries`); a translator `reaction` is `cratis-chronicle-reactor` (cross-service: inbox/`[EventStore]`); a clock or application trigger is a scheduler or host signal | as Automation |
|
|
60
60
|
| UI | `cratis-arc-react-page`, `cratis-arc-command-typescript`, `cratis-arc-query-typescript` | `cratis-application-react-specifications` |
|
|
@@ -85,7 +85,7 @@ Proxies now exist. Build React components from the generated proxies (`react.md`
|
|
|
85
85
|
|
|
86
86
|
- All backend artifacts in one `<Slice>.cs`; namespace mirrors the path; layout per `general.md` (no `Features/` wrapper; `<Module>` optional).
|
|
87
87
|
- `Handle()` returns the event/result directly (no `Task.FromResult` without `await`); validation in `CommandValidator<T>`/`ConceptValidator<T>`/`Provide()`; **never throw for normal business rejection** — return `ValidationResult`/`Result<,>`.
|
|
88
|
-
-
|
|
88
|
+
- Start with model-bound attributes, fluent for structured mappings, reducer code for clearer prior-state branches/calculations/guards; **never `.AutoMap()`**. New .NET reducers default to static `Reduce` on the model; separate `IReducerFor<T>` for DI/replay instance behavior/separation; plain-class nomination only when its assembly cannot reference Chronicle. Follow the read-model/reducer skills for Arc query discovery, exact signatures and builder ownership. Preserve admission/ordering guards when converting; do not infer Stage renders the self form or apply it to other SDKs.
|
|
89
89
|
- Events: no arguments on `[EventType]`, non-nullable, past tense, `<summary>`, never carry the event-source id.
|
|
90
90
|
- `[OnceOnly]` on non-idempotent reactor side effects; reactors return side-effect events or use `ICommandPipeline` (never `IEventLog`).
|
|
91
91
|
- Specs compiled into the application assembly use `#if DEBUG`; dedicated spec projects need no wrapper. Command aliased, per-test unique values.
|
|
@@ -19,7 +19,7 @@ Pick exactly one type per slice folder — determined by what the slice *does*.
|
|
|
19
19
|
| Type | What it does | Contents |
|
|
20
20
|
| --- | --- | --- |
|
|
21
21
|
| **State Change** | Accepts a command, appends events | Command + validator + event(s); optional `[Passive]` for a current read; a rule that must hold under concurrency needs a decision read or constraint (see the `cratis-chronicle-decision-reads` skill, `references/choosing-how-a-rule-holds.md`) |
|
|
22
|
-
| **State View** |
|
|
22
|
+
| **State View** | Builds a queryable read model from events | `[ReadModel]` + projection mappings or reducer code + static query method(s) on the record |
|
|
23
23
|
| **Automation** | Reacts to events, calls external systems / `ICommandPipeline`, or returns follow-up commands/events (including to another stream) | Reactor only |
|
|
24
24
|
| **Translation** | Takes data from outside our own facts (an external system or another service) and records it as our facts | An adapter at the boundary, often a reactor |
|
|
25
25
|
|
|
@@ -31,7 +31,7 @@ Commands are imperative intents (`Register`, `Create`); the slice folder is the
|
|
|
31
31
|
|
|
32
32
|
Tagged **[contract]** (framework-enforced) or **[convention]** (house default). Mechanics and examples live in `vertical-slices.md`.
|
|
33
33
|
|
|
34
|
-
1. **[contract] Model-bound — no controllers.** Commands are `[Command]` records with a public instance `Handle()` (Arc analyzers enforce this); queries are `static` methods on `[ReadModel]` records; projections/constraints/authorization use attributes. Arc generates the HTTP surface.
|
|
34
|
+
1. **[contract] Model-bound — no controllers.** Commands are `[Command]` records with a public instance `Handle()` (Arc analyzers enforce this); queries are `static` methods on `[ReadModel]` records; projections/constraints/authorization use attributes. Arc generates the HTTP surface. For read-model style follow rule 11's ladder; for constraints use `IConstraint` when attributes cannot express the rule.
|
|
35
35
|
2. **[contract] Command validation & data flow.** Put command rejection in `CommandValidator<T>`, global value invariants in `ConceptValidator<T>`, and fetched/computed handler data in **`Provide()`** (runs after validation/authorization; may short-circuit with `ValidationResult.Error` / `Result<TProvided, ValidationResult>`). Keep `Handle()` focused on event construction. For a state-dependent rule that must hold **under concurrency**, enroll a guarded stream decision (`IStreamReads`/`StreamDecision`) or use `[ProtectedDecision]` with an admitted `DecisionRead<T>`; plain injected models remain advisory. Return a typed rejection via `Result<TEvent, ValidationResult>` where needed; the result alone adds no guard. **Throwing from `Provide()`/`Handle()` is an exception (HTTP 500), not a validation rejection** — throw only for genuinely exceptional conditions, never for normal business rejection.
|
|
36
36
|
3. **[contract] Event-source id resolution:** `ICanProvideEventSourceId` first; else the first qualifying property in declaration order — an `EventSourceId`/`EventSourceId<T>`-derived value *or* a `[Key]` property (no priority between them; two candidates is `ARCCHR0002`); else Arc generates one. A value actually used as a Chronicle stream identity derives from `EventSourceId<T>` with the underlying `IComparable` primitive — never `ConceptAs<Guid>` for that stream identity. `NotSet`, `New()`, and primitive→derived-id operators are optional domain/API conveniences, not Chronicle requirements; typed empty/zero values are real specified stream IDs, not `EventSourceId.Unspecified`.
|
|
37
37
|
4. **[contract] Events never carry the event-source id** — it is implicit in the event context.
|
|
@@ -41,7 +41,7 @@ Tagged **[contract]** (framework-enforced) or **[convention]** (house default).
|
|
|
41
41
|
8. **[convention] Every `[EventType]` has an XML `<summary>`** — a Cratis C# documentation convention (not a Chronicle rule); events live in the log forever, so record why they exist.
|
|
42
42
|
9. **[convention] `[ReadModel]` properties carry no default values** except semantically meaningful enum initial states and `[SetValue<T>]`-driven `bool` flags. False defaults hide missing projection wiring.
|
|
43
43
|
10. **[contract] AutoMap is on by default — never call `.AutoMap()`.** Match property names so AutoMap wires them; diverge with `[SetFrom<T>]` / fluent `.Set().To()` only for genuine name differences. Re-enable `.AutoMap()` only inside a scope where it was disabled with `.NoAutoMap()`.
|
|
44
|
-
11. **[contract] Projections consume events and event context — never other read models.**
|
|
44
|
+
11. **[contract] Projections consume events and event context — never other read models.** **[convention]** For application code start with model-bound attributes, use fluent `IProjectionFor<T>` when mappings need structure, and choose reducer code when prior-state branches, calculations or guards read better as code (a normal choice, not a last resort). New .NET reducers default to static `Reduce` on the model; use `IReducerFor<T>` for injected services, replay instance behavior or separation, and nominate a plain instance class only when its assembly cannot reference Chronicle. PDL belongs outside application code. Follow the **cratis-chronicle-read-model** style ladder and **cratis-chronicle-reducer** signatures; preserve admission/ordering guards when converting. This does not change Stage's rendering contract or other SDK reducer contracts.
|
|
45
45
|
12. **[contract] Model-bound query custom paths use `[Path("...")]`** (`PathAttribute`), not ASP.NET `[Route]`. Reserve `[Route]` for controller-based endpoints (which this convention avoids).
|
|
46
46
|
13. **[convention] Cross-slice access is read-only through Chronicle** — inject another slice's read model or reference its events; never instantiate or DI another slice's command/handler/service.
|
|
47
47
|
14. **[contract] Never inject `IEventLog` into `Handle()`** — express appends through return types (`IEnumerable<object>` with `EventForEventSourceId` wrappers for cross-stream). In application reactors, return side-effect events or commands (or use `ICommandPipeline` and inspect the result); don't reach for `IEventLog` directly.
|
|
@@ -337,7 +337,9 @@ These are the building blocks. Each type has a specific role in the vertical sli
|
|
|
337
337
|
| `[ReadModel]` | Marks a record as a model-bound query — define static query methods on the record |
|
|
338
338
|
| `CommandValidator<T>` | FluentValidation validator for commands |
|
|
339
339
|
| `IProjectionFor<T>` | Fluent projection definition — AutoMap is on by default, never call `.AutoMap()` |
|
|
340
|
-
|
|
|
340
|
+
| Self-reducing model | New .NET reducer default: public static `Reduce(event, model? current[, EventContext])`, returns model or `Task<model>` (nullable results allowed); marker-free discovery, no fold-time DI |
|
|
341
|
+
| `IReducerFor<T>` | Separate instance fold for injected services, replay instance behavior or separation from the model |
|
|
342
|
+
| `ChronicleOptions.ExplicitArtifacts.RegisterReducer<T>()` | Nominate a plain instance class only when its assembly cannot reference Chronicle; also accepts self models (see **cratis-chronicle-client-dotnet**, discovery reference) |
|
|
341
343
|
| `IReactor` | Marker interface for side-effect observers — method dispatch by event type parameter |
|
|
342
344
|
| `IConstraint` | Constraint definition — enforced server-side by Chronicle at append time |
|
|
343
345
|
| `AggregateRoot` | Chronicle aggregate root with `Apply()` and `Commit()` |
|
|
@@ -20,9 +20,9 @@ One precise line per load-bearing term, so the same word means the same thing ev
|
|
|
20
20
|
|
|
21
21
|
## Read side
|
|
22
22
|
|
|
23
|
-
- **Read model** —
|
|
24
|
-
- **Projection** — declares how a read model
|
|
25
|
-
- **Reducer** —
|
|
23
|
+
- **Read model** — derived state built from events by a projection or reducer; an optional Arc `[ReadModel]` record exposes static queries, but Chronicle-only models need no query attribute.
|
|
24
|
+
- **Projection** — declares how events build a read model (model-bound attributes, fluent `IProjectionFor<T>`, or PDL outside application code); pure events→state, no side effects, never reads other read models.
|
|
25
|
+
- **Reducer** — a "current state + event → next state" builder when transitions read better as code; new .NET code defaults to static `Reduce(event, model? current[, EventContext])` on a self-reducing model (no marker), with `IReducerFor<T>` for DI/replay instance behavior/separation and nominated plain classes when their assembly cannot reference Chronicle. See **cratis-chronicle-reducer**; other SDKs retain their own contracts.
|
|
26
26
|
- **Reactor** — `IReactor`; observes events and produces **side effects** (notifications, commands, follow-up events). The "if this then that".
|
|
27
27
|
- **Observer** — Chronicle's umbrella for anything consuming an event sequence (projection, reducer, reactor); carries subscription / replay / **quarantine** state. Projection replay and catch-up each walk the sequence in one globally ordered job step; a new catch-up failure stops that step. Full replay is inactive and completion does not resume a quarantined observer (Chronicle v19.50.1, `Documentation/concepts/observers.mdx`, `Observation/Jobs/{CatchUpObserver,ReplayObserver}.cs` under `Source/Kernel/Core/`).
|
|
28
28
|
- **Sink** — where a read model is persisted (MongoDB, EF Core).
|
|
@@ -249,7 +249,7 @@ public record AuthorRegistered(AuthorName Name);
|
|
|
249
249
|
|
|
250
250
|
## Read Models and Queries
|
|
251
251
|
|
|
252
|
-
**[contract]** `[ReadModel]` records expose queries as `public static` methods; dependencies are plain method parameters (no `[FromServices]`).
|
|
252
|
+
**[contract]** `[ReadModel]` records expose queries as `public static` methods; dependencies are plain method parameters (no `[FromServices]`). For application code, start with model-bound mappings, use fluent when the definition needs structure, and choose reducer code when transitions read better as code. For step-by-step creation, invoke the **cratis-chronicle-read-model** skill.
|
|
253
253
|
|
|
254
254
|
Use `[ReadModel(RequireQueryAttribute = true)]` with `[Query]` on intended
|
|
255
255
|
endpoints when public folds/helpers exist (ARC0026/ARCCHR0019). `[Query]` alone
|
|
@@ -325,8 +325,11 @@ evaluate reconstruction frequency, history length, consistency, and security.
|
|
|
325
325
|
Projections build read models from **events** (never from other read models). Use the ladder — for adding one to an existing model, invoke the **cratis-chronicle-projection** skill:
|
|
326
326
|
|
|
327
327
|
1. **Model-bound attributes** on the `[ReadModel]`: `[FromEvent<T>]`, `[SetFrom<T>]`, `[SetFromContext<T>]`, `[ChildrenFrom<T>]`, `[RemovedWith<T>]`, `[Nested]`, `[ClearWith<T>]`, counters, `[FromAll]`.
|
|
328
|
-
2. **Fluent `IProjectionFor<T>`**
|
|
329
|
-
3. **Reducer
|
|
328
|
+
2. **Fluent `IProjectionFor<T>`** when mappings need structure or the contract should stay attribute-free: joins, composite/constant keys, parent-key extraction, context mapping, `.NotRewindable()`, or supported conditional setters. Declarative metadata only — no DI side effects, no imperative `Define()` body, builder lambdas are member access only.
|
|
329
|
+
3. **Reducer code** for clearer "current state + event → next state" logic — prior-state branches, calculations and guards. A normal choice, not a last resort. Default new .NET reducers to **self-reducing models** with public static `Reduce(event, model? current[, EventContext])`, returning model or `Task<model>` (including nullable results), without a marker. Use separate `IReducerFor<T>` for fold-time DI, replay instance behavior or separation.
|
|
330
|
+
4. **Nominated plain instance class** only when its assembly cannot reference Chronicle; nominate through `ChronicleOptions.ExplicitArtifacts` before creating stores. Use **PDL** for definitions authored outside application code, not as the code-first default.
|
|
331
|
+
|
|
332
|
+
For self models, keep `[ReadModel]`, static `Reduce` methods and queries on one record. Before Arc 22.90.0, use `[ReadModel(RequireQueryAttribute = true)]` and `[Query]`; from Arc 22.90.0, Arc excludes methods taking the model itself from query discovery and Arc.Chronicle claims self models for command injection. Complete marker-free shapes become reducers on upgrade; a competing builder fails with `AmbiguousReadModelBuilder`. Preserve admission/ordering guards when converting and remove the previous builder. See **cratis-chronicle-reducer** for exact signatures, hooks and limits. `[Passive]` belongs on the model; it gives fresh reads, not a concurrency guard — decision reads refuse reducers. Self reduction is .NET-only (Cratis/Chronicle#4851); this does not claim Stage renders it.
|
|
330
333
|
|
|
331
334
|
- **[contract] AutoMap is on by default — never call `.AutoMap()`.** Match property names so AutoMap wires them; diverge with `[SetFrom<T>]` / `.Set().To()` only for genuine name differences. Re-enable `.AutoMap()` only inside a scope disabled with `.NoAutoMap()`.
|
|
332
335
|
- ⚠️ **AutoMap runs per *event* across every event the projection references — it does not defer to your explicit setters.** A property sourced with `[SetFrom<A>]` can still be silently overwritten when some *other* referenced event `B` happens to carry an identically named property (AutoMap wires `B`'s value on top). Fence the property with property-level **`[NoAutoMap]`** (which pairs with the `[SetFrom]`, not replaces it) so only your explicit setter writes it. `[SetFrom]` does **not** imply this — leaving AutoMap on is what allows the common create-then-rename pattern (a later event updating a property by name-match). No colliding event property name means no `[NoAutoMap]` needed. (An event subscribed only via an aggregate like `[Count]` doesn't auto-map its other properties, so it can't collide.) The analyzer **`CHR0025`** surfaces this collision as an *informational* heads-up (not a warning, because either resolution — add `[NoAutoMap]`, or accept the update — can be correct).
|
|
@@ -13,7 +13,8 @@ Add a Chronicle projection that populates a read model from events. Invoke the *
|
|
|
13
13
|
|
|
14
14
|
## Key rules
|
|
15
15
|
|
|
16
|
-
-
|
|
16
|
+
- Start with **model-bound attributes** on the read model (`[FromEvent<T>]`, `[SetFrom<T>]`, `[Key]`, `[ChildrenFrom<T>]`, `[RemovedWith<T>]`); use fluent `IProjectionFor<T>` when mappings need structure or an attribute-free model. Choose reducer code when prior-state branches, calculations or guards read better as code: default new .NET reducers to static `Reduce` on the model, not a mandatory separate class. Follow **cratis-chronicle-read-model** for the ladder and **cratis-chronicle-reducer** for placement/signatures.
|
|
17
|
+
- Preserve admission/ordering guards when converting a reducer, and remove competing self-model builders.
|
|
17
18
|
- **AutoMap is on by default — never call `.AutoMap()`** (matching names map automatically).
|
|
18
19
|
- Projections consume Chronicle **events**, never other read models.
|
|
19
20
|
|
|
@@ -5,16 +5,18 @@ description: Add a Chronicle reducer to a read model when model-bound and fluent
|
|
|
5
5
|
|
|
6
6
|
# Add a Reducer
|
|
7
7
|
|
|
8
|
-
Add
|
|
8
|
+
Add reducer code for a "current state + event → next state" transition that reads better as code. Default new .NET code to a self-reducing model with public static `Reduce` methods; use `IReducerFor<T>` for injected services, replay instance behavior or separation. Invoke the **cratis-chronicle-reducer** skill and follow `.cratis/ai/rules/vertical-slices.md`. For ordinary projections, use the **add-projection** prompt instead.
|
|
9
9
|
|
|
10
10
|
## Confirm first
|
|
11
11
|
|
|
12
|
-
- **
|
|
12
|
+
- The **state-transition rule**, **events** and **read model** shape; whether fold-time services or separation justify an instance reducer.
|
|
13
13
|
|
|
14
14
|
## Key rules
|
|
15
15
|
|
|
16
|
-
-
|
|
16
|
+
- Start with attributes for clear mappings, fluent for structure, reducer code for clearer prior-state branches, calculations or guards — a normal choice, not a last resort.
|
|
17
|
+
- Nominate a plain instance class only when its assembly cannot reference Chronicle; keep the other SDK and Stage contracts separate.
|
|
18
|
+
- Keep `Reduce` and Arc queries on the model record; apply the skill's versioned query-discovery guidance. Remove any competing builder and preserve admission/ordering guards.
|
|
17
19
|
- Handle the **nullable current** state (the first event has no prior state).
|
|
18
|
-
- Keep
|
|
20
|
+
- Keep folds deterministic — no side effects, no reading other read models. Passivity is a separate choice (`[Passive]` on the model); it does not make decision reads admit reducers.
|
|
19
21
|
|
|
20
22
|
Run a clean build afterward. The skill carries the detail; don't duplicate it here.
|
|
@@ -18,7 +18,7 @@ Pick exactly one type per slice folder — determined by what the slice *does*.
|
|
|
18
18
|
| Type | What it does | Contents |
|
|
19
19
|
| --- | --- | --- |
|
|
20
20
|
| **State Change** | Accepts a command, appends events | Command + validator + event(s); optional `[Passive]` for a current read; a rule that must hold under concurrency needs a decision read or constraint (see the `cratis-chronicle-decision-reads` skill, `references/choosing-how-a-rule-holds.md`) |
|
|
21
|
-
| **State View** |
|
|
21
|
+
| **State View** | Builds a queryable read model from events | `[ReadModel]` + projection mappings or reducer code + static query method(s) on the record |
|
|
22
22
|
| **Automation** | Reacts to events, calls external systems / `ICommandPipeline`, or returns follow-up commands/events (including to another stream) | Reactor only |
|
|
23
23
|
| **Translation** | Takes data from outside our own facts (an external system or another service) and records it as our facts | An adapter at the boundary, often a reactor |
|
|
24
24
|
|
|
@@ -30,7 +30,7 @@ Commands are imperative intents (`Register`, `Create`); the slice folder is the
|
|
|
30
30
|
|
|
31
31
|
Tagged **[contract]** (framework-enforced) or **[convention]** (house default). Mechanics and examples live in `vertical-slices.md`.
|
|
32
32
|
|
|
33
|
-
1. **[contract] Model-bound — no controllers.** Commands are `[Command]` records with a public instance `Handle()` (Arc analyzers enforce this); queries are `static` methods on `[ReadModel]` records; projections/constraints/authorization use attributes. Arc generates the HTTP surface.
|
|
33
|
+
1. **[contract] Model-bound — no controllers.** Commands are `[Command]` records with a public instance `Handle()` (Arc analyzers enforce this); queries are `static` methods on `[ReadModel]` records; projections/constraints/authorization use attributes. Arc generates the HTTP surface. For read-model style follow rule 11's ladder; for constraints use `IConstraint` when attributes cannot express the rule.
|
|
34
34
|
2. **[contract] Command validation & data flow.** Put command rejection in `CommandValidator<T>`, global value invariants in `ConceptValidator<T>`, and fetched/computed handler data in **`Provide()`** (runs after validation/authorization; may short-circuit with `ValidationResult.Error` / `Result<TProvided, ValidationResult>`). Keep `Handle()` focused on event construction. For a state-dependent rule that must hold **under concurrency**, enroll a guarded stream decision (`IStreamReads`/`StreamDecision`) or use `[ProtectedDecision]` with an admitted `DecisionRead<T>`; plain injected models remain advisory. Return a typed rejection via `Result<TEvent, ValidationResult>` where needed; the result alone adds no guard. **Throwing from `Provide()`/`Handle()` is an exception (HTTP 500), not a validation rejection** — throw only for genuinely exceptional conditions, never for normal business rejection.
|
|
35
35
|
3. **[contract] Event-source id resolution:** `ICanProvideEventSourceId` first; else the first qualifying property in declaration order — an `EventSourceId`/`EventSourceId<T>`-derived value *or* a `[Key]` property (no priority between them; two candidates is `ARCCHR0002`); else Arc generates one. A value actually used as a Chronicle stream identity derives from `EventSourceId<T>` with the underlying `IComparable` primitive — never `ConceptAs<Guid>` for that stream identity. `NotSet`, `New()`, and primitive→derived-id operators are optional domain/API conveniences, not Chronicle requirements; typed empty/zero values are real specified stream IDs, not `EventSourceId.Unspecified`.
|
|
36
36
|
4. **[contract] Events never carry the event-source id** — it is implicit in the event context.
|
|
@@ -40,7 +40,7 @@ Tagged **[contract]** (framework-enforced) or **[convention]** (house default).
|
|
|
40
40
|
8. **[convention] Every `[EventType]` has an XML `<summary>`** — a Cratis C# documentation convention (not a Chronicle rule); events live in the log forever, so record why they exist.
|
|
41
41
|
9. **[convention] `[ReadModel]` properties carry no default values** except semantically meaningful enum initial states and `[SetValue<T>]`-driven `bool` flags. False defaults hide missing projection wiring.
|
|
42
42
|
10. **[contract] AutoMap is on by default — never call `.AutoMap()`.** Match property names so AutoMap wires them; diverge with `[SetFrom<T>]` / fluent `.Set().To()` only for genuine name differences. Re-enable `.AutoMap()` only inside a scope where it was disabled with `.NoAutoMap()`.
|
|
43
|
-
11. **[contract] Projections consume events and event context — never other read models.**
|
|
43
|
+
11. **[contract] Projections consume events and event context — never other read models.** **[convention]** For application code start with model-bound attributes, use fluent `IProjectionFor<T>` when mappings need structure, and choose reducer code when prior-state branches, calculations or guards read better as code (a normal choice, not a last resort). New .NET reducers default to static `Reduce` on the model; use `IReducerFor<T>` for injected services, replay instance behavior or separation, and nominate a plain instance class only when its assembly cannot reference Chronicle. PDL belongs outside application code. Follow the **cratis-chronicle-read-model** style ladder and **cratis-chronicle-reducer** signatures; preserve admission/ordering guards when converting. This does not change Stage's rendering contract or other SDK reducer contracts.
|
|
44
44
|
12. **[contract] Model-bound query custom paths use `[Path("...")]`** (`PathAttribute`), not ASP.NET `[Route]`. Reserve `[Route]` for controller-based endpoints (which this convention avoids).
|
|
45
45
|
13. **[convention] Cross-slice access is read-only through Chronicle** — inject another slice's read model or reference its events; never instantiate or DI another slice's command/handler/service.
|
|
46
46
|
14. **[contract] Never inject `IEventLog` into `Handle()`** — express appends through return types (`IEnumerable<object>` with `EventForEventSourceId` wrappers for cross-stream). In application reactors, return side-effect events or commands (or use `ICommandPipeline` and inspect the result); don't reach for `IEventLog` directly.
|
|
@@ -336,7 +336,9 @@ These are the building blocks. Each type has a specific role in the vertical sli
|
|
|
336
336
|
| `[ReadModel]` | Marks a record as a model-bound query — define static query methods on the record |
|
|
337
337
|
| `CommandValidator<T>` | FluentValidation validator for commands |
|
|
338
338
|
| `IProjectionFor<T>` | Fluent projection definition — AutoMap is on by default, never call `.AutoMap()` |
|
|
339
|
-
|
|
|
339
|
+
| Self-reducing model | New .NET reducer default: public static `Reduce(event, model? current[, EventContext])`, returns model or `Task<model>` (nullable results allowed); marker-free discovery, no fold-time DI |
|
|
340
|
+
| `IReducerFor<T>` | Separate instance fold for injected services, replay instance behavior or separation from the model |
|
|
341
|
+
| `ChronicleOptions.ExplicitArtifacts.RegisterReducer<T>()` | Nominate a plain instance class only when its assembly cannot reference Chronicle; also accepts self models (see **cratis-chronicle-client-dotnet**, discovery reference) |
|
|
340
342
|
| `IReactor` | Marker interface for side-effect observers — method dispatch by event type parameter |
|
|
341
343
|
| `IConstraint` | Constraint definition — enforced server-side by Chronicle at append time |
|
|
342
344
|
| `AggregateRoot` | Chronicle aggregate root with `Apply()` and `Commit()` |
|
|
@@ -19,9 +19,9 @@ One precise line per load-bearing term, so the same word means the same thing ev
|
|
|
19
19
|
|
|
20
20
|
## Read side
|
|
21
21
|
|
|
22
|
-
- **Read model** —
|
|
23
|
-
- **Projection** — declares how a read model
|
|
24
|
-
- **Reducer** —
|
|
22
|
+
- **Read model** — derived state built from events by a projection or reducer; an optional Arc `[ReadModel]` record exposes static queries, but Chronicle-only models need no query attribute.
|
|
23
|
+
- **Projection** — declares how events build a read model (model-bound attributes, fluent `IProjectionFor<T>`, or PDL outside application code); pure events→state, no side effects, never reads other read models.
|
|
24
|
+
- **Reducer** — a "current state + event → next state" builder when transitions read better as code; new .NET code defaults to static `Reduce(event, model? current[, EventContext])` on a self-reducing model (no marker), with `IReducerFor<T>` for DI/replay instance behavior/separation and nominated plain classes when their assembly cannot reference Chronicle. See **cratis-chronicle-reducer**; other SDKs retain their own contracts.
|
|
25
25
|
- **Reactor** — `IReactor`; observes events and produces **side effects** (notifications, commands, follow-up events). The "if this then that".
|
|
26
26
|
- **Observer** — Chronicle's umbrella for anything consuming an event sequence (projection, reducer, reactor); carries subscription / replay / **quarantine** state. Projection replay and catch-up each walk the sequence in one globally ordered job step; a new catch-up failure stops that step. Full replay is inactive and completion does not resume a quarantined observer (Chronicle v19.50.1, `Documentation/concepts/observers.mdx`, `Observation/Jobs/{CatchUpObserver,ReplayObserver}.cs` under `Source/Kernel/Core/`).
|
|
27
27
|
- **Sink** — where a read model is persisted (MongoDB, EF Core).
|
|
@@ -248,7 +248,7 @@ public record AuthorRegistered(AuthorName Name);
|
|
|
248
248
|
|
|
249
249
|
## Read Models and Queries
|
|
250
250
|
|
|
251
|
-
**[contract]** `[ReadModel]` records expose queries as `public static` methods; dependencies are plain method parameters (no `[FromServices]`).
|
|
251
|
+
**[contract]** `[ReadModel]` records expose queries as `public static` methods; dependencies are plain method parameters (no `[FromServices]`). For application code, start with model-bound mappings, use fluent when the definition needs structure, and choose reducer code when transitions read better as code. For step-by-step creation, invoke the **cratis-chronicle-read-model** skill.
|
|
252
252
|
|
|
253
253
|
Use `[ReadModel(RequireQueryAttribute = true)]` with `[Query]` on intended
|
|
254
254
|
endpoints when public folds/helpers exist (ARC0026/ARCCHR0019). `[Query]` alone
|
|
@@ -324,8 +324,11 @@ evaluate reconstruction frequency, history length, consistency, and security.
|
|
|
324
324
|
Projections build read models from **events** (never from other read models). Use the ladder — for adding one to an existing model, invoke the **cratis-chronicle-projection** skill:
|
|
325
325
|
|
|
326
326
|
1. **Model-bound attributes** on the `[ReadModel]`: `[FromEvent<T>]`, `[SetFrom<T>]`, `[SetFromContext<T>]`, `[ChildrenFrom<T>]`, `[RemovedWith<T>]`, `[Nested]`, `[ClearWith<T>]`, counters, `[FromAll]`.
|
|
327
|
-
2. **Fluent `IProjectionFor<T>`**
|
|
328
|
-
3. **Reducer
|
|
327
|
+
2. **Fluent `IProjectionFor<T>`** when mappings need structure or the contract should stay attribute-free: joins, composite/constant keys, parent-key extraction, context mapping, `.NotRewindable()`, or supported conditional setters. Declarative metadata only — no DI side effects, no imperative `Define()` body, builder lambdas are member access only.
|
|
328
|
+
3. **Reducer code** for clearer "current state + event → next state" logic — prior-state branches, calculations and guards. A normal choice, not a last resort. Default new .NET reducers to **self-reducing models** with public static `Reduce(event, model? current[, EventContext])`, returning model or `Task<model>` (including nullable results), without a marker. Use separate `IReducerFor<T>` for fold-time DI, replay instance behavior or separation.
|
|
329
|
+
4. **Nominated plain instance class** only when its assembly cannot reference Chronicle; nominate through `ChronicleOptions.ExplicitArtifacts` before creating stores. Use **PDL** for definitions authored outside application code, not as the code-first default.
|
|
330
|
+
|
|
331
|
+
For self models, keep `[ReadModel]`, static `Reduce` methods and queries on one record. Before Arc 22.90.0, use `[ReadModel(RequireQueryAttribute = true)]` and `[Query]`; from Arc 22.90.0, Arc excludes methods taking the model itself from query discovery and Arc.Chronicle claims self models for command injection. Complete marker-free shapes become reducers on upgrade; a competing builder fails with `AmbiguousReadModelBuilder`. Preserve admission/ordering guards when converting and remove the previous builder. See **cratis-chronicle-reducer** for exact signatures, hooks and limits. `[Passive]` belongs on the model; it gives fresh reads, not a concurrency guard — decision reads refuse reducers. Self reduction is .NET-only (Cratis/Chronicle#4851); this does not claim Stage renders it.
|
|
329
332
|
|
|
330
333
|
- **[contract] AutoMap is on by default — never call `.AutoMap()`.** Match property names so AutoMap wires them; diverge with `[SetFrom<T>]` / `.Set().To()` only for genuine name differences. Re-enable `.AutoMap()` only inside a scope disabled with `.NoAutoMap()`.
|
|
331
334
|
- ⚠️ **AutoMap runs per *event* across every event the projection references — it does not defer to your explicit setters.** A property sourced with `[SetFrom<A>]` can still be silently overwritten when some *other* referenced event `B` happens to carry an identically named property (AutoMap wires `B`'s value on top). Fence the property with property-level **`[NoAutoMap]`** (which pairs with the `[SetFrom]`, not replaces it) so only your explicit setter writes it. `[SetFrom]` does **not** imply this — leaving AutoMap on is what allows the common create-then-rename pattern (a later event updating a property by name-match). No colliding event property name means no `[NoAutoMap]` needed. (An event subscribed only via an aggregate like `[Count]` doesn't auto-map its other properties, so it can't collide.) The analyzer **`CHR0025`** surfaces this collision as an *informational* heads-up (not a warning, because either resolution — add `[NoAutoMap]`, or accept the update — can be correct).
|
|
@@ -21,7 +21,8 @@ from v19.50.0; earlier release numbers identify feature availability.
|
|
|
21
21
|
|
|
22
22
|
| Package | Version | Purpose |
|
|
23
23
|
| --- | --- | --- |
|
|
24
|
-
| `Cratis.Chronicle` | `19.50.1` | `ChronicleClient`, `IEventStore`, `[EventType]`, observers |
|
|
24
|
+
| `Cratis.Chronicle` | `19.50.1` | `ChronicleClient`, `IEventStore`, `[EventType]`, existing observers |
|
|
25
|
+
| `Cratis.Chronicle` | `19.59.4` | Reducer discovery/nomination at tag `v19.59.4`: `Source/Clients/DotNET/DefaultClientArtifactsProvider.cs`, `Reducers/{SelfReducerMethods,RegisteredReducerReadModel,ReducerCatalog}.cs`, `Registrations/ExplicitArtifacts.Types.cs` |
|
|
25
26
|
| `Cratis.Chronicle.Connections` | `19.50.1` | `ChronicleConnectionString`, connection lifecycle |
|
|
26
27
|
| `Cratis.Chronicle.AspNetCore` | `19.50.1` | ASP.NET Core wiring, header/subdomain namespace resolvers |
|
|
27
28
|
| `Cratis.Chronicle.Testing` | `19.50.1` | in-process scenarios |
|
|
@@ -323,46 +324,28 @@ results live on the unit of work.
|
|
|
323
324
|
| Artifact | Shape | Source |
|
|
324
325
|
| --- | --- | --- |
|
|
325
326
|
| Reactor | marker `IReactor` (empty interface), `[Reactor]` optional | `Reactors/IReactor.cs:9`, `Reactors/ReactorAttribute.cs:14` |
|
|
326
|
-
|
|
|
327
|
+
| Self model (.NET reducer default) | public static `Reduce(event, model? current[, EventContext])`, returns model or `Task<model>` (nullable results allowed); no marker | `Reducers/SelfReducerMethods.cs` |
|
|
328
|
+
| Separate reducer | `IReducerFor<TReadModel>` for DI, replay instance behavior or separation | `Reducers/IReducerFor.cs:10` |
|
|
329
|
+
| Plain reducer | instance handlers infer one model; nomination required | `Reducers/RegisteredReducerReadModel.cs` |
|
|
327
330
|
| Projection | `IProjectionFor<TReadModel>` with `Define(IProjectionBuilderFor<TReadModel>)` | `Projections/IProjectionFor.cs:10-17` |
|
|
328
331
|
| Model-bound projection | attributes on the read model | `Projections/ModelBound/` |
|
|
329
332
|
| Read model reactor | marker `IReadModelReactor`, methods `Added`/`Modified`/`Removed` | `ReadModels/IReadModelReactor.cs:10-18` |
|
|
330
333
|
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
return may be `Task`, `void`, or a side-effect event type.
|
|
335
|
-
|
|
336
|
-
```csharp
|
|
337
|
-
using Cratis.Chronicle.Events;
|
|
338
|
-
using Cratis.Chronicle.Reactors;
|
|
339
|
-
|
|
340
|
-
public class <ReactorName>(<IDependency> <dependency>) : IReactor
|
|
341
|
-
{
|
|
342
|
-
public async Task <AnyMethodName>(<EventName> @event, EventContext context)
|
|
343
|
-
{
|
|
344
|
-
await <dependency>.<DoSomething>(context.EventSourceId, @event.<Property>);
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
```
|
|
348
|
-
|
|
349
|
-
> **There is no `[Observer]` attribute and no `IObserver` client artifact.**
|
|
350
|
-
> "Observer" is the kernel's umbrella term for a projection, reducer, or reactor;
|
|
351
|
-
> it is not something you write. `Source/Clients/DotNET/Observation/` holds
|
|
352
|
-
> `ObserverId`, `ObserverRunningState`, and failed-partition types only.
|
|
353
|
-
|
|
354
|
-
Read models are queried through `eventStore.ReadModels`
|
|
355
|
-
(`Source/Clients/DotNET/ReadModels/IReadModels.cs`):
|
|
356
|
-
`GetInstanceById<TReadModel>(ReadModelKey, ReadModelSessionId?)` (`:38`),
|
|
357
|
-
`GetInstances<TReadModel>(EventCount?)` (`:55`),
|
|
358
|
-
`GetSnapshotsById<TReadModel>` (`:63`),
|
|
359
|
-
`IObservable<ReadModelChangeset<TReadModel>> Watch<TReadModel>()` (`:70`).
|
|
334
|
+
Read [observer handlers and reads](references/discovery.md#observer-handlers-and-reads)
|
|
335
|
+
for reactor dispatch, an instance-handler example and `eventStore.ReadModels` APIs.
|
|
336
|
+
There is no `[Observer]` attribute or `IObserver` client artifact.
|
|
360
337
|
|
|
361
338
|
## Discovery
|
|
362
339
|
|
|
363
|
-
|
|
340
|
+
Default scanning finds marked/interface artifacts and complete self shapes.
|
|
341
|
+
Plain instance reducers require nomination before store creation. Self models
|
|
342
|
+
need no activation or fold-time DI. See the [read-model ladder](../cratis-chronicle-read-model/SKILL.md#step-3--choose-a-projection-or-a-reducer)
|
|
343
|
+
and [reducer contract](../cratis-chronicle-reducer/SKILL.md) for placement,
|
|
344
|
+
upgrades, warnings and conflicts. Self reduction is
|
|
345
|
+
.NET-only (Cratis/Chronicle#4851), not an other-client or Stage contract.
|
|
364
346
|
|
|
365
|
-
Read [
|
|
347
|
+
Read [discovery and nomination](references/discovery.md) for missing artifacts,
|
|
348
|
+
plain-class registration or `AutoDiscoverAndRegister = false`.
|
|
366
349
|
|
|
367
350
|
## Common pitfalls
|
|
368
351
|
|
|
@@ -1,12 +1,21 @@
|
|
|
1
|
+
## Contents
|
|
2
|
+
|
|
3
|
+
- Discovery and explicit registration
|
|
4
|
+
- Plain-class reducer nomination
|
|
5
|
+
- Manual discovery and runtime registration
|
|
6
|
+
- Observer handlers and reads
|
|
7
|
+
|
|
1
8
|
<!-- Copyright (c) Cratis. All rights reserved. -->
|
|
2
9
|
<!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
|
|
3
10
|
|
|
4
11
|
## Discovery and explicit registration
|
|
5
12
|
|
|
6
|
-
|
|
13
|
+
Existing projection/reactor APIs were verified at **Cratis/Chronicle v19.50.0**.
|
|
14
|
+
Self and nominated reducer discovery were verified at **v19.59.4**:
|
|
7
15
|
`Source/Clients/DotNET/DefaultClientArtifactsProvider.cs`,
|
|
8
|
-
`
|
|
9
|
-
`
|
|
16
|
+
`Reducers/{SelfReducerMethods,RegisteredReducerReadModel,ReducerCatalog}.cs`,
|
|
17
|
+
`ReadModels/ReadModelBuilderOwnership.cs`,
|
|
18
|
+
`Registrations/{ExplicitArtifacts,ExplicitArtifacts.Types}.cs`.
|
|
10
19
|
|
|
11
20
|
`DefaultClientArtifactsProvider.Default` scans project- and package-referenced
|
|
12
21
|
assemblies. Discovered artifacts include:
|
|
@@ -17,7 +26,8 @@ assemblies. Discovered artifacts include:
|
|
|
17
26
|
| Projections | one `IProjectionFor<T>` per class, or model-bound projection annotations |
|
|
18
27
|
| Reactors | non-generic `IReactor` |
|
|
19
28
|
| Read-model reactors | non-generic `IReadModelReactor` |
|
|
20
|
-
|
|
|
29
|
+
| Separate reducers | non-generic class implementing one `IReducerFor<T>` |
|
|
30
|
+
| Self-reducing models | concrete non-generic non-`IReducer` class with public static non-generic `Reduce(event, model? current[, EventContext])`, returning model or `Task<model>`, including nullable results |
|
|
21
31
|
| Event source definitions | `IEventSource` |
|
|
22
32
|
| Constraints | `IConstraint`, plus `[Unique]`, `[RemoveConstraint]`, `[ClosesStream]` event declarations |
|
|
23
33
|
| Seeds / migrations | `ICanSeedEvents`, `IEventTypeMigrationFor<T>` |
|
|
@@ -27,20 +37,95 @@ Multiple projection or reducer targets in one class fail discovery with
|
|
|
27
37
|
`TypeImplementsMultipleProjectionInterfaces` / `TypeMustImplementOnlyOneReducer`
|
|
28
38
|
(analyzer CHR0057). They are not silently flattened into independent artifacts.
|
|
29
39
|
|
|
30
|
-
|
|
40
|
+
Complete self shapes are marker-free discovery signals (.NET-only since
|
|
41
|
+
19.58.0). Existing static helpers can therefore become reducers on upgrade.
|
|
42
|
+
No model is activated, and `Reduce` cannot take injected services. Static near
|
|
43
|
+
misses whose current/result refers to the model warn (CHR0058) and are skipped;
|
|
44
|
+
explicit nomination rejects them. Once a valid shape exists, malformed siblings
|
|
45
|
+
and hooks fail. A self model with another builder in the same catalog throws
|
|
46
|
+
`AmbiguousReadModelBuilder`. Configuration alone (`[Passive]`, `[Reducer]`,
|
|
47
|
+
filters, sequence selection) is not projection ownership. See the
|
|
48
|
+
[reducer skill](../../cratis-chronicle-reducer/SKILL.md) for selection and hooks.
|
|
49
|
+
|
|
50
|
+
Configure `ChronicleOptions.ExplicitArtifacts` **before creating stores**:
|
|
31
51
|
`RegisterProjection<TReadModel>(define, id)`, `RegisterReadModel<TReadModel>()`,
|
|
32
52
|
`RegisterReactor(id, builder)`. These participate in every normal registration
|
|
33
|
-
pass, including reconnects.
|
|
53
|
+
pass, including reconnects. Each store captures a snapshot at construction;
|
|
54
|
+
later options edits affect only subsequently created stores. For an existing store, use
|
|
34
55
|
`IProjections.Register<TReadModel>(define, id)` or `Register<TReadModel>()`,
|
|
35
56
|
`IReactors.Define/Register(id, builder)`, and the family-specific event type,
|
|
36
57
|
constraint, reducer and read-model registration APIs. Fluent reactors use typed
|
|
37
58
|
`On<TEvent>` handlers or catch-all `Subscribe`.
|
|
38
59
|
|
|
60
|
+
## Plain-class reducer nomination
|
|
61
|
+
|
|
62
|
+
Only nominate a plain instance reducer when its assembly cannot reference
|
|
63
|
+
Chronicle; new application reducers normally keep static transitions on the
|
|
64
|
+
model, or use `IReducerFor<T>` for DI/replay instance behavior/separation.
|
|
65
|
+
Nomination infers exactly one model from supported instance
|
|
66
|
+
`(event, model? current[, EventContext])` handlers against registered events.
|
|
67
|
+
Names do not dispatch; public/non-public instance methods are scanned. Nullable
|
|
68
|
+
or nullable-oblivious current is accepted; returns are model, `Task<model>`
|
|
69
|
+
(including nullable results) or classic bare `Task` (which leaves absent state).
|
|
70
|
+
Nomination does not relax validation or discover arbitrary plain classes.
|
|
71
|
+
|
|
72
|
+
```csharp
|
|
73
|
+
var options = new ChronicleOptions();
|
|
74
|
+
options.ExplicitArtifacts.RegisterReducer<PlainBalanceReducer>();
|
|
75
|
+
// Runtime-type equivalent; use one, not both:
|
|
76
|
+
// options.ExplicitArtifacts.RegisterReducer(typeof(PlainBalanceReducer));
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Import `Cratis.Chronicle` for options. Optional `ReducerId` configures identity.
|
|
80
|
+
The same APIs accept a self model: `RegisterReducer<AccountBalance>()` or
|
|
81
|
+
`RegisterReducer(typeof(AccountBalance))`; there is no special self API.
|
|
82
|
+
Register events with `[EventType]` or `RegisterEventType<T>()`: assembly
|
|
83
|
+
membership alone does not make an event registered. Equal explicit/discovered
|
|
84
|
+
declarations coalesce; incompatible identities fail, rather than overriding.
|
|
85
|
+
|
|
86
|
+
## Manual discovery and runtime registration
|
|
87
|
+
|
|
39
88
|
Runtime reactors also support `IReactors.Register(id, configure, handle)` and
|
|
40
89
|
`Unregister(id)`. Use an explicit stable id for side effects. Variant read models
|
|
41
90
|
cannot be registered explicitly (`VariantReadModelsCannotBeRegisteredExplicitly`).
|
|
42
91
|
|
|
43
92
|
`AutoDiscoverAndRegister = false` disables the automatic pass; owning explicit
|
|
44
|
-
registrations then also means
|
|
93
|
+
registrations then also means calling `DiscoverAll()` to apply recipes,
|
|
94
|
+
`RegisterAll()` when connected, and owning registration/subscription waits.
|
|
95
|
+
Reconnect reuses the captured recipes; `DiscoverAll()` can refresh discovery
|
|
96
|
+
without adopting later options edits.
|
|
45
97
|
Inspect `IEventStore.Discovery` and startup logs before guessing why an artifact
|
|
46
98
|
is missing.
|
|
99
|
+
|
|
100
|
+
## Observer handlers and reads
|
|
101
|
+
|
|
102
|
+
This existing handler/read surface was verified at **v19.50.1**.
|
|
103
|
+
**A reactor handler is found by its first parameter's type**, and further
|
|
104
|
+
parameters are resolved as dependencies — `EventContext`, a read model, a service
|
|
105
|
+
(`Source/Clients/DotNET/Reactors/EventHandlerMethods.cs:21-46`, `:89-103`). The
|
|
106
|
+
return may be `Task`, `void`, or a side-effect event type.
|
|
107
|
+
|
|
108
|
+
```csharp
|
|
109
|
+
using Cratis.Chronicle.Events;
|
|
110
|
+
using Cratis.Chronicle.Reactors;
|
|
111
|
+
|
|
112
|
+
public class <ReactorName>(<IDependency> <dependency>) : IReactor
|
|
113
|
+
{
|
|
114
|
+
public async Task <AnyMethodName>(<EventName> @event, EventContext context)
|
|
115
|
+
{
|
|
116
|
+
await <dependency>.<DoSomething>(context.EventSourceId, @event.<Property>);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
**There is no `[Observer]` attribute and no `IObserver` client artifact.**
|
|
122
|
+
"Observer" is the kernel's umbrella term for a projection, reducer, or reactor;
|
|
123
|
+
it is not something you write. `Source/Clients/DotNET/Observation/` holds
|
|
124
|
+
`ObserverId`, `ObserverRunningState`, and failed-partition types only.
|
|
125
|
+
|
|
126
|
+
Read models are queried through `eventStore.ReadModels`
|
|
127
|
+
(`Source/Clients/DotNET/ReadModels/IReadModels.cs`):
|
|
128
|
+
`GetInstanceById<TReadModel>(ReadModelKey, ReadModelSessionId?)` (`:38`),
|
|
129
|
+
`GetInstances<TReadModel>(EventCount?)` (`:55`),
|
|
130
|
+
`GetSnapshotsById<TReadModel>` (`:63`),
|
|
131
|
+
`IObservable<ReadModelChangeset<TReadModel>> Watch<TReadModel>()` (`:70`).
|
|
@@ -8,8 +8,12 @@ license: MIT
|
|
|
8
8
|
|
|
9
9
|
A projection consumes **events** and produces read-model state. It is pure: no
|
|
10
10
|
side effects, and it never reads another read model. Prefer model-bound
|
|
11
|
-
attributes on the read model;
|
|
12
|
-
|
|
11
|
+
attributes on the read model; use the fluent builder when mappings need
|
|
12
|
+
structure or the model should stay attribute-free; choose reducer code when
|
|
13
|
+
state transitions read better as code. Follow the
|
|
14
|
+
[read-model style ladder](../cratis-chronicle-read-model/SKILL.md#step-3--choose-a-projection-or-a-reducer):
|
|
15
|
+
a self-reducing model is the new .NET reducer default, not a mandatory separate
|
|
16
|
+
class. See [reducers](../cratis-chronicle-reducer/SKILL.md) for that contract.
|
|
13
17
|
|
|
14
18
|
## Verified product sources
|
|
15
19
|
|
|
@@ -17,7 +21,8 @@ This skill is verified against this exact source:
|
|
|
17
21
|
|
|
18
22
|
| Package | Version | Purpose |
|
|
19
23
|
| --- | --- | --- |
|
|
20
|
-
| `Cratis.Chronicle` | `19.50.1` |
|
|
24
|
+
| `Cratis.Chronicle` | `19.50.1` | Existing projections, model-bound attributes, keys and event-sequence APIs |
|
|
25
|
+
| `Cratis.Chronicle` | `19.59.4` | Self-model builder conflicts: `Source/Clients/DotNET/ReadModels/ReadModelBuilderOwnership.cs`, `Reducers/SelfReducerMethods.cs` at tag `v19.59.4` |
|
|
21
26
|
|
|
22
27
|
Reverify product sources before claiming support for another version.
|
|
23
28
|
|
|
@@ -70,10 +75,10 @@ targets. Two things there are worth knowing before you write anything:
|
|
|
70
75
|
`[FromEvent<T>]` is an **object-initializer property**, never a constructor
|
|
71
76
|
argument: `[Count<TEvent>(ConstantKey = "<key>")]`.
|
|
72
77
|
|
|
73
|
-
## Fluent projections —
|
|
78
|
+
## Fluent projections — structured mappings
|
|
74
79
|
|
|
75
|
-
Use `Cratis.Chronicle.Projections.IProjectionFor<TReadModel>` when the
|
|
76
|
-
|
|
80
|
+
Use `Cratis.Chronicle.Projections.IProjectionFor<TReadModel>` when the mapping
|
|
81
|
+
needs structure or an attribute-free model — for example when two events feed one child collection
|
|
77
82
|
through different key properties.
|
|
78
83
|
|
|
79
84
|
```csharp
|
|
@@ -92,7 +97,7 @@ public class <ReadModelName>Projection : IProjectionFor<<ReadModelName>>
|
|
|
92
97
|
the interface** — do not add one. Use `[Projection(id: "<id>")]` when the
|
|
93
98
|
identity must be explicit.
|
|
94
99
|
|
|
95
|
-
When
|
|
100
|
+
When you use the fluent builder, read [references/fluent-builder.md](references/fluent-builder.md) for the real
|
|
96
101
|
member list. The trap that costs the most time: **`UsingKey`, `UsingParentKey`,
|
|
97
102
|
`UsingCompositeKey`, and `UsingConstantKey` are not on the projection builder.**
|
|
98
103
|
They live on the per-event builder that `From<TEvent>` hands to your callback.
|
|
@@ -108,7 +113,9 @@ one collection. Preserve security/compliance boundaries when choosing the shape.
|
|
|
108
113
|
|
|
109
114
|
When replacing a reducer, preserve creation/admission and late-event guards;
|
|
110
115
|
an unconditional `[SetValue<T>]` is not equivalent to guarded state transition
|
|
111
|
-
code.
|
|
116
|
+
code. A self model cannot also have a competing projection in the same catalog
|
|
117
|
+
(`AmbiguousReadModelBuilder`); remove the old builder when switching. See the
|
|
118
|
+
reducer skill's conversion guidance. Evaluate variants below when
|
|
112
119
|
shapes diverge; do not mandate them for every status field.
|
|
113
120
|
|
|
114
121
|
## Joins are on events, never on read models
|
|
@@ -297,8 +304,9 @@ projection spans streams.
|
|
|
297
304
|
|
|
298
305
|
## Verify
|
|
299
306
|
|
|
300
|
-
-
|
|
301
|
-
fluent
|
|
307
|
+
- The style follows the read-model ladder: attributes for clear mappings,
|
|
308
|
+
fluent for structure, reducer code for clearer state transitions; conversion
|
|
309
|
+
preserves guards and leaves no competing self-model builder.
|
|
302
310
|
- `.AutoMap()` is called only inside a `.NoAutoMap()` scope.
|
|
303
311
|
- Every join is on an event type; CHR0042 overlaps are deliberate.
|
|
304
312
|
- One class implements only one `IProjectionFor<T>` (CHR0057).
|
|
@@ -23,7 +23,8 @@ This skill is verified against these exact sources:
|
|
|
23
23
|
|
|
24
24
|
| Package | Version | Purpose |
|
|
25
25
|
| --- | --- | --- |
|
|
26
|
-
| `Cratis.Chronicle` | `18.3.0` |
|
|
26
|
+
| `Cratis.Chronicle` | `18.3.0` | Existing event, key and read-model APIs |
|
|
27
|
+
| `Cratis.Chronicle` | `19.59.4` | Style/discovery: `Source/Clients/DotNET/Reducers/{SelfReducerMethods,RegisteredReducerReadModel}.cs`, `ReadModels/ReadModelBuilderOwnership.cs`, `DefaultClientArtifactsProvider.cs` at tag `v19.59.4` |
|
|
27
28
|
| `Cratis.Arc.Core` | `22.75.0` | `Cratis.Arc.Queries.ModelBound.ReadModelAttribute` and `PathAttribute` |
|
|
28
29
|
| `Cratis.Arc.MongoDB` | `22.75.0` | the `Observe` family of `IMongoCollection<T>` extensions |
|
|
29
30
|
|
|
@@ -94,27 +95,52 @@ and [query cost and composition](references/queries.md#cost-and-composition).
|
|
|
94
95
|
|
|
95
96
|
## Step 3 — Choose a projection or a reducer
|
|
96
97
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
state
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
98
|
+
For application code, work down this ladder:
|
|
99
|
+
|
|
100
|
+
1. **Model-bound attributes** when the mapping reads clearly on the model.
|
|
101
|
+
2. **Fluent `IProjectionFor<T>`** when the definition needs structure or an
|
|
102
|
+
attribute-free contract. Counters, joins, children and composite keys remain
|
|
103
|
+
projection features; fluent lambdas are not arbitrary per-event code.
|
|
104
|
+
3. **Reducer code** when branching on prior state, calculations or guards read
|
|
105
|
+
better as state transitions. A reducer is a normal choice, not a last resort.
|
|
106
|
+
For new .NET code default to a **self-reducing model**: public static
|
|
107
|
+
`Reduce(TEvent @event, TSelf? current[, EventContext context])` on the model,
|
|
108
|
+
returning `TSelf`/`TSelf?` or `Task` of it. No marker or model activation.
|
|
109
|
+
Use a separate **`IReducerFor<T>`** when the fold needs injected services,
|
|
110
|
+
replay-time instance state or separation from the model.
|
|
111
|
+
4. **Nominated plain instance class** only when the contract/reducer assembly
|
|
112
|
+
cannot reference Chronicle; configure `ChronicleOptions.ExplicitArtifacts`
|
|
113
|
+
at the composition root before creating stores.
|
|
114
|
+
|
|
115
|
+
**PDL** is for definitions authored outside application code (Workbench,
|
|
116
|
+
Screenplay, ad-hoc queries), not the code-first default. This ladder does not
|
|
117
|
+
claim Stage renders static self reducers. The self form is .NET-only
|
|
118
|
+
(Cratis/Chronicle#4851); other SDKs keep their own reducer contracts.
|
|
119
|
+
|
|
120
|
+
Default discovery finds projections, interface reducers and complete self shapes.
|
|
121
|
+
Explicit registration remains available, and plain instance reducers require
|
|
122
|
+
nomination; see [discovery](../cratis-chronicle-client-dotnet/references/discovery.md).
|
|
123
|
+
An existing complete static shape becomes a reducer on upgrade without adding a
|
|
124
|
+
marker. Near misses warn (CHR0058). A self model and a competing projection or
|
|
125
|
+
reducer in one catalog fail with `AmbiguousReadModelBuilder`; remove the old
|
|
126
|
+
builder when switching and verify storage/replay separately from output equality.
|
|
127
|
+
|
|
128
|
+
Read [projection behavior](../cratis-chronicle-projection/SKILL.md) for mappings
|
|
129
|
+
and [reducers](../cratis-chronicle-reducer/SKILL.md) for complete signatures,
|
|
130
|
+
null deletion, replay hooks and preserving admission/ordering guards. Reducers
|
|
131
|
+
are source-keyed, have no native joins and are refused by decision reads.
|
|
112
132
|
|
|
113
133
|
## Step 4 — Add a query surface, if the model is read from outside
|
|
114
134
|
|
|
115
135
|
Queries are **static** methods on the read-model record, discovered by Arc.
|
|
116
136
|
Marking the record with `[ReadModel]` from `Cratis.Arc.Queries.ModelBound` is
|
|
117
|
-
what gives it that surface.
|
|
137
|
+
what gives it that surface. For a self-reducing model, put its `Reduce` methods
|
|
138
|
+
and queries on this same record. Before Arc 22.90.0, use
|
|
139
|
+
`[ReadModel(RequireQueryAttribute = true)]` plus `[Query]` on intended queries to
|
|
140
|
+
avoid exposing folds. From Arc 22.90.0, Arc excludes methods taking the
|
|
141
|
+
model itself from query discovery, and Arc.Chronicle claims self models for
|
|
142
|
+
command injection. See the existing
|
|
143
|
+
[explicit query-discovery guidance](references/queries.md#discovery-rules).
|
|
118
144
|
|
|
119
145
|
```csharp
|
|
120
146
|
using System.Reactive.Subjects;
|
|
@@ -206,7 +232,7 @@ This access distinction was checked against Chronicle **v19.31.2**
|
|
|
206
232
|
|
|
207
233
|
`[Passive]` on its own does **not** make a read model a projection. It is
|
|
208
234
|
deliberately excluded from the annotations that do; it changes how an existing
|
|
209
|
-
projection is
|
|
235
|
+
projection or reducer is read; it is not a builder by itself.
|
|
210
236
|
|
|
211
237
|
## Step 6 — Build and verify
|
|
212
238
|
|
|
@@ -236,6 +262,8 @@ spans streams.
|
|
|
236
262
|
`EventSourceId<T>` value.
|
|
237
263
|
- No reserved compliance-subject property name is used.
|
|
238
264
|
- Read-model properties carry no defaults that could hide unwired projection.
|
|
265
|
+
- The style follows the ladder; a self model has no competing builder, and Arc
|
|
266
|
+
folds are excluded from query exposure for the consuming version.
|
|
239
267
|
- Query methods are `static` and declare `ISubject<...>` rather than a concrete
|
|
240
268
|
subject type.
|
|
241
269
|
- A direct `GetInstanceById` result is checked for absence before use.
|
|
@@ -11,7 +11,8 @@ against a sequence of events. No Chronicle server, no database, no network — t
|
|
|
11
11
|
events go in, the materialized instance comes out.
|
|
12
12
|
|
|
13
13
|
Pure reducer decisions use `Specification` plus a direct method call by
|
|
14
|
-
default, with the event and current state supplied explicitly
|
|
14
|
+
default, with the event and current state supplied explicitly (for a self model,
|
|
15
|
+
`Model.Reduce(@event, current)`). Add
|
|
15
16
|
`ReadModelScenario<TReadModel>` only where declarative projection behavior,
|
|
16
17
|
event dispatch, filtering, metadata or read-model wiring contribute proof.
|
|
17
18
|
|
|
@@ -22,10 +23,11 @@ is no separate `When`: seeding the events is what makes the projection run.
|
|
|
22
23
|
|
|
23
24
|
| Package | Version | Purpose |
|
|
24
25
|
| --- | --- | --- |
|
|
25
|
-
| `Cratis.Chronicle.Testing` | `19.
|
|
26
|
+
| `Cratis.Chronicle.Testing` | `19.59.4` | `Source/Clients/Testing/ReadModels/ReadModelScenario.cs` at tag `v19.59.4`: scenario selection, self and nominated reducers |
|
|
27
|
+
| `Cratis.Chronicle` | `19.59.4` | `Source/Clients/DotNET/Reducers/{SelfReducerMethods,RegisteredReducerReadModel}.cs`, `ReadModels/ReadModelBuilderOwnership.cs` at tag `v19.59.4`: supported forms and ownership |
|
|
26
28
|
| `Cratis.Specifications.XUnit` | `4.x` | The `Specification` base and the `ShouldXxx` assertions |
|
|
27
29
|
|
|
28
|
-
Source: `Source/Clients/Testing/ReadModels/` at **Cratis/Chronicle v19.
|
|
30
|
+
Source: `Source/Clients/Testing/ReadModels/` at **Cratis/Chronicle v19.59.4**.
|
|
29
31
|
|
|
30
32
|
```bash
|
|
31
33
|
dotnet add package Cratis.Chronicle.Testing
|
|
@@ -87,7 +89,11 @@ Scenarios implement `IDisposable`; call `_scenario.Dispose()` in `Destroy()`.
|
|
|
87
89
|
and wins over discovery, **including a discovered reducer**. Per-run `Defaults`
|
|
88
90
|
can take a client artifacts provider, service provider and options;
|
|
89
91
|
`InMemoryClientArtifactsProvider` and `ChronicleOptions.ExplicitArtifacts` let a
|
|
90
|
-
specification isolate registrations without global discovery.
|
|
92
|
+
specification isolate registrations without global discovery. Nominate a plain
|
|
93
|
+
instance reducer with `options.ExplicitArtifacts.RegisterReducer<PlainReducer>()`
|
|
94
|
+
before constructing per-run `Defaults(artifacts, serviceProvider, options)`.
|
|
95
|
+
The same API accepts a self model; default discovery needs no marker. Do not
|
|
96
|
+
mutate `Defaults.Instance` across independent runs.
|
|
91
97
|
|
|
92
98
|
## Step 2 — Seed the events
|
|
93
99
|
|
|
@@ -143,16 +149,28 @@ specific reason in the skip message.
|
|
|
143
149
|
|
|
144
150
|
## Step 4 — Know what the scenario picked
|
|
145
151
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
1.
|
|
149
|
-
2. A **
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
152
|
+
`WithProjection` overrides discovery, including a reducer. Otherwise:
|
|
153
|
+
|
|
154
|
+
1. An **explicit projection recipe** for `TReadModel` suppresses reducer selection.
|
|
155
|
+
2. A **registered reducer handler** targeting it: a self-reducing model, a
|
|
156
|
+
separate `IReducerFor<TReadModel>`, or an explicitly nominated plain instance
|
|
157
|
+
class. The scenario uses the store's handler catalog, not its own interface
|
|
158
|
+
scan. Self signatures and registered event membership still matter.
|
|
159
|
+
3. A **fluent projection** implementing `IProjectionFor<TReadModel>`.
|
|
160
|
+
4. **Model-bound attributes** directly on `TReadModel`, then the matching
|
|
161
|
+
model-bound entry in the artifacts provider.
|
|
162
|
+
|
|
163
|
+
If no handler exists, processing throws `NoReadModelHandlerFound`. Classic
|
|
164
|
+
reducer precedence does not authorize competing self-model builders: the store
|
|
165
|
+
rejects those with `AmbiguousReadModelBuilder`. An inline scenario override can
|
|
166
|
+
exercise a different path than production; do not mistake it for registration
|
|
167
|
+
proof. See [reducers](../cratis-chronicle-reducer/SKILL.md) for signatures and
|
|
168
|
+
static direct-call/scenario examples.
|
|
169
|
+
|
|
170
|
+
For every reducer form, cover empty history, first-event null current, guarded
|
|
171
|
+
branches, deletion and recreation. Scenarios substitute storage, observer
|
|
172
|
+
lifecycle and compliance; they do not prove real-kernel registration, replay,
|
|
173
|
+
transport, encryption, erasure or migration.
|
|
156
174
|
|
|
157
175
|
For stricter runs, `WithStrictEventSubscription()` and `WithStrictFidelity()`
|
|
158
176
|
turn silent mismatches into failures.
|
|
@@ -7,9 +7,18 @@ license: MIT
|
|
|
7
7
|
# Chronicle reducers
|
|
8
8
|
|
|
9
9
|
A reducer builds a read model as "current state plus event produces next state",
|
|
10
|
-
with real C# control flow.
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
with real C# control flow. Start with model-bound attributes, use fluent
|
|
11
|
+
`IProjectionFor<T>` when mappings need structure, and choose a reducer when
|
|
12
|
+
branching on prior state, calculations or guards read better as code. A reducer
|
|
13
|
+
is a normal choice, not a last resort. For the application-code ladder and PDL's
|
|
14
|
+
outside-code role, read [choosing a style](../cratis-chronicle-read-model/SKILL.md#step-3--choose-a-projection-or-a-reducer).
|
|
15
|
+
|
|
16
|
+
For new .NET reducers, default to **self-reducing read models**: public static
|
|
17
|
+
`Reduce` methods beside the state, discovered by shape without a marker. Use a
|
|
18
|
+
separate `IReducerFor<T>` for fold-time DI, replay-time instance state or useful
|
|
19
|
+
separation; nominate a plain class only when its assembly cannot reference
|
|
20
|
+
Chronicle. Self reduction is .NET-only (Cratis/Chronicle#4851); other SDKs retain
|
|
21
|
+
their own contracts. This guidance does not claim Stage renders the self form.
|
|
13
22
|
|
|
14
23
|
## Verified product sources
|
|
15
24
|
|
|
@@ -17,33 +26,89 @@ This skill is verified against this exact source:
|
|
|
17
26
|
|
|
18
27
|
| Package | Version | Purpose |
|
|
19
28
|
| --- | --- | --- |
|
|
20
|
-
| `Cratis.Chronicle` | `19.50.1` |
|
|
29
|
+
| `Cratis.Chronicle` | `19.50.1` | Existing reducer, read-model and event APIs |
|
|
30
|
+
| `Cratis.Chronicle` | `19.59.4` | `Source/Clients/DotNET/Reducers/{SelfReducerMethods,SelfReducerInvoker,SelfReducerReplayHooks,RegisteredReducerReadModel,ReducerInvoker,ReducerCatalog}.cs`, `ReadModels/ReadModelBuilderOwnership.cs`, `DefaultClientArtifactsProvider.cs` at tag `v19.59.4`: self/instance forms, discovery and ownership |
|
|
31
|
+
| `Cratis.Chronicle.Testing` | `19.59.4` | `Source/Clients/Testing/ReadModels/ReadModelScenario.cs` at tag `v19.59.4`: static folds through scenarios |
|
|
21
32
|
|
|
22
33
|
Reverify product sources before claiming support for another version.
|
|
23
34
|
|
|
24
|
-
##
|
|
35
|
+
## Choose the form
|
|
36
|
+
|
|
37
|
+
- Direct property mapping, counters and sums usually read best as projections.
|
|
38
|
+
Fluent definitions add mapping structure, not arbitrary per-event code.
|
|
39
|
+
- Prior-state branches and guarded calculations often read best as reducers.
|
|
40
|
+
Explain the state-transition rule, rather than proving both projection APIs
|
|
41
|
+
incapable. Reducers fold per event source: no native cross-source joins,
|
|
42
|
+
custom aggregation keys or variant-group wiring.
|
|
43
|
+
- Keep the state and transition together by default. Choose `IReducerFor<T>`
|
|
44
|
+
when constructor dependencies, replay instance behavior or a separate data
|
|
45
|
+
contract make the extra type useful. Prefer event-recorded rates/times over
|
|
46
|
+
consulting today's service during replay. Never hide durable state on a
|
|
47
|
+
reducer service instance.
|
|
48
|
+
- When the assembly cannot reference Chronicle, nominate a plain instance class
|
|
49
|
+
through `ChronicleOptions.ExplicitArtifacts.RegisterReducer<PlainReducer>()`
|
|
50
|
+
before creating stores. Supported instance handlers must infer exactly one
|
|
51
|
+
model. See [discovery and nomination](../cratis-chronicle-client-dotnet/references/discovery.md).
|
|
52
|
+
|
|
53
|
+
## Default — a self-reducing read model
|
|
54
|
+
|
|
55
|
+
This example's debit guard derives a view; it does not reject the already
|
|
56
|
+
appended debit. Missing state stays absent until a credit creates it.
|
|
25
57
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
58
|
+
```csharp
|
|
59
|
+
using Cratis.Chronicle.Events;
|
|
60
|
+
using Cratis.Concepts;
|
|
61
|
+
|
|
62
|
+
public record Money(decimal Value) : ConceptAs<decimal>(Value);
|
|
63
|
+
|
|
64
|
+
/// <summary>Funds were credited to the account.</summary>
|
|
65
|
+
[EventType]
|
|
66
|
+
public record FundsCredited(Money Amount);
|
|
67
|
+
|
|
68
|
+
/// <summary>A debit was recorded for the account.</summary>
|
|
69
|
+
[EventType]
|
|
70
|
+
public record FundsDebited(Money Amount);
|
|
37
71
|
|
|
38
|
-
|
|
39
|
-
|
|
72
|
+
/// <summary>The balance view was cleared.</summary>
|
|
73
|
+
[EventType]
|
|
74
|
+
public record BalanceCleared;
|
|
75
|
+
|
|
76
|
+
public record AccountBalance(Money Total)
|
|
77
|
+
{
|
|
78
|
+
public static AccountBalance Reduce(FundsCredited @event, AccountBalance? current) =>
|
|
79
|
+
new(new Money((current?.Total.Value ?? 0m) + @event.Amount.Value));
|
|
80
|
+
|
|
81
|
+
public static AccountBalance? Reduce(FundsDebited @event, AccountBalance? current) =>
|
|
82
|
+
current is null || current.Total.Value < @event.Amount.Value
|
|
83
|
+
? current
|
|
84
|
+
: current with { Total = new Money(current.Total.Value - @event.Amount.Value) };
|
|
85
|
+
|
|
86
|
+
public static AccountBalance? Reduce(BalanceCleared @event, AccountBalance? current) => null;
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
No model activation, parameterless constructor or reducer marker is needed.
|
|
91
|
+
`[Reducer]` is optional configuration, not a discovery requirement.
|
|
92
|
+
|
|
93
|
+
### Arc on the same record
|
|
94
|
+
|
|
95
|
+
In Arc applications keep `[ReadModel]`, `Reduce` methods and static queries on
|
|
96
|
+
one record. Before Arc 22.90.0, use
|
|
97
|
+
`[ReadModel(RequireQueryAttribute = true)]` with `[Query]` on intended endpoints;
|
|
98
|
+
see [query discovery](../cratis-chronicle-read-model/references/queries.md#discovery-rules).
|
|
99
|
+
From Arc 22.90.0, Arc excludes methods taking the model itself from query
|
|
100
|
+
discovery, and Arc.Chronicle claims self-reducing models for command injection.
|
|
101
|
+
Check the consuming Arc version; Chronicle's discovery does not fix older Arc.
|
|
102
|
+
|
|
103
|
+
## Separate instance reducer
|
|
104
|
+
|
|
105
|
+
When the fold needs the separation described above, use the classic form:
|
|
40
106
|
|
|
41
107
|
```csharp
|
|
42
108
|
using Cratis.Chronicle.Events;
|
|
43
109
|
using Cratis.Chronicle.Reducers;
|
|
44
110
|
|
|
45
|
-
//
|
|
46
|
-
// per-event rule that no counter or projection operator expresses.
|
|
111
|
+
// This fold lives separately because the model is a shared data contract.
|
|
47
112
|
public class <ReadModelName>Reducer : IReducerFor<<ReadModelName>>
|
|
48
113
|
{
|
|
49
114
|
public <ReadModelName> <Opened>(<OpenedEvent> @event, <ReadModelName>? current, EventContext context) =>
|
|
@@ -66,7 +131,7 @@ plain setter. First inspect guards: does it require a creation event, ignore an
|
|
|
66
131
|
older attempt, preserve a terminal state, or compare prior values? Replacing it
|
|
67
132
|
with unconditional `[SetValue<T>]` can create state too early or resurrect a
|
|
68
133
|
finished entity. Keep the reducer when the projection APIs cannot express those
|
|
69
|
-
semantics; the
|
|
134
|
+
semantics; the style choice is about behavior, not handler length.
|
|
70
135
|
|
|
71
136
|
Evaluate variants for mutually exclusive lifecycle shapes (see the projection
|
|
72
137
|
skill). Their non-entering events are update-only, but that does not replace
|
|
@@ -75,10 +140,35 @@ keep specifications for update-before-create, late events after completion,
|
|
|
75
140
|
repeated events, and each guarded branch, as applicable. Assert the same outcomes
|
|
76
141
|
with the replacement, not only the happy-path final status.
|
|
77
142
|
|
|
78
|
-
## Method signatures —
|
|
143
|
+
## Method signatures — split by form
|
|
144
|
+
|
|
145
|
+
### Self-reducing model
|
|
146
|
+
|
|
147
|
+
The containing type must be concrete, non-generic and not implement `IReducer`.
|
|
148
|
+
Each handler is public static, non-generic and named **`Reduce`**.
|
|
149
|
+
|
|
150
|
+
| Signature | Meaning |
|
|
151
|
+
| --- | --- |
|
|
152
|
+
| `TSelf Reduce(TEvent @event, TSelf? current)` | complete next state |
|
|
153
|
+
| `TSelf Reduce(TEvent @event, TSelf? current, EventContext context)` | next state with metadata |
|
|
154
|
+
| `TSelf?` / `Task<TSelf>` / `Task<TSelf?>` with those parameters | nullable and/or awaited next state |
|
|
155
|
+
| bare `Task`, `ValueTask`, `Task<object>` | invalid self result, not deletion |
|
|
156
|
+
|
|
157
|
+
The event dispatch target is a non-`object` class or interface; current is exactly
|
|
158
|
+
the model type, nullable or nullable-oblivious. No by-ref, optional, `params`,
|
|
159
|
+
reordered or extra service arguments: **no DI in `Reduce`**. Return `null` to
|
|
160
|
+
leave absent state or delete; return `current` to ignore. Awaited results become
|
|
161
|
+
current state before the next event.
|
|
162
|
+
|
|
163
|
+
Dispatch selects from events registered in the owning client: exact type,
|
|
164
|
+
then nearest base class, then uniquely most-derived interface. Equal-specificity
|
|
165
|
+
ties (including overloads with/without context for one event) throw
|
|
166
|
+
`AmbiguousSelfReducerMethod`. Names and declaration order do not break ties.
|
|
167
|
+
|
|
168
|
+
### Separate or nominated instance reducer
|
|
79
169
|
|
|
80
170
|
Dispatch is by the **first parameter's type**, never by the method name. Name the
|
|
81
|
-
method for the reader.
|
|
171
|
+
instance method for the reader.
|
|
82
172
|
|
|
83
173
|
| Signature | Meaning |
|
|
84
174
|
| --- | --- |
|
|
@@ -97,14 +187,16 @@ The rules the invoker enforces:
|
|
|
97
187
|
- Public and non-public instance methods are both scanned, and **one method wins
|
|
98
188
|
per event type** — do not write two handlers for the same event.
|
|
99
189
|
- Return the complete next state. Never mutate `current` in place; use `with { }`.
|
|
100
|
-
-
|
|
101
|
-
|
|
190
|
+
- Keep durable state in the model. Instance replay bookkeeping is not durable
|
|
191
|
+
model state and must not make the fold depend on a previous activation.
|
|
192
|
+
- An instance reducer with no dispatchable methods is not registered. Logs name skipped
|
|
102
193
|
reducer-like methods; CHR0006/CHR0007 flag them. CHR0051 checks nullable current
|
|
103
194
|
state, and CHR0057 rejects multiple `IReducerFor<T>` targets on one class.
|
|
104
195
|
|
|
105
196
|
### Returning null deletes the instance
|
|
106
197
|
|
|
107
|
-
|
|
198
|
+
In either form, `null` sets the state to absent. In the **instance form only**,
|
|
199
|
+
a bare `Task` also sets the read-model state
|
|
108
200
|
to null, which removes the instance. That is the deletion mechanism, so do not
|
|
109
201
|
reach for `null` to mean "ignore this event". To ignore an event, return
|
|
110
202
|
`current` unchanged.
|
|
@@ -114,9 +206,9 @@ stops the reducer for that partition until an operator intervenes.
|
|
|
114
206
|
|
|
115
207
|
`current` is `null` on the first event for a given event source. For a model
|
|
116
208
|
seeded by one event and then updated by many, decide deliberately what an update
|
|
117
|
-
arriving before its seed should do
|
|
118
|
-
|
|
119
|
-
bug.
|
|
209
|
+
arriving before its seed should do. Returning `current` preserves absence;
|
|
210
|
+
synthesizing a partial instance is valid only when it is the deliberate view
|
|
211
|
+
policy. Specify that policy rather than hiding a missing-creation bug.
|
|
120
212
|
|
|
121
213
|
## Identity, passivity, and event sequence
|
|
122
214
|
|
|
@@ -129,7 +221,10 @@ public sealed class ReducerAttribute(string id = "", string? eventSequence = def
|
|
|
129
221
|
|
|
130
222
|
- `id` overrides the generated reducer identity.
|
|
131
223
|
- `eventSequence` selects the source sequence.
|
|
132
|
-
- `isActive: false`
|
|
224
|
+
- `isActive: false` disables active maintenance; it does **not** make reads passive.
|
|
225
|
+
|
|
226
|
+
For a self reducer, place configuration on the model; for a separate reducer,
|
|
227
|
+
place `[Reducer]` on its class. Keep `[Passive]` on the model in both forms.
|
|
133
228
|
|
|
134
229
|
`Cratis.Chronicle.ReadModels.PassiveAttribute` (`[Passive]`) goes on the **read
|
|
135
230
|
model type** and makes it passive as a whole: no sink, nothing materialized, and
|
|
@@ -141,9 +236,49 @@ decision reads. For a rule that must hold under concurrent writers use a flat
|
|
|
141
236
|
projection with a decision read; see
|
|
142
237
|
[choosing how a rule holds](../cratis-chronicle-decision-reads/references/choosing-how-a-rule-holds.md).
|
|
143
238
|
|
|
239
|
+
## Discovery, upgrades and ownership
|
|
240
|
+
|
|
241
|
+
Since 19.58.0, complete marker-free static shapes become reducers on upgrade,
|
|
242
|
+
including existing helpers. Review them before upgrading. Near-miss static
|
|
243
|
+
`Reduce` declarations whose current/result refers to the model warn (CHR0058)
|
|
244
|
+
and are skipped by implicit discovery; explicit nomination throws
|
|
245
|
+
`InvalidSelfReducerSignature`. Once one valid shape exists, invalid sibling
|
|
246
|
+
`Reduce` declarations and malformed hooks fail validation. No registered matching
|
|
247
|
+
event means no observer subscription; assembly membership alone is not event
|
|
248
|
+
membership. Types implementing `IReducer` stay classic even with a self-shaped
|
|
249
|
+
static helper.
|
|
250
|
+
|
|
251
|
+
Use the existing generic or Type `RegisterReducer` API for explicit self-model
|
|
252
|
+
nomination too; there is no special self API. A self model cannot share ownership
|
|
253
|
+
with a separate reducer, fluent projection or genuine model-bound mappings in the
|
|
254
|
+
same store catalog: `AmbiguousReadModelBuilder` rejects it. `[Passive]`, sequence
|
|
255
|
+
selection, filters and `[Reducer]` alone do not establish projection ownership.
|
|
256
|
+
Remove the old builder when switching; registration is not a data migration.
|
|
257
|
+
|
|
258
|
+
## Optional self replay hooks
|
|
259
|
+
|
|
260
|
+
Independently optional public static non-generic hooks return exactly `Task`:
|
|
261
|
+
|
|
262
|
+
```csharp
|
|
263
|
+
public static Task BeginReplay() => Task.CompletedTask;
|
|
264
|
+
public static Task EndReplay() => Task.CompletedTask;
|
|
265
|
+
public static Task BeginReplayPartition(Partition partition) => Task.CompletedTask;
|
|
266
|
+
public static Task EndReplayPartition(Partition partition) => Task.CompletedTask;
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Place these methods on the model and import `Cratis.Chronicle.Observation` for
|
|
270
|
+
`Partition`. Global hooks accept only trailing class/interface service arguments;
|
|
271
|
+
partition hooks require `Partition` first. Services resolve in the notification's
|
|
272
|
+
async DI scope; missing registrations fail. Events, the model, `EventContext`
|
|
273
|
+
and extra partition arguments are not hook services. Chronicle awaits hooks and
|
|
274
|
+
scope disposal; absent hooks create no scope. Do not assume full replay delivers
|
|
275
|
+
partition notifications, failures deliver an end hook, or delivery is exactly
|
|
276
|
+
once. Instance reducers retain replay notification interfaces.
|
|
277
|
+
|
|
144
278
|
## Filtering which events reach the reducer
|
|
145
279
|
|
|
146
|
-
|
|
280
|
+
Place filters on the self model or separate reducer class. These attributes
|
|
281
|
+
genuinely filter a reducer's input, matching append metadata:
|
|
147
282
|
|
|
148
283
|
| Attribute | Filters on |
|
|
149
284
|
| --- | --- |
|
|
@@ -191,7 +326,27 @@ Start with `Specification` plus a direct call for pure reducer decisions:
|
|
|
191
326
|
pass the event and current state explicitly and assert the returned next state.
|
|
192
327
|
Add `ReadModelScenario<TReadModel>` only where event dispatch, filtering,
|
|
193
328
|
metadata or read-model wiring contribute proof; drive the event sequence and
|
|
194
|
-
assert on the resulting instance there.
|
|
329
|
+
assert on the resulting instance there. For the self example:
|
|
330
|
+
|
|
331
|
+
```csharp
|
|
332
|
+
var next = AccountBalance.Reduce(new FundsCredited(new Money(10m)), null);
|
|
333
|
+
next.Total.Value.ShouldEqual(10m);
|
|
334
|
+
|
|
335
|
+
using var scenario = new ReadModelScenario<AccountBalance>();
|
|
336
|
+
await scenario.Given.ForEventSource("account-42").Events(
|
|
337
|
+
new FundsCredited(new Money(10m)),
|
|
338
|
+
new BalanceCleared(),
|
|
339
|
+
new FundsCredited(new Money(3m)));
|
|
340
|
+
scenario.Instance!.Total.Value.ShouldEqual(3m);
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
Import `Cratis.Chronicle.Testing.ReadModels` for the scenario and the project's
|
|
344
|
+
specification assertions. Test deletion alone as absence, then recreation;
|
|
345
|
+
cover empty history and every event without current state. Scenario discovery
|
|
346
|
+
includes self models and nominated plain classes; see
|
|
347
|
+
[read-model specifications](../cratis-chronicle-read-model-specifications/SKILL.md).
|
|
348
|
+
In-process scenarios substitute storage, lifecycle and compliance: they do not
|
|
349
|
+
prove transport, replay, encryption, erasure or sink migration. Cover, at minimum:
|
|
195
350
|
|
|
196
351
|
- the first event, where `current` is `null`;
|
|
197
352
|
- accumulation across several events on one event source;
|
|
@@ -213,16 +368,17 @@ assert on the resulting instance there. Cover, at minimum:
|
|
|
213
368
|
|
|
214
369
|
## Verify
|
|
215
370
|
|
|
216
|
-
- The
|
|
217
|
-
|
|
218
|
-
-
|
|
371
|
+
- The style and placement fit the transition; no projection feature is rebuilt
|
|
372
|
+
unnecessarily and admission/ordering guards are preserved.
|
|
373
|
+
- Every handler accepts nullable current state (CHR0051 for instance methods,
|
|
374
|
+
CHR0058 for self near misses).
|
|
219
375
|
- Logs contain no skipped reducer-like method warning (CHR0006/CHR0007);
|
|
220
|
-
CHR0055–
|
|
376
|
+
CHR0055–CHR0061 are clean, including hooks, ties and ownership.
|
|
221
377
|
- No handler method has more than three parameters, and any third is
|
|
222
378
|
`EventContext`.
|
|
223
379
|
- Exactly one handler exists per event type.
|
|
224
|
-
-
|
|
225
|
-
- `null`
|
|
380
|
+
- Durable state lives in the model, not the reducer instance; never mutate `current`.
|
|
381
|
+
- `null` represents deliberately absent or deleted state, never a skip of existing state.
|
|
226
382
|
- No handler throws to skip an event.
|
|
227
383
|
- The project builds clean and the read-model specifications pass against the
|
|
228
384
|
verified package version.
|