@voltro/plugin-cdc-out 0.83.1 → 0.85.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,49 +1,49 @@
1
- import { Duration as e, Effect as t, Fiber as n, Schedule as r, Schema as i } from "effect";
2
- import { definePlugin as a, pluginInstanceName as o } from "@voltro/protocol";
3
- import { OccurrenceCounter as s, and as c, changeDigest as ee, composeChangeKey as l, count as u, eq as d, generateId as f, id as p, inSet as m, integer as h, json as te, lt as g, registerRetention as ne, retentionTtlMsFromEnv as re, table as _, text as v, timestamp as y } from "@voltro/database";
4
- import { withServerTracer as b } from "@voltro/runtime";
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
5
  //#region src/errors.ts
6
- var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {}, S = class extends i.TaggedError()("CdcDeliveryError", {
7
- sink: i.String,
8
- reason: i.String
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
9
  }) {
10
10
  get message() {
11
11
  return `cdc-out delivery to '${this.sink}' failed: ${this.reason}`;
12
12
  }
13
- }, C = "_voltro_cdcout_outbox", w = "_voltro_cdcout_leases", T = "_voltro_cdcout_claims", E = {
13
+ }, w = "_voltro_cdcout_outbox", T = "_voltro_cdcout_leases", E = "_voltro_cdcout_claims", D = {
14
14
  kind: "typeid",
15
15
  prefix: "cdcout"
16
- }, D = {
16
+ }, O = {
17
17
  kind: "typeid",
18
18
  prefix: "cdcoutclaim"
19
- }, O = () => f(E, C), ie = () => f(D, T), k = _(C, {
20
- id: p({ prefix: "cdcout" }),
21
- pipe: v(),
22
- sourceTable: v(),
23
- op: v(),
24
- key: v(),
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
25
  payload: te().nullable(),
26
- status: v(),
27
- attempts: h().default(0),
28
- nextAttemptAt: y(),
29
- claimedBy: v().nullable(),
30
- claimedAt: y().nullable(),
31
- createdAt: y(),
32
- deliveredAt: y().nullable(),
33
- lastError: v().nullable()
34
- }).index(["pipe", "status"]), A = _(T, {
35
- id: p({ prefix: "cdcoutclaim" }),
36
- pipe: v(),
37
- changeKey: v(),
38
- claimedBy: v(),
39
- seenAt: y()
40
- }).unique("cdcoutClaimKey", ["pipe", "changeKey"]).index(["seenAt"]), j = _(w, {
41
- id: p({ scheme: "numeric" }),
42
- key: v(),
43
- holder: v(),
44
- expiresAt: y(),
45
- renewedAt: y()
46
- }).unique("cdcoutLeaseKey", ["key"]), M = (e) => e instanceof Date ? e.getTime() : new Date(String(e)).getTime(), N = class {
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
47
  opts;
48
48
  held = !1;
49
49
  constructor(e) {
@@ -59,13 +59,13 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
59
59
  renewedAt: new Date(t)
60
60
  };
61
61
  try {
62
- if (await e.updateMany("_voltro_cdcout_leases", n, { where: c(d("key", this.opts.key), d("holder", this.opts.holder)) }) === 1) return this.held = !0, !0;
63
- let r = await e.insertIgnore(w, {
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
64
  key: this.opts.key,
65
65
  ...n
66
66
  }, { conflictColumns: ["key"] });
67
67
  if (r.holder === this.opts.holder) return this.held = !0, !0;
68
- let i = await e.updateMany(w, n, { where: c(d("key", this.opts.key), d("holder", String(r.holder)), g("expiresAt", new Date(t))) });
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
69
  return this.held = i === 1, this.held;
70
70
  } catch {
71
71
  return this.held = !1, !1;
@@ -74,10 +74,10 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
74
74
  async release(e) {
75
75
  this.held = !1;
76
76
  try {
77
- await e.updateMany(w, { expiresAt: /* @__PURE__ */ new Date(0) }, { where: c(d("key", this.opts.key), d("holder", this.opts.holder)) });
77
+ await e.updateMany(T, { expiresAt: /* @__PURE__ */ new Date(0) }, { where: l(p("key", this.opts.key), p("holder", this.opts.holder)) });
78
78
  } catch {}
79
79
  }
80
- }, P = class {
80
+ }, ae = class {
81
81
  #e = [];
82
82
  #t = 0;
83
83
  #n;
@@ -112,27 +112,27 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
112
112
  }
113
113
  }, F = (n, r, i) => t.suspend(() => {
114
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.timeoutFail({
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
116
  duration: e.millis(i.timeoutMs),
117
- onTimeout: () => new S({
117
+ orElse: () => t.fail(new C({
118
118
  sink: n.name,
119
119
  reason: `delivery timed out after ${i.timeoutMs}ms`
120
- })
121
- }), t.onError(() => t.sync(() => a.abort())), t.mapError((e) => e instanceof S ? e : I(n.name, e)), t.withSpan("cdcOut.deliver", { attributes: {
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
122
  pipe: i.pipe,
123
123
  sink: n.name,
124
124
  records: r.length
125
125
  } }));
126
126
  }), I = (e, t) => {
127
- let n = typeof t == "object" && t && "error" in t ? t.error : t;
128
- return new S({
127
+ let n = typeof t == "object" && t && "cause" in t && t.cause !== void 0 ? t.cause : t;
128
+ return new C({
129
129
  sink: e,
130
130
  reason: n instanceof Error ? n.message : String(n)
131
131
  });
132
132
  }, L = (e, t) => {
133
133
  let n = Math.min(t.baseMs * 2 ** Math.max(0, e - 1), t.maxMs);
134
134
  return Math.round(n * (.5 + .5 * (t.random ?? Math.random)()));
135
- }, ae = class {
135
+ }, oe = class {
136
136
  opts;
137
137
  now;
138
138
  stuckClaimMs;
@@ -152,22 +152,22 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
152
152
  }));
153
153
  }
154
154
  async pipeTick(e, n) {
155
- let r = this.now();
156
- if (await e.updateMany(C, {
155
+ let i = this.now();
156
+ if (await e.updateMany(w, {
157
157
  status: "pending",
158
158
  claimedBy: null,
159
159
  claimedAt: null
160
- }, { where: c(d("pipe", n.key), d("status", "delivering"), g("claimedAt", new Date(r - this.stuckClaimMs))) }), (await e.query({
160
+ }, { where: l(p("pipe", n.key), p("status", "delivering"), _("claimedAt", new Date(i - this.stuckClaimMs))) }), (await e.query({
161
161
  table: "_voltro_cdcout_outbox",
162
- predicate: c(d("pipe", n.key), d("status", "delivering")),
162
+ predicate: l(p("pipe", n.key), p("status", "delivering")),
163
163
  order: [],
164
164
  take: 1,
165
165
  skip: void 0,
166
166
  projection: ["id"]
167
167
  })).length > 0) return;
168
- let i = await e.query({
169
- table: C,
170
- predicate: c(d("pipe", n.key), d("status", "pending")),
168
+ let a = await e.query({
169
+ table: w,
170
+ predicate: l(p("pipe", n.key), p("status", "pending")),
171
171
  order: [{
172
172
  column: "id",
173
173
  direction: "asc"
@@ -176,22 +176,22 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
176
176
  skip: void 0,
177
177
  projection: void 0
178
178
  });
179
- if (i.length === 0) return;
180
- let a = [];
181
- for (let e of i) {
182
- if (M(e.nextAttemptAt) > r) break;
183
- a.push(e);
184
- }
185
179
  if (a.length === 0) return;
186
- let o = a.map((e) => e.id);
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
187
  if (await e.updateMany("_voltro_cdcout_outbox", {
188
188
  status: "delivering",
189
189
  claimedBy: this.opts.replicaId,
190
- claimedAt: new Date(r)
191
- }, { where: c(d("pipe", n.key), m("id", o), d("status", "pending")) }) === 0) return;
192
- let s = await e.query({
193
- table: C,
194
- predicate: c(d("pipe", n.key), m("id", o), d("status", "delivering"), d("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
195
  order: [{
196
196
  column: "id",
197
197
  direction: "asc"
@@ -200,36 +200,36 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
200
200
  skip: void 0,
201
201
  projection: void 0
202
202
  });
203
- if (s.length === 0) return;
204
- let ee = s.map((e) => ({
203
+ if (c.length === 0) return;
204
+ let u = c.map((e) => ({
205
205
  table: e.sourceTable,
206
206
  op: e.op,
207
207
  key: e.key,
208
208
  data: e.payload,
209
209
  deliveryKey: e.id
210
- })), l = await t.runPromise(b(t.either(F(n.sink, ee, {
210
+ })), d = await t.runPromise(x(t.result(F(n.sink, u, {
211
211
  timeoutMs: this.opts.deliveryTimeoutMs,
212
212
  pipe: n.key
213
- })))), u = this.now();
214
- if (l._tag === "Right") {
215
- await e.updateMany(C, {
213
+ })))), f = this.now();
214
+ if (r.isSuccess(d)) {
215
+ await e.updateMany(w, {
216
216
  status: "delivered",
217
- deliveredAt: new Date(u),
217
+ deliveredAt: new Date(f),
218
218
  claimedBy: null,
219
219
  claimedAt: null,
220
220
  lastError: null
221
- }, { where: c(d("pipe", n.key), m("id", s.map((e) => e.id)), d("status", "delivering"), d("claimedBy", this.opts.replicaId)) }), n.stats.delivered += s.length, n.stats.lastDeliveryAtMs = u;
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
222
  return;
223
223
  }
224
- let f = l.left.message;
225
- for (let t of s) {
224
+ let m = d.failure.message;
225
+ for (let t of c) {
226
226
  let r = t.attempts + 1;
227
- if (r >= this.opts.maxAttempts) await e.update(C, t.id, {
227
+ if (r >= this.opts.maxAttempts) await e.update(w, t.id, {
228
228
  status: "dead",
229
229
  attempts: r,
230
230
  claimedBy: null,
231
231
  claimedAt: null,
232
- lastError: f
232
+ lastError: m
233
233
  }), n.stats.dead += 1;
234
234
  else {
235
235
  let n = L(r, {
@@ -237,13 +237,13 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
237
237
  maxMs: this.opts.backoffMaxMs,
238
238
  ...this.opts.random === void 0 ? {} : { random: this.opts.random }
239
239
  });
240
- await e.update(C, t.id, {
240
+ await e.update(w, t.id, {
241
241
  status: "pending",
242
242
  attempts: r,
243
- nextAttemptAt: new Date(u + n),
243
+ nextAttemptAt: new Date(f + n),
244
244
  claimedBy: null,
245
245
  claimedAt: null,
246
- lastError: f
246
+ lastError: m
247
247
  });
248
248
  }
249
249
  n.stats.failed += 1;
@@ -251,10 +251,10 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
251
251
  this.opts.warn?.("cdc-out delivery failed (durable retry scheduled)", {
252
252
  pipe: n.key,
253
253
  sink: n.sink.name,
254
- records: s.length,
255
- attempts: s[0] === void 0 ? 1 : s[0].attempts + 1,
254
+ records: c.length,
255
+ attempts: c[0] === void 0 ? 1 : c[0].attempts + 1,
256
256
  maxAttempts: this.opts.maxAttempts,
257
- reason: f
257
+ reason: m
258
258
  });
259
259
  }
260
260
  }, R = (e = "memory") => {
@@ -276,7 +276,7 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
276
276
  try {
277
277
  n = new URL(e).host;
278
278
  } catch {
279
- throw new x({ message: `webhookSink: invalid url '${e}'` });
279
+ throw new S({ message: `webhookSink: invalid url '${e}'` });
280
280
  }
281
281
  let r = `webhook(${n})`;
282
282
  return {
@@ -292,14 +292,14 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
292
292
  body: JSON.stringify({ records: n }),
293
293
  signal: i.signal
294
294
  });
295
- if (!a.ok) throw new S({
295
+ if (!a.ok) throw new C({
296
296
  sink: r,
297
297
  reason: `${a.status} ${a.statusText}`
298
298
  });
299
299
  }
300
300
  };
301
- }, oe = 100, se = 5, ce = 200, le = 3e4, ue = 250, de = 1e4, B = 15e3, fe = 72, pe = 6e4, me = 1e4, he = 1e3, V = (e) => {
302
- throw new x({ message: e });
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
303
  }, H = (e) => {
304
304
  (e.sinks === void 0 || e.sinks.length === 0) && V("cdcOutPlugin: at least one sink config is required");
305
305
  let t = /* @__PURE__ */ new Set();
@@ -342,7 +342,7 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
342
342
  data: t.map ? t.map(n) : n
343
343
  };
344
344
  }, W = (e, t) => `${e}:${t.table}:${t.sink.name}`, G = (e, t, n) => ({
345
- id: O(),
345
+ id: k(),
346
346
  pipe: t,
347
347
  sourceTable: e.table,
348
348
  op: e.op,
@@ -366,20 +366,20 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
366
366
  data: t.map ? t.map(e) : e
367
367
  }, i, a)];
368
368
  });
369
- return o.length > 0 && await e.insertMany(C, o), o.length;
370
- }, q = "@voltro/plugin-cdc-out", J = (i) => {
371
- H(i);
372
- let f = i.name ?? "default", p = o({
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
373
  base: q,
374
- alias: i.alias,
375
- instance: i.name
376
- }), h = `cdcout-${Math.random().toString(36).slice(2, 10)}`, te = i.maxAttempts ?? se, _ = i.sweepIntervalMs ?? ue, v = i.leaseTtlMs ?? B, y = i.dedupWindowMs ?? Math.max(pe, 4 * v), b = i.handoffBufferMs ?? y, x = i.handoffBufferSize ?? me, S = /* @__PURE__ */ new Map();
377
- for (let e of i.sinks) S.set(e.table, {
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
378
  config: e,
379
379
  enginePipe: {
380
- key: W(f, e),
380
+ key: W(a, e),
381
381
  sink: e.sink,
382
- batchSize: e.batchSize ?? oe,
382
+ batchSize: e.batchSize ?? se,
383
383
  busy: !1,
384
384
  stats: {
385
385
  delivered: 0,
@@ -389,121 +389,121 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
389
389
  }
390
390
  }
391
391
  });
392
- let w = new N({
393
- key: f,
392
+ let C = new ie({
393
+ key: a,
394
394
  holder: h,
395
395
  ttlMs: v
396
- }), E = new ae({
396
+ }), T = new oe({
397
397
  pipes: [...S.values()].map((e) => e.enginePipe),
398
398
  replicaId: h,
399
- maxAttempts: te,
400
- backoffBaseMs: i.backoffBaseMs ?? ce,
401
- backoffMaxMs: i.backoffMaxMs ?? le,
402
- deliveryTimeoutMs: i.deliveryTimeoutMs ?? de,
403
- isLeader: () => w.isLeader,
399
+ maxAttempts: ee,
400
+ backoffBaseMs: r.backoffBaseMs ?? le,
401
+ backoffMaxMs: r.backoffMaxMs ?? ue,
402
+ deliveryTimeoutMs: r.deliveryTimeoutMs ?? fe,
403
+ isLeader: () => C.isLeader,
404
404
  warn: (e, t) => O(e, t)
405
- }), D = { current: null }, O = () => void 0, M = 0, F, I, L = new s({
405
+ }), D = { current: null }, O = () => void 0, k = 0, P, F, I = new c({
406
406
  windowMs: 2 * y,
407
407
  maxEntries: Math.max(x, 1e3) * 4
408
- }), R = new P({
408
+ }), L = new ae({
409
409
  windowMs: b,
410
410
  maxEntries: x
411
- }), z = !1, V = 0, K = !1, J = null, Y = 0, ge = !1, _e = !1, X = [], Z = 0;
411
+ }), R = !1, z = 0, V = !1, K = null, J = 0, _e = !1, ve = !1, Y = [], X = 0;
412
412
  ne({
413
413
  source: "plugin",
414
- table: C,
414
+ table: w,
415
415
  timeColumn: "createdAt",
416
- ttlMs: i.retentionHours === void 0 ? re(process.env.CDCOUT_RETENTION_HOURS, fe) : i.retentionHours * 36e5,
417
- where: m("status", ["delivered", "dead"]),
416
+ ttlMs: r.retentionHours === void 0 ? re(process.env.CDCOUT_RETENTION_HOURS, pe) : r.retentionHours * 36e5,
417
+ where: g("status", ["delivered", "dead"]),
418
418
  label: "cdc-out outbox (delivered/dead)"
419
419
  }), ne({
420
420
  source: "plugin",
421
- table: T,
421
+ table: E,
422
422
  timeColumn: "seenAt",
423
423
  ttlMs: y,
424
424
  label: "cdc-out enqueue claims (dedup window)"
425
425
  });
426
- let ve = /* @__PURE__ */ new Set();
427
- for (let e of i.sinks) e.sink.outboundHost && ve.add(e.sink.outboundHost);
428
- let ye = [
426
+ let ye = /* @__PURE__ */ new Set();
427
+ for (let e of r.sinks) e.sink.outboundHost && ye.add(e.sink.outboundHost);
428
+ let be = [
429
429
  "store:changes:read",
430
430
  "store:write",
431
431
  "inspect:read",
432
432
  "inspect:write",
433
- ...[...ve].map((e) => `network:outbound:${e}`)
434
- ], be = [
433
+ ...[...ye].map((e) => `network:outbound:${e}`)
434
+ ], xe = [
435
435
  "pending",
436
436
  "delivering",
437
437
  "delivered",
438
438
  "dead"
439
- ], xe = async (e, t) => {
439
+ ], Se = async (e, t) => {
440
440
  let n = {
441
441
  pending: 0,
442
442
  delivering: 0,
443
443
  delivered: 0,
444
444
  dead: 0
445
445
  };
446
- return await Promise.all(be.map(async (r) => {
446
+ return await Promise.all(xe.map(async (r) => {
447
447
  let i = await e.query({
448
- table: C,
449
- predicate: c(d("pipe", t), d("status", r)),
448
+ table: w,
449
+ predicate: l(p("pipe", t), p("status", r)),
450
450
  order: [],
451
451
  take: void 0,
452
452
  skip: void 0,
453
453
  projection: void 0,
454
- aggregations: [u("n")]
454
+ aggregations: [f("n")]
455
455
  });
456
456
  n[r] = Number(i[0]?.n ?? 0);
457
457
  })), n;
458
- }, Se = (e) => {
458
+ }, Z = (e) => {
459
459
  let t = Date.now();
460
- t - M > 6e4 && (M = t, O("cdc-out: no DataStore bound — change events are NOT being mirrored", { table: e }));
461
- }, Ce = async (e, t, n) => (await e.insertIgnore(T, {
462
- id: ie(),
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(),
463
463
  pipe: t,
464
464
  changeKey: n,
465
465
  claimedBy: h,
466
466
  seenAt: /* @__PURE__ */ new Date()
467
467
  }, { conflictColumns: ["pipe", "changeKey"] })).claimedBy === h, Q = async () => {
468
- if (z) return;
468
+ if (R) return;
469
469
  let e = D.current;
470
470
  if (e !== null) {
471
- z = !0;
471
+ R = !0;
472
472
  try {
473
473
  for (;;) {
474
- let t = R.nextPending();
475
- if (t === void 0 || !w.isLeader) return;
476
- await Ce(e, t.pipe, t.changeKey) && await e.insert(C, G(t.change, t.pipe, Date.now())), t.enqueued = !0;
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;
477
477
  }
478
478
  } finally {
479
- z = !1;
479
+ R = !1;
480
480
  }
481
481
  }
482
482
  }, we = (e) => {
483
- if (ge = !0, !K) {
484
- for (X.push(e); X.length > x;) X.shift(), Z += 1;
483
+ if (_e = !0, !V) {
484
+ for (Y.push(e); Y.length > x;) Y.shift(), X += 1;
485
485
  return;
486
486
  }
487
- R.append({
487
+ L.append({
488
488
  pipe: e.pipe,
489
- changeKey: l(e.digest, L.next(e.digest, e.observedAtMs)),
489
+ changeKey: d(e.digest, I.next(e.digest, e.observedAtMs)),
490
490
  change: e.change,
491
491
  observedAtMs: e.observedAtMs,
492
492
  enqueued: !1
493
493
  });
494
494
  }, Te = (e, t) => {
495
- L.seedFromChangeKeys(e, t), K = !0;
496
- for (let e of X.splice(0, X.length)) we(e);
495
+ I.seedFromChangeKeys(e, t), V = !0;
496
+ for (let e of Y.splice(0, Y.length)) we(e);
497
497
  }, $ = async () => {
498
- if (K) return;
498
+ if (V) return;
499
499
  let e = D.current;
500
500
  if (e !== null) {
501
- if (J === null) {
502
- if (Y !== 0 && Date.now() - Y < he) return;
503
- let t = !ge;
504
- J = (async () => {
501
+ if (K === null) {
502
+ if (J !== 0 && Date.now() - J < ge) return;
503
+ let t = !_e;
504
+ K = (async () => {
505
505
  let n = await e.query({
506
- table: T,
506
+ table: E,
507
507
  predicate: void 0,
508
508
  order: [{
509
509
  column: "seenAt",
@@ -513,26 +513,26 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
513
513
  skip: void 0,
514
514
  projection: ["changeKey"]
515
515
  });
516
- !t && !_e && (_e = !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());
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());
517
517
  })().catch((e) => {
518
- Y = Date.now(), O("cdc-out: could not seed change-occurrence counters — enqueue is held until it lands", { reason: String(e) });
518
+ J = Date.now(), O("cdc-out: could not seed change-occurrence counters — enqueue is held until it lands", { reason: String(e) });
519
519
  }).finally(() => {
520
- J = null;
520
+ K = null;
521
521
  });
522
522
  }
523
- await J;
523
+ await K;
524
524
  }
525
525
  }, Ee = (e) => {
526
526
  let t = e - b;
527
- for (; X.length > 0 && X[0].observedAtMs < t;) X.shift(), Z += 1;
527
+ for (; Y.length > 0 && Y[0].observedAtMs < t;) Y.shift(), X += 1;
528
528
  }, De = async (e, t) => {
529
- t - V < Math.max(1e3, Math.floor(y / 4)) || (V = t, await e.deleteMany(T, { where: g("seenAt", new Date(t - y)) }));
529
+ t - z < Math.max(1e3, Math.floor(y / 4)) || (z = t, await e.deleteMany(E, { where: _("seenAt", new Date(t - y)) }));
530
530
  };
531
- return a({
532
- name: p,
531
+ return o({
532
+ name: m,
533
533
  baseName: q,
534
534
  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
- permissions: ye,
535
+ permissions: be,
536
536
  declaredEnv: [{
537
537
  name: "CDCOUT_RETENTION_HOURS",
538
538
  required: !1,
@@ -541,9 +541,9 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
541
541
  example: "72"
542
542
  }],
543
543
  extendSchema: { tables: [
544
- k,
545
544
  j,
546
- A
545
+ N,
546
+ M
547
547
  ] },
548
548
  bindDataStore: (e) => {
549
549
  D.current = e, $();
@@ -565,7 +565,7 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
565
565
  delivering: 0,
566
566
  delivered: 0,
567
567
  dead: 0
568
- } : await xe(e, n.key);
568
+ } : await Se(e, n.key);
569
569
  return {
570
570
  table: t.table,
571
571
  sink: t.sink.name,
@@ -576,12 +576,12 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
576
576
  };
577
577
  })),
578
578
  handoff: {
579
- leader: w.isLeader,
580
- seeded: K,
581
- awaitingSeed: X.length,
582
- buffered: R.size,
583
- pending: R.pendingCount(),
584
- dropped: R.droppedPending + Z,
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
585
  windowMs: b,
586
586
  dedupWindowMs: y
587
587
  }
@@ -602,8 +602,8 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
602
602
  } : {
603
603
  kind: "json",
604
604
  data: { rows: (await e.query({
605
- table: C,
606
- predicate: c(d("status", "dead"), m("pipe", [...S.values()].map((e) => e.enginePipe.key))),
605
+ table: w,
606
+ predicate: l(p("status", "dead"), g("pipe", [...S.values()].map((e) => e.enginePipe.key))),
607
607
  order: [{
608
608
  column: "id",
609
609
  direction: "desc"
@@ -651,13 +651,13 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
651
651
  data: { error: "Store unavailable." }
652
652
  } : {
653
653
  kind: "json",
654
- data: { accepted: await n.updateMany(C, {
654
+ data: { accepted: await n.updateMany(w, {
655
655
  status: "pending",
656
656
  attempts: 0,
657
657
  nextAttemptAt: /* @__PURE__ */ new Date(),
658
658
  claimedBy: null,
659
659
  claimedAt: null
660
- }, { where: c(d("id", t.deliveryKey), d("status", "dead"), m("pipe", [...S.values()].map((e) => e.enginePipe.key))) }) === 1 }
660
+ }, { where: l(p("id", t.deliveryKey), p("status", "dead"), g("pipe", [...S.values()].map((e) => e.enginePipe.key))) }) === 1 }
661
661
  };
662
662
  })
663
663
  }
@@ -668,7 +668,7 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
668
668
  let r = U(e, n.config);
669
669
  if (r === null) return t.void;
670
670
  if (e.changeScope === "fleet") {
671
- let i = Date.now(), a = ee({
671
+ let i = Date.now(), a = u({
672
672
  pipe: n.enginePipe.key,
673
673
  op: r.op,
674
674
  key: r.key,
@@ -680,44 +680,44 @@ var x = class extends i.TaggedError()("CdcConfigError", { message: i.String }) {
680
680
  digest: a,
681
681
  change: r,
682
682
  observedAtMs: i
683
- }), D.current === null ? (Se(e.table), t.void) : t.promise(() => $()).pipe(t.flatMap(() => w.isLeader ? t.tryPromise(() => Q()) : t.void));
683
+ }), D.current === null ? (Z(e.table), t.void) : t.promise(() => $()).pipe(t.flatMap(() => C.isLeader ? t.tryPromise(() => Q()) : t.void));
684
684
  }
685
685
  if (e.origin === "injected") return t.void;
686
686
  let i = D.current;
687
- if (i === null) return Se(e.table), t.void;
687
+ if (i === null) return Z(e.table), t.void;
688
688
  let a = G(r, n.enginePipe.key, Date.now());
689
- return t.tryPromise(() => i.insert(C, a).then(() => void 0));
689
+ return t.tryPromise(() => i.insert(w, a).then(() => void 0));
690
690
  },
691
691
  onActivate: (n) => t.sync(() => {
692
692
  O = (e, t) => n.logger.warn(e, t);
693
- let i = t.suspend(() => {
693
+ let r = t.suspend(() => {
694
694
  let e = D.current;
695
695
  return e === null ? t.void : t.promise(async () => {
696
696
  await $();
697
- let t = w.isLeader;
698
- await w.heartbeat(e) && !t && await Q().catch((e) => {
697
+ let t = C.isLeader;
698
+ await C.heartbeat(e) && !t && await Q().catch((e) => {
699
699
  O("cdc-out: handoff drain failed (retried on the next sweep)", { reason: String(e) });
700
700
  });
701
701
  });
702
- }).pipe(t.repeat(r.spaced(e.millis(Math.max(1, Math.floor(v / 3)))))), a = t.suspend(() => {
702
+ }).pipe(t.repeat(i.spaced(e.millis(Math.max(1, Math.floor(v / 3)))))), a = t.suspend(() => {
703
703
  let e = D.current;
704
704
  return e === null ? t.void : t.tryPromise(async () => {
705
705
  let t = Date.now();
706
- await $(), Ee(t), R.prune(t), L.prune(t), await De(e, t), w.isLeader && await Q(), await E.tick(e);
707
- }).pipe(t.catchAll((e) => t.sync(() => O("cdc-out worker sweep failed", { reason: String(e) }))));
708
- }).pipe(t.repeat(r.spaced(e.millis(_))));
709
- I = t.runFork(i), F = t.runFork(a), n.logger.info("cdc-out active", {
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
710
  tables: [...S.keys()],
711
711
  replicaId: h,
712
- outbox: C
712
+ outbox: w
713
713
  });
714
714
  }),
715
715
  onDeactivate: () => t.gen(function* () {
716
- F !== void 0 && (yield* n.interrupt(F)), I !== void 0 && (yield* n.interrupt(I)), F = void 0, I = void 0;
716
+ P !== void 0 && (yield* n.interrupt(P)), F !== void 0 && (yield* n.interrupt(F)), P = void 0, F = void 0;
717
717
  let e = D.current;
718
- e !== null && (yield* t.promise(() => w.release(e)));
718
+ e !== null && (yield* t.promise(() => C.release(e)));
719
719
  })
720
720
  });
721
721
  };
722
722
  //#endregion
723
- export { T as CDCOUT_CLAIMS_TABLE, w as CDCOUT_LEASES_TABLE, C as CDCOUT_OUTBOX_TABLE, x as CdcConfigError, S as CdcDeliveryError, N as CdcLeaseManager, ae as CdcOutEngine, P as HandoffBuffer, A as cdcOutClaimsTable, j as cdcOutLeasesTable, k as cdcOutOutboxTable, J as cdcOutPlugin, F as deliverOnce, K as enqueueBackfill, U as mapChange, R as memorySink, ie as nextClaimId, O as nextOutboxId, G as outboxRowFor, W as pipeKey, L as retryDelayMs, H as validateCdcOutConfig, z as webhookSink };
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 };