@guren/server 2.25.1 → 2.27.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.
Files changed (121) hide show
  1. package/dist/{DocsViewerServiceProvider-CIRNHQ2I.js → DocsViewerServiceProvider-BMbcTYVw.js} +1 -1
  2. package/dist/{Gate-YOt54xGF.js → Gate-BL_zW82W.js} +1 -1
  3. package/dist/{Job-COMzBNOL.js → Job-DsFMcXVk.js} +35 -3
  4. package/dist/{McpServiceProvider-B-LioPSz.js → McpServiceProvider-PGFPlYTy.js} +1 -1
  5. package/dist/{Resource-BdYd4J9a.js → Resource-q3tJpJ0K.js} +194 -54
  6. package/dist/{ServiceProvider-DDW3MqQJ.js → ServiceProvider-G0YclITd.js} +60 -8
  7. package/dist/agent/dispatch.d.ts +4 -4
  8. package/dist/agent/public.js +1 -1
  9. package/dist/agent/scopes.d.ts +1 -3
  10. package/dist/agent-request-Caj6bnbj.js +18 -0
  11. package/dist/auth/AuthManager.d.ts +4 -0
  12. package/dist/auth/email-verification.d.ts +8 -1
  13. package/dist/auth/index.js +1 -1
  14. package/dist/auth/password/describe-hasher.d.ts +11 -0
  15. package/dist/auth/password-reset.d.ts +8 -2
  16. package/dist/{auth-vFeem6uM.js → auth-DIugW0O-.js} +108 -13
  17. package/dist/authorization/index.js +2 -2
  18. package/dist/authorization/middleware.d.ts +8 -0
  19. package/dist/{authorization-BLhwA2Yh.js → authorization-Daa6CxCg.js} +17 -2
  20. package/dist/broadcasting/BroadcastManager.d.ts +23 -6
  21. package/dist/broadcasting/index.d.ts +1 -1
  22. package/dist/broadcasting/index.js +1 -1
  23. package/dist/broadcasting/types.d.ts +13 -1
  24. package/dist/{broadcasting-BUBCPCnu.js → broadcasting-N4cRV42s.js} +205 -34
  25. package/dist/cache/CacheManager.d.ts +5 -0
  26. package/dist/cache/TaggedCache.d.ts +2 -0
  27. package/dist/cache/index.js +1 -1
  28. package/dist/cache/pending-computations.d.ts +22 -0
  29. package/dist/cache/stores/FileStore.d.ts +2 -0
  30. package/dist/cache/stores/MemoryStore.d.ts +1 -0
  31. package/dist/cache/stores/RedisStore.d.ts +1 -0
  32. package/dist/cache/stores/file-lock.d.ts +1 -0
  33. package/dist/cache/types.d.ts +2 -0
  34. package/dist/{cache-93n2PCnB.js → cache-BlXopnH1.js} +247 -38
  35. package/dist/contained-path-BkNSBljW.js +78 -0
  36. package/dist/container/Container.d.ts +6 -2
  37. package/dist/container/ServiceProvider.d.ts +27 -2
  38. package/dist/container/defineModule.d.ts +14 -5
  39. package/dist/container/definePlugin.d.ts +2 -0
  40. package/dist/{default-application-D5ezhhiV.js → default-application-DWwscxfW.js} +14 -18
  41. package/dist/dev-banner-CfQDnkfQ.js +51 -0
  42. package/dist/{dispatch-BAwzftws.js → dispatch-ENWpBxbE.js} +26 -4
  43. package/dist/driver-map-CkQc52j-.js +12 -0
  44. package/dist/encryption/index.js +1 -1
  45. package/dist/{encryption-D1dxfMqD.js → encryption-CWK5l22W.js} +1 -1
  46. package/dist/events/EventManager.d.ts +2 -0
  47. package/dist/events/index.js +1 -1
  48. package/dist/{events-c94CdUFc.js → events-DQavGm8W.js} +20 -7
  49. package/dist/health/HealthManager.d.ts +0 -1
  50. package/dist/health/index.js +1 -1
  51. package/dist/{health-CB0oS_UE.js → health-Bg0Xj3aD.js} +8 -8
  52. package/dist/host-port-t6wQFaRu.js +15 -0
  53. package/dist/hot-reload/testing.d.ts +2 -1
  54. package/dist/http/Application.d.ts +31 -2
  55. package/dist/http/dev-banner.d.ts +0 -8
  56. package/dist/http/host-port.d.ts +8 -0
  57. package/dist/http/middleware/force-https.d.ts +2 -1
  58. package/dist/http/middleware/index.d.ts +1 -0
  59. package/dist/http/middleware/rate-limit.d.ts +1 -4
  60. package/dist/http/middleware/session-manager.d.ts +5 -0
  61. package/dist/http/middleware/websocket-origin.d.ts +22 -0
  62. package/dist/http/public-assets.d.ts +6 -1
  63. package/dist/i18n/index.js +1 -1
  64. package/dist/{i18n-DqcRD4qL.js → i18n-DmMKcbqj.js} +1 -1
  65. package/dist/index.d.ts +8 -4
  66. package/dist/index.js +744 -273
  67. package/dist/internal/agent-request.d.ts +18 -0
  68. package/dist/internal/app-conventions.d.ts +6 -0
  69. package/dist/internal/app-conventions.js +9 -0
  70. package/dist/internal/dispatched-request.d.ts +4 -0
  71. package/dist/internal/testing.d.ts +1 -1
  72. package/dist/internal/testing.js +3 -3
  73. package/dist/internal/zod-json-schema.js +1 -1
  74. package/dist/introspection/driver-map.d.ts +3 -0
  75. package/dist/introspection/flag.d.ts +12 -0
  76. package/dist/introspection/manifest.d.ts +17 -0
  77. package/dist/introspection/plain-json.d.ts +7 -0
  78. package/dist/introspection/types.d.ts +167 -0
  79. package/dist/lambda/index.js +66 -28
  80. package/dist/logging/index.js +1 -1
  81. package/dist/{logging-YbKmbAd7.js → logging-Ci0mBk5k.js} +1 -1
  82. package/dist/mail/index.js +1 -1
  83. package/dist/{mail-uRBrUl9q.js → mail-CI2Kfe8P.js} +2 -2
  84. package/dist/mcp/index.js +1 -1
  85. package/dist/mvc/Controller.d.ts +3 -2
  86. package/dist/mvc/Router.d.ts +33 -0
  87. package/dist/mvc/inertia/InertiaEngine.d.ts +31 -0
  88. package/dist/mvc/inertia/props.d.ts +71 -0
  89. package/dist/notifications/index.js +1 -1
  90. package/dist/notifications/registry.d.ts +2 -2
  91. package/dist/{notifications-LHuujttf.js → notifications-Bp2uamzD.js} +7 -5
  92. package/dist/providers/ConfigServiceProvider.d.ts +12 -5
  93. package/dist/queue/Job.d.ts +5 -0
  94. package/dist/queue/QueueManager.d.ts +3 -0
  95. package/dist/queue/Worker.d.ts +6 -1
  96. package/dist/queue/drivers/RedisDriver.d.ts +4 -2
  97. package/dist/queue/drivers/SqsDriver.d.ts +31 -2
  98. package/dist/queue/drivers/redis-queue-scripts.d.ts +83 -0
  99. package/dist/queue/index.js +2 -2
  100. package/dist/queue/serialize.d.ts +7 -0
  101. package/dist/queue/types.d.ts +13 -2
  102. package/dist/{queue-BiBn5Sff.js → queue-C8s3buYz.js} +299 -125
  103. package/dist/redis/RedisEmailVerificationStore.d.ts +2 -0
  104. package/dist/redis/RedisPasswordResetStore.d.ts +2 -0
  105. package/dist/redis/auth-token-scripts.d.ts +4 -0
  106. package/dist/redis/index.js +50 -0
  107. package/dist/runtime/index.js +17 -37
  108. package/dist/scheduling/ScheduledTask.d.ts +2 -1
  109. package/dist/scheduling/index.js +1 -1
  110. package/dist/{scheduling-DhYfbJFj.js → scheduling-DNV5tj44.js} +32 -38
  111. package/dist/serialize-CKXek0Tr.js +17 -0
  112. package/dist/storage/StorageManager.d.ts +5 -0
  113. package/dist/storage/drivers/LocalDriver.d.ts +15 -0
  114. package/dist/storage/index.js +1 -1
  115. package/dist/storage/url-path.d.ts +2 -0
  116. package/dist/{storage-6HLaUf9j.js → storage-IlUesK2t.js} +91 -29
  117. package/dist/support/contained-path.d.ts +8 -0
  118. package/dist/support/registry-collision.d.ts +12 -0
  119. package/dist/{vite-manifest-DK55BTLk.js → vite-manifest-wPxfAzjW.js} +2 -58
  120. package/package.json +6 -2
  121. package/dist/trim-slashes-BLY9hKAa.js +0 -22
