@entifix/transactions 0.1.4 → 0.3.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 (60) hide show
  1. package/dist/contracts/inbox.d.ts +1 -1
  2. package/dist/contracts/inbox.d.ts.map +1 -1
  3. package/dist/contracts/inbox.js +1 -1
  4. package/dist/contracts/inbox.js.map +1 -1
  5. package/dist/contracts/outbox.d.ts +1 -1
  6. package/dist/contracts/outbox.d.ts.map +1 -1
  7. package/dist/contracts/outbox.js +1 -1
  8. package/dist/contracts/outbox.js.map +1 -1
  9. package/dist/contracts/record.d.ts +2 -2
  10. package/dist/contracts/record.d.ts.map +1 -1
  11. package/dist/contracts/record.js +2 -2
  12. package/dist/contracts/record.js.map +1 -1
  13. package/dist/engine/resume-sweep.js +3 -3
  14. package/dist/engine/resume-sweep.js.map +1 -1
  15. package/dist/engine/run-saga.js +2 -2
  16. package/dist/engine/run-saga.js.map +1 -1
  17. package/dist/engine/run-transaction.d.ts +1 -1
  18. package/dist/engine/run-transaction.d.ts.map +1 -1
  19. package/dist/engine/run-transaction.js.map +1 -1
  20. package/dist/mixins/transaction-mixins.d.ts +3 -3
  21. package/dist/mixins/transaction-mixins.d.ts.map +1 -1
  22. package/dist/mixins/transaction-mixins.js +3 -3
  23. package/dist/mixins/transaction-mixins.js.map +1 -1
  24. package/dist/ports/event-bus.d.ts +1 -1
  25. package/dist/ports/event-bus.d.ts.map +1 -1
  26. package/dist/ports/event-bus.js +1 -1
  27. package/dist/ports/event-bus.js.map +1 -1
  28. package/dist/ports/event-source.d.ts +1 -1
  29. package/dist/ports/event-source.d.ts.map +1 -1
  30. package/dist/ports/event-source.js +1 -1
  31. package/dist/ports/event-source.js.map +1 -1
  32. package/dist/ports/lock-service.d.ts +1 -1
  33. package/dist/ports/lock-service.d.ts.map +1 -1
  34. package/dist/ports/lock-service.js +1 -1
  35. package/dist/ports/lock-service.js.map +1 -1
  36. package/dist/ports/saga-dispatcher.d.ts +1 -1
  37. package/dist/ports/saga-dispatcher.d.ts.map +1 -1
  38. package/dist/ports/saga-dispatcher.js +1 -1
  39. package/dist/ports/saga-dispatcher.js.map +1 -1
  40. package/dist/ports/saga-store.d.ts +1 -1
  41. package/dist/ports/saga-store.d.ts.map +1 -1
  42. package/dist/ports/saga-store.js +1 -1
  43. package/dist/ports/saga-store.js.map +1 -1
  44. package/dist/ports/sequence-service.d.ts +1 -1
  45. package/dist/ports/sequence-service.d.ts.map +1 -1
  46. package/dist/ports/sequence-service.js +1 -1
  47. package/dist/ports/sequence-service.js.map +1 -1
  48. package/dist/ports/transaction-handler.d.ts +1 -1
  49. package/dist/ports/transaction-handler.d.ts.map +1 -1
  50. package/dist/ports/transaction-handler.js +1 -1
  51. package/dist/ports/transaction-handler.js.map +1 -1
  52. package/dist/ports/transaction-sink.d.ts +1 -1
  53. package/dist/ports/transaction-sink.d.ts.map +1 -1
  54. package/dist/ports/transaction-sink.js +1 -1
  55. package/dist/ports/transaction-sink.js.map +1 -1
  56. package/dist/stream/transaction-stream-hub.d.ts +1 -1
  57. package/dist/stream/transaction-stream-hub.d.ts.map +1 -1
  58. package/dist/stream/transaction-stream-hub.js +1 -1
  59. package/dist/stream/transaction-stream-hub.js.map +1 -1
  60. package/package.json +5 -6
@@ -73,7 +73,7 @@ export interface TransactionInbox {
73
73
  */
74
74
  claim(eventId: string): Effect.Effect<InboxClaimResult, EntifixConnError>;
75
75
  }
76
- declare const TransactionInboxTag_base: Context.TagClass<TransactionInboxTag, "TransactionInboxTag", TransactionInbox>;
76
+ declare const TransactionInboxTag_base: Context.ServiceClass<TransactionInboxTag, "TransactionInboxTag", TransactionInbox>;
77
77
  export declare class TransactionInboxTag extends TransactionInboxTag_base {
78
78
  }
79
79
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"inbox.d.ts","sourceRoot":"","sources":["../../src/contracts/inbox.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAA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3E;;AAED,qBAAa,mBAAoB,SAAQ,wBAGf;CAAG"}
@@ -1,5 +1,5 @@
1
1
  import { Context } from 'effect';
