@entifix/transactions 0.11.0 → 0.12.1

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 (53) hide show
  1. package/dist/contracts/flow-messages.d.ts +3 -2
  2. package/dist/contracts/flow-messages.d.ts.map +1 -1
  3. package/dist/contracts/flow-messages.js.map +1 -1
  4. package/dist/contracts/outbox.d.ts +18 -0
  5. package/dist/contracts/outbox.d.ts.map +1 -1
  6. package/dist/contracts/outbox.js +16 -0
  7. package/dist/contracts/outbox.js.map +1 -1
  8. package/dist/engine/in-memory-bulkhead.d.ts +20 -0
  9. package/dist/engine/in-memory-bulkhead.d.ts.map +1 -0
  10. package/dist/engine/in-memory-bulkhead.js +38 -0
  11. package/dist/engine/in-memory-bulkhead.js.map +1 -0
  12. package/dist/engine/in-memory-circuit-breaker.d.ts +28 -0
  13. package/dist/engine/in-memory-circuit-breaker.d.ts.map +1 -0
  14. package/dist/engine/in-memory-circuit-breaker.js +151 -0
  15. package/dist/engine/in-memory-circuit-breaker.js.map +1 -0
  16. package/dist/engine/index.d.ts +4 -0
  17. package/dist/engine/index.d.ts.map +1 -1
  18. package/dist/engine/index.js +4 -0
  19. package/dist/engine/index.js.map +1 -1
  20. package/dist/engine/outbox-metrics.d.ts +47 -0
  21. package/dist/engine/outbox-metrics.d.ts.map +1 -0
  22. package/dist/engine/outbox-metrics.js +68 -0
  23. package/dist/engine/outbox-metrics.js.map +1 -0
  24. package/dist/engine/outbox-relay.d.ts +102 -0
  25. package/dist/engine/outbox-relay.d.ts.map +1 -0
  26. package/dist/engine/outbox-relay.js +111 -0
  27. package/dist/engine/outbox-relay.js.map +1 -0
  28. package/dist/index.d.ts +3 -0
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +3 -0
  31. package/dist/index.js.map +1 -1
  32. package/dist/ports/bulkhead.d.ts +28 -0
  33. package/dist/ports/bulkhead.d.ts.map +1 -0
  34. package/dist/ports/bulkhead.js +18 -0
  35. package/dist/ports/bulkhead.js.map +1 -0
  36. package/dist/ports/circuit-breaker.d.ts +62 -0
  37. package/dist/ports/circuit-breaker.d.ts.map +1 -0
  38. package/dist/ports/circuit-breaker.js +42 -0
  39. package/dist/ports/circuit-breaker.js.map +1 -0
  40. package/dist/ports/event-bus.d.ts +10 -0
  41. package/dist/ports/event-bus.d.ts.map +1 -1
  42. package/dist/ports/event-bus.js.map +1 -1
  43. package/dist/ports/flow-engine.d.ts +6 -0
  44. package/dist/ports/flow-engine.d.ts.map +1 -1
  45. package/dist/ports/flow-engine.js.map +1 -1
  46. package/dist/ports/participant-client.d.ts +32 -0
  47. package/dist/ports/participant-client.d.ts.map +1 -0
  48. package/dist/ports/participant-client.js +5 -0
  49. package/dist/ports/participant-client.js.map +1 -0
  50. package/dist/reactions/on.d.ts.map +1 -1
  51. package/dist/reactions/on.js +2 -1
  52. package/dist/reactions/on.js.map +1 -1
  53. package/package.json +3 -3
@@ -1,5 +1,6 @@
1
- import { type AudienceEntry, type DomainEvent } from '@entifix/core';
1
+ import { type AudienceEntry } from '@entifix/core';
2
2
  import { Schema } from 'effect';
3
+ import type { OutboxEvent } from './outbox.js';
3
4
  /** The four things a flow announces about itself. */
4
5
  export declare const FLOW_EVENTS: readonly ["flow.started", "flow.completed", "flow.failed", "flow.suspended"];
5
6
  export type FlowEventName = (typeof FLOW_EVENTS)[number];
