@lunora/queue 0.0.0 → 1.0.0-alpha.10

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.
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Shared types for dispatching a Lunora function back into the worker from a
3
+ * server-initiated context (a workflow body, a queue handler, a scheduled job).
4
+ * Node-safe — no Cloudflare runtime imports — so the consumers stay unit-testable
5
+ * with plain-object doubles.
6
+ */
7
+ /** Opaque generated function reference (`api.foo.bar`), carrying its dispatch id. */
8
+ interface FunctionReference {
9
+ __lunoraRef: string;
10
+ }
11
+ /** Infer the args object a {@link FunctionReference} expects (loose at the boundary). */
12
+ type ArgsOf<F> = F extends FunctionReference ? Record<string, unknown> : never;
13
+ /** Options for a function call made via a dispatch runner. */
14
+ interface RunFunctionOptions {
15
+ /** Route the call to a specific shard (defaults to the worker's root shard). */
16
+ shardKey?: string;
17
+ }
18
+ /** Invoke a Lunora function (query/mutation/action) by reference. The shape of `ctx.run`. */
19
+ type DispatchRunFunction = <F extends FunctionReference>(function_: F, args?: ArgsOf<F>, options?: RunFunctionOptions) => Promise<unknown>;
20
+ /** Console-style logger prefixed for log correlation, routed to wrangler tail / Studio. */
21
+ interface DispatchLogger {
22
+ debug: (message: unknown, ...rest: unknown[]) => void;
23
+ error: (message: unknown, ...rest: unknown[]) => void;
24
+ info: (message: unknown, ...rest: unknown[]) => void;
25
+ warn: (message: unknown, ...rest: unknown[]) => void;
26
+ }
27
+ /** How a queue message body is serialized on the wire (Cloudflare default `"json"`). */
28
+ type QueueContentType = "bytes" | "json" | "text" | "v8";
29
+ /** Options for a single `producer.send(body, options?)`. */
30
+ interface QueueSendOptions {
31
+ /** Wire serialization for this message (defaults to the queue's content type). */
32
+ contentType?: QueueContentType;
33
+ /** Per-message delivery delay in seconds (0–43200, i.e. up to 12 hours). */
34
+ delaySeconds?: number;
35
+ }
36
+ /** Options for a `producer.sendBatch(messages, options?)`. */
37
+ interface QueueSendBatchOptions {
38
+ /** Delivery delay applied to the whole batch, in seconds. */
39
+ delaySeconds?: number;
40
+ }
41
+ /** One entry in a `sendBatch` call — a body plus optional per-message overrides. */
42
+ interface MessageSendRequestLike<Body = unknown> {
43
+ body: Body;
44
+ contentType?: QueueContentType;
45
+ delaySeconds?: number;
46
+ }
47
+ /**
48
+ * Minimal structural projection of workers-types' `Queue&lt;Body>` (the producer
49
+ * binding). The real binding's `send`/`sendBatch` resolve to a metadata object;
50
+ * we widen the return to `Promise&lt;unknown>` so a plain-object fake satisfies it.
51
+ */
52
+ interface QueueBindingLike<Body = unknown> {
53
+ send: (message: Body, options?: QueueSendOptions) => Promise<unknown>;
54
+ sendBatch: (messages: Iterable<MessageSendRequestLike<Body>>, options?: QueueSendBatchOptions) => Promise<unknown>;
55
+ }
56
+ /** Options for retrying a message / batch (`message.retry({ delaySeconds })`). */
57
+ interface QueueRetryOptions {
58
+ delaySeconds?: number;
59
+ }
60
+ /** Structural mirror of workers-types' `Message&lt;Body>` (one delivered message). */
61
+ interface MessageLike<Body = unknown> {
62
+ /** Acknowledge this message so it is not redelivered. */
63
+ ack: () => void;
64
+ readonly attempts: number;
65
+ readonly body: Body;
66
+ readonly id: string;
67
+ /** Explicitly retry this message (optionally after a delay). */
68
+ retry: (options?: QueueRetryOptions) => void;
69
+ readonly timestamp: Date;
70
+ }
71
+ /** Structural mirror of workers-types' `MessageBatch&lt;Body>` handed to a consumer. */
72
+ interface MessageBatchLike<Body = unknown> {
73
+ /** Acknowledge every message in the batch. */
74
+ ackAll: () => void;
75
+ readonly messages: ReadonlyArray<MessageLike<Body>>;
76
+ /** The queue name this batch was delivered from (`batch.queue`), used to route. */
77
+ readonly queue: string;
78
+ /** Retry every message in the batch (optionally after a delay). */
79
+ retryAll: (options?: QueueRetryOptions) => void;
80
+ }
81
+ /**
82
+ * The typed producer bound to `ctx.queues.&lt;name>`. Sending is a side effect, so
83
+ * the generated context exposes this only on `MutationCtx` / `ActionCtx` (never
84
+ * the deterministic `QueryCtx`), mirroring `ctx.scheduler` / `ctx.workflows`.
85
+ */
86
+ interface QueueProducer<Body = unknown> {
87
+ /** Enqueue one message. */
88
+ send: (body: Body, options?: QueueSendOptions) => Promise<void>;
89
+ /** Enqueue a batch of messages in one call. */
90
+ sendBatch: (messages: Iterable<MessageSendRequestLike<Body>>, options?: QueueSendBatchOptions) => Promise<void>;
91
+ }
92
+ /**
93
+ * `ctx.queues` — the map of declared queue export names → typed producers.
94
+ * Codegen narrows this to the exact export names; the package keeps it open so
95
+ * `createQueues` stays schema-agnostic.
96
+ */
97
+ interface Queues {
98
+ [exportName: string]: QueueProducer;
99
+ }
100
+ /** Options the package-level `createQueues` factory takes. */
101
+ interface LunoraQueuesOptions {
102
+ /** Map of `lunora/queues.ts` export name → Cloudflare `Queue` producer binding. */
103
+ bindings: Record<string, QueueBindingLike>;
104
+ }
105
+ /**
106
+ * The context handed to a `defineQueue` handler. Decoupled from `@lunora/server`
107
+ * (like the workflow run context): to touch data, call a Lunora mutation/action
108
+ * via `ctx.run(api.x.y, args)` — the dispatch goes through the same
109
+ * `/_lunora/scheduler/dispatch` path the SchedulerDO and workflows use.
110
+ */
111
+ interface QueueRunContext {
112
+ /** The worker `env` (bindings + vars). */
113
+ readonly env: Record<string, unknown>;
114
+ /** Queue-name-prefixed logger. */
115
+ readonly log: DispatchLogger;
116
+ /** Invoke a Lunora function (query/mutation/action) by reference. */
117
+ readonly run: DispatchRunFunction;
118
+ }
119
+ /** Whether a declared queue is consumed by this worker (push) or polled externally (pull). */
120
+ type QueueConsumerMode = "pull" | "push";
121
+ /** The handler body run for each delivered batch (push consumers only). */
122
+ type QueueHandler<Body = unknown> = (context: QueueRunContext, batch: MessageBatchLike<Body>) => Promise<void> | void;
123
+ /** Push-consumer batch/retry tuning, mirrored onto the wrangler `queues.consumers[]` entry. */
124
+ interface QueueConsumerTuning {
125
+ /** Name of the dead-letter queue messages land in after `maxRetries`. */
126
+ deadLetterQueue?: string;
127
+ /** Max messages per batch (1–100, Cloudflare default 10). */
128
+ maxBatchSize?: number;
129
+ /** Max seconds to wait before delivering a partial batch (0–60, default 5). */
130
+ maxBatchTimeout?: number;
131
+ /** Max delivery attempts before a message is dropped / dead-lettered (default 3). */
132
+ maxRetries?: number;
133
+ /** Delay in seconds before a failed batch is retried. */
134
+ retryDelay?: number;
135
+ }
136
+ /** The config object passed to `defineQueue`. */
137
+ interface QueueConfig<Body = unknown> extends QueueConsumerTuning {
138
+ /**
139
+ * The push-consumer body. Required for `mode: "push"` (the default); omit it
140
+ * for `mode: "pull"`, where an external worker polls the queue over HTTP.
141
+ */
142
+ handler?: QueueHandler<Body>;
143
+ /** How this queue is consumed. Defaults to `"push"`. */
144
+ mode?: QueueConsumerMode;
145
+ /**
146
+ * Stable wrangler queue name (`queues.producers[].queue`). Defaults to the
147
+ * kebab-cased export name (`emailQueue` → `email-queue`).
148
+ */
149
+ name?: string;
150
+ }
151
+ /** The branded result of `defineQueue`, discovered by codegen + config. */
152
+ interface QueueDefinition<Body = unknown> extends QueueConfig<Body> {
153
+ /**
154
+ * Phantom carrier for the message body type, so codegen can type the
155
+ * generated `ctx.queues.&lt;name>` producer as `QueueProducer&lt;Body>` from
156
+ * `typeof &lt;export>`. Never assigned at runtime (type-only).
157
+ */
158
+ readonly __lunoraBody?: Body;
159
+ /** Runtime brand identifying a `defineQueue` result. */
160
+ isLunoraQueue: true;
161
+ }
162
+ /** Wiring info for one declared queue, emitted by codegen into the generated shard/handler. */
163
+ interface QueueBindingSpec {
164
+ /** The Cloudflare `Queue` producer binding name, e.g. `QUEUE_EMAIL`. */
165
+ binding: string;
166
+ /** The `lunora/queues.ts` export name, e.g. `emailQueue`. */
167
+ exportName: string;
168
+ /** The stable wrangler queue name, e.g. `email-queue`. */
169
+ name: string;
170
+ }
171
+ /** One declared queue, keyed for batch routing by its stable wrangler name. */
172
+ interface QueueRegistryEntry {
173
+ /**
174
+ * The `defineQueue` result (carries the push handler). The body type is
175
+ * erased to `any` here because the registry is heterogeneous — different
176
+ * queues carry different message bodies, and the handler param is
177
+ * contravariant, so a precise `QueueDefinition&lt;Body>` would not be assignable
178
+ * to a shared `unknown`-bodied slot. Runtime dispatch passes the delivered
179
+ * batch straight through, so the erasure is type-only.
180
+ */
181
+ definition: QueueDefinition<any>;
182
+ /** The `lunora/queues.ts` export name, for log correlation. */
183
+ exportName: string;
184
+ }
185
+ /** Map of stable wrangler queue name → registry entry, built by codegen. */
186
+ type QueueRegistry = Record<string, QueueRegistryEntry>;
187
+ /** The disposition a consumer left one message in for a single delivery attempt. */
188
+ type QueueMessageOutcome = "ack" | "error" | "retry";
189
+ /**
190
+ * One consumed message as captured by {@link dispatchQueueBatch} and handed to an
191
+ * {@link QueueCaptureSink}. Structurally matches `@lunora/do`'s
192
+ * `RecordQueueMessageInput` (the reserved `recordQueueMessage` admin RPC payload);
193
+ * the two packages share only this contract, so keep them in sync by hand.
194
+ */
195
+ interface CapturedQueueMessage {
196
+ /** Delivery attempt number for this message (`message.attempts`). */
197
+ attempts: number;
198
+ /** The message body (JSON-encoded + capped by the catcher). */
199
+ body: unknown;
200
+ /** `true` when this failed delivery was the message's last (its retries are exhausted — the broker dead-letters it). */
201
+ deadLettered: boolean;
202
+ /** Handler error message when `outcome` is `error`; absent otherwise. */
203
+ error?: string;
204
+ /** The `lunora/queues.ts` export name that consumed it. */
205
+ exportName: string;
206
+ /** The delivered message id (`message.id`). */
207
+ messageId: string;
208
+ /** How the handler disposed of the message this attempt. */
209
+ outcome: QueueMessageOutcome;
210
+ /** The stable wrangler queue name the batch was delivered from (`batch.queue`). */
211
+ queue: string;
212
+ /** Original message timestamp in epoch-ms (`message.timestamp`). */
213
+ timestamp: number;
214
+ }
215
+ /**
216
+ * Persists a batch of consumed messages. The codegen worker wires this to POST the
217
+ * batch to the root shard's `recordQueueMessage` admin RPC (the dev queue catcher).
218
+ * Best-effort by contract: {@link dispatchQueueBatch} swallows a rejection so a
219
+ * capture failure never changes delivery semantics.
220
+ */
221
+ type QueueCaptureSink = (messages: CapturedQueueMessage[]) => Promise<void> | void;
222
+ interface DispatchOptions {
223
+ /**
224
+ * Optional capture sink. When set, the batch is instrumented and every
225
+ * message's final disposition is recorded and handed to this sink after the
226
+ * handler runs. Omitted in production unless queue capture is enabled, so a
227
+ * consumer pays no instrumentation cost by default.
228
+ */
229
+ capture?: QueueCaptureSink;
230
+ /** Worker `env`, forwarded to the queue run context. */
231
+ env: Record<string, unknown>;
232
+ /** Injectable fetch for the `ctx.run` dispatcher (tests). */
233
+ fetchImpl?: typeof fetch;
234
+ }
235
+ /**
236
+ * Look up the handler for `batch.queue` and invoke it with a fresh
237
+ * `QueueRunContext`. Throws a directed error when no push handler is registered
238
+ * for the delivered queue (a misconfiguration — the consumer was declared
239
+ * `pull`, or the queue name drifted from the `defineQueue` export).
240
+ */
241
+ declare const dispatchQueueBatch: (batch: MessageBatchLike, registry: QueueRegistry, options: DispatchOptions) => Promise<void>;
242
+ /** A Worker `env` projected as a plain record (vars, secrets, and bindings are `unknown`-valued). */
243
+ type QueueEnv = Record<string, unknown>;
244
+ /** Options for {@link createQueueCaptureSink}. */
245
+ interface QueueCaptureOptions {
246
+ /** Pin the consumed-message log to a Cloudflare data-residency jurisdiction (match the worker's `jurisdiction`). */
247
+ jurisdiction?: string;
248
+ /** Shard the consumed-message log lives on; override if the worker sets a custom `defaultShardKey`. */
249
+ rootShard?: string;
250
+ }
251
+ /**
252
+ * Whether consumed queue messages should be captured into the studio's log.
253
+ * Explicit `LUNORA_QUEUE_CAPTURE` (`"1"`/`"true"` vs `"0"`/`"false"`) always wins;
254
+ * unset, capture is on only in a development environment. Mirrors
255
+ * `@lunora/mail`'s `shouldCaptureMail` so mail and queue dev capture toggle the
256
+ * same way.
257
+ */
258
+ declare const shouldCaptureQueue: (env: QueueEnv) => boolean;
259
+ /**
260
+ * Build the {@link QueueCaptureSink} that records a processed batch into the
261
+ * studio's root-shard consumed-message log via the reserved `recordQueueMessage`
262
+ * admin RPC. Best-effort by contract: without the `SHARD` binding or
263
+ * `LUNORA_ADMIN_TOKEN` it no-ops, and `dispatchQueueBatch` swallows a
264
+ * rejection, so capture never changes delivery semantics.
265
+ */
266
+ declare const createQueueCaptureSink: (env: QueueEnv, options?: QueueCaptureOptions) => QueueCaptureSink;
267
+ /**
268
+ * Build the `ctx.queues` map for a request: resolve every spec's `env[binding]`
269
+ * into the `exportName → Queue binding` map and wrap it in {@link createQueues}.
270
+ * A spec whose binding is absent from `env` is skipped here — the helpful "no
271
+ * queue named …" error is raised lazily by `ctx.queues.&lt;name>.send(...)` when
272
+ * the missing queue is actually used.
273
+ */
274
+ declare const createQueueContext: (env: Record<string, unknown>, specs: ReadonlyArray<QueueBindingSpec>) => Queues;
275
+ /**
276
+ * Build the `ctx.queues` map from `lunora/queues.ts` export name → Cloudflare
277
+ * `Queue` binding. Each property is a typed {@link QueueProducer}; accessing an
278
+ * export whose binding is absent throws a directed error naming the declared
279
+ * queues (raised lazily on first use).
280
+ */
281
+ declare const createQueues: (options: LunoraQueuesOptions) => Queues;
282
+ /**
283
+ * The wrangler producer binding name for a queue export: `emailQueue` →
284
+ * `QUEUE_EMAIL_QUEUE`, `email` → `QUEUE_EMAIL`. The `QUEUE_` prefix namespaces
285
+ * these away from `SHARD`/`SESSION`/`SCHEDULER`/`WORKFLOW_*`/`CONTAINER_*` so a
286
+ * queue export can never collide with the built-in bindings.
287
+ */
288
+ declare const queueBindingName: (exportName: string) => string;
289
+ /**
290
+ * The stable queue name wrangler registers (`queues.producers[].queue` and
291
+ * `queues.consumers[].queue`): `emailQueue` → `email-queue`. Used as the
292
+ * deployed queue's identifier when no explicit `name` override is given.
293
+ */
294
+ declare const queueDefaultName: (exportName: string) => string;
295
+ /**
296
+ * Declare a Cloudflare Queue deployed alongside the app. Pure validation +
297
+ * branding: codegen discovers the export, emits the typed `ctx.queues.&lt;name>`
298
+ * producer and (for push consumers) the worker `queue()` dispatch; the config
299
+ * layer reconciles the wrangler `queues.producers[]` / `queues.consumers[]`
300
+ * entries from the same definition.
301
+ *
302
+ * ```ts
303
+ * // lunora/queues.ts
304
+ * import { defineQueue } from "@lunora/queue";
305
+ * import { api } from "./_generated/api";
306
+ *
307
+ * export const emailQueue = defineQueue&lt;{ to: string }>({
308
+ * handler: async (ctx, batch) => {
309
+ * for (const message of batch.messages) {
310
+ * await ctx.run(api.email.send, { to: message.body.to });
311
+ * message.ack();
312
+ * }
313
+ * },
314
+ * });
315
+ * ```
316
+ *
317
+ * Enqueue from a mutation or action: `await ctx.queues.emailQueue.send({ to })`.
318
+ *
319
+ * ⚠️ **Privileged dispatch.** A push handler's `ctx.run(...)` calls back into
320
+ * Lunora functions over the admin-authenticated dispatch endpoint (the same
321
+ * trusted path the scheduler and workflows use), so those calls run with the
322
+ * system identity — **end-user RLS is not applied**. Treat a queue handler as
323
+ * trusted server code: validate `message.body` (it may be attacker-influenced if
324
+ * anything user-facing can enqueue) before acting on it, and don't forward an
325
+ * unchecked body straight into a privileged mutation.
326
+ */
327
+ declare const defineQueue: <Body = unknown>(config: QueueConfig<Body>) => QueueDefinition<Body>;
328
+ /** True when a value is a `defineQueue` result (the runtime brand check). */
329
+ declare const isQueueDefinition: (value: unknown) => value is QueueDefinition;
330
+ interface RunContextOptions {
331
+ env: Record<string, unknown>;
332
+ exportName: string;
333
+ fetchImpl?: typeof fetch;
334
+ }
335
+ /** Assemble the {@link QueueRunContext} passed to a `defineQueue` handler. */
336
+ declare const createQueueRunContext: (options: RunContextOptions) => QueueRunContext;
337
+ export { type ArgsOf, type CapturedQueueMessage, type FunctionReference, type LunoraQueuesOptions, type MessageBatchLike, type MessageLike, type MessageSendRequestLike, type QueueBindingLike, type QueueBindingSpec, type QueueCaptureOptions, type QueueCaptureSink, type QueueConfig, type QueueConsumerMode, type QueueConsumerTuning, type QueueContentType, type QueueDefinition, type QueueEnv, type QueueHandler, type DispatchLogger as QueueLogger, type QueueProducer, type QueueRegistry, type QueueRegistryEntry, type QueueRetryOptions, type QueueRunContext, type DispatchRunFunction as QueueRunFunction, type QueueSendBatchOptions, type QueueSendOptions, type Queues, type RunFunctionOptions, createQueueCaptureSink, createQueueContext, createQueueRunContext, createQueues, defineQueue, dispatchQueueBatch, isQueueDefinition, queueBindingName, queueDefaultName, shouldCaptureQueue };
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Shared types for dispatching a Lunora function back into the worker from a
3
+ * server-initiated context (a workflow body, a queue handler, a scheduled job).
4
+ * Node-safe — no Cloudflare runtime imports — so the consumers stay unit-testable
5
+ * with plain-object doubles.
6
+ */
7
+ /** Opaque generated function reference (`api.foo.bar`), carrying its dispatch id. */
8
+ interface FunctionReference {
9
+ __lunoraRef: string;
10
+ }
11
+ /** Infer the args object a {@link FunctionReference} expects (loose at the boundary). */
12
+ type ArgsOf<F> = F extends FunctionReference ? Record<string, unknown> : never;
13
+ /** Options for a function call made via a dispatch runner. */
14
+ interface RunFunctionOptions {
15
+ /** Route the call to a specific shard (defaults to the worker's root shard). */
16
+ shardKey?: string;
17
+ }
18
+ /** Invoke a Lunora function (query/mutation/action) by reference. The shape of `ctx.run`. */
19
+ type DispatchRunFunction = <F extends FunctionReference>(function_: F, args?: ArgsOf<F>, options?: RunFunctionOptions) => Promise<unknown>;
20
+ /** Console-style logger prefixed for log correlation, routed to wrangler tail / Studio. */
21
+ interface DispatchLogger {
22
+ debug: (message: unknown, ...rest: unknown[]) => void;
23
+ error: (message: unknown, ...rest: unknown[]) => void;
24
+ info: (message: unknown, ...rest: unknown[]) => void;
25
+ warn: (message: unknown, ...rest: unknown[]) => void;
26
+ }
27
+ /** How a queue message body is serialized on the wire (Cloudflare default `"json"`). */
28
+ type QueueContentType = "bytes" | "json" | "text" | "v8";
29
+ /** Options for a single `producer.send(body, options?)`. */
30
+ interface QueueSendOptions {
31
+ /** Wire serialization for this message (defaults to the queue's content type). */
32
+ contentType?: QueueContentType;
33
+ /** Per-message delivery delay in seconds (0–43200, i.e. up to 12 hours). */
34
+ delaySeconds?: number;
35
+ }
36
+ /** Options for a `producer.sendBatch(messages, options?)`. */
37
+ interface QueueSendBatchOptions {
38
+ /** Delivery delay applied to the whole batch, in seconds. */
39
+ delaySeconds?: number;
40
+ }
41
+ /** One entry in a `sendBatch` call — a body plus optional per-message overrides. */
42
+ interface MessageSendRequestLike<Body = unknown> {
43
+ body: Body;
44
+ contentType?: QueueContentType;
45
+ delaySeconds?: number;
46
+ }
47
+ /**
48
+ * Minimal structural projection of workers-types' `Queue&lt;Body>` (the producer
49
+ * binding). The real binding's `send`/`sendBatch` resolve to a metadata object;
50
+ * we widen the return to `Promise&lt;unknown>` so a plain-object fake satisfies it.
51
+ */
52
+ interface QueueBindingLike<Body = unknown> {
53
+ send: (message: Body, options?: QueueSendOptions) => Promise<unknown>;
54
+ sendBatch: (messages: Iterable<MessageSendRequestLike<Body>>, options?: QueueSendBatchOptions) => Promise<unknown>;
55
+ }
56
+ /** Options for retrying a message / batch (`message.retry({ delaySeconds })`). */
57
+ interface QueueRetryOptions {
58
+ delaySeconds?: number;
59
+ }
60
+ /** Structural mirror of workers-types' `Message&lt;Body>` (one delivered message). */
61
+ interface MessageLike<Body = unknown> {
62
+ /** Acknowledge this message so it is not redelivered. */
63
+ ack: () => void;
64
+ readonly attempts: number;
65
+ readonly body: Body;
66
+ readonly id: string;
67
+ /** Explicitly retry this message (optionally after a delay). */
68
+ retry: (options?: QueueRetryOptions) => void;
69
+ readonly timestamp: Date;
70
+ }
71
+ /** Structural mirror of workers-types' `MessageBatch&lt;Body>` handed to a consumer. */
72
+ interface MessageBatchLike<Body = unknown> {
73
+ /** Acknowledge every message in the batch. */
74
+ ackAll: () => void;
75
+ readonly messages: ReadonlyArray<MessageLike<Body>>;
76
+ /** The queue name this batch was delivered from (`batch.queue`), used to route. */
77
+ readonly queue: string;
78
+ /** Retry every message in the batch (optionally after a delay). */
79
+ retryAll: (options?: QueueRetryOptions) => void;
80
+ }
81
+ /**
82
+ * The typed producer bound to `ctx.queues.&lt;name>`. Sending is a side effect, so
83
+ * the generated context exposes this only on `MutationCtx` / `ActionCtx` (never
84
+ * the deterministic `QueryCtx`), mirroring `ctx.scheduler` / `ctx.workflows`.
85
+ */
86
+ interface QueueProducer<Body = unknown> {
87
+ /** Enqueue one message. */
88
+ send: (body: Body, options?: QueueSendOptions) => Promise<void>;
89
+ /** Enqueue a batch of messages in one call. */
90
+ sendBatch: (messages: Iterable<MessageSendRequestLike<Body>>, options?: QueueSendBatchOptions) => Promise<void>;
91
+ }
92
+ /**
93
+ * `ctx.queues` — the map of declared queue export names → typed producers.
94
+ * Codegen narrows this to the exact export names; the package keeps it open so
95
+ * `createQueues` stays schema-agnostic.
96
+ */
97
+ interface Queues {
98
+ [exportName: string]: QueueProducer;
99
+ }
100
+ /** Options the package-level `createQueues` factory takes. */
101
+ interface LunoraQueuesOptions {
102
+ /** Map of `lunora/queues.ts` export name → Cloudflare `Queue` producer binding. */
103
+ bindings: Record<string, QueueBindingLike>;
104
+ }
105
+ /**
106
+ * The context handed to a `defineQueue` handler. Decoupled from `@lunora/server`
107
+ * (like the workflow run context): to touch data, call a Lunora mutation/action
108
+ * via `ctx.run(api.x.y, args)` — the dispatch goes through the same
109
+ * `/_lunora/scheduler/dispatch` path the SchedulerDO and workflows use.
110
+ */
111
+ interface QueueRunContext {
112
+ /** The worker `env` (bindings + vars). */
113
+ readonly env: Record<string, unknown>;
114
+ /** Queue-name-prefixed logger. */
115
+ readonly log: DispatchLogger;
116
+ /** Invoke a Lunora function (query/mutation/action) by reference. */
117
+ readonly run: DispatchRunFunction;
118
+ }
119
+ /** Whether a declared queue is consumed by this worker (push) or polled externally (pull). */
120
+ type QueueConsumerMode = "pull" | "push";
121
+ /** The handler body run for each delivered batch (push consumers only). */
122
+ type QueueHandler<Body = unknown> = (context: QueueRunContext, batch: MessageBatchLike<Body>) => Promise<void> | void;
123
+ /** Push-consumer batch/retry tuning, mirrored onto the wrangler `queues.consumers[]` entry. */
124
+ interface QueueConsumerTuning {
125
+ /** Name of the dead-letter queue messages land in after `maxRetries`. */
126
+ deadLetterQueue?: string;
127
+ /** Max messages per batch (1–100, Cloudflare default 10). */
128
+ maxBatchSize?: number;
129
+ /** Max seconds to wait before delivering a partial batch (0–60, default 5). */
130
+ maxBatchTimeout?: number;
131
+ /** Max delivery attempts before a message is dropped / dead-lettered (default 3). */
132
+ maxRetries?: number;
133
+ /** Delay in seconds before a failed batch is retried. */
134
+ retryDelay?: number;
135
+ }
136
+ /** The config object passed to `defineQueue`. */
137
+ interface QueueConfig<Body = unknown> extends QueueConsumerTuning {
138
+ /**
139
+ * The push-consumer body. Required for `mode: "push"` (the default); omit it
140
+ * for `mode: "pull"`, where an external worker polls the queue over HTTP.
141
+ */
142
+ handler?: QueueHandler<Body>;
143
+ /** How this queue is consumed. Defaults to `"push"`. */
144
+ mode?: QueueConsumerMode;
145
+ /**
146
+ * Stable wrangler queue name (`queues.producers[].queue`). Defaults to the
147
+ * kebab-cased export name (`emailQueue` → `email-queue`).
148
+ */
149
+ name?: string;
150
+ }
151
+ /** The branded result of `defineQueue`, discovered by codegen + config. */
152
+ interface QueueDefinition<Body = unknown> extends QueueConfig<Body> {
153
+ /**
154
+ * Phantom carrier for the message body type, so codegen can type the
155
+ * generated `ctx.queues.&lt;name>` producer as `QueueProducer&lt;Body>` from
156
+ * `typeof &lt;export>`. Never assigned at runtime (type-only).
157
+ */
158
+ readonly __lunoraBody?: Body;
159
+ /** Runtime brand identifying a `defineQueue` result. */
160
+ isLunoraQueue: true;
161
+ }
162
+ /** Wiring info for one declared queue, emitted by codegen into the generated shard/handler. */
163
+ interface QueueBindingSpec {
164
+ /** The Cloudflare `Queue` producer binding name, e.g. `QUEUE_EMAIL`. */
165
+ binding: string;
166
+ /** The `lunora/queues.ts` export name, e.g. `emailQueue`. */
167
+ exportName: string;
168
+ /** The stable wrangler queue name, e.g. `email-queue`. */
169
+ name: string;
170
+ }
171
+ /** One declared queue, keyed for batch routing by its stable wrangler name. */
172
+ interface QueueRegistryEntry {
173
+ /**
174
+ * The `defineQueue` result (carries the push handler). The body type is
175
+ * erased to `any` here because the registry is heterogeneous — different
176
+ * queues carry different message bodies, and the handler param is
177
+ * contravariant, so a precise `QueueDefinition&lt;Body>` would not be assignable
178
+ * to a shared `unknown`-bodied slot. Runtime dispatch passes the delivered
179
+ * batch straight through, so the erasure is type-only.
180
+ */
181
+ definition: QueueDefinition<any>;
182
+ /** The `lunora/queues.ts` export name, for log correlation. */
183
+ exportName: string;
184
+ }
185
+ /** Map of stable wrangler queue name → registry entry, built by codegen. */
186
+ type QueueRegistry = Record<string, QueueRegistryEntry>;
187
+ /** The disposition a consumer left one message in for a single delivery attempt. */
188
+ type QueueMessageOutcome = "ack" | "error" | "retry";
189
+ /**
190
+ * One consumed message as captured by {@link dispatchQueueBatch} and handed to an
191
+ * {@link QueueCaptureSink}. Structurally matches `@lunora/do`'s
192
+ * `RecordQueueMessageInput` (the reserved `recordQueueMessage` admin RPC payload);
193
+ * the two packages share only this contract, so keep them in sync by hand.
194
+ */
195
+ interface CapturedQueueMessage {
196
+ /** Delivery attempt number for this message (`message.attempts`). */
197
+ attempts: number;
198
+ /** The message body (JSON-encoded + capped by the catcher). */
199
+ body: unknown;
200
+ /** `true` when this failed delivery was the message's last (its retries are exhausted — the broker dead-letters it). */
201
+ deadLettered: boolean;
202
+ /** Handler error message when `outcome` is `error`; absent otherwise. */
203
+ error?: string;
204
+ /** The `lunora/queues.ts` export name that consumed it. */
205
+ exportName: string;
206
+ /** The delivered message id (`message.id`). */
207
+ messageId: string;
208
+ /** How the handler disposed of the message this attempt. */
209
+ outcome: QueueMessageOutcome;
210
+ /** The stable wrangler queue name the batch was delivered from (`batch.queue`). */
211
+ queue: string;
212
+ /** Original message timestamp in epoch-ms (`message.timestamp`). */
213
+ timestamp: number;
214
+ }
215
+ /**
216
+ * Persists a batch of consumed messages. The codegen worker wires this to POST the
217
+ * batch to the root shard's `recordQueueMessage` admin RPC (the dev queue catcher).
218
+ * Best-effort by contract: {@link dispatchQueueBatch} swallows a rejection so a
219
+ * capture failure never changes delivery semantics.
220
+ */
221
+ type QueueCaptureSink = (messages: CapturedQueueMessage[]) => Promise<void> | void;
222
+ interface DispatchOptions {
223
+ /**
224
+ * Optional capture sink. When set, the batch is instrumented and every
225
+ * message's final disposition is recorded and handed to this sink after the
226
+ * handler runs. Omitted in production unless queue capture is enabled, so a
227
+ * consumer pays no instrumentation cost by default.
228
+ */
229
+ capture?: QueueCaptureSink;
230
+ /** Worker `env`, forwarded to the queue run context. */
231
+ env: Record<string, unknown>;
232
+ /** Injectable fetch for the `ctx.run` dispatcher (tests). */
233
+ fetchImpl?: typeof fetch;
234
+ }
235
+ /**
236
+ * Look up the handler for `batch.queue` and invoke it with a fresh
237
+ * `QueueRunContext`. Throws a directed error when no push handler is registered
238
+ * for the delivered queue (a misconfiguration — the consumer was declared
239
+ * `pull`, or the queue name drifted from the `defineQueue` export).
240
+ */
241
+ declare const dispatchQueueBatch: (batch: MessageBatchLike, registry: QueueRegistry, options: DispatchOptions) => Promise<void>;
242
+ /** A Worker `env` projected as a plain record (vars, secrets, and bindings are `unknown`-valued). */
243
+ type QueueEnv = Record<string, unknown>;
244
+ /** Options for {@link createQueueCaptureSink}. */
245
+ interface QueueCaptureOptions {
246
+ /** Pin the consumed-message log to a Cloudflare data-residency jurisdiction (match the worker's `jurisdiction`). */
247
+ jurisdiction?: string;
248
+ /** Shard the consumed-message log lives on; override if the worker sets a custom `defaultShardKey`. */
249
+ rootShard?: string;
250
+ }
251
+ /**
252
+ * Whether consumed queue messages should be captured into the studio's log.
253
+ * Explicit `LUNORA_QUEUE_CAPTURE` (`"1"`/`"true"` vs `"0"`/`"false"`) always wins;
254
+ * unset, capture is on only in a development environment. Mirrors
255
+ * `@lunora/mail`'s `shouldCaptureMail` so mail and queue dev capture toggle the
256
+ * same way.
257
+ */
258
+ declare const shouldCaptureQueue: (env: QueueEnv) => boolean;
259
+ /**
260
+ * Build the {@link QueueCaptureSink} that records a processed batch into the
261
+ * studio's root-shard consumed-message log via the reserved `recordQueueMessage`
262
+ * admin RPC. Best-effort by contract: without the `SHARD` binding or
263
+ * `LUNORA_ADMIN_TOKEN` it no-ops, and `dispatchQueueBatch` swallows a
264
+ * rejection, so capture never changes delivery semantics.
265
+ */
266
+ declare const createQueueCaptureSink: (env: QueueEnv, options?: QueueCaptureOptions) => QueueCaptureSink;
267
+ /**
268
+ * Build the `ctx.queues` map for a request: resolve every spec's `env[binding]`
269
+ * into the `exportName → Queue binding` map and wrap it in {@link createQueues}.
270
+ * A spec whose binding is absent from `env` is skipped here — the helpful "no
271
+ * queue named …" error is raised lazily by `ctx.queues.&lt;name>.send(...)` when
272
+ * the missing queue is actually used.
273
+ */
274
+ declare const createQueueContext: (env: Record<string, unknown>, specs: ReadonlyArray<QueueBindingSpec>) => Queues;
275
+ /**
276
+ * Build the `ctx.queues` map from `lunora/queues.ts` export name → Cloudflare
277
+ * `Queue` binding. Each property is a typed {@link QueueProducer}; accessing an
278
+ * export whose binding is absent throws a directed error naming the declared
279
+ * queues (raised lazily on first use).
280
+ */
281
+ declare const createQueues: (options: LunoraQueuesOptions) => Queues;
282
+ /**
283
+ * The wrangler producer binding name for a queue export: `emailQueue` →
284
+ * `QUEUE_EMAIL_QUEUE`, `email` → `QUEUE_EMAIL`. The `QUEUE_` prefix namespaces
285
+ * these away from `SHARD`/`SESSION`/`SCHEDULER`/`WORKFLOW_*`/`CONTAINER_*` so a
286
+ * queue export can never collide with the built-in bindings.
287
+ */
288
+ declare const queueBindingName: (exportName: string) => string;
289
+ /**
290
+ * The stable queue name wrangler registers (`queues.producers[].queue` and
291
+ * `queues.consumers[].queue`): `emailQueue` → `email-queue`. Used as the
292
+ * deployed queue's identifier when no explicit `name` override is given.
293
+ */
294
+ declare const queueDefaultName: (exportName: string) => string;
295
+ /**
296
+ * Declare a Cloudflare Queue deployed alongside the app. Pure validation +
297
+ * branding: codegen discovers the export, emits the typed `ctx.queues.&lt;name>`
298
+ * producer and (for push consumers) the worker `queue()` dispatch; the config
299
+ * layer reconciles the wrangler `queues.producers[]` / `queues.consumers[]`
300
+ * entries from the same definition.
301
+ *
302
+ * ```ts
303
+ * // lunora/queues.ts
304
+ * import { defineQueue } from "@lunora/queue";
305
+ * import { api } from "./_generated/api";
306
+ *
307
+ * export const emailQueue = defineQueue&lt;{ to: string }>({
308
+ * handler: async (ctx, batch) => {
309
+ * for (const message of batch.messages) {
310
+ * await ctx.run(api.email.send, { to: message.body.to });
311
+ * message.ack();
312
+ * }
313
+ * },
314
+ * });
315
+ * ```
316
+ *
317
+ * Enqueue from a mutation or action: `await ctx.queues.emailQueue.send({ to })`.
318
+ *
319
+ * ⚠️ **Privileged dispatch.** A push handler's `ctx.run(...)` calls back into
320
+ * Lunora functions over the admin-authenticated dispatch endpoint (the same
321
+ * trusted path the scheduler and workflows use), so those calls run with the
322
+ * system identity — **end-user RLS is not applied**. Treat a queue handler as
323
+ * trusted server code: validate `message.body` (it may be attacker-influenced if
324
+ * anything user-facing can enqueue) before acting on it, and don't forward an
325
+ * unchecked body straight into a privileged mutation.
326
+ */
327
+ declare const defineQueue: <Body = unknown>(config: QueueConfig<Body>) => QueueDefinition<Body>;
328
+ /** True when a value is a `defineQueue` result (the runtime brand check). */
329
+ declare const isQueueDefinition: (value: unknown) => value is QueueDefinition;
330
+ interface RunContextOptions {
331
+ env: Record<string, unknown>;
332
+ exportName: string;
333
+ fetchImpl?: typeof fetch;
334
+ }
335
+ /** Assemble the {@link QueueRunContext} passed to a `defineQueue` handler. */
336
+ declare const createQueueRunContext: (options: RunContextOptions) => QueueRunContext;
337
+ export { type ArgsOf, type CapturedQueueMessage, type FunctionReference, type LunoraQueuesOptions, type MessageBatchLike, type MessageLike, type MessageSendRequestLike, type QueueBindingLike, type QueueBindingSpec, type QueueCaptureOptions, type QueueCaptureSink, type QueueConfig, type QueueConsumerMode, type QueueConsumerTuning, type QueueContentType, type QueueDefinition, type QueueEnv, type QueueHandler, type DispatchLogger as QueueLogger, type QueueProducer, type QueueRegistry, type QueueRegistryEntry, type QueueRetryOptions, type QueueRunContext, type DispatchRunFunction as QueueRunFunction, type QueueSendBatchOptions, type QueueSendOptions, type Queues, type RunFunctionOptions, createQueueCaptureSink, createQueueContext, createQueueRunContext, createQueues, defineQueue, dispatchQueueBatch, isQueueDefinition, queueBindingName, queueDefaultName, shouldCaptureQueue };