@entifix/mongo 0.11.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,113 +1,9 @@
1
- import { ShutdownRegistryTag, type TenantDirectory, TenantDirectoryTag } from '@entifix/business';
2
- import { type EventBus, EventBusTag, type Outbox, type OutboxStats } from '@entifix/transactions';
3
- import { Context, Duration, Effect } from 'effect';
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, **in order within each
73
- * aggregate** ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)),
74
- * and answer how many went.
75
- *
76
- * - A **still-deliverable** failure holds back the rest of its own aggregate
77
- * for this pass, which is what stops a terminal event overtaking the
78
- * `accepted` of the same transaction — and only its own: every other
79
- * aggregate keeps draining.
80
- * - A **quarantined** failure moves on. An entry that can never publish must
81
- * not hold its aggregate forever, and a consumer discards whatever older
82
- * version arrives after a newer one anyway.
83
- */
84
- export declare const drainOutbox: (outbox: Outbox, bus: EventBus, options: DrainOptions) => Effect.Effect<number, import("@entifix/core").StoreFailure, never>;
85
- /**
86
- * Sample a sweep's depth and age.
87
- *
88
- * Defaults to {@link recordOutboxStats}, and a caller overrides it only to
89
- * assert what was sampled. There is no "no sink" option on purpose: an outbox
90
- * whose depth nothing reports is the failure the gauges exist to make visible.
91
- */
92
- export type OutboxStatsSink = (database: string, stats: OutboxStats) => Effect.Effect<void>;
93
- /**
94
- * Drain the one database this service owns, then sample its depth.
95
- *
96
- * The single-database counterpart to `startTenantOutboxRelay`. A
97
- * platform-plane store is one named database, so there is nothing to enumerate
98
- * and `listDatabases` — which needs a `MongoClient` and cluster-wide rights —
99
- * never comes into it.
100
- *
101
- * Stats are sampled **after** the drain, so the gauge reports what is still
102
- * waiting rather than what was waiting when the pass began.
103
- *
104
- * Every failure is caught and reported as `sweepFailed`. This runs inside
105
- * `Effect.forever`, and an error that escapes ends the daemon silently — a
106
- * relay that stopped is indistinguishable from a relay with nothing to do.
107
- */
108
- export declare const sweepOutbox: (outbox: Outbox, bus: EventBus, options: DrainOptions & {
109
- readonly onStats?: OutboxStatsSink;
110
- }) => Effect.Effect<void, never, never>;
111
7
  /**
112
8
  * Start the relay for a service that owns exactly one database.
113
9
  *
@@ -125,7 +21,7 @@ export declare const sweepOutbox: (outbox: Outbox, bus: EventBus, options: Drain
125
21
  export declare const startOutboxRelay: (options?: {
126
22
  readonly onStats?: OutboxStatsSink;
127
23
  readonly onOutcome?: RelayOutcomeSink;
128
- }) => Effect.Effect<void, import("@entifix/core").StoreFailure, ShutdownRegistryTag | MongoDatabaseTag | EventBusTag | OutboxMaxAttempts>;
24
+ }) => Effect.Effect<void, import("@entifix/core").StoreFailure, import("@entifix/business").ShutdownRegistryTag | MongoDatabaseTag | OutboxMaxAttempts | EventBusTag>;
129
25
  /**
130
26
  * One pass over every organization's outbox in a per-organization store.
131
27
  *
@@ -154,7 +50,7 @@ export declare const sweepTenantOutboxes: (directory: TenantDirectory<Db>, bus:
154
50
  export declare const startTenantOutboxRelay: (options?: {
155
51
  readonly onStats?: OutboxStatsSink;
156
52
  readonly onOutcome?: RelayOutcomeSink;
157
- }) => Effect.Effect<void, never, ShutdownRegistryTag | TenantDirectoryTag | EventBusTag | OutboxMaxAttempts>;
53
+ }) => Effect.Effect<void, never, import("@entifix/business").ShutdownRegistryTag | TenantDirectoryTag | OutboxMaxAttempts | EventBusTag>;
158
54
  /**
159
55
  * Drain one database's outbox now, for a write path that has just committed.
160
56
  *
@@ -163,6 +59,5 @@ export declare const startTenantOutboxRelay: (options?: {
163
59
  * later. Every failure is reported as `drainFailed` and swallowed — the entry
164
60
  * is still in the outbox, and the sweep will carry it.
165
61
  */
