@entifix/transactions 0.10.2 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/contracts/command.d.ts +1 -0
  2. package/dist/contracts/command.d.ts.map +1 -1
  3. package/dist/contracts/command.js +7 -3
  4. package/dist/contracts/command.js.map +1 -1
  5. package/dist/contracts/event.d.ts +5 -4
  6. package/dist/contracts/event.d.ts.map +1 -1
  7. package/dist/contracts/event.js +14 -1
  8. package/dist/contracts/event.js.map +1 -1
  9. package/dist/contracts/flow-capability.d.ts +22 -0
  10. package/dist/contracts/flow-capability.d.ts.map +1 -0
  11. package/dist/contracts/flow-capability.js +26 -0
  12. package/dist/contracts/flow-capability.js.map +1 -0
  13. package/dist/contracts/flow-messages.d.ts +52 -0
  14. package/dist/contracts/flow-messages.d.ts.map +1 -0
  15. package/dist/contracts/flow-messages.js +65 -0
  16. package/dist/contracts/flow-messages.js.map +1 -0
  17. package/dist/contracts/inbox.d.ts +19 -2
  18. package/dist/contracts/inbox.d.ts.map +1 -1
  19. package/dist/contracts/inbox.js +16 -1
  20. package/dist/contracts/inbox.js.map +1 -1
  21. package/dist/contracts/messages.d.ts +37 -0
  22. package/dist/contracts/messages.d.ts.map +1 -0
  23. package/dist/contracts/messages.js +68 -0
  24. package/dist/contracts/messages.js.map +1 -0
  25. package/dist/contracts/outbox.d.ts +50 -12
  26. package/dist/contracts/outbox.d.ts.map +1 -1
  27. package/dist/contracts/outbox.js +18 -1
  28. package/dist/contracts/outbox.js.map +1 -1
  29. package/dist/contracts/record.d.ts +7 -8
  30. package/dist/contracts/record.d.ts.map +1 -1
  31. package/dist/contracts/record.js +8 -8
  32. package/dist/contracts/record.js.map +1 -1
  33. package/dist/contracts/unit-of-work.d.ts +3 -2
  34. package/dist/contracts/unit-of-work.d.ts.map +1 -1
  35. package/dist/contracts/unit-of-work.js.map +1 -1
  36. package/dist/engine/in-memory-bulkhead.d.ts +20 -0
  37. package/dist/engine/in-memory-bulkhead.d.ts.map +1 -0
  38. package/dist/engine/in-memory-bulkhead.js +38 -0
  39. package/dist/engine/in-memory-bulkhead.js.map +1 -0
  40. package/dist/engine/in-memory-circuit-breaker.d.ts +28 -0
  41. package/dist/engine/in-memory-circuit-breaker.d.ts.map +1 -0
  42. package/dist/engine/in-memory-circuit-breaker.js +151 -0
  43. package/dist/engine/in-memory-circuit-breaker.js.map +1 -0
  44. package/dist/engine/index.d.ts +4 -0
  45. package/dist/engine/index.d.ts.map +1 -1
  46. package/dist/engine/index.js +4 -0
  47. package/dist/engine/index.js.map +1 -1
  48. package/dist/engine/outbox-metrics.d.ts +47 -0
  49. package/dist/engine/outbox-metrics.d.ts.map +1 -0
  50. package/dist/engine/outbox-metrics.js +68 -0
  51. package/dist/engine/outbox-metrics.js.map +1 -0
  52. package/dist/engine/outbox-relay.d.ts +102 -0
  53. package/dist/engine/outbox-relay.d.ts.map +1 -0
  54. package/dist/engine/outbox-relay.js +111 -0
  55. package/dist/engine/outbox-relay.js.map +1 -0
  56. package/dist/engine/run-transaction.d.ts +4 -4
  57. package/dist/engine/run-transaction.d.ts.map +1 -1
  58. package/dist/engine/run-transaction.js +4 -4
  59. package/dist/engine/run-transaction.js.map +1 -1
  60. package/dist/index.d.ts +7 -0
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +7 -0
  63. package/dist/index.js.map +1 -1
  64. package/dist/ports/bulkhead.d.ts +28 -0
  65. package/dist/ports/bulkhead.d.ts.map +1 -0
  66. package/dist/ports/bulkhead.js +18 -0
  67. package/dist/ports/bulkhead.js.map +1 -0
  68. package/dist/ports/circuit-breaker.d.ts +62 -0
  69. package/dist/ports/circuit-breaker.d.ts.map +1 -0
  70. package/dist/ports/circuit-breaker.js +42 -0
  71. package/dist/ports/circuit-breaker.js.map +1 -0
  72. package/dist/ports/event-bus.d.ts +10 -0
  73. package/dist/ports/event-bus.d.ts.map +1 -1
  74. package/dist/ports/event-bus.js.map +1 -1
  75. package/dist/ports/flow-engine.d.ts +60 -0
  76. package/dist/ports/flow-engine.d.ts.map +1 -0
  77. package/dist/ports/flow-engine.js +19 -0
  78. package/dist/ports/flow-engine.js.map +1 -0
  79. package/dist/ports/participant-client.d.ts +32 -0
  80. package/dist/ports/participant-client.d.ts.map +1 -0
  81. package/dist/ports/participant-client.js +5 -0
  82. package/dist/ports/participant-client.js.map +1 -0
  83. package/dist/reactions/on.d.ts.map +1 -1
  84. package/dist/reactions/on.js +2 -1
  85. package/dist/reactions/on.js.map +1 -1
  86. package/package.json +3 -3
@@ -1,7 +1,20 @@
1
- import type { DomainEvent, StoreFailure } from '@entifix/core';
1
+ import type { AggregateRef, DomainEvent, StoreFailure } from '@entifix/core';
2
2
  import { Context, type Effect } from 'effect';
3
3
  /**
4
- * A transaction event recorded durably *before* it reaches the broker.
4
+ * An event an outbox accepts: one that says which aggregate it is about and
5
+ * which version of it ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)).
6
+ * The relay keeps order within an aggregate and nowhere else, and a consumer
7
+ * discards a version older than one it applied — neither is possible for an
8
+ * event that names neither.
9
+ */
10
+ export type OutboxEvent<TData = unknown> = DomainEvent<TData> & {
11
+ readonly aggregate: AggregateRef;
12
+ readonly version: number;
13
+ };
14
+ /** The key an outbox orders and blocks by: `<type>/<id>`. */
15
+ export declare const aggregateKey: (aggregate: AggregateRef) => string;
16
+ /**
17
+ * A domain event recorded durably *before* it reaches the broker.
5
18
  *
6
19
  * The point of the outbox is that a state change and the event announcing it
7
20
  * become one fact. `execute` used to write Mongo and then call `bus.publish`
@@ -21,14 +34,17 @@ export interface OutboxEntry {
21
34
  * recognised as a retry before any lock is taken or work forked.
22
35
  */
23
36
  eventId: string;
37
+ /** Denormalized out of `event` for the per-aggregate index. */
38
+ aggregate: AggregateRef;
39
+ version: number;
24
40
  event: DomainEvent;
25
41
  sent: boolean;
26
42
  /**
27
43
  * Publish attempts already spent on this entry.
28
44
  *
29
- * The relay drains in order and stops at the first failure, which is what
30
- * keeps `accepted` ahead of a terminal event — and is also why an entry that
31
- * can *never* publish used to block everything behind it forever. Counting
45
+ * A failure holds back the later versions of this entry's aggregate, which
46
+ * is what keeps `accepted` ahead of a terminal event — and is also why an
47
+ * entry that can *never* publish would hold its aggregate forever. Counting
32
48
  * the attempts is what turns "retrying" into a state with an end.
33
49
  */
34
50
  attempts: number;
@@ -43,11 +59,15 @@ export interface OutboxEntry {
43
59
  * stuck transaction nobody is told about is the same as a lost one.
44
60
  */
45
61
  quarantined: boolean;
46
- /** ISO-8601, and the drain order: entries publish oldest-first. */
62
+ /**
63
+ * ISO-8601. Entries are read oldest-first, and published in that order
64
+ * **within each aggregate**: a failing head holds back only its own
65
+ * aggregate's later versions.
66
+ */
47
67
  createdAt: string;
48
68
  }
49
69
  /**
50
- * Whether {@link TransactionOutbox.enqueue} actually wrote.
70
+ * Whether {@link Outbox.enqueue} actually wrote.
51
71
  *
52
72
  * `duplicate` is not a failure — it is how a *retry* is recognised. The
53
73
  * transaction id is the client's idempotency key, so a repeated
@@ -58,7 +78,7 @@ export interface OutboxEntry {
58
78
  */
