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
package/src/sqlite.ts
CHANGED
|
@@ -1,74 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
// Every statement returns rows: better-sqlite3's `all()` refuses one that doesn't, so one `query` fits every driver.
|
|
4
|
-
import { storedJobs, type DatabaseQueueOptions, type JobsSql, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
|
|
5
|
-
import type { JobsAdapter, SqlDatabase } from "./index.ts";
|
|
6
|
-
|
|
7
|
-
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./stored-jobs.ts";
|
|
8
|
-
|
|
9
|
-
const now = `cast(unixepoch('subsec') * 1000 as integer)`;
|
|
10
|
-
|
|
11
|
-
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
12
|
-
export const jobsSchema = `
|
|
13
|
-
CREATE TABLE logic_jobs (
|
|
14
|
-
id text PRIMARY KEY NOT NULL,
|
|
15
|
-
job text NOT NULL,
|
|
16
|
-
status text NOT NULL DEFAULT 'pending',
|
|
17
|
-
attempts integer NOT NULL DEFAULT 0,
|
|
18
|
-
available_at integer NOT NULL DEFAULT (${now}),
|
|
19
|
-
receipt text,
|
|
20
|
-
last_error text,
|
|
21
|
-
failed_at integer,
|
|
22
|
-
replace_key text,
|
|
23
|
-
created_at integer NOT NULL DEFAULT (${now})
|
|
24
|
-
);
|
|
25
|
-
CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
|
|
26
|
-
CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
|
|
27
|
-
CREATE TABLE logic_cron_runs (
|
|
28
|
-
id text PRIMARY KEY NOT NULL,
|
|
29
|
-
ran_at integer NOT NULL DEFAULT (${now})
|
|
30
|
-
);
|
|
31
|
-
`;
|
|
32
|
-
|
|
33
|
-
const ids = "(SELECT value FROM json_each(?))";
|
|
34
|
-
const mine = `id IN ${ids} AND receipt = ? AND status = 'pending'`;
|
|
35
|
-
const inSeconds = `${now} + cast(? * 1000 as integer)`;
|
|
36
|
-
|
|
37
|
-
const statements: JobsSql = {
|
|
38
|
-
// the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`). `json_each.key` is
|
|
39
|
-
// the row's place in the list. `WHERE true`: SQLite needs it to tell an upsert's ON CONFLICT from a join's ON
|
|
40
|
-
insert: `
|
|
41
|
-
INSERT INTO logic_jobs (id, job, available_at, replace_key)
|
|
42
|
-
SELECT value ->> 'id', value -> 'job', coalesce(value ->> 'at', ${inSeconds}), value ->> 'key'
|
|
43
|
-
FROM json_each(?) WHERE true ORDER BY json_each.key
|
|
44
|
-
ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
|
|
45
|
-
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
|
|
46
|
-
RETURNING id`,
|
|
47
|
-
recordTicks: `INSERT INTO logic_cron_runs (id) SELECT value FROM json_each(?) WHERE true ON CONFLICT DO NOTHING RETURNING id`,
|
|
48
|
-
pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < ${now} - 86400000 RETURNING id`,
|
|
49
|
-
claimNew: `
|
|
50
|
-
UPDATE logic_jobs SET attempts = 1, receipt = ?, available_at = ${inSeconds}
|
|
51
|
-
WHERE id IN ${ids} AND attempts = 0 AND status = 'pending' RETURNING id`,
|
|
52
|
-
// no row locks to skip: SQLite has one writer at a time, and this statement is one write
|
|
53
|
-
claimDue: `
|
|
54
|
-
UPDATE logic_jobs SET attempts = attempts + 1, receipt = ?, available_at = ${inSeconds}
|
|
55
|
-
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= ${now} ORDER BY available_at LIMIT 1)
|
|
56
|
-
RETURNING job, attempts`,
|
|
57
|
-
extend: `UPDATE logic_jobs SET available_at = ${inSeconds} WHERE ${mine} RETURNING id`,
|
|
58
|
-
backOff: `UPDATE logic_jobs SET available_at = ${inSeconds}, last_error = ? WHERE ${mine} RETURNING id`,
|
|
59
|
-
markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = ?, failed_at = ${now} WHERE ${mine} RETURNING id`,
|
|
60
|
-
remove: `DELETE FROM logic_jobs WHERE ${mine} RETURNING id`,
|
|
61
|
-
retry: `
|
|
62
|
-
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, available_at = ${now}, last_error = NULL, failed_at = NULL, replace_key = NULL
|
|
63
|
-
WHERE id = ? AND status = 'failed' RETURNING id`,
|
|
64
|
-
fail: `
|
|
65
|
-
INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES (?, ?, 'failed', ?, ${now})
|
|
66
|
-
ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at
|
|
67
|
-
RETURNING id`,
|
|
68
|
-
};
|
|
69
|
-
|
|
70
|
-
/** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
|
|
71
|
-
export const databaseQueue = (database: SqlDatabase, options: DatabaseQueueOptions = {}): StoredJobs => storedJobs(statements, database, options);
|
|
72
|
-
|
|
73
|
-
/** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
|
|
74
|
-
export const outbox = (database: SqlDatabase, queue: JobsAdapter, options: OutboxOptions = {}): StoredJobs => storedJobs(statements, database, options, queue);
|
|
1
|
+
export { databaseQueue, failedJobs, jobsSchema, outbox } from "./adapters/sqlite.ts";
|
|
2
|
+
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./adapters/stored-jobs.ts";
|
package/src/testing.ts
CHANGED
|
@@ -1,305 +1 @@
|
|
|
1
|
-
|
|
2
|
-
replaceKeyOf,
|
|
3
|
-
type Caller,
|
|
4
|
-
type DatabaseAdapter,
|
|
5
|
-
type DeepPartial,
|
|
6
|
-
type CallJob,
|
|
7
|
-
type Cron,
|
|
8
|
-
type Delivery,
|
|
9
|
-
type Envelope,
|
|
10
|
-
type Fn,
|
|
11
|
-
type FnIn,
|
|
12
|
-
type FnOut,
|
|
13
|
-
type Job,
|
|
14
|
-
type JobOutcome,
|
|
15
|
-
type JobsAdapter,
|
|
16
|
-
type Listener,
|
|
17
|
-
type Registry,
|
|
18
|
-
} from "./index.ts";
|
|
19
|
-
import { deliveryOf } from "./jobs.ts";
|
|
20
|
-
import { INTERNAL } from "./types.ts";
|
|
21
|
-
|
|
22
|
-
export interface TestOptions<Cf = unknown> {
|
|
23
|
-
/** Replace services (e.g. `{ mailer: memoryMailer() }`). */
|
|
24
|
-
services?: object;
|
|
25
|
-
/** Override parts of `config` (e.g. `{ orders: { maxItems: 1 } }`). Merged over the registry's, section by section. */
|
|
26
|
-
config?: DeepPartial<Cf>;
|
|
27
|
-
/** Freeze time. */
|
|
28
|
-
now?: Date | string | (() => Date);
|
|
29
|
-
/**
|
|
30
|
-
* `"inline"` (default): listeners run right after each mutation, inside the test. `"manual"`: jobs wait in
|
|
31
|
-
* `t.jobs.queued` until you `drain()` them, to test one module without the others reacting. Like Oban's
|
|
32
|
-
* `testing: :inline | :manual`. Either way, what waits (a listener's `delay`, `ctx.schedule`) waits for `drain()`, and
|
|
33
|
-
* your app's adapter (a database queue, an outbox, Cloudflare) is never used.
|
|
34
|
-
*/
|
|
35
|
-
jobs?: "inline" | "manual";
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** The jobs of the current test, like `registry.jobs` in production. */
|
|
39
|
-
export interface TestJobs<S> {
|
|
40
|
-
/** Listener jobs waiting: every one in `jobs: "manual"`, and the delayed ones in either mode. */
|
|
41
|
-
readonly queued: readonly Delivery[];
|
|
42
|
-
/** What `ctx.schedule` asked for, waiting for `drain()`. */
|
|
43
|
-
readonly scheduled: readonly CallJob[];
|
|
44
|
-
/**
|
|
45
|
-
* Run what's due at the test's now (or `until`), and what that queues, until nothing due is left. Throws a failure.
|
|
46
|
-
* Like Rails' `perform_enqueued_jobs(at:)` and Oban's `drain_queue(with_scheduled:)`.
|
|
47
|
-
*/
|
|
48
|
-
drain(options?: { until?: Date | string }): Promise<void>;
|
|
49
|
-
/** Run one listener by hand, as if its event had been emitted as `scope`. Throws its failure, like `drain()`. */
|
|
50
|
-
perform<O>(listener: Listener<O>, payload: O, options: { scope: S; attempt?: number }): Promise<JobOutcome>;
|
|
51
|
-
/**
|
|
52
|
-
* Run one cron by hand, as its own scope, for the minute `at` (default: the test's now), whatever its schedule. Throws
|
|
53
|
-
* its failure. `t.jobs.tick(at)` runs every cron due that minute instead.
|
|
54
|
-
*/
|
|
55
|
-
perform(cron: Cron, options?: { at?: Date | string; attempt?: number }): Promise<JobOutcome>;
|
|
56
|
-
/** Run the crons due in `at`'s minute (default: the test's now), here and now. Resolves their ids; throws a failure. */
|
|
57
|
-
tick(at?: Date | string): Promise<string[]>;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export interface TestRegistry<S extends object, Mods extends Record<string, object>, Cf> {
|
|
61
|
-
/** Open the test's transaction: `beforeEach(() => t.begin())`. */
|
|
62
|
-
begin(): Promise<void>;
|
|
63
|
-
/** Roll it back: `afterEach(() => t.rollback())`. */
|
|
64
|
-
rollback(): Promise<void>;
|
|
65
|
-
/** Bind who is calling, like `registry.as(...)`. A listener that fails makes `run` throw, so a test can't pass over it. */
|
|
66
|
-
as(scope: S): Caller<S>;
|
|
67
|
-
/** Replace a function's implementation for this test. Matched by identity, so `run(availability.hold, …)` hits the stub. */
|
|
68
|
-
stub<F extends Fn>(fn: F, impl: (ctx: unknown, input: FnIn<F>) => Promise<FnOut<F>>): void;
|
|
69
|
-
/** Every event emitted (and committed) in this test, in order. */
|
|
70
|
-
readonly events: readonly Envelope[];
|
|
71
|
-
/** The test transaction itself: read rows to assert on them. */
|
|
72
|
-
readonly db: any;
|
|
73
|
-
/** The registry bound to this test's transaction, for adapters: an oRPC context's `caller: t.registry.as(scope)`. */
|
|
74
|
-
readonly registry: Registry<S, Mods, Cf>;
|
|
75
|
-
readonly jobs: TestJobs<S>;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/** One test, between `begin` and `rollback`. */
|
|
79
|
-
interface Open<S extends object, Mods extends Record<string, object>, Cf> {
|
|
80
|
-
registry: Registry<S, Mods, Cf>;
|
|
81
|
-
db: unknown;
|
|
82
|
-
events: Envelope[];
|
|
83
|
-
stubs: Map<Fn, (ctx: never, input: never) => Promise<unknown>>;
|
|
84
|
-
queued: Delivery[];
|
|
85
|
-
scheduled: CallJob[];
|
|
86
|
-
/** Job failures (listeners, crons, scheduled calls) during the current call. */
|
|
87
|
-
failures: unknown[];
|
|
88
|
-
close(): Promise<void>;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
class Rollback extends Error {}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* The test's jobs adapter. What waits (a delayed listener, `ctx.schedule`) is held for `drain()`, and in `"manual"` so
|
|
95
|
-
* is everything else; the rest runs now. It holds and replaces what your app's adapter does, so a test fails where
|
|
96
|
-
* production would.
|
|
97
|
-
*/
|
|
98
|
-
const testJobs = (mode: TestOptions["jobs"], app: JobsAdapter | undefined, queued: Delivery[], scheduled: CallJob[]): JobsAdapter => ({
|
|
99
|
-
holds: app?.holds,
|
|
100
|
-
replaces: app?.replaces,
|
|
101
|
-
async deliver(jobs, runner) {
|
|
102
|
-
for (const job of jobs) {
|
|
103
|
-
const key = replaceKeyOf(job);
|
|
104
|
-
if (key) {
|
|
105
|
-
const waiting = scheduled.findIndex((c) => replaceKeyOf(c) === key);
|
|
106
|
-
if (waiting >= 0) scheduled.splice(waiting, 1);
|
|
107
|
-
}
|
|
108
|
-
const waits = job.runAt !== undefined || (mode === "manual" && job.kind !== "cron");
|
|
109
|
-
if (!waits) await runner.run({ ...job, attempts: 1 }); // one try, like inProcess(): reported, so the test sees it
|
|
110
|
-
else if (job.kind === "call") scheduled.push(job);
|
|
111
|
-
else if (job.kind === "delivery") queued.push(job);
|
|
112
|
-
}
|
|
113
|
-
},
|
|
114
|
-
});
|
|
115
|
-
|
|
116
|
-
/** Removes the jobs that are due from `list` and returns them. */
|
|
117
|
-
function takeDue<T extends Job>(list: T[], cutoff: number): T[] {
|
|
118
|
-
const due = (job: T) => !job.runAt || Date.parse(job.runAt) <= cutoff;
|
|
119
|
-
const ready = list.filter(due);
|
|
120
|
-
list.splice(0, list.length, ...list.filter((job) => !due(job)));
|
|
121
|
-
return ready;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Run each test inside a transaction that's rolled back, set up once with hooks:
|
|
126
|
-
*
|
|
127
|
-
* ```ts
|
|
128
|
-
* const t = createTestRegistry(registry);
|
|
129
|
-
* beforeEach(() => t.begin());
|
|
130
|
-
* afterEach(() => t.rollback());
|
|
131
|
-
* ```
|
|
132
|
-
*
|
|
133
|
-
* Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes, like it
|
|
134
|
-
* would in production. Tests that share `t` run one at a time (one connection, nested savepoints).
|
|
135
|
-
*/
|
|
136
|
-
export function createTestRegistry<S extends object, Mods extends Record<string, object>, Cf>(
|
|
137
|
-
registry: Registry<S, Mods, Cf>,
|
|
138
|
-
options: TestOptions<Cf> = {},
|
|
139
|
-
): TestRegistry<S, Mods, Cf> {
|
|
140
|
-
const { options: registryOptions } = registry[INTERNAL];
|
|
141
|
-
const fixed = options.now;
|
|
142
|
-
const now = typeof fixed === "function" ? fixed : fixed === undefined ? undefined : () => new Date(fixed);
|
|
143
|
-
/** While `drain()` runs a job that waited, the time it was due: what `ctx.now()` reads then. */
|
|
144
|
-
let travelled: number | undefined;
|
|
145
|
-
const clock = () => {
|
|
146
|
-
const base = (now ?? registryOptions.now ?? (() => new Date()))();
|
|
147
|
-
return travelled !== undefined && travelled > base.getTime() ? new Date(travelled) : base;
|
|
148
|
-
};
|
|
149
|
-
let open: Open<S, Mods, Cf> | undefined;
|
|
150
|
-
|
|
151
|
-
const current = () => {
|
|
152
|
-
if (!open) throw new Error("[logic-sdk] No test transaction. Add beforeEach(() => t.begin()) and afterEach(() => t.rollback()).");
|
|
153
|
-
return open;
|
|
154
|
-
};
|
|
155
|
-
|
|
156
|
-
/** `db` is the test's transaction, and `database` the adapter nested in it (none without a database). */
|
|
157
|
-
function start(db: unknown, database: DatabaseAdapter<unknown, unknown> | undefined, close: () => Promise<void>): Open<S, Mods, Cf> {
|
|
158
|
-
const events: Envelope[] = [];
|
|
159
|
-
const stubs: Open<S, Mods, Cf>["stubs"] = new Map();
|
|
160
|
-
const queued: Delivery[] = [];
|
|
161
|
-
const scheduled: CallJob[] = [];
|
|
162
|
-
const failures: unknown[] = [];
|
|
163
|
-
const derived = registry[INTERNAL].derive({
|
|
164
|
-
database,
|
|
165
|
-
services: options.services,
|
|
166
|
-
config: options.config,
|
|
167
|
-
now: clock,
|
|
168
|
-
stubs,
|
|
169
|
-
record: (e) => events.push(e),
|
|
170
|
-
adapter: testJobs(options.jobs, registryOptions.jobs?.adapter, queued, scheduled),
|
|
171
|
-
waitUntil: undefined, // listeners finish before a call returns, inside the test
|
|
172
|
-
onError(error, info) {
|
|
173
|
-
if (info.outcome !== "discarded") failures.push(error);
|
|
174
|
-
registryOptions.onError?.(error, info);
|
|
175
|
-
},
|
|
176
|
-
});
|
|
177
|
-
return { registry: derived, db, events, stubs, queued, scheduled, failures, close };
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/** Run `work`, then throw the first listener failure since the last one thrown (calls through `t.registry` included). */
|
|
181
|
-
async function settle<T>(state: Open<S, Mods, Cf>, work: () => Promise<T>): Promise<T> {
|
|
182
|
-
let out: T;
|
|
183
|
-
try {
|
|
184
|
-
out = await work();
|
|
185
|
-
} catch (e) {
|
|
186
|
-
state.failures.length = 0; // what it threw is the failure: don't report it again on the next call
|
|
187
|
-
throw e;
|
|
188
|
-
}
|
|
189
|
-
throwFailures(state);
|
|
190
|
-
return out;
|
|
191
|
-
}
|
|
192
|
-
function throwFailures(state: Open<S, Mods, Cf>) {
|
|
193
|
-
if (!state.failures.length) return;
|
|
194
|
-
const [first] = state.failures.splice(0);
|
|
195
|
-
throw first;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
return {
|
|
199
|
-
async begin() {
|
|
200
|
-
if (open)
|
|
201
|
-
throw new Error(
|
|
202
|
-
"[logic-sdk] t.begin() ran again before t.rollback(). Roll back in afterEach, and don't run tests that share `t` at the same time (test.concurrent).",
|
|
203
|
-
);
|
|
204
|
-
const database = registryOptions.database;
|
|
205
|
-
if (!database) {
|
|
206
|
-
open = start(undefined, undefined, async () => {});
|
|
207
|
-
return;
|
|
208
|
-
}
|
|
209
|
-
if (!database.nest) throw new Error("[logic-sdk] This database adapter can't nest transactions, so tests can't roll back.");
|
|
210
|
-
// Drizzle transactions live inside a callback: park it there until rollback.
|
|
211
|
-
const opened = Promise.withResolvers<unknown>();
|
|
212
|
-
const released = Promise.withResolvers<void>();
|
|
213
|
-
const done = database
|
|
214
|
-
.transaction(async (tx) => {
|
|
215
|
-
opened.resolve(tx);
|
|
216
|
-
await released.promise;
|
|
217
|
-
throw new Rollback();
|
|
218
|
-
})
|
|
219
|
-
.catch((e) => {
|
|
220
|
-
if (!(e instanceof Rollback)) throw e;
|
|
221
|
-
});
|
|
222
|
-
const tx = await Promise.race([opened.promise, done]); // `done` settles first only if the transaction failed to open
|
|
223
|
-
open = start(tx, database.nest(tx), async () => {
|
|
224
|
-
released.resolve();
|
|
225
|
-
await done;
|
|
226
|
-
});
|
|
227
|
-
},
|
|
228
|
-
/** Also throws a listener failure nothing surfaced yet (a call through `t.registry`), so the test fails. */
|
|
229
|
-
async rollback() {
|
|
230
|
-
const state = open;
|
|
231
|
-
open = undefined;
|
|
232
|
-
await state?.close();
|
|
233
|
-
if (state) throwFailures(state);
|
|
234
|
-
},
|
|
235
|
-
as: (scope) => ({
|
|
236
|
-
scope,
|
|
237
|
-
run: (fn, ...args) => {
|
|
238
|
-
const state = current();
|
|
239
|
-
return settle(state, () => state.registry.as(scope).run(fn, ...args));
|
|
240
|
-
},
|
|
241
|
-
}),
|
|
242
|
-
stub: (fn, impl) => void current().stubs.set(fn, impl),
|
|
243
|
-
get events() {
|
|
244
|
-
return current().events;
|
|
245
|
-
},
|
|
246
|
-
get db() {
|
|
247
|
-
return current().db;
|
|
248
|
-
},
|
|
249
|
-
get registry() {
|
|
250
|
-
return current().registry;
|
|
251
|
-
},
|
|
252
|
-
jobs: {
|
|
253
|
-
get queued() {
|
|
254
|
-
return current().queued;
|
|
255
|
-
},
|
|
256
|
-
get scheduled() {
|
|
257
|
-
return current().scheduled;
|
|
258
|
-
},
|
|
259
|
-
async drain({ until } = {}) {
|
|
260
|
-
const state = current();
|
|
261
|
-
const end = until === undefined ? clock() : new Date(until);
|
|
262
|
-
if (Number.isNaN(end.getTime())) throw new Error(`[logic-sdk] drain({ until }) needs a valid date (got ${String(until)}).`);
|
|
263
|
-
try {
|
|
264
|
-
for (let round = 1; ; round++) {
|
|
265
|
-
const ready = [...takeDue(state.queued, end.getTime()), ...takeDue(state.scheduled, end.getTime())];
|
|
266
|
-
if (!ready.length) return;
|
|
267
|
-
if (round > 100) throw new Error("[logic-sdk] drain() ran 100 rounds and jobs are still due: does one reschedule itself, inside `until`, more often than you meant?");
|
|
268
|
-
ready.sort((a, b) => (a.runAt ?? "").localeCompare(b.runAt ?? ""));
|
|
269
|
-
for (const job of ready) {
|
|
270
|
-
// the job runs at the time it was due, so a self-rescheduling one moves forward and its checks see that time
|
|
271
|
-
if (job.runAt) travelled = Math.max(travelled ?? 0, Date.parse(job.runAt));
|
|
272
|
-
await settle(state, () => state.registry.jobs.run(job));
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
} finally {
|
|
276
|
-
travelled = undefined;
|
|
277
|
-
}
|
|
278
|
-
},
|
|
279
|
-
perform(target: Listener<any> | Cron, ...rest: any[]) {
|
|
280
|
-
const state = current();
|
|
281
|
-
if (target.kind === "cron") {
|
|
282
|
-
const { at, attempt } = (rest[0] ?? {}) as { at?: Date | string; attempt?: number };
|
|
283
|
-
const cron = state.registry.definitions.crons.find((c) => c.cron === target);
|
|
284
|
-
if (!cron) throw new Error("[logic-sdk] t.jobs.perform got a cron that isn't registered: export it from its module.");
|
|
285
|
-
const when = at === undefined ? clock() : new Date(at);
|
|
286
|
-
if (Number.isNaN(when.getTime())) throw new Error(`[logic-sdk] t.jobs.perform({ at }) needs a valid date (got ${String(at)}).`);
|
|
287
|
-
const [job] = state.registry[INTERNAL].due(when, cron.id);
|
|
288
|
-
return settle(state, () => state.registry.jobs.run(job!, { attempt }));
|
|
289
|
-
}
|
|
290
|
-
const listener = target;
|
|
291
|
-
const [payload, { scope, attempt }] = rest as [unknown, { scope: S; attempt?: number }];
|
|
292
|
-
const registered = state.registry.definitions.listeners.find((l) => l.listener === listener);
|
|
293
|
-
if (!registered) throw new Error("[logic-sdk] t.jobs.perform got a listener that isn't registered: export it from its module.");
|
|
294
|
-
const envelope = state.registry[INTERNAL].envelope(registered.event, payload, scope);
|
|
295
|
-
return settle(state, () => state.registry.jobs.run(deliveryOf(registered, envelope), { attempt }));
|
|
296
|
-
},
|
|
297
|
-
async tick(at) {
|
|
298
|
-
const state = current();
|
|
299
|
-
const jobs = state.registry[INTERNAL].due(at === undefined ? clock() : new Date(at));
|
|
300
|
-
for (const job of jobs) await settle(state, () => state.registry.jobs.run(job));
|
|
301
|
-
return jobs.map((job) => job.cron);
|
|
302
|
-
},
|
|
303
|
-
},
|
|
304
|
-
};
|
|
305
|
-
}
|
|
1
|
+
export { createTestRegistry, type TestJobs, type TestOptions, type TestRegistry } from "./core/testing.ts";
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|