166
- export declare const drainOutboxNow: (db: Db, onOutcome?: RelayOutcomeSink) => Effect.Effect<void, never, EventBusTag | OutboxMaxAttempts>;
167
- export {};
62
+ export declare const drainOutboxNow: (db: Db, onOutcome?: RelayOutcomeSink) => Effect.Effect<void, never, OutboxMaxAttempts | EventBusTag>;
168
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,EACL,mBAAmB,EACnB,KAAK,eAAe,EACpB,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAEL,KAAK,QAAQ,EACb,WAAW,EACX,KAAK,MAAM,EACX,KAAK,WAAW,EACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAiB,MAAM,QAAQ,CAAC;AAClE,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAElC,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AAevE,eAAO,MAAM,cAAc,mBAAuB,CAAC;AACnD,8CAA8C;AAC9C,eAAO,MAAM,KAAK,MAAM,CAAC;AAEzB;;;;;;;;GAQG;AACH,MAAM,MAAM,YAAY,GACpB;IACE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAA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ShutdownRegistryTag, TenantDirectoryTag } from '@entifix/business';
3
- import { aggregateKey, EventBusTag } from '@entifix/transactions';
4
- import { Context, Duration, Effect, Fiber, Result } from 'effect';
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, **in order within each
36
- * aggregate** ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)),
37
- * and answer how many went.
38
- *
39
- * - A **still-deliverable** failure holds back the rest of its own aggregate
40
- * for this pass, which is what stops a terminal event overtaking the
41
- * `accepted` of the same transaction — and only its own: every other
42
- * aggregate keeps draining.
43
- * - A **quarantined** failure moves on. An entry that can never publish must
44
- * not hold its aggregate forever, and a consumer discards whatever older
45
- * version arrives after a newer one anyway.
46
- */ export const drainOutbox = (outbox, bus, options)=>Effect.gen(function*() {
47
- var _options_onOutcome;
48
- const entries = yield* outbox.pending(BATCH);
49
- const held = new Set();
50
- let sent = 0;
51
- const report = (_options_onOutcome = options.onOutcome) != null ? _options_onOutcome : ignoreRelayOutcome;
52
- for (const entry of entries){
53
- const key = aggregateKey(entry.aggregate);
54
- if (held.has(key)) continue;
55
- const outcome = yield* Effect.result(bus.publish(entry.event));
56
- if (Result.isFailure(outcome)) {
57
- const attempts = entry.attempts + 1;
58
- const quarantine = attempts >= options.maxAttempts;
59
- yield* outbox.recordFailure(entry, failureText(outcome.failure), quarantine);
60
- if (!quarantine) {
61
- held.add(key);
62
- continue;
63
- }
64
- yield* report({
65
- _tag: 'quarantined',
66
- database: options.database,
67
- eventId: entry.eventId,
68
- eventName: entry.event.name,
69
- attempts,
70
- code: outcome.failure.code,
71
- reason: failureText(outcome.failure)
72
- });
73
- continue;
74
- }
75
- yield* outbox.markSent(entry);
76
- sent += 1;
77
- }
78
- yield* report({
79
- _tag: 'drained',
80
- database: options.database,
81
- sent
82
- });
83
- return sent;
84
- });
85
- /**
86
- * Drain the one database this service owns, then sample its depth.
87
- *
88
- * The single-database counterpart to `startTenantOutboxRelay`. A
89
- * platform-plane store is one named database, so there is nothing to enumerate
90
- * and `listDatabases` — which needs a `MongoClient` and cluster-wide rights —
91
- * never comes into it.
92
- *
93
- * Stats are sampled **after** the drain, so the gauge reports what is still
94
- * waiting rather than what was waiting when the pass began.
95
- *
96
- * Every failure is caught and reported as `sweepFailed`. This runs inside
97
- * `Effect.forever`, and an error that escapes ends the daemon silently — a
98
- * relay that stopped is indistinguishable from a relay with nothing to do.
99
- */ export const sweepOutbox = (outbox, bus, options)=>Effect.gen(function*() {
100
- var _options_onStats;
101
- yield* drainOutbox(outbox, bus, options);
102
- const sink = (_options_onStats = options.onStats) != null ? _options_onStats : recordOutboxStats;
103
- yield* sink(options.database, (yield* outbox.stats()));
104
- }).pipe(Effect.catch((failure)=>{
105
- var _options_onOutcome;
106
- return ((_options_onOutcome = options.onOutcome) != null ? _options_onOutcome : ignoreRelayOutcome)({
107
- _tag: 'sweepFailed',
108
- database: options.database,
109
- failure
110
- });
111
- }));
112
8
  /**
113
9
  * Start the relay for a service that owns exactly one database.
114
10
  *
@@ -137,22 +33,6 @@ export const SWEEP_INTERVAL = Duration.seconds(15);
137
33
  onOutcome: options.onOutcome
138
34
  } : {})));
139
35
  });
140
- /**
141
- * Runs `sweepOnce` every {@link SWEEP_INTERVAL}, and once more on the way out.
142
- *
143
- * Interrupting the daemon before that last pass is what stops two sweeps
144
- * publishing the same entry; running the pass is what the hook is for — an
145
- * event committed a moment before shutdown would otherwise wait out the next
146
- * process's whole interval.
147
- */ const runRelayDaemon = (sweepOnce)=>Effect.gen(function*() {
148
- const shutdown = yield* ShutdownRegistryTag;
149
- const daemon = yield* Effect.forkDetach(sweepOnce.pipe(Effect.delay(SWEEP_INTERVAL), Effect.forever));
150
- yield* shutdown.register({
151
- name: 'outbox-relay',
152
- phase: 'flush',
153
- run: Fiber.interrupt(daemon).pipe(Effect.andThen(sweepOnce))
154
- });
155
- });
156
36
  /**
157
37
  * One pass over every organization's outbox in a per-organization store.
158
38
  *
@@ -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 aggregateKey,\n type EventBus,\n EventBusTag,\n type Outbox,\n type OutboxStats,\n} from '@entifix/transactions';\nimport { Context, Duration, Effect, Fiber, Result } from 'effect';\nimport type { Db } from 'mongodb';\n\nimport { MongoDatabaseTag } from '../mongo-database/mongo-database.js';\nimport { recordOutboxStats } from './metrics.js';\nimport { ensureOutboxIndexes, makeMongoOutbox } from './store.js';\n\n/** How often the sweep looks for entries the fast path did not carry. */\n/**\n * What an outbox entry records as the reason its publish failed: the failure's\n * own message, or its code when it carries none — never empty, because an\n * operator reading a quarantined entry has nothing else to go on.\n */\nconst failureText = (failure: {\n readonly message: string;\n readonly code: string;\n}) => (failure.message === '' ? failure.code : failure.message);\n\nexport const SWEEP_INTERVAL = Duration.seconds(15);\n/** Entries drained per pass, per database. */\nexport const BATCH = 100;\n\n/**\n * What a relay pass did, for the host to log\n * ([ADR 0013](../../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n *\n * The relay decides nothing about level or sink: it says what happened and the\n * fork site that started it — the slice's shell — decides how loud that is. A\n * `failure` is whatever the store or the bus failed with; a typed one carries\n * its code and category for the log line.\n */\nexport type RelayOutcome =\n | {\n readonly _tag: 'drained';\n readonly database: string;\n readonly sent: number;\n }\n | {\n readonly _tag: 'quarantined';\n readonly database: string;\n readonly eventId: string;\n readonly eventName: string;\n readonly attempts: number;\n readonly code: string;\n readonly reason: string;\n }\n | {\n readonly _tag: 'sweepFailed';\n readonly database?: string;\n readonly failure: unknown;\n }\n | {\n readonly _tag: 'drainFailed';\n readonly database: string;\n readonly failure: unknown;\n };\n\n/** Where a relay's outcomes go. The host's fork site supplies it. */\nexport type RelayOutcomeSink = (outcome: RelayOutcome) => Effect.Effect<void>;\n\n/**\n * Hears nothing. The default only so a spec can start a relay without one —\n * a host that passes no sink has a relay nobody can watch.\n */\nexport const ignoreRelayOutcome: RelayOutcomeSink = () => Effect.void;\n\n/**\n * Publish attempts an outbox entry gets before it is quarantined, from\n * config-service.\n *\n * Configuration rather than a constant because it is a genuine operational\n * tunable: raising it while a flaky broker settles is a config edit, and the\n * next sweep reads the new value. That is the opposite of a subscription's\n * `maxAttempts`, which becomes an immutable queue argument and therefore stays\n * a literal beside its declaration.\n *\n * ⚠️ **Read it with `getNumber`, never a cast.** A value of `'five'` casts to\n * `NaN`, every `attempts >= maxAttempts` comparison goes false, and nothing is\n * ever quarantined — a relay that looks healthy while its head never moves.\n */\nexport class OutboxMaxAttempts extends Context.Service<\n OutboxMaxAttempts,\n number\n>()('OutboxMaxAttempts') {}\n\n/** What {@link drainOutbox} needs beyond the ports it publishes through. */\nexport interface DrainOptions {\n readonly maxAttempts: number;\n /** The database being drained; carried so a quarantine log names it. */\n readonly database: string;\n /** Where the pass reports what it did; see {@link RelayOutcome}. */\n readonly onOutcome?: RelayOutcomeSink;\n}\n\n/**\n * Publish one batch of pending entries, oldest first, **in order within each\n * aggregate** ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)),\n * and answer how many went.\n *\n * - A **still-deliverable** failure holds back the rest of its own aggregate\n * for this pass, which is what stops a terminal event overtaking the\n * `accepted` of the same transaction — and only its own: every other\n * aggregate keeps draining.\n * - A **quarantined** failure moves on. An entry that can never publish must\n * not hold its aggregate forever, and a consumer discards whatever older\n * version arrives after a newer one anyway.\n */\nexport const drainOutbox = (\n outbox: Outbox,\n bus: EventBus,\n options: DrainOptions,\n) =>\n Effect.gen(function* () {\n const entries = yield* outbox.pending(BATCH);\n const held = new Set<string>();\n let sent = 0;\n const report = options.onOutcome ?? ignoreRelayOutcome;\n for (const entry of entries) {\n const key = aggregateKey(entry.aggregate);\n if (held.has(key)) continue;\n\n const outcome = yield* Effect.result(bus.publish(entry.event));\n\n if (Result.isFailure(outcome)) {\n const attempts = entry.attempts + 1;\n const quarantine = attempts >= options.maxAttempts;\n\n yield* outbox.recordFailure(\n entry,\n failureText(outcome.failure),\n quarantine,\n );\n\n if (!quarantine) {\n held.add(key);\n continue;\n }\n\n yield* report({\n _tag: 'quarantined',\n database: options.database,\n eventId: entry.eventId,\n eventName: entry.event.name,\n attempts,\n code: outcome.failure.code,\n reason: failureText(outcome.failure),\n });\n continue;\n }\n\n yield* outbox.markSent(entry);\n sent += 1;\n }\n yield* report({ _tag: 'drained', database: options.database, sent });\n return sent;\n });\n\n/**\n * Sample a sweep's depth and age.\n *\n * Defaults to {@link recordOutboxStats}, and a caller overrides it only to\n * assert what was sampled. There is no \"no sink\" option on purpose: an outbox\n * whose depth nothing reports is the failure the gauges exist to make visible.\n */\nexport type OutboxStatsSink = (\n database: string,\n stats: OutboxStats,\n) => Effect.Effect<void>;\n\n/**\n * Drain the one database this service owns, then sample its depth.\n *\n * The single-database counterpart to `startTenantOutboxRelay`. A\n * platform-plane store is one named database, so there is nothing to enumerate\n * and `listDatabases` — which needs a `MongoClient` and cluster-wide rights —\n * never comes into it.\n *\n * Stats are sampled **after** the drain, so the gauge reports what is still\n * waiting rather than what was waiting when the pass began.\n *\n * Every failure is caught and reported as `sweepFailed`. This runs inside\n * `Effect.forever`, and an error that escapes ends the daemon silently — a\n * relay that stopped is indistinguishable from a relay with nothing to do.\n */\nexport const sweepOutbox = (\n outbox: Outbox,\n bus: EventBus,\n options: DrainOptions & { readonly onStats?: OutboxStatsSink },\n) =>\n Effect.gen(function* () {\n yield* drainOutbox(outbox, bus, options);\n const sink = options.onStats ?? recordOutboxStats;\n yield* sink(options.database, yield* outbox.stats());\n }).pipe(\n Effect.catch(failure =>\n (options.onOutcome ?? ignoreRelayOutcome)({\n _tag: 'sweepFailed',\n database: options.database,\n failure,\n }),\n ),\n );\n\n/**\n * Start the relay for a service that owns exactly one database.\n *\n * ⚠️ **The shutdown hook is `flush`, not `stop-intake`, and the phase is the\n * whole point.** `AmqpEventBusLayer` registers `stop-intake` to cancel consumers\n * and drain deliveries; this runs after that, so the last sweep publishes into a\n * connection that is still open. Registered the other way round it would try to\n * publish through a channel already closing, and the entries it was holding\n * would sit until the next boot.\n *\n * The daemon is `delay |> forever`, so the first sweep is one interval away\n * rather than at boot — the write path drains inline, and a sweep racing the\n * index bootstrap on a cold database only produces noise.\n */\nexport const startOutboxRelay = (options?: {\n readonly onStats?: OutboxStatsSink;\n readonly onOutcome?: RelayOutcomeSink;\n}) =>\n Effect.gen(function* () {\n const db = yield* MongoDatabaseTag;\n const bus = yield* EventBusTag;\n const maxAttempts = yield* OutboxMaxAttempts;\n\n yield* ensureOutboxIndexes(db);\n const outbox = makeMongoOutbox(db);\n\n yield* runRelayDaemon(\n sweepOutbox(outbox, bus, {\n maxAttempts,\n database: db.databaseName,\n ...(options?.onStats ? { onStats: options.onStats } : {}),\n ...(options?.onOutcome ? { onOutcome: options.onOutcome } : {}),\n }),\n );\n });\n\n/**\n * Runs `sweepOnce` every {@link SWEEP_INTERVAL}, and once more on the way out.\n *\n * Interrupting the daemon before that last pass is what stops two sweeps\n * publishing the same entry; running the pass is what the hook is for — an\n * event committed a moment before shutdown would otherwise wait out the next\n * process's whole interval.\n */\nconst runRelayDaemon = (sweepOnce: Effect.Effect<void>) =>\n Effect.gen(function* () {\n const shutdown = yield* ShutdownRegistryTag;\n\n const daemon = yield* Effect.forkDetach(\n sweepOnce.pipe(Effect.delay(SWEEP_INTERVAL), Effect.forever),\n );\n\n yield* shutdown.register({\n name: 'outbox-relay',\n phase: 'flush',\n run: Fiber.interrupt(daemon).pipe(Effect.andThen(sweepOnce)),\n });\n });\n\n/**\n * One pass over every organization's outbox in a per-organization store.\n *\n * ⚠️ **Each tenant is caught on its own.** A failure that recurs — an index\n * conflict on one old database, say — would otherwise abandon every tenant\n * listed after it on every pass, while the relay went on looking healthy.\n *\n * Indexes are ensured once per database per process (`ensured`), not on every\n * pass: a sweep visits every tenant every interval, and the index build is the\n * same request each time.\n */\nexport const sweepTenantOutboxes = (\n directory: TenantDirectory<Db>,\n bus: EventBus,\n options: {\n readonly maxAttempts: number;\n readonly onStats?: OutboxStatsSink;\n readonly onOutcome?: RelayOutcomeSink;\n readonly ensured?: Set<string>;\n },\n) =>\n Effect.gen(function* () {\n const report = options.onOutcome ?? ignoreRelayOutcome;\n const ensured = options.ensured ?? new Set<string>();\n const tenants = yield* directory.list();\n\n for (const { handle: db } of tenants) {\n const database = db.databaseName;\n yield* Effect.gen(function* () {\n if (!ensured.has(database)) {\n yield* ensureOutboxIndexes(db);\n ensured.add(database);\n }\n yield* sweepOutbox(makeMongoOutbox(db), bus, {\n maxAttempts: options.maxAttempts,\n database,\n onOutcome: report,\n ...(options.onStats ? { onStats: options.onStats } : {}),\n });\n }).pipe(\n Effect.catch(failure =>\n report({ _tag: 'sweepFailed', database, failure }),\n ),\n );\n }\n }).pipe(\n Effect.catch(failure =>\n (options.onOutcome ?? ignoreRelayOutcome)({\n _tag: 'sweepFailed',\n failure,\n }),\n ),\n );\n\n/**\n * Start the relay for a store with one database per organization, listed by\n * the {@link TenantDirectoryTag} the host provides.\n *\n * The same two speeds as {@link startOutboxRelay}: the write path drains its\n * own tenant inline with {@link drainOutboxNow}, and this sweep carries\n * whatever that missed.\n */\nexport const startTenantOutboxRelay = (options?: {\n readonly onStats?: OutboxStatsSink;\n readonly onOutcome?: RelayOutcomeSink;\n}) =>\n Effect.gen(function* () {\n const directory = (yield* TenantDirectoryTag) as TenantDirectory<Db>;\n const bus = yield* EventBusTag;\n const maxAttempts = yield* OutboxMaxAttempts;\n const ensured = new Set<string>();\n\n yield* runRelayDaemon(\n sweepTenantOutboxes(directory, bus, {\n maxAttempts,\n ensured,\n ...(options?.onStats ? { onStats: options.onStats } : {}),\n ...(options?.onOutcome ? { onOutcome: options.onOutcome } : {}),\n }),\n );\n });\n\n/**\n * Drain one database's outbox now, for a write path that has just committed.\n *\n * The fast path the sweep is the fallback for: an event drained here leaves as\n * soon as its transaction commits, rather than up to {@link SWEEP_INTERVAL}\n * later. Every failure is reported as `drainFailed` and swallowed — the entry\n * is still in the outbox, and the sweep will carry it.\n */\nexport const drainOutboxNow = (\n db: Db,\n onOutcome: RelayOutcomeSink = ignoreRelayOutcome,\n) =>\n Effect.gen(function* () {\n const bus = yield* EventBusTag;\n const maxAttempts = yield* OutboxMaxAttempts;\n yield* drainOutbox(makeMongoOutbox(db), bus, {\n maxAttempts,\n database: db.databaseName,\n onOutcome,\n });\n }).pipe(\n Effect.catch(failure =>\n onOutcome({ _tag: 'drainFailed', database: db.databaseName, failure }),\n ),\n );\n"],"names":["ShutdownRegistryTag","TenantDirectoryTag","aggregateKey","EventBusTag","Context","Duration","Effect","Fiber","Result","MongoDatabaseTag","recordOutboxStats","ensureOutboxIndexes","makeMongoOutbox","failureText","failure","message","code","SWEEP_INTERVAL","seconds","BATCH","ignoreRelayOutcome","void","OutboxMaxAttempts","Service","drainOutbox","outbox","bus","options","gen","entries","pending","held","Set","sent","report","onOutcome","entry","key","aggregate","has","outcome","result","publish","event","isFailure","attempts","quarantine","maxAttempts","recordFailure","add","_tag","database","eventId","eventName","name","reason","markSent","sweepOutbox","sink","onStats","stats","pipe","catch","startOutboxRelay","db","runRelayDaemon","databaseName","sweepOnce","shutdown","daemon","forkDetach","delay","forever","register","phase","run","interrupt","andThen","sweepTenantOutboxes","directory","ensured","tenants","list","handle","startTenantOutboxRelay","drainOutboxNow"],"mappings":";AAAA,SACEA,mBAAmB,EAEnBC,kBAAkB,QACb,oBAAoB;AAC3B,SACEC,YAAY,EAEZC,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;;;;;;;;;;;;;CAa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zB;QAC3B,MAAM0D,UAAU,IAAIhD;QAEpB,OAAOiC,eACLa,oBAAoBC,WAAWrD,KAAK;YAClCqB;YACAiC;WACIrD,CAAAA,2BAAAA,QAASgC,OAAO,IAAG;YAAEA,SAAShC,QAAQgC,OAAO;QAAC,IAAI,CAAC,GACnDhC,CAAAA,2BAAAA,QAASQ,SAAS,IAAG;YAAEA,WAAWR,QAAQQ,SAAS;QAAC,IAAI,CAAC;IAGnE,GAAG;AAEL;;;;;;;CAOC,GACD,OAAO,MAAMkD,iBAAiB,CAC5BrB,IACA7B,YAA8Bf,kBAAkB,GAEhDd,OAAOsB,GAAG,CAAC;QACT,MAAMF,MAAM,OAAOvB;QACnB,MAAM4C,cAAc,OAAOzB;QAC3B,OAAOE,YAAYZ,gBAAgBoD,KAAKtC,KAAK;YAC3CqB;YACAI,UAAUa,GAAGE,YAAY;YACzB/B;QACF;IACF,GAAG0B,IAAI,CACLvD,OAAOwD,KAAK,CAAChD,CAAAA,UACXqB,UAAU;YAAEe,MAAM;YAAeC,UAAUa,GAAGE,YAAY;YAAEpD;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,MAAMC,KAAK,OAAON;QAClB,MAAMO,MAAM,OAAOd;QACnB,MAAMe,cAAc,OAAOd;QAE3B,OAAOO,oBAAoBK;QAC3B,MAAMG,SAASP,gBAAgBI;QAE/B,OAAOT,eACLC,YAAYW,QAAQF,KAAK;YACvBC;YACAE,UAAUJ,GAAGK,YAAY;WACrBP,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;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,sBAAsB,CACjCC,WACAR,KACAH,UAOAL,OAAOM,GAAG,CAAC;YACMD,oBACCA;QADhB,MAAMY,UAASZ,qBAAAA,QAAQS,SAAS,YAAjBT,qBAAqBR;QACpC,MAAMqB,WAAUb,mBAAAA,QAAQa,OAAO,YAAfb,mBAAmB,IAAIc;QACvC,MAAMC,UAAU,OAAOJ,UAAUK,IAAI;QAErC,KAAK,MAAM,EAAEC,QAAQf,EAAE,EAAE,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AAOC,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"}
@@ -11,7 +11,6 @@
11
11
  */
