notifkit 0.1.17 → 0.1.19

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.
Files changed (59) hide show
  1. package/README.md +5 -5
  2. package/dist/{bootstrap-P63acBG9.mjs → bootstrap-CHOj1rDv.mjs} +1 -1
  3. package/dist/{bulk-Beblt3ny.mjs → bulk-CAsYwF-9.mjs} +1 -1
  4. package/dist/index.d.mts +29 -111
  5. package/dist/index.mjs +2 -2
  6. package/dist/{main-Dk92nti8.mjs → main-B88bnGHO.mjs} +5 -12
  7. package/dist/{main-BIahf4f9.mjs → main-BDTDp4Bg.mjs} +35 -16
  8. package/dist/{main-C3XcLoCb.mjs → main-C9ekO6RS.mjs} +3 -3
  9. package/dist/{main-_I4b1cmP.mjs → main-CBeKd8wJ.mjs} +3 -3
  10. package/dist/{main-NHUvynW2.mjs → main-CVTZoGzA.mjs} +4 -9
  11. package/dist/{main-CktEylpL.mjs → main-CYxNbgX5.mjs} +23 -94
  12. package/dist/{main-DB0bUh2r.mjs → main-CcGiccDe.mjs} +5 -14
  13. package/dist/{main-Lcbg7aEn.mjs → main-DGF3WtFw.mjs} +8 -58
  14. package/dist/{schedule-or-dispatch-C5qfxQCv.mjs → schedule-or-dispatch-BF85qhMh.mjs} +1 -1
  15. package/dist/{src-BRatuWJS.mjs → src-aiRAj2xr.mjs} +72 -175
  16. package/drizzle/0009_retention_time_indexes.sql +4 -0
  17. package/drizzle/meta/_journal.json +7 -0
  18. package/package.json +1 -1
  19. package/src/client.ts +6 -6
  20. package/src/config/index.ts +8 -10
  21. package/src/contracts/sdk.ts +26 -11
  22. package/src/db/bulk.ts +3 -10
  23. package/src/db/schema.ts +3 -0
  24. package/src/idempotency/index.ts +12 -53
  25. package/src/queue/index.ts +1 -12
  26. package/src/rate-limiter/api-rate-limiter.ts +8 -27
  27. package/src/rate-limiter/project-settings-cache.ts +4 -16
  28. package/src/redis/index.ts +3 -51
  29. package/src/repositories/contact.ts +0 -2
  30. package/src/server.ts +1 -4
  31. package/src/services/api/handlers/auth.ts +3 -11
  32. package/src/services/api/handlers/campaigns.ts +4 -15
  33. package/src/services/api/handlers/events.ts +1 -2
  34. package/src/services/api/handlers/notifications.ts +6 -16
  35. package/src/services/api/handlers/projects.ts +1 -3
  36. package/src/services/api/handlers/shared.ts +7 -29
  37. package/src/services/api/handlers/system.ts +1 -1
  38. package/src/services/api/handlers/unsubscribe.ts +7 -30
  39. package/src/services/api/handlers/users.ts +1 -2
  40. package/src/services/api/http.ts +5 -10
  41. package/src/services/api/main.ts +27 -63
  42. package/src/services/api/webhooks.ts +8 -19
  43. package/src/services/auth/index.ts +2 -21
  44. package/src/services/delivery/main.ts +25 -89
  45. package/src/services/engine/main.ts +33 -69
  46. package/src/services/engine/schedule-or-dispatch.ts +7 -4
  47. package/src/services/enricher/main.ts +19 -49
  48. package/src/services/events/main.ts +3 -12
  49. package/src/services/scheduler/main.ts +26 -32
  50. package/src/services/scheduler/retention.ts +47 -0
  51. package/src/services/scheduler/send-gate.ts +6 -17
  52. package/src/services/workflow/duration.ts +1 -6
  53. package/src/services/workflow/main.ts +3 -9
  54. package/src/services/workflow/timers.ts +2 -1
  55. package/src/shared/batch-processor.ts +3 -7
  56. package/src/shared/utils.ts +2 -8
  57. package/src/transport/index.ts +0 -4
  58. package/src/unsubscribe/index.ts +3 -11
  59. package/src/workers/index.ts +8 -27
@@ -66,14 +66,8 @@ function getPriorityBucket(priority) {
66
66
  return p === "critical" ? "critical" : p === "low" ? "low" : "normal";
67
67
  }
68
68
  /**
69
- * Canonical form of a destination, for suppression lookups.
70
- *
71
- * Both the writer (the provider webhook) and the reader (the engine's
72
- * pre-dispatch gate) must agree on this, or an unsubscribe recorded as
73
- * `Bob@Example.com` will not match a send addressed to `bob@example.com` and
74
- * the person keeps receiving mail. Case folding is safe for email domains and
75
- * for the local part in every mailbox provider in practice; phone numbers and
76
- * push tokens are case-sensitive and are only trimmed.
69
+ * Canonical address for suppression lookups; writers and readers must both use
70
+ * it. Emails are lower-cased; phone numbers and push tokens are case-sensitive.
77
71
  */
