logic-sdk 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +9 -10
  2. package/dist/adapters/cloudflare-queue.d.ts +15 -0
  3. package/dist/adapters/cloudflare-queue.js +58 -0
  4. package/dist/adapters/drizzle-pg.d.ts +280 -0
  5. package/dist/adapters/drizzle-pg.js +78 -0
  6. package/dist/adapters/drizzle-sqlite.d.ts +273 -0
  7. package/dist/adapters/drizzle-sqlite.js +203 -0
  8. package/dist/adapters/postgres.d.ts +33 -0
  9. package/dist/adapters/postgres.js +129 -0
  10. package/dist/adapters/sqlite.d.ts +13 -0
  11. package/dist/adapters/sqlite.js +108 -0
  12. package/dist/adapters/stored-jobs.d.ts +89 -0
  13. package/dist/adapters/stored-jobs.js +370 -0
  14. package/dist/ai.d.ts +1 -32
  15. package/dist/ai.js +1 -40
  16. package/dist/cloudflare.d.ts +2 -55
  17. package/dist/cloudflare.js +2 -85
  18. package/dist/core/in-process.d.ts +9 -0
  19. package/dist/core/in-process.js +37 -0
  20. package/dist/core/jobs.d.ts +63 -0
  21. package/dist/core/jobs.js +514 -0
  22. package/dist/core/registry.d.ts +156 -0
  23. package/dist/core/registry.js +515 -0
  24. package/dist/core/testing.d.ts +75 -0
  25. package/dist/core/testing.js +232 -0
  26. package/dist/{types.d.ts → core/types.d.ts} +289 -64
  27. package/dist/drizzle/pg.d.ts +3 -236
  28. package/dist/drizzle/pg.js +2 -67
  29. package/dist/drizzle/sqlite.d.ts +3 -242
  30. package/dist/drizzle/sqlite.js +2 -194
  31. package/dist/fetch.d.ts +1 -19
  32. package/dist/fetch.js +1 -30
  33. package/dist/hosts/cloudflare.d.ts +43 -0
  34. package/dist/hosts/cloudflare.js +40 -0
  35. package/dist/hosts/node.d.ts +36 -0
  36. package/dist/hosts/node.js +103 -0
  37. package/dist/index.d.ts +5 -122
  38. package/dist/index.js +4 -492
  39. package/dist/integrations/ai.d.ts +32 -0
  40. package/dist/integrations/ai.js +40 -0
  41. package/dist/integrations/fetch.d.ts +19 -0
  42. package/dist/integrations/fetch.js +30 -0
  43. package/dist/integrations/orpc.d.ts +22 -0
  44. package/dist/integrations/orpc.js +37 -0
  45. package/dist/node.d.ts +1 -26
  46. package/dist/node.js +1 -76
  47. package/dist/orpc.d.ts +1 -21
  48. package/dist/orpc.js +1 -37
  49. package/dist/postgres.d.ts +2 -28
  50. package/dist/postgres.js +1 -82
  51. package/dist/sqlite.d.ts +2 -9
  52. package/dist/sqlite.js +1 -65
  53. package/dist/testing.d.ts +1 -75
  54. package/dist/testing.js +1 -227
  55. package/package.json +2 -12
  56. package/skills/logic-sdk/SKILL.md +6 -5
  57. package/src/adapters/cloudflare-queue.ts +65 -0
  58. package/src/adapters/drizzle-pg.ts +117 -0
  59. package/src/adapters/drizzle-sqlite.ts +241 -0
  60. package/src/adapters/postgres.ts +136 -0
  61. package/src/adapters/sqlite.ts +116 -0
  62. package/src/adapters/stored-jobs.ts +463 -0
  63. package/src/ai.ts +1 -62
  64. package/src/cloudflare.ts +2 -107
  65. package/src/core/in-process.ts +38 -0
  66. package/src/core/jobs.ts +548 -0
  67. package/src/core/registry.ts +719 -0
  68. package/src/core/testing.ts +309 -0
  69. package/src/{types.ts → core/types.ts} +280 -60
  70. package/src/drizzle/pg.ts +3 -110
  71. package/src/drizzle/sqlite.ts +3 -236
  72. package/src/fetch.ts +1 -31
  73. package/src/hosts/cloudflare.ts +55 -0
  74. package/src/hosts/node.ts +126 -0
  75. package/src/index.ts +17 -652
  76. package/src/integrations/ai.ts +63 -0
  77. package/src/integrations/fetch.ts +31 -0
  78. package/src/integrations/orpc.ts +47 -0
  79. package/src/node.ts +1 -99
  80. package/src/orpc.ts +1 -46
  81. package/src/postgres.ts +2 -90
  82. package/src/sqlite.ts +2 -74
  83. package/src/testing.ts +1 -305
  84. package/dist/jobs.d.ts +0 -44
  85. package/dist/jobs.js +0 -260
  86. package/dist/pg-boss.d.ts +0 -53
  87. package/dist/pg-boss.js +0 -213
  88. package/dist/stored-jobs.d.ts +0 -64
  89. package/dist/stored-jobs.js +0 -188
  90. package/src/jobs.ts +0 -307
  91. package/src/pg-boss.ts +0 -241
  92. package/src/stored-jobs.ts +0 -260
  93. /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
  94. /package/dist/{errors.js → core/errors.js} +0 -0
  95. /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
  96. /package/dist/{schedule.js → core/schedule.js} +0 -0
  97. /package/dist/{types.js → core/types.js} +0 -0
  98. /package/src/{errors.ts → core/errors.ts} +0 -0
  99. /package/src/{schedule.ts → core/schedule.ts} +0 -0