@@ -1,4 +1,8 @@
1
- import { a as getJob, i as enqueueJob } from "./Job-COMzBNOL.js";
1
+ import { t as warnOnce } from "./warn-once-p-IlMjra.js";
2
+ import { a as getJob, i as enqueueJob } from "./Job-DsFMcXVk.js";
3
+ import { t as describeDriverMap } from "./driver-map-CkQc52j-.js";
4
+ import { t as deserializeQueuedJob } from "./serialize-CKXek0Tr.js";
5
+ import { randomUUID } from "node:crypto";
2
6
  //#region src/queue/drivers/MemoryDriver.ts
3
7
  /** In-memory queue driver for development and testing. */
4
8
  var MemoryDriver = class {
@@ -145,6 +149,120 @@ var SyncDriver = class {
145
149
  }
146
150
  };
147
151
  //#endregion
152
+ //#region src/queue/drivers/redis-queue-scripts.ts
153
+ /** ARGV[1] = job id, ARGV[2] = reservation token ('' skips the ownership check). */
154
+ const OWNER = `
155
+ if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
156
+ if ARGV[2] ~= '' and redis.call('HGET', KEYS[1], 'reservationToken') ~= ARGV[2] then return 0 end
157
+ `;
158
+ const QUEUE_SCRIPTS = {
159
+ /** KEYS: job, pending. ARGV: id, availableAt, ...hash fields. */
160
+ gurenQueuePush: {
161
+ numberOfKeys: 2,
162
+ lua: `
163
+ redis.call('HSET', KEYS[1], unpack(ARGV, 3))
164
+ redis.call('ZADD', KEYS[2], ARGV[2], ARGV[1])
165
+ return 1
166
+ `
167
+ },
168
+ /** KEYS: pending, reserved. ARGV: now, expiresAt, reservedAt, token, job key prefix. */
169
+ gurenQueuePop: {
170
+ numberOfKeys: 2,
171
+ lua: `
172
+ local expired = redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', ARGV[1], 'LIMIT', 0, 100)
173
+ for _, id in ipairs(expired) do
174
+ redis.call('ZREM', KEYS[2], id)
175
+ local key = ARGV[5] .. id
176
+ if redis.call('HEXISTS', key, 'id') == 1 then
177
+ redis.call('ZADD', KEYS[1], ARGV[1], id)
178
+ redis.call('HDEL', key, 'reservedAt', 'reservationToken')
179
+ end
180
+ end
181
+ while true do
182
+ local ids = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', ARGV[1], 'LIMIT', 0, 1)
183
+ if #ids == 0 then return {} end
184
+ local id = ids[1]
185
+ local key = ARGV[5] .. id
186
+ redis.call('ZREM', KEYS[1], id)
187
+ if redis.call('HEXISTS', key, 'id') == 1 then
188
+ redis.call('ZADD', KEYS[2], ARGV[2], id)
189
+ redis.call('HSET', key, 'reservedAt', ARGV[3], 'reservationToken', ARGV[4])
190
+ return redis.call('HGETALL', key)
191
+ end
192
+ end
193
+ `
194
+ },
195
+ /** KEYS: job, pending, reserved. ARGV: id, token, attempts, availableAt ISO, lastError, availableAt ms. */
196
+ gurenQueueRelease: {
197
+ numberOfKeys: 3,
198
+ lua: OWNER + `
199
+ redis.call('HSET', KEYS[1], 'attempts', ARGV[3], 'availableAt', ARGV[4])
200
+ if ARGV[5] ~= '' then redis.call('HSET', KEYS[1], 'lastError', ARGV[5]) else redis.call('HDEL', KEYS[1], 'lastError') end
201
+ redis.call('HDEL', KEYS[1], 'reservedAt', 'reservationToken')
202
+ redis.call('ZREM', KEYS[3], ARGV[1])
203
+ redis.call('ZADD', KEYS[2], ARGV[6], ARGV[1])
204
+ return 1
205
+ `
206
+ },
207
+ /** KEYS: job. ARGV: id, token, queue key prefix. */
208
+ gurenQueueDelete: {
209
+ numberOfKeys: 1,
210
+ lua: OWNER + `
211
+ local queue = redis.call('HGET', KEYS[1], 'queue')
212
+ redis.call('ZREM', ARGV[3] .. queue .. ':pending', ARGV[1])
213
+ redis.call('ZREM', ARGV[3] .. queue .. ':reserved', ARGV[1])
214
+ redis.call('DEL', KEYS[1])
215
+ return 1
216
+ `
217
+ },
218
+ /** KEYS: job, pending, reserved, failed. ARGV: id, token, failedAt, error, stack, attempts. */
219
+ gurenQueueFail: {
220
+ numberOfKeys: 4,
221
+ lua: OWNER + `
222
+ redis.call('HSET', KEYS[1], 'failedAt', ARGV[3], 'error', ARGV[4], 'stack', ARGV[5], 'attempts', ARGV[6])
223
+ redis.call('HDEL', KEYS[1], 'reservedAt', 'reservationToken')
224
+ redis.call('ZREM', KEYS[2], ARGV[1])
225
+ redis.call('ZREM', KEYS[3], ARGV[1])
226
+ redis.call('LREM', KEYS[4], 0, ARGV[1])
227
+ redis.call('LPUSH', KEYS[4], ARGV[1])
228
+ return 1
229
+ `
230
+ },
231
+ /** KEYS: job, reserved. ARGV: id, token, expiresAt. */
232
+ gurenQueueExtend: {
233
+ numberOfKeys: 2,
234
+ lua: OWNER + `
235
+ if not redis.call('ZSCORE', KEYS[2], ARGV[1]) then return 0 end
236
+ redis.call('ZADD', KEYS[2], ARGV[3], ARGV[1])
237
+ return 1
238
+ `
239
+ },
240
+ /** KEYS: job. ARGV: id, now ISO, now ms, queue key prefix. */
241
+ gurenQueueRetry: {
242
+ numberOfKeys: 1,
243
+ lua: `
244
+ local queue = redis.call('HGET', KEYS[1], 'queue')
245
+ if not queue or redis.call('HEXISTS', KEYS[1], 'failedAt') == 0 then return 0 end
246
+ redis.call('LREM', ARGV[4] .. queue .. ':failed', 0, ARGV[1])
247
+ redis.call('HSET', KEYS[1], 'attempts', '0', 'availableAt', ARGV[2], 'createdAt', ARGV[2])
248
+ redis.call('HDEL', KEYS[1], 'reservedAt', 'reservationToken', 'failedAt', 'error', 'stack', 'lastError')
249
+ redis.call('ZADD', ARGV[4] .. queue .. ':pending', ARGV[3], ARGV[1])
250
+ return 1
251
+ `
252
+ },
253
+ /** KEYS: job. ARGV: id, queue key prefix. */
254
+ gurenQueueDeleteFailed: {
255
+ numberOfKeys: 1,
256
+ lua: `
257
+ local queue = redis.call('HGET', KEYS[1], 'queue')
258
+ if not queue or redis.call('HEXISTS', KEYS[1], 'failedAt') == 0 then return 0 end
259
+ redis.call('LREM', ARGV[2] .. queue .. ':failed', 0, ARGV[1])
260
+ redis.call('DEL', KEYS[1])
261
+ return 1
262
+ `
263
+ }
264
+ };
265
+ //#endregion
148
266
  //#region src/queue/drivers/RedisDriver.ts