2
- export class TransactionInboxTag extends Context.Tag('TransactionInboxTag')() {
2
+ export class TransactionInboxTag extends Context.Service()('TransactionInboxTag') {
3
3
  }
4
4
 
5
5
  //# sourceMappingURL=inbox.js.map
@@ -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` (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"}
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.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"}
@@ -130,7 +130,7 @@ export interface TransactionOutbox {
130
130
  */
131
131
  stats(): Effect.Effect<OutboxStats, EntifixConnError>;
132
132
  }
133
- declare const TransactionOutboxTag_base: Context.TagClass<TransactionOutboxTag, "TransactionOutboxTag", TransactionOutbox>;
133
+ declare const TransactionOutboxTag_base: Context.ServiceClass<TransactionOutboxTag, "TransactionOutboxTag", TransactionOutbox>;
134
134
  export declare class TransactionOutboxTag extends TransactionOutboxTag_base {
135
135
  }
136
136
  export {};
@@ -1 +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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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,yBAGf;CAAG"}
@@ -1,5 +1,5 @@
1
1
  import { Context } from 'effect';
2
- export class TransactionOutboxTag extends Context.Tag('TransactionOutboxTag')() {
2
+ export class TransactionOutboxTag extends Context.Service()('TransactionOutboxTag') {
3
3
  }
4
4
 
5
5
  //# sourceMappingURL=outbox.js.map
@@ -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\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"}
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.Service<\n TransactionOutboxTag,\n TransactionOutbox\n>()('TransactionOutboxTag') {}\n"],"names":["Context","TransactionOutboxTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAgJ9C,OAAO,MAAMC,6BAA6BD,QAAQE,OAAO,GAGrD;AAAyB"}
@@ -51,7 +51,7 @@ export interface TransactionStore {
51
51
  */
52
52
  countByState(): Effect.Effect<Record<TransactionState, number>, EntifixConnError>;
53
53
  }
54
- declare const TransactionStoreTag_base: Context.TagClass<TransactionStoreTag, "TransactionStoreTag", TransactionStore>;
54
+ declare const TransactionStoreTag_base: Context.ServiceClass<TransactionStoreTag, "TransactionStoreTag", TransactionStore>;
55
55
  export declare class TransactionStoreTag extends TransactionStoreTag_base {
56
56
  }
57
57
  /**
@@ -101,7 +101,7 @@ export declare function readTransactionRecordEnvelope(body: unknown): Effect.Eff
101
101
  export interface TransactionStatusReader {
102
102
  read(transactionId: string): Effect.Effect<TransactionRecord | undefined, EntifixError>;
103
103
  }
104
- declare const TransactionStatusReaderTag_base: Context.TagClass<TransactionStatusReaderTag, "TransactionStatusReaderTag", TransactionStatusReader>;
104
+ declare const TransactionStatusReaderTag_base: Context.ServiceClass<TransactionStatusReaderTag, "TransactionStatusReaderTag", TransactionStatusReader>;
105
105
  export declare class TransactionStatusReaderTag extends TransactionStatusReaderTag_base {
106
106
  }
107
107
  export {};
@@ -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;IACd,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IACl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,IAAI,EAAE,gBAAgB,CAAC,CAAC;IACxE;;;;;;;;;;;;;OAaG;IACH,YAAY,IAAI,MAAM,CAAC,MAAM,CAC3B,MAAM,CAAC,gBAAgB,EAAE,MAAM,CAAC,EAChC,gBAAgB,CACjB,CAAC;CACH;;AAED,qBAAa,mBAAoB,SAAQ,wBAGf;CAAG;AAE7B;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,mBAAmB;IAClC,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,gBAAgB,CAAC;CACzB;AAED;;;;;GAKG;AACH,wBAAgB,+BAA+B,CAC7C,IAAI,EAAE,OAAO,GACZ,MAAM,CAAC,MAAM,CAAC,mBAAmB,EAAE,YAAY,CAAC,CASlD;AAED;;;;;;;;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,6 +1,6 @@
1
1
  import { readEnvelope } from '@entifix/core';
2
2
  import { Context, Effect } from 'effect';
3
- export class TransactionStoreTag extends Context.Tag('TransactionStoreTag')() {
3
+ export class TransactionStoreTag extends Context.Service()('TransactionStoreTag') {
4
4
  }
5
5
  /**
6
6
  * Parses a `202` accept body, for a browser about to start polling.
@@ -21,7 +21,7 @@ export class TransactionStoreTag extends Context.Tag('TransactionStoreTag')() {
21
21
  */ export function readTransactionRecordEnvelope(body) {
22
22
  return Effect.map(readEnvelope(body, 'transactionRecord', 'transactionRecord'), (envelope)=>envelope.data);
23
23
  }
24
- export class TransactionStatusReaderTag extends Context.Tag('TransactionStatusReaderTag')() {
24
+ export class TransactionStatusReaderTag extends Context.Service()('TransactionStatusReaderTag') {
25
25
  }
26
26
 
27
27
  //# sourceMappingURL=record.js.map
@@ -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 (ADR 0036).\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 the surface #194 deleted `GET /api/transaction` for.\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 surface #194 deleted\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.Tag('TransactionStoreTag')<\n TransactionStoreTag,\n TransactionStore\n>() {}\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 (#176,\n * [ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).\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 (ADR 0043).\n */\nexport interface TransactionStatusReader {\n read(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, EntifixError>;\n}\n\nexport class TransactionStatusReaderTag extends Context.Tag(\n 'TransactionStatusReaderTag',\n)<TransactionStatusReaderTag, TransactionStatusReader>() {}\n"],"names":["readEnvelope","Context","Effect","TransactionStoreTag","Tag","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,GAAG,CAAC;AAGhD;AAmBL;;;;;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,GAAG,CACzD;AACwD"}
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 (ADR 0036).\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 the surface #194 deleted `GET /api/transaction` for.\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 surface #194 deleted\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 (#176,\n * [ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).\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 (ADR 0043).\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;AAmB5B;;;;;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"}
@@ -42,12 +42,12 @@ import { resumeSaga } from './run-saga.js';
42
42
  definition: claimed.definition,
43
43
  resumedFrom: claimed.state,
44
44
  settled: result.state
45
- }))), Effect.catchAll((error)=>Effect.logError('resuming a saga instance failed').pipe(Effect.annotateLogs({
45
+ }))), Effect.catch((error)=>Effect.logError('resuming a saga instance failed').pipe(Effect.annotateLogs({
46
46
  sagaId: claimed.sagaId,
47
47
  error: String(error)
48
48
  }))));
49
49
  }
50
- }).pipe(Effect.catchAll((error)=>Effect.logError('saga resume sweep failed').pipe(Effect.annotateLogs({
50
+ }).pipe(Effect.catch((error)=>Effect.logError('saga resume sweep failed').pipe(Effect.annotateLogs({
51
51
  error: String(error)
52
52
  }))));
53
53
  /**
@@ -63,7 +63,7 @@ import { resumeSaga } from './run-saga.js';
63
63
  // Resolved once at boot and provided to every pass, so the daemon needs
64
64
  // nothing from the context it outlives.
65
65
  const pass = resumeStaleSagas(options).pipe(Effect.provideService(SagaStoreTag, store), Effect.provideService(SagaDispatcherTag, dispatcher));
66
- const daemon = yield* Effect.forkDaemon(pass.pipe(Effect.delay(Duration.millis(options.intervalMs)), Effect.forever));
66
+ const daemon = yield* Effect.forkDetach(pass.pipe(Effect.delay(Duration.millis(options.intervalMs)), Effect.forever));
67
67
  yield* shutdown.register({
68
68
  name: 'saga-resume-sweep',
69
69
  phase: 'stop-intake',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/engine/resume-sweep.ts"],"sourcesContent":["import { ShutdownRegistryTag } from '@entifix/business';\nimport { Duration, Effect, Fiber } from 'effect';\n\nimport type { SagaDefinition } from '../contracts/saga-definition.js';\nimport { SagaDispatcherTag } from '../ports/saga-dispatcher.js';\nimport { SagaStoreTag } from '../ports/saga-store.js';\nimport { resumeSaga } from './run-saga.js';\n\nexport interface ResumeSweepOptions {\n /** Every flow this process can finish, by `definition.name`. */\n readonly definitions: readonly SagaDefinition[];\n /**\n * How long an instance may sit untouched before its coordinator is presumed\n * gone.\n *\n * ⚠️ **Must stay above the longest a step legitimately takes.** `updatedAt`\n * is re-stamped before every dispatch, so a slow participant keeps an instance\n * fresh — but a step slower than this window is resumed underneath the\n * coordinator still waiting on it, and only the participants' inboxes stop\n * that from being two side effects.\n */\n readonly staleAfterMs: number;\n /** Past this many sweeps, an instance settles `STRANDED` instead. */\n readonly maxResumeAttempts: number;\n}\n\n/**\n * One pass: find the instances nobody finished, claim each, and finish it.\n *\n * ⚠️ **`findStale` then `claimForResume`, never `findStale` then resume.** The\n * claim is a conditional write, so an instance another replica already took no\n * longer matches and is skipped. Without it two sweepers would walk one flow\n * together, and the attempt ceiling would count two attempts per tick.\n *\n * Failures are logged, per instance and around the pass, never raised: one flow\n * that cannot be resumed must not abandon the flows behind it, and a store that\n * is briefly unreachable must not kill the daemon that calls this.\n */\nexport const resumeStaleSagas = ({\n definitions,\n staleAfterMs,\n maxResumeAttempts,\n}: ResumeSweepOptions): Effect.Effect<\n void,\n never,\n SagaStoreTag | SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const byName = new Map(\n definitions.map(definition => [definition.name, definition]),\n );\n\n for (const found of yield* store.findStale(staleAfterMs)) {\n const definition = byName.get(found.definition);\n if (definition === undefined) {\n // Nothing here can finish a flow it cannot read, and settling it would\n // be a guess about its steps — so it is surfaced and left alone.\n yield* Effect.logError('stale saga names an unknown definition').pipe(\n Effect.annotateLogs({\n sagaId: found.sagaId,\n definition: found.definition,\n }),\n );\n continue;\n }\n\n const claimed = yield* store.claimForResume(found.sagaId, staleAfterMs);\n if (claimed === undefined) continue;\n\n yield* resumeSaga({\n instance: claimed,\n definition,\n maxResumeAttempts,\n }).pipe(\n Effect.tap(result =>\n Effect.logInfo('resumed a saga instance').pipe(\n Effect.annotateLogs({\n sagaId: claimed.sagaId,\n definition: claimed.definition,\n resumedFrom: claimed.state,\n settled: result.state,\n }),\n ),\n ),\n Effect.catchAll(error =>\n Effect.logError('resuming a saga instance failed').pipe(\n Effect.annotateLogs({\n sagaId: claimed.sagaId,\n error: String(error),\n }),\n ),\n ),\n );\n }\n }).pipe(\n Effect.catchAll(error =>\n Effect.logError('saga resume sweep failed').pipe(\n Effect.annotateLogs({ error: String(error) }),\n ),\n ),\n );\n\n/**\n * Runs {@link resumeStaleSagas} every `intervalMs` as a daemon, and stops it on\n * shutdown.\n *\n * `stop-intake`, not `flush`: the sweep writes the store and dispatches, so it\n * has to stop before the clients it goes through do.\n */\nexport const startSagaResume = (\n options: ResumeSweepOptions & { readonly intervalMs: number },\n): Effect.Effect<\n void,\n never,\n SagaStoreTag | SagaDispatcherTag | ShutdownRegistryTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const dispatcher = yield* SagaDispatcherTag;\n const shutdown = yield* ShutdownRegistryTag;\n\n // Resolved once at boot and provided to every pass, so the daemon needs\n // nothing from the context it outlives.\n const pass = resumeStaleSagas(options).pipe(\n Effect.provideService(SagaStoreTag, store),\n Effect.provideService(SagaDispatcherTag, dispatcher),\n );\n\n const daemon = yield* Effect.forkDaemon(\n pass.pipe(\n Effect.delay(Duration.millis(options.intervalMs)),\n Effect.forever,\n ),\n );\n\n yield* shutdown.register({\n name: 'saga-resume-sweep',\n phase: 'stop-intake',\n run: Fiber.interrupt(daemon).pipe(Effect.asVoid),\n });\n });\n"],"names":["ShutdownRegistryTag","Duration","Effect","Fiber","SagaDispatcherTag","SagaStoreTag","resumeSaga","resumeStaleSagas","definitions","staleAfterMs","maxResumeAttempts","gen","store","byName","Map","map","definition","name","found","findStale","get","undefined","logError","pipe","annotateLogs","sagaId","claimed","claimForResume","instance","tap","result","logInfo","resumedFrom","state","settled","catchAll","error","String","startSagaResume","options","dispatcher","shutdown","pass","provideService","daemon","forkDaemon","delay","millis","intervalMs","forever","register","phase","run","interrupt","asVoid"],"mappings":"AAAA,SAASA,mBAAmB,QAAQ,oBAAoB;AACxD,SAASC,QAAQ,EAAEC,MAAM,EAAEC,KAAK,QAAQ,SAAS;AAGjD,SAASC,iBAAiB,QAAQ,8BAA8B;AAChE,SAASC,YAAY,QAAQ,yBAAyB;AACtD,SAASC,UAAU,QAAQ,gBAAgB;AAoB3C;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,mBAAmB,CAAC,EAC/BC,WAAW,EACXC,YAAY,EACZC,iBAAiB,EACE,GAKnBR,OAAOS,GAAG,CAAC;QACT,MAAMC,QAAQ,OAAOP;QACrB,MAAMQ,SAAS,IAAIC,IACjBN,YAAYO,GAAG,CAACC,CAAAA,aAAc;gBAACA,WAAWC,IAAI;gBAAED;aAAW;QAG7D,KAAK,MAAME,SAAS,OAAON,MAAMO,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AAM0C,OAAOnC,iBAAiBgC,SAAShB,IAAI,CACzCrB,OAAOyC,cAAc,CAACtC,cAAcO,QACpCV,OAAOyC,cAAc,CAACvC,mBAAmBoC;QAG3C,MAAMI,SAAS,OAAO1C,OAAO2C,UAAU,CACrCH,KAAKnB,IAAI,CACPrB,OAAO4C,KAAK,CAAC7C,SAAS8C,MAAM,CAACR,QAAQS,UAAU,IAC/C9C,OAAO+C,OAAO;QAIlB,OAAOR,SAASS,QAAQ,CAAC;YACvBjC,MAAM;YACNkC,OAAO;YACPC,KAAKjD,MAAMkD,SAAS,CAACT,QAAQrB,IAAI,CAACrB,OAAOoD,MAAM;QACjD;IACF,GAAG"}
1
+ {"version":3,"sources":["../../src/engine/resume-sweep.ts"],"sourcesContent":["import { ShutdownRegistryTag } from '@entifix/business';\nimport { Duration, Effect, Fiber } from 'effect';\n\nimport type { SagaDefinition } from '../contracts/saga-definition.js';\nimport { SagaDispatcherTag } from '../ports/saga-dispatcher.js';\nimport { SagaStoreTag } from '../ports/saga-store.js';\nimport { resumeSaga } from './run-saga.js';\n\nexport interface ResumeSweepOptions {\n /** Every flow this process can finish, by `definition.name`. */\n readonly definitions: readonly SagaDefinition[];\n /**\n * How long an instance may sit untouched before its coordinator is presumed\n * gone.\n *\n * ⚠️ **Must stay above the longest a step legitimately takes.** `updatedAt`\n * is re-stamped before every dispatch, so a slow participant keeps an instance\n * fresh — but a step slower than this window is resumed underneath the\n * coordinator still waiting on it, and only the participants' inboxes stop\n * that from being two side effects.\n */\n readonly staleAfterMs: number;\n /** Past this many sweeps, an instance settles `STRANDED` instead. */\n readonly maxResumeAttempts: number;\n}\n\n/**\n * One pass: find the instances nobody finished, claim each, and finish it.\n *\n * ⚠️ **`findStale` then `claimForResume`, never `findStale` then resume.** The\n * claim is a conditional write, so an instance another replica already took no\n * longer matches and is skipped. Without it two sweepers would walk one flow\n * together, and the attempt ceiling would count two attempts per tick.\n *\n * Failures are logged, per instance and around the pass, never raised: one flow\n * that cannot be resumed must not abandon the flows behind it, and a store that\n * is briefly unreachable must not kill the daemon that calls this.\n */\nexport const resumeStaleSagas = ({\n definitions,\n staleAfterMs,\n maxResumeAttempts,\n}: ResumeSweepOptions): Effect.Effect<\n void,\n never,\n SagaStoreTag | SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const byName = new Map(\n definitions.map(definition => [definition.name, definition]),\n );\n\n for (const found of yield* store.findStale(staleAfterMs)) {\n const definition = byName.get(found.definition);\n if (definition === undefined) {\n // Nothing here can finish a flow it cannot read, and settling it would\n // be a guess about its steps — so it is surfaced and left alone.\n yield* Effect.logError('stale saga names an unknown definition').pipe(\n Effect.annotateLogs({\n sagaId: found.sagaId,\n definition: found.definition,\n }),\n );\n continue;\n }\n\n const claimed = yield* store.claimForResume(found.sagaId, staleAfterMs);\n if (claimed === undefined) continue;\n\n yield* resumeSaga({\n instance: claimed,\n definition,\n maxResumeAttempts,\n }).pipe(\n Effect.tap(result =>\n Effect.logInfo('resumed a saga instance').pipe(\n Effect.annotateLogs({\n sagaId: claimed.sagaId,\n definition: claimed.definition,\n resumedFrom: claimed.state,\n settled: result.state,\n }),\n ),\n ),\n Effect.catch(error =>\n Effect.logError('resuming a saga instance failed').pipe(\n Effect.annotateLogs({\n sagaId: claimed.sagaId,\n error: String(error),\n }),\n ),\n ),\n );\n }\n }).pipe(\n Effect.catch(error =>\n Effect.logError('saga resume sweep failed').pipe(\n Effect.annotateLogs({ error: String(error) }),\n ),\n ),\n );\n\n/**\n * Runs {@link resumeStaleSagas} every `intervalMs` as a daemon, and stops it on\n * shutdown.\n *\n * `stop-intake`, not `flush`: the sweep writes the store and dispatches, so it\n * has to stop before the clients it goes through do.\n */\nexport const startSagaResume = (\n options: ResumeSweepOptions & { readonly intervalMs: number },\n): Effect.Effect<\n void,\n never,\n SagaStoreTag | SagaDispatcherTag | ShutdownRegistryTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const dispatcher = yield* SagaDispatcherTag;\n const shutdown = yield* ShutdownRegistryTag;\n\n // Resolved once at boot and provided to every pass, so the daemon needs\n // nothing from the context it outlives.\n const pass = resumeStaleSagas(options).pipe(\n Effect.provideService(SagaStoreTag, store),\n Effect.provideService(SagaDispatcherTag, dispatcher),\n );\n\n const daemon = yield* Effect.forkDetach(\n pass.pipe(\n Effect.delay(Duration.millis(options.intervalMs)),\n Effect.forever,\n ),\n );\n\n yield* shutdown.register({\n name: 'saga-resume-sweep',\n phase: 'stop-intake',\n run: Fiber.interrupt(daemon).pipe(Effect.asVoid),\n });\n });\n"],"names":["ShutdownRegistryTag","Duration","Effect","Fiber","SagaDispatcherTag","SagaStoreTag","resumeSaga","resumeStaleSagas","definitions","staleAfterMs","maxResumeAttempts","gen","store","byName","Map","map","definition","name","found","findStale","get","undefined","logError","pipe","annotateLogs","sagaId","claimed","claimForResume","instance","tap","result","logInfo","resumedFrom","state","settled","catch","error","String","startSagaResume","options","dispatcher","shutdown","pass","provideService","daemon","forkDetach","delay","millis","intervalMs","forever","register","phase","run","interrupt","asVoid"],"mappings":"AAAA,SAASA,mBAAmB,QAAQ,oBAAoB;AACxD,SAASC,QAAQ,EAAEC,MAAM,EAAEC,KAAK,QAAQ,SAAS;AAGjD,SAASC,iBAAiB,QAAQ,8BAA8B;AAChE,SAASC,YAAY,QAAQ,yBAAyB;AACtD,SAASC,UAAU,QAAQ,gBAAgB;AAoB3C;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,mBAAmB,CAAC,EAC/BC,WAAW,EACXC,YAAY,EACZC,iBAAiB,EACE,GAKnBR,OAAOS,GAAG,CAAC;QACT,MAAMC,QAAQ,OAAOP;QACrB,MAAMQ,SAAS,IAAIC,IACjBN,YAAYO,GAAG,CAACC,CAAAA,aAAc;gBAACA,WAAWC,IAAI;gBAAED;aAAW;QAG7D,KAAK,MAAME,SAAS,OAAON,MAAMO,SAAS,CAACV,cAAe;YACxD,MAAMO,aAAaH,OAAOO,GAAG,CAACF,MAAMF,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C,cAAcO,QACpCV,OAAOyC,cAAc,CAACvC,mBAAmBoC;QAG3C,MAAMI,SAAS,OAAO1C,OAAO2C,UAAU,CACrCH,KAAKnB,IAAI,CACPrB,OAAO4C,KAAK,CAAC7C,SAAS8C,MAAM,CAACR,QAAQS,UAAU,IAC/C9C,OAAO+C,OAAO;QAIlB,OAAOR,SAASS,QAAQ,CAAC;YACvBjC,MAAM;YACNkC,OAAO;YACPC,KAAKjD,MAAMkD,SAAS,CAACT,QAAQrB,IAAI,CAACrB,OAAOoD,MAAM;QACjD;IACF,GAAG"}
@@ -144,7 +144,7 @@ const dispatchCall = (step, call, sagaId, index, input, scope)=>Effect.gen(funct
144
144
  organizationId: call.organizationId
145
145
  }, {
146
146
  outcome: call.body
147
- }).pipe(Effect.catchAll((error)=>Effect.succeed({
147
+ }).pipe(Effect.catch((error)=>Effect.succeed({
148
148
  ok: false,
149
149
  status: 0,
150
150
  body: error
@@ -152,7 +152,7 @@ const dispatchCall = (step, call, sagaId, index, input, scope)=>Effect.gen(funct
152
152
  // throws rather than interpolating `undefined`; that is a defect, and
153
153
  // it is reported as a stranded compensation rather than crashing the
154
154
  // walk and leaving every later hold in place.
155
- Effect.catchAllDefect((defect)=>Effect.succeed({
155
+ Effect.catchDefect((defect)=>Effect.succeed({
156
156
  ok: false,
157
157
  status: 0,
158
158
  body: defect
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/engine/run-saga.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Effect } from 'effect';\n\nimport {\n type SagaCall,\n type SagaCallOutcome,\n sagaCommandId,\n type SagaDefinition,\n type SagaInputs,\n type SagaStep,\n type SagaStepInput,\n type SagaStepOutcome,\n} from '../contracts/saga-definition.js';\nimport { SagaDispatcherTag } from '../ports/saga-dispatcher.js';\nimport {\n type SagaInstance,\n type SagaStore,\n SagaStoreTag,\n} from '../ports/saga-store.js';\nimport { resolveBodyTemplate, resolveTemplate } from './resolve-template.js';\n\nexport type { SagaInputs, SagaStepInput };\n\n/**\n * The steps that have run, kept with their outcomes.\n *\n * Paired rather than looked back up by id, because a lookup introduces a\n * not-found branch that cannot happen — and an unreachable branch is a line\n * nothing can ever prove correct. A resumed walk rebuilds this from the stored\n * outcomes, which is the one place the lookup does happen and can genuinely\n * fail.\n */\ntype Taken = Array<{ step: SagaStep; outcome: SagaStepOutcome }>;\n\nexport interface RunSagaOptions {\n readonly sagaId: string;\n readonly definition: SagaDefinition;\n readonly inputs: SagaInputs;\n}\n\n/** How a run ended. */\nexport interface SagaResult {\n readonly state: 'COMPLETED' | 'COMPENSATED' | 'STRANDED';\n readonly outcomes: readonly SagaStepOutcome[];\n readonly error?: string;\n}\n\n/**\n * What one element of a `fanOutFrom` step is dispatched with.\n *\n * The earlier call's body travels as `outcome` rather than `input`, which is the\n * same scope a compensation resolves against and for the same reason: the id\n * being addressed was minted by the participant and is in its response.\n */\ninterface DerivedElement {\n readonly input: SagaStepInput;\n readonly scope: Record<string, unknown>;\n}\n\nconst inputsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n): readonly SagaStepInput[] => {\n const declared = inputs[step.id] ?? [];\n // A non-fan-out step makes exactly one call whether or not it was given an\n // input, so an absent entry is an empty body rather than a skipped step.\n return step.fanOut ? declared : [declared[0] ?? {}];\n};\n\n/**\n * The elements a step actually dispatches: derived from an earlier step's\n * successful calls when it declares `fanOutFrom`, and from the caller's input\n * otherwise.\n *\n * ⚠️ **A `fanOutFrom` step ignores whatever the caller supplied for it.** The\n * cardinality is the earlier step's, and taking the caller's would let a\n * checkout convert a hold it never took — or, more likely, silently convert\n * none, which is how a saga reports COMPLETED with the goods still held.\n */\n/**\n * What every step can point at: the **first successful call** of each step that\n * has already run, by step id.\n *\n * First rather than all, because a template naming a fan-out step is ambiguous\n * by construction — \"the order id\" is one value and \"the reservation ids\" are\n * many, and the many case is what `fanOutFrom` exists for. Keeping this to the\n * unambiguous case is what stops `{steps.reserve.data.id}` quietly meaning\n * \"whichever hold happened to be first\".\n */\nconst stepsScope = (\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): Record<string, unknown> =>\n Object.fromEntries(\n taken\n .filter(entry => entry.outcome.calls.length > 0)\n .map(entry => [entry.step.id, entry.outcome.calls[0]?.body]),\n );\n\nconst elementsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): readonly DerivedElement[] => {\n const steps = stepsScope(taken);\n\n if (step.fanOutFrom === undefined) {\n return inputsFor(step, inputs).map(input => ({\n input,\n scope: { input: input.body, steps },\n }));\n }\n\n const source = taken.find(entry => entry.step.id === step.fanOutFrom);\n const body = inputs[step.id]?.[0]?.body;\n\n return (source?.outcome.calls ?? []).map(call => ({\n // ⚠️ The organization the *earlier call* acted for, never the caller's.\n // A tenant-plane participant resolves its handle from the header, so a\n // conversion dispatched without it is refused `400` and the hold expires\n // under a buyer who has already been charged.\n input: { body, organizationId: call.organizationId },\n scope: { outcome: call.body, input: body, steps },\n }));\n};\n\nconst dispatchCall = (\n step: SagaStep,\n call: SagaCall,\n sagaId: string,\n index: number,\n input: SagaStepInput,\n scope: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n const dispatcher = yield* SagaDispatcherTag;\n return yield* dispatcher.dispatch({\n participant: step.participant,\n call: { method: call.method, path: resolveTemplate(call.path, scope) },\n commandId: sagaCommandId(\n sagaId,\n step.id,\n step.fanOut ? index : undefined,\n ),\n organizationId: input.organizationId,\n body:\n call.method === 'GET' || call.method === 'DELETE'\n ? undefined\n : resolveBodyTemplate(input.body, scope),\n });\n });\n\n/**\n * Run one step: every call it makes, in order, stopping at the first refusal.\n *\n * Returns the calls that **succeeded** alongside the failure, because those are\n * exactly the calls a compensation has to undo — see {@link compensateStep}.\n */\nconst runStep = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const calls: SagaCallOutcome[] = [];\n\n for (const [index, element] of elements.entries()) {\n const { input } = element;\n const response = yield* dispatchCall(\n step,\n step.command,\n sagaId,\n index,\n input,\n element.scope,\n );\n\n if (!response.ok) {\n // A business refusal. The saga fails *forward* into compensation, and\n // the calls already recorded are the ones that have to come back.\n return {\n calls,\n error: `step '${step.id}' call ${String(index)} refused with ${String(\n response.status,\n )}`,\n };\n }\n\n calls.push({\n index,\n status: response.status,\n body: response.body,\n // Carried so the compensation reaches the same tenant. Without it a\n // release is refused `400` and the saga strands holding stock.\n organizationId: input.organizationId,\n });\n }\n\n return { calls };\n });\n\n/**\n * Undo one step — **one compensation per successful call**, never one per step.\n *\n * ⚠️ This is the whole reason an outcome is kept per fan-out element. Five lines\n * with three holds taken and the fourth refused must release exactly three:\n * compensating the step as a unit would either release nothing or attempt to\n * release two holds that were never taken\n * ([ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md)).\n *\n * Never fails: a compensation's own failure is reported by the caller and must\n * not stop the compensations after it, for the reason ADR 0039 gives — a\n * stranded saga nobody is told about is the same as a lost one.\n */\nconst compensateStep = (\n step: SagaStep,\n sagaId: string,\n outcome: SagaStepOutcome,\n): Effect.Effect<readonly string[], never, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const compensation = step.compensation;\n if (!compensation) {\n return [];\n }\n\n const failures: string[] = [];\n // Reverse order: the last thing done is the first thing undone, which is\n // what a reader expects of a stack of effects and what keeps a future\n // ordering dependency from being an accident.\n for (const call of [...outcome.calls].reverse()) {\n const result = yield* dispatchCall(\n step,\n compensation,\n sagaId,\n call.index,\n // ⚠️ The organization the *call* acted for, not an empty input. A\n // tenant-plane participant resolves its handle from the header, so a\n // compensation without it is refused before it reaches the hold.\n { organizationId: call.organizationId },\n { outcome: call.body },\n ).pipe(\n Effect.catchAll(error =>\n Effect.succeed({ ok: false, status: 0, body: error }),\n ),\n // A template that no longer matches the participant's response shape\n // throws rather than interpolating `undefined`; that is a defect, and\n // it is reported as a stranded compensation rather than crashing the\n // walk and leaving every later hold in place.\n Effect.catchAllDefect(defect =>\n Effect.succeed({ ok: false, status: 0, body: defect }),\n ),\n );\n\n // ⚠️ **A `404` is a compensation that has nothing left to undo**, and it\n // counts as success. Compensation is at-least-once the moment a resumed\n // coordinator can retry it, and a participant answering \"no such record\"\n // on the second delivery is describing a flow that *was* reversed. Left\n // as a refusal it strands exactly the sagas that were cleaned up\n // correctly, which is the failure ADR 0054 named on the conversion route\n // and is the same one from the other side.\n if (!result.ok && result.status !== 404) {\n failures.push(\n `compensation for '${step.id}' call ${String(call.index)} failed: ${String(\n result.body,\n )}`,\n );\n }\n }\n\n return failures;\n });\n\n/**\n * How many extra times a step is dispatched once the pivot has committed.\n *\n * Small and immediate on purpose. This is the in-process half of \"roll forward\",\n * and it exists to ride out the blip — a participant restarting, a connection\n * reset — not to be a retry policy. A step that is still refusing after these\n * strands the saga, loudly, because the alternative is a coordinator spinning on\n * a permanent failure while a customer's money sits captured.\n *\n * Durable retry across a coordinator restart is a different mechanism and is not\n * built: see #233, which makes a step dispatch an outbox entry whose relay\n * performs the POST.\n */\nconst POST_PIVOT_RETRIES = 3;\n\n/**\n * Dispatch a step, retrying it `retries` more times while it refuses.\n *\n * ⚠️ **A retry re-dispatches the calls that already succeeded**, and that is\n * safe for exactly one reason: `sagaCommandId(sagaId, step.id, index)` is stable\n * across attempts, so a participant that is idempotent on the command id\n * recognises the replay. ADR 0052 states that requirement on the participant;\n * this is the code that depends on it.\n */\nconst runStepWithRetries = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n retries: number,\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n let result = yield* runStep(step, sagaId, elements);\n\n for (\n let attempt = 1;\n attempt <= retries && result.error !== undefined;\n attempt += 1\n ) {\n yield* Effect.logWarning('retrying a saga step after the pivot').pipe(\n Effect.annotateLogs({\n sagaId,\n stepId: step.id,\n attempt,\n error: result.error,\n }),\n );\n result = yield* runStep(step, sagaId, elements);\n }\n\n return result;\n });\n\n/** Pair each recorded outcome with the step that produced it. */\nconst rebuildTaken = (\n definition: SagaDefinition,\n outcomes: readonly SagaStepOutcome[],\n): Taken | { readonly unknownStep: string } => {\n const taken: Taken = [];\n for (const outcome of outcomes) {\n const step = definition.steps.find(\n candidate => candidate.id === outcome.stepId,\n );\n // ⚠️ Not skipped. An outcome naming a step the definition no longer has\n // means the definition changed under a live instance, so the flow this\n // record describes and the flow the engine would walk are different flows.\n // Carrying on would compensate the wrong steps in the wrong order.\n if (!step) {\n return { unknownStep: outcome.stepId };\n }\n taken.push({ step, outcome });\n }\n return taken;\n};\n\n/** Whether the point of no return is behind us, read off what actually ran. */\nconst pivotCommittedIn = (taken: Taken): boolean =>\n taken.some(\n entry => entry.step.kind === 'pivot' && entry.outcome.error === undefined,\n );\n\n/**\n * Settle a saga that cannot go forward and cannot be reversed, loudly.\n *\n * ⚠️ The message is a parameter because these are **different operational\n * events** and each is grepped for on its own: money is captured behind a\n * pivot, a release was refused and stock is still held, a definition changed\n * under a live instance. Collapsing them into one string would make the log\n * line say only that something is wrong.\n */\nconst strand = (\n store: SagaStore,\n sagaId: string,\n outcomes: readonly SagaStepOutcome[],\n error: string,\n message: string,\n log: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n yield* Effect.logError(message).pipe(\n Effect.annotateLogs({ sagaId, error, ...log }),\n );\n yield* store.settle(sagaId, 'STRANDED', error);\n return { state: 'STRANDED', outcomes, error } as const;\n });\n\n/**\n * Unwind every compensatable step already taken, newest first.\n *\n * Shared by the in-process walk and by a resumed one, which is the whole reason\n * it is a function: a coordinator that died *while* compensating comes back\n * into exactly this loop, and the steps it already gave back carry\n * `compensated` so they are not given back twice.\n */\nconst unwind = (\n store: SagaStore,\n sagaId: string,\n definition: SagaDefinition,\n taken: Taken,\n error: string,\n): Effect.Effect<SagaResult, EntifixConnError, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const outcomes = taken.map(entry => entry.outcome);\n const failures: string[] = [];\n\n for (const done of [...taken].reverse()) {\n if (done.outcome.compensated === true) {\n continue;\n }\n const stepFailures = yield* compensateStep(\n done.step,\n sagaId,\n done.outcome,\n );\n failures.push(...stepFailures);\n // Marked only when the step came back whole. A partial failure stays\n // unmarked so a later resume retries it — safe because a compensation\n // with nothing left to undo answers `404`, which is a success above.\n if (stepFailures.length === 0) {\n yield* store.markCompensated(sagaId, done.step.id);\n }\n }\n\n if (failures.length > 0) {\n // ⚠️ Surfaced, never swallowed. This is the state that leaves a\n // reservation held and — once payment lands — a customer charged, and\n // ADR 0039 names it as the failure class nobody plans for.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga compensation failed',\n { definition: definition.name, failures: failures.join('; ') },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATED', error);\n return { state: 'COMPENSATED', outcomes, error };\n });\n\n/**\n * Dispatch the definition's steps from `startIndex` on, and unwind on a refusal.\n *\n * The state transition is persisted **before** each dispatch, so a crash leaves\n * a record that says what was actually attempted (ADR 0028, extended to\n * commands by ADR 0039).\n *\n * ⚠️ **Once the pivot has committed, nothing is unwound.** That is what a pivot\n * means, and the walk has to know it rather than the definition merely declaring\n * it: `compensateStep` no-ops on a step that declares no compensation, so an\n * unconditional unwind after a successful capture would skip the pivot in\n * silence and then delete the order behind it and release the holds behind that\n * — money taken, goods back on sale, every probe green. The step is retried\n * instead, and a saga that still cannot go forward is settled `STRANDED` and\n * logged, because ADR 0039 is explicit that a stranded saga nobody is told about\n * is the same as a lost one.\n */\nconst walk = (\n store: SagaStore,\n options: RunSagaOptions,\n from: { readonly taken: Taken; readonly startIndex: number },\n): Effect.Effect<SagaResult, EntifixConnError, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const { sagaId, definition, inputs } = options;\n // Step and outcome are kept **together**: looking the step back up by id\n // would introduce a not-found branch that cannot happen, and an unreachable\n // branch is a line nothing can ever prove correct.\n const taken = from.taken;\n const outcomes = () => taken.map(entry => entry.outcome);\n\n // The point of no return, once it is behind us. Tracked rather than read off\n // the definition because what matters is not that a pivot exists but that it\n // *committed* — a pivot that refuses is still fully reversible, and is the\n // ordinary compensation case below.\n let pivotCommitted = pivotCommittedIn(taken);\n\n for (\n let index = from.startIndex;\n index < definition.steps.length;\n index++\n ) {\n const step = definition.steps[index];\n /* v8 ignore next 3 -- the loop bound makes this unreachable; it exists\n because `noUncheckedIndexedAccess` cannot see that. */\n if (!step) {\n continue;\n }\n\n yield* store.beginStep(sagaId, index);\n const { calls, error } = yield* runStepWithRetries(\n step,\n sagaId,\n elementsFor(step, inputs, taken),\n pivotCommitted ? POST_PIVOT_RETRIES : 0,\n );\n\n const outcome: SagaStepOutcome = {\n stepId: step.id,\n calls,\n ...(error === undefined ? {} : { error }),\n };\n taken.push({ step, outcome });\n yield* store.recordOutcome(sagaId, outcome);\n\n if (error === undefined) {\n if (step.kind === 'pivot') {\n pivotCommitted = true;\n }\n continue;\n }\n\n if (pivotCommitted) {\n // ⚠️ Forward or nowhere. Compensating from here would undo steps whose\n // effects the pivot has already been paid for.\n return yield* strand(\n store,\n sagaId,\n outcomes(),\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n // Unwind. The failing step's own successful calls are compensated too —\n // a fan-out step that took three holds before its fourth was refused has\n // three to give back.\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, taken, error);\n }\n\n yield* store.settle(sagaId, 'COMPLETED');\n return { state: 'COMPLETED', outcomes: outcomes() };\n });\n\n/**\n * Start a flow and walk it to a terminal state.\n *\n * ⚠️ **Synchronous, and that is the buyer's requirement.** A checkout needs a\n * yes/no now, so this answers the settled result. What {@link resumeSaga} adds\n * is durability *behind* that answer: if this process dies mid-walk, the record\n * it has been writing all along is enough for another one to finish the flow.\n */\nexport const runSaga = (\n options: RunSagaOptions,\n): Effect.Effect<\n SagaResult,\n EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { sagaId, definition, inputs } = options;\n\n yield* store.start({\n sagaId,\n definition: definition.name,\n state: 'RUNNING',\n stepIndex: 0,\n outcomes: [],\n // ⚠️ Persisted, because a resume has nothing to dispatch without it: a\n // fan-out step's cardinality *is* its input's length (ADR 0055).\n inputs,\n resumeAttempts: 0,\n createdAt: new Date().toISOString(),\n });\n\n return yield* walk(store, options, { taken: [], startIndex: 0 });\n });\n\nexport interface ResumeSagaOptions {\n readonly instance: SagaInstance;\n readonly definition: SagaDefinition;\n /** Past this many sweeps, the instance is surfaced instead of retried. */\n readonly maxResumeAttempts: number;\n}\n\n/**\n * Finish a flow another coordinator abandoned.\n *\n * ⚠️ **Where to re-enter is derived, never stored.** A resume point written\n * beside the outcomes would be a second record of the same fact, free to\n * disagree with them; the outcomes already say what happened, and\n * `beginStep`-before-dispatch means `stepIndex` says what was attempted. The\n * four cases are exhaustive:\n *\n * - the step at `stepIndex` recorded no outcome — the process died during the\n * dispatch, so **re-dispatch it**. Safe because `sagaCommandId` is stable\n * across attempts and every participant claims it in its own command inbox,\n * so calls that did land are recognised as replays rather than repeated\n * (ADR 0052).\n * - it recorded a successful outcome — the process died between\n * `recordOutcome` and the next `beginStep`, so **start at the one after**.\n * - it recorded a refusal — the process died deciding what to do about it, so\n * **re-enter that decision**: unwind, or strand if the pivot had committed.\n * - the instance is `COMPENSATING` — it died mid-unwind, so **continue the\n * unwind**, skipping steps already marked `compensated`.\n */\nexport const resumeSaga = (\n options: ResumeSagaOptions,\n): Effect.Effect<\n SagaResult,\n EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { instance, definition, maxResumeAttempts } = options;\n const { sagaId, outcomes } = instance;\n\n if (instance.resumeAttempts > maxResumeAttempts) {\n // Surfaced rather than retried forever. A coordinator spinning on a\n // permanent failure is how money stays captured with nobody told.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n instance.error ??\n `resumed ${String(instance.resumeAttempts - 1)} times without settling`,\n 'saga abandoned after too many resumes',\n {\n definition: definition.name,\n resumeAttempts: instance.resumeAttempts,\n },\n );\n }\n\n const rebuilt = rebuildTaken(definition, outcomes);\n if ('unknownStep' in rebuilt) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `recorded step '${rebuilt.unknownStep}' is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const resumeOptions: RunSagaOptions = {\n sagaId,\n definition,\n inputs: instance.inputs,\n };\n\n if (instance.state === 'COMPENSATING') {\n return yield* unwind(\n store,\n sagaId,\n definition,\n rebuilt,\n instance.error ?? 'compensation resumed',\n );\n }\n\n const step = definition.steps[instance.stepIndex];\n if (!step) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `step ${String(instance.stepIndex)} is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const recorded = rebuilt.find(entry => entry.step.id === step.id);\n\n if (recorded === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex,\n });\n }\n\n if (recorded.outcome.error === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex + 1,\n });\n }\n\n const error = recorded.outcome.error;\n if (pivotCommittedIn(rebuilt)) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, rebuilt, error);\n });\n"],"names":["Effect","sagaCommandId","SagaDispatcherTag","SagaStoreTag","resolveBodyTemplate","resolveTemplate","inputsFor","step","inputs","declared","id","fanOut","stepsScope","taken","Object","fromEntries","filter","entry","outcome","calls","length","map","body","elementsFor","steps","fanOutFrom","undefined","input","scope","source","find","call","organizationId","dispatchCall","sagaId","index","gen","dispatcher","dispatch","participant","method","path","commandId","runStep","elements","element","entries","response","command","ok","error","String","status","push","compensateStep","compensation","failures","reverse","result","pipe","catchAll","succeed","catchAllDefect","defect","POST_PIVOT_RETRIES","runStepWithRetries","retries","attempt","logWarning","annotateLogs","stepId","rebuildTaken","definition","outcomes","candidate","unknownStep","pivotCommittedIn","some","kind","strand","store","message","log","logError","settle","state","unwind","done","compensated","stepFailures","markCompensated","name","join","walk","options","from","pivotCommitted","startIndex","beginStep","recordOutcome","runSaga","start","stepIndex","resumeAttempts","createdAt","Date","toISOString","resumeSaga","instance","maxResumeAttempts","rebuilt","resumeOptions","recorded"],"mappings":";AACA,SAASA,MAAM,QAAQ,SAAS;AAEhC,SAGEC,aAAa,QAMR,kCAAkC;AACzC,SAASC,iBAAiB,QAAQ,8BAA8B;AAChE,SAGEC,YAAY,QACP,yBAAyB;AAChC,SAASC,mBAAmB,EAAEC,eAAe,QAAQ,wBAAwB;AAwC7E,MAAMC,YAAY,CAChBC,MACAC;QAEiBA,iBAGgBC;IAHjC,MAAMA,YAAWD,kBAAAA,MAAM,CAACD,KAAKG,EAAE,CAAC,YAAfF,kBAAmB,EAAE;IACtC,2EAA2E;IAC3E,yEAAyE;IACzE,OAAOD,KAAKI,MAAM,GAAGF,WAAW;SAACA,aAAAA,QAAQ,CAAC,EAAE,YAAXA,aAAe,CAAC;KAAE;AACrD;AAEA;;;;;;;;;CASC,GACD;;;;;;;;;CASC,GACD,MAAMG,aAAa,CACjBC,QAEAC,OAAOC,WAAW,CAChBF,MACGG,MAAM,CAACC,CAAAA,QAASA,MAAMC,OAAO,CAACC,KAAK,CAACC,MAAM,GAAG,GAC7CC,GAAG,CAACJ,CAAAA;YAAyBA;eAAhB;YAACA,MAAMV,IAAI,CAACG,EAAE;aAAEO,wBAAAA,MAAMC,OAAO,CAACC,KAAK,CAAC,EAAE,qBAAtBF,sBAAwBK,IAAI;SAAC;;AAGjE,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,OAAOtB,OACZN,OACA9C,QACAsC,YACAsC,UACAF,mBAAAA,SAAS1D,KAAK,YAAd0D,mBAAkB;QAEtB;QAEA,MAAMrG,OAAOiE,WAAWhD,KAAK,CAACoF,SAASN,SAAS,CAAC;QACjD,IAAI,CAAC/F,MAAM;YACT,OAAO,OAAOwE,OACZC,OACA9C,QACAuC,UACA,CAAC,KAAK,EAAEtB,OAAOyD,SAASN,SAAS,EAAE,uBAAuB,EAAE9B,WAAWmB,IAAI,CAAC,CAAC,CAAC,EAC9E,+CACA;gBAAEnB,YAAYA,WAAWmB,IAAI;YAAC;QAElC;QAEA,MAAMqB,WAAWF,QAAQhF,IAAI,CAACb,CAAAA,QAASA,MAAMV,IAAI,CAACG,EAAE,KAAKH,KAAKG,EAAE;QAEhE,IAAIsG,aAAatF,WAAW;YAC1B,OAAO,OAAOmE,KAAKb,OAAO+B,eAAe;gBACvClG,OAAOiG;gBACPb,YAAYW,SAASN,SAAS;YAChC;QACF;QAEA,IAAIU,SAAS9F,OAAO,CAACgC,KAAK,KAAKxB,WAAW;YACxC,OAAO,OAAOmE,KAAKb,OAAO+B,eAAe;gBACvClG,OAAOiG;gBACPb,YAAYW,SAASN,SAAS,GAAG;YACnC;QACF;QAEA,MAAMpD,QAAQ8D,SAAS9F,OAAO,CAACgC,KAAK;QACpC,IAAI0B,iBAAiBkC,UAAU;YAC7B,OAAO,OAAO/B,OACZC,OACA9C,QACAuC,UACAvB,OACA,iCACA;gBAAEsB,YAAYA,WAAWmB,IAAI;gBAAErB,QAAQ/D,KAAKG,EAAE;YAAC;QAEnD;QAEA,OAAOsE,MAAMI,MAAM,CAAClD,QAAQ,gBAAgBgB;QAC5C,OAAO,OAAOoC,OAAON,OAAO9C,QAAQsC,YAAYsC,SAAS5D;IAC3D,GAAG"}
1
+ {"version":3,"sources":["../../src/engine/run-saga.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Effect } from 'effect';\n\nimport {\n type SagaCall,\n type SagaCallOutcome,\n sagaCommandId,\n type SagaDefinition,\n type SagaInputs,\n type SagaStep,\n type SagaStepInput,\n type SagaStepOutcome,\n} from '../contracts/saga-definition.js';\nimport { SagaDispatcherTag } from '../ports/saga-dispatcher.js';\nimport {\n type SagaInstance,\n type SagaStore,\n SagaStoreTag,\n} from '../ports/saga-store.js';\nimport { resolveBodyTemplate, resolveTemplate } from './resolve-template.js';\n\nexport type { SagaInputs, SagaStepInput };\n\n/**\n * The steps that have run, kept with their outcomes.\n *\n * Paired rather than looked back up by id, because a lookup introduces a\n * not-found branch that cannot happen — and an unreachable branch is a line\n * nothing can ever prove correct. A resumed walk rebuilds this from the stored\n * outcomes, which is the one place the lookup does happen and can genuinely\n * fail.\n */\ntype Taken = Array<{ step: SagaStep; outcome: SagaStepOutcome }>;\n\nexport interface RunSagaOptions {\n readonly sagaId: string;\n readonly definition: SagaDefinition;\n readonly inputs: SagaInputs;\n}\n\n/** How a run ended. */\nexport interface SagaResult {\n readonly state: 'COMPLETED' | 'COMPENSATED' | 'STRANDED';\n readonly outcomes: readonly SagaStepOutcome[];\n readonly error?: string;\n}\n\n/**\n * What one element of a `fanOutFrom` step is dispatched with.\n *\n * The earlier call's body travels as `outcome` rather than `input`, which is the\n * same scope a compensation resolves against and for the same reason: the id\n * being addressed was minted by the participant and is in its response.\n */\ninterface DerivedElement {\n readonly input: SagaStepInput;\n readonly scope: Record<string, unknown>;\n}\n\nconst inputsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n): readonly SagaStepInput[] => {\n const declared = inputs[step.id] ?? [];\n // A non-fan-out step makes exactly one call whether or not it was given an\n // input, so an absent entry is an empty body rather than a skipped step.\n return step.fanOut ? declared : [declared[0] ?? {}];\n};\n\n/**\n * The elements a step actually dispatches: derived from an earlier step's\n * successful calls when it declares `fanOutFrom`, and from the caller's input\n * otherwise.\n *\n * ⚠️ **A `fanOutFrom` step ignores whatever the caller supplied for it.** The\n * cardinality is the earlier step's, and taking the caller's would let a\n * checkout convert a hold it never took — or, more likely, silently convert\n * none, which is how a saga reports COMPLETED with the goods still held.\n */\n/**\n * What every step can point at: the **first successful call** of each step that\n * has already run, by step id.\n *\n * First rather than all, because a template naming a fan-out step is ambiguous\n * by construction — \"the order id\" is one value and \"the reservation ids\" are\n * many, and the many case is what `fanOutFrom` exists for. Keeping this to the\n * unambiguous case is what stops `{steps.reserve.data.id}` quietly meaning\n * \"whichever hold happened to be first\".\n */\nconst stepsScope = (\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): Record<string, unknown> =>\n Object.fromEntries(\n taken\n .filter(entry => entry.outcome.calls.length > 0)\n .map(entry => [entry.step.id, entry.outcome.calls[0]?.body]),\n );\n\nconst elementsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): readonly DerivedElement[] => {\n const steps = stepsScope(taken);\n\n if (step.fanOutFrom === undefined) {\n return inputsFor(step, inputs).map(input => ({\n input,\n scope: { input: input.body, steps },\n }));\n }\n\n const source = taken.find(entry => entry.step.id === step.fanOutFrom);\n const body = inputs[step.id]?.[0]?.body;\n\n return (source?.outcome.calls ?? []).map(call => ({\n // ⚠️ The organization the *earlier call* acted for, never the caller's.\n // A tenant-plane participant resolves its handle from the header, so a\n // conversion dispatched without it is refused `400` and the hold expires\n // under a buyer who has already been charged.\n input: { body, organizationId: call.organizationId },\n scope: { outcome: call.body, input: body, steps },\n }));\n};\n\nconst dispatchCall = (\n step: SagaStep,\n call: SagaCall,\n sagaId: string,\n index: number,\n input: SagaStepInput,\n scope: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n const dispatcher = yield* SagaDispatcherTag;\n return yield* dispatcher.dispatch({\n participant: step.participant,\n call: { method: call.method, path: resolveTemplate(call.path, scope) },\n commandId: sagaCommandId(\n sagaId,\n step.id,\n step.fanOut ? index : undefined,\n ),\n organizationId: input.organizationId,\n body:\n call.method === 'GET' || call.method === 'DELETE'\n ? undefined\n : resolveBodyTemplate(input.body, scope),\n });\n });\n\n/**\n * Run one step: every call it makes, in order, stopping at the first refusal.\n *\n * Returns the calls that **succeeded** alongside the failure, because those are\n * exactly the calls a compensation has to undo — see {@link compensateStep}.\n */\nconst runStep = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const calls: SagaCallOutcome[] = [];\n\n for (const [index, element] of elements.entries()) {\n const { input } = element;\n const response = yield* dispatchCall(\n step,\n step.command,\n sagaId,\n index,\n input,\n element.scope,\n );\n\n if (!response.ok) {\n // A business refusal. The saga fails *forward* into compensation, and\n // the calls already recorded are the ones that have to come back.\n return {\n calls,\n error: `step '${step.id}' call ${String(index)} refused with ${String(\n response.status,\n )}`,\n };\n }\n\n calls.push({\n index,\n status: response.status,\n body: response.body,\n // Carried so the compensation reaches the same tenant. Without it a\n // release is refused `400` and the saga strands holding stock.\n organizationId: input.organizationId,\n });\n }\n\n return { calls };\n });\n\n/**\n * Undo one step — **one compensation per successful call**, never one per step.\n *\n * ⚠️ This is the whole reason an outcome is kept per fan-out element. Five lines\n * with three holds taken and the fourth refused must release exactly three:\n * compensating the step as a unit would either release nothing or attempt to\n * release two holds that were never taken\n * ([ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md)).\n *\n * Never fails: a compensation's own failure is reported by the caller and must\n * not stop the compensations after it, for the reason ADR 0039 gives — a\n * stranded saga nobody is told about is the same as a lost one.\n */\nconst compensateStep = (\n step: SagaStep,\n sagaId: string,\n outcome: SagaStepOutcome,\n): Effect.Effect<readonly string[], never, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const compensation = step.compensation;\n if (!compensation) {\n return [];\n }\n\n const failures: string[] = [];\n // Reverse order: the last thing done is the first thing undone, which is\n // what a reader expects of a stack of effects and what keeps a future\n // ordering dependency from being an accident.\n for (const call of [...outcome.calls].reverse()) {\n const result = yield* dispatchCall(\n step,\n compensation,\n sagaId,\n call.index,\n // ⚠️ The organization the *call* acted for, not an empty input. A\n // tenant-plane participant resolves its handle from the header, so a\n // compensation without it is refused before it reaches the hold.\n { organizationId: call.organizationId },\n { outcome: call.body },\n ).pipe(\n Effect.catch(error =>\n Effect.succeed({ ok: false, status: 0, body: error }),\n ),\n // A template that no longer matches the participant's response shape\n // throws rather than interpolating `undefined`; that is a defect, and\n // it is reported as a stranded compensation rather than crashing the\n // walk and leaving every later hold in place.\n Effect.catchDefect(defect =>\n Effect.succeed({ ok: false, status: 0, body: defect }),\n ),\n );\n\n // ⚠️ **A `404` is a compensation that has nothing left to undo**, and it\n // counts as success. Compensation is at-least-once the moment a resumed\n // coordinator can retry it, and a participant answering \"no such record\"\n // on the second delivery is describing a flow that *was* reversed. Left\n // as a refusal it strands exactly the sagas that were cleaned up\n // correctly, which is the failure ADR 0054 named on the conversion route\n // and is the same one from the other side.\n if (!result.ok && result.status !== 404) {\n failures.push(\n `compensation for '${step.id}' call ${String(call.index)} failed: ${String(\n result.body,\n )}`,\n );\n }\n }\n\n return failures;\n });\n\n/**\n * How many extra times a step is dispatched once the pivot has committed.\n *\n * Small and immediate on purpose. This is the in-process half of \"roll forward\",\n * and it exists to ride out the blip — a participant restarting, a connection\n * reset — not to be a retry policy. A step that is still refusing after these\n * strands the saga, loudly, because the alternative is a coordinator spinning on\n * a permanent failure while a customer's money sits captured.\n *\n * Durable retry across a coordinator restart is a different mechanism and is not\n * built: see #233, which makes a step dispatch an outbox entry whose relay\n * performs the POST.\n */\nconst POST_PIVOT_RETRIES = 3;\n\n/**\n * Dispatch a step, retrying it `retries` more times while it refuses.\n *\n * ⚠️ **A retry re-dispatches the calls that already succeeded**, and that is\n * safe for exactly one reason: `sagaCommandId(sagaId, step.id, index)` is stable\n * across attempts, so a participant that is idempotent on the command id\n * recognises the replay. ADR 0052 states that requirement on the participant;\n * this is the code that depends on it.\n */\nconst runStepWithRetries = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n retries: number,\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n let result = yield* runStep(step, sagaId, elements);\n\n for (\n let attempt = 1;\n attempt <= retries && result.error !== undefined;\n attempt += 1\n ) {\n yield* Effect.logWarning('retrying a saga step after the pivot').pipe(\n Effect.annotateLogs({\n sagaId,\n stepId: step.id,\n attempt,\n error: result.error,\n }),\n );\n result = yield* runStep(step, sagaId, elements);\n }\n\n return result;\n });\n\n/** Pair each recorded outcome with the step that produced it. */\nconst rebuildTaken = (\n definition: SagaDefinition,\n outcomes: readonly SagaStepOutcome[],\n): Taken | { readonly unknownStep: string } => {\n const taken: Taken = [];\n for (const outcome of outcomes) {\n const step = definition.steps.find(\n candidate => candidate.id === outcome.stepId,\n );\n // ⚠️ Not skipped. An outcome naming a step the definition no longer has\n // means the definition changed under a live instance, so the flow this\n // record describes and the flow the engine would walk are different flows.\n // Carrying on would compensate the wrong steps in the wrong order.\n if (!step) {\n return { unknownStep: outcome.stepId };\n }\n taken.push({ step, outcome });\n }\n return taken;\n};\n\n/** Whether the point of no return is behind us, read off what actually ran. */\nconst pivotCommittedIn = (taken: Taken): boolean =>\n taken.some(\n entry => entry.step.kind === 'pivot' && entry.outcome.error === undefined,\n );\n\n/**\n * Settle a saga that cannot go forward and cannot be reversed, loudly.\n *\n * ⚠️ The message is a parameter because these are **different operational\n * events** and each is grepped for on its own: money is captured behind a\n * pivot, a release was refused and stock is still held, a definition changed\n * under a live instance. Collapsing them into one string would make the log\n * line say only that something is wrong.\n */\nconst strand = (\n store: SagaStore,\n sagaId: string,\n outcomes: readonly SagaStepOutcome[],\n error: string,\n message: string,\n log: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n yield* Effect.logError(message).pipe(\n Effect.annotateLogs({ sagaId, error, ...log }),\n );\n yield* store.settle(sagaId, 'STRANDED', error);\n return { state: 'STRANDED', outcomes, error } as const;\n });\n\n/**\n * Unwind every compensatable step already taken, newest first.\n *\n * Shared by the in-process walk and by a resumed one, which is the whole reason\n * it is a function: a coordinator that died *while* compensating comes back\n * into exactly this loop, and the steps it already gave back carry\n * `compensated` so they are not given back twice.\n */\nconst unwind = (\n store: SagaStore,\n sagaId: string,\n definition: SagaDefinition,\n taken: Taken,\n error: string,\n): Effect.Effect<SagaResult, EntifixConnError, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const outcomes = taken.map(entry => entry.outcome);\n const failures: string[] = [];\n\n for (const done of [...taken].reverse()) {\n if (done.outcome.compensated === true) {\n continue;\n }\n const stepFailures = yield* compensateStep(\n done.step,\n sagaId,\n done.outcome,\n );\n failures.push(...stepFailures);\n // Marked only when the step came back whole. A partial failure stays\n // unmarked so a later resume retries it — safe because a compensation\n // with nothing left to undo answers `404`, which is a success above.\n if (stepFailures.length === 0) {\n yield* store.markCompensated(sagaId, done.step.id);\n }\n }\n\n if (failures.length > 0) {\n // ⚠️ Surfaced, never swallowed. This is the state that leaves a\n // reservation held and — once payment lands — a customer charged, and\n // ADR 0039 names it as the failure class nobody plans for.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga compensation failed',\n { definition: definition.name, failures: failures.join('; ') },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATED', error);\n return { state: 'COMPENSATED', outcomes, error };\n });\n\n/**\n * Dispatch the definition's steps from `startIndex` on, and unwind on a refusal.\n *\n * The state transition is persisted **before** each dispatch, so a crash leaves\n * a record that says what was actually attempted (ADR 0028, extended to\n * commands by ADR 0039).\n *\n * ⚠️ **Once the pivot has committed, nothing is unwound.** That is what a pivot\n * means, and the walk has to know it rather than the definition merely declaring\n * it: `compensateStep` no-ops on a step that declares no compensation, so an\n * unconditional unwind after a successful capture would skip the pivot in\n * silence and then delete the order behind it and release the holds behind that\n * — money taken, goods back on sale, every probe green. The step is retried\n * instead, and a saga that still cannot go forward is settled `STRANDED` and\n * logged, because ADR 0039 is explicit that a stranded saga nobody is told about\n * is the same as a lost one.\n */\nconst walk = (\n store: SagaStore,\n options: RunSagaOptions,\n from: { readonly taken: Taken; readonly startIndex: number },\n): Effect.Effect<SagaResult, EntifixConnError, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const { sagaId, definition, inputs } = options;\n // Step and outcome are kept **together**: looking the step back up by id\n // would introduce a not-found branch that cannot happen, and an unreachable\n // branch is a line nothing can ever prove correct.\n const taken = from.taken;\n const outcomes = () => taken.map(entry => entry.outcome);\n\n // The point of no return, once it is behind us. Tracked rather than read off\n // the definition because what matters is not that a pivot exists but that it\n // *committed* — a pivot that refuses is still fully reversible, and is the\n // ordinary compensation case below.\n let pivotCommitted = pivotCommittedIn(taken);\n\n for (\n let index = from.startIndex;\n index < definition.steps.length;\n index++\n ) {\n const step = definition.steps[index];\n /* v8 ignore next 3 -- the loop bound makes this unreachable; it exists\n because `noUncheckedIndexedAccess` cannot see that. */\n if (!step) {\n continue;\n }\n\n yield* store.beginStep(sagaId, index);\n const { calls, error } = yield* runStepWithRetries(\n step,\n sagaId,\n elementsFor(step, inputs, taken),\n pivotCommitted ? POST_PIVOT_RETRIES : 0,\n );\n\n const outcome: SagaStepOutcome = {\n stepId: step.id,\n calls,\n ...(error === undefined ? {} : { error }),\n };\n taken.push({ step, outcome });\n yield* store.recordOutcome(sagaId, outcome);\n\n if (error === undefined) {\n if (step.kind === 'pivot') {\n pivotCommitted = true;\n }\n continue;\n }\n\n if (pivotCommitted) {\n // ⚠️ Forward or nowhere. Compensating from here would undo steps whose\n // effects the pivot has already been paid for.\n return yield* strand(\n store,\n sagaId,\n outcomes(),\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n // Unwind. The failing step's own successful calls are compensated too —\n // a fan-out step that took three holds before its fourth was refused has\n // three to give back.\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, taken, error);\n }\n\n yield* store.settle(sagaId, 'COMPLETED');\n return { state: 'COMPLETED', outcomes: outcomes() };\n });\n\n/**\n * Start a flow and walk it to a terminal state.\n *\n * ⚠️ **Synchronous, and that is the buyer's requirement.** A checkout needs a\n * yes/no now, so this answers the settled result. What {@link resumeSaga} adds\n * is durability *behind* that answer: if this process dies mid-walk, the record\n * it has been writing all along is enough for another one to finish the flow.\n */\nexport const runSaga = (\n options: RunSagaOptions,\n): Effect.Effect<\n SagaResult,\n EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { sagaId, definition, inputs } = options;\n\n yield* store.start({\n sagaId,\n definition: definition.name,\n state: 'RUNNING',\n stepIndex: 0,\n outcomes: [],\n // ⚠️ Persisted, because a resume has nothing to dispatch without it: a\n // fan-out step's cardinality *is* its input's length (ADR 0055).\n inputs,\n resumeAttempts: 0,\n createdAt: new Date().toISOString(),\n });\n\n return yield* walk(store, options, { taken: [], startIndex: 0 });\n });\n\nexport interface ResumeSagaOptions {\n readonly instance: SagaInstance;\n readonly definition: SagaDefinition;\n /** Past this many sweeps, the instance is surfaced instead of retried. */\n readonly maxResumeAttempts: number;\n}\n\n/**\n * Finish a flow another coordinator abandoned.\n *\n * ⚠️ **Where to re-enter is derived, never stored.** A resume point written\n * beside the outcomes would be a second record of the same fact, free to\n * disagree with them; the outcomes already say what happened, and\n * `beginStep`-before-dispatch means `stepIndex` says what was attempted. The\n * four cases are exhaustive:\n *\n * - the step at `stepIndex` recorded no outcome — the process died during the\n * dispatch, so **re-dispatch it**. Safe because `sagaCommandId` is stable\n * across attempts and every participant claims it in its own command inbox,\n * so calls that did land are recognised as replays rather than repeated\n * (ADR 0052).\n * - it recorded a successful outcome — the process died between\n * `recordOutcome` and the next `beginStep`, so **start at the one after**.\n * - it recorded a refusal — the process died deciding what to do about it, so\n * **re-enter that decision**: unwind, or strand if the pivot had committed.\n * - the instance is `COMPENSATING` — it died mid-unwind, so **continue the\n * unwind**, skipping steps already marked `compensated`.\n */\nexport const resumeSaga = (\n options: ResumeSagaOptions,\n): Effect.Effect<\n SagaResult,\n EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { instance, definition, maxResumeAttempts } = options;\n const { sagaId, outcomes } = instance;\n\n if (instance.resumeAttempts > maxResumeAttempts) {\n // Surfaced rather than retried forever. A coordinator spinning on a\n // permanent failure is how money stays captured with nobody told.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n instance.error ??\n `resumed ${String(instance.resumeAttempts - 1)} times without settling`,\n 'saga abandoned after too many resumes',\n {\n definition: definition.name,\n resumeAttempts: instance.resumeAttempts,\n },\n );\n }\n\n const rebuilt = rebuildTaken(definition, outcomes);\n if ('unknownStep' in rebuilt) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `recorded step '${rebuilt.unknownStep}' is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const resumeOptions: RunSagaOptions = {\n sagaId,\n definition,\n inputs: instance.inputs,\n };\n\n if (instance.state === 'COMPENSATING') {\n return yield* unwind(\n store,\n sagaId,\n definition,\n rebuilt,\n instance.error ?? 'compensation resumed',\n );\n }\n\n const step = definition.steps[instance.stepIndex];\n if (!step) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `step ${String(instance.stepIndex)} is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const recorded = rebuilt.find(entry => entry.step.id === step.id);\n\n if (recorded === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex,\n });\n }\n\n if (recorded.outcome.error === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex + 1,\n });\n }\n\n const error = recorded.outcome.error;\n if (pivotCommittedIn(rebuilt)) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, rebuilt, error);\n });\n"],"names":["Effect","sagaCommandId","SagaDispatcherTag","SagaStoreTag","resolveBodyTemplate","resolveTemplate","inputsFor","step","inputs","declared","id","fanOut","stepsScope","taken","Object","fromEntries","filter","entry","outcome","calls","length","map","body","elementsFor","steps","fanOutFrom","undefined","input","scope","source","find","call","organizationId","dispatchCall","sagaId","index","gen","dispatcher","dispatch","participant","method","path","commandId","runStep","elements","element","entries","response","command","ok","error","String","status","push","compensateStep","compensation","failures","reverse","result","pipe","catch","succeed","catchDefect","defect","POST_PIVOT_RETRIES","runStepWithRetries","retries","attempt","logWarning","annotateLogs","stepId","rebuildTaken","definition","outcomes","candidate","unknownStep","pivotCommittedIn","some","kind","strand","store","message","log","logError","settle","state","unwind","done","compensated","stepFailures","markCompensated","name","join","walk","options","from","pivotCommitted","startIndex","beginStep","recordOutcome","runSaga","start","stepIndex","resumeAttempts","createdAt","Date","toISOString","resumeSaga","instance","maxResumeAttempts","rebuilt","resumeOptions","recorded"],"mappings":";AACA,SAASA,MAAM,QAAQ,SAAS;AAEhC,SAGEC,aAAa,QAMR,kCAAkC;AACzC,SAASC,iBAAiB,QAAQ,8BAA8B;AAChE,SAGEC,YAAY,QACP,yBAAyB;AAChC,SAASC,mBAAmB,EAAEC,eAAe,QAAQ,wBAAwB;AAwC7E,MAAMC,YAAY,CAChBC,MACAC;QAEiBA,iBAGgBC;IAHjC,MAAMA,YAAWD,kBAAAA,MAAM,CAACD,KAAKG,EAAE,CAAC,YAAfF,kBAAmB,EAAE;IACtC,2EAA2E;IAC3E,yEAAyE;IACzE,OAAOD,KAAKI,MAAM,GAAGF,WAAW;SAACA,aAAAA,QAAQ,CAAC,EAAE,YAAXA,aAAe,CAAC;KAAE;AACrD;AAEA;;;;;;;;;CASC,GACD;;;;;;;;;CASC,GACD,MAAMG,aAAa,CACjBC,QAEAC,OAAOC,WAAW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AEA,OAAOsE,MAAMI,MAAM,CAAClD,QAAQ,gBAAgBgB;QAC5C,OAAO,OAAOoC,OAAON,OAAO9C,QAAQsC,YAAYsC,SAAS5D;IAC3D,GAAG"}
@@ -37,7 +37,7 @@ export declare function acceptTransaction(): Effect.Effect<{
37
37
  readonly handles: readonly LockHandle[];
38
38
  }, import("@entifix/core").EntifixError, import("../index.js").TransactionHandlerTag | TransactionOutboxTag | import("../index.js").LockServiceTag | CommandTag | EventSourceTag>;
39
39
  /** What {@link acceptTransaction} decided — a fresh command, or a replay. */
40
- export type AcceptOutcome = Effect.Effect.Success<ReturnType<typeof acceptTransaction>>;
40
+ export type AcceptOutcome = Effect.Success<ReturnType<typeof acceptTransaction>>;
41
41
  /**
42
42
  * Execute phase (asynchronous continuation). Never leaks locks.
43
43
  *
@@ -1 +1 @@
1
- {"version":3,"file":"run-transaction.d.ts","sourceRoot":"","sources":["../../src/engine/run-transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EACL,UAAU,EAGX,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAS3D;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB;;;;;;kLAgBhC;AAED,6EAA6E;AAC7E,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAC/C,UAAU,CAAC,OAAO,iBAAiB,CAAC,CACrC,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,SAAS,UAAU,EAAE,uKA2DjE"}
1
+ {"version":3,"file":"run-transaction.d.ts","sourceRoot":"","sources":["../../src/engine/run-transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EACL,UAAU,EAGX,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAS3D;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB;;;;;;kLAgBhC;AAED,6EAA6E;AAC7E,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,CACxC,UAAU,CAAC,OAAO,iBAAiB,CAAC,CACrC,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,SAAS,UAAU,EAAE,uKA2DjE"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/engine/run-transaction.ts"],"sourcesContent":["import { Effect } from 'effect';\n\nimport { acceptedEvent, failedEvent } from '../contracts/event.js';\nimport { TransactionOutboxTag } from '../contracts/outbox.js';\nimport {\n CommandTag,\n LockHandlesTag,\n OutcomeTag,\n} from '../mixins/transaction-mixins.js';\nimport { EventSourceTag } from '../ports/event-source.js';\nimport type { LockHandle } from '../ports/lock-service.js';\nimport {\n executeUCFactory,\n freeUCFactory,\n lockUCFactory,\n rollbackUCFactory,\n validateUCFactory,\n} from '../use-case/facade.uc.js';\n\n/**\n * The saga engine, split at the 202 boundary so validation/lock failures are\n * synchronous (mapped to `400`/`409`) while the write runs asynchronously:\n *\n * - {@link acceptTransaction} — validate -> claim -> lock. Runs before the\n * service answers `202`; its failures are the client's answer.\n * - {@link completeTransaction} — execute -> free, or rollback -> record\n * `failed` -> free. Forked after `202`; `free` always runs via `ensuring`, so\n * locks never leak on a rollback path.\n *\n * **The engine never publishes.** Every event it produces goes to the\n * {@link TransactionOutbox}, and a relay carries the outbox to the broker. That\n * is the whole fix for the dual write: an event that only ever existed in a\n * `bus.publish` call between two Mongo writes is lost when the broker is down,\n * and the transaction is then mislabelled `STALE` despite having succeeded.\n */\n\n/**\n * Accept phase (synchronous).\n *\n * The order is deliberate: validate, then **claim, then lock**. The claim is the\n * outbox insert for the `accepted` event, and its uniqueness on\n * the message id (`<transactionId>:<step>`) is what makes the client-generated\n * id an idempotency key — a replayed command is recognised here, before a lock is taken and\n * before any work is forked. Locking first would make a retry queue behind its\n * own original.\n */\nexport function acceptTransaction() {\n return Effect.gen(function* () {\n const command = yield* CommandTag;\n const outbox = yield* TransactionOutboxTag;\n const source = yield* EventSourceTag;\n\n yield* validateUCFactory();\n\n const claim = yield* outbox.enqueue(acceptedEvent(command, source));\n if (claim === 'duplicate') {\n return { status: 'duplicate' } as const;\n }\n\n const handles = yield* lockUCFactory();\n return { status: 'accepted', handles } as const;\n });\n}\n\n/** What {@link acceptTransaction} decided — a fresh command, or a replay. */\nexport type AcceptOutcome = Effect.Effect.Success<\n ReturnType<typeof acceptTransaction>\n>;\n\n/**\n * Execute phase (asynchronous continuation). Never leaks locks.\n *\n * The success arm records **nothing**: `execute` is contractually required to\n * have written the `completed` entry in the same storage transaction as its\n * state change, because only the handler holds the session that can make those\n * two writes one. Recording it here as well would reintroduce the dual write in\n * the opposite direction — an event announcing a write that may have rolled\n * back.\n *\n * The failure arm does record, because there is no state change left to be\n * atomic with: the rollback has already undone it.\n */\nexport function completeTransaction(handles: readonly LockHandle[]) {\n return Effect.gen(function* () {\n const command = yield* CommandTag;\n const outbox = yield* TransactionOutboxTag;\n const source = yield* EventSourceTag;\n\n const free = freeUCFactory().pipe(\n Effect.provideService(LockHandlesTag, handles),\n Effect.ignore,\n );\n\n yield* executeUCFactory().pipe(\n Effect.matchEffect({\n onSuccess: () => Effect.void,\n onFailure: error =>\n rollbackUCFactory().pipe(\n Effect.provideService(OutcomeTag, undefined),\n // The compensation's own failure is reported before it is\n // discarded. Discarding it is right — the client is polling for a\n // terminal state and must still get one, so the `failed` record\n // below is written either way — but until this line the error\n // reached nothing: not the record, whose `error` is `execute`'s,\n // and not the log. An operator reading `FAILED` then reasonably\n // concluded the write had been undone when it had not.\n //\n // Annotations rather than message arguments, matching the outbox\n // relay: they reach a sink as structured fields, so a stranded\n // transaction is queryable by its id instead of being parsed out of\n // a rendered string.\n //\n // That is true as of this change and was not before it. A service's\n // Effect→tooling logger bridge (`observability.ts`) dropped\n // `annotations` outright and matched Effect's level labels with the\n // wrong casing, so every annotated field was discarded and every\n // level arrived as INFO — measured in Loki while verifying this log.\n Effect.tapError(rollbackError =>\n Effect.logError('transaction rollback failed').pipe(\n Effect.annotateLogs({\n transactionId: command.transactionId,\n entity: command.entity,\n executeError: String(error),\n rollbackError: String(rollbackError),\n }),\n ),\n ),\n Effect.ignore,\n Effect.andThen(\n // Best-effort: the transaction already failed, and a store that\n // cannot take the failure record must not turn into an unhandled\n // defect in a forked daemon. The recovery sweep is what notices.\n Effect.ignore(\n outbox.enqueue(failedEvent(command, error, source)),\n ),\n ),\n ),\n }),\n Effect.ensuring(free),\n );\n });\n}\n"],"names":["Effect","acceptedEvent","failedEvent","TransactionOutboxTag","CommandTag","LockHandlesTag","OutcomeTag","EventSourceTag","executeUCFactory","freeUCFactory","lockUCFactory","rollbackUCFactory","validateUCFactory","acceptTransaction","gen","command","outbox","source","claim","enqueue","status","handles","completeTransaction","free","pipe","provideService","ignore","matchEffect","onSuccess","void","onFailure","error","undefined","tapError","rollbackError","logError","annotateLogs","transactionId","entity","executeError","String","andThen","ensuring"],"mappings":"AAAA,SAASA,MAAM,QAAQ,SAAS;AAEhC,SAASC,aAAa,EAAEC,WAAW,QAAQ,wBAAwB;AACnE,SAASC,oBAAoB,QAAQ,yBAAyB;AAC9D,SACEC,UAAU,EACVC,cAAc,EACdC,UAAU,QACL,kCAAkC;AACzC,SAASC,cAAc,QAAQ,2BAA2B;AAE1D,SACEC,gBAAgB,EAChBC,aAAa,EACbC,aAAa,EACbC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,CAAC,+BAA+BX,IAAI,CACjDxB,OAAOoC,YAAY,CAAC;wBAClBC,eAAetB,QAAQsB,aAAa;wBACpCC,QAAQvB,QAAQuB,MAAM;wBACtBC,cAAcC,OAAOT;wBACrBG,eAAeM,OAAON;oBACxB,MAGJlC,OAAO0B,MAAM,EACb1B,OAAOyC,OAAO,CACZ,gEAAgE;gBAChE,iEAAiE;gBACjE,iEAAiE;gBACjEzC,OAAO0B,MAAM,CACXV,OAAOG,OAAO,CAACjB,YAAYa,SAASgB,OAAOd;QAIrD,IACAjB,OAAO0C,QAAQ,CAACnB;IAEpB;AACF"}
1
+ {"version":3,"sources":["../../src/engine/run-transaction.ts"],"sourcesContent":["import { Effect } from 'effect';\n\nimport { acceptedEvent, failedEvent } from '../contracts/event.js';\nimport { TransactionOutboxTag } from '../contracts/outbox.js';\nimport {\n CommandTag,\n LockHandlesTag,\n OutcomeTag,\n} from '../mixins/transaction-mixins.js';\nimport { EventSourceTag } from '../ports/event-source.js';\nimport type { LockHandle } from '../ports/lock-service.js';\nimport {\n executeUCFactory,\n freeUCFactory,\n lockUCFactory,\n rollbackUCFactory,\n validateUCFactory,\n} from '../use-case/facade.uc.js';\n\n/**\n * The saga engine, split at the 202 boundary so validation/lock failures are\n * synchronous (mapped to `400`/`409`) while the write runs asynchronously:\n *\n * - {@link acceptTransaction} — validate -> claim -> lock. Runs before the\n * service answers `202`; its failures are the client's answer.\n * - {@link completeTransaction} — execute -> free, or rollback -> record\n * `failed` -> free. Forked after `202`; `free` always runs via `ensuring`, so\n * locks never leak on a rollback path.\n *\n * **The engine never publishes.** Every event it produces goes to the\n * {@link TransactionOutbox}, and a relay carries the outbox to the broker. That\n * is the whole fix for the dual write: an event that only ever existed in a\n * `bus.publish` call between two Mongo writes is lost when the broker is down,\n * and the transaction is then mislabelled `STALE` despite having succeeded.\n */\n\n/**\n * Accept phase (synchronous).\n *\n * The order is deliberate: validate, then **claim, then lock**. The claim is the\n * outbox insert for the `accepted` event, and its uniqueness on\n * the message id (`<transactionId>:<step>`) is what makes the client-generated\n * id an idempotency key — a replayed command is recognised here, before a lock is taken and\n * before any work is forked. Locking first would make a retry queue behind its\n * own original.\n */\nexport function acceptTransaction() {\n return Effect.gen(function* () {\n const command = yield* CommandTag;\n const outbox = yield* TransactionOutboxTag;\n const source = yield* EventSourceTag;\n\n yield* validateUCFactory();\n\n const claim = yield* outbox.enqueue(acceptedEvent(command, source));\n if (claim === 'duplicate') {\n return { status: 'duplicate' } as const;\n }\n\n const handles = yield* lockUCFactory();\n return { status: 'accepted', handles } as const;\n });\n}\n\n/** What {@link acceptTransaction} decided — a fresh command, or a replay. */\nexport type AcceptOutcome = Effect.Success<\n ReturnType<typeof acceptTransaction>\n>;\n\n/**\n * Execute phase (asynchronous continuation). Never leaks locks.\n *\n * The success arm records **nothing**: `execute` is contractually required to\n * have written the `completed` entry in the same storage transaction as its\n * state change, because only the handler holds the session that can make those\n * two writes one. Recording it here as well would reintroduce the dual write in\n * the opposite direction — an event announcing a write that may have rolled\n * back.\n *\n * The failure arm does record, because there is no state change left to be\n * atomic with: the rollback has already undone it.\n */\nexport function completeTransaction(handles: readonly LockHandle[]) {\n return Effect.gen(function* () {\n const command = yield* CommandTag;\n const outbox = yield* TransactionOutboxTag;\n const source = yield* EventSourceTag;\n\n const free = freeUCFactory().pipe(\n Effect.provideService(LockHandlesTag, handles),\n Effect.ignore,\n );\n\n yield* executeUCFactory().pipe(\n Effect.matchEffect({\n onSuccess: () => Effect.void,\n onFailure: error =>\n rollbackUCFactory().pipe(\n Effect.provideService(OutcomeTag, undefined),\n // The compensation's own failure is reported before it is\n // discarded. Discarding it is right — the client is polling for a\n // terminal state and must still get one, so the `failed` record\n // below is written either way — but until this line the error\n // reached nothing: not the record, whose `error` is `execute`'s,\n // and not the log. An operator reading `FAILED` then reasonably\n // concluded the write had been undone when it had not.\n //\n // Annotations rather than message arguments, matching the outbox\n // relay: they reach a sink as structured fields, so a stranded\n // transaction is queryable by its id instead of being parsed out of\n // a rendered string.\n //\n // That is true as of this change and was not before it. A service's\n // Effect→tooling logger bridge (`observability.ts`) dropped\n // `annotations` outright and matched Effect's level labels with the\n // wrong casing, so every annotated field was discarded and every\n // level arrived as INFO — measured in Loki while verifying this log.\n Effect.tapError(rollbackError =>\n Effect.logError('transaction rollback failed').pipe(\n Effect.annotateLogs({\n transactionId: command.transactionId,\n entity: command.entity,\n executeError: String(error),\n rollbackError: String(rollbackError),\n }),\n ),\n ),\n Effect.ignore,\n Effect.andThen(\n // Best-effort: the transaction already failed, and a store that\n // cannot take the failure record must not turn into an unhandled\n // defect in a forked daemon. The recovery sweep is what notices.\n Effect.ignore(\n outbox.enqueue(failedEvent(command, error, source)),\n ),\n ),\n ),\n }),\n Effect.ensuring(free),\n );\n });\n}\n"],"names":["Effect","acceptedEvent","failedEvent","TransactionOutboxTag","CommandTag","LockHandlesTag","OutcomeTag","EventSourceTag","executeUCFactory","freeUCFactory","lockUCFactory","rollbackUCFactory","validateUCFactory","acceptTransaction","gen","command","outbox","source","claim","enqueue","status","handles","completeTransaction","free","pipe","provideService","ignore","matchEffect","onSuccess","void","onFailure","error","undefined","tapError","rollbackError","logError","annotateLogs","transactionId","entity","executeError","String","andThen","ensuring"],"mappings":"AAAA,SAASA,MAAM,QAAQ,SAAS;AAEhC,SAASC,aAAa,EAAEC,WAAW,QAAQ,wBAAwB;AACnE,SAASC,oBAAoB,QAAQ,yBAAyB;AAC9D,SACEC,UAAU,EACVC,cAAc,EACdC,UAAU,QACL,kCAAkC;AACzC,SAASC,cAAc,QAAQ,2BAA2B;AAE1D,SACEC,gBAAgB,EAChBC,aAAa,EACbC,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,QACZ,2BAA2B;AAElC;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;CASC,GACD,OAAO,SAASC;IACd,OAAOb,OAAOc,GAAG,CAAC;QAChB,MAAMC,UAAU,OAAOX;QACvB,MAAMY,SAAS,OAAOb;QACtB,MAAMc,SAAS,O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,CACZ,gEAAgE;gBAChE,iEAAiE;gBACjE,iEAAiE;gBACjEzC,OAAO0B,MAAM,CACXV,OAAOG,OAAO,CAACjB,YAAYa,SAASgB,OAAOd;QAIrD,IACAjB,OAAO0C,QAAQ,CAACnB;IAEpB;AACF"}
@@ -2,7 +2,7 @@ import { Context } from 'effect';
2
2
  import type { TransactionCommand } from '../contracts/command.js';
3
3
  import type { LockHandle } from '../ports/lock-service.js';
4
4
  import type { TransactionOutcome } from '../ports/transaction-handler.js';
5
- declare const CommandTag_base: Context.TagClass<CommandTag, "TransactionCommandTag", TransactionCommand<import("@entifix/core").SerializedEntity>>;
5
+ declare const CommandTag_base: Context.ServiceClass<CommandTag, "TransactionCommandTag", TransactionCommand<import("@entifix/core").SerializedEntity>>;
6
6
  /**
7
7
  * The runtime inputs the facade use-cases yield — the transaction analogue of
8
8
  * `EntityTag`/`EntityIdTag`. The engine provides them at the right moment
@@ -10,10 +10,10 @@ declare const CommandTag_base: Context.TagClass<CommandTag, "TransactionCommandT
10
10
  */
11
11
  export declare class CommandTag extends CommandTag_base {
12
12
  }
13
- declare const LockHandlesTag_base: Context.TagClass<LockHandlesTag, "LockHandlesTag", readonly LockHandle[]>;
13
+ declare const LockHandlesTag_base: Context.ServiceClass<LockHandlesTag, "LockHandlesTag", readonly LockHandle[]>;
14
14
  export declare class LockHandlesTag extends LockHandlesTag_base {
15
15
  }
16
- declare const OutcomeTag_base: Context.TagClass<OutcomeTag, "TransactionOutcomeTag", TransactionOutcome | undefined>;
16
+ declare const OutcomeTag_base: Context.ServiceClass<OutcomeTag, "TransactionOutcomeTag", TransactionOutcome | undefined>;
17
17
  export declare class OutcomeTag extends OutcomeTag_base {
18
18
  }
19
19
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"transaction-mixins.d.ts","sourceRoot":"","sources":["../../src/mixins/transaction-mixins.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;;AAE1E;;;;GAIG;AACH,qBAAa,UAAW,SAAQ,eAG7B;CAAG;;AAEN,qBAAa,cAAe,SAAQ,mBAGjC;CAAG;;AAEN,qBAAa,UAAW,SAAQ,eAG7B;CAAG"}
1
+ {"version":3,"file":"transaction-mixins.d.ts","sourceRoot":"","sources":["../../src/mixins/transaction-mixins.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;;AAE1E;;;;GAIG;AACH,qBAAa,UAAW,SAAQ,eAGJ;CAAG;;AAE/B,qBAAa,cAAe,SAAQ,mBAGf;CAAG;;AAExB,qBAAa,UAAW,SAAQ,eAGJ;CAAG"}
@@ -3,11 +3,11 @@ import { Context } from 'effect';
3
3
  * The runtime inputs the facade use-cases yield — the transaction analogue of
4
4
  * `EntityTag`/`EntityIdTag`. The engine provides them at the right moment
5
5
  * (`LockHandlesTag` after `lock`, `OutcomeTag` before `rollback`).
6
- */ export class CommandTag extends Context.Tag('TransactionCommandTag')() {
6
+ */ export class CommandTag extends Context.Service()('TransactionCommandTag') {
7
7
  }
8
- export class LockHandlesTag extends Context.Tag('LockHandlesTag')() {
8
+ export class LockHandlesTag extends Context.Service()('LockHandlesTag') {
9
9
  }
10
- export class OutcomeTag extends Context.Tag('TransactionOutcomeTag')() {
10
+ export class OutcomeTag extends Context.Service()('TransactionOutcomeTag') {
11
11
  }
12
12
 
13
13
  //# sourceMappingURL=transaction-mixins.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mixins/transaction-mixins.ts"],"sourcesContent":["import { Context } from 'effect';\n\nimport type { TransactionCommand } from '../contracts/command.js';\nimport type { LockHandle } from '../ports/lock-service.js';\nimport type { TransactionOutcome } from '../ports/transaction-handler.js';\n\n/**\n * The runtime inputs the facade use-cases yield — the transaction analogue of\n * `EntityTag`/`EntityIdTag`. The engine provides them at the right moment\n * (`LockHandlesTag` after `lock`, `OutcomeTag` before `rollback`).\n */\nexport class CommandTag extends Context.Tag('TransactionCommandTag')<\n CommandTag,\n TransactionCommand\n>() {}\n\nexport class LockHandlesTag extends Context.Tag('LockHandlesTag')<\n LockHandlesTag,\n readonly LockHandle[]\n>() {}\n\nexport class OutcomeTag extends Context.Tag('TransactionOutcomeTag')<\n OutcomeTag,\n TransactionOutcome | undefined\n>() {}\n"],"names":["Context","CommandTag","Tag","LockHandlesTag","OutcomeTag"],"mappings":"AAAA,SAASA,OAAO,QAAQ,SAAS;AAMjC;;;;CAIC,GACD,OAAO,MAAMC,mBAAmBD,QAAQE,GAAG,CAAC;AAGvC;AAEL,OAAO,MAAMC,uBAAuBH,QAAQE,GAAG,CAAC;AAG3C;AAEL,OAAO,MAAME,mBAAmBJ,QAAQE,GAAG,CAAC;AAGvC"}
1
+ {"version":3,"sources":["../../src/mixins/transaction-mixins.ts"],"sourcesContent":["import { Context } from 'effect';\n\nimport type { TransactionCommand } from '../contracts/command.js';\nimport type { LockHandle } from '../ports/lock-service.js';\nimport type { TransactionOutcome } from '../ports/transaction-handler.js';\n\n/**\n * The runtime inputs the facade use-cases yield — the transaction analogue of\n * `EntityTag`/`EntityIdTag`. The engine provides them at the right moment\n * (`LockHandlesTag` after `lock`, `OutcomeTag` before `rollback`).\n */\nexport class CommandTag extends Context.Service<\n CommandTag,\n TransactionCommand\n>()('TransactionCommandTag') {}\n\nexport class LockHandlesTag extends Context.Service<\n LockHandlesTag,\n readonly LockHandle[]\n>()('LockHandlesTag') {}\n\nexport class OutcomeTag extends Context.Service<\n OutcomeTag,\n TransactionOutcome | undefined\n>()('TransactionOutcomeTag') {}\n"],"names":["Context","CommandTag","Service","LockHandlesTag","OutcomeTag"],"mappings":"AAAA,SAASA,OAAO,QAAQ,SAAS;AAMjC;;;;CAIC,GACD,OAAO,MAAMC,mBAAmBD,QAAQE,OAAO,GAG3C;AAA0B;AAE9B,OAAO,MAAMC,uBAAuBH,QAAQE,OAAO,GAG/C;AAAmB;AAEvB,OAAO,MAAME,mBAAmBJ,QAAQE,OAAO,GAG3C;AAA0B"}
@@ -91,7 +91,7 @@ export interface EventBus {
91
91
  */
92
92
  subscribe(subscription: Subscription, handler: (event: DomainEvent) => Effect.Effect<void, EntifixError>): Effect.Effect<void, EntifixConnError>;
93
93
  }
94
- declare const EventBusTag_base: Context.TagClass<EventBusTag, "EventBusTag", EventBus>;
94
+ declare const EventBusTag_base: Context.ServiceClass<EventBusTag, "EventBusTag", EventBus>;
95
95
  export declare class EventBusTag extends EventBusTag_base {
96
96
  }
97
97
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"event-bus.d.ts","sourceRoot":"","sources":["../../src/ports/event-bus.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAChB,YAAY,EACb,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,WAAW,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,WAAW,YAAY;IAC3B;;;;;;;;;OASG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;;;;;OAMG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,gBAAgB,CAAC;IAChC;;;;;;;OAOG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,C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EAC1B,OAAO,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,GACjE,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;CAC1C;;AAED,qBAAa,WAAY,SAAQ,gBAEhC;CAAG"}
@@ -1,5 +1,5 @@
1
1
  import { Context } from 'effect';
2
- export class EventBusTag extends Context.Tag('EventBusTag')() {
2
+ export class EventBusTag extends Context.Service()('EventBusTag') {
3
3
  }
4
4
 
5
5
  //# sourceMappingURL=event-bus.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ports/event-bus.ts"],"sourcesContent":["import type {\n DomainEvent,\n EntifixConnError,\n EntifixError,\n} from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * How a subscriber's queue is shaped, which is a property of the *workload*\n * rather than of the transport (ADR 0030).\n *\n * - `work` — a named, durable queue that survives the consumer's restart and\n * accumulates while it is gone. Replicas share it, so each message reaches\n * exactly one of them. A projection writer, a fold and a settlement consumer\n * all want this.\n * - `broadcast` — a connection-scoped exclusive queue, so every replica\n * receives every message and nothing is retained across a restart. Correct\n * only when the replicas differ from one another — a socket push holding\n * different clients per process.\n *\n * ADR 0029 built the exclusive queue for every subscriber and gave a stated\n * reason: a shared queue delivers each event to one replica, \"which reads as\n * flakiness rather than as a design\". That reasoning is right for `broadcast`\n * and wrong for `work`; it picked broadcast semantics for a workload that is\n * work, at a time when the only subscriber made the difference invisible.\n */\nexport type SubscriptionMode = 'work' | 'broadcast';\n\n/**\n * A subscriber's declared interest, together with the delivery policy the\n * broker enforces for it.\n *\n * The shape mirrors `subscriptions` in `tools/slices/*.slice.ts`, so \"how does\n * this fail\" is answered where it can be checked rather than in a review\n * comment.\n */\nexport interface Subscription {\n /**\n * The **subscribing** slice — the `tools/slices/` key, and half of the queue\n * name.\n *\n * Deliberately not `EventSourceTag`, which is the *emitting* slice: one\n * deployment hosts several slices (ADR 0021 co-deploys `transaction` inside\n * marketplace-admin-service), so a process-wide \"my slice\" would attribute a\n * consumer's queue to whichever slice happened to publish from the same\n * process.\n */\n readonly slice: string;\n /**\n * The event name pattern, used verbatim as the broker's binding —\n * `transaction.*`, `catalog.published`. Filtering in the handler instead is\n * what this exists to prevent: it makes every consumer pay for every\n * publisher's traffic, and it puts the routing rule where no register can\n * check it.\n */\n readonly pattern: string;\n readonly mode: SubscriptionMode;\n /**\n * How many times the broker may deliver a message before dead-lettering it.\n *\n * Enforced by the queue itself rather than by logic each consumer\n * reimplements, so it applies to a redelivery after a crash as well as to one\n * after a nack. `broadcast` queues have no dead-letter path, so the value is\n * carried but unenforced there.\n */\n readonly maxAttempts: number;\n}\n\n/**\n * The domain event bus (RabbitMQ in `@entifix/amqp`). Services publish\n * what happened; interested slices subscribe to the names they declared.\n *\n * Typed on {@link DomainEvent} rather than on any one publisher's payload: a bus\n * that only knew `TransactionEvent` had nothing for ADR 0009's catalog\n * publication to travel in, which would have meant a second framing and a second\n * transport for the same job.\n *\n * The port stays event-typed rather than envelope-typed — the adapter owns the\n * wire framing — so a handler receives the message and its metadata without\n * ever seeing the envelope that carried them.\n */\nexport interface EventBus {\n publish(event: DomainEvent): Effect.Effect<void, EntifixConnError>;\n /**\n * Register a consumer for the events matching `subscription.pattern`.\n *\n * The returned Effect completes once the subscription is established; the\n * handler then runs per delivered event. Delivery is at-least-once, so a\n * handler that is not idempotent must deduplicate on `event.id`.\n *\n * A handler failure is **transient**: the adapter requeues it and the broker\n * counts the redelivery against `maxAttempts`, dead-lettering at the limit. A\n * payload the adapter cannot read is **poison** and is quarantined with zero\n * retries — a message that cannot be deserialized never becomes\n * deserializable, and retrying it only spends the budget of the messages\n * behind it. A *business* failure is neither: that message was processed\n * successfully and already produced its own event (ADR 0030).\n */\n subscribe(\n subscription: Subscription,\n handler: (event: DomainEvent) => Effect.Effect<void, EntifixError>,\n ): Effect.Effect<void, EntifixConnError>;\n}\n\nexport class EventBusTag extends Context.Tag('EventBusTag')<\n EventBusTag,\n EventBus\n>() {}\n"],"names":["Context","EventBusTag","Tag"],"mappings":"AAKA,SAASA,OAAO,QAAqB,SAAS;AAmG9C,OAAO,MAAMC,oBAAoBD,QAAQE,GAAG,CAAC;AAGxC"}
1
+ {"version":3,"sources":["../../src/ports/event-bus.ts"],"sourcesContent":["import type {\n DomainEvent,\n EntifixConnError,\n EntifixError,\n} from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * How a subscriber's queue is shaped, which is a property of the *workload*\n * rather than of the transport (ADR 0030).\n *\n * - `work` — a named, durable queue that survives the consumer's restart and\n * accumulates while it is gone. Replicas share it, so each message reaches\n * exactly one of them. A projection writer, a fold and a settlement consumer\n * all want this.\n * - `broadcast` — a connection-scoped exclusive queue, so every replica\n * receives every message and nothing is retained across a restart. Correct\n * only when the replicas differ from one another — a socket push holding\n * different clients per process.\n *\n * ADR 0029 built the exclusive queue for every subscriber and gave a stated\n * reason: a shared queue delivers each event to one replica, \"which reads as\n * flakiness rather than as a design\". That reasoning is right for `broadcast`\n * and wrong for `work`; it picked broadcast semantics for a workload that is\n * work, at a time when the only subscriber made the difference invisible.\n */\nexport type SubscriptionMode = 'work' | 'broadcast';\n\n/**\n * A subscriber's declared interest, together with the delivery policy the\n * broker enforces for it.\n *\n * The shape mirrors `subscriptions` in `tools/slices/*.slice.ts`, so \"how does\n * this fail\" is answered where it can be checked rather than in a review\n * comment.\n */\nexport interface Subscription {\n /**\n * The **subscribing** slice — the `tools/slices/` key, and half of the queue\n * name.\n *\n * Deliberately not `EventSourceTag`, which is the *emitting* slice: one\n * deployment hosts several slices (ADR 0021 co-deploys `transaction` inside\n * marketplace-admin-service), so a process-wide \"my slice\" would attribute a\n * consumer's queue to whichever slice happened to publish from the same\n * process.\n */\n readonly slice: string;\n /**\n * The event name pattern, used verbatim as the broker's binding —\n * `transaction.*`, `catalog.published`. Filtering in the handler instead is\n * what this exists to prevent: it makes every consumer pay for every\n * publisher's traffic, and it puts the routing rule where no register can\n * check it.\n */\n readonly pattern: string;\n readonly mode: SubscriptionMode;\n /**\n * How many times the broker may deliver a message before dead-lettering it.\n *\n * Enforced by the queue itself rather than by logic each consumer\n * reimplements, so it applies to a redelivery after a crash as well as to one\n * after a nack. `broadcast` queues have no dead-letter path, so the value is\n * carried but unenforced there.\n */\n readonly maxAttempts: number;\n}\n\n/**\n * The domain event bus (RabbitMQ in `@entifix/amqp`). Services publish\n * what happened; interested slices subscribe to the names they declared.\n *\n * Typed on {@link DomainEvent} rather than on any one publisher's payload: a bus\n * that only knew `TransactionEvent` had nothing for ADR 0009's catalog\n * publication to travel in, which would have meant a second framing and a second\n * transport for the same job.\n *\n * The port stays event-typed rather than envelope-typed — the adapter owns the\n * wire framing — so a handler receives the message and its metadata without\n * ever seeing the envelope that carried them.\n */\nexport interface EventBus {\n publish(event: DomainEvent): Effect.Effect<void, EntifixConnError>;\n /**\n * Register a consumer for the events matching `subscription.pattern`.\n *\n * The returned Effect completes once the subscription is established; the\n * handler then runs per delivered event. Delivery is at-least-once, so a\n * handler that is not idempotent must deduplicate on `event.id`.\n *\n * A handler failure is **transient**: the adapter requeues it and the broker\n * counts the redelivery against `maxAttempts`, dead-lettering at the limit. A\n * payload the adapter cannot read is **poison** and is quarantined with zero\n * retries — a message that cannot be deserialized never becomes\n * deserializable, and retrying it only spends the budget of the messages\n * behind it. A *business* failure is neither: that message was processed\n * successfully and already produced its own event (ADR 0030).\n */\n subscribe(\n subscription: Subscription,\n handler: (event: DomainEvent) => Effect.Effect<void, EntifixError>,\n ): Effect.Effect<void, EntifixConnError>;\n}\n\nexport class EventBusTag extends Context.Service<EventBusTag, EventBus>()(\n 'EventBusTag',\n) {}\n"],"names":["Context","EventBusTag","Service"],"mappings":"AAKA,SAASA,OAAO,QAAqB,SAAS;AAmG9C,OAAO,MAAMC,oBAAoBD,QAAQE,OAAO,GAC9C;AACC"}
@@ -1,5 +1,5 @@
1
1
  import { Context } from 'effect';
2
- declare const EventSourceTag_base: Context.TagClass<EventSourceTag, "EventSourceTag", string>;
2
+ declare const EventSourceTag_base: Context.ServiceClass<EventSourceTag, "EventSourceTag", string>;
3
3
  /**
4
4
  * The name of the slice publishing an event — `marketplace-admin`, `order`.
5
5
  *
@@ -1 +1 @@
1
- {"version":3,"file":"event-source.d.ts","sourceRoot":"","sources":["../../src/ports/event-source.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;;AAEjC;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,cAAe,SAAQ,mBAGjC;CAAG"}
1
+ {"version":3,"file":"event-source.d.ts","sourceRoot":"","sources":["../../src/ports/event-source.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;;AAEjC;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,cAAe,SAAQ,mBAEnC;CAAG"}
@@ -14,7 +14,7 @@ import { Context } from 'effect';
14
14
  * (`TenantDatabasePrefix`, `SagaDatabaseName`) rather than read from an
15
15
  * environment variable, so a service that forgets it fails to build its layer
16
16
  * instead of publishing events signed by nobody.
17
- */ export class EventSourceTag extends Context.Tag('EventSourceTag')() {
17
+ */ export class EventSourceTag extends Context.Service()('EventSourceTag') {
18
18
  }
19
19
 
20
20
  //# sourceMappingURL=event-source.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ports/event-source.ts"],"sourcesContent":["import { Context } from 'effect';\n\n/**\n * The name of the slice publishing an event — `marketplace-admin`, `order`.\n *\n * A **slice**, deliberately, and not one of the two nearer alternatives. Not the\n * deployment: co-deploying two slices into one process is reversible, and a\n * `source` that changed when a process moved would rewrite history for a fact\n * that did not change. Not the domain either: a slice may hold several, so the\n * domain does not identify the publisher. The slice is ADR 0020's ownership\n * noun and is already executable in `tools/slices/`, which is what lets the\n * register be checked against what the bus actually carries.\n *\n * Provided at each composition root beside the other environment facts\n * (`TenantDatabasePrefix`, `SagaDatabaseName`) rather than read from an\n * environment variable, so a service that forgets it fails to build its layer\n * instead of publishing events signed by nobody.\n */\nexport class EventSourceTag extends Context.Tag('EventSourceTag')<\n EventSourceTag,\n string\n>() {}\n"],"names":["Context","EventSourceTag","Tag"],"mappings":"AAAA,SAASA,OAAO,QAAQ,SAAS;AAEjC;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,uBAAuBD,QAAQE,GAAG,CAAC;AAG3C"}
1
+ {"version":3,"sources":["../../src/ports/event-source.ts"],"sourcesContent":["import { Context } from 'effect';\n\n/**\n * The name of the slice publishing an event — `marketplace-admin`, `order`.\n *\n * A **slice**, deliberately, and not one of the two nearer alternatives. Not the\n * deployment: co-deploying two slices into one process is reversible, and a\n * `source` that changed when a process moved would rewrite history for a fact\n * that did not change. Not the domain either: a slice may hold several, so the\n * domain does not identify the publisher. The slice is ADR 0020's ownership\n * noun and is already executable in `tools/slices/`, which is what lets the\n * register be checked against what the bus actually carries.\n *\n * Provided at each composition root beside the other environment facts\n * (`TenantDatabasePrefix`, `SagaDatabaseName`) rather than read from an\n * environment variable, so a service that forgets it fails to build its layer\n * instead of publishing events signed by nobody.\n */\nexport class EventSourceTag extends Context.Service<EventSourceTag, string>()(\n 'EventSourceTag',\n) {}\n"],"names":["Context","EventSourceTag","Service"],"mappings":"AAAA,SAASA,OAAO,QAAQ,SAAS;AAEjC;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,uBAAuBD,QAAQE,OAAO,GACjD;AACC"}
@@ -17,7 +17,7 @@ export interface LockService {
17
17
  acquire(key: string): Effect.Effect<LockHandle, EntifixLockError>;
18
18
  release(handle: LockHandle): Effect.Effect<void, EntifixConnError>;
19
19
  }
20
- declare const LockServiceTag_base: Context.TagClass<LockServiceTag, "LockServiceTag", LockService>;
20
+ declare const LockServiceTag_base: Context.ServiceClass<LockServiceTag, "LockServiceTag", LockService>;
21
21
  export declare class LockServiceTag extends LockServiceTag_base {
22
22
  }
23
23
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"lock-service.d.ts","sourceRoot":"","sources":["../../src/ports/lock-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACxE,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C,gFAAgF;AAChF,MAAM,WAAW,UAAU;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B;;;OAGG;IACH,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,gBAAgB,CAAC,CAAC;IAClE,OAAO,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;CACpE;;AAED,qBAAa,cAAe,SAAQ,mBAGjC;CAAG"}
1
+ {"version":3,"file":"lock-service.d.ts","sourceRoot":"","sources":["../../src/ports/lock-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACxE,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C,gFAAgF;AAChF,MAAM,WAAW,UAAU;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B;;;OAGG;IACH,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,gBAAgB,CAAC,CAAC;IAClE,OAAO,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;CACpE;;AAED,qBAAa,cAAe,SAAQ,mBAGf;CAAG"}
@@ -1,5 +1,5 @@
1
1
  import { Context } from 'effect';
2
- export class LockServiceTag extends Context.Tag('LockServiceTag')() {
2
+ export class LockServiceTag extends Context.Service()('LockServiceTag') {
3
3
  }
4
4
 
5
5
  //# sourceMappingURL=lock-service.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ports/lock-service.ts"],"sourcesContent":["import type { EntifixConnError, EntifixLockError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/** A held lock; `token` proves ownership so release only frees our own lock. */\nexport interface LockHandle {\n key: string;\n token: string;\n}\n\n/**\n * Distributed mutual exclusion — the facade's `lock`/`free` steps. Implemented\n * over Redis (`SET NX PX` + bounded retry) in `@entifix/redis`.\n */\nexport interface LockService {\n /**\n * Acquire `key`, retrying up to the adapter's bounded budget. Fails with\n * {@link EntifixLockError} on contention (surfaced as `409`), not a `500`.\n */\n acquire(key: string): Effect.Effect<LockHandle, EntifixLockError>;\n release(handle: LockHandle): Effect.Effect<void, EntifixConnError>;\n}\n\nexport class LockServiceTag extends Context.Tag('LockServiceTag')<\n LockServiceTag,\n LockService\n>() {}\n"],"names":["Context","LockServiceTag","Tag"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAqB9C,OAAO,MAAMC,uBAAuBD,QAAQE,GAAG,CAAC;AAG3C"}
1
+ {"version":3,"sources":["../../src/ports/lock-service.ts"],"sourcesContent":["import type { EntifixConnError, EntifixLockError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/** A held lock; `token` proves ownership so release only frees our own lock. */\nexport interface LockHandle {\n key: string;\n token: string;\n}\n\n/**\n * Distributed mutual exclusion — the facade's `lock`/`free` steps. Implemented\n * over Redis (`SET NX PX` + bounded retry) in `@entifix/redis`.\n */\nexport interface LockService {\n /**\n * Acquire `key`, retrying up to the adapter's bounded budget. Fails with\n * {@link EntifixLockError} on contention (surfaced as `409`), not a `500`.\n */\n acquire(key: string): Effect.Effect<LockHandle, EntifixLockError>;\n release(handle: LockHandle): Effect.Effect<void, EntifixConnError>;\n}\n\nexport class LockServiceTag extends Context.Service<\n LockServiceTag,\n LockService\n>()('LockServiceTag') {}\n"],"names":["Context","LockServiceTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAqB9C,OAAO,MAAMC,uBAAuBD,QAAQE,OAAO,GAG/C;AAAmB"}
@@ -40,7 +40,7 @@ export interface SagaResponse {
40
40
  export interface SagaDispatcher {
41
41
  dispatch(dispatch: SagaDispatch): Effect.Effect<SagaResponse, EntifixConnError>;
42
42
  }
43
- declare const SagaDispatcherTag_base: Context.TagClass<SagaDispatcherTag, "SagaDispatcherTag", SagaDispatcher>;
43
+ declare const SagaDispatcherTag_base: Context.ServiceClass<SagaDispatcherTag, "SagaDispatcherTag", SagaDispatcher>;
44
44
  export declare class SagaDispatcherTag extends SagaDispatcherTag_base {
45
45
  }
46
46
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"saga-dispatcher.d.ts","sourceRoot":"","sources":["../../src/ports/saga-dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAEhE,sDAAsD;AACtD,MAAM,WAAW,YAAY;IAC3B,iFAAiF;IACjF,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IACxB,mEAAmE;IACnE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B;;;;;;;OAOG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;CACzB;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAC;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+1,5 @@
1
1
  import { Context } from 'effect';
2
- export class SagaDispatcherTag extends Context.Tag('SagaDispatcherTag')() {
2
+ export class SagaDispatcherTag extends Context.Service()('SagaDispatcherTag') {
3
3
  }
4
4
 
5
5
  //# sourceMappingURL=saga-dispatcher.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ports/saga-dispatcher.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\nimport type { SagaCall } from '../contracts/saga-definition.js';\n\n/** One call the engine wants made, fully resolved. */\nexport interface SagaDispatch {\n /** The participant's configuration key — the dispatcher resolves the address. */\n readonly participant: string;\n readonly call: SagaCall;\n /** `<sagaId>:<stepId>[:<index>]`, which the participant claims. */\n readonly commandId: string;\n /**\n * The organization this call acts for, when the participant is tenant-plane.\n *\n * Absent for a platform-plane participant. Present, it becomes ADR 0023's\n * `x-organization-id` — and it is safe only because the crossing token is\n * checked first, so the input the caller controls is never the input that\n * authorizes.\n */\n readonly organizationId?: string;\n readonly body?: unknown;\n}\n\n/**\n * What a dispatched call answered.\n *\n * ⚠️ **A refusal is not a failure, and the split is the dispatcher's job.** A\n * `409` from reserve is the business answer \"not enough stock\" and must fail the\n * saga *forward* into compensation; a `503` is a participant that is down and\n * the entry is retried. Collapsing the two either retries an out-of-stock line\n * forever or permanently fails a checkout because a pod was restarting\n * ([ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md)).\n *\n * So a `refused` response is a **success** of this port carrying `ok: false`,\n * and only a transport or `5xx` failure is an `EntifixConnError`.\n */\nexport interface SagaResponse {\n readonly ok: boolean;\n readonly status: number;\n readonly body: unknown;\n}\n\nexport interface SagaDispatcher {\n dispatch(\n dispatch: SagaDispatch,\n ): Effect.Effect<SagaResponse, EntifixConnError>;\n}\n\nexport class SagaDispatcherTag extends Context.Tag('SagaDispatcherTag')<\n SagaDispatcherTag,\n SagaDispatcher\n>() {}\n"],"names":["Context","SagaDispatcherTag","Tag"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAgD9C,OAAO,MAAMC,0BAA0BD,QAAQE,GAAG,CAAC;AAG9C"}
1
+ {"version":3,"sources":["../../src/ports/saga-dispatcher.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\nimport type { SagaCall } from '../contracts/saga-definition.js';\n\n/** One call the engine wants made, fully resolved. */\nexport interface SagaDispatch {\n /** The participant's configuration key — the dispatcher resolves the address. */\n readonly participant: string;\n readonly call: SagaCall;\n /** `<sagaId>:<stepId>[:<index>]`, which the participant claims. */\n readonly commandId: string;\n /**\n * The organization this call acts for, when the participant is tenant-plane.\n *\n * Absent for a platform-plane participant. Present, it becomes ADR 0023's\n * `x-organization-id` — and it is safe only because the crossing token is\n * checked first, so the input the caller controls is never the input that\n * authorizes.\n */\n readonly organizationId?: string;\n readonly body?: unknown;\n}\n\n/**\n * What a dispatched call answered.\n *\n * ⚠️ **A refusal is not a failure, and the split is the dispatcher's job.** A\n * `409` from reserve is the business answer \"not enough stock\" and must fail the\n * saga *forward* into compensation; a `503` is a participant that is down and\n * the entry is retried. Collapsing the two either retries an out-of-stock line\n * forever or permanently fails a checkout because a pod was restarting\n * ([ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md)).\n *\n * So a `refused` response is a **success** of this port carrying `ok: false`,\n * and only a transport or `5xx` failure is an `EntifixConnError`.\n */\nexport interface SagaResponse {\n readonly ok: boolean;\n readonly status: number;\n readonly body: unknown;\n}\n\nexport interface SagaDispatcher {\n dispatch(\n dispatch: SagaDispatch,\n ): Effect.Effect<SagaResponse, EntifixConnError>;\n}\n\nexport class SagaDispatcherTag extends Context.Service<\n SagaDispatcherTag,\n SagaDispatcher\n>()('SagaDispatcherTag') {}\n"],"names":["Context","SagaDispatcherTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAgD9C,OAAO,MAAMC,0BAA0BD,QAAQE,OAAO,GAGlD;AAAsB"}
@@ -91,7 +91,7 @@ export interface SagaStore {
91
91
  /** Mark one step's calls as given back, so a resumed unwind skips them. */
92
92
  markCompensated(sagaId: string, stepId: string): Effect.Effect<void, EntifixConnError>;
93
93
  }
94
- declare const SagaStoreTag_base: Context.TagClass<SagaStoreTag, "SagaStoreTag", SagaStore>;
94
+ declare const SagaStoreTag_base: Context.ServiceClass<SagaStoreTag, "SagaStoreTag", SagaStore>;
95
95
  export declare class SagaStoreTag extends SagaStoreTag_base {
96
96
  }
97
97
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"saga-store.d.ts","sourceRoot":"","sources":["../../src/ports/saga-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,KAAK,EACV,UAAU,EACV,eAAe,EAChB,MAAM,iCAAiC,CAAC;AAEzC;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW,8EAMd,CAAC;AAEX,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC;AAErD,iEAAiE;AACjE,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,2CAA2C;IAC3C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC;IAC1B,6DAA6D;IAC7D,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,SAAS,eAAe,EAAE,CAAC;IAC9C;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B;;;;;;;;;OASG;IACH,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,SAAS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B,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;IACzC,aAAa,CACX,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,eAAe,GACvB,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;IACzC,MAAM,CACJ,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,SAAS,EAChB,KAAK,CAAC,EAAE,MAAM,GACb,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;IACzC,GAAG,CACD,MAAM,EAAE,MAAM,GACb,MAAM,CAAC,MAAM,CAAC,YAAY,GAAG,SAAS,EAAE,gBAAgB,CAAC,CAAC;IAC7D,iFAAiF;IACjF,SAAS,CACP,WAAW,EAAE,MAAM,GAClB,MAAM,CAAC,MAAM,CAAC,SAAS,YAAY,EAAE,EAAE,gBAAgB,CAAC,CAAC;IAC5D;;;;;;;;;;;;;OAaG;IACH,cAAc,CACZ,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,GAClB,MAAM,CAAC,MAAM,CAAC,YAAY,GAAG,SAAS,EAAE,gBAAgB,CAAC,CAAC;IAC7D,2EAA2E;IAC3E,eAAe,CACb,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GACb,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;CAC1C;;AAED,qBAAa,YAAa,SAAQ,iBAEjC;CAAG"}
@@ -14,7 +14,7 @@ import { Context } from 'effect';
14
14
  'COMPENSATED',
15
15
  'STRANDED'
16
16
  ];
17
- export class SagaStoreTag extends Context.Tag('SagaStoreTag')() {
17
+ export class SagaStoreTag extends Context.Service()('SagaStoreTag') {
18
18
  }
19
19
 
20
20
  //# sourceMappingURL=saga-store.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ports/saga-store.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\nimport type {\n SagaInputs,\n SagaStepOutcome,\n} from '../contracts/saga-definition.js';\n\n/**\n * Where a saga instance is.\n *\n * `COMPENSATED` and `STRANDED` are deliberately different terminal states:\n * \"failed and reversed\" and \"failed with something still held\" are the two\n * outcomes an operator has to be able to tell apart, and a single `FAILED`\n * would make the second look like the first\n * ([ADR 0039](../../../../../../docs/adr/0039-multi-step-sagas-are-orchestrated.md)).\n */\nexport const SAGA_STATES = [\n 'RUNNING',\n 'COMPLETED',\n 'COMPENSATING',\n 'COMPENSATED',\n 'STRANDED',\n] as const;\n\nexport type SagaState = (typeof SAGA_STATES)[number];\n\n/** One flow in progress, and what each of its steps returned. */\nexport interface SagaInstance {\n readonly sagaId: string;\n /** The {@link SagaDefinition}'s `name`. */\n readonly definition: string;\n readonly state: SagaState;\n /** The step being dispatched, or the last one dispatched. */\n readonly stepIndex: number;\n readonly outcomes: readonly SagaStepOutcome[];\n /**\n * What the caller supplied, kept so a **different process** can finish this\n * flow.\n *\n * ⚠️ This is the member that makes the instance a resumable record rather\n * than a report on one. Without it a resumed walk knows which step is next\n * and has nothing to dispatch it with: a fan-out step's cardinality is its\n * input's length, and a body template resolves against `inputs` before it\n * resolves against earlier outcomes\n * ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).\n */\n readonly inputs: SagaInputs;\n /**\n * How many times a sweep has picked this instance up, which is the ceiling\n * that stops a resume loop.\n *\n * It plays the part ADR 0030's `attempts` plays on an outbox entry, on the\n * record that already exists rather than on a second one beside it. Past the\n * ceiling the instance is settled `STRANDED` and logged — surfaced rather\n * than retried forever, because a coordinator spinning on a permanent failure\n * is how a customer's money stays captured with nobody told.\n */\n readonly resumeAttempts: number;\n readonly error?: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\n/**\n * The saga's own state, in the `saga` store.\n *\n * A saga instance is a transaction's state with steps in it, so it belongs in\n * the store that already holds transaction state — no new store, and the\n * `transaction` slice keeps `domains: []`, because orchestration is a mechanism\n * rather than a business domain (ADR 0039).\n */\nexport interface SagaStore {\n start(\n instance: Omit<SagaInstance, 'updatedAt'>,\n ): Effect.Effect<void, EntifixConnError>;\n /**\n * Persist that a step is about to be dispatched.\n *\n * ⚠️ **Before the dispatch, never after.** ADR 0028's rule extended from\n * events to commands: a coordinator that marks a step in flight only after\n * calling has the dual write that record exists to close, with the same\n * consequence — a crash between the two leaves a step that either ran twice\n * or never ran, and the record says the opposite of the truth.\n */\n beginStep(\n sagaId: string,\n stepIndex: number,\n ): Effect.Effect<void, EntifixConnError>;\n recordOutcome(\n sagaId: string,\n outcome: SagaStepOutcome,\n ): Effect.Effect<void, EntifixConnError>;\n settle(\n sagaId: string,\n state: SagaState,\n error?: string,\n ): Effect.Effect<void, EntifixConnError>;\n get(\n sagaId: string,\n ): Effect.Effect<SagaInstance | undefined, EntifixConnError>;\n /** Instances left `RUNNING` or `COMPENSATING` past a deadline, for the sweep. */\n findStale(\n olderThanMs: number,\n ): Effect.Effect<readonly SagaInstance[], EntifixConnError>;\n /**\n * Take ownership of a stale instance, or answer `undefined`.\n *\n * ⚠️ **A claim, not a read**, and it is what makes the sweep safe to run in\n * more than one process: the same conditional write that increments\n * `resumeAttempts` also re-stamps `updatedAt`, so an instance already picked\n * up is no longer stale and the second sweeper gets nothing. Reading and then\n * resuming would have two coordinators dispatching one flow — survivable,\n * because every participant claims the command id, but it would double every\n * call and make the attempt ceiling meaningless.\n *\n * Re-stamping is also what stops *this* sweep's next tick finding the\n * instance it is still working on.\n */\n claimForResume(\n sagaId: string,\n olderThanMs: number,\n ): Effect.Effect<SagaInstance | undefined, EntifixConnError>;\n /** Mark one step's calls as given back, so a resumed unwind skips them. */\n markCompensated(\n sagaId: string,\n stepId: string,\n ): Effect.Effect<void, EntifixConnError>;\n}\n\nexport class SagaStoreTag extends Context.Tag('SagaStoreTag')<\n SagaStoreTag,\n SagaStore\n>() {}\n"],"names":["Context","SAGA_STATES","SagaStoreTag","Tag"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAO9C;;;;;;;;CAQC,GACD,OAAO,MAAMC,cAAc;IACzB;IACA;IACA;IACA;IACA;CACD,CAAU;AA2GX,OAAO,MAAMC,qBAAqBF,QAAQG,GAAG,CAAC;AAGzC"}
1
+ {"version":3,"sources":["../../src/ports/saga-store.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\nimport type {\n SagaInputs,\n SagaStepOutcome,\n} from '../contracts/saga-definition.js';\n\n/**\n * Where a saga instance is.\n *\n * `COMPENSATED` and `STRANDED` are deliberately different terminal states:\n * \"failed and reversed\" and \"failed with something still held\" are the two\n * outcomes an operator has to be able to tell apart, and a single `FAILED`\n * would make the second look like the first\n * ([ADR 0039](../../../../../../docs/adr/0039-multi-step-sagas-are-orchestrated.md)).\n */\nexport const SAGA_STATES = [\n 'RUNNING',\n 'COMPLETED',\n 'COMPENSATING',\n 'COMPENSATED',\n 'STRANDED',\n] as const;\n\nexport type SagaState = (typeof SAGA_STATES)[number];\n\n/** One flow in progress, and what each of its steps returned. */\nexport interface SagaInstance {\n readonly sagaId: string;\n /** The {@link SagaDefinition}'s `name`. */\n readonly definition: string;\n readonly state: SagaState;\n /** The step being dispatched, or the last one dispatched. */\n readonly stepIndex: number;\n readonly outcomes: readonly SagaStepOutcome[];\n /**\n * What the caller supplied, kept so a **different process** can finish this\n * flow.\n *\n * ⚠️ This is the member that makes the instance a resumable record rather\n * than a report on one. Without it a resumed walk knows which step is next\n * and has nothing to dispatch it with: a fan-out step's cardinality is its\n * input's length, and a body template resolves against `inputs` before it\n * resolves against earlier outcomes\n * ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).\n */\n readonly inputs: SagaInputs;\n /**\n * How many times a sweep has picked this instance up, which is the ceiling\n * that stops a resume loop.\n *\n * It plays the part ADR 0030's `attempts` plays on an outbox entry, on the\n * record that already exists rather than on a second one beside it. Past the\n * ceiling the instance is settled `STRANDED` and logged — surfaced rather\n * than retried forever, because a coordinator spinning on a permanent failure\n * is how a customer's money stays captured with nobody told.\n */\n readonly resumeAttempts: number;\n readonly error?: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\n/**\n * The saga's own state, in the `saga` store.\n *\n * A saga instance is a transaction's state with steps in it, so it belongs in\n * the store that already holds transaction state — no new store, and the\n * `transaction` slice keeps `domains: []`, because orchestration is a mechanism\n * rather than a business domain (ADR 0039).\n */\nexport interface SagaStore {\n start(\n instance: Omit<SagaInstance, 'updatedAt'>,\n ): Effect.Effect<void, EntifixConnError>;\n /**\n * Persist that a step is about to be dispatched.\n *\n * ⚠️ **Before the dispatch, never after.** ADR 0028's rule extended from\n * events to commands: a coordinator that marks a step in flight only after\n * calling has the dual write that record exists to close, with the same\n * consequence — a crash between the two leaves a step that either ran twice\n * or never ran, and the record says the opposite of the truth.\n */\n beginStep(\n sagaId: string,\n stepIndex: number,\n ): Effect.Effect<void, EntifixConnError>;\n recordOutcome(\n sagaId: string,\n outcome: SagaStepOutcome,\n ): Effect.Effect<void, EntifixConnError>;\n settle(\n sagaId: string,\n state: SagaState,\n error?: string,\n ): Effect.Effect<void, EntifixConnError>;\n get(\n sagaId: string,\n ): Effect.Effect<SagaInstance | undefined, EntifixConnError>;\n /** Instances left `RUNNING` or `COMPENSATING` past a deadline, for the sweep. */\n findStale(\n olderThanMs: number,\n ): Effect.Effect<readonly SagaInstance[], EntifixConnError>;\n /**\n * Take ownership of a stale instance, or answer `undefined`.\n *\n * ⚠️ **A claim, not a read**, and it is what makes the sweep safe to run in\n * more than one process: the same conditional write that increments\n * `resumeAttempts` also re-stamps `updatedAt`, so an instance already picked\n * up is no longer stale and the second sweeper gets nothing. Reading and then\n * resuming would have two coordinators dispatching one flow — survivable,\n * because every participant claims the command id, but it would double every\n * call and make the attempt ceiling meaningless.\n *\n * Re-stamping is also what stops *this* sweep's next tick finding the\n * instance it is still working on.\n */\n claimForResume(\n sagaId: string,\n olderThanMs: number,\n ): Effect.Effect<SagaInstance | undefined, EntifixConnError>;\n /** Mark one step's calls as given back, so a resumed unwind skips them. */\n markCompensated(\n sagaId: string,\n stepId: string,\n ): Effect.Effect<void, EntifixConnError>;\n}\n\nexport class SagaStoreTag extends Context.Service<SagaStoreTag, SagaStore>()(\n 'SagaStoreTag',\n) {}\n"],"names":["Context","SAGA_STATES","SagaStoreTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAO9C;;;;;;;;CAQC,GACD,OAAO,MAAMC,cAAc;IACzB;IACA;IACA;IACA;IACA;CACD,CAAU;AA2GX,OAAO,MAAMC,qBAAqBF,QAAQG,OAAO,GAC/C;AACC"}
@@ -10,7 +10,7 @@ export interface SequenceService {
10
10
  /** Atomically increments the named sequence and returns the new value. */
11
11
  next(name: string): Effect.Effect<number, EntifixConnError>;
12
12
  }
13
- declare const SequenceServiceTag_base: Context.TagClass<SequenceServiceTag, "SequenceServiceTag", SequenceService>;
13
+ declare const SequenceServiceTag_base: Context.ServiceClass<SequenceServiceTag, "SequenceServiceTag", SequenceService>;
14
14
  export declare class SequenceServiceTag extends SequenceServiceTag_base {
15
15
  }
16
16
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"sequence-service.d.ts","sourceRoot":"","sources":["../../src/ports/sequence-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;;GAKG;AACH,MAAM,WAAW,eAAe;IAC9B,0EAA0E;IAC1E,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;CAC7D;;AAED,qBAAa,kBAAmB,SAAQ,uBAGrC;CAAG"}
1
+ {"version":3,"file":"sequence-service.d.ts","sourceRoot":"","sources":["../../src/ports/sequence-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;;GAKG;AACH,MAAM,WAAW,eAAe;IAC9B,0EAA0E;IAC1E,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;CAC7D;;AAED,qBAAa,kBAAmB,SAAQ,uBAGf;CAAG"}
@@ -1,5 +1,5 @@
1
1
  import { Context } from 'effect';
2
- export class SequenceServiceTag extends Context.Tag('SequenceServiceTag')() {
2
+ export class SequenceServiceTag extends Context.Service()('SequenceServiceTag') {
3
3
  }
4
4
 
5
5
  //# sourceMappingURL=sequence-service.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ports/sequence-service.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * A monotonic, gap-free-under-contention counter — the mechanism that makes\n * codes unique across service instances. Implemented as Redis `INCR` in\n * `@entifix/redis`; the atomicity of `INCR` is what guarantees no two\n * concurrent commands ever draw the same number.\n */\nexport interface SequenceService {\n /** Atomically increments the named sequence and returns the new value. */\n next(name: string): Effect.Effect<number, EntifixConnError>;\n}\n\nexport class SequenceServiceTag extends Context.Tag('SequenceServiceTag')<\n SequenceServiceTag,\n SequenceService\n>() {}\n"],"names":["Context","SequenceServiceTag","Tag"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAa9C,OAAO,MAAMC,2BAA2BD,QAAQE,GAAG,CAAC;AAG/C"}
1
+ {"version":3,"sources":["../../src/ports/sequence-service.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * A monotonic, gap-free-under-contention counter — the mechanism that makes\n * codes unique across service instances. Implemented as Redis `INCR` in\n * `@entifix/redis`; the atomicity of `INCR` is what guarantees no two\n * concurrent commands ever draw the same number.\n */\nexport interface SequenceService {\n /** Atomically increments the named sequence and returns the new value. */\n next(name: string): Effect.Effect<number, EntifixConnError>;\n}\n\nexport class SequenceServiceTag extends Context.Service<\n SequenceServiceTag,\n SequenceService\n>()('SequenceServiceTag') {}\n"],"names":["Context","SequenceServiceTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAa9C,OAAO,MAAMC,2BAA2BD,QAAQE,OAAO,GAGnD;AAAuB"}
@@ -61,7 +61,7 @@ export interface TransactionHandler {
61
61
  */
62
62
  rollback(command: TransactionCommand, outcome: TransactionOutcome | undefined): Effect.Effect<void, EntifixError>;
63
63
  }
64
- declare const TransactionHandlerTag_base: Context.TagClass<TransactionHandlerTag, "TransactionHandlerTag", TransactionHandler>;
64
+ declare const TransactionHandlerTag_base: Context.ServiceClass<TransactionHandlerTag, "TransactionHandlerTag", TransactionHandler>;
65
65
  export declare class TransactionHandlerTag extends TransactionHandlerTag_base {
66
66
  }
67
67
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"transaction-handler.d.ts","sourceRoot":"","sources":["../../src/ports/transaction-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAElE,8EAA8E;AAC9E,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,QAAQ,CAAC;CACpB;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,kBAAkB;IACjC,8DAA8D;IAC9D,QAAQ,CAAC,OAAO,EAAE,kBAAkB,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;IACzE,2EAA2E;IAC3E,QAAQ,CAAC,OAAO,EAAE,kBAAkB,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O,EAAE,kBAAkB,GAAG,SAAS,GACtC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;CACtC;;AAED,qBAAa,qBAAsB,SAAQ,0BAGf;CAAG"}
@@ -1,5 +1,5 @@
1
1
  import { Context } from 'effect';
2
- export class TransactionHandlerTag extends Context.Tag('TransactionHandlerTag')() {
2
+ export class TransactionHandlerTag extends Context.Service()('TransactionHandlerTag') {
3
3
  }
4
4
 
5
5
  //# sourceMappingURL=transaction-handler.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ports/transaction-handler.ts"],"sourcesContent":["import type { EntifixError, EntityId } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\nimport type { TransactionCommand } from '../contracts/command.js';\n\n/** What a successful `execute` produced — echoed into the completed event. */\nexport interface TransactionOutcome {\n code: string;\n entityId: EntityId;\n}\n\n/**\n * The domain-specific half of the facade. `validate`/`lock`/`execute`/`free`/\n * `rollback` are standardised by the engine, but *what* a command validates to,\n * *which* resources it locks, and *how* it executes/rolls back are the service's\n * concern — injected as this handler.\n *\n * Methods return `R = never`: the service closes over its own dependencies (db,\n * sequence, repository) when constructing the handler, exactly as\n * `makeMongoRepository` closes over its `Db`.\n */\nexport interface TransactionHandler {\n /** Reject a malformed/illegal command (surfaced as `400`). */\n validate(command: TransactionCommand): Effect.Effect<void, EntifixError>;\n /** The resource keys to lock for this command (e.g. the code sequence). */\n lockKeys(command: TransactionCommand): readonly string[];\n /**\n * Assign the code and persist — the actual write.\n *\n * **The implementation must write the `completed` outbox entry in the same\n * storage transaction as its state change**, as a full `OutboxEntry` whose\n * `event` is the `DomainEvent` `completedEvent` builds and whose `eventId` is\n * that event's `id`. The engine deliberately records\n * nothing on the success path, because only an implementation holds the\n * driver session that can make those two writes one fact; an engine-level\n * record would be a second dual write, announcing a state change that may\n * still roll back.\n *\n * Two rules that only a replica set will teach you, and only in production:\n * drive the transaction with the driver's retrying helper (Mongo's\n * `session.withTransaction`), because an election aborts in-flight\n * transactions with a `TransientTransactionError` the *application* is\n * expected to retry; and keep any non-transactional side effect — drawing a\n * code from the Redis sequence, say — **outside** that retried callback, or a\n * retry consumes a second value and skips a code.\n */\n execute(\n command: TransactionCommand,\n ): Effect.Effect<TransactionOutcome, EntifixError>;\n /**\n * Undo a failed execution. Must be idempotent (e.g. delete-if-exists), since\n * the recovery sweep may reach a transaction whose rollback already ran.\n *\n * **`outcome` is always `undefined` on the single-step path, and cannot be\n * anything else there.** `rollback` runs on exactly one arm — the one where\n * `execute` failed — so there is no outcome to hand it.\n *\n * That is a property of this path rather than an unfinished signature, and it\n * stays true now that the multi-step engine exists beside it. A saga's\n * compensation is dispatched by `runSaga` with **its own call's** recorded\n * outcome (`SagaStepOutcome`), because reversing a reservation needs the\n * reservation's id and a delete-if-exists does not — see\n * [ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md). A\n * single-step handler is untouched by that, which is what ADR 0039 meant by\n * \"grows a second shape and keeps the first\".\n */\n rollback(\n command: TransactionCommand,\n outcome: TransactionOutcome | undefined,\n ): Effect.Effect<void, EntifixError>;\n}\n\nexport class TransactionHandlerTag extends Context.Tag('TransactionHandlerTag')<\n TransactionHandlerTag,\n TransactionHandler\n>() {}\n"],"names":["Context","TransactionHandlerTag","Tag"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAuE9C,OAAO,MAAMC,8BAA8BD,QAAQE,GAAG,CAAC;AAGlD"}
1
+ {"version":3,"sources":["../../src/ports/transaction-handler.ts"],"sourcesContent":["import type { EntifixError, EntityId } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\nimport type { TransactionCommand } from '../contracts/command.js';\n\n/** What a successful `execute` produced — echoed into the completed event. */\nexport interface TransactionOutcome {\n code: string;\n entityId: EntityId;\n}\n\n/**\n * The domain-specific half of the facade. `validate`/`lock`/`execute`/`free`/\n * `rollback` are standardised by the engine, but *what* a command validates to,\n * *which* resources it locks, and *how* it executes/rolls back are the service's\n * concern — injected as this handler.\n *\n * Methods return `R = never`: the service closes over its own dependencies (db,\n * sequence, repository) when constructing the handler, exactly as\n * `makeMongoRepository` closes over its `Db`.\n */\nexport interface TransactionHandler {\n /** Reject a malformed/illegal command (surfaced as `400`). */\n validate(command: TransactionCommand): Effect.Effect<void, EntifixError>;\n /** The resource keys to lock for this command (e.g. the code sequence). */\n lockKeys(command: TransactionCommand): readonly string[];\n /**\n * Assign the code and persist — the actual write.\n *\n * **The implementation must write the `completed` outbox entry in the same\n * storage transaction as its state change**, as a full `OutboxEntry` whose\n * `event` is the `DomainEvent` `completedEvent` builds and whose `eventId` is\n * that event's `id`. The engine deliberately records\n * nothing on the success path, because only an implementation holds the\n * driver session that can make those two writes one fact; an engine-level\n * record would be a second dual write, announcing a state change that may\n * still roll back.\n *\n * Two rules that only a replica set will teach you, and only in production:\n * drive the transaction with the driver's retrying helper (Mongo's\n * `session.withTransaction`), because an election aborts in-flight\n * transactions with a `TransientTransactionError` the *application* is\n * expected to retry; and keep any non-transactional side effect — drawing a\n * code from the Redis sequence, say — **outside** that retried callback, or a\n * retry consumes a second value and skips a code.\n */\n execute(\n command: TransactionCommand,\n ): Effect.Effect<TransactionOutcome, EntifixError>;\n /**\n * Undo a failed execution. Must be idempotent (e.g. delete-if-exists), since\n * the recovery sweep may reach a transaction whose rollback already ran.\n *\n * **`outcome` is always `undefined` on the single-step path, and cannot be\n * anything else there.** `rollback` runs on exactly one arm — the one where\n * `execute` failed — so there is no outcome to hand it.\n *\n * That is a property of this path rather than an unfinished signature, and it\n * stays true now that the multi-step engine exists beside it. A saga's\n * compensation is dispatched by `runSaga` with **its own call's** recorded\n * outcome (`SagaStepOutcome`), because reversing a reservation needs the\n * reservation's id and a delete-if-exists does not — see\n * [ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md). A\n * single-step handler is untouched by that, which is what ADR 0039 meant by\n * \"grows a second shape and keeps the first\".\n */\n rollback(\n command: TransactionCommand,\n outcome: TransactionOutcome | undefined,\n ): Effect.Effect<void, EntifixError>;\n}\n\nexport class TransactionHandlerTag extends Context.Service<\n TransactionHandlerTag,\n TransactionHandler\n>()('TransactionHandlerTag') {}\n"],"names":["Context","TransactionHandlerTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAuE9C,OAAO,MAAMC,8BAA8BD,QAAQE,OAAO,GAGtD;AAA0B"}
@@ -54,7 +54,7 @@ export type PendingEntry = PendingTransaction & {
54
54
  export interface TransactionSink {
55
55
  began(pending: PendingTransaction): void;
56
56
  }
57
- declare const TransactionSinkTag_base: Context.TagClass<TransactionSinkTag, "TransactionSinkTag", TransactionSink>;
57
+ declare const TransactionSinkTag_base: Context.ServiceClass<TransactionSinkTag, "TransactionSinkTag", TransactionSink>;
58
58
  /**
59
59
  * ⚠️ Read with `Effect.serviceOption`, never `yield*`.
60
60
  *
@@ -1 +1 @@
1
- {"version":3,"file":"transaction-sink.d.ts","sourceRoot":"","sources":["../../src/ports/transaction-sink.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC;;;;;;GAMG;AACH,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,iFAAiF;IACjF,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,4EAA4E;IAC5E,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;CACrB;AAED,4EAA4E;AAC5E,MAAM,MAAM,YAAY,GAAG,kBAAkB,GAAG;IAC9C,QAAQ,CAAC,KAAK,EAAE,SAAS,GAAG,QAAQ,CAAC;IACrC;;;;;;;;;;;;OAYG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;;;OAMG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,eAAe;IAC9B,KAAK,CAAC,OAAO,EAAE,kBAAkB,GAAG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;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,eAAe;IAC9B,KAAK,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI,CAAC;CAC1C;;AAED;;;;;;;;;;;;;GAaG;AACH,qBAAa,kBAAmB,SAAQ,uBAGf;CAAG;AAE5B;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,EAAE,eAEjC,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,WAAW,uBAAwB,SAAQ,eAAe;IAC9D,QAAQ,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,CAAC;IAC1C,qEAAqE;IACrE,MAAM,CAAC,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IACpC;;;;;;;;;;;;;;OAcG;IACH,MAAM,CAAC,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC;IACxD,2EAA2E;IAC3E,IAAI,CAAC,aAAa,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACnD,yCAAyC;IACzC,OAAO,CAAC,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;CACtC"}
@@ -12,7 +12,7 @@ import { Context } from 'effect';
12
12
  * the feature is silently dead. A spec pins the one place that must
13
13
  * (`mergeContext`), because an invariant the compiler cannot hold is one a test
14
14
  * has to.
15
- */ export class TransactionSinkTag extends Context.Tag('TransactionSinkTag')() {
15
+ */ export class TransactionSinkTag extends Context.Service()('TransactionSinkTag') {
16
16
  }
17
17
  /**
18
18
  * The sink where nothing is watching — outside a mounted provider, and in every
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ports/transaction-sink.ts"],"sourcesContent":["import { Context } from 'effect';\n\n/**\n * A write the browser has started and the server has not finished.\n *\n * The `transactionId` is also the stored entity's id — ADR 0028 makes the\n * client's minted id the primary key — so this is enough to find the record\n * later without holding a copy of it.\n */\nexport interface PendingTransaction {\n readonly transactionId: string;\n /** The target entity's `key`, so a settle knows which query scope to refresh. */\n readonly entity: string;\n /** ISO-8601, when the `202` came back. Drives the oldest-first eviction. */\n readonly at: string;\n}\n\n/** A pending write, plus what reconciliation has since learned about it. */\nexport type PendingEntry = PendingTransaction & {\n readonly state: 'pending' | 'failed';\n /**\n * The record as the browser holds it, so a list can show it before the server\n * has one.\n *\n * ⚠️ **In memory only — never persisted.** The store's `partialize` strips it,\n * for ADR 0032's reason: a class instance does not survive a JSON round trip,\n * it comes back as something else. So a refresh keeps the *watch* and loses\n * the row, which is the documented behaviour — past a refresh, server truth\n * plus an honest notice beats a record rebuilt from a blob.\n *\n * Typed `unknown` because this package must not care what an entity is; the\n * shell that put it here is the only thing that reads it back.\n */\n readonly record?: unknown;\n /**\n * Free text from whatever threw, in whatever language it was written in.\n *\n * ⚠️ Diagnostic only — never the headline of anything a user reads. A\n * transaction's failure carries no error *code*, so the message shown has to\n * be a catalog key and this is the detail beside it (ADR 0043's residual).\n */\n readonly reason?: string;\n};\n\n/**\n * How a transactional write announces itself to whoever is watching.\n *\n * The save adapter is the only place that knows a create went out as a command\n * rather than as a plain `POST`, and it learns nothing back — the `202`\n * describes a transaction, not an entity. So it tells this port, and the browser\n * takes it from there.\n *\n * Framework-free and synchronous on purpose: the implementation is a React store\n * action, and keeping that behind a port is what stops `@entifix/transactions`\n * knowing anything about React or about where the pending set is persisted.\n */\nexport interface TransactionSink {\n began(pending: PendingTransaction): void;\n}\n\n/**\n * ⚠️ Read with `Effect.serviceOption`, never `yield*`.\n *\n * That keeps the tag out of the save adapter's `R`, so the storefront, the plain\n * REST adapters and every existing spec compile and run with no layer to\n * provide — an optional capability must not become a build break for callers\n * that will never want it.\n *\n * The cost of that erasure is that **nothing forces a composition root to\n * provide it**: forget to, and the read returns `None`, everything compiles, and\n * the feature is silently dead. A spec pins the one place that must\n * (`mergeContext`), because an invariant the compiler cannot hold is one a test\n * has to.\n */\nexport class TransactionSinkTag extends Context.Tag('TransactionSinkTag')<\n TransactionSinkTag,\n TransactionSink\n>() {}\n\n/**\n * The sink where nothing is watching — outside a mounted provider, and in every\n * caller that never opted into command creates.\n *\n * A create on a plain route still works exactly as it did; it simply gets no\n * optimistic treatment, which is an honest boundary rather than a write into an\n * unscoped store.\n */\nexport const NoopTransactionSink: TransactionSink = {\n began: () => undefined,\n};\n\n/**\n * The full view of the pending set, for the side that reconciles it.\n *\n * It extends {@link TransactionSink} because one store is behind both: the\n * adapter needs only `began`, and the settlement side needs to read entries and\n * retire them. Two interfaces rather than one because they are consumed from\n * opposite sides of a tier boundary — a T3 package may not import a T4 shell,\n * so the store is handed in as a prop, the way `EntityDraftStore` already is for\n * autosave (ADR 0032).\n */\nexport interface PendingTransactionStore extends TransactionSink {\n readonly entries: readonly PendingEntry[];\n /** The write landed. Drop it; the server's copy is the truth now. */\n settle(transactionId: string): void;\n /**\n * Holds the record the browser already has, so the list can render it while\n * the write is still in flight — and answers whether this id was being\n * watched at all.\n *\n * ⚠️ **The return value is why this is one call and not two.** A caller that\n * asked `entries.some(...)` first would be reading a React render closure\n * captured *before* its own `await`, so the announcement the save adapter made\n * during that await is invisible to it and every transactional write reads as\n * a plain one. Answering from the store's current state is the only version\n * without that race.\n *\n * Separate from `began` because the save adapter announces before it returns\n * and has no reason to know about lists.\n */\n attach(transactionId: string, record: unknown): boolean;\n /** The write failed terminally. Keep it, marked, until it is dismissed. */\n fail(transactionId: string, reason?: string): void;\n /** The operator has read the failure. */\n dismiss(transactionId: string): void;\n}\n"],"names":["Context","TransactionSinkTag","Tag","NoopTransactionSink","began","undefined"],"mappings":"AAAA,SAASA,OAAO,QAAQ,SAAS;AA4DjC;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,2BAA2BD,QAAQE,GAAG,CAAC;AAG/C;AAEL;;;;;;;CAOC,GACD,OAAO,MAAMC,sBAAuC;IAClDC,OAAO,IAAMC;AACf,EAAE"}
1
+ {"version":3,"sources":["../../src/ports/transaction-sink.ts"],"sourcesContent":["import { Context } from 'effect';\n\n/**\n * A write the browser has started and the server has not finished.\n *\n * The `transactionId` is also the stored entity's id — ADR 0028 makes the\n * client's minted id the primary key — so this is enough to find the record\n * later without holding a copy of it.\n */\nexport interface PendingTransaction {\n readonly transactionId: string;\n /** The target entity's `key`, so a settle knows which query scope to refresh. */\n readonly entity: string;\n /** ISO-8601, when the `202` came back. Drives the oldest-first eviction. */\n readonly at: string;\n}\n\n/** A pending write, plus what reconciliation has since learned about it. */\nexport type PendingEntry = PendingTransaction & {\n readonly state: 'pending' | 'failed';\n /**\n * The record as the browser holds it, so a list can show it before the server\n * has one.\n *\n * ⚠️ **In memory only — never persisted.** The store's `partialize` strips it,\n * for ADR 0032's reason: a class instance does not survive a JSON round trip,\n * it comes back as something else. So a refresh keeps the *watch* and loses\n * the row, which is the documented behaviour — past a refresh, server truth\n * plus an honest notice beats a record rebuilt from a blob.\n *\n * Typed `unknown` because this package must not care what an entity is; the\n * shell that put it here is the only thing that reads it back.\n */\n readonly record?: unknown;\n /**\n * Free text from whatever threw, in whatever language it was written in.\n *\n * ⚠️ Diagnostic only — never the headline of anything a user reads. A\n * transaction's failure carries no error *code*, so the message shown has to\n * be a catalog key and this is the detail beside it (ADR 0043's residual).\n */\n readonly reason?: string;\n};\n\n/**\n * How a transactional write announces itself to whoever is watching.\n *\n * The save adapter is the only place that knows a create went out as a command\n * rather than as a plain `POST`, and it learns nothing back — the `202`\n * describes a transaction, not an entity. So it tells this port, and the browser\n * takes it from there.\n *\n * Framework-free and synchronous on purpose: the implementation is a React store\n * action, and keeping that behind a port is what stops `@entifix/transactions`\n * knowing anything about React or about where the pending set is persisted.\n */\nexport interface TransactionSink {\n began(pending: PendingTransaction): void;\n}\n\n/**\n * ⚠️ Read with `Effect.serviceOption`, never `yield*`.\n *\n * That keeps the tag out of the save adapter's `R`, so the storefront, the plain\n * REST adapters and every existing spec compile and run with no layer to\n * provide — an optional capability must not become a build break for callers\n * that will never want it.\n *\n * The cost of that erasure is that **nothing forces a composition root to\n * provide it**: forget to, and the read returns `None`, everything compiles, and\n * the feature is silently dead. A spec pins the one place that must\n * (`mergeContext`), because an invariant the compiler cannot hold is one a test\n * has to.\n */\nexport class TransactionSinkTag extends Context.Service<\n TransactionSinkTag,\n TransactionSink\n>()('TransactionSinkTag') {}\n\n/**\n * The sink where nothing is watching — outside a mounted provider, and in every\n * caller that never opted into command creates.\n *\n * A create on a plain route still works exactly as it did; it simply gets no\n * optimistic treatment, which is an honest boundary rather than a write into an\n * unscoped store.\n */\nexport const NoopTransactionSink: TransactionSink = {\n began: () => undefined,\n};\n\n/**\n * The full view of the pending set, for the side that reconciles it.\n *\n * It extends {@link TransactionSink} because one store is behind both: the\n * adapter needs only `began`, and the settlement side needs to read entries and\n * retire them. Two interfaces rather than one because they are consumed from\n * opposite sides of a tier boundary — a T3 package may not import a T4 shell,\n * so the store is handed in as a prop, the way `EntityDraftStore` already is for\n * autosave (ADR 0032).\n */\nexport interface PendingTransactionStore extends TransactionSink {\n readonly entries: readonly PendingEntry[];\n /** The write landed. Drop it; the server's copy is the truth now. */\n settle(transactionId: string): void;\n /**\n * Holds the record the browser already has, so the list can render it while\n * the write is still in flight — and answers whether this id was being\n * watched at all.\n *\n * ⚠️ **The return value is why this is one call and not two.** A caller that\n * asked `entries.some(...)` first would be reading a React render closure\n * captured *before* its own `await`, so the announcement the save adapter made\n * during that await is invisible to it and every transactional write reads as\n * a plain one. Answering from the store's current state is the only version\n * without that race.\n *\n * Separate from `began` because the save adapter announces before it returns\n * and has no reason to know about lists.\n */\n attach(transactionId: string, record: unknown): boolean;\n /** The write failed terminally. Keep it, marked, until it is dismissed. */\n fail(transactionId: string, reason?: string): void;\n /** The operator has read the failure. */\n dismiss(transactionId: string): void;\n}\n"],"names":["Context","TransactionSinkTag","Service","NoopTransactionSink","began","undefined"],"mappings":"AAAA,SAASA,OAAO,QAAQ,SAAS;AA4DjC;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,2BAA2BD,QAAQE,OAAO,GAGnD;AAAuB;AAE3B;;;;;;;CAOC,GACD,OAAO,MAAMC,sBAAuC;IAClDC,OAAO,IAAMC;AACf,EAAE"}
@@ -30,7 +30,7 @@ export interface TransactionStreamHub {
30
30
  */
31
31
  subscribe(organizationId: string): Stream.Stream<DomainEvent<EntityChangeEvent>>;
32
32
  }
33
- declare const TransactionStreamHubTag_base: Context.TagClass<TransactionStreamHubTag, "TransactionStreamHubTag", TransactionStreamHub>;
33
+ declare const TransactionStreamHubTag_base: Context.ServiceClass<TransactionStreamHubTag, "TransactionStreamHubTag", TransactionStreamHub>;
34
34
  export declare class TransactionStreamHubTag extends TransactionStreamHubTag_base {
35
35
  }
36
36
  /** Builds a hub over a sliding {@link PubSub}. */
@@ -1 +1 @@
1
- {"version":3,"file":"transaction-stream-hub.d.ts","sourceRoot":"","sources":["../../src/stream/transaction-stream-hub.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACpE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEzD,OAAO,KAAK,EAAE,gBAAgB,EAAoB,MAAM,uBAAuB,CAAC;AA4BhF;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,GAC1B,OAAO,WAAW,CAAC,gBAAgB,CAAC,KACnC,WAAW,CAAC,iBAAiB,CAW9B,CAAC;AAEH;;;;;;GAMG;AACH,MAAM,WAAW,oBAAoB;IACnC,0EAA0E;IAC1E,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC,gBAAgB,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACnE;;;;;;;OAOG;IACH,SAAS,CACP,cAAc,EAAE,MAAM,GACrB,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,iBAAiB,CAAC,CAAC,CAAC;CAClD;;AAED,qBAAa,uBAAwB,SAAQ,4BAEK;CAAG;AAErD,kDAAkD;AAClD,eAAO,MAAM,wBAAwB,GACnC,QAAQ,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC,KACnD,oBAOD,CAAC;AAEH,2EAA2E;AAC3E,eAAO,MAAM,8BAA8B,mDAG1C,CAAC"}
1
+ {"version":3,"file":"transaction-stream-hub.d.ts","sourceRoot":"","sources":["../../src/stream/transaction-stream-hub.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACpE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEzD,OAAO,KAAK,EAAE,gBAAgB,EAAoB,MAAM,uBAAuB,CAAC;AA4BhF;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,GAC1B,OAAO,WAAW,CAAC,gBAAgB,CAAC,KACnC,WAAW,CAAC,iBAAiB,CAW9B,CAAC;AAEH;;;;;;GAMG;AACH,MAAM,WAAW,oBAAoB;IACnC,0EAA0E;IAC1E,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC,gBAAgB,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACnE;;;;;;;OAOG;IACH,SAAS,CACP,cAAc,EAAE,MAAM,GACrB,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,iBAAiB,CAAC,CAAC,CAAC;CAClD;;AAED,qBAAa,uBAAwB,SAAQ,4BAGf;CAAG;AAEjC,kDAAkD;AAClD,eAAO,MAAM,wBAAwB,GACnC,QAAQ,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC,KACnD,oBAOD,CAAC;AAEH,2EAA2E;AAC3E,eAAO,MAAM,8BAA8B,mDAG1C,CAAC"}
@@ -42,7 +42,7 @@ import { Context, Effect, PubSub, Stream } from 'effect';
42
42
  }
43
43
  };
44
44
  };
45
- export class TransactionStreamHubTag extends Context.Tag('TransactionStreamHubTag')() {
45
+ export class TransactionStreamHubTag extends Context.Service()('TransactionStreamHubTag') {
46
46
  }
47
47
  /** Builds a hub over a sliding {@link PubSub}. */ export const makeTransactionStreamHub = (pubsub)=>({
48
48
  publish: (event)=>Effect.asVoid(PubSub.publish(pubsub, event)),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/stream/transaction-stream-hub.ts"],"sourcesContent":["import type { DomainEvent, EntityChangeEvent } from '@entifix/core';\nimport { Context, Effect, PubSub, Stream } from 'effect';\n\nimport type { TransactionEvent, TransactionState } from '../contracts/event.js';\n\n/**\n * How many undelivered events one hub holds before the oldest are dropped.\n *\n * Bounded with a **sliding** strategy rather than unbounded: a browser that\n * stops reading its connection must not be able to grow the service's heap, and\n * a reactive hint is worth less the older it is — the record behind it is the\n * truth, and re-reading it is cheap (ADR 0036 declines replay for the same\n * reason).\n */\nconst CAPACITY = 256;\n\n/**\n * What a transaction's state means for the entity it is about.\n *\n * `type: 'create'` is the only command that exists, so `PENDING` and\n * `COMPLETED` both announce an entity coming into existence — the id is already\n * known at `accepted`, because ADR 0028 makes the client-minted transaction id\n * the stored entity's id. A terminal failure announces the opposite: nothing was\n * written, so a consumer holding an optimistic row must drop it.\n *\n * When `update`/`delete` commands land this keys off `command.type` instead;\n * the state alone cannot distinguish them.\n */\nconst changeFor = (state: TransactionState): EntityChangeEvent['change'] =>\n state === 'PENDING' || state === 'COMPLETED' ? 'created' : 'deleted';\n\n/**\n * Rewrites a transaction event as the entity change it announces, keeping the\n * message's own metadata untouched.\n *\n * No fourth framing and no duplicated fields: the transaction id, the timestamp\n * and the sequence a consumer needs are already `meta.event.correlationId`,\n * `.at` and `.id` on the message this returns (ADR 0036).\n */\nexport const entityChangeFor = (\n event: DomainEvent<TransactionEvent>,\n): DomainEvent<EntityChangeEvent> => ({\n name: event.name,\n id: event.id,\n source: event.source,\n at: event.at,\n correlationId: event.correlationId,\n data: {\n entity: event.data.entity,\n change: changeFor(event.data.state),\n id: event.data.entityId ?? event.data.transactionId,\n },\n});\n\n/**\n * The in-process fan-out behind `GET /api/transaction/events`.\n *\n * One subscription to the bus feeds it; each connected browser takes its own\n * filtered view. It is a hub rather than a bus subscription per connection\n * because a queue per open tab is a broker resource a client controls.\n */\nexport interface TransactionStreamHub {\n /** Offer one bus event to every connection scoped to its organization. */\n publish(event: DomainEvent<TransactionEvent>): Effect.Effect<void>;\n /**\n * One connection's view, already scoped and already mapped.\n *\n * ⚠️ **Fails closed.** An event whose `organizationId` does not match is\n * dropped, and so is one carrying none at all — including every event emitted\n * before that member existed. Defaulting an absent organization to \"everyone\"\n * is a cross-tenant delivery that raises nothing.\n */\n subscribe(\n organizationId: string,\n ): Stream.Stream<DomainEvent<EntityChangeEvent>>;\n}\n\nexport class TransactionStreamHubTag extends Context.Tag(\n 'TransactionStreamHubTag',\n)<TransactionStreamHubTag, TransactionStreamHub>() {}\n\n/** Builds a hub over a sliding {@link PubSub}. */\nexport const makeTransactionStreamHub = (\n pubsub: PubSub.PubSub<DomainEvent<TransactionEvent>>,\n): TransactionStreamHub => ({\n publish: event => Effect.asVoid(PubSub.publish(pubsub, event)),\n subscribe: organizationId =>\n Stream.fromPubSub(pubsub).pipe(\n Stream.filter(event => event.data.organizationId === organizationId),\n Stream.map(entityChangeFor),\n ),\n});\n\n/** Opens a hub. Scoped, so its subscribers are released with the scope. */\nexport const makeTransactionStreamHubEffect = Effect.map(\n PubSub.sliding<DomainEvent<TransactionEvent>>(CAPACITY),\n makeTransactionStreamHub,\n);\n"],"names":["Context","Effect","PubSub","Stream","CAPACITY","changeFor","state","entityChangeFor","event","name","id","source","at","correlationId","data","entity","change","entityId","transactionId","TransactionStreamHubTag","Tag","makeTransactionStreamHub","pubsub","publish","asVoid","subscribe","organizationId","fromPubSub","pipe","filter","map","makeTransactionStreamHubEffect","sliding"],"mappings":"AACA,SAASA,OAAO,EAAEC,MAAM,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAIzD;;;;;;;;CAQC,GACD,MAAMC,WAAW;AAEjB;;;;;;;;;;;CAWC,GACD,MAAMC,YAAY,CAACC,QACjBA,UAAU,aAAaA,UAAU,cAAc,YAAY;AAE7D;;;;;;;CAOC,GACD,OAAO,MAAMC,kBAAkB,CAC7BC;QAUMA;WAT8B;QACpCC,MAAMD,MAAMC,IAAI;QAChBC,IAAIF,MAAME,EAAE;QACZC,QAAQH,MAAMG,MAAM;QACpBC,IAAIJ,MAAMI,EAAE;QACZC,eAAeL,MAAMK,aAAa;QAClCC,MAAM;YACJC,QAAQP,MAAMM,IAAI,CAACC,MAAM;YACzBC,QAAQX,UAAUG,MAAMM,IAAI,CAACR,KAAK;YAClCI,EAAE,GAAEF,uBAAAA,MAAMM,IAAI,CAACG,QAAQ,YAAnBT,uBAAuBA,MAAMM,IAAI,CAACI,aAAa;QACrD;IACF;EAAG;AAyBH,OAAO,MAAMC,gCAAgCnB,QAAQoB,GAAG,CACtD;AACkD;AAEpD,gDAAgD,GAChD,OAAO,MAAMC,2BAA2B,CACtCC,SAC0B,CAAA;QAC1BC,SAASf,CAAAA,QAASP,OAAOuB,MAAM,CAACtB,OAAOqB,OAAO,CAACD,QAAQd;QACvDiB,WAAWC,CAAAA,iBACTvB,OAAOwB,UAAU,CAACL,QAAQM,IAAI,CAC5BzB,OAAO0B,MAAM,CAACrB,CAAAA,QAASA,MAAMM,IAAI,CAACY,cAAc,KAAKA,iBACrDvB,OAAO2B,GAAG,CAACvB;IAEjB,CAAA,EAAG;AAEH,yEAAyE,GACzE,OAAO,MAAMwB,iCAAiC9B,OAAO6B,GAAG,CACtD5B,OAAO8B,OAAO,CAAgC5B,WAC9CiB,0BACA"}
1
+ {"version":3,"sources":["../../src/stream/transaction-stream-hub.ts"],"sourcesContent":["import type { DomainEvent, EntityChangeEvent } from '@entifix/core';\nimport { Context, Effect, PubSub, Stream } from 'effect';\n\nimport type { TransactionEvent, TransactionState } from '../contracts/event.js';\n\n/**\n * How many undelivered events one hub holds before the oldest are dropped.\n *\n * Bounded with a **sliding** strategy rather than unbounded: a browser that\n * stops reading its connection must not be able to grow the service's heap, and\n * a reactive hint is worth less the older it is — the record behind it is the\n * truth, and re-reading it is cheap (ADR 0036 declines replay for the same\n * reason).\n */\nconst CAPACITY = 256;\n\n/**\n * What a transaction's state means for the entity it is about.\n *\n * `type: 'create'` is the only command that exists, so `PENDING` and\n * `COMPLETED` both announce an entity coming into existence — the id is already\n * known at `accepted`, because ADR 0028 makes the client-minted transaction id\n * the stored entity's id. A terminal failure announces the opposite: nothing was\n * written, so a consumer holding an optimistic row must drop it.\n *\n * When `update`/`delete` commands land this keys off `command.type` instead;\n * the state alone cannot distinguish them.\n */\nconst changeFor = (state: TransactionState): EntityChangeEvent['change'] =>\n state === 'PENDING' || state === 'COMPLETED' ? 'created' : 'deleted';\n\n/**\n * Rewrites a transaction event as the entity change it announces, keeping the\n * message's own metadata untouched.\n *\n * No fourth framing and no duplicated fields: the transaction id, the timestamp\n * and the sequence a consumer needs are already `meta.event.correlationId`,\n * `.at` and `.id` on the message this returns (ADR 0036).\n */\nexport const entityChangeFor = (\n event: DomainEvent<TransactionEvent>,\n): DomainEvent<EntityChangeEvent> => ({\n name: event.name,\n id: event.id,\n source: event.source,\n at: event.at,\n correlationId: event.correlationId,\n data: {\n entity: event.data.entity,\n change: changeFor(event.data.state),\n id: event.data.entityId ?? event.data.transactionId,\n },\n});\n\n/**\n * The in-process fan-out behind `GET /api/transaction/events`.\n *\n * One subscription to the bus feeds it; each connected browser takes its own\n * filtered view. It is a hub rather than a bus subscription per connection\n * because a queue per open tab is a broker resource a client controls.\n */\nexport interface TransactionStreamHub {\n /** Offer one bus event to every connection scoped to its organization. */\n publish(event: DomainEvent<TransactionEvent>): Effect.Effect<void>;\n /**\n * One connection's view, already scoped and already mapped.\n *\n * ⚠️ **Fails closed.** An event whose `organizationId` does not match is\n * dropped, and so is one carrying none at all — including every event emitted\n * before that member existed. Defaulting an absent organization to \"everyone\"\n * is a cross-tenant delivery that raises nothing.\n */\n subscribe(\n organizationId: string,\n ): Stream.Stream<DomainEvent<EntityChangeEvent>>;\n}\n\nexport class TransactionStreamHubTag extends Context.Service<\n TransactionStreamHubTag,\n TransactionStreamHub\n>()('TransactionStreamHubTag') {}\n\n/** Builds a hub over a sliding {@link PubSub}. */\nexport const makeTransactionStreamHub = (\n pubsub: PubSub.PubSub<DomainEvent<TransactionEvent>>,\n): TransactionStreamHub => ({\n publish: event => Effect.asVoid(PubSub.publish(pubsub, event)),\n subscribe: organizationId =>\n Stream.fromPubSub(pubsub).pipe(\n Stream.filter(event => event.data.organizationId === organizationId),\n Stream.map(entityChangeFor),\n ),\n});\n\n/** Opens a hub. Scoped, so its subscribers are released with the scope. */\nexport const makeTransactionStreamHubEffect = Effect.map(\n PubSub.sliding<DomainEvent<TransactionEvent>>(CAPACITY),\n makeTransactionStreamHub,\n);\n"],"names":["Context","Effect","PubSub","Stream","CAPACITY","changeFor","state","entityChangeFor","event","name","id","source","at","correlationId","data","entity","change","entityId","transactionId","TransactionStreamHubTag","Service","makeTransactionStreamHub","pubsub","publish","asVoid","subscribe","organizationId","fromPubSub","pipe","filter","map","makeTransactionStreamHubEffect","sliding"],"mappings":"AACA,SAASA,OAAO,EAAEC,MAAM,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAIzD;;;;;;;;CAQC,GACD,MAAMC,WAAW;AAEjB;;;;;;;;;;;CAWC,GACD,MAAMC,YAAY,CAACC,QACjBA,UAAU,aAAaA,UAAU,cAAc,YAAY;AAE7D;;;;;;;CAOC,GACD,OAAO,MAAMC,kBAAkB,CAC7BC;QAUMA;WAT8B;QACpCC,MAAMD,MAAMC,IAAI;QAChBC,IAAIF,MAAME,EAAE;QACZC,QAAQH,MAAMG,MAAM;QACpBC,IAAIJ,MAAMI,EAAE;QACZC,eAAeL,MAAMK,aAAa;QAClCC,MAAM;YACJC,QAAQP,MAAMM,IAAI,CAACC,MAAM;YACzBC,QAAQX,UAAUG,MAAMM,IAAI,CAACR,KAAK;YAClCI,EAAE,GAAEF,uBAAAA,MAAMM,IAAI,CAACG,QAAQ,YAAnBT,uBAAuBA,MAAMM,IAAI,CAACI,aAAa;QACrD;IACF;EAAG;AAyBH,OAAO,MAAMC,gCAAgCnB,QAAQoB,OAAO,GAGxD;AAA4B;AAEhC,gDAAgD,GAChD,OAAO,MAAMC,2BAA2B,CACtCC,SAC0B,CAAA;QAC1BC,SAASf,CAAAA,QAASP,OAAOuB,MAAM,CAACtB,OAAOqB,OAAO,CAACD,QAAQd;QACvDiB,WAAWC,CAAAA,iBACTvB,OAAOwB,UAAU,CAACL,QAAQM,IAAI,CAC5BzB,OAAO0B,MAAM,CAACrB,CAAAA,QAASA,MAAMM,IAAI,CAACY,cAAc,KAAKA,iBACrDvB,OAAO2B,GAAG,CAACvB;IAEjB,CAAA,EAAG;AAEH,yEAAyE,GACzE,OAAO,MAAMwB,iCAAiC9B,OAAO6B,GAAG,CACtD5B,OAAO8B,OAAO,CAAgC5B,WAC9CiB,0BACA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/transactions",
3
- "version": "0.1.4",
3
+ "version": "0.3.0",
4
4
  "description": "Commands, transactions and sagas: inbox and outbox ports, an event bus, locks, and a declarative saga runner.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -18,7 +18,6 @@
18
18
  "exports": {
19
19
  "./package.json": "./package.json",
20
20
  ".": {
21
- "@entifix/source": "./src/index.ts",
22
21
  "types": "./dist/index.d.ts",
23
22
  "import": "./dist/index.js",
24
23
  "default": "./dist/index.js"
@@ -52,13 +51,13 @@
52
51
  },
53
52
  "dependencies": {
54
53
  "@swc/helpers": "0.5.23",
55
- "@entifix/business": "0.1.4",
56
- "@entifix/core": "0.1.4"
54
+ "@entifix/business": "0.3.0",
55
+ "@entifix/core": "0.3.0"
57
56
  },
58
57
  "peerDependencies": {
59
- "effect": ">=3.22.2 <4"
58
+ "effect": "^4.0.5"
60
59
  },
61
60
  "devDependencies": {
62
- "effect": "3.22.2"
61
+ "effect": "4.0.5"
63
62
  }
64
63
  }