@entifix/transactions 0.14.0 → 0.15.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 (93) hide show
  1. package/README.md +6 -6
  2. package/dist/engine/index.d.ts +2 -9
  3. package/dist/engine/index.d.ts.map +1 -1
  4. package/dist/engine/index.js +3 -10
  5. package/dist/engine/index.js.map +1 -1
  6. package/dist/index.d.ts +0 -14
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +0 -14
  9. package/dist/index.js.map +1 -1
  10. package/dist/ports/participant-client.d.ts +7 -2
  11. package/dist/ports/participant-client.d.ts.map +1 -1
  12. package/dist/ports/participant-client.js.map +1 -1
  13. package/package.json +4 -4
  14. package/dist/contracts/command.d.ts +0 -59
  15. package/dist/contracts/command.d.ts.map +0 -1
  16. package/dist/contracts/command.js +0 -46
  17. package/dist/contracts/command.js.map +0 -1
  18. package/dist/contracts/event.d.ts +0 -85
  19. package/dist/contracts/event.d.ts.map +0 -1
  20. package/dist/contracts/event.js +0 -81
  21. package/dist/contracts/event.js.map +0 -1
  22. package/dist/contracts/messages.d.ts +0 -37
  23. package/dist/contracts/messages.d.ts.map +0 -1
  24. package/dist/contracts/messages.js +0 -68
  25. package/dist/contracts/messages.js.map +0 -1
  26. package/dist/contracts/record.d.ts +0 -106
  27. package/dist/contracts/record.d.ts.map +0 -1
  28. package/dist/contracts/record.js +0 -27
  29. package/dist/contracts/record.js.map +0 -1
  30. package/dist/contracts/saga-definition.d.ts +0 -181
  31. package/dist/contracts/saga-definition.d.ts.map +0 -1
  32. package/dist/contracts/saga-definition.js +0 -101
  33. package/dist/contracts/saga-definition.js.map +0 -1
  34. package/dist/engine/local-saga-dispatcher.d.ts +0 -35
  35. package/dist/engine/local-saga-dispatcher.d.ts.map +0 -1
  36. package/dist/engine/local-saga-dispatcher.js +0 -28
  37. package/dist/engine/local-saga-dispatcher.js.map +0 -1
  38. package/dist/engine/resolve-template.d.ts +0 -48
  39. package/dist/engine/resolve-template.d.ts.map +0 -1
  40. package/dist/engine/resolve-template.js +0 -95
  41. package/dist/engine/resolve-template.js.map +0 -1
  42. package/dist/engine/resume-sweep.d.ts +0 -46
  43. package/dist/engine/resume-sweep.d.ts.map +0 -1
  44. package/dist/engine/resume-sweep.js +0 -74
  45. package/dist/engine/resume-sweep.js.map +0 -1
  46. package/dist/engine/run-saga.d.ts +0 -54
  47. package/dist/engine/run-saga.d.ts.map +0 -1
  48. package/dist/engine/run-saga.js +0 -463
  49. package/dist/engine/run-saga.js.map +0 -1
  50. package/dist/engine/run-transaction.d.ts +0 -55
  51. package/dist/engine/run-transaction.d.ts.map +0 -1
  52. package/dist/engine/run-transaction.js +0 -101
  53. package/dist/engine/run-transaction.js.map +0 -1
  54. package/dist/mixins/transaction-mixins.d.ts +0 -20
  55. package/dist/mixins/transaction-mixins.d.ts.map +0 -1
  56. package/dist/mixins/transaction-mixins.js +0 -13
  57. package/dist/mixins/transaction-mixins.js.map +0 -1
  58. package/dist/ports/lock-service.d.ts +0 -24
  59. package/dist/ports/lock-service.d.ts.map +0 -1
  60. package/dist/ports/lock-service.js +0 -5
  61. package/dist/ports/lock-service.js.map +0 -1
  62. package/dist/ports/saga-dispatcher.d.ts +0 -46
  63. package/dist/ports/saga-dispatcher.d.ts.map +0 -1
  64. package/dist/ports/saga-dispatcher.js +0 -5
  65. package/dist/ports/saga-dispatcher.js.map +0 -1
  66. package/dist/ports/saga-store.d.ts +0 -96
  67. package/dist/ports/saga-store.d.ts.map +0 -1
  68. package/dist/ports/saga-store.js +0 -19
  69. package/dist/ports/saga-store.js.map +0 -1
  70. package/dist/ports/sequence-service.d.ts +0 -17
  71. package/dist/ports/sequence-service.d.ts.map +0 -1
  72. package/dist/ports/sequence-service.js +0 -5
  73. package/dist/ports/sequence-service.js.map +0 -1
  74. package/dist/ports/transaction-handler.d.ts +0 -66
  75. package/dist/ports/transaction-handler.d.ts.map +0 -1
  76. package/dist/ports/transaction-handler.js +0 -5
  77. package/dist/ports/transaction-handler.js.map +0 -1
  78. package/dist/ports/transaction-sink.d.ts +0 -120
  79. package/dist/ports/transaction-sink.d.ts.map +0 -1
  80. package/dist/ports/transaction-sink.js +0 -28
  81. package/dist/ports/transaction-sink.js.map +0 -1
  82. package/dist/ports/transaction-stream-hub.d.ts +0 -28
  83. package/dist/ports/transaction-stream-hub.d.ts.map +0 -1
  84. package/dist/ports/transaction-stream-hub.js +0 -5
  85. package/dist/ports/transaction-stream-hub.js.map +0 -1
  86. package/dist/stream/transaction-stream-hub.d.ts +0 -18
  87. package/dist/stream/transaction-stream-hub.d.ts.map +0 -1
  88. package/dist/stream/transaction-stream-hub.js +0 -50
  89. package/dist/stream/transaction-stream-hub.js.map +0 -1
  90. package/dist/use-case/facade.uc.d.ts +0 -22
  91. package/dist/use-case/facade.uc.d.ts.map +0 -1
  92. package/dist/use-case/facade.uc.js +0 -55
  93. package/dist/use-case/facade.uc.js.map +0 -1
