@openlup/outbox 0.0.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md ADDED
@@ -0,0 +1,65 @@
1
+ # @openlup/outbox for agents
2
+
3
+ ## Purpose and kind
4
+
5
+ Kind: `rail`.
6
+
7
+ The package owns neutral dispatch, registry composition, lease-bound schedules and the default PostgreSQL store. Drivers, application handlers, credentials, producer transactions, host guards and trigger bindings stay in the application. Inside the OpenLup monorepo the root `AGENTS.md` governs.
8
+
9
+ ## Subpath maturity
10
+
11
+ | Export | Role | Maturity |
12
+ | --- | --- | --- |
13
+ | `.` | rail | experimental |
14
+ | `./postgres` | rail | experimental |
15
+ | `./testing` | testing | testing |
16
+
17
+ ## Wiring example
18
+
19
+ The compiled npm-only reference proof uses the same factories at scheduled and immediate entries. A minimal store binding is:
20
+
21
+ ```ts
22
+ import { createPostgresOutboxStore } from "@openlup/outbox/postgres";
23
+ import type { SqlExecutor } from "@openlup/core/readiness";
24
+ export const bindStore = (executor: SqlExecutor) => createPostgresOutboxStore(executor);
25
+ ```
26
+
27
+ The executor must commit every operation before resolving. Apply shipped SQL through the application's migration chain and admit the candidate with the core checker before effects. The README explains full schedule, transaction and failure ownership.
28
+
29
+ ## Sources and declarations
30
+
31
+ Inspect `src/` and the exported declaration files in `dist/`; `sql/manifest.json` binds the baseline. The development preview may change any experimental export.
32
+
33
+ ## Readiness codes
34
+
35
+ Composition can report `OPENLUP_E_PORT_MISSING`, `OPENLUP_E_EVENT_UNHANDLED`, `OPENLUP_E_EVENT_DUPLICATE`, `OPENLUP_E_SCHEDULE_UNBOUND`, `OPENLUP_E_SCHEMA_BEHIND`, `OPENLUP_E_SET_MISMATCH` and `OPENLUP_E_ENV_MISSING`. Unknown observations refuse activation. Catalog observations prove no SQL-body, ACL or provider-recovery semantics.
36
+
37
+ ## Using this package in an application
38
+
39
+ Keep the dispatch engine in its authentic npm package. Do not edit
40
+ `node_modules/@openlup/**`, autonomously patch/fork/vendor/monkey-patch/shadow the
41
+ package or restore a copied engine. Use declared public exports. Drivers,
42
+ handlers, policies, host bindings and compatible native stores remain ordinary
43
+ application code; they need no record per function or upstream release.
44
+
45
+ The public `withPayloadSchema`, `composeHandlers` and `uniqueRegistry` seams keep
46
+ handler policy and effects in the application. The [README](README.md) explains
47
+ retry, transaction, fence and admission obligations; `./testing` supplies the
48
+ store-fence check, not complete adapter or absorption proof. A missing seam needs
49
+ a local reproducer and authorized upstream proposal. Use a supported compatible
50
+ wrapper/adapter, or hold the dependent change while retaining compatible serving
51
+ work or an available compatible rollback. Do not rewrite published SQL or lose
52
+ pending obligations.
53
+
54
+ Upgrade every `@openlup/*` together after reading all `Migration:` blocks. Compare
55
+ current producer/schema/policy/bindings with the actual target at first adoption
56
+ and upgrade. Settle affected nominations as full, partial, retained or hold using
57
+ capability and durable-effect evidence, including dormant branches and retry;
58
+ keep distinct same-event effects. Move or settle open markers when native code is
59
+ refactored even without pin changes. A merged contribution is not adoption proof.
60
+
61
+ This guide describes the installed contract; it grants no host/tool/external-write
62
+ authority and installs no controls. The monorepo's contributor process does not
63
+ govern your application. Your application owns admission, delivery and production
64
+ authority. The [README's adoption route](README.md#adoption-and-native-extensions)
65
+ links optional source guidance; later instructions do not change this version.
package/CHANGELOG.md ADDED
@@ -0,0 +1,27 @@
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ## [0.14.0]
6
+
7
+ - Publishable on the npm `latest` dist-tag as `0.14.0`, from tag
8
+ `openlup-outbox-v0.14.0`.
9
+
10
+ - Republish with the exact `@openlup/core` `0.14.0` peer pin; Outbox APIs, runtime behavior and shipped SQL are unchanged.
11
+
12
+ ## [0.13.1]
13
+
14
+ - Publishable on the npm `latest` dist-tag as `0.13.1`, from tag
15
+ `openlup-outbox-v0.13.1`.
16
+
17
+ - Build the exact workspace core peer before packing outbox on a fresh publication runner. The `0.13.0` outbox publication stopped before npm; `0.13.1` restores the complete package set without changing APIs, runtime behavior or shipped SQL.
18
+
19
+ ## [0.13.0]
20
+
21
+ - Publishable on the npm `latest` dist-tag as `0.13.0`, from tag
22
+ `openlup-outbox-v0.13.0`.
23
+
24
+ - Introduce the experimental transactional outbox rail with bare dispatch, registry composition, typed-payload validation and lease-bound dispatch/prune schedules.
25
+ - Ship the default PostgreSQL store and fresh-install schema; terminal compaction preserves dedupe identities and leaves uncertain discard ages untouched.
26
+
27
+ Migration: before, an application owned its copied dispatch engine. After, compose the package and keep application-owned drivers, handlers, recovery and producer transactions; apply the shipped baseline only to a fresh database through your migration chain, then admit the exact candidate before effects. Upgrade the whole package set when released.
package/LICENSE ADDED
@@ -0,0 +1,204 @@
1
+ Copyright (c) 2026 Bartlomiej Roszkowski
2
+
3
+
4
+ Apache License
5
+ Version 2.0, January 2004
6
+ http://www.apache.org/licenses/
7
+
8
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
9
+
10
+ 1. Definitions.
11
+
12
+ "License" shall mean the terms and conditions for use, reproduction,
13
+ and distribution as defined by Sections 1 through 9 of this document.
14
+
15
+ "Licensor" shall mean the copyright owner or entity authorized by
16
+ the copyright owner that is granting the License.
17
+
18
+ "Legal Entity" shall mean the union of the acting entity and all
19
+ other entities that control, are controlled by, or are under common
20
+ control with that entity. For the purposes of this definition,
21
+ "control" means (i) the power, direct or indirect, to cause the
22
+ direction or management of such entity, whether by contract or
23
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
24
+ outstanding shares, or (iii) beneficial ownership of such entity.
25
+
26
+ "You" (or "Your") shall mean an individual or Legal Entity
27
+ exercising permissions granted by this License.
28
+
29
+ "Source" form shall mean the preferred form for making modifications,
30
+ including but not limited to software source code, documentation
31
+ source, and configuration files.
32
+
33
+ "Object" form shall mean any form resulting from mechanical
34
+ transformation or translation of a Source form, including but
35
+ not limited to compiled object code, generated documentation,
36
+ and conversions to other media types.
37
+
38
+ "Work" shall mean the work of authorship, whether in Source or
39
+ Object form, made available under the License, as indicated by a
40
+ copyright notice that is included in or attached to the work
41
+ (an example is provided in the Appendix below).
42
+
43
+ "Derivative Works" shall mean any work, whether in Source or Object
44
+ form, that is based on (or derived from) the Work and for which the
45
+ editorial revisions, annotations, elaborations, or other modifications
46
+ represent, as a whole, an original work of authorship. For the purposes
47
+ of this License, Derivative Works shall not include works that remain
48
+ separable from, or merely link (or bind by name) to the interfaces of,
49
+ the Work and Derivative Works thereof.
50
+
51
+ "Contribution" shall mean any work of authorship, including
52
+ the original version of the Work and any modifications or additions
53
+ to that Work or Derivative Works thereof, that is intentionally
54
+ submitted to Licensor for inclusion in the Work by the copyright owner
55
+ or by an individual or Legal Entity authorized to submit on behalf of
56
+ the copyright owner. For the purposes of this definition, "submitted"
57
+ means any form of electronic, verbal, or written communication sent
58
+ to the Licensor or its representatives, including but not limited to
59
+ communication on electronic mailing lists, source code control systems,
60
+ and issue tracking systems that are managed by, or on behalf of, the
61
+ Licensor for the purpose of discussing and improving the Work, but
62
+ excluding communication that is conspicuously marked or otherwise
63
+ designated in writing by the copyright owner as "Not a Contribution."
64
+
65
+ "Contributor" shall mean Licensor and any individual or Legal Entity
66
+ on behalf of whom a Contribution has been received by Licensor and
67
+ subsequently incorporated within the Work.
68
+
69
+ 2. Grant of Copyright License. Subject to the terms and conditions of
70
+ this License, each Contributor hereby grants to You a perpetual,
71
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
72
+ copyright license to reproduce, prepare Derivative Works of,
73
+ publicly display, publicly perform, sublicense, and distribute the
74
+ Work and such Derivative Works in Source or Object form.
75
+
76
+ 3. Grant of Patent License. Subject to the terms and conditions of
77
+ this License, each Contributor hereby grants to You a perpetual,
78
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79
+ (except as stated in this section) patent license to make, have made,
80
+ use, offer to sell, sell, import, and otherwise transfer the Work,
81
+ where such license applies only to those patent claims licensable
82
+ by such Contributor that are necessarily infringed by their
83
+ Contribution(s) alone or by combination of their Contribution(s)
84
+ with the Work to which such Contribution(s) was submitted. If You
85
+ institute patent litigation against any entity (including a
86
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
87
+ or a Contribution incorporated within the Work constitutes direct
88
+ or contributory patent infringement, then any patent licenses
89
+ granted to You under this License for that Work shall terminate
90
+ as of the date such litigation is filed.
91
+
92
+ 4. Redistribution. You may reproduce and distribute copies of the
93
+ Work or Derivative Works thereof in any medium, with or without
94
+ modifications, and in Source or Object form, provided that You
95
+ meet the following conditions:
96
+
97
+ (a) You must give any other recipients of the Work or
98
+ Derivative Works a copy of this License; and
99
+
100
+ (b) You must cause any modified files to carry prominent notices
101
+ stating that You changed the files; and
102
+
103
+ (c) You must retain, in the Source form of any Derivative Works
104
+ that You distribute, all copyright, patent, trademark, and
105
+ attribution notices from the Source form of the Work,
106
+ excluding those notices that do not pertain to any part of
107
+ the Derivative Works; and
108
+
109
+ (d) If the Work includes a "NOTICE" text file as part of its
110
+ distribution, then any Derivative Works that You distribute must
111
+ include a readable copy of the attribution notices contained
112
+ within such NOTICE file, excluding those notices that do not
113
+ pertain to any part of the Derivative Works, in at least one
114
+ of the following places: within a NOTICE text file distributed
115
+ as part of the Derivative Works; within the Source form or
116
+ documentation, if provided along with the Derivative Works; or,
117
+ within a display generated by the Derivative Works, if and
118
+ wherever such third-party notices normally appear. The contents
119
+ of the NOTICE file are for informational purposes only and
120
+ do not modify the License. You may add Your own attribution
121
+ notices within Derivative Works that You distribute, alongside
122
+ or as an addendum to the NOTICE text from the Work, provided
123
+ that such additional attribution notices cannot be construed
124
+ as modifying the License.
125
+
126
+ You may add Your own copyright statement to Your modifications and
127
+ may provide additional or different license terms and conditions
128
+ for use, reproduction, or distribution of Your modifications, or
129
+ for any such Derivative Works as a whole, provided Your use,
130
+ reproduction, and distribution of the Work otherwise complies with
131
+ the conditions stated in this License.
132
+
133
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
134
+ any Contribution intentionally submitted for inclusion in the Work
135
+ by You to the Licensor shall be under the terms and conditions of
136
+ this License, without any additional terms or conditions.
137
+ Notwithstanding the above, nothing herein shall supersede or modify
138
+ the terms of any separate license agreement you may have executed
139
+ with Licensor regarding such Contributions.
140
+
141
+ 6. Trademarks. This License does not grant permission to use the trade
142
+ names, trademarks, service marks, or product names of the Licensor,
143
+ except as required for reasonable and customary use in describing the
144
+ origin of the Work and reproducing the content of the NOTICE file.
145
+
146
+ 7. Disclaimer of Warranty. Unless required by applicable law or
147
+ agreed to in writing, Licensor provides the Work (and each
148
+ Contributor provides its Contributions) on an "AS IS" BASIS,
149
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
150
+ implied, including, without limitation, any warranties or conditions
151
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
152
+ PARTICULAR PURPOSE. You are solely responsible for determining the
153
+ appropriateness of using or redistributing the Work and assume any
154
+ risks associated with Your exercise of permissions under this License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable to You for damages, including any direct, indirect, special,
161
+ incidental, or consequential damages of any character arising as a
162
+ result of this License or out of the use or inability to use the
163
+ Work (including but not limited to damages for loss of goodwill,
164
+ work stoppage, computer failure or malfunction, or any and all
165
+ other commercial damages or losses), even if such Contributor
166
+ has been advised of the possibility of such damages.
167
+
168
+ 9. Accepting Warranty or Additional Liability. While redistributing
169
+ the Work or Derivative Works thereof, You may choose to offer,
170
+ and charge a fee for, acceptance of support, warranty, indemnity,
171
+ or other liability obligations and/or rights consistent with this
172
+ License. However, in accepting such obligations, You may act only
173
+ on Your own behalf and on Your sole responsibility, not on behalf
174
+ of any other Contributor, and only if You agree to indemnify,
175
+ defend, and hold each Contributor harmless for any liability
176
+ incurred by, or claims asserted against, such Contributor by reason
177
+ of your accepting any such warranty or additional liability.
178
+
179
+ END OF TERMS AND CONDITIONS
180
+
181
+ APPENDIX: How to apply the Apache License to your work.
182
+
183
+ To apply the Apache License to your work, attach the following
184
+ boilerplate notice, with the fields enclosed by brackets "[]"
185
+ replaced with your own identifying information. (Don't include
186
+ the brackets!) The text should be enclosed in the appropriate
187
+ comment syntax for the file format. We also recommend that a
188
+ file or class name and description of purpose be included on the
189
+ same "printed page" as the copyright notice for easier
190
+ identification within third-party archives.
191
+
192
+ Copyright [yyyy] [name of copyright owner]
193
+
194
+ Licensed under the Apache License, Version 2.0 (the "License");
195
+ you may not use this file except in compliance with the License.
196
+ You may obtain a copy of the License at
197
+
198
+ http://www.apache.org/licenses/LICENSE-2.0
199
+
200
+ Unless required by applicable law or agreed to in writing, software
201
+ distributed under the License is distributed on an "AS IS" BASIS,
202
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203
+ See the License for the specific language governing permissions and
204
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,95 @@
1
- # Package-name registration placeholder
1
+ # @openlup/outbox
2
2
 
3
- This inert version reserves the package name for automated, provenance-backed releases. It contains no implementation. Do not install it for application use.
3
+ Development preview, kind `rail`. One at-least-once dispatch engine, lease-bound dispatch and terminal-compaction schedules, registry composition, transactional enqueue and a driver-free PostgreSQL default. No stable API or universal exactly-once guarantee is claimed.
4
+
5
+ The publication catalogue admits this complete rail to the release set. Catalogue admission does not publish it: direct directory publishing still refuses, and the reviewed release workflow owns provenance-backed publication. New API and shipped SQL require the next minor set.
6
+
7
+ ## Package Surface Maturity
8
+
9
+ | Export | Role | Maturity |
10
+ | --- | --- | --- |
11
+ | `.` | rail | experimental |
12
+ | `./postgres` | rail | experimental |
13
+ | `./testing` | testing | testing |
14
+
15
+ The application supplies its driver, committed-operation executor, lease adapter, effect handlers, explicit ordered known event vocabulary and host trigger bindings. `createOutbox` validates effective composed timeouts before construction and matches the run-built registry before the first claim. The lease must cover the full declared host execution window, including finish time; the factory has no renewal loop. Build after the lease; a builder owns partially acquired resources until it returns a scope. A returned scope closes after finish, including failure. Hook metadata cannot replace reserved run identity or worker counters. A resolved negative business observation is nonfatal; a thrown business hook prevents claims and attempts a failed finish once. A failed finish remains observable; cleanup errors do not turn accepted effects into retries.
16
+
17
+ The bare `runOutboxDispatchWorker` supports immediate dispatch without a job lease. The registry alone supplies its claim allowlist. `knownEventTypes` is explicit and is never derived from enabled handlers. A composed handler replays its first component when the second retries, sums timeouts, and retains the original nested details and top-level delivery observations. Its components deliberately do not receive the transient execution context. Effects must honor abort and enforce their own idempotency; timeout cannot cancel a request already accepted by a provider.
18
+
19
+ ## PostgreSQL installation and transactions
20
+
21
+ Apply [the baseline](sql/0001_outbox.sql) through your own migration chain on a fresh PostgreSQL database. [The manifest](sql/manifest.json) binds its bytes to their public migration owner. PostgreSQL 16 or later supplies the validated timestamp parser used by compaction. Importing the package never applies SQL. Existing managed schemas need their own compatibility assessment; do not apply the fresh-install baseline over them. The default does not supply provider recovery, RLS or role grants.
22
+
23
+ `buildOutboxEnqueue` returns bound SQL for the producer's transaction. Execute the domain write and enqueue on the same transaction client; commit or roll back both. Duplicate `(event_type,idempotency_key)` enqueue creates no second row. The dispatch executor must commit each claim/ack/failure/release operation before its promise resolves, with no transaction held across handler I/O. A type-compatible executor alone does not prove this property. Compaction likewise commits per operation.
24
+
25
+ Claims retain six timestamp digits, per-aggregate ordering, exact dormant identities and claim-token fences. An unknown non-dormant predecessor blocks its aggregate; a known but currently unclaimed type may be bypassed. Snooze and release refund attempts. Storage errors remain exceptions; unstarted claims from an interrupted batch expire rather than being falsely settled.
26
+
27
+ Prune defaults to 30 days for processed and 90 for discarded, in batches of 500. It empties terminal payload/error and stamps `retentionCompactedAt`, `retentionCompactedBy` and `retentionCompactedStatus`; rows and unique dedupe keys survive. Missing/malformed discard timestamps are ineligible. Pending, failed and processing work remains untouched. Application delivery/ledger adjunct retention remains application-owned.
28
+
29
+ ## Readiness and verification
30
+
31
+ <!-- openlup-doc-impact {"unit":"outbox-rail","digest":"sha256-207a9646260642afdf50398c025d2305f1126fc89a45a5652ededd14bef1f402","reason":"The Outbox version and exact Core peer pin move together from 0.13.1 to 0.14.0. This preparation changes no Outbox API, runtime, SQL, readiness responsibilities or verification step."} -->
32
+
33
+ Compose the contribution with `@openlup/core/readiness`, actual loaded package metadata, selected-adapter schema observations and host bindings to the exact contribution run/handle functions before activating the exact new candidate. Only `ready` admits; `unknown` and `unsatisfied` leave the serving version running. Descriptors are inert; the builder supplies the same actual event identities and effective timeouts after lease acquisition. The default schema declaration describes catalog existence and overloads; it does not prove bodies, ACL or recovery. Use framework-free fence conformance from `./testing` and real transactional proof for your adapter. No ambient database URL is used by the packed proof.
34
+
35
+ From an OpenLup task checkout, the existing packed proof accepts an explicit disposable loopback PostgreSQL database and a verified cold-set manifest:
36
+
37
+ ```sh
38
+ node --experimental-strip-types scripts/packages/outbox-consumer-proof.ts \
39
+ postgresql://postgres@127.0.0.1:5432/openlup_outbox_proof \
40
+ .context/scratch/outbox-packed-proof \
41
+ --manifest "$OPENLUP_PACK_MANIFEST" --expected-commit "$OPENLUP_PACK_COMMIT"
42
+ ```
43
+
44
+ Supply both manifest inputs together. The runner verifies the exact publishable inventory, versions, commit and tarball digests before installation; missing or damaged input refuses without repacking. It installs only Core and Outbox, the packages imported by this reference composition; unrelated modules have their own consumers. It installs outside checkout ancestry with scripts disabled, records consumed artifacts and installed identities in task scratch, injects only the host PostgreSQL test driver and compiles the actual reference composition. Omitting both inputs retains manual packing of already-built packages. The caller owns the disposable database; the proof closes its pools and removes its temporary consumer on success or failure. Required CI and its local runner provide an owned PostgreSQL 17 instance and an enclosing deadline.
45
+
46
+ For the local required route, run `node --experimental-strip-types scripts/packages/outbox-disposable-postgres.ts --manifest <manifest-path> --expected-commit <full-sha>`. It owns a fresh pinned PostgreSQL 17 container, loopback port, database and cleanup; it refuses invalid artifacts before starting the service. The CI form receives the exact pinned job service container ID and mapped port, creates only this proof's UUID-named database and drops it afterward, including when the CREATE response is lost. The manual proof above retains its fixed disposable database name; the owned route uses `openlup_outbox_proof_<32 lowercase UUID hex digits>`. Neither form adopts an ambient service. Local cleanup can recover the container by its known unique name if its creation response is lost, and requires the actual name, ID and owner label before removal. Startup is bounded at 30 seconds, packed child work at 180 seconds, and each Docker operation at 30 seconds; interruptions terminate the child process group before owned cleanup. Repeated signals forwarded by npm or the package wrapper remain handled until cleanup finishes. The actual proof owner also shields its bounded cleanup inspect, container removal and database DROP commands from verifier group signals. The owner stays in that group until those commands finish; their existing 30-second limits and all ownership checks remain. Local containers use one CPU and 512 MiB of memory. These are proof bounds, not package runtime settings.
47
+
48
+ Before SQL, the Outbox binding supplies its actual installed schema/probe/checker exports and reference input to the common repository test utility `scripts/packages/schema-budget-proof.mjs`. Future modules can reuse that utility with their own installed requirement and input callback; it carries no package registry or duplicate schema inventory. Its positive serial model uses 250 ms setup plus 100 ms per presence operation, so actual schema growth participates automatically. A single operation longer than the unchanged 3000 ms waiting deadline proves timeout refusal even if the adapter later batches reads. Completeness and overload cases follow the supplied schema's capabilities. Timer cleanup does not imply cancellation of pending driver work; the proof settles its owned fake queue before restoring real timers. The same real database then demonstrates absent table, column and function-overload observations. A single replay witness accepts a synthetic durable effect, loses acknowledgement, reclaims the same event through scheduled work after immediate work, refuses the formerly valid token and acknowledges the new claim. Multiple attempts with one application-owned deduped effect demonstrate at-least-once recovery for this synthetic example, not provider recovery or a universal exactly-once contract.
49
+
50
+ The same installed Core tarball also executes the additive grouped readiness
51
+ catalog query in [the neutral grouped proof](smoke/groupedSchemaProof.ts).
52
+ Within a host-owned read-only repeatable-read transaction it compares grouped
53
+ presence with every scalar probe, including the existing Outbox requirement,
54
+ exact overloads, absent objects, dropped/system columns, views and sequences,
55
+ quoted relation names, duplicate ordinals and an empty request. Independent
56
+ catalog reads verify constraints, indexes, noninternal triggers, policies and
57
+ function definitions. Fresh tables/partitions, identity/generated/default
58
+ columns, RLS, ACL and function configuration/security/volatility exercise rich
59
+ and empty shapes. The proof requires jsonb text rows, definition-string arrays,
60
+ null empty aggregates, raw policy OIDs/command codes/booleans and exact parsed
61
+ jsonb property/nested ordering. Parsed driver objects are refused.
62
+ Invalid catalog resolution still propagates to the host. This reuses the existing
63
+ pinned PostgreSQL service, artifact checks and cleanup; it adds no gate or host
64
+ admission policy and does not prove effective authorization or SQL behavior.
65
+
66
+ The root companion tests retain real interruption and lost-response fixtures. Their owned JSON witness markers are written completely to a same-directory temporary file and then renamed into place, so readers never treat a newly created, partially written file as a ready observation. A plain Node process owns each fixture's service and launcher and stays in the root test process group until teardown finishes, even when Vitest's worker exits. Only the bounded Docker cleanup commands detach; their process-start window can still receive a group TERM. The companion fixture allows one recovery only for a child terminated by SIGTERM with no reported error, inside the original 10-second inspect or removal deadline. An interrupted removal is followed by actual Docker inspection: normal no-such-object refusal confirms absence, otherwise the same full ID, name and UUID label must still match before one removal retry. The recovery never resets its deadline, treats a signal as absence, or masks a timeout, nonzero result, wrong owner or second interruption. Cleanup recovers by the known unique name after a lost creation response. Root cancellation regressions interrupt actual Vitest workers after service creation and after detached proof readiness, and check resource termination before releasing their own test lock. They create no verification stamp or shared verifier lock. Separate teardown regressions cancel the actual npm/launcher route during each cleanup operation and assert that its container or UUID database is removed while an unrelated supplied-service database remains.
67
+
68
+ Upgrade the complete `@openlup/*` set together after reading each changelog. Use ports and composition; do not edit or patch installed package bytes. Sources are in `src/`, built JavaScript/declarations in `dist/`. Synthetic packed-consumer proof is first-party package evidence, not an independent adopter, provider-delivery or deployment certificate.
69
+
70
+ ## Adoption and native extensions
71
+
72
+ One npm package owns the dispatch algorithm. Application drivers, handlers,
73
+ policies, host bindings and compatible native stores remain editable through
74
+ public seams without a nomination or per-function ownership record. Do not
75
+ autonomously fork, vendor, monkey-patch, shadow or restore a copied engine; use
76
+ only the installed package's declared exports. A missing seam follows the
77
+ [agent guide's dependent hold and compatible recovery route](AGENTS.md#using-this-package-in-an-application).
78
+
79
+ At first adoption compare the actual selected artifact with current consumer
80
+ behavior, including producer payload/schema and composition changes outside the
81
+ extracted engine. On upgrades, preserve pending obligations, transactional enqueue,
82
+ claim/ack/fencing and native recovery. Compatible native schema additions remain
83
+ permitted; published SQL stays immutable. Validate the actual adapter and serving
84
+ binding. For full or partial absorption remove only proven duplicate behavior,
85
+ retain distinct effects sharing an event, and demonstrate durable success and
86
+ unfinished work across retries and replacement. Catalogue existence, a handler
87
+ return or an upstream merge alone cannot establish that proof.
88
+
89
+ The public [adopter recipe](https://github.com/openlup/openlup/blob/main/docs/platform/adopter-kit/README.md#adopt-or-upgrade-a-package)
90
+ explains source-local nominations and full/partial/retained/hold dispositions.
91
+ Select that optional source guidance at a deliberate revision against your
92
+ installed contract. This package guide conveys version-bound contract information,
93
+ not tool permissions, an automatic control installation or external-write authority.
94
+ The existing wiring and packed protocol examples remain narrow package evidence;
95
+ a complete extension/absorption/retry witness belongs to the actual module adoption.
@@ -0,0 +1,4 @@
1
+ import type { OutboxDispatchConfig } from "./contracts.js";
2
+ export declare function readOutboxDispatchConfig(env: Record<string, string | undefined>, prefix?: string): OutboxDispatchConfig;
3
+ /** @beta Scheduled configuration is stricter than the bare immediate worker. */
4
+ export declare function validateScheduledConfig(config: OutboxDispatchConfig, hostLimitSeconds: number, timeouts: readonly number[]): void;
package/dist/config.js ADDED
@@ -0,0 +1,73 @@
1
+ const CONFIG_BOUNDS = {
2
+ batchSize: { env: "COMMERCE_OUTBOX_DISPATCH_BATCH_SIZE", def: 25, min: 1, max: 100 },
3
+ maxAttempts: { env: "COMMERCE_OUTBOX_DISPATCH_MAX_ATTEMPTS", def: 8, min: 1, max: 20 },
4
+ visibilitySeconds: {
5
+ env: "COMMERCE_OUTBOX_DISPATCH_VISIBILITY_SECONDS",
6
+ def: 300,
7
+ min: 300,
8
+ max: 3600,
9
+ },
10
+ backoffBaseSeconds: { env: "COMMERCE_OUTBOX_DISPATCH_BACKOFF_BASE_SECONDS", def: 60, min: 5, max: 3600 },
11
+ backoffCapSeconds: { env: "COMMERCE_OUTBOX_DISPATCH_BACKOFF_CAP_SECONDS", def: 3600, min: 5, max: 86_400 },
12
+ snoozeSeconds: { env: "COMMERCE_OUTBOX_DISPATCH_SNOOZE_SECONDS", def: 300, min: 60, max: 3600 },
13
+ maxSnoozes: { env: "COMMERCE_OUTBOX_DISPATCH_MAX_SNOOZES", def: 48, min: 1, max: 1000 },
14
+ // Max keeps a >= 15s tail under the cron's hard kill: drain stop + in-flight
15
+ // handler + marks + queue stats + finishJobRun must all fit after the budget.
16
+ softBudgetMs: {
17
+ env: "COMMERCE_OUTBOX_DISPATCH_SOFT_BUDGET_MS",
18
+ def: 40_000,
19
+ min: 5000,
20
+ max: 60 * 1000 - 15_000,
21
+ },
22
+ };
23
+ function readBoundedInt(env, bound) {
24
+ const raw = env[bound.env];
25
+ if (raw === undefined || raw.trim() === "")
26
+ return bound.def;
27
+ const parsed = Number.parseInt(raw, 10);
28
+ if (!Number.isFinite(parsed)) {
29
+ console.warn(`[outbox-dispatch] invalid ${bound.env}=${raw}; using default ${bound.def}`);
30
+ return bound.def;
31
+ }
32
+ const clamped = Math.min(Math.max(parsed, bound.min), bound.max);
33
+ if (clamped !== parsed) {
34
+ console.warn(`[outbox-dispatch] ${bound.env}=${parsed} clamped to ${clamped}`);
35
+ }
36
+ return clamped;
37
+ }
38
+ export function readOutboxDispatchConfig(env, prefix = "COMMERCE_OUTBOX_DISPATCH_") {
39
+ const bounds = Object.fromEntries(Object.entries(CONFIG_BOUNDS).map(([key, bound]) => [key, { ...bound, env: prefix + bound.env.slice("COMMERCE_OUTBOX_DISPATCH_".length) }]));
40
+ const config = {
41
+ batchSize: readBoundedInt(env, bounds.batchSize),
42
+ maxAttempts: readBoundedInt(env, bounds.maxAttempts),
43
+ visibilitySeconds: readBoundedInt(env, bounds.visibilitySeconds),
44
+ backoffBaseSeconds: readBoundedInt(env, bounds.backoffBaseSeconds),
45
+ backoffCapSeconds: readBoundedInt(env, bounds.backoffCapSeconds),
46
+ snoozeSeconds: readBoundedInt(env, bounds.snoozeSeconds),
47
+ maxSnoozes: readBoundedInt(env, bounds.maxSnoozes),
48
+ softBudgetMs: readBoundedInt(env, bounds.softBudgetMs),
49
+ };
50
+ if (config.backoffCapSeconds < config.backoffBaseSeconds) {
51
+ console.warn(`[outbox-dispatch] backoff cap ${config.backoffCapSeconds}s below base ${config.backoffBaseSeconds}s; raising cap to base`);
52
+ config.backoffCapSeconds = config.backoffBaseSeconds;
53
+ }
54
+ return config;
55
+ }
56
+ /** @beta Scheduled configuration is stricter than the bare immediate worker. */
57
+ export function validateScheduledConfig(config, hostLimitSeconds, timeouts) {
58
+ const fail = (key, fix) => { throw new Error(`@openlup/outbox: ${key}: ${fix}`); };
59
+ if (!Number.isFinite(hostLimitSeconds) || hostLimitSeconds < 20 || hostLimitSeconds > 720)
60
+ fail("hostLimitSeconds", "use 20–720 seconds");
61
+ for (const [key, bound] of Object.entries(CONFIG_BOUNDS)) {
62
+ const value = config[key];
63
+ const min = key === "visibilitySeconds" ? Math.min(5 * hostLimitSeconds, 3600) : bound.min;
64
+ const max = key === "softBudgetMs" ? hostLimitSeconds * 1000 - 15000 : bound.max;
65
+ if (!Number.isInteger(value) || value < min || value > max)
66
+ fail(key, `use an integer in ${min}–${max}`);
67
+ }
68
+ if (config.backoffCapSeconds < config.backoffBaseSeconds)
69
+ fail("backoffCapSeconds", "keep cap at least the base delay");
70
+ for (const timeout of timeouts)
71
+ if (!Number.isFinite(timeout) || timeout <= 0 || timeout + 2000 > config.softBudgetMs)
72
+ fail("handler.timeoutMs", "fit the effective timeout plus 2000 ms mark margin in the budget");
73
+ }
@@ -0,0 +1,88 @@
1
+ import type { OutboxHandler as KernelHandler, OutboxEventRow } from "@openlup/core/outbox";
2
+ export type { OutboxEventRow, OutboxHandlerOutcome, OutboxHandlerExecutionContext, OutboxHandlerDescriptor } from "@openlup/core/outbox";
3
+ /** @beta The worker creates the host's standard AbortController. */
4
+ export type OutboxHandler = KernelHandler<AbortSignal>;
5
+ export type OutboxHandlerRegistry = ReadonlyMap<string, OutboxHandler>;
6
+ export type OutboxMarkFailedStatus = "failed" | "discarded" | "snoozed" | "missed";
7
+ export interface OutboxStore {
8
+ /** Read-only preflight used to admit a terminal handler when active providers are unavailable. */
9
+ hasPendingEventType?(eventType: string): Promise<boolean>;
10
+ claimBatch(input: {
11
+ eventTypes: readonly string[];
12
+ knownEventTypes?: readonly string[];
13
+ batchSize: number;
14
+ visibilitySeconds: number;
15
+ maxAttempts: number;
16
+ }): Promise<OutboxEventRow[]>;
17
+ markProcessed(input: {
18
+ eventId: string;
19
+ claimToken: string;
20
+ metadata?: Record<string, unknown>;
21
+ }): Promise<{
22
+ applied: boolean;
23
+ }>;
24
+ markFailed(input: {
25
+ eventId: string;
26
+ claimToken: string;
27
+ error: string;
28
+ outcome: "retry" | "discard" | "snooze";
29
+ baseDelaySeconds: number;
30
+ maxDelaySeconds: number;
31
+ maxAttempts: number;
32
+ snoozeSeconds: number;
33
+ }): Promise<{
34
+ status: OutboxMarkFailedStatus;
35
+ }>;
36
+ releaseUnprocessed(items: ReadonlyArray<{
37
+ eventId: string;
38
+ claimToken: string;
39
+ }>, delaySeconds: number): Promise<number>;
40
+ }
41
+ /** Managed-only best-effort queue observation, separate from core claim/ack policy. */
42
+ export interface OutboxQueueDiagnostics {
43
+ queueStats(): Promise<Record<string, unknown>>;
44
+ }
45
+ export interface Clock {
46
+ now(): number;
47
+ }
48
+ export interface OutboxDispatchRunResult {
49
+ ok: boolean;
50
+ checked: number;
51
+ updated: number;
52
+ failures: number;
53
+ skipped: boolean;
54
+ reason?: string;
55
+ claimed: number;
56
+ processed: number;
57
+ retried: number;
58
+ snoozed: number;
59
+ discarded: number;
60
+ released: number;
61
+ duplicateInRun: number;
62
+ leaseLost: number;
63
+ batches: number;
64
+ runMs: number;
65
+ byEventType: Record<string, Record<string, number>>;
66
+ discardedEventIds: string[];
67
+ queue?: Record<string, unknown>;
68
+ }
69
+ export interface OutboxDispatchConfig {
70
+ batchSize: number;
71
+ maxAttempts: number;
72
+ visibilitySeconds: number;
73
+ backoffBaseSeconds: number;
74
+ backoffCapSeconds: number;
75
+ snoozeSeconds: number;
76
+ maxSnoozes: number;
77
+ softBudgetMs: number;
78
+ }
79
+ /** @beta Logging defaults retain the dispatch console transcript. */
80
+ export interface OutboxLogger {
81
+ warn(...args: unknown[]): void;
82
+ error(...args: unknown[]): void;
83
+ }
84
+ /** @beta Synchronous bounded observations; no payloads or credentials. */
85
+ export interface OutboxObservation {
86
+ event: "claimed" | "finished";
87
+ count: number;
88
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,15 @@
1
+ /** @beta Caller executes this inside the same transaction as its domain write. */
2
+ export interface EnqueueEvent {
3
+ aggregateType: string;
4
+ aggregateId: string;
5
+ eventType: string;
6
+ idempotencyKey: string;
7
+ payload: Record<string, unknown>;
8
+ metadata?: Record<string, unknown>;
9
+ availableAt?: string;
10
+ }
11
+ /** @beta Duplicate enqueue keeps the durable event identity; no independent commit. */
12
+ export declare function buildOutboxEnqueue(event: EnqueueEvent): {
13
+ text: string;
14
+ values: readonly unknown[];
15
+ };
@@ -0,0 +1,9 @@
1
+ /** @beta Duplicate enqueue keeps the durable event identity; no independent commit. */
2
+ export function buildOutboxEnqueue(event) {
3
+ return {
4
+ text: `insert into public.outbox_events (aggregate_type, aggregate_id, event_type, idempotency_key, payload, metadata, available_at)
5
+ values ($1, $2::uuid, $3, $4, $5::jsonb, $6::jsonb, coalesce($7::timestamptz, now()))
6
+ on conflict (event_type, idempotency_key) do nothing returning id::text`,
7
+ values: [event.aggregateType, event.aggregateId, event.eventType, event.idempotencyKey, JSON.stringify(event.payload), JSON.stringify(event.metadata ?? {}), event.availableAt ?? null],
8
+ };
9
+ }