@venturekit/cli 0.0.0-dev.20260522121047 → 0.0.0-dev.20260602192622

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 (41) hide show
  1. package/dist/commands/dev.d.ts.map +1 -1
  2. package/dist/commands/dev.js +53 -1
  3. package/dist/commands/dev.js.map +1 -1
  4. package/dist/commands/migrate.d.ts.map +1 -1
  5. package/dist/commands/migrate.js +13 -5
  6. package/dist/commands/migrate.js.map +1 -1
  7. package/dist/commands/open.d.ts.map +1 -1
  8. package/dist/commands/open.js +5 -1
  9. package/dist/commands/open.js.map +1 -1
  10. package/dist/utils/auto-deps.d.ts.map +1 -1
  11. package/dist/utils/auto-deps.js +11 -0
  12. package/dist/utils/auto-deps.js.map +1 -1
  13. package/dist/utils/cdk-bridge.d.ts +1 -0
  14. package/dist/utils/cdk-bridge.d.ts.map +1 -1
  15. package/dist/utils/cdk-bridge.js +1 -0
  16. package/dist/utils/cdk-bridge.js.map +1 -1
  17. package/dist/utils/config-loader.d.ts +2 -0
  18. package/dist/utils/config-loader.d.ts.map +1 -1
  19. package/dist/utils/config-loader.js +2 -0
  20. package/dist/utils/config-loader.js.map +1 -1
  21. package/dist/utils/dev-cognito-ui-page.d.ts +1 -1
  22. package/dist/utils/dev-cognito-ui-page.d.ts.map +1 -1
  23. package/dist/utils/dev-cognito-ui-page.js +7 -2
  24. package/dist/utils/dev-cognito-ui-page.js.map +1 -1
  25. package/dist/utils/docker-compose.d.ts +13 -1
  26. package/dist/utils/docker-compose.d.ts.map +1 -1
  27. package/dist/utils/docker-compose.js +134 -34
  28. package/dist/utils/docker-compose.js.map +1 -1
  29. package/dist/utils/local-queue.d.ts +57 -29
  30. package/dist/utils/local-queue.d.ts.map +1 -1
  31. package/dist/utils/local-queue.js +257 -139
  32. package/dist/utils/local-queue.js.map +1 -1
  33. package/dist/utils/local-server.d.ts +20 -0
  34. package/dist/utils/local-server.d.ts.map +1 -1
  35. package/dist/utils/local-server.js +75 -6
  36. package/dist/utils/local-server.js.map +1 -1
  37. package/dist/utils/local-ws.d.ts +184 -0
  38. package/dist/utils/local-ws.d.ts.map +1 -0
  39. package/dist/utils/local-ws.js +667 -0
  40. package/dist/utils/local-ws.js.map +1 -0
  41. package/package.json +7 -5
@@ -1,27 +1,43 @@
1
1
  /**
2
- * Local Queue Processor
2
+ * Local Queue Processor — Redis-backed
3
3
  *
4
- * In-memory queue system for local development that mimics SQS behavior.
5
- * Messages are enqueued via the runtime's `queue.send()` or the HTTP API,
6
- * and dispatched to the matching queue handler automatically.
4
+ * Uses the Redis driver from `@venturekit/runtime/patterns` to faithfully
5
+ * replicate SQS semantics locally: visibility timeout, retry, dead-letter
6
+ * routing, delay queues, and at-least-once delivery.
7
+ *
8
+ * The runtime's `sendMessage()` writes directly to Redis; this processor
9
+ * polls Redis, invokes the matching queue handler with an SQS-shaped event,
10
+ * and acknowledges (deletes) or releases on failure.
11
+ *
12
+ * Failure model (mirrors SQS):
13
+ * - Handler returns OK → `deleteMessage` (ack).
14
+ * - Handler throws + receiveCount < maxRetries
15
+ * → `changeMessageVisibility(0)` returns the
16
+ * message to the visible queue for retry.
17
+ * - Handler throws + receiveCount ≥ maxRetries
18
+ * → append to in-memory DLQ (`dlqLog`) and
19
+ * `deleteMessage` so the queue stops looping.
7
20
  *
8
21
  * Features:
9
- * - In-memory FIFO queue per handler
10
- * - Automatic retry with backoff on handler failure
11
- * - Dead-letter logging after max retries
12
- * - Batch delivery (configurable batch size)
13
- * - HTTP API: POST /_dev/queue/{name} to enqueue messages
22
+ * - Redis-backed persistence (survives dev-server restarts)
23
+ * - Visibility timeout — messages hidden while being processed
24
+ * - Automatic retry with configurable `maxReceiveCount`
25
+ * - In-memory DLQ mirror (visible via `/_dev/queues`)
26
+ * - Delay queue support (DelaySeconds)
27
+ * - At-least-once delivery guarantee
28
+ * - HTTP API: POST /_dev/queue/{name} to enqueue via Redis
14
29
  */
