logic-sdk 0.7.2 → 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.
- package/README.md +2 -3
- package/dist/adapters/cloudflare-queue.d.ts +3 -2
- package/dist/adapters/cloudflare-queue.js +14 -4
- package/dist/adapters/drizzle-pg.d.ts +31 -1
- package/dist/adapters/drizzle-pg.js +14 -5
- package/dist/adapters/drizzle-sqlite.d.ts +17 -1
- package/dist/adapters/drizzle-sqlite.js +11 -4
- package/dist/adapters/postgres.d.ts +9 -8
- package/dist/adapters/postgres.js +43 -19
- package/dist/adapters/sqlite.d.ts +1 -1
- package/dist/adapters/sqlite.js +32 -12
- package/dist/adapters/stored-jobs.d.ts +27 -19
- package/dist/adapters/stored-jobs.js +157 -61
- package/dist/core/in-process.js +23 -3
- package/dist/core/jobs.d.ts +12 -6
- package/dist/core/jobs.js +158 -17
- package/dist/core/registry.d.ts +39 -3
- package/dist/core/registry.js +23 -11
- package/dist/core/testing.js +3 -1
- package/dist/core/types.d.ts +96 -34
- package/dist/hosts/cloudflare.d.ts +5 -4
- package/dist/hosts/cloudflare.js +5 -4
- package/dist/hosts/node.d.ts +25 -15
- package/dist/hosts/node.js +61 -34
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +1 -1
- package/package.json +1 -11
- package/skills/logic-sdk/SKILL.md +4 -4
- package/src/adapters/cloudflare-queue.ts +13 -4
- package/src/adapters/drizzle-pg.ts +14 -5
- package/src/adapters/drizzle-sqlite.ts +11 -4
- package/src/adapters/postgres.ts +43 -19
- package/src/adapters/sqlite.ts +32 -12
- package/src/adapters/stored-jobs.ts +174 -74
- package/src/core/in-process.ts +22 -2
- package/src/core/jobs.ts +146 -19
- package/src/core/registry.ts +62 -14
- package/src/core/testing.ts +3 -1
- package/src/core/types.ts +93 -30
- package/src/hosts/cloudflare.ts +5 -4
- package/src/hosts/node.ts +73 -46
- package/src/index.ts +3 -1
- package/src/node.ts +1 -1
- package/dist/adapters/pg-boss.d.ts +0 -45
- package/dist/adapters/pg-boss.js +0 -180
- package/dist/hosts/pg-boss.d.ts +0 -22
- package/dist/hosts/pg-boss.js +0 -55
- package/dist/pg-boss.d.ts +0 -2
- package/dist/pg-boss.js +0 -2
- package/src/adapters/pg-boss.ts +0 -195
- package/src/hosts/pg-boss.ts +0 -71
- package/src/pg-boss.ts +0 -2
package/dist/core/types.d.ts
CHANGED
|
@@ -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
|
|
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
|
|
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,6 +197,8 @@ 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
203
|
/** A function `ctx.schedule` asked to run later: `id` is `<function id>@<uuid>`. */
|
|
196
204
|
export interface CallJob {
|
|
@@ -212,6 +220,8 @@ export interface CallJob {
|
|
|
212
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 {
|
|
@@ -279,8 +293,18 @@ export interface Listener<O = unknown, C extends Config = any> extends FromInit<
|
|
|
279
293
|
readonly delay?: number;
|
|
280
294
|
/** Whether this event gets a job for this listener, from the parsed payload, at commit. Default: every event. */
|
|
281
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;
|
|
282
304
|
readonly meta?: Readonly<Record<string, unknown>>;
|
|
283
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>;
|
|
284
308
|
}
|
|
285
309
|
/** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
|
|
286
310
|
export interface RunOptions<S = object> {
|
|
@@ -362,6 +386,8 @@ export type ScheduleOptions<S = object> = ({
|
|
|
362
386
|
attempts?: number;
|
|
363
387
|
/** `true`: the call to this function waiting with the same input (not started yet) is replaced by this one. */
|
|
364
388
|
replace?: true;
|
|
389
|
+
/** Its queue, one of `jobs.queues`. Default `"default"`. */
|
|
390
|
+
queue?: string;
|
|
365
391
|
/**
|
|
366
392
|
* Who it runs as, whole, never merged, as `ctx.run` takes it: `{ scope: { kind: "system", job: "tasks.wake", organization } }`.
|
|
367
393
|
* Default: this mutation's scope. The function's policy checks it when it runs.
|
|
@@ -372,7 +398,7 @@ export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C,
|
|
|
372
398
|
services: ServicesOf<C>;
|
|
373
399
|
/** Call any function: `await ctx.run(bookings.confirmPaid, { bookingId })`. Each mutation you run commits on its own. */
|
|
374
400
|
run: Run<Kind, ScopeOf<C>>;
|
|
375
|
-
/** The caller's abort signal: pass it on, `fetch(url, { signal: ctx.signal })`.
|
|
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). */
|
|
376
402
|
signal: AbortSignal | undefined;
|
|
377
403
|
}
|
|
378
404
|
export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
|
|
@@ -435,7 +461,7 @@ export interface DatabaseAdapter<Db = unknown, Tx = Db> {
|
|
|
435
461
|
/** Did this transaction lose a race the database says to retry (deadlock, serialization failure)? */
|
|
436
462
|
retryable?(error: unknown): boolean;
|
|
437
463
|
}
|
|
438
|
-
/** A database adapter that runs SQL: what `databaseQueue()
|
|
464
|
+
/** A database adapter that runs SQL: what `databaseQueue()` and `outbox(queue)` need. */
|
|
439
465
|
export interface SqlDatabase<Db = any, Tx = any> extends DatabaseAdapter<Db, Tx> {
|
|
440
466
|
/**
|
|
441
467
|
* One SQL statement (`$1` parameters on Postgres, `?` on SQLite), on the database or on a transaction of it. Resolves
|
|
@@ -457,10 +483,7 @@ export type RunJob = (job: Job, options?: RunJobOptions) => Promise<JobOutcome>;
|
|
|
457
483
|
export interface RunJobOptions {
|
|
458
484
|
/** 1 on the first try; the adapter counts. */
|
|
459
485
|
attempt?: number;
|
|
460
|
-
/**
|
|
461
|
-
* Called with the error when the job fails for good, before `run` resolves `"failed"`: keep it. Default: the adapter's
|
|
462
|
-
* `fail` (`databaseQueue` and `outbox` write a failed row).
|
|
463
|
-
*/
|
|
486
|
+
/** Called with the error when the job fails for good, before `run` resolves `"failed"`: keep it (a failed row). */
|
|
464
487
|
fail?: (error: unknown) => Promise<void>;
|
|
465
488
|
}
|
|
466
489
|
/** What a sweep did: done, failed for good, discarded (`jobs.scope.load` returned null), or put back with a backoff. */
|
|
@@ -484,6 +507,11 @@ export interface JobsAdapter {
|
|
|
484
507
|
* `createRegistry` refuses `attempts` above 1 rather than ignore them, as it refuses a delay it can't hold.
|
|
485
508
|
*/
|
|
486
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;
|
|
487
515
|
/**
|
|
488
516
|
* It writes jobs with SQL in the mutation's transaction, through the registry's database: `createRegistry` refuses a
|
|
489
517
|
* registry whose `database.adapter` doesn't run SQL (`query`), and `connect` gets it as `setup.sql`.
|
|
@@ -498,11 +526,17 @@ export interface JobsAdapter {
|
|
|
498
526
|
max: number;
|
|
499
527
|
};
|
|
500
528
|
/**
|
|
501
|
-
* Can
|
|
502
|
-
* (`
|
|
503
|
-
* has the message can't. 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.
|
|
504
533
|
*/
|
|
505
534
|
replaces?: true;
|
|
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[];
|
|
506
540
|
/**
|
|
507
541
|
* At `createRegistry`, once: take what the adapter needs from the registry (its database, for an adapter that writes
|
|
508
542
|
* jobs in the mutation's transaction), and refuse a setup it can't honour.
|
|
@@ -513,9 +547,7 @@ export interface JobsAdapter {
|
|
|
513
547
|
/** After commit: run them, or hand them to a queue. A throw is reported to `onError`. */
|
|
514
548
|
deliver(jobs: Job[], runner: Runner): Promise<void>;
|
|
515
549
|
/** Run what's due (retries, deliveries whose runner crashed). Only adapters that store deliveries have it. */
|
|
516
|
-
sweep?(runner: Runner, options?:
|
|
517
|
-
limit?: number;
|
|
518
|
-
}): Promise<SweepResult>;
|
|
550
|
+
sweep?(runner: Runner, options?: SweepOptions): Promise<SweepResult>;
|
|
519
551
|
/** Put a failed job back in line. `false` when there's no failed job with that id. Only adapters that store them. */
|
|
520
552
|
retry?(id: string): Promise<boolean>;
|
|
521
553
|
/** A page of failed jobs, newest first. Only adapters that store them and can filter them. */
|
|
@@ -526,10 +558,11 @@ export interface JobsAdapter {
|
|
|
526
558
|
/** Delete one failed job. `false` when there's no failed job with that id: a waiting or running one is never touched. */
|
|
527
559
|
forget?(id: string): Promise<boolean>;
|
|
528
560
|
/**
|
|
529
|
-
*
|
|
530
|
-
*
|
|
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.
|
|
531
564
|
*/
|
|
532
|
-
|
|
565
|
+
consume?(job: Job, runner: Runner): Promise<void>;
|
|
533
566
|
}
|
|
534
567
|
/**
|
|
535
568
|
* What `onError` gets with a failure after commit. `job`, `attempt` and `outcome` are set when a job failed: the job
|
|
@@ -546,12 +579,30 @@ export interface FailureInfo {
|
|
|
546
579
|
}
|
|
547
580
|
/** What `createRegistry` gives an adapter's `connect`. */
|
|
548
581
|
export interface AdapterSetup {
|
|
549
|
-
|
|
550
|
-
crons: readonly RegisteredCron[];
|
|
551
|
-
/** The registry's `database.adapter`. */
|
|
552
|
-
database: DatabaseAdapter<unknown, unknown> | undefined;
|
|
553
|
-
/** The same, when it runs SQL: always set for an adapter that declares `sql: true`. */
|
|
582
|
+
/** The registry's `database.adapter`, when it runs SQL: always set for an adapter that declares `sql: true`. */
|
|
554
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[];
|
|
555
606
|
}
|
|
556
607
|
/**
|
|
557
608
|
* A store for failed jobs, apart from the queue that runs them, like Laravel's `failed` driver. `failedJobs()`
|
|
@@ -664,6 +715,12 @@ export type JobsOptions<S = object, T = any> = {
|
|
|
664
715
|
* are 2 or 3).
|
|
665
716
|
*/
|
|
666
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[];
|
|
667
724
|
} & ({
|
|
668
725
|
/** `inProcess()` (default), or a durable one like `databaseQueue()`. Its own options go in its factory. */
|
|
669
726
|
adapter?: InProcess;
|
|
@@ -705,9 +762,8 @@ export interface RegistryOptions<Mods extends Record<string, object>> {
|
|
|
705
762
|
/**
|
|
706
763
|
* Serverless: let listeners finish after the response. Pass the platform's global:
|
|
707
764
|
* `import { waitUntil } from "cloudflare:workers"` or `import { waitUntil } from "@vercel/functions"`.
|
|
708
|
-
* Without it, `run` waits for listeners
|
|
709
|
-
*
|
|
710
|
-
* 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.
|
|
711
767
|
*/
|
|
712
768
|
waitUntil?: (promise: Promise<unknown>) => void;
|
|
713
769
|
/** Failures no caller waits for: jobs, and the work after commit that runs them. They never fail the caller. */
|
|
@@ -760,11 +816,14 @@ export interface RegisteredCron extends Registered {
|
|
|
760
816
|
*/
|
|
761
817
|
export interface Jobs {
|
|
762
818
|
/**
|
|
763
|
-
* Run one
|
|
819
|
+
* Run one job from a queue message (consumers): `await registry.jobs.run(message.body, { attempt: message.attempts })`.
|
|
764
820
|
* Resolves `"done"`, `"failed"` or `"discarded"` (acknowledge all three); throws when a retry might help and the
|
|
765
|
-
* job has tries left. A `failed` job
|
|
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"`.
|
|
766
823
|
*/
|
|
767
|
-
run(job: Job, options?:
|
|
824
|
+
run(job: Job, options?: {
|
|
825
|
+
attempt?: number;
|
|
826
|
+
}): Promise<JobOutcome>;
|
|
768
827
|
/**
|
|
769
828
|
* Run the crons due in `at`'s minute (default now), from a timer or your platform's cron trigger:
|
|
770
829
|
* `await registry.jobs.tick(new Date(controller.scheduledTime))`. Resolves the ids of the crons that were due. Each run
|
|
@@ -773,12 +832,15 @@ export interface Jobs {
|
|
|
773
832
|
tick(at?: Date): Promise<string[]>;
|
|
774
833
|
/**
|
|
775
834
|
* Run what your adapter has due, from a cron or an interval: `await registry.jobs.sweep()`. With `databaseQueue()`, that's
|
|
776
|
-
* retries whose backoff is over and jobs whose runner crashed. Adapters that keep nothing
|
|
777
|
-
|
|
835
|
+
* retries whose backoff is over and jobs whose runner crashed. Adapters that keep nothing resolve zeros.
|
|
836
|
+
*/
|
|
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.
|
|
778
842
|
*/
|
|
779
|
-
|
|
780
|
-
limit?: number;
|
|
781
|
-
}): Promise<SweepResult>;
|
|
843
|
+
attach(worker: LocalWorker): () => void;
|
|
782
844
|
/**
|
|
783
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,
|
|
784
846
|
* running, done, or never existed). Throws when your adapter keeps no jobs, like `inProcess()`.
|
|
@@ -787,7 +849,7 @@ export interface Jobs {
|
|
|
787
849
|
/**
|
|
788
850
|
* Failed jobs, newest first, a page at a time: `await registry.jobs.failed({ source: "emails.send", scope: { organizationId } })`.
|
|
789
851
|
* Then `retry` or `forget` each. Pass your stored scope's type to check the filter: `failed<Stored>({ scope })`. Throws
|
|
790
|
-
* when your adapter keeps none (a queue alone without `jobs.failed`)
|
|
852
|
+
* when your adapter keeps none (a queue alone without `jobs.failed`).
|
|
791
853
|
*/
|
|
792
854
|
failed<Stored = Record<string, unknown>>(options?: FailedOptions<Stored>): Promise<FailedPage<Stored>>;
|
|
793
855
|
/**
|
|
@@ -12,8 +12,9 @@ export interface QueueBatch {
|
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
14
|
* Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
|
|
15
|
-
* retries it with a backoff (it threw
|
|
16
|
-
*
|
|
15
|
+
* retries it with a backoff (it threw). One message at a time, each acknowledged on its own, so one failure doesn't
|
|
16
|
+
* redeliver the batch. Alone, a throw means the listener has tries left. Behind an outbox, a message is a signal: the
|
|
17
|
+
* job runs from its row (with a `key`, the key's next jobs, in order), and a throw means the table couldn't be reached.
|
|
17
18
|
*
|
|
18
19
|
* ```ts
|
|
19
20
|
* async queue(batch, env, ctx) {
|
|
@@ -25,8 +26,8 @@ export declare function handleQueue(registry: {
|
|
|
25
26
|
jobs: Pick<Jobs, "run">;
|
|
26
27
|
}, batch: QueueBatch): Promise<void>;
|
|
27
28
|
/**
|
|
28
|
-
* Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (
|
|
29
|
-
* delayed jobs, and
|
|
29
|
+
* Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (the jobs table's retries,
|
|
30
|
+
* delayed jobs, and what a lost signal or a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
|
|
30
31
|
* 1 = Sunday, so write them as names (`MON`) in both places.
|
|
31
32
|
*
|
|
32
33
|
* ```ts
|
package/dist/hosts/cloudflare.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { defaultBackoff } from "../core/jobs.js";
|
|
2
2
|
/**
|
|
3
3
|
* Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
|
|
4
|
-
* retries it with a backoff (it threw
|
|
5
|
-
*
|
|
4
|
+
* retries it with a backoff (it threw). One message at a time, each acknowledged on its own, so one failure doesn't
|
|
5
|
+
* redeliver the batch. Alone, a throw means the listener has tries left. Behind an outbox, a message is a signal: the
|
|
6
|
+
* job runs from its row (with a `key`, the key's next jobs, in order), and a throw means the table couldn't be reached.
|
|
6
7
|
*
|
|
7
8
|
* ```ts
|
|
8
9
|
* async queue(batch, env, ctx) {
|
|
@@ -23,8 +24,8 @@ export async function handleQueue(registry, batch) {
|
|
|
23
24
|
}
|
|
24
25
|
}
|
|
25
26
|
/**
|
|
26
|
-
* Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (
|
|
27
|
-
* delayed jobs, and
|
|
27
|
+
* Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (the jobs table's retries,
|
|
28
|
+
* delayed jobs, and what a lost signal or a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
|
|
28
29
|
* 1 = Sunday, so write them as names (`MON`) in both places.
|
|
29
30
|
*
|
|
30
31
|
* ```ts
|
package/dist/hosts/node.d.ts
CHANGED
|
@@ -1,26 +1,36 @@
|
|
|
1
1
|
import type { Jobs } from "../core/types.ts";
|
|
2
|
-
export interface
|
|
3
|
-
/**
|
|
4
|
-
|
|
5
|
-
/**
|
|
2
|
+
export interface WorkOptions {
|
|
3
|
+
/** Jobs this process runs at once. Default 1, like pg-boss, graphile-worker and a Laravel worker: run more processes, or raise it. */
|
|
4
|
+
concurrency?: number;
|
|
5
|
+
/** Seconds a free slot waits before it looks for a job again, when there was none. Default 2, like pg-boss and graphile-worker. */
|
|
6
|
+
pollEvery?: number;
|
|
7
|
+
/**
|
|
8
|
+
* The queues it runs, in order: each claim takes the first one with a job due, so `["mail", "default"]` sends mail
|
|
9
|
+
* first. Each one of `jobs.queues`, or `"default"`. Default: every queue, oldest due first.
|
|
10
|
+
*/
|
|
11
|
+
queues?: readonly string[];
|
|
12
|
+
/** Where a failed tick or claim goes, and a skipped minute. Default `console.error`. */
|
|
6
13
|
onError?: (error: unknown) => void;
|
|
7
14
|
}
|
|
8
15
|
export interface StopOptions {
|
|
9
|
-
/** Seconds to wait for the running
|
|
16
|
+
/** Seconds to wait for the running jobs and ticks before giving up on them. Default 30, like pg-boss's `stop()`. */
|
|
10
17
|
timeout?: number;
|
|
11
18
|
}
|
|
12
19
|
/**
|
|
13
|
-
* A
|
|
14
|
-
*
|
|
15
|
-
* minute
|
|
16
|
-
*
|
|
20
|
+
* A worker, like Laravel's `queue:work` and `schedule:work` in one process: `concurrency` slots, each claiming the next
|
|
21
|
+
* due job (`registry.jobs.sweep({ limit: 1 })`) and waiting `pollEvery` seconds when there's none, and your crons
|
|
22
|
+
* ticked on every minute. Run as many as you like: a job is claimed once, and a cron's minute runs once. A minute the
|
|
23
|
+
* process wasn't running for is skipped, not caught up. In the web process, it takes the jobs requests commit, so they
|
|
24
|
+
* answer at once and it starts them right away; in a process of its own, it claims what's due, `pollEvery` seconds
|
|
25
|
+
* apart when there's nothing (with `databaseQueue({ runIn: "worker" })` that's every job). Returns `stop()`, which
|
|
26
|
+
* waits for the running jobs and ticks, `timeout` seconds at most.
|
|
17
27
|
*
|
|
18
28
|
* ```ts
|
|
19
|
-
* import {
|
|
20
|
-
* const stop =
|
|
21
|
-
* process.on("SIGTERM", async () => { await stop(); process.exit(0); });
|
|
29
|
+
* import { work } from "logic-sdk/node";
|
|
30
|
+
* const stop = work(registry, { concurrency: 5 });
|
|
31
|
+
* process.on("SIGTERM", async () => { await stop(); process.exit(0); });
|
|
22
32
|
* ```
|
|
23
33
|
*/
|
|
24
|
-
export declare function
|
|
25
|
-
jobs: Pick<Jobs, "tick" | "sweep">;
|
|
26
|
-
}, options?:
|
|
34
|
+
export declare function work(registry: {
|
|
35
|
+
jobs: Pick<Jobs, "tick" | "sweep" | "attach">;
|
|
36
|
+
}, options?: WorkOptions): (options?: StopOptions) => Promise<void>;
|
package/dist/hosts/node.js
CHANGED
|
@@ -1,25 +1,29 @@
|
|
|
1
1
|
const MINUTE = 60_000;
|
|
2
2
|
/**
|
|
3
|
-
* Ticks
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* up would run a backlog of stale minutes when it comes back.
|
|
3
|
+
* Ticks still running before the next is skipped (reported). Overlap is normal, like Laravel and Oban: a slow cron
|
|
4
|
+
* doesn't hold back the next minute. Ten still running means they're stuck (the database is unreachable), and letting
|
|
5
|
+
* them pile up would run a backlog of stale minutes when it comes back.
|
|
7
6
|
*/
|
|
8
7
|
const MAX_RUNNING = 10;
|
|
8
|
+
/** The longest a slot waits between claims while they throw (the database is down), so an outage is reported less and less often. */
|
|
9
|
+
const MAX_WAIT = 30;
|
|
9
10
|
/**
|
|
10
|
-
* A
|
|
11
|
-
*
|
|
12
|
-
* minute
|
|
13
|
-
*
|
|
11
|
+
* A worker, like Laravel's `queue:work` and `schedule:work` in one process: `concurrency` slots, each claiming the next
|
|
12
|
+
* due job (`registry.jobs.sweep({ limit: 1 })`) and waiting `pollEvery` seconds when there's none, and your crons
|
|
13
|
+
* ticked on every minute. Run as many as you like: a job is claimed once, and a cron's minute runs once. A minute the
|
|
14
|
+
* process wasn't running for is skipped, not caught up. In the web process, it takes the jobs requests commit, so they
|
|
15
|
+
* answer at once and it starts them right away; in a process of its own, it claims what's due, `pollEvery` seconds
|
|
16
|
+
* apart when there's nothing (with `databaseQueue({ runIn: "worker" })` that's every job). Returns `stop()`, which
|
|
17
|
+
* waits for the running jobs and ticks, `timeout` seconds at most.
|
|
14
18
|
*
|
|
15
19
|
* ```ts
|
|
16
|
-
* import {
|
|
17
|
-
* const stop =
|
|
18
|
-
* process.on("SIGTERM", async () => { await stop(); process.exit(0); });
|
|
20
|
+
* import { work } from "logic-sdk/node";
|
|
21
|
+
* const stop = work(registry, { concurrency: 5 });
|
|
22
|
+
* process.on("SIGTERM", async () => { await stop(); process.exit(0); });
|
|
19
23
|
* ```
|
|
20
24
|
*/
|
|
21
|
-
export function
|
|
22
|
-
const
|
|
25
|
+
export function work(registry, options = {}) {
|
|
26
|
+
const { concurrency = 1, pollEvery = 2, queues } = options;
|
|
23
27
|
const reportTo = options.onError ?? ((error) => console.error("[logic-sdk]", error));
|
|
24
28
|
const onError = (error) => {
|
|
25
29
|
try {
|
|
@@ -29,22 +33,51 @@ export function startTicking(registry, options = {}) {
|
|
|
29
33
|
console.error("[logic-sdk] onError threw", inner, "while reporting", error); // like the registry's: the loops keep going
|
|
30
34
|
}
|
|
31
35
|
};
|
|
32
|
-
let
|
|
33
|
-
|
|
36
|
+
let stopping = false;
|
|
37
|
+
/** The sleeping slots: a commit wakes as many as it has jobs, `stop()` all of them. */
|
|
38
|
+
const wakes = new Set();
|
|
39
|
+
const wakeUp = (count = Infinity) => {
|
|
40
|
+
for (const wake of [...wakes].slice(0, count))
|
|
41
|
+
wake();
|
|
42
|
+
};
|
|
43
|
+
/** Resolves after `seconds`, or at once on `stop()`. */
|
|
44
|
+
const sleep = (seconds) => new Promise((resolve) => {
|
|
45
|
+
const wake = () => {
|
|
46
|
+
clearTimeout(timer);
|
|
47
|
+
wakes.delete(wake);
|
|
48
|
+
resolve();
|
|
49
|
+
};
|
|
50
|
+
const timer = setTimeout(wake, seconds * 1000);
|
|
51
|
+
wakes.add(wake);
|
|
52
|
+
});
|
|
53
|
+
/** One job at a time: the next due one, back to back while there are some. */
|
|
54
|
+
async function slot() {
|
|
55
|
+
let wait = pollEvery;
|
|
56
|
+
while (!stopping) {
|
|
57
|
+
try {
|
|
58
|
+
const { done, failed, discarded, retrying } = await registry.jobs.sweep({ limit: 1, queues });
|
|
59
|
+
wait = pollEvery;
|
|
60
|
+
if (done + failed + discarded + retrying)
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
onError(error);
|
|
65
|
+
wait = Math.min(wait * 2, MAX_WAIT);
|
|
66
|
+
}
|
|
67
|
+
await sleep(wait);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
34
70
|
const ticks = new Set();
|
|
35
|
-
|
|
71
|
+
let tickTimer;
|
|
36
72
|
const startOfMinute = (ms) => Math.floor(ms / MINUTE) * MINUTE;
|
|
37
|
-
const track = (running, work) => {
|
|
38
|
-
const run = work.then(() => { }, onError);
|
|
39
|
-
running.add(run);
|
|
40
|
-
void run.finally(() => running.delete(run));
|
|
41
|
-
};
|
|
42
73
|
const tick = (at) => {
|
|
43
74
|
if (ticks.size >= MAX_RUNNING) {
|
|
44
75
|
onError(new Error(`[logic-sdk] skipped the ${at.toISOString()} tick: ${ticks.size} earlier ticks are still running. Is the database reachable?`));
|
|
45
76
|
return;
|
|
46
77
|
}
|
|
47
|
-
|
|
78
|
+
const run = registry.jobs.tick(at).then(() => { }, onError);
|
|
79
|
+
ticks.add(run);
|
|
80
|
+
void run.finally(() => ticks.delete(run));
|
|
48
81
|
};
|
|
49
82
|
const armTick = (minute) => {
|
|
50
83
|
tickTimer = setTimeout(() => {
|
|
@@ -54,23 +87,17 @@ export function startTicking(registry, options = {}) {
|
|
|
54
87
|
tick(new Date(due));
|
|
55
88
|
}, minute - Date.now());
|
|
56
89
|
};
|
|
57
|
-
const
|
|
58
|
-
sweepTimer = setTimeout(sweep, sweepEvery * 1000); // the next one first, so a hung job can't stop the sweeps
|
|
59
|
-
if (sweeps.size >= MAX_RUNNING) {
|
|
60
|
-
onError(new Error(`[logic-sdk] skipped a sweep: ${sweeps.size} earlier sweeps are still running. Is a job hung, or the database unreachable?`));
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
track(sweeps, registry.jobs.sweep());
|
|
64
|
-
};
|
|
90
|
+
const detach = registry.jobs.attach({ wake: wakeUp, queues }); // first: it throws on a queue jobs.queues doesn't declare
|
|
65
91
|
armTick(startOfMinute(Date.now()) + MINUTE);
|
|
66
|
-
|
|
67
|
-
sweepTimer = setTimeout(sweep, sweepEvery * 1000);
|
|
92
|
+
const slots = Array.from({ length: concurrency }, slot);
|
|
68
93
|
return async ({ timeout = 30 } = {}) => {
|
|
94
|
+
stopping = true;
|
|
95
|
+
detach(); // requests run their own jobs again
|
|
69
96
|
clearTimeout(tickTimer);
|
|
70
|
-
|
|
97
|
+
wakeUp();
|
|
71
98
|
let timer;
|
|
72
99
|
const gaveUp = new Promise((resolve) => (timer = setTimeout(resolve, timeout * 1000)));
|
|
73
|
-
await Promise.race([Promise.all([...
|
|
100
|
+
await Promise.race([Promise.all([...slots, ...ticks]), gaveUp]);
|
|
74
101
|
clearTimeout(timer);
|
|
75
102
|
};
|
|
76
103
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export type { ActionCtx, AdapterSetup, Call, CallJob, Caller, Config, Constructor, Cron, CronCtx, CronRun, CronJob, DatabaseAdapter, DatabaseOptions, DeepPartial, Delivery, EmittedEvent, Envelope, Errors, EventDef, FailedJob, FailedJobs, FailedOptions, FailedPage, FailedQuery, FailedRow, FailureInfo, Fn, FnIn, FnOut, ForFunctions, ForListeners, Frozen, In, InProcess, Job, JobOutcome, JobsAdapter, JobScope, Jobs, JobsOptions, Kind, Listener, ListenerCtx, ListenerEvent, MutationCtx, Out, Policy, PublishableFn, ScopeOfFn, QueryCtx, ReadWrite, Registered, RegisteredCron, RegisteredEvent, RegisteredFn, RegisteredListener, Registry, RegistryOptions, RunArgs, RunJob, RunJobOptions, RunOptions, Runner, ScheduleOptions, Schema, ScopeMatch, SqlDatabase, SweepResult, } from "./core/types.ts";
|
|
1
|
+
export type { ActionCtx, AdapterSetup, LocalWorker, Call, CallJob, Caller, Config, Constructor, Cron, CronCtx, CronRun, CronJob, DatabaseAdapter, DatabaseOptions, DeepPartial, Delivery, EmittedEvent, Envelope, Errors, EventDef, FailedJob, FailedJobs, FailedOptions, FailedPage, FailedQuery, FailedRow, FailureInfo, Fn, FnIn, FnOut, ForFunctions, ForListeners, Frozen, In, InProcess, Job, JobOutcome, JobsAdapter, JobScope, Jobs, JobsOptions, Kind, Listener, ListenerCtx, ListenerEvent, MutationCtx, Out, Policy, PublishableFn, ScopeOfFn, QueryCtx, ReadWrite, Registered, RegisteredCron, RegisteredEvent, RegisteredFn, RegisteredListener, Registry, RegistryOptions, RunArgs, RunJob, RunJobOptions, RunOptions, Runner, ScheduleOptions, Schema, ScopeMatch, SqlDatabase, SweepOptions, SweepResult, } from "./core/types.ts";
|
|
2
2
|
export { DomainError, isDomainError, unauthenticated, type ErrorKind } from "./core/errors.ts";
|
|
3
3
|
export { inProcess } from "./core/in-process.ts";
|
|
4
|
-
export { defaultBackoff,
|
|
4
|
+
export { defaultBackoff, storedUniqueKey } from "./core/jobs.ts";
|
|
5
5
|
export { createRegistry, describeModules, init } from "./core/registry.ts";
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { DomainError, isDomainError, unauthenticated } from "./core/errors.js";
|
|
2
2
|
export { inProcess } from "./core/in-process.js";
|
|
3
|
-
export { defaultBackoff,
|
|
3
|
+
export { defaultBackoff, storedUniqueKey } from "./core/jobs.js";
|
|
4
4
|
export { createRegistry, describeModules, init } from "./core/registry.js";
|
package/dist/node.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { work, type StopOptions, type WorkOptions } from "./hosts/node.ts";
|
package/dist/node.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { work } from "./hosts/node.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "logic-sdk",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.3",
|
|
4
4
|
"description": "Queries, mutations, actions and events for TypeScript apps. Transactions, after-commit events and scopes, on any runtime.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"actions",
|
|
@@ -12,7 +12,6 @@
|
|
|
12
12
|
"drizzle",
|
|
13
13
|
"events",
|
|
14
14
|
"mutations",
|
|
15
|
-
"pg-boss",
|
|
16
15
|
"queries",
|
|
17
16
|
"tools",
|
|
18
17
|
"transactions",
|
|
@@ -67,10 +66,6 @@
|
|
|
67
66
|
"types": "./dist/cloudflare.d.ts",
|
|
68
67
|
"default": "./dist/cloudflare.js"
|
|
69
68
|
},
|
|
70
|
-
"./pg-boss": {
|
|
71
|
-
"types": "./dist/pg-boss.d.ts",
|
|
72
|
-
"default": "./dist/pg-boss.js"
|
|
73
|
-
},
|
|
74
69
|
"./node": {
|
|
75
70
|
"types": "./dist/node.d.ts",
|
|
76
71
|
"default": "./dist/node.js"
|
|
@@ -111,7 +106,6 @@
|
|
|
111
106
|
"peerDependencies": {
|
|
112
107
|
"@orpc/server": ">=2.0.0-beta.51 <3",
|
|
113
108
|
"drizzle-orm": ">=1.0.0-rc.6 <2",
|
|
114
|
-
"pg-boss": ">=12.39.0 <13",
|
|
115
109
|
"ai": ">=7 <8",
|
|
116
110
|
"@logic-sdk/cli": ">=0.6.6 <0.7.0"
|
|
117
111
|
},
|
|
@@ -122,9 +116,6 @@
|
|
|
122
116
|
"drizzle-orm": {
|
|
123
117
|
"optional": true
|
|
124
118
|
},
|
|
125
|
-
"pg-boss": {
|
|
126
|
-
"optional": true
|
|
127
|
-
},
|
|
128
119
|
"ai": {
|
|
129
120
|
"optional": true
|
|
130
121
|
},
|
|
@@ -139,7 +130,6 @@
|
|
|
139
130
|
"ai": "^7.0.177",
|
|
140
131
|
"croner": "11.0.1",
|
|
141
132
|
"drizzle-orm": "1.0.0-rc.6",
|
|
142
|
-
"pg-boss": "12.39.0",
|
|
143
133
|
"postgres": "^4.1.1",
|
|
144
134
|
"zod": "^4.6.7"
|
|
145
135
|
}
|