@@ -47,5 +48,5 @@ export interface FlowEventInput {
47
48
  * the same message, `correlationId` the flow, the step ordinal as version, and
48
49
  * an audience that must not be empty.
49
50
  */
50
- export declare const flowEvent: (input: FlowEventInput) => DomainEvent<FlowEventData>;
51
+ export declare const flowEvent: (input: FlowEventInput) => OutboxEvent<FlowEventData>;
51
52
  //# sourceMappingURL=flow-messages.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"flow-messages.d.ts","sourceRoot":"","sources":["../../src/contracts/flow-messages.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,WAAW,EAI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AO,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC;AAQzD;;;;GAIG;AACH,eAAO,MAAM,aAAa;;;;;;;;;;EAOxB,CAAC;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,aAAa,CAAC,IAAI,CAAC;AAYtD;;;GAGG;AACH,eAAO,MAAM,YAAY;;;;;;EAQvB,CAAC;AACH,MAAM,MAAM,YAAY,GAAG,OAAO,YAAY,CAAC,IAAI,CAAC;AAIpD,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,2EAA2E;IAC3E,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,SAAS,aAAa,EAAE,CAAC;IAC5C,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC;CAC9B;AAED;;;;GAIG;AACH,eAAO,MAAM,SAAS,GACpB,OAAO,cAAc,KACpB,WAAW,CAAC,aAAa,CAU1B,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/flow-messages.ts"],"sourcesContent":["import {\n type AudienceEntry,\n type DomainEvent,\n openStruct,\n registerEvent,\n registerMessage,\n} from '@entifix/core';\nimport { Schema } from 'effect';\n\n/** The four things a flow announces about itself. */\nexport const FLOW_EVENTS = [\n 'flow.started',\n 'flow.completed',\n 'flow.failed',\n 'flow.suspended',\n] as const;\nexport type FlowEventName = (typeof FLOW_EVENTS)[number];\n\n/** A failure inside an asynchronous message: the problem's code and category. */\nconst FlowFailure = openStruct({\n code: Schema.NonEmptyString,\n category: Schema.NonEmptyString,\n});\n\n/**\n * What a `flow.*` event carries. A `flow.failed` without a failure, or with a\n * failure missing its `code` or `category`, does not decode: a client settling\n * a write must be able to translate why it failed.\n */\nexport const FlowEventData = Schema.Struct({\n flowId: Schema.String,\n definition: Schema.String,\n slipVersion: Schema.Number,\n step: Schema.optionalKey(Schema.String),\n outcome: Schema.optionalKey(Schema.Unknown),\n failure: Schema.optionalKey(FlowFailure),\n});\nexport type FlowEventData = typeof FlowEventData.Type;\n\nconst FlowFailedData = Schema.Struct({\n ...FlowEventData.fields,\n failure: FlowFailure,\n});\n\nfor (const name of FLOW_EVENTS)\n registerEvent(name, name === 'flow.failed' ? FlowFailedData : FlowEventData, {\n versioned: true,\n });\n\n/**\n * The `202` body a flow start answers: the flow's id, and where to watch it —\n * its status read and its stream.\n */\nexport const FlowAccepted = Schema.Struct({\n flowId: Schema.String,\n links: Schema.Array(\n Schema.Struct({\n rel: Schema.Literals(['status', 'stream']),\n href: Schema.String,\n }),\n ),\n});\nexport type FlowAccepted = typeof FlowAccepted.Type;\n\nregisterMessage('flowAccepted', FlowAccepted);\n\nexport interface FlowEventInput {\n readonly name: FlowEventName;\n readonly source: string;\n readonly at: string;\n /** The step this event is about, and its ordinal — the event's version. */\n readonly step: string;\n readonly ordinal: number;\n readonly audience: readonly AudienceEntry[];\n readonly data: FlowEventData;\n}\n\n/**\n * Builds a `flow.*` event: id `<flowId>:<step>` so a redelivered announce is\n * the same message, `correlationId` the flow, the step ordinal as version, and\n * an audience that must not be empty.\n */\nexport const flowEvent = (\n input: FlowEventInput,\n): DomainEvent<FlowEventData> => ({\n name: input.name,\n id: `${input.data.flowId}:${input.step}`,\n source: input.source,\n at: input.at,\n correlationId: input.data.flowId,\n aggregate: { type: 'flow', id: input.data.flowId },\n version: input.ordinal,\n audience: input.audience,\n data: input.data,\n});\n"],"names":["openStruct","registerEvent","registerMessage","Schema","FLOW_EVENTS","FlowFailure","code","NonEmptyString","category","FlowEventData","Struct","flowId","String","definition","slipVersion","Number","step","optionalKey","outcome","Unknown","failure","FlowFailedData","fields","name","versioned","FlowAccepted","links","Array","rel","Literals","href","flowEvent","input","id","data","source","at","correlationId","aggregate","type","version","ordinal","audience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AAIJ,MAAMI,EAAE;QACZC,eAAeL,MAAME,IAAI,CAACvB,MAAM;QAChC2B,WAAW;YAAEC,MAAM;YAAQN,IAAID,MAAME,IAAI,CAACvB,MAAM;QAAC;QACjD6B,SAASR,MAAMS,OAAO;QACtBC,UAAUV,MAAMU,QAAQ;QACxBR,MAAMF,MAAME,IAAI;IAClB,CAAA,EAAG"}
1
+ {"version":3,"sources":["../../src/contracts/flow-messages.ts"],"sourcesContent":["import {\n type AudienceEntry,\n openStruct,\n registerEvent,\n registerMessage,\n} from '@entifix/core';\nimport { Schema } from 'effect';\n\nimport type { OutboxEvent } from './outbox.js';\n\n/** The four things a flow announces about itself. */\nexport const FLOW_EVENTS = [\n 'flow.started',\n 'flow.completed',\n 'flow.failed',\n 'flow.suspended',\n] as const;\nexport type FlowEventName = (typeof FLOW_EVENTS)[number];\n\n/** A failure inside an asynchronous message: the problem's code and category. */\nconst FlowFailure = openStruct({\n code: Schema.NonEmptyString,\n category: Schema.NonEmptyString,\n});\n\n/**\n * What a `flow.*` event carries. A `flow.failed` without a failure, or with a\n * failure missing its `code` or `category`, does not decode: a client settling\n * a write must be able to translate why it failed.\n */\nexport const FlowEventData = Schema.Struct({\n flowId: Schema.String,\n definition: Schema.String,\n slipVersion: Schema.Number,\n step: Schema.optionalKey(Schema.String),\n outcome: Schema.optionalKey(Schema.Unknown),\n failure: Schema.optionalKey(FlowFailure),\n});\nexport type FlowEventData = typeof FlowEventData.Type;\n\nconst FlowFailedData = Schema.Struct({\n ...FlowEventData.fields,\n failure: FlowFailure,\n});\n\nfor (const name of FLOW_EVENTS)\n registerEvent(name, name === 'flow.failed' ? FlowFailedData : FlowEventData, {\n versioned: true,\n });\n\n/**\n * The `202` body a flow start answers: the flow's id, and where to watch it —\n * its status read and its stream.\n */\nexport const FlowAccepted = Schema.Struct({\n flowId: Schema.String,\n links: Schema.Array(\n Schema.Struct({\n rel: Schema.Literals(['status', 'stream']),\n href: Schema.String,\n }),\n ),\n});\nexport type FlowAccepted = typeof FlowAccepted.Type;\n\nregisterMessage('flowAccepted', FlowAccepted);\n\nexport interface FlowEventInput {\n readonly name: FlowEventName;\n readonly source: string;\n readonly at: string;\n /** The step this event is about, and its ordinal — the event's version. */\n readonly step: string;\n readonly ordinal: number;\n readonly audience: readonly AudienceEntry[];\n readonly data: FlowEventData;\n}\n\n/**\n * Builds a `flow.*` event: id `<flowId>:<step>` so a redelivered announce is\n * the same message, `correlationId` the flow, the step ordinal as version, and\n * an audience that must not be empty.\n */\nexport const flowEvent = (\n input: FlowEventInput,\n): OutboxEvent<FlowEventData> => ({\n name: input.name,\n id: `${input.data.flowId}:${input.step}`,\n source: input.source,\n at: input.at,\n correlationId: input.data.flowId,\n aggregate: { type: 'flow', id: input.data.flowId },\n version: input.ordinal,\n audience: input.audience,\n data: input.data,\n});\n"],"names":["openStruct","registerEvent","registerMessage","Schema","FLOW_EVENTS","FlowFailure","code","NonEmptyString","category","FlowEventData","Struct","flowId","String","definition","slipVersion","Number","step","optionalKey","outcome","Unknown","failure","FlowFailedData","fields","name","versioned","FlowAccepted","links","Array","rel","Literals","href","flowEvent","input","id","data","source","at","correlationId","aggregate","type","version","ordinal","audience"],"mappings":";AAAA,SAEEA,UAAU,EACVC,aAAa,EACbC,eAAe,QACV,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAIhC,mDAAmD,GACnD,OAAO,MAAMC,cAAc;IACzB;IACA;IACA;IACA;CACD,CAAU;AAGX,+EAA+E,GAC/E,MAAMC,cAAcL,WAAW;IAC7BM,MAAMH,OAAOI,cAAc;IAC3BC,UAAUL,OAAOI,cAAc;AACjC;AAEA;;;;CAIC,GACD,OAAO,MAAME,gBAAgBN,OAAOO,MAAM,CAAC;IACzCC,QAAQR,OAAOS,MAAM;IACrBC,YAAYV,OAAOS,MAAM;IACzBE,aAAaX,OAAOY,MAAM;IAC1BC,MAAMb,OAAOc,WAAW,CAACd,OAAOS,MAAM;IACtCM,SAASf,OAAOc,WAAW,CAACd,OAAOgB,OAAO;IAC1CC,SAASjB,OAAOc,WAAW,CAACZ;AAC9B,GAAG;AAGH,MAAMgB,iBAAiBlB,OAAOO,MAAM,CAAC,aAChCD,cAAca,MAAM;IACvBF,SAASf;;AAGX,KAAK,MAAMkB,QAAQnB,YACjBH,cAAcsB,MAAMA,SAAS,gBAAgBF,iBAAiBZ,eAAe;IAC3Ee,WAAW;AACb;AAEF;;;CAGC,GACD,OAAO,MAAMC,eAAetB,OAAOO,MAAM,CAAC;IACxCC,QAAQR,OAAOS,MAAM;IACrBc,OAAOvB,OAAOwB,KAAK,CACjBxB,OAAOO,MAAM,CAAC;QACZkB,KAAKzB,OAAO0B,QAAQ,CAAC;YAAC;YAAU;SAAS;QACzCC,MAAM3B,OAAOS,MAAM;IACrB;AAEJ,GAAG;AAGHV,gBAAgB,gBAAgBuB;AAahC;;;;CAIC,GACD,OAAO,MAAMM,YAAY,CACvBC,QACgC,CAAA;QAChCT,MAAMS,MAAMT,IAAI;QAChBU,IAAI,GAAGD,MAAME,IAAI,CAACvB,MAAM,CAAC,CAAC,EAAEqB,MAAMhB,IAAI,EAAE;QACxCmB,QAAQH,MAAMG,MAAM;QACpBC,IAAIJ,MAAMI,EAAE;QACZC,eAAeL,MAAME,IAAI,CAACvB,MAAM;QAChC2B,WAAW;YAAEC,MAAM;YAAQN,IAAID,MAAME,IAAI,CAACvB,MAAM;QAAC;QACjD6B,SAASR,MAAMS,OAAO;QACtBC,UAAUV,MAAMU,QAAQ;QACxBR,MAAMF,MAAME,IAAI;IAClB,CAAA,EAAG"}
@@ -152,5 +152,23 @@ export interface Outbox {
152
152
  declare const OutboxTag_base: Context.ServiceClass<OutboxTag, "@entifix/transactions/Outbox", Outbox>;
153
153
  export declare class OutboxTag extends OutboxTag_base {
154
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 {
172
+ }
155
173
  export {};
156
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,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;;;GAMG;AACH,MAAM,MAAM,WAAW,CAAC,KAAK,GAAG,OAAO,IAAI,WAAW,CAAC,KAAK,CAAC,GAAG;IAC9D,QAAQ,CAAC,SAAS,EAAE,YAAY,CAAC;IACjC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,6DAA6D;AAC7D,eAAO,MAAM,YAAY,GAAI,WAAW,YAAY,KAAG,MAClB,CAAC;AAEtC;;;;;;;;;;GAUG;AACH,MAAM,WAAW,WAAW;IAC1B;;;;;;;OAOG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB,+DAA+D;IAC/D,SAAS,EAAE,YAAY,CAAC;IACxB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,WAAW,CAAC;IACnB,IAAI,EAAE,OAAO,CAAC;IACd;;;;;;;OAOG;IACH,QAAQ,EAAE,MAAM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Y,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"}
@@ -2,5 +2,21 @@ import { Context } from 'effect';
2
2
  /** The key an outbox orders and blocks by: `<type>/<id>`. */ export const aggregateKey = (aggregate)=>`${aggregate.type}/${aggregate.id}`;
3
3
  export class OutboxTag extends Context.Service()('@entifix/transactions/Outbox') {
4
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') {
20
+ }
5
21
 
6
22
  //# sourceMappingURL=outbox.js.map
@@ -1 +1 @@
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"],"names":["Context","aggregateKey","aggregate","type","id","OutboxTag","Service"],"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"}
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"}
@@ -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
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/engine/in-memory-circuit-breaker.ts"],"sourcesContent":["import { isFailure } from '@entifix/core';\nimport { Cause, Effect, Exit, Layer, Metric } from 'effect';\n\nimport {\n BREAKER_STATE_VALUE,\n type BreakerDials,\n BreakerOpen,\n breakerRejections,\n type BreakerState,\n breakerState,\n breakerTransitions,\n type CircuitBreaker,\n CircuitBreakerTag,\n DEFAULT_BREAKER_DIALS,\n} from '../ports/circuit-breaker.js';\n\n/** One call's outcome, as the window holds it. */\ninterface Recorded {\n readonly at: number;\n readonly failed: boolean;\n readonly slow: boolean;\n}\n\ninterface Circuit {\n state: BreakerState;\n /** When it opened, and how long it waits — a `Retry-After` may lengthen it. */\n openedAt: number;\n waitMs: number;\n window: Recorded[];\n /** Half-open: probes let through, and their outcomes. */\n admitted: number;\n probes: Recorded[];\n}\n\nexport interface InMemoryCircuitBreakerOptions {\n /** Dials for every key, over the defaults. */\n readonly dials?: Partial<BreakerDials>;\n /** Dials for one key, over `dials` — a participant's own row. */\n readonly dialsFor?: (key: string) => Partial<BreakerDials> | undefined;\n /** The clock, in epoch milliseconds. Injected so a spec can move time. */\n readonly now?: () => number;\n}\n\n/** What a call's exit means to the window: a failure, a success, or neither. */\nconst verdictOf = (exit: Exit.Exit<unknown, unknown>) => {\n if (Exit.isSuccess(exit)) return { recorded: true, failed: false } as const;\n const failure = Cause.findErrorOption(exit.cause);\n if (failure._tag === 'None') return { recorded: false } as const;\n const error = failure.value;\n // An answer is not a failure of the dependency, and a protocol failure is a\n // bug that waiting does not fix: neither moves the breaker.\n if (!isFailure(error)) return { recorded: false } as const;\n if (error.family === 'business')\n return { recorded: true, failed: false } as const;\n if (error.category === 'protocol') return { recorded: false } as const;\n return { recorded: true, failed: true, failure: error } as const;\n};\n\n/** Seconds a dependency asked to be left alone for, when it said so. */\nconst retryAfterOf = (failure: unknown): number | undefined => {\n const seconds = (failure as { readonly retryAfterSeconds?: unknown })\n .retryAfterSeconds;\n return typeof seconds === 'number' && seconds > 0 ? seconds : undefined;\n};\n\nconst rates = (calls: readonly Recorded[]) => ({\n failure: calls.filter(call => call.failed).length / calls.length,\n slow: calls.filter(call => call.slow).length / calls.length,\n});\n\n/**\n * Per-process breakers, one per key, on Resilience4j's state machine\n * ([ADR 0017](../../../../../docs/adr/0017-circuit-breaker-and-bulkhead-ports.md)).\n *\n * Closed, every call is recorded in a count- or time-based window; once the\n * window holds `minimumCalls` and the failure or slow-call rate reaches its\n * threshold, the breaker opens. A dependency answering with `Retry-After` opens\n * it at once, for at least as long as it asked. Open, every call is refused\n * until `waitInOpenMs` has passed; then `halfOpenPermits` probes go through, and\n * their outcome closes or reopens it.\n *\n * Per process on purpose: a fleet-wide breaker would put a shared store on the\n * hot path, and per-process state converges within a window.\n */\nexport const makeInMemoryCircuitBreaker = (\n options: InMemoryCircuitBreakerOptions = {},\n): CircuitBreaker => {\n const now = options.now ?? Date.now;\n const circuits = new Map<string, Circuit>();\n const dialsOf = (key: string): BreakerDials => ({\n ...DEFAULT_BREAKER_DIALS,\n ...options.dials,\n ...options.dialsFor?.(key),\n });\n\n const circuitOf = (key: string): Circuit => {\n let circuit = circuits.get(key);\n if (circuit === undefined) {\n circuit = {\n state: 'closed',\n openedAt: 0,\n waitMs: 0,\n window: [],\n admitted: 0,\n probes: [],\n };\n circuits.set(key, circuit);\n }\n return circuit;\n };\n\n const report = (key: string, circuit: Circuit) =>\n Metric.update(\n Metric.withAttributes(breakerState, { key }),\n BREAKER_STATE_VALUE[circuit.state],\n );\n\n const move = (key: string, circuit: Circuit, to: BreakerState) => {\n const from = circuit.state;\n circuit.state = to;\n circuit.admitted = 0;\n circuit.probes = [];\n if (to === 'closed') circuit.window = [];\n return Metric.update(\n Metric.withAttributes(breakerTransitions, { key, from, to }),\n 1,\n ).pipe(Effect.andThen(report(key, circuit)));\n };\n\n const open = (key: string, circuit: Circuit, waitMs: number) => {\n circuit.openedAt = now();\n circuit.waitMs = waitMs;\n return move(key, circuit, 'open');\n };\n\n /** An open breaker whose wait has passed is half-open, read lazily. */\n const settle = (key: string, circuit: Circuit) =>\n circuit.state === 'open' && now() - circuit.openedAt >= circuit.waitMs\n ? move(key, circuit, 'halfOpen')\n : Effect.void;\n\n const trimmed = (window: Recorded[], dials: BreakerDials): Recorded[] =>\n dials.windowType === 'count'\n ? window.slice(-dials.windowSize)\n : window.filter(call => now() - call.at < dials.windowSize * 1_000);\n\n const record = (\n key: string,\n circuit: Circuit,\n call: Recorded,\n failure: unknown,\n ) =>\n Effect.suspend(() => {\n const dials = dialsOf(key);\n const retryAfter = call.failed ? retryAfterOf(failure) : undefined;\n if (retryAfter !== undefined && circuit.state !== 'disabled')\n return open(\n key,\n circuit,\n Math.max(dials.waitInOpenMs, retryAfter * 1_000),\n );\n\n if (circuit.state === 'halfOpen') {\n circuit.probes.push(call);\n if (circuit.probes.length < dials.halfOpenPermits) return Effect.void;\n const probed = rates(circuit.probes);\n return probed.failure >= dials.failureRateThreshold ||\n probed.slow >= dials.slowCallRateThreshold\n ? open(key, circuit, dials.waitInOpenMs)\n : move(key, circuit, 'closed');\n }\n\n if (circuit.state !== 'closed') return Effect.void;\n circuit.window = trimmed([...circuit.window, call], dials);\n if (circuit.window.length < dials.minimumCalls) return Effect.void;\n const windowed = rates(circuit.window);\n return windowed.failure >= dials.failureRateThreshold ||\n windowed.slow >= dials.slowCallRateThreshold\n ? open(key, circuit, dials.waitInOpenMs)\n : Effect.void;\n });\n\n const refuse = (key: string) =>\n Metric.update(Metric.withAttributes(breakerRejections, { key }), 1).pipe(\n Effect.andThen(Effect.fail(new BreakerOpen({ dependency: key }))),\n );\n\n return {\n guard:\n key =>\n <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n Effect.gen(function* () {\n const circuit = circuitOf(key);\n yield* settle(key, circuit);\n if (circuit.state === 'disabled') return yield* effect;\n if (circuit.state === 'open' || circuit.state === 'forcedOpen')\n return yield* refuse(key);\n if (circuit.state === 'halfOpen') {\n const dials = dialsOf(key);\n if (circuit.admitted >= dials.halfOpenPermits)\n return yield* refuse(key);\n circuit.admitted += 1;\n }\n\n const startedAt = now();\n const exit = yield* Effect.exit(effect);\n const verdict = verdictOf(exit);\n if (verdict.recorded)\n yield* record(\n key,\n circuit,\n {\n at: startedAt,\n failed: verdict.failed,\n slow: now() - startedAt > dialsOf(key).slowCallDurationMs,\n },\n verdict.failed ? verdict.failure : undefined,\n );\n return yield* exit;\n }),\n\n state: key =>\n Effect.gen(function* () {\n const circuit = circuitOf(key);\n yield* settle(key, circuit);\n return circuit.state;\n }),\n\n force: (key, state) =>\n Effect.suspend(() => move(key, circuitOf(key), state)),\n };\n};\n\n/** One breaker set for the process, for the composition root. */\nexport const InMemoryCircuitBreakerLayer = (\n options: InMemoryCircuitBreakerOptions = {},\n) => Layer.sync(CircuitBreakerTag, () => makeInMemoryCircuitBreaker(options));\n"],"names":["isFailure","Cause","Effect","Exit","Layer","Metric","BREAKER_STATE_VALUE","BreakerOpen","breakerRejections","breakerState","breakerTransitions","CircuitBreakerTag","DEFAULT_BREAKER_DIALS","verdictOf","exit","isSuccess","recorded","failed","failure","findErrorOption","cause","_tag","error","value","family","category","retryAfterOf","seconds","retryAfterSeconds","undefined","rates","calls","filter","call","length","slow","makeInMemoryCircuitBreaker","options","now","Date","circuits","Map","dialsOf","key","dials","dialsFor","circuitOf","circuit","get","state","openedAt","waitMs","window","admitted","probes","set","report","update","withAttributes","move","to","from","pipe","andThen","open","settle","void","trimmed","windowType","slice","windowSize","at","record","suspend","retryAfter","Math","max","waitInOpenMs","push","halfOpenPermits","probed","failureRateThreshold","slowCallRateThreshold","minimumCalls","windowed","refuse","fail","dependency","guard","effect","gen","startedAt","verdict","slowCallDurationMs","force","InMemoryCircuitBreakerLayer","sync"],"mappings":";AAAA,SAASA,SAAS,QAAQ,gBAAgB;AAC1C,SAASC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,MAAM,QAAQ,SAAS;AAE5D,SACEC,mBAAmB,EAEnBC,WAAW,EACXC,iBAAiB,EAEjBC,YAAY,EACZC,kBAAkB,EAElB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B,KAAKI;gBACnB,OAAOA,QAAQE,KAAK;YACtB;QAEF6C,OAAO,CAACnD,KAAKM,QACX/C,OAAOuE,OAAO,CAAC,IAAMd,KAAKhB,KAAKG,UAAUH,MAAMM;IACnD;AACF,EAAE;AAEF,+DAA+D,GAC/D,OAAO,MAAM8C,8BAA8B,CACzC1D,UAAyC,CAAC,CAAC,GACxCjC,MAAM4F,IAAI,CAACrF,mBAAmB,IAAMyB,2BAA2BC,UAAU"}
@@ -9,8 +9,12 @@
9
9
  * specifier (ADR 0006).
10
10
  */
11
11
  export * from '../stream/transaction-stream-hub.js';
12
+ export * from './in-memory-bulkhead.js';
13
+ export * from './in-memory-circuit-breaker.js';
12
14
  export * from './in-memory-retry-budget.js';
13
15
  export * from './local-saga-dispatcher.js';
16
+ export * from './outbox-metrics.js';
17
+ export * from './outbox-relay.js';
14
18
  export * from './resolve-template.js';
15
19
  export * from './resume-sweep.js';
16
20
  export * from './run-saga.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/engine/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,cAAc,qCAAqC,CAAC;AACpD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC;AAC9B,cAAc,sBAAsB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/engine/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,cAAc,qCAAqC,CAAC;AACpD,cAAc,yBAAyB,CAAC;AACxC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC;AAC9B,cAAc,sBAAsB,CAAC"}
@@ -8,8 +8,12 @@
8
8
  * participant — must be able to ban the engine by name, and a ban matches a
9
9
  * specifier (ADR 0006).
10
10
  */ export * from '../stream/transaction-stream-hub.js';
11
+ export * from './in-memory-bulkhead.js';
12
+ export * from './in-memory-circuit-breaker.js';
11
13
  export * from './in-memory-retry-budget.js';
12
14
  export * from './local-saga-dispatcher.js';
15
+ export * from './outbox-metrics.js';
16
+ export * from './outbox-relay.js';
13
17
  export * from './resolve-template.js';
14
18
  export * from './resume-sweep.js';
15
19
  export * from './run-saga.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/engine/index.ts"],"sourcesContent":["/**\n * The mechanism behind `@entifix/transactions`' ports: the saga runner and its\n * resume sweep, the single-step transaction engine, the in-process dispatcher\n * and the stream hub.\n *\n * A subpath rather than part of `.` although it installs nothing `.` does not,\n * because a consumer that writes against the contracts — a cell, a route, a\n * participant — must be able to ban the engine by name, and a ban matches a\n * specifier (ADR 0006).\n */\nexport * from '../stream/transaction-stream-hub.js';\nexport * from './in-memory-retry-budget.js';\nexport * from './local-saga-dispatcher.js';\nexport * from './resolve-template.js';\nexport * from './resume-sweep.js';\nexport * from './run-saga.js';\nexport * from './run-transaction.js';\n"],"names":[],"mappings":"AAAA;;;;;;;;;CASC,GACD,cAAc,sCAAsC;AACpD,cAAc,8BAA8B;AAC5C,cAAc,6BAA6B;AAC3C,cAAc,wBAAwB;AACtC,cAAc,oBAAoB;AAClC,cAAc,gBAAgB;AAC9B,cAAc,uBAAuB"}
1
+ {"version":3,"sources":["../../src/engine/index.ts"],"sourcesContent":["/**\n * The mechanism behind `@entifix/transactions`' ports: the saga runner and its\n * resume sweep, the single-step transaction engine, the in-process dispatcher\n * and the stream hub.\n *\n * A subpath rather than part of `.` although it installs nothing `.` does not,\n * because a consumer that writes against the contracts — a cell, a route, a\n * participant — must be able to ban the engine by name, and a ban matches a\n * specifier (ADR 0006).\n */\nexport * from '../stream/transaction-stream-hub.js';\nexport * from './in-memory-bulkhead.js';\nexport * from './in-memory-circuit-breaker.js';\nexport * from './in-memory-retry-budget.js';\nexport * from './local-saga-dispatcher.js';\nexport * from './outbox-metrics.js';\nexport * from './outbox-relay.js';\nexport * from './resolve-template.js';\nexport * from './resume-sweep.js';\nexport * from './run-saga.js';\nexport * from './run-transaction.js';\n"],"names":[],"mappings":"AAAA;;;;;;;;;CASC,GACD,cAAc,sCAAsC;AACpD,cAAc,0BAA0B;AACxC,cAAc,iCAAiC;AAC/C,cAAc,8BAA8B;AAC5C,cAAc,6BAA6B;AAC3C,cAAc,sBAAsB;AACpC,cAAc,oBAAoB;AAClC,cAAc,wBAAwB;AACtC,cAAc,oBAAoB;AAClC,cAAc,gBAAgB;AAC9B,cAAc,uBAAuB"}
@@ -0,0 +1,47 @@
1
+ import { Effect, Metric } from 'effect';
2
+ import type { OutboxStats } from '../contracts/outbox.js';
3
+ /**
4
+ * The outbox half of the framework's first metric set; the bus half is in
5
+ * `@entifix/amqp`.
6
+ *
7
+ * It lives beside the relay that samples it rather than in any one service,
8
+ * because three slices now own an outbox — `catalog`, `order` and `payment` —
9
+ * and the warning below is exactly why a copy per service is not an option: an
10
+ * Effect metric is keyed on its **description**, so three hand-maintained
11
+ * definitions of `outbox_pending_entries` are three series the moment one
12
+ * wording drifts, and a dashboard would go quiet without failing anything.
13
+ *
14
+ * ⚠️ The metric objects are **exported so a reader uses the same instance**. An
15
+ * Effect metric's registry key includes its description, so rebuilding one by
16
+ * name without the description addresses a different series that is permanently
17
+ * zero — a silent way to write a query against nothing.
18
+ *
19
+ * These are gauges rather than counters because they describe a *backlog*: the
20
+ * question is how many are waiting right now, not how many there have ever
21
+ * been. They are sampled by the two daemons that already run on an interval, so
22
+ * nothing new is scheduled to produce them.
23
+ *
24
+ * ⚠️ **A dimensionless gauge reaches Prometheus with a `_ratio` suffix.** That
25
+ * is the OTel exporter's convention for unit `1`, not a mistake here, so
26
+ * `outbox_pending_entries` is queried as `outbox_pending_entries_ratio`.
27
+ * Counters are unaffected. Where a metric has a real unit, tag it — see
28
+ * {@link outboxOldestPendingAge}.
29
+ */
30
+ /** Unsent, un-quarantined entries, per database. */
31
+ export declare const outboxPending: Metric.Gauge<number>;
32
+ /**
33
+ * Age in seconds of the oldest unsent entry, per database.
34
+ *
35
+ * **The metric that makes a stuck relay visible.** Quarantine gave the relay a
36
+ * ceiling, so an entry that can never publish is quarantined and skipped rather
37
+ * than blocking the head of the line forever — but that is reported only as a
38
+ * log line, so how far behind the outbox has fallen is otherwise unanswerable.
39
+ * A depth that is flat and an age that climbs is the signature of a relay whose
40
+ * head has stopped moving.
41
+ */
42
+ export declare const outboxOldestPendingAge: Metric.Gauge<number>;
43
+ /** Entries past the ceiling, which nothing retries and nothing deletes. */
44
+ export declare const outboxQuarantined: Metric.Gauge<number>;
45
+ /** Record one outbox's depth and age. */
46
+ export declare const recordOutboxStats: (database: string, stats: OutboxStats) => Effect.Effect<void, never, never>;
47
+ //# sourceMappingURL=outbox-metrics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outbox-metrics.d.ts","sourceRoot":"","sources":["../../src/engine/outbox-metrics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAExC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,oDAAoD;AACpD,eAAO,MAAM,aAAa,sBAExB,CAAC;AAEH;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB,EAAE,MAAM,CAAC,KAAK,CAAC,MAAM,CAkBvD,CAAC;AAEF,2EAA2E;AAC3E,eAAO,MAAM,iBAAiB,sBAE5B,CAAC;AAEH,yCAAyC;AACzC,eAAO,MAAM,iBAAiB,GAAI,UAAU,MAAM,EAAE,OAAO,WAAW,sCAgBrE,CAAC"}
@@ -0,0 +1,68 @@
1
+ import { Effect, Metric } from 'effect';
2
+ /**
3
+ * The outbox half of the framework's first metric set; the bus half is in
4
+ * `@entifix/amqp`.
5
+ *
6
+ * It lives beside the relay that samples it rather than in any one service,
7
+ * because three slices now own an outbox — `catalog`, `order` and `payment` —
8
+ * and the warning below is exactly why a copy per service is not an option: an
9
+ * Effect metric is keyed on its **description**, so three hand-maintained
10
+ * definitions of `outbox_pending_entries` are three series the moment one
11
+ * wording drifts, and a dashboard would go quiet without failing anything.
12
+ *
13
+ * ⚠️ The metric objects are **exported so a reader uses the same instance**. An
14
+ * Effect metric's registry key includes its description, so rebuilding one by
15
+ * name without the description addresses a different series that is permanently
16
+ * zero — a silent way to write a query against nothing.
17
+ *
18
+ * These are gauges rather than counters because they describe a *backlog*: the
19
+ * question is how many are waiting right now, not how many there have ever
20
+ * been. They are sampled by the two daemons that already run on an interval, so
21
+ * nothing new is scheduled to produce them.
22
+ *
23
+ * ⚠️ **A dimensionless gauge reaches Prometheus with a `_ratio` suffix.** That
24
+ * is the OTel exporter's convention for unit `1`, not a mistake here, so
25
+ * `outbox_pending_entries` is queried as `outbox_pending_entries_ratio`.
26
+ * Counters are unaffected. Where a metric has a real unit, tag it — see
27
+ * {@link outboxOldestPendingAge}.
28
+ */ /** Unsent, un-quarantined entries, per database. */ export const outboxPending = Metric.gauge('outbox_pending_entries', {
29
+ description: 'Unsent, un-quarantined outbox entries, by database.'
30
+ });
31
+ /**
32
+ * Age in seconds of the oldest unsent entry, per database.
33
+ *
34
+ * **The metric that makes a stuck relay visible.** Quarantine gave the relay a
35
+ * ceiling, so an entry that can never publish is quarantined and skipped rather
36
+ * than blocking the head of the line forever — but that is reported only as a
37
+ * log line, so how far behind the outbox has fallen is otherwise unanswerable.
38
+ * A depth that is flat and an age that climbs is the signature of a relay whose
39
+ * head has stopped moving.
40
+ */ export const outboxOldestPendingAge = Metric.gauge('outbox_oldest_pending_age', {
41
+ description: 'Age of the oldest unsent outbox entry, by database. Zero when ' + 'the outbox is empty.'
42
+ }).pipe(// ⚠️ **The unit is carried as a tag, and that is the only way to set it.**
43
+ // `@effect/opentelemetry`'s producer reads `tags.unit ?? tags.time_unit ??
44
+ // '1'`, so a gauge with no `unit` tag is exported as dimensionless — and the
45
+ // Prometheus exporter then appends `_ratio` to a dimensionless gauge's name.
46
+ // Measured: this series arrived as `outbox_oldest_pending_age_seconds_ratio`,
47
+ // a duration announcing itself as a ratio. Tagging it makes the exporter name
48
+ // it `_seconds`, which is why the name above no longer carries that suffix
49
+ // itself. The cost is a constant `unit` label, because the producer builds the
50
+ // datapoint attributes from the same tag set it reads the unit from.
51
+ Metric.withAttributes({
52
+ unit: 's'
53
+ }));
54
+ /** Entries past the ceiling, which nothing retries and nothing deletes. */ export const outboxQuarantined = Metric.gauge('outbox_quarantined_entries', {
55
+ description: 'Quarantined outbox entries, by database.'
56
+ });
57
+ /** Record one outbox's depth and age. */ export const recordOutboxStats = (database, stats)=>{
58
+ const tagged = (metric)=>Metric.withAttributes(metric, {
59
+ database
60
+ });
61
+ // Zero when nothing is waiting. The alternative — not reporting the series —
62
+ // reads on most dashboards as "no data", which is indistinguishable from the
63
+ // exporter having broken at exactly the moment a healthy relay looks idle.
64
+ const ageSeconds = stats.oldestPendingAt === undefined ? 0 : Math.max(0, (Date.now() - Date.parse(stats.oldestPendingAt)) / 1000);
65
+ return Metric.update(tagged(outboxPending), stats.pending).pipe(Effect.andThen(Metric.update(tagged(outboxOldestPendingAge), ageSeconds)), Effect.andThen(Metric.update(tagged(outboxQuarantined), stats.quarantined)));
66
+ };
67
+
68
+ //# sourceMappingURL=outbox-metrics.js.map