149
267
  /**
150
268
  * Redis-backed queue driver for production. Key layout:
@@ -160,6 +278,18 @@ var RedisDriver = class {
160
278
  this.redis = redis;
161
279
  this.prefix = options.prefix ?? "queue:";
162
280
  this.visibilityTimeout = options.visibilityTimeout ?? 6e4;
281
+ if (!Number.isFinite(this.visibilityTimeout) || this.visibilityTimeout < 3) throw new Error("Redis queue visibilityTimeout must be at least 3 milliseconds");
282
+ for (const [name, script] of Object.entries(QUEUE_SCRIPTS)) redis.defineCommand(name, script);
283
+ }
284
+ run(name, ...args) {
285
+ return this.redis[name](...args);
286
+ }
287
+ get heartbeatInterval() {
288
+ return Math.max(1, Math.floor(this.visibilityTimeout / 3));
289
+ }
290
+ async extendReservation(job) {
291
+ if (!job.reservationToken) return false;
292
+ return await this.run("gurenQueueExtend", this.jobKey(job.id), this.reservedKey(job.queue), job.id, job.reservationToken, Date.now() + this.visibilityTimeout) === 1;
163
293
  }
164
294
  pendingKey(queue) {
165
295
  return `${this.prefix}${queue}:pending`;
@@ -184,69 +314,25 @@ var RedisDriver = class {
184
314
  availableAt: job.availableAt.toISOString(),
185
315
  createdAt: job.createdAt.toISOString()
186
316
  };
187
- const pipeline = this.redis.pipeline();
188
- pipeline.hset(this.jobKey(job.id), jobData);
189
- pipeline.zadd(this.pendingKey(job.queue), job.availableAt.getTime(), job.id);
190
- await pipeline.exec();
317
+ await this.run("gurenQueuePush", this.jobKey(job.id), this.pendingKey(job.queue), job.id, job.availableAt.getTime(), ...Object.entries(jobData).flat());
191
318
  }
192
319
  async pop(queue) {
193
320
  const now = Date.now();
194
- await this.releaseTimedOutJobs(queue);
195
- const jobIds = await this.redis.zrangebyscore(this.pendingKey(queue), "-inf", now, "LIMIT", 0, 1);
196
- if (jobIds.length === 0) return null;
197
- const jobId = jobIds[0];
198
- if (await this.redis.zrem(this.pendingKey(queue), jobId) === 0) return null;
199
- const timeout = now + this.visibilityTimeout;
200
- await this.redis.zadd(this.reservedKey(queue), timeout, jobId);
201
- await this.redis.hset(this.jobKey(jobId), "reservedAt", (/* @__PURE__ */ new Date()).toISOString());
202
- const jobData = await this.redis.hgetall(this.jobKey(jobId));
203
- if (!jobData || !jobData.id) {
204
- await this.redis.zrem(this.reservedKey(queue), jobId);
205
- return null;
206
- }
207
- return this.parseJobData(jobData);
208
- }
209
- async releaseTimedOutJobs(queue) {
210
- const now = Date.now();
211
- const timedOutIds = await this.redis.zrangebyscore(this.reservedKey(queue), "-inf", now);
212
- for (const jobId of timedOutIds) if (await this.redis.zrem(this.reservedKey(queue), jobId) > 0) {
213
- await this.redis.zadd(this.pendingKey(queue), now, jobId);
214
- await this.redis.hdel(this.jobKey(jobId), "reservedAt");
215
- }
321
+ const fields = await this.run("gurenQueuePop", this.pendingKey(queue), this.reservedKey(queue), now, now + this.visibilityTimeout, new Date(now).toISOString(), randomUUID(), this.jobKey(""));
322
+ if (fields.length === 0) return null;
323
+ const data = {};
324
+ for (let i = 0; i < fields.length; i += 2) data[fields[i]] = fields[i + 1];
325
+ return this.parseJobData(data);
216
326
  }
