logic-sdk 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +9 -10
  2. package/dist/adapters/cloudflare-queue.d.ts +15 -0
  3. package/dist/adapters/cloudflare-queue.js +58 -0
  4. package/dist/adapters/drizzle-pg.d.ts +280 -0
  5. package/dist/adapters/drizzle-pg.js +78 -0
  6. package/dist/adapters/drizzle-sqlite.d.ts +273 -0
  7. package/dist/adapters/drizzle-sqlite.js +203 -0
  8. package/dist/adapters/postgres.d.ts +33 -0
  9. package/dist/adapters/postgres.js +129 -0
  10. package/dist/adapters/sqlite.d.ts +13 -0
  11. package/dist/adapters/sqlite.js +108 -0
  12. package/dist/adapters/stored-jobs.d.ts +89 -0
  13. package/dist/adapters/stored-jobs.js +370 -0
  14. package/dist/ai.d.ts +1 -32
  15. package/dist/ai.js +1 -40
  16. package/dist/cloudflare.d.ts +2 -55
  17. package/dist/cloudflare.js +2 -85
  18. package/dist/core/in-process.d.ts +9 -0
  19. package/dist/core/in-process.js +37 -0
  20. package/dist/core/jobs.d.ts +63 -0
  21. package/dist/core/jobs.js +514 -0
  22. package/dist/core/registry.d.ts +156 -0
  23. package/dist/core/registry.js +515 -0
  24. package/dist/core/testing.d.ts +75 -0
  25. package/dist/core/testing.js +232 -0
  26. package/dist/{types.d.ts → core/types.d.ts} +289 -64
  27. package/dist/drizzle/pg.d.ts +3 -236
  28. package/dist/drizzle/pg.js +2 -67
  29. package/dist/drizzle/sqlite.d.ts +3 -242
  30. package/dist/drizzle/sqlite.js +2 -194
  31. package/dist/fetch.d.ts +1 -19
  32. package/dist/fetch.js +1 -30
  33. package/dist/hosts/cloudflare.d.ts +43 -0
  34. package/dist/hosts/cloudflare.js +40 -0
  35. package/dist/hosts/node.d.ts +36 -0
  36. package/dist/hosts/node.js +103 -0
  37. package/dist/index.d.ts +5 -122
  38. package/dist/index.js +4 -492
  39. package/dist/integrations/ai.d.ts +32 -0
  40. package/dist/integrations/ai.js +40 -0
  41. package/dist/integrations/fetch.d.ts +19 -0
  42. package/dist/integrations/fetch.js +30 -0
  43. package/dist/integrations/orpc.d.ts +22 -0
  44. package/dist/integrations/orpc.js +37 -0
  45. package/dist/node.d.ts +1 -26
  46. package/dist/node.js +1 -76
  47. package/dist/orpc.d.ts +1 -21
  48. package/dist/orpc.js +1 -37
  49. package/dist/postgres.d.ts +2 -28
  50. package/dist/postgres.js +1 -82
  51. package/dist/sqlite.d.ts +2 -9
  52. package/dist/sqlite.js +1 -65
  53. package/dist/testing.d.ts +1 -75
  54. package/dist/testing.js +1 -227
  55. package/package.json +2 -12
  56. package/skills/logic-sdk/SKILL.md +6 -5
  57. package/src/adapters/cloudflare-queue.ts +65 -0
  58. package/src/adapters/drizzle-pg.ts +117 -0
  59. package/src/adapters/drizzle-sqlite.ts +241 -0
  60. package/src/adapters/postgres.ts +136 -0
  61. package/src/adapters/sqlite.ts +116 -0
  62. package/src/adapters/stored-jobs.ts +463 -0
  63. package/src/ai.ts +1 -62
  64. package/src/cloudflare.ts +2 -107
  65. package/src/core/in-process.ts +38 -0
  66. package/src/core/jobs.ts +548 -0
  67. package/src/core/registry.ts +719 -0
  68. package/src/core/testing.ts +309 -0
  69. package/src/{types.ts → core/types.ts} +280 -60
  70. package/src/drizzle/pg.ts +3 -110
  71. package/src/drizzle/sqlite.ts +3 -236
  72. package/src/fetch.ts +1 -31
  73. package/src/hosts/cloudflare.ts +55 -0
  74. package/src/hosts/node.ts +126 -0
  75. package/src/index.ts +17 -652
  76. package/src/integrations/ai.ts +63 -0
  77. package/src/integrations/fetch.ts +31 -0
  78. package/src/integrations/orpc.ts +47 -0
  79. package/src/node.ts +1 -99
  80. package/src/orpc.ts +1 -46
  81. package/src/postgres.ts +2 -90
  82. package/src/sqlite.ts +2 -74
  83. package/src/testing.ts +1 -305
  84. package/dist/jobs.d.ts +0 -44
  85. package/dist/jobs.js +0 -260
  86. package/dist/pg-boss.d.ts +0 -53
  87. package/dist/pg-boss.js +0 -213
  88. package/dist/stored-jobs.d.ts +0 -64
  89. package/dist/stored-jobs.js +0 -188
  90. package/src/jobs.ts +0 -307
  91. package/src/pg-boss.ts +0 -241
  92. package/src/stored-jobs.ts +0 -260
  93. /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
  94. /package/dist/{errors.js → core/errors.js} +0 -0
  95. /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
  96. /package/dist/{schedule.js → core/schedule.js} +0 -0
  97. /package/dist/{types.js → core/types.js} +0 -0
  98. /package/src/{errors.ts → core/errors.ts} +0 -0
  99. /package/src/{schedule.ts → core/schedule.ts} +0 -0
