@lunora/queue 1.0.0-alpha.9 → 1.0.0-alpha.91

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
@@ -1,3 +1,5 @@
1
+ import { QueueBindingLike, MessageBatchLike, MessageLike, QueueSendOptions, MessageSendRequestLike, QueueSendBatchOptions } from '@lunora/platform';
2
+ export type { MessageBatchLike, MessageLike, MessageSendRequestLike, QueueBindingLike, QueueContentType, QueueRetryOptions, QueueSendBatchOptions, QueueSendOptions } from '@lunora/platform';
1
3
  /**
2
4
  * Shared types for dispatching a Lunora function back into the worker from a
3
5
  * server-initiated context (a workflow body, a queue handler, a scheduled job).
@@ -12,8 +14,45 @@ interface FunctionReference {
12
14
  type ArgsOf<F> = F extends FunctionReference ? Record<string, unknown> : never;
13
15
  /** Options for a function call made via a dispatch runner. */
14
16
  interface RunFunctionOptions {
17
+ /**
18
+ * The at-least-once dedup key for THIS ONE CALL, sent to the dispatch
19
+ * endpoint as the body's `id` and forwarded to the shard as the
20
+ * replay-dedup `mutationId` — so a redelivery that re-runs the same call
21
+ * applies it exactly once instead of twice.
22
+ *
23
+ * Must be unique per call and stable across redeliveries. It is NOT
24
+ * {@link RunFunctionOptions.messageId}: the shard's dedup table is keyed
25
+ * `(identity, mutationId)` with no function path in it, and every
26
+ * server-initiated dispatch shares the `"system:"` identity, so reusing
27
+ * one id across two calls makes the second return the FIRST call's cached
28
+ * result without ever executing. A per-message id is 1:N with the calls a
29
+ * handler makes; this is 1:1.
30
+ *
31
+ * `@lunora/queue`'s `message.run` derives one automatically as
32
+ * `<messageId>#<n>`, `n` counting that message's calls in order. That is
33
+ * stable across redeliveries because the handler replays from the start —
34
+ * it relies on the handler issuing its `run` calls in a DETERMINISTIC
35
+ * order, which at-least-once replay already assumes. A handler whose call
36
+ * order varies per attempt (branching on `Date.now()`, `Math.random()`,
37
+ * or unordered concurrent settles) must pass its own stable ids instead.
38
+ *
39
+ * Optional; when omitted the dispatch is at-least-once.
40
+ */
41
+ dedupId?: string;
42
+ /**
43
+ * Correlate this call with a caller-defined message/item id (e.g. a queue
44
+ * message's `id`), for failure attribution only — never sent to the
45
+ * dispatch endpoint. Carried onto the `LunoraError` a deterministic
46
+ * dispatch failure throws, so a batching consumer (`@lunora/queue`'s push
47
+ * handler) can read it back and attribute the failure to the one item that
48
+ * caused it instead of the whole batch. Deliberately NOT the dedup key —
49
+ * see {@link RunFunctionOptions.dedupId}. Optional and inert when omitted.
50
+ */
51
+ messageId?: string;
15
52
  /** Route the call to a specific shard (defaults to the worker's root shard). */
16
53
  shardKey?: string;
54
+ /** Abort the dispatch after this many ms; the abort is retryable. Overrides the runner's default. */
55
+ timeoutMs?: number;
17
56
  }
18
57
  /** Invoke a Lunora function (query/mutation/action) by reference. The shape of `ctx.run`. */
19
58
  type DispatchRunFunction = <F extends FunctionReference>(function_: F, args?: ArgsOf<F>, options?: RunFunctionOptions) => Promise<unknown>;
@@ -24,62 +63,8 @@ interface DispatchLogger {
24
63
  info: (message: unknown, ...rest: unknown[]) => void;
25
64
  warn: (message: unknown, ...rest: unknown[]) => void;
26
65
  }
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
66
  /**
82
- * The typed producer bound to `ctx.queues.&lt;name>`. Sending is a side effect, so
67
+ * The typed producer bound to `ctx.queues.<name>`. Sending is a side effect, so
83
68
  * the generated context exposes this only on `MutationCtx` / `ActionCtx` (never
84
69
  * the deterministic `QueryCtx`), mirroring `ctx.scheduler` / `ctx.workflows`.
85
70
  */
@@ -113,13 +98,39 @@ interface QueueRunContext {
113
98
  readonly env: Record<string, unknown>;
114
99
  /** Queue-name-prefixed logger. */
115
100
  readonly log: DispatchLogger;
116
- /** Invoke a Lunora function (query/mutation/action) by reference. */
101
+ /**
102
+ * Invoke a Lunora function (query/mutation/action) by reference.
103
+ *
104
+ * Batch-unaware: a failure it throws is attributed to nothing, so a
105
+ * deterministic failure retries the whole batch. Inside the `batch.messages`
106
+ * loop, prefer {@link QueueMessage.run}, which pins the call to its message.
107
+ */
108
+ readonly run: DispatchRunFunction;
109
+ }
110
+ /**
111
+ * One delivered message as the push handler sees it: the Cloudflare `Message`
112
+ * plus `run` — a {@link QueueRunContext.run} pinned to THIS message.
113
+ *
114
+ * Prefer `message.run(api.x.y, args)` over `ctx.run(...)` inside the batch
115
+ * loop. The pin is what lets the dispatcher attribute a deterministic dispatch
116
+ * failure (400/403/404/422) to the one message that caused it: that message is
117
+ * acked and every other one is retried, instead of the whole batch being
118
+ * re-delivered because of a single poison message. A plain `ctx.run` call
119
+ * carries no message id, so its failure stays unattributed and the whole batch
120
+ * retries.
121
+ */
122
+ interface QueueMessage<Body = unknown> extends MessageLike<Body> {
123
+ /** {@link QueueRunContext.run}, pinned to this message for failure attribution. */
117
124
  readonly run: DispatchRunFunction;
118
125
  }
126
+ /** The delivered batch as the push handler sees it — {@link QueueMessage}s rather than bare `Message`s. */
127
+ interface QueueMessageBatch<Body = unknown> extends Omit<MessageBatchLike<Body>, "messages"> {
128
+ readonly messages: ReadonlyArray<QueueMessage<Body>>;
129
+ }
119
130
  /** Whether a declared queue is consumed by this worker (push) or polled externally (pull). */
120
131
  type QueueConsumerMode = "pull" | "push";
121
132
  /** The handler body run for each delivered batch (push consumers only). */
122
- type QueueHandler<Body = unknown> = (context: QueueRunContext, batch: MessageBatchLike<Body>) => Promise<void> | void;
133
+ type QueueHandler<Body = unknown> = (context: QueueRunContext, batch: QueueMessageBatch<Body>) => Promise<void> | void;
123
134
  /** Push-consumer batch/retry tuning, mirrored onto the wrangler `queues.consumers[]` entry. */
