@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,81 @@
1
+ # Application structure
2
+
3
+ Use module boundaries as the main organization. Within a module, begin with one implementation
4
+ project and a Contracts project when the host or another module needs its business API.
5
+ Use folders inside the implementation for domain, application operations and persistence.
6
+
7
+ ~~~text
8
+ <Application>.slnx
9
+ global.json
10
+ Directory.Build.props
11
+ Directory.Packages.props
12
+ orchestration/
13
+ local/
14
+ <Application>.Local.AppHost.csproj
15
+ src/
16
+ <Application>.Server/
17
+ <Application>.Worker/
18
+ <Application>.Migrator/
19
+ <Application>.ServiceDefaults/
20
+ Modules/
21
+ X/
22
+ <Application>.X.Contracts/
23
+ <Application>.X/
24
+ Domain/
25
+ Application/
26
+ Persistence/
27
+ Migrations/
28
+ Y/
29
+ <Application>.Y.Contracts/
30
+ <Application>.Y/
31
+ tests/
32
+ <Application>.ArchitectureTests/
33
+ <Application>.IntegrationTests/
34
+ docs/
35
+ architecture.md
36
+ ~~~
37
+
38
+ Create folders when they contain implementation. Worker and service-default projects have
39
+ their selected lifecycle responsibilities; document or omit an unnecessary host rather than
40
+ inventing recurring jobs. Existing repositories may use a different layout while keeping the
41
+ same ownership boundaries.
42
+ Add `orchestration/e2e`, `orchestration/shared` and a publishing AppHost only when used.
43
+ The [browser stack profile](dotnet-react-vite.md) adds `apps/`, private workspace `packages/`
44
+ and `eng/` helpers for its selected frontend and verification tools.
45
+
46
+ ## Dependencies
47
+
48
+ - Contracts exposes business operations, inputs and results. Keep EF rows, DbContexts,
49
+ event-store internals and implementation DTOs inside the module implementation.
50
+ - A module implementation references its Contracts, selected technical libraries and another
51
+ module's Contracts when needed. It does not reference another module implementation.
52
+ - Server/Worker composition roots reference implementations to register native services.
53
+ Business endpoints and cross-module calls use Contracts.
54
+ - Migrator invokes explicit module setup entry points for their migrations and grants.
55
+ AppHost references executable hosts for local orchestration.
56
+ - Business modules have no dependency on Server, Worker, Migrator, AppHost or Aspire.
57
+ - Domain objects contain their own invariants. State-stored aggregates need no shared domain
58
+ base. Event-sourced aggregates may select Gloaming bookkeeping without moving rules into it.
59
+
60
+ Use names from the target application. Wholesale's Access/Sales/Inventory language is example
61
+ policy and is not a prescribed set of modules.
62
+
63
+ ## Persistence ownership
64
+
65
+ Give every module a native DbContext, owned schema, migration history and named connection.
66
+ A shared physical PostgreSQL instance/database is a deliberate deployment choice; it does not
67
+ create a shared context or cross-module unit of work. Separate databases/roles are appropriate
68
+ when the application's isolation requirements call for them.
69
+ Keep native `IEntityTypeConfiguration<T>` mappings with the module alongside migrations.
70
+ Hosts supply configuration and select setup operations; modules own schema-specific SQL.
71
+
72
+ Use business IDs in another module's data rather than cross-module EF navigation or database
73
+ foreign keys. Query another module through its Contracts or maintain an explicitly owned
74
+ receiving view. Same-process calls that commit independently do not create atomicity.
75
+
76
+ ## Record the result
77
+
78
+ The target architecture document lists each module, aggregate roots, persistence mode,
79
+ schema/database, connection/credential roles, public Contracts and transaction owner.
80
+ It also records chosen hosts, identity/tenant admission and any durable delivery boundary.
81
+ Keep library API details in their owning library contracts.
@@ -0,0 +1,81 @@
1
+ # Verify the resulting application
2
+
3
+ Apply the target repository's checks, then verify the selected behavior. Record actual commands
4
+ and outcomes; a project list or copied test does not establish working composition.
5
+
6
+ ## Build and architecture
7
+
8
+ - Restore/build the selected solution with its pinned SDK/packages.
9
+ - Prove locked restore with the exact selected Gloaming archives from an initially empty package
10
+ cache. Record the archive source and any temporary bridge; a warm cache can hide distribution gaps.
11
+ - Verify module implementations do not reference each other or host projects.
12
+ - Verify business callers use Contracts; composition and migration roots may reference
13
+ native implementation configuration deliberately.
14
+ - Ensure library dependencies match selected capabilities and local package versions restore
15
+ without Gloaming source ProjectReferences.
16
+ - Verify all solution, tooling and CI paths against the actual target repository.
17
+ - Include selected SDK-style AppHosts/shared orchestration projects in solution checks. Verify
18
+ the pinned CLI can start the exact host as well; solution build alone does not prove CLI startup.
19
+
20
+ Run the scaffold's own formatting/analyzer checks with its generated-file policy. If hooks check
21
+ staged content, retain an isolated Git fixture proving both directions: staged errors fail despite
22
+ an unstaged fix, and clean staged content passes despite unfinished working-tree edits. Include
23
+ linked workspace dependencies and staged formatter configuration; preserve the real index.
24
+
25
+ ## Module persistence
26
+
27
+ For each requested module, exercise a real accepted operation and read it through its API.
28
+ Cover invalid/stale work, native rollback and module/tenant isolation. A new module's schema,
29
+ migrations and migration history belong to it.
30
+ Exercise denied direct Contracts calls as well as HTTP authorization. For first-login account
31
+ creation, race registration of one issuer/subject and verify one account and its selected audit.
32
+ Keep global pre-admission registry checks distinct from tenant-owned persistence isolation.
33
+
34
+ Use the actual provider for provider guarantees. If data already exists, prove a populated
35
+ forward migration and compatible payload/result readers; a new empty database is insufficient.
36
+ For selected event sourcing, include event/head/inline-state atomicity and optimistic conflicts.
37
+ For transactional audit, inject a database failure and check from fresh state that neither
38
+ business nor history writes remain. Use the runtime role to attempt forbidden schema changes
39
+ and audit updates/deletes, alongside successful permitted operations.
40
+
41
+ For RLS, verify restricted runtime credentials, policies, transaction-local context, denied
42
+ foreign writes and unfiltered SQL behavior. Query filters alone cannot prove these properties.
43
+
44
+ ## Hosts and operations
45
+
46
+ Verify Server startup and one real endpoint. Verify Migrator applies the selected migrations
47
+ and exits with failure when setup fails. Verify AppHost resource references, migration completion
48
+ ordering and configured readiness before claiming local orchestration works.
49
+
50
+ For configured OIDC, use the actual local issuer for one login/callback/protected/logout flow.
51
+ Test-only authentication verifies application policy separately and does not certify OIDC.
52
+ Restart the developer stack and verify persistent data, identity mappings and signed-in cookies.
53
+ An E2E stack owns separate data, identity/key storage, ports and lifecycle; prove it leaves the
54
+ developer stack intact and retains ownership information when cleanup fails.
55
+ A selected worker must establish fresh admitted scopes, propagate cancellation, expose faults
56
+ and follow the chosen native supervision/restart policy.
57
+
58
+ For the selected .NET/React/Vite profile, complete its
59
+ [clean-consumer acceptance sequence](dotnet-react-vite.md#clean-consumer-acceptance).
60
+
61
+ ## Durable behavior
62
+
63
+ When messaging is selected, prove transactional enqueue/intake, duplicate handling, rollback,
64
+ competing consumers, uncertain completion and actual process recovery. External provider effects
65
+ need their own idempotency/reconciliation policy.
66
+
67
+ When command receipts are selected, prove replay of the original result after uncertain commit,
68
+ input conflict and current authorization. Do not repeat a business decision because decoding an
69
+ old retained result fails.
70
+
71
+ ## Handoff
72
+
73
+ Update the consuming application's architecture and setup docs with its module map, native
74
+ infrastructure, credentials/configuration names and transaction owners.
75
+ Report implemented behavior, checks actually run, configuration still required and unresolved
76
+ business decisions. Keep unsupported guarantees explicit. Avoid empty placeholders and invented
77
+ extra modules merely to fill the preferred layout.
78
+ Distinguish fresh execution from historical evidence, retained automated checks from one-off
79
+ fixtures, and local results from remote CI/deployment. Name the reviewed source revision,
80
+ package versions/archive source and selected capability coverage; a first access slice does not
81
+ certify every library family.
@@ -0,0 +1,244 @@
1
+ # .NET, React and Vite bootstrap profile
2
+
3
+ Apply this profile when the application selects native ASP.NET Core cookie/OIDC authentication,
4
+ PostgreSQL, a React/Vite frontend and Aspire orchestration. Follow [bootstrap](bootstrap.md)
5
+ and the [first-module walkthrough](first-module.md) for backend ownership. Existing repository
6
+ instructions and explicit owner choices take precedence. These are consumer implementation
7
+ defaults; Gloaming supplies no frontend package, generated template or required runtime.
8
+
9
+ ## Pinned workspace and tooling
10
+
11
+ Use `apps/<portal>` for application source and private pnpm workspace packages under `packages/`.
12
+ Pin Node, pnpm, the .NET SDK, central NuGet versions and local .NET tools. Commit workspace,
13
+ orchestration npm and NuGet dependency locks. Include the AppHosts in locked solution restore.
14
+
15
+ Supply working editor configuration, manifests, root commands and matching CI checks together:
16
+
17
+ | Concern | Starting behavior |
18
+ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
19
+ | Formatting | Prettier for frontend/configuration; CSharpier for handwritten C#/project XML. Declare generated API types, EF migrations, lock files and build output policies explicitly. |
20
+ | C# spacing | Enable IDE2003 through `.editorconfig` and Roslyn style verification. CSharpier preserves logical groups but does not infer them. Agent guidance asks for semantic grouping and keeps `else`, `catch` and `finally` attached. |
21
+ | Type-aware lint | Pin Oxlint and `oxlint-tsgolint`; enable `typescript/no-deprecated` and fail warnings. Cover application and shared workspace source. Use the installed React declarations' supported event types. |
22
+ | Git hooks | Lefthook runs checks against staged blobs and conventional commit validation. Hooks preserve the user's index and working tree. |
23
+ | Install scripts | Use the policy supported by the pinned pnpm version. For pnpm 12, configure explicit `allowBuilds` entries for required packages; verify them during clean installation. |
24
+
25
+ Keep this commitlint configuration, including its disabled capitalization check:
26
+
27
+ ```js
28
+ export default {
29
+ extends: ["@commitlint/config-conventional"],
30
+ rules: {
31
+ // Capitalization does not change the meaning of a conventional commit.
32
+ "subject-case": [0],
33
+ },
34
+ };
35
+ ```
36
+
37
+ Accept a capitalized Dependabot subject such as `chore(deps): Bump dependency`; reject malformed
38
+ messages through the same configuration in hooks and CI. Pin tool versions in manifests rather
39
+ than copying a dated dependency list from this guide. See [type-aware lint setup](https://oxc.rs/docs/guide/usage/linter/type-aware.html)
40
+ and [pnpm build settings](https://pnpm.io/settings#allowbuilds).
41
+
42
+ A staged-content helper exports the complete index into scratch storage, uses staged tool
43
+ configuration, and redirects workspace dependency symlinks to exported package source. External
44
+ dependencies may reuse installed packages matching the staged manifests/locks; require an install
45
+ when they differ. Checking working-tree files by staged filename does not check the commit.
46
+ CSharpier accepts explicitly named files even when normally ignored, so apply the staged ignore
47
+ policy before passing its file list. Retain isolated Git fixtures for both staged/unstaged
48
+ directions, including a workspace dependency and generated migrations.
49
+
50
+ Use `eng/` for enduring verification/codegen helpers, preferably TypeScript for new durable
51
+ scripts. Document their runtime and invocation. Inventory temporary package bridges separately
52
+ with a removal condition; remove superseded one-off helpers. Keep workspace source visible to
53
+ Git/formatters/lint while excluding every nested `node_modules`, build output and generated cache.
54
+
55
+ Done: a frozen clean install and the scaffold's own formatting, type-aware lint and hook fixtures
56
+ pass without changing source or the index.
57
+
58
+ ## Solution-owned orchestration
59
+
60
+ Create `orchestration/local/<Application>.Local.AppHost.csproj` using `Aspire.AppHost.Sdk`,
61
+ with a C# entrypoint, `Aspire.Hosting.AppHost` and explicit runnable project references. Include
62
+ it in the main `.slnx`. Pin the SDK/package versions and use standard
63
+ `Properties/launchSettings.json` for dashboard/telemetry ports and environment settings.
64
+ The [Aspire SDK](https://aspire.dev/get-started/aspire-sdk/) describes typed `Projects.*`
65
+ metadata and CLI-bundle configuration.
66
+
67
+ When an isolated browser suite exists, add a sibling E2E AppHost and a shared orchestration
68
+ class library. Reference the latter with `IsAspireProjectResource="false"`; runnable backend
69
+ references remain in each AppHost. Keep entrypoints thin. Share explicit infrastructure,
70
+ backend/portal and identity wiring; use named local/E2E profiles for ports, database names and
71
+ persistence. Additional portals get application-specific resource names and wiring. Keep a
72
+ future publishing AppHost absent until its deployment behavior is implemented.
73
+
74
+ Use an independent npm-locked Aspire CLI under `orchestration/local`, even though application
75
+ packages use pnpm. Document `npm ci --prefix orchestration/local` separately. Install workspace
76
+ dependencies once, then use `.WithPnpm(install: false)` for Vite resources. A root
77
+ `aspire.config.json` selects the default local project; commands/tests for other hosts always
78
+ pass their exact project path. Shared editor launch entries select hosts while project launch
79
+ profiles retain runtime settings. Reconcile editor-extension and command-line tool versions.
80
+
81
+ With Aspire CLI 13.6.4, the observed central `Aspire.Hosting.AppHost` version form is `13.6.4`:
82
+ `[13.6.4]` builds but fails CLI startup version parsing. Keep the dependency lock and verify
83
+ actual CLI startup for the selected toolchain; this is not a general change to NuGet pinning.
84
+
85
+ Persist local PostgreSQL, identity-provider data, key storage and generated secret parameters.
86
+ Keep issuer/callback endpoints stable and explicitly migrate persisted identity configuration;
87
+ realm import does not itself reconcile an existing realm. Preserve volume names and UserSecrets
88
+ IDs during host/project moves. Allocate application-specific names for a new scaffold rather
89
+ than copying a consumer's migration-specific volume names. Include pgAdmin locally, discovered
90
+ through the dashboard; disposable E2E stacks omit it.
91
+
92
+ Done: solution restore/build covers orchestration, the pinned CLI starts the selected host,
93
+ the finite Migrator gates backend readiness, and a restart preserves data and identity.
94
+
95
+ ## Browser authentication and serving
96
+
97
+ Let Vite serve the SPA in development. Proxy `/api`, `/auth`, `/signin-oidc`,
98
+ `/signout-callback-oidc` and `/signout-oidc` to the backend HTTPS endpoint. Preserve the public
99
+ frontend Host (`changeOrigin: false`) so native OIDC constructs the intended callbacks. A local
100
+ development-certificate exception belongs only to that development proxy. The backend serves
101
+ API/auth endpoints; remove SPA static-file middleware and `MapFallbackToFile("index.html")`
102
+ for this topology. Production serving, ingress and forwarded-header trust require their own
103
+ configuration and checks.
104
+
105
+ Keep browser API calls same-origin with native secure, HttpOnly cookies. Return API 401/403
106
+ responses without browser-login redirects; navigate to login deliberately. Protect mutations
107
+ and the logout POST with native antiforgery. Put generic HTTP filters in host HTTP infrastructure
108
+ and use native local-return URL validation. Application modules keep business authorization.
109
+
110
+ Use authorization-code OIDC with PKCE. When the selected provider needs an ID token for
111
+ RP-initiated logout, retain only that token in the encrypted authentication ticket. Inside
112
+ the native `AddOpenIdConnect` options, compose this with any existing validated-token event:
113
+
114
+ ```csharp
115
+ options.ResponseType = "code";
116
+ options.UsePkce = true;
117
+ options.SaveTokens = false;
118
+ options.Events.OnTokenValidated = context =>
119
+ {
120
+ var idToken = context.TokenEndpointResponse?.IdToken ?? context.ProtocolMessage.IdToken;
121
+ if (!string.IsNullOrEmpty(idToken))
122
+ {
123
+ context.Properties!.StoreTokens([
124
+ new AuthenticationToken { Name = "id_token", Value = idToken },
125
+ ]);
126
+ }
127
+
128
+ return Task.CompletedTask;
129
+ };
130
+ ```
131
+
132
+ Map logout to both schemes, using the same `"oidc"` name supplied to `AddOpenIdConnect`:
133
+
134
+ ```csharp
135
+ app.MapPost("/auth/logout", async (HttpContext context, IAntiforgery antiforgery) =>
136
+ {
137
+ await antiforgery.ValidateRequestAsync(context);
138
+
139
+ return Results.SignOut(
140
+ new AuthenticationProperties { RedirectUri = "/" },
141
+ [CookieAuthenticationDefaults.AuthenticationScheme, "oidc"]);
142
+ })
143
+ .RequireAuthorization()
144
+ .AllowTenantless()
145
+ .ExcludeFromDescription();
146
+ ```
147
+
148
+ These excerpts use `Microsoft.AspNetCore.Authentication`, its `.Cookies` namespace,
149
+ `Microsoft.AspNetCore.Antiforgery` and `Gloaming.Tenancy.AspNetCore`, with native authentication
150
+ and antiforgery already registered. The browser submits the native antiforgery form token or
151
+ configured header. Configure the provider's callback/logout registrations and map validation
152
+ failures to the application's 400 problem response. Access and refresh tokens remain unstored;
153
+ keeping identity claims alone does not supply the provider's logout token hint. Follow the
154
+ [native OIDC composition guide](https://learn.microsoft.com/en-us/aspnet/core/security/authentication/configure-oidc-web-authentication).
155
+
156
+ Persist native Data Protection keys in Azurite locally and provision its container before the
157
+ backend starts. Replicas of one application/environment share the intended keyring/application
158
+ discriminator; independently trusted hosts and environments have separate rings. Configure
159
+ production storage access and key wrapping separately. Ephemeral keys are an explicit isolated
160
+ test or schema-generation choice. Schema generation must not relax normal runtime configuration.
161
+
162
+ Done: an actual browser completes login/callback, a protected operation and provider logout
163
+ through the frontend origin; local restart preserves the signed-in cookie.
164
+
165
+ ## Generated HTTP contracts
166
+
167
+ Use native .NET OpenAPI generation with `Microsoft.AspNetCore.OpenApi` and build-time
168
+ `Microsoft.Extensions.ApiDescription.Server`. Give JSON operations stable names, explicit
169
+ route parameters, success types and problem responses. A tenant parameter consumed only by
170
+ middleware must still appear in endpoint/OpenAPI metadata. Exclude browser redirect endpoints
171
+ from the JSON client contract.
172
+
173
+ Build-time schema generation executes the entrypoint with a mock server. Follow the native
174
+ [entry-assembly detection guidance](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/openapi/aspnetcore-openapi?view=aspnetcore-10.0#customize-runtime-behavior-during-build-time-document-generation)
175
+ for `GetDocument.Insider` to bypass infrastructure startup/runtime secrets only during that
176
+ generation. Keep endpoint/service descriptions available. Normal startup still requires its
177
+ real database, identity and key configuration.
178
+
179
+ Generate reviewed frontend types with `openapi-typescript` and consume them through
180
+ `openapi-fetch`. Keep application-owned TanStack Query caching and mutation boundaries. Define
181
+ root `generate:api` and non-writing `generate:api:check` commands; CI builds the backend schema,
182
+ checks generated-client drift, then type-checks and builds the frontend. Handwritten API
183
+ wrappers may compose generated types; DTO copies are not an additional contract source.
184
+
185
+ Done: generation succeeds without live PostgreSQL, cloud services or runtime secrets, and the
186
+ generated client compiles with every selected route parameter and response shape.
187
+
188
+ ## Frontend ownership and state
189
+
190
+ Keep `main.tsx` to composition, with individual views and focused session/data hooks. A private
191
+ workspace app-shell package owns presentation slots/styles; application routing, account state
192
+ and business behavior stay in the portal. A separate private UI source package owns shared
193
+ controls and Tailwind theme tokens. Use shadcn's Base UI registry, pinned generation tooling
194
+ and matching application/package `components.json` aliases following its
195
+ [monorepo guide](https://ui.shadcn.com/docs/monorepo). Include shared component source in
196
+ Tailwind scanning and consume the controls in real views. Keep generator provenance/licenses.
197
+
198
+ Enable stable React Compiler transforms in development and production for the installed React
199
+ major, including linked workspace source. For `@vitejs/plugin-react` 6+, use
200
+ `reactCompilerPreset` through `@rolldown/plugin-babel`; follow the
201
+ [version-matched installation guide](https://react.dev/learn/react-compiler/installation).
202
+ Inspect representative optimizable application, shell and shared-control output; a successful
203
+ Vite build alone does not establish that the compiler transformed linked source.
204
+
205
+ Include account identity and tenant/resource identity in scoped query keys. Reset view and
206
+ form state when the resource changes; version alone is insufficient because different resources
207
+ can have equal versions. Include identity plus version when resetting an editor to refreshed
208
+ server state, preserving the application's intended unsaved-edit behavior. Mutation invalidation
209
+ stays application-owned. Treat 403 membership revocation and 409 stale writes explicitly.
210
+
211
+ Done: cached navigation between two resources with equal versions displays the correct data
212
+ and form values. Switching accounts cannot display another account's cached data; a suspended
213
+ membership loses protected access while any remaining account/organization access follows policy.
214
+
215
+ ## Clean-consumer acceptance
216
+
217
+ Provide these root commands with the behavior above. Run against a clean checkout and record
218
+ the exact toolchain, Gloaming revision/version/archive source and outcomes:
219
+
220
+ 1. Prepare the selected package source as described in [library integration](gloaming.md).
221
+ Run `pnpm install --frozen-lockfile`, `npm ci --prefix orchestration/local` and
222
+ `dotnet tool restore`, then locked solution restore from an initially empty NuGet package cache.
223
+ 2. Run `pnpm format:check` and `pnpm lint`, plus the retained staged-content fixtures. Check
224
+ both the capitalized conventional-commit example and an invalid message through commitlint.
225
+ 3. Build the backend/native OpenAPI, run `pnpm generate:api:check`, then `pnpm check:web`,
226
+ `pnpm check:e2e` and `pnpm build:web`. Include workspace UI/shell in type/lint checks.
227
+ Verify development and production compiler output for representative shared source.
228
+ 4. Run native PostgreSQL integration/architecture checks through the finite Migrator and
229
+ restricted runtime role. Include admission/direct Contracts rejection, registration races,
230
+ stale writes, audit rollback and forbidden schema/audit SQL from [verification](verification.md).
231
+ 5. Install Playwright Test's browser and Linux system dependencies where required. Run
232
+ `pnpm test:e2e` against a sibling E2E AppHost with its own disposable PostgreSQL, identity
233
+ realm, key storage, secret parameters and ports. Cover actual OIDC/logout, CSRF, generated
234
+ client operations, account changes, equal-version resource navigation and membership revocation.
235
+ 6. Hold an exclusive E2E run lock from startup through teardown, refuse occupied ports and
236
+ target the exact E2E AppHost. Retain ownership/recovery information after failed stop;
237
+ verify the developer stack/data survive. Separately prove developer restart persistence.
238
+
239
+ Use Playwright Test for browser journeys and xUnit with Microsoft Testing Platform for new
240
+ .NET integration/architecture checks, preserving an existing application's selected runner.
241
+ Retain failure traces/screenshots and cleanup instructions.
242
+ Automate ongoing acceptance checks in consumer CI; label one-off or historical execution and
243
+ remote CI/deployment gaps in the handoff. A local browser result does not establish production
244
+ ingress, customer federation or another Gloaming capability's support.
package/entity-work.md ADDED
@@ -0,0 +1,93 @@
1
+ # Serializing work for one entity
2
+
3
+ Different deliveries can target the same consumer entity. Choose an explicit complete entity key
4
+ when cooperating workers must exclude each other across those deliveries. Native PostgreSQL
5
+ transaction advisory locks are sufficient for this selected composition; no additional Gloaming
6
+ library interface or reusable mechanism is introduced.
7
+
8
+ Use the owning module's fresh native ReadCommitted transaction. Acquire the lock **before** reading the business
9
+ state used for the decision. Hold it through the selected state/outbox save and native commit.
10
+ Rollback, connection loss and process death release a transaction lock. Committing releases it
11
+ even while the process/connection remains alive. Do not substitute a session advisory lock on a
12
+ pooled connection, release early or move the business decision to another transaction.
13
+ See PostgreSQL's [advisory-lock lifetime](https://www.postgresql.org/docs/18/explicit-locking.html#ADVISORY-LOCKS)
14
+ and [native advisory functions](https://www.postgresql.org/docs/18/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS).
15
+ Rolling back to a savepoint created **before** acquisition releases that lock even while the
16
+ outer transaction remains open. Discard the old decision; reacquire and reread in a supported
17
+ fresh decision before doing more protected work. A savepoint is not evidence of continued exclusion.
18
+
19
+ ## Native composition
20
+
21
+ All cooperating deployed writers agree on the same versioned key protocol and namespace. This
22
+ example uses UTF-8 byte lengths to frame opaque module, technical scope and complete entity keys.
23
+ Native ID values must be canonically encoded by their consumer; an entity with tenant/partition
24
+ components includes all of them. Module and scope are not inferred from optional message metadata.
25
+ Key comparison is ordinal and case-sensitive. A delimiter-joined ambiguous string, `GetHashCode`
26
+ or a delivery ID is not the same protocol.
27
+
28
+ ```csharp
29
+ string[] fields = ["consumer.entity-work.v1", moduleKey, scopeKey, entityKey];
30
+ foreach (string field in fields)
31
+ ArgumentException.ThrowIfNullOrWhiteSpace(field);
32
+
33
+ string framed = string.Concat(fields.Select(field =>
34
+ FormattableString.Invariant($"{Encoding.UTF8.GetByteCount(field)}:{field}")));
35
+ long lockKey = BinaryPrimitives.ReadInt64BigEndian(
36
+ SHA256.HashData(Encoding.UTF8.GetBytes(framed)));
37
+
38
+ await using var command = new NpgsqlCommand(
39
+ "SELECT pg_advisory_xact_lock(@key)", connection, transaction);
40
+ command.Parameters.AddWithValue("key", lockKey);
41
+ await command.ExecuteNonQueryAsync(token);
42
+
43
+ // Now load and decide using this transaction. Save selected effects/outbox, then commit.
44
+ ```
45
+
46
+ Imports are `System.Buffers.Binary`, `System.Security.Cryptography`, `System.Text` and `Npgsql`.
47
+ The application owns `connection`, `transaction`, key admission, bounded execution and cleanup.
48
+ EF consumers may use the current Npgsql connection/transaction from their owning context; don't
49
+ open a separate connection for the lock. Database names are naturally separate PostgreSQL lock
50
+ namespaces. The prefix separates this protocol from logical command receipts and other advisory
51
+ lock conventions. A 64-bit hash collision adds unnecessary contention; it does not admit two
52
+ equal complete keys simultaneously. Advisory locking remains cooperative: raw SQL or other
53
+ writers that omit it can still change rows. Keep native concurrency predicates/constraints.
54
+
55
+ ## Guarantees and limits
56
+
57
+ This supplies mutual exclusion among cooperating transactions for the same complete key. It
58
+ does **not** supply FIFO, ordering by delivery or commit/start time, fairness, deduplication,
59
+ retry policy, admission or exactly-once effects. A waiter may be cancelled or selected in a
60
+ different order. Consumers control queue order and retry/backoff if their business needs them.
61
+ Use logical command/inbox receipts separately for retained duplicate/content evidence. Recheck
62
+ current business state and permissions after acquisition; the lock grants no authority.
63
+
64
+ Use one complete entity per transaction where possible. If a decision locks several entities,
65
+ every writer must use the same total acquisition order; otherwise native deadlock detection may
66
+ abort one transaction. Keep work bounded, propagate cancellation and dispose failed transactions.
67
+ Retry only a fresh authorized decision according to consumer policy. A lost commit response may
68
+ already mean success; inspect retained business/receipt evidence, not the existence of a lock.
69
+ No generic lock table, automatic worker serialization or cleanup scheduler is installed.
70
+
71
+ Ordinary module credentials need only their selected business-table/schema permissions and
72
+ EXECUTE on the native advisory-lock function. The usual PostgreSQL public function grant suffices
73
+ in the proof; deployments that revoke it must deliberately grant required execution. No migration,
74
+ retention, superuser or BYPASSRLS authority is needed. Business tables/migrations and reader/writer
75
+ deployment remain application-owned. Changing key encoding/namespaces during mixed deployment
76
+ requires a coordinated writer rollout; old and new lock keys would not exclude each other.
77
+
78
+ ## Executable evidence
79
+
80
+ The [native-only worker fixture](https://github.com/oxface/gloaming/blob/main/src/Gloaming.Messaging/tests/Fixtures/EntityWork/README.md)
81
+ references Npgsql without Gloaming packages. Two real worker processes prove same-key exclusion
82
+ with an observed ungranted native advisory lock; different module/scope/entity keys proceed while
83
+ the first transaction stays open. Other cases cover commit while the process stays alive,
84
+ rollback, killed process recovery, cancellation of an actually blocked acquire, fresh recovery
85
+ and restricted ordinary runtime grants with denied retention deletion. Literal full-key hash
86
+ vectors retain the native composition protocol. These tests establish this PostgreSQL/Linux
87
+ composition, not arbitrary providers or host topologies.
88
+
89
+ From the Gloaming repository root, run the owning provider suite:
90
+
91
+ ```bash
92
+ dotnet test --project src/Gloaming.Messaging/tests/OutboxPostgresTests/OutboxPostgresTests.csproj
93
+ ```
@@ -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/main/eng/release/consumers/HttpEstablishment.cs): native authentication, actor mapping, tenant admission and failed requests.
30
+ - [Personnel consumer](https://github.com/oxface/gloaming/blob/main/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/main/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/main/src/Gloaming.ActorIdentity/Gloaming.ActorIdentity.AspNetCore/README.md) and
42
+ [tenant](https://github.com/oxface/gloaming/blob/main/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/main/src/Gloaming.Persistence/Gloaming.Persistence.EntityFrameworkCore/README.md);
85
+ audit setup is in the
86
+ [audit contract](https://github.com/oxface/gloaming/blob/main/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/main/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.