diff --git a/.gitignore b/.gitignore index a38f554..9746e2b 100644 --- a/.gitignore +++ b/.gitignore @@ -488,3 +488,5 @@ $RECYCLE.BIN/ appsettings.*.local.json # Personal Claude Code settings (shared skills in .claude/skills are committed) .claude/settings.local.json +# Schema contract output of a failed run: review it, never commit it (ADR 0036) +*.received.json diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d5c248e..957e6a5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -129,6 +129,8 @@ The host runs one Wolverine bus ([ADR 0017](docs/adr/0017-wolverine-wiring.md)). - **Dispatch:** `.Api` and `.Mcp` call `IMessageBus.InvokeAsync>(…)` and use no other Wolverine type (`adapters-dispatch-through-the-message-bus`). - **Idempotency:** every command record implements `ICommand` and so carries an `IdempotencyKey IdempotencyKey`. `AddServiceDomainStore` wraps every command handler with the idempotency policy ([ADR 0018](docs/adr/0018-idempotency-keys-for-commands.md)): the same key and payload return the stored acknowledgement and the handler does not run again; the same key with another payload returns `shared.idempotency-key-reused`; a key still being handled returns `shared.idempotency-key-in-use`; a missing key returns `shared.idempotency-key-missing`. Only successful results are stored, so a rejected command can be retried with the same key. Keys are scoped to the caller: two callers with the same key never replay or block each other, and messages no caller sent share the system scope ([ADR 0019](docs/adr/0019-authentication-baseline.md)). The handler never reads the key. A `.Subscriptions` adapter builds the key from the requesting record's identifier (`IdempotencyKey.From(...)`). - **HTTP:** every `.Api` endpoint that dispatches a command requires the header with `RequireIdempotencyKey()` from `RimBank.Api` (on the endpoint or its route group), takes an `IdempotencyKeyHeader idempotency` parameter and passes `idempotency.Value` into the command. `Retrieve` (query) endpoints take no key. +- **Published language** ([ADR 0036](docs/adr/0036-party-published-language.md)): an integration event other contexts consume is a BCL record in the context's `.PublishedLanguage` project, with `public const string Channel` (its BIAN AsyncAPI channel) and `public const string MessageIdentity` (`..v`), which is its name on the wire. A pure mapper in the core builds it from the decided domain events, never from a view, and the command handler returns it as `(Result, TEvent?)`. +- **Changing a published event:** you may only add a field. Removing, renaming or retyping a field, or changing its meaning, needs a new type with the next `.v` identity, published next to the old one until its consumers move. Each event's schema is pinned by `Publication/Approved/.approved.json` in the context's `.Postgresql.Tests`. When the contract test fails, it writes `.received.json` next to it (git-ignored). Review it, and copy it over the approved file only for an additive change, in the same pull request. - **Host message store:** Wolverine keeps its own bookkeeping in schema `wolverine` (role `rimbank_wolverine`, `ConnectionStrings:Wolverine`). Without that connection string, as before the first context, messages stay in memory. ### BIAN conformance diff --git a/RimBank.slnx b/RimBank.slnx index 9a69ce2..21c6f0b 100644 --- a/RimBank.slnx +++ b/RimBank.slnx @@ -8,6 +8,7 @@ + diff --git a/docs/adr/0024-party-reference-data-directory-mapping.md b/docs/adr/0024-party-reference-data-directory-mapping.md index b99b3b0..72e4277 100644 --- a/docs/adr/0024-party-reference-data-directory-mapping.md +++ b/docs/adr/0024-party-reference-data-directory-mapping.md @@ -148,12 +148,12 @@ The exact names are fixed by the phase that adds each event, within this list. E ### Integration channels -Integration events are mapped from domain events, never from views (tech-stack §8.4). Each one carries the state its consumers need. +Integration events are mapped from domain events, never from views (tech-stack §8.4). Each one carries the state its consumers need. [ADR 0036](0036-party-published-language.md) fixes their shape, identity, versioning and contract test. | AsyncAPI channel | From | Phase | |---|---|---| -| `PartyReferenceDataDirectoryEntry/Created` | `PartyRegistered` | 1.13 | -| `PartyReferenceDataDirectoryEntry/Updated` | `PartyReferenceDataDirectoryEntryUpdated` | 1.13 | +| `PartyReferenceDataDirectoryEntry/Created` | `PartyRegistered`, published as `PartyReferenceDataDirectoryEntryCreated` (`party-reference-data-directory-entry.created.v1`) | 1.13 | +| `PartyReferenceDataDirectoryEntry/Updated` | `PartyReferenceDataDirectoryEntryUpdated`, published as `PartyReferenceDataDirectoryEntryUpdated` (`party-reference-data-directory-entry.updated.v1`) | 1.13 | | `Demographics/Created`, `Demographics/Updated` | The first / a later `DemographicsUpdated` or `DemographicsExchanged` of an entry | deferred | | `Reference/Created`, `Reference/Updated` | The first / a later `PartyReferenceUpdated` of an entry | deferred | | `Associations/Created`, `Associations/Updated` | `PartyAssociationRegistered` / `PartyAssociationUpdated` | deferred | diff --git a/docs/adr/0036-party-published-language.md b/docs/adr/0036-party-published-language.md new file mode 100644 index 0000000..5e50123 --- /dev/null +++ b/docs/adr/0036-party-published-language.md @@ -0,0 +1,73 @@ +# 0036. Party Reference Data Directory: published language + +- Status: Accepted +- Date: 2026-11-08 +- Roadmap phase: 1.13 + +## Context + +Until 1.13, nothing left Party Reference Data Directory. Current Account (roadmap 4.1) will need to know that a party exists, without querying Party ([mission](../../specs/mission.md) principle 7, consumers own their copy). [Tech-stack §8.4](../../specs/tech-stack.md#84-read-models-across-contexts-loose-coupling) sets the producer rules: integration events are mapped from domain events through the outbox, never from read models; they carry the state consumers need; they are versioned and change only in backwards-compatible ways; and a contract test pins each schema. + +[ADR 0024](0024-party-reference-data-directory-mapping.md#integration-channels) maps the two Control Record channels of the [BIAN AsyncAPI](../../doc-0/release14.0.0/apis-iso20022_ext-ddd/asyncapi-3.x/yamls/PartyReferenceDataDirectory.yaml) to phase 1.13: `PartyRegistered` maps to `PartyReferenceDataDirectoryEntry/Created`, and `PartyReferenceDataDirectoryEntryUpdated` maps to `…/Updated`. It defers the 8 BQ channels. The BIAN payload is the Control Record schema: `PartyReference`, `PartyType`, `DirectoryEntryDateType` (`OpenDate` / `RefreshDate`) and `DirectoryEntryDate`. + +Constraints: +- `.PublishedLanguage` is BCL only ([tech-stack §4](../../specs/tech-stack.md#4-dependency-rules-enforced-by-architecture-tests)), so it cannot use Wolverine's `[MessageIdentity]` attribute. +- The core uses no Wolverine type ([ADR 0017](0017-wolverine-wiring.md)). +- No new package is allowed without a reason ([ADR 0013](0013-warning-and-package-governance.md)). + +## Options considered + +**Payload** +1. **The Control Record state plus a small envelope** (`EventId`, `OccurredAt`, `Version`). Consumers can order and deduplicate. There is no PII. +2. The same, with the Behavior Qualifier ids. No consumer needs them yet. +3. Only the id and party type. Too thin: a consumer could not order events. + +**Versioning** +1. **A stable message identity declared on the type as a constant** (`MessageIdentity`), given to Wolverine by a naming strategy in the adapter wiring. Changes may only add fields. +2. A `V1` suffix on the CLR type. Simpler, but the wire name would be the CLR name, so a rename or a move would break consumers. +3. A version field in the payload. It does not say which type to deserialise to. + +**Mapping and delivery** +1. **A pure mapper in core, cascaded by the command handler** as `(Result, Event?)`, the 0.11 pattern. The event commits with the domain events in one transaction. +2. Marten event forwarding in `.Postgresql`. Handlers stay unchanged, but the business mapping moves into an adapter, and the transaction behaviour depends on more wiring. + +**Contract test** +1. **A JSON schema exported with `System.Text.Json.Schema.JsonSchemaExporter` (BCL), compared to a committed approved file.** +2. A snapshot package (Verify). It needs a new package for little gain. + +## Decision + +- **Project:** `src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage` (namespace `RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage`, BCL only). It holds `PartyReferenceDataDirectoryEntryCreated` and `PartyReferenceDataDirectoryEntryUpdated`, with the fields: + - `EventId` (Guid v7); + - `OccurredAt`; + - `PartyReferenceDataDirectoryEntryId`; + - `Version` (the entry's stream version after the event); + - `PartyType`; + - `DirectoryEntryDateType`; + - `DirectoryEntryDate`. + + `PartyType` and `DirectoryEntryDateType` are strings, with the allowed values in `PartyTypes` and `DirectoryEntryDateTypes`. They are not enums, so a value added later never breaks an older consumer. There is no PII and no BQ id. +- **Identity:** each event declares `public const string Channel` (its BIAN channel) and `public const string MessageIdentity`: `party-reference-data-directory-entry.created.v1` and `…updated.v1`. + - `RimBank.Postgresql.PublishedLanguageMessageNaming` gives any type in a `*.PublishedLanguage` namespace the identity it declares. It is registered once, ahead of Wolverine's own naming, by `AddServiceDomainStore`, through `WolverineMessageNaming.InsertFirst`. Every other message keeps Wolverine's default name. + - **Compatibility:** a field may be added; a field is never removed, renamed or retyped. A breaking change is a new type with a `.v2` identity, published next to v1 until consumers move. +- **Mapping:** `PartyReferenceDataDirectoryPublication` (core, `Publication/`) maps a decided `PartyRegistered` or `PartyReferenceDataDirectoryEntryUpdated` to its integration event. `OccurredAt` and `DirectoryEntryDate` are the open or refresh date, so the mapper is pure. `RegisterPartyHandler` and `UpdatePartyReferenceDataDirectoryEntryHandler` return `(Result<…Acknowledged>, ?)`, with the event id from their `TimeProvider`. An error returns `null`, so a refused command publishes nothing by construction. An idempotent replay does not run the handler (ADR 0018), so it publishes nothing again. Behavior Qualifier commands publish nothing. +- **Delivery:** the cascaded event goes to the context's durable local queue (ADR 0017's namespace rule also covers the child namespace `.PublishedLanguage`). Its envelope is saved in `party_reference_data_directory.wolverine_incoming_envelopes` in the same transaction as the events. Until a consumer exists (4.1), no handler receives it, and Wolverine logs it and discards it (`UnknownMessageBehavior.LogOnly`, the default). Events are not replayed for entries registered before 1.13, because there is no consumer to replay for. 4.1 decides how a new consumer catches up. +- **Wire format:** Wolverine's default System.Text.Json serializer, so property names are camelCase on the wire (`partyType`). Reads are case-insensitive, and an unknown field is ignored. BIAN names the same fields in PascalCase; 1.14 compares them without regard to case. +- **Contract:** `PartyPublishedLanguageSchemaTests` (Party `.Postgresql.Tests`, `Publication/`) exports each event's schema with the wire settings and compares it, with its channel and identity, to `Publication/Approved/.approved.json`. On a mismatch it writes `.received.json` (git-ignored). The test also checks: + - Wolverine writes the same property names; + - an event survives the wire round trip; + - a v1 reader tolerates an added field; + - every published type goes on the wire under its declared identity. + +## Consequences + +- Any change to a published event shows up in review as a diff of the approved file. Updating that file on purpose is the only way to change the contract, and a removal or rename must be a new versioned type instead. +- `PartyReferenceDataDirectoryCatalogue` (conformance) gives each 1.13 channel its event type. Its tests check that each event's `Channel` matches its row, that only deferred channels have no event, and that the addresses exist in the AsyncAPI. +- Integration tests (`PublishedLanguageOutboxTests`) prove: + - exactly one event per accepted Register or Update, with the right version and payload; + - the stored envelope carries the v1 identity and the expected JSON; + - nothing for a conflict, an unknown entry, a replay or a BQ update; + - one envelope per committed Control Record event, all in the context's own schema. +- Next contexts follow the same pattern: a BCL `.PublishedLanguage` whose types declare `Channel` and `MessageIdentity`, a pure mapper in core, a handler cascade and an approved schema per event. The naming strategy needs no per-context wiring. +- **4.1** must decide how Current Account receives these events (its handler in `.Subscriptions` will run on Party's queue unless it routes them to its own), and how a new consumer catches up on parties registered before it existed. +- Wolverine's message naming is process-wide (static). The naming strategy only answers for `*.PublishedLanguage` types, so it changes no other message name. diff --git a/specs/2026-11-08-party-published-language/plan.md b/specs/2026-11-08-party-published-language/plan.md new file mode 100644 index 0000000..678ee93 --- /dev/null +++ b/specs/2026-11-08-party-published-language/plan.md @@ -0,0 +1,46 @@ +# Plan: Party Reference Data Directory: published language + +The solution builds and every test passes after each group. + +## 1. Published language project and events +- [ ] Create `src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/` (csproj with no package reference, `packages.lock.json`), add it to `RimBank.slnx`, and reference it from `RimBank.Core`. +- [ ] `PartyReferenceDataDirectoryEntryCreated` and `PartyReferenceDataDirectoryEntryUpdated` sealed records (fields in requirements.md), with XML docs naming the BIAN channel and the v1 identity. +- [ ] `PartyTypes` and `DirectoryEntryDateTypes` constants classes. +- [ ] Run the architecture tests: the existing `.PublishedLanguage` rules (BCL only, no views, only own core and `.Subscriptions` may use it) now apply to a real project and stay green. + +## 2. Mapper in core +- [ ] `RimBank.Core/Party/PartyReferenceDataDirectory/Publication/PartyReferenceDataDirectoryPublication.cs`: `Created(PartyRegistered, version, eventId)` and `Updated(PartyReferenceDataDirectoryEntryUpdated, version, eventId)`. `PartyType` is mapped to its published string with a switch expression (IDE0066). +- [ ] `tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Publication/PartyReferenceDataDirectoryPublicationTests.cs`: + - Register maps to Created with `OpenDate`; + - Update maps to Updated with `RefreshDate`; + - every party type has a published value, and an unknown one is refused; + - the `PartyType` string, the version and `OccurredAt` are carried. + +## 3. Handler cascade and Wolverine wiring +- [ ] `RegisterPartyHandler` returns `(Result, PartyReferenceDataDirectoryEntryCreated?)`, and `UpdatePartyReferenceDataDirectoryEntryHandler` returns `(…, PartyReferenceDataDirectoryEntryUpdated?)`. The event id is `Guid.CreateVersion7(time.GetUtcNow())`, and the event is `null` on every error path. +- [ ] Update the handler tests in `RimBank.Core.Tests`: + - success yields exactly one event, with version 1 after Register and N+1 after Update; + - not found, version conflict and decision errors yield `null`. +- [ ] Check the API and MCP callers that `InvokeAsync>` still gets the acknowledgement. `RimBank.Api` should need no change. +- [ ] `RimBank.Postgresql/PublishedLanguageMessageNaming.cs`: an `IMessageTypeNaming` that reads the `MessageIdentity` constant of `*.PublishedLanguage` types, registered once in `AddServiceDomainStore` (`WolverineMessageNaming.InsertFirst`), with unit tests in `RimBank.Postgresql.Tests`. +- [ ] Confirm the events are persisted in the party schema's `wolverine_incoming_envelopes` (durable local queue). With no handler, Wolverine discards them with a log entry. That is accepted until 4.1. + +## 4. Outbox integration tests (Testcontainers) +- [ ] `tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/PublishedLanguageOutboxTests.cs`, using a Wolverine tracked session and a test-only subscriber handler: + - Register publishes exactly one Created with the right id, type, date and version 1; + - Update publishes exactly one Updated with version 2; + - a stale `ExpectedVersion` publishes nothing; + - an unknown entry publishes nothing; + - a replayed `Idempotency-Key` publishes nothing again; + - a BQ Update (Demographics) publishes nothing; + - the stored envelope carries the v1 identity and the expected JSON payload; + - there is exactly one envelope per committed Control Record event, and none in the host's `wolverine` schema. + +## 5. Schema contract +- [ ] `tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/PartyPublishedLanguageSchemaTests.cs` (it references Wolverine, so it can check the real serializer): export each event's JSON schema with `JsonSchemaExporter` and Wolverine's wire settings. Compare it, with the event's channel and identity, to `Publication/Approved/.approved.json`. On a mismatch, the test writes `*.received.json` (git-ignored) and fails with a message pointing to ADR 0036. +- [ ] Also test: Wolverine writes the same property names, an event survives the wire round trip, a v1 reader tolerates an added field, and each type goes on the wire under its declared identity. + +## 6. Catalogue, ADRs and docs +- [ ] `PartyReferenceDataDirectoryCatalogue`: give each CR channel its CLR type, and add a test that every channel catalogued for a done phase has a type and that its address exists in the AsyncAPI YAML. +- [ ] ADR 0036 (Party published language), ADR 0024 integration-channel table, tech-stack §3 tree and §8.4 link, and the CONTRIBUTING "changing a published event" note. +- [ ] Tick roadmap 1.13. Then run `dotnet format --verify-no-changes` and the full `dotnet test`. diff --git a/specs/2026-11-08-party-published-language/requirements.md b/specs/2026-11-08-party-published-language/requirements.md new file mode 100644 index 0000000..1c2637a --- /dev/null +++ b/specs/2026-11-08-party-published-language/requirements.md @@ -0,0 +1,71 @@ +# Party Reference Data Directory: published language + +Roadmap phase: 1.13 +Branch: plan/1.13-party-published-language + +## Context +Every Behavior Qualifier of Party Reference Data Directory now has a working write and read side (1.2–1.12, 1.18–1.21). Until now, nothing has left the context. 1.13 publishes the first **integration events** of RimBank: the two Control Record channels of the [BIAN AsyncAPI](../../doc-0/release14.0.0/apis-iso20022_ext-ddd/asyncapi-3.x/yamls/PartyReferenceDataDirectory.yaml), `PartyReferenceDataDirectoryEntry/Created` and `PartyReferenceDataDirectoryEntry/Updated`. Their payload is the CR schema: `PartyReference`, `PartyType`, `DirectoryEntryDateType` (`OpenDate` / `RefreshDate`), `DirectoryEntryDate`. + +[ADR 0024](../../docs/adr/0024-party-reference-data-directory-mapping.md#integration-channels) already maps them: `PartyRegistered` → Created and `PartyReferenceDataDirectoryEntryUpdated` → Updated. It also defers the 8 BQ channels until a consumer needs them, and keeps their PII unpublished before 7.2. The conformance catalogue already lists both CR channels with phase `1.13`. + +**Chosen in the interview:** full CR state plus a small envelope, versioned v1 through a stable message identity. The mapping is a pure mapper in core, and the command handlers cascade its result into Wolverine's Marten outbox. + +It depends on 0.10 and 0.11 (Marten store, Wolverine outbox, durable local queue, ADR 0016–0017) and on 1.2–1.8 (Register and Update). It unblocks **4.1** (Current Account subscribes to these events to know that a party exists) and the AsyncAPI half of **1.14**. + +Drivers: +- Mission principle 7: loosely coupled contexts; consumers own their copy, and no callbacks to read. +- Tech-stack §3 (`RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage` is its own project and BCL only; integration events only, never views or domain types). +- Tech-stack §4 dependency table (core uses only its own `.PublishedLanguage`). +- Tech-stack §7 (integration events are versioned and backwards compatible). +- Tech-stack §8.4 (mapped from domain events, never from read models; event-carried state; a contract test pins each schema). +- ADR 0017 (handler, then cascade, then `SaveChangesAsync`: events and outgoing envelopes commit in one transaction). + +**CQRS split:** +- **Command side only.** `RegisterParty` and `UpdatePartyReferenceDataDirectoryEntry` still decide and append as today. When the decision accepts, they also return the mapped integration event as a cascaded message. A failed decision returns `null`, so nothing is published. +- **Query side:** unchanged. No view is read or added. Integration events are never built from `PartyReferenceDataDirectoryEntryView`. + +## Scope +### In scope +- **New project `src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/`** (namespace `RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage`, BCL only, no package reference). It is added to `RimBank.slnx` and referenced by `RimBank.Core`, and it has its own `packages.lock.json`. +- **Integration events (sealed records, BCL types only):** + - `PartyReferenceDataDirectoryEntryCreated`: `EventId` (Guid), `OccurredAt` (DateTimeOffset), `PartyReferenceDataDirectoryEntryId` (Guid), `Version` (long, the entry's stream version after this event), `PartyType` (string `Person` / `Organisation`), `DirectoryEntryDateType` (`OpenDate`), `DirectoryEntryDate` (the open date). + - `PartyReferenceDataDirectoryEntryUpdated`: the same fields, with `DirectoryEntryDateType` `RefreshDate` and the refresh date. + - Constants classes `PartyTypes` / `DirectoryEntryDateTypes` for the allowed strings. Strings, not enums, so a new value never breaks an older consumer's deserialisation. + - No PII and no BQ ids, because the only known consumer (4.1) needs "this party exists, of this type". `OccurredAt` is the domain event's date, so the mapping stays pure. Each event gets a new Guid v7 `EventId`. Consumers deduplicate and order on (`PartyReferenceDataDirectoryEntryId`, `Version`). +- **Versioning:** each event has a stable message identity, `party-reference-data-directory-entry.created.v1` and `….updated.v1`. It is assigned in the adapter wiring, so `.PublishedLanguage` keeps no Wolverine attribute. Changes may only add optional fields. A breaking change is a new `…V2` type, published next to v1 until consumers move. The schema snapshot enforces this. +- **Pure mapper in core** (`RimBank.Core/Party/PartyReferenceDataDirectory/Publication/PartyReferenceDataDirectoryPublication.cs`, flat namespace per ADR 0026): `Created(PartyRegistered, version, eventId)` and `Updated(PartyReferenceDataDirectoryEntryUpdated, version, eventId)`. BQ events have no mapping, because no published channel exists for them yet (ADR 0024), so their handlers publish nothing. +- **Handlers:** `RegisterPartyHandler` and `UpdatePartyReferenceDataDirectoryEntryHandler` return `(Result<…Acknowledged>, ?)`. This is the cascade pattern of the 0.11 fake ledger, with BCL types only and no Wolverine type in core. The event id comes from the handler's `TimeProvider` (`Guid.CreateVersion7`). +- **Wolverine:** each event declares `Channel` and `MessageIdentity` as constants. A shared naming strategy in `RimBank.Postgresql` (`PublishedLanguageMessageNaming`, registered by `AddServiceDomainStore`) gives any `*.PublishedLanguage` type its declared identity on the wire. The event goes through the party store's durable local queue: its envelope is in `party_reference_data_directory.wolverine_incoming_envelopes`, in the same transaction as the events (ADR 0017). With no subscriber in production yet, Wolverine logs it and discards it. That is accepted and documented: 4.1 adds the first consumer. +- **Schema contract:** a committed approved JSON schema per event (with its channel and identity), exported with `System.Text.Json.Schema.JsonSchemaExporter` using Wolverine's wire settings (camelCase), and compared in a test that also proves Wolverine writes the same names. +- **Catalogue:** `PartyReferenceDataDirectoryCatalogue` maps each CR channel to its CLR type, and the tests assert that each address exists in the AsyncAPI YAML. +- **Docs:** + - ADR 0036 (new); + - ADR 0024 integration-channel table: names the two types and identities, still in phase 1.13; + - tech-stack §3 tree and §8.4 (link to ADR 0036); + - CONTRIBUTING: a "changing a published event" note; + - roadmap 1.13 ticked. + +### Out of scope +- The 8 BQ channels (Demographics, Reference, Associations, BankRelations Created/Updated): deferred by ADR 0024 until a consumer needs them, and after the PII protection of 7.2. +- Any consumer, `.Subscriptions` project, inbox handling or local reference read model: 4.1–4.2. +- Full AsyncAPI conformance, including payload shape against the BIAN schema: 1.14. +- Authorisation of subscribers, and a RabbitMQ transport: 1.15, and context extraction (Stage 8+). +- Back-publishing events for entries registered before 1.13. No consumer exists yet, so there is nothing to replay. A later consumer rebuilds its copy from events published from now on, or an ADR in 4.1 decides a replay. + +## Decisions +| Decision | Choice | Rationale | +|---|---|---| +| Payload | Full CR state (id, type, date type and date) plus `EventId`, `OccurredAt`, `Version` | Event-carried state (§8.4); the version lets 4.1 drop duplicates and out-of-order events; no PII | +| Value types | Strings with constants classes, not enums | Unknown future values must not break older consumers (4.1 "tolerant of unknown fields") | +| Versioning | Stable message identity `…created.v1` / `…updated.v1`, additive changes only, a breaking change means a new type | A C# rename must not change the wire contract; `.PublishedLanguage` stays BCL only | +| Where the mapping lives | Pure mapper in `RimBank.Core` (`Publication/`), called by the command handlers | Business mapping belongs in core (memory: business logic in core); testable without I/O; uses the decided events, never a view | +| How it reaches the outbox | Handler cascade `(Result, Event?)` | Same transaction as the events (ADR 0017); a failed decision publishes nothing by construction; no Wolverine type in core | +| Contract test | `JsonSchemaExporter` (BCL) snapshot against a committed approved file | No new package (ADR 0013); a removed, renamed or retyped field fails | +| BQ channels | Not published | ADR 0024: no consumer yet, PII before 7.2 | + +## ADRs to write +- **ADR 0036, Party published language:** the event shape and envelope fields, string values, message identity and versioning rules, mapping through a handler cascade from decided domain events, the "no route until 4.1" consequence, and the schema snapshot as the compatibility gate. +- ADR 0024 amended (integration-channel table). + +## Open questions +- None. Resolved during implementation: Wolverine 6.62 has a public `IMessageTypeNaming` and `WolverineMessageNaming.InsertFirst()`, so the identity is a `const` on the BCL record, read by a naming strategy in `RimBank.Postgresql` (ADR 0036). diff --git a/specs/2026-11-08-party-published-language/validation.md b/specs/2026-11-08-party-published-language/validation.md new file mode 100644 index 0000000..4fa71f9 --- /dev/null +++ b/specs/2026-11-08-party-published-language/validation.md @@ -0,0 +1,43 @@ +# Validation: Party Reference Data Directory: published language + +## Done when (from roadmap) +> **1.13 Published language:** `PartyReferenceDataDirectoryEntryCreated/Updated` integration events, mapped from domain events (not from read models), carrying the state consumers need, versioned, published through the outbox, and pinned by a schema contract test. +> + Definition of done (roadmap.md) + +In practice: every accepted Register publishes one Created, and every accepted Update publishes one Updated, in the same transaction as the domain events. A rejected command publishes nothing. Both schemas are pinned by approved snapshots. + +## Automated checks +- [ ] **Core (Shouldly)** in `RimBank.Core.Tests`: + - `PartyReferenceDataDirectoryPublicationTests`: + - `PartyRegistered` maps to Created (`OpenDate`); + - `PartyReferenceDataDirectoryEntryUpdated` maps to Updated (`RefreshDate`); + - every party type has a published value, and an unknown one is refused; + - version, `OccurredAt` and the `PartyType` string are carried. + - Register and Update handler tests: one cascaded event on success, with the right version; `null` on `party.party-not-found`, `party.version-conflict` and decision errors. +- [ ] **PostgreSQL (Testcontainers)** `PublishedLanguageOutboxTests`: + - Register publishes exactly one Created (version 1), and Update exactly one Updated (version 2); + - a stale version, an unknown entry, an idempotent replay and a BQ Update publish nothing; + - the envelope (v1 identity, expected JSON payload) is in the context's own `wolverine_incoming_envelopes`, one per committed Control Record event. +- [ ] **Schema contract** `PartyPublishedLanguageSchemaTests`: + - the exported JSON schema of each event equals its committed approved file; + - removing, renaming or retyping a field fails the test; + - Wolverine writes the same property names; the round trip is stable; an unknown extra field is tolerated; each type goes on the wire under its identity. +- [ ] **Naming** `PublishedLanguageMessageNamingTests` (`RimBank.Postgresql.Tests`): a type outside `.PublishedLanguage` keeps Wolverine's name, and registering twice is harmless. +- [ ] **Catalogue / AsyncAPI** `PartyReferenceDataDirectoryCatalogueTests`: both CR channels (phase 1.13) have a CLR type, and their addresses exist in `asyncapi-3.x/yamls/PartyReferenceDataDirectory.yaml`. The BQ channels stay `deferred`. +- [ ] **Architecture tests** green: the new `.PublishedLanguage` project uses the BCL only and holds no views; only `RimBank.Core` (own context) references it; there is no Wolverine type in core. +- [ ] Existing API, MCP and Postgresql tests for Register and Update are unchanged and green (the acknowledgement and the responses are not affected). +- [ ] `dotnet format --verify-no-changes`, full `dotnet test`, CodeQL: green in GitHub Actions. + +## Manual / demo checks +- [ ] `dotnet run --project src/RimBank.AppHost`, then run the Register and Update requests of `src/RimBank.Host/RimBank.Host.http`: + - `200`/`201` responses unchanged; + - in the party schema, `wolverine_incoming_envelopes` (or the Aspire dashboard's Wolverine traces) shows one envelope per command, with the v1 message type; + - a stale `If-Match` returns `409` `party.version-conflict` Problem Details and produces no envelope. +- [ ] Paste the approved schema files and the demo trace in the PR description. + +## Merge criteria +- [ ] All checks above pass in CI +- [ ] Roadmap checkbox 1.13 ticked in the same PR +- [ ] ADR 0036 written; ADR 0024 integration-channel table updated +- [ ] No PII in the published events or in their logs (party type and dates only) +- [ ] tech-stack §3 and §8.4 and CONTRIBUTING updated diff --git a/specs/roadmap.md b/specs/roadmap.md index 0e23408..32ac28a 100644 --- a/specs/roadmap.md +++ b/specs/roadmap.md @@ -59,7 +59,7 @@ - [x] **1.11 Associations BQ:** party-to-party relationships as their own aggregate `PartyAssociation` (ADR 0024), with its own stream and inline view; Register/Update commands (owner and associate checked on the write side) and Retrieve query. It records the associate, the relationship type and the validity period ([ADR 0033](../docs/adr/0033-party-associations.md)). - [x] **1.21 Reference BQ: corporate and officer references:** `CorporateCustomerReference`, `CorporateCustomerLegalEntityReference`, `CompanyOfficerReference` and `CompanyOfficerRole`, references to other parties, added to the Reference Update and Retrieve after the Associations BQ (ADR 0032). Each reference is another registered entry, checked on the write side; they are recorded only on an organisation, the corporate customer and legal entity are organisations and the officer a person ([ADR 0034](../docs/adr/0034-reference-corporate-and-officer-references.md)). - [x] **1.12 BankRelations BQ:** the party's relationships with the bank; Update command and Retrieve query. It records a closed relation type, the bank employee (a person) or unit (an organisation) as a registered entry checked on the write side, and the relationship's dates and lifecycle status ([ADR 0035](../docs/adr/0035-party-bank-relations.md)). -- [ ] **1.13 Published language:** `PartyReferenceDataDirectoryEntryCreated/Updated` integration events, mapped from domain events (not from read models), carrying the state consumers need, versioned, published through the outbox, and pinned by a schema contract test. +- [x] **1.13 Published language:** `PartyReferenceDataDirectoryEntryCreated/Updated` integration events, mapped from domain events (not from read models), carrying the state consumers need, versioned, published through the outbox, and pinned by a schema contract test. - [ ] **1.14 Conformance:** OpenAPI and AsyncAPI conformance tests green for the implemented subset. - [ ] **1.15 Authorisation policies:** per-operation policies (separate scopes for command and query operations), with tests. - [ ] **1.16 MCP adapter: Register & Retrieve:** `RimBank.Party.PartyReferenceDataDirectory.Mcp` tools for Register (command) and Retrieve (query, `readOnly`), with a parity test against the HTTP endpoints. diff --git a/specs/tech-stack.md b/specs/tech-stack.md index c1b6e49..2f4e824 100644 --- a/specs/tech-stack.md +++ b/specs/tech-stack.md @@ -88,12 +88,12 @@ Before a service domain is created, its mapping must be checked against the BIAN │ │ ├─ (root) # namespace RimBank.Api: the Idempotency-Key header (ADR 0018), stream-version entity tags (ETag, If-None-Match, If-Match: ADR 0027) │ │ └─ Party/PartyReferenceDataDirectory/ # namespace RimBank.Party.PartyReferenceDataDirectory.Api for every folder: Registration/, Retrieval/, Update/, Demographics/, Reference/, Associations/, BankRelations/ │ ├─ RimBank.Mcp/ # MCP conventions at its root: Error → isError Problem Details, the tool error filter (ADR 0022); each context's tools as a folder from 1.16 (ADR 0025) -│ ├─ RimBank.Postgresql/ # Marten conventions every .Postgresql uses: per-context store, role, views, rebuild (ADR 0016); Wolverine wiring with write and read ports (ADR 0017); command idempotency (ADR 0018); one retry on a lost concurrency race (ADR 0027) +│ ├─ RimBank.Postgresql/ # Marten conventions every .Postgresql uses: per-context store, role, views, rebuild (ADR 0016); Wolverine wiring with write and read ports (ADR 0017); command idempotency (ADR 0018); one retry on a lost concurrency race (ADR 0027); published-language message identities (ADR 0036) │ ├─ RimBank.Core/ # the core of every context: domain + application logic, one folder per context (ADR 0023) │ │ ├─ Party/PartyReferenceDataDirectory/ # namespace RimBank.Party.PartyReferenceDataDirectory for every folder (§3.4, ADR 0026) │ │ └─ LoansAndDeposits/CurrentAccount/ # namespace RimBank.LoansAndDeposits.CurrentAccount │ └─ Party/ # a context's own adapter projects, each referencing RimBank.Core -│ ├─ RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/ +│ ├─ RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/ # BCL only: the integration events, each declaring its Channel and MessageIdentity (ADR 0036) │ ├─ RimBank.Party.PartyReferenceDataDirectory.Postgresql/ │ └─ RimBank.Party.PartyReferenceDataDirectory.Subscriptions/ # only when it consumes other contexts' events └─ tests/ @@ -205,6 +205,8 @@ RimBank.Core/Party/PartyReferenceDataDirectory/ # namespace RimBank.Party.P │ ├─ Events.cs # BankRelationsUpdated (decided by the entry's Decide) │ ├─ UpdateBankRelations.cs # command, with its acknowledgement and handler (which loads the referenced entry) │ └─ RetrieveBankRelations.cs # query over the entry's view, with its handler +├─ Publication/ # published language (1.13, ADR 0036) +│ └─ PartyReferenceDataDirectoryPublication.cs # pure mapper: decided entry events → .PublishedLanguage events, cascaded by the handlers ├─ IPartyDirectory.cs # write port: load and append the entry and association event streams └─ IPartyDirectoryEnquiry.cs # read port: query the entry and association views ``` @@ -319,7 +321,7 @@ CQRS is applied **logically everywhere** and **physically where needed**. Every ### 8.4 Read models across contexts (loose coupling) - **Ownership:** a view belongs to exactly one context and is reachable only through that context's read port, `.Api` and `.Mcp`. Views are never shared, never put in `.PublishedLanguage`, and never read by another context. -- **Producer side:** integration events are mapped from domain events (through the outbox), never from read models. They carry the state consumers need (event-carried state transfer), are versioned, and only change in backwards-compatible ways. A contract test pins each published event's schema. +- **Producer side:** integration events are mapped from domain events (through the outbox), never from read models. They carry the state consumers need (event-carried state transfer), are versioned, and only change in backwards-compatible ways. A contract test pins each published event's schema. Each event declares its BIAN `Channel` and a versioned `MessageIdentity` (for example `party-reference-data-directory-entry.created.v1`); the command handler maps it from the decided events with a pure mapper in core and returns it as a cascaded message, so it commits with the events ([ADR 0036](../docs/adr/0036-party-published-language.md)). - **Consumer side:** the `.Subscriptions` adapter receives the integration event (idempotently, through Wolverine's durable inbox), translates it into the consumer's own types, and records it as a local reference event in the consumer's own store. The local reference read model is projected from those local events, so it can be rebuilt **without the producer**. - **Cross-context requests are events, not commands.** A context never sends another context's command, because commands are internal to the context that owns them and are never in `.PublishedLanguage`. When context A needs context B to act, A publishes a request event in A's `.PublishedLanguage` (for example `PaymentOrderExecutionRequested`). B's `.Subscriptions` adapter turns it into one of B's own commands, decided by B's rules. B then publishes the outcome (for example `CurrentAccountPaymentExecuted` or `CurrentAccountPaymentRejected`), and A's `.Subscriptions` adapter reacts to it. The requesting record's identifier (for example the payment order ID) is the correlation ID and the idempotency key of the translated command, so a redelivered request never moves money twice. - **Minimal copies:** a local reference read model keeps only the fields its context needs (for example "party is known and active", not the party's demographics). This also limits the spread of PII. @@ -334,7 +336,7 @@ CQRS is applied **logically everywhere** and **physically where needed**. Every | Property-based | FsCheck | Money arithmetic, balance invariants, evolve/decide laws, projection/aggregate agreement | | Integration | Testcontainers (PostgreSQL), Alba | Marten persistence and projections (inline and async daemon), Wolverine outbox, HTTP endpoints end to end | | Architecture | ArchUnitNET | Dependency rules and CQRS rules in §4, naming rules in §3, cross-context isolation in §8.4 | -| Contract | OpenAPI/AsyncAPI conformance tests (`RimBank.Conformance.Testing`: Microsoft.OpenApi, YamlDotNet, [ADR 0020](../docs/adr/0020-bian-conformance-harness.md)); published-event schema snapshots | Implemented routes and channels exist in the BIAN v14 ext-DDD YAML with the spec's method, `Retrieve` is `GET` and nothing else is; published integration events stay backwards compatible | +| Contract | OpenAPI/AsyncAPI conformance tests (`RimBank.Conformance.Testing`: Microsoft.OpenApi, YamlDotNet, [ADR 0020](../docs/adr/0020-bian-conformance-harness.md)); published-event schema snapshots (`JsonSchemaExporter` against committed approved files, [ADR 0036](../docs/adr/0036-party-published-language.md)) | Implemented routes and channels exist in the BIAN v14 ext-DDD YAML with the spec's method, `Retrieve` is `GET` and nothing else is; published integration events stay backwards compatible | | MCP | MCP C# SDK client in-process against the test host | Tool list, input schemas, results, Problem Details errors, and parity with the HTTP endpoint for the same operation | | Mutation (later) | Stryker.NET | The `RimBank.Core` folders of money-moving domains (`--mutate "//**"`) | diff --git a/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/packages.lock.json b/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/packages.lock.json index b14bf15..859a332 100644 --- a/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/packages.lock.json +++ b/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/packages.lock.json @@ -453,9 +453,13 @@ "rimbank.core": { "type": "Project", "dependencies": { + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "RimBank.SharedKernel": "[0.1.0-alpha, )" } }, + "rimbank.party.partyreferencedatadirectory.publishedlanguage": { + "type": "Project" + }, "rimbank.postgresql": { "type": "Project", "dependencies": { diff --git a/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/DirectoryEntryDateTypes.cs b/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/DirectoryEntryDateTypes.cs new file mode 100644 index 0000000..4b65d52 --- /dev/null +++ b/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/DirectoryEntryDateTypes.cs @@ -0,0 +1,14 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; + +/// +/// The values of DirectoryEntryDateType in a published event (BIAN Directoryentrydatetypevalues): which +/// date of the entry DirectoryEntryDate is (ADR 0036). +/// +public static class DirectoryEntryDateTypes +{ + /// When the entry was registered. + public const string OpenDate = "OpenDate"; + + /// When the entry was last updated. + public const string RefreshDate = "RefreshDate"; +} diff --git a/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/PartyReferenceDataDirectoryEntryCreated.cs b/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/PartyReferenceDataDirectoryEntryCreated.cs new file mode 100644 index 0000000..964b061 --- /dev/null +++ b/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/PartyReferenceDataDirectoryEntryCreated.cs @@ -0,0 +1,29 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; + +/// +/// A party was registered in the directory: BIAN channel PartyReferenceDataDirectoryEntry/Created, message +/// identity party-reference-data-directory-entry.created.v1 (ADR 0036). It carries the Control Record's state, +/// so a consumer needs no callback. Fields are only ever added, never removed, renamed or retyped. +/// +/// This event's own id; a redelivery carries the same one. +/// When the party was registered. +/// The new entry. +/// The entry's version after this event (1): consumers order and deduplicate on it. +/// A value. +/// Always . +/// The entry's open date. +public sealed record PartyReferenceDataDirectoryEntryCreated( + Guid EventId, + DateTimeOffset OccurredAt, + Guid PartyReferenceDataDirectoryEntryId, + long Version, + string PartyType, + string DirectoryEntryDateType, + DateTimeOffset DirectoryEntryDate) +{ + /// The BIAN AsyncAPI channel this event is published on. + public const string Channel = "PartyReferenceDataDirectoryEntry/Created"; + + /// The stable message identity on the wire; a breaking change publishes a new type with a new identity. + public const string MessageIdentity = "party-reference-data-directory-entry.created.v1"; +} diff --git a/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/PartyReferenceDataDirectoryEntryUpdated.cs b/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/PartyReferenceDataDirectoryEntryUpdated.cs new file mode 100644 index 0000000..c3ab12e --- /dev/null +++ b/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/PartyReferenceDataDirectoryEntryUpdated.cs @@ -0,0 +1,29 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; + +/// +/// A party's directory entry was updated: BIAN channel PartyReferenceDataDirectoryEntry/Updated, message +/// identity party-reference-data-directory-entry.updated.v1 (ADR 0036). It carries the Control Record's state +/// after the update, so a consumer needs no callback. Fields are only ever added, never removed, renamed or retyped. +/// +/// This event's own id; a redelivery carries the same one. +/// When the entry was updated. +/// The entry. +/// The entry's version after this event: consumers order and deduplicate on it. +/// A value: the entry's party type from now on. +/// Always . +/// The entry's refresh date. +public sealed record PartyReferenceDataDirectoryEntryUpdated( + Guid EventId, + DateTimeOffset OccurredAt, + Guid PartyReferenceDataDirectoryEntryId, + long Version, + string PartyType, + string DirectoryEntryDateType, + DateTimeOffset DirectoryEntryDate) +{ + /// The BIAN AsyncAPI channel this event is published on. + public const string Channel = "PartyReferenceDataDirectoryEntry/Updated"; + + /// The stable message identity on the wire; a breaking change publishes a new type with a new identity. + public const string MessageIdentity = "party-reference-data-directory-entry.updated.v1"; +} diff --git a/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/PartyTypes.cs b/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/PartyTypes.cs new file mode 100644 index 0000000..cc15c92 --- /dev/null +++ b/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/PartyTypes.cs @@ -0,0 +1,14 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; + +/// +/// The values of PartyType in a published event (BIAN Partytypevalues). They are strings, not an enum, +/// so a value added later never breaks an older consumer (ADR 0036). +/// +public static class PartyTypes +{ + /// A human being. + public const string Person = "Person"; + + /// An organised structure: a business, government body, charity or financial institution. + public const string Organisation = "Organisation"; +} diff --git a/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage.csproj b/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage.csproj new file mode 100644 index 0000000..350de54 --- /dev/null +++ b/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage.csproj @@ -0,0 +1,10 @@ + + + + RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage + + diff --git a/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/packages.lock.json b/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/packages.lock.json new file mode 100644 index 0000000..6afd678 --- /dev/null +++ b/src/Party/RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/packages.lock.json @@ -0,0 +1,6 @@ +{ + "version": 2, + "dependencies": { + "net10.0": {} + } +} \ No newline at end of file diff --git a/src/RimBank.Api/packages.lock.json b/src/RimBank.Api/packages.lock.json index 61c80bd..b49489e 100644 --- a/src/RimBank.Api/packages.lock.json +++ b/src/RimBank.Api/packages.lock.json @@ -92,9 +92,13 @@ "rimbank.core": { "type": "Project", "dependencies": { + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "RimBank.SharedKernel": "[0.1.0-alpha, )" } }, + "rimbank.party.partyreferencedatadirectory.publishedlanguage": { + "type": "Project" + }, "rimbank.problems": { "type": "Project", "dependencies": { diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Publication/PartyReferenceDataDirectoryPublication.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Publication/PartyReferenceDataDirectoryPublication.cs new file mode 100644 index 0000000..86f66d1 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Publication/PartyReferenceDataDirectoryPublication.cs @@ -0,0 +1,56 @@ +using Published = RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// Maps the entry's decided domain events to the context's published language (ADR 0024, ADR 0036). It reads only the +/// domain event, never a view (tech-stack §8.4), and holds no I/O: the command handler supplies the stream version +/// the event produced and a new event id, and cascades the result into the outbox in the same transaction. +/// Only the Control Record is published; the Behavior Qualifier events have no published channel yet (ADR 0024). +/// +public static class PartyReferenceDataDirectoryPublication +{ + /// Maps a registration to PartyReferenceDataDirectoryEntry/Created. + /// The decided event. + /// The entry's stream version after the event. + /// The integration event's own id. + /// The integration event. + public static Published.PartyReferenceDataDirectoryEntryCreated Created(PartyRegistered registered, long version, Guid eventId) + { + ArgumentNullException.ThrowIfNull(registered); + return new Published.PartyReferenceDataDirectoryEntryCreated( + eventId, + registered.OpenDate, + registered.EntryId.Value, + version, + Publish(registered.PartyType), + Published.DirectoryEntryDateTypes.OpenDate, + registered.OpenDate); + } + + /// Maps an update of the entry to PartyReferenceDataDirectoryEntry/Updated. + /// The decided event. + /// The entry's stream version after the event. + /// The integration event's own id. + /// The integration event. + public static Published.PartyReferenceDataDirectoryEntryUpdated Updated(PartyReferenceDataDirectoryEntryUpdated updated, long version, Guid eventId) + { + ArgumentNullException.ThrowIfNull(updated); + return new Published.PartyReferenceDataDirectoryEntryUpdated( + eventId, + updated.RefreshDate, + updated.EntryId.Value, + version, + Publish(updated.PartyType), + Published.DirectoryEntryDateTypes.RefreshDate, + updated.RefreshDate); + } + + private static string Publish(PartyType partyType) => + partyType switch + { + PartyType.Person => Published.PartyTypes.Person, + PartyType.Organisation => Published.PartyTypes.Organisation, + _ => throw new ArgumentOutOfRangeException(nameof(partyType), partyType, "Not a party type."), + }; +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Registration/RegisterPartyHandler.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Registration/RegisterPartyHandler.cs index bc17018..f220708 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Registration/RegisterPartyHandler.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Registration/RegisterPartyHandler.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using RimBank.SharedKernel; +using Published = RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; namespace RimBank.Party.PartyReferenceDataDirectory; @@ -9,13 +10,18 @@ public static class RegisterPartyHandler /// /// Creates the entry id, the ids of its Demographics, Reference and BankRelations, and the open date; decides /// Register against the entry's stored history; and starts the entry's stream only when the decision accepts. + /// An accepted registration also publishes PartyReferenceDataDirectoryEntry/Created, mapped from the decided + /// event and cascaded into the outbox in the same transaction (ADR 0036). /// /// The command. /// The context's write port. /// The clock for the new ids and the open date. /// Cancels the load. - /// The acknowledgement built from the decided state, or the decision's . - public static async Task> HandleAsync( + /// + /// The acknowledgement built from the decided state with the integration event to publish, or the decision's + /// with nothing to publish. + /// + public static async Task<(Result Outcome, Published.PartyReferenceDataDirectoryEntryCreated? Created)> HandleAsync( RegisterParty command, IPartyDirectory directory, TimeProvider time, @@ -36,13 +42,27 @@ public static async Task> HandleAsync( var history = await directory.LoadEntryAsync(register.EntryId, cancellationToken); var state = history.Aggregate(PartyReferenceDataDirectoryEntry.Initial, PartyReferenceDataDirectoryEntry.Evolve); - return PartyReferenceDataDirectoryEntry.Decide(register, state).Map(events => - { - directory.StartEntry(register.EntryId, events); - return Acknowledge(events.Aggregate(state, PartyReferenceDataDirectoryEntry.Evolve), history.Count + events.Count); - }); + return PartyReferenceDataDirectoryEntry.Decide(register, state).Match<(Result, Published.PartyReferenceDataDirectoryEntryCreated?)>( + events => + { + directory.StartEntry(register.EntryId, events); + return ( + Acknowledge(events.Aggregate(state, PartyReferenceDataDirectoryEntry.Evolve), history.Count + events.Count), + Publish(events, history.Count, time)); + }, + error => (error, null)); } + private static Published.PartyReferenceDataDirectoryEntryCreated? Publish( + IReadOnlyList events, + long versionBefore, + TimeProvider time) => + events + .Select((domainEvent, index) => domainEvent is PartyRegistered registered + ? PartyReferenceDataDirectoryPublication.Created(registered, versionBefore + index + 1, Guid.CreateVersion7(time.GetUtcNow())) + : null) + .SingleOrDefault(published => published is not null); + private static RegisterPartyAcknowledged Acknowledge(PartyReferenceDataDirectoryEntry registered, long version) => registered switch { diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryHandler.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryHandler.cs index a4273ed..ac6706c 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryHandler.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryHandler.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using RimBank.SharedKernel; +using Published = RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; namespace RimBank.Party.PartyReferenceDataDirectory; @@ -9,17 +10,20 @@ public static class UpdatePartyReferenceDataDirectoryEntryHandler /// /// Loads the entry, checks that it exists and that the caller's expected version is its current stream version, /// decides Update with the current time as the refresh date, and appends the events with that expected version, so - /// the commit also fails if another writer appended in between. + /// the commit also fails if another writer appended in between. An accepted update also publishes + /// PartyReferenceDataDirectoryEntry/Updated, mapped from the decided event and cascaded into the outbox in + /// the same transaction (ADR 0036). /// /// The command. /// The context's write port. /// The clock for the refresh date. /// Cancels the load. /// - /// The acknowledgement built from the decided state, party.party-not-found, party.version-conflict, - /// or the decision's . + /// The acknowledgement built from the decided state with the integration event to publish; or + /// party.party-not-found, party.version-conflict or the decision's , with nothing + /// to publish. /// - public static async Task> HandleAsync( + public static async Task<(Result Outcome, Published.PartyReferenceDataDirectoryEntryUpdated? Updated)> HandleAsync( UpdatePartyReferenceDataDirectoryEntry command, IPartyDirectory directory, TimeProvider time, @@ -34,18 +38,32 @@ public static async Task PartyReferenceDataDirectoryEntryErrors.PartyNotFound, - (true, false) => PartyReferenceDataDirectoryEntryErrors.VersionConflict, + (false, _) => (PartyReferenceDataDirectoryEntryErrors.PartyNotFound, null), + (true, false) => (PartyReferenceDataDirectoryEntryErrors.VersionConflict, null), (true, true) => PartyReferenceDataDirectoryEntry .Decide(new UpdatePartyReferenceDataDirectoryEntryDetails(command.PartyType, time.GetUtcNow()), state) - .Map(events => - { - directory.AppendToEntry(command.EntryId, command.ExpectedVersion, events); - return Acknowledge(events.Aggregate(state, PartyReferenceDataDirectoryEntry.Evolve), history.Count + events.Count); - }), + .Match<(Result, Published.PartyReferenceDataDirectoryEntryUpdated?)>( + events => + { + directory.AppendToEntry(command.EntryId, command.ExpectedVersion, events); + return ( + Acknowledge(events.Aggregate(state, PartyReferenceDataDirectoryEntry.Evolve), history.Count + events.Count), + Publish(events, history.Count, time)); + }, + error => (error, null)), }; } + private static Published.PartyReferenceDataDirectoryEntryUpdated? Publish( + IReadOnlyList events, + long versionBefore, + TimeProvider time) => + events + .Select((domainEvent, index) => domainEvent is PartyReferenceDataDirectoryEntryUpdated updated + ? PartyReferenceDataDirectoryPublication.Updated(updated, versionBefore + index + 1, Guid.CreateVersion7(time.GetUtcNow())) + : null) + .SingleOrDefault(published => published is not null); + private static UpdatePartyReferenceDataDirectoryEntryAcknowledged Acknowledge(PartyReferenceDataDirectoryEntry updated, long version) => updated switch { diff --git a/src/RimBank.Core/RimBank.Core.csproj b/src/RimBank.Core/RimBank.Core.csproj index 8217adb..9e34a9e 100644 --- a/src/RimBank.Core/RimBank.Core.csproj +++ b/src/RimBank.Core/RimBank.Core.csproj @@ -11,5 +11,6 @@ + diff --git a/src/RimBank.Core/packages.lock.json b/src/RimBank.Core/packages.lock.json index f33bdf0..f7b1295 100644 --- a/src/RimBank.Core/packages.lock.json +++ b/src/RimBank.Core/packages.lock.json @@ -2,6 +2,9 @@ "version": 2, "dependencies": { "net10.0": { + "rimbank.party.partyreferencedatadirectory.publishedlanguage": { + "type": "Project" + }, "rimbank.sharedkernel": { "type": "Project" } diff --git a/src/RimBank.Host/RimBank.Host.http b/src/RimBank.Host/RimBank.Host.http index 54b5cc8..080fa23 100644 --- a/src/RimBank.Host/RimBank.Host.http +++ b/src/RimBank.Host/RimBank.Host.http @@ -35,6 +35,9 @@ GET {{host}}/PartyReferenceDataDirectory/does-not-exist/Retrieve Authorization: Bearer {{token.response.body.$.access_token}} ### Party Reference Data Directory (ADR 0024): register a party. The ETag of the answer is the entry's version, "1". +# It also publishes party-reference-data-directory-entry.created.v1 (roadmap 1.13, ADR 0036), and each accepted Update +# below publishes …updated.v1; a refused one publishes nothing. See them in the party schema: +# SELECT message_type, received_at FROM party_reference_data_directory.wolverine_incoming_envelopes; # @name register POST {{host}}/PartyReferenceDataDirectory/Register Authorization: Bearer {{token.response.body.$.access_token}} diff --git a/src/RimBank.Host/packages.lock.json b/src/RimBank.Host/packages.lock.json index a25892c..2945b72 100644 --- a/src/RimBank.Host/packages.lock.json +++ b/src/RimBank.Host/packages.lock.json @@ -588,6 +588,7 @@ "rimbank.core": { "type": "Project", "dependencies": { + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "RimBank.SharedKernel": "[0.1.0-alpha, )" } }, @@ -606,6 +607,9 @@ "RimBank.Postgresql": "[0.1.0-alpha, )" } }, + "rimbank.party.partyreferencedatadirectory.publishedlanguage": { + "type": "Project" + }, "rimbank.postgresql": { "type": "Project", "dependencies": { diff --git a/src/RimBank.Postgresql/PublishedLanguageMessageNaming.cs b/src/RimBank.Postgresql/PublishedLanguageMessageNaming.cs new file mode 100644 index 0000000..88488fd --- /dev/null +++ b/src/RimBank.Postgresql/PublishedLanguageMessageNaming.cs @@ -0,0 +1,50 @@ +using System.Reflection; +using Wolverine.Util; + +namespace RimBank.Postgresql; + +/// +/// Gives every integration event of a context's .PublishedLanguage its stable wire identity: the value of its +/// public const string MessageIdentity (ADR 0036). The published language stays BCL only, so it carries the +/// identity as a constant rather than a Wolverine attribute, and renaming or moving the CLR type never changes the +/// contract. Every other message keeps Wolverine's default name. +/// +public sealed class PublishedLanguageMessageNaming : IMessageTypeNaming +{ + /// The namespace suffix of a context's published language (specs/tech-stack.md §3). + public const string PublishedLanguageSuffix = ".PublishedLanguage"; + + /// The name of the constant that holds a published event's message identity. + public const string MessageIdentityField = "MessageIdentity"; + + private static int _registered; + + /// Adds this naming ahead of Wolverine's own, once per process: Wolverine's naming is static. + public static void Register() + { + if (Interlocked.Exchange(ref _registered, 1) == 0) + { + WolverineMessageNaming.InsertFirst(); + } + } + + /// The message identity a published event declares, or for any other type. + /// The message type. + /// The declared identity, if any. + public static string? DeclaredIdentity(Type messageType) + { + ArgumentNullException.ThrowIfNull(messageType); + return messageType.Namespace?.EndsWith(PublishedLanguageSuffix, StringComparison.Ordinal) == true + && messageType.GetField(MessageIdentityField, BindingFlags.Public | BindingFlags.Static) is { IsLiteral: true } field + && field.GetRawConstantValue() is string { Length: > 0 } identity + ? identity + : null; + } + + /// + public bool TryDetermineName(Type messageType, out string messageTypeName) + { + messageTypeName = DeclaredIdentity(messageType)!; + return messageTypeName is not null; + } +} diff --git a/src/RimBank.Postgresql/ServiceDomainStoreRegistration.cs b/src/RimBank.Postgresql/ServiceDomainStoreRegistration.cs index aab09f5..2c54ac3 100644 --- a/src/RimBank.Postgresql/ServiceDomainStoreRegistration.cs +++ b/src/RimBank.Postgresql/ServiceDomainStoreRegistration.cs @@ -64,6 +64,9 @@ public static IHostApplicationBuilder AddServiceDomainStore(this var production = builder.Environment.IsProduction(); AddDatabaseAccess(services, name); + // The context's integration events go on the wire under their declared, versioned identity (ADR 0036). + PublishedLanguageMessageNaming.Register(); + var store = services .AddMartenStore(provider => { diff --git a/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/PartyHost.cs b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/PartyHost.cs index b6c826a..3b62208 100644 --- a/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/PartyHost.cs +++ b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/PartyHost.cs @@ -17,6 +17,9 @@ public sealed class PartyHost(IHost host, NpgsqlDataSource administrator) : IAsy /// The host's message bus, as an .Api or .Mcp adapter uses it. public IMessageBus Bus => host.Services.GetRequiredService(); + /// The running host itself, for Wolverine's message tracking. + public IHost Application => host; + /// Runs a single-value query as the administrator, to look at what was stored. public async Task ScalarAsync(string sql) { diff --git a/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/Approved/party-reference-data-directory-entry.created.v1.approved.json b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/Approved/party-reference-data-directory-entry.created.v1.approved.json new file mode 100644 index 0000000..12d56cd --- /dev/null +++ b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/Approved/party-reference-data-directory-entry.created.v1.approved.json @@ -0,0 +1,43 @@ +{ + "channel": "PartyReferenceDataDirectoryEntry/Created", + "messageIdentity": "party-reference-data-directory-entry.created.v1", + "schema": { + "type": "object", + "properties": { + "eventId": { + "type": "string", + "format": "uuid" + }, + "occurredAt": { + "type": "string", + "format": "date-time" + }, + "partyReferenceDataDirectoryEntryId": { + "type": "string", + "format": "uuid" + }, + "version": { + "type": "integer" + }, + "partyType": { + "type": "string" + }, + "directoryEntryDateType": { + "type": "string" + }, + "directoryEntryDate": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "eventId", + "occurredAt", + "partyReferenceDataDirectoryEntryId", + "version", + "partyType", + "directoryEntryDateType", + "directoryEntryDate" + ] + } +} diff --git a/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/Approved/party-reference-data-directory-entry.updated.v1.approved.json b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/Approved/party-reference-data-directory-entry.updated.v1.approved.json new file mode 100644 index 0000000..38ee65a --- /dev/null +++ b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/Approved/party-reference-data-directory-entry.updated.v1.approved.json @@ -0,0 +1,43 @@ +{ + "channel": "PartyReferenceDataDirectoryEntry/Updated", + "messageIdentity": "party-reference-data-directory-entry.updated.v1", + "schema": { + "type": "object", + "properties": { + "eventId": { + "type": "string", + "format": "uuid" + }, + "occurredAt": { + "type": "string", + "format": "date-time" + }, + "partyReferenceDataDirectoryEntryId": { + "type": "string", + "format": "uuid" + }, + "version": { + "type": "integer" + }, + "partyType": { + "type": "string" + }, + "directoryEntryDateType": { + "type": "string" + }, + "directoryEntryDate": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "eventId", + "occurredAt", + "partyReferenceDataDirectoryEntryId", + "version", + "partyType", + "directoryEntryDateType", + "directoryEntryDate" + ] + } +} diff --git a/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/PartyPublishedLanguageSchemaTests.cs b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/PartyPublishedLanguageSchemaTests.cs new file mode 100644 index 0000000..343b2f5 --- /dev/null +++ b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/PartyPublishedLanguageSchemaTests.cs @@ -0,0 +1,137 @@ +using System.Runtime.CompilerServices; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Schema; +using RimBank.Postgresql; +using Wolverine; +using Wolverine.Util; +using Published = RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; + +namespace RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests; + +// Roadmap 1.13: the schema contract of the published language (ADR 0036). Each published event's JSON schema on the +// wire, with its channel and message identity, is pinned by an approved file next to this test. A field removed, +// renamed or retyped, or a changed identity, fails here; an added field fails too, until the approved file is +// updated on purpose in the same pull request. On a mismatch the test writes .received.json beside it. +public sealed class PartyPublishedLanguageSchemaTests +{ + // Wolverine's default System.Text.Json settings for messages (camelCase, case-insensitive reads, strict numbers). + // The wire_names test below proves they still match what Wolverine writes. + private static readonly JsonSerializerOptions _wire = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true, + }; + + private static readonly JsonSerializerOptions _approvedFile = new() + { + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + private static readonly DateTimeOffset _at = new(2026, 11, 8, 10, 0, 0, TimeSpan.Zero); + private static readonly Guid _eventId = Guid.CreateVersion7(_at); + private static readonly Guid _entryId = Guid.CreateVersion7(_at); + + public static TheoryData PublishedEvents { get; } = + [.. typeof(Published.PartyTypes).Assembly.GetExportedTypes() + .Where(type => type.GetField(PublishedLanguageMessageNaming.MessageIdentityField) is not null) + .OrderBy(type => type.FullName, StringComparer.Ordinal)]; + + [Fact] + public void The_published_language_holds_the_two_control_record_events() + { + PublishedEvents.Select(row => row.Data).ShouldBe( + [typeof(Published.PartyReferenceDataDirectoryEntryCreated), typeof(Published.PartyReferenceDataDirectoryEntryUpdated)], + ignoreOrder: true); + } + + [Theory] + [MemberData(nameof(PublishedEvents))] + public void The_schema_on_the_wire_matches_the_approved_contract(Type published) + { + var identity = PublishedLanguageMessageNaming.DeclaredIdentity(published).ShouldNotBeNull(); + var contract = new JsonObject + { + ["channel"] = (string?)published.GetField("Channel")?.GetRawConstantValue(), + ["messageIdentity"] = identity, + ["schema"] = JsonSchemaExporter.GetJsonSchemaAsNode( + _wire, + published, + new JsonSchemaExporterOptions { TreatNullObliviousAsNonNullable = true }), + }; + var received = contract.ToJsonString(_approvedFile).ReplaceLineEndings("\n") + "\n"; + var approvedPath = ApprovedPath(identity); + var receivedPath = Path.ChangeExtension(approvedPath, null).Replace(".approved", ".received", StringComparison.Ordinal) + ".json"; + + var approved = File.Exists(approvedPath) ? File.ReadAllText(approvedPath).ReplaceLineEndings("\n") : null; + if (approved == received) + { + File.Delete(receivedPath); + return; + } + + File.WriteAllText(receivedPath, received); + approved.ShouldBe( + received, + $"The published contract of {identity} changed. A breaking change needs a new versioned event (ADR 0036). " + + $"If the change only adds a field, review {receivedPath} and copy it over {approvedPath}."); + } + + [Theory] + [MemberData(nameof(PublishedEvents))] + public void Every_published_event_goes_on_the_wire_under_its_declared_identity(Type published) + { + PublishedLanguageMessageNaming.Register(); + + var identity = PublishedLanguageMessageNaming.DeclaredIdentity(published).ShouldNotBeNull(); + + identity.ShouldMatch(@"^[a-z]+(-[a-z]+)*\.[a-z]+\.v[1-9][0-9]*$"); + published.ToMessageTypeName().ShouldBe(identity); + } + + [Fact] + public void The_wire_names_are_the_ones_Wolverine_writes() + { + var created = Created(); + + var written = JsonNode.Parse(new WolverineOptions().DefaultSerializer.WriteMessage(created))!.AsObject(); + + written.Select(property => property.Key).ShouldBe( + JsonSerializer.SerializeToNode(created, _wire)!.AsObject().Select(property => property.Key)); + } + + [Fact] + public void A_published_event_survives_the_wire_round_trip() + { + var serializer = new WolverineOptions().DefaultSerializer; + object[] events = [Created(), Updated()]; + + events.Select(published => serializer.ReadFromData(published.GetType(), new Envelope { Data = serializer.WriteMessage(published) })) + .ShouldBe(events); + } + + [Fact] + public void A_consumer_reading_v1_tolerates_a_field_added_later() + { + var serializer = new WolverineOptions().DefaultSerializer; + var payload = JsonSerializer.SerializeToNode(Created(), _wire)!.AsObject(); + payload["addedLater"] = "a value an older consumer does not know"; + + var read = serializer.ReadFromData( + typeof(Published.PartyReferenceDataDirectoryEntryCreated), + new Envelope { Data = JsonSerializer.SerializeToUtf8Bytes(payload) }); + + read.ShouldBe(Created()); + } + + private static Published.PartyReferenceDataDirectoryEntryCreated Created() => + new(_eventId, _at, _entryId, 1, Published.PartyTypes.Person, Published.DirectoryEntryDateTypes.OpenDate, _at); + + private static Published.PartyReferenceDataDirectoryEntryUpdated Updated() => + new(_eventId, _at, _entryId, 2, Published.PartyTypes.Organisation, Published.DirectoryEntryDateTypes.RefreshDate, _at); + + private static string ApprovedPath(string identity, [CallerFilePath] string thisFile = "") => + Path.Combine(Path.GetDirectoryName(thisFile)!, "Approved", identity + ".approved.json"); +} diff --git a/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/PublishedLanguageOutboxTests.cs b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/PublishedLanguageOutboxTests.cs new file mode 100644 index 0000000..2685554 --- /dev/null +++ b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/Publication/PublishedLanguageOutboxTests.cs @@ -0,0 +1,176 @@ +using System.Text.Json; +using RimBank.SharedKernel; +using Wolverine.Tracking; +using Published = RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; + +namespace RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests; + +// Roadmap 1.13: an accepted Register or Update publishes exactly one integration event, saved under its v1 identity in +// the context's own schema in the same transaction as the domain events, and a refused, replayed or Behavior Qualifier +// command publishes none (ADR 0017, ADR 0036). +public sealed class PublishedLanguageOutboxTests(PostgresqlServer server) +{ + private const string Schema = "party_reference_data_directory"; + + private static readonly JsonSerializerOptions _wire = new(JsonSerializerDefaults.Web); + + private static CancellationToken Cancellation => TestContext.Current.CancellationToken; + + [Fact] + public async Task Registering_a_party_publishes_the_entry_created_once_under_its_v1_identity() + { + await using var host = await server.StartHostAsync(); + + var (session, outcome) = await TrackAsync(host, new RegisterParty(PartyType.Organisation, NewKey())); + + var registered = outcome.Value; + var created = session.Sent.MessagesOf().ShouldHaveSingleItem(); + created.ShouldBe(new Published.PartyReferenceDataDirectoryEntryCreated( + created.EventId, + PostgresqlServer.Now, + registered.EntryId.Value, + 1, + Published.PartyTypes.Organisation, + Published.DirectoryEntryDateTypes.OpenDate, + PostgresqlServer.Now)); + session.Sent.AllMessages().OfType().ShouldBeEmpty(); + (await StoredAsync(host, Published.PartyReferenceDataDirectoryEntryCreated.MessageIdentity)) + .ShouldBe([created]); + } + + [Fact] + public async Task Updating_an_entry_publishes_the_entry_updated_once_at_its_new_version() + { + await using var host = await server.StartHostAsync(); + var registered = await RegisterAsync(host); + + var (session, outcome) = await TrackAsync( + host, + new UpdatePartyReferenceDataDirectoryEntry(registered.EntryId, 1, PartyType.Organisation, NewKey())); + + outcome.IsSuccess.ShouldBeTrue(); + var updated = session.Sent.MessagesOf().ShouldHaveSingleItem(); + updated.ShouldBe(new Published.PartyReferenceDataDirectoryEntryUpdated( + updated.EventId, + PostgresqlServer.Now, + registered.EntryId.Value, + 2, + Published.PartyTypes.Organisation, + Published.DirectoryEntryDateTypes.RefreshDate, + PostgresqlServer.Now)); + (await StoredAsync(host, Published.PartyReferenceDataDirectoryEntryUpdated.MessageIdentity)) + .ShouldBe([updated]); + } + + [Fact] + public async Task An_update_at_a_stale_version_publishes_nothing() + { + await using var host = await server.StartHostAsync(); + var registered = await RegisterAsync(host); + await host.Bus.InvokeAsync>( + new UpdatePartyReferenceDataDirectoryEntry(registered.EntryId, 1, PartyType.Organisation, NewKey()), + Cancellation); + + var (session, outcome) = await TrackAsync( + host, + new UpdatePartyReferenceDataDirectoryEntry(registered.EntryId, 1, PartyType.Person, NewKey())); + + outcome.Error.ShouldBe(PartyReferenceDataDirectoryEntryErrors.VersionConflict); + PublishedIn(session).ShouldBeEmpty(); + (await EnvelopesAsync(host, Published.PartyReferenceDataDirectoryEntryUpdated.MessageIdentity)).ShouldBe(1); + } + + [Fact] + public async Task An_update_of_an_unknown_entry_publishes_nothing() + { + await using var host = await server.StartHostAsync(); + + var (session, outcome) = await TrackAsync( + host, + new UpdatePartyReferenceDataDirectoryEntry(PartyReferenceDataDirectoryEntryId.New(TimeProvider.System), 1, PartyType.Person, NewKey())); + + outcome.Error.ShouldBe(PartyReferenceDataDirectoryEntryErrors.PartyNotFound); + PublishedIn(session).ShouldBeEmpty(); + (await EnvelopesAsync(host, Published.PartyReferenceDataDirectoryEntryUpdated.MessageIdentity)).ShouldBe(0); + } + + [Fact] + public async Task A_replayed_registration_publishes_nothing_again() + { + await using var host = await server.StartHostAsync(); + var key = NewKey(); + var first = await TrackAsync(host, new RegisterParty(PartyType.Person, key)); + + var (replay, outcome) = await TrackAsync(host, new RegisterParty(PartyType.Person, key)); + + outcome.Value.ShouldBe(first.Outcome.Value); + PublishedIn(replay).ShouldBeEmpty(); + (await EnvelopesAsync(host, Published.PartyReferenceDataDirectoryEntryCreated.MessageIdentity)).ShouldBe(1); + } + + [Fact] + public async Task A_behavior_qualifier_update_publishes_nothing() + { + await using var host = await server.StartHostAsync(); + var registered = await RegisterAsync(host); + + var (session, outcome) = await TrackAsync( + host, + new UpdateDemographics( + registered.EntryId, + registered.DemographicsId, + 1, + new DemographicsChanges("B2", null, null, null, null), + NewKey())); + + outcome.IsSuccess.ShouldBeTrue(); + PublishedIn(session).ShouldBeEmpty(); + } + + [Fact] + public async Task Every_committed_control_record_event_has_exactly_one_published_envelope() + { + await using var host = await server.StartHostAsync(); + var registered = await RegisterAsync(host); + await host.Bus.InvokeAsync>( + new UpdatePartyReferenceDataDirectoryEntry(registered.EntryId, 1, PartyType.Organisation, NewKey()), + Cancellation); + await host.Bus.InvokeAsync>( + new UpdatePartyReferenceDataDirectoryEntry(registered.EntryId, 1, PartyType.Person, NewKey()), + Cancellation); + + var registrations = await host.ScalarAsync($"SELECT count(*) FROM {Schema}.mt_events WHERE type = 'party_registered'"); + var updates = await host.ScalarAsync($"SELECT count(*) FROM {Schema}.mt_events WHERE type = 'party_reference_data_directory_entry_updated'"); + + (registrations, updates).ShouldBe((1L, 1L)); + (await EnvelopesAsync(host, Published.PartyReferenceDataDirectoryEntryCreated.MessageIdentity)).ShouldBe(registrations); + (await EnvelopesAsync(host, Published.PartyReferenceDataDirectoryEntryUpdated.MessageIdentity)).ShouldBe(updates); + (await host.ScalarAsync("SELECT count(*) FROM wolverine.wolverine_incoming_envelopes WHERE message_type LIKE 'party-reference-data-directory-entry.%'")) + .ShouldBe(0); + } + + private static async Task<(ITrackedSession Session, Result Outcome)> TrackAsync(PartyHost host, object command) + { + var (session, outcome) = await host.Application.InvokeMessageAndWaitAsync>(command, 30_000); + return (session, outcome.ShouldNotBeNull()); + } + + private static object[] PublishedIn(ITrackedSession session) => + [.. session.Sent.AllMessages().Where(message => message.GetType().Namespace == typeof(Published.PartyTypes).Namespace)]; + + private static async Task RegisterAsync(PartyHost host) => + (await host.Bus.InvokeAsync>(new RegisterParty(PartyType.Person, NewKey()), Cancellation)).Value; + + private static Task EnvelopesAsync(PartyHost host, string identity) => + host.ScalarAsync($"SELECT count(*) FROM {Schema}.wolverine_incoming_envelopes WHERE message_type = '{identity}'"); + + // The stored envelope ends with the message as it goes on the wire: Wolverine's headers, then the JSON payload. + private static async Task StoredAsync(PartyHost host, string identity) + { + var body = await host.ScalarAsync($"SELECT body FROM {Schema}.wolverine_incoming_envelopes WHERE message_type = '{identity}'"); + var payload = body.AsSpan(body.AsSpan().IndexOf("{\""u8)); + return [JsonSerializer.Deserialize(payload, _wire)]; + } + + private static IdempotencyKey NewKey() => IdempotencyKey.From(Guid.CreateVersion7().ToString()); +} diff --git a/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/packages.lock.json b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/packages.lock.json index 07563b6..5ceef8b 100644 --- a/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/packages.lock.json +++ b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/packages.lock.json @@ -930,6 +930,7 @@ "rimbank.core": { "type": "Project", "dependencies": { + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "RimBank.SharedKernel": "[0.1.0-alpha, )" } }, @@ -940,6 +941,9 @@ "RimBank.Postgresql": "[0.1.0-alpha, )" } }, + "rimbank.party.partyreferencedatadirectory.publishedlanguage": { + "type": "Project" + }, "rimbank.postgresql": { "type": "Project", "dependencies": { diff --git a/tests/RimBank.Api.Tests/packages.lock.json b/tests/RimBank.Api.Tests/packages.lock.json index fcc3952..d33a50e 100644 --- a/tests/RimBank.Api.Tests/packages.lock.json +++ b/tests/RimBank.Api.Tests/packages.lock.json @@ -1213,6 +1213,7 @@ "rimbank.core": { "type": "Project", "dependencies": { + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "RimBank.SharedKernel": "[0.1.0-alpha, )" } }, @@ -1251,6 +1252,9 @@ "RimBank.Postgresql": "[0.1.0-alpha, )" } }, + "rimbank.party.partyreferencedatadirectory.publishedlanguage": { + "type": "Project" + }, "rimbank.postgresql": { "type": "Project", "dependencies": { diff --git a/tests/RimBank.Architecture.Tests/RimBank.Architecture.Tests.csproj b/tests/RimBank.Architecture.Tests/RimBank.Architecture.Tests.csproj index 803fb3a..ad0a7c4 100644 --- a/tests/RimBank.Architecture.Tests/RimBank.Architecture.Tests.csproj +++ b/tests/RimBank.Architecture.Tests/RimBank.Architecture.Tests.csproj @@ -21,6 +21,7 @@ + diff --git a/tests/RimBank.Architecture.Tests/SolutionRulesTests.cs b/tests/RimBank.Architecture.Tests/SolutionRulesTests.cs index 9d90cc0..e13c756 100644 --- a/tests/RimBank.Architecture.Tests/SolutionRulesTests.cs +++ b/tests/RimBank.Architecture.Tests/SolutionRulesTests.cs @@ -35,6 +35,7 @@ public void The_solution_loads_every_project_and_never_the_fixtures() "RimBank.Mcp.Tests", "RimBank.Party.PartyReferenceDataDirectory.Postgresql", "RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests", + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage", "RimBank.Problems", "RimBank.Problems.Tests", "RimBank.Postgresql", diff --git a/tests/RimBank.Architecture.Tests/packages.linux-x64.lock.json b/tests/RimBank.Architecture.Tests/packages.linux-x64.lock.json index da98f8e..18984cc 100644 --- a/tests/RimBank.Architecture.Tests/packages.linux-x64.lock.json +++ b/tests/RimBank.Architecture.Tests/packages.linux-x64.lock.json @@ -1559,6 +1559,7 @@ "dependencies": { "Microsoft.AspNetCore.Mvc.Testing": "[10.0.14, )", "RimBank.Conformance.Testing": "[0.1.0-alpha, )", + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "Shouldly": "[4.3.0, )", "xunit.v3": "[4.0.2, )" } @@ -1566,6 +1567,7 @@ "rimbank.core": { "type": "Project", "dependencies": { + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "RimBank.SharedKernel": "[0.1.0-alpha, )" } }, @@ -1644,6 +1646,9 @@ "xunit.v3": "[4.0.2, )" } }, + "rimbank.party.partyreferencedatadirectory.publishedlanguage": { + "type": "Project" + }, "rimbank.postgresql": { "type": "Project", "dependencies": { diff --git a/tests/RimBank.Architecture.Tests/packages.win-x64.lock.json b/tests/RimBank.Architecture.Tests/packages.win-x64.lock.json index 8244171..e196589 100644 --- a/tests/RimBank.Architecture.Tests/packages.win-x64.lock.json +++ b/tests/RimBank.Architecture.Tests/packages.win-x64.lock.json @@ -1559,6 +1559,7 @@ "dependencies": { "Microsoft.AspNetCore.Mvc.Testing": "[10.0.14, )", "RimBank.Conformance.Testing": "[0.1.0-alpha, )", + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "Shouldly": "[4.3.0, )", "xunit.v3": "[4.0.2, )" } @@ -1566,6 +1567,7 @@ "rimbank.core": { "type": "Project", "dependencies": { + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "RimBank.SharedKernel": "[0.1.0-alpha, )" } }, @@ -1644,6 +1646,9 @@ "xunit.v3": "[4.0.2, )" } }, + "rimbank.party.partyreferencedatadirectory.publishedlanguage": { + "type": "Project" + }, "rimbank.postgresql": { "type": "Project", "dependencies": { diff --git a/tests/RimBank.Conformance.Tests/Catalogues/PartyReferenceDataDirectoryCatalogue.cs b/tests/RimBank.Conformance.Tests/Catalogues/PartyReferenceDataDirectoryCatalogue.cs index c607227..cb8724c 100644 --- a/tests/RimBank.Conformance.Tests/Catalogues/PartyReferenceDataDirectoryCatalogue.cs +++ b/tests/RimBank.Conformance.Tests/Catalogues/PartyReferenceDataDirectoryCatalogue.cs @@ -1,4 +1,5 @@ using RimBank.Conformance.Testing; +using RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; namespace RimBank.Conformance.Tests; @@ -11,7 +12,8 @@ public sealed record CataloguedOperation(string OperationId, BianOperationKind K /// One BIAN AsyncAPI channel of a service domain, as an ADR maps it. /// The channel address, for example PartyReferenceDataDirectoryEntry/Created. /// The roadmap phase that publishes it, or . -public sealed record CataloguedChannel(string Address, string Phase); +/// The integration event published on it (ADR 0036), or while it is deferred. +public sealed record CataloguedChannel(string Address, string Phase, Type? PublishedEvent = null); // Roadmap 1.1: the operation and channel tables of ADR 0024 (docs/adr/0024-party-reference-data-directory-mapping.md) // as data, pinned to the real BIAN v14 specifications by PartyReferenceDataDirectoryCatalogueTests. @@ -49,8 +51,8 @@ public static class PartyReferenceDataDirectoryCatalogue /// Every channel of the AsyncAPI specification. public static IReadOnlyList Channels { get; } = [ - new("PartyReferenceDataDirectoryEntry/Created", "1.13"), - new("PartyReferenceDataDirectoryEntry/Updated", "1.13"), + new("PartyReferenceDataDirectoryEntry/Created", "1.13", typeof(PartyReferenceDataDirectoryEntryCreated)), + new("PartyReferenceDataDirectoryEntry/Updated", "1.13", typeof(PartyReferenceDataDirectoryEntryUpdated)), new("Demographics/Created", Deferred), new("Demographics/Updated", Deferred), new("Reference/Created", Deferred), diff --git a/tests/RimBank.Conformance.Tests/Catalogues/PartyReferenceDataDirectoryCatalogueTests.cs b/tests/RimBank.Conformance.Tests/Catalogues/PartyReferenceDataDirectoryCatalogueTests.cs index 46f2148..a8af88c 100644 --- a/tests/RimBank.Conformance.Tests/Catalogues/PartyReferenceDataDirectoryCatalogueTests.cs +++ b/tests/RimBank.Conformance.Tests/Catalogues/PartyReferenceDataDirectoryCatalogueTests.cs @@ -55,6 +55,21 @@ public void Phases_are_stage_one_or_deferred() .ShouldBeEmpty(); } + [Fact] + public async Task Each_published_channel_has_its_event_and_each_deferred_channel_has_none() + { + var specification = await BianSpecifications.LoadAsync(PartyReferenceDataDirectoryCatalogue.ServiceDomain); + var published = PartyReferenceDataDirectoryCatalogue.Channels.Where(row => row.PublishedEvent is not null).ToList(); + + PartyReferenceDataDirectoryCatalogue.Channels + .Where(row => (row.Phase == PartyReferenceDataDirectoryCatalogue.Deferred) == (row.PublishedEvent is not null)) + .Select(row => row.Address) + .ShouldBeEmpty("a channel has an event exactly when it is not deferred"); + published.Select(row => $"{row.Address} <- {row.PublishedEvent!.GetField("Channel")?.GetRawConstantValue()}") + .ShouldBe(published.Select(row => $"{row.Address} <- {row.Address}"), "each event declares the channel it is catalogued on"); + published.Select(row => row.Address).ShouldBeChannelsOf(specification); + } + private static List Duplicates(IEnumerable values) => values.GroupBy(value => value, StringComparer.Ordinal).Where(group => group.Count() > 1).Select(group => group.Key).ToList(); diff --git a/tests/RimBank.Conformance.Tests/RimBank.Conformance.Tests.csproj b/tests/RimBank.Conformance.Tests/RimBank.Conformance.Tests.csproj index 696e911..0d93c33 100644 --- a/tests/RimBank.Conformance.Tests/RimBank.Conformance.Tests.csproj +++ b/tests/RimBank.Conformance.Tests/RimBank.Conformance.Tests.csproj @@ -20,6 +20,7 @@ + diff --git a/tests/RimBank.Conformance.Tests/packages.lock.json b/tests/RimBank.Conformance.Tests/packages.lock.json index f9ef0b1..603dcac 100644 --- a/tests/RimBank.Conformance.Tests/packages.lock.json +++ b/tests/RimBank.Conformance.Tests/packages.lock.json @@ -192,6 +192,9 @@ "YamlDotNet": "[18.1.0, )" } }, + "rimbank.party.partyreferencedatadirectory.publishedlanguage": { + "type": "Project" + }, "Microsoft.OpenApi": { "type": "CentralTransitive", "requested": "[2.13.0, )", diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Publication/PartyReferenceDataDirectoryPublicationTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Publication/PartyReferenceDataDirectoryPublicationTests.cs new file mode 100644 index 0000000..e13eca4 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Publication/PartyReferenceDataDirectoryPublicationTests.cs @@ -0,0 +1,59 @@ +using static RimBank.Party.PartyReferenceDataDirectory.Tests.EntryExamples; +using Published = RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// Roadmap 1.13: the Control Record's domain events mapped to the published language (ADR 0024, ADR 0036). The mapping +// reads the decided event only, never a view, and carries the state a consumer needs. +public sealed class PartyReferenceDataDirectoryPublicationTests +{ + private static readonly Guid _eventId = Guid.CreateVersion7(OpenDate); + + [Theory] + [InlineData(PartyType.Person, Published.PartyTypes.Person)] + [InlineData(PartyType.Organisation, Published.PartyTypes.Organisation)] + public void A_registration_is_published_as_the_entry_created_with_its_open_date(PartyType partyType, string publishedPartyType) + { + var created = PartyReferenceDataDirectoryPublication.Created(Registered(partyType), 1, _eventId); + + created.ShouldBe(new Published.PartyReferenceDataDirectoryEntryCreated( + _eventId, + OpenDate, + EntryId.Value, + 1, + publishedPartyType, + Published.DirectoryEntryDateTypes.OpenDate, + OpenDate)); + } + + [Theory] + [InlineData(PartyType.Person, Published.PartyTypes.Person)] + [InlineData(PartyType.Organisation, Published.PartyTypes.Organisation)] + public void An_update_is_published_as_the_entry_updated_with_its_refresh_date(PartyType partyType, string publishedPartyType) + { + var updated = PartyReferenceDataDirectoryPublication.Updated(Updated(partyType), 7, _eventId); + + updated.ShouldBe(new Published.PartyReferenceDataDirectoryEntryUpdated( + _eventId, + RefreshDate, + EntryId.Value, + 7, + publishedPartyType, + Published.DirectoryEntryDateTypes.RefreshDate, + RefreshDate)); + } + + [Fact] + public void Every_party_type_has_a_published_value() + { + Enum.GetValues() + .Select(partyType => PartyReferenceDataDirectoryPublication.Created(Registered(partyType), 1, _eventId).PartyType) + .ShouldBe([Published.PartyTypes.Person, Published.PartyTypes.Organisation]); + } + + [Fact] + public void A_value_outside_the_party_types_is_never_published() + { + Should.Throw(() => PartyReferenceDataDirectoryPublication.Created(Registered((PartyType)99), 1, _eventId)); + } +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Registration/RegisterPartyHandlerTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Registration/RegisterPartyHandlerTests.cs index 72f59e8..892d14f 100644 --- a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Registration/RegisterPartyHandlerTests.cs +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Registration/RegisterPartyHandlerTests.cs @@ -2,6 +2,7 @@ using RimBank.SharedKernel; using RimBank.SharedKernel.Testing; using static RimBank.Party.PartyReferenceDataDirectory.Tests.EntryExamples; +using Published = RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; namespace RimBank.Party.PartyReferenceDataDirectory.Tests; @@ -87,12 +88,13 @@ public async Task An_entry_that_is_already_registered_is_refused_and_nothing_is_ { var directory = new EveryEntryRegisteredDirectory(); - var result = await RegisterPartyHandler.HandleAsync( + var (result, created) = await RegisterPartyHandler.HandleAsync( new RegisterParty(PartyType.Person, IdempotencyKey.From("register-1")), directory, _time, TestContext.Current.CancellationToken); + created.ShouldBeNull(); result.IsFailure.ShouldBeTrue(); result.Error.Kind.ShouldBe(ErrorKind.Conflict); result.Error.Code.ShouldBe("party.party-already-registered"); @@ -124,7 +126,42 @@ public async Task The_acknowledgement_survives_a_json_round_trip() JsonSerializer.Deserialize(json, _json).ShouldBe(acknowledged); } - private Task> Register(PartyType partyType = PartyType.Person, string key = "register-1") => + [Theory] + [InlineData(PartyType.Person, Published.PartyTypes.Person)] + [InlineData(PartyType.Organisation, Published.PartyTypes.Organisation)] + public async Task An_accepted_registration_publishes_the_entry_created_at_version_1(PartyType partyType, string publishedPartyType) + { + var (result, created) = await Handle(partyType); + + var acknowledged = result.Value; + var published = created.ShouldNotBeNull(); + published.ShouldBe(new Published.PartyReferenceDataDirectoryEntryCreated( + published.EventId, + OpenDate, + acknowledged.EntryId.Value, + 1, + publishedPartyType, + Published.DirectoryEntryDateTypes.OpenDate, + OpenDate)); + published.EventId.Version.ShouldBe(7); + published.EventId.ShouldNotBe(acknowledged.EntryId.Value); + } + + [Fact] + public async Task A_refused_registration_publishes_nothing() + { + var (result, created) = await Handle((PartyType)99); + + result.IsFailure.ShouldBeTrue(); + created.ShouldBeNull(); + } + + private async Task> Register(PartyType partyType = PartyType.Person, string key = "register-1") => + (await Handle(partyType, key)).Outcome; + + private Task<(Result Outcome, Published.PartyReferenceDataDirectoryEntryCreated? Created)> Handle( + PartyType partyType = PartyType.Person, + string key = "register-1") => RegisterPartyHandler.HandleAsync( new RegisterParty(partyType, IdempotencyKey.From(key)), _directory, diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryHandlerTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryHandlerTests.cs index 5764b13..204bf97 100644 --- a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryHandlerTests.cs +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryHandlerTests.cs @@ -2,6 +2,7 @@ using RimBank.SharedKernel; using RimBank.SharedKernel.Testing; using static RimBank.Party.PartyReferenceDataDirectory.Tests.EntryExamples; +using Published = RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; namespace RimBank.Party.PartyReferenceDataDirectory.Tests; @@ -104,7 +105,59 @@ public async Task The_acknowledgement_survives_a_json_round_trip() JsonSerializer.Deserialize(json, _json).ShouldBe(acknowledged); } - private Task> Update(long expectedVersion, PartyType? partyType) => + [Fact] + public async Task An_accepted_update_publishes_the_entry_updated_at_its_new_version() + { + _directory.Seed(EntryId, Registered(PartyType.Person), Updated(PartyType.Organisation)); + + var (result, updated) = await Handle(expectedVersion: 2, PartyType.Person); + + result.IsSuccess.ShouldBeTrue(); + var published = updated.ShouldNotBeNull(); + published.ShouldBe(new Published.PartyReferenceDataDirectoryEntryUpdated( + published.EventId, + RefreshDate, + EntryId.Value, + 3, + Published.PartyTypes.Person, + Published.DirectoryEntryDateTypes.RefreshDate, + RefreshDate)); + published.EventId.Version.ShouldBe(7); + } + + [Fact] + public async Task An_update_that_keeps_the_party_type_still_publishes_the_full_state() + { + _directory.Seed(EntryId, Registered(PartyType.Organisation)); + + var (_, updated) = await Handle(expectedVersion: 1, partyType: null); + + updated.ShouldNotBeNull().PartyType.ShouldBe(Published.PartyTypes.Organisation); + } + + [Theory] + [InlineData(true, 1, 1)] + [InlineData(false, 0, 1)] + [InlineData(false, 1, 99)] + public async Task A_refused_update_publishes_nothing(bool unknownEntry, long expectedVersion, int partyType) + { + if (!unknownEntry) + { + _directory.Seed(EntryId, Registered()); + } + + var (result, updated) = await Handle(expectedVersion, (PartyType)partyType); + + result.IsFailure.ShouldBeTrue(); + updated.ShouldBeNull(); + } + + private async Task> Update(long expectedVersion, PartyType? partyType) => + (await Handle(expectedVersion, partyType)).Outcome; + + private Task<(Result Outcome, Published.PartyReferenceDataDirectoryEntryUpdated? Updated)> Handle( + long expectedVersion, + PartyType? partyType) => UpdatePartyReferenceDataDirectoryEntryHandler.HandleAsync( new UpdatePartyReferenceDataDirectoryEntry(EntryId, expectedVersion, partyType, IdempotencyKey.From("update-1")), _directory, diff --git a/tests/RimBank.Core.Tests/packages.lock.json b/tests/RimBank.Core.Tests/packages.lock.json index 5470f7a..87ba23c 100644 --- a/tests/RimBank.Core.Tests/packages.lock.json +++ b/tests/RimBank.Core.Tests/packages.lock.json @@ -177,9 +177,13 @@ "rimbank.core": { "type": "Project", "dependencies": { + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "RimBank.SharedKernel": "[0.1.0-alpha, )" } }, + "rimbank.party.partyreferencedatadirectory.publishedlanguage": { + "type": "Project" + }, "rimbank.sharedkernel": { "type": "Project" }, diff --git a/tests/RimBank.Host.Testing/packages.lock.json b/tests/RimBank.Host.Testing/packages.lock.json index 7df2800..549b89a 100644 --- a/tests/RimBank.Host.Testing/packages.lock.json +++ b/tests/RimBank.Host.Testing/packages.lock.json @@ -905,6 +905,7 @@ "rimbank.core": { "type": "Project", "dependencies": { + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "RimBank.SharedKernel": "[0.1.0-alpha, )" } }, @@ -937,6 +938,9 @@ "RimBank.Postgresql": "[0.1.0-alpha, )" } }, + "rimbank.party.partyreferencedatadirectory.publishedlanguage": { + "type": "Project" + }, "rimbank.postgresql": { "type": "Project", "dependencies": { diff --git a/tests/RimBank.Host.Tests/packages.lock.json b/tests/RimBank.Host.Tests/packages.lock.json index 83c2259..59b11d8 100644 --- a/tests/RimBank.Host.Tests/packages.lock.json +++ b/tests/RimBank.Host.Tests/packages.lock.json @@ -1077,6 +1077,7 @@ "rimbank.core": { "type": "Project", "dependencies": { + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "RimBank.SharedKernel": "[0.1.0-alpha, )" } }, @@ -1115,6 +1116,9 @@ "RimBank.Postgresql": "[0.1.0-alpha, )" } }, + "rimbank.party.partyreferencedatadirectory.publishedlanguage": { + "type": "Project" + }, "rimbank.postgresql": { "type": "Project", "dependencies": { diff --git a/tests/RimBank.Postgresql.Tests/Messaging/PublishedLanguageMessageNamingTests.cs b/tests/RimBank.Postgresql.Tests/Messaging/PublishedLanguageMessageNamingTests.cs new file mode 100644 index 0000000..4da98bb --- /dev/null +++ b/tests/RimBank.Postgresql.Tests/Messaging/PublishedLanguageMessageNamingTests.cs @@ -0,0 +1,34 @@ +namespace RimBank.Postgresql.Tests; + +// Roadmap 1.13: only a context's .PublishedLanguage gets a declared wire identity; every other message, even one that +// happens to have a MessageIdentity constant, keeps Wolverine's default name (ADR 0036). The positive case runs on the +// real Party events in PartyPublishedLanguageSchemaTests. +public sealed class PublishedLanguageMessageNamingTests +{ + [Fact] + public void A_message_outside_a_published_language_has_no_declared_identity() + { + PublishedLanguageMessageNaming.DeclaredIdentity(typeof(NotPublished)).ShouldBeNull(); + new PublishedLanguageMessageNaming().TryDetermineName(typeof(NotPublished), out _).ShouldBeFalse(); + } + + [Fact] + public void A_message_without_the_constant_has_no_declared_identity() + { + PublishedLanguageMessageNaming.DeclaredIdentity(typeof(string)).ShouldBeNull(); + } + + [Fact] + public void Registering_twice_is_harmless() + { + PublishedLanguageMessageNaming.Register(); + PublishedLanguageMessageNaming.Register(); + + Wolverine.Util.WolverineMessageNaming.ToMessageTypeName(typeof(NotPublished)).ShouldNotBe(NotPublished.MessageIdentity); + } + + private sealed record NotPublished + { + public const string MessageIdentity = "not-published.v1"; + } +}