@brickkit/core 0.13.3 → 0.14.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.
@@ -6,7 +6,7 @@ import { TypeCompiler } from "@sinclair/typebox/compiler";
6
6
  import { formatWithOptions } from "node:util";
7
7
  import { join, resolve } from "node:path";
8
8
  import { fileURLToPath, pathToFileURL } from "node:url";
9
- import { and, asc, eq, inArray, lt, lte, or, sql } from "drizzle-orm";
9
+ import { and, asc, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
10
10
  import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
11
11
  import { bigserial, index as index$1, integer as integer$1, jsonb, pgTable, text as text$1, timestamp } from "drizzle-orm/pg-core";
12
12
  import { existsSync, readFileSync } from "node:fs";
@@ -1631,6 +1631,19 @@ var WorkflowRuntime = class {
1631
1631
  });
1632
1632
  }
1633
1633
  /**
1634
+ * Start the workflow of a schedule's run. The workflow run is named after
1635
+ * the run key, so a run that is tried again does not start another.
1636
+ */
1637
+ async startScheduled(schedule, run) {
1638
+ const sdk = await this.ensure();
1639
+ const { attempt: _attempt, ...workflowRun } = run;
1640
+ await sdk.start(schedule.workflow, [workflowRun], {
1641
+ world: this.world,
1642
+ runKey: `schedule:${run.runKey}`,
1643
+ runKeyTime: Date.parse(run.slot)
1644
+ });
1645
+ }
1646
+ /**
1634
1647
  * Answer a request to a webhook a workflow created with `createWebhook`, by
1635
1648
  * resuming the workflow that waits on it. Needs the world but not the queue
1636
1649
  * consumer, so a process that only records events (`dispatch: false`) serves
@@ -3039,6 +3052,609 @@ var Dispatcher = class {
3039
3052
  await this.db.delete(t).where(and(eq(t.status, "delivered"), lt(t.deliveredAt, new Date(now - keep))));
3040
3053
  }
3041
3054
  };
3055
+ // src/schedules/cron.ts
3056
+ const MACROS = {
3057
+ "@yearly": "0 0 1 1 *",
3058
+ "@annually": "0 0 1 1 *",
3059
+ "@monthly": "0 0 1 * *",
3060
+ "@weekly": "0 0 * * 0",
3061
+ "@daily": "0 0 * * *",
3062
+ "@midnight": "0 0 * * *",
3063
+ "@hourly": "0 * * * *"
3064
+ };
3065
+ const MONTH_NAMES = "jan feb mar apr may jun jul aug sep oct nov dec".split(" ");
3066
+ const DAY_NAMES = "sun mon tue wed thu fri sat".split(" ");
3067
+ function parseField(field, min, max, names = [], nameBase = 0) {
3068
+ const value = (text) => {
3069
+ const named = names.indexOf(text.toLowerCase());
3070
+ if (named >= 0) return named + nameBase;
3071
+ if (!/^\d+$/.test(text)) throw new Error(`'${text}' is not a number`);
3072
+ const number = Number(text);
3073
+ if (number < min || number > max) throw new Error(`${number} is outside ${min}-${max}`);
3074
+ return number;
3075
+ };
3076
+ const values = /* @__PURE__ */ new Set();
3077
+ for (const part of field.split(",")) {
3078
+ const [range, stepText, extra] = part.split("/");
3079
+ if (extra !== void 0 || !range) throw new Error(`'${part}' is not a valid field`);
3080
+ const step = stepText === void 0 ? 1 : Number(stepText);
3081
+ if (!Number.isInteger(step) || step < 1) throw new Error(`'${stepText}' is not a valid step`);
3082
+ let from;
3083
+ let to;
3084
+ if (range === "*") [from, to] = [min, max];
3085
+ else if (range.includes("-")) {
3086
+ const [a, b, extra] = range.split("-");
3087
+ if (extra !== void 0) throw new Error(`'${range}' is not a valid range`);
3088
+ [from, to] = [value(a), value(b)];
3089
+ if (from > to) throw new Error(`'${range}' runs backwards`);
3090
+ } else {
3091
+ from = value(range);
3092
+ to = stepText === void 0 ? from : max;
3093
+ }
3094
+ for (let v = from; v <= to; v += step) values.add(v);
3095
+ }
3096
+ return {
3097
+ values,
3098
+ star: field.startsWith("*") || field.startsWith("?")
3099
+ };
3100
+ }
3101
+ /**
3102
+ * Parse a cron expression.
3103
+ *
3104
+ * @throws When the expression is malformed.
3105
+ */
3106
+ function parseCron(expression) {
3107
+ const source = expression.trim();
3108
+ const fields = (MACROS[source.toLowerCase()] ?? source).split(/\s+/);
3109
+ if (fields.length === 5) fields.unshift("0");
3110
+ if (fields.length !== 6) throw new Error(`Cron expression '${expression}' needs 5 fields (minute hour day month weekday), or 6 with seconds first`);
3111
+ const [sec, min, hour, day, month, weekday] = fields;
3112
+ try {
3113
+ const days = parseField(day.replace("?", "*"), 1, 31);
3114
+ const weekdays = parseField(weekday.replace("?", "*"), 0, 7, DAY_NAMES);
3115
+ if (weekdays.values.delete(7)) weekdays.values.add(0);
3116
+ return {
3117
+ source,
3118
+ seconds: parseField(sec, 0, 59).values,
3119
+ minutes: parseField(min, 0, 59).values,
3120
+ hours: parseField(hour, 0, 23).values,
3121
+ days: days.values,
3122
+ months: parseField(month, 1, 12, MONTH_NAMES, 1).values,
3123
+ weekdays: weekdays.values,
3124
+ eitherDay: !days.star && !weekdays.star
3125
+ };
3126
+ } catch (error) {
3127
+ throw new Error(`Cron expression '${expression}': ${error.message}`);
3128
+ }
3129
+ }
3130
+ const formatters = /* @__PURE__ */ new Map();
3131
+ /**
3132
+ * @throws When `timeZone` is not an IANA time zone this runtime knows.
3133
+ */
3134
+ function checkTimeZone(timeZone) {
3135
+ formatter(timeZone);
3136
+ }
3137
+ function formatter(timeZone) {
3138
+ let found = formatters.get(timeZone);
3139
+ if (!found) {
3140
+ try {
3141
+ found = new Intl.DateTimeFormat("en-US", {
3142
+ timeZone,
3143
+ hourCycle: "h23",
3144
+ year: "numeric",
3145
+ month: "numeric",
3146
+ day: "numeric",
3147
+ hour: "numeric",
3148
+ minute: "numeric",
3149
+ second: "numeric"
3150
+ });
3151
+ } catch {
3152
+ throw new Error(`Unknown time zone '${timeZone}'`);
3153
+ }
3154
+ formatters.set(timeZone, found);
3155
+ }
3156
+ return found;
3157
+ }
3158
+ /** The wall-clock time at `instant` in `timeZone`, as if it were UTC (whole seconds). */
3159
+ function wallClock(instant, timeZone) {
3160
+ const parts = {};
3161
+ for (const part of formatter(timeZone).formatToParts(instant)) if (part.type !== "literal") parts[part.type] = Number(part.value);
3162
+ return Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
3163
+ }
3164
+ const DAY_MS = 864e5;
3165
+ /** The offset of `timeZone` from UTC at `instant`, in milliseconds. */
3166
+ const offsetAt = (instant, timeZone) => wallClock(instant, timeZone) - Math.floor(instant / 1e3) * 1e3;
3167
+ /**
3168
+ * The first instant whose wall-clock time in `timeZone` is `wall`, or, when
3169
+ * a DST change skips `wall`, the instant the clocks jump past it, shifted by
3170
+ * the gap.
3171
+ */
3172
+ function instantOf(wall, timeZone) {
3173
+ const before = wall - offsetAt(wall - DAY_MS, timeZone);
3174
+ const valid = [before, wall - offsetAt(wall + DAY_MS, timeZone)].filter((instant) => wallClock(instant, timeZone) === wall);
3175
+ return valid.length ? Math.min(...valid) : before;
3176
+ }
3177
+ function dayMatches(cron, date) {
3178
+ const day = cron.days.has(date.getUTCDate());
3179
+ const weekday = cron.weekdays.has(date.getUTCDay());
3180
+ return cron.eitherDay ? day || weekday : day && weekday;
3181
+ }
3182
+ /** The first wall-clock time at or after `wall` that the expression matches, or undefined within eight years. */
3183
+ function nextWall(cron, wall) {
3184
+ const d = new Date(wall);
3185
+ const limit = d.getUTCFullYear() + 8;
3186
+ while (d.getUTCFullYear() <= limit) if (!cron.months.has(d.getUTCMonth() + 1)) {
3187
+ d.setUTCMonth(d.getUTCMonth() + 1, 1);
3188
+ d.setUTCHours(0, 0, 0);
3189
+ } else if (!dayMatches(cron, d)) {
3190
+ d.setUTCDate(d.getUTCDate() + 1);
3191
+ d.setUTCHours(0, 0, 0);
3192
+ } else if (!cron.hours.has(d.getUTCHours())) d.setUTCHours(d.getUTCHours() + 1, 0, 0);
3193
+ else if (!cron.minutes.has(d.getUTCMinutes())) d.setUTCMinutes(d.getUTCMinutes() + 1, 0);
3194
+ else if (!cron.seconds.has(d.getUTCSeconds())) d.setUTCSeconds(d.getUTCSeconds() + 1);
3195
+ else return d.getTime();
3196
+ }
3197
+ /**
3198
+ * The first time after `after` that the expression fires in `timeZone`.
3199
+ *
3200
+ * @returns The instant, or `undefined` when it never fires (`0 0 31 2 *`).
3201
+ */
3202
+ function nextCron(cron, after, timeZone = "UTC") {
3203
+ const from = after.getTime();
3204
+ let wall = wallClock(from, timeZone) + 1e3;
3205
+ for (;;) {
3206
+ const found = nextWall(cron, wall);
3207
+ if (found === void 0) return void 0;
3208
+ const instant = instantOf(found, timeZone);
3209
+ if (instant > from) return new Date(instant);
3210
+ wall = found + 1e3;
3211
+ }
3212
+ }
3213
+ /** A century: well inside what a `Date` can hold after any due time. */
3214
+ const MAX_DURATION_MS = 36600 * DAY_MS;
3215
+ const UNITS = {
3216
+ ms: 1,
3217
+ s: 1e3,
3218
+ m: 6e4,
3219
+ h: 36e5,
3220
+ d: DAY_MS
3221
+ };
3222
+ /**
3223
+ * A duration in milliseconds: a number of milliseconds, or text such as
3224
+ * `"90s"`, `"15m"`, `"6h"`, `"1d"` or `"1h30m"`.
3225
+ *
3226
+ * @throws When it is not a positive duration (or zero, with `allowZero`), or
3227
+ * is longer than a century.
3228
+ */
3229
+ function parseDuration(duration, options = {}) {
3230
+ let ms = 0;
3231
+ if (typeof duration === "number") ms = duration;
3232
+ else {
3233
+ const text = duration.replace(/\s+/g, "");
3234
+ const pattern = /(\d+(?:\.\d+)?)(ms|s|m|h|d)/gy;
3235
+ let match;
3236
+ let read = 0;
3237
+ while (match = pattern.exec(text)) {
3238
+ ms += Number(match[1]) * UNITS[match[2]];
3239
+ read = pattern.lastIndex;
3240
+ }
3241
+ if (!text || read !== text.length) ms = NaN;
3242
+ }
3243
+ const rounded = Math.round(ms);
3244
+ if (!Number.isFinite(rounded) || rounded < (options.allowZero ? 0 : 1) || rounded > MAX_DURATION_MS) throw new Error(`'${duration}' is not a duration: use milliseconds or text such as "15m", "6h" or "1h30m"`);
3245
+ return rounded;
3246
+ }
3247
+ // src/schedules/schedule.ts
3248
+ /**
3249
+ * Define a schedule: code that runs at set times, in one process among all
3250
+ * those that run the app. Pass it to `brick({ events: { schedules } })`.
3251
+ *
3252
+ * It runs either on a `cron` expression, at fixed wall-clock times in a time
3253
+ * zone, or `every` so long, counted from the end of the last successful run.
3254
+ * State lives in the app's `scheduleTable()`, so a due time runs once however
3255
+ * many processes there are, and a restart or deploy carries on where it
3256
+ * stopped. A due time counts as done only once its run succeeds: a run that
3257
+ * throws is retried with a growing delay, and one whose process died is taken
3258
+ * over by another process. A run is never started while the last one is still
3259
+ * running; due times that pass in the meantime are skipped.
3260
+ *
3261
+ * @param config - `name`, `cron` (and `timeZone`) or `every`, `run` or
3262
+ * `workflow`, and optionally `catchUp`, `maxAttempts`, `backoff`, `jitter` and
3263
+ * `enabled`.
3264
+ * @returns The schedule.
3265
+ * @throws When the name is empty or contains `:`, the cron expression or time
3266
+ * zone is invalid, or the schedule has both or neither of `cron` and `every`,
3267
+ * or of `run` and `workflow`.
3268
+ * @example
3269
+ * import { brick, defineSchedule } from "@brickkit/core";
3270
+ *
3271
+ * const backup = defineSchedule({
3272
+ * name: "db-backup",
3273
+ * cron: "0 *\/6 * * *",
3274
+ * timeZone: "Europe/Berlin",
3275
+ * run: () => backupDatabase(),
3276
+ * });
3277
+ *
3278
+ * export default brick({ services, events: { schedules: [backup] } });
3279
+ */
3280
+ function defineSchedule(config) {
3281
+ const { name } = config;
3282
+ if (typeof name !== "string" || !name) throw new Error("A schedule needs a name");
3283
+ if (name.includes(":")) throw new Error(`Schedule name '${name}' must not contain ':'`);
3284
+ const fail = (message) => {
3285
+ throw new Error(`Schedule '${name}': ${message}`);
3286
+ };
3287
+ const attempt = (fn) => {
3288
+ try {
3289
+ return fn();
3290
+ } catch (error) {
3291
+ return fail(error.message);
3292
+ }
3293
+ };
3294
+ /** A duration that may also be 0: none. */
3295
+ const optionalDuration = (value, fallback) => value === void 0 ? fallback : attempt(() => parseDuration(value, { allowZero: true }));
3296
+ if (config.cron === void 0 === (config.every === void 0)) fail("give it a cron expression or an interval (every), not both");
3297
+ if (config.run === void 0 === (config.workflow === void 0)) fail("give it a run handler or a workflow, not both");
3298
+ if (config.run !== void 0 && typeof config.run !== "function") fail("run must be a function");
3299
+ if (config.workflow !== void 0 && typeof config.workflow !== "function") fail("workflow must be a function marked \"use workflow\"");
3300
+ const maxAttempts = config.maxAttempts ?? 3;
3301
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) fail("maxAttempts must be a positive integer");
3302
+ if (config.catchUp !== void 0 && !["once", "skip"].includes(config.catchUp)) fail("catchUp must be \"once\" or \"skip\"");
3303
+ let when;
3304
+ if (config.cron !== void 0) {
3305
+ const timeZone = config.timeZone ?? "UTC";
3306
+ const cron = attempt(() => parseCron(config.cron));
3307
+ attempt(() => checkTimeZone(timeZone));
3308
+ if (!nextCron(cron, /* @__PURE__ */ new Date(), timeZone)) fail(`cron expression '${config.cron}' never fires`);
3309
+ when = {
3310
+ cron,
3311
+ timeZone,
3312
+ spec: `cron ${cron.source} ${timeZone}`
3313
+ };
3314
+ } else {
3315
+ const every = attempt(() => parseDuration(config.every));
3316
+ when = {
3317
+ every,
3318
+ spec: `every ${every}`
3319
+ };
3320
+ }
3321
+ return Object.freeze({
3322
+ name,
3323
+ ...when,
3324
+ catchUp: config.catchUp ?? "once",
3325
+ maxAttempts,
3326
+ backoffMs: optionalDuration(config.backoff, 6e4),
3327
+ jitterMs: optionalDuration(config.jitter, 0),
3328
+ enabled: config.enabled ?? true,
3329
+ ...config.run ? { run: config.run } : {},
3330
+ ...config.workflow ? { workflow: config.workflow } : {}
3331
+ });
3332
+ }
3333
+ /**
3334
+ * The first due time of `schedule` after `after`, before jitter: the next
3335
+ * cron time, or `after` plus the interval. `undefined` when the cron
3336
+ * expression fires no more.
3337
+ */
3338
+ function nextDue(schedule, after) {
3339
+ return schedule.cron ? nextCron(schedule.cron, after, schedule.timeZone) : new Date(after.getTime() + schedule.every);
3340
+ }
3341
+ // src/schedules/scheduler.ts
3342
+ /** A due time this late, on its first try, counts as missed for `catchUp: "skip"`. */
3343
+ const MISSED_AFTER_MS = 6e4;
3344
+ /** Runs kept per schedule. */
3345
+ const KEEP_RUNS = 20;
3346
+ const ABANDONED = "The process running it stopped before it finished";
3347
+ /**
3348
+ * Runs an app's schedules from one schedule table, shared by every process
3349
+ * that runs the app.
3350
+ *
3351
+ * Each schedule has one row. A process claims a due row with a conditional
3352
+ * update (due, and not held by a live claim), so one process wins each due
3353
+ * time, on Postgres and SQLite alike. While it runs, the process renews its
3354
+ * claim; a process that dies stops renewing, and after `claimTimeoutMs`
3355
+ * another process takes the due time over. On Postgres claims are timed by
3356
+ * the database's clock, so hosts whose clocks disagree still agree on them. Only success (or giving up after
3357
+ * `maxAttempts`) moves the row to the next due time.
3358
+ */
3359
+ var Scheduler = class {
3360
+ db;
3361
+ table;
3362
+ runner;
3363
+ options;
3364
+ byName;
3365
+ inFlight = /* @__PURE__ */ new Map();
3366
+ timer;
3367
+ tickQueue;
3368
+ synced;
3369
+ postgres;
3370
+ constructor(db, table, schedules, runner, options) {
3371
+ this.db = db;
3372
+ this.table = table;
3373
+ this.runner = runner;
3374
+ this.options = options;
3375
+ this.byName = new Map(schedules.map((s) => [s.name, s]));
3376
+ this.postgres = !isSqliteDatabase(db);
3377
+ }
3378
+ start() {
3379
+ if (this.timer || !this.options.timer) return;
3380
+ this.timer = setInterval(() => void this.tick(), this.options.intervalMs);
3381
+ this.timer.unref?.();
3382
+ this.tick();
3383
+ }
3384
+ /** Stop the timer and wait for the runs in progress. */
3385
+ async stop() {
3386
+ if (this.timer) clearInterval(this.timer);
3387
+ this.timer = void 0;
3388
+ await this.tickQueue;
3389
+ await Promise.allSettled(this.inFlight.values());
3390
+ }
3391
+ /**
3392
+ * Run what is due now and wait for it. Retries that are not due yet are not
3393
+ * waited for. For tests and for workers driven by hand.
3394
+ *
3395
+ * @returns How many runs it started.
3396
+ */
3397
+ async drain() {
3398
+ let total = 0;
3399
+ for (;;) {
3400
+ const started = await this.tick();
3401
+ await Promise.allSettled(this.inFlight.values());
3402
+ if (started === 0) return total;
3403
+ total += started;
3404
+ }
3405
+ }
3406
+ /** Every schedule with its state. */
3407
+ async list(now = /* @__PURE__ */ new Date()) {
3408
+ const t = this.table;
3409
+ const rows = await this.db.select().from(t);
3410
+ const byName = new Map(rows.map((row) => [row.name, row]));
3411
+ return [...this.byName.values()].map((schedule) => {
3412
+ const row = byName.get(schedule.name);
3413
+ return {
3414
+ name: schedule.name,
3415
+ kind: schedule.workflow ? "workflow" : "handler",
3416
+ ...schedule.cron ? {
3417
+ cron: schedule.cron.source,
3418
+ timeZone: schedule.timeZone
3419
+ } : { every: schedule.every },
3420
+ enabled: schedule.enabled,
3421
+ nextRunAt: row ? row.nextAt.toISOString() : null,
3422
+ running: Boolean(row?.runId && row.leaseUntil && row.leaseUntil > now),
3423
+ attempts: row?.runId ? row.attempts : row?.attempts ?? 0,
3424
+ lastSuccessAt: row?.lastSuccessAt?.toISOString() ?? null,
3425
+ runs: row?.runs ?? []
3426
+ };
3427
+ });
3428
+ }
3429
+ /**
3430
+ * Make a schedule due now, as a manual run. Whichever process runs the
3431
+ * schedules picks it up; this one at once if it does.
3432
+ *
3433
+ * @returns `false` when the schedule is running now.
3434
+ * @throws When no schedule has that name.
3435
+ */
3436
+ async trigger(name) {
3437
+ if (!this.byName.has(name)) throw new Error(`No schedule named '${name}'`);
3438
+ await this.sync();
3439
+ const now = /* @__PURE__ */ new Date();
3440
+ if (!await this.reset(name, now, {
3441
+ slot: now,
3442
+ nextAt: now,
3443
+ attempts: 0,
3444
+ trigger: "manual"
3445
+ })) return false;
3446
+ if (this.timer) setTimeout(() => void this.tick(), 0).unref?.();
3447
+ return true;
3448
+ }
3449
+ /**
3450
+ * Set a schedule's row afresh, unless a live claim holds it. A claim whose
3451
+ * process died is recorded first, as a failed run of its own due time.
3452
+ *
3453
+ * @returns Whether the row was set.
3454
+ */
3455
+ async reset(name, now, values) {
3456
+ const t = this.table;
3457
+ const [row] = await this.db.select().from(t).where(eq(t.name, name));
3458
+ if (!row) return false;
3459
+ return (await this.db.update(t).set({
3460
+ ...values,
3461
+ runId: null,
3462
+ startedAt: null,
3463
+ leaseUntil: null,
3464
+ ...row.runId ? { runs: [this.record(row, row.startedAt, "failed", ABANDONED), ...row.runs].slice(0, KEEP_RUNS) } : {}
3465
+ }).where(and(eq(t.name, name), this.unchanged(row.runId), this.free(now))).returning({ name: t.name })).length > 0;
3466
+ }
3467
+ /** Not held by a live claim. */
3468
+ free(now) {
3469
+ const t = this.table;
3470
+ return or(isNull(t.runId), lt(t.leaseUntil, this.clock(now)));
3471
+ }
3472
+ /** Still held by the claim `runId`, or by none when it is null. */
3473
+ unchanged(runId) {
3474
+ const t = this.table;
3475
+ return runId ? eq(t.runId, runId) : isNull(t.runId);
3476
+ }
3477
+ /** Now, for claims: the database's clock on Postgres, this host's on SQLite (one host). */
3478
+ clock(now) {
3479
+ return this.postgres ? sql`now()` : now;
3480
+ }
3481
+ /** When a claim made or renewed now runs out. */
3482
+ leaseFrom(now) {
3483
+ const ms = this.options.claimTimeoutMs;
3484
+ return this.postgres ? sql`now() + make_interval(secs => ${ms / 1e3})` : new Date(now.getTime() + ms);
3485
+ }
3486
+ /** A row due at the schedule's first time from now: an interval at once, a cron schedule at its next time. */
3487
+ fresh(schedule, now) {
3488
+ const slot = schedule.cron ? nextDue(schedule, now) : now;
3489
+ return slot && {
3490
+ spec: schedule.spec,
3491
+ slot,
3492
+ nextAt: this.jittered(schedule, slot),
3493
+ attempts: 0,
3494
+ trigger: "schedule"
3495
+ };
3496
+ }
3497
+ /**
3498
+ * Give each schedule its row, and work its next due time out again when what
3499
+ * decides it changed (an edited cron expression). Once per scheduler.
3500
+ */
3501
+ sync() {
3502
+ this.synced ??= this.writeRows().catch((error) => {
3503
+ this.synced = void 0;
3504
+ throw error;
3505
+ });
3506
+ return this.synced;
3507
+ }
3508
+ async writeRows() {
3509
+ const t = this.table;
3510
+ const now = /* @__PURE__ */ new Date();
3511
+ for (const schedule of this.byName.values()) {
3512
+ const fresh = this.fresh(schedule, now);
3513
+ if (!fresh) continue;
3514
+ await this.db.insert(t).values({
3515
+ name: schedule.name,
3516
+ runs: [],
3517
+ ...fresh
3518
+ }).onConflictDoNothing();
3519
+ const [row] = await this.db.select({ spec: t.spec }).from(t).where(eq(t.name, schedule.name));
3520
+ if (row && row.spec !== schedule.spec) await this.reset(schedule.name, now, fresh);
3521
+ }
3522
+ }
3523
+ tick() {
3524
+ this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(() => this.claimAndRun(), () => this.claimAndRun());
3525
+ return this.tickQueue;
3526
+ }
3527
+ async claimAndRun() {
3528
+ try {
3529
+ await this.sync();
3530
+ const t = this.table;
3531
+ const now = /* @__PURE__ */ new Date();
3532
+ const due = await this.db.select({
3533
+ name: t.name,
3534
+ spec: t.spec,
3535
+ trigger: t.trigger,
3536
+ runId: t.runId,
3537
+ startedAt: t.startedAt
3538
+ }).from(t).where(and(inArray(t.name, [...this.byName.keys()]), lte(t.nextAt, now), this.free(now)));
3539
+ let started = 0;
3540
+ for (const candidate of due) {
3541
+ const schedule = this.byName.get(candidate.name);
3542
+ if (this.inFlight.has(schedule.name)) continue;
3543
+ if (!schedule.enabled && candidate.trigger !== "manual") continue;
3544
+ if (candidate.spec !== schedule.spec) {
3545
+ const fresh = this.fresh(schedule, now);
3546
+ if (fresh) await this.reset(schedule.name, now, fresh);
3547
+ continue;
3548
+ }
3549
+ const runId = crypto.randomUUID();
3550
+ const [row] = await this.db.update(t).set({
3551
+ runId,
3552
+ startedAt: now,
3553
+ leaseUntil: this.leaseFrom(now),
3554
+ attempts: sql`${t.attempts} + 1`
3555
+ }).where(and(eq(t.name, schedule.name), lte(t.nextAt, now), this.free(now), this.unchanged(candidate.runId))).returning();
3556
+ if (!row) continue;
3557
+ started++;
3558
+ const run = this.execute(schedule, row, candidate.runId === null ? void 0 : candidate.startedAt).catch((error) => this.logError(error)).finally(() => this.inFlight.delete(schedule.name));
3559
+ this.inFlight.set(schedule.name, run);
3560
+ }
3561
+ return started;
3562
+ } catch (error) {
3563
+ this.logError(error);
3564
+ return 0;
3565
+ }
3566
+ }
3567
+ async execute(schedule, row, abandonedAt) {
3568
+ const runs = [...row.runs];
3569
+ const startedAt = row.startedAt;
3570
+ const attempt = row.attempts;
3571
+ if (abandonedAt) runs.unshift(this.record({
3572
+ ...row,
3573
+ attempts: attempt - 1
3574
+ }, abandonedAt, "failed", ABANDONED));
3575
+ const now = () => /* @__PURE__ */ new Date();
3576
+ if (attempt === 1 && row.trigger === "schedule" && schedule.cron && schedule.catchUp === "skip" && startedAt.getTime() - row.nextAt.getTime() > MISSED_AFTER_MS) {
3577
+ runs.unshift(this.record(row, startedAt, "skipped"));
3578
+ return this.advance(schedule, row, runs, now(), false);
3579
+ }
3580
+ if (attempt > schedule.maxAttempts) return this.advance(schedule, row, runs, now(), false);
3581
+ const heartbeat = setInterval(() => void this.renew(row).catch((error) => this.logError(error)), Math.max(10, Math.floor(this.options.claimTimeoutMs / 3)));
3582
+ heartbeat.unref?.();
3583
+ const slot = row.slot.toISOString();
3584
+ try {
3585
+ await this.runner(schedule, {
3586
+ schedule: schedule.name,
3587
+ slot,
3588
+ trigger: row.trigger,
3589
+ attempt,
3590
+ runKey: `${schedule.name}:${slot}`
3591
+ });
3592
+ } catch (error) {
3593
+ clearInterval(heartbeat);
3594
+ const message = error instanceof Error ? error.message : String(error);
3595
+ runs.unshift(this.record(row, startedAt, "failed", message));
3596
+ return this.retry(schedule, row, runs, now());
3597
+ }
3598
+ clearInterval(heartbeat);
3599
+ runs.unshift(this.record(row, startedAt, "succeeded"));
3600
+ return this.advance(schedule, row, runs, now(), true);
3601
+ }
3602
+ async renew(row) {
3603
+ const t = this.table;
3604
+ if (!(await this.db.update(t).set({ leaseUntil: this.leaseFrom(/* @__PURE__ */ new Date()) }).where(and(eq(t.name, row.name), eq(t.runId, row.runId))).returning({ name: t.name })).length) console.warn(`[Brick-TS schedules] Schedule '${row.name}' lost its claim while running; another process may run it too.`);
3605
+ }
3606
+ /** After a failure: try the same due time again later, unless the tries ran out or the next due time comes first. */
3607
+ async retry(schedule, row, runs, now) {
3608
+ const retryAt = new Date(now.getTime() + schedule.backoffMs * 2 ** (row.attempts - 1));
3609
+ const next = schedule.cron ? nextDue(schedule, now) : void 0;
3610
+ if (row.attempts >= schedule.maxAttempts || next && next <= retryAt) return this.advance(schedule, row, runs, now, false);
3611
+ await this.release(row, {
3612
+ nextAt: retryAt,
3613
+ runs
3614
+ });
3615
+ }
3616
+ /** Done with this due time: on to the next one. */
3617
+ async advance(schedule, row, runs, now, succeeded) {
3618
+ const slot = nextDue(schedule, now);
3619
+ await this.release(row, {
3620
+ spec: schedule.spec,
3621
+ ...slot ? {
3622
+ slot,
3623
+ nextAt: this.jittered(schedule, slot)
3624
+ } : { nextAt: /* @__PURE__ */ new Date(864e13) },
3625
+ attempts: 0,
3626
+ trigger: "schedule",
3627
+ runs,
3628
+ ...succeeded ? { lastSuccessAt: now } : {}
3629
+ });
3630
+ }
3631
+ async release(row, values) {
3632
+ const t = this.table;
3633
+ if (!(await this.db.update(t).set({
3634
+ ...values,
3635
+ runs: values.runs?.slice(0, KEEP_RUNS),
3636
+ runId: null,
3637
+ leaseUntil: null
3638
+ }).where(and(eq(t.name, row.name), eq(t.runId, row.runId))).returning({ name: t.name })).length) console.warn(`[Brick-TS schedules] Schedule '${row.name}': another process took the run over, so this outcome is not recorded.`);
3639
+ }
3640
+ record(row, startedAt, outcome, error) {
3641
+ return {
3642
+ slot: row.slot.toISOString(),
3643
+ trigger: row.trigger,
3644
+ attempt: row.attempts,
3645
+ startedAt: startedAt.toISOString(),
3646
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
3647
+ outcome,
3648
+ ...error !== void 0 ? { error } : {}
3649
+ };
3650
+ }
3651
+ jittered(schedule, slot) {
3652
+ return schedule.jitterMs ? new Date(slot.getTime() + Math.floor(Math.random() * schedule.jitterMs)) : slot;
3653
+ }
3654
+ logError(error) {
3655
+ console.error("[Brick-TS schedules]", error);
3656
+ }
3657
+ };
3042
3658
  // src/events/hub.ts
