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.
Files changed (54) hide show
  1. package/README.md +2 -3
  2. package/dist/adapters/cloudflare-queue.d.ts +3 -2
  3. package/dist/adapters/cloudflare-queue.js +14 -4
  4. package/dist/adapters/drizzle-pg.d.ts +31 -1
  5. package/dist/adapters/drizzle-pg.js +14 -5
  6. package/dist/adapters/drizzle-sqlite.d.ts +17 -1
  7. package/dist/adapters/drizzle-sqlite.js +11 -4
  8. package/dist/adapters/postgres.d.ts +9 -8
  9. package/dist/adapters/postgres.js +43 -19
  10. package/dist/adapters/sqlite.d.ts +1 -1
  11. package/dist/adapters/sqlite.js +32 -12
  12. package/dist/adapters/stored-jobs.d.ts +27 -19
  13. package/dist/adapters/stored-jobs.js +157 -61
  14. package/dist/core/in-process.js +23 -3
  15. package/dist/core/jobs.d.ts +12 -6
  16. package/dist/core/jobs.js +158 -17
  17. package/dist/core/registry.d.ts +39 -3
  18. package/dist/core/registry.js +23 -11
  19. package/dist/core/testing.js +3 -1
  20. package/dist/core/types.d.ts +96 -34
  21. package/dist/hosts/cloudflare.d.ts +5 -4
  22. package/dist/hosts/cloudflare.js +5 -4
  23. package/dist/hosts/node.d.ts +25 -15
  24. package/dist/hosts/node.js +61 -34
  25. package/dist/index.d.ts +2 -2
  26. package/dist/index.js +1 -1
  27. package/dist/node.d.ts +1 -1
  28. package/dist/node.js +1 -1
  29. package/package.json +1 -11
  30. package/skills/logic-sdk/SKILL.md +4 -4
  31. package/src/adapters/cloudflare-queue.ts +13 -4
  32. package/src/adapters/drizzle-pg.ts +14 -5
  33. package/src/adapters/drizzle-sqlite.ts +11 -4
  34. package/src/adapters/postgres.ts +43 -19
  35. package/src/adapters/sqlite.ts +32 -12
  36. package/src/adapters/stored-jobs.ts +174 -74
  37. package/src/core/in-process.ts +22 -2
  38. package/src/core/jobs.ts +146 -19
  39. package/src/core/registry.ts +62 -14
  40. package/src/core/testing.ts +3 -1
  41. package/src/core/types.ts +93 -30
  42. package/src/hosts/cloudflare.ts +5 -4
  43. package/src/hosts/node.ts +73 -46
  44. package/src/index.ts +3 -1
  45. package/src/node.ts +1 -1
  46. package/dist/adapters/pg-boss.d.ts +0 -45
  47. package/dist/adapters/pg-boss.js +0 -180
  48. package/dist/hosts/pg-boss.d.ts +0 -22
  49. package/dist/hosts/pg-boss.js +0 -55
  50. package/dist/pg-boss.d.ts +0 -2
  51. package/dist/pg-boss.js +0 -2
  52. package/src/adapters/pg-boss.ts +0 -195
  53. package/src/hosts/pg-boss.ts +0 -71
  54. package/src/pg-boss.ts +0 -2