@@ -20,7 +20,7 @@ export interface Config {
20
20
  */
21
21
  config?: object;
22
22
  /**
23
- * The shape of `meta`: yours, plus what your adapters read (`AppMeta & AIMeta & PgBossMeta`). Yours goes on functions
23
+ * The shape of `meta`: yours, plus what your adapters read (`AppMeta & AIMeta`). Yours goes on functions
24
24
  * and listeners, each adapter's only where it reads it.
25
25
  */
26
26
  meta?: object;
@@ -61,7 +61,7 @@ declare const FOR_LISTENERS: unique symbol;
61
61
  export interface ForFunctions<M> {
62
62
  readonly [FOR_FUNCTIONS]?: M;
63
63
  }
64
- /** An adapter's part of `meta`, read on listeners: `type PgBossMeta = ForListeners<{ pgBoss?: ... }>`. */
64
+ /** An adapter's part of `meta`, read on listeners: `type QueueMeta = ForListeners<{ queue?: ... }>`. */
65
65
  export interface ForListeners<M> {
66
66
  readonly [FOR_LISTENERS]?: M;
67
67
  }
@@ -178,6 +178,12 @@ export interface Delivery {
178
178
  attempts: number;
179
179
  /** When it may run (ISO), for a listener with a `delay`. Absent: right away. */
180
180
  runAt?: string;
181
+ /** Its listener's `key`, as `<listener id>@<key>`: jobs with the same one run one at a time, in order. */
182
+ key?: string;
183
+ /** Its listener's `unique`, as `<listener id>@<value>`: a later job with the same one is dropped while this one waits. */
184
+ unique?: string;
185
+ /** Its queue, when it isn't `"default"`: a worker drains its queues in the order it lists them. */
186
+ queue?: string;
181
187
  }
182
188
  /** One run of a cron: `id` is `<cron id>@<minute>` (`reports.weekly@20261123T0900Z`), so a tick runs once. */
183
189
  export interface CronJob {
@@ -191,8 +197,10 @@ export interface CronJob {
191
197
  attempts: number;
192
198
  /** When it may run (ISO), like a delivery's. Absent for crons: they run when ticked. */
193
199
  runAt?: string;
200
+ /** Its queue, when it isn't `"default"`: a worker drains its queues in the order it lists them. */
201
+ queue?: string;
194
202
  }
195
- /** A function `ctx.schedule` asked to run later: `id` is `<function id>@<uuid>`, returned by `ctx.schedule`. */
203
+ /** A function `ctx.schedule` asked to run later: `id` is `<function id>@<uuid>`. */
196
204
  export interface CallJob {
197
205
  kind: "call";
198
206
  id: string;
@@ -208,10 +216,12 @@ export interface CallJob {
208
216
  * function that schedules itself with no delay stops like a listener loop. A delayed one starts a new chain (0).
209
217
  */
210
218
  depth: number;
211
- /** Its `replace` key: a newer call to `fn` with the same key replaces this one while it waits. */
212
- replace?: string;
219
+ /** `true`: a newer call to `fn` with the same input replaces this one while it waits (the function and its input are the identity). */
220
+ replace?: true;
213
221
  /** When it may run (ISO). */
214
222
  runAt?: string;
223
+ /** Its queue, when it isn't `"default"`: a worker drains its queues in the order it lists them. */
224
+ queue?: string;
215
225
  }
216
226
  /**
217
227
  * One unit of background work, what `registry.jobs` runs, sweeps and retries: a listener's share of an event, a cron's
@@ -227,8 +237,12 @@ export interface Cron<C extends Config = any> extends FromInit<C> {
227
237
  readonly timezone?: string;
228
238
  readonly scope: object;
229
239
  readonly attempts?: number;
240
+ /** Its queue, one of `jobs.queues`. Default `"default"`. */
241
+ readonly queue?: string;
230
242
  readonly meta?: Readonly<Record<string, unknown>>;
231
243
  readonly handler: (ctx: never) => Promise<unknown>;
244
+ /** Runs once its last try has failed: `(ctx, error)`. */
245
+ readonly failed?: (ctx: never, error: unknown) => Promise<unknown>;
232
246
  }
233
247
  /** The run a cron's handler is doing. No scope here: `ctx.scope` is the one it runs as. */
234
248
  export interface CronRun {
@@ -246,6 +260,17 @@ export interface CronRun {
246
260
  * `discarded`: `jobs.scope.load` returned null (who it ran as is gone). Acknowledge it too; it's been reported.
247
261
  */
248
262
  export type JobOutcome = "done" | "failed" | "discarded";
263
+ /**
264
+ * What `ctx.emit` queued: the `id`, `name` and `occurredAt` its listeners see as `ctx.event`. `payload` is a copy of what
265
+ * you passed; listeners get it parsed by the event's schema.
266
+ */
267
+ export interface EmittedEvent<I = unknown> {
268
+ readonly id: string;
269
+ readonly name: string;
270
+ readonly payload: I;
271
+ /** ISO. */
272
+ readonly occurredAt: string;
273
+ }
249
274
  /** The event a listener is handling. No scope here: `ctx.scope` is the one it runs as. */
250
275
  export interface ListenerEvent<O = unknown> {
251
276
  id: string;
@@ -268,8 +293,18 @@ export interface Listener<O = unknown, C extends Config = any> extends FromInit<
268
293
  readonly delay?: number;
269
294
  /** Whether this event gets a job for this listener, from the parsed payload, at commit. Default: every event. */
270
295
  readonly when?: (payload: O) => boolean;
296
+ /** Jobs with the same key run one at a time, in the order their events were emitted. */
297
+ readonly key?: (payload: O) => string;
298
+ /** While a job with the same value hasn't started, later ones are dropped. */
299
+ readonly unique?: (payload: O) => string;
300
+ /** Seconds a try may run before it's stopped and counted as failed. */
301
+ readonly timeout?: number;
302
+ /** Its queue, one of `jobs.queues`. Default `"default"`. */
303
+ readonly queue?: string;
271
304
  readonly meta?: Readonly<Record<string, unknown>>;
272
305
  readonly handler: (ctx: never, payload: O) => Promise<unknown>;
306
+ /** Runs once its last try has failed: `(ctx, payload, error)`. */
307
+ readonly failed?: (ctx: never, payload: O, error: unknown) => Promise<unknown>;
273
308
  }
274
309
  /** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
275
310
  export interface RunOptions<S = object> {
@@ -324,19 +359,24 @@ export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C
324
359
  * `await ctx.run(availability.hold, { propertyId })`. If it fails, the whole transaction rolls back.
325
360
  */
326
361
  run: Run<"query" | "mutation", ScopeOf<C>>;
327
- /** Queue an event. Delivered to listeners only after the transaction commits. */
328
- emit<I>(event: EventDef<I, unknown>, payload: I): void;
362
+ /**
363
+ * Queue an event. Delivered to listeners only after the transaction commits. Returns what it queued: the id, name and
364
+ * time its listeners see as `ctx.event`, so a row you write in this transaction can carry `event.id` and a listener
365
+ * finds it by `ctx.event.id`.
366
+ */
367
+ emit<I>(event: EventDef<I, unknown>, payload: I): EmittedEvent<I>;
329
368
  /**
330
369
  * Run a mutation or action once, later, as this scope: `ctx.schedule(guests.remind, { bookingId }, { at })` or
331
- * `{ delay: 3600 }` (seconds). Committed with this transaction, so a rollback never leaves one behind. Returns its job
332
- * id. It runs whatever happens meanwhile, so it should check that its reason still holds ("still confirmed?").
333
- * `attempts`: tries in total, default 1; give an action that calls an API a few. `replace`: a key, so a newer call
334
- * with it replaces the one still waiting (`replace: booking.id` when the dates change), like Oban's `replace`.
370
+ * `{ delay: 3600 }` (seconds). Committed with this transaction, so a rollback never leaves one behind. Nothing to
371
+ * keep: there's no cancel. It runs whatever happens meanwhile, so it checks that its reason still holds ("still
372
+ * confirmed?") against your own row. `attempts`: tries in total, default 1; give an action that calls an API a few.
373
+ * `replace: true`: a newer call to this function with the same input replaces the one still waiting (the dates of
374
+ * `{ bookingId }` changed), like Oban's `replace`. Keep the input to ids, so it names one thing.
335
375
  */
336
- schedule<F extends Fn<"mutation" | "action">>(fn: F, input: FnIn<F>, options: ScheduleOptions): string;
376
+ schedule<F extends Fn<"mutation" | "action">>(fn: F, input: FnIn<F>, options: ScheduleOptions<ScopeOf<C>>): void;
337
377
  }
338
378
  /** When a scheduled call runs (`at` or `delay` in seconds), and how many tries it gets. */
339
- export type ScheduleOptions = ({
379
+ export type ScheduleOptions<S = object> = ({
340
380
  at: Date;
341
381
  delay?: never;
342
382
  } | {
@@ -344,14 +384,21 @@ export type ScheduleOptions = ({
344
384
  at?: never;
345
385
  }) & {
346
386
  attempts?: number;
347
- /** A key: the call to this function waiting with the same key (not started yet) is replaced by this one. */
348
- replace?: string;
387
+ /** `true`: the call to this function waiting with the same input (not started yet) is replaced by this one. */
388
+ replace?: true;
389
+ /** Its queue, one of `jobs.queues`. Default `"default"`. */
390
+ queue?: string;
391
+ /**
392
+ * Who it runs as, whole, never merged, as `ctx.run` takes it: `{ scope: { kind: "system", job: "tasks.wake", organization } }`.
393
+ * Default: this mutation's scope. The function's policy checks it when it runs.
394
+ */
395
+ scope?: S;
349
396
  };
350
397
  export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
351
398
  services: ServicesOf<C>;
352
399
  /** Call any function: `await ctx.run(bookings.confirmPaid, { bookingId })`. Each mutation you run commits on its own. */
353
400
  run: Run<Kind, ScopeOf<C>>;
354
- /** The caller's abort signal: pass it on, `fetch(url, { signal: ctx.signal })`. Always undefined in listeners (they outlive the request). */
401
+ /** The caller's abort signal: pass it on, `fetch(url, { signal: ctx.signal })`. In a listener, aborted when its `timeout` runs out (else undefined: listeners outlive the request). */
355
402
  signal: AbortSignal | undefined;
356
403
  }
357
404
  export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
@@ -413,30 +460,30 @@ export interface DatabaseAdapter<Db = unknown, Tx = Db> {
413
460
  nest?(tx: Tx): DatabaseAdapter<Tx, Tx>;
414
461
  /** Did this transaction lose a race the database says to retry (deadlock, serialization failure)? */
415
462
  retryable?(error: unknown): boolean;
416
- /**
417
- * Tries in total for a top-level mutation whose transaction is `retryable`, each in a fresh one, like Laravel's
418
- * `DB::transaction(fn, attempts)`. Default 3; 1 turns it off. A job's own tries are its `attempts`.
419
- */
420
- transactionAttempts?: number;
421
- /**
422
- * One SQL statement (`$1` parameters on Postgres, `?` on SQLite), on the database or on a transaction of it. Resolves the rows it
423
- * returns. `databaseQueue` and `outbox` run their table through it, so any ORM that can run SQL has them.
424
- */
425
- query?(client: Db | Tx, text: string, params: unknown[]): Promise<Record<string, unknown>[]>;
426
463
  }
427
- /** A database adapter with `query`: what `databaseQueue(database)` and `outbox(database, queue)` take. */
464
+ /** A database adapter that runs SQL: what `databaseQueue()` and `outbox(queue)` need. */
428
465
  export interface SqlDatabase<Db = any, Tx = any> extends DatabaseAdapter<Db, Tx> {
466
+ /**
467
+ * One SQL statement (`$1` parameters on Postgres, `?` on SQLite), on the database or on a transaction of it. Resolves
468
+ * the rows it returns. The jobs table runs through it, so any ORM that can run SQL has it.
469
+ */
429
470
  query(client: Db | Tx, text: string, params: unknown[]): Promise<Record<string, unknown>[]>;
430
471
  }
472
+ /**
473
+ * `createRegistry({ database })`: the adapter, and how the core uses it. `transactionAttempts`: tries in total for a
474
+ * top-level mutation whose transaction lost a race (`retryable`), each in a fresh one, like Laravel's
475
+ * `DB::transaction(fn, attempts)`. Default 3; 1 turns it off. A job's own tries are its `attempts`.
476
+ */
477
+ export interface DatabaseOptions<A extends DatabaseAdapter<any, any> = DatabaseAdapter<unknown, unknown>> {
478
+ adapter: A;
479
+ transactionAttempts?: number;
480
+ }
431
481
  /** Runs one job: resolves when it's done or failed for good (acknowledge it), throws when a retry might help. */
432
482
  export type RunJob = (job: Job, options?: RunJobOptions) => Promise<JobOutcome>;
433
483
  export interface RunJobOptions {
434
484
  /** 1 on the first try; the adapter counts. */
435
485
  attempt?: number;
436
- /**
437
- * Called with the error when the job fails for good, before `run` resolves `"failed"`: keep it. Default: the adapter's
438
- * `fail` (`databaseQueue` and `outbox` write a failed row).
439
- */
486
+ /** Called with the error when the job fails for good, before `run` resolves `"failed"`: keep it (a failed row). */
440
487
  fail?: (error: unknown) => Promise<void>;
441
488
  }
442
489
  /** What a sweep did: done, failed for good, discarded (`jobs.scope.load` returned null), or put back with a backoff. */
@@ -453,6 +500,23 @@ export interface Runner {
453
500
  report(error: unknown, job: Job, attempt?: number): void;
454
501
  }
455
502
  export interface JobsAdapter {
503
+ /** How it's set up, for messages: `"databaseQueue()"`. The core names capabilities, the adapter itself. */
504
+ name?: string;
505
+ /**
506
+ * It can run a job again after a failed try: a queue redelivers it, a table backs off. Without it (`inProcess()`),
507
+ * `createRegistry` refuses `attempts` above 1 rather than ignore them, as it refuses a delay it can't hold.
508
+ */
509
+ retries?: true;
510
+ /**
511
+ * It runs jobs with the same `key` one at a time, in the order they were queued, like an SQS FIFO queue's message
512
+ * groups. Without it, `createRegistry` refuses a listener with a `key`.
513
+ */
514
+ orders?: true;
515
+ /**
516
+ * It writes jobs with SQL in the mutation's transaction, through the registry's database: `createRegistry` refuses a
517
+ * registry whose `database.adapter` doesn't run SQL (`query`), and `connect` gets it as `setup.sql`.
518
+ */
519
+ sql?: true;
456
520
  /**
457
521
  * It can hold a job until its `runAt` (a listener's `delay`, `ctx.schedule`): `true`, or for at most `max` seconds.
458
522
  * Without it (`inProcess()`), `createRegistry` refuses delayed listeners and `ctx.schedule` throws, rather than run
@@ -462,32 +526,43 @@ export interface JobsAdapter {
462
526
  max: number;
463
527
  };
464
528
  /**
465
- * Can replace a call waiting to run: `enqueue` gets a call with `replace`, and a pending call to the same `fn` with
466
- * the same key that hasn't started is replaced by it. `databaseQueue` and `outbox` can; a queue that already has the message can't.
467
- * Without it, `ctx.schedule` with `replace` is refused.
529
+ * Can keep one waiting job per key: `enqueue` gets a call with `replace`, and a pending call with the same key
530
+ * (`storedUniqueKey`) that hasn't started is replaced by it; a delivery with `unique` is dropped while one with the
531
+ * same key waits. A queue that already has the message can't. Without it, `ctx.schedule` with `replace` is refused,
532
+ * and so is `unique` on an adapter that holds jobs.
468
533
  */
469
534
  replaces?: true;
470
- /** At `createRegistry`: refuse a setup this adapter can't honour (a database it doesn't share). */
471
- check?(setup: {
472
- listeners: readonly RegisteredListener[];
473
- crons: readonly RegisteredCron[];
474
- database: DatabaseAdapter<unknown, unknown> | undefined;
475
- }): void;
535
+ /**
536
+ * It keeps jobs of different queues apart: any name (`true`), or only these (a queue per binding). Without it,
537
+ * `createRegistry` refuses `jobs.queues`; with a list, a declared queue (or `"default"`) it doesn't have.
538
+ */
539
+ queues?: true | readonly string[];
540
+ /**
541
+ * At `createRegistry`, once: take what the adapter needs from the registry (its database, for an adapter that writes
542
+ * jobs in the mutation's transaction), and refuse a setup it can't honour.
543
+ */
544
+ connect?(setup: AdapterSetup): void;
476
545
  /** Inside the transaction, before commit. In-process: nothing. `databaseQueue` and `outbox`: insert one row per job with `tx`. */
477
546
  enqueue?(tx: unknown, jobs: Job[]): Promise<void>;
478
547
  /** After commit: run them, or hand them to a queue. A throw is reported to `onError`. */
479
548
  deliver(jobs: Job[], runner: Runner): Promise<void>;
480
549
  /** Run what's due (retries, deliveries whose runner crashed). Only adapters that store deliveries have it. */
481
- sweep?(runner: Runner, options?: {
482
- limit?: number;
483
- }): Promise<SweepResult>;
550
+ sweep?(runner: Runner, options?: SweepOptions): Promise<SweepResult>;
484
551
  /** Put a failed job back in line. `false` when there's no failed job with that id. Only adapters that store them. */
485
552
  retry?(id: string): Promise<boolean>;
553
+ /** A page of failed jobs, newest first. Only adapters that store them and can filter them. */
554
+ failed?(options: FailedQuery): Promise<{
555
+ rows: FailedRow[];
556
+ cursor: string | null;
557
+ }>;
558
+ /** Delete one failed job. `false` when there's no failed job with that id: a waiting or running one is never touched. */
559
+ forget?(id: string): Promise<boolean>;
486
560
  /**
487
- * Keep a job that failed for good after it left the adapter: `registry.jobs.run` calls it from a queue consumer, so
488
- * `outbox` stores the failure Cloudflare would otherwise drop. Not called for jobs the adapter ran itself.
561
+ * For an adapter that keeps its jobs as rows and sends a queue only signals: a consumer got this job's
562
+ * message, so run it from the rows (with a `key`, the key's next jobs, in order), recording each outcome itself.
563
+ * `registry.jobs.run` calls it in place of running the message.
489
564
  */
490
- fail?(job: Job, error: unknown): Promise<void>;
565
+ consume?(job: Job, runner: Runner): Promise<void>;
491
566
  }
492
567
  /**
493
568
  * What `onError` gets with a failure after commit. `job`, `attempt` and `outcome` are set when a job failed: the job
@@ -502,6 +577,111 @@ export interface FailureInfo {
502
577
  /** `retry`: tries are left and the adapter may run it again. `failed` and `discarded`: it's over. */
503
578
  outcome?: "retry" | "failed" | "discarded";
504
579
  }
580
+ /** What `createRegistry` gives an adapter's `connect`. */
581
+ export interface AdapterSetup {
582
+ /** The registry's `database.adapter`, when it runs SQL: always set for an adapter that declares `sql: true`. */
583
+ sql: SqlDatabase | undefined;
584
+ /**
585
+ * The loops running jobs in this process (`work()`, through `registry.jobs.attach`): whether one takes `job`, so the
586
+ * request leaves it to them instead of running it, and `wake(count)` once that many are committed.
587
+ */
588
+ workers: {
589
+ takes(job: Job): boolean;
590
+ wake(count: number): void;
591
+ };
592
+ }
593
+ /** What `registry.jobs.sweep` and an adapter's `sweep` take. */
594
+ export interface SweepOptions {
595
+ /** At most this many jobs. Default 100. */
596
+ limit?: number;
597
+ /** Only these queues, in this order: each claim takes the first one with a job due. Default: every queue. */
598
+ queues?: readonly string[];
599
+ }
600
+ /** A loop running jobs in this process: `registry.jobs.attach({ wake, queues })`. */
601
+ export interface LocalWorker {
602
+ /** How many jobs just committed for it: claim them now. */
603
+ wake(count: number): void;
604
+ /** The queues it runs. Default: all. */
605
+ queues?: readonly string[];
606
+ }
607
+ /**
608
+ * A store for failed jobs, apart from the queue that runs them, like Laravel's `failed` driver. `failedJobs()`
609
+ * keeps them in the jobs table. For adapters that keep their own, it isn't needed.
610
+ */
611
+ export interface FailedJobs {
612
+ /** For messages: `"failedJobs()"`. */
613
+ name?: string;
614
+ /** Keeps failed jobs with SQL, through the registry's database (`setup.sql`): see `JobsAdapter.sql`. */
615
+ sql?: true;
616
+ /** At `createRegistry`, once: take the registry's database. */
617
+ connect?(setup: AdapterSetup): void;
618
+ /** Keep a job that failed for good. */
619
+ fail(job: Job, error: unknown): Promise<void>;
620
+ /** A page of failed jobs, newest first. */
621
+ failed(query: FailedQuery): Promise<{
622
+ rows: FailedRow[];
623
+ cursor: string | null;
624
+ }>;
625
+ /** Remove a failed job and return it, for `retry` to hand to the queue again. Undefined when there's none with that id. */
626
+ take(id: string): Promise<Job | undefined>;
627
+ /** Delete a failed job. `false` when there's none with that id. */
628
+ forget(id: string): Promise<boolean>;
629
+ }
630
+ /** One field of a stored scope a `failed({ scope })` filter matches exactly: `["organization", "id"]` and `"org_1"`. */
631
+ export interface ScopeMatch {
632
+ path: string[];
633
+ value: string | number | boolean | null;
634
+ }
635
+ /** What `registry.jobs.failed` asks an adapter for. The core checks and flattens the filter first. */
636
+ export interface FailedQuery {
637
+ /** The listener, cron or function id. */
638
+ source?: string;
639
+ /** Every one must equal the stored scope's field at `path` (the job's `scope`, or its envelope's). */
640
+ scope?: ScopeMatch[];
641
+ limit: number;
642
+ /** From the last page: where to go on. */
643
+ cursor?: string;
644
+ }
645
+ /** A failed job as an adapter keeps it. */
646
+ export interface FailedRow {
647
+ id: string;
648
+ job: Job;
649
+ error: string;
650
+ /** ISO. */
651
+ failedAt: string;
652
+ }
653
+ /** A failed job, as `registry.jobs.failed` lists it: pass its `id` to `retry` or `forget`. */
654
+ export interface FailedJob<Stored = Record<string, unknown>> {
655
+ id: string;
656
+ kind: Job["kind"];
657
+ /** The listener, cron or function that failed, as in `FailureInfo`. */
658
+ source: string;
659
+ /** What `jobs.scope.store` saved with it. Undefined for a cron run: it has none. */
660
+ scope: Stored | undefined;
661
+ /** The last error, with its stack. */
662
+ error: string;
663
+ /** ISO. */
664
+ failedAt: string;
665
+ job: Job;
666
+ }
667
+ export interface FailedOptions<Stored = Record<string, unknown>> {
668
+ /** Only this listener's, cron's or function's: `"emails.send"`. */
669
+ source?: string;
670
+ /**
671
+ * Only jobs whose stored scope has these values (what `jobs.scope.store` saved): `{ organizationId: "org_1" }`,
672
+ * nested fields too. Never a cron run: it stores none. Values are strings, numbers, booleans or null.
673
+ */
674
+ scope?: DeepPartial<Stored>;
675
+ /** 1 to 1000. Default 100. */
676
+ limit?: number;
677
+ /** The `cursor` of the page before. */
678
+ cursor?: string;
679
+ }
680
+ export interface FailedPage<Stored = Record<string, unknown>> {
681
+ jobs: FailedJob<Stored>[];
682
+ /** Pass it back for the next page; null on the last one. */
683
+ cursor: string | null;
684
+ }
505
685
  /**
506
686
  * Who a job runs as, at rest. `store` picks what's saved with the job (ids, not whole objects); `load` rebuilds the
507
687
  * scope when it runs, so policies see today's roles. `load` returning null discards the job (reported to `onError`),
@@ -524,19 +704,30 @@ export interface InProcess extends JobsAdapter {
524
704
  * checked at startup: requiring it here would report a missing one as a wrong `store`.
525
705
  */
526
706
  export type JobsOptions<S = object, T = any> = {
707
+ /**
708
+ * Where failed jobs are kept when your adapter can't keep them itself (a queue on its own), like Laravel's `failed`
709
+ * driver: `failed: failedJobs()`. `registry.jobs.failed`, `retry` and `forget` then work on it.
710
+ */
711
+ failed?: FailedJobs;
527
712
  /**
528
713
  * Max chain of listener → mutation → event → listener… before queueing stops, reported. Calls `ctx.schedule` runs
529
714
  * right away count too, so a function that schedules itself with no delay stops the same way. Default 8 (real chains
530
715
  * are 2 or 3).
531
716
  */
532
717
  maxEventDepth?: number;
718
+ /**
719
+ * Queues besides `"default"`, for listeners, crons and `ctx.schedule` (`queue: "mail"`): `queues: ["mail", "reports"]`.
720
+ * A worker takes them in the order it lists them (`work(registry, { queues: ["mail", "default"] })`). A name not
721
+ * declared here is refused, at `createRegistry` or at the call.
722
+ */
723
+ queues?: readonly string[];
533
724
  } & ({
534
- /** `inProcess()` (default), or a durable one like `databaseQueue(database)`. Its own options go in its factory. */
725
+ /** `inProcess()` (default), or a durable one like `databaseQueue()`. Its own options go in its factory. */
535
726
  adapter?: InProcess;
536
727
  /** Applied by the registry in every adapter, `inProcess()` and tests included. */
537
728
  scope?: JobScope<S, T>;
538
729
  } | {
539
- /** An adapter that keeps jobs to run later, like `databaseQueue(database)`. */
730
+ /** An adapter that keeps jobs to run later, like `databaseQueue()`. */
540
731
  adapter?: JobsAdapter;
541
732
  /** Required: such a job runs as the scope `load` rebuilds, with today's roles. */
542
733
  scope: JobScope<S, T>;
@@ -544,6 +735,11 @@ export type JobsOptions<S = object, T = any> = {
544
735
  export interface Call<M = unknown> {
545
736
  id: string;
546
737
  kind: Kind | "listener" | "cron";
738
+ /** Set on a job's own run (a listener's, a cron's, a scheduled call's): which job, and which try (1 on the first). */
739
+ job?: {
740
+ id: string;
741
+ attempt: number;
742
+ };
547
743
  /** The function's, listener's or cron's `meta` (undefined when it has none). */
548
744
  meta: M | undefined;
549
745
  /** Raw input as received (before validation). */
@@ -554,20 +750,20 @@ export interface Call<M = unknown> {
554
750
  export interface RegistryOptions<Mods extends Record<string, object>> {
555
751
  /** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
556
752
  modules: Mods;
557
- database?: DatabaseAdapter<unknown, unknown>;
753
+ /** `database: { adapter: drizzleAdapter(db) }`, with `transactionAttempts` when 3 isn't right. */
754
+ database?: DatabaseOptions;
558
755
  services?: object;
559
756
  /** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
560
757
  config?: object;
561
- /** Background work: `jobs: { adapter: databaseQueue(database), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
758
+ /** Background work: `jobs: { adapter: databaseQueue(), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
562
759
  jobs?: JobsOptions;
563
760
  /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
564
761
  wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
565
762
  /**
566
763
  * Serverless: let listeners finish after the response. Pass the platform's global:
567
764
  * `import { waitUntil } from "cloudflare:workers"` or `import { waitUntil } from "@vercel/functions"`.
568
- * Without it, `run` waits for listeners. On a long-lived server with `databaseQueue`, `() => {}` answers first (a restart
569
- * is swept up after its lease: retried, or failed when it was out of attempts); with `inProcess()`, don't: work
570
- * still running at a restart is lost.
765
+ * Without it, `run` waits for listeners, unless a worker in this process takes them (`work(registry)` on Node or Bun,
766
+ * with `databaseQueue`): then the request answers at once.
571
767
  */
572
768
  waitUntil?: (promise: Promise<unknown>) => void;
573
769
  /** Failures no caller waits for: jobs, and the work after commit that runs them. They never fail the caller. */
@@ -595,6 +791,8 @@ export interface Overrides {
595
791
  /** Merged over the registry's config, section by section. */
596
792
  config?: unknown;
597
793
  adapter?: JobsAdapter;
794
+ /** Where failed jobs go instead of `jobs.failed`; `null` keeps none (a test registry: failures throw). */
795
+ failed?: FailedJobs | null;
598
796
  now?: () => Date;
599
797
  stubs?: Map<Fn, (ctx: never, input: never) => Promise<unknown>>;
600
798
  record?: (envelope: Envelope) => void;
@@ -612,14 +810,20 @@ export interface RegisteredListener extends Registered {
612
810
  export interface RegisteredCron extends Registered {
613
811
  cron: Cron;
614
812
  }
615
- /** `registry.jobs`: what you call from a queue consumer, a cron, or a script. */
813
+ /**
814
+ * `registry.jobs`: what you call from a queue consumer, a timer, a script or a staff route. Outside your functions, as
815
+ * Laravel's queue commands are: guard the route yourself. A job a user wants again is a mutation that emits again.
816
+ */
616
817
  export interface Jobs {
617
818
  /**
618
- * Run one stored job (queue consumers): `await registry.jobs.run(message.body, { attempt: message.attempts })`.
819
+ * Run one job from a queue message (consumers): `await registry.jobs.run(message.body, { attempt: message.attempts })`.
619
820
  * Resolves `"done"`, `"failed"` or `"discarded"` (acknowledge all three); throws when a retry might help and the
620
- * job has tries left. A `failed` job goes to `fail`: yours, or your adapter's (`databaseQueue` and `outbox` keep it).
821
+ * job has tries left. A `failed` job is kept by `jobs.failed`, if you have one. On an adapter that only sends
822
+ * signals, the job runs from its row, which records how it went, and `run` resolves `"done"`.
621
823
  */
622
- run(job: Job, options?: RunJobOptions): Promise<JobOutcome>;
824
+ run(job: Job, options?: {
825
+ attempt?: number;
826
+ }): Promise<JobOutcome>;
623
827
  /**
624
828
  * Run the crons due in `at`'s minute (default now), from a timer or your platform's cron trigger:
625
829
  * `await registry.jobs.tick(new Date(controller.scheduledTime))`. Resolves the ids of the crons that were due. Each run
@@ -627,18 +831,40 @@ export interface Jobs {
627
831
  */
628
832
  tick(at?: Date): Promise<string[]>;
629
833
  /**
630
- * Run what your adapter has due, from a cron or an interval: `await registry.jobs.sweep()`. With `databaseQueue(database)`, that's
631
- * retries whose backoff is over and jobs whose runner crashed. Adapters that keep nothing, or maintain themselves
632
- * (pg-boss), resolve zeros.
834
+ * Run what your adapter has due, from a cron or an interval: `await registry.jobs.sweep()`. With `databaseQueue()`, that's
835
+ * retries whose backoff is over and jobs whose runner crashed. Adapters that keep nothing resolve zeros.
633
836
  */
634
- sweep(options?: {
635
- limit?: number;
636
- }): Promise<SweepResult>;
837
+ sweep(options?: SweepOptions): Promise<SweepResult>;
838
+ /**
839
+ * For a host that runs jobs in this process, like `work()`: requests leave their jobs due now to it (in its `queues`,
840
+ * or all) and answer at once, and `wake(count)` tells it how many just committed, so it claims them right away rather
841
+ * than at its next poll. Returns the detach, for its stop. Throws on a queue `jobs.queues` doesn't declare.
842
+ */
843
+ attach(worker: LocalWorker): () => void;
637
844
  /**
638
845
  * Put a failed job back in line with a fresh set of attempts. `false` when no failed job has that id (it's pending,
639
846
  * running, done, or never existed). Throws when your adapter keeps no jobs, like `inProcess()`.
640
847
  */
641
848
  retry(id: string): Promise<boolean>;
849
+ /**
850
+ * Failed jobs, newest first, a page at a time: `await registry.jobs.failed({ source: "emails.send", scope: { organizationId } })`.
851
+ * Then `retry` or `forget` each. Pass your stored scope's type to check the filter: `failed<Stored>({ scope })`. Throws
852
+ * when your adapter keeps none (a queue alone without `jobs.failed`).
853
+ */
854
+ failed<Stored = Record<string, unknown>>(options?: FailedOptions<Stored>): Promise<FailedPage<Stored>>;
855
+ /**
856
+ * Delete a failed job, like Laravel's `queue:forget`. `false` when no failed job has that id: a waiting or running one
857
+ * is never touched. Throws when your adapter keeps no jobs.
858
+ */
859
+ forget(id: string): Promise<boolean>;
860
+ /**
861
+ * Run a cron now, outside its schedule, through your jobs adapter like a tick: `await registry.jobs.invoke(orders.sendDigest)`,
862
+ * or its id from a script. `at`: the minute the run is for (`ctx.cron.scheduledAt`), default now, to redo a missed one.
863
+ * Its own job id, so the real tick for that minute still runs. Resolves the id; throws when the hand-off fails.
864
+ */
865
+ invoke(cron: Cron | string, options?: {
866
+ at?: Date;
867
+ }): Promise<string>;
642
868
  }
643
869
  /** What `createRegistry` returns. `Cf` is your config's type, so tests can override parts of it. */
644
870
  export interface Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> {
@@ -658,7 +884,6 @@ export interface Registry<S extends object = object, Mods extends Record<string,
658
884
  /** @internal used by `logic-sdk/testing` */
659
885
  readonly [INTERNAL]: {
660
886
  options: RegistryOptions<Mods>;
661
- config: Frozen<Cf>;
662
887
  derive(more: Overrides): Registry<S, Mods, Cf>;
663
888
  /** An event as `emit` would make it, for `t.jobs.perform`. */
664
889
  envelope(event: EventDef, payload: unknown, scope: S): Envelope;