3043
3659
  function matchesEvent(pattern, name) {
3044
3660
  if (pattern === "*") return true;
@@ -3070,6 +3686,8 @@ var EventsHub = class {
3070
3686
  dispatchOptions;
3071
3687
  runtime;
3072
3688
  recorderNames = [];
3689
+ scheduleList = [];
3690
+ scheduler;
3073
3691
  started = false;
3074
3692
  stopping;
3075
3693
  /**
@@ -3084,9 +3702,15 @@ var EventsHub = class {
3084
3702
  if (this.byName.has(listener.name)) throw new DuplicateNameError(`Duplicate event listener '${listener.name}'`);
3085
3703
  this.byName.set(listener.name, listener);
3086
3704
  }
3087
- const workflowListeners = [...this.byName.values()].filter((listener) => listener.workflow);
3705
+ const scheduleNames = /* @__PURE__ */ new Set();
3706
+ for (const schedule of options.schedules ?? []) {
3707
+ if (scheduleNames.has(schedule.name)) throw new DuplicateNameError(`Duplicate schedule '${schedule.name}'`);
3708
+ scheduleNames.add(schedule.name);
3709
+ this.scheduleList.push(schedule);
3710
+ }
3711
+ const workflowListeners = [...this.byName.values(), ...this.scheduleList].filter((listener) => listener.workflow);
3088
3712
  if (workflowListeners.length) {
3089
- if (!options.world) throw new Error(`Event listener '${workflowListeners[0].name}' runs a workflow, so events needs a world: brick({ events: { world: createWorld(...) } }) with createWorld from @brickkit/redis-world.`);
3713
+ if (!options.world) throw new Error(`${"on" in workflowListeners[0] ? "Event listener" : "Schedule"} '${workflowListeners[0].name}' runs a workflow, so events needs a world: brick({ events: { world: createWorld(...) } }) with createWorld from @brickkit/redis-world.`);
3090
3714
  this.runtime = new WorkflowRuntime(options.world, options.workflows, workflowListeners, deps);
3091
3715
  }
3092
3716
  this.dispatchOptions = options.dispatch === false ? false : options.dispatch === true || options.dispatch === void 0 ? {} : options.dispatch;
@@ -3109,6 +3733,7 @@ var EventsHub = class {
3109
3733
  if (db && typeof db === "object") recordingServices.set(db, service);
3110
3734
  if (!this.dispatchers.has(table)) this.dispatchers.set(table, new Dispatcher(db, table, (name) => this.deliverable(name), this.dispatchOptions || {}));
3111
3735
  }
3736
+ if (this.scheduleList.length) this.attachSchedules(services);
3112
3737
  if (this.recorderNames.length === 0 && this.byName.size > 0) console.warn("[Brick-TS] events are configured, but no service database has an outbox table. Add outboxTable() to a database's tables so its writes can record events.");
3113
3738
  return this;
3114
3739
  }
@@ -3125,10 +3750,49 @@ var EventsHub = class {
3125
3750
  kind: listener.workflow ? "workflow" : "handler"
3126
3751
  })),
