@entifix/mongo 0.10.2 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/idempotency/store.d.ts +24 -0
- package/dist/idempotency/store.d.ts.map +1 -0
- package/dist/idempotency/store.js +115 -0
- package/dist/idempotency/store.js.map +1 -0
- package/dist/outbox/relay.d.ts +7 -111
- package/dist/outbox/relay.d.ts.map +1 -1
- package/dist/outbox/relay.js +4 -125
- package/dist/outbox/relay.js.map +1 -1
- package/dist/outbox/store.d.ts +7 -8
- package/dist/outbox/store.d.ts.map +1 -1
- package/dist/outbox/store.js +18 -7
- package/dist/outbox/store.js.map +1 -1
- package/dist/transactions/index.d.ts +1 -1
- package/dist/transactions/index.d.ts.map +1 -1
- package/dist/transactions/index.js +2 -2
- package/dist/transactions/index.js.map +1 -1
- package/dist/unit-of-work/mongo-unit-of-work.d.ts.map +1 -1
- package/dist/unit-of-work/mongo-unit-of-work.js.map +1 -1
- package/package.json +6 -6
- package/dist/outbox/metrics.d.ts +0 -47
- package/dist/outbox/metrics.d.ts.map +0 -1
- package/dist/outbox/metrics.js +0 -68
- package/dist/outbox/metrics.js.map +0 -1
|
@@ -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;gBAAE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OAAOV,CAAAA,QAASX,oBAAoBW;YACtC;QACF8B,UAAU,CAACtC,UAAUG,WACnBP,OAAOgB,UAAU,CAAC;gBAChBC,KAAK,IACHC,WAAWc,SAAS,CAClB;wBAAE5B;oBAAS,GACX;wBAAE8B,MAAM;4BAAE5B,OAAO;4BAAaC;wBAAS;oBAAE;gBAE7Ce,OAAOV,CAAAA,QAASX,oBAAoBW;YACtC,GAAG+B,IAAI,CAAC3C,OAAO4C,MAAM;QACvBC,SAASzC,CAAAA,WACPJ,OAAOgB,UAAU,CAAC;gBAChBC,KAAK,IAAMC,WAAW4B,SAAS,CAAC;wBAAE1C;oBAAS;gBAC3CkB,OAAOV,CAAAA,QAASX,oBAAoBW;YACtC,GAAG+B,IAAI,CAAC3C,OAAO4C,MAAM;IACzB;AACF,EAAE"}
|
package/dist/outbox/relay.d.ts
CHANGED
|
@@ -1,112 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { type EventBus, EventBusTag,
|
|
3
|
-
import {
|
|
1
|
+
import { type TenantDirectory, TenantDirectoryTag } from '@entifix/business';
|
|
2
|
+
import { type EventBus, EventBusTag, OutboxMaxAttempts } from '@entifix/transactions';
|
|
3
|
+
import { type OutboxStatsSink, type RelayOutcomeSink } from '@entifix/transactions/engine';
|
|
4
|
+
import { Effect } from 'effect';
|
|
4
5
|
import type { Db } from 'mongodb';
|
|
5
6
|
import { MongoDatabaseTag } from '../mongo-database/mongo-database.js';
|
|
6
|
-
export declare const SWEEP_INTERVAL: Duration.Duration;
|
|
7
|
-
/** Entries drained per pass, per database. */
|
|
8
|
-
export declare const BATCH = 100;
|
|
9
|
-
/**
|
|
10
|
-
* What a relay pass did, for the host to log
|
|
11
|
-
* ([ADR 0013](../../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).
|
|
12
|
-
*
|
|
13
|
-
* The relay decides nothing about level or sink: it says what happened and the
|
|
14
|
-
* fork site that started it — the slice's shell — decides how loud that is. A
|
|
15
|
-
* `failure` is whatever the store or the bus failed with; a typed one carries
|
|
16
|
-
* its code and category for the log line.
|
|
17
|
-
*/
|
|
18
|
-
export type RelayOutcome = {
|
|
19
|
-
readonly _tag: 'drained';
|
|
20
|
-
readonly database: string;
|
|
21
|
-
readonly sent: number;
|
|
22
|
-
} | {
|
|
23
|
-
readonly _tag: 'quarantined';
|
|
24
|
-
readonly database: string;
|
|
25
|
-
readonly eventId: string;
|
|
26
|
-
readonly eventName: string;
|
|
27
|
-
readonly attempts: number;
|
|
28
|
-
readonly code: string;
|
|
29
|
-
readonly reason: string;
|
|
30
|
-
} | {
|
|
31
|
-
readonly _tag: 'sweepFailed';
|
|
32
|
-
readonly database?: string;
|
|
33
|
-
readonly failure: unknown;
|
|
34
|
-
} | {
|
|
35
|
-
readonly _tag: 'drainFailed';
|
|
36
|
-
readonly database: string;
|
|
37
|
-
readonly failure: unknown;
|
|
38
|
-
};
|
|
39
|
-
/** Where a relay's outcomes go. The host's fork site supplies it. */
|
|
40
|
-
export type RelayOutcomeSink = (outcome: RelayOutcome) => Effect.Effect<void>;
|
|
41
|
-
/**
|
|
42
|
-
* Hears nothing. The default only so a spec can start a relay without one —
|
|
43
|
-
* a host that passes no sink has a relay nobody can watch.
|
|
44
|
-
*/
|
|
45
|
-
export declare const ignoreRelayOutcome: RelayOutcomeSink;
|
|
46
|
-
declare const OutboxMaxAttempts_base: Context.ServiceClass<OutboxMaxAttempts, "OutboxMaxAttempts", number>;
|
|
47
|
-
/**
|
|
48
|
-
* Publish attempts an outbox entry gets before it is quarantined, from
|
|
49
|
-
* config-service.
|
|
50
|
-
*
|
|
51
|
-
* Configuration rather than a constant because it is a genuine operational
|
|
52
|
-
* tunable: raising it while a flaky broker settles is a config edit, and the
|
|
53
|
-
* next sweep reads the new value. That is the opposite of a subscription's
|
|
54
|
-
* `maxAttempts`, which becomes an immutable queue argument and therefore stays
|
|
55
|
-
* a literal beside its declaration.
|
|
56
|
-
*
|
|
57
|
-
* ⚠️ **Read it with `getNumber`, never a cast.** A value of `'five'` casts to
|
|
58
|
-
* `NaN`, every `attempts >= maxAttempts` comparison goes false, and nothing is
|
|
59
|
-
* ever quarantined — a relay that looks healthy while its head never moves.
|
|
60
|
-
*/
|
|
61
|
-
export declare class OutboxMaxAttempts extends OutboxMaxAttempts_base {
|
|
62
|
-
}
|
|
63
|
-
/** What {@link drainOutbox} needs beyond the ports it publishes through. */
|
|
64
|
-
export interface DrainOptions {
|
|
65
|
-
readonly maxAttempts: number;
|
|
66
|
-
/** The database being drained; carried so a quarantine log names it. */
|
|
67
|
-
readonly database: string;
|
|
68
|
-
/** Where the pass reports what it did; see {@link RelayOutcome}. */
|
|
69
|
-
readonly onOutcome?: RelayOutcomeSink;
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* Publish one batch of pending entries, oldest first, and answer how many went.
|
|
73
|
-
*
|
|
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.
|
|
82
|
-
*/
|
|
83
|
-
export declare const drainOutbox: (outbox: TransactionOutbox, bus: EventBus, options: DrainOptions) => Effect.Effect<number, import("@entifix/core").StoreFailure, never>;
|
|
84
|
-
/**
|
|
85
|
-
* Sample a sweep's depth and age.
|
|
86
|
-
*
|
|
87
|
-
* Defaults to {@link recordOutboxStats}, and a caller overrides it only to
|
|
88
|
-
* assert what was sampled. There is no "no sink" option on purpose: an outbox
|
|
89
|
-
* whose depth nothing reports is the failure the gauges exist to make visible.
|
|
90
|
-
*/
|
|
91
|
-
export type OutboxStatsSink = (database: string, stats: OutboxStats) => Effect.Effect<void>;
|
|
92
|
-
/**
|
|
93
|
-
* Drain the one database this service owns, then sample its depth.
|
|
94
|
-
*
|
|
95
|
-
* The single-database counterpart to `startTenantOutboxRelay`. A
|
|
96
|
-
* platform-plane store is one named database, so there is nothing to enumerate
|
|
97
|
-
* and `listDatabases` — which needs a `MongoClient` and cluster-wide rights —
|
|
98
|
-
* never comes into it.
|
|
99
|
-
*
|
|
100
|
-
* Stats are sampled **after** the drain, so the gauge reports what is still
|
|
101
|
-
* waiting rather than what was waiting when the pass began.
|
|
102
|
-
*
|
|
103
|
-
* Every failure is caught and reported as `sweepFailed`. This runs inside
|
|
104
|
-
* `Effect.forever`, and an error that escapes ends the daemon silently — a
|
|
105
|
-
* relay that stopped is indistinguishable from a relay with nothing to do.
|
|
106
|
-
*/
|
|
107
|
-
export declare const sweepOutbox: (outbox: TransactionOutbox, bus: EventBus, options: DrainOptions & {
|
|
108
|
-
readonly onStats?: OutboxStatsSink;
|
|
109
|
-
}) => Effect.Effect<void, never, never>;
|
|
110
7
|
/**
|
|
111
8
|
* Start the relay for a service that owns exactly one database.
|
|
112
9
|
*
|
|
@@ -124,7 +21,7 @@ export declare const sweepOutbox: (outbox: TransactionOutbox, bus: EventBus, opt
|
|
|
124
21
|
export declare const startOutboxRelay: (options?: {
|
|
125
22
|
readonly onStats?: OutboxStatsSink;
|
|
126
23
|
readonly onOutcome?: RelayOutcomeSink;
|
|
127
|
-
}) => Effect.Effect<void, import("@entifix/core").StoreFailure, ShutdownRegistryTag | MongoDatabaseTag |
|
|
24
|
+
}) => Effect.Effect<void, import("@entifix/core").StoreFailure, import("@entifix/business").ShutdownRegistryTag | MongoDatabaseTag | OutboxMaxAttempts | EventBusTag>;
|
|
128
25
|
/**
|
|
129
26
|
* One pass over every organization's outbox in a per-organization store.
|
|
130
27
|
*
|
|
@@ -153,7 +50,7 @@ export declare const sweepTenantOutboxes: (directory: TenantDirectory<Db>, bus:
|
|
|
153
50
|
export declare const startTenantOutboxRelay: (options?: {
|
|
154
51
|
readonly onStats?: OutboxStatsSink;
|
|
155
52
|
readonly onOutcome?: RelayOutcomeSink;
|
|
156
|
-
}) => Effect.Effect<void, never, ShutdownRegistryTag | TenantDirectoryTag |
|
|
53
|
+
}) => Effect.Effect<void, never, import("@entifix/business").ShutdownRegistryTag | TenantDirectoryTag | OutboxMaxAttempts | EventBusTag>;
|
|
157
54
|
/**
|
|
158
55
|
* Drain one database's outbox now, for a write path that has just committed.
|
|
159
56
|
*
|
|
@@ -162,6 +59,5 @@ export declare const startTenantOutboxRelay: (options?: {
|
|
|
162
59
|
* later. Every failure is reported as `drainFailed` and swallowed — the entry
|
|
163
60
|
* is still in the outbox, and the sweep will carry it.
|
|
164
61
|
*/
|
|
165
|
-
export declare const drainOutboxNow: (db: Db, onOutcome?: RelayOutcomeSink) => Effect.Effect<void, never,
|
|
166
|
-
export {};
|
|
62
|
+
export declare const drainOutboxNow: (db: Db, onOutcome?: RelayOutcomeSink) => Effect.Effect<void, never, OutboxMaxAttempts | EventBusTag>;
|
|
167
63
|
//# sourceMappingURL=relay.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relay.d.ts","sourceRoot":"","sources":["../../src/outbox/relay.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"relay.d.ts","sourceRoot":"","sources":["../../src/outbox/relay.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,eAAe,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC7E,OAAO,EACL,KAAK,QAAQ,EACb,WAAW,EACX,iBAAiB,EAClB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAGL,KAAK,eAAe,EACpB,KAAK,gBAAgB,EAGtB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAElC,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AAGvE;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,gBAAgB,GAAI,UAAU;IACzC,QAAQ,CAAC,OAAO,CAAC,EAAE,eAAe,CAAC;IACnC,QAAQ,CAAC,SAAS,CAAC,EAAE,gBAAgB,CAAC;CACvC,oKAiBG,CAAC;AAEL;;;;;;;;;;GAUG;AACH,eAAO,MAAM,mBAAmB,GAC9B,WAAW,eAAe,CAAC,EAAE,CAAC,EAC9B,KAAK,QAAQ,EACb,SAAS;IACP,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,OAAO,CAAC,EAAE,eAAe,CAAC;IACnC,QAAQ,CAAC,SAAS,CAAC,EAAE,gBAAgB,CAAC;IACtC,QAAQ,CAAC,OAAO,CAAC,EAAE,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,uIAeG,CAAC;AAEL;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,GACzB,IAAI,EAAE,EACN,YAAW,gBAAqC,gEAc/C,CAAC"}
|
package/dist/outbox/relay.js
CHANGED
|
@@ -1,115 +1,10 @@
|
|
|
1
1
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
-
import {
|
|
3
|
-
import { EventBusTag } from '@entifix/transactions';
|
|
4
|
-
import {
|
|
2
|
+
import { TenantDirectoryTag } from '@entifix/business';
|
|
3
|
+
import { EventBusTag, OutboxMaxAttempts } from '@entifix/transactions';
|
|
4
|
+
import { drainOutbox, ignoreRelayOutcome, runRelayDaemon, sweepOutbox } from '@entifix/transactions/engine';
|
|
5
|
+
import { Effect } from 'effect';
|
|
5
6
|
import { MongoDatabaseTag } from '../mongo-database/mongo-database.js';
|
|
6
|
-
import { recordOutboxStats } from './metrics.js';
|
|
7
7
|
import { ensureOutboxIndexes, makeMongoOutbox } from './store.js';
|
|
8
|
-
/** How often the sweep looks for entries the fast path did not carry. */ /**
|
|
9
|
-
* What an outbox entry records as the reason its publish failed: the failure's
|
|
10
|
-
* own message, or its code when it carries none — never empty, because an
|
|
11
|
-
* operator reading a quarantined entry has nothing else to go on.
|
|
12
|
-
*/ const failureText = (failure)=>failure.message === '' ? failure.code : failure.message;
|
|
13
|
-
export const SWEEP_INTERVAL = Duration.seconds(15);
|
|
14
|
-
/** Entries drained per pass, per database. */ export const BATCH = 100;
|
|
15
|
-
/**
|
|
16
|
-
* Hears nothing. The default only so a spec can start a relay without one —
|
|
17
|
-
* a host that passes no sink has a relay nobody can watch.
|
|
18
|
-
*/ export const ignoreRelayOutcome = ()=>Effect.void;
|
|
19
|
-
/**
|
|
20
|
-
* Publish attempts an outbox entry gets before it is quarantined, from
|
|
21
|
-
* config-service.
|
|
22
|
-
*
|
|
23
|
-
* Configuration rather than a constant because it is a genuine operational
|
|
24
|
-
* tunable: raising it while a flaky broker settles is a config edit, and the
|
|
25
|
-
* next sweep reads the new value. That is the opposite of a subscription's
|
|
26
|
-
* `maxAttempts`, which becomes an immutable queue argument and therefore stays
|
|
27
|
-
* a literal beside its declaration.
|
|
28
|
-
*
|
|
29
|
-
* ⚠️ **Read it with `getNumber`, never a cast.** A value of `'five'` casts to
|
|
30
|
-
* `NaN`, every `attempts >= maxAttempts` comparison goes false, and nothing is
|
|
31
|
-
* ever quarantined — a relay that looks healthy while its head never moves.
|
|
32
|
-
*/ export class OutboxMaxAttempts extends Context.Service()('OutboxMaxAttempts') {
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Publish one batch of pending entries, oldest first, and answer how many went.
|
|
36
|
-
*
|
|
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.
|
|
45
|
-
*/ export const drainOutbox = (outbox, bus, options)=>Effect.gen(function*() {
|
|
46
|
-
var _options_onOutcome;
|
|
47
|
-
const entries = yield* outbox.pending(BATCH);
|
|
48
|
-
let sent = 0;
|
|
49
|
-
const report = (_options_onOutcome = options.onOutcome) != null ? _options_onOutcome : ignoreRelayOutcome;
|
|
50
|
-
for (const entry of entries){
|
|
51
|
-
const outcome = yield* Effect.result(bus.publish(entry.event));
|
|
52
|
-
if (Result.isFailure(outcome)) {
|
|
53
|
-
var _options_onOutcome1;
|
|
54
|
-
const attempts = entry.attempts + 1;
|
|
55
|
-
const quarantine = attempts >= options.maxAttempts;
|
|
56
|
-
yield* outbox.recordFailure(entry, failureText(outcome.failure), quarantine);
|
|
57
|
-
if (!quarantine) {
|
|
58
|
-
yield* report({
|
|
59
|
-
_tag: 'drained',
|
|
60
|
-
database: options.database,
|
|
61
|
-
sent
|
|
62
|
-
});
|
|
63
|
-
return sent;
|
|
64
|
-
}
|
|
65
|
-
yield* ((_options_onOutcome1 = options.onOutcome) != null ? _options_onOutcome1 : ignoreRelayOutcome)({
|
|
66
|
-
_tag: 'quarantined',
|
|
67
|
-
database: options.database,
|
|
68
|
-
eventId: entry.eventId,
|
|
69
|
-
eventName: entry.event.name,
|
|
70
|
-
attempts,
|
|
71
|
-
code: outcome.failure.code,
|
|
72
|
-
reason: failureText(outcome.failure)
|
|
73
|
-
});
|
|
74
|
-
continue;
|
|
75
|
-
}
|
|
76
|
-
yield* outbox.markSent(entry);
|
|
77
|
-
sent += 1;
|
|
78
|
-
}
|
|
79
|
-
yield* report({
|
|
80
|
-
_tag: 'drained',
|
|
81
|
-
database: options.database,
|
|
82
|
-
sent
|
|
83
|
-
});
|
|
84
|
-
return sent;
|
|
85
|
-
});
|
|
86
|
-
/**
|
|
87
|
-
* Drain the one database this service owns, then sample its depth.
|
|
88
|
-
*
|
|
89
|
-
* The single-database counterpart to `startTenantOutboxRelay`. A
|
|
90
|
-
* platform-plane store is one named database, so there is nothing to enumerate
|
|
91
|
-
* and `listDatabases` — which needs a `MongoClient` and cluster-wide rights —
|
|
92
|
-
* never comes into it.
|
|
93
|
-
*
|
|
94
|
-
* Stats are sampled **after** the drain, so the gauge reports what is still
|
|
95
|
-
* waiting rather than what was waiting when the pass began.
|
|
96
|
-
*
|
|
97
|
-
* Every failure is caught and reported as `sweepFailed`. This runs inside
|
|
98
|
-
* `Effect.forever`, and an error that escapes ends the daemon silently — a
|
|
99
|
-
* relay that stopped is indistinguishable from a relay with nothing to do.
|
|
100
|
-
*/ export const sweepOutbox = (outbox, bus, options)=>Effect.gen(function*() {
|
|
101
|
-
var _options_onStats;
|
|
102
|
-
yield* drainOutbox(outbox, bus, options);
|
|
103
|
-
const sink = (_options_onStats = options.onStats) != null ? _options_onStats : recordOutboxStats;
|
|
104
|
-
yield* sink(options.database, (yield* outbox.stats()));
|
|
105
|
-
}).pipe(Effect.catch((failure)=>{
|
|
106
|
-
var _options_onOutcome;
|
|
107
|
-
return ((_options_onOutcome = options.onOutcome) != null ? _options_onOutcome : ignoreRelayOutcome)({
|
|
108
|
-
_tag: 'sweepFailed',
|
|
109
|
-
database: options.database,
|
|
110
|
-
failure
|
|
111
|
-
});
|
|
112
|
-
}));
|
|
113
8
|
/**
|
|
114
9
|
* Start the relay for a service that owns exactly one database.
|
|
115
10
|
*
|
|
@@ -138,22 +33,6 @@ export const SWEEP_INTERVAL = Duration.seconds(15);
|
|
|
138
33
|
onOutcome: options.onOutcome
|
|
139
34
|
} : {})));
|
|
140
35
|
});
|
|
141
|
-
/**
|
|
142
|
-
* Runs `sweepOnce` every {@link SWEEP_INTERVAL}, and once more on the way out.
|
|
143
|
-
*
|
|
144
|
-
* Interrupting the daemon before that last pass is what stops two sweeps
|
|
145
|
-
* publishing the same entry; running the pass is what the hook is for — an
|
|
146
|
-
* event committed a moment before shutdown would otherwise wait out the next
|
|
147
|
-
* process's whole interval.
|
|
148
|
-
*/ const runRelayDaemon = (sweepOnce)=>Effect.gen(function*() {
|
|
149
|
-
const shutdown = yield* ShutdownRegistryTag;
|
|
150
|
-
const daemon = yield* Effect.forkDetach(sweepOnce.pipe(Effect.delay(SWEEP_INTERVAL), Effect.forever));
|
|
151
|
-
yield* shutdown.register({
|
|
152
|
-
name: 'outbox-relay',
|
|
153
|
-
phase: 'flush',
|
|
154
|
-
run: Fiber.interrupt(daemon).pipe(Effect.andThen(sweepOnce))
|
|
155
|
-
});
|
|
156
|
-
});
|
|
157
36
|
/**
|
|
158
37
|
* One pass over every organization's outbox in a per-organization store.
|
|
159
38
|
*
|
package/dist/outbox/relay.js.map
CHANGED
|
@@ -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,MAAMc,SAASL,QAAS;YAC3B,MAAMM,UAAU,OAAO7B,OAAO8B,MAAM,CAACV,IAAIW,OAAO,CAACH,MAAMI,KAAK;YAE5D,IAAI9B,OAAO+B,SAAS,CAACJ,UAAU;oBAerBR;gBAdR,MAAMa,WAAWN,MAAMM,QAAQ,GAAG;gBAClC,MAAMC,aAAaD,YAAYb,QAAQe,WAAW;g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Y;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 { type TenantDirectory, TenantDirectoryTag } from '@entifix/business';\nimport {\n type EventBus,\n EventBusTag,\n OutboxMaxAttempts,\n} from '@entifix/transactions';\nimport {\n drainOutbox,\n ignoreRelayOutcome,\n type OutboxStatsSink,\n type RelayOutcomeSink,\n runRelayDaemon,\n sweepOutbox,\n} from '@entifix/transactions/engine';\nimport { Effect } from 'effect';\nimport type { Db } from 'mongodb';\n\nimport { MongoDatabaseTag } from '../mongo-database/mongo-database.js';\nimport { ensureOutboxIndexes, makeMongoOutbox } from './store.js';\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 * 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":["TenantDirectoryTag","EventBusTag","OutboxMaxAttempts","drainOutbox","ignoreRelayOutcome","runRelayDaemon","sweepOutbox","Effect","MongoDatabaseTag","ensureOutboxIndexes","makeMongoOutbox","startOutboxRelay","options","gen","db","bus","maxAttempts","outbox","database","databaseName","onStats","onOutcome","sweepTenantOutboxes","directory","report","ensured","Set","tenants","list","handle","has","add","pipe","catch","failure","_tag","startTenantOutboxRelay","drainOutboxNow"],"mappings":";AAAA,SAA+BA,kBAAkB,QAAQ,oBAAoB;AAC7E,SAEEC,WAAW,EACXC,iBAAiB,QACZ,wBAAwB;AAC/B,SACEC,WAAW,EACXC,kBAAkB,EAGlBC,cAAc,EACdC,WAAW,QACN,+BAA+B;AACtC,SAASC,MAAM,QAAQ,SAAS;AAGhC,SAASC,gBAAgB,QAAQ,sCAAsC;AACvE,SAASC,mBAAmB,EAAEC,eAAe,QAAQ,aAAa;AAElE;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,mBAAmB,CAACC,UAI/BL,OAAOM,GAAG,CAAC;QACT,MAAM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AAA;YACVtB;eAAD,EAACA,qBAAAA,QAAQS,SAAS,YAAjBT,qBAAqBR,oBAAoB;YACxC+B,MAAM;YACND;QACF;QAEF;AAEJ;;;;;;;CAOC,GACD,OAAO,MAAME,yBAAyB,CAACxB,UAIrCL,OAAOM,GAAG,CAAC;QACT,MAAMU,YAAa,OAAOvB;QAC1B,MAAMe,MAAM,OAAOd;QACnB,MAAMe,cAAc,OAAOd;QAC3B,MAAMuB,UAAU,IAAIC;QAEpB,OAAOrB,eACLiB,oBAAoBC,WAAWR,KAAK;YAClCC;YACAS;WACIb,CAAAA,2BAAAA,QAASQ,OAAO,IAAG;YAAEA,SAASR,QAAQQ,OAAO;QAAC,IAAI,CAAC,GACnDR,CAAAA,2BAAAA,QAASS,SAAS,IAAG;YAAEA,WAAWT,QAAQS,SAAS;QAAC,IAAI,CAAC;IAGnE,GAAG;AAEL;;;;;;;CAOC,GACD,OAAO,MAAMgB,iBAAiB,CAC5BvB,IACAO,YAA8BjB,kBAAkB,GAEhDG,OAAOM,GAAG,CAAC;QACT,MAAME,MAAM,OAAOd;QACnB,MAAMe,cAAc,OAAOd;QAC3B,OAAOC,YAAYO,gBAAgBI,KAAKC,KAAK;YAC3CC;YACAE,UAAUJ,GAAGK,YAAY;YACzBE;QACF;IACF,GAAGW,IAAI,CACLzB,OAAO0B,KAAK,CAACC,CAAAA,UACXb,UAAU;YAAEc,MAAM;YAAejB,UAAUJ,GAAGK,YAAY;YAAEe;QAAQ,KAEtE"}
|
package/dist/outbox/store.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import type {
|
|
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 = "
|
|
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:
|
|
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
|
|
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
|
|
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
|
|
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) =>
|
|
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,
|
|
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"}
|
package/dist/outbox/store.js
CHANGED
|
@@ -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 = '
|
|
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
|
|
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
|
|
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
|
|
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,
|
|
153
|
-
//
|
|
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
|
}),
|
package/dist/outbox/store.js.map
CHANGED
|
@@ -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","quarantine","$inc","cause"],"mappings":";AAEA,SAASA,MAAM,QAAQ,SAAS;AAGhC,SAASC,mBAAmB,QAAQ,qCAAqC;AAEzE;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,oBAAoB,qBAAqB;AAEtD,iDAAiD,GACjD,MAAMC,mBAAmB;IAAEC,YAAY;QAAEC,KAAK;IAAE;AAAE;AAElD,gFAAgF,GAChF,MAAMC,gBA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W4B,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,AAACA,MAA6BC,IAAI,KAAKH;AAEzC;;;;;;;CAOC,GACD,OAAO,MAAMI,iBAAiB,CAACC,QAAqC,CAAA;QAClEC,SAASD,MAAME,EAAE;QACjBC,WAAWH,MAAMG,SAAS;QAC1BC,SAASJ,MAAMI,OAAO;QACtBJ;QACAK,MAAM;QACN,yEAAyE;QACzE,wEAAwE;QACxE,4EAA4E;QAC5E,2EAA2E;QAC3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ACrBf,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,8 +9,8 @@
|
|
|
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
|
-
export * from '../outbox/metrics.js';
|
|
14
14
|
export * from '../outbox/relay.js';
|
|
15
15
|
export * from '../outbox/store.js';
|
|
16
16
|
export * from '../saga/store.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/transactions/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,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,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,kCAAkC,CAAC;AACjD,cAAc,uCAAuC,CAAC"}
|
|
@@ -8,8 +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 '../
|
|
12
|
-
export * from '../
|
|
11
|
+
*/ export * from '../idempotency/store.js';
|
|
12
|
+
export * from '../inbox/store.js';
|
|
13
13
|
export * from '../outbox/relay.js';
|
|
14
14
|
export * from '../outbox/store.js';
|
|
15
15
|
export * from '../saga/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 '../
|
|
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/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,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":"
|
|
1
|
+
{"version":3,"file":"mongo-unit-of-work.d.ts","sourceRoot":"","sources":["../../src/unit-of-work/mongo-unit-of-work.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAGV,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,EAAE,CAAC;IAChB,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAC;CACjC;AAED,6DAA6D;AAC7D,MAAM,WAAW,kBAAkB;IACjC,YAAY,IAAI,aAAa,CAAC;CAC/B;AA4GD;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,GAAI,QAAQ,kBAAkB;sBAuBpC,EAAE,KAAG,UAAU,CAAC,SAAS,CAAC;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,MA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,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,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,MA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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.
|
|
3
|
+
"version": "0.12.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/
|
|
61
|
-
"@entifix/
|
|
60
|
+
"@entifix/business": "0.12.0",
|
|
61
|
+
"@entifix/core": "0.12.0"
|
|
62
62
|
},
|
|
63
63
|
"devDependencies": {
|
|
64
64
|
"effect": "4.0.6",
|
|
65
|
-
"@entifix/
|
|
66
|
-
"@entifix/
|
|
65
|
+
"@entifix/testing-unit": "0.12.0",
|
|
66
|
+
"@entifix/transactions": "0.12.0"
|
|
67
67
|
},
|
|
68
68
|
"peerDependencies": {
|
|
69
69
|
"effect": "^4.0.6",
|
|
70
|
-
"@entifix/transactions": "0.
|
|
70
|
+
"@entifix/transactions": "0.12.0"
|
|
71
71
|
},
|
|
72
72
|
"peerDependenciesMeta": {
|
|
73
73
|
"@entifix/transactions": {
|
package/dist/outbox/metrics.d.ts
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import type { OutboxStats } from '@entifix/transactions';
|
|
2
|
-
import { Effect, Metric } from 'effect';
|
|
3
|
-
/**
|
|
4
|
-
* The outbox half of the framework's first metric set; the bus half is in
|
|
5
|
-
* `@entifix/amqp`.
|
|
6
|
-
*
|
|
7
|
-
* It lives beside the relay that samples it rather than in any one service,
|
|
8
|
-
* because three slices now own an outbox — `catalog`, `order` and `payment` —
|
|
9
|
-
* and the warning below is exactly why a copy per service is not an option: an
|
|
10
|
-
* Effect metric is keyed on its **description**, so three hand-maintained
|
|
11
|
-
* definitions of `outbox_pending_entries` are three series the moment one
|
|
12
|
-
* wording drifts, and a dashboard would go quiet without failing anything.
|
|
13
|
-
*
|
|
14
|
-
* ⚠️ The metric objects are **exported so a reader uses the same instance**. An
|
|
15
|
-
* Effect metric's registry key includes its description, so rebuilding one by
|
|
16
|
-
* name without the description addresses a different series that is permanently
|
|
17
|
-
* zero — a silent way to write a query against nothing.
|
|
18
|
-
*
|
|
19
|
-
* These are gauges rather than counters because they describe a *backlog*: the
|
|
20
|
-
* question is how many are waiting right now, not how many there have ever
|
|
21
|
-
* been. They are sampled by the two daemons that already run on an interval, so
|
|
22
|
-
* nothing new is scheduled to produce them.
|
|
23
|
-
*
|
|
24
|
-
* ⚠️ **A dimensionless gauge reaches Prometheus with a `_ratio` suffix.** That
|
|
25
|
-
* is the OTel exporter's convention for unit `1`, not a mistake here, so
|
|
26
|
-
* `outbox_pending_entries` is queried as `outbox_pending_entries_ratio`.
|
|
27
|
-
* Counters are unaffected. Where a metric has a real unit, tag it — see
|
|
28
|
-
* {@link outboxOldestPendingAge}.
|
|
29
|
-
*/
|
|
30
|
-
/** Unsent, un-quarantined entries, per database. */
|
|
31
|
-
export declare const outboxPending: Metric.Gauge<number>;
|
|
32
|
-
/**
|
|
33
|
-
* Age in seconds of the oldest unsent entry, per database.
|
|
34
|
-
*
|
|
35
|
-
* **The metric that makes a stuck relay visible.** Quarantine gave the relay a
|
|
36
|
-
* ceiling, so an entry that can never publish is quarantined and skipped rather
|
|
37
|
-
* than blocking the head of the line forever — but that is reported only as a
|
|
38
|
-
* log line, so how far behind the outbox has fallen is otherwise unanswerable.
|
|
39
|
-
* A depth that is flat and an age that climbs is the signature of a relay whose
|
|
40
|
-
* head has stopped moving.
|
|
41
|
-
*/
|
|
42
|
-
export declare const outboxOldestPendingAge: Metric.Gauge<number>;
|
|
43
|
-
/** Entries past the ceiling, which nothing retries and nothing deletes. */
|
|
44
|
-
export declare const outboxQuarantined: Metric.Gauge<number>;
|
|
45
|
-
/** Record one outbox's depth and age. */
|
|
46
|
-
export declare const recordOutboxStats: (database: string, stats: OutboxStats) => Effect.Effect<void, never, never>;
|
|
47
|
-
//# sourceMappingURL=metrics.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"metrics.d.ts","sourceRoot":"","sources":["../../src/outbox/metrics.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAExC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,oDAAoD;AACpD,eAAO,MAAM,aAAa,sBAExB,CAAC;AAEH;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB,EAAE,MAAM,CAAC,KAAK,CAAC,MAAM,CAkBvD,CAAC;AAEF,2EAA2E;AAC3E,eAAO,MAAM,iBAAiB,sBAE5B,CAAC;AAEH,yCAAyC;AACzC,eAAO,MAAM,iBAAiB,GAAI,UAAU,MAAM,EAAE,OAAO,WAAW,sCAgBrE,CAAC"}
|
package/dist/outbox/metrics.js
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
import { Effect, Metric } from 'effect';
|
|
2
|
-
/**
|
|
3
|
-
* The outbox half of the framework's first metric set; the bus half is in
|
|
4
|
-
* `@entifix/amqp`.
|
|
5
|
-
*
|
|
6
|
-
* It lives beside the relay that samples it rather than in any one service,
|
|
7
|
-
* because three slices now own an outbox — `catalog`, `order` and `payment` —
|
|
8
|
-
* and the warning below is exactly why a copy per service is not an option: an
|
|
9
|
-
* Effect metric is keyed on its **description**, so three hand-maintained
|
|
10
|
-
* definitions of `outbox_pending_entries` are three series the moment one
|
|
11
|
-
* wording drifts, and a dashboard would go quiet without failing anything.
|
|
12
|
-
*
|
|
13
|
-
* ⚠️ The metric objects are **exported so a reader uses the same instance**. An
|
|
14
|
-
* Effect metric's registry key includes its description, so rebuilding one by
|
|
15
|
-
* name without the description addresses a different series that is permanently
|
|
16
|
-
* zero — a silent way to write a query against nothing.
|
|
17
|
-
*
|
|
18
|
-
* These are gauges rather than counters because they describe a *backlog*: the
|
|
19
|
-
* question is how many are waiting right now, not how many there have ever
|
|
20
|
-
* been. They are sampled by the two daemons that already run on an interval, so
|
|
21
|
-
* nothing new is scheduled to produce them.
|
|
22
|
-
*
|
|
23
|
-
* ⚠️ **A dimensionless gauge reaches Prometheus with a `_ratio` suffix.** That
|
|
24
|
-
* is the OTel exporter's convention for unit `1`, not a mistake here, so
|
|
25
|
-
* `outbox_pending_entries` is queried as `outbox_pending_entries_ratio`.
|
|
26
|
-
* Counters are unaffected. Where a metric has a real unit, tag it — see
|
|
27
|
-
* {@link outboxOldestPendingAge}.
|
|
28
|
-
*/ /** Unsent, un-quarantined entries, per database. */ export const outboxPending = Metric.gauge('outbox_pending_entries', {
|
|
29
|
-
description: 'Unsent, un-quarantined outbox entries, by database.'
|
|
30
|
-
});
|
|
31
|
-
/**
|
|
32
|
-
* Age in seconds of the oldest unsent entry, per database.
|
|
33
|
-
*
|
|
34
|
-
* **The metric that makes a stuck relay visible.** Quarantine gave the relay a
|
|
35
|
-
* ceiling, so an entry that can never publish is quarantined and skipped rather
|
|
36
|
-
* than blocking the head of the line forever — but that is reported only as a
|
|
37
|
-
* log line, so how far behind the outbox has fallen is otherwise unanswerable.
|
|
38
|
-
* A depth that is flat and an age that climbs is the signature of a relay whose
|
|
39
|
-
* head has stopped moving.
|
|
40
|
-
*/ export const outboxOldestPendingAge = Metric.gauge('outbox_oldest_pending_age', {
|
|
41
|
-
description: 'Age of the oldest unsent outbox entry, by database. Zero when ' + 'the outbox is empty.'
|
|
42
|
-
}).pipe(// ⚠️ **The unit is carried as a tag, and that is the only way to set it.**
|
|
43
|
-
// `@effect/opentelemetry`'s producer reads `tags.unit ?? tags.time_unit ??
|
|
44
|
-
// '1'`, so a gauge with no `unit` tag is exported as dimensionless — and the
|
|
45
|
-
// Prometheus exporter then appends `_ratio` to a dimensionless gauge's name.
|
|
46
|
-
// Measured: this series arrived as `outbox_oldest_pending_age_seconds_ratio`,
|
|
47
|
-
// a duration announcing itself as a ratio. Tagging it makes the exporter name
|
|
48
|
-
// it `_seconds`, which is why the name above no longer carries that suffix
|
|
49
|
-
// itself. The cost is a constant `unit` label, because the producer builds the
|
|
50
|
-
// datapoint attributes from the same tag set it reads the unit from.
|
|
51
|
-
Metric.withAttributes({
|
|
52
|
-
unit: 's'
|
|
53
|
-
}));
|
|
54
|
-
/** Entries past the ceiling, which nothing retries and nothing deletes. */ export const outboxQuarantined = Metric.gauge('outbox_quarantined_entries', {
|
|
55
|
-
description: 'Quarantined outbox entries, by database.'
|
|
56
|
-
});
|
|
57
|
-
/** Record one outbox's depth and age. */ export const recordOutboxStats = (database, stats)=>{
|
|
58
|
-
const tagged = (metric)=>Metric.withAttributes(metric, {
|
|
59
|
-
database
|
|
60
|
-
});
|
|
61
|
-
// Zero when nothing is waiting. The alternative — not reporting the series —
|
|
62
|
-
// reads on most dashboards as "no data", which is indistinguishable from the
|
|
63
|
-
// exporter having broken at exactly the moment a healthy relay looks idle.
|
|
64
|
-
const ageSeconds = stats.oldestPendingAt === undefined ? 0 : Math.max(0, (Date.now() - Date.parse(stats.oldestPendingAt)) / 1000);
|
|
65
|
-
return Metric.update(tagged(outboxPending), stats.pending).pipe(Effect.andThen(Metric.update(tagged(outboxOldestPendingAge), ageSeconds)), Effect.andThen(Metric.update(tagged(outboxQuarantined), stats.quarantined)));
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
//# sourceMappingURL=metrics.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/outbox/metrics.ts"],"sourcesContent":["import type { OutboxStats } from '@entifix/transactions';\nimport { Effect, Metric } from 'effect';\n\n/**\n * The outbox half of the framework's first metric set; the bus half is in\n * `@entifix/amqp`.\n *\n * It lives beside the relay that samples it rather than in any one service,\n * because three slices now own an outbox — `catalog`, `order` and `payment` —\n * and the warning below is exactly why a copy per service is not an option: an\n * Effect metric is keyed on its **description**, so three hand-maintained\n * definitions of `outbox_pending_entries` are three series the moment one\n * wording drifts, and a dashboard would go quiet without failing anything.\n *\n * ⚠️ The metric objects are **exported so a reader uses the same instance**. An\n * Effect metric's registry key includes its description, so rebuilding one by\n * name without the description addresses a different series that is permanently\n * zero — a silent way to write a query against nothing.\n *\n * These are gauges rather than counters because they describe a *backlog*: the\n * question is how many are waiting right now, not how many there have ever\n * been. They are sampled by the two daemons that already run on an interval, so\n * nothing new is scheduled to produce them.\n *\n * ⚠️ **A dimensionless gauge reaches Prometheus with a `_ratio` suffix.** That\n * is the OTel exporter's convention for unit `1`, not a mistake here, so\n * `outbox_pending_entries` is queried as `outbox_pending_entries_ratio`.\n * Counters are unaffected. Where a metric has a real unit, tag it — see\n * {@link outboxOldestPendingAge}.\n */\n\n/** Unsent, un-quarantined entries, per database. */\nexport const outboxPending = Metric.gauge('outbox_pending_entries', {\n description: 'Unsent, un-quarantined outbox entries, by database.',\n});\n\n/**\n * Age in seconds of the oldest unsent entry, per database.\n *\n * **The metric that makes a stuck relay visible.** Quarantine gave the relay a\n * ceiling, so an entry that can never publish is quarantined and skipped rather\n * than blocking the head of the line forever — but that is reported only as a\n * log line, so how far behind the outbox has fallen is otherwise unanswerable.\n * A depth that is flat and an age that climbs is the signature of a relay whose\n * head has stopped moving.\n */\nexport const outboxOldestPendingAge: Metric.Gauge<number> = Metric.gauge(\n 'outbox_oldest_pending_age',\n {\n description:\n 'Age of the oldest unsent outbox entry, by database. Zero when ' +\n 'the outbox is empty.',\n },\n).pipe(\n // ⚠️ **The unit is carried as a tag, and that is the only way to set it.**\n // `@effect/opentelemetry`'s producer reads `tags.unit ?? tags.time_unit ??\n // '1'`, so a gauge with no `unit` tag is exported as dimensionless — and the\n // Prometheus exporter then appends `_ratio` to a dimensionless gauge's name.\n // Measured: this series arrived as `outbox_oldest_pending_age_seconds_ratio`,\n // a duration announcing itself as a ratio. Tagging it makes the exporter name\n // it `_seconds`, which is why the name above no longer carries that suffix\n // itself. The cost is a constant `unit` label, because the producer builds the\n // datapoint attributes from the same tag set it reads the unit from.\n Metric.withAttributes({ unit: 's' }),\n);\n\n/** Entries past the ceiling, which nothing retries and nothing deletes. */\nexport const outboxQuarantined = Metric.gauge('outbox_quarantined_entries', {\n description: 'Quarantined outbox entries, by database.',\n});\n\n/** Record one outbox's depth and age. */\nexport const recordOutboxStats = (database: string, stats: OutboxStats) => {\n const tagged = (metric: Metric.Gauge<number>) =>\n Metric.withAttributes(metric, { database });\n\n // Zero when nothing is waiting. The alternative — not reporting the series —\n // reads on most dashboards as \"no data\", which is indistinguishable from the\n // exporter having broken at exactly the moment a healthy relay looks idle.\n const ageSeconds =\n stats.oldestPendingAt === undefined\n ? 0\n : Math.max(0, (Date.now() - Date.parse(stats.oldestPendingAt)) / 1000);\n\n return Metric.update(tagged(outboxPending), stats.pending).pipe(\n Effect.andThen(Metric.update(tagged(outboxOldestPendingAge), ageSeconds)),\n Effect.andThen(Metric.update(tagged(outboxQuarantined), stats.quarantined)),\n );\n};\n"],"names":["Effect","Metric","outboxPending","gauge","description","outboxOldestPendingAge","pipe","withAttributes","unit","outboxQuarantined","recordOutboxStats","database","stats","tagged","metric","ageSeconds","oldestPendingAt","undefined","Math","max","Date","now","parse","update","pending","andThen","quarantined"],"mappings":"AACA,SAASA,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAExC;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GAED,kDAAkD,GAClD,OAAO,MAAMC,gBAAgBD,OAAOE,KAAK,CAAC,0BAA0B;IAClEC,aAAa;AACf,GAAG;AAEH;;;;;;;;;CASC,GACD,OAAO,MAAMC,yBAA+CJ,OAAOE,KAAK,CACtE,6BACA;IACEC,aACE,mEACA;AACJ,GACAE,IAAI,CACJ,2EAA2E;AAC3E,2EAA2E;AAC3E,6EAA6E;AAC7E,6EAA6E;AAC7E,8EAA8E;AAC9E,8EAA8E;AAC9E,2EAA2E;AAC3E,+EAA+E;AAC/E,qEAAqE;AACrEL,OAAOM,cAAc,CAAC;IAAEC,MAAM;AAAI,IAClC;AAEF,yEAAyE,GACzE,OAAO,MAAMC,oBAAoBR,OAAOE,KAAK,CAAC,8BAA8B;IAC1EC,aAAa;AACf,GAAG;AAEH,uCAAuC,GACvC,OAAO,MAAMM,oBAAoB,CAACC,UAAkBC;IAClD,MAAMC,SAAS,CAACC,SACdb,OAAOM,cAAc,CAACO,QAAQ;YAAEH;QAAS;IAE3C,6EAA6E;IAC7E,6EAA6E;IAC7E,2EAA2E;IAC3E,MAAMI,aACJH,MAAMI,eAAe,KAAKC,YACtB,IACAC,KAAKC,GAAG,CAAC,GAAG,AAACC,CAAAA,KAAKC,GAAG,KAAKD,KAAKE,KAAK,CAACV,MAAMI,eAAe,CAAA,IAAK;IAErE,OAAOf,OAAOsB,MAAM,CAACV,OAAOX,gBAAgBU,MAAMY,OAAO,EAAElB,IAAI,CAC7DN,OAAOyB,OAAO,CAACxB,OAAOsB,MAAM,CAACV,OAAOR,yBAAyBU,cAC7Df,OAAOyB,OAAO,CAACxB,OAAOsB,MAAM,CAACV,OAAOJ,oBAAoBG,MAAMc,WAAW;AAE7E,EAAE"}
|