@krizaka/outbox 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,39 @@
1
- # Temporary Holding Version
1
+ # @krizaka/outbox
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The transactional outbox of every Krizaka product. An event is **written in the caller's transaction**, so it exists exactly when the work committed, and is **delivered after the commit, at least once**, by workers that lease a batch. No broker: PostgreSQL and `FOR UPDATE SKIP LOCKED` share the work between instances. It replaces Akinaza's `mail_outbox` (whose `flushOutbox` nobody called), Orochia's `reco_outbox` and analytics outbox and Yasakia's `analytics_outbox`; it is the TypeScript twin of `krizaka-messaging`'s `krizaka_outbox` (the envelope is `id`, `type`, `occurredAt`, `payload`).
4
+
5
+ > **The guarantee is *at least once*. Consumers must be idempotent on the message id.** A claim is exclusive while its lease is valid. A worker that delivers and then crashes before `complete` lets the lease expire, and the message is delivered **again**. The outbox never promises « exactly once ».
6
+
7
+ ```ts
8
+ import { emitMigration, transaction } from "@krizaka/db";
9
+ import { consumeOnce, createOutbox, outboxSchema, runWorker } from "@krizaka/outbox";
10
+ import { readOutboxSettings } from "@krizaka/outbox/settings";
11
+
12
+ emitMigration(outboxSchema, 1, { tables: {} }); // commit the SQL once, in your migrations: outbox.message and outbox.processed
13
+
14
+ const outbox = createOutbox({ clock: { now: () => new Date() }, settings: () => readOutboxSettings((key) => settings.get(key)) });
15
+
16
+ // 1. in the use case: the message commits or rolls back with the work
17
+ await transaction(connect, async (tx) => {
18
+ const redemption = await coupons.redeem(tx, { code, accountId });
19
+ await outbox.append(tx, { topic: "credits", type: "evt.coupon.redeemed.v1", payload: { redemptionId: redemption.id }, id: redemption.eventId });
20
+ });
21
+
22
+ // 2. a worker the product starts (Next.js instrumentation.ts); the package has no timer, you pass `sleep`
23
+ const stop = new AbortController();
24
+ void runWorker({
25
+ outbox, query: pool.query.bind(pool) /* a pool-level Query */, owner: `${hostname}:${process.pid}`, topic: "credits", signal: stop.signal,
26
+ sleep: (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000)),
27
+ deliver: async (message) => { /* throw to retry */ },
28
+ });
29
+
30
+ // 3. a consumer with an effect in the database applies it once per message id, in the effect's transaction
31
+ await transaction(connect, (tx) => consumeOnce(tx, "credits", message.id, clock.now(), () => credits.grant(tx, …)));
32
+ ```
33
+
34
+ - **`append(tx, { topic, type, payload, id?, availableAt? })`** takes the transaction's `Query` first. A given `id` makes the append idempotent (the same fact twice is one message). `type` is a routing key, `evt.<module>.<fact>.v1` like Java's.
35
+ - **`claim(query, { owner, topic? })`** is `UPDATE … WHERE id IN (SELECT … FOR UPDATE SKIP LOCKED)` and sets the lease. **`complete`** and **`fail(error)`** act only for the lease's owner (a worker that lost its lease cannot overwrite the new holder). `fail` backs off — `availableAt = now + backoffSeconds × 2^(attempts−1)`, capped — and after `maxAttempts` the message is **dead** (kept, with its last error; `retryDead` gives it another life). A message whose *last* allowed attempt's lease expired with no answer is dead too, not delivered a ninth time.
36
+ - **`runWorker`** loops `drainOnce` (claim a batch, deliver in order, record each outcome), sleeps through the `sleep` you pass when a round found nothing, and ends when the signal is aborted. Run `drainOnce` from a scheduler instead if you prefer cron to a loop.
37
+ - **Settings** (`@krizaka/outbox/settings`, needs `@krizaka/settings` and `zod`): `outbox.batchSize` (50, 1–500), `outbox.leaseSeconds` (60, 10–3600: longer than your slowest delivery), `outbox.maxAttempts` (8, 1–50), `outbox.backoffSeconds` (30, 1–3600), `outbox.backoffMaxSeconds` (3600), `outbox.retentionDays` (7). `purge` removes delivered and dead messages older than the retention: call it from the product's job.
38
+ - **Tables** (`outboxSchema`, Postgres schema `outbox`): `message` (id, topic, event_type, payload, created_at, available_at, attempts, leased_until, lease_owner, delivered_at, dead_at, last_error) and `processed` (consumer, message_id), which `consumeOnce` uses: the marker and the effect commit in the same transaction, so a crash leaves neither and a redelivery finds the marker.
39
+ - `outboxStoreContract` (from `@krizaka/outbox/testkit`) is the contract every store runs; `memoryOutboxStore()` is for unit tests.
@@ -0,0 +1,24 @@
1
+ // src/port.ts
2
+ var FAIL_STATE = { retry: "retry", dead: "dead", lost: "lost" };
3
+ var OUTBOX_CODE = {
4
+ badTopic: "OUTBOX_BAD_TOPIC",
5
+ badType: "OUTBOX_BAD_TYPE",
6
+ badId: "OUTBOX_BAD_ID",
7
+ badPayload: "OUTBOX_BAD_PAYLOAD",
8
+ badSettings: "OUTBOX_BAD_SETTINGS"
9
+ };
10
+ var OutboxError = class extends Error {
11
+ constructor(code, message) {
12
+ super(message);
13
+ this.code = code;
14
+ this.name = "OutboxError";
15
+ }
16
+ code;
17
+ };
18
+
19
+ export {
20
+ FAIL_STATE,
21
+ OUTBOX_CODE,
22
+ OutboxError
23
+ };
24
+ //# sourceMappingURL=chunk-7WIJNAGK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/port.ts"],"sourcesContent":["/**\n * The ports of « outbox »: a message written in the caller's transaction and delivered after the commit, AT LEAST ONCE. Generic:\n * no broker, no product import, no database client (a `Query` comes in), no wall clock (a `Clock` comes in).\n *\n * THE GUARANTEE. A claim is exclusive while its lease is valid. A worker that delivers and then crashes before `complete` lets the\n * lease expire, and the message is delivered AGAIN. So every consumer must be idempotent on the message id (see `consumeOnce`).\n * The outbox never promises « exactly once ».\n */\nexport type { Clock, Query } from \"@krizaka/db\";\n\n/** What a product appends. */\nexport interface NewMessage {\n /** Where it goes: a worker claims one topic (`mail`, `recommender`, `webhooks`). Lower-case letters, digits, `_ . : -`. */\n topic: string;\n /** What happened, as a routing key (`evt.credit.granted.v1`): the Java kit's form. Lower-case letters, digits, `_ . -`. */\n type: string;\n /** The event's data: JSON. Never a secret, and as little personal data as the consumer needs. */\n payload: unknown;\n /** A stable id (a UUID) when the same fact can be appended twice: the second append is a no-op. Default: a fresh UUID. */\n id?: string;\n /** Not before this instant (a scheduled delivery). Default: now. */\n availableAt?: Date;\n}\n\n/** The envelope a worker receives: the Java kit's `id`, `type`, `occurredAt`, `payload`, and where it is in its attempts. */\nexport interface OutboxMessage {\n id: string;\n topic: string;\n type: string;\n payload: unknown;\n occurredAt: Date;\n /** How many deliveries have been started for it, this one included. */\n attempts: number;\n}\n\n/** The knobs of the outbox, read from the admin's settings (`@krizaka/outbox/settings`). */\nexport interface OutboxSettings {\n /** Messages a worker claims at once. */\n batchSize: number;\n /** Seconds a claim holds a message before another worker may take it. Longer than the slowest delivery. */\n leaseSeconds: number;\n /** Deliveries started before a message is dead. */\n maxAttempts: number;\n /** Seconds before the second attempt; it doubles with each attempt. */\n backoffSeconds: number;\n /** The most seconds a retry waits. */\n backoffMaxSeconds: number;\n /** Days a delivered or dead message is kept before `purge`. */\n retentionDays: number;\n}\n\n/** What `claim` takes. */\nexport interface ClaimOptions {\n /** Only this topic; default every topic. */\n topic?: string;\n /** Who claims: a worker's id, so that only the holder of a lease can complete or fail the message. */\n owner: string;\n}\n\n/** What became of a failed delivery. */\nexport const FAIL_STATE = { retry: \"retry\", dead: \"dead\", lost: \"lost\" } as const;\n\n/** The result of `fail`: the message will be retried, is dead, or was not this worker's any more. */\nexport type FailOutcome = { state: typeof FAIL_STATE.retry; availableAt: Date } | { state: typeof FAIL_STATE.dead } | { state: typeof FAIL_STATE.lost };\n\nexport interface OutboxStats {\n /** Waiting for a worker (including retries). */\n pending: number;\n /** Held by a worker right now. */\n leased: number;\n delivered: number;\n dead: number;\n}\n\n/** Where the messages live. Every adapter runs `outboxStoreContract` (`@krizaka/outbox/testkit`). Times come from the caller. */\nexport interface OutboxStore {\n /** Writes the message. A second append of the same id writes nothing and answers `false`. */\n append(message: { id: string; topic: string; type: string; payload: unknown; createdAt: Date; availableAt: Date }): Promise<boolean>;\n /** First marks dead the messages whose last attempt's lease expired with no answer, then leases up to `limit` due messages. */\n claim(options: ClaimOptions & { limit: number; leaseSeconds: number; maxAttempts: number; now: Date }): Promise<OutboxMessage[]>;\n /** Marks it delivered, when `owner` still holds it. `false` when the lease was lost: the other worker delivers. */\n complete(id: string, owner: string, now: Date): Promise<boolean>;\n /** Records the failure: back off, or dead after `maxAttempts`. */\n fail(id: string, owner: string, error: string, options: { now: Date; maxAttempts: number; backoffSeconds: number; backoffMaxSeconds: number }): Promise<FailOutcome>;\n /** Gives a dead message another life: no attempts, due now. `false` when it is not dead. */\n retryDead(id: string, now: Date): Promise<boolean>;\n /** Removes the delivered and dead messages older than `before`. Returns how many. */\n purgeBefore(before: Date): Promise<number>;\n stats(now: Date): Promise<OutboxStats>;\n}\n\nexport const OUTBOX_CODE = {\n badTopic: \"OUTBOX_BAD_TOPIC\",\n badType: \"OUTBOX_BAD_TYPE\",\n badId: \"OUTBOX_BAD_ID\",\n badPayload: \"OUTBOX_BAD_PAYLOAD\",\n badSettings: \"OUTBOX_BAD_SETTINGS\",\n} as const;\nexport type OutboxCode = (typeof OUTBOX_CODE)[keyof typeof OUTBOX_CODE];\n\nexport class OutboxError extends Error {\n constructor(\n readonly code: OutboxCode,\n message: string,\n ) {\n super(message);\n this.name = \"OutboxError\";\n }\n}\n"],"mappings":";AA4DO,IAAM,aAAa,EAAE,OAAO,SAAS,MAAM,QAAQ,MAAM,OAAO;AA+BhE,IAAM,cAAc;AAAA,EACzB,UAAU;AAAA,EACV,SAAS;AAAA,EACT,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,aAAa;AACf;AAGO,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YACW,MACT,SACA;AACA,UAAM,OAAO;AAHJ;AAIT,SAAK,OAAO;AAAA,EACd;AAAA,EALW;AAMb;","names":[]}
@@ -0,0 +1,44 @@
1
+ import {
2
+ OUTBOX_CODE,
3
+ OutboxError
4
+ } from "./chunk-7WIJNAGK.js";
5
+
6
+ // src/rules.ts
7
+ var OUTBOX_DEFAULTS = { batchSize: 50, leaseSeconds: 60, maxAttempts: 8, backoffSeconds: 30, backoffMaxSeconds: 3600, retentionDays: 7 };
8
+ var OUTBOX_BOUNDS = {
9
+ batchSize: [1, 500],
10
+ leaseSeconds: [10, 3600],
11
+ maxAttempts: [1, 50],
12
+ backoffSeconds: [1, 3600],
13
+ backoffMaxSeconds: [1, 86400],
14
+ retentionDays: [1, 365]
15
+ };
16
+ var TOPIC = /^[a-z][a-z0-9_.:-]{0,59}$/;
17
+ var TYPE = /^[a-z][a-z0-9_.-]{0,99}$/;
18
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
19
+ function checkMessage(input) {
20
+ if (!TOPIC.test(input.topic)) throw new OutboxError(OUTBOX_CODE.badTopic, `topic \xAB ${input.topic} \xBB: lower-case letters, digits and _ . : -, starting with a letter, at most 60 characters`);
21
+ if (!TYPE.test(input.type)) throw new OutboxError(OUTBOX_CODE.badType, `type \xAB ${input.type} \xBB: lower-case letters, digits and _ . -, starting with a letter, at most 100 characters (evt.credit.granted.v1)`);
22
+ if (input.id !== void 0 && !UUID.test(input.id)) throw new OutboxError(OUTBOX_CODE.badId, `id \xAB ${input.id} \xBB is not a UUID`);
23
+ if (input.payload === void 0 || JSON.stringify(input.payload) === void 0) throw new OutboxError(OUTBOX_CODE.badPayload, "the payload must be JSON-serialisable (and not undefined)");
24
+ }
25
+ function checkSettings(settings) {
26
+ for (const key of Object.keys(OUTBOX_BOUNDS)) {
27
+ const [min, max] = OUTBOX_BOUNDS[key];
28
+ const value = settings[key];
29
+ if (!Number.isInteger(value) || value < min || value > max) throw new OutboxError(OUTBOX_CODE.badSettings, `outbox.${key} must be a whole number from ${min} to ${max}, got ${value}`);
30
+ }
31
+ return settings;
32
+ }
33
+ function backoffSeconds(attempts, settings) {
34
+ return Math.min(settings.backoffMaxSeconds, settings.backoffSeconds * 2 ** Math.max(0, attempts - 1));
35
+ }
36
+
37
+ export {
38
+ OUTBOX_DEFAULTS,
39
+ OUTBOX_BOUNDS,
40
+ checkMessage,
41
+ checkSettings,
42
+ backoffSeconds
43
+ };
44
+ //# sourceMappingURL=chunk-AD76AB44.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/rules.ts"],"sourcesContent":["import { OUTBOX_CODE, OutboxError, type OutboxSettings } from \"./port\";\n\n/**\n * The defaults of the settings, and their bounds. The settings fragment (`@krizaka/outbox/settings`) is built from these, so the\n * admin sees the same numbers the code falls back to.\n */\n// @fixed: the defaults and bounds of the admin's knobs; the admin chooses within them\nexport const OUTBOX_DEFAULTS: OutboxSettings = { batchSize: 50, leaseSeconds: 60, maxAttempts: 8, backoffSeconds: 30, backoffMaxSeconds: 3600, retentionDays: 7 };\n\n/** The bounds of each setting: [min, max]. */\n// @fixed: what an admin may set\nexport const OUTBOX_BOUNDS: Readonly<Record<keyof OutboxSettings, readonly [number, number]>> = {\n batchSize: [1, 500],\n leaseSeconds: [10, 3600],\n maxAttempts: [1, 50],\n backoffSeconds: [1, 3600],\n backoffMaxSeconds: [1, 86_400],\n retentionDays: [1, 365],\n};\n\nconst TOPIC = /^[a-z][a-z0-9_.:-]{0,59}$/;\nconst TYPE = /^[a-z][a-z0-9_.-]{0,99}$/;\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** @throws OutboxError for a topic, a type or an id that is not well formed, or a payload that is not JSON */\nexport function checkMessage(input: { topic: string; type: string; id?: string; payload: unknown }): void {\n if (!TOPIC.test(input.topic)) throw new OutboxError(OUTBOX_CODE.badTopic, `topic « ${input.topic} »: lower-case letters, digits and _ . : -, starting with a letter, at most 60 characters`);\n if (!TYPE.test(input.type)) throw new OutboxError(OUTBOX_CODE.badType, `type « ${input.type} »: lower-case letters, digits and _ . -, starting with a letter, at most 100 characters (evt.credit.granted.v1)`);\n if (input.id !== undefined && !UUID.test(input.id)) throw new OutboxError(OUTBOX_CODE.badId, `id « ${input.id} » is not a UUID`);\n if (input.payload === undefined || JSON.stringify(input.payload) === undefined) throw new OutboxError(OUTBOX_CODE.badPayload, \"the payload must be JSON-serialisable (and not undefined)\");\n}\n\n/** @throws OutboxError when a setting is not a whole number within its bounds */\nexport function checkSettings(settings: OutboxSettings): OutboxSettings {\n for (const key of Object.keys(OUTBOX_BOUNDS) as (keyof OutboxSettings)[]) {\n const [min, max] = OUTBOX_BOUNDS[key];\n const value = settings[key];\n if (!Number.isInteger(value) || value < min || value > max) throw new OutboxError(OUTBOX_CODE.badSettings, `outbox.${key} must be a whole number from ${min} to ${max}, got ${value}`);\n }\n return settings;\n}\n\n/**\n * The seconds a message waits after its `attempts`-th delivery failed: the base for the first, doubling with each, capped.\n * @param attempts deliveries started so far (1 for the first failure)\n */\nexport function backoffSeconds(attempts: number, settings: Pick<OutboxSettings, \"backoffSeconds\" | \"backoffMaxSeconds\">): number {\n return Math.min(settings.backoffMaxSeconds, settings.backoffSeconds * 2 ** Math.max(0, attempts - 1));\n}\n"],"mappings":";;;;;;AAOO,IAAM,kBAAkC,EAAE,WAAW,IAAI,cAAc,IAAI,aAAa,GAAG,gBAAgB,IAAI,mBAAmB,MAAM,eAAe,EAAE;AAIzJ,IAAM,gBAAmF;AAAA,EAC9F,WAAW,CAAC,GAAG,GAAG;AAAA,EAClB,cAAc,CAAC,IAAI,IAAI;AAAA,EACvB,aAAa,CAAC,GAAG,EAAE;AAAA,EACnB,gBAAgB,CAAC,GAAG,IAAI;AAAA,EACxB,mBAAmB,CAAC,GAAG,KAAM;AAAA,EAC7B,eAAe,CAAC,GAAG,GAAG;AACxB;AAEA,IAAM,QAAQ;AACd,IAAM,OAAO;AACb,IAAM,OAAO;AAGN,SAAS,aAAa,OAA6E;AACxG,MAAI,CAAC,MAAM,KAAK,MAAM,KAAK,EAAG,OAAM,IAAI,YAAY,YAAY,UAAU,cAAW,MAAM,KAAK,8FAA2F;AAC3L,MAAI,CAAC,KAAK,KAAK,MAAM,IAAI,EAAG,OAAM,IAAI,YAAY,YAAY,SAAS,aAAU,MAAM,IAAI,qHAAkH;AAC7M,MAAI,MAAM,OAAO,UAAa,CAAC,KAAK,KAAK,MAAM,EAAE,EAAG,OAAM,IAAI,YAAY,YAAY,OAAO,WAAQ,MAAM,EAAE,qBAAkB;AAC/H,MAAI,MAAM,YAAY,UAAa,KAAK,UAAU,MAAM,OAAO,MAAM,OAAW,OAAM,IAAI,YAAY,YAAY,YAAY,2DAA2D;AAC3L;AAGO,SAAS,cAAc,UAA0C;AACtE,aAAW,OAAO,OAAO,KAAK,aAAa,GAA+B;AACxE,UAAM,CAAC,KAAK,GAAG,IAAI,cAAc,GAAG;AACpC,UAAM,QAAQ,SAAS,GAAG;AAC1B,QAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,OAAO,QAAQ,IAAK,OAAM,IAAI,YAAY,YAAY,aAAa,UAAU,GAAG,gCAAgC,GAAG,OAAO,GAAG,SAAS,KAAK,EAAE;AAAA,EACvL;AACA,SAAO;AACT;AAMO,SAAS,eAAe,UAAkB,UAAgF;AAC/H,SAAO,KAAK,IAAI,SAAS,mBAAmB,SAAS,iBAAiB,KAAK,KAAK,IAAI,GAAG,WAAW,CAAC,CAAC;AACtG;","names":[]}
@@ -0,0 +1,164 @@
1
+ import * as _krizaka_db from '@krizaka/db';
2
+ import { Query, Clock } from '@krizaka/db';
3
+ export { Clock, Query } from '@krizaka/db';
4
+ import { O as OutboxStore, N as NewMessage, C as ClaimOptions, a as OutboxMessage, F as FailOutcome, b as OutboxStats, c as OutboxSettings } from './port-CXch5iMa.js';
5
+ export { d as FAIL_STATE, e as OUTBOX_CODE, f as OutboxCode, g as OutboxError } from './port-CXch5iMa.js';
6
+
7
+ /**
8
+ * The idempotent consumer: the outbox delivers AT LEAST ONCE, so a consumer that has an effect in the database applies it once per
9
+ * message id. Run it inside the transaction of the effect: the marker and the effect commit together, so a crash between them
10
+ * leaves neither and the redelivery applies both; a redelivery after the commit finds the marker and does nothing.
11
+ *
12
+ * ```ts
13
+ * await db.transaction(async (tx) => {
14
+ * const result = await consumeOnce(tx, "credits", message.id, clock.now(), () => credits.grant(tx, …));
15
+ * });
16
+ * ```
17
+ * @param tx the transaction the effect writes through
18
+ * @param consumer who applies it (`credits`, `mail`): a message may be consumed once by each consumer
19
+ * @param messageId the outbox message's id
20
+ * @param effect what to do the first time; its failure rolls the marker back with the transaction
21
+ * @param schema the Postgres schema of the module, default `outbox`
22
+ * @returns `applied` the first time, `duplicate` after
23
+ */
24
+ declare function consumeOnce(tx: Query, consumer: string, messageId: string, now: Date, effect: () => Promise<void>, schema?: string): Promise<"applied" | "duplicate">;
25
+
26
+ interface Row {
27
+ id: string;
28
+ topic: string;
29
+ type: string;
30
+ payload: unknown;
31
+ createdAt: Date;
32
+ availableAt: Date;
33
+ attempts: number;
34
+ leasedUntil: Date | null;
35
+ leaseOwner: string | null;
36
+ deliveredAt: Date | null;
37
+ deadAt: Date | null;
38
+ lastError: string | null;
39
+ }
40
+ /** An in-memory outbox store, for unit tests and demos (the same behaviour as the database's: the contract kit runs on both). */
41
+ declare function memoryOutboxStore(): OutboxStore & {
42
+ rows(): readonly Readonly<Row>[];
43
+ };
44
+
45
+ interface OutboxDeps {
46
+ clock: Clock;
47
+ /** The settings, read at each call so the admin's change applies at once: an object, or a function over the settings service. */
48
+ settings: OutboxSettings | (() => OutboxSettings | Promise<OutboxSettings>);
49
+ /** The store over a query (a pool or a transaction). Default: the PostgreSQL store on schema `outbox`. */
50
+ storeFor?: (query: Query) => OutboxStore;
51
+ /** The Postgres schema, when the product renamed the module's (used by the default store). */
52
+ schema?: string;
53
+ }
54
+ /** The outbox as a product uses it. Every function takes the `Query` it works through: pass `tx` to join a unit of work. */
55
+ interface Outbox {
56
+ /** Appends a message INSIDE the caller's transaction: it commits or rolls back with it. Answers its id, and `false` when that id was already appended. */
57
+ append(tx: Query, message: NewMessage): Promise<{
58
+ id: string;
59
+ appended: boolean;
60
+ }>;
61
+ /** Leases a batch of due messages to `owner`. Exclusive while each lease is valid. */
62
+ claim(query: Query, options: ClaimOptions & {
63
+ limit?: number;
64
+ leaseSeconds?: number;
65
+ }): Promise<OutboxMessage[]>;
66
+ /** The delivery succeeded. `false` when the lease was lost to another worker. */
67
+ complete(query: Query, id: string, owner: string): Promise<boolean>;
68
+ /** The delivery failed: back off (doubling, capped), or dead after `maxAttempts`. */
69
+ fail(query: Query, id: string, owner: string, error: unknown): Promise<FailOutcome>;
70
+ /** A dead message gets another life, due now. */
71
+ retryDead(query: Query, id: string): Promise<boolean>;
72
+ /** Removes delivered and dead messages older than the retention. Returns how many. */
73
+ purge(query: Query): Promise<number>;
74
+ stats(query: Query): Promise<OutboxStats>;
75
+ }
76
+ /**
77
+ * The outbox of a product.
78
+ * @param deps the clock, the settings, and optionally the store and schema
79
+ * @returns the outbox's functions
80
+ */
81
+ declare function createOutbox(deps: OutboxDeps): Outbox;
82
+
83
+ /**
84
+ * The PostgreSQL store of the outbox, in `outbox.message` (see `outboxSchema`), over the `Query` it is given: the caller's
85
+ * transaction for `append` (so the message commits or rolls back with the work), a pool for the worker's calls.
86
+ *
87
+ * `claim` is `UPDATE … WHERE id IN (SELECT … FOR UPDATE SKIP LOCKED)`: two workers never lease the same message while a lease is
88
+ * valid. `complete` and `fail` only act for the lease's owner, so a worker that lost its lease cannot overwrite the new holder's outcome.
89
+ * Times come from the caller (the injected clock), never from the database's `now()`.
90
+ * @param schema the Postgres schema of the module, default `outbox`
91
+ */
92
+ declare function dbOutboxStore(query: Query, schema?: string): OutboxStore;
93
+
94
+ /**
95
+ * The defaults of the settings, and their bounds. The settings fragment (`@krizaka/outbox/settings`) is built from these, so the
96
+ * admin sees the same numbers the code falls back to.
97
+ */
98
+ declare const OUTBOX_DEFAULTS: OutboxSettings;
99
+ /** The bounds of each setting: [min, max]. */
100
+ declare const OUTBOX_BOUNDS: Readonly<Record<keyof OutboxSettings, readonly [number, number]>>;
101
+ /** @throws OutboxError for a topic, a type or an id that is not well formed, or a payload that is not JSON */
102
+ declare function checkMessage(input: {
103
+ topic: string;
104
+ type: string;
105
+ id?: string;
106
+ payload: unknown;
107
+ }): void;
108
+ /** @throws OutboxError when a setting is not a whole number within its bounds */
109
+ declare function checkSettings(settings: OutboxSettings): OutboxSettings;
110
+ /**
111
+ * The seconds a message waits after its `attempts`-th delivery failed: the base for the first, doubling with each, capped.
112
+ * @param attempts deliveries started so far (1 for the first failure)
113
+ */
114
+ declare function backoffSeconds(attempts: number, settings: Pick<OutboxSettings, "backoffSeconds" | "backoffMaxSeconds">): number;
115
+
116
+ /**
117
+ * The tables of « outbox », in their own Postgres schema (ADR-001 §3). `message` is the outbox itself, the columns of the Java kit's
118
+ * envelope (id, type, occurredAt = created_at, payload) and the state of its delivery; `processed` is the idempotent consumers'
119
+ * record of the message ids they already applied. They reference no product table. Version 1 is frozen once released: a change is version 2.
120
+ */
121
+ declare const outboxSchema: _krizaka_db.ModuleSchema;
122
+
123
+ interface DrainSummary {
124
+ claimed: number;
125
+ delivered: number;
126
+ retried: number;
127
+ dead: number;
128
+ /** Deliveries whose outcome could not be recorded because the lease had been lost to another worker. */
129
+ lost: number;
130
+ }
131
+ interface DrainOptions {
132
+ outbox: Outbox;
133
+ /** A pool-level query: each call is its own statement, never one long transaction, so a lease is all that holds a message. */
134
+ query: Query;
135
+ /** Who this worker is (a hostname and a process id): only the holder of a lease can complete or fail its message. */
136
+ owner: string;
137
+ /** Delivers one message: resolve on success, throw on failure. It must be idempotent on `message.id` (at-least-once). */
138
+ deliver: (message: OutboxMessage) => Promise<void>;
139
+ /** Only this topic; default every topic. */
140
+ topic?: string;
141
+ }
142
+ /**
143
+ * One round: leases a batch, delivers each message in order, records each outcome. Safe to run from several instances at once.
144
+ * A delivery that throws is retried later (or is dead after `maxAttempts`); the round goes on with the next message.
145
+ * @returns what happened
146
+ */
147
+ declare function drainOnce(options: DrainOptions): Promise<DrainSummary>;
148
+ interface WorkerOptions extends DrainOptions {
149
+ /** Waits this many seconds (a timer: the package has none of its own). */
150
+ sleep: (seconds: number) => Promise<void>;
151
+ /** The worker stops when this signal is aborted (checked between rounds). */
152
+ signal?: AbortSignal;
153
+ /** Seconds to wait when a round found nothing. Default 5. */
154
+ idleSeconds?: number;
155
+ /** Told of a round that threw (the store was unreachable): the loop waits and goes on. */
156
+ onError?: (error: unknown) => void;
157
+ }
158
+ /**
159
+ * The loop a product starts (Next.js `instrumentation.ts`, a worker process): drain, and sleep when there was nothing. It has no
160
+ * timer of its own — the product passes `sleep` — and it ends when the signal is aborted.
161
+ */
162
+ declare function runWorker(options: WorkerOptions): Promise<void>;
163
+
164
+ export { ClaimOptions, type DrainOptions, type DrainSummary, FailOutcome, NewMessage, OUTBOX_BOUNDS, OUTBOX_DEFAULTS, type Outbox, type OutboxDeps, OutboxMessage, OutboxSettings, OutboxStats, OutboxStore, type WorkerOptions, backoffSeconds, checkMessage, checkSettings, consumeOnce, createOutbox, dbOutboxStore, drainOnce, memoryOutboxStore, outboxSchema, runWorker };