59
79
  export type OutboxEnqueueResult = 'enqueued' | 'duplicate';
60
80
  /**
61
- * An aggregate view of one outbox, for {@link TransactionOutbox.stats}.
81
+ * An aggregate view of one outbox, for {@link Outbox.stats}.
62
82
  *
63
83
  * Counts and one timestamp — **no ids and no payloads**. That is what makes it
64
84
  * safe where a listing is not: an outbox holds event payloads, and once
@@ -94,9 +114,9 @@ export interface OutboxStats {
94
114
  * handle is opaque and whose `emit` records the event inside the same
95
115
  * transaction (ADR 0009). `enqueue` is for an event with no write to join.
96
116
  */
97
- export interface TransactionOutbox {
117
+ export interface Outbox {
98
118
  /** Record an event durably. Idempotent per `event.id`. */
99
- enqueue(event: DomainEvent): Effect.Effect<OutboxEnqueueResult, StoreFailure>;
119
+ enqueue(event: OutboxEvent): Effect.Effect<OutboxEnqueueResult, StoreFailure>;
100
120
  /**
101
121
  * Unsent, un-quarantined entries, oldest first — the relay's input.
102
122
  *
@@ -129,8 +149,26 @@ export interface TransactionOutbox {
129
149
  */
130
150
  stats(): Effect.Effect<OutboxStats, StoreFailure>;
131
151
  }
132
- declare const TransactionOutboxTag_base: Context.ServiceClass<TransactionOutboxTag, "TransactionOutboxTag", TransactionOutbox>;
133
- export declare class TransactionOutboxTag extends TransactionOutboxTag_base {
152
+ declare const OutboxTag_base: Context.ServiceClass<OutboxTag, "@entifix/transactions/Outbox", Outbox>;
153
+ export declare class OutboxTag extends OutboxTag_base {
154
+ }
155
+ declare const OutboxMaxAttempts_base: Context.ServiceClass<OutboxMaxAttempts, "OutboxMaxAttempts", number>;
156
+ /**
157
+ * Publish attempts an outbox entry gets before it is quarantined, from
158
+ * config-service — the dial every store's drain reads, so it sits with the
159
+ * outbox port rather than with one engine.
160
+ *
161
+ * Configuration rather than a constant because it is a genuine operational
162
+ * tunable: raising it while a flaky broker settles is a config edit, and the
163
+ * next sweep reads the new value. That is the opposite of a subscription's
164
+ * `maxAttempts`, which becomes an immutable queue argument and therefore stays
165
+ * a literal beside its declaration.
166
+ *
167
+ * ⚠️ **Read it with `getNumber`, never a cast.** A value of `'five'` casts to
168
+ * `NaN`, every `attempts >= maxAttempts` comparison goes false, and nothing is
169
+ * ever quarantined — a relay that looks healthy while its head never moves.
170
+ */
171
+ export declare class OutboxMaxAttempts extends OutboxMaxAttempts_base {
134
172
  }
135
173
  export {};
136
174
  //# sourceMappingURL=outbox.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"outbox.d.ts","sourceRoot":"","sources":["../../src/contracts/outbox.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC/D,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;;;;;;;GAUG;AACH,MAAM,WAAW,WAAW;IAC1B;;;;;;;OAOG;IACH,OAAO,EAAE,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MAAM,WAAW,MAAM;IACrB,0DAA0D;IAC1D,OAAO,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC,mBAAmB,EAAE,YAAY,CAAC,CAAC;IAC9E;;;;;OAKG;IACH,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,WAAW,EAAE,EAAE,YAAY,CAAC,CAAC;IAC5E;;;;OAIG;IACH,QAAQ,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;IAChE;;;;;;;OAOG;IACH,aAAa,CACX,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,OAAO,GAClB,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;IACrC;;;;;;;OAOG;IACH,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;CACnD;;AAED,qBAAa,SAAU,SAAQ,cAE9B;CAAG;;AAEJ;;;;;;;;;;;;;;GAcG;AACH,qBAAa,iBAAkB,SAAQ,sBAGf;CAAG"}
@@ -1,5 +1,22 @@
1
1
  import { Context } from 'effect';
2
- export class TransactionOutboxTag extends Context.Service()('TransactionOutboxTag') {
2
+ /** The key an outbox orders and blocks by: `<type>/<id>`. */ export const aggregateKey = (aggregate)=>`${aggregate.type}/${aggregate.id}`;
3
+ export class OutboxTag extends Context.Service()('@entifix/transactions/Outbox') {
4
+ }
5
+ /**
6
+ * Publish attempts an outbox entry gets before it is quarantined, from
7
+ * config-service — the dial every store's drain reads, so it sits with the
8
+ * outbox port rather than with one engine.
9
+ *
10
+ * Configuration rather than a constant because it is a genuine operational
11
+ * tunable: raising it while a flaky broker settles is a config edit, and the
12
+ * next sweep reads the new value. That is the opposite of a subscription's
13
+ * `maxAttempts`, which becomes an immutable queue argument and therefore stays
14
+ * a literal beside its declaration.
15
+ *
16
+ * ⚠️ **Read it with `getNumber`, never a cast.** A value of `'five'` casts to
17
+ * `NaN`, every `attempts >= maxAttempts` comparison goes false, and nothing is
18
+ * ever quarantined — a relay that looks healthy while its head never moves.
19
+ */ export class OutboxMaxAttempts extends Context.Service()('OutboxMaxAttempts') {
3
20
  }
4
21
 
5
22
  //# sourceMappingURL=outbox.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/outbox.ts"],"sourcesContent":["import type { DomainEvent, StoreFailure } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * A transaction event recorded durably *before* it reaches the broker.\n *\n * The point of the outbox is that a state change and the event announcing it\n * become one fact. `execute` used to write Mongo and then call `bus.publish`\n * separately: with the broker down between the two, the write happened and the\n * event never did, so the saga record sat `PENDING` until the sweep mislabelled\n * a successful transaction `STALE`. An entry written in the same transaction as\n * the state change cannot be lost that way, and a relay carries it to the bus\n * afterwards.\n */\nexport interface OutboxEntry {\n /**\n * The message's own id, denormalized out of `event` so the unique index sits\n * on a plain top-level field rather than a nested path.\n *\n * This **is** the idempotency claim: for a transaction step it is\n * `<transactionId>:<step>`, so a replayed command collides here and is\n * recognised as a retry before any lock is taken or work forked.\n */\n eventId: string;\n event: DomainEvent;\n sent: boolean;\n /**\n * Publish attempts already spent on this entry.\n *\n * The relay drains in order and stops at the first failure, which is what\n * keeps `accepted` ahead of a terminal event — and is also why an entry that\n * can *never* publish used to block everything behind it forever. Counting\n * the attempts is what turns \"retrying\" into a state with an end.\n */\n attempts: number;\n /**\n * Why the last attempt failed. Absent until one has, so its presence alone\n * says this entry has been tried.\n */\n lastError?: string;\n /**\n * Set once the attempts are spent. A quarantined entry is **skipped** rather\n * than retried, so the head of the line moves; nothing deletes it, because a\n * stuck transaction nobody is told about is the same as a lost one.\n */\n quarantined: boolean;\n /** ISO-8601, and the drain order: entries publish oldest-first. */\n createdAt: string;\n}\n\n/**\n * Whether {@link TransactionOutbox.enqueue} actually wrote.\n *\n * `duplicate` is not a failure — it is how a *retry* is recognised. The\n * transaction id is the client's idempotency key, so a repeated\n * command must return the first one's answer rather than execute twice. The\n * adapter owns the detection because the mechanism is storage-specific (a Mongo\n * `E11000` against the unique index on `eventId`), and translating it here keeps\n * driver error codes out of route handlers.\n */\nexport type OutboxEnqueueResult = 'enqueued' | 'duplicate';\n\n/**\n * An aggregate view of one outbox, for {@link TransactionOutbox.stats}.\n *\n * Counts and one timestamp — **no ids and no payloads**. That is what makes it\n * safe where a listing is not: an outbox holds event payloads, and once\n * `catalog.published` carries a whole offering an unfiltered read of one is a\n * tenant-data surface.\n */\nexport interface OutboxStats {\n /** Unsent, un-quarantined entries — the same set {@link pending} drains. */\n pending: number;\n /**\n * `createdAt` of the oldest such entry, absent when there are none.\n *\n * The age derived from this is the metric that makes a stuck relay visible.\n * An entry that can never publish no longer blocks the ones behind it —\n * quarantine gave the relay a ceiling — but a quarantine is reported only as a log line,\n * so *how far behind* the head has fallen is otherwise unanswerable.\n */\n oldestPendingAt?: string;\n /** Entries past the ceiling, which {@link pending} skips and nothing deletes. */\n quarantined: number;\n}\n\n/**\n * The durable hand-off between a transactional write and the event bus.\n *\n * Deliberately **not** a publisher: it never touches the broker. `enqueue` is\n * the only write, and the relay composes `pending`/`markSent` with an\n * {@link EventBus} — which is what keeps the engine framework-free and lets the\n * relay be tested without either a database or a broker.\n *\n * There is no `enqueueWithin(session)` here on purpose: a driver session in\n * this port would drag a datastore into a framework-free contract. A write that\n * must be atomic with its event runs in a {@link UnitOfWork} instead, whose\n * handle is opaque and whose `emit` records the event inside the same\n * transaction (ADR 0009). `enqueue` is for an event with no write to join.\n */\nexport interface TransactionOutbox {\n /** Record an event durably. Idempotent per `event.id`. */\n enqueue(event: DomainEvent): Effect.Effect<OutboxEnqueueResult, StoreFailure>;\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(limit: number): Effect.Effect<readonly OutboxEntry[], StoreFailure>;\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, StoreFailure>;\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, StoreFailure>;\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, StoreFailure>;\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;AA2I9C,OAAO,MAAMC,6BAA6BD,QAAQE,OAAO,GAGrD;AAAyB"}
1
+ {"version":3,"sources":["../../src/contracts/outbox.ts"],"sourcesContent":["import type { AggregateRef, DomainEvent, StoreFailure } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * An event an outbox accepts: one that says which aggregate it is about and\n * which version of it ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)).\n * The relay keeps order within an aggregate and nowhere else, and a consumer\n * discards a version older than one it applied — neither is possible for an\n * event that names neither.\n */\nexport type OutboxEvent<TData = unknown> = DomainEvent<TData> & {\n readonly aggregate: AggregateRef;\n readonly version: number;\n};\n\n/** The key an outbox orders and blocks by: `<type>/<id>`. */\nexport const aggregateKey = (aggregate: AggregateRef): string =>\n `${aggregate.type}/${aggregate.id}`;\n\n/**\n * A domain 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 /** Denormalized out of `event` for the per-aggregate index. */\n aggregate: AggregateRef;\n version: number;\n event: DomainEvent;\n sent: boolean;\n /**\n * Publish attempts already spent on this entry.\n *\n * A failure holds back the later versions of this entry's aggregate, which\n * is what keeps `accepted` ahead of a terminal event — and is also why an\n * entry that can *never* publish would hold its aggregate forever. Counting\n * the attempts is what turns \"retrying\" into a state with an end.\n */\n attempts: number;\n /**\n * Why the last attempt failed. Absent until one has, so its presence alone\n * says this entry has been tried.\n */\n lastError?: string;\n /**\n * Set once the attempts are spent. A quarantined entry is **skipped** rather\n * than retried, so the head of the line moves; nothing deletes it, because a\n * stuck transaction nobody is told about is the same as a lost one.\n */\n quarantined: boolean;\n /**\n * ISO-8601. Entries are read oldest-first, and published in that order\n * **within each aggregate**: a failing head holds back only its own\n * aggregate's later versions.\n */\n createdAt: string;\n}\n\n/**\n * Whether {@link Outbox.enqueue} actually wrote.\n *\n * `duplicate` is not a failure — it is how a *retry* is recognised. The\n * transaction id is the client's idempotency key, so a repeated\n * command must return the first one's answer rather than execute twice. The\n * adapter owns the detection because the mechanism is storage-specific (a Mongo\n * `E11000` against the unique index on `eventId`), and translating it here keeps\n * driver error codes out of route handlers.\n */\nexport type OutboxEnqueueResult = 'enqueued' | 'duplicate';\n\n/**\n * An aggregate view of one outbox, for {@link Outbox.stats}.\n *\n * Counts and one timestamp — **no ids and no payloads**. That is what makes it\n * safe where a listing is not: an outbox holds event payloads, and once\n * `catalog.published` carries a whole offering an unfiltered read of one is a\n * tenant-data surface.\n */\nexport interface OutboxStats {\n /** Unsent, un-quarantined entries — the same set {@link pending} drains. */\n pending: number;\n /**\n * `createdAt` of the oldest such entry, absent when there are none.\n *\n * The age derived from this is the metric that makes a stuck relay visible.\n * An entry that can never publish no longer blocks the ones behind it —\n * quarantine gave the relay a ceiling — but a quarantine is reported only as a log line,\n * so *how far behind* the head has fallen is otherwise unanswerable.\n */\n oldestPendingAt?: string;\n /** Entries past the ceiling, which {@link pending} skips and nothing deletes. */\n quarantined: number;\n}\n\n/**\n * The durable hand-off between a transactional write and the event bus.\n *\n * Deliberately **not** a publisher: it never touches the broker. `enqueue` is\n * the only write, and the relay composes `pending`/`markSent` with an\n * {@link EventBus} — which is what keeps the engine framework-free and lets the\n * relay be tested without either a database or a broker.\n *\n * There is no `enqueueWithin(session)` here on purpose: a driver session in\n * this port would drag a datastore into a framework-free contract. A write that\n * must be atomic with its event runs in a {@link UnitOfWork} instead, whose\n * handle is opaque and whose `emit` records the event inside the same\n * transaction (ADR 0009). `enqueue` is for an event with no write to join.\n */\nexport interface Outbox {\n /** Record an event durably. Idempotent per `event.id`. */\n enqueue(event: OutboxEvent): Effect.Effect<OutboxEnqueueResult, StoreFailure>;\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(limit: number): Effect.Effect<readonly OutboxEntry[], StoreFailure>;\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, StoreFailure>;\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, StoreFailure>;\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, StoreFailure>;\n}\n\nexport class OutboxTag extends Context.Service<OutboxTag, Outbox>()(\n '@entifix/transactions/Outbox',\n) {}\n\n/**\n * Publish attempts an outbox entry gets before it is quarantined, from\n * config-service — the dial every store's drain reads, so it sits with the\n * outbox port rather than with one engine.\n *\n * Configuration rather than a constant because it is a genuine operational\n * tunable: raising it while a flaky broker settles is a config edit, and the\n * next sweep reads the new value. That is the opposite of a subscription's\n * `maxAttempts`, which becomes an immutable queue argument and therefore stays\n * a literal beside its declaration.\n *\n * ⚠️ **Read it with `getNumber`, never a cast.** A value of `'five'` casts to\n * `NaN`, every `attempts >= maxAttempts` comparison goes false, and nothing is\n * ever quarantined — a relay that looks healthy while its head never moves.\n */\nexport class OutboxMaxAttempts extends Context.Service<\n OutboxMaxAttempts,\n number\n>()('OutboxMaxAttempts') {}\n"],"names":["Context","aggregateKey","aggregate","type","id","OutboxTag","Service","OutboxMaxAttempts"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAc9C,2DAA2D,GAC3D,OAAO,MAAMC,eAAe,CAACC,YAC3B,GAAGA,UAAUC,IAAI,CAAC,CAAC,EAAED,UAAUE,EAAE,EAAE,CAAC;AAkJtC,OAAO,MAAMC,kBAAkBL,QAAQM,OAAO,GAC5C;AACC;AAEH;;;;;;;;;;;;;;CAcC,GACD,OAAO,MAAMC,0BAA0BP,QAAQM,OAAO,GAGlD;AAAsB"}
@@ -1,4 +1,5 @@
1
- import { type EntifixConnError, type EntityId, type InvalidEnvelope, type TransitionalFailure } from '@entifix/core';
1
+ import './messages.js';
2
+ import { type EntifixConnError, type EntityId, type ProtocolFailure, type TransitionalFailure } from '@entifix/core';
2
3
  import { Context, Effect } from 'effect';
3
4
  import type { TransactionEvent, TransactionState } from './event.js';
4
5
  /**
@@ -75,17 +76,15 @@ export interface TransactionAccepted {
75
76
  * Read for its **shape**, not its contents: it asserts the service really
76
77
  * accepted a transaction rather than answering something else with a `2xx`.
77
78
  */
78
- export declare function readTransactionAcceptedEnvelope(body: unknown): Effect.Effect<TransactionAccepted, InvalidEnvelope>;
79
+ export declare function readTransactionAcceptedEnvelope(body: unknown): Effect.Effect<TransactionAccepted, ProtocolFailure>;
79
80
  /**
80
81
  * Parses the tracker's by-id response, which frames a {@link TransactionRecord}.
81
82
  *
82
- * ⚠️ **`readEnvelope` validates the discriminant and then *casts* the payload**
83
- * — it checks no members. So a discriminant shared by two shapes hands back
84
- * whichever one the caller asked for, typed and wrong: a record read as an
85
- * event has no `step`, no `at`, and a `state` the caller is about to branch on.
86
- * That is the reason the four transaction-shaped discriminants are four.
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.
87
86
  */
88
- export declare function readTransactionRecordEnvelope(body: unknown): Effect.Effect<TransactionRecord, InvalidEnvelope>;
87
+ export declare function readTransactionRecordEnvelope(body: unknown): Effect.Effect<TransactionRecord, ProtocolFailure>;
89
88
  /**
90
89
  * Reads one transaction's record, for a browser reconciling a write it started.
91
90
  *
@@ -1 +1 @@
1
- {"version":3,"file":"record.d.ts","sourceRoot":"","sources":["../../src/contracts/record.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,QAAQ,EACb,KAAK,eAAe,EAEpB,KAAK,mBAAmB,EACzB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO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+1,6 @@
1
- import { readEnvelope } from '@entifix/core';
1
+ // Evaluated for its registrations: this reader decodes against them.
2
+ import './messages.js';
3
+ import { decodeEnvelope } from '@entifix/core';
2
4
  import { Context, Effect } from 'effect';
3
5
  export class TransactionStoreTag extends Context.Service()('TransactionStoreTag') {
4
6
  }
@@ -8,18 +10,16 @@ export class TransactionStoreTag extends Context.Service()('TransactionStoreTag'
8
10
  * Read for its **shape**, not its contents: it asserts the service really
9
11
  * accepted a transaction rather than answering something else with a `2xx`.
10
12
  */ export function readTransactionAcceptedEnvelope(body) {
11
- return Effect.map(readEnvelope(body, 'transactionAccepted', 'transactionAccepted'), (envelope)=>envelope.data);
13
+ return Effect.map(decodeEnvelope(body, 'transactionAccepted'), (envelope)=>envelope.data);
12
14
  }
13
15
  /**
14
16
  * Parses the tracker's by-id response, which frames a {@link TransactionRecord}.
15
17
  *
16
- * ⚠️ **`readEnvelope` validates the discriminant and then *casts* the payload**
17
- * — it checks no members. So a discriminant shared by two shapes hands back
18
- * whichever one the caller asked for, typed and wrong: a record read as an
19
- * event has no `step`, no `at`, and a `state` the caller is about to branch on.
20
- * That is the reason the four transaction-shaped discriminants are four.
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
21
  */ export function readTransactionRecordEnvelope(body) {
22
- return Effect.map(readEnvelope(body, 'transactionRecord', 'transactionRecord'), (envelope)=>envelope.data);
22
+ return Effect.map(decodeEnvelope(body, 'transactionRecord'), (envelope)=>envelope.data);
23
23
  }
24
24
  export class TransactionStatusReaderTag extends Context.Service()('TransactionStatusReaderTag') {
25
25
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/record.ts"],"sourcesContent":["import {\n type EntifixConnError,\n type EntityId,\n type InvalidEnvelope,\n readEnvelope,\n type TransitionalFailure,\n} from '@entifix/core';\nimport { Context, Effect } from 'effect';\n\nimport type { TransactionEvent, TransactionState } from './event.js';\n\n/**\n * The the saga tracker's persisted view of a transaction, folded from the\n * events it observes. It is the source of truth a client polls.\n */\nexport interface TransactionRecord {\n transactionId: string;\n entity: string;\n state: TransactionState;\n code?: string;\n entityId?: EntityId;\n error?: string;\n createdAt: string;\n updatedAt: string;\n /**\n * Whose organization this transaction happened in, folded from the event.\n *\n * The `saga` store is control-plane and single-partition — it holds every\n * organization's records by design — so isolation on the read routes has to be\n * this filter. A record written before the member existed carries none and is\n * therefore readable by nobody, which is the direction to fail.\n */\n organizationId?: string;\n}\n\n/**\n * Port the manager tracks transactions through. Implemented over Mongo in the\n * service; framework-free here so the engine/manager stay environment-agnostic.\n */\nexport interface TransactionStore {\n /** Folds an event into the record, creating it on first sight. */\n upsertFromEvent(\n event: TransactionEvent,\n ): Effect.Effect<TransactionRecord, EntifixConnError>;\n get(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, EntifixConnError>;\n // There is deliberately no `list`. The `saga` store is control-plane and\n // single-partition, so an unfiltered index is every organization's\n // transactions — which is why there is no `GET /api/transaction` list.\n // Anything that needs a set of records asks for one narrow enough to scope,\n // the way `findStale` does.\n /** Non-terminal records not updated within `olderThanMs` — recovery input. */\n findStale(\n olderThanMs: number,\n ): Effect.Effect<readonly TransactionRecord[], EntifixConnError>;\n markStale(transactionId: string): Effect.Effect<void, EntifixConnError>;\n /**\n * How many records sit in each state — the recovery sweep samples it.\n *\n * ⚠️ **This is a count, and is not the `list` above.** It returns no record,\n * no id and no organization, so it does not reopen the list surface removed\n * `GET /api/transaction` for: an unfiltered *listing* of this store is every\n * organization's transactions, while a total of how many are `STALE` is a\n * fleet health number that names nobody. The distinction is the whole reason\n * one is here and the other is refused.\n *\n * It exists so `STALE` is something a dashboard shows rather than something a\n * poll discovers — which is what the recovery sweep, whose only action is to\n * apply that label, otherwise leaves entirely unobservable.\n */\n countByState(): Effect.Effect<\n Record<TransactionState, number>,\n EntifixConnError\n >;\n}\n\nexport class TransactionStoreTag extends Context.Service<\n TransactionStoreTag,\n TransactionStore\n>()('TransactionStoreTag') {}\n\n/**\n * What a service answers a `202` with: the id to poll, and the state it starts\n * in.\n *\n * ⚠️ **Not a {@link TransactionRecord}, which is why it has its own\n * discriminant.** Nothing has been folded yet — there is no `createdAt`, no\n * entity id, and no code, because the write has not run. Framing it as a record\n * meant the browser's accept-shape assertion was checking a name that the\n * by-id route and the bus payload also answered to, so it asserted nothing it\n * claimed to.\n */\nexport interface TransactionAccepted {\n transactionId: string;\n state: TransactionState;\n}\n\n/**\n * Parses a `202` accept body, for a browser about to start polling.\n *\n * Read for its **shape**, not its contents: it asserts the service really\n * accepted a transaction rather than answering something else with a `2xx`.\n */\nexport function readTransactionAcceptedEnvelope(\n body: unknown,\n): Effect.Effect<TransactionAccepted, InvalidEnvelope> {\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, InvalidEnvelope> {\n return Effect.map(\n readEnvelope<TransactionRecord>(\n body,\n 'transactionRecord',\n 'transactionRecord',\n ),\n envelope => envelope.data,\n );\n}\n\n/**\n * Reads one transaction's record, for a browser reconciling a write it started.\n *\n * ⚠️ **`undefined` means _not tracked yet_, not _failed_.** `accepted` reaches\n * the tracker over the bus, so with the broker down the entity write commits —\n * the outbox is in the same Mongo transaction — while no event is ever\n * published and this answers `404`. That is a write in perfect health, and a\n * caller that rolls back on it un-renders a record that is about to appear, at\n * exactly the moment nobody can tell a UI bug from an outage. Only `FAILED` and\n * `STALE` are terminal.\n */\nexport interface TransactionStatusReader {\n read(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, TransitionalFailure>;\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,QAEP,gBAAgB;AACvB,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AAsEzC,OAAO,MAAMC,4BAA4BF,QAAQG,OAAO,GAGpD;AAAwB;AAkB5B;;;;;CAKC,GACD,OAAO,SAASC,gCACdC,IAAa;IAEb,OAAOJ,OAAOK,GAAG,CACfP,aACEM,MACA,uBACA,wBAEFE,CAAAA,WAAYA,SAASC,IAAI;AAE7B;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASC,8BACdJ,IAAa;IAEb,OAAOJ,OAAOK,GAAG,CACfP,aACEM,MACA,qBACA,sBAEFE,CAAAA,WAAYA,SAASC,IAAI;AAE7B;AAmBA,OAAO,MAAME,mCAAmCV,QAAQG,OAAO,GAG3D;AAA+B"}
1
+ {"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 EntifixConnError,\n type EntityId,\n type ProtocolFailure,\n type TransitionalFailure,\n} from '@entifix/core';\nimport { Context, Effect } from 'effect';\n\nimport type { TransactionEvent, TransactionState } from './event.js';\n\n/**\n * The the saga tracker's persisted view of a transaction, folded from the\n * events it observes. It is the source of truth a client polls.\n */\nexport interface TransactionRecord {\n transactionId: string;\n entity: string;\n state: TransactionState;\n code?: string;\n entityId?: EntityId;\n error?: string;\n createdAt: string;\n updatedAt: string;\n /**\n * Whose organization this transaction happened in, folded from the event.\n *\n * The `saga` store is control-plane and single-partition — it holds every\n * organization's records by design — so isolation on the read routes has to be\n * this filter. A record written before the member existed carries none and is\n * therefore readable by nobody, which is the direction to fail.\n */\n organizationId?: string;\n}\n\n/**\n * Port the manager tracks transactions through. Implemented over Mongo in the\n * service; framework-free here so the engine/manager stay environment-agnostic.\n */\nexport interface TransactionStore {\n /** Folds an event into the record, creating it on first sight. */\n upsertFromEvent(\n event: TransactionEvent,\n ): Effect.Effect<TransactionRecord, EntifixConnError>;\n get(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, EntifixConnError>;\n // There is deliberately no `list`. The `saga` store is control-plane and\n // single-partition, so an unfiltered index is every organization's\n // transactions — which is why there is no `GET /api/transaction` list.\n // Anything that needs a set of records asks for one narrow enough to scope,\n // the way `findStale` does.\n /** Non-terminal records not updated within `olderThanMs` — recovery input. */\n findStale(\n olderThanMs: number,\n ): Effect.Effect<readonly TransactionRecord[], EntifixConnError>;\n markStale(transactionId: string): Effect.Effect<void, EntifixConnError>;\n /**\n * How many records sit in each state — the recovery sweep samples it.\n *\n * ⚠️ **This is a count, and is not the `list` above.** It returns no record,\n * no id and no organization, so it does not reopen the list surface removed\n * `GET /api/transaction` for: an unfiltered *listing* of this store is every\n * organization's transactions, while a total of how many are `STALE` is a\n * fleet health number that names nobody. The distinction is the whole reason\n * one is here and the other is refused.\n *\n * It exists so `STALE` is something a dashboard shows rather than something a\n * poll discovers — which is what the recovery sweep, whose only action is to\n * apply that label, otherwise leaves entirely unobservable.\n */\n countByState(): Effect.Effect<\n Record<TransactionState, number>,\n EntifixConnError\n >;\n}\n\nexport class TransactionStoreTag extends Context.Service<\n TransactionStoreTag,\n TransactionStore\n>()('TransactionStoreTag') {}\n\n/**\n * What a service answers a `202` with: the id to poll, and the state it starts\n * in.\n *\n * ⚠️ **Not a {@link TransactionRecord}, which is why it has its own\n * discriminant.** Nothing has been folded yet — there is no `createdAt`, no\n * entity id, and no code, because the write has not run. Framing it as a record\n * meant the browser's accept-shape assertion was checking a name that the\n * by-id route and the bus payload also answered to, so it asserted nothing it\n * claimed to.\n */\nexport interface TransactionAccepted {\n transactionId: string;\n state: TransactionState;\n}\n\n/**\n * Parses a `202` accept body, for a browser about to start polling.\n *\n * Read for its **shape**, not its contents: it asserts the service really\n * accepted a transaction rather than answering something else with a `2xx`.\n */\nexport function readTransactionAcceptedEnvelope(\n body: unknown,\n): Effect.Effect<TransactionAccepted, 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, TransitionalFailure>;\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;AAsEzC,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,5 +1,6 @@
1
- import type { DomainEvent, StoreFault } from '@entifix/core';
1
+ import type { StoreFault } from '@entifix/core';
2
2
  import type { Effect, Option } from 'effect';
3
+ import type { OutboxEvent } from './outbox.js';
3
4
  /**
4
5
  * What a unit of work deduplicates on, if anything. At most one per unit.
5
6
  *
@@ -38,7 +39,7 @@ export interface Unit<H> {
38
39
  * same transaction, so the state change and its announcement are one fact,
39
40
  * and the relay carries it to the bus afterwards.
40
41
  */
41
- emit(event: DomainEvent): void;
42
+ emit(event: OutboxEvent): void;
42
43
  }
43
44
  /**
44
45
  * How a unit ended. A failure of the store itself is not one of these — it is
@@ -1 +1 @@
1
- {"version":3,"file":"unit-of-work.d.ts","sourceRoot":"","sources":["../../src/contracts/unit-of-work.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC7D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE7C;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,SAAS,GACjB;IACE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;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["../../src/contracts/unit-of-work.ts"],"sourcesContent":["import type { DomainEvent, StoreFault } from '@entifix/core';\nimport type { Effect, Option } from 'effect';\n\n/**\n * What a unit of work deduplicates on, if anything. At most one per unit.\n *\n * Two kinds, because there are two directions a duplicate arrives from:\n *\n * - `event` — a consumer folding a bus message. Keyed on `(consumer, eventId)`,\n * the inbox's compound key: two consumers legitimately process one event,\n * and a key on `eventId` alone would let whichever claimed first starve the\n * other.\n * - `command` — a participant answering a dispatched command. Keyed on the\n * command id alone, and it **remembers an answer**: a redelivered command must\n * be told what the first delivery decided, not that it was a duplicate.\n */\nexport type UnitClaim =\n | {\n readonly kind: 'event';\n readonly consumer: string;\n readonly eventId: string;\n }\n | { readonly kind: 'command'; readonly commandId: string };\n\n/**\n * The view a unit's body gets of the transaction it runs in.\n *\n * `handle` is the store's own — a driver session and the database it is bound\n * to, for Mongo. It is opaque to this package on purpose: the contract states\n * what commits together, and only the adapter that implements it (and the\n * persistence code written against that adapter) ever looks inside.\n */\nexport interface Unit<H> {\n readonly handle: H;\n /**\n * Record an event to publish **if and only if** the unit commits.\n *\n * Recorded, not published. The adapter writes it to the outbox inside the\n * same transaction, so the state change and its announcement are one fact,\n * and the relay carries it to the bus afterwards.\n */\n emit(event: DomainEvent): void;\n}\n\n/**\n * How a unit ended. A failure of the store itself is not one of these — it is\n * the `StoreFault` in the error channel of {@link UnitOfWork.run}.\n *\n * - `committed` — every write, every event and the claim are durable.\n * - `duplicate` — the claim was already taken, so the body's work had already\n * committed once. Nothing was written. `replay` is what the first run asked\n * to be remembered (`command` claims only).\n * - `aborted` — the body failed with a business reason. Nothing was written.\n * This is how a refusal leaves a unit: as a typed value, never as a thrown\n * sentinel caught three frames up.\n */\nexport type UnitOutcome<A, E> =\n | { readonly _tag: 'committed'; readonly value: A }\n | { readonly _tag: 'duplicate'; readonly replay: Option.Option<unknown> }\n | { readonly _tag: 'aborted'; readonly reason: E };\n\nexport interface UnitRunOptions<A, R = never> {\n readonly claim?: UnitClaim;\n /**\n * What a later duplicate of this `command` claim is answered with, derived\n * from the committed value. Stored with the claim, in the same transaction.\n *\n * It must be JSON: it is written to the store and read back by a different\n * process, possibly after a restart.\n */\n readonly replay?: (value: A) => unknown;\n /**\n * Runs once the unit has committed, and never otherwise — the place to drain\n * the outbox inline so the event leaves now rather than at the next sweep.\n *\n * Its failure does not undo the commit, and is not reported as the unit's: a\n * drain that fails here is retried by the sweep, which is exactly the\n * fallback the outbox exists to provide.\n */\n readonly afterCommit?: Effect.Effect<void, unknown, R>;\n}\n\n/**\n * One storage transaction that the outbox, the inbox and a command claim all\n * join: domain writes, zero or more events, and at most one claim, which commit\n * or vanish together.\n *\n * The body may run **more than once**. A store that retries a transient\n * conflict re-runs it from the start, so the body must be a pure function of\n * its inputs and the handle — no clock read that has to match a value already\n * returned, no call to another service, no counter drawn from outside the\n * store. Do those before the unit and pass the results in.\n *\n * The body's typed failure is the abort: `run` rolls back and answers\n * `aborted` with it. A `StoreFault` is the exception — the store failing\n * is not a business decision, so it rolls back and surfaces in `run`'s own\n * error channel instead.\n *\n * Reads through the handle see the unit's own uncommitted writes.\n */\nexport interface UnitOfWork<H> {\n run<A, E, R>(\n body: (unit: Unit<H>) => Effect.Effect<A, E, R>,\n options?: UnitRunOptions<A, R>,\n ): Effect.Effect<UnitOutcome<A, Exclude<E, StoreFault>>, StoreFault, R>;\n /**\n * What the run that took this `command` claim asked to be remembered, or\n * `none` if no run has taken it — for a caller that has to answer a duplicate\n * outside a unit.\n */\n replay(commandId: string): Effect.Effect<Option.Option<unknown>, StoreFault>;\n}\n"],"names":[],"mappings":"AAkFA;;;;;;;;;;;;;;;;;CAiBC,GACD,WAWC"}
1
+ {"version":3,"sources":["../../src/contracts/unit-of-work.ts"],"sourcesContent":["import type { StoreFault } from '@entifix/core';\nimport type { Effect, Option } from 'effect';\n\nimport type { OutboxEvent } from './outbox.js';\n\n/**\n * What a unit of work deduplicates on, if anything. At most one per unit.\n *\n * Two kinds, because there are two directions a duplicate arrives from:\n *\n * - `event` — a consumer folding a bus message. Keyed on `(consumer, eventId)`,\n * the inbox's compound key: two consumers legitimately process one event,\n * and a key on `eventId` alone would let whichever claimed first starve the\n * other.\n * - `command` — a participant answering a dispatched command. Keyed on the\n * command id alone, and it **remembers an answer**: a redelivered command must\n * be told what the first delivery decided, not that it was a duplicate.\n */\nexport type UnitClaim =\n | {\n readonly kind: 'event';\n readonly consumer: string;\n readonly eventId: string;\n }\n | { readonly kind: 'command'; readonly commandId: string };\n\n/**\n * The view a unit's body gets of the transaction it runs in.\n *\n * `handle` is the store's own — a driver session and the database it is bound\n * to, for Mongo. It is opaque to this package on purpose: the contract states\n * what commits together, and only the adapter that implements it (and the\n * persistence code written against that adapter) ever looks inside.\n */\nexport interface Unit<H> {\n readonly handle: H;\n /**\n * Record an event to publish **if and only if** the unit commits.\n *\n * Recorded, not published. The adapter writes it to the outbox inside the\n * same transaction, so the state change and its announcement are one fact,\n * and the relay carries it to the bus afterwards.\n */\n emit(event: OutboxEvent): void;\n}\n\n/**\n * How a unit ended. A failure of the store itself is not one of these — it is\n * the `StoreFault` in the error channel of {@link UnitOfWork.run}.\n *\n * - `committed` — every write, every event and the claim are durable.\n * - `duplicate` — the claim was already taken, so the body's work had already\n * committed once. Nothing was written. `replay` is what the first run asked\n * to be remembered (`command` claims only).\n * - `aborted` — the body failed with a business reason. Nothing was written.\n * This is how a refusal leaves a unit: as a typed value, never as a thrown\n * sentinel caught three frames up.\n */\nexport type UnitOutcome<A, E> =\n | { readonly _tag: 'committed'; readonly value: A }\n | { readonly _tag: 'duplicate'; readonly replay: Option.Option<unknown> }\n | { readonly _tag: 'aborted'; readonly reason: E };\n\nexport interface UnitRunOptions<A, R = never> {\n readonly claim?: UnitClaim;\n /**\n * What a later duplicate of this `command` claim is answered with, derived\n * from the committed value. Stored with the claim, in the same transaction.\n *\n * It must be JSON: it is written to the store and read back by a different\n * process, possibly after a restart.\n */\n readonly replay?: (value: A) => unknown;\n /**\n * Runs once the unit has committed, and never otherwise — the place to drain\n * the outbox inline so the event leaves now rather than at the next sweep.\n *\n * Its failure does not undo the commit, and is not reported as the unit's: a\n * drain that fails here is retried by the sweep, which is exactly the\n * fallback the outbox exists to provide.\n */\n readonly afterCommit?: Effect.Effect<void, unknown, R>;\n}\n\n/**\n * One storage transaction that the outbox, the inbox and a command claim all\n * join: domain writes, zero or more events, and at most one claim, which commit\n * or vanish together.\n *\n * The body may run **more than once**. A store that retries a transient\n * conflict re-runs it from the start, so the body must be a pure function of\n * its inputs and the handle — no clock read that has to match a value already\n * returned, no call to another service, no counter drawn from outside the\n * store. Do those before the unit and pass the results in.\n *\n * The body's typed failure is the abort: `run` rolls back and answers\n * `aborted` with it. A `StoreFault` is the exception — the store failing\n * is not a business decision, so it rolls back and surfaces in `run`'s own\n * error channel instead.\n *\n * Reads through the handle see the unit's own uncommitted writes.\n */\nexport interface UnitOfWork<H> {\n run<A, E, R>(\n body: (unit: Unit<H>) => Effect.Effect<A, E, R>,\n options?: UnitRunOptions<A, R>,\n ): Effect.Effect<UnitOutcome<A, Exclude<E, StoreFault>>, StoreFault, R>;\n /**\n * What the run that took this `command` claim asked to be remembered, or\n * `none` if no run has taken it — for a caller that has to answer a duplicate\n * outside a unit.\n */\n replay(commandId: string): Effect.Effect<Option.Option<unknown>, StoreFault>;\n}\n"],"names":[],"mappings":"AAoFA;;;;;;;;;;;;;;;;;CAiBC,GACD,WAWC"}
@@ -0,0 +1,20 @@
1
+ import { Layer } from 'effect';
2
+ import { type Bulkhead, BulkheadTag } from '../ports/bulkhead.js';
3
+ export interface InMemoryBulkheadOptions {
4
+ /** Permits per key unless `permitsFor` names one. */
5
+ readonly permits?: number;
6
+ /** A participant's own permits — its config row. */
7
+ readonly permitsFor?: (key: string) => number | undefined;
8
+ }
9
+ /** Ten concurrent calls per dependency, unless a dial says otherwise. */
10
+ export declare const DEFAULT_BULKHEAD_PERMITS = 10;
11
+ /**
12
+ * A per-process bulkhead: a count of permits per key, taken for the length of
13
+ * a call and given back however it ends. A call that finds none free is
14
+ * refused with `bulkheadFull` at once — queueing it would hold the caller's
15
+ * deadline on a dependency that is already saturated.
16
+ */
17
+ export declare const makeInMemoryBulkhead: (options?: InMemoryBulkheadOptions) => Bulkhead;
18
+ /** One bulkhead set for the process, for the composition root. */
19
+ export declare const InMemoryBulkheadLayer: (options?: InMemoryBulkheadOptions) => Layer.Layer<BulkheadTag, never, never>;
20
+ //# sourceMappingURL=in-memory-bulkhead.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory-bulkhead.d.ts","sourceRoot":"","sources":["../../src/engine/in-memory-bulkhead.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,EAAU,MAAM,QAAQ,CAAC;AAE/C,OAAO,EACL,KAAK,QAAQ,EAGb,WAAW,EACZ,MAAM,sBAAsB,CAAC;AAE9B,MAAM,WAAW,uBAAuB;IACtC,qDAAqD;IACrD,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,oDAAoD;IACpD,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;CAC3D;AAED,yEAAyE;AACzE,eAAO,MAAM,wBAAwB,KAAK,CAAC;AAE3C;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,GAC/B,UAAS,uBAA4B,KACpC,QA4BF,CAAC;AAEF,kEAAkE;AAClE,eAAO,MAAM,qBAAqB,GAAI,UAAS,uBAA4B,2CACb,CAAC"}
@@ -0,0 +1,38 @@
1
+ import { Effect, Layer, Metric } from 'effect';
2
+ import { BulkheadFull, bulkheadInUse, BulkheadTag } from '../ports/bulkhead.js';
3
+ /** Ten concurrent calls per dependency, unless a dial says otherwise. */ export const DEFAULT_BULKHEAD_PERMITS = 10;
4
+ /**
5
+ * A per-process bulkhead: a count of permits per key, taken for the length of
6
+ * a call and given back however it ends. A call that finds none free is
7
+ * refused with `bulkheadFull` at once — queueing it would hold the caller's
8
+ * deadline on a dependency that is already saturated.
9
+ */ export const makeInMemoryBulkhead = (options = {})=>{
10
+ const taken = new Map();
11
+ const permitsOf = (key)=>{
12
+ var _ref, _ref1;
13
+ return (_ref = (_ref1 = options.permitsFor == null ? void 0 : options.permitsFor.call(options, key)) != null ? _ref1 : options.permits) != null ? _ref : DEFAULT_BULKHEAD_PERMITS;
14
+ };
15
+ const inUse = (key)=>{
16
+ var _taken_get;
17
+ return (_taken_get = taken.get(key)) != null ? _taken_get : 0;
18
+ };
19
+ const report = (key)=>Metric.update(Metric.withAttributes(bulkheadInUse, {
20
+ key
21
+ }), inUse(key));
22
+ return {
23
+ withPermit: (key)=>(effect)=>Effect.acquireUseRelease(Effect.suspend(()=>{
24
+ if (inUse(key) >= permitsOf(key)) return Effect.fail(new BulkheadFull({
25
+ dependency: key
26
+ }));
27
+ taken.set(key, inUse(key) + 1);
28
+ return report(key);
29
+ }), ()=>effect, ()=>Effect.suspend(()=>{
30
+ taken.set(key, inUse(key) - 1);
31
+ return report(key);
32
+ })),
33
+ inUse: (key)=>Effect.sync(()=>inUse(key))
34
+ };
35
+ };
36
+ /** One bulkhead set for the process, for the composition root. */ export const InMemoryBulkheadLayer = (options = {})=>Layer.sync(BulkheadTag, ()=>makeInMemoryBulkhead(options));
37
+
38
+ //# sourceMappingURL=in-memory-bulkhead.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/engine/in-memory-bulkhead.ts"],"sourcesContent":["import { Effect, Layer, Metric } from 'effect';\n\nimport {\n type Bulkhead,\n BulkheadFull,\n bulkheadInUse,\n BulkheadTag,\n} from '../ports/bulkhead.js';\n\nexport interface InMemoryBulkheadOptions {\n /** Permits per key unless `permitsFor` names one. */\n readonly permits?: number;\n /** A participant's own permits — its config row. */\n readonly permitsFor?: (key: string) => number | undefined;\n}\n\n/** Ten concurrent calls per dependency, unless a dial says otherwise. */\nexport const DEFAULT_BULKHEAD_PERMITS = 10;\n\n/**\n * A per-process bulkhead: a count of permits per key, taken for the length of\n * a call and given back however it ends. A call that finds none free is\n * refused with `bulkheadFull` at once — queueing it would hold the caller's\n * deadline on a dependency that is already saturated.\n */\nexport const makeInMemoryBulkhead = (\n options: InMemoryBulkheadOptions = {},\n): Bulkhead => {\n const taken = new Map<string, number>();\n const permitsOf = (key: string) =>\n options.permitsFor?.(key) ?? options.permits ?? DEFAULT_BULKHEAD_PERMITS;\n const inUse = (key: string) => taken.get(key) ?? 0;\n const report = (key: string) =>\n Metric.update(Metric.withAttributes(bulkheadInUse, { key }), inUse(key));\n\n return {\n withPermit:\n key =>\n <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n Effect.acquireUseRelease(\n Effect.suspend(() => {\n if (inUse(key) >= permitsOf(key))\n return Effect.fail(new BulkheadFull({ dependency: key }));\n taken.set(key, inUse(key) + 1);\n return report(key);\n }),\n () => effect,\n () =>\n Effect.suspend(() => {\n taken.set(key, inUse(key) - 1);\n return report(key);\n }),\n ),\n inUse: key => Effect.sync(() => inUse(key)),\n };\n};\n\n/** One bulkhead set for the process, for the composition root. */\nexport const InMemoryBulkheadLayer = (options: InMemoryBulkheadOptions = {}) =>\n Layer.sync(BulkheadTag, () => makeInMemoryBulkhead(options));\n"],"names":["Effect","Layer","Metric","BulkheadFull","bulkheadInUse","BulkheadTag","DEFAULT_BULKHEAD_PERMITS","makeInMemoryBulkhead","options","taken","Map","permitsOf","key","permitsFor","permits","inUse","get","report","update","withAttributes","withPermit","effect","acquireUseRelease","suspend","fail","dependency","set","sync","InMemoryBulkheadLayer"],"mappings":"AAAA,SAASA,MAAM,EAAEC,KAAK,EAAEC,MAAM,QAAQ,SAAS;AAE/C,SAEEC,YAAY,EACZC,aAAa,EACbC,WAAW,QACN,uBAAuB;AAS9B,uEAAuE,GACvE,OAAO,MAAMC,2BAA2B,GAAG;AAE3C;;;;;CAKC,GACD,OAAO,MAAMC,uBAAuB,CAClCC,UAAmC,CAAC,CAAC;IAErC,MAAMC,QAAQ,IAAIC;IAClB,MAAMC,YAAY,CAACC;YACjBJ;gBAAAA,gBAAAA,QAAQK,UAAU,oBAAlBL,QAAQK,UAAU,MAAlBL,SAAqBI,wBAAQJ,QAAQM,OAAO,YAA5CN,OAAgDF;;IAClD,MAAMS,QAAQ,CAACH;YAAgBH;gBAAAA,aAAAA,MAAMO,GAAG,CAACJ,gBAAVH,aAAkB;;IACjD,MAAMQ,SAAS,CAACL,MACdV,OAAOgB,MAAM,CAAChB,OAAOiB,cAAc,CAACf,eAAe;YAAEQ;QAAI,IAAIG,MAAMH;IAErE,OAAO;QACLQ,YACER,CAAAA,MACA,CAAUS,SACRrB,OAAOsB,iBAAiB,CACtBtB,OAAOuB,OAAO,CAAC;oBACb,IAAIR,MAAMH,QAAQD,UAAUC,MAC1B,OAAOZ,OAAOwB,IAAI,CAAC,IAAIrB,aAAa;wBAAEsB,YAAYb;oBAAI;oBACxDH,MAAMiB,GAAG,CAACd,KAAKG,MAAMH,OAAO;oBAC5B,OAAOK,OAAOL;gBAChB,IACA,IAAMS,QACN,IACErB,OAAOuB,OAAO,CAAC;wBACbd,MAAMiB,GAAG,CAACd,KAAKG,MAAMH,OAAO;wBAC5B,OAAOK,OAAOL;oBAChB;QAERG,OAAOH,CAAAA,MAAOZ,OAAO2B,IAAI,CAAC,IAAMZ,MAAMH;IACxC;AACF,EAAE;AAEF,gEAAgE,GAChE,OAAO,MAAMgB,wBAAwB,CAACpB,UAAmC,CAAC,CAAC,GACzEP,MAAM0B,IAAI,CAACtB,aAAa,IAAME,qBAAqBC,UAAU"}
@@ -0,0 +1,28 @@
1
+ import { Layer } from 'effect';
2
+ import { type BreakerDials, type CircuitBreaker, CircuitBreakerTag } from '../ports/circuit-breaker.js';
3
+ export interface InMemoryCircuitBreakerOptions {
4
+ /** Dials for every key, over the defaults. */
5
+ readonly dials?: Partial<BreakerDials>;
6
+ /** Dials for one key, over `dials` — a participant's own row. */
7
+ readonly dialsFor?: (key: string) => Partial<BreakerDials> | undefined;
8
+ /** The clock, in epoch milliseconds. Injected so a spec can move time. */
9
+ readonly now?: () => number;
10
+ }
11
+ /**
12
+ * Per-process breakers, one per key, on Resilience4j's state machine
13
+ * ([ADR 0017](../../../../../docs/adr/0017-circuit-breaker-and-bulkhead-ports.md)).
14
+ *
15
+ * Closed, every call is recorded in a count- or time-based window; once the
16
+ * window holds `minimumCalls` and the failure or slow-call rate reaches its
17
+ * threshold, the breaker opens. A dependency answering with `Retry-After` opens
18
+ * it at once, for at least as long as it asked. Open, every call is refused
19
+ * until `waitInOpenMs` has passed; then `halfOpenPermits` probes go through, and
20
+ * their outcome closes or reopens it.
21
+ *
22
+ * Per process on purpose: a fleet-wide breaker would put a shared store on the
23
+ * hot path, and per-process state converges within a window.
24
+ */
25
+ export declare const makeInMemoryCircuitBreaker: (options?: InMemoryCircuitBreakerOptions) => CircuitBreaker;
26
+ /** One breaker set for the process, for the composition root. */
27
+ export declare const InMemoryCircuitBreakerLayer: (options?: InMemoryCircuitBreakerOptions) => Layer.Layer<CircuitBreakerTag, never, never>;
28
+ //# sourceMappingURL=in-memory-circuit-breaker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory-circuit-breaker.d.ts","sourceRoot":"","sources":["../../src/engine/in-memory-circuit-breaker.ts"],"names":[],"mappings":"AACA,OAAO,EAAuB,KAAK,EAAU,MAAM,QAAQ,CAAC;AAE5D,OAAO,EAEL,KAAK,YAAY,EAMjB,KAAK,cAAc,EACnB,iBAAiB,EAElB,MAAM,6BAA6B,CAAC;AAoBrC,MAAM,WAAW,6BAA6B;IAC5C,8CAA8C;IAC9C,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC;IACvC,iEAAiE;IACjE,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,YAAY,CAAC,GAAG,SAAS,CAAC;IACvE,0EAA0E;IAC1E,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC7B;AA6BD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,0BAA0B,GACrC,UAAS,6BAAkC,KAC1C,cAiJF,CAAC;AAEF,iEAAiE;AACjE,eAAO,MAAM,2BAA2B,GACtC,UAAS,6BAAkC,iDACgC,CAAC"}
@@ -0,0 +1,151 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ import { isFailure } from '@entifix/core';
3
+ import { Cause, Effect, Exit, Layer, Metric } from 'effect';
4
+ import { BREAKER_STATE_VALUE, BreakerOpen, breakerRejections, breakerState, breakerTransitions, CircuitBreakerTag, DEFAULT_BREAKER_DIALS } from '../ports/circuit-breaker.js';
5
+ /** What a call's exit means to the window: a failure, a success, or neither. */ const verdictOf = (exit)=>{
6
+ if (Exit.isSuccess(exit)) return {
7
+ recorded: true,
8
+ failed: false
9
+ };
10
+ const failure = Cause.findErrorOption(exit.cause);
11
+ if (failure._tag === 'None') return {
12
+ recorded: false
13
+ };
14
+ const error = failure.value;
15
+ // An answer is not a failure of the dependency, and a protocol failure is a
16
+ // bug that waiting does not fix: neither moves the breaker.
17
+ if (!isFailure(error)) return {
18
+ recorded: false
19
+ };
20
+ if (error.family === 'business') return {
21
+ recorded: true,
22
+ failed: false
23
+ };
24
+ if (error.category === 'protocol') return {
25
+ recorded: false
26
+ };
27
+ return {
28
+ recorded: true,
29
+ failed: true,
30
+ failure: error
31
+ };
32
+ };
33
+ /** Seconds a dependency asked to be left alone for, when it said so. */ const retryAfterOf = (failure)=>{
34
+ const seconds = failure.retryAfterSeconds;
35
+ return typeof seconds === 'number' && seconds > 0 ? seconds : undefined;
36
+ };
37
+ const rates = (calls)=>({
38
+ failure: calls.filter((call)=>call.failed).length / calls.length,
39
+ slow: calls.filter((call)=>call.slow).length / calls.length
40
+ });
41
+ /**
42
+ * Per-process breakers, one per key, on Resilience4j's state machine
43
+ * ([ADR 0017](../../../../../docs/adr/0017-circuit-breaker-and-bulkhead-ports.md)).
44
+ *
45
+ * Closed, every call is recorded in a count- or time-based window; once the
46
+ * window holds `minimumCalls` and the failure or slow-call rate reaches its
47
+ * threshold, the breaker opens. A dependency answering with `Retry-After` opens
48
+ * it at once, for at least as long as it asked. Open, every call is refused
49
+ * until `waitInOpenMs` has passed; then `halfOpenPermits` probes go through, and
50
+ * their outcome closes or reopens it.
51
+ *
52
+ * Per process on purpose: a fleet-wide breaker would put a shared store on the
53
+ * hot path, and per-process state converges within a window.
54
+ */ export const makeInMemoryCircuitBreaker = (options = {})=>{
55
+ var _options_now;
56
+ const now = (_options_now = options.now) != null ? _options_now : Date.now;
57
+ const circuits = new Map();
58
+ const dialsOf = (key)=>_extends({}, DEFAULT_BREAKER_DIALS, options.dials, options.dialsFor == null ? void 0 : options.dialsFor.call(options, key));
59
+ const circuitOf = (key)=>{
60
+ let circuit = circuits.get(key);
61
+ if (circuit === undefined) {
62
+ circuit = {
63
+ state: 'closed',
64
+ openedAt: 0,
65
+ waitMs: 0,
66
+ window: [],
67
+ admitted: 0,
68
+ probes: []
69
+ };
70
+ circuits.set(key, circuit);
71
+ }
72
+ return circuit;
73
+ };
74
+ const report = (key, circuit)=>Metric.update(Metric.withAttributes(breakerState, {
75
+ key
76
+ }), BREAKER_STATE_VALUE[circuit.state]);
77
+ const move = (key, circuit, to)=>{
78
+ const from = circuit.state;
79
+ circuit.state = to;
80
+ circuit.admitted = 0;
81
+ circuit.probes = [];
82
+ if (to === 'closed') circuit.window = [];
83
+ return Metric.update(Metric.withAttributes(breakerTransitions, {
84
+ key,
85
+ from,
86
+ to
87
+ }), 1).pipe(Effect.andThen(report(key, circuit)));
88
+ };
89
+ const open = (key, circuit, waitMs)=>{
90
+ circuit.openedAt = now();
91
+ circuit.waitMs = waitMs;
92
+ return move(key, circuit, 'open');
93
+ };
94
+ /** An open breaker whose wait has passed is half-open, read lazily. */ const settle = (key, circuit)=>circuit.state === 'open' && now() - circuit.openedAt >= circuit.waitMs ? move(key, circuit, 'halfOpen') : Effect.void;
95
+ const trimmed = (window, dials)=>dials.windowType === 'count' ? window.slice(-dials.windowSize) : window.filter((call)=>now() - call.at < dials.windowSize * 1000);
96
+ const record = (key, circuit, call, failure)=>Effect.suspend(()=>{
97
+ const dials = dialsOf(key);
98
+ const retryAfter = call.failed ? retryAfterOf(failure) : undefined;
99
+ if (retryAfter !== undefined && circuit.state !== 'disabled') return open(key, circuit, Math.max(dials.waitInOpenMs, retryAfter * 1000));
100
+ if (circuit.state === 'halfOpen') {
101
+ circuit.probes.push(call);
102
+ if (circuit.probes.length < dials.halfOpenPermits) return Effect.void;
103
+ const probed = rates(circuit.probes);
104
+ return probed.failure >= dials.failureRateThreshold || probed.slow >= dials.slowCallRateThreshold ? open(key, circuit, dials.waitInOpenMs) : move(key, circuit, 'closed');
105
+ }
106
+ if (circuit.state !== 'closed') return Effect.void;
107
+ circuit.window = trimmed([
108
+ ...circuit.window,
109
+ call
110
+ ], dials);
111
+ if (circuit.window.length < dials.minimumCalls) return Effect.void;
112
+ const windowed = rates(circuit.window);
113
+ return windowed.failure >= dials.failureRateThreshold || windowed.slow >= dials.slowCallRateThreshold ? open(key, circuit, dials.waitInOpenMs) : Effect.void;
114
+ });
115
+ const refuse = (key)=>Metric.update(Metric.withAttributes(breakerRejections, {
116
+ key
117
+ }), 1).pipe(Effect.andThen(Effect.fail(new BreakerOpen({
118
+ dependency: key
119
+ }))));
120
+ return {
121
+ guard: (key)=>(effect)=>Effect.gen(function*() {
122
+ const circuit = circuitOf(key);
123
+ yield* settle(key, circuit);
124
+ if (circuit.state === 'disabled') return yield* effect;
125
+ if (circuit.state === 'open' || circuit.state === 'forcedOpen') return yield* refuse(key);
126
+ if (circuit.state === 'halfOpen') {
127
+ const dials = dialsOf(key);
128
+ if (circuit.admitted >= dials.halfOpenPermits) return yield* refuse(key);
129
+ circuit.admitted += 1;
130
+ }
131
+ const startedAt = now();
132
+ const exit = yield* Effect.exit(effect);
133
+ const verdict = verdictOf(exit);
134
+ if (verdict.recorded) yield* record(key, circuit, {
135
+ at: startedAt,
136
+ failed: verdict.failed,
137
+ slow: now() - startedAt > dialsOf(key).slowCallDurationMs
138
+ }, verdict.failed ? verdict.failure : undefined);
139
+ return yield* exit;
140
+ }),
141
+ state: (key)=>Effect.gen(function*() {
142
+ const circuit = circuitOf(key);
143
+ yield* settle(key, circuit);
144
+ return circuit.state;
145
+ }),
146
+ force: (key, state)=>Effect.suspend(()=>move(key, circuitOf(key), state))
147
+ };
148
+ };
149
+ /** One breaker set for the process, for the composition root. */ export const InMemoryCircuitBreakerLayer = (options = {})=>Layer.sync(CircuitBreakerTag, ()=>makeInMemoryCircuitBreaker(options));
150
+
151
+ //# sourceMappingURL=in-memory-circuit-breaker.js.map