@entifix/mongo 0.10.2 → 0.11.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.
@@ -0,0 +1,24 @@
1
+ import type { IdempotencyStore } from '@entifix/business';
2
+ import { Effect } from 'effect';
3
+ import type { Db } from 'mongodb';
4
+ /**
5
+ * Where a route remembers the requests it answered under an `Idempotency-Key`,
6
+ * in the database its own writes go to.
7
+ */
8
+ export declare const IDEMPOTENCY_COLLECTION = "idempotency";
9
+ /**
10
+ * The unique index the claim rides, and the TTL index that reaps an expired
11
+ * record. The TTL monitor runs about once a minute, so a record can outlive
12
+ * `expiresAt` briefly — which is why a claim also treats an expired record it
13
+ * meets as absent rather than trusting the reaper.
14
+ */
15
+ export declare const ensureIdempotencyIndexes: (db: Db) => Effect.Effect<void, import("@entifix/core").StoreFailure, never>;
16
+ export interface MongoIdempotencyOptions {
17
+ /** How long a record lives, in milliseconds — a dial from the composition root. */
18
+ readonly retentionMs: number;
19
+ /** The clock, in epoch milliseconds. */
20
+ readonly now?: () => number;
21
+ }
22
+ /** Mongo-backed {@link IdempotencyStore} over one database. */
23
+ export declare const makeMongoIdempotencyStore: (db: Db, { retentionMs, now }: MongoIdempotencyOptions) => IdempotencyStore;
24
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/idempotency/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,gBAAgB,EAEjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAIlC;;;GAGG;AACH,eAAO,MAAM,sBAAsB,gBAAgB,CAAC;AA8BpD;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,GAAI,IAAI,EAAE,qEAQ3C,CAAC;AAEL,MAAM,WAAW,uBAAuB;IACtC,mFAAmF;IACnF,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,wCAAwC;IACxC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC7B;AAED,+DAA+D;AAC/D,eAAO,MAAM,yBAAyB,GACpC,IAAI,EAAE,EACN,sBAAiC,uBAAuB,KACvD,gBA0DF,CAAC"}
@@ -0,0 +1,115 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ import { Effect } from 'effect';
3
+ import { translateMongoError } from '../errors/translate-mongo-error.js';
4
+ /**
5
+ * Where a route remembers the requests it answered under an `Idempotency-Key`,
6
+ * in the database its own writes go to.
7
+ */ export const IDEMPOTENCY_COLLECTION = 'idempotency';
8
+ const toRecord = ({ dedupKey, fingerprint, state, response, expiresAt })=>_extends({
9
+ dedupKey,
10
+ fingerprint,
11
+ state
12
+ }, response === undefined ? {} : {
13
+ response
14
+ }, {
15
+ expiresAt: expiresAt.toISOString()
16
+ });
17
+ const isDuplicateKey = (error)=>typeof error === 'object' && error !== null && error.code === 11000;
18
+ /**
19
+ * The unique index the claim rides, and the TTL index that reaps an expired
20
+ * record. The TTL monitor runs about once a minute, so a record can outlive
21
+ * `expiresAt` briefly — which is why a claim also treats an expired record it
22
+ * meets as absent rather than trusting the reaper.
23
+ */ export const ensureIdempotencyIndexes = (db)=>Effect.tryPromise({
24
+ try: async ()=>{
25
+ const collection = db.collection(IDEMPOTENCY_COLLECTION);
26
+ await collection.createIndex({
27
+ dedupKey: 1
28
+ }, {
29
+ unique: true
30
+ });
31
+ await collection.createIndex({
32
+ expiresAt: 1
33
+ }, {
34
+ expireAfterSeconds: 0
35
+ });
36
+ },
37
+ catch: (error)=>translateMongoError(error)
38
+ });
39
+ /** Mongo-backed {@link IdempotencyStore} over one database. */ export const makeMongoIdempotencyStore = (db, { retentionMs, now = Date.now })=>{
40
+ const collection = db.collection(IDEMPOTENCY_COLLECTION);
41
+ const fresh = (dedupKey, fingerprint)=>({
42
+ dedupKey,
43
+ fingerprint,
44
+ state: 'inFlight',
45
+ expiresAt: new Date(now() + retentionMs)
46
+ });
47
+ return {
48
+ claim: (dedupKey, fingerprint)=>Effect.tryPromise({
49
+ try: async ()=>{
50
+ try {
51
+ await collection.insertOne(fresh(dedupKey, fingerprint));
52
+ return {
53
+ _tag: 'claimed'
54
+ };
55
+ } catch (error) {
56
+ if (!isDuplicateKey(error)) throw error;
57
+ }
58
+ // Taken. An expired holder is replaced by a conditional write, so of
59
+ // two requests meeting one expired record exactly one gets the key.
60
+ const replaced = await collection.updateOne({
61
+ dedupKey,
62
+ expiresAt: {
63
+ $lte: new Date(now())
64
+ }
65
+ }, {
66
+ $set: fresh(dedupKey, fingerprint),
67
+ $unset: {
68
+ response: ''
69
+ }
70
+ });
71
+ if (replaced.modifiedCount === 1) return {
72
+ _tag: 'claimed'
73
+ };
74
+ const existing = await collection.findOne({
75
+ dedupKey
76
+ }, {
77
+ projection: {
78
+ _id: 0
79
+ }
80
+ });
81
+ if (existing !== null) return {
82
+ _tag: 'existing',
83
+ record: toRecord(existing)
84
+ };
85
+ // Released between the insert and this read: the key is free again.
86
+ // One more insert takes it; losing that race too surfaces as the
87
+ // duplicate key it is, not as a claim nobody holds.
88
+ await collection.insertOne(fresh(dedupKey, fingerprint));
89
+ return {
90
+ _tag: 'claimed'
91
+ };
92
+ },
93
+ catch: (error)=>translateMongoError(error)
94
+ }),
95
+ complete: (dedupKey, response)=>Effect.tryPromise({
96
+ try: ()=>collection.updateOne({
97
+ dedupKey
98
+ }, {
99
+ $set: {
100
+ state: 'completed',
101
+ response
102
+ }
103
+ }),
104
+ catch: (error)=>translateMongoError(error)
105
+ }).pipe(Effect.asVoid),
106
+ release: (dedupKey)=>Effect.tryPromise({
107
+ try: ()=>collection.deleteOne({
108
+ dedupKey
109
+ }),
110
+ catch: (error)=>translateMongoError(error)
111
+ }).pipe(Effect.asVoid)
112
+ };
113
+ };
114
+
115
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/idempotency/store.ts"],"sourcesContent":["import type {\n IdempotencyClaim,\n IdempotencyRecord,\n IdempotencyStore,\n StoredResponse,\n} from '@entifix/business';\nimport { Effect } from 'effect';\nimport type { Db } from 'mongodb';\n\nimport { translateMongoError } from '../errors/translate-mongo-error.js';\n\n/**\n * Where a route remembers the requests it answered under an `Idempotency-Key`,\n * in the database its own writes go to.\n */\nexport const IDEMPOTENCY_COLLECTION = 'idempotency';\n\n/** The stored shape: `expiresAt` is a `Date`, which is what a TTL index reads. */\ninterface IdempotencyDocument {\n readonly dedupKey: string;\n readonly fingerprint: string;\n readonly state: 'inFlight' | 'completed';\n readonly response?: StoredResponse;\n readonly expiresAt: Date;\n}\n\nconst toRecord = ({\n dedupKey,\n fingerprint,\n state,\n response,\n expiresAt,\n}: IdempotencyDocument): IdempotencyRecord => ({\n dedupKey,\n fingerprint,\n state,\n ...(response === undefined ? {} : { response }),\n expiresAt: expiresAt.toISOString(),\n});\n\nconst isDuplicateKey = (error: unknown): boolean =>\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === 11000;\n\n/**\n * The unique index the claim rides, and the TTL index that reaps an expired\n * record. The TTL monitor runs about once a minute, so a record can outlive\n * `expiresAt` briefly — which is why a claim also treats an expired record it\n * meets as absent rather than trusting the reaper.\n */\nexport const ensureIdempotencyIndexes = (db: Db) =>\n Effect.tryPromise({\n try: async () => {\n const collection = db.collection(IDEMPOTENCY_COLLECTION);\n await collection.createIndex({ dedupKey: 1 }, { unique: true });\n await collection.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });\n },\n catch: error => translateMongoError(error),\n });\n\nexport interface MongoIdempotencyOptions {\n /** How long a record lives, in milliseconds — a dial from the composition root. */\n readonly retentionMs: number;\n /** The clock, in epoch milliseconds. */\n readonly now?: () => number;\n}\n\n/** Mongo-backed {@link IdempotencyStore} over one database. */\nexport const makeMongoIdempotencyStore = (\n db: Db,\n { retentionMs, now = Date.now }: MongoIdempotencyOptions,\n): IdempotencyStore => {\n const collection = db.collection<IdempotencyDocument>(IDEMPOTENCY_COLLECTION);\n const fresh = (\n dedupKey: string,\n fingerprint: string,\n ): IdempotencyDocument => ({\n dedupKey,\n fingerprint,\n state: 'inFlight',\n expiresAt: new Date(now() + retentionMs),\n });\n\n return {\n claim: (dedupKey, fingerprint) =>\n Effect.tryPromise({\n try: async (): Promise<IdempotencyClaim> => {\n try {\n await collection.insertOne(fresh(dedupKey, fingerprint));\n return { _tag: 'claimed' };\n } catch (error) {\n if (!isDuplicateKey(error)) throw error;\n }\n // Taken. An expired holder is replaced by a conditional write, so of\n // two requests meeting one expired record exactly one gets the key.\n const replaced = await collection.updateOne(\n { dedupKey, expiresAt: { $lte: new Date(now()) } },\n { $set: fresh(dedupKey, fingerprint), $unset: { response: '' } },\n );\n if (replaced.modifiedCount === 1) return { _tag: 'claimed' };\n const existing = await collection.findOne(\n { dedupKey },\n { projection: { _id: 0 } },\n );\n if (existing !== null)\n return { _tag: 'existing', record: toRecord(existing) };\n // Released between the insert and this read: the key is free again.\n // One more insert takes it; losing that race too surfaces as the\n // duplicate key it is, not as a claim nobody holds.\n await collection.insertOne(fresh(dedupKey, fingerprint));\n return { _tag: 'claimed' };\n },\n catch: error => translateMongoError(error),\n }),\n complete: (dedupKey, response) =>\n Effect.tryPromise({\n try: () =>\n collection.updateOne(\n { dedupKey },\n { $set: { state: 'completed', response } },\n ),\n catch: error => translateMongoError(error),\n }).pipe(Effect.asVoid),\n release: dedupKey =>\n Effect.tryPromise({\n try: () => collection.deleteOne({ dedupKey }),\n catch: error => translateMongoError(error),\n }).pipe(Effect.asVoid),\n };\n};\n"],"names":["Effect","translateMongoError","IDEMPOTENCY_COLLECTION","toRecord","dedupKey","fingerprint","state","response","expiresAt","undefined","toISOString","isDuplicateKey","error","code","ensureIdempotencyIndexes","db","tryPromise","try","collection","createIndex","unique","expireAfterSeconds","catch","makeMongoIdempotencyStore","retentionMs","now","Date","fresh","claim","insertOne","_tag","replaced","updateOne","$lte","$set","$unset","modifiedCount","existing","findOne","projection","_id","record","complete","pipe","asVoid","release","deleteOne"],"mappings":";AAMA,SAASA,MAAM,QAAQ,SAAS;AAGhC,SAASC,mBAAmB,QAAQ,qCAAqC;AAEzE;;;CAGC,GACD,OAAO,MAAMC,yBAAyB,cAAc;AAWpD,MAAMC,WAAW,CAAC,EAChBC,QAAQ,EACRC,WAAW,EACXC,KAAK,EACLC,QAAQ,EACRC,SAAS,EACW,GAAyB;QAC7CJ;QACAC;QACAC;OACIC,aAAaE,YAAY,CAAC,IAAI;QAAEF;IAAS;QAC7CC,WAAWA,UAAUE,WAAW;;AAGlC,MAAMC,iBAAiB,CAACC,QACtB,OAAOA,UAAU,YACjBA,UAAU,QACV,AAACA,MAA6BC,IAAI,KAAK;AAEzC;;;;;CAKC,GACD,OAAO,MAAMC,2BAA2B,CAACC,KACvCf,OAAOgB,UAAU,CAAC;QAChBC,KAAK;YACH,MAAMC,aAAaH,GAAGG,UAAU,CAAChB;YACjC,MAAMgB,WAAWC,WAAW,CAAC;gBAAEf,UAAU;YAAE,GAAG;gBAAEgB,QAAQ;YAAK;YAC7D,MAAMF,WAAWC,WAAW,CAAC;gBAAEX,WAAW;YAAE,GAAG;gBAAEa,oBAAoB;YAAE;QACzE;QACAC,OAAOV,CAAAA,QAASX,oBAAoBW;IACtC,GAAG;AASL,6DAA6D,GAC7D,OAAO,MAAMW,4BAA4B,CACvCR,IACA,EAAES,WAAW,EAAEC,MAAMC,KAAKD,GAAG,EAA2B;IAExD,MAAMP,aAAaH,GAAGG,UAAU,CAAsBhB;IACtD,MAAMyB,QAAQ,CACZvB,UACAC,cACyB,CAAA;YACzBD;YACAC;YACAC,OAAO;YACPE,WAAW,IAAIkB,KAAKD,QAAQD;QAC9B,CAAA;IAEA,OAAO;QACLI,OAAO,CAACxB,UAAUC,cAChBL,OAAOgB,UAAU,CAAC;gBAChBC,KAAK;oBACH,IAAI;wBACF,MAAMC,WAAWW,SA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+B,IAAI,CAAC3C,OAAO4C,MAAM;IACzB;AACF,EAAE"}
@@ -1,5 +1,5 @@
1
1
  import { ShutdownRegistryTag, type TenantDirectory, TenantDirectoryTag } from '@entifix/business';
2
- import { type EventBus, EventBusTag, type OutboxStats, type TransactionOutbox } from '@entifix/transactions';
2
+ import { type EventBus, EventBusTag, type Outbox, type OutboxStats } from '@entifix/transactions';
3
3
  import { Context, Duration, Effect } from 'effect';
4
4
  import type { Db } from 'mongodb';
5
5
  import { MongoDatabaseTag } from '../mongo-database/mongo-database.js';
@@ -69,18 +69,19 @@ export interface DrainOptions {
69
69
  readonly onOutcome?: RelayOutcomeSink;
70
70
  }
71
71
  /**
72
- * Publish one batch of pending entries, oldest first, and answer how many went.
72
+ * Publish one batch of pending entries, oldest first, **in order within each
73
+ * aggregate** ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)),
74
+ * and answer how many went.
73
75
  *
74
- * Two orderings are load-bearing here and neither is obvious:
75
- *
76
- * - A **still-deliverable** failure returns immediately rather than continuing.
77
- * The entries behind this one keep their order relative to it, which is what
78
- * stops a terminal event overtaking the `accepted` for the same transaction.
79
- * - A **quarantined** failure continues. That is the deliberate
80
- * skip-so-the-head-moves: an entry that can never publish must stop blocking
81
- * every entry behind it forever.
76
+ * - A **still-deliverable** failure holds back the rest of its own aggregate
77
+ * for this pass, which is what stops a terminal event overtaking the
78
+ * `accepted` of the same transaction — and only its own: every other
79
+ * aggregate keeps draining.
80
+ * - A **quarantined** failure moves on. An entry that can never publish must
81
+ * not hold its aggregate forever, and a consumer discards whatever older
82
+ * version arrives after a newer one anyway.
82
83
  */
83
- export declare const drainOutbox: (outbox: TransactionOutbox, bus: EventBus, options: DrainOptions) => Effect.Effect<number, import("@entifix/core").StoreFailure, never>;
84
+ export declare const drainOutbox: (outbox: Outbox, bus: EventBus, options: DrainOptions) => Effect.Effect<number, import("@entifix/core").StoreFailure, never>;
84
85
  /**
85
86
  * Sample a sweep's depth and age.
86
87
  *
@@ -104,7 +105,7 @@ export type OutboxStatsSink = (database: string, stats: OutboxStats) => Effect.E
104
105
  * `Effect.forever`, and an error that escapes ends the daemon silently — a
105
106
  * relay that stopped is indistinguishable from a relay with nothing to do.
106
107
  */
107
- export declare const sweepOutbox: (outbox: TransactionOutbox, bus: EventBus, options: DrainOptions & {
108
+ export declare const sweepOutbox: (outbox: Outbox, bus: EventBus, options: DrainOptions & {
108
109
  readonly onStats?: OutboxStatsSink;
109
110
  }) => Effect.Effect<void, never, never>;
110
111
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"relay.d.ts","sourceRoot":"","sources":["../../src/outbox/relay.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,KAAK,eAAe,EACpB,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,KAAK,QAAQ,EACb,WAAW,EACX,KAAK,WAAW,EAChB,KAAK,iBAAiB,EACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAiB,MAAM,QAAQ,CAAC;AAClE,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAElC,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AAevE,eAAO,MAAM,cAAc,mBAAuB,CAAC;AACnD,8CAA8C;AAC9C,eAAO,MAAM,KAAK,MAAM,CAAC;AAEzB;;;;;;;;GAQG;AACH,MAAM,MAAM,YAAY,GACpB;IACE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB,GACD;IACE,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,SAAS,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E,GAAG,CAAC,MAAM,CAAC,CAAC;CAChC,sCAiCA,CAAC;AAEJ;;;;;;;GAOG;AACH,eAAO,MAAM,sBAAsB,GAAI,UAAU;IAC/C,QAAQ,CAAC,OAAO,CAAC,EAAE,eAAe,CAAC;IACnC,QAAQ,CAAC,SAAS,CAAC,EAAE,gBAAgB,CAAC;CACvC,2GAeG,CAAC;AAEL;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,GACzB,IAAI,EAAE,EACN,YAAW,gBAAqC,gEAc/C,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import { _ as _extends } from "@swc/helpers/_/_extends";
2
2
  import { ShutdownRegistryTag, TenantDirectoryTag } from '@entifix/business';
3
- import { EventBusTag } from '@entifix/transactions';
3
+ import { aggregateKey, EventBusTag } from '@entifix/transactions';
4
4
  import { Context, Duration, Effect, Fiber, Result } from 'effect';
5
5
  import { MongoDatabaseTag } from '../mongo-database/mongo-database.js';
6
6
  import { recordOutboxStats } from './metrics.js';
@@ -32,37 +32,36 @@ export const SWEEP_INTERVAL = Duration.seconds(15);
32
32
  */ export class OutboxMaxAttempts extends Context.Service()('OutboxMaxAttempts') {
33
33
  }
34
34
  /**
35
- * Publish one batch of pending entries, oldest first, and answer how many went.
35
+ * Publish one batch of pending entries, oldest first, **in order within each
36
+ * aggregate** ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)),
37
+ * and answer how many went.
36
38
  *
37
- * Two orderings are load-bearing here and neither is obvious:
38
- *
39
- * - A **still-deliverable** failure returns immediately rather than continuing.
40
- * The entries behind this one keep their order relative to it, which is what
41
- * stops a terminal event overtaking the `accepted` for the same transaction.
42
- * - A **quarantined** failure continues. That is the deliberate
43
- * skip-so-the-head-moves: an entry that can never publish must stop blocking
44
- * every entry behind it forever.
39
+ * - A **still-deliverable** failure holds back the rest of its own aggregate
40
+ * for this pass, which is what stops a terminal event overtaking the
41
+ * `accepted` of the same transaction — and only its own: every other
42
+ * aggregate keeps draining.
43
+ * - A **quarantined** failure moves on. An entry that can never publish must
44
+ * not hold its aggregate forever, and a consumer discards whatever older
45
+ * version arrives after a newer one anyway.
45
46
  */ export const drainOutbox = (outbox, bus, options)=>Effect.gen(function*() {
46
47
  var _options_onOutcome;
47
48
  const entries = yield* outbox.pending(BATCH);
49
+ const held = new Set();
48
50
  let sent = 0;
49
51
  const report = (_options_onOutcome = options.onOutcome) != null ? _options_onOutcome : ignoreRelayOutcome;
50
52
  for (const entry of entries){
53
+ const key = aggregateKey(entry.aggregate);
54
+ if (held.has(key)) continue;
51
55
  const outcome = yield* Effect.result(bus.publish(entry.event));
52
56
  if (Result.isFailure(outcome)) {
53
- var _options_onOutcome1;
54
57
  const attempts = entry.attempts + 1;
55
58
  const quarantine = attempts >= options.maxAttempts;
56
59
  yield* outbox.recordFailure(entry, failureText(outcome.failure), quarantine);
57
60
  if (!quarantine) {
58
- yield* report({
59
- _tag: 'drained',
60
- database: options.database,
61
- sent
62
- });
63
- return sent;
61
+ held.add(key);
62
+ continue;
64
63
  }
65
- yield* ((_options_onOutcome1 = options.onOutcome) != null ? _options_onOutcome1 : ignoreRelayOutcome)({
64
+ yield* report({
66
65
  _tag: 'quarantined',
67
66
  database: options.database,
68
67
  eventId: entry.eventId,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/outbox/relay.ts"],"sourcesContent":["import {\n ShutdownRegistryTag,\n type TenantDirectory,\n TenantDirectoryTag,\n} from '@entifix/business';\nimport {\n type EventBus,\n EventBusTag,\n type OutboxStats,\n type TransactionOutbox,\n} from '@entifix/transactions';\nimport { Context, Duration, Effect, Fiber, Result } from 'effect';\nimport type { Db } from 'mongodb';\n\nimport { MongoDatabaseTag } from '../mongo-database/mongo-database.js';\nimport { recordOutboxStats } from './metrics.js';\nimport { ensureOutboxIndexes, makeMongoOutbox } from './store.js';\n\n/** How often the sweep looks for entries the fast path did not carry. */\n/**\n * What an outbox entry records as the reason its publish failed: the failure's\n * own message, or its code when it carries none — never empty, because an\n * operator reading a quarantined entry has nothing else to go on.\n */\nconst failureText = (failure: {\n readonly message: string;\n readonly code: string;\n}) => (failure.message === '' ? failure.code : failure.message);\n\nexport const SWEEP_INTERVAL = Duration.seconds(15);\n/** Entries drained per pass, per database. */\nexport const BATCH = 100;\n\n/**\n * What a relay pass did, for the host to log\n * ([ADR 0013](../../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n *\n * The relay decides nothing about level or sink: it says what happened and the\n * fork site that started it — the slice's shell — decides how loud that is. A\n * `failure` is whatever the store or the bus failed with; a typed one carries\n * its code and category for the log line.\n */\nexport type RelayOutcome =\n | {\n readonly _tag: 'drained';\n readonly database: string;\n readonly sent: number;\n }\n | {\n readonly _tag: 'quarantined';\n readonly database: string;\n readonly eventId: string;\n readonly eventName: string;\n readonly attempts: number;\n readonly code: string;\n readonly reason: string;\n }\n | {\n readonly _tag: 'sweepFailed';\n readonly database?: string;\n readonly failure: unknown;\n }\n | {\n readonly _tag: 'drainFailed';\n readonly database: string;\n readonly failure: unknown;\n };\n\n/** Where a relay's outcomes go. The host's fork site supplies it. */\nexport type RelayOutcomeSink = (outcome: RelayOutcome) => Effect.Effect<void>;\n\n/**\n * Hears nothing. The default only so a spec can start a relay without one —\n * a host that passes no sink has a relay nobody can watch.\n */\nexport const ignoreRelayOutcome: RelayOutcomeSink = () => Effect.void;\n\n/**\n * Publish attempts an outbox entry gets before it is quarantined, from\n * config-service.\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\n/** What {@link drainOutbox} needs beyond the ports it publishes through. */\nexport interface DrainOptions {\n readonly maxAttempts: number;\n /** The database being drained; carried so a quarantine log names it. */\n readonly database: string;\n /** Where the pass reports what it did; see {@link RelayOutcome}. */\n readonly onOutcome?: RelayOutcomeSink;\n}\n\n/**\n * Publish one batch of pending entries, oldest first, and answer how many went.\n *\n * Two orderings are load-bearing here and neither is obvious:\n *\n * - A **still-deliverable** failure returns immediately rather than continuing.\n * The entries behind this one keep their order relative to it, which is what\n * stops a terminal event overtaking the `accepted` for the same transaction.\n * - A **quarantined** failure continues. That is the deliberate\n * skip-so-the-head-moves: an entry that can never publish must stop blocking\n * every entry behind it forever.\n */\nexport const drainOutbox = (\n outbox: TransactionOutbox,\n bus: EventBus,\n options: DrainOptions,\n) =>\n Effect.gen(function* () {\n const entries = yield* outbox.pending(BATCH);\n let sent = 0;\n const report = options.onOutcome ?? ignoreRelayOutcome;\n for (const entry of entries) {\n const outcome = yield* Effect.result(bus.publish(entry.event));\n\n if (Result.isFailure(outcome)) {\n const attempts = entry.attempts + 1;\n const quarantine = attempts >= options.maxAttempts;\n\n yield* outbox.recordFailure(\n entry,\n failureText(outcome.failure),\n quarantine,\n );\n\n if (!quarantine) {\n yield* report({ _tag: 'drained', database: options.database, sent });\n return sent;\n }\n\n yield* (options.onOutcome ?? ignoreRelayOutcome)({\n _tag: 'quarantined',\n database: options.database,\n eventId: entry.eventId,\n eventName: entry.event.name,\n attempts,\n code: outcome.failure.code,\n reason: failureText(outcome.failure),\n });\n continue;\n }\n\n yield* outbox.markSent(entry);\n sent += 1;\n }\n yield* report({ _tag: 'drained', database: options.database, sent });\n return sent;\n });\n\n/**\n * Sample a sweep's depth and age.\n *\n * Defaults to {@link recordOutboxStats}, and a caller overrides it only to\n * assert what was sampled. There is no \"no sink\" option on purpose: an outbox\n * whose depth nothing reports is the failure the gauges exist to make visible.\n */\nexport type OutboxStatsSink = (\n database: string,\n stats: OutboxStats,\n) => Effect.Effect<void>;\n\n/**\n * Drain the one database this service owns, then sample its depth.\n *\n * The single-database counterpart to `startTenantOutboxRelay`. A\n * platform-plane store is one named database, so there is nothing to enumerate\n * and `listDatabases` — which needs a `MongoClient` and cluster-wide rights —\n * never comes into it.\n *\n * Stats are sampled **after** the drain, so the gauge reports what is still\n * waiting rather than what was waiting when the pass began.\n *\n * Every failure is caught and reported as `sweepFailed`. This runs inside\n * `Effect.forever`, and an error that escapes ends the daemon silently — a\n * relay that stopped is indistinguishable from a relay with nothing to do.\n */\nexport const sweepOutbox = (\n outbox: TransactionOutbox,\n bus: EventBus,\n options: DrainOptions & { readonly onStats?: OutboxStatsSink },\n) =>\n Effect.gen(function* () {\n yield* drainOutbox(outbox, bus, options);\n const sink = options.onStats ?? recordOutboxStats;\n yield* sink(options.database, yield* outbox.stats());\n }).pipe(\n Effect.catch(failure =>\n (options.onOutcome ?? ignoreRelayOutcome)({\n _tag: 'sweepFailed',\n database: options.database,\n failure,\n }),\n ),\n );\n\n/**\n * Start the relay for a service that owns exactly one database.\n *\n * ⚠️ **The shutdown hook is `flush`, not `stop-intake`, and the phase is the\n * whole point.** `AmqpEventBusLayer` registers `stop-intake` to cancel consumers\n * and drain deliveries; this runs after that, so the last sweep publishes into a\n * connection that is still open. Registered the other way round it would try to\n * publish through a channel already closing, and the entries it was holding\n * would sit until the next boot.\n *\n * The daemon is `delay |> forever`, so the first sweep is one interval away\n * rather than at boot — the write path drains inline, and a sweep racing the\n * index bootstrap on a cold database only produces noise.\n */\nexport const startOutboxRelay = (options?: {\n readonly onStats?: OutboxStatsSink;\n readonly onOutcome?: RelayOutcomeSink;\n}) =>\n Effect.gen(function* () {\n const db = yield* MongoDatabaseTag;\n const bus = yield* EventBusTag;\n const maxAttempts = yield* OutboxMaxAttempts;\n\n yield* ensureOutboxIndexes(db);\n const outbox = makeMongoOutbox(db);\n\n yield* runRelayDaemon(\n sweepOutbox(outbox, bus, {\n maxAttempts,\n database: db.databaseName,\n ...(options?.onStats ? { onStats: options.onStats } : {}),\n ...(options?.onOutcome ? { onOutcome: options.onOutcome } : {}),\n }),\n );\n });\n\n/**\n * Runs `sweepOnce` every {@link SWEEP_INTERVAL}, and once more on the way out.\n *\n * Interrupting the daemon before that last pass is what stops two sweeps\n * publishing the same entry; running the pass is what the hook is for — an\n * event committed a moment before shutdown would otherwise wait out the next\n * process's whole interval.\n */\nconst runRelayDaemon = (sweepOnce: Effect.Effect<void>) =>\n Effect.gen(function* () {\n const shutdown = yield* ShutdownRegistryTag;\n\n const daemon = yield* Effect.forkDetach(\n sweepOnce.pipe(Effect.delay(SWEEP_INTERVAL), Effect.forever),\n );\n\n yield* shutdown.register({\n name: 'outbox-relay',\n phase: 'flush',\n run: Fiber.interrupt(daemon).pipe(Effect.andThen(sweepOnce)),\n });\n });\n\n/**\n * One pass over every organization's outbox in a per-organization store.\n *\n * ⚠️ **Each tenant is caught on its own.** A failure that recurs — an index\n * conflict on one old database, say — would otherwise abandon every tenant\n * listed after it on every pass, while the relay went on looking healthy.\n *\n * Indexes are ensured once per database per process (`ensured`), not on every\n * pass: a sweep visits every tenant every interval, and the index build is the\n * same request each time.\n */\nexport const sweepTenantOutboxes = (\n directory: TenantDirectory<Db>,\n bus: EventBus,\n options: {\n readonly maxAttempts: number;\n readonly onStats?: OutboxStatsSink;\n readonly onOutcome?: RelayOutcomeSink;\n readonly ensured?: Set<string>;\n },\n) =>\n Effect.gen(function* () {\n const report = options.onOutcome ?? ignoreRelayOutcome;\n const ensured = options.ensured ?? new Set<string>();\n const tenants = yield* directory.list();\n\n for (const { handle: db } of tenants) {\n const database = db.databaseName;\n yield* Effect.gen(function* () {\n if (!ensured.has(database)) {\n yield* ensureOutboxIndexes(db);\n ensured.add(database);\n }\n yield* sweepOutbox(makeMongoOutbox(db), bus, {\n maxAttempts: options.maxAttempts,\n database,\n onOutcome: report,\n ...(options.onStats ? { onStats: options.onStats } : {}),\n });\n }).pipe(\n Effect.catch(failure =>\n report({ _tag: 'sweepFailed', database, failure }),\n ),\n );\n }\n }).pipe(\n Effect.catch(failure =>\n (options.onOutcome ?? ignoreRelayOutcome)({\n _tag: 'sweepFailed',\n failure,\n }),\n ),\n );\n\n/**\n * Start the relay for a store with one database per organization, listed by\n * the {@link TenantDirectoryTag} the host provides.\n *\n * The same two speeds as {@link startOutboxRelay}: the write path drains its\n * own tenant inline with {@link drainOutboxNow}, and this sweep carries\n * whatever that missed.\n */\nexport const startTenantOutboxRelay = (options?: {\n readonly onStats?: OutboxStatsSink;\n readonly onOutcome?: RelayOutcomeSink;\n}) =>\n Effect.gen(function* () {\n const directory = (yield* TenantDirectoryTag) as TenantDirectory<Db>;\n const bus = yield* EventBusTag;\n const maxAttempts = yield* OutboxMaxAttempts;\n const ensured = new Set<string>();\n\n yield* runRelayDaemon(\n sweepTenantOutboxes(directory, bus, {\n maxAttempts,\n ensured,\n ...(options?.onStats ? { onStats: options.onStats } : {}),\n ...(options?.onOutcome ? { onOutcome: options.onOutcome } : {}),\n }),\n );\n });\n\n/**\n * Drain one database's outbox now, for a write path that has just committed.\n *\n * The fast path the sweep is the fallback for: an event drained here leaves as\n * soon as its transaction commits, rather than up to {@link SWEEP_INTERVAL}\n * later. Every failure is reported as `drainFailed` and swallowed — the entry\n * is still in the outbox, and the sweep will carry it.\n */\nexport const drainOutboxNow = (\n db: Db,\n onOutcome: RelayOutcomeSink = ignoreRelayOutcome,\n) =>\n Effect.gen(function* () {\n const bus = yield* EventBusTag;\n const maxAttempts = yield* OutboxMaxAttempts;\n yield* drainOutbox(makeMongoOutbox(db), bus, {\n maxAttempts,\n database: db.databaseName,\n onOutcome,\n });\n }).pipe(\n Effect.catch(failure =>\n onOutcome({ _tag: 'drainFailed', database: db.databaseName, failure }),\n ),\n );\n"],"names":["ShutdownRegistryTag","TenantDirectoryTag","EventBusTag","Context","Duration","Effect","Fiber","Result","MongoDatabaseTag","recordOutboxStats","ensureOutboxIndexes","makeMongoOutbox","failureText","failure","message","code","SWEEP_INTERVAL","seconds","BATCH","ignoreRelayOutcome","void","OutboxMaxAttempts","Service","drainOutbox","outbox","bus","options","gen","entries","pending","sent","report","onOutcome","entry","outcome","result","publish","event","isFailure","attempts","quarantine","maxAttempts","recordFailure","_tag","database","eventId","eventName","name","reason","markSent","sweepOutbox","sink","onStats","stats","pipe","catch","startOutboxRelay","db","runRelayDaemon","databaseName","sweepOnce","shutdown","daemon","forkDetach","delay","forever","register","phase","run","interrupt","andThen","sweepTenantOutboxes","directory","ensured","Set","tenants","list","handle","has","add","startTenantOutboxRelay","drainOutboxNow"],"mappings":";AAAA,SACEA,mBAAmB,EAEnBC,kBAAkB,QACb,oBAAoB;AAC3B,SAEEC,WAAW,QAGN,wBAAwB;AAC/B,SAASC,OAAO,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,KAAK,EAAEC,MAAM,QAAQ,SAAS;AAGlE,SAASC,gBAAgB,QAAQ,sCAAsC;AACvE,SAASC,iBAAiB,QAAQ,eAAe;AACjD,SAASC,mBAAmB,EAAEC,eAAe,QAAQ,aAAa;AAElE,uEAAuE,GACvE;;;;CAIC,GACD,MAAMC,cAAc,CAACC,UAGdA,QAAQC,OAAO,KAAK,KAAKD,QAAQE,IAAI,GAAGF,QAAQC,OAAO;AAE9D,OAAO,MAAME,iBAAiBZ,SAASa,OAAO,CAAC,IAAI;AACnD,4CAA4C,GAC5C,OAAO,MAAMC,QAAQ,IAAI;AAwCzB;;;CAGC,GACD,OAAO,MAAMC,qBAAuC,IAAMd,OAAOe,IAAI,CAAC;AAEtE;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,0BAA0BlB,QAAQmB,OAAO,GAGlD;AAAsB;AAW1B;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,cAAc,CACzBC,QACAC,KACAC,UAEArB,OAAOsB,GAAG,CAAC;YAGMD;QAFf,MAAME,UAAU,OAAOJ,OAAOK,OAAO,CAACX;QACtC,IAAIY,OAAO;QACX,MAAMC,UAASL,qBAAAA,QAAQM,SAAS,YAAjBN,qBAAqBP;QACpC,KAAK,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;;;CAOC,GACD,OAAO,MAAMiD,iBAAiB,CAC5BxB,IACAzB,YAA8Bb,kBAAkB,GAEhDd,OAAOsB,GAAG,CAAC;QACT,MAAMF,MAAM,OAAOvB;QACnB,MAAMuC,cAAc,OAAOpB;QAC3B,OAAOE,YAAYZ,gBAAgB8C,KAAKhC,KAAK;YAC3CgB;YACAG,UAAUa,GAAGE,YAAY;YACzB3B;QACF;IACF,GAAGsB,IAAI,CACLjD,OAAOkD,KAAK,CAAC1C,CAAAA,UACXmB,UAAU;YAAEW,MAAM;YAAeC,UAAUa,GAAGE,YAAY;YAAE9C;QAAQ,KAEtE"}
1
+ {"version":3,"sources":["../../src/outbox/relay.ts"],"sourcesContent":["import {\n ShutdownRegistryTag,\n type TenantDirectory,\n TenantDirectoryTag,\n} from '@entifix/business';\nimport {\n aggregateKey,\n type EventBus,\n EventBusTag,\n type Outbox,\n type OutboxStats,\n} from '@entifix/transactions';\nimport { Context, Duration, Effect, Fiber, Result } from 'effect';\nimport type { Db } from 'mongodb';\n\nimport { MongoDatabaseTag } from '../mongo-database/mongo-database.js';\nimport { recordOutboxStats } from './metrics.js';\nimport { ensureOutboxIndexes, makeMongoOutbox } from './store.js';\n\n/** How often the sweep looks for entries the fast path did not carry. */\n/**\n * What an outbox entry records as the reason its publish failed: the failure's\n * own message, or its code when it carries none — never empty, because an\n * operator reading a quarantined entry has nothing else to go on.\n */\nconst failureText = (failure: {\n readonly message: string;\n readonly code: string;\n}) => (failure.message === '' ? failure.code : failure.message);\n\nexport const SWEEP_INTERVAL = Duration.seconds(15);\n/** Entries drained per pass, per database. */\nexport const BATCH = 100;\n\n/**\n * What a relay pass did, for the host to log\n * ([ADR 0013](../../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n *\n * The relay decides nothing about level or sink: it says what happened and the\n * fork site that started it — the slice's shell — decides how loud that is. A\n * `failure` is whatever the store or the bus failed with; a typed one carries\n * its code and category for the log line.\n */\nexport type RelayOutcome =\n | {\n readonly _tag: 'drained';\n readonly database: string;\n readonly sent: number;\n }\n | {\n readonly _tag: 'quarantined';\n readonly database: string;\n readonly eventId: string;\n readonly eventName: string;\n readonly attempts: number;\n readonly code: string;\n readonly reason: string;\n }\n | {\n readonly _tag: 'sweepFailed';\n readonly database?: string;\n readonly failure: unknown;\n }\n | {\n readonly _tag: 'drainFailed';\n readonly database: string;\n readonly failure: unknown;\n };\n\n/** Where a relay's outcomes go. The host's fork site supplies it. */\nexport type RelayOutcomeSink = (outcome: RelayOutcome) => Effect.Effect<void>;\n\n/**\n * Hears nothing. The default only so a spec can start a relay without one —\n * a host that passes no sink has a relay nobody can watch.\n */\nexport const ignoreRelayOutcome: RelayOutcomeSink = () => Effect.void;\n\n/**\n * Publish attempts an outbox entry gets before it is quarantined, from\n * config-service.\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\n/** What {@link drainOutbox} needs beyond the ports it publishes through. */\nexport interface DrainOptions {\n readonly maxAttempts: number;\n /** The database being drained; carried so a quarantine log names it. */\n readonly database: string;\n /** Where the pass reports what it did; see {@link RelayOutcome}. */\n readonly onOutcome?: RelayOutcomeSink;\n}\n\n/**\n * Publish one batch of pending entries, oldest first, **in order within each\n * aggregate** ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)),\n * and answer how many went.\n *\n * - A **still-deliverable** failure holds back the rest of its own aggregate\n * for this pass, which is what stops a terminal event overtaking the\n * `accepted` of the same transaction — and only its own: every other\n * aggregate keeps draining.\n * - A **quarantined** failure moves on. An entry that can never publish must\n * not hold its aggregate forever, and a consumer discards whatever older\n * version arrives after a newer one anyway.\n */\nexport const drainOutbox = (\n outbox: Outbox,\n bus: EventBus,\n options: DrainOptions,\n) =>\n Effect.gen(function* () {\n const entries = yield* outbox.pending(BATCH);\n const held = new Set<string>();\n let sent = 0;\n const report = options.onOutcome ?? ignoreRelayOutcome;\n for (const entry of entries) {\n const key = aggregateKey(entry.aggregate);\n if (held.has(key)) continue;\n\n const outcome = yield* Effect.result(bus.publish(entry.event));\n\n if (Result.isFailure(outcome)) {\n const attempts = entry.attempts + 1;\n const quarantine = attempts >= options.maxAttempts;\n\n yield* outbox.recordFailure(\n entry,\n failureText(outcome.failure),\n quarantine,\n );\n\n if (!quarantine) {\n held.add(key);\n continue;\n }\n\n yield* report({\n _tag: 'quarantined',\n database: options.database,\n eventId: entry.eventId,\n eventName: entry.event.name,\n attempts,\n code: outcome.failure.code,\n reason: failureText(outcome.failure),\n });\n continue;\n }\n\n yield* outbox.markSent(entry);\n sent += 1;\n }\n yield* report({ _tag: 'drained', database: options.database, sent });\n return sent;\n });\n\n/**\n * Sample a sweep's depth and age.\n *\n * Defaults to {@link recordOutboxStats}, and a caller overrides it only to\n * assert what was sampled. There is no \"no sink\" option on purpose: an outbox\n * whose depth nothing reports is the failure the gauges exist to make visible.\n */\nexport type OutboxStatsSink = (\n database: string,\n stats: OutboxStats,\n) => Effect.Effect<void>;\n\n/**\n * Drain the one database this service owns, then sample its depth.\n *\n * The single-database counterpart to `startTenantOutboxRelay`. A\n * platform-plane store is one named database, so there is nothing to enumerate\n * and `listDatabases` — which needs a `MongoClient` and cluster-wide rights —\n * never comes into it.\n *\n * Stats are sampled **after** the drain, so the gauge reports what is still\n * waiting rather than what was waiting when the pass began.\n *\n * Every failure is caught and reported as `sweepFailed`. This runs inside\n * `Effect.forever`, and an error that escapes ends the daemon silently — a\n * relay that stopped is indistinguishable from a relay with nothing to do.\n */\nexport const sweepOutbox = (\n outbox: Outbox,\n bus: EventBus,\n options: DrainOptions & { readonly onStats?: OutboxStatsSink },\n) =>\n Effect.gen(function* () {\n yield* drainOutbox(outbox, bus, options);\n const sink = options.onStats ?? recordOutboxStats;\n yield* sink(options.database, yield* outbox.stats());\n }).pipe(\n Effect.catch(failure =>\n (options.onOutcome ?? ignoreRelayOutcome)({\n _tag: 'sweepFailed',\n database: options.database,\n failure,\n }),\n ),\n );\n\n/**\n * Start the relay for a service that owns exactly one database.\n *\n * ⚠️ **The shutdown hook is `flush`, not `stop-intake`, and the phase is the\n * whole point.** `AmqpEventBusLayer` registers `stop-intake` to cancel consumers\n * and drain deliveries; this runs after that, so the last sweep publishes into a\n * connection that is still open. Registered the other way round it would try to\n * publish through a channel already closing, and the entries it was holding\n * would sit until the next boot.\n *\n * The daemon is `delay |> forever`, so the first sweep is one interval away\n * rather than at boot — the write path drains inline, and a sweep racing the\n * index bootstrap on a cold database only produces noise.\n */\nexport const startOutboxRelay = (options?: {\n readonly onStats?: OutboxStatsSink;\n readonly onOutcome?: RelayOutcomeSink;\n}) =>\n Effect.gen(function* () {\n const db = yield* MongoDatabaseTag;\n const bus = yield* EventBusTag;\n const maxAttempts = yield* OutboxMaxAttempts;\n\n yield* ensureOutboxIndexes(db);\n const outbox = makeMongoOutbox(db);\n\n yield* runRelayDaemon(\n sweepOutbox(outbox, bus, {\n maxAttempts,\n database: db.databaseName,\n ...(options?.onStats ? { onStats: options.onStats } : {}),\n ...(options?.onOutcome ? { onOutcome: options.onOutcome } : {}),\n }),\n );\n });\n\n/**\n * Runs `sweepOnce` every {@link SWEEP_INTERVAL}, and once more on the way out.\n *\n * Interrupting the daemon before that last pass is what stops two sweeps\n * publishing the same entry; running the pass is what the hook is for — an\n * event committed a moment before shutdown would otherwise wait out the next\n * process's whole interval.\n */\nconst runRelayDaemon = (sweepOnce: Effect.Effect<void>) =>\n Effect.gen(function* () {\n const shutdown = yield* ShutdownRegistryTag;\n\n const daemon = yield* Effect.forkDetach(\n sweepOnce.pipe(Effect.delay(SWEEP_INTERVAL), Effect.forever),\n );\n\n yield* shutdown.register({\n name: 'outbox-relay',\n phase: 'flush',\n run: Fiber.interrupt(daemon).pipe(Effect.andThen(sweepOnce)),\n });\n });\n\n/**\n * One pass over every organization's outbox in a per-organization store.\n *\n * ⚠️ **Each tenant is caught on its own.** A failure that recurs — an index\n * conflict on one old database, say — would otherwise abandon every tenant\n * listed after it on every pass, while the relay went on looking healthy.\n *\n * Indexes are ensured once per database per process (`ensured`), not on every\n * pass: a sweep visits every tenant every interval, and the index build is the\n * same request each time.\n */\nexport const sweepTenantOutboxes = (\n directory: TenantDirectory<Db>,\n bus: EventBus,\n options: {\n readonly maxAttempts: number;\n readonly onStats?: OutboxStatsSink;\n readonly onOutcome?: RelayOutcomeSink;\n readonly ensured?: Set<string>;\n },\n) =>\n Effect.gen(function* () {\n const report = options.onOutcome ?? ignoreRelayOutcome;\n const ensured = options.ensured ?? new Set<string>();\n const tenants = yield* directory.list();\n\n for (const { handle: db } of tenants) {\n const database = db.databaseName;\n yield* Effect.gen(function* () {\n if (!ensured.has(database)) {\n yield* ensureOutboxIndexes(db);\n ensured.add(database);\n }\n yield* sweepOutbox(makeMongoOutbox(db), bus, {\n maxAttempts: options.maxAttempts,\n database,\n onOutcome: report,\n ...(options.onStats ? { onStats: options.onStats } : {}),\n });\n }).pipe(\n Effect.catch(failure =>\n report({ _tag: 'sweepFailed', database, failure }),\n ),\n );\n }\n }).pipe(\n Effect.catch(failure =>\n (options.onOutcome ?? ignoreRelayOutcome)({\n _tag: 'sweepFailed',\n failure,\n }),\n ),\n );\n\n/**\n * Start the relay for a store with one database per organization, listed by\n * the {@link TenantDirectoryTag} the host provides.\n *\n * The same two speeds as {@link startOutboxRelay}: the write path drains its\n * own tenant inline with {@link drainOutboxNow}, and this sweep carries\n * whatever that missed.\n */\nexport const startTenantOutboxRelay = (options?: {\n readonly onStats?: OutboxStatsSink;\n readonly onOutcome?: RelayOutcomeSink;\n}) =>\n Effect.gen(function* () {\n const directory = (yield* TenantDirectoryTag) as TenantDirectory<Db>;\n const bus = yield* EventBusTag;\n const maxAttempts = yield* OutboxMaxAttempts;\n const ensured = new Set<string>();\n\n yield* runRelayDaemon(\n sweepTenantOutboxes(directory, bus, {\n maxAttempts,\n ensured,\n ...(options?.onStats ? { onStats: options.onStats } : {}),\n ...(options?.onOutcome ? { onOutcome: options.onOutcome } : {}),\n }),\n );\n });\n\n/**\n * Drain one database's outbox now, for a write path that has just committed.\n *\n * The fast path the sweep is the fallback for: an event drained here leaves as\n * soon as its transaction commits, rather than up to {@link SWEEP_INTERVAL}\n * later. Every failure is reported as `drainFailed` and swallowed — the entry\n * is still in the outbox, and the sweep will carry it.\n */\nexport const drainOutboxNow = (\n db: Db,\n onOutcome: RelayOutcomeSink = ignoreRelayOutcome,\n) =>\n Effect.gen(function* () {\n const bus = yield* EventBusTag;\n const maxAttempts = yield* OutboxMaxAttempts;\n yield* drainOutbox(makeMongoOutbox(db), bus, {\n maxAttempts,\n database: db.databaseName,\n onOutcome,\n });\n }).pipe(\n Effect.catch(failure =>\n onOutcome({ _tag: 'drainFailed', database: db.databaseName, failure }),\n ),\n );\n"],"names":["ShutdownRegistryTag","TenantDirectoryTag","aggregateKey","EventBusTag","Context","Duration","Effect","Fiber","Result","MongoDatabaseTag","recordOutboxStats","ensureOutboxIndexes","makeMongoOutbox","failureText","failure","message","code","SWEEP_INTERVAL","seconds","BATCH","ignoreRelayOutcome","void","OutboxMaxAttempts","Service","drainOutbox","outbox","bus","options","gen","entries","pending","held","Set","sent","report","onOutcome","entry","key","aggregate","has","outcome","result","publish","event","isFailure","attempts","quarantine","maxAttempts","recordFailure","add","_tag","database","eventId","eventName","name","reason","markSent","sweepOutbox","sink","onStats","stats","pipe","catch","startOutboxRelay","db","runRelayDaemon","databaseName","sweepOnce","shutdown","daemon","forkDetach","delay","forever","register","phase","run","interrupt","andThen","sweepTenantOutboxes","directory","ensured","tenants","list","handle","startTenantOutboxRelay","drainOutboxNow"],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A,UACXqB,UAAU;YAAEe,MAAM;YAAeC,UAAUa,GAAGE,YAAY;YAAEpD;QAAQ,KAEtE"}
@@ -1,5 +1,4 @@
1
- import type { DomainEvent } from '@entifix/core';
2
- import type { OutboxEntry, TransactionOutbox } from '@entifix/transactions';
1
+ import type { Outbox, OutboxEntry, OutboxEvent } from '@entifix/transactions';
3
2
  import { Effect } from 'effect';
4
3
  import type { Db } from 'mongodb';
5
4
  /**
@@ -18,7 +17,7 @@ import type { Db } from 'mongodb';
18
17
  * identically to a per-organization `tenant_<id>` and to a single platform-plane
19
18
  * database, and the second publisher is what turned a copy into a seam.
20
19
  */
21
- export declare const OUTBOX_COLLECTION = "transaction_outbox";
20
+ export declare const OUTBOX_COLLECTION = "outbox";
22
21
  /**
23
22
  * The stored shape of an outbox entry.
24
23
  *
@@ -27,7 +26,7 @@ export declare const OUTBOX_COLLECTION = "transaction_outbox";
27
26
  * cannot live in a framework-free contract. The handler inserts this document
28
27
  * itself; everything else goes through {@link makeMongoOutbox}.
29
28
  */
30
- export declare const outboxDocument: (event: DomainEvent) => OutboxEntry;
29
+ export declare const outboxDocument: (event: OutboxEvent) => OutboxEntry;
31
30
  /**
32
31
  * Puts a **quarantined** entry back in the queue, and touches nothing else.
33
32
  *
@@ -44,7 +43,7 @@ export declare const outboxDocument: (event: DomainEvent) => OutboxEntry;
44
43
  * walk that would re-publish the whole fleet on every boot and un-quarantine
45
44
  * genuine poison each time.
46
45
  *
47
- * Not a `TransactionOutbox` method: the port is framework-free and shared by
46
+ * Not an `Outbox` method: the port is framework-free and shared by
48
47
  * every publisher, and this is a repair specific to the rebuild. `outboxDocument`
49
48
  * is exported beside it for the same class of reason.
50
49
  *
@@ -52,7 +51,7 @@ export declare const outboxDocument: (event: DomainEvent) => OutboxEntry;
52
51
  */
53
52
  export declare const reviveQuarantined: (db: Db, eventId: string) => Effect.Effect<boolean, import("@entifix/core").StoreFailure, never>;
54
53
  /**
55
- * Ensures the two indexes the outbox depends on.
54
+ * Ensures the three indexes the outbox depends on.
56
55
  *
57
56
  * The unique one is load-bearing rather than defensive: it *is* the idempotency
58
57
  * check behind the client-generated transaction id, so a replayed command is
@@ -72,12 +71,12 @@ export declare const reviveQuarantined: (db: Db, eventId: string) => Effect.Effe
72
71
  */
73
72
  export declare const ensureOutboxIndexes: (db: Db) => Effect.Effect<void, import("@entifix/core").StoreFailure, never>;
74
73
  /**
75
- * Mongo-backed {@link TransactionOutbox} over one database.
74
+ * Mongo-backed {@link Outbox} over one database.
76
75
  *
77
76
  * `db` is closed over, so every method's Effect has `R = never` — the same
78
77
  * technique `makeMongoRepository` uses. There is no publishing here: the relay
79
78
  * composes these methods with the event bus, which is what lets the relay be
80
79
  * tested without a broker.
81
80
  */
82
- export declare const makeMongoOutbox: (db: Db) => TransactionOutbox;
81
+ export declare const makeMongoOutbox: (db: Db) => Outbox;
83
82
  //# sourceMappingURL=store.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/outbox/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC5E,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAIlC;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,iBAAiB,uBAAuB,CAAC;AAatD;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,WAAW,KAAG,WAWlD,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,iBAAiB,GAAI,IAAI,EAAE,EAAE,SAAS,MAAM,wEAiBrD,CAAC;AAEL;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,mBAAmB,GAAI,IAAI,EAAE,qEAWtC,CAAC;AAEL;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,GAAI,IAAI,EAAE,KAAG,iBA4FxC,CAAC"}
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/outbox/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAC9E,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAIlC;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAa1C;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,WAAW,KAAG,WAalD,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,iBAAiB,GAAI,IAAI,EAAE,EAAE,SAAS,MAAM,wEAiBrD,CAAC;AAEL;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,mBAAmB,GAAI,IAAI,EAAE,qEAkBtC,CAAC;AAEL;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,GAAI,IAAI,EAAE,KAAG,MA6FxC,CAAC"}
@@ -16,7 +16,7 @@ import { translateMongoError } from '../errors/translate-mongo-error.js';
16
16
  * That rule is why this lives here rather than in one service. It applies
17
17
  * identically to a per-organization `tenant_<id>` and to a single platform-plane
18
18
  * database, and the second publisher is what turned a copy into a seam.
19
- */ export const OUTBOX_COLLECTION = 'transaction_outbox';
19
+ */ export const OUTBOX_COLLECTION = 'outbox';
20
20
  /** Drop Mongo's internal `_id` from every read. */ const WITHOUT_MONGO_ID = {
21
21
  projection: {
22
22
  _id: 0
@@ -33,6 +33,8 @@ const isDuplicateKey = (error)=>typeof error === 'object' && error !== null && e
33
33
  * itself; everything else goes through {@link makeMongoOutbox}.
34
34
  */ export const outboxDocument = (event)=>({
35
35
  eventId: event.id,
36
+ aggregate: event.aggregate,
37
+ version: event.version,
36
38
  event,
37
39
  sent: false,
38
40
  // Defaulted here rather than at each write site because there are two of
@@ -59,7 +61,7 @@ const isDuplicateKey = (error)=>typeof error === 'object' && error !== null && e
59
61
  * walk that would re-publish the whole fleet on every boot and un-quarantine
60
62
  * genuine poison each time.
61
63
  *
62
- * Not a `TransactionOutbox` method: the port is framework-free and shared by
64
+ * Not an `Outbox` method: the port is framework-free and shared by
63
65
  * every publisher, and this is a repair specific to the rebuild. `outboxDocument`
64
66
  * is exported beside it for the same class of reason.
65
67
  *
@@ -86,7 +88,7 @@ const isDuplicateKey = (error)=>typeof error === 'object' && error !== null && e
86
88
  catch: (error)=>translateMongoError(error)
87
89
  });
88
90
  /**
89
- * Ensures the two indexes the outbox depends on.
91
+ * Ensures the three indexes the outbox depends on.
90
92
  *
91
93
  * The unique one is load-bearing rather than defensive: it *is* the idempotency
92
94
  * check behind the client-generated transaction id, so a replayed command is
@@ -119,11 +121,18 @@ const isDuplicateKey = (error)=>typeof error === 'object' && error !== null && e
119
121
  quarantined: false
120
122
  }
121
123
  });
124
+ // What the per-aggregate order reads, and what a rebuild finds an
125
+ // aggregate's latest announced version by.
126
+ await collection.createIndex({
127
+ 'aggregate.type': 1,
128
+ 'aggregate.id': 1,
129
+ version: 1
130
+ });
122
131
  },
123
132
  catch: (error)=>translateMongoError(error)
124
133
  });
125
134
  /**
126
- * Mongo-backed {@link TransactionOutbox} over one database.
135
+ * Mongo-backed {@link Outbox} over one database.
127
136
  *
128
137
  * `db` is closed over, so every method's Effect has `R = never` — the same
129
138
  * technique `makeMongoRepository` uses. There is no publishing here: the relay
@@ -149,13 +158,15 @@ const isDuplicateKey = (error)=>typeof error === 'object' && error !== null && e
149
158
  catch: (error)=>translateMongoError(error)
150
159
  }),
151
160
  pending: (limit)=>Effect.tryPromise({
152
- // Oldest first, so `accepted` reaches the bus before the terminal event
153
- // for the same transaction and the tracker folds them in order.
161
+ // Oldest first, then by version: the relay publishes in this order
162
+ // within each aggregate, so `accepted` reaches the bus before the
163
+ // terminal event of the same transaction.
154
164
  try: ()=>collection.find({
155
165
  sent: false,
156
166
  quarantined: false
157
167
  }, WITHOUT_MONGO_ID).sort({
158
- createdAt: 1
168
+ createdAt: 1,
169
+ version: 1
159
170
  }).limit(limit).toArray(),
160
171
  catch: (error)=>translateMongoError(error)
161
172
  }),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/outbox/store.ts"],"sourcesContent":["import type { DomainEvent } from '@entifix/core';\nimport type { OutboxEntry, TransactionOutbox } from '@entifix/transactions';\nimport { Effect } from 'effect';\nimport type { Db } from 'mongodb';\n\nimport { translateMongoError } from '../errors/translate-mongo-error.js';\n\n/**\n * The outbox collection, and it lives in the **same database as the entity it\n * describes** — never in a shared control-plane store.\n *\n * Two reasons, and the second only shows up later. Same database means the\n * entity write and its event are one single-database transaction, which stays a\n * single-*shard* transaction if this ever shards; a control-plane outbox would\n * be cross-database from the first commit. And an outbox holds event payloads:\n * a `TransactionEvent` carries no tenant data, but `catalog.published` carries a\n * whole offering and `order.placed` a whole receipt, and neither may land in the\n * control plane on its way to the bus.\n *\n * That rule is why this lives here rather than in one service. It applies\n * identically to a per-organization `tenant_<id>` and to a single platform-plane\n * database, and the second publisher is what turned a copy into a seam.\n */\nexport const OUTBOX_COLLECTION = 'transaction_outbox';\n\n/** Drop Mongo's internal `_id` from every read. */\nconst WITHOUT_MONGO_ID = { projection: { _id: 0 } } as const;\n\n/** Mongo's duplicate-key error, which is how a replayed command is recognised. */\nconst DUPLICATE_KEY = 11000;\n\nconst isDuplicateKey = (error: unknown): boolean =>\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === DUPLICATE_KEY;\n\n/**\n * The stored shape of an outbox entry.\n *\n * Exported because the `completed` entry is **not** written through the port:\n * it has to join the entity write's session to be atomic with it, and a session\n * cannot live in a framework-free contract. The handler inserts this document\n * itself; everything else goes through {@link makeMongoOutbox}.\n */\nexport const outboxDocument = (event: DomainEvent): OutboxEntry => ({\n eventId: event.id,\n event,\n sent: false,\n // Defaulted here rather than at each write site because there are two of\n // them: the relay's `enqueue`, and the transaction handler's own insert\n // inside the entity's Mongo session. An entry missing `attempts` would sort\n // into `pending` and then fail `attempts + 1` arithmetic on a `undefined`.\n attempts: 0,\n quarantined: false,\n createdAt: event.at,\n});\n\n/**\n * Puts a **quarantined** entry back in the queue, and touches nothing else.\n *\n * A rebuild walk's repair for the one failure measured on a live lab: with the\n * broker down long enough, the relay spends `outbox.maxAttempts` on an\n * announcement and quarantines it (the deliberate skip-so-the-head-moves),\n * after which the tenant store reads one thing and the storefront shows another\n * with nothing reporting it. Re-emitting cannot help on its own — the event id is\n * `<offeringId>:<publishedAt>` and the unique index answers `duplicate`.\n *\n * ⚠️ **`quarantined: true` is in the filter, not the update.** An entry that is\n * merely pending keeps its `attempts`, and one already `sent` is never re-sent —\n * which is what keeps this from quietly becoming \"re-announce everything\", a\n * walk that would re-publish the whole fleet on every boot and un-quarantine\n * genuine poison each time.\n *\n * Not a `TransactionOutbox` method: the port is framework-free and shared by\n * every publisher, and this is a repair specific to the rebuild. `outboxDocument`\n * is exported beside it for the same class of reason.\n *\n * Answers whether an entry was actually revived.\n */\nexport const reviveQuarantined = (db: Db, eventId: string) =>\n Effect.tryPromise({\n try: async () => {\n const result = await db\n .collection<OutboxEntry>(OUTBOX_COLLECTION)\n .updateOne(\n { eventId, quarantined: true },\n {\n $set: { sent: false, quarantined: false, attempts: 0 },\n // The failure that put it here is spent; leaving it would make the\n // next quarantine's log name an error from a different outage.\n $unset: { lastError: '' },\n },\n );\n return result.modifiedCount === 1;\n },\n catch: error => translateMongoError(error),\n });\n\n/**\n * Ensures the two indexes the outbox depends on.\n *\n * The unique one is load-bearing rather than defensive: it *is* the idempotency\n * check behind the client-generated transaction id, so a replayed command is\n * rejected by the storage engine rather than by a read-then-write race. It is on\n * `eventId` — `<transactionId>:<step>` for a transaction — so the claim and the\n * bus's deduplication key are one value rather than two that can drift. The\n * partial one keeps the relay's `pending` query cheap once the collection fills\n * with sent entries; it filters on `quarantined` too, so an entry past its\n * ceiling leaves the index rather than being read and skipped forever.\n *\n * Mongo rejects a `createIndex` that reuses a key pattern with a different\n * `partialFilterExpression` (`IndexOptionsConflict`), and this runs on every\n * sweep and every create. A database that predates the `quarantined` filter\n * therefore fails here on every pass — which is loud only because the sweep now\n * logs what it catches. The fix is `pnpm run <app>:dev:reset`; nothing runs in\n * production, so there is no migration to write.\n */\nexport const ensureOutboxIndexes = (db: Db) =>\n Effect.tryPromise({\n try: async () => {\n const collection = db.collection(OUTBOX_COLLECTION);\n await collection.createIndex({ eventId: 1 }, { unique: true });\n await collection.createIndex(\n { createdAt: 1 },\n { partialFilterExpression: { sent: false, quarantined: false } },\n );\n },\n catch: error => translateMongoError(error),\n });\n\n/**\n * Mongo-backed {@link TransactionOutbox} over one database.\n *\n * `db` is closed over, so every method's Effect has `R = never` — the same\n * technique `makeMongoRepository` uses. There is no publishing here: the relay\n * composes these methods with the event bus, which is what lets the relay be\n * tested without a broker.\n */\nexport const makeMongoOutbox = (db: Db): TransactionOutbox => {\n const collection = db.collection<OutboxEntry>(OUTBOX_COLLECTION);\n\n return {\n enqueue: event =>\n Effect.tryPromise({\n try: async () => {\n try {\n await collection.insertOne(outboxDocument(event));\n return 'enqueued' as const;\n } catch (error) {\n // Not a failure: the unique index rejected a second claim for this\n // message id, which is precisely how a retry is identified.\n if (isDuplicateKey(error)) {\n return 'duplicate' as const;\n }\n throw error;\n }\n },\n catch: error => translateMongoError(error),\n }),\n\n pending: limit =>\n Effect.tryPromise({\n // Oldest first, so `accepted` reaches the bus before the terminal event\n // for the same transaction and the tracker folds them in order.\n try: () =>\n collection\n .find({ sent: false, quarantined: false }, WITHOUT_MONGO_ID)\n .sort({ createdAt: 1 })\n .limit(limit)\n .toArray(),\n catch: error => translateMongoError(error),\n }),\n\n markSent: entry =>\n Effect.tryPromise({\n try: () =>\n collection.updateOne(\n { eventId: entry.eventId },\n { $set: { sent: true } },\n ),\n catch: error => translateMongoError(error),\n }).pipe(Effect.asVoid),\n\n stats: () =>\n Effect.tryPromise({\n // Two counts and one `findOne`, rather than reading the entries: the\n // pending set can be arbitrarily large when the relay is stuck, which\n // is exactly the moment this must stay cheap. Both queries ride the\n // partial index on `{ createdAt: 1 }` filtered to the same predicate.\n try: async () => {\n const pendingFilter = { sent: false, quarantined: false };\n const [pending, quarantined, oldest] = await Promise.all([\n collection.countDocuments(pendingFilter),\n collection.countDocuments({ quarantined: true }),\n collection.findOne(pendingFilter, {\n sort: { createdAt: 1 },\n projection: { _id: 0, createdAt: 1 },\n }),\n ]);\n\n return {\n pending,\n quarantined,\n // Absent rather than zero when the outbox is empty: an age of zero\n // and \"nothing is waiting\" are opposite conditions, and a gauge\n // that reports 0 for both is indistinguishable from a healthy relay\n // at exactly the moment it is not one.\n ...(oldest === null ? {} : { oldestPendingAt: oldest.createdAt }),\n };\n },\n catch: error => translateMongoError(error),\n }),\n\n recordFailure: (entry, error, quarantine) =>\n Effect.tryPromise({\n // `$inc` rather than a read-modify-write: two relays can be draining the\n // same tenant (the request's inline drain and the daemon sweep), and an\n // absolute write would let one of them lose the other's attempt and\n // stretch the ceiling indefinitely.\n try: () =>\n collection.updateOne(\n { eventId: entry.eventId },\n {\n $inc: { attempts: 1 },\n $set: { lastError: error, quarantined: quarantine },\n },\n ),\n catch: cause => translateMongoError(cause),\n }).pipe(Effect.asVoid),\n };\n};\n"],"names":["Effect","translateMongoError","OUTBOX_COLLECTION","WITHOUT_MONGO_ID","projection","_id","DUPLICATE_KEY","isDuplicateKey","error","code","outboxDocument","event","eventId","id","sent","attempts","quarantined","createdAt","at","reviveQuarantined","db","tryPromise","try","result","collection","updateOne","$set","$unset","lastError","modifiedCount","catch","ensureOutboxIndexes","createIndex","unique","partialFilterExpression","makeMongoOutbox","enqueue","insertOne","pending","limit","find","sort","toArray","markSent","entry","pipe","asVoid","stats","pendingFilter","oldest","Promise","all","countDocuments","findOne","oldestPendingAt","recordFailure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U,CAAC;gBAChB,qEAAqE;gBACrE,sEAAsE;gBACtE,oEAAoE;gBACpE,sEAAsE;gBACtEC,KAAK;oBACH,MAAM0B,gBAAgB;wBAAElC,MAAM;wBAAOE,aAAa;oBAAM;oBACxD,MAAM,CAACsB,SAAStB,aAAaiC,OAAO,GAAG,MAAMC,QAAQC,GAAG,CAAC;wBACvD3B,WAAW4B,cAAc,CAACJ;wBAC1BxB,WAAW4B,cAAc,CAAC;4BAAEpC,aAAa;wBAAK;wBAC9CQ,WAAW6B,OAAO,CAACL,eAAe;4BAChCP,MAAM;gCAAExB,WAAW;4BAAE;4BACrBb,YAAY;gCAAEC,KAAK;gCAAGY,WAAW;4BAAE;wBACrC;qBACD;oBAED,OAAO;wBACLqB;wBACAtB;uBAKIiC,WAAW,OAAO,CAAC,IAAI;wBAAEK,iBAAiBL,OAAOhC,SAAS;oBAAC;gBAEnE;gBACAa,OAAOtB,CAAAA,QAASP,oBAAoBO;YACtC;QAEF+C,eAAe,CAACX,OAAOpC,OAAOgD,aAC5BxD,OAAOqB,UAAU,CAAC;gBAChB,yEAAyE;gBACzE,wEAAwE;gBACxE,oEAAoE;gBACpE,oCAAoC;gBACpCC,KAAK,IACHE,WAAWC,SAAS,CAClB;wBAAEb,SAASgC,MAAMhC,OAAO;oBAAC,GACzB;wBACE6C,MAAM;4BAAE1C,UAAU;wBAAE;wBACpBW,MAAM;4BAAEE,WAAWpB;4BAAOQ,aAAawC;wBAAW;oBACpD;gBAEJ1B,OAAO4B,CAAAA,QAASzD,oBAAoByD;YACtC,GAAGb,IAAI,CAAC7C,OAAO8C,MAAM;IACzB;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/outbox/store.ts"],"sourcesContent":["import type { Outbox, OutboxEntry, OutboxEvent } from '@entifix/transactions';\nimport { Effect } from 'effect';\nimport type { Db } from 'mongodb';\n\nimport { translateMongoError } from '../errors/translate-mongo-error.js';\n\n/**\n * The outbox collection, and it lives in the **same database as the entity it\n * describes** — never in a shared control-plane store.\n *\n * Two reasons, and the second only shows up later. Same database means the\n * entity write and its event are one single-database transaction, which stays a\n * single-*shard* transaction if this ever shards; a control-plane outbox would\n * be cross-database from the first commit. And an outbox holds event payloads:\n * a `TransactionEvent` carries no tenant data, but `catalog.published` carries a\n * whole offering and `order.placed` a whole receipt, and neither may land in the\n * control plane on its way to the bus.\n *\n * That rule is why this lives here rather than in one service. It applies\n * identically to a per-organization `tenant_<id>` and to a single platform-plane\n * database, and the second publisher is what turned a copy into a seam.\n */\nexport const OUTBOX_COLLECTION = 'outbox';\n\n/** Drop Mongo's internal `_id` from every read. */\nconst WITHOUT_MONGO_ID = { projection: { _id: 0 } } as const;\n\n/** Mongo's duplicate-key error, which is how a replayed command is recognised. */\nconst DUPLICATE_KEY = 11000;\n\nconst isDuplicateKey = (error: unknown): boolean =>\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === DUPLICATE_KEY;\n\n/**\n * The stored shape of an outbox entry.\n *\n * Exported because the `completed` entry is **not** written through the port:\n * it has to join the entity write's session to be atomic with it, and a session\n * cannot live in a framework-free contract. The handler inserts this document\n * itself; everything else goes through {@link makeMongoOutbox}.\n */\nexport const outboxDocument = (event: OutboxEvent): OutboxEntry => ({\n eventId: event.id,\n aggregate: event.aggregate,\n version: event.version,\n event,\n sent: false,\n // Defaulted here rather than at each write site because there are two of\n // them: the relay's `enqueue`, and the transaction handler's own insert\n // inside the entity's Mongo session. An entry missing `attempts` would sort\n // into `pending` and then fail `attempts + 1` arithmetic on a `undefined`.\n attempts: 0,\n quarantined: false,\n createdAt: event.at,\n});\n\n/**\n * Puts a **quarantined** entry back in the queue, and touches nothing else.\n *\n * A rebuild walk's repair for the one failure measured on a live lab: with the\n * broker down long enough, the relay spends `outbox.maxAttempts` on an\n * announcement and quarantines it (the deliberate skip-so-the-head-moves),\n * after which the tenant store reads one thing and the storefront shows another\n * with nothing reporting it. Re-emitting cannot help on its own — the event id is\n * `<offeringId>:<publishedAt>` and the unique index answers `duplicate`.\n *\n * ⚠️ **`quarantined: true` is in the filter, not the update.** An entry that is\n * merely pending keeps its `attempts`, and one already `sent` is never re-sent —\n * which is what keeps this from quietly becoming \"re-announce everything\", a\n * walk that would re-publish the whole fleet on every boot and un-quarantine\n * genuine poison each time.\n *\n * Not an `Outbox` method: the port is framework-free and shared by\n * every publisher, and this is a repair specific to the rebuild. `outboxDocument`\n * is exported beside it for the same class of reason.\n *\n * Answers whether an entry was actually revived.\n */\nexport const reviveQuarantined = (db: Db, eventId: string) =>\n Effect.tryPromise({\n try: async () => {\n const result = await db\n .collection<OutboxEntry>(OUTBOX_COLLECTION)\n .updateOne(\n { eventId, quarantined: true },\n {\n $set: { sent: false, quarantined: false, attempts: 0 },\n // The failure that put it here is spent; leaving it would make the\n // next quarantine's log name an error from a different outage.\n $unset: { lastError: '' },\n },\n );\n return result.modifiedCount === 1;\n },\n catch: error => translateMongoError(error),\n });\n\n/**\n * Ensures the three indexes the outbox depends on.\n *\n * The unique one is load-bearing rather than defensive: it *is* the idempotency\n * check behind the client-generated transaction id, so a replayed command is\n * rejected by the storage engine rather than by a read-then-write race. It is on\n * `eventId` — `<transactionId>:<step>` for a transaction — so the claim and the\n * bus's deduplication key are one value rather than two that can drift. The\n * partial one keeps the relay's `pending` query cheap once the collection fills\n * with sent entries; it filters on `quarantined` too, so an entry past its\n * ceiling leaves the index rather than being read and skipped forever.\n *\n * Mongo rejects a `createIndex` that reuses a key pattern with a different\n * `partialFilterExpression` (`IndexOptionsConflict`), and this runs on every\n * sweep and every create. A database that predates the `quarantined` filter\n * therefore fails here on every pass — which is loud only because the sweep now\n * logs what it catches. The fix is `pnpm run <app>:dev:reset`; nothing runs in\n * production, so there is no migration to write.\n */\nexport const ensureOutboxIndexes = (db: Db) =>\n Effect.tryPromise({\n try: async () => {\n const collection = db.collection(OUTBOX_COLLECTION);\n await collection.createIndex({ eventId: 1 }, { unique: true });\n await collection.createIndex(\n { createdAt: 1 },\n { partialFilterExpression: { sent: false, quarantined: false } },\n );\n // What the per-aggregate order reads, and what a rebuild finds an\n // aggregate's latest announced version by.\n await collection.createIndex({\n 'aggregate.type': 1,\n 'aggregate.id': 1,\n version: 1,\n });\n },\n catch: error => translateMongoError(error),\n });\n\n/**\n * Mongo-backed {@link Outbox} over one database.\n *\n * `db` is closed over, so every method's Effect has `R = never` — the same\n * technique `makeMongoRepository` uses. There is no publishing here: the relay\n * composes these methods with the event bus, which is what lets the relay be\n * tested without a broker.\n */\nexport const makeMongoOutbox = (db: Db): Outbox => {\n const collection = db.collection<OutboxEntry>(OUTBOX_COLLECTION);\n\n return {\n enqueue: event =>\n Effect.tryPromise({\n try: async () => {\n try {\n await collection.insertOne(outboxDocument(event));\n return 'enqueued' as const;\n } catch (error) {\n // Not a failure: the unique index rejected a second claim for this\n // message id, which is precisely how a retry is identified.\n if (isDuplicateKey(error)) {\n return 'duplicate' as const;\n }\n throw error;\n }\n },\n catch: error => translateMongoError(error),\n }),\n\n pending: limit =>\n Effect.tryPromise({\n // Oldest first, then by version: the relay publishes in this order\n // within each aggregate, so `accepted` reaches the bus before the\n // terminal event of the same transaction.\n try: () =>\n collection\n .find({ sent: false, quarantined: false }, WITHOUT_MONGO_ID)\n .sort({ createdAt: 1, version: 1 })\n .limit(limit)\n .toArray(),\n catch: error => translateMongoError(error),\n }),\n\n markSent: entry =>\n Effect.tryPromise({\n try: () =>\n collection.updateOne(\n { eventId: entry.eventId },\n { $set: { sent: true } },\n ),\n catch: error => translateMongoError(error),\n }).pipe(Effect.asVoid),\n\n stats: () =>\n Effect.tryPromise({\n // Two counts and one `findOne`, rather than reading the entries: the\n // pending set can be arbitrarily large when the relay is stuck, which\n // is exactly the moment this must stay cheap. Both queries ride the\n // partial index on `{ createdAt: 1 }` filtered to the same predicate.\n try: async () => {\n const pendingFilter = { sent: false, quarantined: false };\n const [pending, quarantined, oldest] = await Promise.all([\n collection.countDocuments(pendingFilter),\n collection.countDocuments({ quarantined: true }),\n collection.findOne(pendingFilter, {\n sort: { createdAt: 1 },\n projection: { _id: 0, createdAt: 1 },\n }),\n ]);\n\n return {\n pending,\n quarantined,\n // Absent rather than zero when the outbox is empty: an age of zero\n // and \"nothing is waiting\" are opposite conditions, and a gauge\n // that reports 0 for both is indistinguishable from a healthy relay\n // at exactly the moment it is not one.\n ...(oldest === null ? {} : { oldestPendingAt: oldest.createdAt }),\n };\n },\n catch: error => translateMongoError(error),\n }),\n\n recordFailure: (entry, error, quarantine) =>\n Effect.tryPromise({\n // `$inc` rather than a read-modify-write: two relays can be draining the\n // same tenant (the request's inline drain and the daemon sweep), and an\n // absolute write would let one of them lose the other's attempt and\n // stretch the ceiling indefinitely.\n try: () =>\n collection.updateOne(\n { eventId: entry.eventId },\n {\n $inc: { attempts: 1 },\n $set: { lastError: error, quarantined: quarantine },\n },\n ),\n catch: cause => translateMongoError(cause),\n }).pipe(Effect.asVoid),\n };\n};\n"],"names":["Effect","translateMongoError","OUTBOX_COLLECTION","WITHOUT_MONGO_ID","projection","_id","DUPLICATE_KEY","isDuplicateKey","error","code","outboxDocument","event","eventId","id","aggregate","version","sent","attempts","quarantined","createdAt","at","reviveQuarantined","db","tryPromise","try","result","collection","updateOne","$set","$unset","lastError","modifiedCount","catch","ensureOutboxIndexes","createIndex","unique","partialFilterExpression","makeMongoOutbox","enqueue","insertOne","pending","limit","find","sort","toArray","markSent","entry","pipe","asVoid","stats","pendingFilter","oldest","Promise","all","countDocuments","findOne","oldestPendingAt","recordFailure","quarantine","$inc","cause"],"mappings":";AACA,SAASA,MAAM,QAAQ,SAAS;AAGhC,SAASC,mBAAmB,QAAQ,qCAAqC;AAEzE;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,oBAAoB,SAAS;AAE1C,iDAAiD,GACjD,MAAMC,mBAAmB;IAAEC,YAAY;QAAEC,KAAK;IAAE;AAAE;AAElD,gFAAgF,GAChF,MAAMC,gBAAgB;AAEtB,MAAMC,iBAAiB,CAACC,QACtB,OAAOA,UAAU,YACjBA,UAAU,QACV,A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wBAAOE,aAAa;oBAAM;oBACxD,MAAM,CAACsB,SAAStB,aAAaiC,OAAO,GAAG,MAAMC,QAAQC,GAAG,CAAC;wBACvD3B,WAAW4B,cAAc,CAACJ;wBAC1BxB,WAAW4B,cAAc,CAAC;4BAAEpC,aAAa;wBAAK;wBAC9CQ,WAAW6B,OAAO,CAACL,eAAe;4BAChCP,MAAM;gCAAExB,WAAW;4BAAE;4BACrBf,YAAY;gCAAEC,KAAK;gCAAGc,WAAW;4BAAE;wBACrC;qBACD;oBAED,OAAO;wBACLqB;wBACAtB;uBAKIiC,WAAW,OAAO,CAAC,IAAI;wBAAEK,iBAAiBL,OAAOhC,SAAS;oBAAC;gBAEnE;gBACAa,OAAOxB,CAAAA,QAASP,oBAAoBO;YACtC;QAEFiD,eAAe,CAACX,OAAOtC,OAAOkD,aAC5B1D,OAAOuB,UAAU,CAAC;gBAChB,yEAAyE;gBACzE,wEAAwE;gBACxE,oEAAoE;gBACpE,oCAAoC;gBACpCC,KAAK,IACHE,WAAWC,SAAS,CAClB;wBAAEf,SAASkC,MAAMlC,OAAO;oBAAC,GACzB;wBACE+C,MAAM;4BAAE1C,UAAU;wBAAE;wBACpBW,MAAM;4BAAEE,WAAWtB;4BAAOU,aAAawC;wBAAW;oBACpD;gBAEJ1B,OAAO4B,CAAAA,QAAS3D,oBAAoB2D;YACtC,GAAGb,IAAI,CAAC/C,OAAOgD,MAAM;IACzB;AACF,EAAE"}
@@ -9,6 +9,7 @@
9
9
  * the manifest — importing this module without that peer installed is the
10
10
  * error, and it is the adopter's to make deliberately.
11
11
  */
12
+ export * from '../idempotency/store.js';
12
13
  export * from '../inbox/store.js';
13
14
  export * from '../outbox/metrics.js';
14
15
  export * from '../outbox/relay.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/transactions/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,cAAc,mBAAmB,CAAC;AAClC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,kCAAkC,CAAC;AACjD,cAAc,uCAAuC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/transactions/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,cAAc,yBAAyB,CAAC;AACxC,cAAc,mBAAmB,CAAC;AAClC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,kCAAkC,CAAC;AACjD,cAAc,uCAAuC,CAAC"}
@@ -8,7 +8,8 @@
8
8
  * actually keeps it optional is the `peerDependenciesMeta.optional` entry in
9
9
  * the manifest — importing this module without that peer installed is the
10
10
  * error, and it is the adopter's to make deliberately.
11
- */ export * from '../inbox/store.js';
11
+ */ export * from '../idempotency/store.js';
12
+ export * from '../inbox/store.js';
12
13
  export * from '../outbox/metrics.js';
13
14
  export * from '../outbox/relay.js';
14
15
  export * from '../outbox/store.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/transactions/index.ts"],"sourcesContent":["/**\n * The half of this package that needs `@entifix/transactions`: the\n * transactional outbox written inside the entity's own Mongo\n * transaction, and the inbox that makes a redelivered command idempotent.\n *\n * Behind a subpath so entity CRUD over Mongo does not arrive with the saga\n * engine attached. Package-level dependencies are not per-subpath, so what\n * actually keeps it optional is the `peerDependenciesMeta.optional` entry in\n * the manifest — importing this module without that peer installed is the\n * error, and it is the adopter's to make deliberately.\n */\nexport * from '../inbox/store.js';\nexport * from '../outbox/metrics.js';\nexport * from '../outbox/relay.js';\nexport * from '../outbox/store.js';\nexport * from '../saga/store.js';\nexport * from '../unit-of-work/command-inbox.js';\nexport * from '../unit-of-work/mongo-unit-of-work.js';\n"],"names":[],"mappings":"AAAA;;;;;;;;;;CAUC,GACD,cAAc,oBAAoB;AAClC,cAAc,uBAAuB;AACrC,cAAc,qBAAqB;AACnC,cAAc,qBAAqB;AACnC,cAAc,mBAAmB;AACjC,cAAc,mCAAmC;AACjD,cAAc,wCAAwC"}
1
+ {"version":3,"sources":["../../src/transactions/index.ts"],"sourcesContent":["/**\n * The half of this package that needs `@entifix/transactions`: the\n * transactional outbox written inside the entity's own Mongo\n * transaction, and the inbox that makes a redelivered command idempotent.\n *\n * Behind a subpath so entity CRUD over Mongo does not arrive with the saga\n * engine attached. Package-level dependencies are not per-subpath, so what\n * actually keeps it optional is the `peerDependenciesMeta.optional` entry in\n * the manifest — importing this module without that peer installed is the\n * error, and it is the adopter's to make deliberately.\n */\nexport * from '../idempotency/store.js';\nexport * from '../inbox/store.js';\nexport * from '../outbox/metrics.js';\nexport * from '../outbox/relay.js';\nexport * from '../outbox/store.js';\nexport * from '../saga/store.js';\nexport * from '../unit-of-work/command-inbox.js';\nexport * from '../unit-of-work/mongo-unit-of-work.js';\n"],"names":[],"mappings":"AAAA;;;;;;;;;;CAUC,GACD,cAAc,0BAA0B;AACxC,cAAc,oBAAoB;AAClC,cAAc,uBAAuB;AACrC,cAAc,qBAAqB;AACnC,cAAc,qBAAqB;AACnC,cAAc,mBAAmB;AACjC,cAAc,mCAAmC;AACjD,cAAc,wCAAwC"}
@@ -1 +1 @@
1
- {"version":3,"file":"mongo-unit-of-work.d.ts","sourceRoot":"","sources":["../../src/unit-of-work/mongo-unit-of-work.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAEV,UAAU,EAGX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,OAAO,EAAU,KAAK,EAA4B,MAAM,QAAQ,CAAC;AAC1E,OAAO,KAAK,EAAE,aAAa,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AASjD,OAAO,EACL,cAAc,EACd,gBAAgB,EACjB,MAAM,qCAAqC,CAAC;AAc7C;;;;GAIG;AACH,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,EAAE,EAAE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C;CAqHpD,CAAC;AAEF,8CAA8C;AAC9C,eAAO,MAAM,mBAAmB,GAAI,SAAS;IAC3C,QAAQ,CAAC,MAAM,EAAE,kBAAkB,CAAC;IACpC,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC;CACjB,KAAG,UAAU,CAAC,SAAS,CACsC,CAAC;;AAE/D,wDAAwD;AACxD,qBAAa,kBAAmB,SAAQ,uBAGf;CAAG;AAE5B;;;GAGG;AACH,eAAO,MAAM,oBAAoB,2EAOhC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/unit-of-work/mongo-unit-of-work.ts"],"sourcesContent":["import {\n Contention,\n type DomainEvent,\n isFailure,\n isStoreFault,\n type StoreFault,\n} from '@entifix/core';\nimport type {\n UnitClaim,\n UnitOfWork,\n UnitOutcome,\n UnitRunOptions,\n} from '@entifix/transactions';\nimport { Context, Effect, Layer, Option, Result, Schedule } from 'effect';\nimport type { ClientSession, Db } from 'mongodb';\n\nimport { translateMongoFault } from '../errors/translate-mongo-error.js';\nimport {\n ensureInboxIndexes,\n INBOX_COLLECTION,\n inboxDocument,\n isDuplicateKey,\n} from '../inbox/store.js';\nimport {\n MongoClientTag,\n MongoDatabaseTag,\n} from '../mongo-database/mongo-database.js';\nimport {\n ensureOutboxIndexes,\n OUTBOX_COLLECTION,\n outboxDocument,\n} from '../outbox/store.js';\nimport {\n COMMAND_INBOX_COLLECTION,\n commandClaimDocument,\n ensureCommandInboxIndexes,\n readCommandReplay,\n rememberCommandReplay,\n} from './command-inbox.js';\n\n/**\n * What a Mongo unit's body writes through: the database and the session bound\n * to the unit's transaction. Every write must pass `{ session }`, or it is not\n * part of the unit.\n */\nexport interface MongoUnit {\n readonly db: Db;\n readonly session: ClientSession;\n}\n\n/** What starts a session — a `MongoClient`, structurally. */\nexport interface MongoSessionSource {\n startSession(): ClientSession;\n}\n\n/**\n * How many times a unit runs before a transient conflict is reported as the\n * failure it is, and how long it waits between runs.\n *\n * Measured against a real replica set: eight units incrementing one document\n * at once conflict on every attempt but one, so a short fixed retry count\n * starves most of them. A jittered exponential back-off spreads the reruns so\n * each eventually runs alone.\n */\nconst ATTEMPTS = 10;\nconst BACK_OFF = Schedule.exponential('5 millis', 1.5).pipe(Schedule.jittered);\n\nconst hasErrorLabel = (error: unknown, label: string): boolean => {\n const candidate = error as {\n hasErrorLabel?: (label: string) => boolean;\n errorLabels?: readonly string[];\n } | null;\n return (\n candidate?.hasErrorLabel?.(label) ??\n candidate?.errorLabels?.includes(label) ??\n false\n );\n};\n\n/**\n * Whether a server label is on `error` or anywhere in its cause chain — a\n * driver error reaches here wrapped once by the adapter and possibly again by\n * the body that called the driver.\n */\nconst labelledInChain = (error: unknown, label: string): boolean => {\n let current: unknown = error;\n for (let depth = 0; current != null && depth < 5; depth += 1) {\n if (hasErrorLabel(current, label)) return true;\n current = (current as { cause?: unknown }).cause;\n }\n return false;\n};\n\n/** A transient conflict, which reruns the whole unit. */\nconst isTransient = (error: unknown): boolean =>\n isFailure(error) && error._tag === 'Contention';\n\nconst fault = (error: unknown): StoreFault => translateMongoFault(error);\n\nconst driver = <A>(run: () => Promise<A>) =>\n Effect.tryPromise({ try: run, catch: fault });\n\n/** A duplicate-key rejection answered as `duplicate` rather than as an error. */\nconst insertOrDuplicate = (run: () => Promise<unknown>) =>\n Effect.tryPromise({\n try: async () => {\n try {\n await run();\n return 'inserted' as const;\n } catch (error) {\n if (isDuplicateKey(error)) return 'duplicate' as const;\n throw error;\n }\n },\n catch: fault,\n });\n\nconst takeClaim = (db: Db, session: ClientSession, claim: UnitClaim) =>\n claim.kind === 'event'\n ? insertOrDuplicate(() =>\n db\n .collection(INBOX_COLLECTION)\n .insertOne(inboxDocument(claim.consumer, claim.eventId), {\n session,\n }),\n )\n : insertOrDuplicate(() =>\n db\n .collection(COMMAND_INBOX_COLLECTION)\n .insertOne(commandClaimDocument(claim.commandId), { session }),\n );\n\n/**\n * Commits, retrying a commit whose result the server could not report. Such a\n * commit may or may not have applied, and Mongo makes retrying it safe.\n */\n/**\n * Retried on the **driver's** error, before translation: the label that says\n * the commit's result is unknown lives on it, and a translated failure no\n * longer carries it.\n */\nconst commit = (session: ClientSession) =>\n Effect.tryPromise({\n try: () => session.commitTransaction(),\n catch: error => error,\n }).pipe(\n Effect.retry({\n times: ATTEMPTS - 1,\n while: error => labelledInChain(error, 'UnknownTransactionCommitResult'),\n }),\n Effect.mapError(fault),\n );\n\n/** Rolls back, and never fails: the unit is already ending for another reason. */\nconst abort = (session: ClientSession) =>\n driver(() => session.abortTransaction()).pipe(Effect.ignore);\n\ntype Decision<A> =\n | { readonly kind: 'commit'; readonly value: A }\n | { readonly kind: 'duplicate' };\n\n/**\n * A {@link UnitOfWork} per database, sharing one client — the shape a\n * per-organization store needs, where the database is resolved inside the\n * request. Each database's indexes are ensured once, before its first unit.\n */\nexport const makeMongoUnitsOfWork = (client: MongoSessionSource) => {\n const ensured = new Map<string, Promise<void>>();\n\n const ensureIndexes = (db: Db) =>\n Effect.suspend(() => {\n const key = db.databaseName;\n const done = ensured.get(key);\n if (done !== undefined) {\n return driver(() => done);\n }\n const pending = Effect.runPromise(\n Effect.all([\n ensureOutboxIndexes(db),\n ensureInboxIndexes(db),\n ensureCommandInboxIndexes(db),\n ]),\n ).then(() => undefined);\n ensured.set(key, pending);\n // A failed ensure must be retried by the next unit, not remembered.\n pending.catch(() => ensured.delete(key));\n return driver(() => pending);\n });\n\n const forDatabase = (db: Db): UnitOfWork<MongoUnit> => {\n const attempt = <A, E, R>(\n body: (unit: {\n readonly handle: MongoUnit;\n emit(event: DomainEvent): void;\n }) => Effect.Effect<A, E, R>,\n options: UnitRunOptions<A, R> | undefined,\n ) =>\n Effect.acquireUseRelease(\n Effect.sync(() => client.startSession()),\n session =>\n Effect.gen(function* () {\n yield* Effect.try({\n try: () => session.startTransaction(),\n catch: fault,\n });\n\n const work = Effect.gen(function* () {\n const claim = options?.claim;\n if (\n claim &&\n (yield* takeClaim(db, session, claim)) === 'duplicate'\n ) {\n return { kind: 'duplicate' } as Decision<A>;\n }\n\n const emitted: DomainEvent[] = [];\n const value = yield* body({\n handle: { db, session },\n emit: event => void emitted.push(event),\n });\n\n if (emitted.length > 0) {\n const written = yield* insertOrDuplicate(() =>\n db\n .collection(OUTBOX_COLLECTION)\n .insertMany(emitted.map(outboxDocument), { session }),\n );\n // An event id already recorded is the outbox's own\n // idempotency claim: what it announces committed before.\n if (written === 'duplicate') {\n return { kind: 'duplicate' } as Decision<A>;\n }\n }\n\n if (claim?.kind === 'command' && options?.replay) {\n const replay = options.replay(value);\n yield* driver(() =>\n rememberCommandReplay(db, session, claim.commandId, replay),\n );\n }\n return { kind: 'commit', value } as Decision<A>;\n });\n\n const decided = yield* Effect.result(work);\n\n if (Result.isFailure(decided)) {\n yield* abort(session);\n const failure = decided.failure;\n if (isStoreFault(failure)) {\n return yield* Effect.fail(failure);\n }\n // A conflict the body surfaced without translating is still the\n // store's, not a business decision: it is retried, not aborted.\n if (labelledInChain(failure, 'TransientTransactionError')) {\n return yield* Effect.fail(new Contention());\n }\n return {\n _tag: 'aborted',\n reason: failure as Exclude<E, StoreFault>,\n } as UnitOutcome<A, Exclude<E, StoreFault>>;\n }\n\n if (decided.success.kind === 'duplicate') {\n yield* abort(session);\n const replay =\n options?.claim?.kind === 'command'\n ? yield* readCommandReplay(db, options.claim.commandId)\n : Option.none();\n return { _tag: 'duplicate', replay } as UnitOutcome<\n A,\n Exclude<E, StoreFault>\n >;\n }\n\n yield* commit(session);\n return {\n _tag: 'committed',\n value: decided.success.value,\n } as UnitOutcome<A, Exclude<E, StoreFault>>;\n }),\n session => driver(() => session.endSession()).pipe(Effect.ignore),\n );\n\n return {\n run: (body, options) =>\n Effect.gen(function* () {\n yield* ensureIndexes(db);\n const outcome = yield* attempt(body, options).pipe(\n // The whole unit runs again, body included: that is why the body\n // must be retry-safe.\n Effect.retry({\n times: ATTEMPTS - 1,\n while: isTransient,\n schedule: BACK_OFF,\n }),\n );\n if (outcome._tag === 'committed' && options?.afterCommit) {\n yield* options.afterCommit.pipe(Effect.ignore);\n }\n return outcome;\n }),\n replay: commandId => readCommandReplay(db, commandId),\n };\n };\n\n return { forDatabase };\n};\n\n/** A {@link UnitOfWork} over one database. */\nexport const makeMongoUnitOfWork = (options: {\n readonly client: MongoSessionSource;\n readonly db: Db;\n}): UnitOfWork<MongoUnit> =>\n makeMongoUnitsOfWork(options.client).forDatabase(options.db);\n\n/** The unit of work over the service's own database. */\nexport class MongoUnitOfWorkTag extends Context.Service<\n MongoUnitOfWorkTag,\n UnitOfWork<MongoUnit>\n>()('MongoUnitOfWorkTag') {}\n\n/**\n * Provides {@link MongoUnitOfWorkTag} from the client and the named database\n * {@link MongoDatabaseLayer} opened.\n */\nexport const MongoUnitOfWorkLayer = Layer.effect(\n MongoUnitOfWorkTag,\n Effect.gen(function* () {\n const client = yield* MongoClientTag;\n const db = yield* MongoDatabaseTag;\n return makeMongoUnitOfWork({ client, db });\n }),\n);\n"],"names":["Contention","isFailure","isStoreFault","Context","Effect","Layer","Option","Result","Schedule","translateMongoFault","ensureInboxIndexes","INBOX_COLLECTION","inboxDocument","isDuplicateKey","MongoClientTag","MongoDatabaseTag","ensureOutboxIndexes","OUTBOX_COLLECTION","outboxDocument","COMMAND_INBOX_COLLECTION","commandClaimDocument","ensureCommandInboxIndexes","readCommandReplay","rememberCommandReplay","ATTEMPTS","BACK_OFF","exponential","pipe","jittered","hasErrorLabel","error","label","candidate","errorLabels","includes","labelledInChain","current","depth","cause","isTransient","_tag","fault","driver","run","tryPromise","try","catch","insertOrDuplicate","takeClaim","db","session","claim","kind","collection","insertOne","consumer","eventId","commandId","commit","commitTransaction","retry","times","while","mapError","abort","abortTransaction","ignore","makeMongoUnitsOfWork","client","ensured","Map","ensureIndexes","suspend","key","databaseName","done","get","undefined","pending","runPromise","all","then","set","delete","forDatabase","attempt","body","options","acquireUseRelease","sync","startSession","gen","startTransaction","work","emitted","value","handle","emit","event","push","length","written","insertMany","map","replay","decided","result","failure","fail","reason","success","none","endSession","outcome","schedule","afterCommit","makeMongoUnitOfWork","MongoUnitOfWorkTag","Service","MongoUnitOfWorkLayer","effect"],"mappings":"AAAA,SACEA,UAAU,EAEVC,SAAS,EACTC,YAAY,QAEP,gBAAgB;AAOvB,SAASC,OAAO,EAAEC,MAAM,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,SAAS;AAG1E,SAASC,mBAAmB,QAAQ,qCAAqC;AACzE,SACEC,kBAAkB,EAClBC,gBAAgB,EAChBC,aAAa,EACbC,cAAc,QACT,oBAAoB;AAC3B,SACEC,cAAc,EACdC,gBAAgB,QACX,sCAAsC;AAC7C,SACEC,mBAAmB,EACnBC,iBAAiB,EACjBC,cAAc,QACT,qBAAqB;AAC5B,SACEC,wBAAwB,EACxBC,oBAAoB,EACpBC,yBAAyB,EACzBC,iBAAiB,EACjBC,qBAAqB,QAChB,qBAAqB;AAiB5B;;;;;;;;CAQC,GACD,MAAMC,WAAW;AACjB,MAAMC,WAAWjB,SAASkB,WAAW,CAAC,YAAY,KAAKC,IAAI,CAACnB,SAASoB,QAAQ;AAE7E,MAAMC,gBAAgB,CAACC,OAAgBC;QAMnCC;QAAAA,0BACAA;IANF,MAAMA,YAAYF;IAIlB,QACEE,gBAAAA,8BAAAA,2BAAAA,UAAWH,aAAa,qBAAxBG,8BAAAA,WAA2BD,0BAC3BC,8BAAAA,yBAAAA,UAAWC,WAAW,qBAAtBD,uBAAwBE,QAAQ,CAACH,kBADjCC,OAEA;AAEJ;AAEA;;;;CAIC,GACD,MAAMG,kBAAkB,CAACL,OAAgBC;IACvC,IAAIK,UAAmBN;IACvB,IAAK,IAAIO,QAAQ,GAAGD,WAAW,QAAQC,QAAQ,GAAGA,SAAS,EAAG;QAC5D,IAAIR,cAAcO,SAASL,QAAQ,OAAO;QAC1CK,UAAU,AAACA,QAAgCE,KAAK;IAClD;IACA,OAAO;AACT;AAEA,uDAAuD,GACvD,MAAMC,cAAc,CAACT,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ACf,KAAK;oBAC9B;gBACF,IACF7C,CAAAA,UAAWR,OAAO,IAAMQ,QAAQ8D,UAAU,IAAIrF,IAAI,CAACvB,OAAO8D,MAAM;QAGpE,OAAO;YACLvB,KAAK,CAAC2C,MAAMC,UACVnF,OAAOuF,GAAG,CAAC;oBACT,OAAOpB,cAActB;oBACrB,MAAMgE,UAAU,OAAO5B,QAAQC,MAAMC,SAAS5D,IAAI,CAChD,iEAAiE;oBACjE,sBAAsB;oBACtBvB,OAAOwD,KAAK,CAAC;wBACXC,OAAOrC,WAAW;wBAClBsC,OAAOvB;wBACP2E,UAAUzF;oBACZ;oBAEF,IAAIwF,QAAQzE,IAAI,KAAK,gBAAe+C,2BAAAA,QAAS4B,WAAW,GAAE;wBACxD,OAAO5B,QAAQ4B,WAAW,CAACxF,IAAI,CAACvB,OAAO8D,MAAM;oBAC/C;oBACA,OAAO+C;gBACT;YACFT,QAAQ/C,CAAAA,YAAanC,kBAAkB2B,IAAIQ;QAC7C;IACF;IAEA,OAAO;QAAE2B;IAAY;AACvB,EAAE;AAEF,4CAA4C,GAC5C,OAAO,MAAMgC,sBAAsB,CAAC7B,UAIlCpB,qBAAqBoB,QAAQnB,MAAM,EAAEgB,WAAW,CAACG,QAAQtC,EAAE,EAAE;AAE/D,sDAAsD,GACtD,OAAO,MAAMoE,2BAA2BlH,QAAQmH,OAAO,GAGnD;AAAuB;AAE3B;;;CAGC,GACD,OAAO,MAAMC,uBAAuBlH,MAAMmH,MAAM,CAC9CH,oBACAjH,OAAOuF,GAAG,CAAC;IACT,MAAMvB,SAAS,OAAOtD;IACtB,MAAMmC,KAAK,OAAOlC;IAClB,OAAOqG,oBAAoB;QAAEhD;QAAQnB;IAAG;AAC1C,IACA"}
1
+ {"version":3,"sources":["../../src/unit-of-work/mongo-unit-of-work.ts"],"sourcesContent":["import {\n Contention,\n isFailure,\n isStoreFault,\n type StoreFault,\n} from '@entifix/core';\nimport type {\n OutboxEvent,\n UnitClaim,\n UnitOfWork,\n UnitOutcome,\n UnitRunOptions,\n} from '@entifix/transactions';\nimport { Context, Effect, Layer, Option, Result, Schedule } from 'effect';\nimport type { ClientSession, Db } from 'mongodb';\n\nimport { translateMongoFault } from '../errors/translate-mongo-error.js';\nimport {\n ensureInboxIndexes,\n INBOX_COLLECTION,\n inboxDocument,\n isDuplicateKey,\n} from '../inbox/store.js';\nimport {\n MongoClientTag,\n MongoDatabaseTag,\n} from '../mongo-database/mongo-database.js';\nimport {\n ensureOutboxIndexes,\n OUTBOX_COLLECTION,\n outboxDocument,\n} from '../outbox/store.js';\nimport {\n COMMAND_INBOX_COLLECTION,\n commandClaimDocument,\n ensureCommandInboxIndexes,\n readCommandReplay,\n rememberCommandReplay,\n} from './command-inbox.js';\n\n/**\n * What a Mongo unit's body writes through: the database and the session bound\n * to the unit's transaction. Every write must pass `{ session }`, or it is not\n * part of the unit.\n */\nexport interface MongoUnit {\n readonly db: Db;\n readonly session: ClientSession;\n}\n\n/** What starts a session — a `MongoClient`, structurally. */\nexport interface MongoSessionSource {\n startSession(): ClientSession;\n}\n\n/**\n * How many times a unit runs before a transient conflict is reported as the\n * failure it is, and how long it waits between runs.\n *\n * Measured against a real replica set: eight units incrementing one document\n * at once conflict on every attempt but one, so a short fixed retry count\n * starves most of them. A jittered exponential back-off spreads the reruns so\n * each eventually runs alone.\n */\nconst ATTEMPTS = 10;\nconst BACK_OFF = Schedule.exponential('5 millis', 1.5).pipe(Schedule.jittered);\n\nconst hasErrorLabel = (error: unknown, label: string): boolean => {\n const candidate = error as {\n hasErrorLabel?: (label: string) => boolean;\n errorLabels?: readonly string[];\n } | null;\n return (\n candidate?.hasErrorLabel?.(label) ??\n candidate?.errorLabels?.includes(label) ??\n false\n );\n};\n\n/**\n * Whether a server label is on `error` or anywhere in its cause chain — a\n * driver error reaches here wrapped once by the adapter and possibly again by\n * the body that called the driver.\n */\nconst labelledInChain = (error: unknown, label: string): boolean => {\n let current: unknown = error;\n for (let depth = 0; current != null && depth < 5; depth += 1) {\n if (hasErrorLabel(current, label)) return true;\n current = (current as { cause?: unknown }).cause;\n }\n return false;\n};\n\n/** A transient conflict, which reruns the whole unit. */\nconst isTransient = (error: unknown): boolean =>\n isFailure(error) && error._tag === 'Contention';\n\nconst fault = (error: unknown): StoreFault => translateMongoFault(error);\n\nconst driver = <A>(run: () => Promise<A>) =>\n Effect.tryPromise({ try: run, catch: fault });\n\n/** A duplicate-key rejection answered as `duplicate` rather than as an error. */\nconst insertOrDuplicate = (run: () => Promise<unknown>) =>\n Effect.tryPromise({\n try: async () => {\n try {\n await run();\n return 'inserted' as const;\n } catch (error) {\n if (isDuplicateKey(error)) return 'duplicate' as const;\n throw error;\n }\n },\n catch: fault,\n });\n\nconst takeClaim = (db: Db, session: ClientSession, claim: UnitClaim) =>\n claim.kind === 'event'\n ? insertOrDuplicate(() =>\n db\n .collection(INBOX_COLLECTION)\n .insertOne(inboxDocument(claim.consumer, claim.eventId), {\n session,\n }),\n )\n : insertOrDuplicate(() =>\n db\n .collection(COMMAND_INBOX_COLLECTION)\n .insertOne(commandClaimDocument(claim.commandId), { session }),\n );\n\n/**\n * Commits, retrying a commit whose result the server could not report. Such a\n * commit may or may not have applied, and Mongo makes retrying it safe.\n */\n/**\n * Retried on the **driver's** error, before translation: the label that says\n * the commit's result is unknown lives on it, and a translated failure no\n * longer carries it.\n */\nconst commit = (session: ClientSession) =>\n Effect.tryPromise({\n try: () => session.commitTransaction(),\n catch: error => error,\n }).pipe(\n Effect.retry({\n times: ATTEMPTS - 1,\n while: error => labelledInChain(error, 'UnknownTransactionCommitResult'),\n }),\n Effect.mapError(fault),\n );\n\n/** Rolls back, and never fails: the unit is already ending for another reason. */\nconst abort = (session: ClientSession) =>\n driver(() => session.abortTransaction()).pipe(Effect.ignore);\n\ntype Decision<A> =\n | { readonly kind: 'commit'; readonly value: A }\n | { readonly kind: 'duplicate' };\n\n/**\n * A {@link UnitOfWork} per database, sharing one client — the shape a\n * per-organization store needs, where the database is resolved inside the\n * request. Each database's indexes are ensured once, before its first unit.\n */\nexport const makeMongoUnitsOfWork = (client: MongoSessionSource) => {\n const ensured = new Map<string, Promise<void>>();\n\n const ensureIndexes = (db: Db) =>\n Effect.suspend(() => {\n const key = db.databaseName;\n const done = ensured.get(key);\n if (done !== undefined) {\n return driver(() => done);\n }\n const pending = Effect.runPromise(\n Effect.all([\n ensureOutboxIndexes(db),\n ensureInboxIndexes(db),\n ensureCommandInboxIndexes(db),\n ]),\n ).then(() => undefined);\n ensured.set(key, pending);\n // A failed ensure must be retried by the next unit, not remembered.\n pending.catch(() => ensured.delete(key));\n return driver(() => pending);\n });\n\n const forDatabase = (db: Db): UnitOfWork<MongoUnit> => {\n const attempt = <A, E, R>(\n body: (unit: {\n readonly handle: MongoUnit;\n emit(event: OutboxEvent): void;\n }) => Effect.Effect<A, E, R>,\n options: UnitRunOptions<A, R> | undefined,\n ) =>\n Effect.acquireUseRelease(\n Effect.sync(() => client.startSession()),\n session =>\n Effect.gen(function* () {\n yield* Effect.try({\n try: () => session.startTransaction(),\n catch: fault,\n });\n\n const work = Effect.gen(function* () {\n const claim = options?.claim;\n if (\n claim &&\n (yield* takeClaim(db, session, claim)) === 'duplicate'\n ) {\n return { kind: 'duplicate' } as Decision<A>;\n }\n\n const emitted: OutboxEvent[] = [];\n const value = yield* body({\n handle: { db, session },\n emit: event => void emitted.push(event),\n });\n\n if (emitted.length > 0) {\n const written = yield* insertOrDuplicate(() =>\n db\n .collection(OUTBOX_COLLECTION)\n .insertMany(emitted.map(outboxDocument), { session }),\n );\n // An event id already recorded is the outbox's own\n // idempotency claim: what it announces committed before.\n if (written === 'duplicate') {\n return { kind: 'duplicate' } as Decision<A>;\n }\n }\n\n if (claim?.kind === 'command' && options?.replay) {\n const replay = options.replay(value);\n yield* driver(() =>\n rememberCommandReplay(db, session, claim.commandId, replay),\n );\n }\n return { kind: 'commit', value } as Decision<A>;\n });\n\n const decided = yield* Effect.result(work);\n\n if (Result.isFailure(decided)) {\n yield* abort(session);\n const failure = decided.failure;\n if (isStoreFault(failure)) {\n return yield* Effect.fail(failure);\n }\n // A conflict the body surfaced without translating is still the\n // store's, not a business decision: it is retried, not aborted.\n if (labelledInChain(failure, 'TransientTransactionError')) {\n return yield* Effect.fail(new Contention());\n }\n return {\n _tag: 'aborted',\n reason: failure as Exclude<E, StoreFault>,\n } as UnitOutcome<A, Exclude<E, StoreFault>>;\n }\n\n if (decided.success.kind === 'duplicate') {\n yield* abort(session);\n const replay =\n options?.claim?.kind === 'command'\n ? yield* readCommandReplay(db, options.claim.commandId)\n : Option.none();\n return { _tag: 'duplicate', replay } as UnitOutcome<\n A,\n Exclude<E, StoreFault>\n >;\n }\n\n yield* commit(session);\n return {\n _tag: 'committed',\n value: decided.success.value,\n } as UnitOutcome<A, Exclude<E, StoreFault>>;\n }),\n session => driver(() => session.endSession()).pipe(Effect.ignore),\n );\n\n return {\n run: (body, options) =>\n Effect.gen(function* () {\n yield* ensureIndexes(db);\n const outcome = yield* attempt(body, options).pipe(\n // The whole unit runs again, body included: that is why the body\n // must be retry-safe.\n Effect.retry({\n times: ATTEMPTS - 1,\n while: isTransient,\n schedule: BACK_OFF,\n }),\n );\n if (outcome._tag === 'committed' && options?.afterCommit) {\n yield* options.afterCommit.pipe(Effect.ignore);\n }\n return outcome;\n }),\n replay: commandId => readCommandReplay(db, commandId),\n };\n };\n\n return { forDatabase };\n};\n\n/** A {@link UnitOfWork} over one database. */\nexport const makeMongoUnitOfWork = (options: {\n readonly client: MongoSessionSource;\n readonly db: Db;\n}): UnitOfWork<MongoUnit> =>\n makeMongoUnitsOfWork(options.client).forDatabase(options.db);\n\n/** The unit of work over the service's own database. */\nexport class MongoUnitOfWorkTag extends Context.Service<\n MongoUnitOfWorkTag,\n UnitOfWork<MongoUnit>\n>()('MongoUnitOfWorkTag') {}\n\n/**\n * Provides {@link MongoUnitOfWorkTag} from the client and the named database\n * {@link MongoDatabaseLayer} opened.\n */\nexport const MongoUnitOfWorkLayer = Layer.effect(\n MongoUnitOfWorkTag,\n Effect.gen(function* () {\n const client = yield* MongoClientTag;\n const db = yield* MongoDatabaseTag;\n return makeMongoUnitOfWork({ client, db });\n }),\n);\n"],"names":["Contention","isFailure","isStoreFault","Context","Effect","Layer","Option","Result","Schedule","translateMongoFault","ensureInboxIndexes","INBOX_COLLECTION","inboxDocument","isDuplicateKey","MongoClientTag","MongoDatabaseTag","ensureOutboxIndexes","OUTBOX_COLLECTION","outboxDocument","COMMAND_INBOX_COLLECTION","commandClaimDocument","ensureCommandInboxIndexes","readCommandReplay","rememberCommandReplay","ATTEMPTS","BACK_OFF","exponential","pipe","jittered","hasErrorLabel","error","label","candidate","errorLabels","includes","labelledInChain","current","depth","cause","isTransient","_tag","fault","driver","run","tryPromise","try","catch","insertOrDuplicate","takeClaim","db","session","claim","kind","collection","insertOne","consumer","eventId","commandId","commit","commitTransaction","retry","times","while","mapError","abort","abortTransaction","ignore","makeMongoUnitsOfWork","client","ensured","Map","ensureIndexes","suspend","key","databaseName","done","get","undefined","pending","runPromise","all","then","set","delete","forDatabase","attempt","body","options","acquireUseRelease","sync","startSession","gen","startTransaction","work","emitted","value","handle","emit","event","push","length","written","insertMany","map","replay","decided","result","failure","fail","reason","success","none","endSession","outcome","schedule","afterCommit","makeMongoUnitOfWork","MongoUnitOfWorkTag","Service","MongoUnitOfWorkLayer","effect"],"mappings":"AAAA,SACEA,UAAU,EACVC,SAAS,EACTC,YAAY,QAEP,gBAAgB;AAQvB,SAASC,OAAO,EAAEC,MAAM,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,SAAS;AAG1E,SAASC,mBAAmB,QAAQ,qCAAqC;AACzE,SACEC,kBAAkB,EAClBC,gBAAgB,EAChBC,aAAa,EACbC,cAAc,QACT,oBAAoB;AAC3B,SACEC,cAAc,EACdC,gBAAgB,QACX,sCAAsC;AAC7C,SACEC,mBAAmB,EACnBC,iBAAiB,EACjBC,cAAc,QACT,qBAAqB;AAC5B,SACEC,wB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AACxF,IAAI,CAACvB,OAAO8D,MAAM;oBAC/C;oBACA,OAAO+C;gBACT;YACFT,QAAQ/C,CAAAA,YAAanC,kBAAkB2B,IAAIQ;QAC7C;IACF;IAEA,OAAO;QAAE2B;IAAY;AACvB,EAAE;AAEF,4CAA4C,GAC5C,OAAO,MAAMgC,sBAAsB,CAAC7B,UAIlCpB,qBAAqBoB,QAAQnB,MAAM,EAAEgB,WAAW,CAACG,QAAQtC,EAAE,EAAE;AAE/D,sDAAsD,GACtD,OAAO,MAAMoE,2BAA2BlH,QAAQmH,OAAO,GAGnD;AAAuB;AAE3B;;;CAGC,GACD,OAAO,MAAMC,uBAAuBlH,MAAMmH,MAAM,CAC9CH,oBACAjH,OAAOuF,GAAG,CAAC;IACT,MAAMvB,SAAS,OAAOtD;IACtB,MAAMmC,KAAK,OAAOlC;IAClB,OAAOqG,oBAAoB;QAAEhD;QAAQnB;IAAG;AAC1C,IACA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/mongo",
3
- "version": "0.10.2",
3
+ "version": "0.11.0",
4
4
  "description": "MongoDB adapter: an entity repository, RSQL-to-Mongo query translation, per-tenant databases, and an optional transactional outbox.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -57,17 +57,17 @@
57
57
  "dependencies": {
58
58
  "@swc/helpers": "0.5.23",
59
59
  "mongodb": "7.7.0",
60
- "@entifix/core": "0.10.2",
61
- "@entifix/business": "0.10.2"
60
+ "@entifix/business": "0.11.0",
61
+ "@entifix/core": "0.11.0"
62
62
  },
63
63
  "devDependencies": {
64
64
  "effect": "4.0.6",
65
- "@entifix/transactions": "0.10.2",
66
- "@entifix/testing-unit": "0.10.2"
65
+ "@entifix/testing-unit": "0.11.0",
66
+ "@entifix/transactions": "0.11.0"
67
67
  },
68
68
  "peerDependencies": {
69
69
  "effect": "^4.0.6",
70
- "@entifix/transactions": "0.10.2"
70
+ "@entifix/transactions": "0.11.0"
71
71
  },
72
72
  "peerDependenciesMeta": {
73
73
  "@entifix/transactions": {