logic-sdk 0.7.0 → 0.7.2

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 (100) hide show
  1. package/README.md +9 -9
  2. package/dist/adapters/cloudflare-queue.d.ts +14 -0
  3. package/dist/adapters/cloudflare-queue.js +48 -0
  4. package/dist/adapters/drizzle-pg.d.ts +250 -0
  5. package/dist/adapters/drizzle-pg.js +69 -0
  6. package/dist/adapters/drizzle-sqlite.d.ts +257 -0
  7. package/dist/adapters/drizzle-sqlite.js +196 -0
  8. package/dist/adapters/pg-boss.d.ts +45 -0
  9. package/dist/adapters/pg-boss.js +180 -0
  10. package/dist/adapters/postgres.d.ts +32 -0
  11. package/dist/adapters/postgres.js +105 -0
  12. package/dist/adapters/sqlite.d.ts +13 -0
  13. package/dist/adapters/sqlite.js +88 -0
  14. package/dist/{stored-jobs.d.ts → adapters/stored-jobs.d.ts} +27 -10
  15. package/dist/{stored-jobs.js → adapters/stored-jobs.js} +106 -20
  16. package/dist/ai.d.ts +1 -32
  17. package/dist/ai.js +1 -40
  18. package/dist/cloudflare.d.ts +2 -55
  19. package/dist/cloudflare.js +2 -85
  20. package/dist/core/in-process.d.ts +9 -0
  21. package/dist/core/in-process.js +17 -0
  22. package/dist/core/jobs.d.ts +57 -0
  23. package/dist/{jobs.js → core/jobs.js} +161 -42
  24. package/dist/core/registry.d.ts +120 -0
  25. package/dist/core/registry.js +503 -0
  26. package/dist/core/testing.d.ts +75 -0
  27. package/dist/core/testing.js +230 -0
  28. package/dist/{types.d.ts → core/types.d.ts} +224 -49
  29. package/dist/drizzle/pg.d.ts +3 -236
  30. package/dist/drizzle/pg.js +2 -67
  31. package/dist/drizzle/sqlite.d.ts +3 -242
  32. package/dist/drizzle/sqlite.js +2 -194
  33. package/dist/fetch.d.ts +1 -19
  34. package/dist/fetch.js +1 -30
  35. package/dist/hosts/cloudflare.d.ts +42 -0
  36. package/dist/hosts/cloudflare.js +39 -0
  37. package/dist/hosts/node.d.ts +26 -0
  38. package/dist/hosts/node.js +76 -0
  39. package/dist/hosts/pg-boss.d.ts +22 -0
  40. package/dist/hosts/pg-boss.js +55 -0
  41. package/dist/index.d.ts +5 -124
  42. package/dist/index.js +4 -495
  43. package/dist/integrations/ai.d.ts +32 -0
  44. package/dist/integrations/ai.js +40 -0
  45. package/dist/integrations/fetch.d.ts +19 -0
  46. package/dist/integrations/fetch.js +30 -0
  47. package/dist/integrations/orpc.d.ts +22 -0
  48. package/dist/integrations/orpc.js +37 -0
  49. package/dist/node.d.ts +1 -26
  50. package/dist/node.js +1 -76
  51. package/dist/orpc.d.ts +1 -21
  52. package/dist/orpc.js +1 -37
  53. package/dist/pg-boss.d.ts +2 -55
  54. package/dist/pg-boss.js +2 -211
  55. package/dist/postgres.d.ts +2 -28
  56. package/dist/postgres.js +1 -82
  57. package/dist/sqlite.d.ts +2 -9
  58. package/dist/sqlite.js +1 -65
  59. package/dist/testing.d.ts +1 -67
  60. package/dist/testing.js +1 -214
  61. package/package.json +2 -2
  62. package/skills/logic-sdk/SKILL.md +7 -6
  63. package/src/adapters/cloudflare-queue.ts +56 -0
  64. package/src/adapters/drizzle-pg.ts +108 -0
  65. package/src/adapters/drizzle-sqlite.ts +234 -0
  66. package/src/adapters/pg-boss.ts +195 -0
  67. package/src/adapters/postgres.ts +112 -0
  68. package/src/adapters/sqlite.ts +96 -0
  69. package/src/{stored-jobs.ts → adapters/stored-jobs.ts} +133 -30
  70. package/src/ai.ts +1 -62
  71. package/src/cloudflare.ts +2 -107
  72. package/src/core/in-process.ts +18 -0
  73. package/src/{jobs.ts → core/jobs.ts} +166 -43
  74. package/src/core/registry.ts +671 -0
  75. package/src/core/testing.ts +307 -0
  76. package/src/{types.ts → core/types.ts} +219 -46
  77. package/src/drizzle/pg.ts +3 -110
  78. package/src/drizzle/sqlite.ts +3 -236
  79. package/src/fetch.ts +1 -31
  80. package/src/hosts/cloudflare.ts +54 -0
  81. package/src/hosts/node.ts +99 -0
  82. package/src/hosts/pg-boss.ts +71 -0
  83. package/src/index.ts +17 -655
  84. package/src/integrations/ai.ts +63 -0
  85. package/src/integrations/fetch.ts +31 -0
  86. package/src/integrations/orpc.ts +47 -0
  87. package/src/node.ts +1 -99
  88. package/src/orpc.ts +1 -46
  89. package/src/pg-boss.ts +2 -242
  90. package/src/postgres.ts +2 -90
  91. package/src/sqlite.ts +2 -74
  92. package/src/testing.ts +1 -288
  93. package/dist/jobs.d.ts +0 -44
  94. /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
  95. /package/dist/{errors.js → core/errors.js} +0 -0
  96. /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
  97. /package/dist/{schedule.js → core/schedule.js} +0 -0
  98. /package/dist/{types.js → core/types.js} +0 -0
  99. /package/src/{errors.ts → core/errors.ts} +0 -0
  100. /package/src/{schedule.ts → core/schedule.ts} +0 -0
