logic-sdk 0.7.1 → 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.
- package/README.md +7 -7
- package/dist/adapters/cloudflare-queue.d.ts +14 -0
- package/dist/adapters/cloudflare-queue.js +48 -0
- package/dist/adapters/drizzle-pg.d.ts +250 -0
- package/dist/adapters/drizzle-pg.js +69 -0
- package/dist/adapters/drizzle-sqlite.d.ts +257 -0
- package/dist/adapters/drizzle-sqlite.js +196 -0
- package/dist/adapters/pg-boss.d.ts +45 -0
- package/dist/adapters/pg-boss.js +180 -0
- package/dist/adapters/postgres.d.ts +32 -0
- package/dist/adapters/postgres.js +105 -0
- package/dist/adapters/sqlite.d.ts +13 -0
- package/dist/adapters/sqlite.js +88 -0
- package/dist/{stored-jobs.d.ts → adapters/stored-jobs.d.ts} +27 -10
- package/dist/{stored-jobs.js → adapters/stored-jobs.js} +106 -20
- package/dist/ai.d.ts +1 -32
- package/dist/ai.js +1 -40
- package/dist/cloudflare.d.ts +2 -55
- package/dist/cloudflare.js +2 -85
- package/dist/core/in-process.d.ts +9 -0
- package/dist/core/in-process.js +17 -0
- package/dist/{jobs.d.ts → core/jobs.d.ts} +23 -10
- package/dist/{jobs.js → core/jobs.js} +152 -39
- package/dist/core/registry.d.ts +120 -0
- package/dist/core/registry.js +503 -0
- package/dist/core/testing.d.ts +75 -0
- package/dist/core/testing.js +230 -0
- package/dist/{types.d.ts → core/types.d.ts} +203 -40
- package/dist/drizzle/pg.d.ts +3 -236
- package/dist/drizzle/pg.js +2 -67
- package/dist/drizzle/sqlite.d.ts +3 -242
- package/dist/drizzle/sqlite.js +2 -194
- package/dist/fetch.d.ts +1 -19
- package/dist/fetch.js +1 -30
- package/dist/hosts/cloudflare.d.ts +42 -0
- package/dist/hosts/cloudflare.js +39 -0
- package/dist/hosts/node.d.ts +26 -0
- package/dist/hosts/node.js +76 -0
- package/dist/hosts/pg-boss.d.ts +22 -0
- package/dist/hosts/pg-boss.js +55 -0
- package/dist/index.d.ts +5 -122
- package/dist/index.js +4 -492
- package/dist/integrations/ai.d.ts +32 -0
- package/dist/integrations/ai.js +40 -0
- package/dist/integrations/fetch.d.ts +19 -0
- package/dist/integrations/fetch.js +30 -0
- package/dist/integrations/orpc.d.ts +22 -0
- package/dist/integrations/orpc.js +37 -0
- package/dist/node.d.ts +1 -26
- package/dist/node.js +1 -76
- package/dist/orpc.d.ts +1 -21
- package/dist/orpc.js +1 -37
- package/dist/pg-boss.d.ts +2 -53
- package/dist/pg-boss.js +2 -213
- package/dist/postgres.d.ts +2 -28
- package/dist/postgres.js +1 -82
- package/dist/sqlite.d.ts +2 -9
- package/dist/sqlite.js +1 -65
- package/dist/testing.d.ts +1 -75
- package/dist/testing.js +1 -227
- package/package.json +2 -2
- package/skills/logic-sdk/SKILL.md +4 -3
- package/src/adapters/cloudflare-queue.ts +56 -0
- package/src/adapters/drizzle-pg.ts +108 -0
- package/src/adapters/drizzle-sqlite.ts +234 -0
- package/src/adapters/pg-boss.ts +195 -0
- package/src/adapters/postgres.ts +112 -0
- package/src/adapters/sqlite.ts +96 -0
- package/src/{stored-jobs.ts → adapters/stored-jobs.ts} +133 -30
- package/src/ai.ts +1 -62
- package/src/cloudflare.ts +2 -107
- package/src/core/in-process.ts +18 -0
- package/src/{jobs.ts → core/jobs.ts} +152 -38
- package/src/core/registry.ts +671 -0
- package/src/core/testing.ts +307 -0
- package/src/{types.ts → core/types.ts} +197 -40
- package/src/drizzle/pg.ts +3 -110
- package/src/drizzle/sqlite.ts +3 -236
- package/src/fetch.ts +1 -31
- package/src/hosts/cloudflare.ts +54 -0
- package/src/hosts/node.ts +99 -0
- package/src/hosts/pg-boss.ts +71 -0
- package/src/index.ts +15 -652
- package/src/integrations/ai.ts +63 -0
- package/src/integrations/fetch.ts +31 -0
- package/src/integrations/orpc.ts +47 -0
- package/src/node.ts +1 -99
- package/src/orpc.ts +1 -46
- package/src/pg-boss.ts +2 -241
- package/src/postgres.ts +2 -90
- package/src/sqlite.ts +2 -74
- package/src/testing.ts +1 -305
- /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
- /package/dist/{errors.js → core/errors.js} +0 -0
- /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
- /package/dist/{schedule.js → core/schedule.js} +0 -0
- /package/dist/{types.js → core/types.js} +0 -0
- /package/src/{errors.ts → core/errors.ts} +0 -0
- /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
|
|
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
|
-
/**
|
|
207
|
-
replace?:
|
|
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
|
}
|
|
@@ -246,6 +246,18 @@ export interface CronRun {
|
|
|
246
246
|
*/
|
|
247
247
|
export type JobOutcome = "done" | "failed" | "discarded";
|
|
248
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
|
+
|
|
249
261
|
/** The event a listener is handling. No scope here: `ctx.scope` is the one it runs as. */
|
|
250
262
|
export interface ListenerEvent<O = unknown> {
|
|
251
263
|
id: string;
|
|
@@ -329,22 +341,32 @@ export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C
|
|
|
329
341
|
* `await ctx.run(availability.hold, { propertyId })`. If it fails, the whole transaction rolls back.
|
|
330
342
|
*/
|
|
331
343
|
run: Run<"query" | "mutation", ScopeOf<C>>;
|
|
332
|
-
/**
|
|
333
|
-
|
|
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>;
|
|
334
350
|
/**
|
|
335
351
|
* Run a mutation or action once, later, as this scope: `ctx.schedule(guests.remind, { bookingId }, { at })` or
|
|
336
|
-
* `{ delay: 3600 }` (seconds). Committed with this transaction, so a rollback never leaves one behind.
|
|
337
|
-
*
|
|
338
|
-
* `attempts`: tries in total, default 1; give an action that calls an API a few.
|
|
339
|
-
* with
|
|
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.
|
|
340
357
|
*/
|
|
341
|
-
schedule<F extends Fn<"mutation" | "action">>(fn: F, input: FnIn<F>, options: ScheduleOptions):
|
|
358
|
+
schedule<F extends Fn<"mutation" | "action">>(fn: F, input: FnIn<F>, options: ScheduleOptions<ScopeOf<C>>): void;
|
|
342
359
|
}
|
|
343
360
|
/** When a scheduled call runs (`at` or `delay` in seconds), and how many tries it gets. */
|
|
344
|
-
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 }) & {
|
|
345
362
|
attempts?: number;
|
|
346
|
-
/**
|
|
347
|
-
replace?:
|
|
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;
|
|
348
370
|
};
|
|
349
371
|
export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
350
372
|
services: ServicesOf<C>;
|
|
@@ -432,23 +454,27 @@ export interface DatabaseAdapter<Db = unknown, Tx = Db> {
|
|
|
432
454
|
nest?(tx: Tx): DatabaseAdapter<Tx, Tx>;
|
|
433
455
|
/** Did this transaction lose a race the database says to retry (deadlock, serialization failure)? */
|
|
434
456
|
retryable?(error: unknown): boolean;
|
|
435
|
-
/**
|
|
436
|
-
* Tries in total for a top-level mutation whose transaction is `retryable`, each in a fresh one, like Laravel's
|
|
437
|
-
* `DB::transaction(fn, attempts)`. Default 3; 1 turns it off. A job's own tries are its `attempts`.
|
|
438
|
-
*/
|
|
439
|
-
transactionAttempts?: number;
|
|
440
|
-
/**
|
|
441
|
-
* One SQL statement (`$1` parameters on Postgres, `?` on SQLite), on the database or on a transaction of it. Resolves the rows it
|
|
442
|
-
* returns. `databaseQueue` and `outbox` run their table through it, so any ORM that can run SQL has them.
|
|
443
|
-
*/
|
|
444
|
-
query?(client: Db | Tx, text: string, params: unknown[]): Promise<Record<string, unknown>[]>;
|
|
445
457
|
}
|
|
446
458
|
|
|
447
|
-
/** A database adapter
|
|
459
|
+
/** A database adapter that runs SQL: what `databaseQueue()`, `outbox(queue)` and `pgBoss(boss)` need. */
|
|
448
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
|
+
*/
|
|
449
465
|
query(client: Db | Tx, text: string, params: unknown[]): Promise<Record<string, unknown>[]>;
|
|
450
466
|
}
|
|
451
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
|
+
|
|
452
478
|
/** Runs one job: resolves when it's done or failed for good (acknowledge it), throws when a retry might help. */
|
|
453
479
|
export type RunJob = (job: Job, options?: RunJobOptions) => Promise<JobOutcome>;
|
|
454
480
|
|
|
@@ -478,6 +504,18 @@ export interface Runner {
|
|
|
478
504
|
}
|
|
479
505
|
|
|
480
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;
|
|
481
519
|
/**
|
|
482
520
|
* It can hold a job until its `runAt` (a listener's `delay`, `ctx.schedule`): `true`, or for at most `max` seconds.
|
|
483
521
|
* Without it (`inProcess()`), `createRegistry` refuses delayed listeners and `ctx.schedule` throws, rather than run
|
|
@@ -485,17 +523,16 @@ export interface JobsAdapter {
|
|
|
485
523
|
*/
|
|
486
524
|
holds?: true | { max: number };
|
|
487
525
|
/**
|
|
488
|
-
* Can replace a call waiting to run: `enqueue` gets a call with `replace`, and a pending call
|
|
489
|
-
*
|
|
490
|
-
* 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.
|
|
491
529
|
*/
|
|
492
530
|
replaces?: true;
|
|
493
|
-
/**
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
}): 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;
|
|
499
536
|
/** Inside the transaction, before commit. In-process: nothing. `databaseQueue` and `outbox`: insert one row per job with `tx`. */
|
|
500
537
|
enqueue?(tx: unknown, jobs: Job[]): Promise<void>;
|
|
501
538
|
/** After commit: run them, or hand them to a queue. A throw is reported to `onError`. */
|
|
@@ -504,6 +541,10 @@ export interface JobsAdapter {
|
|
|
504
541
|
sweep?(runner: Runner, options?: { limit?: number }): Promise<SweepResult>;
|
|
505
542
|
/** Put a failed job back in line. `false` when there's no failed job with that id. Only adapters that store them. */
|
|
506
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>;
|
|
507
548
|
/**
|
|
508
549
|
* Keep a job that failed for good after it left the adapter: `registry.jobs.run` calls it from a queue consumer, so
|
|
509
550
|
* `outbox` stores the failure Cloudflare would otherwise drop. Not called for jobs the adapter ran itself.
|
|
@@ -525,6 +566,93 @@ export interface FailureInfo {
|
|
|
525
566
|
outcome?: "retry" | "failed" | "discarded";
|
|
526
567
|
}
|
|
527
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
|
+
|
|
528
656
|
/**
|
|
529
657
|
* Who a job runs as, at rest. `store` picks what's saved with the job (ids, not whole objects); `load` rebuilds the
|
|
530
658
|
* scope when it runs, so policies see today's roles. `load` returning null discards the job (reported to `onError`),
|
|
@@ -549,6 +677,11 @@ export interface InProcess extends JobsAdapter {
|
|
|
549
677
|
* checked at startup: requiring it here would report a missing one as a wrong `store`.
|
|
550
678
|
*/
|
|
551
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;
|
|
552
685
|
/**
|
|
553
686
|
* Max chain of listener → mutation → event → listener… before queueing stops, reported. Calls `ctx.schedule` runs
|
|
554
687
|
* right away count too, so a function that schedules itself with no delay stops the same way. Default 8 (real chains
|
|
@@ -557,13 +690,13 @@ export type JobsOptions<S = object, T = any> = {
|
|
|
557
690
|
maxEventDepth?: number;
|
|
558
691
|
} & (
|
|
559
692
|
| {
|
|
560
|
-
/** `inProcess()` (default), or a durable one like `databaseQueue(
|
|
693
|
+
/** `inProcess()` (default), or a durable one like `databaseQueue()`. Its own options go in its factory. */
|
|
561
694
|
adapter?: InProcess;
|
|
562
695
|
/** Applied by the registry in every adapter, `inProcess()` and tests included. */
|
|
563
696
|
scope?: JobScope<S, T>;
|
|
564
697
|
}
|
|
565
698
|
| {
|
|
566
|
-
/** An adapter that keeps jobs to run later, like `databaseQueue(
|
|
699
|
+
/** An adapter that keeps jobs to run later, like `databaseQueue()`. */
|
|
567
700
|
adapter?: JobsAdapter;
|
|
568
701
|
/** Required: such a job runs as the scope `load` rebuilds, with today's roles. */
|
|
569
702
|
scope: JobScope<S, T>;
|
|
@@ -573,6 +706,8 @@ export type JobsOptions<S = object, T = any> = {
|
|
|
573
706
|
export interface Call<M = unknown> {
|
|
574
707
|
id: string;
|
|
575
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 };
|
|
576
711
|
/** The function's, listener's or cron's `meta` (undefined when it has none). */
|
|
577
712
|
meta: M | undefined;
|
|
578
713
|
/** Raw input as received (before validation). */
|
|
@@ -584,11 +719,12 @@ export interface Call<M = unknown> {
|
|
|
584
719
|
export interface RegistryOptions<Mods extends Record<string, object>> {
|
|
585
720
|
/** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
|
|
586
721
|
modules: Mods;
|
|
587
|
-
database
|
|
722
|
+
/** `database: { adapter: drizzleAdapter(db) }`, with `transactionAttempts` when 3 isn't right. */
|
|
723
|
+
database?: DatabaseOptions;
|
|
588
724
|
services?: object;
|
|
589
725
|
/** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
|
|
590
726
|
config?: object;
|
|
591
|
-
/** Background work: `jobs: { adapter: databaseQueue(
|
|
727
|
+
/** Background work: `jobs: { adapter: databaseQueue(), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
|
|
592
728
|
jobs?: JobsOptions;
|
|
593
729
|
/** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
|
|
594
730
|
wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
|
|
@@ -628,6 +764,8 @@ export interface Overrides {
|
|
|
628
764
|
/** Merged over the registry's config, section by section. */
|
|
629
765
|
config?: unknown;
|
|
630
766
|
adapter?: JobsAdapter;
|
|
767
|
+
/** Where failed jobs go instead of `jobs.failed`; `null` keeps none (a test registry: failures throw). */
|
|
768
|
+
failed?: FailedJobs | null;
|
|
631
769
|
now?: () => Date;
|
|
632
770
|
stubs?: Map<Fn, (ctx: never, input: never) => Promise<unknown>>;
|
|
633
771
|
record?: (envelope: Envelope) => void;
|
|
@@ -647,7 +785,10 @@ export interface RegisteredCron extends Registered {
|
|
|
647
785
|
cron: Cron;
|
|
648
786
|
}
|
|
649
787
|
|
|
650
|
-
/**
|
|
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
|
+
*/
|
|
651
792
|
export interface Jobs {
|
|
652
793
|
/**
|
|
653
794
|
* Run one stored job (queue consumers): `await registry.jobs.run(message.body, { attempt: message.attempts })`.
|
|
@@ -662,7 +803,7 @@ export interface Jobs {
|
|
|
662
803
|
*/
|
|
663
804
|
tick(at?: Date): Promise<string[]>;
|
|
664
805
|
/**
|
|
665
|
-
* Run what your adapter has due, from a cron or an interval: `await registry.jobs.sweep()`. With `databaseQueue(
|
|
806
|
+
* Run what your adapter has due, from a cron or an interval: `await registry.jobs.sweep()`. With `databaseQueue()`, that's
|
|
666
807
|
* retries whose backoff is over and jobs whose runner crashed. Adapters that keep nothing, or maintain themselves
|
|
667
808
|
* (pg-boss), resolve zeros.
|
|
668
809
|
*/
|
|
@@ -672,6 +813,23 @@ export interface Jobs {
|
|
|
672
813
|
* running, done, or never existed). Throws when your adapter keeps no jobs, like `inProcess()`.
|
|
673
814
|
*/
|
|
674
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>;
|
|
675
833
|
}
|
|
676
834
|
|
|
677
835
|
/** What `createRegistry` returns. `Cf` is your config's type, so tests can override parts of it. */
|
|
@@ -692,7 +850,6 @@ export interface Registry<S extends object = object, Mods extends Record<string,
|
|
|
692
850
|
/** @internal used by `logic-sdk/testing` */
|
|
693
851
|
readonly [INTERNAL]: {
|
|
694
852
|
options: RegistryOptions<Mods>;
|
|
695
|
-
config: Frozen<Cf>;
|
|
696
853
|
derive(more: Overrides): Registry<S, Mods, Cf>;
|
|
697
854
|
/** An event as `emit` would make it, for `t.jobs.perform`. */
|
|
698
855
|
envelope(event: EventDef, payload: unknown, scope: S): Envelope;
|
package/src/drizzle/pg.ts
CHANGED
|
@@ -1,110 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
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";
|