@entifix/transactions 0.4.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/contracts/command.d.ts +2 -3
- package/dist/contracts/command.d.ts.map +1 -1
- package/dist/contracts/command.js.map +1 -1
- package/dist/contracts/event.d.ts +3 -3
- package/dist/contracts/event.js.map +1 -1
- package/dist/contracts/inbox.d.ts +1 -1
- package/dist/contracts/inbox.js.map +1 -1
- package/dist/contracts/outbox.d.ts +4 -5
- package/dist/contracts/outbox.d.ts.map +1 -1
- package/dist/contracts/outbox.js.map +1 -1
- package/dist/contracts/record.d.ts +4 -5
- package/dist/contracts/record.d.ts.map +1 -1
- package/dist/contracts/record.js.map +1 -1
- package/dist/contracts/saga-definition.d.ts +15 -20
- package/dist/contracts/saga-definition.d.ts.map +1 -1
- package/dist/contracts/saga-definition.js +6 -6
- package/dist/contracts/saga-definition.js.map +1 -1
- package/dist/engine/index.d.ts +17 -0
- package/dist/engine/index.d.ts.map +1 -0
- package/dist/engine/index.js +17 -0
- package/dist/engine/index.js.map +1 -0
- package/dist/engine/resolve-template.d.ts +2 -3
- package/dist/engine/resolve-template.d.ts.map +1 -1
- package/dist/engine/resolve-template.js +2 -3
- package/dist/engine/resolve-template.js.map +1 -1
- package/dist/engine/run-saga.d.ts +1 -2
- package/dist/engine/run-saga.d.ts.map +1 -1
- package/dist/engine/run-saga.js +13 -17
- package/dist/engine/run-saga.js.map +1 -1
- package/dist/index.d.ts +1 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -6
- package/dist/index.js.map +1 -1
- package/dist/ports/event-bus.d.ts +6 -7
- package/dist/ports/event-bus.d.ts.map +1 -1
- package/dist/ports/event-bus.js.map +1 -1
- package/dist/ports/event-source.d.ts +3 -3
- package/dist/ports/event-source.js +3 -3
- package/dist/ports/event-source.js.map +1 -1
- package/dist/ports/saga-dispatcher.d.ts +3 -4
- package/dist/ports/saga-dispatcher.d.ts.map +1 -1
- package/dist/ports/saga-dispatcher.js.map +1 -1
- package/dist/ports/saga-store.d.ts +5 -7
- package/dist/ports/saga-store.d.ts.map +1 -1
- package/dist/ports/saga-store.js +1 -2
- package/dist/ports/saga-store.js.map +1 -1
- package/dist/ports/transaction-handler.d.ts +2 -4
- package/dist/ports/transaction-handler.d.ts.map +1 -1
- package/dist/ports/transaction-handler.js.map +1 -1
- package/dist/ports/transaction-sink.d.ts +6 -5
- package/dist/ports/transaction-sink.d.ts.map +1 -1
- package/dist/ports/transaction-sink.js.map +1 -1
- package/dist/ports/transaction-stream-hub.d.ts +28 -0
- package/dist/ports/transaction-stream-hub.d.ts.map +1 -0
- package/dist/ports/transaction-stream-hub.js +5 -0
- package/dist/ports/transaction-stream-hub.js.map +1 -0
- package/dist/stream/transaction-stream-hub.d.ts +3 -26
- package/dist/stream/transaction-stream-hub.d.ts.map +1 -1
- package/dist/stream/transaction-stream-hub.js +5 -8
- package/dist/stream/transaction-stream-hub.js.map +1 -1
- package/package.json +8 -3
package/README.md
CHANGED
|
@@ -12,9 +12,10 @@ pnpm add @entifix/transactions effect
|
|
|
12
12
|
|
|
13
13
|
## Entry points
|
|
14
14
|
|
|
15
|
-
| Import
|
|
16
|
-
|
|
|
17
|
-
| `@entifix/transactions`
|
|
15
|
+
| Import | What it holds |
|
|
16
|
+
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
17
|
+
| `@entifix/transactions` | Command envelopes, transaction events, inbox / outbox / event-bus / lock / sequence / saga ports, `defineSaga`, the facade use case, `TransactionStreamHubTag` |
|
|
18
|
+
| `@entifix/transactions/engine` | The mechanism behind those ports: `runSaga`, `resumeSaga`, `resumeStaleSagas` / `startSagaResume`, `acceptTransaction` / `completeTransaction`, `makeLocalSagaDispatcher`, the stream hub's factories |
|
|
18
19
|
|
|
19
20
|
---
|
|
20
21
|
|
|
@@ -9,8 +9,7 @@ import { Effect } from 'effect';
|
|
|
9
9
|
*/
|
|
10
10
|
export interface TransactionCommand<TPayload = SerializedEntity> {
|
|
11
11
|
/**
|
|
12
|
-
* Correlates every event and record for this run, and **the client mints it
|
|
13
|
-
* (ADR 0028).
|
|
12
|
+
* Correlates every event and record for this run, and **the client mints it**.
|
|
14
13
|
*
|
|
15
14
|
* It is also the stored entity's id and the idempotency key: re-sending a
|
|
16
15
|
* command with the same id returns the first one's answer instead of writing
|
|
@@ -38,7 +37,7 @@ export interface TransactionCommand<TPayload = SerializedEntity> {
|
|
|
38
37
|
* Optional because the parser produces a command without it and the route
|
|
39
38
|
* fills it in a moment later. A command that reaches the engine still carrying
|
|
40
39
|
* `undefined` emits events that no tenant-scoped stream connection receives —
|
|
41
|
-
* which is the intended direction to fail
|
|
40
|
+
* which is the intended direction to fail.
|
|
42
41
|
*/
|
|
43
42
|
organizationId?: string;
|
|
44
43
|
}
|
|
@@ -1 +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
|
|
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;;;;;;;;OAQG;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"}
|
|
@@ -1 +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
|
|
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 *\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.\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;AAgDhC,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"}
|
|
@@ -24,7 +24,7 @@ export type TransactionStep = 'accepted' | 'completed' | 'failed';
|
|
|
24
24
|
* consumer of these: for a single-step write it dispatches nothing and only
|
|
25
25
|
* records what the events tell it, which is what keeps such a write
|
|
26
26
|
* choreographed. A flow spanning slices is orchestrated instead, from a
|
|
27
|
-
* declarative definition
|
|
27
|
+
* declarative definition, and its coordinator both reads these and
|
|
28
28
|
* issues the next step — but that engine is not built, and single-step writes
|
|
29
29
|
* stay exactly as described here when it is.
|
|
30
30
|
*
|
|
@@ -50,9 +50,9 @@ export interface TransactionEvent {
|
|
|
50
50
|
at: string;
|
|
51
51
|
/**
|
|
52
52
|
* Whose organization this happened in — the per-connection scoping key for
|
|
53
|
-
* the reactive stream
|
|
53
|
+
* the reactive stream.
|
|
54
54
|
*
|
|
55
|
-
* In `data` rather than in `meta`, under
|
|
55
|
+
* In `data` rather than in `meta`, under the envelope's rule: `meta` describes the
|
|
56
56
|
* message, `data` describes the occurrence, and which vendor's catalog a
|
|
57
57
|
* record was written in is a fact about what happened.
|
|
58
58
|
*
|
|
@@ -1 +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
|
|
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, 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.\n *\n * In `data` rather than in `meta`, under the envelope'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"}
|
|
@@ -27,7 +27,7 @@ export interface InboxClaim {
|
|
|
27
27
|
*
|
|
28
28
|
* Never `correlationId`: one transaction emits up to three messages, so
|
|
29
29
|
* keying on the correlation id would make `completed` look like a
|
|
30
|
-
* redelivery of `accepted
|
|
30
|
+
* redelivery of `accepted`.
|
|
31
31
|
*/
|
|
32
32
|
eventId: string;
|
|
33
33
|
/** ISO-8601, for retention — nothing reads it to make a decision. */
|
|
@@ -1 +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
|
|
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`.\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.Service<\n TransactionInboxTag,\n TransactionInbox\n>()('TransactionInboxTag') {}\n"],"names":["Context","TransactionInboxTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AA8E9C,OAAO,MAAMC,4BAA4BD,QAAQE,OAAO,GAGpD;AAAwB"}
|
|
@@ -29,8 +29,7 @@ export interface OutboxEntry {
|
|
|
29
29
|
* The relay drains in order and stops at the first failure, which is what
|
|
30
30
|
* keeps `accepted` ahead of a terminal event — and is also why an entry that
|
|
31
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).
|
|
32
|
+
* the attempts is what turns "retrying" into a state with an end.
|
|
34
33
|
*/
|
|
35
34
|
attempts: number;
|
|
36
35
|
/**
|
|
@@ -51,7 +50,7 @@ export interface OutboxEntry {
|
|
|
51
50
|
* Whether {@link TransactionOutbox.enqueue} actually wrote.
|
|
52
51
|
*
|
|
53
52
|
* `duplicate` is not a failure — it is how a *retry* is recognised. The
|
|
54
|
-
* transaction id is the client's idempotency key
|
|
53
|
+
* transaction id is the client's idempotency key, so a repeated
|
|
55
54
|
* command must return the first one's answer rather than execute twice. The
|
|
56
55
|
* adapter owns the detection because the mechanism is storage-specific (a Mongo
|
|
57
56
|
* `E11000` against the unique index on `eventId`), and translating it here keeps
|
|
@@ -73,8 +72,8 @@ export interface OutboxStats {
|
|
|
73
72
|
* `createdAt` of the oldest such entry, absent when there are none.
|
|
74
73
|
*
|
|
75
74
|
* 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 —
|
|
77
|
-
* gave the relay a ceiling — but a quarantine is reported only as a log line,
|
|
75
|
+
* An entry that can never publish no longer blocks the ones behind it —
|
|
76
|
+
* quarantine gave the relay a ceiling — but a quarantine is reported only as a log line,
|
|
78
77
|
* so *how far behind* the head has fallen is otherwise unanswerable.
|
|
79
78
|
*/
|
|
80
79
|
oldestPendingAt?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outbox.d.ts","sourceRoot":"","sources":["../../src/contracts/outbox.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,gBA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B,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,yBAGf;CAAG"}
|
|
@@ -1 +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
|
|
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 */\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, 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 —\n * quarantine 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.Service<\n TransactionOutboxTag,\n TransactionOutbox\n>()('TransactionOutboxTag') {}\n"],"names":["Context","TransactionOutboxTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AA+I9C,OAAO,MAAMC,6BAA6BD,QAAQE,OAAO,GAGrD;AAAyB"}
|
|
@@ -20,7 +20,7 @@ export interface TransactionRecord {
|
|
|
20
20
|
* The `saga` store is control-plane and single-partition — it holds every
|
|
21
21
|
* organization's records by design — so isolation on the read routes has to be
|
|
22
22
|
* this filter. A record written before the member existed carries none and is
|
|
23
|
-
* therefore readable by nobody, which is the direction to fail
|
|
23
|
+
* therefore readable by nobody, which is the direction to fail.
|
|
24
24
|
*/
|
|
25
25
|
organizationId?: string;
|
|
26
26
|
}
|
|
@@ -39,7 +39,7 @@ export interface TransactionStore {
|
|
|
39
39
|
* How many records sit in each state — the recovery sweep samples it.
|
|
40
40
|
*
|
|
41
41
|
* ⚠️ **This is a count, and is not the `list` above.** It returns no record,
|
|
42
|
-
* no id and no organization, so it does not reopen the surface
|
|
42
|
+
* no id and no organization, so it does not reopen the list surface removed
|
|
43
43
|
* `GET /api/transaction` for: an unfiltered *listing* of this store is every
|
|
44
44
|
* organization's transactions, while a total of how many are `STALE` is a
|
|
45
45
|
* fleet health number that names nobody. The distinction is the whole reason
|
|
@@ -63,8 +63,7 @@ export declare class TransactionStoreTag extends TransactionStoreTag_base {
|
|
|
63
63
|
* entity id, and no code, because the write has not run. Framing it as a record
|
|
64
64
|
* meant the browser's accept-shape assertion was checking a name that the
|
|
65
65
|
* by-id route and the bus payload also answered to, so it asserted nothing it
|
|
66
|
-
* claimed to
|
|
67
|
-
* [ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).
|
|
66
|
+
* claimed to.
|
|
68
67
|
*/
|
|
69
68
|
export interface TransactionAccepted {
|
|
70
69
|
transactionId: string;
|
|
@@ -96,7 +95,7 @@ export declare function readTransactionRecordEnvelope(body: unknown): Effect.Eff
|
|
|
96
95
|
* published and this answers `404`. That is a write in perfect health, and a
|
|
97
96
|
* caller that rolls back on it un-renders a record that is about to appear, at
|
|
98
97
|
* exactly the moment nobody can tell a UI bug from an outage. Only `FAILED` and
|
|
99
|
-
* `STALE` are terminal
|
|
98
|
+
* `STALE` are terminal.
|
|
100
99
|
*/
|
|
101
100
|
export interface TransactionStatusReader {
|
|
102
101
|
read(transactionId: string): Effect.Effect<TransactionRecord | undefined, EntifixError>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"record.d.ts","sourceRoot":"","sources":["../../src/contracts/record.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,YAAY,EACjB,KAAK,QAAQ,EAEd,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEzC,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAErE;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,gBAAgB,CAAC;IACxB,IAAI,CAAC,EAAE,MAAM,CAAC;I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;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAC3C,IAAI,EAAE,OAAO,GACZ,MAAM,CAAC,MAAM,CAAC,iBAAiB,EAAE,YAAY,CAAC,CAShD;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,uBAAuB;IACtC,IAAI,CACF,aAAa,EAAE,MAAM,GACpB,MAAM,CAAC,MAAM,CAAC,iBAAiB,GAAG,SAAS,EAAE,YAAY,CAAC,CAAC;CAC/D;;AAED,qBAAa,0BAA2B,SAAQ,+BAGf;CAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/contracts/record.ts"],"sourcesContent":["import {\n type EntifixConnError,\n type EntifixError,\n type EntityId,\n readEnvelope,\n} from '@entifix/core';\nimport { Context, Effect } from 'effect';\n\nimport type { TransactionEvent, TransactionState } from './event.js';\n\n/**\n * The the saga tracker's persisted view of a transaction, folded from the\n * events it observes. It is the source of truth a client polls.\n */\nexport interface TransactionRecord {\n transactionId: string;\n entity: string;\n state: TransactionState;\n code?: string;\n entityId?: EntityId;\n error?: string;\n createdAt: string;\n updatedAt: string;\n /**\n * Whose organization this transaction happened in, folded from the event.\n *\n * The `saga` store is control-plane and single-partition — it holds every\n * organization's records by design — so isolation on the read routes has to be\n * this filter. A record written before the member existed carries none and is\n * therefore readable by nobody, which is the direction to fail
|
|
1
|
+
{"version":3,"sources":["../../src/contracts/record.ts"],"sourcesContent":["import {\n type EntifixConnError,\n type EntifixError,\n type EntityId,\n readEnvelope,\n} from '@entifix/core';\nimport { Context, Effect } from 'effect';\n\nimport type { TransactionEvent, TransactionState } from './event.js';\n\n/**\n * The the saga tracker's persisted view of a transaction, folded from the\n * events it observes. It is the source of truth a client polls.\n */\nexport interface TransactionRecord {\n transactionId: string;\n entity: string;\n state: TransactionState;\n code?: string;\n entityId?: EntityId;\n error?: string;\n createdAt: string;\n updatedAt: string;\n /**\n * Whose organization this transaction happened in, folded from the event.\n *\n * The `saga` store is control-plane and single-partition — it holds every\n * organization's records by design — so isolation on the read routes has to be\n * this filter. A record written before the member existed carries none and is\n * therefore readable by nobody, which is the direction to fail.\n */\n organizationId?: string;\n}\n\n/**\n * Port the manager tracks transactions through. Implemented over Mongo in the\n * service; framework-free here so the engine/manager stay environment-agnostic.\n */\nexport interface TransactionStore {\n /** Folds an event into the record, creating it on first sight. */\n upsertFromEvent(\n event: TransactionEvent,\n ): Effect.Effect<TransactionRecord, EntifixConnError>;\n get(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, EntifixConnError>;\n // There is deliberately no `list`. The `saga` store is control-plane and\n // single-partition, so an unfiltered index is every organization's\n // transactions — which is why there is no `GET /api/transaction` list.\n // Anything that needs a set of records asks for one narrow enough to scope,\n // the way `findStale` does.\n /** Non-terminal records not updated within `olderThanMs` — recovery input. */\n findStale(\n olderThanMs: number,\n ): Effect.Effect<readonly TransactionRecord[], EntifixConnError>;\n markStale(transactionId: string): Effect.Effect<void, EntifixConnError>;\n /**\n * How many records sit in each state — the recovery sweep samples it.\n *\n * ⚠️ **This is a count, and is not the `list` above.** It returns no record,\n * no id and no organization, so it does not reopen the list surface removed\n * `GET /api/transaction` for: an unfiltered *listing* of this store is every\n * organization's transactions, while a total of how many are `STALE` is a\n * fleet health number that names nobody. The distinction is the whole reason\n * one is here and the other is refused.\n *\n * It exists so `STALE` is something a dashboard shows rather than something a\n * poll discovers — which is what the recovery sweep, whose only action is to\n * apply that label, otherwise leaves entirely unobservable.\n */\n countByState(): Effect.Effect<\n Record<TransactionState, number>,\n EntifixConnError\n >;\n}\n\nexport class TransactionStoreTag extends Context.Service<\n TransactionStoreTag,\n TransactionStore\n>()('TransactionStoreTag') {}\n\n/**\n * What a service answers a `202` with: the id to poll, and the state it starts\n * in.\n *\n * ⚠️ **Not a {@link TransactionRecord}, which is why it has its own\n * discriminant.** Nothing has been folded yet — there is no `createdAt`, no\n * entity id, and no code, because the write has not run. Framing it as a record\n * meant the browser's accept-shape assertion was checking a name that the\n * by-id route and the bus payload also answered to, so it asserted nothing it\n * claimed to.\n */\nexport interface TransactionAccepted {\n transactionId: string;\n state: TransactionState;\n}\n\n/**\n * Parses a `202` accept body, for a browser about to start polling.\n *\n * Read for its **shape**, not its contents: it asserts the service really\n * accepted a transaction rather than answering something else with a `2xx`.\n */\nexport function readTransactionAcceptedEnvelope(\n body: unknown,\n): Effect.Effect<TransactionAccepted, EntifixError> {\n return Effect.map(\n readEnvelope<TransactionAccepted>(\n body,\n 'transactionAccepted',\n 'transactionAccepted',\n ),\n envelope => envelope.data,\n );\n}\n\n/**\n * Parses the tracker's by-id response, which frames a {@link TransactionRecord}.\n *\n * ⚠️ **`readEnvelope` validates the discriminant and then *casts* the payload**\n * — it checks no members. So a discriminant shared by two shapes hands back\n * whichever one the caller asked for, typed and wrong: a record read as an\n * event has no `step`, no `at`, and a `state` the caller is about to branch on.\n * That is the reason the four transaction-shaped discriminants are four.\n */\nexport function readTransactionRecordEnvelope(\n body: unknown,\n): Effect.Effect<TransactionRecord, EntifixError> {\n return Effect.map(\n readEnvelope<TransactionRecord>(\n body,\n 'transactionRecord',\n 'transactionRecord',\n ),\n envelope => envelope.data,\n );\n}\n\n/**\n * Reads one transaction's record, for a browser reconciling a write it started.\n *\n * ⚠️ **`undefined` means _not tracked yet_, not _failed_.** `accepted` reaches\n * the tracker over the bus, so with the broker down the entity write commits —\n * the outbox is in the same Mongo transaction — while no event is ever\n * published and this answers `404`. That is a write in perfect health, and a\n * caller that rolls back on it un-renders a record that is about to appear, at\n * exactly the moment nobody can tell a UI bug from an outage. Only `FAILED` and\n * `STALE` are terminal.\n */\nexport interface TransactionStatusReader {\n read(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, EntifixError>;\n}\n\nexport class TransactionStatusReaderTag extends Context.Service<\n TransactionStatusReaderTag,\n TransactionStatusReader\n>()('TransactionStatusReaderTag') {}\n"],"names":["readEnvelope","Context","Effect","TransactionStoreTag","Service","readTransactionAcceptedEnvelope","body","map","envelope","data","readTransactionRecordEnvelope","TransactionStatusReaderTag"],"mappings":"AAAA,SAIEA,YAAY,QACP,gBAAgB;AACvB,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AAsEzC,OAAO,MAAMC,4BAA4BF,QAAQG,OAAO,GAGpD;AAAwB;AAkB5B;;;;;CAKC,GACD,OAAO,SAASC,gCACdC,IAAa;IAEb,OAAOJ,OAAOK,GAAG,CACfP,aACEM,MACA,uBACA,wBAEFE,CAAAA,WAAYA,SAASC,IAAI;AAE7B;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASC,8BACdJ,IAAa;IAEb,OAAOJ,OAAOK,GAAG,CACfP,aACEM,MACA,qBACA,sBAEFE,CAAAA,WAAYA,SAASC,IAAI;AAE7B;AAmBA,OAAO,MAAME,mCAAmCV,QAAQG,OAAO,GAG3D;AAA+B"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Richardson's classification, and adopting the vocabulary is most of the answer
|
|
3
|
-
* to "which steps are compensable at all"
|
|
4
|
-
* ([ADR 0039](../../../../../../docs/adr/0039-multi-step-sagas-are-orchestrated.md)).
|
|
3
|
+
* to "which steps are compensable at all".
|
|
5
4
|
*
|
|
6
5
|
* - `compensatable` — before the point of no return; a failure downstream
|
|
7
6
|
* reverses it.
|
|
@@ -20,9 +19,9 @@ export type SagaMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
|
20
19
|
*
|
|
21
20
|
* ⚠️ **A template rather than a callback, and that is the constraint that
|
|
22
21
|
* shaped the whole type.** A callback would have to name the participant's
|
|
23
|
-
* types, and
|
|
24
|
-
*
|
|
25
|
-
*
|
|
22
|
+
* types, and one domain package may not import another — which is exactly the
|
|
23
|
+
* import that has no legal home and the reason a definition is **data** in the
|
|
24
|
+
* first place.
|
|
26
25
|
*/
|
|
27
26
|
export interface SagaCall {
|
|
28
27
|
readonly method: SagaMethod;
|
|
@@ -38,8 +37,7 @@ export interface SagaStep {
|
|
|
38
37
|
* A URI in a definition is a deployment fact written into a business
|
|
39
38
|
* artifact, and it is what makes a definition untestable and un-relocatable.
|
|
40
39
|
* The same lookup yields the crossing token for that participant, so a
|
|
41
|
-
* definition carries no secret and never could
|
|
42
|
-
* ([ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md)).
|
|
40
|
+
* definition carries no secret and never could.
|
|
43
41
|
*/
|
|
44
42
|
readonly participant: string;
|
|
45
43
|
readonly command: SagaCall;
|
|
@@ -52,8 +50,8 @@ export interface SagaStep {
|
|
|
52
50
|
* ⚠️ **Cardinality is data, because it has to be.** Checkout reserves once per
|
|
53
51
|
* vendor and how many vendors is known only from the cart, so writing that as
|
|
54
52
|
* N steps would mean generating a definition per request — at which point it
|
|
55
|
-
* is no longer data, and
|
|
56
|
-
*
|
|
53
|
+
* is no longer data, and the whole construction collapses back into the class
|
|
54
|
+
* that has no legal home.
|
|
57
55
|
*
|
|
58
56
|
* The consequence carried by {@link SagaStepOutcome}: **the unit of
|
|
59
57
|
* compensation is the call, not the step.** Five lines with three holds taken
|
|
@@ -69,7 +67,7 @@ export interface SagaStep {
|
|
|
69
67
|
* call per hold, addressed by the reservation id — which stock-service mints,
|
|
70
68
|
* so the caller cannot know it when it starts the flow. Supplying the ids as
|
|
71
69
|
* input is impossible, and generating a definition per request is the thing
|
|
72
|
-
*
|
|
70
|
+
* a definition-as-data exists to avoid.
|
|
73
71
|
*
|
|
74
72
|
* Each element inherits that call's `organizationId`, so a tenant-plane
|
|
75
73
|
* participant reaches the same tenant it did the first time, and the `path`
|
|
@@ -116,8 +114,7 @@ export interface SagaCallOutcome {
|
|
|
116
114
|
* `x-organization-id`, so a compensation dispatched without it is refused
|
|
117
115
|
* `400` — and the saga strands with every hold still in place while the
|
|
118
116
|
* engine reports it tried. Measured on the live lab: two holds taken, a third
|
|
119
|
-
* line refused, and both releases rejected for a missing header
|
|
120
|
-
* ([ADR 0023](../../../../../../docs/adr/0023-service-to-service-tenant-crossing.md)).
|
|
117
|
+
* line refused, and both releases rejected for a missing header.
|
|
121
118
|
*/
|
|
122
119
|
readonly organizationId?: string;
|
|
123
120
|
}
|
|
@@ -128,7 +125,7 @@ export interface SagaCallOutcome {
|
|
|
128
125
|
export interface SagaStepInput {
|
|
129
126
|
/** The body to send. */
|
|
130
127
|
readonly body?: unknown;
|
|
131
|
-
/**
|
|
128
|
+
/** The explicit organization, for a tenant-plane participant. */
|
|
132
129
|
readonly organizationId?: string;
|
|
133
130
|
}
|
|
134
131
|
/**
|
|
@@ -136,8 +133,7 @@ export interface SagaStepInput {
|
|
|
136
133
|
*
|
|
137
134
|
* ⚠️ **Here rather than in the engine**, because the durable instance carries
|
|
138
135
|
* it: a resumed walk is a different process reading this off the store, so the
|
|
139
|
-
* port that persists it may not reach up into the engine to name its type
|
|
140
|
-
* ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).
|
|
136
|
+
* port that persists it may not reach up into the engine to name its type.
|
|
141
137
|
*/
|
|
142
138
|
export type SagaInputs = Readonly<Record<string, readonly SagaStepInput[]>>;
|
|
143
139
|
/** Every call one step made, in dispatch order. */
|
|
@@ -151,8 +147,7 @@ export interface SagaStepOutcome {
|
|
|
151
147
|
* one.** `calls` holds what succeeded either way, so the two are
|
|
152
148
|
* indistinguishable on the stored document, and the distinction is what
|
|
153
149
|
* decides whether the pivot committed. Guessing it either compensates behind
|
|
154
|
-
* a capture or walks past a refusal
|
|
155
|
-
* ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).
|
|
150
|
+
* a capture or walks past a refusal.
|
|
156
151
|
*/
|
|
157
152
|
readonly error?: string;
|
|
158
153
|
/**
|
|
@@ -168,8 +163,8 @@ export interface SagaStepOutcome {
|
|
|
168
163
|
* Validate a definition and return it, or throw.
|
|
169
164
|
*
|
|
170
165
|
* ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path
|
|
171
|
-
* is a fault that ships — the same reasoning
|
|
172
|
-
*
|
|
166
|
+
* is a fault that ships — the same reasoning that makes an unrenderable action
|
|
167
|
+
* cell throw at render. Every definition is therefore constructed through this
|
|
173
168
|
* function at module scope, and loaded in a spec: a definition that never loads
|
|
174
169
|
* is a definition that never fails.
|
|
175
170
|
*/
|
|
@@ -178,7 +173,7 @@ export declare function defineSaga(definition: SagaDefinition): SagaDefinition;
|
|
|
178
173
|
* The command id one call is dispatched under.
|
|
179
174
|
*
|
|
180
175
|
* `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,
|
|
181
|
-
* so
|
|
176
|
+
* so the `TransactionInbox` serves saga steps with no second dedup store and
|
|
182
177
|
* no second key. A fan-out step appends the element index, because its calls are
|
|
183
178
|
* separate side effects that must each be claimed on their own.
|
|
184
179
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"saga-definition.d.ts","sourceRoot":"","sources":["../../src/contracts/saga-definition.ts"],"names":[],"mappings":"AAEA
|
|
1
|
+
{"version":3,"file":"saga-definition.d.ts","sourceRoot":"","sources":["../../src/contracts/saga-definition.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AACH,MAAM,MAAM,YAAY,GAAG,eAAe,GAAG,OAAO,GAAG,WAAW,CAAC;AAEnE,oDAAoD;AACpD,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAC;AAErE;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,QAAQ;IACvB,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAED,0BAA0B;AAC1B,MAAM,WAAW,QAAQ;IACvB,gFAAgF;IAChF,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB;;;;;;;OAOG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC;IAC3B,yEAAyE;IACzE,QAAQ,CAA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MG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;CAChC;AAUD;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,UAAU,EAAE,cAAc,GAAG,cAAc,CAoGrE;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa,GACxB,QAAQ,MAAM,EACd,QAAQ,MAAM,EACd,QAAQ,MAAM,KACb,MAGyC,CAAC"}
|
|
@@ -8,8 +8,8 @@ const fail = (definition, detail)=>{
|
|
|
8
8
|
* Validate a definition and return it, or throw.
|
|
9
9
|
*
|
|
10
10
|
* ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path
|
|
11
|
-
* is a fault that ships — the same reasoning
|
|
12
|
-
*
|
|
11
|
+
* is a fault that ships — the same reasoning that makes an unrenderable action
|
|
12
|
+
* cell throw at render. Every definition is therefore constructed through this
|
|
13
13
|
* function at module scope, and loaded in a spec: a definition that never loads
|
|
14
14
|
* is a definition that never fails.
|
|
15
15
|
*/ export function defineSaga(definition) {
|
|
@@ -41,14 +41,14 @@ const fail = (definition, detail)=>{
|
|
|
41
41
|
const pivots = steps.filter((step)=>step.kind === 'pivot');
|
|
42
42
|
if (pivots.length > 1) {
|
|
43
43
|
// A flow with two points of no return is a flow that has not been designed
|
|
44
|
-
// yet, and the engine says so out loud
|
|
44
|
+
// yet, and the engine says so out loud.
|
|
45
45
|
fail(name, `it declares ${String(pivots.length)} pivots (${pivots.map((step)=>step.id).join(', ')}); a flow has at most one point of no return`);
|
|
46
46
|
}
|
|
47
47
|
// ⚠️ **Zero pivots is legal**, and checkout is the case that forced saying so.
|
|
48
48
|
// Payment capture is M4; until it lands every step of checkout reverses. A
|
|
49
49
|
// validator demanding exactly one would push the order write into a role it
|
|
50
50
|
// would have to be removed from later — a wrong answer that passes
|
|
51
|
-
|
|
51
|
+
//. A definition with no pivot means the whole saga can be unwound,
|
|
52
52
|
// which is a stronger property than a pivot rather than a missing one.
|
|
53
53
|
const pivot = pivots[0];
|
|
54
54
|
const pivotAt = pivot ? steps.indexOf(pivot) : -1;
|
|
@@ -71,7 +71,7 @@ const fail = (definition, detail)=>{
|
|
|
71
71
|
if (step.compensation) {
|
|
72
72
|
// Not dead code — a *false assurance*. Such a compensation could
|
|
73
73
|
// never run, so writing one says the step is reversible when it is
|
|
74
|
-
// not
|
|
74
|
+
// not.
|
|
75
75
|
fail(name, `step '${step.id}' is ${step.kind} and declares a compensation, ` + 'which could never run');
|
|
76
76
|
}
|
|
77
77
|
if (step.kind === 'retriable' && !afterPivot(index)) {
|
|
@@ -87,7 +87,7 @@ const fail = (definition, detail)=>{
|
|
|
87
87
|
* The command id one call is dispatched under.
|
|
88
88
|
*
|
|
89
89
|
* `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,
|
|
90
|
-
* so
|
|
90
|
+
* so the `TransactionInbox` serves saga steps with no second dedup store and
|
|
91
91
|
* no second key. A fan-out step appends the element index, because its calls are
|
|
92
92
|
* separate side effects that must each be claimed on their own.
|
|
93
93
|
*/ export const sagaCommandId = (sagaId, stepId, index)=>index === undefined ? `${sagaId}:${stepId}` : `${sagaId}:${stepId}:${String(index)}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/contracts/saga-definition.ts"],"sourcesContent":["import { EntifixLogicError } from '@entifix/core';\n\n/**\n * Richardson's classification, and adopting the vocabulary is most of the answer\n * to \"which steps are compensable at all\"\n * ([ADR 0039](../../../../../../docs/adr/0039-multi-step-sagas-are-orchestrated.md)).\n *\n * - `compensatable` — before the point of no return; a failure downstream\n * reverses it.\n * - `pivot` — the point of no return. Once it commits, the saga goes forward.\n * - `retriable` — after the pivot; no compensation exists, so the only path is\n * to retry until it succeeds.\n */\nexport type SagaStepKind = 'compensatable' | 'pivot' | 'retriable';\n\n/** The HTTP verbs a step may be dispatched with. */\nexport type SagaMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * One call a step makes, as a template rather than a closure.\n *\n * `path` may carry `{…}` placeholders resolved by field path against the step's\n * recorded outcome — `/api/reservation/{outcome.data.id}`.\n *\n * ⚠️ **A template rather than a callback, and that is the constraint that\n * shaped the whole type.** A callback would have to name the participant's\n * types, and a `business:domain` package may not import another\n * (`docs/_shared/layering.md`) — which is exactly the import that has no legal\n * home and the reason ADR 0039 made a definition **data** in the first place.\n */\nexport interface SagaCall {\n readonly method: SagaMethod;\n readonly path: string;\n}\n\n/** One step of a flow. */\nexport interface SagaStep {\n /** Unique within the definition; half of the command id `<sagaId>:<stepId>`. */\n readonly id: string;\n /**\n * Which service answers it, as a **configuration key** — never a URI.\n *\n * A URI in a definition is a deployment fact written into a business\n * artifact, and it is what makes a definition untestable and un-relocatable.\n * The same lookup yields the crossing token for that participant, so a\n * definition carries no secret and never could\n * ([ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md)).\n */\n readonly participant: string;\n readonly command: SagaCall;\n /** Required on a `compensatable` step, forbidden on every other kind. */\n readonly compensation?: SagaCall;\n readonly kind: SagaStepKind;\n /**\n * Dispatch one call per element of this step's input, rather than one call.\n *\n * ⚠️ **Cardinality is data, because it has to be.** Checkout reserves once per\n * vendor and how many vendors is known only from the cart, so writing that as\n * N steps would mean generating a definition per request — at which point it\n * is no longer data, and ADR 0039's whole construction collapses back into the\n * class that has no legal home.\n *\n * The consequence carried by {@link SagaStepOutcome}: **the unit of\n * compensation is the call, not the step.** Five lines with three holds taken\n * and the fourth refused must release exactly three.\n */\n readonly fanOut?: boolean;\n /**\n * Fan out over an **earlier step's successful calls** instead of over an\n * input the caller supplied.\n *\n * ⚠️ **Without this a later step cannot address what an earlier one created**,\n * and checkout is the case that proves it. `convert-reservation` needs one\n * call per hold, addressed by the reservation id — which stock-service mints,\n * so the caller cannot know it when it starts the flow. Supplying the ids as\n * input is impossible, and generating a definition per request is the thing\n * ADR 0039 exists to avoid.\n *\n * Each element inherits that call's `organizationId`, so a tenant-plane\n * participant reaches the same tenant it did the first time, and the `path`\n * template resolves against `{outcome.…}` — the same scope a compensation\n * gets, for the same reason: the id being addressed is in the response body.\n *\n * Implies {@link fanOut}. It names a step that must appear **before** this one,\n * and `defineSaga` refuses a forward or self reference at module load.\n */\n readonly fanOutFrom?: string;\n}\n\n/** A flow, as the data a generic engine walks. */\nexport interface SagaDefinition {\n readonly name: string;\n /**\n * What a caller must hold to run this flow, as a `<domain>:<entity>:<action>`\n * string.\n *\n * ⚠️ **On the definition rather than on the route**, so the route that runs a\n * flow stays generic. The alternative was one permission for every saga, which\n * would make \"may run a flow\" a single capability regardless of what the flow\n * does — and checkout writes an order.\n *\n * It is a plain string here rather than authz's `Permission`: this package is\n * T2, and `@entifix/authz` sits above it at T4. The service that\n * mounts the route resolves the string against\n * `SERVICE_CROSSING_PERMISSIONS`, which is where the closed list belongs.\n */\n readonly permission: string;\n readonly steps: readonly SagaStep[];\n}\n\n/** What one dispatched call returned, kept so its compensation can read it. */\nexport interface SagaCallOutcome {\n /** The fan-out element this call was made for; `0` on a single-call step. */\n readonly index: number;\n readonly status: number;\n readonly body: unknown;\n /**\n * The organization this call acted for, carried so its compensation acts on\n * the same one.\n *\n * ⚠️ **Not derivable from the outcome, and its absence is silent.** A\n * tenant-plane participant resolves its storage handle from\n * `x-organization-id`, so a compensation dispatched without it is refused\n * `400` — and the saga strands with every hold still in place while the\n * engine reports it tried. Measured on the live lab: two holds taken, a third\n * line refused, and both releases rejected for a missing header\n * ([ADR 0023](../../../../../../docs/adr/0023-service-to-service-tenant-crossing.md)).\n */\n readonly organizationId?: string;\n}\n\n/**\n * What one step is given to work with — one element per call on a `fanOut` step,\n * exactly one otherwise.\n */\nexport interface SagaStepInput {\n /** The body to send. */\n readonly body?: unknown;\n /** ADR 0023's explicit organization, for a tenant-plane participant. */\n readonly organizationId?: string;\n}\n\n/**\n * The inputs each step needs, keyed by step id, supplied by the caller.\n *\n * ⚠️ **Here rather than in the engine**, because the durable instance carries\n * it: a resumed walk is a different process reading this off the store, so the\n * port that persists it may not reach up into the engine to name its type\n * ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).\n */\nexport type SagaInputs = Readonly<Record<string, readonly SagaStepInput[]>>;\n\n/** Every call one step made, in dispatch order. */\nexport interface SagaStepOutcome {\n readonly stepId: string;\n readonly calls: readonly SagaCallOutcome[];\n /**\n * Why this step stopped, when it did — absent on a step that succeeded.\n *\n * ⚠️ **Without it a resumed walk cannot tell a finished step from a refused\n * one.** `calls` holds what succeeded either way, so the two are\n * indistinguishable on the stored document, and the distinction is what\n * decides whether the pivot committed. Guessing it either compensates behind\n * a capture or walks past a refusal\n * ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).\n */\n readonly error?: string;\n /**\n * Whether this step's calls have already been given back.\n *\n * ⚠️ **What keeps a resumed unwind from compensating twice.** A second\n * `DELETE` of an order already deleted answers `404`, which the dispatcher\n * classifies as a refusal, which strands a flow that was in fact reversed.\n */\n readonly compensated?: boolean;\n}\n\nconst fail = (definition: string, detail: string): never => {\n throw new EntifixLogicError(\n `saga definition '${definition}' is invalid: ${detail}`,\n undefined,\n { definition },\n );\n};\n\n/**\n * Validate a definition and return it, or throw.\n *\n * ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path\n * is a fault that ships — the same reasoning ADR 0035 used for `collection` +\n * `determining`. Every definition is therefore constructed through this\n * function at module scope, and loaded in a spec: a definition that never loads\n * is a definition that never fails.\n */\nexport function defineSaga(definition: SagaDefinition): SagaDefinition {\n const { name, steps } = definition;\n\n if (steps.length === 0) {\n fail(name, 'it declares no steps');\n }\n\n const seen = new Set<string>();\n for (const step of steps) {\n if (seen.has(step.id)) {\n // The command id is `<sagaId>:<stepId>`, so a duplicate id is two steps\n // sharing one idempotency key — the second would be dropped as a\n // redelivery of the first and never run at all.\n fail(name, `two steps share the id '${step.id}'`);\n }\n seen.add(step.id);\n }\n\n // `fanOutFrom` must name a step that has already run, or the outcomes it fans\n // out over do not exist yet. A forward reference would silently produce zero\n // calls — a step that looks like it ran and did nothing, which is exactly how\n // a conversion gets skipped while a saga reports COMPLETED.\n const before = new Set<string>();\n for (const step of steps) {\n if (step.fanOutFrom !== undefined && !before.has(step.fanOutFrom)) {\n fail(\n name,\n `step '${step.id}' fans out from '${step.fanOutFrom}', which is not a ` +\n 'step before it',\n );\n }\n before.add(step.id);\n }\n\n const pivots = steps.filter(step => step.kind === 'pivot');\n if (pivots.length > 1) {\n // A flow with two points of no return is a flow that has not been designed\n // yet, and the engine says so out loud (ADR 0039).\n fail(\n name,\n `it declares ${String(pivots.length)} pivots (${pivots\n .map(step => step.id)\n .join(', ')}); a flow has at most one point of no return`,\n );\n }\n\n // ⚠️ **Zero pivots is legal**, and checkout is the case that forced saying so.\n // Payment capture is M4; until it lands every step of checkout reverses. A\n // validator demanding exactly one would push the order write into a role it\n // would have to be removed from later — a wrong answer that passes\n // (ADR 0052). A definition with no pivot means the whole saga can be unwound,\n // which is a stronger property than a pivot rather than a missing one.\n const pivot = pivots[0];\n const pivotAt = pivot ? steps.indexOf(pivot) : -1;\n const afterPivot = (index: number) => pivot !== undefined && index > pivotAt;\n\n for (const [index, step] of steps.entries()) {\n switch (step.kind) {\n case 'compensatable': {\n if (afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is compensatable but sits after the pivot ` +\n `'${String(pivot?.id)}', where nothing can be reversed`,\n );\n }\n if (!step.compensation) {\n fail(\n name,\n `step '${step.id}' is compensatable but declares no compensation`,\n );\n }\n break;\n }\n case 'pivot':\n case 'retriable': {\n if (step.compensation) {\n // Not dead code — a *false assurance*. Such a compensation could\n // never run, so writing one says the step is reversible when it is\n // not (ADR 0039).\n fail(\n name,\n `step '${step.id}' is ${step.kind} and declares a compensation, ` +\n 'which could never run',\n );\n }\n if (step.kind === 'retriable' && !afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is retriable but sits before the pivot; a step ` +\n 'that cannot be reversed must not run while the saga can still ' +\n 'be unwound',\n );\n }\n break;\n }\n }\n }\n\n return definition;\n}\n\n/**\n * The command id one call is dispatched under.\n *\n * `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,\n * so #178's `TransactionInbox` serves saga steps with no second dedup store and\n * no second key. A fan-out step appends the element index, because its calls are\n * separate side effects that must each be claimed on their own.\n */\nexport const sagaCommandId = (\n sagaId: string,\n stepId: string,\n index?: number,\n): string =>\n index === undefined\n ? `${sagaId}:${stepId}`\n : `${sagaId}:${stepId}:${String(index)}`;\n"],"names":["EntifixLogicError","fail","definition","detail","undefined","defineSaga","name","steps","length","seen","Set","step","has","id","add","before","fanOutFrom","pivots","filter","kind","String","map","join","pivot","pivotAt","indexOf","afterPivot","index","entries","compensation","sagaCommandId","sagaId","stepId"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,gBAAgB;AAiLlD,MAAMC,OAAO,CAACC,YAAoBC;IAChC,MAAM,IAAIH,kBACR,CAAC,iBAAiB,EAAEE,WAAW,cAAc,EAAEC,QAAQ,EACvDC,WACA;QAAEF;IAAW;AAEjB;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASG,WAAWH,UAA0B;IACnD,MAAM,EAAEI,IAAI,EAAEC,KAAK,EAAE,GAAGL;IAExB,IAAIK,MAAMC,MAAM,KAAK,GAAG;QACtBP,KAAKK,MAAM;IACb;IAEA,MAAMG,OAAO,IAAIC;IACjB,KAAK,MAAMC,QAAQJ,MAAO;QACxB,IAAIE,KAAKG,GAAG,CAACD,KAAKE,EAAE,GAAG;YACrB,wEAAwE;YACxE,iEAAiE;YACjE,gDAAgD;YAChDZ,KAAKK,MAAM,CAAC,wBAAwB,EAAEK,KAAKE,EAAE,CAAC,CAAC,CAAC;QAClD;QACAJ,KAAKK,GAAG,CAACH,KAAKE,EAAE;IAClB;IAEA,8EAA8E;IAC9E,6EAA6E;IAC7E,8EAA8E;IAC9E,4DAA4D;IAC5D,MAAME,SAAS,IAAIL;IACnB,KAAK,MAAMC,QAAQJ,MAAO;QACxB,IAAII,KAAKK,UAAU,KAAKZ,aAAa,CAACW,OAAOH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F,KAAKkB,YAAY,EAAE;wBACrB,iEAAiE;wBACjE,mEAAmE;wBACnE,kBAAkB;wBAClB5B,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,KAAK,EAAEF,KAAKQ,IAAI,CAAC,8BAA8B,CAAC,GAC/D;oBAEN;oBACA,IAAIR,KAAKQ,IAAI,KAAK,eAAe,CAACO,WAAWC,QAAQ;wBACnD1B,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,iDAAiD,CAAC,GACjE,mEACA;oBAEN;oBACA;gBACF;QACF;IACF;IAEA,OAAOX;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,MAAM4B,gBAAgB,CAC3BC,QACAC,QACAL,QAEAA,UAAUvB,YACN,GAAG2B,OAAO,CAAC,EAAEC,QAAQ,GACrB,GAAGD,OAAO,CAAC,EAAEC,OAAO,CAAC,EAAEZ,OAAOO,QAAQ,CAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/contracts/saga-definition.ts"],"sourcesContent":["import { EntifixLogicError } from '@entifix/core';\n\n/**\n * Richardson's classification, and adopting the vocabulary is most of the answer\n * to \"which steps are compensable at all\".\n *\n * - `compensatable` — before the point of no return; a failure downstream\n * reverses it.\n * - `pivot` — the point of no return. Once it commits, the saga goes forward.\n * - `retriable` — after the pivot; no compensation exists, so the only path is\n * to retry until it succeeds.\n */\nexport type SagaStepKind = 'compensatable' | 'pivot' | 'retriable';\n\n/** The HTTP verbs a step may be dispatched with. */\nexport type SagaMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * One call a step makes, as a template rather than a closure.\n *\n * `path` may carry `{…}` placeholders resolved by field path against the step's\n * recorded outcome — `/api/reservation/{outcome.data.id}`.\n *\n * ⚠️ **A template rather than a callback, and that is the constraint that\n * shaped the whole type.** A callback would have to name the participant's\n * types, and one domain package may not import another — which is exactly the\n * import that has no legal home and the reason a definition is **data** in the\n * first place.\n */\nexport interface SagaCall {\n readonly method: SagaMethod;\n readonly path: string;\n}\n\n/** One step of a flow. */\nexport interface SagaStep {\n /** Unique within the definition; half of the command id `<sagaId>:<stepId>`. */\n readonly id: string;\n /**\n * Which service answers it, as a **configuration key** — never a URI.\n *\n * A URI in a definition is a deployment fact written into a business\n * artifact, and it is what makes a definition untestable and un-relocatable.\n * The same lookup yields the crossing token for that participant, so a\n * definition carries no secret and never could.\n */\n readonly participant: string;\n readonly command: SagaCall;\n /** Required on a `compensatable` step, forbidden on every other kind. */\n readonly compensation?: SagaCall;\n readonly kind: SagaStepKind;\n /**\n * Dispatch one call per element of this step's input, rather than one call.\n *\n * ⚠️ **Cardinality is data, because it has to be.** Checkout reserves once per\n * vendor and how many vendors is known only from the cart, so writing that as\n * N steps would mean generating a definition per request — at which point it\n * is no longer data, and the whole construction collapses back into the class\n * that has no legal home.\n *\n * The consequence carried by {@link SagaStepOutcome}: **the unit of\n * compensation is the call, not the step.** Five lines with three holds taken\n * and the fourth refused must release exactly three.\n */\n readonly fanOut?: boolean;\n /**\n * Fan out over an **earlier step's successful calls** instead of over an\n * input the caller supplied.\n *\n * ⚠️ **Without this a later step cannot address what an earlier one created**,\n * and checkout is the case that proves it. `convert-reservation` needs one\n * call per hold, addressed by the reservation id — which stock-service mints,\n * so the caller cannot know it when it starts the flow. Supplying the ids as\n * input is impossible, and generating a definition per request is the thing\n * a definition-as-data exists to avoid.\n *\n * Each element inherits that call's `organizationId`, so a tenant-plane\n * participant reaches the same tenant it did the first time, and the `path`\n * template resolves against `{outcome.…}` — the same scope a compensation\n * gets, for the same reason: the id being addressed is in the response body.\n *\n * Implies {@link fanOut}. It names a step that must appear **before** this one,\n * and `defineSaga` refuses a forward or self reference at module load.\n */\n readonly fanOutFrom?: string;\n}\n\n/** A flow, as the data a generic engine walks. */\nexport interface SagaDefinition {\n readonly name: string;\n /**\n * What a caller must hold to run this flow, as a `<domain>:<entity>:<action>`\n * string.\n *\n * ⚠️ **On the definition rather than on the route**, so the route that runs a\n * flow stays generic. The alternative was one permission for every saga, which\n * would make \"may run a flow\" a single capability regardless of what the flow\n * does — and checkout writes an order.\n *\n * It is a plain string here rather than authz's `Permission`: this package is\n * T2, and `@entifix/authz` sits above it at T4. The service that\n * mounts the route resolves the string against\n * `SERVICE_CROSSING_PERMISSIONS`, which is where the closed list belongs.\n */\n readonly permission: string;\n readonly steps: readonly SagaStep[];\n}\n\n/** What one dispatched call returned, kept so its compensation can read it. */\nexport interface SagaCallOutcome {\n /** The fan-out element this call was made for; `0` on a single-call step. */\n readonly index: number;\n readonly status: number;\n readonly body: unknown;\n /**\n * The organization this call acted for, carried so its compensation acts on\n * the same one.\n *\n * ⚠️ **Not derivable from the outcome, and its absence is silent.** A\n * tenant-plane participant resolves its storage handle from\n * `x-organization-id`, so a compensation dispatched without it is refused\n * `400` — and the saga strands with every hold still in place while the\n * engine reports it tried. Measured on the live lab: two holds taken, a third\n * line refused, and both releases rejected for a missing header.\n */\n readonly organizationId?: string;\n}\n\n/**\n * What one step is given to work with — one element per call on a `fanOut` step,\n * exactly one otherwise.\n */\nexport interface SagaStepInput {\n /** The body to send. */\n readonly body?: unknown;\n /** The explicit organization, for a tenant-plane participant. */\n readonly organizationId?: string;\n}\n\n/**\n * The inputs each step needs, keyed by step id, supplied by the caller.\n *\n * ⚠️ **Here rather than in the engine**, because the durable instance carries\n * it: a resumed walk is a different process reading this off the store, so the\n * port that persists it may not reach up into the engine to name its type.\n */\nexport type SagaInputs = Readonly<Record<string, readonly SagaStepInput[]>>;\n\n/** Every call one step made, in dispatch order. */\nexport interface SagaStepOutcome {\n readonly stepId: string;\n readonly calls: readonly SagaCallOutcome[];\n /**\n * Why this step stopped, when it did — absent on a step that succeeded.\n *\n * ⚠️ **Without it a resumed walk cannot tell a finished step from a refused\n * one.** `calls` holds what succeeded either way, so the two are\n * indistinguishable on the stored document, and the distinction is what\n * decides whether the pivot committed. Guessing it either compensates behind\n * a capture or walks past a refusal.\n */\n readonly error?: string;\n /**\n * Whether this step's calls have already been given back.\n *\n * ⚠️ **What keeps a resumed unwind from compensating twice.** A second\n * `DELETE` of an order already deleted answers `404`, which the dispatcher\n * classifies as a refusal, which strands a flow that was in fact reversed.\n */\n readonly compensated?: boolean;\n}\n\nconst fail = (definition: string, detail: string): never => {\n throw new EntifixLogicError(\n `saga definition '${definition}' is invalid: ${detail}`,\n undefined,\n { definition },\n );\n};\n\n/**\n * Validate a definition and return it, or throw.\n *\n * ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path\n * is a fault that ships — the same reasoning that makes an unrenderable action\n * cell throw at render. Every definition is therefore constructed through this\n * function at module scope, and loaded in a spec: a definition that never loads\n * is a definition that never fails.\n */\nexport function defineSaga(definition: SagaDefinition): SagaDefinition {\n const { name, steps } = definition;\n\n if (steps.length === 0) {\n fail(name, 'it declares no steps');\n }\n\n const seen = new Set<string>();\n for (const step of steps) {\n if (seen.has(step.id)) {\n // The command id is `<sagaId>:<stepId>`, so a duplicate id is two steps\n // sharing one idempotency key — the second would be dropped as a\n // redelivery of the first and never run at all.\n fail(name, `two steps share the id '${step.id}'`);\n }\n seen.add(step.id);\n }\n\n // `fanOutFrom` must name a step that has already run, or the outcomes it fans\n // out over do not exist yet. A forward reference would silently produce zero\n // calls — a step that looks like it ran and did nothing, which is exactly how\n // a conversion gets skipped while a saga reports COMPLETED.\n const before = new Set<string>();\n for (const step of steps) {\n if (step.fanOutFrom !== undefined && !before.has(step.fanOutFrom)) {\n fail(\n name,\n `step '${step.id}' fans out from '${step.fanOutFrom}', which is not a ` +\n 'step before it',\n );\n }\n before.add(step.id);\n }\n\n const pivots = steps.filter(step => step.kind === 'pivot');\n if (pivots.length > 1) {\n // A flow with two points of no return is a flow that has not been designed\n // yet, and the engine says so out loud.\n fail(\n name,\n `it declares ${String(pivots.length)} pivots (${pivots\n .map(step => step.id)\n .join(', ')}); a flow has at most one point of no return`,\n );\n }\n\n // ⚠️ **Zero pivots is legal**, and checkout is the case that forced saying so.\n // Payment capture is M4; until it lands every step of checkout reverses. A\n // validator demanding exactly one would push the order write into a role it\n // would have to be removed from later — a wrong answer that passes\n //. A definition with no pivot means the whole saga can be unwound,\n // which is a stronger property than a pivot rather than a missing one.\n const pivot = pivots[0];\n const pivotAt = pivot ? steps.indexOf(pivot) : -1;\n const afterPivot = (index: number) => pivot !== undefined && index > pivotAt;\n\n for (const [index, step] of steps.entries()) {\n switch (step.kind) {\n case 'compensatable': {\n if (afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is compensatable but sits after the pivot ` +\n `'${String(pivot?.id)}', where nothing can be reversed`,\n );\n }\n if (!step.compensation) {\n fail(\n name,\n `step '${step.id}' is compensatable but declares no compensation`,\n );\n }\n break;\n }\n case 'pivot':\n case 'retriable': {\n if (step.compensation) {\n // Not dead code — a *false assurance*. Such a compensation could\n // never run, so writing one says the step is reversible when it is\n // not.\n fail(\n name,\n `step '${step.id}' is ${step.kind} and declares a compensation, ` +\n 'which could never run',\n );\n }\n if (step.kind === 'retriable' && !afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is retriable but sits before the pivot; a step ` +\n 'that cannot be reversed must not run while the saga can still ' +\n 'be unwound',\n );\n }\n break;\n }\n }\n }\n\n return definition;\n}\n\n/**\n * The command id one call is dispatched under.\n *\n * `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,\n * so the `TransactionInbox` serves saga steps with no second dedup store and\n * no second key. A fan-out step appends the element index, because its calls are\n * separate side effects that must each be claimed on their own.\n */\nexport const sagaCommandId = (\n sagaId: string,\n stepId: string,\n index?: number,\n): string =>\n index === undefined\n ? `${sagaId}:${stepId}`\n : `${sagaId}:${stepId}:${String(index)}`;\n"],"names":["EntifixLogicError","fail","definition","detail","undefined","defineSaga","name","steps","length","seen","Set","step","has","id","add","before","fanOutFrom","pivots","filter","kind","String","map","join","pivot","pivotAt","indexOf","afterPivot","index","entries","compensation","sagaCommandId","sagaId","stepId"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,gBAAgB;AA4KlD,MAAMC,OAAO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AAEC,QAAQ,GACrB,GAAGD,OAAO,CAAC,EAAEC,OAAO,CAAC,EAAEZ,OAAOO,QAAQ,CAAC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The mechanism behind `@entifix/transactions`' ports: the saga runner and its
|
|
3
|
+
* resume sweep, the single-step transaction engine, the in-process dispatcher
|
|
4
|
+
* and the stream hub.
|
|
5
|
+
*
|
|
6
|
+
* A subpath rather than part of `.` although it installs nothing `.` does not,
|
|
7
|
+
* because a consumer that writes against the contracts — a cell, a route, a
|
|
8
|
+
* participant — must be able to ban the engine by name, and a ban matches a
|
|
9
|
+
* specifier (ADR 0006).
|
|
10
|
+
*/
|
|
11
|
+
export * from '../stream/transaction-stream-hub.js';
|
|
12
|
+
export * from './local-saga-dispatcher.js';
|
|
13
|
+
export * from './resolve-template.js';
|
|
14
|
+
export * from './resume-sweep.js';
|
|
15
|
+
export * from './run-saga.js';
|
|
16
|
+
export * from './run-transaction.js';
|
|
17
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/engine/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,cAAc,qCAAqC,CAAC;AACpD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC;AAC9B,cAAc,sBAAsB,CAAC"}
|