@@ -187,7 +187,7 @@ export interface CronJob {
187
187
  runAt?: string;
188
188
  }
189
189
 
190
- /** A function `ctx.schedule` asked to run later: `id` is `<function id>@<uuid>`, returned by `ctx.schedule`. */
190
+ /** A function `ctx.schedule` asked to run later: `id` is `<function id>@<uuid>`. */
191
191
  export interface CallJob {
192
192
  kind: "call";
193
193
  id: string;
@@ -203,8 +203,8 @@ export interface CallJob {
203
203
  * function that schedules itself with no delay stops like a listener loop. A delayed one starts a new chain (0).
204
204
  */
205
205
  depth: number;
206
- /** Its `replace` key: a newer call to `fn` with the same key replaces this one while it waits. */
207
- replace?: string;
206
+ /** `true`: a newer call to `fn` with the same input replaces this one while it waits (the function and its input are the identity). */
207
+ replace?: true;
208
208
  /** When it may run (ISO). */
209
209
  runAt?: string;
210
210
  }
@@ -215,18 +215,27 @@ export interface CallJob {
215
215
  */
216
216
  export type Job = Delivery | CronJob | CallJob;
217
217
 
218
- /** A function to run on a schedule, as `scope`. Export it from a module, like listeners. */
218
+ /** Work on a schedule, as `scope`: a handler, like a listener's, run when the clock says. Export it from a module. */
219
219
  export interface Cron<C extends Config = any> extends FromInit<C> {
220
220
  readonly [BRAND]: "cron";
221
221
  readonly kind: "cron";
222
222
  readonly id?: string;
223
223
  readonly schedule: string;
224
224
  readonly timezone?: string;
225
- /** The function it runs, read when the registry is built, like a listener's `event`. */
226
- readonly run: () => Fn;
227
- readonly input?: unknown;
228
225
  readonly scope: object;
229
226
  readonly attempts?: number;
227
+ readonly meta?: Readonly<Record<string, unknown>>;
228
+ readonly handler: (ctx: never) => Promise<unknown>;
229
+ }
230
+
231
+ /** The run a cron's handler is doing. No scope here: `ctx.scope` is the one it runs as. */
232
+ export interface CronRun {
233
+ /** The cron's id: `tasks.wakeDue`. */
234
+ id: string;
235
+ /** The minute this run is for (ISO), even when it runs late or again: which day a digest covers. */
236
+ scheduledAt: string;
237
+ /** 1 on the first try. */
238
+ attempt: number;
230
239
  }
231
240
 
232
241
  /**
@@ -237,6 +246,18 @@ export interface Cron<C extends Config = any> extends FromInit<C> {
237
246
  */
238
247
  export type JobOutcome = "done" | "failed" | "discarded";
239
248
 
249
+ /**
250
+ * What `ctx.emit` queued: the `id`, `name` and `occurredAt` its listeners see as `ctx.event`. `payload` is a copy of what
251
+ * you passed; listeners get it parsed by the event's schema.
252
+ */
253
+ export interface EmittedEvent<I = unknown> {
254
+ readonly id: string;
255
+ readonly name: string;
256
+ readonly payload: I;
257
+ /** ISO. */
258
+ readonly occurredAt: string;
259
+ }
260
+
240
261
  /** The event a listener is handling. No scope here: `ctx.scope` is the one it runs as. */
241
262
  export interface ListenerEvent<O = unknown> {
242
263
  id: string;
@@ -268,7 +289,7 @@ export interface Listener<O = unknown, C extends Config = any> extends FromInit<
268
289
  export interface RunOptions<S = object> {
269
290
  /**
270
291
  * The whole scope for this call and everything it runs, never merged: `{ scope: { ...ctx.scope, locale: "es" } }`
271
- * to render in another language, `{ scope: asSystem("reports.weekly") }` to act as someone else on purpose. The
292
+ * to render in another language, `{ scope: { kind: "system", job: "reports.weekly" } }` to act as someone else on purpose. The
272
293
  * callee's policy sees it. Whole, so it's one of your scope's variants: a patch could build one that isn't.
273
294
  */
274
295
  scope?: S;
@@ -320,22 +341,32 @@ export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C
320
341
  * `await ctx.run(availability.hold, { propertyId })`. If it fails, the whole transaction rolls back.
321
342
  */
322
343
  run: Run<"query" | "mutation", ScopeOf<C>>;
323
- /** Queue an event. Delivered to listeners only after the transaction commits. */
324
- emit<I>(event: EventDef<I, unknown>, payload: I): void;
344
+ /**
345
+ * Queue an event. Delivered to listeners only after the transaction commits. Returns what it queued: the id, name and
346
+ * time its listeners see as `ctx.event`, so a row you write in this transaction can carry `event.id` and a listener
347
+ * finds it by `ctx.event.id`.
348
+ */
349
+ emit<I>(event: EventDef<I, unknown>, payload: I): EmittedEvent<I>;
325
350
  /**
326
351
  * Run a mutation or action once, later, as this scope: `ctx.schedule(guests.remind, { bookingId }, { at })` or
327
- * `{ delay: 3600 }` (seconds). Committed with this transaction, so a rollback never leaves one behind. Returns its job
328
- * id. It runs whatever happens meanwhile, so it should check that its reason still holds ("still confirmed?").
329
- * `attempts`: tries in total, default 1; give an action that calls an API a few. `replace`: a key, so a newer call
330
- * with it replaces the one still waiting (`replace: booking.id` when the dates change), like Oban's `replace`.
352
+ * `{ delay: 3600 }` (seconds). Committed with this transaction, so a rollback never leaves one behind. Nothing to
353
+ * keep: there's no cancel. It runs whatever happens meanwhile, so it checks that its reason still holds ("still
354
+ * confirmed?") against your own row. `attempts`: tries in total, default 1; give an action that calls an API a few.
355
+ * `replace: true`: a newer call to this function with the same input replaces the one still waiting (the dates of
356
+ * `{ bookingId }` changed), like Oban's `replace`. Keep the input to ids, so it names one thing.
331
357
  */
332
- schedule<F extends Fn<"mutation" | "action">>(fn: F, input: FnIn<F>, options: ScheduleOptions): string;
358
+ schedule<F extends Fn<"mutation" | "action">>(fn: F, input: FnIn<F>, options: ScheduleOptions<ScopeOf<C>>): void;
333
359
  }
334
360
  /** When a scheduled call runs (`at` or `delay` in seconds), and how many tries it gets. */
335
- export type ScheduleOptions = ({ at: Date; delay?: never } | { delay: number; at?: never }) & {
361
+ export type ScheduleOptions<S = object> = ({ at: Date; delay?: never } | { delay: number; at?: never }) & {
336
362
  attempts?: number;
337
- /** A key: the call to this function waiting with the same key (not started yet) is replaced by this one. */
338
- replace?: string;
363
+ /** `true`: the call to this function waiting with the same input (not started yet) is replaced by this one. */
364
+ replace?: true;
365
+ /**
366
+ * Who it runs as, whole, never merged, as `ctx.run` takes it: `{ scope: { kind: "system", job: "tasks.wake", organization } }`.
367
+ * Default: this mutation's scope. The function's policy checks it when it runs.
368
+ */
369
+ scope?: S;
339
370
  };
340
371
  export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
341
372
  services: ServicesOf<C>;
@@ -347,6 +378,10 @@ export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C,
347
378
  export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
348
379
  event: ListenerEvent<O>;
349
380
  }
381
+ /** A cron's handler's ctx: an action's, as the cron's own scope, plus the run. */
382
+ export interface CronCtx<C extends Config, S = ScopeOf<C>> extends ActionCtx<C, S> {
383
+ cron: CronRun;
384
+ }
350
385
 
351
386
  /**
352
387
  * Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
@@ -419,23 +454,27 @@ export interface DatabaseAdapter<Db = unknown, Tx = Db> {
419
454
  nest?(tx: Tx): DatabaseAdapter<Tx, Tx>;
420
455
  /** Did this transaction lose a race the database says to retry (deadlock, serialization failure)? */
421
456
  retryable?(error: unknown): boolean;
422
- /**
423
- * Tries in total for a top-level mutation whose transaction is `retryable`, each in a fresh one, like Laravel's
424
- * `DB::transaction(fn, attempts)`. Default 3; 1 turns it off. A job's own tries are its `attempts`.
425
- */
426
- transactionAttempts?: number;
427
- /**
428
- * One SQL statement (`$1` parameters on Postgres, `?` on SQLite), on the database or on a transaction of it. Resolves the rows it
429
- * returns. `databaseQueue` and `outbox` run their table through it, so any ORM that can run SQL has them.
430
- */
431
- query?(client: Db | Tx, text: string, params: unknown[]): Promise<Record<string, unknown>[]>;
432
457
  }
433
458
 
434
- /** A database adapter with `query`: what `databaseQueue(database)` and `outbox(database, queue)` take. */
459
+ /** A database adapter that runs SQL: what `databaseQueue()`, `outbox(queue)` and `pgBoss(boss)` need. */
435
460
  export interface SqlDatabase<Db = any, Tx = any> extends DatabaseAdapter<Db, Tx> {
461
+ /**
462
+ * One SQL statement (`$1` parameters on Postgres, `?` on SQLite), on the database or on a transaction of it. Resolves
463
+ * the rows it returns. The jobs table runs through it, so any ORM that can run SQL has it.
464
+ */
436
465
  query(client: Db | Tx, text: string, params: unknown[]): Promise<Record<string, unknown>[]>;
437
466
  }
438
467
 
468
+ /**
469
+ * `createRegistry({ database })`: the adapter, and how the core uses it. `transactionAttempts`: tries in total for a
470
+ * top-level mutation whose transaction lost a race (`retryable`), each in a fresh one, like Laravel's
471
+ * `DB::transaction(fn, attempts)`. Default 3; 1 turns it off. A job's own tries are its `attempts`.
472
+ */
473
+ export interface DatabaseOptions<A extends DatabaseAdapter<any, any> = DatabaseAdapter<unknown, unknown>> {
474
+ adapter: A;
475
+ transactionAttempts?: number;
476
+ }
477
+
439
478
  /** Runs one job: resolves when it's done or failed for good (acknowledge it), throws when a retry might help. */
440
479
  export type RunJob = (job: Job, options?: RunJobOptions) => Promise<JobOutcome>;
441
480
 
@@ -465,6 +504,18 @@ export interface Runner {
465
504
  }
466
505
 
467
506
  export interface JobsAdapter {
507
+ /** How it's set up, for messages: `"databaseQueue()"`. The core names capabilities, the adapter itself. */
508
+ name?: string;
509
+ /**
510
+ * It can run a job again after a failed try: a queue redelivers it, a table backs off. Without it (`inProcess()`),
511
+ * `createRegistry` refuses `attempts` above 1 rather than ignore them, as it refuses a delay it can't hold.
512
+ */
513
+ retries?: true;
514
+ /**
515
+ * It writes jobs with SQL in the mutation's transaction, through the registry's database: `createRegistry` refuses a
516
+ * registry whose `database.adapter` doesn't run SQL (`query`), and `connect` gets it as `setup.sql`.
517
+ */
518
+ sql?: true;
468
519
  /**
469
520
  * It can hold a job until its `runAt` (a listener's `delay`, `ctx.schedule`): `true`, or for at most `max` seconds.
470
521
  * Without it (`inProcess()`), `createRegistry` refuses delayed listeners and `ctx.schedule` throws, rather than run
@@ -472,13 +523,16 @@ export interface JobsAdapter {
472
523
  */
473
524
  holds?: true | { max: number };
474
525
  /**
475
- * Can replace a call waiting to run: `enqueue` gets a call with `replace`, and a pending call to the same `fn` with
476
- * the same key that hasn't started is replaced by it. `databaseQueue` and `outbox` can; a queue that already has the message can't.
477
- * Without it, `ctx.schedule` with `replace` is refused.
526
+ * Can replace a call waiting to run: `enqueue` gets a call with `replace`, and a pending call with the same key
527
+ * (`storedReplaceKey`) that hasn't started is replaced by it. `databaseQueue` and `outbox` can; a queue that already
528
+ * has the message can't. Without it, `ctx.schedule` with `replace` is refused.
478
529
  */
479
530
  replaces?: true;
480
- /** At `createRegistry`: refuse a setup this adapter can't honour (a database it doesn't share). */
481
- check?(setup: { listeners: readonly RegisteredListener[]; database: DatabaseAdapter<unknown, unknown> | undefined }): void;
531
+ /**
532
+ * At `createRegistry`, once: take what the adapter needs from the registry (its database, for an adapter that writes
533
+ * jobs in the mutation's transaction), and refuse a setup it can't honour.
534
+ */
535
+ connect?(setup: AdapterSetup): void;
482
536
  /** Inside the transaction, before commit. In-process: nothing. `databaseQueue` and `outbox`: insert one row per job with `tx`. */
483
537
  enqueue?(tx: unknown, jobs: Job[]): Promise<void>;
484
538
  /** After commit: run them, or hand them to a queue. A throw is reported to `onError`. */
@@ -487,6 +541,10 @@ export interface JobsAdapter {
487
541
  sweep?(runner: Runner, options?: { limit?: number }): Promise<SweepResult>;
488
542
  /** Put a failed job back in line. `false` when there's no failed job with that id. Only adapters that store them. */
489
543
  retry?(id: string): Promise<boolean>;
544
+ /** A page of failed jobs, newest first. Only adapters that store them and can filter them. */
545
+ failed?(options: FailedQuery): Promise<{ rows: FailedRow[]; cursor: string | null }>;
546
+ /** Delete one failed job. `false` when there's no failed job with that id: a waiting or running one is never touched. */
547
+ forget?(id: string): Promise<boolean>;
490
548
  /**
491
549
  * Keep a job that failed for good after it left the adapter: `registry.jobs.run` calls it from a queue consumer, so
492
550
  * `outbox` stores the failure Cloudflare would otherwise drop. Not called for jobs the adapter ran itself.
@@ -508,6 +566,93 @@ export interface FailureInfo {
508
566
  outcome?: "retry" | "failed" | "discarded";
509
567
  }
510
568
 
569
+ /** What `createRegistry` gives an adapter's `connect`. */
570
+ export interface AdapterSetup {
571
+ listeners: readonly RegisteredListener[];
572
+ crons: readonly RegisteredCron[];
573
+ /** The registry's `database.adapter`. */
574
+ database: DatabaseAdapter<unknown, unknown> | undefined;
575
+ /** The same, when it runs SQL: always set for an adapter that declares `sql: true`. */
576
+ sql: SqlDatabase | undefined;
577
+ }
578
+
579
+ /**
580
+ * A store for failed jobs, apart from the queue that runs them, like Laravel's `failed` driver. `failedJobs()`
581
+ * keeps them in the jobs table. For adapters that keep their own, it isn't needed.
582
+ */
583
+ export interface FailedJobs {
584
+ /** For messages: `"failedJobs()"`. */
585
+ name?: string;
586
+ /** Keeps failed jobs with SQL, through the registry's database (`setup.sql`): see `JobsAdapter.sql`. */
587
+ sql?: true;
588
+ /** At `createRegistry`, once: take the registry's database. */
589
+ connect?(setup: AdapterSetup): void;
590
+ /** Keep a job that failed for good. */
591
+ fail(job: Job, error: unknown): Promise<void>;
592
+ /** A page of failed jobs, newest first. */
593
+ failed(query: FailedQuery): Promise<{ rows: FailedRow[]; cursor: string | null }>;
594
+ /** Remove a failed job and return it, for `retry` to hand to the queue again. Undefined when there's none with that id. */
595
+ take(id: string): Promise<Job | undefined>;
596
+ /** Delete a failed job. `false` when there's none with that id. */
597
+ forget(id: string): Promise<boolean>;
598
+ }
599
+
600
+ /** One field of a stored scope a `failed({ scope })` filter matches exactly: `["organization", "id"]` and `"org_1"`. */
601
+ export interface ScopeMatch {
602
+ path: string[];
603
+ value: string | number | boolean | null;
604
+ }
605
+ /** What `registry.jobs.failed` asks an adapter for. The core checks and flattens the filter first. */
606
+ export interface FailedQuery {
607
+ /** The listener, cron or function id. */
608
+ source?: string;
609
+ /** Every one must equal the stored scope's field at `path` (the job's `scope`, or its envelope's). */
610
+ scope?: ScopeMatch[];
611
+ limit: number;
612
+ /** From the last page: where to go on. */
613
+ cursor?: string;
614
+ }
615
+ /** A failed job as an adapter keeps it. */
616
+ export interface FailedRow {
617
+ id: string;
618
+ job: Job;
619
+ error: string;
620
+ /** ISO. */
621
+ failedAt: string;
622
+ }
623
+ /** A failed job, as `registry.jobs.failed` lists it: pass its `id` to `retry` or `forget`. */
624
+ export interface FailedJob<Stored = Record<string, unknown>> {
625
+ id: string;
626
+ kind: Job["kind"];
627
+ /** The listener, cron or function that failed, as in `FailureInfo`. */
628
+ source: string;
629
+ /** What `jobs.scope.store` saved with it. Undefined for a cron run: it has none. */
630
+ scope: Stored | undefined;
631
+ /** The last error, with its stack. */
632
+ error: string;
633
+ /** ISO. */
634
+ failedAt: string;
635
+ job: Job;
636
+ }
637
+ export interface FailedOptions<Stored = Record<string, unknown>> {
638
+ /** Only this listener's, cron's or function's: `"emails.send"`. */
639
+ source?: string;
640
+ /**
641
+ * Only jobs whose stored scope has these values (what `jobs.scope.store` saved): `{ organizationId: "org_1" }`,
642
+ * nested fields too. Never a cron run: it stores none. Values are strings, numbers, booleans or null.
643
+ */
644
+ scope?: DeepPartial<Stored>;
645
+ /** 1 to 1000. Default 100. */
646
+ limit?: number;
647
+ /** The `cursor` of the page before. */
648
+ cursor?: string;
649
+ }
650
+ export interface FailedPage<Stored = Record<string, unknown>> {
651
+ jobs: FailedJob<Stored>[];
652
+ /** Pass it back for the next page; null on the last one. */
653
+ cursor: string | null;
654
+ }
655
+
511
656
  /**
512
657
  * Who a job runs as, at rest. `store` picks what's saved with the job (ids, not whole objects); `load` rebuilds the
513
658
  * scope when it runs, so policies see today's roles. `load` returning null discards the job (reported to `onError`),
@@ -532,6 +677,11 @@ export interface InProcess extends JobsAdapter {
532
677
  * checked at startup: requiring it here would report a missing one as a wrong `store`.
533
678
  */
534
679
  export type JobsOptions<S = object, T = any> = {
680
+ /**
681
+ * Where failed jobs are kept when your adapter can't keep them itself (a queue on its own), like Laravel's `failed`
682
+ * driver: `failed: failedJobs()`. `registry.jobs.failed`, `retry` and `forget` then work on it.
683
+ */
684
+ failed?: FailedJobs;
535
685
  /**
536
686
  * Max chain of listener → mutation → event → listener… before queueing stops, reported. Calls `ctx.schedule` runs
537
687
  * right away count too, so a function that schedules itself with no delay stops the same way. Default 8 (real chains
@@ -540,13 +690,13 @@ export type JobsOptions<S = object, T = any> = {
540
690
  maxEventDepth?: number;
541
691
  } & (
542
692
  | {
543
- /** `inProcess()` (default), or a durable one like `databaseQueue(database)`. Its own options go in its factory. */
693
+ /** `inProcess()` (default), or a durable one like `databaseQueue()`. Its own options go in its factory. */
544
694
  adapter?: InProcess;
545
695
  /** Applied by the registry in every adapter, `inProcess()` and tests included. */
546
696
  scope?: JobScope<S, T>;
547
697
  }
548
698
  | {
549
- /** An adapter that keeps jobs to run later, like `databaseQueue(database)`. */
699
+ /** An adapter that keeps jobs to run later, like `databaseQueue()`. */
550
700
  adapter?: JobsAdapter;
551
701
  /** Required: such a job runs as the scope `load` rebuilds, with today's roles. */
552
702
  scope: JobScope<S, T>;
@@ -555,8 +705,10 @@ export type JobsOptions<S = object, T = any> = {
555
705
 
556
706
  export interface Call<M = unknown> {
557
707
  id: string;
558
- kind: Kind | "listener";
559
- /** The function's or listener's `meta` (undefined when it has none). */
708
+ kind: Kind | "listener" | "cron";
709
+ /** 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). */
710
+ job?: { id: string; attempt: number };
711
+ /** The function's, listener's or cron's `meta` (undefined when it has none). */
560
712
  meta: M | undefined;
561
713
  /** Raw input as received (before validation). */
562
714
  input: unknown;
@@ -567,11 +719,12 @@ export interface Call<M = unknown> {
567
719
  export interface RegistryOptions<Mods extends Record<string, object>> {
568
720
  /** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
569
721
  modules: Mods;
570
- database?: DatabaseAdapter<unknown, unknown>;
722
+ /** `database: { adapter: drizzleAdapter(db) }`, with `transactionAttempts` when 3 isn't right. */
723
+ database?: DatabaseOptions;
571
724
  services?: object;
572
725
  /** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
573
726
  config?: object;
574
- /** Background work: `jobs: { adapter: databaseQueue(database), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
727
+ /** Background work: `jobs: { adapter: databaseQueue(), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
575
728
  jobs?: JobsOptions;
576
729
  /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
577
730
  wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
@@ -611,6 +764,8 @@ export interface Overrides {
611
764
  /** Merged over the registry's config, section by section. */
612
765
  config?: unknown;
613
766
  adapter?: JobsAdapter;
767
+ /** Where failed jobs go instead of `jobs.failed`; `null` keeps none (a test registry: failures throw). */
768
+ failed?: FailedJobs | null;
614
769
  now?: () => Date;
615
770
  stubs?: Map<Fn, (ctx: never, input: never) => Promise<unknown>>;
616
771
  record?: (envelope: Envelope) => void;
@@ -628,10 +783,12 @@ export interface RegisteredListener extends Registered {
628
783
  }
629
784
  export interface RegisteredCron extends Registered {
630
785
  cron: Cron;
631
- run: Fn;
632
786
  }
633
787
 
634
- /** `registry.jobs`: what you call from a queue consumer, a cron, or a script. */
788
+ /**
789
+ * `registry.jobs`: what you call from a queue consumer, a timer, a script or a staff route. Outside your functions, as
790
+ * Laravel's queue commands are: guard the route yourself. A job a user wants again is a mutation that emits again.
791
+ */
635
792
  export interface Jobs {
636
793
  /**
637
794
  * Run one stored job (queue consumers): `await registry.jobs.run(message.body, { attempt: message.attempts })`.
@@ -646,7 +803,7 @@ export interface Jobs {
646
803
  */
647
804
  tick(at?: Date): Promise<string[]>;
648
805
  /**
649
- * Run what your adapter has due, from a cron or an interval: `await registry.jobs.sweep()`. With `databaseQueue(database)`, that's
806
+ * Run what your adapter has due, from a cron or an interval: `await registry.jobs.sweep()`. With `databaseQueue()`, that's
650
807
  * retries whose backoff is over and jobs whose runner crashed. Adapters that keep nothing, or maintain themselves
651
808
  * (pg-boss), resolve zeros.
652
809
  */
@@ -656,6 +813,23 @@ export interface Jobs {
656
813
  * running, done, or never existed). Throws when your adapter keeps no jobs, like `inProcess()`.
657
814
  */
658
815
  retry(id: string): Promise<boolean>;
816
+ /**
817
+ * Failed jobs, newest first, a page at a time: `await registry.jobs.failed({ source: "emails.send", scope: { organizationId } })`.
818
+ * Then `retry` or `forget` each. Pass your stored scope's type to check the filter: `failed<Stored>({ scope })`. Throws
819
+ * when your adapter keeps none (a queue alone without `jobs.failed`) or can't list them: its message says where they are.
820
+ */
821
+ failed<Stored = Record<string, unknown>>(options?: FailedOptions<Stored>): Promise<FailedPage<Stored>>;
822
+ /**
823
+ * Delete a failed job, like Laravel's `queue:forget`. `false` when no failed job has that id: a waiting or running one
824
+ * is never touched. Throws when your adapter keeps no jobs.
825
+ */
826
+ forget(id: string): Promise<boolean>;
827
+ /**
828
+ * Run a cron now, outside its schedule, through your jobs adapter like a tick: `await registry.jobs.invoke(orders.sendDigest)`,
829
+ * or its id from a script. `at`: the minute the run is for (`ctx.cron.scheduledAt`), default now, to redo a missed one.
830
+ * Its own job id, so the real tick for that minute still runs. Resolves the id; throws when the hand-off fails.
831
+ */
832
+ invoke(cron: Cron | string, options?: { at?: Date }): Promise<string>;
659
833
  }
660
834
 
661
835
  /** What `createRegistry` returns. `Cf` is your config's type, so tests can override parts of it. */
@@ -676,12 +850,11 @@ export interface Registry<S extends object = object, Mods extends Record<string,
676
850
  /** @internal used by `logic-sdk/testing` */
677
851
  readonly [INTERNAL]: {
678
852
  options: RegistryOptions<Mods>;
679
- config: Frozen<Cf>;
680
853
  derive(more: Overrides): Registry<S, Mods, Cf>;
681
854
  /** An event as `emit` would make it, for `t.jobs.perform`. */
682
855
  envelope(event: EventDef, payload: unknown, scope: S): Envelope;
683
- /** The cron runs due in a minute, for `t.jobs.tick`. */
684
- due(at: Date): CronJob[];
856
+ /** The cron runs due in a minute, for `t.jobs.tick`; with `only`, that cron's run, due or not (`t.jobs.perform`). */
857
+ due(at: Date, only?: string): CronJob[];
685
858
  };
686
859
  }
687
860
 
package/src/drizzle/pg.ts CHANGED
@@ -1,110 +1,3 @@
1
- import { sql, type SQL } from "drizzle-orm";
2
- import { index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
3
- import type { DatabaseAdapter, Job, ReadWrite, SqlDatabase } from "../index.ts";
4
- import { causes } from "../errors.ts";
5
-
6
- export { databaseQueue, jobsSchema, outbox, type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "../postgres.ts";
7
-
8
- /** Anything with Drizzle's `transaction(fn)` and `execute(sql)`: a database or a transaction (nested = savepoint). */
9
- interface Transactional {
10
- transaction<T>(fn: (tx: any) => Promise<T>, config?: any): Promise<T>;
11
- execute(query: SQL, mode: "objects"): PromiseLike<Record<string, unknown>[]>;
12
- }
13
-
14
- /** Drizzle's transaction for a database. Nested `transaction` calls on it are savepoints. */
15
- type Transaction<Db extends Transactional> = Parameters<Parameters<Db["transaction"]>[0]>[0];
16
-
17
- /**
18
- * What mutations get: the transaction minus `transaction`, since a savepoint that rolled back would still send the
19
- * events and calls made inside it. Type helpers with it: `type Tx = DrizzleTx<typeof db>`. A type-level guard.
20
- */
21
- export type DrizzleTx<Db extends Transactional> = Omit<Transaction<Db>, "transaction">;
22
-
23
- /** What queries get: the database minus write methods. A type-level guard, not a runtime one. */
24
- export type DrizzleReader<Db> = Omit<
25
- Db,
26
- "insert" | "update" | "delete" | "execute" | "transaction" | "batch" | "refreshMaterializedView"
27
- >;
28
-
29
- /**
30
- * Your database in `Config`: `db: DrizzleDb<Db>`, where `type Db = typeof db`. Queries get a `DrizzleReader`, mutations
31
- * the transaction.
32
- */
33
- export type DrizzleDb<Db extends Transactional> = ReadWrite<DrizzleReader<DrizzleTx<Db>>, DrizzleTx<Db>>;
34
-
35
- export type DrizzleAdapterOptions = Pick<DatabaseAdapter, "transactionAttempts">;
36
-
37
- /**
38
- * Use a Drizzle database for mutations. Needs a driver with async interactive transactions: node-postgres, postgres.js,
39
- * PGlite, Neon websocket, Hyperdrive. Not D1 or HTTP drivers. SQLite has its own adapter, `logic-sdk/drizzle/sqlite`.
40
- * The types reject SQLite and libsql databases here.
41
- */
42
- export function drizzleAdapter<Db extends Transactional>(
43
- db: Db,
44
- options: DrizzleAdapterOptions = {},
45
- ): SqlDatabase<Db, Transaction<Db>> { // the whole transaction, for `nest`; mutations see it as a DrizzleTx
46
- return {
47
- db,
48
- transactionAttempts: options.transactionAttempts,
49
- transaction: (fn) => db.transaction(fn),
50
- nest: (tx) => drizzleAdapter(tx), // the test registry's savepoints
51
- retryable: (e) => RETRYABLE.has(sqlState(e) ?? ""),
52
- query: async (client: Transactional, text, params) => client.execute(toSql(text, params), "objects"),
53
- };
54
- }
55
-
56
- /** SQL text with `$1` parameters as a Drizzle query. Splitting on a captured number leaves them at the odd places. */
57
- const toSql = (text: string, params: unknown[]) =>
58
- sql.join(text.split(/\$(\d+)/).map((part, i) => (i % 2 ? sql.param(params[Number(part) - 1]) : sql.raw(part))));
59
-
60
- /** Postgres: serialization_failure, deadlock_detected. The transaction lost a race; running it again is the fix. */
61
- const RETRYABLE = new Set(["40001", "40P01"]);
62
-
63
- /** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
64
- export function sqlState(error: unknown): string | undefined {
65
- for (const e of causes(error)) if ("code" in e && typeof e.code === "string") return e.code;
66
- return undefined;
67
- }
68
-
69
- /**
70
- * The table behind `databaseQueue` and `outbox` (Postgres), Laravel's `jobs`. Re-export it from your schema so
71
- * drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/pg";`. One row per pending job;
72
- * done rows are deleted, failed ones stay so you can query them and `retry` them.
73
- */
74
- export const jobsTable = pgTable(
75
- "logic_jobs",
76
- {
77
- /** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
78
- id: text("id").primaryKey(),
79
- job: jsonb("job").$type<Job>().notNull(),
80
- /** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
81
- status: text("status").$type<"pending" | "failed">().notNull().default("pending"),
82
- /** Incremented when a runner claims it, so a crash still uses an attempt. */
83
- attempts: integer("attempts").notNull().default(0),
84
- /** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
85
- availableAt: timestamp("available_at", { withTimezone: true }).notNull().defaultNow(),
86
- /** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
87
- receipt: text("receipt"),
88
- /** The last failure, with its stack. */
89
- lastError: text("last_error"),
90
- failedAt: timestamp("failed_at", { withTimezone: true }),
91
- /** A scheduled call's `replace` key, `<function id>@<key>`: a newer call with it replaces this row while it waits. */
92
- replaceKey: text("replace_key"),
93
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
94
- },
95
- (t) => [
96
- index("logic_jobs_due").on(t.availableAt).where(sql`${t.status} = 'pending'`),
97
- // one waiting call per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
98
- uniqueIndex("logic_jobs_replace").on(t.replaceKey).where(sql`status = 'pending' and attempts = 0`),
99
- ],
100
- );
101
-
102
- /**
103
- * The cron runs already ticked, so a minute ticked twice (several servers, a redelivered trigger) runs once, like
104
- * Solid Queue's recurring executions. Re-export it next to `jobsTable` when you have crons. Rows older than a day go.
105
- */
106
- export const cronRunsTable = pgTable("logic_cron_runs", {
107
- /** The cron job's id, `<cron id>@<minute>`. */
108
- id: text("id").primaryKey(),
109
- ranAt: timestamp("ran_at", { withTimezone: true }).notNull().defaultNow(),
110
- });
1
+ export { cronRunsTable, drizzleAdapter, jobsTable, sqlState, type DrizzleDb, type DrizzleReader, type DrizzleTx } from "../adapters/drizzle-pg.ts";
2
+ export { databaseQueue, failedJobs, jobsSchema, outbox } from "../adapters/postgres.ts";
3
+ export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "../adapters/stored-jobs.ts";