@oxface/modular-monolith-patterns 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,135 @@
1
+ # First protected state-stored module
2
+
3
+ Use this route for one application-selected operation backed by native EF/PostgreSQL,
4
+ tenant ownership and accepted-change audit. Start with [structure](structure.md) and
5
+ [bootstrap](bootstrap.md); the application team chooses the module, business behavior,
6
+ identity mapping, admission and permissions.
7
+
8
+ ## 1. Select packages and matching examples
9
+
10
+ Use the [package and version instructions](gloaming.md#package-integration) to configure the
11
+ NuGet source and pin the selected roots to one published version. Current packages target .NET 10.
12
+ Select a compatible native PostgreSQL EF provider and pin its version in the application.
13
+
14
+ | Application responsibility | Selected packages |
15
+ | --- | --- |
16
+ | Actor and tenant values/accessors | `Gloaming.ActorIdentity`, `Gloaming.Tenancy` |
17
+ | Native HTTP context establishment | `Gloaming.ActorIdentity.AspNetCore`, `Gloaming.Tenancy.AspNetCore` |
18
+ | EF ownership mapping and save protection | `Gloaming.Persistence.EntityFrameworkCore` |
19
+ | Explicit transactional audit | `Gloaming.Auditing.EntityFrameworkCore` |
20
+ | Native PostgreSQL persistence | `Npgsql.EntityFrameworkCore.PostgreSQL` |
21
+
22
+ Reference packages from the projects that use their APIs. The host selects the HTTP adapters;
23
+ the module owns its persistence and audit wiring. Follow transitive Gloaming dependencies from
24
+ the selected package version. Add RLS, command receipts or durable messaging when the requested
25
+ behavior requires their separate guarantees.
26
+
27
+ Use these executable examples at the adopted source revision:
28
+
29
+ - [Independent HTTP consumer](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/eng/release/consumers/HttpEstablishment.cs): native authentication, actor mapping, tenant admission and failed requests.
30
+ - [Personnel consumer](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/eng/release/consumers/PersonnelSlice.cs): versioned module migration, tenant-owned business rows, guarded saving and transactional history.
31
+ - [Ownership example](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Persistence/samples/PersistenceDemo/README.md): separate contexts, schemas and migration histories.
32
+
33
+ The Personnel example's entities and membership/permission rules are disposable test policy.
34
+ Its direct invocation proves neither HTTP authentication nor production RLS; use it to locate
35
+ the native persistence and transaction composition.
36
+
37
+ ## 2. Establish a request before resolving protected persistence
38
+
39
+ Register native authentication/authorization and implement the application's actor resolver
40
+ and tenant admission resolver. Follow the exact
41
+ [actor](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.ActorIdentity/Gloaming.ActorIdentity.AspNetCore/README.md) and
42
+ [tenant](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Tenancy/Gloaming.Tenancy.AspNetCore/README.md)
43
+ registration contracts. Their HTTP pipeline is:
44
+
45
+ ```csharp
46
+ app.UseRouting();
47
+ app.UseAuthentication();
48
+ app.UseAuthorization();
49
+ app.UseHttpActorContext();
50
+ app.UseHttpTenantContext();
51
+ ```
52
+
53
+ The actor adapter establishes after the policy's authentication and before its authorization
54
+ handlers; the completion middleware also covers policy-free requests. Tenant admission follows
55
+ authorization and actor completion. Native authorization handlers therefore cannot use the
56
+ selected tenant. Perform tenant-aware resource permission checks in the module operation after
57
+ admission, before business changes or history disclosure.
58
+
59
+ Resolve the protected scoped DbContext only after the required contexts are established.
60
+ Keep anonymous and tenantless endpoints explicit. A selected tenant or attributed actor alone
61
+ does not grant a business permission.
62
+ An application's global account/membership registry may need to resolve identity and admission
63
+ before tenancy exists. Its explicit query policy is separate from this walkthrough's tenant-owned
64
+ business context; proving registry access alone does not prove persistence ownership protection.
65
+
66
+ ## 3. Map the module and deploy its migration
67
+
68
+ Create the module's Contracts and implementation, scoped native DbContext, schema, migration
69
+ history and named connection. Register its operation implementation and DbContext explicitly
70
+ through the composition root; endpoints call Contracts. Use the
71
+ [module steps](modules.md#common-module-steps) for dependencies and commit ownership.
72
+ Keep individual native `IEntityTypeConfiguration<T>` classes in the owning module.
73
+
74
+ For the first path, follow the Personnel consumer's manual save integration:
75
+
76
+ - Map protected business rows with `HasTenantOwnership`, using the established tenant getter.
77
+ Supply owner values and complete tenant-bearing keys/relationships in the module.
78
+ - Map history through `ConfigureAudit`, select PostgreSQL `jsonb` for `Details`, and configure
79
+ tenant visibility for audit reads explicitly. Audit mapping supplies no tenant query filter.
80
+ - Call `ValidateTenantChanges` and `ValidateAuditChanges` before the base implementation in
81
+ both `SaveChanges(bool)` and `SaveChangesAsync(bool, CancellationToken)` overrides.
82
+ - Register `IAudit<ModuleDbContext>` with `EfAudit<ModuleDbContext>` in native scoped DI,
83
+ substituting the owning context type. Ownership mapping and validators are described in the
84
+ [ownership contract](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Persistence/Gloaming.Persistence.EntityFrameworkCore/README.md);
85
+ audit setup is in the
86
+ [audit contract](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Auditing/Gloaming.Auditing.EntityFrameworkCore/README.md).
87
+
88
+ The typed save coordinator is an alternative to these overrides; choose one integration for
89
+ the context. It still leaves save/commit with the native operation owner.
90
+
91
+ Apply the module's versioned migration through the finite Migrator before runtime work.
92
+ Keep setup credentials separate from runtime credentials. If RLS is selected, deploy its
93
+ policies/grants and transaction-local tenant setup before protected reads and writes; the
94
+ ownership query filter and save guards do not establish that database protection.
95
+
96
+ ## 4. Implement one accepted operation and its read
97
+
98
+ In a fresh admitted operation scope, resolve the owning context and begin a native transaction.
99
+ Load the tenant-visible resource, check current resource permission and expected business
100
+ version, then apply the module's accepted change. Stage its explicitly selected `AuditEntry`
101
+ through `IAudit<ModuleDbContext>` in that same transaction. The module chooses the action,
102
+ subject, actor/tenant attribution, clock, ID and versioned safe details.
103
+
104
+ Call native save and commit before returning the accepted Contract result. Audit staging
105
+ neither saves nor commits, and its guard cannot detect a business change that omitted staging.
106
+ On failure, roll back/dispose the transaction and context. Reconcile an uncertain commit from
107
+ fresh state before repeating a business action; add logical receipts when retained action/result
108
+ recovery is required.
109
+
110
+ Expose the corresponding read through Contracts with current permission and tenant predicates.
111
+ Protect history disclosure as well as the business row. Record the transaction owner and
112
+ configuration names in the application's architecture/setup documentation.
113
+
114
+ ## 5. Prove the slice with the native provider
115
+
116
+ Use the application's own integration suite and actual PostgreSQL to show:
117
+
118
+ - An accepted operation commits exactly the expected business change and audit attribution/details.
119
+ - A denied or newly suspended operation commits neither business changes nor accepted-change audit.
120
+ - Direct Contracts calls reject an unauthorized actor or inadmissible tenant even when HTTP
121
+ middleware is absent; include history reads as well as writes.
122
+ - Two tenants can use equal resource IDs while business and history reads remain isolated.
123
+ - Invalid/stale work and a native SQL failure preserve the earlier committed state.
124
+ - Rollback after saving removes both proposed business and history writes; a fresh operation recovers.
125
+ - Every supported sync/async save path runs the selected guards.
126
+
127
+ Inject a real database failure into a selected audited operation, then query from fresh state
128
+ to prove both business and audit writes rolled back. Verify restricted runtime credentials
129
+ cannot alter the schema or update/delete accepted-change audit, while permitted operations work.
130
+
131
+ The [full verification guide](verification.md) adds host startup, migration failure and actual
132
+ OIDC checks when those are selected. The
133
+ [package-adoption guide](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/eng/release/README.md#full-package-adoption-proof)
134
+ describes the separate Gloaming-owned proof and its PostgreSQL prerequisites. Run those library
135
+ proof commands from the Gloaming checkout; run the new module's acceptance tests in its application.
@@ -0,0 +1,69 @@
1
+ # Select Gloaming capabilities
2
+
3
+ These patterns work with native .NET composition. Add a Gloaming capability only where its
4
+ documented guarantee removes a technical obligation in the consuming application.
5
+ The package README is authoritative for the version in use.
6
+
7
+ ## Package integration
8
+
9
+ Select published Gloaming packages from NuGet.org and pin the roots the application needs.
10
+ Keep dependency locks and check the selected package's target framework, native dependencies
11
+ and public contract. Keep application project references inside the application; consume
12
+ technical libraries as packages.
13
+
14
+ For changes to Gloaming itself, use native SDK candidate packing and the
15
+ [package-only proofs](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/eng/release/README.md).
16
+ The first public release starts at 0.1.0; use an actually published version in an application.
17
+
18
+ ### Distribution boundary
19
+
20
+ [Release operations](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/docs/releases.md) describes
21
+ hosted NuGet/npm delivery. Applications own their package pins, locks, migrations and upgrade
22
+ acceptance. A temporary candidate folder is useful for testing unpublished changes; it is not
23
+ required application infrastructure. Rebuilding source need not reproduce an existing archive's
24
+ bytes. Never replace an already published version with changed source.
25
+
26
+ ### Read contracts for the adopted version
27
+
28
+ Start with the README included in the chosen package. Its nuspec repository commit identifies
29
+ the corresponding source revision. The source links in these patterns point to main for
30
+ navigation; inspect the selected revision when applying an older package's contract. A built
31
+ skill pins those links to its own source revision. Later changes on main do not change the
32
+ package or the consuming application's selected version.
33
+
34
+ For one protected EF/PostgreSQL operation, the [first-module walkthrough](first-module.md)
35
+ identifies the selected packages and executable examples.
36
+
37
+ | Requirement | Contract and selection |
38
+ | --- | --- |
39
+ | Actor/initiator attribution | [ActorIdentity](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.ActorIdentity/README.md), with optional native HTTP establishment |
40
+ | Selected tenant/tenantless context | [Tenancy](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Tenancy/README.md), independent of actor identity |
41
+ | Ownership/protected saves and optional RLS | [Persistence](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Persistence/README.md) |
42
+ | Ordered native save preparation/validation | [EntityFrameworkCore](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.EntityFrameworkCore/README.md) |
43
+ | Event-sourced aggregate writes/replay | [EventSourcing](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.EventSourcing/README.md) |
44
+ | Stable JSON event names/upcasting/history | [Events](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Events/README.md) |
45
+ | Local fact capture/reactions | [EventReactions](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.EventReactions/README.md) |
46
+ | Explicit accepted-change audit | [Auditing](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Auditing/README.md) |
47
+ | Logical action/result retention | [CommandReceipts](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.CommandReceipts/README.md) |
48
+ | Durable inbox/outbox and selected continuations | [Messaging](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Messaging/README.md) |
49
+
50
+ ## Integration obligations
51
+
52
+ Bind registrations and model/save configuration to the same typed context. For every selected
53
+ capability, account for native sync and async saving, required transaction isolation,
54
+ failure disposal and its supported mapping constraints. Use the save coordinator where its
55
+ ordered phases help; it does not create a generic transaction middleware or silently commit.
56
+
57
+ Establish required immutable actor/tenant context before resolving protected scoped persistence.
58
+ HTTP and worker ingress have different admission paths. RLS also requires native policies,
59
+ restricted credentials and transaction-local setup for reads as well as writes.
60
+
61
+ Keep explicit mappings, connection/credential roles, migrations and deployment ordering in the
62
+ application. Library scope or tenant metadata does not authorize access. Select transport-specific
63
+ packages only for the routes that need them.
64
+
65
+ ## Reference application
66
+
67
+ [Wholesale](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/samples/Wholesale/README.md) shows native
68
+ composition across Access, Sales and Inventory. Use its wiring and proof boundaries as examples;
69
+ application users, grants, stock rules, SQL roles and exact module graph are its own policy.
@@ -0,0 +1,142 @@
1
+ # Native Kafka delivery with PostgreSQL inbox/outbox
2
+
3
+ Compose Kafka through the existing `IMessagePublisher` and typed PostgreSQL inbox/outbox
4
+ interfaces. The application owns the native Confluent client, routing, wire contract,
5
+ trusted producer mapping, consumer group, bootstrap position and poison-record policy.
6
+ This recipe adds no Gloaming package, runtime or reusable library mechanism.
7
+
8
+ The executable [package-only consumer](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/eng/release/consumers/Kafka/README.md) demonstrates
9
+ one sequential intake loop with Confluent.Kafka 2.16.0, Kafka 4.3.1 and PostgreSQL 18.6.
10
+ Its record format, table names and sample effects are consumer-owned examples.
11
+
12
+ ## Publish retained intent
13
+
14
+ Enqueue `OutgoingMessage` in the producer module's ordinary native transaction. Save business
15
+ state and outbox work, then commit. Dispatch runs independently and claims work before invoking
16
+ the publisher; no producer database transaction spans Kafka I/O. See the
17
+ [PostgreSQL messaging contract](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Messaging/Gloaming.Messaging.EntityFrameworkCore.Postgres/README.md).
18
+
19
+ The host owns a native `IProducer<byte[], byte[]>` configured with `Acks.All` and
20
+ `EnableIdempotence = true`. Supply it to the consumer's
21
+ [KafkaPublisher](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/eng/release/consumers/Kafka/KafkaAdapter.cs) and reuse it for its selected
22
+ lifetime. Keep credentials/TLS, native timeouts and disposal in host composition.
23
+ `PublishAsync` validates the selected route, serializes the retained envelope and awaits
24
+ `ProduceAsync`. It returns normally only when the report says `PersistenceStatus.Persisted`.
25
+ Failed or unconfirmed acceptance throws. Cancellation does not prove broker rejection.
26
+ The example's wire codec allows one wrapper around the core's 64-level JSON payload (65 total).
27
+ Keep application payload admission and transport byte/depth budgets consistent before durable
28
+ staging; another transport contract may impose stricter consumer-owned limits.
29
+
30
+ Keep MessageId unchanged across dispatch attempts. A producer session's idempotence does not
31
+ deduplicate a fresh producer after process loss. Broker acceptance can precede recorded outbox
32
+ completion; receiving intake must still deduplicate. The example's Kafka key is an item key;
33
+ it is neither delivery identity nor an authorization credential. Kafka partition order does not
34
+ establish domain causality or FIFO from an independently scheduled outbox.
35
+
36
+ ## Commit intake before advancing a position
37
+
38
+ Select a native consumer group and bootstrap/reset policy explicitly. The fixture uses classic
39
+ groups, Range assignment and earliest reset for its new isolated topics; that is not a production
40
+ retention/replay decision. Disable **both** `EnableAutoCommit` and `EnableAutoOffsetStore`.
41
+ Native prefetch may continue internally, but the application accepts one delivered record at a
42
+ time. See the native client's [offset-management guidance](https://docs.confluent.io/kafka-clients/dotnet/current/overview.html).
43
+
44
+ For each record:
45
+
46
+ 1. Decode the selected wire contract and map its trusted native route to the application's
47
+ stable producer namespace. MessageId, message alias/version and business metadata come from
48
+ the validated envelope. An asserted producer name or TenantKey alone grants no authority.
49
+ 2. Create a fresh scope and receiving DbContext. Begin an explicit native ReadCommitted
50
+ transaction, call `IInbox<TContext>.ReceiveAsync`, then commit.
51
+ 3. After committed intake, call `consumer.Commit(record)`. Both `Queued` and `AlreadyReceived`
52
+ permit this acknowledgement. An unobserved/failed database commit does not.
53
+ 4. Dispose the operation scope before accepting more work. Local business processing runs
54
+ separately through `IInboxProcessor<TContext>` with its own fresh scopes and atomic local
55
+ effects/completion. Do not hold Kafka intake across slow external work.
56
+
57
+ The [native adapter](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/eng/release/consumers/Kafka/KafkaAdapter.cs) contains the complete
58
+ receive/commit composition. Both native EF save forms call the selected guards in the
59
+ [consumer mappings](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/eng/release/consumers/Kafka/Database.cs). Production schema placement,
60
+ migrations, grants, tenant admission and reader permissions stay with the application.
61
+
62
+ If intake fails, stop that consumer attempt or deliberately seek/retry the same record before
63
+ reading further. Do not catch a failure, continue and later commit a higher position in that
64
+ partition. Kafka commits a next position; it does not acknowledge arbitrary independent records.
65
+ This recipe supplies no parallel-intake watermark, batch acknowledgement or partition scheduler.
66
+
67
+ Intake commit followed by offset-commit failure can redeliver. Reconcile through retained intake
68
+ in a fresh scope; do not repeat business work directly from the broker record. Ownership-loss
69
+ errors such as Local_State or UnknownMemberId do not roll back the committed receipt. They must
70
+ not become a blanket policy that ignores every Kafka exception. The host owns fail-stop/restart,
71
+ backoff and readiness; the proof observes an actual live group handoff and rejected stale commit.
72
+
73
+ ## Reject or retain poison work deliberately
74
+
75
+ Malformed or conflicting records have not entered accepted intake. The library's
76
+ [inbox dead letters](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Messaging/docs/inbox-recovery.md) instead describe failures
77
+ after accepted intake; they cannot dispose an undecodable Kafka record.
78
+
79
+ The executable example first proves fail-stop at a conflicting offset while later valid work
80
+ remains unacknowledged. It then selects a different explicit policy: commit a receiver-owned
81
+ quarantine record before committing that position. Its controlled reasons distinguish invalid
82
+ envelopes and identity/content conflicts. Database/storage failures still propagate.
83
+
84
+ Quarantine retains a source-incarnation key, topic, partition, position, raw key/value bytes,
85
+ ordered headers and broker timestamp. Repeating disposition checks retained content rather than
86
+ overwriting it. Use a new admitted source incarnation after relevant cluster/topic recreation;
87
+ topic name plus numeric offset is not permanent source identity. The fixture uses unique topics
88
+ and never recreates one under its existing incarnation.
89
+
90
+ This is example policy and schema, not a Gloaming quarantine store. Applications choose operator
91
+ authority, disclosure, retention and repair/replay. Retained payloads/headers may contain sensitive
92
+ data. No replay UI, automatic discard, automatic evidence expiry or application admission follows
93
+ from this recipe.
94
+
95
+ ## Lifetime and recovery
96
+
97
+ Bound native publication and operation budgets. Cancel a native `Consume` call cooperatively,
98
+ await it, then close/dispose its consumer; do not use that consumer concurrently from another
99
+ thread during close. Stop new work before shutdown. A pending database/offset boundary remains
100
+ uncertain under process loss; fresh operation scopes and retained delivery identity own recovery.
101
+ Producer delivery timers, native session limits and external process termination are separate
102
+ policies. No wrapper here bounds arbitrary user code or supplies a supervisor.
103
+
104
+ The host also owns source retention and receipt evidence lifetime. Deleting a processed receipt
105
+ ends its deduplication/content evidence; replay may execute old work again. A new group cannot
106
+ recover broker records removed by retention. Separate query projection rebuilds from historical
107
+ email, inference and other external effects. Kafka producer transactions do not atomically commit
108
+ PostgreSQL effects.
109
+
110
+ ## Verification and limits
111
+
112
+ From the Gloaming repository root, with the pinned SDK, Node and a Docker-compatible engine:
113
+
114
+ ```sh
115
+ npm ci --prefix eng/release --ignore-scripts
116
+ npm run verify:kafka -- --feed .artifacts/packages --version 0.1.0
117
+ ```
118
+
119
+ Pack candidates with the native SDK as described in the [package guide](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/eng/release/README.md).
120
+ The [runner](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/eng/release/verify-kafka.ts) consumes the selected package folder/version and restores an external
121
+ consumer through source mapping into a fresh cache, verifies its exact four-package Gloaming
122
+ closure and zero ProjectReferences, then uses Testcontainers to provision an isolated broker and
123
+ PostgreSQL. It retains redacted logs, selected package identities, per-scenario outcomes and cleanup
124
+ evidence. See the [consumer guide](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/eng/release/consumers/Kafka/README.md)
125
+ for rootless Podman setup.
126
+ The [Native Kafka package adoption check](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/.github/workflows/ci.yml)
127
+ owns this profile. The ordinary package command uses PostgreSQL.
128
+
129
+ The selected proofs cover process death before/after intake commit, accepted publication before
130
+ outbox completion, duplicate effects, native local rollback, conflicting/malformed disposition,
131
+ live max-poll ownership loss, dropped native Produce acknowledgements, broker restart, cancelled
132
+ consume/close and an owned literal v1 record. The database uncertainty case throws through a
133
+ native post-commit observer; it proves an unobserved committed result, not a TCP-level PostgreSQL
134
+ response fault. The frame proxy and process barriers are test-owned and absent from the recipe
135
+ adapter.
136
+
137
+ The tested topology is Linux x64, one combined broker/controller, one partition per topic, classic
138
+ groups and local plaintext. Replication-factor-one acceptance is no broker-availability claim.
139
+ Managed-service TLS/ACLs, cooperative/new consumer protocols, multiple partitions, parallel intake,
140
+ throughput, real production migrations and cross-released-client compatibility require their own
141
+ selected evidence. The initial literal v1 fixture does not certify two released library versions.
142
+ No Share Groups dependency or new Gloaming root runtime is introduced.
@@ -0,0 +1,89 @@
1
+ # Add durable handoff and logical command receipts
2
+
3
+ Select this document when the requested behavior needs work to survive process loss,
4
+ independent module commits or ambiguous command completion. Modules alone do not imply messaging.
5
+
6
+ ## Define the boundary
7
+
8
+ Name the sender, receiver, wire contract, admitted scope, logical action and failure behavior.
9
+ Decide whether delivery is a native local adapter or an external transport.
10
+ The application owns routes, queues/subscriptions, credentials, identity admission and workers.
11
+
12
+ Keep these identities distinct:
13
+
14
+ | Identity | Meaning |
15
+ | --- | --- |
16
+ | Entity/aggregate ID | Business resource |
17
+ | Logical command ID | One accepted action, reused after an uncertain response |
18
+ | Delivery MessageId | One retained outgoing/incoming envelope |
19
+ | Correlation/causation | Conversation and immediate cause |
20
+
21
+ ## Outbox and inbox
22
+
23
+ The sender stages an immutable outgoing envelope with its business changes in the same
24
+ module context/transaction, then saves and commits. Install the required native outbox guards.
25
+
26
+ A separately invoked dispatcher publishes retained messages outside the claim transaction.
27
+ Transport acceptance can be uncertain; delivery can repeat. Database fencing cannot recall an
28
+ external provider effect.
29
+
30
+ The receiver validates transport/wire/scope admission, durably retains intake and commits before
31
+ acknowledging transport. Its independently invoked inbox processor commits local effects,
32
+ completion and any next outgoing message together. The selected processor owns that bounded
33
+ transaction; follow its savepoint, failure-accounting and cancellation contract.
34
+
35
+ Use the callable storage/dispatch/processing roles directly or select the separate Hosting
36
+ package. The application decides polling, supervision and process restart.
37
+
38
+ For optional PostgreSQL notifications around callable roles, follow
39
+ [the native wakeup recipe](postgres-wakeups.md). Preserve independent polling, fresh scopes and
40
+ terminal completion/accounting supervision; notification payloads never select business work.
41
+ Broker-free adapters must still preserve retained intent, stable identity, admitted intake and
42
+ recoverable response delivery. A direct independently committing method call alone does not.
43
+
44
+ Done: native tests prove producer rollback, receiver deduplication, redelivery after uncertain
45
+ acceptance, competing processing and recovery after process death.
46
+
47
+ For different deliveries targeting one entity, compose the native
48
+ [entity-work exclusion recipe](entity-work.md). It keeps a complete consumer key locked through
49
+ the original transaction; it does not supply FIFO, retained deduplication or business authority.
50
+
51
+ ## Logical command receipts
52
+
53
+ Use receipts for an explicitly selected action whose accepted result must be recovered after a
54
+ lost response. The client/operator retains the action ID before sending and reuses it for that
55
+ same intent. A deliberate new action uses a new ID.
56
+
57
+ Authorize before exposing a retained result. In one fresh ReadCommitted context/transaction,
58
+ acquire the full scope/operation/action key and compare stable consumer-selected input.
59
+ An existing result is decoded with a compatible reader; a new accepted decision retains its
60
+ result/reference with the business and outgoing changes before save/commit.
61
+
62
+ The consumer owns comparison meaning, result format and readers, permissions, retention and
63
+ migration. Retain evidence for module lifetime under the current contract; explicit removal ends
64
+ duplicate protection. Unknown result formats must fail without re-executing the action.
65
+
66
+ Done: equal concurrent attempts commit one effect, changed input conflicts, rollback leaves
67
+ no completed receipt, and a fresh authorized retry recovers an uncertain committed result.
68
+
69
+ ## Longer processes
70
+
71
+ Select the optional continuation runner only for its supported saved-method/request-reply model.
72
+ Business branching, compensation, response validation and operator authority stay in the module.
73
+ One pending request is supported. For parallel named replies, select the separate
74
+ [technical contribution protocol](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Messaging/docs/contributions.md) and explicitly
75
+ choose participant/count policy and outcome messages. Business approval, strict deadline policy
76
+ and human-workflow assignment remain module decisions; no parallel workflow graph is supplied.
77
+
78
+ A due-time signal is an invitation to reconsider current business state, not authority to
79
+ complete a task. Generation/current-state checks remain necessary after cancellation or reassignment.
80
+ Select [finite due-time intents](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Messaging/docs/due-intents.md) when a module
81
+ needs retained occurrence identity, suppression and bounded outbox handoff. The module still
82
+ owns its clock, source rules, transaction/save/commit and polling. This finite mechanism does
83
+ not supply a calendar, human assignment or workflow deadline policy.
84
+
85
+ Select the optional [recurrence module](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Messaging/Gloaming.Messaging.Recurrence.EntityFrameworkCore.Postgres/README.md)
86
+ when repeated technical work needs retained planning progress. Pin and verify calendar inputs,
87
+ choose Skip/Coalesce/bounded CatchUp explicitly, and keep current-generation relevance in the
88
+ module. The module invokes planning/stopping in fresh native transactions; recurrence does not
89
+ install a worker or select business recipients and holidays.
@@ -0,0 +1,75 @@
1
+ # Add modules and aggregate roots
2
+
3
+ Use [structure](structure.md) for project boundaries. Interpret persistence per aggregate from
4
+ the request; ordinary EF state is the default. A module can use more than one persistence style
5
+ while retaining one clear native transaction owner.
6
+
7
+ ## Common module steps
8
+
9
+ 1. Create the named implementation and its needed Contracts. Define the requested aggregate
10
+ roots and a small application-facing command/query API. Keep business inputs/results free
11
+ from EF and persistence implementation types.
12
+ 2. Add a scoped native DbContext with module-owned mappings, schema and migrations.
13
+ Configure a distinct migrations history/schema for modules sharing a database.
14
+ Host connection options are supplied to explicit module registration.
15
+ 3. Implement current resource permission checks in the application operation. Use the
16
+ application-admitted actor and tenant; neither replaces resource authorization.
17
+ 4. Make public commands return after their chosen local transaction commits. The module
18
+ application service normally owns the native transaction, save/commit and failure disposal.
19
+ If the application deliberately selects caller-owned staging instead, expose that contract
20
+ explicitly and keep commit ownership visible in its adapter.
21
+ 5. Map HTTP/worker ingress through the module's Contracts. Native endpoint style and status
22
+ mapping belong to the host. Inter-module calls use Contracts and preserve module ownership.
23
+ 6. Add migrations and meaningful operation/isolation/rollback tests before considering the
24
+ module ready. Update the application's module map.
25
+
26
+ An operation performs its accepted business changes and selected audit/outbox/receipt writes
27
+ in the same owning transaction. On failure or uncertain commit, dispose the transaction/context
28
+ and reconcile from fresh state. Independent module commits have independent recovery obligations.
29
+
30
+ ## State-stored aggregates
31
+
32
+ Use ordinary domain classes or immutable state/candidates with native EF mappings.
33
+ Keep invariants, complete-candidate validation and optimistic versions in the module.
34
+ A generic repository, universal entity base and CQRS dispatcher are not required.
35
+
36
+ Choose native concurrency tokens for contested writes. Check expected versions at the business
37
+ boundary and handle save-time concurrency as well. Validate the complete accepted change before
38
+ mutating persisted state. Child/value mappings remain application decisions.
39
+
40
+ For multitenant data, select [ownership/save protection](gloaming.md) and include tenant identity
41
+ in all relevant keys/predicates. A query filter alone does not protect detached updates,
42
+ relationships or raw SQL. Use native constraints and selected RLS where the threat model requires.
43
+
44
+ Done: create/load and the selected mutation preserve invariants, ownership and versions;
45
+ stale/invalid changes and rollback leave committed state unchanged.
46
+
47
+ ## Event-sourced aggregates
48
+
49
+ Select Gloaming's EventSourcing core and native EF store, then read their exact current contracts.
50
+ Use consumer-owned immutable state/facts and pure evolution. Stable event names/schema versions
51
+ and JSON encoding belong to the module; persisted CLR names are not the event contract.
52
+
53
+ Configure the complete stream key, event/header mappings and one required inline aggregate
54
+ state. Registered aggregate writes stage the accepted events, head and inline state together.
55
+ Install every required sync/async save validation. Save/commit stays with the selected operation
56
+ owner; the store is not an automatic unit of work.
57
+
58
+ Ordinary aggregate loading uses validated inline state at the current head.
59
+ Explicit history reading and complete regeneration are separate operations; production reads
60
+ do not silently rebuild or emit historical side effects. Payload upcasting is independently
61
+ selected. Reducer changes that affect persisted state require a deliberate repair/rollout plan.
62
+
63
+ For the initial example, use the named aggregate's smallest create/load lifecycle with an
64
+ explicit creation fact. Add business decisions only from actual requirements.
65
+
66
+ Done: native tests prove contiguous facts, consistent event/head/inline-state versions,
67
+ optimistic conflicts, complete rollback and replay of retained literal data when compatibility
68
+ is promised. State-stored aggregates in other modules take no event-sourcing dependency.
69
+
70
+ ## Cross-module behavior
71
+
72
+ Same-process invocation is enough only when its failure/commit behavior meets the requirement.
73
+ If one module commits and the caller can die before recording the result, select a durable
74
+ handoff or explicitly prove a shared native transaction. Follow [messaging](messaging.md) when
75
+ durable progress is required; compensations remain business decisions.
@@ -0,0 +1,96 @@
1
+ # Optional PostgreSQL queue wakeups
2
+
3
+ Use notifications to shorten an application worker's idle wait while keeping periodic polling
4
+ authoritative. This is native application composition using existing typed Gloaming inbox/outbox
5
+ operations, Npgsql and bounded channels. It establishes **no new reusable library mechanism** and
6
+ adds no dependency to the provider-free hosting package. The standard polling hosts remain useful
7
+ without this optional recipe.
8
+
9
+ ## Native session and startup
10
+
11
+ The application owns a dedicated direct PostgreSQL connection, independent of all business/
12
+ processing contexts. Use `Pooling=false`, `Multiplexing=false`, `Enlist=false`, an explicit endpoint,
13
+ bounded connection/command timeouts and a reconnect delay. A listener must retain one server
14
+ session; do not use transaction-pooled endpoints. The executable proof uses direct PostgreSQL18
15
+ with Npgsql10.0.3. Other proxies/topologies have no execution certificate here.
16
+
17
+ Attach `Notification` before issuing fixed reviewed `LISTEN` commands. Commit registration outside
18
+ a business/ambient transaction, then force each selected worker to poll durable state. A notification
19
+ may be consumed while processing an ordinary command before a later `WaitAsync`; the callback must
20
+ retain a hint. Never assume the next wait replays an already consumed event.
21
+
22
+ Give the inbox and outbox worker **separate capacity-one signals**. The callback only performs a
23
+ nonblocking signal write; it runs no handler, query or publication. Bursts coalesce with bounded
24
+ memory. The proved composition has one reader per signal; additional workers need their own signals
25
+ or an explicitly selected application fan-out policy. A signal is neither work nor authority.
26
+
27
+ Run one exclusive native receive pump. On connection failure, dispose that session, report degraded
28
+ wakeups, wait the selected reconnect delay, open/register again and force fresh polls. Worker polling
29
+ continues independently throughout listener outages. Hints lost during disconnect are harmless to
30
+ correctness. Cancel and await the pump before disposing its connection; never command or close a
31
+ connection concurrently with its wait. Cancellation/keepalive may break a session: discard it.
32
+
33
+ Npgsql's integer `WaitAsync(timeout, token)` needs a positive bounded millisecond timeout when
34
+ bounded waiting is intended;0/-1 mean indefinite. Multiplexing is unsupported. Driver pooled reset
35
+ removes LISTEN registrations; a new/reopened session always registers again. Each held listener
36
+ consumes a database connection even when no queue work exists.
37
+
38
+ ## Two ordinary callers
39
+
40
+ For each inbox poll, create a fresh established scope and call
41
+ `IInboxProcessor<ModuleDatabase>.ProcessNextAsync(selectedSubscription, token)`. For each outbox
42
+ poll, independently create a fresh scope and call
43
+ `IOutboxDispatcher<ModuleDatabase>.DispatchNextAsync(token)`. Dispose each operation scope before
44
+ idling. After `NoWork`, consume its retained hint or wait for a hint **or a positive fallback delay**,
45
+ then poll again. A hint never selects a message, tenant, subscription or acknowledgment.
46
+
47
+ Use a cancelled-and-awaited losing read, not an abandoned `Task.WhenAny` read that could steal the
48
+ next hint. The executable recipe uses a linked cancellation source with the fallback deadline and
49
+ awaits its channel read to completion. Eligibility, retry availability and lease expiry can change
50
+ solely with time; insert/update notifications cannot replace that fallback.
51
+
52
+ The consumer supervises listener and workers together. Unexpected worker completion or any thrown
53
+ processing/publication/accounting fault reaches the host and cancels the other tasks. Listener
54
+ connection errors only degrade wakeups; they must not convert fatal `InboxFailureAccountingException`,
55
+ `OutboxFailureAccountingException` or `OutboxCompletionException` into ordinary retries. Cancellation
56
+ and cleanup have independent budgets; preserve original failures. The recipe selects terminal
57
+ supervision for thrown worker errors. Backoff, restarts, logging and readiness remain application
58
+ policy; no universal retry loop or Gloaming runtime is introduced.
59
+
60
+ ## Additive migration and grants
61
+
62
+ The consumer installs reviewed `AFTER INSERT` triggers on its selected inbox/outbox tables. A fixed
63
+ `SECURITY INVOKER` function calls qualified `pg_catalog.pg_notify` with a constant channel and **empty
64
+ payload**, using a trusted fixed search path. Schema/table/function ownership stays with migration
65
+ credentials. Runtime credentials need normal queue/handler grants plus database CONNECT; they do not
66
+ need schema CREATE, function ownership, trigger changes or deletion. Prove actual grants, including
67
+ any locally revoked native function privileges. Notifications do not change RLS or admission policy.
68
+
69
+ Pause/coordinate native DDL as appropriate to the application's migration process. Install additively
70
+ over retained rows; the initial post-registration poll drains pre-trigger work. Unchanged older
71
+ writers signal through the database trigger. Removing triggers leaves ordinary polling functional.
72
+ Keep owned table mappings, migrations and compiled old/new writers; no library release compatibility
73
+ claim follows merely from compiling the current source twice.
74
+
75
+ Notifications commit with the producer transaction and are not durable offline delivery. Identical
76
+ hints within one transaction can fold; spurious/untrusted hints may cause an extra poll. Notifications
77
+ are visible to database users, so channels/payloads must contain no secrets. A saturated native
78
+ notification queue can fail the notifying transaction's **commit**; selecting a trigger therefore
79
+ adds a producer failure mode. Monitor native queue usage and transaction duration, and recover failed
80
+ producer decisions through their existing fresh-context transaction protocol. There is no external
81
+ exactly-once, FIFO, zero-latency or always-available-listener guarantee.
82
+
83
+ ## Executable owners
84
+
85
+ The [native application fixture](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Messaging/tests/Fixtures/Wakeups/README.md) contains
86
+ the complete pump, typed callers and fault supervisor. [Provider tests](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/src/Gloaming.Messaging/tests/OutboxPostgresTests/WakeupTests.cs)
87
+ cover actual queue processing, disconnected fallback/reconnect, cancellation, pooled reset,
88
+ notification-before-wait, bounded coalescing, restricted grants and separately compiled earlier
89
+ writes across trigger installation/removal. The [independent package consumer](https://github.com/oxface/gloaming/blob/46610d7faee75376cedbfe665cc04d890e759457/eng/release/consumers/Wakeups.cs)
90
+ uses both real callable roles and native notifications from NuGet packages without Hosting.
91
+
92
+ Native semantics are described in [PostgreSQL LISTEN](https://www.postgresql.org/docs/18/sql-listen.html),
93
+ [NOTIFY](https://www.postgresql.org/docs/18/sql-notify.html) and
94
+ [Npgsql notification waiting](https://www.npgsql.org/doc/wait.html). The application chooses whether
95
+ the reduced idle latency justifies session/notification overhead; no throughput benchmark or
96
+ production latency objective is certified by these bounded proofs.