@protobase/server 0.8.1 → 0.9.0

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 (63) hide show
  1. package/dist/batch/run-batch.js +4 -2
  2. package/dist/changes/actor.js +7 -1
  3. package/dist/changes/capture-schema.js +1 -1
  4. package/dist/changes/capture-sql.js +13 -2
  5. package/dist/changes/coalesce.d.ts +4 -0
  6. package/dist/changes/coalesce.js +2 -1
  7. package/dist/changes/outbox.d.ts +14 -0
  8. package/dist/changes/outbox.js +51 -0
  9. package/dist/changes/resource-change.d.ts +2 -0
  10. package/dist/changes/resource-change.js +2 -1
  11. package/dist/create-admin.d.ts +11 -3
  12. package/dist/create-admin.js +21 -5
  13. package/dist/functions/require-env.d.ts +1 -1
  14. package/dist/index.d.ts +15 -3
  15. package/dist/index.js +15 -5
  16. package/dist/jobs/current.d.ts +10 -0
  17. package/dist/jobs/current.js +20 -0
  18. package/dist/jobs/database.js +36 -0
  19. package/dist/jobs/define-job.d.ts +8 -0
  20. package/dist/jobs/define-job.js +38 -0
  21. package/dist/jobs/drain-route.d.ts +21 -0
  22. package/dist/jobs/drain-route.js +28 -0
  23. package/dist/jobs/failed-jobs.js +67 -0
  24. package/dist/jobs/functions-sql.js +126 -0
  25. package/dist/jobs/job-types.d.ts +73 -0
  26. package/dist/jobs/options.js +44 -0
  27. package/dist/jobs/run-job.d.ts +9 -0
  28. package/dist/jobs/run-job.js +78 -0
  29. package/dist/jobs/runtime.d.ts +46 -0
  30. package/dist/jobs/runtime.js +158 -0
  31. package/dist/jobs/schedule.js +25 -0
  32. package/dist/jobs/schedules.js +41 -0
  33. package/dist/jobs/schema.d.ts +15 -0
  34. package/dist/jobs/schema.js +63 -0
  35. package/dist/project-config.d.ts +7 -2
  36. package/dist/project-config.js +24 -3
  37. package/dist/resource-source.d.ts +8 -3
  38. package/dist/resource-source.js +6 -3
  39. package/dist/types.d.ts +5 -1
  40. package/dist/webhooks/attempt.js +91 -0
  41. package/dist/webhooks/retry-schedule.js +40 -0
  42. package/dist/webhooks/route-events.js +61 -0
  43. package/dist/webhooks/standard-webhooks.d.ts +4 -0
  44. package/dist/webhooks/standard-webhooks.js +36 -0
  45. package/dist/webhooks/subscriber-view.js +76 -0
  46. package/dist/webhooks/subscription.d.ts +92 -0
  47. package/dist/webhooks/subscription.js +28 -0
  48. package/dist/webhooks/table/address-check.js +28 -0
  49. package/dist/webhooks/table/options.d.ts +23 -0
  50. package/dist/webhooks/table/options.js +14 -0
  51. package/dist/webhooks/table/owner-roles.js +23 -0
  52. package/dist/webhooks/table/plugin.d.ts +10 -0
  53. package/dist/webhooks/table/plugin.js +18 -0
  54. package/dist/webhooks/table/schema-sql.js +116 -0
  55. package/dist/webhooks/table/schema.d.ts +13 -0
  56. package/dist/webhooks/table/schema.js +44 -0
  57. package/dist/webhooks/table/table-subscriptions.js +77 -0
  58. package/dist/webhooks/table/validate-hook.js +32 -0
  59. package/dist/webhooks/table/webhook-table.js +23 -0
  60. package/dist/webhooks/test-event.js +48 -0
  61. package/dist/webhooks/webhooks.js +233 -0
  62. package/dist/write-pipeline.js +4 -2
  63. package/package.json +6 -4
