@rdlabo/workers-hono-kit 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -29,6 +29,10 @@ export type { KVNamespace, KVCacheOptions } from './cache/kv-cache.js';
29
29
  export { createStripeClient, verifyStripeWebhook } from './stripe/client.js';
30
30
  export type { CreateStripeClientOptions } from './stripe/client.js';
31
31
  export { retryWhenDeadlock } from './db/retry.js';
32
+ export { sendInChunks } from './queue/send.js';
33
+ export type { QueueLike, QueueSendMessage } from './queue/send.js';
34
+ export { processBatch } from './queue/consumer.js';
35
+ export type { QueueMessageLike, MessageBatchLike, ProcessBatchOptions, ProcessBatchResult } from './queue/consumer.js';
32
36
  export { createAiGatewayProvider } from './ai/gateway.js';
33
37
  export type { AiGatewayConfig, AiGatewayProvider, AiGatewayBinding, AiGateway, AiGatewayOptions, } from './ai/gateway.js';
34
38
  export { getAuthenticationSecret } from './aws/secrets-manager.js';
package/dist/index.js CHANGED
@@ -26,6 +26,9 @@ export { KVCache } from './cache/kv-cache.js';
26
26
  export { createStripeClient, verifyStripeWebhook } from './stripe/client.js';
27
27
  // db
28
28
  export { retryWhenDeadlock } from './db/retry.js';
29
+ // queue
30
+ export { sendInChunks } from './queue/send.js';
31
+ export { processBatch } from './queue/consumer.js';
29
32
  // ai
30
33
  export { createAiGatewayProvider } from './ai/gateway.js';