package/src/core/types.ts CHANGED
@@ -28,7 +28,7 @@ export interface Config {
28
28
  */
29
29
  config?: object;
30
30
  /**
31
- * The shape of `meta`: yours, plus what your adapters read (`AppMeta & AIMeta & PgBossMeta`). Yours goes on functions
31
+ * The shape of `meta`: yours, plus what your adapters read (`AppMeta & AIMeta`). Yours goes on functions
32
32
  * and listeners, each adapter's only where it reads it.
33
33
  */
34
34
  meta?: object;
@@ -56,7 +56,7 @@ declare const FOR_LISTENERS: unique symbol;
56
56
  export interface ForFunctions<M> {
57
57
  readonly [FOR_FUNCTIONS]?: M;
58
58
  }
59
- /** An adapter's part of `meta`, read on listeners: `type PgBossMeta = ForListeners<{ pgBoss?: ... }>`. */
59
+ /** An adapter's part of `meta`, read on listeners: `type QueueMeta = ForListeners<{ queue?: ... }>`. */
60
60
  export interface ForListeners<M> {
61
61
  readonly [FOR_LISTENERS]?: M;
62
62
  }
@@ -171,6 +171,12 @@ export interface Delivery {
171
171
  attempts: number;
172
172
  /** When it may run (ISO), for a listener with a `delay`. Absent: right away. */
173
173
  runAt?: string;
174
+ /** Its listener's `key`, as `<listener id>@<key>`: jobs with the same one run one at a time, in order. */
175
+ key?: string;
176
+ /** Its listener's `unique`, as `<listener id>@<value>`: a later job with the same one is dropped while this one waits. */
177
+ unique?: string;
178
+ /** Its queue, when it isn't `"default"`: a worker drains its queues in the order it lists them. */
179
+ queue?: string;
174
180
  }
175
181
 
176
182
  /** One run of a cron: `id` is `<cron id>@<minute>` (`reports.weekly@20261123T0900Z`), so a tick runs once. */
@@ -185,6 +191,8 @@ export interface CronJob {
185
191
  attempts: number;
186
192
  /** When it may run (ISO), like a delivery's. Absent for crons: they run when ticked. */
187
193
  runAt?: string;
194
+ /** Its queue, when it isn't `"default"`: a worker drains its queues in the order it lists them. */
195
+ queue?: string;
188
196
  }
189
197
 
190
198
  /** A function `ctx.schedule` asked to run later: `id` is `<function id>@<uuid>`. */
@@ -207,6 +215,8 @@ export interface CallJob {
207
215
  replace?: true;
208
216
  /** When it may run (ISO). */
209
217
  runAt?: string;
218
+ /** Its queue, when it isn't `"default"`: a worker drains its queues in the order it lists them. */
219
+ queue?: string;
210
220
  }
211
221
 
212
222
  /**
@@ -224,8 +234,12 @@ export interface Cron<C extends Config = any> extends FromInit<C> {
224
234
  readonly timezone?: string;
225
235
  readonly scope: object;
226
236
  readonly attempts?: number;
237
+ /** Its queue, one of `jobs.queues`. Default `"default"`. */
238
+ readonly queue?: string;
227
239
  readonly meta?: Readonly<Record<string, unknown>>;
228
240
  readonly handler: (ctx: never) => Promise<unknown>;
241
+ /** Runs once its last try has failed: `(ctx, error)`. */
242
+ readonly failed?: (ctx: never, error: unknown) => Promise<unknown>;
229
243
  }
230
244
 
231
245
  /** The run a cron's handler is doing. No scope here: `ctx.scope` is the one it runs as. */
@@ -281,8 +295,18 @@ export interface Listener<O = unknown, C extends Config = any> extends FromInit<
281
295
  readonly delay?: number;
282
296
  /** Whether this event gets a job for this listener, from the parsed payload, at commit. Default: every event. */
283
297
  readonly when?: (payload: O) => boolean;
298
+ /** Jobs with the same key run one at a time, in the order their events were emitted. */
299
+ readonly key?: (payload: O) => string;
300
+ /** While a job with the same value hasn't started, later ones are dropped. */
301
+ readonly unique?: (payload: O) => string;
302
+ /** Seconds a try may run before it's stopped and counted as failed. */
303
+ readonly timeout?: number;
304
+ /** Its queue, one of `jobs.queues`. Default `"default"`. */
305
+ readonly queue?: string;
284
306
  readonly meta?: Readonly<Record<string, unknown>>;
285
307
  readonly handler: (ctx: never, payload: O) => Promise<unknown>;
308
+ /** Runs once its last try has failed: `(ctx, payload, error)`. */
309
+ readonly failed?: (ctx: never, payload: O, error: unknown) => Promise<unknown>;
286
310
  }
287
311
 
288
312
  /** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
@@ -362,6 +386,8 @@ export type ScheduleOptions<S = object> = ({ at: Date; delay?: never } | { delay
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 })`. Always undefined in listeners (they outlive the request). */
401
+ /** The caller's abort signal: pass it on, `fetch(url, { signal: ctx.signal })`. In a listener, aborted when its `timeout` runs out (else undefined: listeners outlive the request). */
376
402
  signal: AbortSignal | undefined;
377
403
  }
378
404
  export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
@@ -456,7 +482,7 @@ export interface DatabaseAdapter<Db = unknown, Tx = Db> {
456
482
  retryable?(error: unknown): boolean;
457
483
  }
458
484
 