@@ -0,0 +1,67 @@
1
+ import { jobsSchema } from "./schema.js";
2
+ import { f, l, resource, view } from "@protobase/schema";
3
+ //#region src/jobs/failed-jobs.ts
4
+ const admins = ({ user }) => user?.roles?.includes("admin") ?? false;
5
+ /**
6
+ * The failed jobs, over the `jobs.failed` view: the admin app lists them with their last error, and retries or deletes
7
+ * one through the view's triggers. Admins only, whatever the project's roles say.
8
+ */
9
+ const failedJobs = resource("failedJobs").table(`${jobsSchema}.failed`).fields({
10
+ id: f.uuid().readOnly().filterable(),
11
+ name: f.text().readOnly().filterable().sortable(),
12
+ error: f.text().optional().readOnly(),
13
+ attempts: f.integer().readOnly(),
14
+ failedAt: f.timestamp().readOnly().filterable().sortable(),
15
+ createdAt: f.timestamp().readOnly().sortable(),
16
+ key: f.text().optional().readOnly().filterable(),
17
+ payload: f.json().optional().readOnly(),
18
+ output: f.json().optional().readOnly(),
19
+ retry: f.boolean()
20
+ }).primaryKey((r) => r.id).access({
21
+ list: admins,
22
+ read: admins,
23
+ update: admins,
24
+ delete: admins,
25
+ create: () => false
26
+ });
27
+ const failedJobsView = view("failedJobs").names({
28
+ singular: "Failed job",
29
+ plural: "Failed jobs"
30
+ }).icon("triangle-alert").title((r) => r.name).help("Jobs that used up their attempts, or failed for good. Retry one once its cause is fixed: it gets one more attempt.").fields((r) => ({
31
+ name: r.name.label("Job"),
32
+ error: r.error.label("Last error"),
33
+ failedAt: r.failedAt.label("Failed"),
34
+ createdAt: r.createdAt.label("Enqueued"),
35
+ output: r.output.label("Error details")
36
+ })).list((r) => ({
37
+ columns: [
38
+ r.name,
39
+ r.error,
40
+ r.attempts,
41
+ r.failedAt
42
+ ],
43
+ sort: [[r.failedAt, "desc"]]
44
+ })).layout((r) => [
45
+ l.section("Failure", [r.error, r.output]),
46
+ l.section("Job", [
47
+ r.name,
48
+ r.key,
49
+ r.payload
50
+ ]),
51
+ l.sidebar([
52
+ r.attempts,
53
+ r.failedAt,
54
+ r.createdAt
55
+ ])
56
+ ]).actions((a) => [a.update("retry", {
57
+ label: "Retry",
58
+ icon: "rotate-ccw",
59
+ set: { retry: true },
60
+ confirm: "Run this job once more, from now?"
61
+ }), a.remove("delete", {
62
+ label: "Delete",
63
+ icon: "trash-2",
64
+ confirm: "Delete this job? It will not run again."
65
+ })]);
66
+ //#endregion
67
+ export { failedJobs, failedJobsView };
@@ -0,0 +1,126 @@
1
+ /** The comment each Protobase function in the jobs schema carries, which the startup check reads. */
2
+ const functionsComment = `Protobase jobs 2`;
3
+ /** Protobase's own functions beside pg-boss's tables, by name; each carries `functionsComment`. */
4
+ const functionNames = [
5
+ "enqueue",
6
+ "next_due",
7
+ "failed_retry",
8
+ "failed_delete"
9
+ ];
10
+ /**
11
+ * `jobs.enqueue(name, payload, run_at, key, group_key, priority)`: a job from SQL, such as a trigger, in the caller's
12
+ * transaction. It inserts what pg-boss's `send()` does, with the queue's retry settings; it creates a queue that no
13
+ * worker has created yet. A `key` keeps one waiting job, as `mode: 'dedupe'` does, and an ordered job takes its group
14
+ * as `group_key`. Tied to the pg-boss schema version, which the startup check pins.
15
+ */
16
+ const enqueue = (schema) => `create or replace function ${schema}.enqueue(
17
+ job_name text,
18
+ payload jsonb default null,
19
+ run_at timestamptz default null,
20
+ key text default null,
21
+ group_key text default null,
22
+ priority integer default 0
23
+ ) returns uuid
24
+ language plpgsql as $$
25
+ declare
26
+ queue ${schema}.queue;
27
+ start timestamptz := coalesce(run_at, ${schema}.job_now());
28
+ job_id uuid;
29
+ begin
30
+ if key is not null and group_key is not null then
31
+ raise exception 'Job "%": an ordered job takes a group_key and no key', job_name;
32
+ end if;
33
+ perform ${schema}.create_queue(job_name, jsonb_build_object('policy', case when group_key is null then 'standard' else 'key_strict_fifo' end));
34
+ select * into queue from ${schema}.queue where name = job_name;
35
+ if (queue.policy = 'key_strict_fifo') <> (group_key is not null) then
36
+ raise exception 'Job "%" %', job_name, case when group_key is null then 'is ordered: pass its group_key' else 'is not ordered: it takes no group_key' end;
37
+ end if;
38
+ if key is not null then
39
+ select id into job_id from ${schema}.job
40
+ where name = job_name and singleton_key = key and state < 'active'
41
+ order by created_on desc limit 1;
42
+ if found then
43
+ return job_id;
44
+ end if;
45
+ end if;
46
+ execute format(
47
+ 'insert into ${schema}.%I (name, data, priority, start_after, singleton_key, retry_limit, retry_delay, retry_backoff,
48
+ retry_delay_max, expire_seconds, deletion_seconds, keep_until, policy, dead_letter, heartbeat_seconds, upsert_by_key)
49
+ values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $4 + $12 * interval ''1s'', $13, $14, $15, $16)
50
+ on conflict do nothing
51
+ returning id',
52
+ queue.table_name)
53
+ using job_name, payload, priority, start, coalesce(key, group_key), queue.retry_limit, queue.retry_delay,
54
+ queue.retry_backoff, queue.retry_delay_max, queue.expire_seconds, queue.deletion_seconds, queue.retention_seconds,
55
+ queue.policy, queue.dead_letter, queue.heartbeat_seconds, key is not null
56
+ into job_id;
57
+ -- A concurrent enqueue of the same key inserted first: its job is the one waiting.
58
+ if job_id is null and key is not null then
59
+ select id into job_id from ${schema}.job
60
+ where name = job_name and singleton_key = key and state < 'active'
61
+ order by created_on desc limit 1;
62
+ end if;
63
+ return job_id;
64
+ end
65
+ $$;
66
+ comment on function ${schema}.enqueue(text, jsonb, timestamptz, text, text, integer) is '${functionsComment}';`;
67
+ /**
68
+ * `jobs.next_due()`: when the next job is due, or `null` when none waits: what a host that sleeps reads to know when to
69
+ * wake the app, through any pooler. A waiting job counts from its start time, unless a failed job holds back its ordered
70
+ * group; a running one from when its try times out, since its worker may have died with the app. Recurring jobs wait
71
+ * as their next run, so they count too.
72
+ */
73
+ const nextDue = (schema) => `create or replace function ${schema}.next_due() returns timestamptz
74
+ language sql stable as $$
75
+ select min(due) from (
76
+ select j.start_after as due from ${schema}.job j
77
+ where j.state < 'active' and not j.blocked
78
+ and not (j.policy = 'key_strict_fifo' and exists (
79
+ select 1 from ${schema}.job h where h.name = j.name and h.singleton_key = j.singleton_key and h.state = 'failed'))
80
+ union all
81
+ select started_on + expire_seconds * interval '1s' from ${schema}.job where state = 'active'
82
+ ) jobs
83
+ $$;
84
+ comment on function ${schema}.next_due() is '${functionsComment}';`;
85
+ /**
86
+ * `jobs.failed`: the failed jobs, for the admin app's page, with their last error. Updating `retry` to true retries a
87
+ * job, as pg-boss's `retry()` does: one more attempt, from now; deleting a row deletes the job.
88
+ */
89
+ const failed = (schema) => `create index if not exists job_failed_i on ${schema}.job (completed_on) where state = 'failed';
90
+ drop view if exists ${schema}.failed;
91
+ create view ${schema}.failed as
92
+ select id, name, data as payload, retry_count + 1 as attempts,
93
+ coalesce(output ->> 'message', output -> 'value' ->> 'message', output ->> 'value') as error,
94
+ output, completed_on as failed_at, created_on as created_at, singleton_key as key, false as retry
95
+ from ${schema}.job where state = 'failed';
96
+ create or replace function ${schema}.failed_retry() returns trigger
97
+ language plpgsql as $$
98
+ begin
99
+ if new.retry then
100
+ update ${schema}.job
101
+ set state = 'retry', retry_limit = retry_limit + 1, completed_on = null,
102
+ start_after = greatest(start_after, ${schema}.job_now()), keep_until = greatest(keep_until, ${schema}.job_now() + interval '14 days')
103
+ where name = old.name and id = old.id and state = 'failed';
104
+ end if;
105
+ return new;
106
+ end
107
+ $$;
108
+ comment on function ${schema}.failed_retry() is '${functionsComment}';
109
+ create or replace function ${schema}.failed_delete() returns trigger
110
+ language plpgsql as $$
111
+ begin
112
+ delete from ${schema}.job where name = old.name and id = old.id and state = 'failed';
113
+ return old;
114
+ end
115
+ $$;
116
+ comment on function ${schema}.failed_delete() is '${functionsComment}';
117
+ create trigger failed_retry instead of update on ${schema}.failed for each row execute function ${schema}.failed_retry();
118
+ create trigger failed_delete instead of delete on ${schema}.failed for each row execute function ${schema}.failed_delete();`;
119
+ /** The statements that create or replace every Protobase object in `schema`. */
120
+ const functionsSql = (schema) => [
121
+ enqueue(schema),
122
+ nextDue(schema),
123
+ failed(schema)
124
+ ].join("\n\n");
125
+ //#endregion
126
+ export { functionNames, functionsComment, functionsSql };
@@ -0,0 +1,73 @@
1
+ import { StandardSchema } from "../functions/read-json.js";
2
+ import { Db } from "@protobase/query";
3
+ //#region src/jobs/job-types.d.ts
4
+ /** What `run` gets beside the payload. */
5
+ export type JobContext = {
6
+ /** The database pool. The enqueuer's transaction has committed by the time a job runs. */
7
+ db: Db;
8
+ job: {
9
+ id: string;
10
+ name: string;
11
+ attempt: number;
12
+ maxAttempts: number;
13
+ };
14
+ /** Aborted when the job's timeout passes, or when the worker shuts down and its grace period ends. */
15
+ signal: AbortSignal;
16
+ };
17
+ export type JobOptions<Payload> = {
18
+ /** Letters, digits, `_`, `-`, `.` and `/`; the job's queue in the `jobs` schema. */
19
+ name: string;
20
+ /** Checks the payload when it is enqueued and again before it runs, such as a zod schema. */
21
+ payload?: StandardSchema<Payload>;
22
+ run: (payload: Payload, context: JobContext) => Promise<void> | void;
23
+ /** Tries before the job is kept as failed, listed in the admin app. Default 10. */
24
+ maxAttempts?: number;
25
+ /** The wait before the first retry, doubling with each one: milliseconds or text such as `30 seconds`. Default `2s`. */
26
+ retryDelay?: number | string;
27
+ /** The longest wait between two tries. Default `1 hour`. */
28
+ maxRetryDelay?: number | string;
29
+ /** How long one try may run before it counts as failed. Default `15 minutes`. */
30
+ timeout?: number | string;
31
+ /** Jobs of this name running at once in each worker process. Default 1. */
32
+ concurrency?: number;
33
+ /**
34
+ * Jobs run one at a time per group, in the order they were enqueued, and every enqueue names its group. A job that is
35
+ * retrying or failed holds back the rest of its group until it succeeds, or is retried or deleted in the admin app.
36
+ */
37
+ ordered?: boolean;
38
+ /**
39
+ * Runs the job on this cron schedule, such as `0 7 * * *` (with an optional seconds field first), with no payload: one
40
+ * run per time, however many workers run. A run missed while no worker ran happens once, as soon as one does.
41
+ */
42
+ schedule?: string;
43
+ /** The time zone `schedule` is read in, such as `Europe/Amsterdam`. Default `UTC`. */
44
+ timezone?: string;
45
+ };
46
+ /** Where and how one enqueue lands; a job runs as soon as possible by default. */
47
+ export type EnqueueOptions = {
48
+ /** When the job may run first. */
49
+ runAt?: Date;
50
+ /** How long from now before the job may run first: milliseconds or text such as `5 minutes`. */
51
+ delay?: number | string;
52
+ /**
53
+ * Keeps one waiting job per key; a running job does not count. With `mode: 'dedupe'` (the default) an enqueue while
54
+ * one waits leaves it as it is, with `'replace'` it takes this payload and these options. Not for ordered jobs.
55
+ */
56
+ key?: string;
57
+ mode?: 'dedupe' | 'replace';
58
+ /** The group of an ordered job; required there, refused elsewhere. */
59
+ group?: string;
60
+ /** Higher runs first. Default 0. */
61
+ priority?: number;
62
+ };
63
+ export type JobDefinition<Payload = any> = {
64
+ readonly kind: 'job';
65
+ readonly name: string;
66
+ readonly options: JobOptions<Payload>;
67
+ /**
68
+ * Adds a job and returns its id: in `db`'s own transaction when it is one, so the job commits with the caller's
69
+ * writes or not at all. With a `key` it returns the waiting job's id when that one is kept.
70
+ */
71
+ enqueue(db: Db, ...args: Payload extends undefined ? [payload?: Payload, options?: EnqueueOptions] : [payload: Payload, options?: EnqueueOptions]): Promise<string>;
72
+ };
73
+ //#endregion
@@ -0,0 +1,44 @@
1
+ import { parseDuration } from "../files/duration.js";
2
+ //#region src/jobs/options.ts
3
+ /** pg-boss counts in whole seconds; a duration rounds up, so a wait is never shorter than asked. */
4
+ const seconds = (value, label) => Math.ceil(parseDuration(value, label) / 1e3);
5
+ const positive = (value, label) => {
6
+ if (!Number.isSafeInteger(value) || value < 1) throw new Error(`${label} must be a whole number of at least 1, not ${value}`);
7
+ return value;
8
+ };
9
+ /** The pg-boss queue a job definition runs in: its policy, retries with backoff and timeout. */
10
+ const queueOptions = (options) => {
11
+ const label = `Job "${options.name}"`;
12
+ return {
13
+ policy: options.ordered ? "key_strict_fifo" : "standard",
14
+ retryLimit: positive(options.maxAttempts ?? 10, `${label} maxAttempts`) - 1,
15
+ retryDelay: positive(seconds(options.retryDelay ?? "2s", `${label} retryDelay`), `${label} retryDelay in seconds`),
16
+ retryBackoff: true,
17
+ retryDelayMax: positive(seconds(options.maxRetryDelay ?? "1 hour", `${label} maxRetryDelay`), `${label} maxRetryDelay in seconds`),
18
+ expireInSeconds: positive(seconds(options.timeout ?? "15 minutes", `${label} timeout`), `${label} timeout in seconds`)
19
+ };
20
+ };
21
+ /** The queue settings `queueOptions` sets, as `getQueue` reads them back, so a changed definition is noticed. */
22
+ const queueSettingsDiffer = (wanted, stored) => Object.keys(wanted).some((key) => key !== "policy" && stored[key] !== wanted[key]);
23
+ /**
24
+ * The pg-boss send options of one enqueue: when, how urgent, and the key a waiting job is found by. An ordered job's
25
+ * group is its key in pg-boss, which keeps one group's jobs in order.
26
+ */
27
+ const sendOptions = (options, enqueue = {}) => {
28
+ const label = `Job "${options.name}"`;
29
+ if (enqueue.runAt && enqueue.delay !== void 0) throw new Error(`${label}: pass runAt or delay, not both`);
30
+ if (options.ordered && enqueue.group === void 0) throw new Error(`${label} is ordered: name the group each job runs in with { group }`);
31
+ if (options.ordered && enqueue.key !== void 0) throw new Error(`${label} is ordered: its jobs are found by their group, so it takes no key`);
32
+ if (!options.ordered && enqueue.group !== void 0) throw new Error(`${label} is not ordered: a group needs ordered: true in defineJob`);
33
+ if (enqueue.mode && enqueue.key === void 0) throw new Error(`${label}: mode needs a key`);
34
+ if (enqueue.priority !== void 0 && !Number.isSafeInteger(enqueue.priority)) throw new Error(`${label}: priority must be a whole number`);
35
+ const startAfter = enqueue.runAt ?? (enqueue.delay === void 0 ? void 0 : seconds(enqueue.delay, `${label} delay`));
36
+ const singletonKey = options.ordered ? enqueue.group : enqueue.key;
37
+ return {
38
+ ...startAfter !== void 0 && { startAfter },
39
+ ...enqueue.priority !== void 0 && { priority: enqueue.priority },
40
+ ...singletonKey !== void 0 && { singletonKey }
41
+ };
42
+ };
43
+ //#endregion
44
+ export { queueOptions, queueSettingsDiffer, sendOptions };
@@ -0,0 +1,9 @@
1
+ import "./job-types.js";
2
+ import { Db } from "@protobase/query";
3
+ import "pg-boss";
4
+ //#region src/jobs/run-job.d.ts
5
+ /** Thrown from a job's `run`, it fails the job now: the attempts it has left are not used. */
6
+ export declare class FatalJobError extends Error {
7
+ name: string;
8
+ }
9
+ //#endregion
@@ -0,0 +1,78 @@
1
+ //#region src/jobs/run-job.ts
2
+ /** Thrown from a job's `run`, it fails the job now: the attempts it has left are not used. */
3
+ var FatalJobError = class extends Error {
4
+ name = "FatalJobError";
5
+ };
6
+ /** The payload as the job's `payload` schema returns it, or why it does not pass. */
7
+ const validatePayload = async (definition, payload) => {
8
+ const schema = definition.options.payload;
9
+ if (!schema) return { value: payload };
10
+ const result = await schema["~standard"].validate(payload);
11
+ if (!result.issues) return { value: result.value };
12
+ const issues = result.issues.map((issue) => {
13
+ const field = (issue.path ?? []).map((part) => String(typeof part === "object" ? part.key : part)).join(".");
14
+ return field ? `${field}: ${issue.message}` : issue.message;
15
+ });
16
+ return { invalid: `Job "${definition.name}" has an invalid payload: ${issues.join("; ")}` };
17
+ };
18
+ const checkPayload = async (definition, payload) => {
19
+ const checked = await validatePayload(definition, payload);
20
+ if ("invalid" in checked) throw new FatalJobError(checked.invalid);
21
+ return checked.value;
22
+ };
23
+ const readOnly = (error) => error?.code === "25006";
24
+ const pause = (ms, signal) => new Promise((resolve) => {
25
+ if (signal.aborted) return resolve();
26
+ const timer = setTimeout(resolve, ms);
27
+ signal.addEventListener("abort", () => {
28
+ clearTimeout(timer);
29
+ resolve();
30
+ }, { once: true });
31
+ });
32
+ /** Runs `run` again every `waitMs` while the database is read-only, until the signal ends the try. */
33
+ const throughWriteFreeze = async (run, signal, waitMs = 5e3) => {
34
+ for (;;) try {
35
+ return await run();
36
+ } catch (error) {
37
+ if (!readOnly(error) || signal.aborted) throw error;
38
+ await pause(waitMs, signal);
39
+ }
40
+ };
41
+ /** What a failed try keeps as the job's output, which the admin app shows as its last error. */
42
+ const errorOutput = (error) => error instanceof Error ? {
43
+ name: error.name,
44
+ message: error.message,
45
+ ...error.stack && { stack: error.stack }
46
+ } : { message: String(error) };
47
+ /**
48
+ * One try of one job: completed when `run` returns, failed (to be retried while attempts are left) when it throws, and
49
+ * failed for good on a `FatalJobError` or an invalid payload.
50
+ */
51
+ const runJob = async (definition, job, db) => {
52
+ try {
53
+ const payload = await checkPayload(definition, job.data ?? void 0);
54
+ const context = {
55
+ db,
56
+ job: {
57
+ id: job.id,
58
+ name: job.name,
59
+ attempt: job.retryCount + 1,
60
+ maxAttempts: job.retryLimit + 1
61
+ },
62
+ signal: job.signal
63
+ };
64
+ await throughWriteFreeze(() => definition.options.run(payload, context), job.signal);
65
+ return {
66
+ id: job.id,
67
+ status: "completed"
68
+ };
69
+ } catch (error) {
70
+ return {
71
+ id: job.id,
72
+ status: error instanceof FatalJobError ? "deadletter" : "failed",
73
+ output: errorOutput(error)
74
+ };
75
+ }
76
+ };
77
+ //#endregion
78
+ export { FatalJobError, runJob, throughWriteFreeze, validatePayload };
@@ -0,0 +1,46 @@
1
+ import { JobDefinition } from "./job-types.js";
2
+ import { JobsEnqueuer } from "./current.js";
3
+ import { Db } from "@protobase/query";
4
+ //#region src/jobs/runtime.d.ts
5
+ export type StartJobsOptions = {
6
+ db: Db;
7
+ jobs: JobDefinition[];
8
+ /** Runs the jobs in this process; `false` only enqueues them, for a process whose jobs another one runs. Default true. */
9
+ work?: boolean;
10
+ /** Seconds between a worker's checks for due jobs; an enqueue outside a transaction wakes this process's worker at once. Default 2. */
11
+ pollSeconds?: number;
12
+ /** Seconds running jobs get to finish when the jobs stop, before they are failed and retried later. Default 30. */
13
+ shutdownSeconds?: number;
14
+ /** Gets every error the workers and the queue maintenance meet outside a job's own `run`. */
15
+ onError: (error: unknown) => void;
16
+ /** The time recurring jobs are scheduled from; tests pass their own. */
17
+ now?: () => Date;
18
+ };
19
+ /** What a drain left: whether no job is due or running any more, how many are, and when the next one is due. */
20
+ export type DrainResult = {
21
+ drained: boolean;
22
+ remaining: number;
23
+ nextDue: Date | null;
24
+ };
25
+ export type JobsRuntime = JobsEnqueuer & {
26
+ /** Whether this process runs the jobs, or only enqueues them. */
27
+ readonly works: boolean;
28
+ /** Takes the project's jobs again, as `protobase dev` does when their files change. */
29
+ update(jobs: JobDefinition[]): Promise<void>;
30
+ /**
31
+ * Runs the jobs that are due until none is due or running, or `seconds` have passed: for a host that wakes a sleeping
32
+ * app to run its jobs. Needs this process to run jobs.
33
+ */
34
+ drain(seconds: number): Promise<DrainResult>;
35
+ /** When the next job is due, or `null` when none waits (`jobs.next_due()`). */
36
+ nextDue(): Promise<Date | null>;
37
+ /** Stops taking jobs, lets running ones finish within `shutdownSeconds`, then fails and releases the rest. */
38
+ stop(): Promise<void>;
39
+ };
40
+ /**
41
+ * Starts the app's jobs in this process: their queues, a worker per job unless `work` is false, and the maintenance
42
+ * that retries jobs whose worker died. It reads the jobs schema, never changes it: check it first with
43
+ * `checkJobsSchema`. Enqueueing through `defineJob(...).enqueue` reaches the runtime started here.
44
+ */
45
+ export declare const startJobs: ({ db, jobs, work, pollSeconds, shutdownSeconds, onError, now }: StartJobsOptions) => Promise<JobsRuntime>;
46
+ //#endregion
@@ -0,0 +1,158 @@
1
+ import { clearCurrentJobs, setCurrentJobs } from "./current.js";
2
+ import { jobsSchema } from "./schema.js";
3
+ import "./schedule.js";
4
+ import { runJob, validatePayload } from "./run-job.js";
5
+ import { jobsDatabase } from "./database.js";
6
+ import { queueOptions, queueSettingsDiffer, sendOptions } from "./options.js";
7
+ import { createSchedules } from "./schedules.js";
8
+ import { sql } from "kysely";
9
+ import { PgBoss } from "pg-boss";
10
+ //#region src/jobs/runtime.ts
11
+ const createBoss = (db, work) => new PgBoss({
12
+ db: jobsDatabase(db),
13
+ schema: jobsSchema,
14
+ migrate: false,
15
+ createSchema: false,
16
+ schedule: false,
17
+ supervise: work,
18
+ registerInstance: false,
19
+ reindex: false,
20
+ monitorVacuum: false,
21
+ useListenNotify: false
22
+ });
23
+ /**
24
+ * Starts the app's jobs in this process: their queues, a worker per job unless `work` is false, and the maintenance
25
+ * that retries jobs whose worker died. It reads the jobs schema, never changes it: check it first with
26
+ * `checkJobsSchema`. Enqueueing through `defineJob(...).enqueue` reaches the runtime started here.
27
+ */
28
+ const startJobs = async ({ db, jobs, work = true, pollSeconds = 2, shutdownSeconds = 30, onError, now = () => /* @__PURE__ */ new Date() }) => {
29
+ const boss = createBoss(db, work);
30
+ boss.on("error", onError);
31
+ await boss.start();
32
+ const schedules = createSchedules(boss, db, now);
33
+ const definitions = /* @__PURE__ */ new Map();
34
+ const workers = /* @__PURE__ */ new Map();
35
+ const ensureQueue = async (definition) => {
36
+ const wanted = queueOptions(definition.options);
37
+ const queue = await boss.getQueue(definition.name);
38
+ if (!queue) return boss.createQueue(definition.name, wanted);
39
+ if (queue.policy !== wanted.policy) throw new Error(`Job "${definition.name}" ${definition.options.ordered ? "became" : "is no longer"} ordered, but its queue keeps the old order. Let its jobs finish or delete them, drop the queue with \`select ${jobsSchema}.delete_queue('${definition.name}')\`, then start again.`);
40
+ if (queueSettingsDiffer(wanted, queue)) {
41
+ const { policy, ...settings } = wanted;
42
+ await boss.updateQueue(definition.name, settings);
43
+ }
44
+ };
45
+ const startWorker = async (definition) => {
46
+ const concurrency = definition.options.concurrency ?? 1;
47
+ const running = workers.get(definition.name);
48
+ if (running?.concurrency === concurrency) return;
49
+ if (running) await boss.offWork(definition.name);
50
+ const id = await boss.work(definition.name, {
51
+ batchSize: 1,
52
+ localConcurrency: concurrency,
53
+ pollingIntervalSeconds: pollSeconds,
54
+ includeMetadata: true,
55
+ perJobResults: true
56
+ }, async ([job]) => {
57
+ const current = definitions.get(definition.name) ?? definition;
58
+ if (current.options.schedule !== void 0 && job.singletonKey === "protobase.schedule") await schedules.following(current, job.startAfter);
59
+ return [await runJob(current, job, db)];
60
+ });
61
+ workers.set(definition.name, {
62
+ id,
63
+ concurrency
64
+ });
65
+ };
66
+ const update = async (next) => {
67
+ for (const definition of next) await ensureQueue(definition);
68
+ for (const name of definitions.keys()) {
69
+ if (next.some((definition) => definition.name === name)) continue;
70
+ definitions.delete(name);
71
+ if (workers.delete(name)) await boss.offWork(name);
72
+ }
73
+ for (const definition of next) definitions.set(definition.name, definition);
74
+ if (!work) return;
75
+ for (const definition of next) await startWorker(definition);
76
+ await schedules.sync(next);
77
+ };
78
+ const enqueue = async (definition, target, payload, options = {}) => {
79
+ const { name } = definition;
80
+ if (!definitions.has(name)) throw new Error(`Job "${name}" is not among the app's jobs; export it from the module protobase.config.ts passes as \`jobs\``);
81
+ const checked = await validatePayload(definition, payload);
82
+ if ("invalid" in checked) throw new Error(checked.invalid);
83
+ const data = checked.value ?? null;
84
+ const send = {
85
+ ...sendOptions(definition.options, options),
86
+ db: jobsDatabase(target)
87
+ };
88
+ const keyed = async (key) => {
89
+ if (options.mode !== "replace") {
90
+ const [waiting] = await boss.findJobs(name, {
91
+ key,
92
+ queued: true,
93
+ db: send.db
94
+ });
95
+ if (waiting) return waiting.id;
96
+ }
97
+ return (await boss.upsert(name, data, send)).jobs[0];
98
+ };
99
+ const id = options.key === void 0 ? await boss.send(name, data, send) : await keyed(options.key);
100
+ if (!id) throw new Error(`Job "${name}" was not enqueued`);
101
+ if (!target.isTransaction) wake(name);
102
+ return id;
103
+ };
104
+ const nextDue = async () => (await sql`select ${sql.id(jobsSchema, "next_due")}() as due`.execute(db)).rows[0].due;
105
+ const pending = async () => {
106
+ const job = sql.id(jobsSchema, "job");
107
+ const { rows } = await sql`
108
+ select count(*)::int as count from ${job} j where j.name = any(${[...definitions.keys()]}::text[]) and (
109
+ (j.state < 'active' and not j.blocked and j.start_after <= now()
110
+ and not (j.policy = 'key_strict_fifo' and exists (
111
+ select 1 from ${job} h where h.name = j.name and h.singleton_key = j.singleton_key and h.state = 'failed')))
112
+ or (j.state = 'active' and j.started_on + j.expire_seconds * interval '1s' > now()))`.execute(db);
113
+ return rows[0].count;
114
+ };
115
+ const drain = async (seconds) => {
116
+ if (!work) throw new Error("This process runs no jobs, so it cannot drain them");
117
+ const deadline = Date.now() + seconds * 1e3;
118
+ for (;;) {
119
+ for (const worker of workers.values()) boss.notifyWorker(worker.id);
120
+ const remaining = await pending();
121
+ if (remaining === 0 || Date.now() >= deadline) return {
122
+ drained: remaining === 0,
123
+ remaining,
124
+ nextDue: await nextDue()
125
+ };
126
+ await new Promise((resolve) => setTimeout(resolve, 100));
127
+ }
128
+ };
129
+ const wake = (name) => {
130
+ const worker = workers.get(name);
131
+ if (worker) boss.notifyWorker(worker.id);
132
+ };
133
+ const runtime = {
134
+ works: work,
135
+ enqueue,
136
+ wake,
137
+ update,
138
+ drain,
139
+ nextDue,
140
+ stop: async () => {
141
+ await boss.stop({
142
+ graceful: true,
143
+ timeout: shutdownSeconds * 1e3
144
+ });
145
+ clearCurrentJobs(runtime);
146
+ }
147
+ };
148
+ try {
149
+ await update(jobs);
150
+ setCurrentJobs(runtime);
151
+ } catch (error) {
152
+ await boss.stop({ graceful: false });
153
+ throw error;
154
+ }
155
+ return runtime;
156
+ };
157
+ //#endregion
158
+ export { startJobs };
@@ -0,0 +1,25 @@
1
+ import { createHash } from "node:crypto";
2
+ import { CronExpressionParser } from "cron-parser";
3
+ //#region src/jobs/schedule.ts
4
+ /**
5
+ * The key every run of a recurring job waits under. Each run is a job of its own, enqueued for its time: it is what
6
+ * `jobs.next_due()` sees while the app sleeps, so a host that wakes the app for due jobs wakes it for these too.
7
+ */
8
+ const scheduleKey = "protobase.schedule";
9
+ /** The first run of `schedule` strictly after `after`, in `timezone`; throws on an expression cron-parser refuses. */
10
+ const nextRun = (schedule, timezone, after) => CronExpressionParser.parse(schedule, {
11
+ currentDate: after,
12
+ tz: timezone
13
+ }).next().toDate();
14
+ /** Whether `at` is a run of `schedule`, so a run left from an earlier schedule can be told apart. */
15
+ const isRun = (schedule, timezone, at) => nextRun(schedule, timezone, /* @__PURE__ */ new Date(at.getTime() - 1)).getTime() === at.getTime();
16
+ /**
17
+ * The id of the run of job `name` at `at`: the same in every process, so however many workers enqueue a run, the
18
+ * database keeps one (its primary key), and the run happens once.
19
+ */
20
+ const runId = (name, at) => {
21
+ const hex = createHash("sha256").update(`${name}@${at.toISOString()}`).digest("hex");
22
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-8${hex.slice(13, 16)}-${(parseInt(hex[16], 16) & 3 | 8).toString(16)}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
23
+ };
24
+ //#endregion
25
+ export { isRun, nextRun, runId, scheduleKey };
@@ -0,0 +1,41 @@
1
+ import { jobsSchema } from "./schema.js";
2
+ import { isRun, nextRun, runId, scheduleKey } from "./schedule.js";
3
+ import { jobsDatabase } from "./database.js";
4
+ import { sql } from "kysely";
5
+ //#region src/jobs/schedules.ts
6
+ const job = sql.id(jobsSchema, "job");
7
+ /** The recurring jobs' runs: enqueued ahead, one per time, and kept in step with their schedules. */
8
+ const createSchedules = (boss, db, now) => {
9
+ const timezone = (definition) => definition.options.timezone ?? "UTC";
10
+ const enqueueRun = (definition, at) => boss.send(definition.name, null, {
11
+ id: runId(definition.name, at),
12
+ startAfter: at,
13
+ singletonKey: scheduleKey,
14
+ db: jobsDatabase(db)
15
+ });
16
+ /**
17
+ * Makes the waiting runs match `definitions`: drops those of jobs without a schedule now, and those at a time the
18
+ * schedule no longer has, then enqueues each schedule's next run. A run that is due stays, to run as soon as it can.
19
+ */
20
+ const sync = async (definitions) => {
21
+ const scheduled = definitions.filter((definition) => definition.options.schedule !== void 0);
22
+ await sql`delete from ${job} where singleton_key = ${scheduleKey} and state < 'active' and not (name = any(${scheduled.map(({ name }) => name)}::text[]))`.execute(db);
23
+ for (const definition of scheduled) {
24
+ const stale = (await sql`
25
+ select id, start_after from ${job} where name = ${definition.name} and singleton_key = ${scheduleKey} and state < 'active'`.execute(db)).rows.filter((run) => !isRun(definition.options.schedule, timezone(definition), new Date(run.start_after))).map((run) => run.id);
26
+ if (stale.length > 0) await sql`delete from ${job} where name = ${definition.name} and id = any(${stale}::uuid[])`.execute(db);
27
+ await enqueueRun(definition, nextRun(definition.options.schedule, timezone(definition), now()));
28
+ }
29
+ };
30
+ /** As a run starts, the one after it: from its own time, or from now when it ran late, so missed times are skipped. */
31
+ const following = async (definition, ranAt) => {
32
+ const from = new Date(Math.max(ranAt.getTime(), now().getTime()));
33
+ await enqueueRun(definition, nextRun(definition.options.schedule, timezone(definition), from));
34
+ };
35
+ return {
36
+ sync,
37
+ following
38
+ };
39
+ };
40
+ //#endregion
41
+ export { createSchedules };