12
12
  export * from '../idempotency/store.js';
13
13
  export * from '../inbox/store.js';
14
- export * from '../outbox/metrics.js';
15
14
  export * from '../outbox/relay.js';
16
15
  export * from '../outbox/store.js';
17
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,yBAAyB,CAAC;AACxC,cAAc,mBAAmB,CAAC;AAClC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,kCAAkC,CAAC;AACjD,cAAc,uCAAuC,CAAC"}
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"}
@@ -10,7 +10,6 @@
10
10
  * error, and it is the adopter's to make deliberately.
11
11
  */ export * from '../idempotency/store.js';
12
12
  export * from '../inbox/store.js';
13
- export * from '../outbox/metrics.js';
14
13
  export * from '../outbox/relay.js';
15
14
  export * from '../outbox/store.js';
16
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 '../idempotency/store.js';\nexport * from '../inbox/store.js';\nexport * from '../outbox/metrics.js';\nexport * from '../outbox/relay.js';\nexport * from '../outbox/store.js';\nexport * from '../saga/store.js';\nexport * from '../unit-of-work/command-inbox.js';\nexport * from '../unit-of-work/mongo-unit-of-work.js';\n"],"names":[],"mappings":"AAAA;;;;;;;;;;CAUC,GACD,cAAc,0BAA0B;AACxC,cAAc,oBAAoB;AAClC,cAAc,uBAAuB;AACrC,cAAc,qBAAqB;AACnC,cAAc,qBAAqB;AACnC,cAAc,mBAAmB;AACjC,cAAc,mCAAmC;AACjD,cAAc,wCAAwC"}
1
+ {"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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/mongo",
3
- "version": "0.11.0",
3
+ "version": "0.12.1",
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/business": "0.11.0",
61
- "@entifix/core": "0.11.0"
60
+ "@entifix/core": "0.12.1",
61
+ "@entifix/business": "0.12.1"
62
62
  },
63
63
  "devDependencies": {
64
64
  "effect": "4.0.6",
65
- "@entifix/testing-unit": "0.11.0",
66
- "@entifix/transactions": "0.11.0"
65
+ "@entifix/testing-unit": "0.12.1",
66
+ "@entifix/transactions": "0.12.1"
67
67
  },
68
68
  "peerDependencies": {
69
69
  "effect": "^4.0.6",
70
- "@entifix/transactions": "0.11.0"
70
+ "@entifix/transactions": "0.12.1"
71
71
  },
72
72
  "peerDependenciesMeta": {
73
73
  "@entifix/transactions": {
@@ -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"}
@@ -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"}