217
327
  async release(job, delayMs = 0) {
218
328
  const availableAt = Date.now() + delayMs;
219
- await this.redis.zrem(this.reservedKey(job.queue), job.id);
220
- const updates = {
221
- attempts: String(job.attempts),
222
- availableAt: new Date(availableAt).toISOString()
223
- };
224
- if (job.lastError) updates.lastError = job.lastError;
225
- await this.redis.hset(this.jobKey(job.id), updates);
226
- await this.redis.hdel(this.jobKey(job.id), "reservedAt");
227
- await this.redis.zadd(this.pendingKey(job.queue), availableAt, job.id);
329
+ await this.run("gurenQueueRelease", this.jobKey(job.id), this.pendingKey(job.queue), this.reservedKey(job.queue), job.id, job.reservationToken ?? "", job.attempts, new Date(availableAt).toISOString(), job.lastError ?? "", availableAt);
228
330
  }
229
- async delete(jobId) {
230
- const jobData = await this.redis.hgetall(this.jobKey(jobId));
231
- if (jobData && jobData.queue) {
232
- const pipeline = this.redis.pipeline();
233
- pipeline.zrem(this.pendingKey(jobData.queue), jobId);
234
- pipeline.zrem(this.reservedKey(jobData.queue), jobId);
235
- pipeline.del(this.jobKey(jobId));
236
- await pipeline.exec();
237
- } else await this.redis.del(this.jobKey(jobId));
331
+ async delete(jobId, reservationToken) {
332
+ await this.run("gurenQueueDelete", this.jobKey(jobId), jobId, reservationToken ?? "", this.prefix);
238
333
  }
239
334
  async fail(job, error) {
240
- const failedData = {
241
- failedAt: (/* @__PURE__ */ new Date()).toISOString(),
242
- error: error.message,
243
- stack: error.stack ?? ""
244
- };
245
- await this.redis.hset(this.jobKey(job.id), failedData);
246
- const pipeline = this.redis.pipeline();
247
- pipeline.zrem(this.reservedKey(job.queue), job.id);
248
- pipeline.lpush(this.failedKey(job.queue), job.id);
249
- await pipeline.exec();
335
+ await this.run("gurenQueueFail", this.jobKey(job.id), this.pendingKey(job.queue), this.reservedKey(job.queue), this.failedKey(job.queue), job.id, job.reservationToken ?? "", (/* @__PURE__ */ new Date()).toISOString(), error.message, error.stack ?? "", job.attempts);
250
336
  }
251
337
  async size(queue) {
252
338
  return this.redis.zcard(this.pendingKey(queue));
@@ -288,23 +374,11 @@ var RedisDriver = class {
288
374
  return jobs;
289
375
  }
290
376
  async retryFailedJob(jobId) {
291
- const jobData = await this.redis.hgetall(this.jobKey(jobId));
292
- if (!jobData || !jobData.queue) throw new Error(`Failed job not found: ${jobId}`);
293
- const queue = jobData.queue;
294
- await this.redis.lrem(this.failedKey(queue), 1, jobId);
295
377
  const now = /* @__PURE__ */ new Date();
296
- await this.redis.hset(this.jobKey(jobId), {
297
- attempts: "0",
298
- availableAt: now.toISOString(),
299
- createdAt: now.toISOString()
300
- });
301
- await this.redis.hdel(this.jobKey(jobId), "reservedAt", "failedAt", "error", "stack", "lastError");
302
- await this.redis.zadd(this.pendingKey(queue), now.getTime(), jobId);
378
+ if (await this.run("gurenQueueRetry", this.jobKey(jobId), jobId, now.toISOString(), now.getTime(), this.prefix) === 0) throw new Error(`Failed job not found: ${jobId}`);
303
379
  }
304
380
  async deleteFailedJob(jobId) {
305
- const jobData = await this.redis.hgetall(this.jobKey(jobId));
306
- if (jobData && jobData.queue) await this.redis.lrem(this.failedKey(jobData.queue), 1, jobId);
307
- await this.redis.del(this.jobKey(jobId));
381
+ await this.run("gurenQueueDeleteFailed", this.jobKey(jobId), jobId, this.prefix);
308
382
  }
309
383
  /** Testing only. */
310
384
  async clear() {
@@ -329,12 +403,18 @@ var RedisDriver = class {
329
403
  availableAt: new Date(data.availableAt),
330
404
  createdAt: new Date(data.createdAt),
331
405
  reservedAt: data.reservedAt ? new Date(data.reservedAt) : null,
332
- lastError: data.lastError
406
+ lastError: data.lastError,
407
+ reservationToken: data.reservationToken
333
408
  };
334
409
  }
335
410
  };
336
411
  //#endregion
337
412
  //#region src/queue/drivers/SqsDriver.ts
413
+ const EXPIRED_RECEIPT_ERRORS = /* @__PURE__ */ new Set(["ReceiptHandleIsInvalid", "MessageNotInflight"]);
414
+ /** SQS counts deliveries from 1; anything else is an adapter reporting none. */
415
+ function toReceiveCount(value) {
416
+ return Number.isSafeInteger(value) && value >= 1 ? value : void 0;
417
+ }
338
418
  /** Builds an SqsAdapter over an @aws-sdk/client-sqs SQSClient. */
339
419
  function createSqsAdapter(client) {
340
420
  return {
@@ -356,22 +436,37 @@ function createSqsAdapter(client) {
356
436
  const msg = (await client.send(new ReceiveMessageCommand({
357
437
  QueueUrl: params.queueUrl,
358
438
  MaxNumberOfMessages: 1,
439
+ MessageSystemAttributeNames: ["ApproximateReceiveCount"],
359
440
  WaitTimeSeconds: params.waitTimeSeconds ?? 5
360
441
  }))).Messages?.[0];
361
442
  if (!msg?.Body || !msg.ReceiptHandle) return null;
362
443
  return {
363
444
  body: msg.Body,
364
- receiptHandle: msg.ReceiptHandle
445
+ receiptHandle: msg.ReceiptHandle,
446
+ receiveCount: toReceiveCount(Number(msg.Attributes?.ApproximateReceiveCount))
365
447
  };
366
448
  },
367
- async changeMessageVisibility(params) {
368
- const { ChangeMessageVisibilityCommand } = await importSqs();
369
- await client.send(new ChangeMessageVisibilityCommand({
449
+ async deleteMessage(params) {
450
+ const { DeleteMessageCommand } = await importSqs();
451
+ await client.send(new DeleteMessageCommand({
370
452
  QueueUrl: params.queueUrl,
371
- ReceiptHandle: params.receiptHandle,
372
- VisibilityTimeout: params.visibilityTimeout
453
+ ReceiptHandle: params.receiptHandle
373
454
  }));
374
455
  },
456
+ async changeMessageVisibility(params) {
457
+ const { ChangeMessageVisibilityCommand } = await importSqs();
458
+ try {
459
+ await client.send(new ChangeMessageVisibilityCommand({
460
+ QueueUrl: params.queueUrl,
461
+ ReceiptHandle: params.receiptHandle,
462
+ VisibilityTimeout: params.visibilityTimeout
463
+ }));
464
+ return true;
465
+ } catch (error) {
466
+ if (EXPIRED_RECEIPT_ERRORS.has(error.name ?? "")) return false;
467
+ throw error;
468
+ }
469
+ },
375
470
  async getApproximateMessageCount(queueUrl) {
376
471
  const { GetQueueAttributesCommand } = await importSqs();
377
472
  const result = await client.send(new GetQueueAttributesCommand({
@@ -395,11 +490,26 @@ var SqsDriver = class {
395
490
  adapter;
396
491
  options;
397
492
  failedJobs = /* @__PURE__ */ new Map();
398
- receiptHandles = /* @__PURE__ */ new Map();
493
+ reservations = /* @__PURE__ */ new Map();
399
494
  constructor(adapter, options) {
400
495
  this.adapter = adapter;
401
496
  this.options = options;
402
497
  }
498
+ get heartbeatInterval() {
499
+ return Math.max(1e3, Math.floor(this.visibilityTimeout * 1e3 / 3));
500
+ }
501
+ async extendReservation(job) {
502
+ const reservation = this.reservations.get(job.id);
503
+ if (!reservation) return false;
504
+ return await this.adapter.changeMessageVisibility({
505
+ queueUrl: reservation.queueUrl,
506
+ receiptHandle: reservation.receiptHandle,
507
+ visibilityTimeout: this.visibilityTimeout
508
+ }) !== false;
509
+ }
510
+ get visibilityTimeout() {
511
+ return this.options.visibilityTimeout ?? 30;
512
+ }
403
513
  async push(job) {
404
514
  const delaySeconds = Math.min(900, Math.max(0, Math.floor((job.availableAt.getTime() - Date.now()) / 1e3)));
405
515
  await this.adapter.sendMessage({
@@ -411,22 +521,29 @@ var SqsDriver = class {
411
521
  });
412
522
  }
413
523
  async pop(queue) {
414
- const result = await this.adapter.receiveMessage({ queueUrl: this.resolveQueueUrl(queue) });
524
+ const queueUrl = this.resolveQueueUrl(queue);
525
+ const result = await this.adapter.receiveMessage({ queueUrl });
415
526
  if (!result) return null;
416
- const job = deserializeJob(result.body);
417
- this.receiptHandles.set(job.id, result.receiptHandle);
527
+ const job = deserializeQueuedJob(result.body);
528
+ const receiveCount = toReceiveCount(result.receiveCount);
529
+ if (receiveCount !== void 0) job.attempts += receiveCount - 1;
530
+ else warnOnce("sqs-adapter-missing-receive-count", "[guren] The SqsAdapter returned no receiveCount: retry counts restart from the message body on every redelivery, so a failing job retries until the queue drops it. Return ApproximateReceiveCount as receiveCount from receiveMessage(), or build the adapter with createSqsAdapter().");
531
+ this.reservations.set(job.id, {
532
+ receiptHandle: result.receiptHandle,
533
+ queueUrl
534
+ });
418
535
  job.reservedAt = /* @__PURE__ */ new Date();
419
536
  return job;
420
537
  }
421
538
  async release(job, delayMs = 0) {
422
- const receiptHandle = this.receiptHandles.get(job.id);
423
- if (receiptHandle) {
539
+ const reservation = this.reservations.get(job.id);
540
+ if (reservation) {
424
541
  await this.adapter.changeMessageVisibility({
425
- queueUrl: this.resolveQueueUrl(job.queue),
426
- receiptHandle,
542
+ queueUrl: reservation.queueUrl,
543
+ receiptHandle: reservation.receiptHandle,
427
544
  visibilityTimeout: Math.ceil(delayMs / 1e3)
428
545
  });
429
- this.receiptHandles.delete(job.id);
546
+ this.reservations.delete(job.id);
430
547
  } else {
431
548
  job.reservedAt = null;
432
549
  job.availableAt = new Date(Date.now() + delayMs);
@@ -434,7 +551,7 @@ var SqsDriver = class {
434
551
  }
435
552
  }
436
553
  async delete(jobId) {
437
- this.receiptHandles.delete(jobId);
554
+ await this.acknowledge(jobId);
438
555
  }
439
556
  async fail(job, error) {
440
557
  const failedJob = {
@@ -444,7 +561,17 @@ var SqsDriver = class {
444
561
  stack: error.stack
445
562
  };
446
563
  this.failedJobs.set(job.id, failedJob);
447
- this.receiptHandles.delete(job.id);
564
+ try {
565
+ await this.acknowledge(job.id);
566
+ } catch (deleteError) {
567
+ console.error(JSON.stringify({
568
+ level: "error",
569
+ msg: `Could not delete the SQS message for failed job: ${job.name}`,
570
+ job: job.name,
571
+ queue: job.queue,
572
+ error: deleteError.message
573
+ }));
574
+ }
448
575
  }
449
576
  async size(queue) {
450
577
  return this.adapter.getApproximateMessageCount(this.resolveQueueUrl(queue));
@@ -476,23 +603,26 @@ var SqsDriver = class {
476
603
  }
477
604
  async clear() {
478
605
  this.failedJobs.clear();
479
- this.receiptHandles.clear();
606
+ this.reservations.clear();
607
+ }
608
+ /** Drops the reservation only once SQS has accepted the deletion. */
609
+ async acknowledge(jobId) {
610
+ const reservation = this.reservations.get(jobId);
611
+ if (!reservation) return;
612
+ if (this.adapter.deleteMessage) await this.adapter.deleteMessage({
613
+ queueUrl: reservation.queueUrl,
614
+ receiptHandle: reservation.receiptHandle
615
+ });
616
+ else warnOnce("sqs-adapter-missing-delete-message", "[guren] The SqsAdapter has no deleteMessage(): acknowledged jobs stay on the queue and SQS redelivers them once the visibility timeout expires. Implement deleteMessage() on your adapter, or build it with createSqsAdapter().");
617
+ this.reservations.delete(jobId);
480
618
  }
481
619
  resolveQueueUrl(queue) {
482
620
  return this.options.queueUrls?.[queue] ?? this.options.queueUrl;
483
621
  }
484
622
  };
485
- function deserializeJob(body) {
486
- const raw = JSON.parse(body);
487
- return {
488
- ...raw,
489
- availableAt: new Date(raw.availableAt),
490
- createdAt: new Date(raw.createdAt),
491
- reservedAt: raw.reservedAt ? new Date(raw.reservedAt) : null
492
- };
493
- }
494
623
  //#endregion
495
624
  //#region src/queue/Worker.ts
625
+ var ReservationLostError = class extends Error {};
496
626
  /**
497
627
  * Pulls jobs off a driver's queues in priority order and runs each under a
498
628
  * timeout, retrying through `driver.release()`.
@@ -525,20 +655,24 @@ var Worker = class {
525
655
  this.running = true;
526
656
  this.shouldStop = false;
527
657
  this.processedJobs = 0;
528
- this.events.workerStarted?.();
529
- while (!this.shouldStop) {
530
- if (this.maxJobs > 0 && this.processedJobs >= this.maxJobs) break;
531
- const job = await this.getNextJob();
532
- if (job) {
533
- await this.processJob(job);
534
- this.processedJobs++;
535
- } else {
536
- if (this.stopWhenEmpty) break;
537
- await this.sleepMs(this.sleep);
658
+ try {
659
+ this.events.workerStarted?.();
660
+ while (!this.shouldStop) {
661
+ if (this.maxJobs > 0 && this.processedJobs >= this.maxJobs) break;
662
+ const job = await this.getNextJob();
663
+ if (job) {
664
+ await this.processJob(job);
665
+ this.processedJobs++;
666
+ } else {
667
+ if (this.stopWhenEmpty) break;
668
+ await this.sleepMs(this.sleep);
669
+ }
538
670
  }
671
+ } finally {
672
+ this.currentJob = null;
673
+ this.running = false;
674
+ this.events.workerStopped?.();
539
675
  }
540
- this.running = false;
541
- this.events.workerStopped?.();
542
676
  }
543
677
  async stop() {
544
678
  this.shouldStop = true;
@@ -569,12 +703,22 @@ var Worker = class {
569
703
  return;
570
704
  }
571
705
  try {
572
- const instance = this.instantiate(JobClass);
573
- await this.executeWithTimeout(async () => instance.handle(job.payload), this.timeout);
574
- await this.driver.delete(job.id);
706
+ await this.runHandler(this.instantiate(JobClass), job);
707
+ await this.driver.delete(job.id, job.reservationToken);
575
708
  this.events.jobProcessed?.(job);
576
709
  } catch (error) {
577
- await this.handleFailedJob(job, error, JobClass);
710
+ if (error instanceof ReservationLostError) {
711
+ console.error(JSON.stringify({
712
+ level: "error",
713
+ msg: `Job reservation lost: ${job.name}`,
714
+ job: job.name,
715
+ queue: job.queue,
716
+ attempt: job.attempts
717
+ }));
718
+ this.events.jobFailed?.(job, error, true);
719
+ return;
720
+ }
721
+ await this.handleFailedJob(job, error instanceof Error ? error : new Error(String(error)), JobClass);
578
722
  } finally {
579
723
  this.currentJob = null;
580
724
  }
@@ -611,19 +755,45 @@ var Worker = class {
611
755
  if (this.options.container) instance.setContainer(this.options.container);
612
756
  return instance;
613
757
  }
614
- async executeWithTimeout(fn, timeoutMs) {
615
- return new Promise((resolve, reject) => {
616
- const timer = setTimeout(() => {
617
- reject(/* @__PURE__ */ new Error(`Job timed out after ${timeoutMs}ms`));
618
- }, timeoutMs);
619
- fn().then((result) => {
620
- clearTimeout(timer);
621
- resolve(result);
622
- }).catch((error) => {
623
- clearTimeout(timer);
624
- reject(error);
758
+ /**
759
+ * Runs `handle()` under the timeout while renewing the driver's reservation. A
760
+ * timeout requests cancellation through the job's signal and then waits for the
761
+ * handler to settle, so a retry never runs beside its predecessor.
762
+ */
763
+ async runHandler(instance, job) {
764
+ const cancellation = new AbortController();
765
+ const timeout = setTimeout(() => {
766
+ cancellation.abort(/* @__PURE__ */ new Error(`Job timed out after ${this.timeout}ms`));
767
+ }, this.timeout);
768
+ const interval = this.driver.extendReservation ? this.driver.heartbeatInterval : void 0;
769
+ let heartbeat;
770
+ let renewal;
771
+ let reservationError;
772
+ let settled = false;
773
+ const renew = () => {
774
+ renewal = this.driver.extendReservation(job).then((owned) => {
775
+ if (owned) return;
776
+ reservationError = new ReservationLostError("Job reservation now belongs to another worker");
777
+ cancellation.abort(reservationError);
778
+ }, () => {}).finally(() => {
779
+ if (!settled && !reservationError && interval !== void 0) heartbeat = setTimeout(renew, interval);
625
780
  });
626
- });
781
+ };
782
+ if (interval !== void 0) heartbeat = setTimeout(renew, interval);
783
+ let failure;
784
+ try {
785
+ instance.setExecutionSignal(cancellation.signal);
786
+ await instance.handle(job.payload);
787
+ } catch (error) {
788
+ failure = { error };
789
+ } finally {
790
+ settled = true;
791
+ clearTimeout(timeout);
792
+ clearTimeout(heartbeat);
793
+ await renewal;
794
+ }
795
+ if (reservationError) throw reservationError;
796
+ if (failure) throw cancellation.signal.aborted ? cancellation.signal.reason : failure.error;
627
797
  }
628
798
  sleepMs(ms) {
629
799
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -718,6 +888,10 @@ var QueueManager = class {
718
888
  getDriverNames() {
719
889
  return Array.from(this.driverFactories.keys());
720
890
  }
891
+ /** The declared drivers and the default, resolving none. Every driver is a bare factory, so `driver` is null. */
892
+ describe() {
893
+ return describeDriverMap(this.defaultDriver, Array.from(this.driverFactories.keys(), (name) => [name, null]));
894
+ }
721
895
  /**
722
896
  * After this, `driver()` with no name, `getDefaultDriverName()`, and — for a
723
897
  * manager bound as `queue` — `Job.dispatch()` all use the new driver.
@@ -13,6 +13,8 @@ export declare class RedisEmailVerificationStore implements EmailVerificationTok
13
13
  private readonly prefix;
14
14
  constructor(redis: Redis, options?: RedisEmailVerificationStoreOptions);
15
15
  store(token: EmailVerificationToken): Promise<void>;
16
+ replace(token: EmailVerificationToken): Promise<void>;
17
+ consume(tokenId: string, email: string): Promise<boolean>;
16
18
  findByTokenId(tokenId: string): Promise<EmailVerificationToken | null>;
17
19
  delete(tokenId: string): Promise<void>;
18
20
  deleteForEmail(email: string): Promise<void>;
@@ -13,6 +13,8 @@ export declare class RedisPasswordResetStore implements PasswordResetTokenStore
13
13
  private readonly prefix;
14
14
  constructor(redis: Redis, options?: RedisPasswordResetStoreOptions);
15
15
  store(tokenId: string, email: string, expiresAt: Date): Promise<void>;
16
+ replace(tokenId: string, email: string, expiresAt: Date): Promise<void>;
17
+ consume(tokenId: string, email: string): Promise<boolean>;
16
18
  find(tokenId: string): Promise<{
17
19
  email: string;
18
20
  expiresAt: Date;
@@ -0,0 +1,4 @@
1
+ /** Replace the indexed tokens and publish their successor as one Redis operation. */
2
+ export declare const REPLACE_AUTH_TOKEN = "\nlocal ids = redis.call('SMEMBERS', KEYS[1])\nfor _, id in ipairs(ids) do\n redis.call('DEL', ARGV[1] .. id)\nend\nredis.call('DEL', KEYS[1])\nlocal ttl = tonumber(ARGV[4])\nif ttl > 0 then\n redis.call('PSETEX', KEYS[2], ttl, ARGV[3])\n redis.call('SADD', KEYS[1], ARGV[2])\n redis.call('PEXPIRE', KEYS[1], ttl + 60000)\nend\nreturn 1\n";
3
+ /** Compare and consume without a GET/DEL race between different workers. */
4
+ export declare const CONSUME_AUTH_TOKEN = "\nlocal raw = redis.call('GET', KEYS[1])\nif not raw then return 0 end\nlocal ok, record = pcall(cjson.decode, raw)\nif not ok or type(record) ~= 'table' or record.email ~= ARGV[1] then return 0 end\nredis.call('DEL', KEYS[1])\nredis.call('SREM', KEYS[2], ARGV[2])\nreturn 1\n";
@@ -245,6 +245,33 @@ var RedisApiTokenStore = class {
245
245
  }
246
246
  };
247
247
  //#endregion
248
+ //#region src/redis/auth-token-scripts.ts
249
+ /** Replace the indexed tokens and publish their successor as one Redis operation. */
250
+ const REPLACE_AUTH_TOKEN = `
251
+ local ids = redis.call('SMEMBERS', KEYS[1])
252
+ for _, id in ipairs(ids) do
253
+ redis.call('DEL', ARGV[1] .. id)
254
+ end
255
+ redis.call('DEL', KEYS[1])
256
+ local ttl = tonumber(ARGV[4])
257
+ if ttl > 0 then
258
+ redis.call('PSETEX', KEYS[2], ttl, ARGV[3])
259
+ redis.call('SADD', KEYS[1], ARGV[2])
260
+ redis.call('PEXPIRE', KEYS[1], ttl + 60000)
261
+ end
262
+ return 1
263
+ `;
264
+ /** Compare and consume without a GET/DEL race between different workers. */
265
+ const CONSUME_AUTH_TOKEN = `
266
+ local raw = redis.call('GET', KEYS[1])
267
+ if not raw then return 0 end
268
+ local ok, record = pcall(cjson.decode, raw)
269
+ if not ok or type(record) ~= 'table' or record.email ~= ARGV[1] then return 0 end
270
+ redis.call('DEL', KEYS[1])
271
+ redis.call('SREM', KEYS[2], ARGV[2])
272
+ return 1
273
+ `;
274
+ //#endregion
248
275
  //#region src/redis/RedisPasswordResetStore.ts
249
276
  /**
250
277
  * Key layout: `pwreset:{tokenId}` JSON of email + expiresAt,
@@ -272,6 +299,17 @@ var RedisPasswordResetStore = class {
272
299
  pipeline.pexpire(emailKey, ttlMs + 6e4);
273
300
  await pipeline.exec();
274
301
  }
302
+ async replace(tokenId, email, expiresAt) {
303
+ email = email.toLowerCase();
304
+ const data = JSON.stringify({
305
+ email,
306
+ expiresAt: expiresAt.toISOString()
307
+ });
308
+ await this.redis.eval(REPLACE_AUTH_TOKEN, 2, `${this.prefix}email:${email}`, `${this.prefix}${tokenId}`, this.prefix, tokenId, data, Math.max(0, expiresAt.getTime() - Date.now()));
309
+ }
310
+ async consume(tokenId, email) {
311
+ return await this.redis.eval(CONSUME_AUTH_TOKEN, 2, `${this.prefix}${tokenId}`, `${this.prefix}email:${email.toLowerCase()}`, email, tokenId) === 1;
312
+ }
275
313
  async find(tokenId) {
276
314
  const tokenKey = `${this.prefix}${tokenId}`;
277
315
  const data = await this.redis.get(tokenKey);
@@ -342,6 +380,18 @@ var RedisEmailVerificationStore = class {
342
380
  pipeline.pexpire(emailKey, ttlMs + 6e4);
343
381
  await pipeline.exec();
344
382
  }
383
+ async replace(token) {
384
+ const { tokenId, expiresAt } = token;
385
+ const email = token.email.toLowerCase();
386
+ const data = JSON.stringify({
387
+ ...token,
388
+ email
389
+ });
390
+ await this.redis.eval(REPLACE_AUTH_TOKEN, 2, `${this.prefix}email:${email}`, `${this.prefix}${tokenId}`, this.prefix, tokenId, data, Math.max(0, expiresAt.getTime() - Date.now()));
391
+ }
392
+ async consume(tokenId, email) {
393
+ return await this.redis.eval(CONSUME_AUTH_TOKEN, 2, `${this.prefix}${tokenId}`, `${this.prefix}email:${email.toLowerCase()}`, email, tokenId) === 1;
394
+ }
345
395
  async findByTokenId(tokenId) {
346
396
  const tokenKey = `${this.prefix}${tokenId}`;
347
397
  const data = await this.redis.get(tokenKey);