31
34
  // aws
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Consumer-side helper for processing a Cloudflare Queues `MessageBatch` with per-message success and
3
+ * failure handling.
4
+ *
5
+ * A queue consumer invocation receives at most `max_batch_size` messages (configured in
6
+ * `wrangler.toml`), which is precisely the mechanism that bounds its subrequest budget: with a small
7
+ * `max_batch_size`, each invocation performs a fixed, small number of external calls no matter how
8
+ * many messages are backed up in the queue. {@link processBatch} applies the standard
9
+ * ack-on-success / retry-on-failure discipline so one poison message does not fail its whole batch.
10
+ *
11
+ * Messages are processed sequentially. This keeps the number of *simultaneously open* subrequests at
12
+ * one, staying well clear of the Workers concurrent-connection ceiling, and makes the per-invocation
13
+ * subrequest count deterministic (`<= max_batch_size`). For a queue consumer — which is not on a
14
+ * user-facing latency path — sequential processing is the safer default.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * // Worker `queue` handler
19
+ * export default {
20
+ * async queue(batch: MessageBatchLike<{ userId: number }>, env: Env) {
21
+ * await processBatch(batch, async ({ userId }) => {
22
+ * await reloadOneCustomer(env, userId); // exactly one external payment call
23
+ * });
24
+ * },
25
+ * };
26
+ * ```
27
+ *
28
+ * @packageDocumentation
29
+ */
30
+ /**
31
+ * Minimal subset of `@cloudflare/workers-types`' `Message` used by {@link processBatch}.
32
+ *
33
+ * Declared locally so consumers are not forced to depend on `@cloudflare/workers-types`.
34
+ *
35
+ * @typeParam Body - Type of the message body.
36
+ */
37
+ export interface QueueMessageLike<Body = unknown> {
38
+ /** Unique id assigned by the Queues runtime. */
39
+ readonly id: string;
40
+ /** Number of delivery attempts so far (starts at 1 on first delivery). */
41
+ readonly attempts: number;
42
+ /** The message payload. */
43
+ readonly body: Body;
44
+ /** Explicitly acknowledge this message so it is not redelivered. */
45
+ ack: () => void;
46
+ /** Mark this message for redelivery, optionally after a delay. */
47
+ retry: (options?: {
48
+ delaySeconds?: number;
49
+ }) => void;
50
+ }
51
+ /**
52
+ * Minimal subset of `@cloudflare/workers-types`' `MessageBatch` used by {@link processBatch}.
53
+ *
54
+ * @typeParam Body - Type of each message body in the batch.
55
+ */
56
+ export interface MessageBatchLike<Body = unknown> {
57
+ /** Name of the queue this batch was delivered from. */
58
+ readonly queue: string;
59
+ /** The messages in this batch; length is bounded by the consumer's `max_batch_size`. */
60
+ readonly messages: readonly QueueMessageLike<Body>[];
61
+ }
62
+ /**
63
+ * Options for {@link processBatch}.
64
+ *
65
+ * @typeParam Body - Type of each message body.
66
+ */
67
+ export interface ProcessBatchOptions<Body = unknown> {
68
+ /**
69
+ * Invoked when `handler` throws for a message, immediately before the message is marked for retry.
70
+ * Use it to log or report; it must not throw. Defaults to `console.error`.
71
+ */
72
+ onError?: (error: unknown, message: QueueMessageLike<Body>) => void;
73
+ /**
74
+ * Delay, in seconds, applied when re-queuing a failed message. Omit to retry with the queue's
75
+ * default backoff.
76
+ */
77
+ retryDelaySeconds?: number;
78
+ }
79
+ /**
80
+ * Outcome counts returned by {@link processBatch}.
81
+ */
82
+ export interface ProcessBatchResult {
83
+ /** Messages whose handler completed successfully and were acked. */
84
+ processed: number;
85
+ /** Messages whose handler threw and were marked for retry. */
86
+ failed: number;
87
+ }
88
+ /**
89
+ * Process every message in `batch` sequentially, acking on success and retrying on failure.
90
+ *
91
+ * Each message is passed to `handler`; if it resolves the message is acked, and if it throws the
92
+ * error is routed to {@link ProcessBatchOptions.onError} and the message is marked for retry (honoring
93
+ * {@link ProcessBatchOptions.retryDelaySeconds}). One failing message never affects the others, and
94
+ * the returned counts let tests assert that the per-invocation workload — and therefore the
95
+ * subrequest count — stayed bounded by the batch size.
96
+ *
97
+ * @typeParam Body - Type of each message body.
98
+ * @param batch - The delivered message batch.
99
+ * @param handler - Async work for a single message; performs the bounded external call(s). Receives
100
+ * the decoded `body` and the raw message (for `attempts`, `id`, etc.).
101
+ * @param options - Error reporting and retry tuning; see {@link ProcessBatchOptions}.
102
+ * @returns The number of processed and failed messages.
103
+ * @example
104
+ * ```ts
105
+ * const { processed, failed } = await processBatch(
106
+ * batch,
107
+ * async ({ id }) => sendOneMail(id),
108
+ * { retryDelaySeconds: 30, onError: (e, m) => report(e, m.id) },
109
+ * );
110
+ * ```
111
+ */
112
+ export declare function processBatch<Body>(batch: MessageBatchLike<Body>, handler: (body: Body, message: QueueMessageLike<Body>) => Promise<void>, options?: ProcessBatchOptions<Body>): Promise<ProcessBatchResult>;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Consumer-side helper for processing a Cloudflare Queues `MessageBatch` with per-message success and
3
+ * failure handling.
4
+ *
5
+ * A queue consumer invocation receives at most `max_batch_size` messages (configured in
6
+ * `wrangler.toml`), which is precisely the mechanism that bounds its subrequest budget: with a small
7
+ * `max_batch_size`, each invocation performs a fixed, small number of external calls no matter how
8
+ * many messages are backed up in the queue. {@link processBatch} applies the standard
9
+ * ack-on-success / retry-on-failure discipline so one poison message does not fail its whole batch.
10
+ *
11
+ * Messages are processed sequentially. This keeps the number of *simultaneously open* subrequests at
12
+ * one, staying well clear of the Workers concurrent-connection ceiling, and makes the per-invocation
13
+ * subrequest count deterministic (`<= max_batch_size`). For a queue consumer — which is not on a
14
+ * user-facing latency path — sequential processing is the safer default.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * // Worker `queue` handler
19
+ * export default {
20
+ * async queue(batch: MessageBatchLike<{ userId: number }>, env: Env) {
21
+ * await processBatch(batch, async ({ userId }) => {
22
+ * await reloadOneCustomer(env, userId); // exactly one external payment call
23
+ * });
24
+ * },
25
+ * };
26
+ * ```
27
+ *
28
+ * @packageDocumentation
29
+ */
30
+ /**
31
+ * Process every message in `batch` sequentially, acking on success and retrying on failure.
32
+ *
33
+ * Each message is passed to `handler`; if it resolves the message is acked, and if it throws the
34
+ * error is routed to {@link ProcessBatchOptions.onError} and the message is marked for retry (honoring
35
+ * {@link ProcessBatchOptions.retryDelaySeconds}). One failing message never affects the others, and
36
+ * the returned counts let tests assert that the per-invocation workload — and therefore the
37
+ * subrequest count — stayed bounded by the batch size.
38
+ *
39
+ * @typeParam Body - Type of each message body.
40
+ * @param batch - The delivered message batch.
41
+ * @param handler - Async work for a single message; performs the bounded external call(s). Receives
42
+ * the decoded `body` and the raw message (for `attempts`, `id`, etc.).
43
+ * @param options - Error reporting and retry tuning; see {@link ProcessBatchOptions}.
44
+ * @returns The number of processed and failed messages.
45
+ * @example
46
+ * ```ts
47
+ * const { processed, failed } = await processBatch(
48
+ * batch,
49
+ * async ({ id }) => sendOneMail(id),
50
+ * { retryDelaySeconds: 30, onError: (e, m) => report(e, m.id) },
51
+ * );
52
+ * ```
53
+ */
54
+ export async function processBatch(batch, handler, options) {
55
+ const onError = options?.onError ??
56
+ ((error, message) => {
57
+ console.error(`[queue:${batch.queue}] message ${message.id} failed`, error);
58
+ });
59
+ const retryOptions = options?.retryDelaySeconds === undefined ? undefined : { delaySeconds: options.retryDelaySeconds };
60
+ let processed = 0;
61
+ let failed = 0;
62
+ for (const message of batch.messages) {
63
+ try {
64
+ await handler(message.body, message);
65
+ message.ack();
66
+ processed++;
67
+ }
68
+ catch (error) {
69
+ try {
70
+ onError(error, message);
71
+ }
72
+ catch {
73
+ // onError contract says "must not throw"; guard defensively so retry() and remaining messages still run.
74
+ }
75
+ message.retry(retryOptions);
76
+ failed++;
77
+ }
78
+ }
79
+ return { processed, failed };
80
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Producer-side helper for fanning a large list of items into a Cloudflare Queue without letting the
3
+ * producer's own subrequest count scale linearly with the list.
4
+ *
5
+ * A Worker may issue at most 50 (free) / 1000 (paid) subrequests per invocation, and each
6
+ * {@link QueueLike.send} counts as one subrequest. Enqueuing `N` items with per-item `send()` calls
7
+ * therefore reintroduces the very unbounded fan-out that queues exist to remove. {@link sendInChunks}
8
+ * instead groups items into batches and issues one {@link QueueLike.sendBatch} per batch, so the
9
+ * producer spends `ceil(N / chunkSize)` subrequests regardless of how large `N` grows.
10
+ *
11
+ * The heavy per-item work (external API calls, etc.) is expected to run in the queue *consumer*,
12
+ * where each invocation processes only `max_batch_size` messages and thus enjoys its own bounded
13
+ * subrequest budget. See {@link processBatch} for the consumer side.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * // In a Cron Trigger `scheduled` handler: enqueue every billing user, then let the consumer
18
+ * // re-derive payment state one user per message.
19
+ * const userIds = await query.getUserIdForReloadCustomer(); // DB read — not a subrequest
20
+ * await sendInChunks(env.PAYMENT_RELOAD_QUEUE, userIds); // ceil(N / 100) subrequests
21
+ * ```
22
+ *
23
+ * @packageDocumentation
24
+ */
25
+ /**
26
+ * Minimal subset of `@cloudflare/workers-types`' `Queue` used by {@link sendInChunks}.
27
+ *
28
+ * Declared locally so consumers are not forced to depend on `@cloudflare/workers-types`. Only the
29
+ * batch-send operation the helper actually needs is modeled.
30
+ *
31
+ * @typeParam Body - Type of each message body enqueued onto this queue.
32
+ */
33
+ export interface QueueLike<Body = unknown> {
34
+ /**
35
+ * Enqueue up to 100 messages in a single operation (one subrequest).
36
+ *
37
+ * @param messages - The message envelopes to enqueue; at most 100 per call, 256 KB per batch.
38
+ * @param options - Optional batch-level options, e.g. a `delaySeconds` applied to every message.
39
+ * @returns A promise that resolves once the batch is accepted. The resolved value is ignored, so a
40
+ * real `Queue` binding (whose `sendBatch` resolves to a `QueueSendBatchResponse`) is assignable.
41
+ */
42
+ sendBatch: (messages: Iterable<QueueSendMessage<Body>>, options?: {
43
+ delaySeconds?: number;
44
+ }) => Promise<unknown>;
45
+ }
46
+ /**
47
+ * A single message envelope passed to {@link QueueLike.sendBatch}.
48
+ *
49
+ * @typeParam Body - Type of the message body.
50
+ */
51
+ export interface QueueSendMessage<Body = unknown> {
52
+ /** The message payload; structured-cloned by the Queues runtime. */
53
+ body: Body;
54
+ /** Optional content type hint (`'json'` by default for object bodies). */
55
+ contentType?: 'text' | 'bytes' | 'json' | 'v8';
56
+ /** Optional per-message delivery delay, in seconds. */
57
+ delaySeconds?: number;
58
+ }
59
+ /**
60
+ * Enqueue every item in `items` using batched sends so the producer's subrequest count stays
61
+ * bounded at `ceil(items.length / chunkSize)` rather than growing per item.
62
+ *
63
+ * Each element becomes one queue message (`{ body: item }`); wrap or map your rows into small,
64
+ * self-describing payloads (e.g. an id plus a discriminator) before calling. Keep each batch under
65
+ * the Queues 256 KB limit — with `chunkSize <= 100` and small id-shaped payloads this is not a
66
+ * concern, but large bodies may require a smaller `chunkSize`.
67
+ *
68
+ * Batches are sent sequentially so a mid-list failure surfaces promptly (the already-sent batches
69
+ * are durably enqueued; the throw lets the caller decide whether to retry the remainder). An empty
70
+ * `items` is a no-op.
71
+ *
72
+ * @typeParam Body - Type of each message body.
73
+ * @param queue - The producer binding to send onto.
74
+ * @param items - The full list of message bodies to enqueue; may be arbitrarily large.
75
+ * @param options - Tuning options.
76
+ * @param options.chunkSize - Messages per `sendBatch` call. Defaults to and is capped at 100 (the
77
+ * Queues per-batch maximum); values below 1 are clamped to 1.
78
+ * @returns The number of `sendBatch` calls issued (i.e. subrequests spent), useful for asserting the
79
+ * fan-out stayed bounded in tests.
80
+ * @example
81
+ * ```ts
82
+ * const batches = await sendInChunks(env.MY_QUEUE, ids); // one send per 100 ids
83
+ * const batches = await sendInChunks(env.MY_QUEUE, rows, { // custom batch size for larger bodies
84
+ * chunkSize: 25,
85
+ * });
86
+ * ```
87
+ */
88
+ export declare function sendInChunks<Body>(queue: QueueLike<Body>, items: readonly Body[], options?: {
89
+ chunkSize?: number;
90
+ }): Promise<number>;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Producer-side helper for fanning a large list of items into a Cloudflare Queue without letting the
3
+ * producer's own subrequest count scale linearly with the list.
4
+ *
5
+ * A Worker may issue at most 50 (free) / 1000 (paid) subrequests per invocation, and each
6
+ * {@link QueueLike.send} counts as one subrequest. Enqueuing `N` items with per-item `send()` calls
7
+ * therefore reintroduces the very unbounded fan-out that queues exist to remove. {@link sendInChunks}
8
+ * instead groups items into batches and issues one {@link QueueLike.sendBatch} per batch, so the
9
+ * producer spends `ceil(N / chunkSize)` subrequests regardless of how large `N` grows.
10
+ *
11
+ * The heavy per-item work (external API calls, etc.) is expected to run in the queue *consumer*,
12
+ * where each invocation processes only `max_batch_size` messages and thus enjoys its own bounded
13
+ * subrequest budget. See {@link processBatch} for the consumer side.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * // In a Cron Trigger `scheduled` handler: enqueue every billing user, then let the consumer
18
+ * // re-derive payment state one user per message.
19
+ * const userIds = await query.getUserIdForReloadCustomer(); // DB read — not a subrequest
20
+ * await sendInChunks(env.PAYMENT_RELOAD_QUEUE, userIds); // ceil(N / 100) subrequests
21
+ * ```
22
+ *
23
+ * @packageDocumentation
24
+ */
25
+ /**
26
+ * The Cloudflare Queues hard limit on messages per {@link QueueLike.sendBatch} call.
27
+ */
28
+ const MAX_BATCH_SIZE = 100;
29
+ /**
30
+ * Split a list into fixed-size chunks (order preserving).
31
+ *
32
+ * @typeParam T - Element type.
33
+ * @param items - Source list.
34
+ * @param size - Maximum chunk length (assumed `>= 1`).
35
+ * @returns An array of chunks, each at most `size` long.
36
+ * @internal
37
+ */
38
+ function chunk(items, size) {
39
+ const result = [];
40
+ for (let i = 0; i < items.length; i += size) {
41
+ result.push(items.slice(i, i + size));
42
+ }
43
+ return result;
44
+ }
45
+ /**
46
+ * Enqueue every item in `items` using batched sends so the producer's subrequest count stays
47
+ * bounded at `ceil(items.length / chunkSize)` rather than growing per item.
48
+ *
49
+ * Each element becomes one queue message (`{ body: item }`); wrap or map your rows into small,
50
+ * self-describing payloads (e.g. an id plus a discriminator) before calling. Keep each batch under
51
+ * the Queues 256 KB limit — with `chunkSize <= 100` and small id-shaped payloads this is not a
52
+ * concern, but large bodies may require a smaller `chunkSize`.
53
+ *
54
+ * Batches are sent sequentially so a mid-list failure surfaces promptly (the already-sent batches
55
+ * are durably enqueued; the throw lets the caller decide whether to retry the remainder). An empty
56
+ * `items` is a no-op.
57
+ *
58
+ * @typeParam Body - Type of each message body.
59
+ * @param queue - The producer binding to send onto.
60
+ * @param items - The full list of message bodies to enqueue; may be arbitrarily large.
61
+ * @param options - Tuning options.
62
+ * @param options.chunkSize - Messages per `sendBatch` call. Defaults to and is capped at 100 (the
63
+ * Queues per-batch maximum); values below 1 are clamped to 1.
64
+ * @returns The number of `sendBatch` calls issued (i.e. subrequests spent), useful for asserting the
65
+ * fan-out stayed bounded in tests.
66
+ * @example
67
+ * ```ts
68
+ * const batches = await sendInChunks(env.MY_QUEUE, ids); // one send per 100 ids
69
+ * const batches = await sendInChunks(env.MY_QUEUE, rows, { // custom batch size for larger bodies
70
+ * chunkSize: 25,
71
+ * });
72
+ * ```
73
+ */
74
+ export async function sendInChunks(queue, items, options) {
75
+ if (items.length === 0) {
76
+ return 0;
77
+ }
78
+ const rawChunkSize = options?.chunkSize ?? MAX_BATCH_SIZE;
79
+ const chunkSize = Math.min(MAX_BATCH_SIZE, Math.max(1, Math.trunc(Number.isNaN(rawChunkSize) ? MAX_BATCH_SIZE : rawChunkSize)));
80
+ const batches = chunk(items, chunkSize);
81
+ for (const batch of batches) {
82
+ await queue.sendBatch(batch.map((body) => ({ body })));
83
+ }
84
+ return batches.length;
85
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rdlabo/workers-hono-kit",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -40,7 +40,8 @@
40
40
  "!src/**/*.spec.ts"
41
41
  ],
42
42
  "bin": {
43
- "workers-hono-kit-sync-dev-aws": "./scripts/sync-dev-aws.mjs"
43
+ "workers-hono-kit-sync-dev-aws": "./scripts/sync-dev-aws.mjs",
44
+ "workers-hono-kit-check-subrequest-fanout": "./scripts/check-subrequest-fanout.mjs"
44
45
  },
45
46
  "exports": {
46
47
  ".": {
@@ -0,0 +1,86 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * check-subrequest-fanout — flag per-item external-call fan-outs that scale with data size.
4
+ *
5
+ * Cloudflare Workers cap subrequests per invocation (50 free / 1000 paid). Looping an external call
6
+ * (fetch / AI / Stripe / push / ES) once per row reintroduces an unbounded fan-out that eventually
7
+ * exceeds the cap as the userbase/data grows. This gate greps for the concurrency-loop markers that
8
+ * usually wrap such fan-outs and fails CI unless the site is explicitly annotated as safe.
9
+ *
10
+ * Markers: `runWithConcurrency(`, `PromisePool`, `.withConcurrency(`.
11
+ *
12
+ * To allow a genuinely-safe site (e.g. the loop body only writes to the DB over TCP, which is NOT a
13
+ * subrequest, or the iteration count is hard-capped), put `subrequest-ok` in a comment on the same
14
+ * line or the line immediately above. Prefer a short reason, e.g. `// subrequest-ok: DB writes only`.
15
+ *
16
+ * Usage:
17
+ * node node_modules/@rdlabo/workers-hono-kit/scripts/check-subrequest-fanout.mjs [dir ...]
18
+ * Defaults to scanning `src`. Exits 1 if any un-annotated marker is found.
19
+ */
20
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
21
+ import { join } from 'node:path';
22
+
23
+ const MARKER = /runWithConcurrency\(|PromisePool|\.withConcurrency\(/;
24
+ const ALLOW = /subrequest-ok/;
25
+ const SKIP_DIRS = new Set(['node_modules', 'dist', '.git', 'coverage']);
26
+
27
+ /** Recursively collect .ts files (excluding *.spec.ts / *.test.ts). */
28
+ function collect(dir) {
29
+ const out = [];
30
+ let entries;
31
+ try {
32
+ entries = readdirSync(dir);
33
+ } catch {
34
+ return out;
35
+ }
36
+ for (const name of entries) {
37
+ const full = join(dir, name);
38
+ const st = statSync(full);
39
+ if (st.isDirectory()) {
40
+ if (!SKIP_DIRS.has(name)) {
41
+ out.push(...collect(full));
42
+ }
43
+ } else if (name.endsWith('.ts') && !name.endsWith('.spec.ts') && !name.endsWith('.test.ts')) {
44
+ out.push(full);
45
+ }
46
+ }
47
+ return out;
48
+ }
49
+
50
+ const targets = process.argv.slice(2);
51
+ const roots = targets.length > 0 ? targets : ['src'];
52
+
53
+ const violations = [];
54
+ for (const root of roots) {
55
+ for (const file of collect(root)) {
56
+ const lines = readFileSync(file, 'utf8').split('\n');
57
+ lines.forEach((line, i) => {
58
+ if (!MARKER.test(line)) {
59
+ return;
60
+ }
61
+ // Only flag executable code, not porting notes / JSDoc that merely mention the markers.
62
+ const trimmed = line.trim();
63
+ if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('/*')) {
64
+ return;
65
+ }
66
+ const prev = i > 0 ? lines[i - 1] : '';
67
+ if (ALLOW.test(line) || ALLOW.test(prev)) {
68
+ return;
69
+ }
70
+ violations.push({ file, line: i + 1, text: trimmed });
71
+ });
72
+ }
73
+ }
74
+
75
+ if (violations.length > 0) {
76
+ console.error('✖ subrequest fan-out gate: un-annotated concurrency loop(s) found.');
77
+ console.error(' Each may loop an external call per item (fetch/AI/Stripe/push/ES) and blow the');
78
+ console.error(' Workers subrequest cap as data grows. Move it behind a queue / cap it, or, if the');
79
+ console.error(' loop body is DB-only or hard-capped, annotate with `// subrequest-ok: <reason>`.\n');
80
+ for (const v of violations) {
81
+ console.error(` ${v.file}:${v.line} ${v.text}`);
82
+ }
83
+ process.exit(1);
84
+ }
85
+
86
+ console.log('✓ subrequest fan-out gate: no un-annotated concurrency loops.');
package/src/index.ts CHANGED
@@ -46,6 +46,12 @@ export type { CreateStripeClientOptions } from './stripe/client.js';
46
46
  // db
47
47
  export { retryWhenDeadlock } from './db/retry.js';
48
48
 
49
+ // queue
50
+ export { sendInChunks } from './queue/send.js';
51
+ export type { QueueLike, QueueSendMessage } from './queue/send.js';
52
+ export { processBatch } from './queue/consumer.js';
53
+ export type { QueueMessageLike, MessageBatchLike, ProcessBatchOptions, ProcessBatchResult } from './queue/consumer.js';
54
+
49
55
  // ai
50
56
  export { createAiGatewayProvider } from './ai/gateway.js';
51
57
  export type {
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Consumer-side helper for processing a Cloudflare Queues `MessageBatch` with per-message success and
3
+ * failure handling.
4
+ *
5
+ * A queue consumer invocation receives at most `max_batch_size` messages (configured in
6
+ * `wrangler.toml`), which is precisely the mechanism that bounds its subrequest budget: with a small
7
+ * `max_batch_size`, each invocation performs a fixed, small number of external calls no matter how
8
+ * many messages are backed up in the queue. {@link processBatch} applies the standard
9
+ * ack-on-success / retry-on-failure discipline so one poison message does not fail its whole batch.
10
+ *
11
+ * Messages are processed sequentially. This keeps the number of *simultaneously open* subrequests at
12
+ * one, staying well clear of the Workers concurrent-connection ceiling, and makes the per-invocation
13
+ * subrequest count deterministic (`<= max_batch_size`). For a queue consumer — which is not on a
14
+ * user-facing latency path — sequential processing is the safer default.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * // Worker `queue` handler
19
+ * export default {
20
+ * async queue(batch: MessageBatchLike<{ userId: number }>, env: Env) {
21
+ * await processBatch(batch, async ({ userId }) => {
22
+ * await reloadOneCustomer(env, userId); // exactly one external payment call
23
+ * });
24
+ * },
25
+ * };
26
+ * ```
27
+ *
28
+ * @packageDocumentation
29
+ */
30
+
31
+ /**
32
+ * Minimal subset of `@cloudflare/workers-types`' `Message` used by {@link processBatch}.
33
+ *
34
+ * Declared locally so consumers are not forced to depend on `@cloudflare/workers-types`.
35
+ *
36
+ * @typeParam Body - Type of the message body.
37
+ */
38
+ export interface QueueMessageLike<Body = unknown> {
39
+ /** Unique id assigned by the Queues runtime. */
40
+ readonly id: string;
41
+ /** Number of delivery attempts so far (starts at 1 on first delivery). */
42
+ readonly attempts: number;
43
+ /** The message payload. */
44
+ readonly body: Body;
45
+ /** Explicitly acknowledge this message so it is not redelivered. */
46
+ ack: () => void;
47
+ /** Mark this message for redelivery, optionally after a delay. */
48
+ retry: (options?: { delaySeconds?: number }) => void;
49
+ }
50
+
51
+ /**
52
+ * Minimal subset of `@cloudflare/workers-types`' `MessageBatch` used by {@link processBatch}.
53
+ *
54
+ * @typeParam Body - Type of each message body in the batch.
55
+ */
56
+ export interface MessageBatchLike<Body = unknown> {
57
+ /** Name of the queue this batch was delivered from. */
58
+ readonly queue: string;
59
+ /** The messages in this batch; length is bounded by the consumer's `max_batch_size`. */
60
+ readonly messages: readonly QueueMessageLike<Body>[];
61
+ }
62
+
63
+ /**
64
+ * Options for {@link processBatch}.
65
+ *
66
+ * @typeParam Body - Type of each message body.
67
+ */
68
+ export interface ProcessBatchOptions<Body = unknown> {
69
+ /**
70
+ * Invoked when `handler` throws for a message, immediately before the message is marked for retry.
71
+ * Use it to log or report; it must not throw. Defaults to `console.error`.
72
+ */
73
+ onError?: (error: unknown, message: QueueMessageLike<Body>) => void;
74
+ /**
75
+ * Delay, in seconds, applied when re-queuing a failed message. Omit to retry with the queue's
76
+ * default backoff.
77
+ */
78
+ retryDelaySeconds?: number;
79
+ }
80
+
81
+ /**
82
+ * Outcome counts returned by {@link processBatch}.
83
+ */
84
+ export interface ProcessBatchResult {
85
+ /** Messages whose handler completed successfully and were acked. */
86
+ processed: number;
87
+ /** Messages whose handler threw and were marked for retry. */
88
+ failed: number;
89
+ }
90
+
91
+ /**
92
+ * Process every message in `batch` sequentially, acking on success and retrying on failure.
93
+ *
94
+ * Each message is passed to `handler`; if it resolves the message is acked, and if it throws the
95
+ * error is routed to {@link ProcessBatchOptions.onError} and the message is marked for retry (honoring
96
+ * {@link ProcessBatchOptions.retryDelaySeconds}). One failing message never affects the others, and
97
+ * the returned counts let tests assert that the per-invocation workload — and therefore the
98
+ * subrequest count — stayed bounded by the batch size.
99
+ *
100
+ * @typeParam Body - Type of each message body.
101
+ * @param batch - The delivered message batch.
102
+ * @param handler - Async work for a single message; performs the bounded external call(s). Receives
103
+ * the decoded `body` and the raw message (for `attempts`, `id`, etc.).
104
+ * @param options - Error reporting and retry tuning; see {@link ProcessBatchOptions}.
105
+ * @returns The number of processed and failed messages.
106
+ * @example
107
+ * ```ts
108
+ * const { processed, failed } = await processBatch(
109
+ * batch,
110
+ * async ({ id }) => sendOneMail(id),
111
+ * { retryDelaySeconds: 30, onError: (e, m) => report(e, m.id) },
112
+ * );
113
+ * ```
114
+ */
115
+ export async function processBatch<Body>(
116
+ batch: MessageBatchLike<Body>,
117
+ handler: (body: Body, message: QueueMessageLike<Body>) => Promise<void>,
118
+ options?: ProcessBatchOptions<Body>,
119
+ ): Promise<ProcessBatchResult> {
120
+ const onError =
121
+ options?.onError ??
122
+ ((error, message) => {
123
+ console.error(`[queue:${batch.queue}] message ${message.id} failed`, error);
124
+ });
125
+ const retryOptions =
126
+ options?.retryDelaySeconds === undefined ? undefined : { delaySeconds: options.retryDelaySeconds };
127
+
128
+ let processed = 0;
129
+ let failed = 0;
130
+ for (const message of batch.messages) {
131
+ try {
132
+ await handler(message.body, message);
133
+ message.ack();
134
+ processed++;
135
+ } catch (error) {
136
+ try {
137
+ onError(error, message);
138
+ } catch {
139
+ // onError contract says "must not throw"; guard defensively so retry() and remaining messages still run.
140
+ }
141
+ message.retry(retryOptions);
142
+ failed++;
143
+ }
144
+ }
145
+ return { processed, failed };
146
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Producer-side helper for fanning a large list of items into a Cloudflare Queue without letting the
3
+ * producer's own subrequest count scale linearly with the list.
4
+ *
5
+ * A Worker may issue at most 50 (free) / 1000 (paid) subrequests per invocation, and each
6
+ * {@link QueueLike.send} counts as one subrequest. Enqueuing `N` items with per-item `send()` calls
7
+ * therefore reintroduces the very unbounded fan-out that queues exist to remove. {@link sendInChunks}
8
+ * instead groups items into batches and issues one {@link QueueLike.sendBatch} per batch, so the
9
+ * producer spends `ceil(N / chunkSize)` subrequests regardless of how large `N` grows.
10
+ *
11
+ * The heavy per-item work (external API calls, etc.) is expected to run in the queue *consumer*,
12
+ * where each invocation processes only `max_batch_size` messages and thus enjoys its own bounded
13
+ * subrequest budget. See {@link processBatch} for the consumer side.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * // In a Cron Trigger `scheduled` handler: enqueue every billing user, then let the consumer
18
+ * // re-derive payment state one user per message.
19
+ * const userIds = await query.getUserIdForReloadCustomer(); // DB read — not a subrequest
20
+ * await sendInChunks(env.PAYMENT_RELOAD_QUEUE, userIds); // ceil(N / 100) subrequests
21
+ * ```
22
+ *
23
+ * @packageDocumentation
24
+ */
25
+
26
+ /**
27
+ * Minimal subset of `@cloudflare/workers-types`' `Queue` used by {@link sendInChunks}.
28
+ *
29
+ * Declared locally so consumers are not forced to depend on `@cloudflare/workers-types`. Only the
30
+ * batch-send operation the helper actually needs is modeled.
31
+ *
32
+ * @typeParam Body - Type of each message body enqueued onto this queue.
33
+ */
34
+ export interface QueueLike<Body = unknown> {
35
+ /**
36
+ * Enqueue up to 100 messages in a single operation (one subrequest).
37
+ *
38
+ * @param messages - The message envelopes to enqueue; at most 100 per call, 256 KB per batch.
39
+ * @param options - Optional batch-level options, e.g. a `delaySeconds` applied to every message.
40
+ * @returns A promise that resolves once the batch is accepted. The resolved value is ignored, so a
41
+ * real `Queue` binding (whose `sendBatch` resolves to a `QueueSendBatchResponse`) is assignable.
42
+ */
43
+ sendBatch: (messages: Iterable<QueueSendMessage<Body>>, options?: { delaySeconds?: number }) => Promise<unknown>;
44
+ }
45
+
46
+ /**
47
+ * A single message envelope passed to {@link QueueLike.sendBatch}.
48
+ *
49
+ * @typeParam Body - Type of the message body.
50
+ */
51
+ export interface QueueSendMessage<Body = unknown> {
52
+ /** The message payload; structured-cloned by the Queues runtime. */
53
+ body: Body;
54
+ /** Optional content type hint (`'json'` by default for object bodies). */
55
+ contentType?: 'text' | 'bytes' | 'json' | 'v8';
56
+ /** Optional per-message delivery delay, in seconds. */
57
+ delaySeconds?: number;
58
+ }
59
+
60
+ /**
61
+ * The Cloudflare Queues hard limit on messages per {@link QueueLike.sendBatch} call.
62
+ */
63
+ const MAX_BATCH_SIZE = 100;
64
+
65
+ /**
66
+ * Split a list into fixed-size chunks (order preserving).
67
+ *
68
+ * @typeParam T - Element type.
69
+ * @param items - Source list.
70
+ * @param size - Maximum chunk length (assumed `>= 1`).
71
+ * @returns An array of chunks, each at most `size` long.
72
+ * @internal
73
+ */
74
+ function chunk<T>(items: readonly T[], size: number): T[][] {
75
+ const result: T[][] = [];
76
+ for (let i = 0; i < items.length; i += size) {
77
+ result.push(items.slice(i, i + size));
78
+ }
79
+ return result;
80
+ }
81
+
82
+ /**
83
+ * Enqueue every item in `items` using batched sends so the producer's subrequest count stays
84
+ * bounded at `ceil(items.length / chunkSize)` rather than growing per item.
85
+ *
86
+ * Each element becomes one queue message (`{ body: item }`); wrap or map your rows into small,
87
+ * self-describing payloads (e.g. an id plus a discriminator) before calling. Keep each batch under
88
+ * the Queues 256 KB limit — with `chunkSize <= 100` and small id-shaped payloads this is not a
89
+ * concern, but large bodies may require a smaller `chunkSize`.
90
+ *
91
+ * Batches are sent sequentially so a mid-list failure surfaces promptly (the already-sent batches
92
+ * are durably enqueued; the throw lets the caller decide whether to retry the remainder). An empty
93
+ * `items` is a no-op.
94
+ *
95
+ * @typeParam Body - Type of each message body.
96
+ * @param queue - The producer binding to send onto.
97
+ * @param items - The full list of message bodies to enqueue; may be arbitrarily large.
98
+ * @param options - Tuning options.
99
+ * @param options.chunkSize - Messages per `sendBatch` call. Defaults to and is capped at 100 (the
100
+ * Queues per-batch maximum); values below 1 are clamped to 1.
101
+ * @returns The number of `sendBatch` calls issued (i.e. subrequests spent), useful for asserting the
102
+ * fan-out stayed bounded in tests.
103
+ * @example
104
+ * ```ts
105
+ * const batches = await sendInChunks(env.MY_QUEUE, ids); // one send per 100 ids
106
+ * const batches = await sendInChunks(env.MY_QUEUE, rows, { // custom batch size for larger bodies
107
+ * chunkSize: 25,
108
+ * });
109
+ * ```
110
+ */
111
+ export async function sendInChunks<Body>(
112
+ queue: QueueLike<Body>,
113
+ items: readonly Body[],
114
+ options?: { chunkSize?: number },
115
+ ): Promise<number> {
116
+ if (items.length === 0) {
117
+ return 0;
118
+ }
119
+ const rawChunkSize = options?.chunkSize ?? MAX_BATCH_SIZE;
120
+ const chunkSize = Math.min(
121
+ MAX_BATCH_SIZE,
122
+ Math.max(1, Math.trunc(Number.isNaN(rawChunkSize) ? MAX_BATCH_SIZE : rawChunkSize)),
123
+ );
124
+ const batches = chunk(items, chunkSize);
125
+ for (const batch of batches) {
126
+ await queue.sendBatch(batch.map((body) => ({ body })));
127
+ }
128
+ return batches.length;
129
+ }