@entifix/transactions 0.1.0-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.
Files changed (86) hide show
  1. package/LICENSE +21 -0
  2. package/dist/contracts/command.d.ts +59 -0
  3. package/dist/contracts/command.d.ts.map +1 -0
  4. package/dist/contracts/command.js +42 -0
  5. package/dist/contracts/command.js.map +1 -0
  6. package/dist/contracts/event.d.ts +84 -0
  7. package/dist/contracts/event.d.ts.map +1 -0
  8. package/dist/contracts/event.js +67 -0
  9. package/dist/contracts/event.js.map +1 -0
  10. package/dist/contracts/inbox.d.ts +80 -0
  11. package/dist/contracts/inbox.d.ts.map +1 -0
  12. package/dist/contracts/inbox.js +5 -0
  13. package/dist/contracts/inbox.js.map +1 -0
  14. package/dist/contracts/outbox.d.ts +137 -0
  15. package/dist/contracts/outbox.d.ts.map +1 -0
  16. package/dist/contracts/outbox.js +5 -0
  17. package/dist/contracts/outbox.js.map +1 -0
  18. package/dist/contracts/record.d.ts +108 -0
  19. package/dist/contracts/record.d.ts.map +1 -0
  20. package/dist/contracts/record.js +27 -0
  21. package/dist/contracts/record.js.map +1 -0
  22. package/dist/contracts/saga-definition.d.ts +186 -0
  23. package/dist/contracts/saga-definition.d.ts.map +1 -0
  24. package/dist/contracts/saga-definition.js +95 -0
  25. package/dist/contracts/saga-definition.js.map +1 -0
  26. package/dist/engine/resolve-template.d.ts +49 -0
  27. package/dist/engine/resolve-template.d.ts.map +1 -0
  28. package/dist/engine/resolve-template.js +106 -0
  29. package/dist/engine/resolve-template.js.map +1 -0
  30. package/dist/engine/run-saga.d.ts +55 -0
  31. package/dist/engine/run-saga.d.ts.map +1 -0
  32. package/dist/engine/run-saga.js +467 -0
  33. package/dist/engine/run-saga.js.map +1 -0
  34. package/dist/engine/run-transaction.d.ts +55 -0
  35. package/dist/engine/run-transaction.d.ts.map +1 -0
  36. package/dist/engine/run-transaction.js +101 -0
  37. package/dist/engine/run-transaction.js.map +1 -0
  38. package/dist/index.d.ts +21 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +22 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/mixins/transaction-mixins.d.ts +20 -0
  43. package/dist/mixins/transaction-mixins.d.ts.map +1 -0
  44. package/dist/mixins/transaction-mixins.js +13 -0
  45. package/dist/mixins/transaction-mixins.js.map +1 -0
  46. package/dist/ports/event-bus.d.ts +98 -0
  47. package/dist/ports/event-bus.d.ts.map +1 -0
  48. package/dist/ports/event-bus.js +5 -0
  49. package/dist/ports/event-bus.js.map +1 -0
  50. package/dist/ports/event-source.d.ts +22 -0
  51. package/dist/ports/event-source.d.ts.map +1 -0
  52. package/dist/ports/event-source.js +20 -0
  53. package/dist/ports/event-source.js.map +1 -0
  54. package/dist/ports/lock-service.d.ts +24 -0
  55. package/dist/ports/lock-service.d.ts.map +1 -0
  56. package/dist/ports/lock-service.js +5 -0
  57. package/dist/ports/lock-service.js.map +1 -0
  58. package/dist/ports/saga-dispatcher.d.ts +47 -0
  59. package/dist/ports/saga-dispatcher.d.ts.map +1 -0
  60. package/dist/ports/saga-dispatcher.js +5 -0
  61. package/dist/ports/saga-dispatcher.js.map +1 -0
  62. package/dist/ports/saga-store.d.ts +98 -0
  63. package/dist/ports/saga-store.d.ts.map +1 -0
  64. package/dist/ports/saga-store.js +20 -0
  65. package/dist/ports/saga-store.js.map +1 -0
  66. package/dist/ports/sequence-service.d.ts +17 -0
  67. package/dist/ports/sequence-service.d.ts.map +1 -0
  68. package/dist/ports/sequence-service.js +5 -0
  69. package/dist/ports/sequence-service.js.map +1 -0
  70. package/dist/ports/transaction-handler.d.ts +68 -0
  71. package/dist/ports/transaction-handler.d.ts.map +1 -0
  72. package/dist/ports/transaction-handler.js +5 -0
  73. package/dist/ports/transaction-handler.js.map +1 -0
  74. package/dist/ports/transaction-sink.d.ts +119 -0
  75. package/dist/ports/transaction-sink.d.ts.map +1 -0
  76. package/dist/ports/transaction-sink.js +28 -0
  77. package/dist/ports/transaction-sink.js.map +1 -0
  78. package/dist/stream/transaction-stream-hub.d.ts +41 -0
  79. package/dist/stream/transaction-stream-hub.d.ts.map +1 -0
  80. package/dist/stream/transaction-stream-hub.js +53 -0
  81. package/dist/stream/transaction-stream-hub.js.map +1 -0
  82. package/dist/use-case/facade.uc.d.ts +22 -0
  83. package/dist/use-case/facade.uc.d.ts.map +1 -0
  84. package/dist/use-case/facade.uc.js +55 -0
  85. package/dist/use-case/facade.uc.js.map +1 -0
  86. package/package.json +65 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 r10c Technologies
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,59 @@
1
+ import { EntifixBuildError, type EntifixEnvelope, type SerializedEntity } from '@entifix/core';
2
+ import { Effect } from 'effect';
3
+ /**
4
+ * A write intent in CQRS terms. A client no longer mutates directly — it issues
5
+ * a command, the service runs the transaction facade over it, and answers with a
6
+ * transaction id. `payload` is a serialized entity (the same wire shape the
7
+ * entity envelopes carry), so a command round-trips through the existing
8
+ * (de)serializer.
9
+ */
10
+ export interface TransactionCommand<TPayload = SerializedEntity> {
11
+ /**
12
+ * Correlates every event and record for this run, and **the client mints it**
13
+ * (ADR 0028).
14
+ *
15
+ * It is also the stored entity's id and the idempotency key: re-sending a
16
+ * command with the same id returns the first one's answer instead of writing
17
+ * twice. That makes it untrusted input which becomes a primary key, so
18
+ * {@link readCommandEnvelope} constrains it to a UUID rather than accepting
19
+ * any string.
20
+ */
21
+ transactionId: string;
22
+ /** What to do — only `create` in phase 1. */
23
+ type: 'create';
24
+ /** The target entity's `key` (e.g. `product`), the routing/lock subject. */
25
+ entity: string;
26
+ /** The serialized entity to act on. */
27
+ payload: TPayload;
28
+ /**
29
+ * Whose organization this command acts in — **stamped by the route from the
30
+ * verified token, never read from the wire**.
31
+ *
32
+ * {@link readCommandEnvelope} drops whatever a caller sent under this name, so
33
+ * a client cannot name another tenant by writing one into the body. It is the
34
+ * same rule the id already follows (`entity.id = params.id`), and the same
35
+ * rule `requireOrganization` states: the organization comes from the token and
36
+ * nowhere else.
37
+ *
38
+ * Optional because the parser produces a command without it and the route
39
+ * fills it in a moment later. A command that reaches the engine still carrying
40
+ * `undefined` emits events that no tenant-scoped stream connection receives —
41
+ * which is the intended direction to fail (ADR 0036).
42
+ */
43
+ organizationId?: string;
44
+ }
45
+ export type CommandEnvelope<TPayload = SerializedEntity> = EntifixEnvelope<TransactionCommand<TPayload>>;
46
+ /** Frames a command as a transport-free `command` envelope. */
47
+ export declare function makeCommandEnvelope<TPayload = SerializedEntity>(command: TransactionCommand<TPayload>): CommandEnvelope<TPayload>;
48
+ /** Whether a value is a usable transaction id. */
49
+ export declare const isTransactionId: (value: unknown) => value is string;
50
+ /**
51
+ * Parses a `command` envelope, failing on a wrong shape/type.
52
+ *
53
+ * A command carrying no valid transaction id is rejected outright — there is no
54
+ * server-side fallback that mints one. That is deliberate: the id is the
55
+ * idempotency key, and a caller who omits it silently loses retry safety while
56
+ * appearing to succeed.
57
+ */
58
+ export declare function readCommandEnvelope<TPayload = SerializedEntity>(body: unknown): Effect.Effect<TransactionCommand<TPayload>, EntifixBuildError>;
59
+ //# sourceMappingURL=command.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command.d.ts","sourceRoot":"","sources":["../../src/contracts/command.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,KAAK,eAAe,EAGpB,KAAK,gBAAgB,EACtB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC;;;;;;GAMG;AACH,MAAM,WAAW,kBAAkB,CAAC,QAAQ,GAAG,gBAAgB;IAC7D;;;;;;;;;OASG;IACH,aAAa,EAAE,MAAM,CAAC;IACtB,6CAA6C;IAC7C,IAAI,EAAE,QAAQ,CAAC;IACf,4EAA4E;IAC5E,MAAM,EAAE,MAAM,CAAC;IACf,uCAAuC;IACvC,OAAO,EAAE,QAAQ,CAAC;IAClB;;;;;;;;;;;;;;OAcG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,MAAM,eAAe,CAAC,QAAQ,GAAG,gBAAgB,IAAI,eAAe,CACxE,kBAAkB,CAAC,QAAQ,CAAC,CAC7B,CAAC;AAEF,+DAA+D;AAC/D,wBAAgB,mBAAmB,CAAC,QAAQ,GAAG,gBAAgB,EAC7D,OAAO,EAAE,kBAAkB,CAAC,QAAQ,CAAC,GACpC,eAAe,CAAC,QAAQ,CAAC,CAE3B;AAaD,kDAAkD;AAClD,eAAO,MAAM,eAAe,GAAI,OAAO,OAAO,KAAG,KAAK,IAAI,MACX,CAAC;AAEhD;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,GAAG,gBAAgB,EAC7D,IAAI,EAAE,OAAO,GACZ,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,QAAQ,CAAC,EAAE,iBAAiB,CAAC,CA6BhE"}
@@ -0,0 +1,42 @@
1
+ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
2
+ import { EntifixBuildError, makeEnvelope, readEnvelope } from '@entifix/core';
3
+ import { Effect } from 'effect';
4
+ /** Frames a command as a transport-free `command` envelope. */ export function makeCommandEnvelope(command) {
5
+ return makeEnvelope('command', command.entity, command);
6
+ }
7
+ /**
8
+ * A canonical RFC 9562 UUID — any version, standard variant.
9
+ *
10
+ * The transaction id arrives from the client and becomes a primary key, so the
11
+ * key space it may address has to be fixed rather than "whatever string was
12
+ * sent". Accepting every version keeps v4 (random) and v7 (time-ordered) both
13
+ * usable without the wire format becoming a second decision.
14
+ */ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
15
+ /** Whether a value is a usable transaction id. */ export const isTransactionId = (value)=>typeof value === 'string' && UUID.test(value);
16
+ /**
17
+ * Parses a `command` envelope, failing on a wrong shape/type.
18
+ *
19
+ * A command carrying no valid transaction id is rejected outright — there is no
20
+ * server-side fallback that mints one. That is deliberate: the id is the
21
+ * idempotency key, and a caller who omits it silently loses retry safety while
22
+ * appearing to succeed.
23
+ */ export function readCommandEnvelope(body) {
24
+ return Effect.gen(function*() {
25
+ const envelope = yield* readEnvelope(body, 'command', 'command');
26
+ const command = envelope.data;
27
+ if (command == null || !isTransactionId(command.transactionId) || typeof command.entity !== 'string') {
28
+ return yield* Effect.fail(new EntifixBuildError('command envelope carried no valid command', undefined, {
29
+ body
30
+ }));
31
+ }
32
+ // `organizationId` is deliberately **not** carried over from the parsed
33
+ // body. Spreading the caller's object here would let a request name another
34
+ // tenant, which is precisely the scoping the stream depends on.
35
+ const { organizationId: _ignored } = command, trusted = _object_without_properties_loose(command, [
36
+ "organizationId"
37
+ ]);
38
+ return trusted;
39
+ });
40
+ }
41
+
42
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/contracts/command.ts"],"sourcesContent":["import {\n EntifixBuildError,\n type EntifixEnvelope,\n makeEnvelope,\n readEnvelope,\n type SerializedEntity,\n} from '@entifix/core';\nimport { Effect } from 'effect';\n\n/**\n * A write intent in CQRS terms. A client no longer mutates directly — it issues\n * a command, the service runs the transaction facade over it, and answers with a\n * transaction id. `payload` is a serialized entity (the same wire shape the\n * entity envelopes carry), so a command round-trips through the existing\n * (de)serializer.\n */\nexport interface TransactionCommand<TPayload = SerializedEntity> {\n /**\n * Correlates every event and record for this run, and **the client mints it**\n * (ADR 0028).\n *\n * It is also the stored entity's id and the idempotency key: re-sending a\n * command with the same id returns the first one's answer instead of writing\n * twice. That makes it untrusted input which becomes a primary key, so\n * {@link readCommandEnvelope} constrains it to a UUID rather than accepting\n * any string.\n */\n transactionId: string;\n /** What to do — only `create` in phase 1. */\n type: 'create';\n /** The target entity's `key` (e.g. `product`), the routing/lock subject. */\n entity: string;\n /** The serialized entity to act on. */\n payload: TPayload;\n /**\n * Whose organization this command acts in — **stamped by the route from the\n * verified token, never read from the wire**.\n *\n * {@link readCommandEnvelope} drops whatever a caller sent under this name, so\n * a client cannot name another tenant by writing one into the body. It is the\n * same rule the id already follows (`entity.id = params.id`), and the same\n * rule `requireOrganization` states: the organization comes from the token and\n * nowhere else.\n *\n * Optional because the parser produces a command without it and the route\n * fills it in a moment later. A command that reaches the engine still carrying\n * `undefined` emits events that no tenant-scoped stream connection receives —\n * which is the intended direction to fail (ADR 0036).\n */\n organizationId?: string;\n}\n\nexport type CommandEnvelope<TPayload = SerializedEntity> = EntifixEnvelope<\n TransactionCommand<TPayload>\n>;\n\n/** Frames a command as a transport-free `command` envelope. */\nexport function makeCommandEnvelope<TPayload = SerializedEntity>(\n command: TransactionCommand<TPayload>,\n): CommandEnvelope<TPayload> {\n return makeEnvelope('command', command.entity, command);\n}\n\n/**\n * A canonical RFC 9562 UUID — any version, standard variant.\n *\n * The transaction id arrives from the client and becomes a primary key, so the\n * key space it may address has to be fixed rather than \"whatever string was\n * sent\". Accepting every version keeps v4 (random) and v7 (time-ordered) both\n * usable without the wire format becoming a second decision.\n */\nconst UUID =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n/** Whether a value is a usable transaction id. */\nexport const isTransactionId = (value: unknown): value is string =>\n typeof value === 'string' && UUID.test(value);\n\n/**\n * Parses a `command` envelope, failing on a wrong shape/type.\n *\n * A command carrying no valid transaction id is rejected outright — there is no\n * server-side fallback that mints one. That is deliberate: the id is the\n * idempotency key, and a caller who omits it silently loses retry safety while\n * appearing to succeed.\n */\nexport function readCommandEnvelope<TPayload = SerializedEntity>(\n body: unknown,\n): Effect.Effect<TransactionCommand<TPayload>, EntifixBuildError> {\n return Effect.gen(function* () {\n const envelope = yield* readEnvelope<TransactionCommand<TPayload>>(\n body,\n 'command',\n 'command',\n );\n const command = envelope.data;\n if (\n command == null ||\n !isTransactionId(command.transactionId) ||\n typeof command.entity !== 'string'\n ) {\n return yield* Effect.fail(\n new EntifixBuildError(\n 'command envelope carried no valid command',\n undefined,\n {\n body,\n },\n ),\n );\n }\n // `organizationId` is deliberately **not** carried over from the parsed\n // body. Spreading the caller's object here would let a request name another\n // tenant, which is precisely the scoping the stream depends on.\n const { organizationId: _ignored, ...trusted } = command;\n return trusted as TransactionCommand<TPayload>;\n });\n}\n"],"names":["EntifixBuildError","makeEnvelope","readEnvelope","Effect","makeCommandEnvelope","command","entity","UUID","isTransactionId","value","test","readCommandEnvelope","body","gen","envelope","data","transactionId","fail","undefined","organizationId","_ignored","trusted"],"mappings":";AAAA,SACEA,iBAAiB,EAEjBC,YAAY,EACZC,YAAY,QAEP,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAiDhC,6DAA6D,GAC7D,OAAO,SAASC,oBACdC,OAAqC;IAErC,OAAOJ,aAAa,WAAWI,QAAQC,MAAM,EAAED;AACjD;AAEA;;;;;;;CAOC,GACD,MAAME,OACJ;AAEF,gDAAgD,GAChD,OAAO,MAAMC,kBAAkB,CAACC,QAC9B,OAAOA,UAAU,YAAYF,KAAKG,IAAI,CAACD,OAAO;AAEhD;;;;;;;CAOC,GACD,OAAO,SAASE,oBACdC,IAAa;IAEb,OAAOT,OAAOU,GAAG,CAAC;QAChB,MAAMC,WAAW,OAAOZ,aACtBU,MACA,WACA;QAEF,MAAMP,UAAUS,SAASC,IAAI;QAC7B,IACEV,WAAW,QACX,CAACG,gBAAgBH,QAAQW,aAAa,KACtC,OAAOX,QAAQC,MAAM,KAAK,UAC1B;YACA,OAAO,OAAOH,OAAOc,IAAI,CACvB,IAAIjB,kBACF,6CACAkB,WACA;gBACEN;YACF;QAGN;QACA,wEAAwE;QACxE,4EAA4E;QAC5E,gEAAgE;QAChE,MAAM,EAAEO,gBAAgBC,QAAQ,EAAc,GAAGf,SAAZgB,2CAAYhB;;;QACjD,OAAOgB;IACT;AACF"}
@@ -0,0 +1,84 @@
1
+ import { type DomainEvent, type EntifixEnvelope, type EntityId } from '@entifix/core';
2
+ import type { TransactionOutcome } from '../ports/transaction-handler.js';
3
+ import type { TransactionCommand } from './command.js';
4
+ /**
5
+ * The lifecycle states a transaction record settles into.
6
+ *
7
+ * A const array rather than a bare union because something has to **enumerate**
8
+ * them: a by-state gauge must report every state including the ones at zero, and
9
+ * a series that simply stops being reported reads on most dashboards as "no
10
+ * data" rather than as "none" — so `STALE` falling to zero would look exactly
11
+ * like the metric having broken.
12
+ *
13
+ * Note there are four states but only three {@link TransactionStep}s: `STALE` is
14
+ * applied by the recovery sweep and has no event of its own.
15
+ */
16
+ export declare const TRANSACTION_STATES: readonly ["PENDING", "COMPLETED", "FAILED", "STALE"];
17
+ /** The lifecycle state a transaction record settles into. */
18
+ export type TransactionState = (typeof TRANSACTION_STATES)[number];
19
+ /** The facade step a given event reports. */
20
+ export type TransactionStep = 'accepted' | 'completed' | 'failed';
21
+ /**
22
+ * What a service reports as its transaction progresses — the **payload** of a
23
+ * {@link DomainEvent}, not the message itself. The saga tracker is a passive
24
+ * consumer of these: for a single-step write it dispatches nothing and only
25
+ * records what the events tell it, which is what keeps such a write
26
+ * choreographed. A flow spanning slices is orchestrated instead, from a
27
+ * declarative definition (ADR 0039), and its coordinator both reads these and
28
+ * issues the next step — but that engine is not built, and single-step writes
29
+ * stay exactly as described here when it is.
30
+ *
31
+ * `transactionId` and `at` are also reachable as the message's `correlationId`
32
+ * and `at`. That duplication is deliberate and standard (CloudEvents' `subject`
33
+ * does the same): metadata is what the *transport* routes and deduplicates on,
34
+ * and the payload has to stand on its own for a consumer that has already
35
+ * unwrapped it.
36
+ */
37
+ export interface TransactionEvent {
38
+ transactionId: string;
39
+ /** The target entity's `key`. */
40
+ entity: string;
41
+ state: TransactionState;
42
+ step: TransactionStep;
43
+ /** The assigned code once executed (`product-001`). */
44
+ code?: string;
45
+ /** The stored entity id once executed. */
46
+ entityId?: EntityId;
47
+ /** Failure detail when `step === 'failed'`. */
48
+ error?: string;
49
+ /** ISO-8601 emission time. */
50
+ at: string;
51
+ /**
52
+ * Whose organization this happened in — the per-connection scoping key for
53
+ * the reactive stream (ADR 0036).
54
+ *
55
+ * In `data` rather than in `meta`, under ADR 0029's rule: `meta` describes the
56
+ * message, `data` describes the occurrence, and which vendor's catalog a
57
+ * record was written in is a fact about what happened.
58
+ *
59
+ * **Optional, and absence is not a wildcard.** An event carrying no
60
+ * organization is delivered to no tenant-scoped connection. Defaulting the
61
+ * other way would make every event emitted before this member existed a
62
+ * cross-tenant delivery, and it fails silently in the direction that matters.
63
+ */
64
+ organizationId?: string;
65
+ }
66
+ /** The register's name for a transaction message: `transaction.completed`. */
67
+ export declare const transactionEventName: (step: TransactionStep) => string;
68
+ /**
69
+ * The message id for one step of one transaction — and therefore the
70
+ * deduplication key.
71
+ *
72
+ * It is the transaction id **and** the step, never the transaction id alone.
73
+ * One transaction emits up to three messages, so a consumer keying on the
74
+ * transaction id would treat `completed` as a redelivery of `accepted` and drop
75
+ * the outcome. The outbox's unique index is on exactly this value, which is what
76
+ * keeps the idempotency claim and the dedup key the same fact rather than two
77
+ * that can drift.
78
+ */
79
+ export declare const transactionEventId: (transactionId: string, step: TransactionStep) => string;
80
+ export declare const acceptedEvent: (command: TransactionCommand, source: string) => DomainEvent<TransactionEvent>;
81
+ export declare const completedEvent: (command: TransactionCommand, outcome: TransactionOutcome, source: string) => DomainEvent<TransactionEvent>;
82
+ export declare const failedEvent: (command: TransactionCommand, error: unknown, source: string) => DomainEvent<TransactionEvent>;
83
+ export type TransactionEventEnvelope = EntifixEnvelope<TransactionEvent>;
84
+ //# sourceMappingURL=event.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event.d.ts","sourceRoot":"","sources":["../../src/contracts/event.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,eAAe,EACpB,KAAK,QAAQ,EACd,MAAM,eAAe,CAAC;AAEvB,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAC1E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAEvD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,kBAAkB,sDAKrB,CAAC;AAEX,6DAA6D;AAC7D,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEnE,6CAA6C;AAC7C,MAAM,MAAM,eAAe,GAAG,UAAU,GAAG,WAAW,GAAG,QAAQ,CAAC;AAElE;;;;;;;;;;;;;;;GAeG;AACH,MAAM,WAAW,gBAAgB;IAC/B,aAAa,EAAE,MAAM,CAAC;IACtB,iCAAiC;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,gBAAgB,CAAC;IACxB,IAAI,EAAE,eAAe,CAAC;IACtB,uDAAuD;IACvD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,0CAA0C;IAC1C,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,+CAA+C;IAC/C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,8BAA8B;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX;;;;;;;;;;;;OAYG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAID,8EAA8E;AAC9E,eAAO,MAAM,oBAAoB,GAAI,MAAM,eAAe,KAAG,MACtC,CAAC;AAExB;;;;;;;;;;GAUG;AACH,eAAO,MAAM,kBAAkB,GAC7B,eAAe,MAAM,EACrB,MAAM,eAAe,KACpB,MAAoC,CAAC;AAexC,eAAO,MAAM,aAAa,GACxB,SAAS,kBAAkB,EAC3B,QAAQ,MAAM,KACb,WAAW,CAAC,gBAAgB,CAQ3B,CAAC;AAEL,eAAO,MAAM,cAAc,GACzB,SAAS,kBAAkB,EAC3B,SAAS,kBAAkB,EAC3B,QAAQ,MAAM,KACb,WAAW,CAAC,gBAAgB,CAU3B,CAAC;AAEL,eAAO,MAAM,WAAW,GACtB,SAAS,kBAAkB,EAC3B,OAAO,OAAO,EACd,QAAQ,MAAM,KACb,WAAW,CAAC,gBAAgB,CAS3B,CAAC;AAEL,MAAM,MAAM,wBAAwB,GAAG,eAAe,CAAC,gBAAgB,CAAC,CAAC"}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The lifecycle states a transaction record settles into.
3
+ *
4
+ * A const array rather than a bare union because something has to **enumerate**
5
+ * them: a by-state gauge must report every state including the ones at zero, and
6
+ * a series that simply stops being reported reads on most dashboards as "no
7
+ * data" rather than as "none" — so `STALE` falling to zero would look exactly
8
+ * like the metric having broken.
9
+ *
10
+ * Note there are four states but only three {@link TransactionStep}s: `STALE` is
11
+ * applied by the recovery sweep and has no event of its own.
12
+ */ export const TRANSACTION_STATES = [
13
+ 'PENDING',
14
+ 'COMPLETED',
15
+ 'FAILED',
16
+ 'STALE'
17
+ ];
18
+ const now = ()=>new Date().toISOString();
19
+ /** The register's name for a transaction message: `transaction.completed`. */ export const transactionEventName = (step)=>`transaction.${step}`;
20
+ /**
21
+ * The message id for one step of one transaction — and therefore the
22
+ * deduplication key.
23
+ *
24
+ * It is the transaction id **and** the step, never the transaction id alone.
25
+ * One transaction emits up to three messages, so a consumer keying on the
26
+ * transaction id would treat `completed` as a redelivery of `accepted` and drop
27
+ * the outcome. The outbox's unique index is on exactly this value, which is what
28
+ * keeps the idempotency claim and the dedup key the same fact rather than two
29
+ * that can drift.
30
+ */ export const transactionEventId = (transactionId, step)=>`${transactionId}:${step}`;
31
+ /** Wraps a payload as a routable message from `source`. */ const message = (source, data)=>({
32
+ name: transactionEventName(data.step),
33
+ id: transactionEventId(data.transactionId, data.step),
34
+ source,
35
+ at: data.at,
36
+ correlationId: data.transactionId,
37
+ data
38
+ });
39
+ export const acceptedEvent = (command, source)=>message(source, {
40
+ transactionId: command.transactionId,
41
+ entity: command.entity,
42
+ state: 'PENDING',
43
+ step: 'accepted',
44
+ at: now(),
45
+ organizationId: command.organizationId
46
+ });
47
+ export const completedEvent = (command, outcome, source)=>message(source, {
48
+ transactionId: command.transactionId,
49
+ entity: command.entity,
50
+ state: 'COMPLETED',
51
+ step: 'completed',
52
+ code: outcome.code,
53
+ entityId: outcome.entityId,
54
+ at: now(),
55
+ organizationId: command.organizationId
56
+ });
57
+ export const failedEvent = (command, error, source)=>message(source, {
58
+ transactionId: command.transactionId,
59
+ entity: command.entity,
60
+ state: 'FAILED',
61
+ step: 'failed',
62
+ error: error instanceof Error ? error.message : String(error),
63
+ at: now(),
64
+ organizationId: command.organizationId
65
+ });
66
+
67
+ //# sourceMappingURL=event.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/contracts/event.ts"],"sourcesContent":["import {\n type DomainEvent,\n type EntifixEnvelope,\n type EntityId,\n} from '@entifix/core';\n\nimport type { TransactionOutcome } from '../ports/transaction-handler.js';\nimport type { TransactionCommand } from './command.js';\n\n/**\n * The lifecycle states a transaction record settles into.\n *\n * A const array rather than a bare union because something has to **enumerate**\n * them: a by-state gauge must report every state including the ones at zero, and\n * a series that simply stops being reported reads on most dashboards as \"no\n * data\" rather than as \"none\" — so `STALE` falling to zero would look exactly\n * like the metric having broken.\n *\n * Note there are four states but only three {@link TransactionStep}s: `STALE` is\n * applied by the recovery sweep and has no event of its own.\n */\nexport const TRANSACTION_STATES = [\n 'PENDING',\n 'COMPLETED',\n 'FAILED',\n 'STALE',\n] as const;\n\n/** The lifecycle state a transaction record settles into. */\nexport type TransactionState = (typeof TRANSACTION_STATES)[number];\n\n/** The facade step a given event reports. */\nexport type TransactionStep = 'accepted' | 'completed' | 'failed';\n\n/**\n * What a service reports as its transaction progresses — the **payload** of a\n * {@link DomainEvent}, not the message itself. The saga tracker is a passive\n * consumer of these: for a single-step write it dispatches nothing and only\n * records what the events tell it, which is what keeps such a write\n * choreographed. A flow spanning slices is orchestrated instead, from a\n * declarative definition (ADR 0039), and its coordinator both reads these and\n * issues the next step — but that engine is not built, and single-step writes\n * stay exactly as described here when it is.\n *\n * `transactionId` and `at` are also reachable as the message's `correlationId`\n * and `at`. That duplication is deliberate and standard (CloudEvents' `subject`\n * does the same): metadata is what the *transport* routes and deduplicates on,\n * and the payload has to stand on its own for a consumer that has already\n * unwrapped it.\n */\nexport interface TransactionEvent {\n transactionId: string;\n /** The target entity's `key`. */\n entity: string;\n state: TransactionState;\n step: TransactionStep;\n /** The assigned code once executed (`product-001`). */\n code?: string;\n /** The stored entity id once executed. */\n entityId?: EntityId;\n /** Failure detail when `step === 'failed'`. */\n error?: string;\n /** ISO-8601 emission time. */\n at: string;\n /**\n * Whose organization this happened in — the per-connection scoping key for\n * the reactive stream (ADR 0036).\n *\n * In `data` rather than in `meta`, under ADR 0029's rule: `meta` describes the\n * message, `data` describes the occurrence, and which vendor's catalog a\n * record was written in is a fact about what happened.\n *\n * **Optional, and absence is not a wildcard.** An event carrying no\n * organization is delivered to no tenant-scoped connection. Defaulting the\n * other way would make every event emitted before this member existed a\n * cross-tenant delivery, and it fails silently in the direction that matters.\n */\n organizationId?: string;\n}\n\nconst now = (): string => new Date().toISOString();\n\n/** The register's name for a transaction message: `transaction.completed`. */\nexport const transactionEventName = (step: TransactionStep): string =>\n `transaction.${step}`;\n\n/**\n * The message id for one step of one transaction — and therefore the\n * deduplication key.\n *\n * It is the transaction id **and** the step, never the transaction id alone.\n * One transaction emits up to three messages, so a consumer keying on the\n * transaction id would treat `completed` as a redelivery of `accepted` and drop\n * the outcome. The outbox's unique index is on exactly this value, which is what\n * keeps the idempotency claim and the dedup key the same fact rather than two\n * that can drift.\n */\nexport const transactionEventId = (\n transactionId: string,\n step: TransactionStep,\n): string => `${transactionId}:${step}`;\n\n/** Wraps a payload as a routable message from `source`. */\nconst message = (\n source: string,\n data: TransactionEvent,\n): DomainEvent<TransactionEvent> => ({\n name: transactionEventName(data.step),\n id: transactionEventId(data.transactionId, data.step),\n source,\n at: data.at,\n correlationId: data.transactionId,\n data,\n});\n\nexport const acceptedEvent = (\n command: TransactionCommand,\n source: string,\n): DomainEvent<TransactionEvent> =>\n message(source, {\n transactionId: command.transactionId,\n entity: command.entity,\n state: 'PENDING',\n step: 'accepted',\n at: now(),\n organizationId: command.organizationId,\n });\n\nexport const completedEvent = (\n command: TransactionCommand,\n outcome: TransactionOutcome,\n source: string,\n): DomainEvent<TransactionEvent> =>\n message(source, {\n transactionId: command.transactionId,\n entity: command.entity,\n state: 'COMPLETED',\n step: 'completed',\n code: outcome.code,\n entityId: outcome.entityId,\n at: now(),\n organizationId: command.organizationId,\n });\n\nexport const failedEvent = (\n command: TransactionCommand,\n error: unknown,\n source: string,\n): DomainEvent<TransactionEvent> =>\n message(source, {\n transactionId: command.transactionId,\n entity: command.entity,\n state: 'FAILED',\n step: 'failed',\n error: error instanceof Error ? error.message : String(error),\n at: now(),\n organizationId: command.organizationId,\n });\n\nexport type TransactionEventEnvelope = EntifixEnvelope<TransactionEvent>;\n"],"names":["TRANSACTION_STATES","now","Date","toISOString","transactionEventName","step","transactionEventId","transactionId","message","source","data","name","id","at","correlationId","acceptedEvent","command","entity","state","organizationId","completedEvent","outcome","code","entityId","failedEvent","error","Error","String"],"mappings":"AASA;;;;;;;;;;;CAWC,GACD,OAAO,MAAMA,qBAAqB;IAChC;IACA;IACA;IACA;CACD,CAAU;AAsDX,MAAMC,MAAM,IAAc,IAAIC,OAAOC,WAAW;AAEhD,4EAA4E,GAC5E,OAAO,MAAMC,uBAAuB,CAACC,OACnC,CAAC,YAAY,EAAEA,MAAM,CAAC;AAExB;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,qBAAqB,CAChCC,eACAF,OACW,GAAGE,cAAc,CAAC,EAAEF,MAAM,CAAC;AAExC,yDAAyD,GACzD,MAAMG,UAAU,CACdC,QACAC,OACmC,CAAA;QACnCC,MAAMP,qBAAqBM,KAAKL,IAAI;QACpCO,IAAIN,mBAAmBI,KAAKH,aAAa,EAAEG,KAAKL,IAAI;QACpDI;QACAI,IAAIH,KAAKG,EAAE;QACXC,eAAeJ,KAAKH,aAAa;QACjCG;IACF,CAAA;AAEA,OAAO,MAAMK,gBAAgB,CAC3BC,SACAP,SAEAD,QAAQC,QAAQ;QACdF,eAAeS,QAAQT,aAAa;QACpCU,QAAQD,QAAQC,MAAM;QACtBC,OAAO;QACPb,MAAM;QACNQ,IAAIZ;QACJkB,gBAAgBH,QAAQG,cAAc;IACxC,GAAG;AAEL,OAAO,MAAMC,iBAAiB,CAC5BJ,SACAK,SACAZ,SAEAD,QAAQC,QAAQ;QACdF,eAAeS,QAAQT,aAAa;QACpCU,QAAQD,QAAQC,MAAM;QACtBC,OAAO;QACPb,MAAM;QACNiB,MAAMD,QAAQC,IAAI;QAClBC,UAAUF,QAAQE,QAAQ;QAC1BV,IAAIZ;QACJkB,gBAAgBH,QAAQG,cAAc;IACxC,GAAG;AAEL,OAAO,MAAMK,cAAc,CACzBR,SACAS,OACAhB,SAEAD,QAAQC,QAAQ;QACdF,eAAeS,QAAQT,aAAa;QACpCU,QAAQD,QAAQC,MAAM;QACtBC,OAAO;QACPb,MAAM;QACNoB,OAAOA,iBAAiBC,QAAQD,MAAMjB,OAAO,GAAGmB,OAAOF;QACvDZ,IAAIZ;QACJkB,gBAAgBH,QAAQG,cAAc;IACxC,GAAG"}
@@ -0,0 +1,80 @@
1
+ import type { EntifixConnError } from '@entifix/core';
2
+ import { Context, type Effect } from 'effect';
3
+ /**
4
+ * A consumer's claim on one delivered message.
5
+ *
6
+ * The mirror of an {@link OutboxEntry}: the outbox makes a publisher's event
7
+ * survive a broker outage, the inbox makes a consumer's side effect survive a
8
+ * redelivery. Each end owns one unique index, and the value in it is the same
9
+ * `event.id`.
10
+ */
11
+ export interface InboxClaim {
12
+ /**
13
+ * Which consumer claimed it — the subscription's durable work-queue name
14
+ * (`<slice>.<pattern>`).
15
+ *
16
+ * **Half of the key, and the half that is easy to leave out.** Two consumers
17
+ * legitimately process the same event: the saga tracker's fold and the SSE
18
+ * hub both bind `transaction.*` today. Keyed on `eventId` alone, whichever
19
+ * claimed first would starve the other of every message — a consumer that
20
+ * silently stops working while the broker, the queue and the handler all
21
+ * report success.
22
+ */
23
+ consumer: string;
24
+ /**
25
+ * The message's own id, which for a transaction step is
26
+ * `<transactionId>:<step>`.
27
+ *
28
+ * Never `correlationId`: one transaction emits up to three messages, so
29
+ * keying on the correlation id would make `completed` look like a
30
+ * redelivery of `accepted` (ADR 0029).
31
+ */
32
+ eventId: string;
33
+ /** ISO-8601, for retention — nothing reads it to make a decision. */
34
+ claimedAt: string;
35
+ }
36
+ /**
37
+ * Whether {@link TransactionInbox.claim} actually wrote.
38
+ *
39
+ * `duplicate` is not a failure — it is how a **redelivery** is recognised, the
40
+ * same way `OutboxEnqueueResult`'s `duplicate` recognises a replayed command.
41
+ * Delivery is at-least-once by construction (a crash between `publish` and
42
+ * `markSent` re-sends), so a consumer seeing this should skip its side effect
43
+ * and ack, not error.
44
+ */
45
+ export type InboxClaimResult = 'claimed' | 'duplicate';
46
+ /**
47
+ * The consumer-side half of exactly-once processing over an at-least-once bus.
48
+ *
49
+ * A claim is only worth anything if it is written **in the same storage
50
+ * transaction as the side effect it guards**. Claim-then-act leaves a crash
51
+ * window in which the claim is taken and the effect never ran, so the
52
+ * redelivery is skipped and the work is lost — strictly worse than doing it
53
+ * twice.
54
+ *
55
+ * There is deliberately **no `claimWithin(session)` here**, for the reason
56
+ * {@link TransactionOutbox} states about `enqueueWithin`: a driver session may
57
+ * not enter a framework-free contract. The consumer owns that write, exactly as
58
+ * a {@link TransactionHandler} owns the `completed` outbox entry — it holds the
59
+ * session, it inserts the document {@link InboxClaim} describes, and this port
60
+ * is what a consumer that can claim standalone uses instead.
61
+ *
62
+ * It follows that **the inbox lives with the side effect, not in one central
63
+ * place**: the claim and the write must be in the same database to be one fact.
64
+ * The outbox is per-tenant because the entity is; the saga tracker's inbox is in
65
+ * the `saga` database because that is where its fold writes.
66
+ */
67
+ export interface TransactionInbox {
68
+ /**
69
+ * Claim an event for this consumer. Idempotent per `(consumer, eventId)`.
70
+ *
71
+ * Answering `duplicate` means some earlier delivery already ran the side
72
+ * effect to completion, because the claim and the effect commit together.
73
+ */
74
+ claim(eventId: string): Effect.Effect<InboxClaimResult, EntifixConnError>;
75
+ }
76
+ declare const TransactionInboxTag_base: Context.TagClass<TransactionInboxTag, "TransactionInboxTag", TransactionInbox>;
77
+ export declare class TransactionInboxTag extends TransactionInboxTag_base {
78
+ }
79
+ export {};
80
+ //# sourceMappingURL=inbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inbox.d.ts","sourceRoot":"","sources":["../../src/contracts/inbox.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;;;;GAOG;AACH,MAAM,WAAW,UAAU;IACzB;;;;;;;;;;OAUG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;;;;OAOG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB,qEAAqE;IACrE,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;;GAQG;AACH,MAAM,MAAM,gBAAgB,GAAG,SAAS,GAAG,WAAW,CAAC;AAEvD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;;;OAKG;IACH,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,CAAC;CAC3E;;AAED,qBAAa,mBAAoB,SAAQ,wBAGtC;CAAG"}
@@ -0,0 +1,5 @@
1
+ import { Context } from 'effect';
2
+ export class TransactionInboxTag extends Context.Tag('TransactionInboxTag')() {
3
+ }
4
+
5
+ //# sourceMappingURL=inbox.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/contracts/inbox.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * A consumer's claim on one delivered message.\n *\n * The mirror of an {@link OutboxEntry}: the outbox makes a publisher's event\n * survive a broker outage, the inbox makes a consumer's side effect survive a\n * redelivery. Each end owns one unique index, and the value in it is the same\n * `event.id`.\n */\nexport interface InboxClaim {\n /**\n * Which consumer claimed it — the subscription's durable work-queue name\n * (`<slice>.<pattern>`).\n *\n * **Half of the key, and the half that is easy to leave out.** Two consumers\n * legitimately process the same event: the saga tracker's fold and the SSE\n * hub both bind `transaction.*` today. Keyed on `eventId` alone, whichever\n * claimed first would starve the other of every message — a consumer that\n * silently stops working while the broker, the queue and the handler all\n * report success.\n */\n consumer: string;\n /**\n * The message's own id, which for a transaction step is\n * `<transactionId>:<step>`.\n *\n * Never `correlationId`: one transaction emits up to three messages, so\n * keying on the correlation id would make `completed` look like a\n * redelivery of `accepted` (ADR 0029).\n */\n eventId: string;\n /** ISO-8601, for retention — nothing reads it to make a decision. */\n claimedAt: string;\n}\n\n/**\n * Whether {@link TransactionInbox.claim} actually wrote.\n *\n * `duplicate` is not a failure — it is how a **redelivery** is recognised, the\n * same way `OutboxEnqueueResult`'s `duplicate` recognises a replayed command.\n * Delivery is at-least-once by construction (a crash between `publish` and\n * `markSent` re-sends), so a consumer seeing this should skip its side effect\n * and ack, not error.\n */\nexport type InboxClaimResult = 'claimed' | 'duplicate';\n\n/**\n * The consumer-side half of exactly-once processing over an at-least-once bus.\n *\n * A claim is only worth anything if it is written **in the same storage\n * transaction as the side effect it guards**. Claim-then-act leaves a crash\n * window in which the claim is taken and the effect never ran, so the\n * redelivery is skipped and the work is lost — strictly worse than doing it\n * twice.\n *\n * There is deliberately **no `claimWithin(session)` here**, for the reason\n * {@link TransactionOutbox} states about `enqueueWithin`: a driver session may\n * not enter a framework-free contract. The consumer owns that write, exactly as\n * a {@link TransactionHandler} owns the `completed` outbox entry — it holds the\n * session, it inserts the document {@link InboxClaim} describes, and this port\n * is what a consumer that can claim standalone uses instead.\n *\n * It follows that **the inbox lives with the side effect, not in one central\n * place**: the claim and the write must be in the same database to be one fact.\n * The outbox is per-tenant because the entity is; the saga tracker's inbox is in\n * the `saga` database because that is where its fold writes.\n */\nexport interface TransactionInbox {\n /**\n * Claim an event for this consumer. Idempotent per `(consumer, eventId)`.\n *\n * Answering `duplicate` means some earlier delivery already ran the side\n * effect to completion, because the claim and the effect commit together.\n */\n claim(eventId: string): Effect.Effect<InboxClaimResult, EntifixConnError>;\n}\n\nexport class TransactionInboxTag extends Context.Tag('TransactionInboxTag')<\n TransactionInboxTag,\n TransactionInbox\n>() {}\n"],"names":["Context","TransactionInboxTag","Tag"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AA8E9C,OAAO,MAAMC,4BAA4BD,QAAQE,GAAG,CAAC;AAGhD"}
@@ -0,0 +1,137 @@
1
+ import type { DomainEvent, EntifixConnError } from '@entifix/core';
2
+ import { Context, type Effect } from 'effect';
3
+ /**
4
+ * A transaction event recorded durably *before* it reaches the broker.
5
+ *
6
+ * The point of the outbox is that a state change and the event announcing it
7
+ * become one fact. `execute` used to write Mongo and then call `bus.publish`
8
+ * separately: with the broker down between the two, the write happened and the
9
+ * event never did, so the saga record sat `PENDING` until the sweep mislabelled
10
+ * a successful transaction `STALE`. An entry written in the same transaction as
11
+ * the state change cannot be lost that way, and a relay carries it to the bus
12
+ * afterwards.
13
+ */
14
+ export interface OutboxEntry {
15
+ /**
16
+ * The message's own id, denormalized out of `event` so the unique index sits
17
+ * on a plain top-level field rather than a nested path.
18
+ *
19
+ * This **is** the idempotency claim: for a transaction step it is
20
+ * `<transactionId>:<step>`, so a replayed command collides here and is
21
+ * recognised as a retry before any lock is taken or work forked.
22
+ */
23
+ eventId: string;
24
+ event: DomainEvent;
25
+ sent: boolean;
26
+ /**
27
+ * Publish attempts already spent on this entry.
28
+ *
29
+ * The relay drains in order and stops at the first failure, which is what
30
+ * keeps `accepted` ahead of a terminal event — and is also why an entry that
31
+ * can *never* publish used to block everything behind it forever. Counting
32
+ * the attempts is what turns "retrying" into a state with an end
33
+ * (ADR 0030).
34
+ */
35
+ attempts: number;
36
+ /**
37
+ * Why the last attempt failed. Absent until one has, so its presence alone
38
+ * says this entry has been tried.
39
+ */
40
+ lastError?: string;
41
+ /**
42
+ * Set once the attempts are spent. A quarantined entry is **skipped** rather
43
+ * than retried, so the head of the line moves; nothing deletes it, because a
44
+ * stuck transaction nobody is told about is the same as a lost one.
45
+ */
46
+ quarantined: boolean;
47
+ /** ISO-8601, and the drain order: entries publish oldest-first. */
48
+ createdAt: string;
49
+ }
50
+ /**
51
+ * Whether {@link TransactionOutbox.enqueue} actually wrote.
52
+ *
53
+ * `duplicate` is not a failure — it is how a *retry* is recognised. The
54
+ * transaction id is the client's idempotency key (ADR 0028), so a repeated
55
+ * command must return the first one's answer rather than execute twice. The
56
+ * adapter owns the detection because the mechanism is storage-specific (a Mongo
57
+ * `E11000` against the unique index on `eventId`), and translating it here keeps
58
+ * driver error codes out of route handlers.
59
+ */
60
+ export type OutboxEnqueueResult = 'enqueued' | 'duplicate';
61
+ /**
62
+ * An aggregate view of one outbox, for {@link TransactionOutbox.stats}.
63
+ *
64
+ * Counts and one timestamp — **no ids and no payloads**. That is what makes it
65
+ * safe where a listing is not: an outbox holds event payloads, and once
66
+ * `catalog.published` carries a whole offering an unfiltered read of one is a
67
+ * tenant-data surface.
68
+ */
69
+ export interface OutboxStats {
70
+ /** Unsent, un-quarantined entries — the same set {@link pending} drains. */
71
+ pending: number;
72
+ /**
73
+ * `createdAt` of the oldest such entry, absent when there are none.
74
+ *
75
+ * The age derived from this is the metric that makes a stuck relay visible.
76
+ * An entry that can never publish no longer blocks the ones behind it — #179
77
+ * gave the relay a ceiling — but a quarantine is reported only as a log line,
78
+ * so *how far behind* the head has fallen is otherwise unanswerable.
79
+ */
80
+ oldestPendingAt?: string;
81
+ /** Entries past the ceiling, which {@link pending} skips and nothing deletes. */
82
+ quarantined: number;
83
+ }
84
+ /**
85
+ * The durable hand-off between a transactional write and the event bus.
86
+ *
87
+ * Deliberately **not** a publisher: it never touches the broker. `enqueue` is
88
+ * the only write, and the relay composes `pending`/`markSent` with an
89
+ * {@link EventBus} — which is what keeps the engine framework-free and lets the
90
+ * relay be tested without either a database or a broker.
91
+ *
92
+ * There is no `enqueueWithin(session)` here on purpose. Making the `completed`
93
+ * entry atomic with the entity write needs the storage driver's own session, and
94
+ * putting one in this port (or in `EntityRepository`) would drag Mongo into a
95
+ * framework-free contract. The handler owns that write instead — see
96
+ * {@link TransactionHandler}.
97
+ */
98
+ export interface TransactionOutbox {
99
+ /** Record an event durably. Idempotent per `event.id`. */
100
+ enqueue(event: DomainEvent): Effect.Effect<OutboxEnqueueResult, EntifixConnError>;
101
+ /**
102
+ * Unsent, un-quarantined entries, oldest first — the relay's input.
103
+ *
104
+ * Excluding the quarantined ones here rather than in the relay is deliberate:
105
+ * a skip the caller has to remember is a skip the next caller forgets.
106
+ */
107
+ pending(limit: number): Effect.Effect<readonly OutboxEntry[], EntifixConnError>;
108
+ /**
109
+ * Mark an entry published. A crash between the publish and this call re-sends
110
+ * the event on the next drain, which is why delivery is at-least-once and why
111
+ * a consumer that must not fold twice dedupes on `event.id`.
112
+ */
113
+ markSent(entry: OutboxEntry): Effect.Effect<void, EntifixConnError>;
114
+ /**
115
+ * Record a failed publish: increments `attempts` and stores `error`.
116
+ *
117
+ * `quarantine` is the caller's decision rather than the adapter's, because
118
+ * the ceiling is configuration the relay reads and the store has no business
119
+ * knowing it. Once set, {@link pending} must stop returning the entry — that
120
+ * is the whole mechanism by which the queue's head moves.
121
+ */
122
+ recordFailure(entry: OutboxEntry, error: string, quarantine: boolean): Effect.Effect<void, EntifixConnError>;
123
+ /**
124
+ * Depth and age, for the relay to sample once per sweep.
125
+ *
126
+ * An aggregate rather than a read, deliberately: `pending(limit)` truncates at
127
+ * the relay's batch size, so counting what it returns answers "is the batch
128
+ * full" and not "how far behind are we" — which are the same number right up
129
+ * to the moment the second one starts to matter.
130
+ */
131
+ stats(): Effect.Effect<OutboxStats, EntifixConnError>;
132
+ }
133
+ declare const TransactionOutboxTag_base: Context.TagClass<TransactionOutboxTag, "TransactionOutboxTag", TransactionOutbox>;
134
+ export declare class TransactionOutboxTag extends TransactionOutboxTag_base {
135
+ }
136
+ export {};
137
+ //# sourceMappingURL=outbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outbox.d.ts","sourceRoot":"","sources":["../../src/contracts/outbox.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;;;;;;;GAUG;AACH,MAAM,WAAW,WAAW;IAC1B;;;;;;;OAOG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,WAAW,CAAC;IACnB,IAAI,EAAE,OAAO,CAAC;IACd;;;;;;;;OAQG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,WAAW,EAAE,OAAO,CAAC;IACrB,mEAAmE;IACnE,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;;;GASG;AACH,MAAM,MAAM,mBAAmB,GAAG,UAAU,GAAG,WAAW,CAAC;AAE3D;;;;;;;GAOG;AACH,MAAM,WAAW,WAAW;IAC1B,4EAA4E;IAC5E,OAAO,EAAE,MAAM,CAAC;IAChB;;;;;;;OAOG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,iFAAiF;IACjF,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,iBAAiB;IAChC,0DAA0D;IAC1D,OAAO,CACL,KAAK,EAAE,WAAW,GACjB,MAAM,CAAC,MAAM,CAAC,mBAAmB,EAAE,gBAAgB,CAAC,CAAC;IACxD;;;;;OAKG;IACH,OAAO,CACL,KAAK,EAAE,MAAM,GACZ,MAAM,CAAC,MAAM,CAAC,SAAS,WAAW,EAAE,EAAE,gBAAgB,CAAC,CAAC;IAC3D;;;;OAIG;IACH,QAAQ,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;IACpE;;;;;;;OAOG;IACH,aAAa,CACX,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,OAAO,GAClB,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;IACzC;;;;;;;OAOG;IACH,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC;CACvD;;AAED,qBAAa,oBAAqB,SAAQ,yBAGvC;CAAG"}
@@ -0,0 +1,5 @@
1
+ import { Context } from 'effect';
2
+ export class TransactionOutboxTag extends Context.Tag('TransactionOutboxTag')() {
3
+ }
4
+
5
+ //# sourceMappingURL=outbox.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/contracts/outbox.ts"],"sourcesContent":["import type { DomainEvent, EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * A transaction event recorded durably *before* it reaches the broker.\n *\n * The point of the outbox is that a state change and the event announcing it\n * become one fact. `execute` used to write Mongo and then call `bus.publish`\n * separately: with the broker down between the two, the write happened and the\n * event never did, so the saga record sat `PENDING` until the sweep mislabelled\n * a successful transaction `STALE`. An entry written in the same transaction as\n * the state change cannot be lost that way, and a relay carries it to the bus\n * afterwards.\n */\nexport interface OutboxEntry {\n /**\n * The message's own id, denormalized out of `event` so the unique index sits\n * on a plain top-level field rather than a nested path.\n *\n * This **is** the idempotency claim: for a transaction step it is\n * `<transactionId>:<step>`, so a replayed command collides here and is\n * recognised as a retry before any lock is taken or work forked.\n */\n eventId: string;\n event: DomainEvent;\n sent: boolean;\n /**\n * Publish attempts already spent on this entry.\n *\n * The relay drains in order and stops at the first failure, which is what\n * keeps `accepted` ahead of a terminal event — and is also why an entry that\n * can *never* publish used to block everything behind it forever. Counting\n * the attempts is what turns \"retrying\" into a state with an end\n * (ADR 0030).\n */\n attempts: number;\n /**\n * Why the last attempt failed. Absent until one has, so its presence alone\n * says this entry has been tried.\n */\n lastError?: string;\n /**\n * Set once the attempts are spent. A quarantined entry is **skipped** rather\n * than retried, so the head of the line moves; nothing deletes it, because a\n * stuck transaction nobody is told about is the same as a lost one.\n */\n quarantined: boolean;\n /** ISO-8601, and the drain order: entries publish oldest-first. */\n createdAt: string;\n}\n\n/**\n * Whether {@link TransactionOutbox.enqueue} actually wrote.\n *\n * `duplicate` is not a failure — it is how a *retry* is recognised. The\n * transaction id is the client's idempotency key (ADR 0028), so a repeated\n * command must return the first one's answer rather than execute twice. The\n * adapter owns the detection because the mechanism is storage-specific (a Mongo\n * `E11000` against the unique index on `eventId`), and translating it here keeps\n * driver error codes out of route handlers.\n */\nexport type OutboxEnqueueResult = 'enqueued' | 'duplicate';\n\n/**\n * An aggregate view of one outbox, for {@link TransactionOutbox.stats}.\n *\n * Counts and one timestamp — **no ids and no payloads**. That is what makes it\n * safe where a listing is not: an outbox holds event payloads, and once\n * `catalog.published` carries a whole offering an unfiltered read of one is a\n * tenant-data surface.\n */\nexport interface OutboxStats {\n /** Unsent, un-quarantined entries — the same set {@link pending} drains. */\n pending: number;\n /**\n * `createdAt` of the oldest such entry, absent when there are none.\n *\n * The age derived from this is the metric that makes a stuck relay visible.\n * An entry that can never publish no longer blocks the ones behind it — #179\n * gave the relay a ceiling — but a quarantine is reported only as a log line,\n * so *how far behind* the head has fallen is otherwise unanswerable.\n */\n oldestPendingAt?: string;\n /** Entries past the ceiling, which {@link pending} skips and nothing deletes. */\n quarantined: number;\n}\n\n/**\n * The durable hand-off between a transactional write and the event bus.\n *\n * Deliberately **not** a publisher: it never touches the broker. `enqueue` is\n * the only write, and the relay composes `pending`/`markSent` with an\n * {@link EventBus} — which is what keeps the engine framework-free and lets the\n * relay be tested without either a database or a broker.\n *\n * There is no `enqueueWithin(session)` here on purpose. Making the `completed`\n * entry atomic with the entity write needs the storage driver's own session, and\n * putting one in this port (or in `EntityRepository`) would drag Mongo into a\n * framework-free contract. The handler owns that write instead — see\n * {@link TransactionHandler}.\n */\nexport interface TransactionOutbox {\n /** Record an event durably. Idempotent per `event.id`. */\n enqueue(\n event: DomainEvent,\n ): Effect.Effect<OutboxEnqueueResult, EntifixConnError>;\n /**\n * Unsent, un-quarantined entries, oldest first — the relay's input.\n *\n * Excluding the quarantined ones here rather than in the relay is deliberate:\n * a skip the caller has to remember is a skip the next caller forgets.\n */\n pending(\n limit: number,\n ): Effect.Effect<readonly OutboxEntry[], EntifixConnError>;\n /**\n * Mark an entry published. A crash between the publish and this call re-sends\n * the event on the next drain, which is why delivery is at-least-once and why\n * a consumer that must not fold twice dedupes on `event.id`.\n */\n markSent(entry: OutboxEntry): Effect.Effect<void, EntifixConnError>;\n /**\n * Record a failed publish: increments `attempts` and stores `error`.\n *\n * `quarantine` is the caller's decision rather than the adapter's, because\n * the ceiling is configuration the relay reads and the store has no business\n * knowing it. Once set, {@link pending} must stop returning the entry — that\n * is the whole mechanism by which the queue's head moves.\n */\n recordFailure(\n entry: OutboxEntry,\n error: string,\n quarantine: boolean,\n ): Effect.Effect<void, EntifixConnError>;\n /**\n * Depth and age, for the relay to sample once per sweep.\n *\n * An aggregate rather than a read, deliberately: `pending(limit)` truncates at\n * the relay's batch size, so counting what it returns answers \"is the batch\n * full\" and not \"how far behind are we\" — which are the same number right up\n * to the moment the second one starts to matter.\n */\n stats(): Effect.Effect<OutboxStats, EntifixConnError>;\n}\n\nexport class TransactionOutboxTag extends Context.Tag('TransactionOutboxTag')<\n TransactionOutboxTag,\n TransactionOutbox\n>() {}\n"],"names":["Context","TransactionOutboxTag","Tag"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAgJ9C,OAAO,MAAMC,6BAA6BD,QAAQE,GAAG,CAAC;AAGjD"}