@@ -1,55 +1,2 @@
1
- import type { Job, Jobs, JobsAdapter } from "./index.ts";
2
- /** What the adapter uses of a Cloudflare Queue binding: `env.JOBS` fits. */
3
- export interface QueueBinding {
4
- sendBatch(messages: Iterable<{
5
- body: Job;
6
- delaySeconds?: number;
7
- }>): Promise<unknown>;
8
- }
9
- /** What the handler uses of a consumer's `MessageBatch<Job>`. Type your Worker with `ExportedHandler<Env, Job>`. */
10
- export interface QueueBatch {
11
- readonly messages: readonly {
12
- readonly body: Job;
13
- readonly attempts: number;
14
- ack(): void;
15
- retry(options?: {
16
- delaySeconds?: number;
17
- }): void;
18
- }[];
19
- }
20
- /**
21
- * Send jobs to a Cloudflare Queue after commit. Alone it's lossy (a Worker that dies between commit and send loses
22
- * them); behind an outbox it's durable: `jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }`.
23
- * Run them with `handleQueue(registry, batch)` in your consumer.
24
- */
25
- export declare function cloudflareQueue(queue: QueueBinding): JobsAdapter;
26
- /**
27
- * Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
28
- * retries it with a backoff (it threw and the listener has tries left). One message at a time, each acknowledged on
29
- * its own, so one failure doesn't redeliver the batch.
30
- *
31
- * ```ts
32
- * async queue(batch, env, ctx) {
33
- * await handleQueue(makeRegistry(env, ctx), batch);
34
- * },
35
- * ```
36
- */
37
- export declare function handleQueue(registry: {
38
- jobs: Pick<Jobs, "run">;
39
- }, batch: QueueBatch): Promise<void>;
40
- /**
41
- * Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (databaseQueue's retries,
42
- * delayed jobs, and sends a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
43
- * 1 = Sunday, so write them as names (`MON`) in both places.
44
- *
45
- * ```ts
46
- * async scheduled(controller, env, ctx) {
47
- * await handleScheduled(makeRegistry(env, ctx), controller);
48
- * },
49
- * ```
50
- */
51
- export declare function handleScheduled(registry: {
52
- jobs: Pick<Jobs, "tick" | "sweep">;
53
- }, controller: {
54
- readonly scheduledTime: number;
55
- }): Promise<void>;
1
+ export { cloudflareQueue, type QueueBinding } from "./adapters/cloudflare-queue.ts";
2
+ export { handleQueue, handleScheduled, type QueueBatch } from "./hosts/cloudflare.ts";
@@ -1,85 +1,2 @@
1
- import { defaultBackoff } from "./stored-jobs.js";
2
- // Cloudflare's limits, where 1 KB is 1000 bytes: https://developers.cloudflare.com/queues/platform/limits/
3
- const MAX_MESSAGES = 100;
4
- const MAX_BATCH_BYTES = 256_000;
5
- const MAX_MESSAGE_BYTES = 128_000;
6
- /** Cloudflare counts about this much metadata per message toward the limits. */
7
- const OVERHEAD_BYTES = 100;
8
- /** The longest `delaySeconds` Cloudflare takes, for a send and for a retry: 24 hours. */
9
- const MAX_DELAY = 86_400;
10
- const encoder = new TextEncoder();
11
- /**
12
- * Send jobs to a Cloudflare Queue after commit. Alone it's lossy (a Worker that dies between commit and send loses
13
- * them); behind an outbox it's durable: `jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }`.
14
- * Run them with `handleQueue(registry, batch)` in your consumer.
15
- */
16
- export function cloudflareQueue(queue) {
17
- return {
18
- holds: { max: MAX_DELAY }, // delaySeconds, up to 24 hours
19
- async deliver(jobs) {
20
- for (const batch of batches(jobs))
21
- await queue.sendBatch(batch);
22
- },
23
- };
24
- }
25
- /** Under Cloudflare's limits per send: 100 messages, 256 KB in all, 128 KB each. Checks every job before sending any. */
26
- function* batches(jobs) {
27
- const sized = jobs.map((body) => {
28
- const size = encoder.encode(JSON.stringify(body)).length + OVERHEAD_BYTES;
29
- if (size > MAX_MESSAGE_BYTES)
30
- throw new Error(`[logic-sdk] job ${body.id} is ${size} bytes; Cloudflare Queues take ${MAX_MESSAGE_BYTES} per message. Keep payloads to ids.`);
31
- return { body, size };
32
- });
33
- let batch = [];
34
- let bytes = 0;
35
- for (const { body, size } of sized) {
36
- if (batch.length && (batch.length === MAX_MESSAGES || bytes + size > MAX_BATCH_BYTES)) {
37
- yield batch;
38
- batch = [];
39
- bytes = 0;
40
- }
41
- batch.push(body.runAt ? { body, delaySeconds: secondsUntil(body.runAt) } : { body });
42
- bytes += size;
43
- }
44
- if (batch.length)
45
- yield batch;
46
- }
47
- const secondsUntil = (iso) => Math.min(MAX_DELAY, Math.max(0, Math.ceil((Date.parse(iso) - Date.now()) / 1000)));
48
- /**
49
- * Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
50
- * retries it with a backoff (it threw and the listener has tries left). One message at a time, each acknowledged on
51
- * its own, so one failure doesn't redeliver the batch.
52
- *
53
- * ```ts
54
- * async queue(batch, env, ctx) {
55
- * await handleQueue(makeRegistry(env, ctx), batch);
56
- * },
57
- * ```
58
- */
59
- export async function handleQueue(registry, batch) {
60
- for (const message of batch.messages) {
61
- try {
62
- await registry.jobs.run(message.body, { attempt: message.attempts });
63
- message.ack();
64
- }
65
- catch {
66
- // already reported to onError. databaseQueue's curve, so a listener's tries aren't spent back to back.
67
- message.retry({ delaySeconds: Math.ceil(defaultBackoff(message.attempts)) });
68
- }
69
- }
70
- }
71
- /**
72
- * Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (databaseQueue's retries,
73
- * delayed jobs, and sends a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
74
- * 1 = Sunday, so write them as names (`MON`) in both places.
75
- *
76
- * ```ts
77
- * async scheduled(controller, env, ctx) {
78
- * await handleScheduled(makeRegistry(env, ctx), controller);
79
- * },
80
- * ```
81
- */
82
- export async function handleScheduled(registry, controller) {
83
- await registry.jobs.tick(new Date(controller.scheduledTime));
84
- await registry.jobs.sweep();
85
- }
1
+ export { cloudflareQueue } from "./adapters/cloudflare-queue.js";
2
+ export { handleQueue, handleScheduled } from "./hosts/cloudflare.js";
@@ -0,0 +1,9 @@
1
+ import type { InProcess, JobsAdapter } from "./types.ts";
2
+ import { RUNS_NOW } from "./types.ts";
3
+ /**
4
+ * Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
5
+ * hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
6
+ */
7
+ export declare const inProcess: () => InProcess;
8
+ /** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
9
+ export declare const runsNow: (adapter: JobsAdapter) => adapter is JobsAdapter & Record<typeof RUNS_NOW, unknown>;
@@ -0,0 +1,37 @@
1
+ import { RUNS_NOW } from "./types.js";
2
+ /** The last job of each key, in this process: the next one starts after it. */
3
+ const lastOfKey = new Map();
4
+ const IN_PROCESS = {
5
+ [RUNS_NOW]: true,
6
+ name: "inProcess()",
7
+ orders: true,
8
+ queues: true, // nothing waits, so there's nothing to keep apart
9
+ async deliver(jobs, { run }) {
10
+ for (const job of jobs) {
11
+ // one try, whatever `attempts` says: what throws has failed, so onError never hears of a retry that won't come
12
+ const once = () => run({ ...job, attempts: 1 });
13
+ const key = job.kind === "delivery" ? job.key : undefined;
14
+ if (!key) {
15
+ await once();
16
+ continue;
17
+ }
18
+ const mine = (lastOfKey.get(key) ?? Promise.resolve()).then(once);
19
+ const settled = mine.catch(() => { });
20
+ lastOfKey.set(key, settled);
21
+ try {
22
+ await mine;
23
+ }
24
+ finally {
25
+ if (lastOfKey.get(key) === settled)
26
+ lastOfKey.delete(key);
27
+ }
28
+ }
29
+ },
30
+ };
31
+ /**
32
+ * Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
33
+ * hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
34
+ */
35
+ export const inProcess = () => IN_PROCESS;
36
+ /** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
37
+ export const runsNow = (adapter) => RUNS_NOW in adapter;
@@ -0,0 +1,63 @@
1
+ import type { ActionCtx, AdapterSetup, Call, CallJob, CronJob, DatabaseAdapter, Delivery, FailedJobs, Envelope, FailureInfo, Fn, Job, JobsAdapter, JobScope, Jobs, RegisteredCron, RegisteredFn, RegisteredListener } from "./types.ts";
2
+ export declare const isPlainObject: (v: unknown) => v is Record<string, unknown>;
3
+ /**
4
+ * What makes a scheduled call with `replace: true` replaceable: its function and its input, `<function id>@<input>`. A
5
+ * newer call with the same one replaces it while it waits. Undefined for every other job.
6
+ */
7
+ export declare const replaceKeyOf: (job: Job) => string | undefined;
8
+ /**
9
+ * The key adapters that keep one waiting job per key (`replaces: true`) store: a delivery's `unique` as it is, a call's
10
+ * `replaceKeyOf` as `<function id>@<sha-256 of the input>`, so a large input still fits an index and the function
11
+ * stays readable. Undefined for every other job.
12
+ */
13
+ export declare function storedUniqueKey(job: Job): Promise<string | undefined>;
14
+ /**
15
+ * Seconds to wait after a failed try: e^attempt, capped at e^10 (about 6 hours), the curve Graphile Worker uses. The
16
+ * core's, so every adapter that backs off (the jobs table, Cloudflare's redelivery) waits the same.
17
+ */
18
+ export declare const defaultBackoff: (attempt: number) => number;
19
+ /** Where the docs list each adapter and what it can do. */
20
+ export declare const ADAPTERS = "see Jobs, Adapters in the docs";
21
+ /** What an adapter's `connect` gets as `setup.workers`: does a loop here take this job, and wake them. */
22
+ export declare function workersOf(adapter: JobsAdapter): AdapterSetup["workers"];
23
+ /** One listener's share of an event, as a job: `<listener id>@<event id>`, with the listener's tries. */
24
+ export declare const deliveryOf: (l: RegisteredListener, e: Envelope) => Delivery;
25
+ /** What running jobs needs from the registry: its definitions, and how it runs a function or a listener's handler. */
26
+ export interface JobsDeps {
27
+ listeners: readonly RegisteredListener[];
28
+ crons: readonly RegisteredCron[];
29
+ functions: readonly RegisteredFn[];
30
+ idOf(x: object): string;
31
+ jobsAdapter: JobsAdapter;
32
+ database: DatabaseAdapter<unknown, unknown> | undefined;
33
+ jobScope: JobScope | undefined;
34
+ /** `jobs.failed`: where failed jobs are kept when the adapter keeps none. */
35
+ failedStore: FailedJobs | undefined;
36
+ maxEventDepth: number;
37
+ /** `jobs.queues`: the queues besides `"default"`. */
38
+ queues: readonly string[];
39
+ now(): Date;
40
+ wrap(call: Call, next: () => Promise<unknown>): Promise<unknown>;
41
+ report(error: unknown, info: FailureInfo): void;
42
+ /** Run a function as `scope`, like `registry.as(scope).run`. `eventDepth`: the chain's hops so far (a scheduled call's `depth`). */
43
+ runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined, job: {
44
+ id: string;
45
+ attempt: number;
46
+ }): Promise<unknown>;
47
+ /** The ctx a listener's or cron's handler gets, as `scope`, in an event chain `eventDepth` deep. `stop`: its timeout. */
48
+ handlerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined, stop?: AbortSignal): ActionCtx<any>;
49
+ }
50
+ /**
51
+ * Jobs, for one registry: a listener's share of an event, a cron's run, a scheduled call. Turns a commit's events and
52
+ * calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
53
+ */
54
+ export declare function makeJobs(deps: JobsDeps): {
55
+ toJobs: (envelopes: Envelope[], calls: CallJob[], parsed: Map<Envelope, unknown>) => Job[];
56
+ deliver: (jobs: Job[]) => Promise<void>;
57
+ jobs: Jobs;
58
+ due: (at: Date, only?: string) => CronJob[];
59
+ checkHold: (what: string, seconds: number) => void;
60
+ checkRetries: (what: string, attempts: number) => void;
61
+ checkQueue: (what: string, queue: string | undefined) => void;
62
+ yours: string;
63
+ };