459
- /** A database adapter that runs SQL: what `databaseQueue()`, `outbox(queue)` and `pgBoss(boss)` need. */
485
+ /** A database adapter that runs SQL: what `databaseQueue()` and `outbox(queue)` need. */
460
486
  export interface SqlDatabase<Db = any, Tx = any> extends DatabaseAdapter<Db, Tx> {
461
487
  /**
462
488
  * One SQL statement (`$1` parameters on Postgres, `?` on SQLite), on the database or on a transaction of it. Resolves
@@ -481,10 +507,7 @@ export type RunJob = (job: Job, options?: RunJobOptions) => Promise<JobOutcome>;
481
507
  export interface RunJobOptions {
482
508
  /** 1 on the first try; the adapter counts. */
483
509
  attempt?: number;
484
- /**
485
- * Called with the error when the job fails for good, before `run` resolves `"failed"`: keep it. Default: the adapter's
486
- * `fail` (`databaseQueue` and `outbox` write a failed row).
487
- */
510
+ /** Called with the error when the job fails for good, before `run` resolves `"failed"`: keep it (a failed row). */
488
511
  fail?: (error: unknown) => Promise<void>;
489
512
  }
490
513
 
@@ -511,6 +534,11 @@ export interface JobsAdapter {
511
534
  * `createRegistry` refuses `attempts` above 1 rather than ignore them, as it refuses a delay it can't hold.
512
535
  */
513
536
  retries?: true;
537
+ /**
538
+ * It runs jobs with the same `key` one at a time, in the order they were queued, like an SQS FIFO queue's message
539
+ * groups. Without it, `createRegistry` refuses a listener with a `key`.
540
+ */
541
+ orders?: true;
514
542
  /**
515
543
  * It writes jobs with SQL in the mutation's transaction, through the registry's database: `createRegistry` refuses a
516
544
  * registry whose `database.adapter` doesn't run SQL (`query`), and `connect` gets it as `setup.sql`.
@@ -523,11 +551,17 @@ export interface JobsAdapter {
523
551
  */
524
552
  holds?: true | { max: number };
525
553
  /**
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.
554
+ * Can keep one waiting job per key: `enqueue` gets a call with `replace`, and a pending call with the same key
555
+ * (`storedUniqueKey`) that hasn't started is replaced by it; a delivery with `unique` is dropped while one with the
556
+ * same key waits. A queue that already has the message can't. Without it, `ctx.schedule` with `replace` is refused,
557
+ * and so is `unique` on an adapter that holds jobs.
529
558
  */
530
559
  replaces?: true;
560
+ /**
561
+ * It keeps jobs of different queues apart: any name (`true`), or only these (a queue per binding). Without it,
562
+ * `createRegistry` refuses `jobs.queues`; with a list, a declared queue (or `"default"`) it doesn't have.
563
+ */
564
+ queues?: true | readonly string[];
531
565
  /**
532
566
  * At `createRegistry`, once: take what the adapter needs from the registry (its database, for an adapter that writes
533
567
  * jobs in the mutation's transaction), and refuse a setup it can't honour.
@@ -538,7 +572,7 @@ export interface JobsAdapter {
538
572
  /** After commit: run them, or hand them to a queue. A throw is reported to `onError`. */
539
573
  deliver(jobs: Job[], runner: Runner): Promise<void>;
540
574
  /** Run what's due (retries, deliveries whose runner crashed). Only adapters that store deliveries have it. */
541
- sweep?(runner: Runner, options?: { limit?: number }): Promise<SweepResult>;
575
+ sweep?(runner: Runner, options?: SweepOptions): Promise<SweepResult>;
542
576
  /** Put a failed job back in line. `false` when there's no failed job with that id. Only adapters that store them. */
543
577
  retry?(id: string): Promise<boolean>;
544
578
  /** A page of failed jobs, newest first. Only adapters that store them and can filter them. */
@@ -546,10 +580,11 @@ export interface JobsAdapter {
546
580
  /** Delete one failed job. `false` when there's no failed job with that id: a waiting or running one is never touched. */
547
581
  forget?(id: string): Promise<boolean>;
548
582
  /**
549
- * Keep a job that failed for good after it left the adapter: `registry.jobs.run` calls it from a queue consumer, so
550
- * `outbox` stores the failure Cloudflare would otherwise drop. Not called for jobs the adapter ran itself.
583
+ * For an adapter that keeps its jobs as rows and sends a queue only signals: a consumer got this job's
584
+ * message, so run it from the rows (with a `key`, the key's next jobs, in order), recording each outcome itself.
585
+ * `registry.jobs.run` calls it in place of running the message.
551
586
  */
552
- fail?(job: Job, error: unknown): Promise<void>;
587
+ consume?(job: Job, runner: Runner): Promise<void>;
553
588
  }
554
589
 
555
590
  /**
@@ -568,12 +603,29 @@ export interface FailureInfo {
568
603
 
569
604
  /** What `createRegistry` gives an adapter's `connect`. */
570
605
  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`. */
606
+ /** The registry's `database.adapter`, when it runs SQL: always set for an adapter that declares `sql: true`. */
576
607
  sql: SqlDatabase | undefined;
608
+ /**
609
+ * The loops running jobs in this process (`work()`, through `registry.jobs.attach`): whether one takes `job`, so the
610
+ * request leaves it to them instead of running it, and `wake(count)` once that many are committed.
611
+ */
612
+ workers: { takes(job: Job): boolean; wake(count: number): void };
613
+ }
614
+
615
+ /** What `registry.jobs.sweep` and an adapter's `sweep` take. */
616
+ export interface SweepOptions {
617
+ /** At most this many jobs. Default 100. */
618
+ limit?: number;
619
+ /** Only these queues, in this order: each claim takes the first one with a job due. Default: every queue. */
620
+ queues?: readonly string[];
621
+ }
622
+
623
+ /** A loop running jobs in this process: `registry.jobs.attach({ wake, queues })`. */
624
+ export interface LocalWorker {
625
+ /** How many jobs just committed for it: claim them now. */
626
+ wake(count: number): void;
627
+ /** The queues it runs. Default: all. */
628
+ queues?: readonly string[];
577
629
  }
578
630
 
579
631
  /**
@@ -688,6 +740,12 @@ export type JobsOptions<S = object, T = any> = {
688
740
  * are 2 or 3).
689
741
  */
690
742
  maxEventDepth?: number;
743
+ /**
744
+ * Queues besides `"default"`, for listeners, crons and `ctx.schedule` (`queue: "mail"`): `queues: ["mail", "reports"]`.
745
+ * A worker takes them in the order it lists them (`work(registry, { queues: ["mail", "default"] })`). A name not
746
+ * declared here is refused, at `createRegistry` or at the call.
747
+ */
748
+ queues?: readonly string[];
691
749
  } & (
692
750
  | {
693
751
  /** `inProcess()` (default), or a durable one like `databaseQueue()`. Its own options go in its factory. */
@@ -731,9 +789,8 @@ export interface RegistryOptions<Mods extends Record<string, object>> {
731
789
  /**
732
790
  * Serverless: let listeners finish after the response. Pass the platform's global:
733
791
  * `import { waitUntil } from "cloudflare:workers"` or `import { waitUntil } from "@vercel/functions"`.
734
- * Without it, `run` waits for listeners. On a long-lived server with `databaseQueue`, `() => {}` answers first (a restart
735
- * is swept up after its lease: retried, or failed when it was out of attempts); with `inProcess()`, don't: work
736
- * still running at a restart is lost.
792
+ * Without it, `run` waits for listeners, unless a worker in this process takes them (`work(registry)` on Node or Bun,
793
+ * with `databaseQueue`): then the request answers at once.
737
794
  */
738
795
  waitUntil?: (promise: Promise<unknown>) => void;
739
796
  /** Failures no caller waits for: jobs, and the work after commit that runs them. They never fail the caller. */
@@ -791,11 +848,12 @@ export interface RegisteredCron extends Registered {
791
848
  */
792
849
  export interface Jobs {
793
850
  /**
794
- * Run one stored job (queue consumers): `await registry.jobs.run(message.body, { attempt: message.attempts })`.
851
+ * Run one job from a queue message (consumers): `await registry.jobs.run(message.body, { attempt: message.attempts })`.
795
852
  * Resolves `"done"`, `"failed"` or `"discarded"` (acknowledge all three); throws when a retry might help and the
796
- * job has tries left. A `failed` job goes to `fail`: yours, or your adapter's (`databaseQueue` and `outbox` keep it).
853
+ * job has tries left. A `failed` job is kept by `jobs.failed`, if you have one. On an adapter that only sends
854
+ * signals, the job runs from its row, which records how it went, and `run` resolves `"done"`.
797
855
  */
798
- run(job: Job, options?: RunJobOptions): Promise<JobOutcome>;
856
+ run(job: Job, options?: { attempt?: number }): Promise<JobOutcome>;
799
857
  /**
800
858
  * Run the crons due in `at`'s minute (default now), from a timer or your platform's cron trigger:
801
859
  * `await registry.jobs.tick(new Date(controller.scheduledTime))`. Resolves the ids of the crons that were due. Each run
@@ -804,10 +862,15 @@ export interface Jobs {
804
862
  tick(at?: Date): Promise<string[]>;
805
863
  /**
806
864
  * Run what your adapter has due, from a cron or an interval: `await registry.jobs.sweep()`. With `databaseQueue()`, that's
807
- * retries whose backoff is over and jobs whose runner crashed. Adapters that keep nothing, or maintain themselves
808
- * (pg-boss), resolve zeros.
865
+ * retries whose backoff is over and jobs whose runner crashed. Adapters that keep nothing resolve zeros.
866
+ */
867
+ sweep(options?: SweepOptions): Promise<SweepResult>;
868
+ /**
869
+ * For a host that runs jobs in this process, like `work()`: requests leave their jobs due now to it (in its `queues`,
870
+ * or all) and answer at once, and `wake(count)` tells it how many just committed, so it claims them right away rather
871
+ * than at its next poll. Returns the detach, for its stop. Throws on a queue `jobs.queues` doesn't declare.
809
872
  */
810
- sweep(options?: { limit?: number }): Promise<SweepResult>;
873
+ attach(worker: LocalWorker): () => void;
811
874
  /**
812
875
  * Put a failed job back in line with a fresh set of attempts. `false` when no failed job has that id (it's pending,
813
876
  * running, done, or never existed). Throws when your adapter keeps no jobs, like `inProcess()`.
@@ -816,7 +879,7 @@ export interface Jobs {
816
879
  /**
817
880
  * Failed jobs, newest first, a page at a time: `await registry.jobs.failed({ source: "emails.send", scope: { organizationId } })`.
818
881
  * 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.
882
+ * when your adapter keeps none (a queue alone without `jobs.failed`).
820
883
  */
821
884
  failed<Stored = Record<string, unknown>>(options?: FailedOptions<Stored>): Promise<FailedPage<Stored>>;
822
885
  /**
@@ -13,8 +13,9 @@ export interface QueueBatch {
13
13
 
14
14
  /**
15
15
  * Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
16
- * retries it with a backoff (it threw and the listener has tries left). One message at a time, each acknowledged on
17
- * its own, so one failure doesn't redeliver the batch.
16
+ * retries it with a backoff (it threw). One message at a time, each acknowledged on its own, so one failure doesn't
17
+ * redeliver the batch. Alone, a throw means the listener has tries left. Behind an outbox, a message is a signal: the
18
+ * 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.
18
19
  *
19
20
  * ```ts
20
21
  * async queue(batch, env, ctx) {
@@ -35,8 +36,8 @@ export async function handleQueue(registry: { jobs: Pick<Jobs, "run"> }, batch:
35
36
  }
36
37
 
37
38
  /**
38
- * Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (databaseQueue's retries,
39
- * delayed jobs, and sends a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
39
+ * Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (the jobs table's retries,
40
+ * delayed jobs, and what a lost signal or a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
40
41
  * 1 = Sunday, so write them as names (`MON`) in both places.
41
42
  *
42
43
  * ```ts
package/src/hosts/node.ts CHANGED
@@ -1,43 +1,51 @@
1
1
  import type { Jobs } from "../core/types.ts";
2
2
 
3
- export interface TickingOptions {
4
- /** Seconds between sweeps: databaseQueue's retries, delayed jobs and what a crash left behind. Default 60; 0 turns it off. */
5
- sweepEvery?: number;
6
- /** Where a failed tick or sweep goes, and a skipped minute. Default `console.error`. */
3
+ export interface WorkOptions {
4
+ /** Jobs this process runs at once. Default 1, like pg-boss, graphile-worker and a Laravel worker: run more processes, or raise it. */
5
+ concurrency?: number;
6
+ /** Seconds a free slot waits before it looks for a job again, when there was none. Default 2, like pg-boss and graphile-worker. */
7
+ pollEvery?: number;
8
+ /**
9
+ * The queues it runs, in order: each claim takes the first one with a job due, so `["mail", "default"]` sends mail
10
+ * first. Each one of `jobs.queues`, or `"default"`. Default: every queue, oldest due first.
11
+ */
12
+ queues?: readonly string[];
13
+ /** Where a failed tick or claim goes, and a skipped minute. Default `console.error`. */
7
14
  onError?: (error: unknown) => void;
8
15
  }
9
16
 
10
17
  export interface StopOptions {
11
- /** Seconds to wait for the running ticks and sweeps before giving up on them. Default 30, like pg-boss's `stop()`. */
18
+ /** Seconds to wait for the running jobs and ticks before giving up on them. Default 30, like pg-boss's `stop()`. */
12
19
  timeout?: number;
13
20
  }
14
21
 
15
22
  const MINUTE = 60_000;
16
23
  /**
17
- * Ticks, and sweeps, still running before the next of its kind is skipped (reported). Overlap is normal, like Laravel and
18
- * Oban: a slow cron doesn't hold back the next minute, and a hung job doesn't stop the sweeps, as it wouldn't stop the
19
- * other workers of a queue. Ten still running means they're stuck (the database is unreachable), and letting them pile
20
- * up would run a backlog of stale minutes when it comes back.
24
+ * Ticks still running before the next is skipped (reported). Overlap is normal, like Laravel and Oban: a slow cron
25
+ * doesn't hold back the next minute. Ten still running means they're stuck (the database is unreachable), and letting
26
+ * them pile up would run a backlog of stale minutes when it comes back.
21
27
  */
22
28
  const MAX_RUNNING = 10;
29
+ /** The longest a slot waits between claims while they throw (the database is down), so an outage is reported less and less often. */
30
+ const MAX_WAIT = 30;
23
31
 
24
32
  /**
25
- * A long-running process's cron trigger, like Laravel's `schedule:work`: ticks your crons on every minute and sweeps
26
- * every `sweepEvery` seconds, neither waiting for the last, so a slow cron or a hung job doesn't hold back the rest. A
27
- * minute the process wasn't running for is skipped, not caught up (Laravel and pg-boss do the same). Returns `stop()`,
28
- * which resolves once the running ticks and sweeps finish, or after `timeout` seconds (30) if they're stuck.
33
+ * A worker, like Laravel's `queue:work` and `schedule:work` in one process: `concurrency` slots, each claiming the next
34
+ * due job (`registry.jobs.sweep({ limit: 1 })`) and waiting `pollEvery` seconds when there's none, and your crons
35
+ * 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
36
+ * process wasn't running for is skipped, not caught up. In the web process, it takes the jobs requests commit, so they
37
+ * answer at once and it starts them right away; in a process of its own, it claims what's due, `pollEvery` seconds
38
+ * apart when there's nothing (with `databaseQueue({ runIn: "worker" })` that's every job). Returns `stop()`, which
39
+ * waits for the running jobs and ticks, `timeout` seconds at most.
29
40
  *
30
41
  * ```ts
31
- * import { startTicking } from "logic-sdk/node";
32
- * const stop = startTicking(registry);
33
- * process.on("SIGTERM", async () => { await stop(); process.exit(0); }); // waits 30 s at most: stop({ timeout })
42
+ * import { work } from "logic-sdk/node";
43
+ * const stop = work(registry, { concurrency: 5 });
44
+ * process.on("SIGTERM", async () => { await stop(); process.exit(0); });
34
45
  * ```
35
46
  */
36
- export function startTicking(
37
- registry: { jobs: Pick<Jobs, "tick" | "sweep"> },
38
- options: TickingOptions = {},
39
- ): (options?: StopOptions) => Promise<void> {
40
- const sweepEvery = options.sweepEvery ?? 60;
47
+ export function work(registry: { jobs: Pick<Jobs, "tick" | "sweep" | "attach"> }, options: WorkOptions = {}): (options?: StopOptions) => Promise<void> {
48
+ const { concurrency = 1, pollEvery = 2, queues } = options;
41
49
  const reportTo = options.onError ?? ((error) => console.error("[logic-sdk]", error));
42
50
  const onError = (error: unknown) => {
43
51
  try {
@@ -46,27 +54,52 @@ export function startTicking(
46
54
  console.error("[logic-sdk] onError threw", inner, "while reporting", error); // like the registry's: the loops keep going
47
55
  }
48
56
  };
49
- let tickTimer: ReturnType<typeof setTimeout> | undefined;
50
- let sweepTimer: ReturnType<typeof setTimeout> | undefined;
51
- const ticks = new Set<Promise<void>>();
52
- const sweeps = new Set<Promise<void>>();
53
-
54
- const startOfMinute = (ms: number) => Math.floor(ms / MINUTE) * MINUTE;
55
-
56
- const track = (running: Set<Promise<void>>, work: Promise<unknown>) => {
57
- const run = work.then(() => {}, onError);
58
- running.add(run);
59
- void run.finally(() => running.delete(run));
57
+ let stopping = false;
58
+ /** The sleeping slots: a commit wakes as many as it has jobs, `stop()` all of them. */
59
+ const wakes = new Set<() => void>();
60
+ const wakeUp = (count = Infinity) => {
61
+ for (const wake of [...wakes].slice(0, count)) wake();
60
62
  };
63
+ /** Resolves after `seconds`, or at once on `stop()`. */
64
+ const sleep = (seconds: number) =>
65
+ new Promise<void>((resolve) => {
66
+ const wake = () => {
67
+ clearTimeout(timer);
68
+ wakes.delete(wake);
69
+ resolve();
70
+ };
71
+ const timer = setTimeout(wake, seconds * 1000);
72
+ wakes.add(wake);
73
+ });
74
+
75
+ /** One job at a time: the next due one, back to back while there are some. */
76
+ async function slot() {
77
+ let wait = pollEvery;
78
+ while (!stopping) {
79
+ try {
80
+ const { done, failed, discarded, retrying } = await registry.jobs.sweep({ limit: 1, queues });
81
+ wait = pollEvery;
82
+ if (done + failed + discarded + retrying) continue;
83
+ } catch (error) {
84
+ onError(error);
85
+ wait = Math.min(wait * 2, MAX_WAIT);
86
+ }
87
+ await sleep(wait);
88
+ }
89
+ }
61
90
 
91
+ const ticks = new Set<Promise<void>>();
92
+ let tickTimer: ReturnType<typeof setTimeout> | undefined;
93
+ const startOfMinute = (ms: number) => Math.floor(ms / MINUTE) * MINUTE;
62
94
  const tick = (at: Date) => {
63
95
  if (ticks.size >= MAX_RUNNING) {
64
96
  onError(new Error(`[logic-sdk] skipped the ${at.toISOString()} tick: ${ticks.size} earlier ticks are still running. Is the database reachable?`));
65
97
  return;
66
98
  }
67
- track(ticks, registry.jobs.tick(at));
99
+ const run = registry.jobs.tick(at).then(() => {}, onError);
100
+ ticks.add(run);
101
+ void run.finally(() => ticks.delete(run));
68
102
  };
69
-
70
103
  const armTick = (minute: number) => {
71
104
  tickTimer = setTimeout(() => {
72
105
  // early by a millisecond: still this minute. Late (the machine slept): the current one, not a backlog
@@ -76,24 +109,18 @@ export function startTicking(
76
109
  }, minute - Date.now());
77
110
  };
78
111
 
79
- const sweep = () => {
80
- sweepTimer = setTimeout(sweep, sweepEvery * 1000); // the next one first, so a hung job can't stop the sweeps
81
- if (sweeps.size >= MAX_RUNNING) {
82
- onError(new Error(`[logic-sdk] skipped a sweep: ${sweeps.size} earlier sweeps are still running. Is a job hung, or the database unreachable?`));
83
- return;
84
- }
85
- track(sweeps, registry.jobs.sweep());
86
- };
87
-
112
+ const detach = registry.jobs.attach({ wake: wakeUp, queues }); // first: it throws on a queue jobs.queues doesn't declare
88
113
  armTick(startOfMinute(Date.now()) + MINUTE);
89
- if (sweepEvery > 0) sweepTimer = setTimeout(sweep, sweepEvery * 1000);
114
+ const slots = Array.from({ length: concurrency }, slot);
90
115
 
91
116
  return async ({ timeout = 30 } = {}) => {
117
+ stopping = true;
118
+ detach(); // requests run their own jobs again
92
119
  clearTimeout(tickTimer);
93
- clearTimeout(sweepTimer);
120
+ wakeUp();
94
121
  let timer: ReturnType<typeof setTimeout> | undefined;
95
122
  const gaveUp = new Promise<void>((resolve) => (timer = setTimeout(resolve, timeout * 1000)));
96
- await Promise.race([Promise.all([...ticks, ...sweeps]), gaveUp]);
123
+ await Promise.race([Promise.all([...slots, ...ticks]), gaveUp]);
97
124
  clearTimeout(timer);
98
125
  };
99
126
  }
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export type {
2
2
  ActionCtx,
3
3
  AdapterSetup,
4
+ LocalWorker,
4
5
  Call,
5
6
  CallJob,
6
7
  Caller,
@@ -66,9 +67,10 @@ export type {
66
67
  Schema,
67
68
  ScopeMatch,
68
69
  SqlDatabase,
70
+ SweepOptions,
69
71
  SweepResult,
70
72
  } from "./core/types.ts";
71
73
  export { DomainError, isDomainError, unauthenticated, type ErrorKind } from "./core/errors.ts";
72
74
  export { inProcess } from "./core/in-process.ts";
73
- export { defaultBackoff, storedReplaceKey } from "./core/jobs.ts";
75
+ export { defaultBackoff, storedUniqueKey } from "./core/jobs.ts";
74
76
  export { createRegistry, describeModules, init } from "./core/registry.ts";
package/src/node.ts CHANGED
@@ -1 +1 @@
1
- export { startTicking, type StopOptions, type TickingOptions } from "./hosts/node.ts";
1
+ export { work, type StopOptions, type WorkOptions } from "./hosts/node.ts";
@@ -1,45 +0,0 @@
1
- import { type PgBoss, type Queue, type WorkOptions } from "pg-boss";
2
- import type { ForListeners, JobsAdapter } from "../core/types.ts";
3
- /** One queue's tuning: a listener's or cron's `meta.pgBoss`, and `work()`'s `calls`. */
4
- export interface PgBossTuning {
5
- /** The listener's queue (`expireInSeconds`, `retryDelay`, `deadLetter`…), applied by `work()`. `partition` only when it's created. */
6
- queue?: Omit<Queue, "name" | "retryLimit" | "retryBackoff" | "policy">;
7
- /** Its workers in each process that calls `work()`: `localConcurrency`, `batchSize`, `pollingIntervalSeconds`… */
8
- worker?: Omit<WorkOptions, "includeMetadata" | "perJobResults" | "transactional" | "transactionTimeoutSeconds">;
9
- }
10
- /**
11
- * What this adapter reads from a listener's or cron's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
12
- * `meta: { pgBoss: { queue: { expireInSeconds: 120 }, worker: { localConcurrency: 5 } } }`. Tuning only: retries are the
13
- * listener's `attempts`, and the other adapters ignore it.
14
- */
15
- export type PgBossMeta = ForListeners<{
16
- pgBoss?: PgBossTuning;
17
- }>;
18
- /** Our queues' names start with it, so they can't collide with your own pg-boss queues, and `work()` can find ours. */
19
- export declare const PREFIX = "logic-sdk.";
20
- /** A listener's or cron's queue: `logic-sdk.notifications.send`. */
21
- export declare const queueName: (id: string) => string;
22
- /** Where scheduled calls (`ctx.schedule`) wait: one queue for all of them, so no function needs a worker of its own. */
23
- export declare const CALLS_QUEUE = "logic-sdk.calls";
24
- /** A queue as `meta.pgBoss.queue` tunes it. Backoff on, as on every job we insert, which `retryDelayMax` needs. */
25
- export declare const queueConfig: (queue: PgBossTuning["queue"]) => {
26
- expireInSeconds?: number;
27
- retentionSeconds?: number;
28
- deleteAfterSeconds?: number;
29
- retryDelay?: number;
30
- retryDelayMax?: number;
31
- partition?: boolean;
32
- deadLetter?: string;
33
- warningQueueSize?: number;
34
- heartbeatSeconds?: number;
35
- notify?: boolean;
36
- retryBackoff: boolean;
37
- };
38
- /** `meta.pgBoss` as `PgBossMeta` types it where you write it (meta is stored loose). */
39
- export declare const tuningOf: (meta: Readonly<Record<string, unknown>> | undefined) => PgBossTuning | undefined;
40
- /**
41
- * The pg-boss id of a job: a UUID v5 of its logic-sdk id (pg-boss ids are UUIDs). The same job is the same row, so a
42
- * minute ticked by several servers inserts once. Use it to find a job in pg-boss: `boss.findJobs(queue, { id: pgBossId(id) })`.
43
- */
44
- export declare function pgBossId(id: string): string;
45
- export declare function pgBoss(boss: PgBoss): JobsAdapter;