15
- interface QueueMessage {
16
- id: string;
17
- body: string;
18
- enqueuedAt: number;
19
- attempts: number;
20
- nextRetryAt: number;
21
- }
22
30
  interface QueueDef {
23
31
  name: string;
24
32
  handlerFile: string;
33
+ /**
34
+ * Per-queue config sourced from `config.infrastructure.queues` in
35
+ * `vk.config.ts`. Falls back to processor-wide defaults when omitted.
36
+ */
37
+ config?: {
38
+ visibilityTimeoutSeconds?: number;
39
+ batchSize?: number;
40
+ };
25
41
  }
26
42
  interface LocalQueueOptions {
27
43
  /** Max delivery attempts before DLQ (default: 3) */
@@ -30,28 +46,40 @@ interface LocalQueueOptions {
30
46
  batchSize?: number;
31
47
  /** Poll interval in ms (default: 500) */
32
48
  pollIntervalMs?: number;
49
+ /** Visibility timeout in seconds (default: 30) */
50
+ visibilityTimeout?: number;
51
+ /** Redis URL (default: from VENTURE_REDIS_URL or VENTURE_QUEUE_REDIS_HOST/PORT) */
52
+ redisUrl?: string;
53
+ }
54
+ interface DlqEntry {
55
+ queueName: string;
56
+ messageId: string;
57
+ body: unknown;
58
+ error: string;
59
+ attempts: number;
60
+ deadLetteredAt: number;
61
+ }
62
+ interface QueueStatsRow {
63
+ pending: number;
64
+ inflight: number;
65
+ delayed: number;
66
+ dlq: number;
33
67
  }
34
68
  /**
35
- * Create a local queue processor.
69
+ * Create a Redis-backed local queue processor.
36
70
  *
37
- * Returns an object with methods to enqueue messages and start/stop processing.
71
+ * Returns an object with methods to enqueue messages, start/stop polling,
72
+ * inspect DLQ contents, and query per-queue stats.
38
73
  */
39
74
  export declare function createLocalQueueProcessor(options?: LocalQueueOptions): {
40
75
  registerQueues: (queueDefs: QueueDef[]) => void;
41
76
  setHandlerLoader: (loader: (file: string) => Promise<Function | null>) => void;
42
- enqueue: (queueName: string, body: unknown) => string;
77
+ enqueue: (queueName: string, body: unknown) => Promise<string>;
43
78
  start: (projectName: string, stage: string) => void;
44
- stop: () => void;
79
+ stop: () => Promise<void>;
45
80
  clearHandlerCache: () => void;
46
- getDlq: () => {
47
- queueName: string;
48
- message: QueueMessage;
49
- error: string;
50
- }[];
51
- getStats: () => Record<string, {
52
- pending: number;
53
- dlq: number;
54
- }>;
81
+ getDlq: () => DlqEntry[];
82
+ getStats: () => Promise<Record<string, QueueStatsRow>>;
55
83
  };
56
84
  export type LocalQueueProcessor = ReturnType<typeof createLocalQueueProcessor>;
57
85
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"local-queue.d.ts","sourceRoot":"","sources":["../../src/utils/local-queue.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAKH,UAAU,YAAY;IACpB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,UAAU,QAAQ;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,UAAU,iBAAiB;IACzB,oDAAoD;IACpD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,2CAA2C;IAC3C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,yCAAyC;IACzC,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,GAAE,iBAAsB;gCAqBpC,QAAQ,EAAE,KAAG,IAAI;+BAYlB,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAG,IAAI;yBAOvD,MAAM,QAAQ,OAAO,KAAG,MAAM;yBA8I9B,MAAM,SAAS,MAAM,KAAG,IAAI;gBAavC,IAAI;6BAWS,IAAI;;mBAlMJ,MAAM;iBAAW,YAAY;eAAS,MAAM;;;iBAiNjC,MAAM;aAAO,MAAM;;EAoB7D;AAED,MAAM,MAAM,mBAAmB,GAAG,UAAU,CAAC,OAAO,yBAAyB,CAAC,CAAC"}
1
+ {"version":3,"file":"local-queue.d.ts","sourceRoot":"","sources":["../../src/utils/local-queue.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAUH,UAAU,QAAQ;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB;;;OAGG;IACH,MAAM,CAAC,EAAE;QACP,wBAAwB,CAAC,EAAE,MAAM,CAAC;QAClC,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,CAAC;CACH;AAED,UAAU,iBAAiB;IACzB,oDAAoD;IACpD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,2CAA2C;IAC3C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,yCAAyC;IACzC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,kDAAkD;IAClD,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,mFAAmF;IACnF,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,UAAU,QAAQ;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,UAAU,aAAa;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,GAAE,iBAAsB;gCA+DpC,QAAQ,EAAE,KAAG,IAAI;+BAalB,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAG,IAAI;yBASjD,MAAM,QAAQ,OAAO,KAAG,OAAO,CAAC,MAAM,CAAC;yBAiM7C,MAAM,SAAS,MAAM,KAAG,IAAI;gBAmBjC,OAAO,CAAC,IAAI,CAAC;6BAgBN,IAAI;kBAOf,QAAQ,EAAE;oBASF,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;EAmClE;AAED,MAAM,MAAM,mBAAmB,GAAG,UAAU,CAAC,OAAO,yBAAyB,CAAC,CAAC"}
@@ -1,48 +1,102 @@
1
1
  /**
2
- * Local Queue Processor
2
+ * Local Queue Processor — Redis-backed
3
3
  *
4
- * In-memory queue system for local development that mimics SQS behavior.
5
- * Messages are enqueued via the runtime's `queue.send()` or the HTTP API,
6
- * and dispatched to the matching queue handler automatically.
4
+ * Uses the Redis driver from `@venturekit/runtime/patterns` to faithfully
5
+ * replicate SQS semantics locally: visibility timeout, retry, dead-letter
6
+ * routing, delay queues, and at-least-once delivery.
7
+ *
8
+ * The runtime's `sendMessage()` writes directly to Redis; this processor
9
+ * polls Redis, invokes the matching queue handler with an SQS-shaped event,
10
+ * and acknowledges (deletes) or releases on failure.
11
+ *
12
+ * Failure model (mirrors SQS):
13
+ * - Handler returns OK → `deleteMessage` (ack).
14
+ * - Handler throws + receiveCount < maxRetries
15
+ * → `changeMessageVisibility(0)` returns the
16
+ * message to the visible queue for retry.
17
+ * - Handler throws + receiveCount ≥ maxRetries
18
+ * → append to in-memory DLQ (`dlqLog`) and
19
+ * `deleteMessage` so the queue stops looping.
7
20
  *
8
21
  * Features:
9
- * - In-memory FIFO queue per handler
10
- * - Automatic retry with backoff on handler failure
11
- * - Dead-letter logging after max retries
12
- * - Batch delivery (configurable batch size)
13
- * - HTTP API: POST /_dev/queue/{name} to enqueue messages
22
+ * - Redis-backed persistence (survives dev-server restarts)
23
+ * - Visibility timeout — messages hidden while being processed
24
+ * - Automatic retry with configurable `maxReceiveCount`
25
+ * - In-memory DLQ mirror (visible via `/_dev/queues`)
26
+ * - Delay queue support (DelaySeconds)
27
+ * - At-least-once delivery guarantee
28
+ * - HTTP API: POST /_dev/queue/{name} to enqueue via Redis
14
29
  */
15
30
  import * as crypto from 'crypto';
16
31
  import chalk from 'chalk';
17
32
  /**
18
- * Create a local queue processor.
33
+ * Create a Redis-backed local queue processor.
19
34
  *
20
- * Returns an object with methods to enqueue messages and start/stop processing.
35
+ * Returns an object with methods to enqueue messages, start/stop polling,
36
+ * inspect DLQ contents, and query per-queue stats.
21
37
  */
22
38
  export function createLocalQueueProcessor(options = {}) {
23
39
  const maxRetries = options.maxRetries ?? 3;
24
40
  const batchSize = options.batchSize ?? 1;
25
41
  const pollIntervalMs = options.pollIntervalMs ?? 500;
26
- // Per-queue message buffers
27
- const queues = new Map();
42
+ const visibilityTimeout = options.visibilityTimeout ?? 30;
43
+ // Typed driver handle — `any` here was a major footgun in the original
44
+ // patch because it silenced the `changeMessageVisibility(... , 0)` arity
45
+ // bug at compile time.
46
+ let _driver = null;
28
47
  // Registered handler functions (resolved lazily)
29
48
  const handlers = new Map();
30
49
  // Handler file paths (for lazy loading)
31
50
  const handlerFiles = new Map();
32
- // Dead letter queue
33
- const dlq = [];
51
+ // Registered queue names
52
+ const queueNames = new Set();
53
+ // Per-queue config sourced from vk.config.ts
54
+ const queueConfigs = new Map();
55
+ // In-memory DLQ mirror. Populated by `processAll` on the max-retry branch
56
+ // so `/_dev/queues` has something to show. The runtime driver also keeps a
57
+ // Redis-side DLQ list (`vk:q:<queueId>:dlq`) for inspection from Redis CLI.
58
+ const dlqLog = [];
34
59
  let _running = false;
60
+ let _draining = false; // single-flight guard for `processAll`
35
61
  let _timer = null;
36
62
  let _loadHandler = null;
63
+ function buildDriverQueueConfigs() {
64
+ const map = {};
65
+ for (const name of queueNames) {
66
+ const cfg = queueConfigs.get(name);
67
+ map[name] = {
68
+ id: name,
69
+ visibilityTimeout: cfg?.visibilityTimeoutSeconds ?? visibilityTimeout,
70
+ maxReceiveCount: maxRetries,
71
+ };
72
+ }
73
+ return map;
74
+ }
75
+ async function getDriver() {
76
+ if (!_driver) {
77
+ // Dynamic import — runtime is a devDep of the CLI in the workspace, and
78
+ // a resolved peer in consumer projects via `ensureDependencies`.
79
+ const { createRedisDriver } = await import('@venturekit/runtime/patterns');
80
+ _driver = createRedisDriver({
81
+ url: options.redisUrl,
82
+ keyPrefix: 'vk:q',
83
+ reclaimIntervalMs: 1000,
84
+ queues: buildDriverQueueConfigs(),
85
+ });
86
+ }
87
+ return _driver;
88
+ }
37
89
  /**
38
- * Register queue handlers from discovered queue definitions.
90
+ * Register queue handlers from discovered queue definitions. Safe to call
91
+ * repeatedly — used by the dev server on file-watcher add/remove events.
39
92
  */
40
93
  function registerQueues(queueDefs) {
41
94
  for (const q of queueDefs) {
42
- if (!queues.has(q.name)) {
43
- queues.set(q.name, []);
44
- }
95
+ queueNames.add(q.name);
45
96
  handlerFiles.set(q.name, q.handlerFile);
97
+ if (q.config) {
98
+ queueConfigs.set(q.name, q.config);
99
+ }
46
100
  }
47
101
  }
48
102
  /**
@@ -52,153 +106,202 @@ export function createLocalQueueProcessor(options = {}) {
52
106
  _loadHandler = loader;
53
107
  }
54
108
  /**
55
- * Enqueue a message to a named queue.
109
+ * Enqueue a message to a named queue via Redis. Rejects with a clear error
110
+ * for unknown queues so misconfigured callers don't silently dead-letter
111
+ * messages into untracked Redis keys.
56
112
  */
57
- function enqueue(queueName, body) {
58
- const id = crypto.randomUUID();
59
- const message = {
60
- id,
61
- body: typeof body === 'string' ? body : JSON.stringify(body),
62
- enqueuedAt: Date.now(),
63
- attempts: 0,
64
- nextRetryAt: 0,
65
- };
66
- let queue = queues.get(queueName);
67
- if (!queue) {
68
- queue = [];
69
- queues.set(queueName, queue);
113
+ async function enqueue(queueName, body) {
114
+ if (!queueNames.has(queueName)) {
115
+ throw new Error(`Unknown queue "${queueName}". Declared queues: ${[...queueNames].join(', ') || '(none)'}`);
70
116
  }
71
- queue.push(message);
72
- console.log(chalk.gray(` ENQUEUE `) +
117
+ const driver = await getDriver();
118
+ const result = await driver.sendMessage(queueName, body);
119
+ console.log(chalk.gray(' ENQUEUE ') +
73
120
  chalk.cyan(queueName) +
74
- chalk.gray(` msg:${id.slice(0, 8)}`));
75
- return id;
121
+ chalk.gray(` msg:${result.messageId.slice(0, 8)}`));
122
+ return result.messageId;
76
123
  }
77
124
  /**
78
- * Process pending messages for all queues.
125
+ * Process pending messages for all registered queues.
126
+ *
127
+ * Single-flight guard (`_draining`) prevents the next interval tick from
128
+ * piling on while the previous run is still awaiting Redis or the handler.
129
+ * Without this guard, two `setInterval` ticks would each invoke
130
+ * `receiveMessage` against the same queue and double-deliver every message.
79
131
  */
80
132
  async function processAll(projectName, stage) {
81
- const now = Date.now();
82
- for (const [queueName, queue] of queues.entries()) {
83
- if (queue.length === 0)
84
- continue;
85
- // Collect ready messages (not waiting for retry backoff)
86
- const ready = queue.filter(m => m.nextRetryAt <= now);
87
- if (ready.length === 0)
88
- continue;
89
- // Take a batch
90
- const batch = ready.slice(0, batchSize);
91
- // Get or load handler
92
- let handlerFn = handlers.get(queueName);
93
- if (!handlerFn) {
94
- const file = handlerFiles.get(queueName);
95
- if (!file || !_loadHandler)
96
- continue;
97
- handlerFn = await _loadHandler(file);
98
- if (!handlerFn)
133
+ if (_draining)
134
+ return;
135
+ _draining = true;
136
+ try {
137
+ const driver = await getDriver();
138
+ for (const queueName of queueNames) {
139
+ const cfg = queueConfigs.get(queueName);
140
+ const queueVisibilityTimeout = cfg?.visibilityTimeoutSeconds ?? visibilityTimeout;
141
+ const queueBatchSize = cfg?.batchSize ?? batchSize;
142
+ const messages = await driver.receiveMessage(queueName, {
143
+ maxMessages: queueBatchSize,
144
+ visibilityTimeout: queueVisibilityTimeout,
145
+ waitTimeSeconds: 0,
146
+ });
147
+ if (messages.length === 0)
99
148
  continue;
100
- handlers.set(queueName, handlerFn);
149
+ let handlerFn = handlers.get(queueName);
150
+ if (!handlerFn) {
151
+ const file = handlerFiles.get(queueName);
152
+ if (!file || !_loadHandler)
153
+ continue;
154
+ const loaded = await _loadHandler(file);
155
+ if (!loaded)
156
+ continue;
157
+ handlerFn = loaded;
158
+ handlers.set(queueName, handlerFn);
159
+ }
160
+ const sqsEvent = buildSqsEvent(projectName, stage, queueName, messages);
161
+ const context = buildLambdaContext(projectName, stage, queueName);
162
+ const start = Date.now();
163
+ try {
164
+ await handlerFn(sqsEvent, context);
165
+ const duration = Date.now() - start;
166
+ for (const msg of messages) {
167
+ await driver.deleteMessage(queueName, msg.receiptHandle);
168
+ }
169
+ console.log(chalk.gray(' QUEUE ') +
170
+ chalk.cyan(queueName) +
171
+ chalk.gray(` [${messages.length} msg] → `) +
172
+ chalk.green('OK') +
173
+ chalk.gray(` (${duration}ms)`));
174
+ }
175
+ catch (err) {
176
+ const duration = Date.now() - start;
177
+ const errMsg = err instanceof Error ? err.message : String(err);
178
+ console.error(chalk.gray(' QUEUE ') +
179
+ chalk.cyan(queueName) +
180
+ chalk.gray(` [${messages.length} msg] → `) +
181
+ chalk.red('ERROR') +
182
+ chalk.gray(` (${duration}ms)`));
183
+ console.error(chalk.red(` ${errMsg}`));
184
+ await handleBatchFailure(driver, queueName, messages, errMsg);
185
+ }
101
186
  }
102
- // Build SQS-like event
103
- const sqsEvent = {
104
- Records: batch.map((msg, i) => ({
105
- messageId: msg.id,
106
- receiptHandle: `local-${msg.id}`,
187
+ }
188
+ finally {
189
+ _draining = false;
190
+ }
191
+ }
192
+ /**
193
+ * Decide what to do with each message in a failed batch.
194
+ *
195
+ * - At-or-past max retries → push to in-memory DLQ + delete (stop looping).
196
+ * - Otherwise → release with `visibilityTimeout: 0` so the
197
+ * next poll picks it up immediately.
198
+ *
199
+ * `approximateReceiveCount` is the post-increment value the driver already
200
+ * recorded on this receive — DO NOT add `+ 1` here (the original patch did,
201
+ * which caused DLQ to fire after 2 attempts instead of 3).
202
+ */
203
+ async function handleBatchFailure(driver, queueName, messages, error) {
204
+ for (const msg of messages) {
205
+ const attempts = msg.approximateReceiveCount;
206
+ if (attempts >= maxRetries) {
207
+ dlqLog.push({
208
+ queueName,
209
+ messageId: msg.messageId,
107
210
  body: msg.body,
211
+ error,
212
+ attempts,
213
+ deadLetteredAt: Date.now(),
214
+ });
215
+ await driver.deleteMessage(queueName, msg.receiptHandle);
216
+ console.log(chalk.yellow(' DLQ ') +
217
+ chalk.cyan(queueName) +
218
+ chalk.gray(` msg:${msg.messageId.slice(0, 8)} after ${attempts} attempts`));
219
+ }
220
+ else {
221
+ // SQS semantics: `ChangeMessageVisibility(0)` releases the message
222
+ // back to the visible queue immediately. Driver's Lua script does
223
+ // the inflight→visible transition atomically — see
224
+ // `CHANGE_VISIBILITY_SCRIPT` in `runtime/queue/drivers/redis.ts`.
225
+ await driver.changeMessageVisibility(queueName, msg.receiptHandle, {
226
+ visibilityTimeout: 0,
227
+ });
228
+ console.log(chalk.gray(' RETRY ') +
229
+ chalk.cyan(queueName) +
230
+ chalk.gray(` msg:${msg.messageId.slice(0, 8)} attempt ${attempts}/${maxRetries}`));
231
+ }
232
+ }
233
+ }
234
+ function buildSqsEvent(projectName, stage, queueName, messages) {
235
+ return {
236
+ Records: messages.map((msg) => {
237
+ const bodyStr = typeof msg.body === 'string' ? msg.body : JSON.stringify(msg.body);
238
+ return {
239
+ messageId: msg.messageId,
240
+ receiptHandle: msg.receiptHandle,
241
+ body: bodyStr,
108
242
  attributes: {
109
- ApproximateReceiveCount: String(msg.attempts + 1),
110
- SentTimestamp: String(msg.enqueuedAt),
111
- ApproximateFirstReceiveTimestamp: String(now),
243
+ ApproximateReceiveCount: String(msg.approximateReceiveCount),
244
+ SentTimestamp: String(msg.sentTimestamp),
245
+ ApproximateFirstReceiveTimestamp: String(msg.approximateFirstReceiveTimestamp),
112
246
  },
113
247
  messageAttributes: {},
114
248
  md5OfBody: '',
115
249
  eventSource: 'aws:sqs',
116
250
  eventSourceARN: `arn:aws:sqs:local:000000000000:${projectName}-${stage}-${queueName}`,
117
251
  awsRegion: 'local',
118
- })),
119
- };
120
- const context = {
121
- callbackWaitsForEmptyEventLoop: true,
122
- functionName: `${projectName}-${stage}-queue-${queueName}`,
123
- functionVersion: '$LATEST',
124
- invokedFunctionArn: `arn:aws:lambda:local:000000000000:function:${projectName}-${stage}-queue-${queueName}`,
125
- memoryLimitInMB: '256',
126
- awsRequestId: crypto.randomUUID(),
127
- logGroupName: `/aws/lambda/${projectName}-${stage}-queue-${queueName}`,
128
- logStreamName: `local/${crypto.randomUUID()}`,
129
- getRemainingTimeInMillis: () => 30000,
130
- done: () => { },
131
- fail: () => { },
132
- succeed: () => { },
133
- };
134
- const start = Date.now();
135
- try {
136
- await handlerFn(sqsEvent, context);
137
- const duration = Date.now() - start;
138
- console.log(chalk.gray(` QUEUE `) +
139
- chalk.cyan(queueName) +
140
- chalk.gray(` [${batch.length} msg] → `) +
141
- chalk.green('OK') +
142
- chalk.gray(` (${duration}ms)`));
143
- // Remove processed messages from queue
144
- for (const msg of batch) {
145
- const idx = queue.indexOf(msg);
146
- if (idx >= 0)
147
- queue.splice(idx, 1);
148
- }
149
- }
150
- catch (err) {
151
- const duration = Date.now() - start;
152
- const errMsg = err instanceof Error ? err.message : String(err);
153
- console.error(chalk.gray(` QUEUE `) +
154
- chalk.cyan(queueName) +
155
- chalk.gray(` [${batch.length} msg] → `) +
156
- chalk.red('ERROR') +
157
- chalk.gray(` (${duration}ms)`));
158
- console.error(chalk.red(` ${errMsg}`));
159
- // Retry or DLQ
160
- for (const msg of batch) {
161
- msg.attempts++;
162
- if (msg.attempts >= maxRetries) {
163
- // Move to DLQ
164
- const idx = queue.indexOf(msg);
165
- if (idx >= 0)
166
- queue.splice(idx, 1);
167
- dlq.push({ queueName, message: msg, error: errMsg });
168
- console.log(chalk.yellow(` DLQ `) +
169
- chalk.cyan(queueName) +
170
- chalk.gray(` msg:${msg.id.slice(0, 8)} after ${msg.attempts} attempts`));
171
- }
172
- else {
173
- // Exponential backoff: 1s, 4s, 9s ...
174
- msg.nextRetryAt = Date.now() + (msg.attempts * msg.attempts * 1000);
175
- }
176
- }
177
- }
178
- }
252
+ };
253
+ }),
254
+ };
255
+ }
256
+ function buildLambdaContext(projectName, stage, queueName) {
257
+ return {
258
+ callbackWaitsForEmptyEventLoop: true,
259
+ functionName: `${projectName}-${stage}-queue-${queueName}`,
260
+ functionVersion: '$LATEST',
261
+ invokedFunctionArn: `arn:aws:lambda:local:000000000000:function:${projectName}-${stage}-queue-${queueName}`,
262
+ memoryLimitInMB: '256',
263
+ awsRequestId: crypto.randomUUID(),
264
+ logGroupName: `/aws/lambda/${projectName}-${stage}-queue-${queueName}`,
265
+ logStreamName: `local/${crypto.randomUUID()}`,
266
+ getRemainingTimeInMillis: () => 30000,
267
+ done: () => { },
268
+ fail: () => { },
269
+ succeed: () => { },
270
+ };
179
271
  }
180
272
  /**
181
- * Start polling for messages.
273
+ * Start polling Redis for messages.
182
274
  */
183
275
  function start(projectName, stage) {
184
276
  if (_running)
185
277
  return;
186
278
  _running = true;
187
279
  _timer = setInterval(() => {
188
- processAll(projectName, stage).catch(err => {
280
+ processAll(projectName, stage).catch((err) => {
189
281
  console.error(chalk.red(` Queue processor error: ${err instanceof Error ? err.message : err}`));
190
282
  });
191
283
  }, pollIntervalMs);
284
+ // Don't keep Node alive for this timer.
285
+ if (typeof _timer.unref === 'function') {
286
+ _timer.unref();
287
+ }
192
288
  }
193
289
  /**
194
- * Stop the processor.
290
+ * Stop the processor and close the Redis connection. Safe to call multiple
291
+ * times. The dev server awaits this from its SIGINT cleanup hook so the
292
+ * Redis socket + reclaim timer don't outlive the dev server.
195
293
  */
196
- function stop() {
294
+ async function stop() {
197
295
  _running = false;
198
296
  if (_timer) {
199
297
  clearInterval(_timer);
200
298
  _timer = null;
201
299
  }
300
+ const driver = _driver;
301
+ _driver = null;
302
+ if (driver) {
303
+ await driver.close();
304
+ }
202
305
  }
203
306
  /**
204
307
  * Clear handler cache (for hot reload).
@@ -207,21 +310,36 @@ export function createLocalQueueProcessor(options = {}) {
207
310
  handlers.clear();
208
311
  }
209
312
  /**
210
- * Get DLQ contents for debugging.
313
+ * Get DLQ contents for debugging. Returns a shallow copy.
211
314
  */
212
315
  function getDlq() {
213
- return [...dlq];
316
+ return [...dlqLog];
214
317
  }
215
318
  /**
216
- * Get queue stats.
319
+ * Get queue stats (queries Redis for live counts). When Redis is
320
+ * unreachable, every queue is reported with zeros and the error is logged
321
+ * to the console so the developer knows the dev server lost Redis.
217
322
  */
218
- function getStats() {
323
+ async function getStats() {
219
324
  const stats = {};
220
- for (const [name, queue] of queues.entries()) {
221
- stats[name] = {
222
- pending: queue.length,
223
- dlq: dlq.filter(d => d.queueName === name).length,
224
- };
325
+ try {
326
+ const driver = await getDriver();
327
+ for (const name of queueNames) {
328
+ const s = await driver.getQueueStats(name);
329
+ stats[name] = {
330
+ pending: s.approximateMessageCount,
331
+ inflight: s.approximateInflightCount,
332
+ delayed: s.approximateDelayedCount,
333
+ dlq: dlqLog.filter((d) => d.queueName === name).length,
334
+ };
335
+ }
336
+ }
337
+ catch (err) {
338
+ console.error(chalk.gray(' /_dev/queues stats: ') +
339
+ chalk.yellow(err instanceof Error ? err.message : String(err)));
340
+ for (const name of queueNames) {
341
+ stats[name] = { pending: 0, inflight: 0, delayed: 0, dlq: 0 };
342
+ }
225
343
  }
226
344
  return stats;
227
345
  }