@voltro/plugin-cdc-out 0.85.0 → 0.86.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/index.js CHANGED
@@ -1,311 +1,20 @@
1
- import { Duration as e, Effect as t, Fiber as n, Result as r, Schedule as i, Schema as a } from "effect";
2
- import { definePlugin as o, pluginInstanceName as s } from "@voltro/protocol";
3
- import { OccurrenceCounter as c, and as l, changeDigest as u, composeChangeKey as d, count as f, eq as p, generateId as m, id as h, inSet as g, integer as ee, json as te, lt as _, registerRetention as ne, retentionTtlMsFromEnv as re, table as v, text as y, timestamp as b } from "@voltro/database";
4
- import { withServerTracer as x } from "@voltro/runtime";
5
- //#region src/errors.ts
6
- var S = class extends a.TaggedError()("CdcConfigError", { message: a.String }) {}, C = class extends a.TaggedError()("CdcDeliveryError", {
7
- sink: a.String,
8
- reason: a.String
9
- }) {
10
- get message() {
11
- return `cdc-out delivery to '${this.sink}' failed: ${this.reason}`;
12
- }
13
- }, w = "_voltro_cdcout_outbox", T = "_voltro_cdcout_leases", E = "_voltro_cdcout_claims", D = {
14
- kind: "typeid",
15
- prefix: "cdcout"
16
- }, O = {
17
- kind: "typeid",
18
- prefix: "cdcoutclaim"
19
- }, k = () => m(D, w), A = () => m(O, E), j = v(w, {
20
- id: h({ prefix: "cdcout" }),
21
- pipe: y(),
22
- sourceTable: y(),
23
- op: y(),
24
- key: y(),
25
- payload: te().nullable(),
26
- status: y(),
27
- attempts: ee().default(0),
28
- nextAttemptAt: b(),
29
- claimedBy: y().nullable(),
30
- claimedAt: b().nullable(),
31
- createdAt: b(),
32
- deliveredAt: b().nullable(),
33
- lastError: y().nullable()
34
- }).index(["pipe", "status"]), M = v(E, {
35
- id: h({ prefix: "cdcoutclaim" }),
36
- pipe: y(),
37
- changeKey: y(),
38
- claimedBy: y(),
39
- seenAt: b()
40
- }).unique("cdcoutClaimKey", ["pipe", "changeKey"]).index(["seenAt"]), N = v(T, {
41
- id: h({ scheme: "numeric" }),
42
- key: y(),
43
- holder: y(),
44
- expiresAt: b(),
45
- renewedAt: b()
46
- }).unique("cdcoutLeaseKey", ["key"]), P = (e) => e instanceof Date ? e.getTime() : new Date(String(e)).getTime(), ie = class {
47
- opts;
48
- held = !1;
49
- constructor(e) {
50
- this.opts = e;
51
- }
52
- get isLeader() {
53
- return this.held;
54
- }
55
- async heartbeat(e) {
56
- let t = (this.opts.now ?? Date.now)(), n = {
57
- holder: this.opts.holder,
58
- expiresAt: new Date(t + this.opts.ttlMs),
59
- renewedAt: new Date(t)
60
- };
61
- try {
62
- if (await e.updateMany("_voltro_cdcout_leases", n, { where: l(p("key", this.opts.key), p("holder", this.opts.holder)) }) === 1) return this.held = !0, !0;
63
- let r = await e.insertIgnore(T, {
64
- key: this.opts.key,
65
- ...n
66
- }, { conflictColumns: ["key"] });
67
- if (r.holder === this.opts.holder) return this.held = !0, !0;
68
- let i = await e.updateMany(T, n, { where: l(p("key", this.opts.key), p("holder", String(r.holder)), _("expiresAt", new Date(t))) });
69
- return this.held = i === 1, this.held;
70
- } catch {
71
- return this.held = !1, !1;
72
- }
73
- }
74
- async release(e) {
75
- this.held = !1;
76
- try {
77
- await e.updateMany(T, { expiresAt: /* @__PURE__ */ new Date(0) }, { where: l(p("key", this.opts.key), p("holder", this.opts.holder)) });
78
- } catch {}
79
- }
80
- }, ae = class {
81
- #e = [];
82
- #t = 0;
83
- #n;
84
- #r;
85
- #i = 0;
86
- constructor(e) {
87
- this.#n = e.windowMs, this.#r = Math.max(1, e.maxEntries);
88
- }
89
- get size() {
90
- return this.#e.length;
91
- }
92
- get droppedPending() {
93
- return this.#i;
94
- }
95
- append(e) {
96
- for (this.#e.push(e); this.#e.length > this.#r;) {
97
- let e = this.#e.shift();
98
- e !== void 0 && !e.enqueued && (this.#i += 1), this.#t > 0 && --this.#t;
99
- }
100
- }
101
- nextPending() {
102
- for (; this.#t < this.#e.length && this.#e[this.#t].enqueued;) this.#t += 1;
103
- return this.#e[this.#t];
104
- }
105
- pendingCount() {
106
- return this.#e.reduce((e, t) => t.enqueued ? e : e + 1, 0);
107
- }
108
- prune(e) {
109
- let t = e - this.#n, n = [], r = 0;
110
- for (let [e, i] of this.#e.entries()) i.observedAtMs >= t ? (e < this.#t && (r += 1), n.push(i)) : i.enqueued || (this.#i += 1);
111
- this.#e = n, this.#t = r;
112
- }
113
- }, F = (n, r, i) => t.suspend(() => {
114
- let a = new AbortController();
115
- return t.try(() => n.deliver(r, { signal: a.signal })).pipe(t.flatMap((e) => t.isEffect(e) ? e : t.tryPromise(() => e))).pipe(t.timeoutOrElse({
116
- duration: e.millis(i.timeoutMs),
117
- orElse: () => t.fail(new C({
118
- sink: n.name,
119
- reason: `delivery timed out after ${i.timeoutMs}ms`
120
- }))
121
- }), t.onError(() => t.sync(() => a.abort())), t.mapError((e) => e instanceof C ? e : I(n.name, e)), t.withSpan("cdcOut.deliver", { attributes: {
122
- pipe: i.pipe,
123
- sink: n.name,
124
- records: r.length
125
- } }));
126
- }), I = (e, t) => {
127
- let n = typeof t == "object" && t && "cause" in t && t.cause !== void 0 ? t.cause : t;
128
- return new C({
129
- sink: e,
130
- reason: n instanceof Error ? n.message : String(n)
131
- });
132
- }, L = (e, t) => {
133
- let n = Math.min(t.baseMs * 2 ** Math.max(0, e - 1), t.maxMs);
134
- return Math.round(n * (.5 + .5 * (t.random ?? Math.random)()));
135
- }, oe = class {
136
- opts;
137
- now;
138
- stuckClaimMs;
139
- constructor(e) {
140
- this.opts = e, this.now = e.now ?? Date.now, this.stuckClaimMs = Math.max(2 * e.deliveryTimeoutMs, 1e4);
141
- }
142
- async tick(e) {
143
- this.opts.isLeader() && await Promise.all(this.opts.pipes.map(async (t) => {
144
- if (!t.busy) {
145
- t.busy = !0;
146
- try {
147
- await this.pipeTick(e, t);
148
- } finally {
149
- t.busy = !1;
150
- }
151
- }
152
- }));
153
- }
154
- async pipeTick(e, n) {
155
- let i = this.now();
156
- if (await e.updateMany(w, {
157
- status: "pending",
158
- claimedBy: null,
159
- claimedAt: null
160
- }, { where: l(p("pipe", n.key), p("status", "delivering"), _("claimedAt", new Date(i - this.stuckClaimMs))) }), (await e.query({
161
- table: "_voltro_cdcout_outbox",
162
- predicate: l(p("pipe", n.key), p("status", "delivering")),
163
- order: [],
164
- take: 1,
165
- skip: void 0,
166
- projection: ["id"]
167
- })).length > 0) return;
168
- let a = await e.query({
169
- table: w,
170
- predicate: l(p("pipe", n.key), p("status", "pending")),
171
- order: [{
172
- column: "id",
173
- direction: "asc"
174
- }],
175
- take: n.batchSize,
176
- skip: void 0,
177
- projection: void 0
178
- });
179
- if (a.length === 0) return;
180
- let o = [];
181
- for (let e of a) {
182
- if (P(e.nextAttemptAt) > i) break;
183
- o.push(e);
184
- }
185
- if (o.length === 0) return;
186
- let s = o.map((e) => e.id);
187
- if (await e.updateMany("_voltro_cdcout_outbox", {
188
- status: "delivering",
189
- claimedBy: this.opts.replicaId,
190
- claimedAt: new Date(i)
191
- }, { where: l(p("pipe", n.key), g("id", s), p("status", "pending")) }) === 0) return;
192
- let c = await e.query({
193
- table: w,
194
- predicate: l(p("pipe", n.key), g("id", s), p("status", "delivering"), p("claimedBy", this.opts.replicaId)),
195
- order: [{
196
- column: "id",
197
- direction: "asc"
198
- }],
199
- take: void 0,
200
- skip: void 0,
201
- projection: void 0
202
- });
203
- if (c.length === 0) return;
204
- let u = c.map((e) => ({
205
- table: e.sourceTable,
206
- op: e.op,
207
- key: e.key,
208
- data: e.payload,
209
- deliveryKey: e.id
210
- })), d = await t.runPromise(x(t.result(F(n.sink, u, {
211
- timeoutMs: this.opts.deliveryTimeoutMs,
212
- pipe: n.key
213
- })))), f = this.now();
214
- if (r.isSuccess(d)) {
215
- await e.updateMany(w, {
216
- status: "delivered",
217
- deliveredAt: new Date(f),
218
- claimedBy: null,
219
- claimedAt: null,
220
- lastError: null
221
- }, { where: l(p("pipe", n.key), g("id", c.map((e) => e.id)), p("status", "delivering"), p("claimedBy", this.opts.replicaId)) }), n.stats.delivered += c.length, n.stats.lastDeliveryAtMs = f;
222
- return;
223
- }
224
- let m = d.failure.message;
225
- for (let t of c) {
226
- let r = t.attempts + 1;
227
- if (r >= this.opts.maxAttempts) await e.update(w, t.id, {
228
- status: "dead",
229
- attempts: r,
230
- claimedBy: null,
231
- claimedAt: null,
232
- lastError: m
233
- }), n.stats.dead += 1;
234
- else {
235
- let n = L(r, {
236
- baseMs: this.opts.backoffBaseMs,
237
- maxMs: this.opts.backoffMaxMs,
238
- ...this.opts.random === void 0 ? {} : { random: this.opts.random }
239
- });
240
- await e.update(w, t.id, {
241
- status: "pending",
242
- attempts: r,
243
- nextAttemptAt: new Date(f + n),
244
- claimedBy: null,
245
- claimedAt: null,
246
- lastError: m
247
- });
248
- }
249
- n.stats.failed += 1;
250
- }
251
- this.opts.warn?.("cdc-out delivery failed (durable retry scheduled)", {
252
- pipe: n.key,
253
- sink: n.sink.name,
254
- records: c.length,
255
- attempts: c[0] === void 0 ? 1 : c[0].attempts + 1,
256
- maxAttempts: this.opts.maxAttempts,
257
- reason: m
258
- });
259
- }
260
- }, R = (e = "memory") => {
261
- let t = [];
262
- return {
263
- name: e,
264
- deliver: async (e) => {
265
- t.push([...e]);
266
- },
267
- get batches() {
268
- return t;
269
- },
270
- get delivered() {
271
- return t.flat();
272
- }
273
- };
274
- }, z = (e, t) => {
275
- let n;
276
- try {
277
- n = new URL(e).host;
278
- } catch {
279
- throw new S({ message: `webhookSink: invalid url '${e}'` });
280
- }
281
- let r = `webhook(${n})`;
282
- return {
283
- name: r,
284
- outboundHost: n,
285
- deliver: async (n, i) => {
286
- let a = await fetch(e, {
287
- method: "POST",
288
- headers: {
289
- "content-type": "application/json",
290
- ...t?.headers ?? {}
291
- },
292
- body: JSON.stringify({ records: n }),
293
- signal: i.signal
294
- });
295
- if (!a.ok) throw new C({
296
- sink: r,
297
- reason: `${a.status} ${a.statusText}`
298
- });
299
- }
300
- };
301
- }, se = 100, ce = 5, le = 200, ue = 3e4, de = 250, fe = 1e4, B = 15e3, pe = 72, me = 6e4, he = 1e4, ge = 1e3, V = (e) => {
302
- throw new S({ message: e });
303
- }, H = (e) => {
304
- (e.sinks === void 0 || e.sinks.length === 0) && V("cdcOutPlugin: at least one sink config is required");
1
+ import { CdcConfigError as e, CdcDeliveryError as t } from "./errors.js";
2
+ import { CDCOUT_CLAIMS_TABLE as n, CDCOUT_LEASES_TABLE as r, CDCOUT_OUTBOX_TABLE as i, CdcLeaseManager as a, cdcOutClaimsTable as o, cdcOutLeasesTable as s, cdcOutOutboxTable as c, nextClaimId as l, nextOutboxId as u } from "./outbox.js";
3
+ import { HandoffBuffer as ee } from "./handoff.js";
4
+ import { CdcOutEngine as d, deliverOnce as f, retryDelayMs as p } from "./engine.js";
5
+ import { memorySink as m, webhookSink as h } from "./sinks.js";
6
+ import { Duration as g, Effect as _, Fiber as v, Schedule as y } from "effect";
7
+ import { definePlugin as te, pluginInstanceName as ne } from "@voltro/protocol";
8
+ import { OccurrenceCounter as re, and as b, changeDigest as ie, composeChangeKey as ae, count as oe, eq as x, inSet as S, lt as se, registerRetention as C, retentionTtlMsFromEnv as ce } from "@voltro/database";
9
+ //#region src/index.ts
10
+ var le = 100, ue = 5, de = 200, fe = 3e4, pe = 250, me = 1e4, w = 15e3, he = 72, ge = 6e4, _e = 1e4, ve = 1e3, T = (t) => {
11
+ throw new e({ message: t });
12
+ }, E = (e) => {
13
+ (e.sinks === void 0 || e.sinks.length === 0) && T("cdcOutPlugin: at least one sink config is required");
305
14
  let t = /* @__PURE__ */ new Set();
306
15
  e.sinks.forEach((e, n) => {
307
- (typeof e.table != "string" || e.table.length === 0) && V(`cdcOutPlugin: sinks[${n}].table is required`), e.table.startsWith("_voltro_cdcout") && V(`cdcOutPlugin: sinks[${n}].table '${e.table}' is the plugin's own delivery state — it cannot be mirrored`), t.has(e.table) && V(`cdcOutPlugin: duplicate sink config for table '${e.table}' — one sink config per table per instance; for multiple sinks on one table wire a second cdcOutPlugin({ name: '…' }) instance`), t.add(e.table), (e.sink === void 0 || typeof e.sink.deliver != "function") && V(`cdcOutPlugin: sinks[${n}] (table '${e.table}') needs a sink with a deliver(batch) function`), e.batchSize !== void 0 && e.batchSize <= 0 && V(`cdcOutPlugin: sinks[${n}] (table '${e.table}') batchSize must be > 0`);
308
- }), e.name !== void 0 && !/^[a-zA-Z0-9-]+$/.test(e.name) && V(`cdcOutPlugin: name '${e.name}' must match [a-zA-Z0-9-]+ (it lands in the inspect URL)`);
16
+ (typeof e.table != "string" || e.table.length === 0) && T(`cdcOutPlugin: sinks[${n}].table is required`), e.table.startsWith("_voltro_cdcout") && T(`cdcOutPlugin: sinks[${n}].table '${e.table}' is the plugin's own delivery state — it cannot be mirrored`), t.has(e.table) && T(`cdcOutPlugin: duplicate sink config for table '${e.table}' — one sink config per table per instance; for multiple sinks on one table wire a second cdcOutPlugin({ name: '…' }) instance`), t.add(e.table), (e.sink === void 0 || typeof e.sink.deliver != "function") && T(`cdcOutPlugin: sinks[${n}] (table '${e.table}') needs a sink with a deliver(batch) function`), e.batchSize !== void 0 && e.batchSize <= 0 && T(`cdcOutPlugin: sinks[${n}] (table '${e.table}') batchSize must be > 0`);
17
+ }), e.name !== void 0 && !/^[a-zA-Z0-9-]+$/.test(e.name) && T(`cdcOutPlugin: name '${e.name}' must match [a-zA-Z0-9-]+ (it lands in the inspect URL)`);
309
18
  let n = [
310
19
  ["maxAttempts", e.maxAttempts],
311
20
  ["backoffBaseMs", e.backoffBaseMs],
@@ -318,10 +27,10 @@ var S = class extends a.TaggedError()("CdcConfigError", { message: a.String }) {
318
27
  ["handoffBufferMs", e.handoffBufferMs],
319
28
  ["handoffBufferSize", e.handoffBufferSize]
320
29
  ];
321
- for (let [e, t] of n) t !== void 0 && t < 1 && V(`cdcOutPlugin: ${e} must be >= 1`);
322
- let r = e.leaseTtlMs ?? B;
323
- e.dedupWindowMs !== void 0 && e.dedupWindowMs <= r && V(`cdcOutPlugin: dedupWindowMs (${e.dedupWindowMs}) must exceed leaseTtlMs (${r}) — a claim that expires inside a leadership handoff lets two replicas enqueue the same change`);
324
- }, U = (e, t) => {
30
+ for (let [e, t] of n) t !== void 0 && t < 1 && T(`cdcOutPlugin: ${e} must be >= 1`);
31
+ let r = e.leaseTtlMs ?? w;
32
+ e.dedupWindowMs !== void 0 && e.dedupWindowMs <= r && T(`cdcOutPlugin: dedupWindowMs (${e.dedupWindowMs}) must exceed leaseTtlMs (${r}) — a claim that expires inside a leadership handoff lets two replicas enqueue the same change`);
33
+ }, D = (e, t) => {
325
34
  if (t.filter !== void 0 && !t.filter(e)) return null;
326
35
  if (e.op === "delete") {
327
36
  let t = String(e.old?.id ?? "");
@@ -341,8 +50,8 @@ var S = class extends a.TaggedError()("CdcConfigError", { message: a.String }) {
341
50
  key: r,
342
51
  data: t.map ? t.map(n) : n
343
52
  };
344
- }, W = (e, t) => `${e}:${t.table}:${t.sink.name}`, G = (e, t, n) => ({
345
- id: k(),
53
+ }, O = (e, t) => `${e}:${t.table}:${t.sink.name}`, k = (e, t, n) => ({
54
+ id: u(),
346
55
  pipe: t,
347
56
  sourceTable: e.table,
348
57
  op: e.op,
@@ -356,30 +65,30 @@ var S = class extends a.TaggedError()("CdcConfigError", { message: a.String }) {
356
65
  createdAt: new Date(n),
357
66
  deliveredAt: null,
358
67
  lastError: null
359
- }), K = async (e, t, n, r) => {
360
- let i = W(r?.instanceName ?? "default", t), a = (r?.now ?? Date.now)(), o = n.flatMap((e) => {
68
+ }), A = async (e, t, n, r) => {
69
+ let a = O(r?.instanceName ?? "default", t), o = (r?.now ?? Date.now)(), s = n.flatMap((e) => {
361
70
  let n = String(e.id ?? "");
362
- return n === "" ? [] : [G({
71
+ return n === "" ? [] : [k({
363
72
  table: t.table,
364
73
  op: "insert",
365
74
  key: n,
366
75
  data: t.map ? t.map(e) : e
367
- }, i, a)];
76
+ }, a, o)];
368
77
  });
369
- return o.length > 0 && await e.insertMany(w, o), o.length;
370
- }, q = "@voltro/plugin-cdc-out", J = (r) => {
371
- H(r);
372
- let a = r.name ?? "default", m = s({
373
- base: q,
374
- alias: r.alias,
375
- instance: r.name
376
- }), h = `cdcout-${Math.random().toString(36).slice(2, 10)}`, ee = r.maxAttempts ?? ce, te = r.sweepIntervalMs ?? de, v = r.leaseTtlMs ?? B, y = r.dedupWindowMs ?? Math.max(me, 4 * v), b = r.handoffBufferMs ?? y, x = r.handoffBufferSize ?? he, S = /* @__PURE__ */ new Map();
377
- for (let e of r.sinks) S.set(e.table, {
378
- config: e,
78
+ return s.length > 0 && await e.insertMany(i, s), s.length;
79
+ }, j = "@voltro/plugin-cdc-out", M = (e) => {
80
+ E(e);
81
+ let t = e.name ?? "default", r = ne({
82
+ base: j,
83
+ alias: e.alias,
84
+ instance: e.name
85
+ }), u = `cdcout-${Math.random().toString(36).slice(2, 10)}`, f = e.maxAttempts ?? ue, p = e.sweepIntervalMs ?? pe, m = e.leaseTtlMs ?? w, h = e.dedupWindowMs ?? Math.max(ge, 4 * m), T = e.handoffBufferMs ?? h, A = e.handoffBufferSize ?? _e, M = /* @__PURE__ */ new Map();
86
+ for (let n of e.sinks) M.set(n.table, {
87
+ config: n,
379
88
  enginePipe: {
380
- key: W(a, e),
381
- sink: e.sink,
382
- batchSize: e.batchSize ?? se,
89
+ key: O(t, n),
90
+ sink: n.sink,
91
+ batchSize: n.batchSize ?? le,
383
92
  busy: !1,
384
93
  stats: {
385
94
  delivered: 0,
@@ -389,48 +98,48 @@ var S = class extends a.TaggedError()("CdcConfigError", { message: a.String }) {
389
98
  }
390
99
  }
391
100
  });
392
- let C = new ie({
393
- key: a,
394
- holder: h,
395
- ttlMs: v
396
- }), T = new oe({
397
- pipes: [...S.values()].map((e) => e.enginePipe),
398
- replicaId: h,
399
- maxAttempts: ee,
400
- backoffBaseMs: r.backoffBaseMs ?? le,
401
- backoffMaxMs: r.backoffMaxMs ?? ue,
402
- deliveryTimeoutMs: r.deliveryTimeoutMs ?? fe,
403
- isLeader: () => C.isLeader,
404
- warn: (e, t) => O(e, t)
405
- }), D = { current: null }, O = () => void 0, k = 0, P, F, I = new c({
406
- windowMs: 2 * y,
407
- maxEntries: Math.max(x, 1e3) * 4
408
- }), L = new ae({
409
- windowMs: b,
410
- maxEntries: x
411
- }), R = !1, z = 0, V = !1, K = null, J = 0, _e = !1, ve = !1, Y = [], X = 0;
412
- ne({
101
+ let N = new a({
102
+ key: t,
103
+ holder: u,
104
+ ttlMs: m
105
+ }), ye = new d({
106
+ pipes: [...M.values()].map((e) => e.enginePipe),
107
+ replicaId: u,
108
+ maxAttempts: f,
109
+ backoffBaseMs: e.backoffBaseMs ?? de,
110
+ backoffMaxMs: e.backoffMaxMs ?? fe,
111
+ deliveryTimeoutMs: e.deliveryTimeoutMs ?? me,
112
+ isLeader: () => N.isLeader,
113
+ warn: (e, t) => F(e, t)
114
+ }), P = { current: null }, F = () => void 0, I = 0, L, R, z = new re({
115
+ windowMs: 2 * h,
116
+ maxEntries: Math.max(A, 1e3) * 4
117
+ }), B = new ee({
118
+ windowMs: T,
119
+ maxEntries: A
120
+ }), V = !1, H = 0, U = !1, W = null, G = 0, K = !1, q = !1, J = [], Y = 0;
121
+ C({
413
122
  source: "plugin",
414
- table: w,
123
+ table: i,
415
124
  timeColumn: "createdAt",
416
- ttlMs: r.retentionHours === void 0 ? re(process.env.CDCOUT_RETENTION_HOURS, pe) : r.retentionHours * 36e5,
417
- where: g("status", ["delivered", "dead"]),
125
+ ttlMs: e.retentionHours === void 0 ? ce(process.env.CDCOUT_RETENTION_HOURS, he) : e.retentionHours * 36e5,
126
+ where: S("status", ["delivered", "dead"]),
418
127
  label: "cdc-out outbox (delivered/dead)"
419
- }), ne({
128
+ }), C({
420
129
  source: "plugin",
421
- table: E,
130
+ table: n,
422
131
  timeColumn: "seenAt",
423
- ttlMs: y,
132
+ ttlMs: h,
424
133
  label: "cdc-out enqueue claims (dedup window)"
425
134
  });
426
- let ye = /* @__PURE__ */ new Set();
427
- for (let e of r.sinks) e.sink.outboundHost && ye.add(e.sink.outboundHost);
135
+ let X = /* @__PURE__ */ new Set();
136
+ for (let t of e.sinks) t.sink.outboundHost && X.add(t.sink.outboundHost);
428
137
  let be = [
429
138
  "store:changes:read",
430
139
  "store:write",
431
140
  "inspect:read",
432
141
  "inspect:write",
433
- ...[...ye].map((e) => `network:outbound:${e}`)
142
+ ...[...X].map((e) => `network:outbound:${e}`)
434
143
  ], xe = [
435
144
  "pending",
436
145
  "delivering",
@@ -444,93 +153,90 @@ var S = class extends a.TaggedError()("CdcConfigError", { message: a.String }) {
444
153
  dead: 0
445
154
  };
446
155
  return await Promise.all(xe.map(async (r) => {
447
- let i = await e.query({
448
- table: w,
449
- predicate: l(p("pipe", t), p("status", r)),
156
+ let a = await e.query({
157
+ table: i,
158
+ predicate: b(x("pipe", t), x("status", r)),
450
159
  order: [],
451
160
  take: void 0,
452
161
  skip: void 0,
453
162
  projection: void 0,
454
- aggregations: [f("n")]
163
+ aggregations: [oe("n")]
455
164
  });
456
- n[r] = Number(i[0]?.n ?? 0);
165
+ n[r] = Number(a[0]?.n ?? 0);
457
166
  })), n;
458
- }, Z = (e) => {
167
+ }, Ce = (e) => {
459
168
  let t = Date.now();
460
- t - k > 6e4 && (k = t, O("cdc-out: no DataStore bound — change events are NOT being mirrored", { table: e }));
461
- }, Ce = async (e, t, n) => (await e.insertIgnore(E, {
462
- id: A(),
169
+ t - I > 6e4 && (I = t, F("cdc-out: no DataStore bound — change events are NOT being mirrored", { table: e }));
170
+ }, we = async (e, t, r) => (await e.insertIgnore(n, {
171
+ id: l(),
463
172
  pipe: t,
464
- changeKey: n,
465
- claimedBy: h,
173
+ changeKey: r,
174
+ claimedBy: u,
466
175
  seenAt: /* @__PURE__ */ new Date()
467
- }, { conflictColumns: ["pipe", "changeKey"] })).claimedBy === h, Q = async () => {
468
- if (R) return;
469
- let e = D.current;
176
+ }, { conflictColumns: ["pipe", "changeKey"] })).claimedBy === u, Z = async () => {
177
+ if (V) return;
178
+ let e = P.current;
470
179
  if (e !== null) {
471
- R = !0;
180
+ V = !0;
472
181
  try {
473
182
  for (;;) {
474
- let t = L.nextPending();
475
- if (t === void 0 || !C.isLeader) return;
476
- await Ce(e, t.pipe, t.changeKey) && await e.insert(w, G(t.change, t.pipe, Date.now())), t.enqueued = !0;
183
+ let t = B.nextPending();
184
+ if (t === void 0 || !N.isLeader) return;
185
+ await we(e, t.pipe, t.changeKey) && await e.insert(i, k(t.change, t.pipe, Date.now())), t.enqueued = !0;
477
186
  }
478
187
  } finally {
479
- R = !1;
188
+ V = !1;
480
189
  }
481
190
  }
482
- }, we = (e) => {
483
- if (_e = !0, !V) {
484
- for (Y.push(e); Y.length > x;) Y.shift(), X += 1;
485
- return;
486
- }
487
- L.append({
191
+ }, Q = (e) => {
192
+ if (K = !0, !U) for (J.push(e); J.length > A;) J.shift(), Y += 1;
193
+ else B.append({
488
194
  pipe: e.pipe,
489
- changeKey: d(e.digest, I.next(e.digest, e.observedAtMs)),
195
+ changeKey: ae(e.digest, z.next(e.digest, e.observedAtMs)),
490
196
  change: e.change,
491
197
  observedAtMs: e.observedAtMs,
492
198
  enqueued: !1
493
199
  });
494
200
  }, Te = (e, t) => {
495
- I.seedFromChangeKeys(e, t), V = !0;
496
- for (let e of Y.splice(0, Y.length)) we(e);
201
+ z.seedFromChangeKeys(e, t), U = !0;
202
+ for (let e of J.splice(0, J.length)) Q(e);
497
203
  }, $ = async () => {
498
- if (V) return;
499
- let e = D.current;
204
+ if (U) return;
205
+ let e = P.current;
500
206
  if (e !== null) {
501
- if (K === null) {
502
- if (J !== 0 && Date.now() - J < ge) return;
503
- let t = !_e;
504
- K = (async () => {
505
- let n = await e.query({
506
- table: E,
207
+ if (W === null) {
208
+ if (G !== 0 && Date.now() - G < ve) return;
209
+ let t = !K;
210
+ W = (async () => {
211
+ let r = await e.query({
212
+ table: n,
507
213
  predicate: void 0,
508
214
  order: [{
509
215
  column: "seenAt",
510
216
  direction: "desc"
511
217
  }],
512
- take: Math.max(x, 1e3),
218
+ take: Math.max(A, 1e3),
513
219
  skip: void 0,
514
220
  projection: ["changeKey"]
515
221
  });
516
- !t && !ve && (ve = !0, O("cdc-out: occurrence counters start from this replica's own stream — the claims snapshot was only reachable after it began observing, and counting it could duplicate a change", { replicaId: h })), Te(t ? n.flatMap((e) => typeof e.changeKey == "string" ? [e.changeKey] : []) : [], Date.now());
222
+ !t && !q && (q = !0, F("cdc-out: occurrence counters start from this replica's own stream — the claims snapshot was only reachable after it began observing, and counting it could duplicate a change", { replicaId: u })), Te(t ? r.flatMap((e) => typeof e.changeKey == "string" ? [e.changeKey] : []) : [], Date.now());
517
223
  })().catch((e) => {
518
- J = Date.now(), O("cdc-out: could not seed change-occurrence counters — enqueue is held until it lands", { reason: String(e) });
224
+ G = Date.now(), F("cdc-out: could not seed change-occurrence counters — enqueue is held until it lands", { reason: String(e) });
519
225
  }).finally(() => {
520
- K = null;
226
+ W = null;
521
227
  });
522
228
  }
523
- await K;
229
+ await W;
524
230
  }
525
231
  }, Ee = (e) => {
526
- let t = e - b;
527
- for (; Y.length > 0 && Y[0].observedAtMs < t;) Y.shift(), X += 1;
232
+ let t = e - T;
233
+ for (; J.length > 0 && J[0].observedAtMs < t;) J.shift(), Y += 1;
528
234
  }, De = async (e, t) => {
529
- t - z < Math.max(1e3, Math.floor(y / 4)) || (z = t, await e.deleteMany(E, { where: _("seenAt", new Date(t - y)) }));
235
+ t - H < Math.max(1e3, Math.floor(h / 4)) || (H = t, await e.deleteMany(n, { where: se("seenAt", new Date(t - h)) }));
530
236
  };
531
- return o({
532
- name: m,
533
- baseName: q,
237
+ return te({
238
+ name: r,
239
+ baseName: j,
534
240
  description: "Declarative reverse-ETL: mirror table changes outward to external sinks (webhook, Kafka via @voltro/plugin-queue's kafkaSink, plus a CdcSink interface for custom sinks) through a durable outbox — ordered per pipe, at-least-once from enqueue, retried with backoff, dead-lettered.",
535
241
  permissions: be,
536
242
  declaredEnv: [{
@@ -541,12 +247,12 @@ var S = class extends a.TaggedError()("CdcConfigError", { message: a.String }) {
541
247
  example: "72"
542
248
  }],
543
249
  extendSchema: { tables: [
544
- j,
545
- N,
546
- M
250
+ c,
251
+ s,
252
+ o
547
253
  ] },
548
254
  bindDataStore: (e) => {
549
- D.current = e, $();
255
+ P.current = e, $();
550
256
  },
551
257
  inspectEndpoints: [
552
258
  {
@@ -554,12 +260,12 @@ var S = class extends a.TaggedError()("CdcConfigError", { message: a.String }) {
554
260
  path: "/sinks",
555
261
  scope: "process",
556
262
  description: "Configured sinks + per-pipe outbox counts and delivery stats.",
557
- handler: () => t.tryPromise(async () => {
558
- let e = D.current;
263
+ handler: () => _.tryPromise(async () => {
264
+ let e = P.current;
559
265
  return {
560
266
  kind: "json",
561
267
  data: {
562
- sinks: await Promise.all([...S.values()].map(async ({ config: t, enginePipe: n }) => {
268
+ sinks: await Promise.all([...M.values()].map(async ({ config: t, enginePipe: n }) => {
563
269
  let r = e === null ? {
564
270
  pending: 0,
565
271
  delivering: 0,
@@ -576,14 +282,14 @@ var S = class extends a.TaggedError()("CdcConfigError", { message: a.String }) {
576
282
  };
577
283
  })),
578
284
  handoff: {
579
- leader: C.isLeader,
580
- seeded: V,
581
- awaitingSeed: Y.length,
582
- buffered: L.size,
583
- pending: L.pendingCount(),
584
- dropped: L.droppedPending + X,
585
- windowMs: b,
586
- dedupWindowMs: y
285
+ leader: N.isLeader,
286
+ seeded: U,
287
+ awaitingSeed: J.length,
288
+ buffered: B.size,
289
+ pending: B.pendingCount(),
290
+ dropped: B.droppedPending + Y,
291
+ windowMs: T,
292
+ dedupWindowMs: h
587
293
  }
588
294
  }
589
295
  };
@@ -594,16 +300,16 @@ var S = class extends a.TaggedError()("CdcConfigError", { message: a.String }) {
594
300
  path: "/dead-letter",
595
301
  scope: "process",
596
302
  description: "Outbox rows that exhausted maxAttempts (newest first, capped at 100).",
597
- handler: () => t.tryPromise(async () => {
598
- let e = D.current;
303
+ handler: () => _.tryPromise(async () => {
304
+ let e = P.current;
599
305
  return e === null ? {
600
306
  kind: "json",
601
307
  data: { rows: [] }
602
308
  } : {
603
309
  kind: "json",
604
310
  data: { rows: (await e.query({
605
- table: w,
606
- predicate: l(p("status", "dead"), g("pipe", [...S.values()].map((e) => e.enginePipe.key))),
311
+ table: i,
312
+ predicate: b(x("status", "dead"), S("pipe", [...M.values()].map((e) => e.enginePipe.key))),
607
313
  order: [{
608
314
  column: "id",
609
315
  direction: "desc"
@@ -628,7 +334,7 @@ var S = class extends a.TaggedError()("CdcConfigError", { message: a.String }) {
628
334
  method: "POST",
629
335
  path: "/dead-letter/retry",
630
336
  description: "Re-enqueue one confirmed dead delivery in this plugin instance with its original delivery key.",
631
- handler: (e) => t.tryPromise(async () => {
337
+ handler: (e) => _.tryPromise(async () => {
632
338
  let t;
633
339
  try {
634
340
  t = JSON.parse(e.body ?? "");
@@ -644,80 +350,80 @@ var S = class extends a.TaggedError()("CdcConfigError", { message: a.String }) {
644
350
  status: 400,
645
351
  data: { error: "A delivery key and explicit confirmation are required." }
646
352
  };
647
- let n = D.current;
353
+ let n = P.current;
648
354
  return n === null ? {
649
355
  kind: "json",
650
356
  status: 503,
651
357
  data: { error: "Store unavailable." }
652
358
  } : {
653
359
  kind: "json",
654
- data: { accepted: await n.updateMany(w, {
360
+ data: { accepted: await n.updateMany(i, {
655
361
  status: "pending",
656
362
  attempts: 0,
657
363
  nextAttemptAt: /* @__PURE__ */ new Date(),
658
364
  claimedBy: null,
659
365
  claimedAt: null
660
- }, { where: l(p("id", t.deliveryKey), p("status", "dead"), g("pipe", [...S.values()].map((e) => e.enginePipe.key))) }) === 1 }
366
+ }, { where: b(x("id", t.deliveryKey), x("status", "dead"), S("pipe", [...M.values()].map((e) => e.enginePipe.key))) }) === 1 }
661
367
  };
662
368
  })
663
369
  }
664
370
  ],
665
371
  onChangeEvent: (e) => {
666
- let n = S.get(e.table);
667
- if (n === void 0) return t.void;
668
- let r = U(e, n.config);
669
- if (r === null) return t.void;
372
+ let t = M.get(e.table);
373
+ if (t === void 0) return _.void;
374
+ let n = D(e, t.config);
375
+ if (n === null) return _.void;
670
376
  if (e.changeScope === "fleet") {
671
- let i = Date.now(), a = u({
672
- pipe: n.enginePipe.key,
673
- op: r.op,
674
- key: r.key,
377
+ let r = Date.now(), i = ie({
378
+ pipe: t.enginePipe.key,
379
+ op: n.op,
380
+ key: n.key,
675
381
  next: e.new,
676
382
  prev: e.old
677
383
  });
678
- return we({
679
- pipe: n.enginePipe.key,
680
- digest: a,
681
- change: r,
682
- observedAtMs: i
683
- }), D.current === null ? (Z(e.table), t.void) : t.promise(() => $()).pipe(t.flatMap(() => C.isLeader ? t.tryPromise(() => Q()) : t.void));
384
+ return Q({
385
+ pipe: t.enginePipe.key,
386
+ digest: i,
387
+ change: n,
388
+ observedAtMs: r
389
+ }), P.current === null ? (Ce(e.table), _.void) : _.promise(() => $()).pipe(_.flatMap(() => N.isLeader ? _.tryPromise(() => Z()) : _.void));
684
390
  }
685
- if (e.origin === "injected") return t.void;
686
- let i = D.current;
687
- if (i === null) return Z(e.table), t.void;
688
- let a = G(r, n.enginePipe.key, Date.now());
689
- return t.tryPromise(() => i.insert(w, a).then(() => void 0));
391
+ if (e.origin === "injected") return _.void;
392
+ let r = P.current;
393
+ if (r === null) return Ce(e.table), _.void;
394
+ let a = k(n, t.enginePipe.key, Date.now());
395
+ return _.tryPromise(() => r.insert(i, a).then(() => void 0));
690
396
  },
691
- onActivate: (n) => t.sync(() => {
692
- O = (e, t) => n.logger.warn(e, t);
693
- let r = t.suspend(() => {
694
- let e = D.current;
695
- return e === null ? t.void : t.promise(async () => {
397
+ onActivate: (e) => _.sync(() => {
398
+ F = (t, n) => e.logger.warn(t, n);
399
+ let t = _.suspend(() => {
400
+ let e = P.current;
401
+ return e === null ? _.void : _.promise(async () => {
696
402
  await $();
697
- let t = C.isLeader;
698
- await C.heartbeat(e) && !t && await Q().catch((e) => {
699
- O("cdc-out: handoff drain failed (retried on the next sweep)", { reason: String(e) });
403
+ let t = N.isLeader;
404
+ await N.heartbeat(e) && !t && await Z().catch((e) => {
405
+ F("cdc-out: handoff drain failed (retried on the next sweep)", { reason: String(e) });
700
406
  });
701
407
  });
702
- }).pipe(t.repeat(i.spaced(e.millis(Math.max(1, Math.floor(v / 3)))))), a = t.suspend(() => {
703
- let e = D.current;
704
- return e === null ? t.void : t.tryPromise(async () => {
408
+ }).pipe(_.repeat(y.spaced(g.millis(Math.max(1, Math.floor(m / 3)))))), n = _.suspend(() => {
409
+ let e = P.current;
410
+ return e === null ? _.void : _.tryPromise(async () => {
705
411
  let t = Date.now();
706
- await $(), Ee(t), L.prune(t), I.prune(t), await De(e, t), C.isLeader && await Q(), await T.tick(e);
707
- }).pipe(t.catch((e) => t.sync(() => O("cdc-out worker sweep failed", { reason: String(e) }))));
708
- }).pipe(t.repeat(i.spaced(e.millis(te))));
709
- F = t.runFork(r), P = t.runFork(a), n.logger.info("cdc-out active", {
710
- tables: [...S.keys()],
711
- replicaId: h,
712
- outbox: w
412
+ await $(), Ee(t), B.prune(t), z.prune(t), await De(e, t), N.isLeader && await Z(), await ye.tick(e);
413
+ }).pipe(_.catch((e) => _.sync(() => F("cdc-out worker sweep failed", { reason: String(e) }))));
414
+ }).pipe(_.repeat(y.spaced(g.millis(p))));
415
+ R = _.runFork(t), L = _.runFork(n), e.logger.info("cdc-out active", {
416
+ tables: [...M.keys()],
417
+ replicaId: u,
418
+ outbox: i
713
419
  });
714
420
  }),
715
- onDeactivate: () => t.gen(function* () {
716
- P !== void 0 && (yield* n.interrupt(P)), F !== void 0 && (yield* n.interrupt(F)), P = void 0, F = void 0;
717
- let e = D.current;
718
- e !== null && (yield* t.promise(() => C.release(e)));
421
+ onDeactivate: () => _.gen(function* () {
422
+ L !== void 0 && (yield* v.interrupt(L)), R !== void 0 && (yield* v.interrupt(R)), L = void 0, R = void 0;
423
+ let e = P.current;
424
+ e !== null && (yield* _.promise(() => N.release(e)));
719
425
  })
720
426
  });
721
427
  };
722
428
  //#endregion
723
- export { E as CDCOUT_CLAIMS_TABLE, T as CDCOUT_LEASES_TABLE, w as CDCOUT_OUTBOX_TABLE, S as CdcConfigError, C as CdcDeliveryError, ie as CdcLeaseManager, oe as CdcOutEngine, ae as HandoffBuffer, M as cdcOutClaimsTable, N as cdcOutLeasesTable, j as cdcOutOutboxTable, J as cdcOutPlugin, F as deliverOnce, K as enqueueBackfill, U as mapChange, R as memorySink, A as nextClaimId, k as nextOutboxId, G as outboxRowFor, W as pipeKey, L as retryDelayMs, H as validateCdcOutConfig, z as webhookSink };
429
+ export { n as CDCOUT_CLAIMS_TABLE, r as CDCOUT_LEASES_TABLE, i as CDCOUT_OUTBOX_TABLE, e as CdcConfigError, t as CdcDeliveryError, a as CdcLeaseManager, d as CdcOutEngine, ee as HandoffBuffer, o as cdcOutClaimsTable, s as cdcOutLeasesTable, c as cdcOutOutboxTable, M as cdcOutPlugin, f as deliverOnce, A as enqueueBackfill, D as mapChange, m as memorySink, l as nextClaimId, u as nextOutboxId, k as outboxRowFor, O as pipeKey, p as retryDelayMs, E as validateCdcOutConfig, h as webhookSink };