124
135
  interface QueueConsumerTuning {
125
136
  /** Name of the dead-letter queue messages land in after `maxRetries`. */
@@ -128,7 +139,7 @@ interface QueueConsumerTuning {
128
139
  maxBatchSize?: number;
129
140
  /** Max seconds to wait before delivering a partial batch (0–60, default 5). */
130
141
  maxBatchTimeout?: number;
131
- /** Max delivery attempts before a message is dropped / dead-lettered (default 3). */
142
+ /** Retries **after** the initial delivery, before a message is dropped / dead-lettered. Default 3, so up to 4 deliveries in total. */
132
143
  maxRetries?: number;
133
144
  /** Delay in seconds before a failed batch is retried. */
134
145
  retryDelay?: number;
@@ -152,13 +163,71 @@ interface QueueConfig<Body = unknown> extends QueueConsumerTuning {
152
163
  interface QueueDefinition<Body = unknown> extends QueueConfig<Body> {
153
164
  /**
154
165
  * 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).
166
+ * generated `ctx.queues.<name>` producer as `QueueProducer<Body>` from
167
+ * `typeof <export>`. Never assigned at runtime (type-only).
157
168
  */
158
169
  readonly __lunoraBody?: Body;
159
170
  /** Runtime brand identifying a `defineQueue` result. */
160
171
  isLunoraQueue: true;
161
172
  }
173
+ /**
174
+ * The typed publisher bound to `ctx.topics.<name>`. A publish is one send to
175
+ * **each** subscription's queue, in parallel, so it is not atomic: when one send
176
+ * fails the call rejects, and a retry re-delivers to the subscriptions whose send
177
+ * already succeeded. Delivery is at-least-once per subscription — make handlers
178
+ * idempotent. A topic with no subscriptions publishes to nobody.
179
+ */
180
+ interface TopicPublisher<Payload = unknown> {
181
+ /** Publish one message to every subscription. */
182
+ publish: (payload: Payload, options?: QueueSendOptions) => Promise<void>;
183
+ /** Publish a batch (at most 100) to every subscription in one send per subscription. */
184
+ publishBatch: (messages: Iterable<MessageSendRequestLike<Payload>>, options?: QueueSendBatchOptions) => Promise<void>;
185
+ }
186
+ /** `ctx.topics` — declared topic export names → typed publishers. Codegen narrows it to the exact names. */
187
+ interface Topics {
188
+ [exportName: string]: TopicPublisher;
189
+ }
190
+ /** The branded result of `defineTopic`, discovered by codegen. Carries no deploy config of its own. */
191
+ interface TopicDefinition<Payload = unknown> {
192
+ /**
193
+ * Phantom carrier for the payload type, so codegen can type `ctx.topics.<name>`.
194
+ * Named like {@link QueueDefinition}'s so one emitted helper reads both. Never
195
+ * assigned at runtime.
196
+ */
197
+ readonly __lunoraBody?: Payload;
198
+ /** Runtime brand identifying a `defineTopic` result. */
199
+ isLunoraTopic: true;
200
+ }
201
+ /** The config passed to `defineSubscription`: a push consumer's handler plus its own retry/DLQ tuning. */
202
+ interface SubscriptionConfig<Payload = unknown> extends QueueConsumerTuning {
203
+ handler: QueueHandler<Payload>;
204
+ /**
205
+ * Stable wrangler queue name for this subscription. Defaults to the
206
+ * kebab-cased export name, exactly like a `defineQueue` export.
207
+ */
208
+ name?: string;
209
+ }
210
+ /**
211
+ * The branded result of `defineSubscription`: a push {@link QueueDefinition}
212
+ * (so dispatch, retries, the DLQ, wrangler reconcile and the studio treat it as
213
+ * the queue it is) tagged with the topic it consumes.
214
+ */
215
+ interface SubscriptionDefinition<Payload = unknown> extends QueueDefinition<Payload> {
216
+ handler: QueueHandler<Payload>;
217
+ mode: "push";
218
+ /** The topic this subscription consumes. */
219
+ topic: TopicDefinition<Payload>;
220
+ }
221
+ /** Wiring info for one declared topic, emitted by codegen into the generated shard. */
222
+ interface TopicBindingSpec {
223
+ /** The `lunora/queues.ts` topic export name, e.g. `signups`. */
224
+ exportName: string;
225
+ /** One entry per subscription: its export name and its `Queue` producer binding. */
226
+ subscriptions: ReadonlyArray<{
227
+ binding: string;
228
+ exportName: string;
229
+ }>;
230
+ }
162
231
  /** Wiring info for one declared queue, emitted by codegen into the generated shard/handler. */
163
232
  interface QueueBindingSpec {
164
233
  /** The Cloudflare `Queue` producer binding name, e.g. `QUEUE_EMAIL`. */
@@ -170,11 +239,18 @@ interface QueueBindingSpec {
170
239
  }
171
240
  /** One declared queue, keyed for batch routing by its stable wrangler name. */
172
241
  interface QueueRegistryEntry {
242
+ /**
243
+ * The queue's own producer binding on `env` (`QUEUE_*`). A message whose
244
+ * dispatch is declined on its last delivery is re-enqueued through it (see
245
+ * {@link resolveDeclinedBatch}); without it that message is dead-lettered or
246
+ * dropped, and logged. Codegen always emits it.
247
+ */
248
+ binding?: string;
173
249
  /**
174
250
  * The `defineQueue` result (carries the push handler). The body type is
175
251
  * erased to `any` here because the registry is heterogeneous — different
176
252
  * queues carry different message bodies, and the handler param is
177
- * contravariant, so a precise `QueueDefinition&lt;Body>` would not be assignable
253
+ * contravariant, so a precise `QueueDefinition<Body>` would not be assignable
178
254
  * to a shared `unknown`-bodied slot. Runtime dispatch passes the delivered
179
255
  * batch straight through, so the erasure is type-only.
180
256
  */
@@ -197,7 +273,28 @@ interface CapturedQueueMessage {
197
273
  attempts: number;
198
274
  /** The message body (JSON-encoded + capped by the catcher). */
199
275
  body: unknown;
200
- /** `true` when this failed delivery was the message's last (its retries are exhausted — the broker dead-letters it). */
276
+ /**
277
+ * `true` when this failed delivery was the message's last (its retries are
278
+ * exhausted) AND the queue declares a `deadLetterQueue` for it to land in.
279
+ * Stays `false` for a queue with no DLQ, where the broker drops the
280
+ * exhausted message instead — `attempts > maxRetries` with
281
+ * `outcome !== "ack"` is what identifies that case.
282
+ *
283
+ * Read from the `defineQueue` DECLARATION, because a consumer has no
284
+ * runtime API that exposes its deployed `queues.consumers[]` settings. It is
285
+ * true of the deployed broker only as far as Lunora's binding reconcile (run
286
+ * by `lunora dev`, `deploy` and `prepare`) keeps the two in step: it writes
287
+ * every declared tuning field onto the consumer, including onto one that
288
+ * already exists, and takes a field back out once `defineQueue` drops it
289
+ * (it records what `defineQueue` declared in `package.json`
290
+ * `lunora.queueTuning`). The gaps that remain: a field changed by hand to
291
+ * another value than the declared one is
292
+ * kept when the declaration drops it, so a hand-set DLQ still reads
293
+ * `false` here; a `--env` deploy retunes the `env.<name>` consumers but
294
+ * never writes their `dead_letter_queue`, which that block names itself;
295
+ * and a bare `wrangler deploy` over a hand-edited consumer can disagree
296
+ * too. Nothing on this side can see any of it.
297
+ */
201
298
  deadLettered: boolean;
202
299
  /** Handler error message when `outcome` is `error`; absent otherwise. */
203
300
  error?: string;
@@ -221,16 +318,25 @@ interface CapturedQueueMessage {
221
318
  type QueueCaptureSink = (messages: CapturedQueueMessage[]) => Promise<void> | void;
222
319
  interface DispatchOptions {
223
320
  /**
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.
321
+ * Optional capture sink. When set, every message's final disposition is
322
+ * turned into a record and handed to this sink after the handler runs.
323
+ * Omitted in production unless queue capture is enabled, so a consumer pays
324
+ * no record-building or sink cost by default. Delivery semantics — including
325
+ * poison-message isolation — do not depend on it.
228
326
  */
229
327
  capture?: QueueCaptureSink;
230
328
  /** Worker `env`, forwarded to the queue run context. */
231
329
  env: Record<string, unknown>;
232
330
  /** Injectable fetch for the `ctx.run` dispatcher (tests). */
233
331
  fetchImpl?: typeof fetch;
332
+ /**
333
+ * W3C `traceparent` of the consumer invocation's own trace, supplied by the
334
+ * runtime's `queue()` entry. Forwarded on every `ctx.run` dispatch so the
335
+ * functions a handler calls are CHILDREN of the queue span instead of a set of
336
+ * unrelated root traces. Absent (a hand-built dispatch, a unit test) keeps the
337
+ * prior behaviour: the callee mints its own trace.
338
+ */
339
+ traceparent?: string;
234
340
  }
235
341
  /**
236
342
  * Look up the handler for `batch.queue` and invoke it with a fresh
@@ -268,7 +374,7 @@ declare const createQueueCaptureSink: (env: QueueEnv, options?: QueueCaptureOpti
268
374
  * Build the `ctx.queues` map for a request: resolve every spec's `env[binding]`
269
375
  * into the `exportName → Queue binding` map and wrap it in {@link createQueues}.
270
376
  * 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
377
+ * queue named …" error is raised lazily by `ctx.queues.<name>.send(...)` when
272
378
  * the missing queue is actually used.
273
379
  */
274
380
  declare const createQueueContext: (env: Record<string, unknown>, specs: ReadonlyArray<QueueBindingSpec>) => Queues;
@@ -282,7 +388,7 @@ declare const createQueues: (options: LunoraQueuesOptions) => Queues;
282
388
  /**
283
389
  * The wrangler producer binding name for a queue export: `emailQueue` →
284
390
  * `QUEUE_EMAIL_QUEUE`, `email` → `QUEUE_EMAIL`. The `QUEUE_` prefix namespaces
285
- * these away from `SHARD`/`SESSION`/`SCHEDULER`/`WORKFLOW_*`/`CONTAINER_*` so a
391
+ * these away from `SHARD`/`SESSION`/`SCHEDULER`/`CONTAINER_*` so a
286
392
  * queue export can never collide with the built-in bindings.
287
393
  */
288
394
  declare const queueBindingName: (exportName: string) => string;
@@ -294,7 +400,7 @@ declare const queueBindingName: (exportName: string) => string;
294
400
  declare const queueDefaultName: (exportName: string) => string;
295
401
  /**
296
402
  * Declare a Cloudflare Queue deployed alongside the app. Pure validation +
297
- * branding: codegen discovers the export, emits the typed `ctx.queues.&lt;name>`
403
+ * branding: codegen discovers the export, emits the typed `ctx.queues.<name>`
298
404
  * producer and (for push consumers) the worker `queue()` dispatch; the config
299
405
  * layer reconciles the wrangler `queues.producers[]` / `queues.consumers[]`
300
406
  * entries from the same definition.
@@ -304,10 +410,10 @@ declare const queueDefaultName: (exportName: string) => string;
304
410
  * import { defineQueue } from "@lunora/queue";
305
411
  * import { api } from "./_generated/api";
306
412
  *
307
- * export const emailQueue = defineQueue&lt;{ to: string }>({
413
+ * export const emailQueue = defineQueue<{ to: string }>({
308
414
  * handler: async (ctx, batch) => {
309
415
  * for (const message of batch.messages) {
310
- * await ctx.run(api.email.send, { to: message.body.to });
416
+ * await message.run(api.email.send, { to: message.body.to });
311
417
  * message.ack();
312
418
  * }
313
419
  * },
@@ -316,6 +422,12 @@ declare const queueDefaultName: (exportName: string) => string;
316
422
  *
317
423
  * Enqueue from a mutation or action: `await ctx.queues.emailQueue.send({ to })`.
318
424
  *
425
+ * `message.run(...)` is `ctx.run(...)` pinned to that message — prefer it inside
426
+ * the batch loop. A deterministic failure (400/403/404/422) from a pinned call
427
+ * is attributed to its message: that one is acked and the rest are retried,
428
+ * instead of one poison message re-delivering (and eventually dead-lettering)
429
+ * the whole batch.
430
+ *
319
431
  * ⚠️ **Privileged dispatch.** A push handler's `ctx.run(...)` calls back into
320
432
  * Lunora functions over the admin-authenticated dispatch endpoint (the same
321
433
  * trusted path the scheduler and workflows use), so those calls run with the
@@ -331,7 +443,29 @@ interface RunContextOptions {
331
443
  env: Record<string, unknown>;
332
444
  exportName: string;
333
445
  fetchImpl?: typeof fetch;
446
+ /** The consumer invocation's `traceparent`, so `ctx.run` joins the queue's trace. */
447
+ traceparent?: string;
334
448
  }
335
449
  /** Assemble the {@link QueueRunContext} passed to a `defineQueue` handler. */
336
450
  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 };
451
+ /**
452
+ * Declare a topic in `lunora/queues.ts`. The payload type is the only thing a
453
+ * topic carries; delivery config lives on each subscription.
454
+ */
455
+ declare const defineTopic: <Payload = unknown>() => TopicDefinition<Payload>;
456
+ /**
457
+ * Subscribe to a topic. The result is a push queue definition — export it from
458
+ * `lunora/queues.ts` and it deploys, retries and dead-letters exactly like a
459
+ * `defineQueue` export of the same name.
460
+ *
461
+ * ⚠️ Same trust model as a queue handler: `message.run(...)` dispatches with the
462
+ * system identity, so validate `message.body` before acting on it.
463
+ */
464
+ declare const defineSubscription: <Payload>(topic: TopicDefinition<Payload>, config: SubscriptionConfig<Payload>) => SubscriptionDefinition<Payload>;
465
+ /**
466
+ * Build `ctx.topics` for a request from the Worker `env` and the codegen-emitted
467
+ * specs. A topic with no subscriptions publishes to nobody; a topic with an
468
+ * unbound subscription rejects every publish (see {@link unboundPublisher}).
469
+ */
470
+ declare const createTopicContext: (env: Record<string, unknown>, specs: ReadonlyArray<TopicBindingSpec>) => Topics;
471
+ export { type ArgsOf, type CapturedQueueMessage, type FunctionReference, type LunoraQueuesOptions, type QueueBindingSpec, type QueueCaptureOptions, type QueueCaptureSink, type QueueConfig, type QueueConsumerMode, type QueueConsumerTuning, type QueueDefinition, type QueueEnv, type QueueHandler, type DispatchLogger as QueueLogger, type QueueMessage, type QueueMessageBatch, type QueueProducer, type QueueRegistry, type QueueRegistryEntry, type QueueRunContext, type DispatchRunFunction as QueueRunFunction, type Queues, type RunFunctionOptions, type SubscriptionConfig, type SubscriptionDefinition, type TopicBindingSpec, type TopicDefinition, type TopicPublisher, type Topics, createQueueCaptureSink, createQueueContext, createQueueRunContext, createQueues, createTopicContext, defineQueue, defineSubscription, defineTopic, dispatchQueueBatch, isQueueDefinition, queueBindingName, queueDefaultName, shouldCaptureQueue };
package/dist/index.mjs CHANGED
@@ -1,6 +1 @@
1
- export { createQueueCaptureSink, shouldCaptureQueue } from './packem_shared/createQueueCaptureSink-B8WE0eHf.mjs';
2
- export { createQueueContext } from './packem_shared/createQueueContext-D0XCdCsd.mjs';
3
- export { default as createQueues } from './packem_shared/createQueues-14-vSICK.mjs';
4
- export { defineQueue, isQueueDefinition, queueBindingName, queueDefaultName } from './packem_shared/defineQueue-D40gREfg.mjs';
5
- export { dispatchQueueBatch } from './packem_shared/dispatchQueueBatch-DSEWhEy8.mjs';
6
- export { createQueueRunContext } from './packem_shared/createQueueRunContext-C8jboCk6.mjs';
1
+ import{createQueueCaptureSink as t,shouldCaptureQueue as o}from"./packem_shared/createQueueCaptureSink-CSOPftvj.mjs";import{createQueueContext as i}from"./packem_shared/createQueueContext-aj6p-gxk.mjs";import{createQueues as n}from"./packem_shared/createQueues-BVaXTnAh.mjs";import{defineQueue as f,isQueueDefinition as c,queueBindingName as x,queueDefaultName as m}from"./packem_shared/defineQueue-TY4-i3nG.mjs";import{dispatchQueueBatch as d}from"./packem_shared/dispatchQueueBatch-B8GbPNBs.mjs";import{c as C}from"./packem_shared/run-context-wO-J6k6F.mjs";import{createTopicContext as l,defineSubscription as q,defineTopic as B}from"./packem_shared/createTopicContext-nG16dV5W.mjs";export{t as createQueueCaptureSink,i as createQueueContext,C as createQueueRunContext,n as createQueues,l as createTopicContext,f as defineQueue,q as defineSubscription,B as defineTopic,d as dispatchQueueBatch,c as isQueueDefinition,x as queueBindingName,m as queueDefaultName,o as shouldCaptureQueue};
@@ -0,0 +1 @@
1
+ import{LunoraError as E}from"@lunora/errors";const _="__lunora_admin__:recordQueueMessage",N="__root__",f=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,p=["CF_ENV","ENVIRONMENT","NODE_ENV","WORKER_ENV"],T=5e3,O=o=>{const t=o.LUNORA_QUEUE_CAPTURE;if(typeof t=="string"){const e=t.toLowerCase();if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;console.warn(`@lunora/queue: unrecognized LUNORA_QUEUE_CAPTURE value "${t}" — expected "1"/"true" or "0"/"false"; falling back to environment detection.`)}return p.some(e=>{const r=o[e];return typeof r=="string"&&f.test(r)})},h=(o,t={})=>{const e=t.rootShard??N;return async r=>{if(r.length===0)return;const i=o.SHARD,s=typeof o.LUNORA_ADMIN_TOKEN=="string"?o.LUNORA_ADMIN_TOKEN:void 0;if(i===void 0||s===void 0)return;let a=i;if(t.jurisdiction!==void 0){if(typeof i.jurisdiction!="function")throw new TypeError(`@lunora/queue: Durable Object namespace does not support jurisdiction("${t.jurisdiction}") — update @cloudflare/workers-types or remove the jurisdiction option`);a=i.jurisdiction(t.jurisdiction)}const l=a.get(a.idFromName(e)),u=new AbortController,d=setTimeout(()=>{u.abort()},T);try{const n=await l.fetch("https://shard.internal/rpc",{body:JSON.stringify({args:{messages:r},functionPath:_}),headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},method:"POST",signal:u.signal});if(!n.ok){const c=await n.text().catch(()=>"");throw new E("INTERNAL",`@lunora/queue: capture write to the root shard failed (${String(n.status)} ${n.statusText})${c===""?"":`: ${c}`}`)}await n.body?.cancel()}finally{clearTimeout(d)}}};export{h as createQueueCaptureSink,O as shouldCaptureQueue};
@@ -0,0 +1 @@
1
+ import{resolveQueueBinding as r,createQueues as s}from"./createQueues-BVaXTnAh.mjs";const u=(t,i)=>{const e={};for(const n of i){const o=r(t,n.binding);o&&(e[n.exportName]=o)}return s({bindings:e})};export{u as createQueueContext};
@@ -0,0 +1 @@
1
+ import{c as o}from"./run-context-wO-J6k6F.mjs";export{o as createQueueRunContext};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import{h as g,R as h}from"./requeue-envelope-BjL4JftH.mjs";const i=100,d=43200,l=(t,n)=>{if(t!==void 0&&t>d)throw new a("VALIDATION_ERROR",`@lunora/queue: ${n} delaySeconds is ${String(t)}, over the Cloudflare Queues ceiling of ${String(d)} (12 hours) — use @lunora/scheduler for longer schedules`)},$=(t,n)=>{if(g(t))throw new a("VALIDATION_ERROR",`@lunora/queue: ${n} body may not contain the reserved key "${h}"`)},f=(t,n,e)=>{l(n?.delaySeconds,e),$(t,e)},E=(t,n,e)=>{l(n?.delaySeconds,e);const s=[...t];if(s.length>i)throw new a("VALIDATION_ERROR",`@lunora/queue: ${e} exceeds ${String(i)} (got ${String(s.length)}) — split across calls`);for(const[r,o]of s.entries())f(o.body,o,`${e} message ${String(r)}`);return s},O=t=>({send:async(n,e)=>{f(n,e,"send"),await t.send(n,e)},sendBatch:async(n,e)=>{await t.sendBatch(E(n,e,"sendBatch"),e)}}),y=(t,n)=>{const e=t[n];return e&&typeof e.send=="function"&&typeof e.sendBatch=="function"?e:void 0},R=(t,n,e)=>{const s=Object.assign(Object.create(null),t),r=Object.keys(s),o=r.length===0?`no ${n}s are declared`:`known ${n}s: ${r.join(", ")}`;return new Proxy(s,{get(u,c){if(typeof c=="string")return Object.hasOwn(u,c)?u[c]:e(()=>Promise.reject(new Error(`@lunora/queue: no ${n} named "${c}" (${o})`)))}})},w=t=>{const n=t.bindings??{},e={};for(const[s,r]of Object.entries(n))e[s]=O(r);return R(e,"queue",s=>({send:s,sendBatch:s}))};export{f as assertSendable,w as createQueues,R as namedLookup,E as prepareBatch,y as resolveQueueBinding};
@@ -0,0 +1 @@
1
+ import{resolveQueueBinding as c,namedLookup as p,prepareBatch as a,assertSendable as h}from"./createQueues-BVaXTnAh.mjs";const f=()=>({isLunoraTopic:!0}),b=n=>typeof n=="object"&&n!==null&&n.isLunoraTopic===!0,w=(n,e)=>{if(!b(n))throw new TypeError("defineSubscription: the first argument must be a `defineTopic()` result");if(typeof e.handler!="function")throw new TypeError("defineSubscription: `handler` must be a function");if(e.name!==void 0&&(typeof e.name!="string"||e.name.length===0))throw new TypeError("defineSubscription: `name` must be a non-empty string when provided");return{...e,isLunoraQueue:!0,mode:"push",topic:n}},l=n=>({publish:async(e,t)=>{h(e,t,"publish"),await Promise.all(n.map(async r=>r.send(e,t)))},publishBatch:async(e,t)=>{const r=a(e,t,"publishBatch");await Promise.all(n.map(async i=>i.sendBatch(r,t)))}}),d=n=>{const e=()=>Promise.reject(new Error(`@lunora/queue: missing queue binding(s) ${n.join(", ")} — add them to wrangler.jsonc (lunora dev reconciles them); nothing was published`));return{publish:e,publishBatch:e}},y=(n,e)=>{const t={};for(const r of e){const i=[],s=[];for(const o of r.subscriptions){const u=c(n,o.binding);u?i.push(u):s.push(o.binding)}t[r.exportName]=s.length>0?d(s):l(i)}return p(t,"topic",r=>({publish:r,publishBatch:r}))};export{y as createTopicContext,w as defineSubscription,f as defineTopic};
@@ -0,0 +1 @@
1
+ const n=e=>`QUEUE_${e.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g,"_").toUpperCase()}`,t=e=>e.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g,"-").toLowerCase(),o=e=>{const u=e.mode??"push";if(u!=="push"&&u!=="pull")throw new TypeError(`defineQueue: \`mode\` must be "push" or "pull" (got ${JSON.stringify(e.mode)})`);if(u==="push"&&typeof e.handler!="function")throw new TypeError('defineQueue: `handler` must be a function for a push consumer (omit it only when `mode: "pull"`)');if(e.name!==void 0&&(typeof e.name!="string"||e.name.length===0))throw new TypeError("defineQueue: `name` must be a non-empty string when provided");return{...e,isLunoraQueue:!0,mode:u}},r=e=>typeof e=="object"&&e!==null&&e.isLunoraQueue===!0;export{o as defineQueue,r as isQueueDefinition,n as queueBindingName,t as queueDefaultName};
@@ -0,0 +1 @@
1
+ import{c as h,u as x,f as N,a as q,d as k,o as R}from"./run-context-wO-J6k6F.mjs";import{LunoraError as $,toErrorBody as M}from"@lunora/errors";import{s as A,o as I}from"./requeue-envelope-BjL4JftH.mjs";const b=e=>typeof e.definition.maxRetries=="number"?e.definition.maxRetries:R,O=e=>{if(e instanceof Date)return e.getTime();const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:0},T=async(e,t)=>{const o=await I(t,e.body).catch(()=>{});return o===void 0?{body:e.body,id:e.id,requeued:!1}:{...o,requeued:!0}},g=e=>{const t=e.LUNORA_ADMIN_TOKEN;return typeof t=="string"&&t.length>0?t:void 0},B=(e,t)=>{let o=0;return(i,n,r)=>(o+=1,e(i,n,{...r,dedupId:`${t}#${String(o)}`,messageId:t}))},L=(e,t,o,i)=>{const n=B(i,t.id);return new Proxy(e,{get:(r,s)=>s==="id"?t.id:s==="body"?t.body:s==="ack"?()=>{o.set(r,"ack"),r.ack()}:s==="retry"?f=>{o.set(r,"retry"),r.retry(f)}:s==="run"?n:Reflect.get(r,s,r)})},S=(e,t,o)=>new Proxy(e,{get:(i,n)=>n==="ackAll"?()=>{o("ack"),i.ackAll()}:n==="retryAll"?r=>{o("retry"),i.retryAll(r)}:n==="messages"?t:Reflect.get(i,n,i)}),j=async(e,t,o)=>{const i=new Map,n=e.messages,r=new Map,s=[];for(const c of n){const u=await T(c,o);r.set(c,u),s.push(L(c,u,i,t))}const l=S(e,s,c=>{for(const u of n)i.has(u)||i.set(u,c)});return{dispositions:i,originals:n,requeued:new Set,views:r,wrappedBatch:l}},w=(e,t)=>e.views.get(t)??{body:t.body,id:t.id,requeued:!1},v=(e,t)=>w(e,t).id,Q=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e!==null&&typeof e=="object")try{return JSON.stringify(e)}catch{return"[unserializable thrown value]"}return String(e)},D=(e,t,o,i,n,r)=>{const s=i?Q(n):void 0,f=b(t),l=i?"error":"ack",c=typeof t.definition.deadLetterQueue=="string"&&t.definition.deadLetterQueue.length>0;return e.originals.map(u=>{const d=u===r,a=e.dispositions.get(u),p=d?"error":a??l,m=typeof u.attempts=="number"?u.attempts:1,y=w(e,u);return{attempts:m,body:y.body,deadLettered:c&&!d&&!e.requeued.has(u)&&p!=="ack"&&m>f,error:p==="error"?s:void 0,exportName:t.exportName,messageId:y.id,outcome:p,queue:o,timestamp:O(u.timestamp)}})},C=(e,t,o)=>{if(!t||!N(o))return;const i=q(o);if(i===void 0)return;const n=e.originals.find(r=>v(e,r)===i);if(!(n===void 0||e.dispositions.has(n)))return n},P=(e,t)=>{t.ack();for(const o of e.originals)o!==t&&!e.dispositions.has(o)&&(e.dispositions.set(o,"retry"),o.retry())},F=async(e,t,o,i,n)=>{const r=g(n),s=q(t),f=e.originals.find(d=>v(e,d)===s&&!e.dispositions.has(d)),l=`@lunora/queue: queue "${i}" (${o.exportName})`,c=o.binding===void 0?void 0:n[o.binding],u=[];for(const d of e.originals)if(!e.dispositions.has(d)){if(e.dispositions.set(d,"retry"),f!==void 0&&d!==f){d.retry();continue}u.push(d)}await Promise.all(u.map(async d=>{const a=w(e,d),p=typeof c?.send!="function"||a.requeued||r===void 0?void 0:async m=>{await c.send(await A(r,a.id,a.body),{contentType:"json",delaySeconds:m})};await k(d,{maxRetries:b(o),requeue:p,where:l})==="requeued"&&e.requeued.add(d)}))},E=async(e,t,o)=>{const i=Object.hasOwn(t,e.queue)?t[e.queue]:void 0;if(i===void 0){const a=Object.keys(t),p=a.length===0?"no push queues are declared":`known push queues: ${a.join(", ")}`;throw new $("INTERNAL",`@lunora/queue: received a batch for queue "${e.queue}" but no push handler is registered (${p})`)}const{handler:n}=i.definition;if(typeof n!="function")throw new TypeError(`@lunora/queue: queue "${e.queue}" (${i.exportName}) has no push handler — it is declared as a pull consumer`);const r=h({env:o.env,exportName:i.exportName,fetchImpl:o.fetchImpl,...o.traceparent===void 0?{}:{traceparent:o.traceparent}}),s=await j(e,r.run,g(o.env));let f=!1,l;try{await n(r,s.wrappedBatch)}catch(a){f=!0,l=a}const c=C(s,f,l);if(c!==void 0){P(s,c);const{body:a,status:p}=M(l,{redactedMessage:"internal error"});console.error(`@lunora/queue: dropped message ${v(s,c)} on queue "${e.queue}" (${i.exportName}) — a dispatch it made failed with a deterministic ${String(p)} (${a.code}: ${a.message}), so it was acked, not retried. Its retries are NOT exhausted and it is not dead-lettered — it will never be redelivered.`)}const u=f&&x(l);u&&await F(s,l,i,e.queue,o.env);const d=f&&c===void 0&&!u;if(o.capture!==void 0)try{await o.capture(D(s,i,e.queue,f,l,c))}catch(a){console.warn("@lunora/queue: capture sink failed (delivery unaffected):",a)}if(d)throw l};export{E as dispatchQueueBatch};
@@ -0,0 +1,4 @@
1
+ const T="lunora.requeue.v1",O=new TextEncoder,j=async(r,t)=>crypto.subtle.importKey("raw",O.encode(r),{hash:"SHA-256",name:"HMAC"},!1,[t]),S=(r,t,o)=>O.encode(`${T}
2
+ ${r}
3
+ ${t}
4
+ ${o}`),U=r=>[...new Uint8Array(r)].map(t=>t.toString(16).padStart(2,"0")).join(""),$=/^[\da-f]{64}$/u,I=async(r,t,o,i)=>U(await crypto.subtle.sign("HMAC",await j(r,"sign"),S(t,o,i))),N=async(r,t,o,i,s)=>{if(typeof s!="string"||!$.test(s))return!1;const e=Uint8Array.from({length:s.length/2},(n,c)=>Number.parseInt(s.slice(c*2,c*2+2),16));return crypto.subtle.verify("HMAC",await j(r,"verify"),e,S(t,o,i))},m=r=>{let t="";for(let i=0;i<r.length;i+=32768)t+=String.fromCharCode(...r.subarray(i,i+32768));return btoa(t)},_=r=>{const t=atob(r),o=new Uint8Array(t.length);for(let i=0;i<t.length;i+=1)o[i]=t.codePointAt(i)??0;return o},a="$lunora.wire$",w=64,l=1024,g="__proto__",A={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},E={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},k=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},b=(r,t=0)=>{if(t>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(r===void 0)return[a,"undefined"];if(r===null)return null;const o=typeof r;if(o==="bigint")return[a,"bigint",r.toString()];if(o==="number"){const e=r;return Number.isNaN(e)?[a,"nan"]:e===1/0?[a,"inf"]:e===-1/0?[a,"-inf"]:e}if(o!=="object")return r;if(r instanceof Date)return[a,"date",b(r.getTime(),t+1)];if(r instanceof Error){const e=r,n={};for(const f of Object.keys(e)){if(e[f]===void 0)continue;const u=b(e[f],t+1);f===g?Object.defineProperty(n,f,{configurable:!0,enumerable:!0,value:u,writable:!0}):n[f]=u}const c=[a,"error",String(e.name),String(e.message),n];return e.cause!==void 0&&c.push(b(e.cause,t+1)),c}if(r instanceof URL)return[a,"url",r.href];if(r instanceof Map)return[a,"map",[...r.entries()].map(([e,n])=>[b(e,t+1),b(n,t+1)])];if(r instanceof Set)return[a,"set",[...r].map(e=>b(e,t+1))];if(r instanceof ArrayBuffer)return[a,"bytes",m(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,n=e.constructor.name,c=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return n==="Uint8Array"?[a,"bytes",m(c)]:[a,"bytes",m(c),n]}if(Array.isArray(r)){const e=r.map(n=>b(n,t+1));return e.length>0&&e[0]===a?[a,"arr",e]:e}if(!k(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const i=r,s={};for(const e of Object.keys(i)){const n=i[e];if(n===void 0)continue;const c=b(n,t+1);e===g?Object.defineProperty(s,e,{configurable:!0,enumerable:!0,value:c,writable:!0}):s[e]=c}return s},y=(r,t=0)=>{if(t>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===a)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(e=>y(e,t+1));case"bigint":{const e=r[2];if(typeof e!="string"||e.length>l||!/^-?\d+$/.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${l} digits)`);return BigInt(e)}case"date":{const e=y(r[2],t+1);if(typeof e!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(e)}case"map":{const e=r[2];return new Map(e.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(r[2].map(e=>y(e,t+1)));case"url":{const e=r[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(e)}case"error":{const e=r[2],n=r[3];if(typeof e!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const c=(Object.hasOwn(E,e)?E[e]:void 0)??Error,f=new c(n);f.name!==e&&Object.defineProperty(f,"name",{configurable:!0,value:e,writable:!0});const u=y(r[4],t+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error — props must be an object");for(const d of Object.keys(u))d===g?Object.defineProperty(f,d,{configurable:!0,enumerable:!0,value:u[d],writable:!0}):f[d]=u[d];return r.length>5&&Object.defineProperty(f,"cause",{configurable:!0,value:y(r[5],t+1),writable:!0}),f}case"bytes":{const e=r[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=_(e);if(m(n)!==e)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const c=r[3]??"Uint8Array";if(c==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const f=Object.hasOwn(A,c)?A[c]:void 0;return f?new f(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(e=>y(e,t+1))}return r.map(s=>y(s,t+1))}const o=r,i={};for(const s of Object.keys(o)){const e=y(o[s],t+1);s===g?Object.defineProperty(i,s,{configurable:!0,enumerable:!0,value:e,writable:!0}):i[s]=e}return i},p="$lunora.requeued$",R="queue",h=128*1024,B=r=>typeof r=="object"&&r!==null&&Object.hasOwn(r,p),P=async(r,t,o)=>{const i=JSON.stringify(b(o)),s={[p]:{body:i,id:t,mac:await I(r,R,t,i)}},e=new TextEncoder().encode(JSON.stringify(s)).byteLength;if(e>h)throw new RangeError(`the copy would be ${String(e)} bytes, over the ${String(h)}-byte queue message limit`);return s},C=async(r,t)=>{if(r===void 0||!B(t))return;const o=t[p];if(!(typeof o?.id!="string"||typeof o.body!="string")&&await N(r,R,o.id,o.body,o.mac))return{body:y(JSON.parse(o.body)),id:o.id}};export{p as R,B as h,C as o,P as s};
@@ -0,0 +1 @@
1
+ import{LunoraError as b,isLunoraError as _}from"@lunora/errors";const J=r=>({debug:(e,...o)=>{console.debug(r,e,...o)},error:(e,...o)=>{console.error(r,e,...o)},info:(e,...o)=>{console.info(r,e,...o)},warn:(e,...o)=>{console.warn(r,e,...o)}}),K=9e5,L="DISPATCH_IN_PROGRESS",F="x-lunora-dispatch-declined",H=(r,e,o)=>{if(e===void 0)return{dispose:()=>{},signal:r};const a=new AbortController,n=setTimeout(()=>{a.abort(o())},e);return{dispose:()=>{clearTimeout(n)},signal:a.signal}},A=r=>{let e="";for(let o=0;o<r.length;o+=32768)e+=String.fromCharCode(...r.subarray(o,o+32768));return btoa(e)},W=r=>{const e=atob(r),o=new Uint8Array(e.length);for(let a=0;a<e.length;a+=1)o[a]=e.codePointAt(a)??0;return o},p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",U=r=>{let e="",o=0;const a=r.length-2;for(;o<a;o+=3){const t=r[o]<<16|r[o+1]<<8|r[o+2];e+=p.charAt(t>>18&63)+p.charAt(t>>12&63)+p.charAt(t>>6&63)+p.charAt(t&63)}const n=r.length-o;if(n===1){const t=r[o]<<16;e+=p.charAt(t>>18&63)+p.charAt(t>>12&63)}else if(n===2){const t=r[o]<<16|r[o+1]<<8;e+=p.charAt(t>>18&63)+p.charAt(t>>12&63)+p.charAt(t>>6&63)}return e};new TextDecoder;const x=new TextEncoder,S="=",G=r=>{for(let e=0;e<r.length;e+=1)if(r.charCodeAt(e)>255)return!1;return!0},Q=r=>U(x.encode(JSON.stringify(r))),z=r=>!r.startsWith(S)&&G(r)?r:`${S}${U(x.encode(r))}`,u="$lunora.wire$",v=64,T=1024,E="__proto__",I={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},R={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},V=r=>{if(r===null||typeof r!="object")return!1;const e=Object.getPrototypeOf(r);return e===null||e===Object.prototype},h=(r,e=0)=>{if(e>v)throw new RangeError(`wire-codec: value nesting exceeds the ${v}-level limit`);if(r===void 0)return[u,"undefined"];if(r===null)return null;const o=typeof r;if(o==="bigint")return[u,"bigint",r.toString()];if(o==="number"){const t=r;return Number.isNaN(t)?[u,"nan"]:t===1/0?[u,"inf"]:t===-1/0?[u,"-inf"]:t}if(o!=="object")return r;if(r instanceof Date)return[u,"date",h(r.getTime(),e+1)];if(r instanceof Error){const t=r,s={};for(const c of Object.keys(t)){if(t[c]===void 0)continue;const l=h(t[c],e+1);c===E?Object.defineProperty(s,c,{configurable:!0,enumerable:!0,value:l,writable:!0}):s[c]=l}const i=[u,"error",String(t.name),String(t.message),s];return t.cause!==void 0&&i.push(h(t.cause,e+1)),i}if(r instanceof URL)return[u,"url",r.href];if(r instanceof Map)return[u,"map",[...r.entries()].map(([t,s])=>[h(t,e+1),h(s,e+1)])];if(r instanceof Set)return[u,"set",[...r].map(t=>h(t,e+1))];if(r instanceof ArrayBuffer)return[u,"bytes",A(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const t=r,s=t.constructor.name,i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return s==="Uint8Array"?[u,"bytes",A(i)]:[u,"bytes",A(i),s]}if(Array.isArray(r)){const t=r.map(s=>h(s,e+1));return t.length>0&&t[0]===u?[u,"arr",t]:t}if(!V(r)){const t=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${t} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const a=r,n={};for(const t of Object.keys(a)){const s=a[t];if(s===void 0)continue;const i=h(s,e+1);t===E?Object.defineProperty(n,t,{configurable:!0,enumerable:!0,value:i,writable:!0}):n[t]=i}return n},f=(r,e=0)=>{if(e>v)throw new RangeError(`wire-codec: value nesting exceeds the ${v}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===u)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(n=>f(n,e+1));case"bigint":{const n=r[2];if(typeof n!="string"||n.length>T||!/^-?\d+$/.test(n))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${T} digits)`);return BigInt(n)}case"date":{const n=f(r[2],e+1);if(typeof n!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(n)}case"map":{const n=r[2];return new Map(n.map(t=>{if(!Array.isArray(t)||t.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[f(t[0],e+1),f(t[1],e+1)]}))}case"set":return new Set(r[2].map(n=>f(n,e+1)));case"url":{const n=r[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(n)}case"error":{const n=r[2],t=r[3];if(typeof n!="string"||typeof t!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(R,n)?R[n]:void 0)??Error,i=new s(t);i.name!==n&&Object.defineProperty(i,"name",{configurable:!0,value:n,writable:!0});const c=f(r[4],e+1);if(c===null||typeof c!="object"||Array.isArray(c))throw new TypeError("wire-codec: malformed error — props must be an object");for(const l of Object.keys(c))l===E?Object.defineProperty(i,l,{configurable:!0,enumerable:!0,value:c[l],writable:!0}):i[l]=c[l];return r.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(r[5],e+1),writable:!0}),i}case"bytes":{const n=r[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const t=W(n);if(A(t)!==n)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=r[3]??"Uint8Array";if(s==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const i=Object.hasOwn(I,s)?I[s]:void 0;return i?new i(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(n=>f(n,e+1))}return r.map(n=>f(n,e+1))}const o=r,a={};for(const n of Object.keys(o)){const t=f(o[n],e+1);n===E?Object.defineProperty(a,n,{configurable:!0,enumerable:!0,value:t,writable:!0}):a[n]=t}return a},X=(r,e,o)=>{try{return h(o)}catch(a){throw new TypeError(`${r}: cannot encode args for '${e}' — ${a instanceof Error?a.message:String(a)}`,a instanceof Error?{cause:a}:void 0)}},Y="/_lunora/scheduler/dispatch",Z=3e4,rr=r=>{let e=r.length;for(;e>0&&r[e-1]==="/";)e-=1;return r.slice(0,e)},P=Symbol("lunoraDispatchFailure"),D=Symbol("lunoraDispatchDecline"),k=Symbol("lunoraDispatchMessageId"),B=(r,e)=>(e!==void 0&&Object.defineProperty(r,k,{value:e}),r),er=(r,e)=>(Object.defineProperty(r,P,{value:!0}),B(r,e)),ur=r=>_(r)?r[k]:void 0,tr=(r,e,o,a)=>{const{status:n}=e;try{const t=JSON.parse(o)?.error;if(typeof t=="object"&&t!==null&&typeof t.code=="string"){const{code:s,data:i,message:c}=t,l=er(new b(s,typeof c=="string"?c:void 0,{data:i,status:n}),a);return e.headers.get(F)==="1"&&Object.defineProperty(l,D,{value:!0}),l}}catch{}return B(new b("INTERNAL",`${r}: function dispatch failed (${String(n)}): ${o}`,{status:n}),a)},nr=new Set([400,403,404,422]),or=new Set([L,"DISPATCH_UNAUTHENTICATED"]),C=r=>_(r)&&r[P]===!0,lr=r=>C(r)&&nr.has(r.status)&&!or.has(r.code),fr=r=>C(r)&&r[D]===!0,j=K/1e3,ar=3,dr=async(r,e)=>{const o=e.maxRetries??ar,a=typeof r.attempts=="number"&&r.attempts>o;let n="";if(a&&e.requeue!==void 0)try{return await e.requeue(j),r.ack(),"requeued"}catch(t){n=` Re-enqueueing a delayed copy failed (${t instanceof Error?t.message:String(t)}).`}return r.retry({delaySeconds:j}),a&&console.error(`${e.where}: message ${r.id} was declined (${L}) on its last delivery (attempt ${String(r.attempts)} of ${String(o+1)}) — its earlier delivery is still running the call.${n} It is retried anyway, but its retries are exhausted, so it will be dead-lettered if the queue has a deadLetterQueue and dropped if not. Raise max_retries so a slow call cannot exhaust it.`),"retried"},sr=(r,e,o)=>new b("INTERNAL",`${r}: function dispatch to "${e}" timed out after ${String(o)}ms`,{status:503}),ir=r=>{const{label:e}=r,o=globalThis.fetch,a=r.fetchImpl??(typeof o=="function"?o.bind(globalThis):void 0);return async(n,t,s={})=>{if(typeof a!="function")throw new TypeError(`${e}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const i=()=>r.argsAlreadyEncoded===!0?t??{}:X(e,n.__lunoraRef,t??{}),c=r.env.LUNORA_ORIGIN_URL;if(typeof c!="string"||c.length===0)throw new b("INTERNAL",`${e}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const l=r.env.LUNORA_ADMIN_TOKEN;if(typeof l!="string"||l.length===0)throw new b("INTERNAL",`${e}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const M=`${rr(c)}${Y}`,w={authorization:`Bearer ${l}`,"content-type":"application/json"};r.traceparent!==void 0&&r.traceparent.length>0&&(w.traceparent=r.traceparent),r.identity?.userId!==void 0&&(w["x-lunora-userid"]=z(r.identity.userId)),r.identity?.claims!==void 0&&(w["x-lunora-identity"]=Q(r.identity.claims));const $=s.timeoutMs??Z,O=H(void 0,$,()=>new DOMException(`dispatch timed out after ${String($)}ms`,"TimeoutError")),N=y=>{throw y instanceof Error&&y.name==="TimeoutError"?sr(e,n.__lunoraRef,$):y};let d;try{try{d=await a(M,{body:JSON.stringify({args:i(),functionPath:n.__lunoraRef,id:s.dedupId,shardKey:s.shardKey}),headers:w,method:"POST",signal:O.signal})}catch(m){return N(m)}if(!d.ok){let m;try{m=await d.text()}catch(q){return N(q)}throw tr(e,d,m,s.messageId)}let y;try{y=await d.text()}catch(m){return N(m)}if(y.length===0)return;let g;try{g=JSON.parse(y)}catch{throw new b("INTERNAL",`${e}: function dispatch returned a non-JSON body (${String(d.status)}): ${y}`,{status:d.status})}if(g===null||typeof g!="object"||Array.isArray(g)||!("result"in g))throw new b("INTERNAL",`${e}: function dispatch returned a JSON body that is not a { result } envelope (${String(d.status)}): ${y}`,{status:d.status});return f(g.result)}finally{O.dispose()}}},yr=r=>({env:r.env,log:J(`[queue:${r.exportName}]`),run:ir({env:r.env,fetchImpl:r.fetchImpl,label:"@lunora/queue",...r.traceparent===void 0?{}:{traceparent:r.traceparent}})});export{ur as a,yr as c,dr as d,lr as f,ar as o,fr as u};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/queue",
3
- "version": "1.0.0-alpha.9",
3
+ "version": "1.0.0-alpha.91",
4
4
  "description": "Cloudflare Queues for Lunora: defineQueue producers + consumers, the ctx.queues surface, and the generated queue() worker handler",
5
5
  "keywords": [
6
6
  "background-jobs",
@@ -44,7 +44,8 @@
44
44
  "access": "public"
45
45
  },
46
46
  "dependencies": {
47
- "@lunora/errors": "1.0.0-alpha.6"
47
+ "@lunora/errors": "1.0.0-alpha.50",
48
+ "@lunora/platform": "1.0.0-alpha.55"
48
49
  },
49
50
  "engines": {
50
51
  "node": "^22.15.0 || >=24.11.0"
@@ -1,64 +0,0 @@
1
- import { LunoraError } from '@lunora/errors';
2
-
3
- const RECORD_QUEUE_MESSAGE_OP = "__lunora_admin__:recordQueueMessage";
4
- const DEFAULT_ROOT_SHARD = "__root__";
5
- const DEV_ENVIRONMENT_PATTERN = /^(?:dev(?:elopment)?|local(?:host)?|test)$/iu;
6
- const ENVIRONMENT_VARS = ["CF_ENV", "ENVIRONMENT", "NODE_ENV", "WORKER_ENV"];
7
- const CAPTURE_FETCH_TIMEOUT_MS = 5e3;
8
- const shouldCaptureQueue = (env) => {
9
- const flag = env["LUNORA_QUEUE_CAPTURE"];
10
- if (typeof flag === "string") {
11
- return flag === "1" || flag.toLowerCase() === "true";
12
- }
13
- return ENVIRONMENT_VARS.some((key) => {
14
- const value = env[key];
15
- return typeof value === "string" && DEV_ENVIRONMENT_PATTERN.test(value);
16
- });
17
- };
18
- const createQueueCaptureSink = (env, options = {}) => {
19
- const rootShard = options.rootShard ?? DEFAULT_ROOT_SHARD;
20
- return async (messages) => {
21
- if (messages.length === 0) {
22
- return;
23
- }
24
- const binding = env["SHARD"];
25
- const adminToken = typeof env["LUNORA_ADMIN_TOKEN"] === "string" ? env["LUNORA_ADMIN_TOKEN"] : void 0;
26
- if (binding === void 0 || adminToken === void 0) {
27
- return;
28
- }
29
- let namespace = binding;
30
- if (options.jurisdiction !== void 0) {
31
- if (typeof binding.jurisdiction !== "function") {
32
- throw new TypeError(
33
- `@lunora/queue: Durable Object namespace does not support jurisdiction("${options.jurisdiction}") — update @cloudflare/workers-types or remove the jurisdiction option`
34
- );
35
- }
36
- namespace = binding.jurisdiction(options.jurisdiction);
37
- }
38
- const stub = namespace.get(namespace.idFromName(rootShard));
39
- const controller = new AbortController();
40
- const timeout = setTimeout(() => {
41
- controller.abort();
42
- }, CAPTURE_FETCH_TIMEOUT_MS);
43
- try {
44
- const response = await stub.fetch("https://shard.internal/rpc", {
45
- body: JSON.stringify({ args: { messages }, functionPath: RECORD_QUEUE_MESSAGE_OP }),
46
- headers: { authorization: `Bearer ${adminToken}`, "content-type": "application/json" },
47
- method: "POST",
48
- signal: controller.signal
49
- });
50
- if (!response.ok) {
51
- const detail = await response.text().catch(() => "");
52
- throw new LunoraError(
53
- "INTERNAL",
54
- `@lunora/queue: capture write to the root shard failed (${String(response.status)} ${response.statusText})${detail === "" ? "" : `: ${detail}`}`
55
- );
56
- }
57
- await response.body?.cancel();
58
- } finally {
59
- clearTimeout(timeout);
60
- }
61
- };
62
- };
63
-
64
- export { createQueueCaptureSink, shouldCaptureQueue };
@@ -1,14 +0,0 @@
1
- import createQueues from './createQueues-14-vSICK.mjs';
2
-
3
- const createQueueContext = (env, specs) => {
4
- const bindings = {};
5
- for (const spec of specs) {
6
- const binding = env[spec.binding];
7
- if (binding && typeof binding.send === "function" && typeof binding.sendBatch === "function") {
8
- bindings[spec.exportName] = binding;
9
- }
10
- }
11
- return createQueues({ bindings });
12
- };
13
-
14
- export { createQueueContext };