@@ -1,68 +0,0 @@
1
- import { openStruct, registerEvent, registerMessage } from '@entifix/core';
2
- import { Schema } from 'effect';
3
- import { TRANSACTION_STATES, transactionEventName } from './event.js';
4
- /**
5
- * The transaction-shaped messages, registered by the package that owns them —
6
- * core's registry is open, so these left core's closed union in 0.11.0 and are
7
- * deleted with the saga runner and the tracker (#127).
8
- *
9
- * Each schema names only what a reader of it branches on and keeps the rest,
10
- * which is enough to refuse a body that is some other message wearing this
11
- * one's name.
12
- */ const State = Schema.Literals(TRANSACTION_STATES);
13
- export const TransactionCommandSchema = openStruct({
14
- transactionId: Schema.String,
15
- type: Schema.String,
16
- entity: Schema.String,
17
- payload: Schema.Unknown
18
- });
19
- export const TransactionAcceptedSchema = openStruct({
20
- transactionId: Schema.String,
21
- state: State
22
- });
23
- export const TransactionRecordSchema = openStruct({
24
- transactionId: Schema.String,
25
- entity: Schema.String,
26
- state: State,
27
- createdAt: Schema.String,
28
- updatedAt: Schema.String
29
- });
30
- export const SagaResultSchema = openStruct({
31
- state: Schema.String,
32
- outcomes: Schema.Array(Schema.Unknown)
33
- });
34
- export const SagaInstanceSchema = openStruct({
35
- sagaId: Schema.String,
36
- definition: Schema.String,
37
- state: Schema.String,
38
- stepIndex: Schema.Number,
39
- outcomes: Schema.Array(Schema.Unknown)
40
- });
41
- export const TransactionEventSchema = openStruct({
42
- transactionId: Schema.String,
43
- entity: Schema.String,
44
- state: State,
45
- step: Schema.Literals([
46
- 'accepted',
47
- 'completed',
48
- 'failed'
49
- ]),
50
- at: Schema.String
51
- });
52
- registerMessage('command', TransactionCommandSchema);
53
- registerMessage('transactionAccepted', TransactionAcceptedSchema);
54
- registerMessage('transactionRecord', TransactionRecordSchema);
55
- registerMessage('sagaResult', SagaResultSchema);
56
- registerMessage('sagaInstance', SagaInstanceSchema);
57
- // ⚠️ Registered audience-free: a transaction event is scoped by the
58
- // `organizationId` in its `data`, which is what the stream hub filters on
59
- // today. The flow events that replace these carry a real audience.
60
- for (const step of [
61
- 'accepted',
62
- 'completed',
63
- 'failed'
64
- ])registerEvent(transactionEventName(step), TransactionEventSchema, {
65
- audience: 'none'
66
- });
67
-
68
- //# sourceMappingURL=messages.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/contracts/messages.ts"],"sourcesContent":["import { openStruct, registerEvent, registerMessage } from '@entifix/core';\nimport { Schema } from 'effect';\n\nimport { TRANSACTION_STATES, transactionEventName } from './event.js';\n\n/**\n * The transaction-shaped messages, registered by the package that owns them —\n * core's registry is open, so these left core's closed union in 0.11.0 and are\n * deleted with the saga runner and the tracker (#127).\n *\n * Each schema names only what a reader of it branches on and keeps the rest,\n * which is enough to refuse a body that is some other message wearing this\n * one's name.\n */\nconst State = Schema.Literals(TRANSACTION_STATES);\n\nexport const TransactionCommandSchema = openStruct({\n transactionId: Schema.String,\n type: Schema.String,\n entity: Schema.String,\n payload: Schema.Unknown,\n});\n\nexport const TransactionAcceptedSchema = openStruct({\n transactionId: Schema.String,\n state: State,\n});\n\nexport const TransactionRecordSchema = openStruct({\n transactionId: Schema.String,\n entity: Schema.String,\n state: State,\n createdAt: Schema.String,\n updatedAt: Schema.String,\n});\n\nexport const SagaResultSchema = openStruct({\n state: Schema.String,\n outcomes: Schema.Array(Schema.Unknown),\n});\n\nexport const SagaInstanceSchema = openStruct({\n sagaId: Schema.String,\n definition: Schema.String,\n state: Schema.String,\n stepIndex: Schema.Number,\n outcomes: Schema.Array(Schema.Unknown),\n});\n\nexport const TransactionEventSchema = openStruct({\n transactionId: Schema.String,\n entity: Schema.String,\n state: State,\n step: Schema.Literals(['accepted', 'completed', 'failed']),\n at: Schema.String,\n});\n\nregisterMessage('command', TransactionCommandSchema);\nregisterMessage('transactionAccepted', TransactionAcceptedSchema);\nregisterMessage('transactionRecord', TransactionRecordSchema);\nregisterMessage('sagaResult', SagaResultSchema);\nregisterMessage('sagaInstance', SagaInstanceSchema);\n\n// ⚠️ Registered audience-free: a transaction event is scoped by the\n// `organizationId` in its `data`, which is what the stream hub filters on\n// today. The flow events that replace these carry a real audience.\nfor (const step of ['accepted', 'completed', 'failed'] as const)\n registerEvent(transactionEventName(step), TransactionEventSchema, {\n audience: 'none',\n });\n"],"names":["openStruct","registerEvent","registerMessage","Schema","TRANSACTION_STATES","transactionEventName","State","Literals","TransactionCommandSchema","transactionId","String","type","entity","payload","Unknown","TransactionAcceptedSchema","state","TransactionRecordSchema","createdAt","updatedAt","SagaResultSchema","outcomes","Array","SagaInstanceSchema","sagaId","definition","stepIndex","Number","TransactionEventSchema","step","at","audience"],"mappings":"AAAA,SAASA,UAAU,EAAEC,aAAa,EAAEC,eAAe,QAAQ,gBAAgB;AAC3E,SAASC,MAAM,QAAQ,SAAS;AAEhC,SAASC,kBAAkB,EAAEC,oBAAoB,QAAQ,aAAa;AAEtE;;;;;;;;CAQC,GACD,MAAMC,QAAQH,OAAOI,QAAQ,CAACH;AAE9B,OAAO,MAAMI,2BAA2BR,WAAW;IACjDS,eAAeN,OAAOO,MAAM;IAC5BC,MAAMR,OAAOO,MAAM;IACn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ocolFailure, type StoreFault } from '@entifix/core';
3
- import { Context, Effect } from 'effect';
4
- import type { TransactionEvent, TransactionState } from './event.js';
5
- /**
6
- * The the saga tracker's persisted view of a transaction, folded from the
7
- * events it observes. It is the source of truth a client polls.
8
- */
9
- export interface TransactionRecord {
10
- transactionId: string;
11
- entity: string;
12
- state: TransactionState;
13
- code?: string;
14
- entityId?: EntityId;
15
- error?: string;
16
- createdAt: string;
17
- updatedAt: string;
18
- /**
19
- * Whose organization this transaction happened in, folded from the event.
20
- *
21
- * The `saga` store is control-plane and single-partition — it holds every
22
- * organization's records by design — so isolation on the read routes has to be
23
- * this filter. A record written before the member existed carries none and is
24
- * therefore readable by nobody, which is the direction to fail.
25
- */
26
- organizationId?: string;
27
- }
28
- /**
29
- * Port the manager tracks transactions through. Implemented over Mongo in the
30
- * service; framework-free here so the engine/manager stay environment-agnostic.
31
- */
32
- export interface TransactionStore {
33
- /** Folds an event into the record, creating it on first sight. */
34
- upsertFromEvent(event: TransactionEvent): Effect.Effect<TransactionRecord, StoreFault>;
35
- get(transactionId: string): Effect.Effect<TransactionRecord | undefined, StoreFault>;
36
- /** Non-terminal records not updated within `olderThanMs` — recovery input. */
37
- findStale(olderThanMs: number): Effect.Effect<readonly TransactionRecord[], StoreFault>;
38
- markStale(transactionId: string): Effect.Effect<void, StoreFault>;
39
- /**
40
- * How many records sit in each state — the recovery sweep samples it.
41
- *
42
- * ⚠️ **This is a count, and is not the `list` above.** It returns no record,
43
- * no id and no organization, so it does not reopen the list surface removed
44
- * `GET /api/transaction` for: an unfiltered *listing* of this store is every
45
- * organization's transactions, while a total of how many are `STALE` is a
46
- * fleet health number that names nobody. The distinction is the whole reason
47
- * one is here and the other is refused.
48
- *
49
- * It exists so `STALE` is something a dashboard shows rather than something a
50
- * poll discovers — which is what the recovery sweep, whose only action is to
51
- * apply that label, otherwise leaves entirely unobservable.
52
- */
53
- countByState(): Effect.Effect<Record<TransactionState, number>, StoreFault>;
54
- }
55
- declare const TransactionStoreTag_base: Context.ServiceClass<TransactionStoreTag, "TransactionStoreTag", TransactionStore>;
56
- export declare class TransactionStoreTag extends TransactionStoreTag_base {
57
- }
58
- /**
59
- * What a service answers a `202` with: the id to poll, and the state it starts
60
- * in.
61
- *
62
- * ⚠️ **Not a {@link TransactionRecord}, which is why it has its own
63
- * discriminant.** Nothing has been folded yet — there is no `createdAt`, no
64
- * entity id, and no code, because the write has not run. Framing it as a record
65
- * meant the browser's accept-shape assertion was checking a name that the
66
- * by-id route and the bus payload also answered to, so it asserted nothing it
67
- * claimed to.
68
- */
69
- export interface TransactionAccepted {
70
- transactionId: string;
71
- state: TransactionState;
72
- }
73
- /**
74
- * Parses a `202` accept body, for a browser about to start polling.
75
- *
76
- * Read for its **shape**, not its contents: it asserts the service really
77
- * accepted a transaction rather than answering something else with a `2xx`.
78
- */
79
- export declare function readTransactionAcceptedEnvelope(body: unknown): Effect.Effect<TransactionAccepted, ProtocolFailure>;
80
- /**
81
- * Parses the tracker's by-id response, which frames a {@link TransactionRecord}.
82
- *
83
- * The body is decoded against `transactionRecord`'s registered schema, so a
84
- * different message wearing the name — an event, which has a `step` and no
85
- * `createdAt` — is refused rather than handed back typed and wrong.
86
- */
87
- export declare function readTransactionRecordEnvelope(body: unknown): Effect.Effect<TransactionRecord, ProtocolFailure>;
88
- /**
89
- * Reads one transaction's record, for a browser reconciling a write it started.
90
- *
91
- * ⚠️ **`undefined` means _not tracked yet_, not _failed_.** `accepted` reaches
92
- * the tracker over the bus, so with the broker down the entity write commits —
93
- * the outbox is in the same Mongo transaction — while no event is ever
94
- * published and this answers `404`. That is a write in perfect health, and a
95
- * caller that rolls back on it un-renders a record that is about to appear, at
96
- * exactly the moment nobody can tell a UI bug from an outage. Only `FAILED` and
97
- * `STALE` are terminal.
98
- */
99
- export interface TransactionStatusReader {
100
- read(transactionId: string): Effect.Effect<TransactionRecord | undefined, EntifixFailure>;
101
- }
102
- declare const TransactionStatusReaderTag_base: Context.ServiceClass<TransactionStatusReaderTag, "TransactionStatusReaderTag", TransactionStatusReader>;
103
- export declare class TransactionStatusReaderTag extends TransactionStatusReaderTag_base {
104
- }
105
- export {};
106
- //# sourceMappingURL=record.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"record.d.ts","sourceRoot":"","sources":["../../src/contracts/record.ts"],"names":[],"mappings":"AACA,OAAO,eAAe,CAAC;AAEvB,OAAO,EAEL,KAAK,cAAc,EACnB,KAAK,QAAQ,EACb,KAAK,eAAe,EACpB,KAAK,UAAU,EAChB,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;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB;;;;;;;OAOG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,kEAAkE;IAClE,eAAe,CACb,KAAK,EAAE,gBAAgB,GACtB,MAAM,CAAC,MAAM,CAAC,iBAAiB,EAAE,UAAU,CAAC,CAAC;IAChD,GAAG,CACD,aAAa,EAAE,MAAM,GACpB,MAAM,CAAC,MAAM,CAAC,iBAAiB,GAAG,SAAS,EAAE,UAAU,CAAC,CAAC;IAM5D,8EAA8E;IAC9E,SAAS,CACP,WAAW,EAAE,MAAM,GAClB,MAAM,CAAC,MAAM,CAAC,SAAS,iBAAiB,EAAE,EAAE,UAAU,CAAC,CAAC;IAC3D,SAAS,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;IAClE;;;;;;;;;;;;;OAaG;IACH,YAAY,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,gBAAgB,EAAE,MAAM,CAAC,EAAE,UAAU,CAAC,CAAC;CAC7E;;AAED,qBAAa,mBAAoB,SAAQ,wBAGf;CAAG;AAE7B;;;;;;;;;;GAUG;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,eAAe,CAAC,CAKrD;AAED;;;;;;GAMG;AACH,wBAAgB,6BAA6B,CAC3C,IAAI,EAAE,OAAO,GACZ,MAAM,CAAC,MAAM,CAAC,iBAAiB,EAAE,eAAe,CAAC,CAKnD;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,uBAAuB;IACtC,IAAI,CACF,aAAa,EAAE,MAAM,GACpB,MAAM,CAAC,MAAM,CAAC,iBAAiB,GAAG,SAAS,EAAE,cAAc,CAAC,CAAC;CACjE;;AAED,qBAAa,0BAA2B,SAAQ,+BAGf;CAAG"}
@@ -1,27 +0,0 @@
1
- // Evaluated for its registrations: this reader decodes against them.
2
- import './messages.js';
3
- import { decodeEnvelope } from '@entifix/core';
4
- import { Context, Effect } from 'effect';
5
- export class TransactionStoreTag extends Context.Service()('TransactionStoreTag') {
6
- }
7
- /**
8
- * Parses a `202` accept body, for a browser about to start polling.
9
- *
10
- * Read for its **shape**, not its contents: it asserts the service really
11
- * accepted a transaction rather than answering something else with a `2xx`.
12
- */ export function readTransactionAcceptedEnvelope(body) {
13
- return Effect.map(decodeEnvelope(body, 'transactionAccepted'), (envelope)=>envelope.data);
14
- }
15
- /**
16
- * Parses the tracker's by-id response, which frames a {@link TransactionRecord}.
17
- *
18
- * The body is decoded against `transactionRecord`'s registered schema, so a
19
- * different message wearing the name — an event, which has a `step` and no
20
- * `createdAt` — is refused rather than handed back typed and wrong.
21
- */ export function readTransactionRecordEnvelope(body) {
22
- return Effect.map(decodeEnvelope(body, 'transactionRecord'), (envelope)=>envelope.data);
23
- }
24
- export class TransactionStatusReaderTag extends Context.Service()('TransactionStatusReaderTag') {
25
- }
26
-
27
- //# sourceMappingURL=record.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/contracts/record.ts"],"sourcesContent":["// Evaluated for its registrations: this reader decodes against them.\nimport './messages.js';\n\nimport {\n decodeEnvelope,\n type EntifixFailure,\n type EntityId,\n type ProtocolFailure,\n type StoreFault,\n} from '@entifix/core';\nimport { Context, Effect } from 'effect';\n\nimport type { TransactionEvent, TransactionState } from './event.js';\n\n/**\n * The the saga tracker's persisted view of a transaction, folded from the\n * events it observes. It is the source of truth a client polls.\n */\nexport interface TransactionRecord {\n transactionId: string;\n entity: string;\n state: TransactionState;\n code?: string;\n entityId?: EntityId;\n error?: string;\n createdAt: string;\n updatedAt: string;\n /**\n * Whose organization this transaction happened in, folded from the event.\n *\n * The `saga` store is control-plane and single-partition — it holds every\n * organization's records by design — so isolation on the read routes has to be\n * this filter. A record written before the member existed carries none and is\n * therefore readable by nobody, which is the direction to fail.\n */\n organizationId?: string;\n}\n\n/**\n * Port the manager tracks transactions through. Implemented over Mongo in the\n * service; framework-free here so the engine/manager stay environment-agnostic.\n */\nexport interface TransactionStore {\n /** Folds an event into the record, creating it on first sight. */\n upsertFromEvent(\n event: TransactionEvent,\n ): Effect.Effect<TransactionRecord, StoreFault>;\n get(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, StoreFault>;\n // There is deliberately no `list`. The `saga` store is control-plane and\n // single-partition, so an unfiltered index is every organization's\n // transactions — which is why there is no `GET /api/transaction` list.\n // Anything that needs a set of records asks for one narrow enough to scope,\n // the way `findStale` does.\n /** Non-terminal records not updated within `olderThanMs` — recovery input. */\n findStale(\n olderThanMs: number,\n ): Effect.Effect<readonly TransactionRecord[], StoreFault>;\n markStale(transactionId: string): Effect.Effect<void, StoreFault>;\n /**\n * How many records sit in each state — the recovery sweep samples it.\n *\n * ⚠️ **This is a count, and is not the `list` above.** It returns no record,\n * no id and no organization, so it does not reopen the list surface removed\n * `GET /api/transaction` for: an unfiltered *listing* of this store is every\n * organization's transactions, while a total of how many are `STALE` is a\n * fleet health number that names nobody. The distinction is the whole reason\n * one is here and the other is refused.\n *\n * It exists so `STALE` is something a dashboard shows rather than something a\n * poll discovers — which is what the recovery sweep, whose only action is to\n * apply that label, otherwise leaves entirely unobservable.\n */\n countByState(): Effect.Effect<Record<TransactionState, number>, StoreFault>;\n}\n\nexport class TransactionStoreTag extends Context.Service<\n TransactionStoreTag,\n TransactionStore\n>()('TransactionStoreTag') {}\n\n/**\n * What a service answers a `202` with: the id to poll, and the state it starts\n * in.\n *\n * ⚠️ **Not a {@link TransactionRecord}, which is why it has its own\n * discriminant.** Nothing has been folded yet — there is no `createdAt`, no\n * entity id, and no code, because the write has not run. Framing it as a record\n * meant the browser's accept-shape assertion was checking a name that the\n * by-id route and the bus payload also answered to, so it asserted nothing it\n * claimed to.\n */\nexport interface TransactionAccepted {\n transactionId: string;\n state: TransactionState;\n}\n\n/**\n * Parses a `202` accept body, for a browser about to start polling.\n *\n * Read for its **shape**, not its contents: it asserts the service really\n * accepted a transaction rather than answering something else with a `2xx`.\n */\nexport function readTransactionAcceptedEnvelope(\n body: unknown,\n): Effect.Effect<TransactionAccepted, ProtocolFailure> {\n return Effect.map(\n decodeEnvelope(body, 'transactionAccepted'),\n envelope => envelope.data as TransactionAccepted,\n );\n}\n\n/**\n * Parses the tracker's by-id response, which frames a {@link TransactionRecord}.\n *\n * The body is decoded against `transactionRecord`'s registered schema, so a\n * different message wearing the name — an event, which has a `step` and no\n * `createdAt` — is refused rather than handed back typed and wrong.\n */\nexport function readTransactionRecordEnvelope(\n body: unknown,\n): Effect.Effect<TransactionRecord, ProtocolFailure> {\n return Effect.map(\n decodeEnvelope(body, 'transactionRecord'),\n envelope => envelope.data as TransactionRecord,\n );\n}\n\n/**\n * Reads one transaction's record, for a browser reconciling a write it started.\n *\n * ⚠️ **`undefined` means _not tracked yet_, not _failed_.** `accepted` reaches\n * the tracker over the bus, so with the broker down the entity write commits —\n * the outbox is in the same Mongo transaction — while no event is ever\n * published and this answers `404`. That is a write in perfect health, and a\n * caller that rolls back on it un-renders a record that is about to appear, at\n * exactly the moment nobody can tell a UI bug from an outage. Only `FAILED` and\n * `STALE` are terminal.\n */\nexport interface TransactionStatusReader {\n read(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, EntifixFailure>;\n}\n\nexport class TransactionStatusReaderTag extends Context.Service<\n TransactionStatusReaderTag,\n TransactionStatusReader\n>()('TransactionStatusReaderTag') {}\n"],"names":["decodeEnvelope","Context","Effect","TransactionStoreTag","Service","readTransactionAcceptedEnvelope","body","map","envelope","data","readTransactionRecordEnvelope","TransactionStatusReaderTag"],"mappings":"AAAA,qEAAqE;AACrE,OAAO,gBAAgB;AAEvB,SACEA,cAAc,QAKT,gBAAgB;AACvB,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AAmEzC,OAAO,MAAMC,4BAA4BF,QAAQG,OAAO,GAGpD;AAAwB;AAkB5B;;;;;CAKC,GACD,OAAO,SAASC,gCACdC,IAAa;IAEb,OAAOJ,OAAOK,GAAG,CACfP,eAAeM,MAAM,wBACrBE,CAAAA,WAAYA,SAASC,IAAI;AAE7B;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,8BACdJ,IAAa;IAEb,OAAOJ,OAAOK,GAAG,CACfP,eAAeM,MAAM,sBACrBE,CAAAA,WAAYA,SAASC,IAAI;AAE7B;AAmBA,OAAO,MAAME,mCAAmCV,QAAQG,OAAO,GAG3D;AAA+B"}
@@ -1,181 +0,0 @@
1
- /**
2
- * Richardson's classification, and adopting the vocabulary is most of the answer
3
- * to "which steps are compensable at all".
4
- *
5
- * - `compensatable` — before the point of no return; a failure downstream
6
- * reverses it.
7
- * - `pivot` — the point of no return. Once it commits, the saga goes forward.
8
- * - `retriable` — after the pivot; no compensation exists, so the only path is
9
- * to retry until it succeeds.
10
- */
11
- export type SagaStepKind = 'compensatable' | 'pivot' | 'retriable';
12
- /** The HTTP verbs a step may be dispatched with. */
13
- export type SagaMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
14
- /**
15
- * One call a step makes, as a template rather than a closure.
16
- *
17
- * `path` may carry `{…}` placeholders resolved by field path against the step's
18
- * recorded outcome — `/api/reservation/{outcome.data.id}`.
19
- *
20
- * ⚠️ **A template rather than a callback, and that is the constraint that
21
- * shaped the whole type.** A callback would have to name the participant's
22
- * types, and one domain package may not import another — which is exactly the
23
- * import that has no legal home and the reason a definition is **data** in the
24
- * first place.
25
- */
26
- export interface SagaCall {
27
- readonly method: SagaMethod;
28
- readonly path: string;
29
- }
30
- /** One step of a flow. */
31
- export interface SagaStep {
32
- /** Unique within the definition; half of the command id `<sagaId>:<stepId>`. */
33
- readonly id: string;
34
- /**
35
- * Which service answers it, as a **configuration key** — never a URI.
36
- *
37
- * A URI in a definition is a deployment fact written into a business
38
- * artifact, and it is what makes a definition untestable and un-relocatable.
39
- * The same lookup yields the crossing token for that participant, so a
40
- * definition carries no secret and never could.
41
- */
42
- readonly participant: string;
43
- readonly command: SagaCall;
44
- /** Required on a `compensatable` step, forbidden on every other kind. */
45
- readonly compensation?: SagaCall;
46
- readonly kind: SagaStepKind;
47
- /**
48
- * Dispatch one call per element of this step's input, rather than one call.
49
- *
50
- * ⚠️ **Cardinality is data, because it has to be.** Checkout reserves once per
51
- * vendor and how many vendors is known only from the cart, so writing that as
52
- * N steps would mean generating a definition per request — at which point it
53
- * is no longer data, and the whole construction collapses back into the class
54
- * that has no legal home.
55
- *
56
- * The consequence carried by {@link SagaStepOutcome}: **the unit of
57
- * compensation is the call, not the step.** Five lines with three holds taken
58
- * and the fourth refused must release exactly three.
59
- */
60
- readonly fanOut?: boolean;
61
- /**
62
- * Fan out over an **earlier step's successful calls** instead of over an
63
- * input the caller supplied.
64
- *
65
- * ⚠️ **Without this a later step cannot address what an earlier one created**,
66
- * and checkout is the case that proves it. `convert-reservation` needs one
67
- * call per hold, addressed by the reservation id — which stock-service mints,
68
- * so the caller cannot know it when it starts the flow. Supplying the ids as
69
- * input is impossible, and generating a definition per request is the thing
70
- * a definition-as-data exists to avoid.
71
- *
72
- * Each element inherits that call's `organizationId`, so a tenant-plane
73
- * participant reaches the same tenant it did the first time, and the `path`
74
- * template resolves against `{outcome.…}` — the same scope a compensation
75
- * gets, for the same reason: the id being addressed is in the response body.
76
- *
77
- * Implies {@link fanOut}. It names a step that must appear **before** this one,
78
- * and `defineSaga` refuses a forward or self reference at module load.
79
- */
80
- readonly fanOutFrom?: string;
81
- }
82
- /** A flow, as the data a generic engine walks. */
83
- export interface SagaDefinition {
84
- readonly name: string;
85
- /**
86
- * What a caller must hold to run this flow, as a `<domain>:<entity>:<action>`
87
- * string.
88
- *
89
- * ⚠️ **On the definition rather than on the route**, so the route that runs a
90
- * flow stays generic. The alternative was one permission for every saga, which
91
- * would make "may run a flow" a single capability regardless of what the flow
92
- * does — and checkout writes an order.
93
- *
94
- * It is a plain string here rather than authz's `Permission`: this package is
95
- * T2, and `@entifix/authz` sits above it at T4. The service that
96
- * mounts the route resolves the string against
97
- * `SERVICE_CROSSING_PERMISSIONS`, which is where the closed list belongs.
98
- */
99
- readonly permission: string;
100
- readonly steps: readonly SagaStep[];
101
- }
102
- /** What one dispatched call returned, kept so its compensation can read it. */
103
- export interface SagaCallOutcome {
104
- /** The fan-out element this call was made for; `0` on a single-call step. */
105
- readonly index: number;
106
- readonly status: number;
107
- readonly body: unknown;
108
- /**
109
- * The organization this call acted for, carried so its compensation acts on
110
- * the same one.
111
- *
112
- * ⚠️ **Not derivable from the outcome, and its absence is silent.** A
113
- * tenant-plane participant resolves its storage handle from
114
- * `x-organization-id`, so a compensation dispatched without it is refused
115
- * `400` — and the saga strands with every hold still in place while the
116
- * engine reports it tried. Measured on the live lab: two holds taken, a third
117
- * line refused, and both releases rejected for a missing header.
118
- */
119
- readonly organizationId?: string;
120
- }
121
- /**
122
- * What one step is given to work with — one element per call on a `fanOut` step,
123
- * exactly one otherwise.
124
- */
125
- export interface SagaStepInput {
126
- /** The body to send. */
127
- readonly body?: unknown;
128
- /** The explicit organization, for a tenant-plane participant. */
129
- readonly organizationId?: string;
130
- }
131
- /**
132
- * The inputs each step needs, keyed by step id, supplied by the caller.
133
- *
134
- * ⚠️ **Here rather than in the engine**, because the durable instance carries
135
- * it: a resumed walk is a different process reading this off the store, so the
136
- * port that persists it may not reach up into the engine to name its type.
137
- */
138
- export type SagaInputs = Readonly<Record<string, readonly SagaStepInput[]>>;
139
- /** Every call one step made, in dispatch order. */
140
- export interface SagaStepOutcome {
141
- readonly stepId: string;
142
- readonly calls: readonly SagaCallOutcome[];
143
- /**
144
- * Why this step stopped, when it did — absent on a step that succeeded.
145
- *
146
- * ⚠️ **Without it a resumed walk cannot tell a finished step from a refused
147
- * one.** `calls` holds what succeeded either way, so the two are
148
- * indistinguishable on the stored document, and the distinction is what
149
- * decides whether the pivot committed. Guessing it either compensates behind
150
- * a capture or walks past a refusal.
151
- */
152
- readonly error?: string;
153
- /**
154
- * Whether this step's calls have already been given back.
155
- *
156
- * ⚠️ **What keeps a resumed unwind from compensating twice.** A second
157
- * `DELETE` of an order already deleted answers `404`, which the dispatcher
158
- * classifies as a refusal, which strands a flow that was in fact reversed.
159
- */
160
- readonly compensated?: boolean;
161
- }
162
- /**
163
- * Validate a definition and return it, or throw.
164
- *
165
- * ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path
166
- * is a fault that ships — the same reasoning that makes an unrenderable action
167
- * cell throw at render. Every definition is therefore constructed through this
168
- * function at module scope, and loaded in a spec: a definition that never loads
169
- * is a definition that never fails.
170
- */
171
- export declare function defineSaga(definition: SagaDefinition): SagaDefinition;
172
- /**
173
- * The command id one call is dispatched under.
174
- *
175
- * `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,
176
- * so the `TransactionInbox` serves saga steps with no second dedup store and
177
- * no second key. A fan-out step appends the element index, because its calls are
178
- * separate side effects that must each be claimed on their own.
179
- */
180
- export declare const sagaCommandId: (sagaId: string, stepId: string, index?: number) => string;
181
- //# sourceMappingURL=saga-definition.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"saga-definition.d.ts","sourceRoot":"","sources":["../../src/contracts/saga-definition.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,MAAM,YAAY,GAAG,eAAe,GAAG,OAAO,GAAG,WAAW,CAAC;AAEnE,oDAAoD;AACpD,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAC;AAErE;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,QAAQ;IACvB,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAED,0BAA0B;AAC1B,MAAM,WAAW,QAAQ;IACvB,gFAAgF;IAChF,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB;;;;;;;OAOG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC;IAC3B,yEAAyE;IACzE,QAAQ,CAAC,YAAY,CAAC,EAAE,QAAQ,CAAC;IACjC,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAC5B;;;;;;;;;;;;OAYG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;;;;;;;;;;;;;;;OAkBG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,kDAAkD;AAClD,MAAM,WAAW,cAAc;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
- /**
2
- * Richardson's classification, and adopting the vocabulary is most of the answer
3
- * to "which steps are compensable at all".
4
- *
5
- * - `compensatable` — before the point of no return; a failure downstream
6
- * reverses it.
7
- * - `pivot` — the point of no return. Once it commits, the saga goes forward.
8
- * - `retriable` — after the pivot; no compensation exists, so the only path is
9
- * to retry until it succeeds.
10
- */ const fail = (definition, detail)=>{
11
- throw new Error(`saga definition '${definition}' is invalid: ${detail}`);
12
- };
13
- /**
14
- * Validate a definition and return it, or throw.
15
- *
16
- * ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path
17
- * is a fault that ships — the same reasoning that makes an unrenderable action
18
- * cell throw at render. Every definition is therefore constructed through this
19
- * function at module scope, and loaded in a spec: a definition that never loads
20
- * is a definition that never fails.
21
- */ export function defineSaga(definition) {
22
- const { name, steps } = definition;
23
- if (steps.length === 0) {
24
- fail(name, 'it declares no steps');
25
- }
26
- const seen = new Set();
27
- for (const step of steps){
28
- if (seen.has(step.id)) {
29
- // The command id is `<sagaId>:<stepId>`, so a duplicate id is two steps
30
- // sharing one idempotency key — the second would be dropped as a
31
- // redelivery of the first and never run at all.
32
- fail(name, `two steps share the id '${step.id}'`);
33
- }
34
- seen.add(step.id);
35
- }
36
- // `fanOutFrom` must name a step that has already run, or the outcomes it fans
37
- // out over do not exist yet. A forward reference would silently produce zero
38
- // calls — a step that looks like it ran and did nothing, which is exactly how
39
- // a conversion gets skipped while a saga reports COMPLETED.
40
- const before = new Set();
41
- for (const step of steps){
42
- if (step.fanOutFrom !== undefined && !before.has(step.fanOutFrom)) {
43
- fail(name, `step '${step.id}' fans out from '${step.fanOutFrom}', which is not a ` + 'step before it');
44
- }
45
- before.add(step.id);
46
- }
47
- const pivots = steps.filter((step)=>step.kind === 'pivot');
48
- if (pivots.length > 1) {
49
- // A flow with two points of no return is a flow that has not been designed
50
- // yet, and the engine says so out loud.
51
- fail(name, `it declares ${String(pivots.length)} pivots (${pivots.map((step)=>step.id).join(', ')}); a flow has at most one point of no return`);
52
- }
53
- // ⚠️ **Zero pivots is legal**, and checkout is the case that forced saying so.
54
- // Payment capture is M4; until it lands every step of checkout reverses. A
55
- // validator demanding exactly one would push the order write into a role it
56
- // would have to be removed from later — a wrong answer that passes
57
- //. A definition with no pivot means the whole saga can be unwound,
58
- // which is a stronger property than a pivot rather than a missing one.
59
- const pivot = pivots[0];
60
- const pivotAt = pivot ? steps.indexOf(pivot) : -1;
61
- const afterPivot = (index)=>pivot !== undefined && index > pivotAt;
62
- for (const [index, step] of steps.entries()){
63
- switch(step.kind){
64
- case 'compensatable':
65
- {
66
- if (afterPivot(index)) {
67
- fail(name, `step '${step.id}' is compensatable but sits after the pivot ` + `'${String(pivot == null ? void 0 : pivot.id)}', where nothing can be reversed`);
68
- }
69
- if (!step.compensation) {
70
- fail(name, `step '${step.id}' is compensatable but declares no compensation`);
71
- }
72
- break;
73
- }
74
- case 'pivot':
75
- case 'retriable':
76
- {
77
- if (step.compensation) {
78
- // Not dead code — a *false assurance*. Such a compensation could
79
- // never run, so writing one says the step is reversible when it is
80
- // not.
81
- fail(name, `step '${step.id}' is ${step.kind} and declares a compensation, ` + 'which could never run');
82
- }
83
- if (step.kind === 'retriable' && !afterPivot(index)) {
84
- fail(name, `step '${step.id}' is retriable but sits before the pivot; a step ` + 'that cannot be reversed must not run while the saga can still ' + 'be unwound');
85
- }
86
- break;
87
- }
88
- }
89
- }
90
- return definition;
91
- }
92
- /**
93
- * The command id one call is dispatched under.
94
- *
95
- * `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,
96
- * so the `TransactionInbox` serves saga steps with no second dedup store and
97
- * no second key. A fan-out step appends the element index, because its calls are
98
- * separate side effects that must each be claimed on their own.
99
- */ export const sagaCommandId = (sagaId, stepId, index)=>index === undefined ? `${sagaId}:${stepId}` : `${sagaId}:${stepId}:${String(index)}`;
100
-
101
- //# sourceMappingURL=saga-definition.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/contracts/saga-definition.ts"],"sourcesContent":["/**\n * Richardson's classification, and adopting the vocabulary is most of the answer\n * to \"which steps are compensable at all\".\n *\n * - `compensatable` — before the point of no return; a failure downstream\n * reverses it.\n * - `pivot` — the point of no return. Once it commits, the saga goes forward.\n * - `retriable` — after the pivot; no compensation exists, so the only path is\n * to retry until it succeeds.\n */\nexport type SagaStepKind = 'compensatable' | 'pivot' | 'retriable';\n\n/** The HTTP verbs a step may be dispatched with. */\nexport type SagaMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * One call a step makes, as a template rather than a closure.\n *\n * `path` may carry `{…}` placeholders resolved by field path against the step's\n * recorded outcome — `/api/reservation/{outcome.data.id}`.\n *\n * ⚠️ **A template rather than a callback, and that is the constraint that\n * shaped the whole type.** A callback would have to name the participant's\n * types, and one domain package may not import another — which is exactly the\n * import that has no legal home and the reason a definition is **data** in the\n * first place.\n */\nexport interface SagaCall {\n readonly method: SagaMethod;\n readonly path: string;\n}\n\n/** One step of a flow. */\nexport interface SagaStep {\n /** Unique within the definition; half of the command id `<sagaId>:<stepId>`. */\n readonly id: string;\n /**\n * Which service answers it, as a **configuration key** — never a URI.\n *\n * A URI in a definition is a deployment fact written into a business\n * artifact, and it is what makes a definition untestable and un-relocatable.\n * The same lookup yields the crossing token for that participant, so a\n * definition carries no secret and never could.\n */\n readonly participant: string;\n readonly command: SagaCall;\n /** Required on a `compensatable` step, forbidden on every other kind. */\n readonly compensation?: SagaCall;\n readonly kind: SagaStepKind;\n /**\n * Dispatch one call per element of this step's input, rather than one call.\n *\n * ⚠️ **Cardinality is data, because it has to be.** Checkout reserves once per\n * vendor and how many vendors is known only from the cart, so writing that as\n * N steps would mean generating a definition per request — at which point it\n * is no longer data, and the whole construction collapses back into the class\n * that has no legal home.\n *\n * The consequence carried by {@link SagaStepOutcome}: **the unit of\n * compensation is the call, not the step.** Five lines with three holds taken\n * and the fourth refused must release exactly three.\n */\n readonly fanOut?: boolean;\n /**\n * Fan out over an **earlier step's successful calls** instead of over an\n * input the caller supplied.\n *\n * ⚠️ **Without this a later step cannot address what an earlier one created**,\n * and checkout is the case that proves it. `convert-reservation` needs one\n * call per hold, addressed by the reservation id — which stock-service mints,\n * so the caller cannot know it when it starts the flow. Supplying the ids as\n * input is impossible, and generating a definition per request is the thing\n * a definition-as-data exists to avoid.\n *\n * Each element inherits that call's `organizationId`, so a tenant-plane\n * participant reaches the same tenant it did the first time, and the `path`\n * template resolves against `{outcome.…}` — the same scope a compensation\n * gets, for the same reason: the id being addressed is in the response body.\n *\n * Implies {@link fanOut}. It names a step that must appear **before** this one,\n * and `defineSaga` refuses a forward or self reference at module load.\n */\n readonly fanOutFrom?: string;\n}\n\n/** A flow, as the data a generic engine walks. */\nexport interface SagaDefinition {\n readonly name: string;\n /**\n * What a caller must hold to run this flow, as a `<domain>:<entity>:<action>`\n * string.\n *\n * ⚠️ **On the definition rather than on the route**, so the route that runs a\n * flow stays generic. The alternative was one permission for every saga, which\n * would make \"may run a flow\" a single capability regardless of what the flow\n * does — and checkout writes an order.\n *\n * It is a plain string here rather than authz's `Permission`: this package is\n * T2, and `@entifix/authz` sits above it at T4. The service that\n * mounts the route resolves the string against\n * `SERVICE_CROSSING_PERMISSIONS`, which is where the closed list belongs.\n */\n readonly permission: string;\n readonly steps: readonly SagaStep[];\n}\n\n/** What one dispatched call returned, kept so its compensation can read it. */\nexport interface SagaCallOutcome {\n /** The fan-out element this call was made for; `0` on a single-call step. */\n readonly index: number;\n readonly status: number;\n readonly body: unknown;\n /**\n * The organization this call acted for, carried so its compensation acts on\n * the same one.\n *\n * ⚠️ **Not derivable from the outcome, and its absence is silent.** A\n * tenant-plane participant resolves its storage handle from\n * `x-organization-id`, so a compensation dispatched without it is refused\n * `400` — and the saga strands with every hold still in place while the\n * engine reports it tried. Measured on the live lab: two holds taken, a third\n * line refused, and both releases rejected for a missing header.\n */\n readonly organizationId?: string;\n}\n\n/**\n * What one step is given to work with — one element per call on a `fanOut` step,\n * exactly one otherwise.\n */\nexport interface SagaStepInput {\n /** The body to send. */\n readonly body?: unknown;\n /** The explicit organization, for a tenant-plane participant. */\n readonly organizationId?: string;\n}\n\n/**\n * The inputs each step needs, keyed by step id, supplied by the caller.\n *\n * ⚠️ **Here rather than in the engine**, because the durable instance carries\n * it: a resumed walk is a different process reading this off the store, so the\n * port that persists it may not reach up into the engine to name its type.\n */\nexport type SagaInputs = Readonly<Record<string, readonly SagaStepInput[]>>;\n\n/** Every call one step made, in dispatch order. */\nexport interface SagaStepOutcome {\n readonly stepId: string;\n readonly calls: readonly SagaCallOutcome[];\n /**\n * Why this step stopped, when it did — absent on a step that succeeded.\n *\n * ⚠️ **Without it a resumed walk cannot tell a finished step from a refused\n * one.** `calls` holds what succeeded either way, so the two are\n * indistinguishable on the stored document, and the distinction is what\n * decides whether the pivot committed. Guessing it either compensates behind\n * a capture or walks past a refusal.\n */\n readonly error?: string;\n /**\n * Whether this step's calls have already been given back.\n *\n * ⚠️ **What keeps a resumed unwind from compensating twice.** A second\n * `DELETE` of an order already deleted answers `404`, which the dispatcher\n * classifies as a refusal, which strands a flow that was in fact reversed.\n */\n readonly compensated?: boolean;\n}\n\nconst fail = (definition: string, detail: string): never => {\n throw new Error(`saga definition '${definition}' is invalid: ${detail}`);\n};\n\n/**\n * Validate a definition and return it, or throw.\n *\n * ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path\n * is a fault that ships — the same reasoning that makes an unrenderable action\n * cell throw at render. Every definition is therefore constructed through this\n * function at module scope, and loaded in a spec: a definition that never loads\n * is a definition that never fails.\n */\nexport function defineSaga(definition: SagaDefinition): SagaDefinition {\n const { name, steps } = definition;\n\n if (steps.length === 0) {\n fail(name, 'it declares no steps');\n }\n\n const seen = new Set<string>();\n for (const step of steps) {\n if (seen.has(step.id)) {\n // The command id is `<sagaId>:<stepId>`, so a duplicate id is two steps\n // sharing one idempotency key — the second would be dropped as a\n // redelivery of the first and never run at all.\n fail(name, `two steps share the id '${step.id}'`);\n }\n seen.add(step.id);\n }\n\n // `fanOutFrom` must name a step that has already run, or the outcomes it fans\n // out over do not exist yet. A forward reference would silently produce zero\n // calls — a step that looks like it ran and did nothing, which is exactly how\n // a conversion gets skipped while a saga reports COMPLETED.\n const before = new Set<string>();\n for (const step of steps) {\n if (step.fanOutFrom !== undefined && !before.has(step.fanOutFrom)) {\n fail(\n name,\n `step '${step.id}' fans out from '${step.fanOutFrom}', which is not a ` +\n 'step before it',\n );\n }\n before.add(step.id);\n }\n\n const pivots = steps.filter(step => step.kind === 'pivot');\n if (pivots.length > 1) {\n // A flow with two points of no return is a flow that has not been designed\n // yet, and the engine says so out loud.\n fail(\n name,\n `it declares ${String(pivots.length)} pivots (${pivots\n .map(step => step.id)\n .join(', ')}); a flow has at most one point of no return`,\n );\n }\n\n // ⚠️ **Zero pivots is legal**, and checkout is the case that forced saying so.\n // Payment capture is M4; until it lands every step of checkout reverses. A\n // validator demanding exactly one would push the order write into a role it\n // would have to be removed from later — a wrong answer that passes\n //. A definition with no pivot means the whole saga can be unwound,\n // which is a stronger property than a pivot rather than a missing one.\n const pivot = pivots[0];\n const pivotAt = pivot ? steps.indexOf(pivot) : -1;\n const afterPivot = (index: number) => pivot !== undefined && index > pivotAt;\n\n for (const [index, step] of steps.entries()) {\n switch (step.kind) {\n case 'compensatable': {\n if (afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is compensatable but sits after the pivot ` +\n `'${String(pivot?.id)}', where nothing can be reversed`,\n );\n }\n if (!step.compensation) {\n fail(\n name,\n `step '${step.id}' is compensatable but declares no compensation`,\n );\n }\n break;\n }\n case 'pivot':\n case 'retriable': {\n if (step.compensation) {\n // Not dead code — a *false assurance*. Such a compensation could\n // never run, so writing one says the step is reversible when it is\n // not.\n fail(\n name,\n `step '${step.id}' is ${step.kind} and declares a compensation, ` +\n 'which could never run',\n );\n }\n if (step.kind === 'retriable' && !afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is retriable but sits before the pivot; a step ` +\n 'that cannot be reversed must not run while the saga can still ' +\n 'be unwound',\n );\n }\n break;\n }\n }\n }\n\n return definition;\n}\n\n/**\n * The command id one call is dispatched under.\n *\n * `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,\n * so the `TransactionInbox` serves saga steps with no second dedup store and\n * no second key. A fan-out step appends the element index, because its calls are\n * separate side effects that must each be claimed on their own.\n */\nexport const sagaCommandId = (\n sagaId: string,\n stepId: string,\n index?: number,\n): string =>\n index === undefined\n ? `${sagaId}:${stepId}`\n : `${sagaId}:${stepId}:${String(index)}`;\n"],"names":["fail","definition","detail","Error","defineSaga","name","steps","length","seen","Set","step","has","id","add","before","fanOutFrom","undefined","pivots","filter","kind","String","map","join","pivot","pivotAt","indexOf","afterPivot","index","entries","compensation","sagaCommandId","sagaId","stepId"],"mappings":"AAAA;;;;;;;;;CASC,GAiKD,MAAMA,OAAO,CAACC,YAAoBC;IAChC,MAAM,IAAIC,MAAM,CAAC,iBAAiB,EAAEF,WAAW,cAAc,EAAEC,QAAQ;AACzE;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASE,WAAWH,UAA0B;IACnD,MAAM,EAAEI,IAAI,EAAEC,KAAK,EAAE,GAAGL;IAExB,IAAIK,MAAMC,MAAM,KAAK,GAAG;QACtBP,KAAKK,MAAM;IACb;IAEA,MAAMG,OAAO,IAAIC;IACjB,KAAK,MAAMC,QAAQJ,MAAO;QACxB,IAAIE,KAAKG,GAAG,CAACD,KAAKE,EAAE,GAAG;YACrB,wEAAwE;YACxE,iEAAiE;YACjE,gDAAgD;YAChDZ,KAAKK,MAAM,CAAC,wBAAwB,EAAEK,KAAKE,EAAE,CAAC,CAAC,CAAC;QAClD;QACAJ,KAAKK,GAAG,CAACH,KAAKE,EAAE;IAClB;IAEA,8EAA8E;IAC9E,6EAA6E;IAC7E,8EAA8E;IAC9E,4DAA4D;IAC5D,MAAME,SAAS,IAAIL;IACnB,KAAK,MAAMC,QAAQJ,MAAO;QACxB,IAAII,KAAKK,UAAU,KAAKC,aAAa,CAACF,OAAOH,GAAG,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,YAAY,EAAE;wBACrB,iEAAiE;wBACjE,mEAAmE;wBACnE,OAAO;wBACP7B,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,KAAK,EAAEF,KAAKS,IAAI,CAAC,8BAA8B,CAAC,GAC/D;oBAEN;oBACA,IAAIT,KAAKS,IAAI,KAAK,eAAe,CAACO,WAAWC,QAAQ;wBACnD3B,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,iDAAiD,CAAC,GACjE,mEACA;oBAEN;oBACA;gBACF;QACF;IACF;IAEA,OAAOX;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,MAAM6B,gBAAgB,CAC3BC,QACAC,QACAL,QAEAA,UAAUX,YACN,GAAGe,OAAO,CAAC,EAAEC,QAAQ,GACrB,GAAGD,OAAO,CAAC,EAAEC,OAAO,CAAC,EAAEZ,OAAOO,QAAQ,CAAC"}
@@ -1,35 +0,0 @@
1
- import type { Unavailable } from '@entifix/core';
2
- import { Effect, Layer } from 'effect';
3
- import type { SagaCall } from '../contracts/saga-definition.js';
4
- import { type SagaDispatch, type SagaDispatcher, SagaDispatcherTag, type SagaResponse } from '../ports/saga-dispatcher.js';
5
- /** What a local participant is handed: the dispatch, minus whom it is for. */
6
- export type LocalSagaRequest = Omit<SagaDispatch, 'participant'>;
7
- /**
8
- * One participant answered in-process.
9
- *
10
- * The same contract an HTTP participant keeps: a business refusal is a response
11
- * with `ok: false` — the engine compensates on it — and only a failure to reach
12
- * the participant at all is an {@link Unavailable}. Key the side effect on
13
- * `commandId` (an inbox), because a resumed flow dispatches the same command
14
- * again.
15
- */
16
- export type LocalSagaParticipant = (request: LocalSagaRequest) => Effect.Effect<SagaResponse, Unavailable>;
17
- /**
18
- * A {@link SagaDispatcher} that calls participants in this process.
19
- *
20
- * The saga engine never does HTTP itself: a step is a `{ method, path }` handed
21
- * to the dispatcher port. So a flow whose every step belongs to one service needs
22
- * no transport, no crossing token and no second process — only this, with each
23
- * participant name mapped to the Effect that performs its commands. A handler
24
- * that serves several commands routes on `request.call`.
25
- *
26
- * ⚠️ A participant the definition names and this map lacks is a **defect**, not
27
- * a failed step: it is a wiring mistake the flow cannot recover from, and
28
- * reporting it as a refusal would compensate a flow for a bug.
29
- */
30
- export declare const makeLocalSagaDispatcher: (participants: Readonly<Record<string, LocalSagaParticipant>>) => SagaDispatcher;
31
- /** Provides {@link SagaDispatcherTag} from local participants. */
32
- export declare const LocalSagaDispatcherLayer: (participants: Readonly<Record<string, LocalSagaParticipant>>) => Layer.Layer<SagaDispatcherTag>;
33
- /** True when a request is the given command, for a participant routing on it. */
34
- export declare const isSagaCall: (request: LocalSagaRequest, call: SagaCall) => boolean;
35
- //# sourceMappingURL=local-saga-dispatcher.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"local-saga-dispatcher.d.ts","sourceRoot":"","sources":["../../src/engine/local-saga-dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAEvC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAChE,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,iBAAiB,EACjB,KAAK,YAAY,EAClB,MAAM,6BAA6B,CAAC;AAErC,8EAA8E;AAC9E,MAAM,MAAM,gBAAgB,GAAG,IAAI,CAAC,YAAY,EAAE,aAAa,CAAC,CAAC;AAEjE;;;;;;;;GAQG;AACH,MAAM,MAAM,oBAAoB,GAAG,CACjC,OAAO,EAAE,gBAAgB,KACtB,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,WAAW,CAAC,CAAC;AAE9C;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,uBAAuB,GAClC,cAAc,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAC,KAC3D,cAWD,CAAC;AAEH,kEAAkE;AAClE,eAAO,MAAM,wBAAwB,GACnC,cAAc,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAC,KAC3D,KAAK,CAAC,KAAK,CAAC,iBAAiB,CACyC,CAAC;AAE1E,iFAAiF;AACjF,eAAO,MAAM,UAAU,GACrB,SAAS,gBAAgB,EACzB,MAAM,QAAQ,KACb,OACqE,CAAC"}
@@ -1,28 +0,0 @@
1
- import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
2
- import { Effect, Layer } from 'effect';
3
- import { SagaDispatcherTag } from '../ports/saga-dispatcher.js';
4
- /**
5
- * A {@link SagaDispatcher} that calls participants in this process.
6
- *
7
- * The saga engine never does HTTP itself: a step is a `{ method, path }` handed
8
- * to the dispatcher port. So a flow whose every step belongs to one service needs
9
- * no transport, no crossing token and no second process — only this, with each
10
- * participant name mapped to the Effect that performs its commands. A handler
11
- * that serves several commands routes on `request.call`.
12
- *
13
- * ⚠️ A participant the definition names and this map lacks is a **defect**, not
14
- * a failed step: it is a wiring mistake the flow cannot recover from, and
15
- * reporting it as a refusal would compensate a flow for a bug.
16
- */ export const makeLocalSagaDispatcher = (participants)=>({
17
- dispatch: (_0)=>{
18
- let { participant } = _0, request = _object_without_properties_loose(_0, [
19
- "participant"
20
- ]);
21
- const handle = participants[participant];
22
- return handle === undefined ? Effect.die(new Error(`The saga dispatched to participant "${participant}", which this service registered no local handler for.`)) : handle(request);
23
- }
24
- });
25
- /** Provides {@link SagaDispatcherTag} from local participants. */ export const LocalSagaDispatcherLayer = (participants)=>Layer.succeed(SagaDispatcherTag, makeLocalSagaDispatcher(participants));
26
- /** True when a request is the given command, for a participant routing on it. */ export const isSagaCall = (request, call)=>request.call.method === call.method && request.call.path === call.path;
27
-
28
- //# sourceMappingURL=local-saga-dispatcher.js.map