3127
3752
  dispatch: this.dispatchOptions !== false,
3128
- recorders: [...this.recorderNames]
3753
+ recorders: [...this.recorderNames],
3754
+ ...this.scheduleList.length ? { schedules: this.scheduleList.map((schedule) => ({
3755
+ name: schedule.name,
3756
+ kind: schedule.workflow ? "workflow" : "handler",
3757
+ ...schedule.cron ? {
3758
+ cron: schedule.cron.source,
3759
+ timeZone: schedule.timeZone
3760
+ } : { every: schedule.every },
3761
+ enabled: schedule.enabled
3762
+ })) } : {}
3763
+ };
3764
+ }
3765
+ /** The app's schedules, when it has any. Running them follows `start()` and `stop()`. */
3766
+ get schedules() {
3767
+ const scheduler = this.scheduler;
3768
+ return scheduler && {
3769
+ list: () => scheduler.list(),
3770
+ trigger: (name) => scheduler.trigger(name),
3771
+ drain: () => scheduler.drain()
3129
3772
  };
3130
3773
  }
3131
3774
  /**
3775
+ * Find the one schedule table among the services' databases.
3776
+ *
3777
+ * @throws When none holds one, or more than one does: a schedule must have
3778
+ * one place where its state lives.
3779
+ */
3780
+ attachSchedules(services) {
3781
+ const found = /* @__PURE__ */ new Map();
3782
+ for (const service of services.map(portOf)) {
3783
+ const table = service.getScheduleTable();
3784
+ if (table && !found.has(table)) found.set(table, service.getDb());
3785
+ }
3786
+ if (found.size !== 1) throw new Error(found.size ? "Brick: schedules need exactly one scheduleTable(), but several databases hold one." : "Brick: schedules keep their state in a scheduleTable(), and no service database holds one. Add scheduleTable() to a database's tables.");
3787
+ const [[table, db]] = [...found];
3788
+ const options = this.dispatchOptions || {};
3789
+ this.scheduler = new Scheduler(db, table, this.scheduleList, (schedule, run) => schedule.workflow ? this.runtime.startScheduled(schedule, run) : runWithDeps(this.deps, async () => schedule.run(run)), {
3790
+ timer: options.timer ?? true,
3791
+ intervalMs: options.intervalMs ?? 1e3,
3792
+ claimTimeoutMs: options.claimTimeoutMs ?? 6e4
3793
+ });
3794
+ }
3795
+ /**
3132
3796
  * Where the workflow bundle is read from, the project it is built from, and
3133
3797
  * the world the workflows run on. Only set when a listener runs a workflow.
3134
3798
  * The CLI builds the bundle there before events start, and shows the world's
@@ -3162,6 +3826,7 @@ var EventsHub = class {
3162
3826
  startedHubs.add(this);
3163
3827
  this.runtime?.warmUp();
3164
3828
  for (const dispatcher of this.dispatchers.values()) dispatcher.start();
3829
+ this.scheduler?.start();
3165
3830
  }
3166
3831
  /**
3167
3832
  * Stop delivering, wait for the deliveries that are running, and close the
@@ -3176,7 +3841,7 @@ var EventsHub = class {
3176
3841
  }
3177
3842
  async shutDown() {
3178
3843
  this.started = false;
3179
- await Promise.all([...this.dispatchers.values()].map((dispatcher) => dispatcher.stop()));
3844
+ await Promise.all([...[...this.dispatchers.values()].map((dispatcher) => dispatcher.stop()), this.scheduler?.stop()]);
3180
3845
  await this.runtime?.close();
3181
3846
  }
3182
3847
  /**
@@ -4038,6 +4703,6 @@ function cachedJsonRoute(build, revision) {
4038
4703
  return json;
4039
4704
  };
4040
4705
  }
4041
- export { validateName as $, resolveWorkflowPaths as A, createActionHandler as B, setActionAccess as C, compileBrickApplication as D, bindCompiledApplication as E, crudEventSource as F, useDeps as G, definitionSite as H, eventRefs as I, getPluginEndpoints as J, defineResourcePlugin as K, isCrudEvent as L, checkEvent as M, checkPayload as N, loadCompiledBrickApp as O, crudEventName as P, segmentClaimant as Q, isBrickApp as R, getActionAccess as S, resetGlobalRegistry as T, INTERNALS as U, claimName as V, port as W, installPlugin as X, hasPlugin as Y, isInstallingPlugin as Z, listSecrets as _, Dispatcher as a, baseContext as at, resolveSecrets as b, isOutboxTable as c, t as ct, registerReferenceRoute as d, withCallSpan as dt, portOf as et, scalarDocsHTML as f, PLUGIN_COMMIT as ft, envSource as g, defineSecret as h, stopAllEvents as i, deny as it, defineListener as j, WORKFLOW_BUNDLE as k, outboxTable as l, validateWithSchema as lt, SecretRef as m, defineServiceSocket as n, defineAction as nt, onTransactionCommit as o, pickContextEnvelope as ot, requestLoggingPlugin as p, PLUGIN_KIND as pt, defineServicePlugin as q, recordingServices as r, errorsOf as rt, runInTransaction as s, Type as st, brick as t, buildErrorHelpers as tt, referencePlugin as u, traceRoute as ut, overrideSecret as v, getGlobalRegistry as w, generateOpenApiSpec as x, resetSecrets as y, requireBrickApp as z };
4706
+ export { segmentClaimant as $, WORKFLOW_BUNDLE as A, requireBrickApp as B, getActionAccess as C, bindCompiledApplication as D, resetGlobalRegistry as E, crudEventName as F, port as G, claimName as H, crudEventSource as I, defineServicePlugin as J, useDeps as K, eventRefs as L, defineListener as M, checkEvent as N, compileBrickApplication as O, checkPayload as P, isInstallingPlugin as Q, isCrudEvent as R, generateOpenApiSpec as S, getGlobalRegistry as T, definitionSite as U, createActionHandler as V, INTERNALS as W, hasPlugin as X, getPluginEndpoints as Y, installPlugin as Z, envSource as _, defineSchedule as a, deny as at, resetSecrets as b, runInTransaction as c, Type as ct, referencePlugin as d, traceRoute as dt, validateName as et, registerReferenceRoute as f, withCallSpan as ft, defineSecret as g, SecretRef as h, stopAllEvents as i, errorsOf as it, resolveWorkflowPaths as j, loadCompiledBrickApp as k, isOutboxTable as l, t as lt, requestLoggingPlugin as m, PLUGIN_KIND as mt, defineServiceSocket as n, buildErrorHelpers as nt, Dispatcher as o, baseContext as ot, scalarDocsHTML as p, PLUGIN_COMMIT as pt, defineResourcePlugin as q, recordingServices as r, defineAction as rt, onTransactionCommit as s, pickContextEnvelope as st, brick as t, portOf as tt, outboxTable as u, validateWithSchema as ut, listSecrets as v, setActionAccess as w, resolveSecrets as x, overrideSecret as y, isBrickApp as z };
4042
4707
 
4043
4708
  //# sourceMappingURL=server.js.map