78
72
  function normaliseTarget(target) {
79
73
  const trimmed = target.trim();
@@ -108,13 +102,9 @@ var AsyncSemaphore = class {
108
102
  //#endregion
109
103
  //#region src/shared/batch-processor.ts
110
104
  /**
111
- * Coalesces individual `add()` calls into batched `flushFn` calls.
112
- *
113
- * A batch goes out when `maxSize` items are waiting or `maxWaitMs` has passed
114
- * since the first one arrived. Up to `maxConcurrent` flushes may be in flight
115
- * at once: with a single flight, every caller queued behind a slow flush holds
116
- * its worker slot for the whole round trip, which caps a worker's throughput at
117
- * `maxSize / flushLatency` no matter how much concurrency it was given.
105
+ * Batches `add()` calls into `flushFn` calls, at `maxSize` items or after
106
+ * `maxWaitMs`. Several flushes may run at once so one slow flush doesn't cap
107
+ * the worker's throughput.
118
108
  */
119
109
  var BatchProcessor = class {
120
110
  maxSize;
@@ -364,14 +354,13 @@ const baseConfigSchema = z.object({
364
354
  PIPELINE_FUSED: z.string().optional().transform((v) => v === "true" || v === "1"),
365
355
  QUEUE_MAX_LEN: z.coerce.number().int().min(1).default(1e5),
366
356
  /**
367
- * How long the pipeline remembers it handled a message, so a redelivery
368
- * after a crash is not sent twice. It only has to outlast redelivery (about
369
- * ten minutes) plus however far behind the streams run; a caller's own
370
- * X-Idempotency-Key is always kept for 24 hours regardless. These markers
371
- * are most of Redis memory under load, so the cost of a longer window is
372
- * real: a few hundred bytes per message for as long as it lasts.
357
+ * How long the pipeline remembers a handled message, so a redelivery isn't
358
+ * sent twice. Must outlast redelivery plus stream lag. These markers are most
359
+ * of Redis memory under load. A caller's X-Idempotency-Key always keeps 24h.
373
360
  */
374
361
  IDEMPOTENCY_TTL_SECONDS: z.coerce.number().int().min(60).default(3600),
362
+ /** Non-critical sends per user per hour, unless the project overrides it. */
363
+ RATE_LIMIT_PER_HOUR: z.coerce.number().int().min(0).default(100),
375
364
  DB_MAX_CONNECTIONS: z.coerce.number().int().min(1).default(2),
376
365
  /**
377
366
  * PostgreSQL schema that holds notifkit's tables and enum types. Defaults to
@@ -381,6 +370,8 @@ const baseConfigSchema = z.object({
381
370
  */
382
371
  DB_SCHEMA: z.string().trim().regex(/^[a-z_][a-z0-9_]{0,62}$/, "must be a lowercase PostgreSQL identifier").default("public"),
383
372
  LOG_FLUSH_INTERVAL_MS: z.coerce.number().int().min(50).default(500),
373
+ /** Days of delivery logs to keep; the scheduler deletes older rows hourly. Unset keeps them forever. */
374
+ LOG_RETENTION_DAYS: z.coerce.number().int().min(1).optional(),
384
375
  LOG_BUFFER_MAX_SIZE: z.coerce.number().int().min(100).default(5e3),
385
376
  SEGMENT_MAX_USERS: z.coerce.number().int().min(1).default(1e5),
386
377
  /**
@@ -610,6 +601,15 @@ const PreferencesSchema = z.object({
610
601
  topics: z.record(z.string(), z.boolean()).optional(),
611
602
  quietHours: z.array(QuietHoursSchema).optional()
612
603
  });
604
+ const TimezoneSchema = z.string().refine((tz) => {
605
+ if (tz !== "UTC" && !tz.includes("/")) return false;
606
+ try {
607
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
608
+ return true;
609
+ } catch {
610
+ return false;
611
+ }
612
+ }, { message: "expected an IANA timezone, e.g. America/New_York" });
613
613
  /** Channels that carry an addressable target (email address, phone, push token, url, chat id). */
614
614
  const ContactChannelSchema = NotificationChannelSchema;
615
615
  /** Accept a single value or an array; always normalise to a non-empty array. */
@@ -630,7 +630,7 @@ const UserContactInputSchema = z.object({
630
630
  const AddUserSchema = z.object({
631
631
  id: z.string().min(1),
632
632
  language: z.string().optional(),
633
- timezone: z.string().optional(),
633
+ timezone: TimezoneSchema.optional(),
634
634
  contacts: z.array(UserContactInputSchema).optional(),
635
635
  email: stringOrArray.optional(),
636
636
  phone: stringOrArray.optional(),
@@ -641,7 +641,7 @@ const AddUserSchema = z.object({
641
641
  /** updateUser(id, patch) — every field optional; id comes from the path. */
642
642
  const UpdateUserSchema = z.object({
643
643
  language: z.string().optional(),
644
- timezone: z.string().optional(),
644
+ timezone: TimezoneSchema.optional(),
645
645
  contacts: z.array(UserContactInputSchema).optional(),
646
646
  email: stringOrArray.optional(),
647
647
  phone: stringOrArray.optional(),
@@ -1168,6 +1168,7 @@ const messageLogs = pgTable("message_logs", {
1168
1168
  projectIdTaskIdIdx: index("message_logs_project_task_idx").on(table.projectId, table.taskId),
1169
1169
  providerMsgIdx: index("provider_msg_idx").on(table.providerMessageId),
1170
1170
  projectTimeIdx: index("msg_log_proj_time_idx").on(table.projectId, table.timestamp),
1171
+ timeIdx: index("msg_log_time_idx").on(table.timestamp),
1171
1172
  templateIdx: index("msg_log_template_idx").on(table.projectId, table.templateId),
1172
1173
  workflowIdx: index("msg_log_workflow_idx").on(table.projectId, table.workflowInstanceId),
1173
1174
  campaignIdx: index("msg_log_campaign_idx").on(table.projectId, table.campaignId),
@@ -1259,7 +1260,8 @@ const deliveryOutbox = pgTable("delivery_outbox", {
1259
1260
  table.channel,
1260
1261
  table.destination
1261
1262
  ] }),
1262
- destinationIdx: index("delivery_outbox_destination_idx").on(table.destination)
1263
+ destinationIdx: index("delivery_outbox_destination_idx").on(table.destination),
1264
+ createdIdx: index("delivery_outbox_created_idx").on(table.createdAt)
1263
1265
  }));
1264
1266
  const scheduledPayloads = pgTable("scheduled_payloads", {
1265
1267
  taskId: varchar("task_id").primaryKey(),
@@ -1421,10 +1423,7 @@ async function migrateDatabase({ url, schema: dbSchema }) {
1421
1423
  }
1422
1424
  //#endregion
1423
1425
  //#region src/idempotency/index.ts
1424
- /**
1425
- * SET NX-based idempotency guard.
1426
- * One key per id: `L` while leased, `1` once processed.
1427
- */
1426
+ /** One Redis key per id: `L` while a worker holds it, `1` once processed. */
1428
1427
  var IdempotencyGuard = class {
1429
1428
  redis;
1430
1429
  keyPrefix;
@@ -1437,38 +1436,20 @@ var IdempotencyGuard = class {
1437
1436
  key(id) {
1438
1437
  return `${this.keyPrefix}:${id}`;
1439
1438
  }
1440
- /** @deprecated Nothing writes `:lock` keys any more; read only for markers from older versions. Remove in the next minor. */
1441
- lockKey(id) {
1442
- return `${this.keyPrefix}:${id}:lock`;
1443
- }
1444
- /** @deprecated Nothing writes `:sent` keys any more; read only for markers from older versions. Remove in the next minor. */
1445
- completedKey(id) {
1446
- return `${this.keyPrefix}:${id}:sent`;
1447
- }
1448
- /**
1449
- * Leases the id with SET NX. One key per id: `L` while leased, `1` once processed.
1450
- * Returns "completed" if already processed, "locked" if another worker holds the lease.
1451
- */
1452
1439
  async acquireLease(id, lockTtlSeconds = 30) {
1453
- const mainKey = this.key(id);
1454
- const lockKey = this.lockKey(id);
1455
- if (await this.redis.set(mainKey, "L", "EX", lockTtlSeconds, "NX") === "OK") return "acquired";
1456
- const [val, sent, lockVal] = await Promise.all([
1457
- this.redis.get(mainKey),
1458
- this.redis.get(this.completedKey(id)),
1459
- this.redis.get(lockKey)
1460
- ]);
1461
- if (val === "S" || val === "1" || sent !== null) return "completed";
1462
- if (val === "L" || lockVal !== null) return "locked";
1463
- if (await this.redis.set(mainKey, "L", "EX", lockTtlSeconds, "NX") === "OK") return "acquired";
1464
- return "locked";
1465
- }
1466
- /** Atomically mark id as processed. Returns true on first call; false if already seen. */
1440
+ const key = this.key(id);
1441
+ if (await this.redis.set(key, "L", "EX", lockTtlSeconds, "NX") === "OK") return "acquired";
1442
+ const val = await this.redis.get(key);
1443
+ if (val === "1") return "completed";
1444
+ if (val === "L") return "locked";
1445
+ return await this.redis.set(key, "L", "EX", lockTtlSeconds, "NX") === "OK" ? "acquired" : "locked";
1446
+ }
1447
+ /** Marks the id processed. Returns false if it was already seen. */
1467
1448
  async checkAndMark(id, customTtlSeconds) {
1468
1449
  const ttl = customTtlSeconds ?? this.ttlSeconds;
1469
1450
  return await this.redis.set(this.key(id), "1", "EX", ttl, "NX") === "OK";
1470
1451
  }
1471
- /** Unconditionally mark id as processed (upgrades lock to completed "1" with full TTL). */
1452
+ /** Marks the id processed, replacing a lease with the full TTL. */
1472
1453
  async markProcessed(id, customTtlSeconds) {
1473
1454
  const ttl = customTtlSeconds ?? this.ttlSeconds;
1474
1455
  await this.redis.set(this.key(id), "1", "EX", ttl);
@@ -1477,13 +1458,8 @@ var IdempotencyGuard = class {
1477
1458
  const val = await this.redis.get(this.key(id));
1478
1459
  return val !== null && val !== void 0;
1479
1460
  }
1480
- /** Remove the idempotency marker (useful in tests or manual rollbacks). */
1481
1461
  async unmark(id) {
1482
- await Promise.all([
1483
- this.redis.del(this.key(id)),
1484
- this.redis.del(this.lockKey(id)),
1485
- this.redis.del(this.completedKey(id))
1486
- ]);
1462
+ await this.redis.del(this.key(id));
1487
1463
  }
1488
1464
  };
1489
1465
  //#endregion
@@ -2015,26 +1991,14 @@ const NO_OVERRIDES = {
2015
1991
  throttleWindowHours: null
2016
1992
  };
2017
1993
  /**
2018
- * Caches per-project throttle overrides for the engine.
2019
- *
2020
- * The throttle check runs once per notification, so an uncached lookup here
2021
- * would put a Postgres round trip on the hot path. Projects with no overrides
2022
- * are cached as well — the common case must not cost a query per message.
2023
- *
2024
- * The TTL bounds staleness on its own; `invalidate()` exists so a settings
2025
- * change published over pub/sub applies immediately rather than at expiry.
1994
+ * Per-project throttle overrides, read once per notification. Projects with no
1995
+ * overrides are cached too. `invalidate()` lets a settings change apply before
1996
+ * the TTL runs out.
2026
1997
  */
2027
1998
  var ProjectSettingsCache = class {
2028
1999
  load;
2029
2000
  cache;
2030
- /**
2031
- * Lookups already on the wire, keyed by project.
2032
- *
2033
- * The cache only fills once a query has come back, so without this a cold
2034
- * project at the start of a campaign puts one query per in-flight message on
2035
- * Postgres before the first answer lands — exactly when the database is
2036
- * busiest. Followers wait on the leader's promise instead.
2037
- */
2001
+ /** Lookups in flight, so a cold project at the start of a campaign costs one query. */
2038
2002
  inFlight = /* @__PURE__ */ new Map();
2039
2003
  constructor(load, { maxSize = 1e3, ttlMs = 6e4 } = {}) {
2040
2004
  this.load = load;
@@ -2120,11 +2084,7 @@ var UserThrottle = class {
2120
2084
  };
2121
2085
  //#endregion
2122
2086
  //#region src/rate-limiter/api-rate-limiter.ts
2123
- /**
2124
- * Computes dynamic token lease batch size based on RPM.
2125
- * Targets ~5s of limit capacity so Redis is contacted at most ~12 times/min
2126
- * regardless of instantaneous request rate. Bounded between 1 and maxBatchSize.
2127
- */
2087
+ /** About five seconds' worth of the limit, so Redis is asked ~12 times a minute. */
2128
2088
  function calculateTokenBatchSize(limitRpm, maxBatchSize = 500) {
2129
2089
  if (limitRpm <= 0) return 0;
2130
2090
  if (limitRpm <= 10) return 1;
@@ -2146,11 +2106,6 @@ var ApiRateLimiter = class {
2146
2106
  this.logger = logger;
2147
2107
  this.keyPrefix = keyPrefix;
2148
2108
  }
2149
- /**
2150
- * Evaluates if a request for `projectId` is allowed within its `limitRpm`.
2151
- * Fast-path uses local in-memory token lease (0ms Redis network latency).
2152
- * Refills in the background before tokens are depleted.
2153
- */
2154
2109
  async check(projectId, limitRpm) {
2155
2110
  if (limitRpm <= 0) return false;
2156
2111
  const nowMs = Date.now();
@@ -2225,11 +2180,9 @@ var ApiRateLimiter = class {
2225
2180
  for (const [id, s] of this.leases) if (currentBucket - s.bucketIndex > 1) this.leases.delete(id);
2226
2181
  }
2227
2182
  }
2228
- /** Reset all local cached leases */
2229
2183
  clear() {
2230
2184
  this.leases.clear();
2231
2185
  }
2232
- /** Invalidate local lease for a specific project */
2233
2186
  invalidate(projectId) {
2234
2187
  this.leases.delete(projectId);
2235
2188
  }
@@ -2359,33 +2312,6 @@ const LUA_COUNT_REQUEST = `
2359
2312
  return count
2360
2313
  `;
2361
2314
  /**
2362
- * Two-phase idempotency lease acquisition. Checks sent/legacy, then attempts SET NX lock.
2363
- * @deprecated Nothing calls the `acquireLease` command; removed in the next minor version.
2364
- */
2365
- const LUA_ACQUIRE_LEASE = `
2366
- if redis.call('EXISTS', KEYS[1]) == 1 or redis.call('EXISTS', KEYS[3]) == 1 then
2367
- return 'completed'
2368
- end
2369
- local lockAcquired = redis.call('SET', KEYS[2], '1', 'EX', ARGV[1], 'NX')
2370
- if lockAcquired then
2371
- return 'acquired'
2372
- end
2373
- if redis.call('EXISTS', KEYS[1]) == 1 or redis.call('EXISTS', KEYS[3]) == 1 then
2374
- return 'completed'
2375
- end
2376
- return 'locked'
2377
- `;
2378
- /**
2379
- * Two-phase idempotency completion marker. Atomically sets completed + legacy and deletes lock.
2380
- * @deprecated Nothing calls the `markProcessed` command; removed in the next minor version.
2381
- */
2382
- const LUA_MARK_PROCESSED = `
2383
- redis.call('SET', KEYS[1], '1', 'EX', ARGV[1])
2384
- redis.call('SET', KEYS[2], '1', 'EX', ARGV[1])
2385
- redis.call('DEL', KEYS[3])
2386
- return 1
2387
- `;
2388
- /**
2389
2315
  * Registers pre-compiled custom commands on an ioredis instance.
2390
2316
  * Calls defineCommand so ioredis uses EVALSHA rather than re-transmitting
2391
2317
  * full script strings over the wire.
@@ -2411,34 +2337,18 @@ function registerCustomCommands(redis) {
2411
2337
  numberOfKeys: 1,
2412
2338
  lua: LUA_SCHEDULER_POLL
2413
2339
  });
2414
- redis.defineCommand("acquireLease", {
2415
- numberOfKeys: 3,
2416
- lua: LUA_ACQUIRE_LEASE
2417
- });
2418
2340
  redis.defineCommand("countRequest", {
2419
2341
  numberOfKeys: 1,
2420
2342
  lua: LUA_COUNT_REQUEST
2421
2343
  });
2422
- redis.defineCommand("markProcessed", {
2423
- numberOfKeys: 3,
2424
- lua: LUA_MARK_PROCESSED
2425
- });
2426
2344
  }
2427
2345
  const sharedClients = /* @__PURE__ */ new Map();
2428
2346
  var RedisClient = class RedisClient {
2429
2347
  native;
2430
2348
  /**
2431
- * One command connection per Redis URL for every service in this process.
2432
- *
2433
- * Each service used to open its own, so a single notification's commands
2434
- * reached Redis over three or four sockets, one round trip each. Sharing a
2435
- * connection lets auto-pipelining merge whatever the services issue in the
2436
- * same tick into one write, and Redis spends most of its time per round trip
2437
- * rather than per command. Blocking reads and subscribers still duplicate
2438
- * their own connections.
2439
- *
2440
- * The handle's `disconnect()` releases this caller's reference; the
2441
- * connection closes when the last service lets go.
2349
+ * One command connection per URL for every service in the process, so
2350
+ * auto-pipelining can batch what they send in the same tick. `disconnect()`
2351
+ * drops this caller's reference; the last one closes the connection.
2442
2352
  */
2443
2353
  static shared(options) {
2444
2354
  let entry = sharedClients.get(options.url);
@@ -3625,15 +3535,9 @@ var BaseWorker = class {
3625
3535
  };
3626
3536
  }
3627
3537
  /**
3628
- * Processes an event produced by an upstream stage in this same process,
3629
- * skipping the stream hop in between.
3630
- *
3631
- * The caller is still holding its own stream entry, and does not ack it until
3632
- * this returns. A thrown error therefore leaves that entry pending and the
3633
- * whole chain is replayed from the upstream stage; the idempotency keys each
3634
- * stage already checks make the replay safe. Non-retryable failures go to the
3635
- * dead-letter stream here, as they would have from this worker's own stream,
3636
- * so they do not send the upstream message there instead.
3538
+ * Processes an event from an upstream stage in this process, skipping the stream.
3539
+ * A throw leaves the caller's entry pending, so the chain replays from upstream.
3540
+ * Non-retryable failures are dead-lettered here so the upstream message isn't.
3637
3541
  */
3638
3542
  async processInline(event) {
3639
3543
  try {
@@ -3735,11 +3639,8 @@ var BaseWorker = class {
3735
3639
  }
3736
3640
  }
3737
3641
  /**
3738
- * Runs `process` while keeping the entry's idle time below the reclaim
3739
- * threshold. Without this, a handler that outlasts `recoveryIntervalMs` (a
3740
- * large segment fan-out) is reclaimed mid-run and started again elsewhere,
3741
- * over and over, until it is dead-lettered while the first run still works.
3742
- * If this process dies the touches stop, so the entry is reclaimed as before.
3642
+ * Keeps the entry's idle time under the reclaim threshold while `process` runs,
3643
+ * so a long fan-out isn't reclaimed mid-run. If this process dies, the touches stop.
3743
3644
  */
3744
3645
  async processHoldingLease(message, attempt) {
3745
3646
  const stream = message.stream;
@@ -3758,12 +3659,8 @@ var BaseWorker = class {
3758
3659
  }
3759
3660
  }
3760
3661
  /**
3761
- * `recoveryIntervalMs` is how long an entry must sit idle before it is
3762
- * claimed, not how often to look. Scanning only once per interval, timed from
3763
- * this worker's start, meant a worker restarted more often than that (a crash
3764
- * loop, an eager autoscaler) never scanned at all, and whatever its
3765
- * predecessors held stayed pending for good. So scan on start and then
3766
- * several times per interval; the idle threshold alone decides what is taken.
3662
+ * `recoveryIntervalMs` is the idle time before a claim, not the scan period.
3663
+ * Scan on start and several times per interval so crash-looping workers still recover.
3767
3664
  */
3768
3665
  startRecoveryLoop() {
3769
3666
  const scan = () => {
@@ -4224,35 +4121,35 @@ var NotifkitServer = class extends EventEmitter {
4224
4121
  }
4225
4122
  const startupPromises = [];
4226
4123
  if (services.includes("api")) {
4227
- const { startApiServer } = await import("./main-CktEylpL.mjs");
4124
+ const { startApiServer } = await import("./main-CYxNbgX5.mjs");
4228
4125
  startupPromises.push(startApiServer());
4229
4126
  }
4230
4127
  if (services.includes("delivery")) {
4231
- const { startDeliveryWorker } = await import("./main-Lcbg7aEn.mjs");
4128
+ const { startDeliveryWorker } = await import("./main-DGF3WtFw.mjs");
4232
4129
  startupPromises.push(startDeliveryWorker());
4233
4130
  }
4234
4131
  if (services.includes("engine")) {
4235
- const { startEngineWorker } = await import("./main-DB0bUh2r.mjs");
4132
+ const { startEngineWorker } = await import("./main-CcGiccDe.mjs");
4236
4133
  startupPromises.push(startEngineWorker());
4237
4134
  }
4238
4135
  if (services.includes("enricher")) {
4239
- const { startEnricherWorker } = await import("./main-Dk92nti8.mjs");
4136
+ const { startEnricherWorker } = await import("./main-B88bnGHO.mjs");
4240
4137
  startupPromises.push(startEnricherWorker());
4241
4138
  }
4242
4139
  if (services.includes("scheduler")) {
4243
- const { startSchedulerWorker } = await import("./main-BIahf4f9.mjs");
4140
+ const { startSchedulerWorker } = await import("./main-BDTDp4Bg.mjs");
4244
4141
  startupPromises.push(startSchedulerWorker());
4245
4142
  }
4246
4143
  if (services.includes("ai")) {
4247
- const { startAiWorker } = await import("./main-C3XcLoCb.mjs");
4144
+ const { startAiWorker } = await import("./main-C9ekO6RS.mjs");
4248
4145
  startupPromises.push(startAiWorker());
4249
4146
  }
4250
4147
  if (services.includes("workflow")) {
4251
- const { startWorkflowWorker } = await import("./main-NHUvynW2.mjs");
4148
+ const { startWorkflowWorker } = await import("./main-CVTZoGzA.mjs");
4252
4149
  startupPromises.push(startWorkflowWorker());
4253
4150
  }
4254
4151
  if (services.includes("events")) {
4255
- const { startEventWorker } = await import("./main-_I4b1cmP.mjs");
4152
+ const { startEventWorker } = await import("./main-CBeKd8wJ.mjs");
4256
4153
  startupPromises.push(startEventWorker());
4257
4154
  }
4258
4155
  const handleSignal = async (signal) => {
@@ -4274,9 +4171,9 @@ var NotifkitServer = class extends EventEmitter {
4274
4171
  await Promise.all(startupPromises);
4275
4172
  if (readBaseConfig().PIPELINE_FUSED && services.includes("enricher") && services.includes("engine") && services.includes("delivery")) {
4276
4173
  const [{ getEnricherWorker }, { getEngineWorker }, { getDeliveryWorker }] = await Promise.all([
4277
- import("./main-Dk92nti8.mjs"),
4278
- import("./main-DB0bUh2r.mjs"),
4279
- import("./main-Lcbg7aEn.mjs")
4174
+ import("./main-B88bnGHO.mjs"),
4175
+ import("./main-CcGiccDe.mjs"),
4176
+ import("./main-DGF3WtFw.mjs")
4280
4177
  ]);
4281
4178
  const enricher = getEnricherWorker();
4282
4179
  const engine = getEngineWorker();
@@ -4307,14 +4204,14 @@ var NotifkitServer = class extends EventEmitter {
4307
4204
  "events"
4308
4205
  ] : this.options.services;
4309
4206
  const shutdownOrder = [
4310
- ["api", async () => (await import("./main-CktEylpL.mjs")).stopApiServer()],
4311
- ["workflow", async () => (await import("./main-NHUvynW2.mjs")).stopWorkflowWorker()],
4312
- ["enricher", async () => (await import("./main-Dk92nti8.mjs")).stopEnricherWorker()],
4313
- ["ai", async () => (await import("./main-C3XcLoCb.mjs")).stopAiWorker()],
4314
- ["engine", async () => (await import("./main-DB0bUh2r.mjs")).stopEngineWorker()],
4315
- ["scheduler", async () => (await import("./main-BIahf4f9.mjs")).stopSchedulerWorker()],
4316
- ["delivery", async () => (await import("./main-Lcbg7aEn.mjs")).stopDeliveryWorker()],
4317
- ["events", async () => (await import("./main-_I4b1cmP.mjs")).stopEventWorker()]
4207
+ ["api", async () => (await import("./main-CYxNbgX5.mjs")).stopApiServer()],
4208
+ ["workflow", async () => (await import("./main-CVTZoGzA.mjs")).stopWorkflowWorker()],
4209
+ ["enricher", async () => (await import("./main-B88bnGHO.mjs")).stopEnricherWorker()],
4210
+ ["ai", async () => (await import("./main-C9ekO6RS.mjs")).stopAiWorker()],
4211
+ ["engine", async () => (await import("./main-CcGiccDe.mjs")).stopEngineWorker()],
4212
+ ["scheduler", async () => (await import("./main-BDTDp4Bg.mjs")).stopSchedulerWorker()],
4213
+ ["delivery", async () => (await import("./main-DGF3WtFw.mjs")).stopDeliveryWorker()],
4214
+ ["events", async () => (await import("./main-CBeKd8wJ.mjs")).stopEventWorker()]
4318
4215
  ];
4319
4216
  for (const [name, stop] of shutdownOrder) if (services.includes(name)) await stop();
4320
4217
  if (this.pgContainer) {
@@ -4328,4 +4225,4 @@ var NotifkitServer = class extends EventEmitter {
4328
4225
  }
4329
4226
  };
4330
4227
  //#endregion
4331
- export { assertTablesInSchema as $, OUTBOUND_STREAMS as $t, LUA_ACQUIRE_LEASE as A, globalEmitter as An, NotificationTargetSchema as At, redactUrl as B, QuietHoursSchema as Bt, SegmentRepository as C, DataLoader as Cn, NotificationDispatchedPayloadSchema as Ct, ContactRepository as D, getPriorityBucket as Dn, RecipientProfileSchema as Dt, TemplateRepository as E, AsyncSemaphore as En, NotificationEnrichedPayloadSchema as Et, LUA_RENEW_LOCK as F, CreateWorkflowSchema as Ft, ProjectSettingsCache as G, UpdateUserSchema as Gt, ApiRateLimiter as H, TemplateSchema as Ht, LUA_SCHEDULER_POLL as I, IngestEventSchema as It, StreamProducer as J, WorkflowStepSchema as Jt, PendingMessageScanner as K, UserContactInputSchema as Kt, LUA_USER_THROTTLE as L, InlineUserSchema as Lt, LUA_LEASE_API_RATE_LIMIT as M, AddUserSchema as Mt, LUA_MARK_PROCESSED as N, BatchAddContactsSchema as Nt, PreferenceRepository as O, normaliseTarget as On, NotificationCreatedPayloadSchema as Ot, LUA_RELEASE_LOCK as P, ContactChannelSchema as Pt, IdempotencyGuard as Q, INBOUND_STREAMS as Qt, Redis as R, NotifyRequestSchema as Rt, AdminUserRepository as S, sleep as Sn, DeliveryOptionsSchema as St, ProjectRepository as T, BatchProcessor as Tn, NotificationScheduledPayloadSchema as Tt, calculateTokenBatchSize as U, TriggerWorkflowSchema as Ut, registerCustomCommands as V, SyncTemplatesSchema as Vt, UserThrottle as W, UpdateProjectSchema as Wt, metrics as X, CONSUMER_GROUPS as Xt, getMetricsRegistry as Y, buildStreamEvent as Yt, createLogger as Z, ENRICHED_STREAMS as Zt, TemplateCache as _, setAiConfig as _n, NotificationAiPendingPayloadSchema as _t, SuspendExecutionError as a, EventRegistry as an, deliveryOutbox as at, interpolate as b, ValidationError as bn, NotificationFailedPayloadSchema as bt, BaseWorker as c, NotificationChannelSchema as cn, projects as ct, startHealthReporter as d, AI_DEFAULTS as dn, userTopicPreferences as dt, PUBSUB_CHANNELS as en, createDatabase as et, buildUnsubscribeHeaders as f, baseConfigSchema as fn, users as ft, transportRegistry as g, readBaseConfig as gn, workflowWaiters as gt, registerTransport as h, parseConfig as hn, workflowSteps as ht, workflowRegistry as i, StreamEventSchema as in, runMigrations as it, LUA_COUNT_REQUEST as j, AddContactSchema as jt, UserRepository as k, LRUCache as kn, NotificationRequestedPayloadSchema as kt, LockHeldError as l, NotificationPrioritySchema as ln, scheduledPayloads as lt, verifyUnsubscribeToken as m, loadEnv as mn, workflowInstances as mt, NotifkitClient as n, EventEnvelopeSchema as nn, notifkitTableNames as nt, buildStepNotifyPayload as o, registry as on, messageLogs as ot, signUnsubscribeToken as p, getAiConfig as pn, workflowDefinitions as pt, StreamConsumer as q, WorkflowNotifyPayloadSchema as qt, workflow as r, StreamEventMetadataSchema as rn, qualifyMigrationSql as rt, resolveStepTarget as s, EventMetadataSchema as sn, projectApiKeys as st, NotifkitServer as t, STREAMS as tn, migrateDatabase as tt, NonRetryableError as u, NotificationStatusSchema as un, suppressions as ut, escapeHeader as v, setGlobalConfig as vn, NotificationCanceledPayloadSchema as vt, WorkflowRepository as w, CircuitBreaker as wn, RenderedContentSchema as wt, renderWithTemplate as x, generateId as xn, NotificationDeliveredPayloadSchema as xt, escapeHtml as y, AppError as yn, NotificationSkippedPayloadSchema as yt, RedisClient as z, PreferencesSchema as zt };
4228
+ export { migrateDatabase as $, STREAMS as $t, LUA_COUNT_REQUEST as A, AddUserSchema as At, ApiRateLimiter as B, TemplateSchema as Bt, SegmentRepository as C, BatchProcessor as Cn, NotificationScheduledPayloadSchema as Ct, ContactRepository as D, LRUCache as Dn, NotificationRequestedPayloadSchema as Dt, TemplateRepository as E, normaliseTarget as En, NotificationCreatedPayloadSchema as Et, LUA_USER_THROTTLE as F, InlineUserSchema as Ft, StreamConsumer as G, WorkflowNotifyPayloadSchema as Gt, UserThrottle as H, UpdateProjectSchema as Ht, Redis as I, NotifyRequestSchema as It, metrics as J, CONSUMER_GROUPS as Jt, StreamProducer as K, WorkflowStepSchema as Kt, RedisClient as L, PreferencesSchema as Lt, LUA_RELEASE_LOCK as M, ContactChannelSchema as Mt, LUA_RENEW_LOCK as N, CreateWorkflowSchema as Nt, PreferenceRepository as O, globalEmitter as On, NotificationTargetSchema as Ot, LUA_SCHEDULER_POLL as P, IngestEventSchema as Pt, createDatabase as Q, PUBSUB_CHANNELS as Qt, redactUrl as R, QuietHoursSchema as Rt, AdminUserRepository as S, CircuitBreaker as Sn, RenderedContentSchema as St, ProjectRepository as T, getPriorityBucket as Tn, RecipientProfileSchema as Tt, ProjectSettingsCache as U, UpdateUserSchema as Ut, calculateTokenBatchSize as V, TriggerWorkflowSchema as Vt, PendingMessageScanner as W, UserContactInputSchema as Wt, IdempotencyGuard as X, INBOUND_STREAMS as Xt, createLogger as Y, ENRICHED_STREAMS as Yt, assertTablesInSchema as Z, OUTBOUND_STREAMS as Zt, TemplateCache as _, AppError as _n, NotificationSkippedPayloadSchema as _t, SuspendExecutionError as a, EventMetadataSchema as an, projectApiKeys as at, interpolate as b, sleep as bn, DeliveryOptionsSchema as bt, BaseWorker as c, NotificationStatusSchema as cn, suppressions as ct, startHealthReporter as d, getAiConfig as dn, workflowDefinitions as dt, EventEnvelopeSchema as en, notifkitTableNames as et, buildUnsubscribeHeaders as f, loadEnv as fn, workflowInstances as ft, transportRegistry as g, setGlobalConfig as gn, NotificationCanceledPayloadSchema as gt, registerTransport as h, setAiConfig as hn, NotificationAiPendingPayloadSchema as ht, workflowRegistry as i, registry as in, messageLogs as it, LUA_LEASE_API_RATE_LIMIT as j, BatchAddContactsSchema as jt, UserRepository as k, AddContactSchema as kt, LockHeldError as l, AI_DEFAULTS as ln, userTopicPreferences as lt, verifyUnsubscribeToken as m, readBaseConfig as mn, workflowWaiters as mt, NotifkitClient as n, StreamEventSchema as nn, runMigrations as nt, buildStepNotifyPayload as o, NotificationChannelSchema as on, projects as ot, signUnsubscribeToken as p, parseConfig as pn, workflowSteps as pt, getMetricsRegistry as q, buildStreamEvent as qt, workflow as r, EventRegistry as rn, deliveryOutbox as rt, resolveStepTarget as s, NotificationPrioritySchema as sn, scheduledPayloads as st, NotifkitServer as t, StreamEventMetadataSchema as tn, qualifyMigrationSql as tt, NonRetryableError as u, baseConfigSchema as un, users as ut, escapeHeader as v, ValidationError as vn, NotificationFailedPayloadSchema as vt, WorkflowRepository as w, AsyncSemaphore as wn, NotificationEnrichedPayloadSchema as wt, renderWithTemplate as x, DataLoader as xn, NotificationDispatchedPayloadSchema as xt, escapeHtml as y, generateId as yn, NotificationDeliveredPayloadSchema as yt, registerCustomCommands as z, SyncTemplatesSchema as zt };
@@ -0,0 +1,4 @@
1
+ -- The hourly retention prune deletes by age; without these it scans both tables.
2
+ -- Timestamps only grow, so each insert appends to the right edge of the index.
3
+ CREATE INDEX IF NOT EXISTS "msg_log_time_idx" ON "message_logs" USING btree ("timestamp");--> statement-breakpoint
4
+ CREATE INDEX IF NOT EXISTS "delivery_outbox_created_idx" ON "delivery_outbox" USING btree ("created_at");
@@ -64,6 +64,13 @@
64
64
  "when": 1790800000000,
65
65
  "tag": "0008_delivery_outbox_destination_idx",
66
66
  "breakpoints": true
67
+ },
68
+ {
69
+ "idx": 9,
70
+ "version": "7",
71
+ "when": 1790900000000,
72
+ "tag": "0009_retention_time_indexes",
73
+ "breakpoints": true
67
74
  }
68
75
  ]
69
76
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notifkit",
3
- "version": "0.1.17",
3
+ "version": "0.1.19",
4
4
  "description": "Self-hosted notification infrastructure. One call delivers to email, SMS, push, and webhook — routed by preference, quiet hours, and consent.",
5
5
  "license": "MIT",
6
6
  "author": "devkitshq",
package/src/client.ts CHANGED
@@ -320,7 +320,7 @@ export class NotifkitClient {
320
320
  return this.request("/v1/segments", "GET");
321
321
  }
322
322
 
323
- // ─── Campaigns ───────────────────────────────────────────────────────────────
323
+ // Campaigns
324
324
 
325
325
  /** List campaign labels seen in the delivery log, most recent activity first. */
326
326
  async listCampaigns(options?: {
@@ -371,7 +371,7 @@ export class NotifkitClient {
371
371
  return this.request(`/v1/campaigns/${encodeURIComponent(campaign)}/stats`, "GET");
372
372
  }
373
373
 
374
- // ─── Suppressions ────────────────────────────────────────────────────────────
374
+ // Suppressions
375
375
 
376
376
  /** List suppressed destinations. */
377
377
  async listSuppressions(options?: {
@@ -406,7 +406,7 @@ export class NotifkitClient {
406
406
  );
407
407
  }
408
408
 
409
- // ─── Notification Status & Cancellation ─────────────────────────────────────
409
+ // Notification Status & Cancellation
410
410
 
411
411
  /** Get real-time status and delivery logs for a specific notification task. */
412
412
  async getNotificationStatus(
@@ -425,7 +425,7 @@ export class NotifkitClient {
425
425
  return this.request("/v1/notifications/scheduled", "GET");
426
426
  }
427
427
 
428
- // ─── User Profile & Preferences ─────────────────────────────────────────────
428
+ // User Profile & Preferences
429
429
 
430
430
  /** Get user profile and contacts by ID. */
431
431
  async getUser(id: string): Promise<UserResponse> {
@@ -450,7 +450,7 @@ export class NotifkitClient {
450
450
  return this.request(`/v1/users/${encodeURIComponent(id)}/preferences`, "PATCH", preferences);
451
451
  }
452
452
 
453
- // ─── Templates Querying ─────────────────────────────────────────────────────
453
+ // Templates Querying
454
454
 
455
455
  /** List all templates for the project. */
456
456
  async listTemplates(): Promise<{ templates: TemplateRecordResponse[] }> {
@@ -462,7 +462,7 @@ export class NotifkitClient {
462
462
  return this.request(`/v1/templates/${encodeURIComponent(id)}`, "GET");
463
463
  }
464
464
 
465
- // ─── System Health, Metrics & DLQ ───────────────────────────────────────────
465
+ // System Health, Metrics & DLQ
466
466
 
467
467
  /** Get system health and worker status. */
468
468
  async getSystemHealth(): Promise<SystemHealthRecord> {
@@ -38,10 +38,7 @@ export const baseConfigSchema = z.object({
38
38
  HOST: z.string().default("127.0.0.1"),
39
39
  REDIS_URL: z.string().url().default("redis://localhost:6379"),
40
40
  DATABASE_URL: z.string().url().default("postgres://platform:platform@localhost:5432/notifkit"),
41
- // Trimmed because the incoming bearer token is trimmed before comparison, so
42
- // an untrimmed value here could never match it. `set KEY=value && cmd` on
43
- // Windows puts a trailing space in the variable, which otherwise turns every
44
- // admin request into a 401 that reads like a wrong key.
41
+ // Trimmed like the incoming token; Windows `set KEY=value && cmd` adds a trailing space.
45
42
  ADMIN_API_KEY: z.string().trim().optional(),
46
43
  ADMIN_EMAIL: z.string().trim().email().optional(),
47
44
  ADMIN_PASSWORD: z.string().trim().min(6).optional(),
@@ -60,14 +57,13 @@ export const baseConfigSchema = z.object({
60
57
  .transform((v) => v === "true" || v === "1"),
61
58
  QUEUE_MAX_LEN: z.coerce.number().int().min(1).default(100000),
62
59
  /**
63
- * How long the pipeline remembers it handled a message, so a redelivery
64
- * after a crash is not sent twice. It only has to outlast redelivery (about
65
- * ten minutes) plus however far behind the streams run; a caller's own
66
- * X-Idempotency-Key is always kept for 24 hours regardless. These markers
67
- * are most of Redis memory under load, so the cost of a longer window is
68
- * real: a few hundred bytes per message for as long as it lasts.
60
+ * How long the pipeline remembers a handled message, so a redelivery isn't
61
+ * sent twice. Must outlast redelivery plus stream lag. These markers are most
62
+ * of Redis memory under load. A caller's X-Idempotency-Key always keeps 24h.
69
63
  */
70
64
  IDEMPOTENCY_TTL_SECONDS: z.coerce.number().int().min(60).default(3600),
65
+ /** Non-critical sends per user per hour, unless the project overrides it. */
66
+ RATE_LIMIT_PER_HOUR: z.coerce.number().int().min(0).default(100),
71
67
  DB_MAX_CONNECTIONS: z.coerce.number().int().min(1).default(2),
72
68
  /**
73
69
  * PostgreSQL schema that holds notifkit's tables and enum types. Defaults to
@@ -81,6 +77,8 @@ export const baseConfigSchema = z.object({
81
77
  .regex(/^[a-z_][a-z0-9_]{0,62}$/, "must be a lowercase PostgreSQL identifier")
82
78
  .default("public"),
83
79
  LOG_FLUSH_INTERVAL_MS: z.coerce.number().int().min(50).default(500),
80
+ /** Days of delivery logs to keep; the scheduler deletes older rows hourly. Unset keeps them forever. */
81
+ LOG_RETENTION_DAYS: z.coerce.number().int().min(1).optional(),
84
82
  LOG_BUFFER_MAX_SIZE: z.coerce.number().int().min(100).default(5000),
85
83
  SEGMENT_MAX_USERS: z.coerce.number().int().min(1).default(100_000),
86
84
  /**