diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b69d5d..71bfaf8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- Accept `skip` as a `missed` policy beside `latest` and `all`. Actor-facing + `ScheduledReminder` now includes `lastRunAtMilliseconds`, `occurrence`, and + `errorName` on both the SQL and Durable Objects adapters. + - Separate isolated benchmark baselines from historical shared-workstation measurements. Publish the retained DigitalOcean 1.0.5 baseline with provenance and teardown evidence, and validate dataset version labels and summaries in CI before publication. diff --git a/docs/api.md b/docs/api.md index 7c453c5..944881e 100644 --- a/docs/api.md +++ b/docs/api.md @@ -203,6 +203,20 @@ row per item. It also cannot strand an entry when the runtime coalesces an occurrence. Prefer it for a large queue of interchangeable items. Prefer `key` when one item needs an alarm that you can move on its own. +`schedule({ at })` stores `at.getTime()` as epoch milliseconds. An invalid +`Date` is a `TypeError` (`reminder time must be valid`). That stored time is +compared with the runtime's now. On SQL, now is the connection's +`nowMilliseconds`, or a test `now` passed into the scheduler. On Durable +Objects, now is `Date.now()` at the due pass. Retry and retention of a fired +reminder follow the mailbox message it enqueued. Time zone and clock skew are +not a documented guarantee. + +When a recurring reminder is considered after its scheduled time, `missed` +chooses which occurrences become mailbox messages. The default when `missed` +is omitted is `latest`. `latest` is the original PRD's `run_once`. `all` is +the PRD's `catch_up`. `skip` drops missed occurrences and waits for the next +scheduled time. + #### A schedule call needs an operation `schedule()` returns an object, and the reminder exists only after you call an @@ -330,9 +344,14 @@ operation the actor does not declare, as `schedule()` and `unschedule()` do. A one-shot that already fired is not reported. Its row stays as `completed`, and an alarm that cannot fire again is not armed. -`ScheduledReminder` carries no occurrence count. The SQL backends track one and -Durable Objects does not, so it is left out rather than reported for one backend -only. +`occurrence` is how many times this reminder has been enqueued. It is the +original PRD's "attempt". It starts at 0 and goes up by 1 on each enqueue. A +skipped `skip` window does not increment it, and neither does a mailbox retry +of an already enqueued message. `lastRunAtMilliseconds` is the adapter's now +when that enqueue happened, or `null` if it has never been enqueued. +`errorName` is the error that paused the reminder, or `null`. Scheduling an +existing name keeps `lastRunAtMilliseconds` and `occurrence` and clears +`errorName`. A cancellation is staged like a schedule, so it commits with the state change that decided it and a turn that throws cancels nothing. Both apply in the order diff --git a/src/actor.ts b/src/actor.ts index 8023412..40760e5 100644 --- a/src/actor.ts +++ b/src/actor.ts @@ -116,7 +116,7 @@ export interface ReminderIntent { atMilliseconds: number arguments: JsonObject intervalMilliseconds?: number - missedPolicy: "all" | "latest" + missedPolicy: "latest" | "all" | "skip" } export interface UnscheduleIntent { @@ -159,7 +159,7 @@ export interface ActorClass { export interface ReminderOptions { at: Date everyMilliseconds?: number - missed?: "all" | "latest" + missed?: "latest" | "all" | "skip" /** Your own identifier for the item this alarm waits on, so each item gets one. */ key?: string | number } @@ -221,6 +221,7 @@ function applyReminderIntent(view: Map, intent: Remin return } + const existing = view.get(intent.name) view.set(intent.name, { name: intent.name, operation: intent.operation, @@ -230,6 +231,9 @@ function applyReminderIntent(view: Map, intent: Remin missedPolicy: intent.missedPolicy, status: "scheduled", handle: { name: intent.name }, + lastRunAtMilliseconds: existing?.lastRunAtMilliseconds ?? null, + occurrence: existing?.occurrence ?? 0, + errorName: null, }) } @@ -464,10 +468,11 @@ export abstract class Actor { throw new TypeError("reading reminders is not available outside an actor turn") } const view = new Map() - for (const reminder of await this.#readReminders()) { - if (reminder.status !== "completed") view.set(reminder.name, reminder) - } + for (const reminder of await this.#readReminders()) view.set(reminder.name, reminder) for (const intent of this.#intents.reminders) applyReminderIntent(view, intent) + for (const [name, reminder] of view) { + if (reminder.status === "completed") view.delete(name) + } return view } diff --git a/src/cloudflare/engine.ts b/src/cloudflare/engine.ts index 0613a26..a792a4e 100644 --- a/src/cloudflare/engine.ts +++ b/src/cloudflare/engine.ts @@ -41,7 +41,14 @@ import type { import type { CloudflareSettings } from "./configuration.js" import { boundedKeys } from "../repository.js" import { actorName, callHost, type ActorIdentity, type HostRequest } from "./protocol.js" -import type { Instance, Message, Outbox, Reminder, Subscription } from "./records.js" +import { + storedReminder, + type Instance, + type Message, + type Outbox, + type Reminder, + type Subscription, +} from "./records.js" import { beforeDeadline, CloudflareRuntime } from "./runtime.js" import { ActorStorage } from "./storage.js" @@ -404,7 +411,7 @@ export class ActorEngine { } private readReminders = async (): Promise => - this.store.rows("SELECT record FROM reminders ORDER BY name").map((reminder) => ({ + this.reminderRows("SELECT record FROM reminders ORDER BY name").map((reminder) => ({ name: reminder.name, operation: reminder.operation, key: @@ -416,8 +423,18 @@ export class ActorEngine { missedPolicy: reminder.missed, status: reminder.status, handle: { name: reminder.name }, + lastRunAtMilliseconds: reminder.lastRunAtMilliseconds, + occurrence: reminder.occurrence, + errorName: reminder.errorName, })) + private reminderRows( + query: string, + parameters: readonly (string | number | null)[] = [], + ): Reminder[] { + return this.store.rows(query, parameters).map(storedReminder) + } + private async snapshot(identity: ActorIdentity): Promise { const { definition, instance, state } = this.committed(identity) const actor = hydrateActor({ @@ -785,6 +802,9 @@ export class ActorEngine { this.store.deleteReminder(intent.name) continue } + const existing = this.reminderRows("SELECT record FROM reminders WHERE name = ?", [ + intent.name, + ])[0] this.store.saveReminder({ name: intent.name, generation: crypto.randomUUID(), @@ -794,6 +814,9 @@ export class ActorEngine { interval: intent.intervalMilliseconds ?? null, missed: intent.missedPolicy, status: "scheduled", + occurrence: existing?.occurrence ?? 0, + lastRunAtMilliseconds: existing?.lastRunAtMilliseconds ?? null, + errorName: null, }) } if (!broadcast) return @@ -1018,11 +1041,23 @@ export class ActorEngine { const dispatched: JsonObject[] = [] const instance = this.store.instance() if (!instance || instance.paused) return dispatched - for (const reminder of this.store.rows( + const now = Date.now() + for (const reminder of this.reminderRows( "SELECT record FROM reminders WHERE status = 'scheduled' AND due_at <= ? ORDER BY due_at LIMIT ?", - [Date.now(), this.settings.maxMessagesPerActivationPass], + [now, this.settings.maxMessagesPerActivationPass], )) { try { + if ( + reminder.interval !== null && + reminder.missed === "skip" && + now >= reminder.at + reminder.interval + ) { + reminder.at += + (Math.floor((now - reminder.at) / reminder.interval) + 1) * reminder.interval + reminder.status = "scheduled" + this.store.saveReminder(reminder) + continue + } const message = this.enqueue({ ...instance, method: "internal", @@ -1038,10 +1073,12 @@ export class ActorEngine { dispatched.push({ messageId: message.id, attempt: message.attempt, - latenessMilliseconds: Math.max(0, Date.now() - reminder.at), + latenessMilliseconds: Math.max(0, now - reminder.at), }) message.reminder = { name: reminder.name, generation: reminder.generation } this.store.saveMessage(message) + reminder.occurrence += 1 + reminder.lastRunAtMilliseconds = now reminder.status = "completed" this.store.saveReminder(reminder) } catch (error) { @@ -1054,7 +1091,7 @@ export class ActorEngine { private completeReminder(message: Message): void { if (!message.reminder) return - const reminder = this.store.rows("SELECT record FROM reminders WHERE name = ?", [ + const reminder = this.reminderRows("SELECT record FROM reminders WHERE name = ?", [ message.reminder.name, ])[0] if ( @@ -1064,9 +1101,9 @@ export class ActorEngine { ) return const steps = - reminder.missed === "latest" - ? Math.max(1, Math.floor((Date.now() - reminder.at) / reminder.interval) + 1) - : 1 + reminder.missed === "all" + ? 1 + : Math.max(1, Math.floor((Date.now() - reminder.at) / reminder.interval) + 1) reminder.at += steps * reminder.interval reminder.status = "scheduled" this.store.saveReminder(reminder) @@ -1074,11 +1111,12 @@ export class ActorEngine { private pauseReminder(message: Message): void { if (!message.reminder) return - const reminder = this.store.rows("SELECT record FROM reminders WHERE name = ?", [ + const reminder = this.reminderRows("SELECT record FROM reminders WHERE name = ?", [ message.reminder.name, ])[0] if (!reminder || reminder.generation !== message.reminder.generation) return reminder.status = "paused" + reminder.errorName = typeof message.error?.name === "string" ? message.error.name : "Error" this.store.saveReminder(reminder) } @@ -1137,7 +1175,7 @@ export class ActorEngine { return normalizeJson(outbox) } if (action === "resumeReminder") { - const reminder = this.store.rows("SELECT record FROM reminders WHERE name = ?", [ + const reminder = this.reminderRows("SELECT record FROM reminders WHERE name = ?", [ String(input.payload.name), ])[0] if (!reminder) throw new UnknownReminder("unknown reminder") @@ -1147,6 +1185,7 @@ export class ActorEngine { reminder.at = at reminder.status = "scheduled" reminder.generation = crypto.randomUUID() + reminder.errorName = null this.store.saveReminder(reminder) const instance = this.store.instance() if (instance) { diff --git a/src/cloudflare/records.ts b/src/cloudflare/records.ts index 20e80fd..4fe4867 100644 --- a/src/cloudflare/records.ts +++ b/src/cloudflare/records.ts @@ -60,8 +60,21 @@ export interface Reminder { arguments: JsonObject at: number interval: number | null - missed: "all" | "latest" + missed: "latest" | "all" | "skip" status: "scheduled" | "paused" | "completed" + occurrence: number + lastRunAtMilliseconds: number | null + errorName: string | null +} + +export function storedReminder(reminder: Reminder): Reminder { + return { + ...reminder, + occurrence: typeof reminder.occurrence === "number" ? reminder.occurrence : 0, + lastRunAtMilliseconds: + typeof reminder.lastRunAtMilliseconds === "number" ? reminder.lastRunAtMilliseconds : null, + errorName: typeof reminder.errorName === "string" ? reminder.errorName : null, + } } export interface Subscription { diff --git a/src/records.ts b/src/records.ts index 132f4c3..0bf8a2a 100644 --- a/src/records.ts +++ b/src/records.ts @@ -124,12 +124,13 @@ export interface ReminderRow { run_at_ms: number | bigint arguments: string interval_ms: number | bigint | null - missed_policy: "latest" | "all" + missed_policy: "latest" | "all" | "skip" occurrence: number | bigint status: "scheduled" | "paused" | "completed" claimed_by: string | null claimed_at_ms: number | bigint | null error: string | null + last_run_at_ms: number | bigint | null } export interface BroadcastRow { diff --git a/src/reminder-administration.ts b/src/reminder-administration.ts index 658a21c..999a71d 100644 --- a/src/reminder-administration.ts +++ b/src/reminder-administration.ts @@ -12,7 +12,7 @@ export interface ReminderRecord { readonly operation: string readonly runAt: Date readonly intervalMilliseconds: number | null - readonly missedPolicy: "latest" | "all" + readonly missedPolicy: "latest" | "all" | "skip" readonly occurrence: number readonly status: ReminderStatus readonly errorName: string | null diff --git a/src/repository.ts b/src/repository.ts index 475c9c5..598d099 100644 --- a/src/repository.ts +++ b/src/repository.ts @@ -1900,7 +1900,7 @@ export class Repository { async enqueueReminder( reminder: ReminderRow, - options: { nowMilliseconds?: number } = {}, + options: { nowMilliseconds?: number; beforeEnqueue?: (reminder: ReminderRow) => void } = {}, ): Promise { return this.settings.database.transaction(async (connection) => { const now = options.nowMilliseconds ?? (await connection.nowMilliseconds()) @@ -1919,15 +1919,6 @@ export class Repository { )) if (!claimed && !surviving) return undefined if (!claimed) throw new LostActivation("reminder claim no longer matches") - const message = await this.enqueueInTransaction(connection, { - actorType: claimed.actor_type, - actorId: claimed.actor_id, - operation: claimed.message_operation ?? claimed.operation, - deliveryMode: "internal", - arguments: jsonObject(JSON.parse(claimed.arguments)), - idempotencyKey: `reminder:${claimed.id}:${claimed.occurrence}`, - }) - const interval = claimed.interval_ms === null ? undefined : Number(claimed.interval_ms) const nextRun = interval === undefined @@ -1938,13 +1929,33 @@ export class Repository { missedPolicy: claimed.missed_policy, now, }) + if (!reminderShouldEnqueue({ reminder: claimed, now })) { + await connection.run( + `UPDATE ${this.table("reminders")} + SET run_at_ms = ?, claimed_by = NULL, claimed_at_ms = NULL + WHERE id = ? AND claimed_by = ?`, + [nextRun, claimed.id, claimed.claimed_by], + ) + return undefined + } + options.beforeEnqueue?.(claimed) + const message = await this.enqueueInTransaction(connection, { + actorType: claimed.actor_type, + actorId: claimed.actor_id, + operation: claimed.message_operation ?? claimed.operation, + deliveryMode: "internal", + arguments: jsonObject(JSON.parse(claimed.arguments)), + idempotencyKey: `reminder:${claimed.id}:${claimed.occurrence}`, + }) await connection.run( `UPDATE ${this.table("reminders")} - SET status = ?, occurrence = occurrence + 1, run_at_ms = ?, claimed_by = NULL, claimed_at_ms = NULL + SET status = ?, occurrence = occurrence + 1, run_at_ms = ?, last_run_at_ms = ?, + claimed_by = NULL, claimed_at_ms = NULL WHERE id = ? AND claimed_by = ?`, [ interval === undefined ? "completed" : "scheduled", nextRun, + now, claimed.id, claimed.claimed_by, ], @@ -2474,10 +2485,18 @@ function earliestReminder( return first.id < second.id ? first : second } +function reminderShouldEnqueue(options: { reminder: ReminderRow; now: number }): boolean { + const interval = + options.reminder.interval_ms === null ? undefined : Number(options.reminder.interval_ms) + if (interval === undefined) return true + if (options.reminder.missed_policy !== "skip") return true + return options.now < Number(options.reminder.run_at_ms) + interval +} + function nextReminderRun(options: { previousRun: number interval: number - missedPolicy: "latest" | "all" + missedPolicy: "latest" | "all" | "skip" now: number }): number { const { previousRun, interval, missedPolicy, now } = options diff --git a/src/runtime.ts b/src/runtime.ts index f75958f..61987c4 100644 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -178,6 +178,7 @@ type CommitActionHandler = ( function scheduledReminderOf(row: ReminderRow): ScheduledReminder { const operation = row.message_operation ?? row.operation const name = row.operation + const parsedError = row.error === null ? null : jsonObject(JSON.parse(row.error)) return { name, operation, @@ -187,6 +188,9 @@ function scheduledReminderOf(row: ReminderRow): ScheduledReminder { missedPolicy: row.missed_policy, status: row.status, handle: { name }, + lastRunAtMilliseconds: row.last_run_at_ms == null ? null : Number(row.last_run_at_ms), + occurrence: Number(row.occurrence), + errorName: typeof parsedError?.name === "string" ? parsedError.name : null, } } @@ -1693,12 +1697,18 @@ export class SolidObjectsRuntime { reminder: ReminderRow, options: { nowMilliseconds?: number } = {}, ): Promise { - const actor = this.fetchActor(reminder.actor_type) - const dispatchOperation = reminder.message_operation ?? reminder.operation - if (!actor.operations.has(dispatchOperation)) { - throw new UnknownOperation(`unknown reminder operation ${JSON.stringify(dispatchOperation)}`) - } - const message = await this.repository.enqueueReminder(reminder, options) + const message = await this.repository.enqueueReminder(reminder, { + ...options, + beforeEnqueue: (claimed) => { + const actor = this.fetchActor(claimed.actor_type) + const dispatchOperation = claimed.message_operation ?? claimed.operation + if (!actor.operations.has(dispatchOperation)) { + throw new UnknownOperation( + `unknown reminder operation ${JSON.stringify(dispatchOperation)}`, + ) + } + }, + }) if (!message) return this.wakeUp("actors") diff --git a/src/schema.ts b/src/schema.ts index 85f34f8..1c35501 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -15,7 +15,8 @@ const DEAD_LETTER_REDRIVE_VERSION = 11 const REQUEST_ID_LOOKUP_VERSION = 12 const REMEMBERED_KEYS_VERSION = 13 const EFFECT_POSITION_VERSION = 14 -const LATEST_VERSION = EFFECT_POSITION_VERSION +const REMINDER_SKIP_VERSION = 15 +const LATEST_VERSION = REMINDER_SKIP_VERSION export const SCHEMA_VERSIONS: readonly number[] = Object.freeze( Array.from({ length: LATEST_VERSION }, (_unused, index) => index + 1), @@ -142,12 +143,13 @@ export async function installSchema(options: { run_at_ms INTEGER NOT NULL, arguments TEXT NOT NULL, interval_ms INTEGER, - missed_policy TEXT NOT NULL CHECK (missed_policy IN ('latest', 'all')), + missed_policy TEXT NOT NULL CHECK (missed_policy IN ('latest', 'all', 'skip')), occurrence INTEGER NOT NULL DEFAULT 0, status TEXT NOT NULL CHECK (status IN ('scheduled', 'paused', 'completed')), claimed_by TEXT, claimed_at_ms INTEGER, error TEXT, + last_run_at_ms INTEGER, UNIQUE (instance_id, operation), FOREIGN KEY (instance_id) REFERENCES ${table("instances")}(id) ON DELETE CASCADE ) STRICT`) @@ -401,6 +403,16 @@ export async function installSchema(options: { }) } + if (!installedVersions.has(REMINDER_SKIP_VERSION)) { + await installReminderSkip({ connection, family, table: table, prefix }) + await recordMigration({ + connection, + table: table("schema_migrations"), + version: REMINDER_SKIP_VERSION, + schemaIdentity, + }) + } + if (installedVersions.has(POLLING_INDEXES_VERSION)) return const pollingIndexes = [ ["effects", `${prefix}effects_poll`, "status, available_at_ms, id"], @@ -482,6 +494,162 @@ async function installRedrive(options: { }) } +const MISSED_POLICY_CHECK = "missed_policy IN ('latest', 'all', 'skip')" + +async function installReminderSkip(options: { + connection: DatabaseConnection + family: DatabaseFamily + table: (name: string) => string + prefix: string +}): Promise { + const { connection, family, table, prefix } = options + const reminders = table("reminders") + const hasLastRun = await hasColumn({ + connection, + family, + table: reminders, + column: "last_run_at_ms", + }) + const allowsSkip = await missedPolicyAllowsSkip({ connection, family, table: reminders }) + if (hasLastRun && allowsSkip) return + + if (family === "sqlite") { + await rebuildSqliteReminders({ connection, table, prefix }) + return + } + + if (!hasLastRun) { + const ifExists = family === "postgresql" ? "IF NOT EXISTS " : "" + await connection.run(`ALTER TABLE ${reminders} ADD COLUMN ${ifExists}last_run_at_ms BIGINT`) + } + if (!allowsSkip) await replaceMissedPolicyCheck({ connection, family, table: reminders, prefix }) +} + +async function missedPolicyAllowsSkip(options: { + connection: DatabaseConnection + family: DatabaseFamily + table: string +}): Promise { + const { connection, family, table } = options + if (family === "sqlite") { + const row = await connection.get<{ sql: string | null }>( + "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", + [table], + ) + const sql = row?.sql ?? "" + return sql.includes("missed_policy") && sql.includes("'skip'") + } + if (family === "postgresql") { + const constraints = await connection.all<{ def: string }>( + `SELECT pg_get_constraintdef(oid) AS def FROM pg_constraint + WHERE conrelid = ?::regclass AND contype = 'c'`, + [table], + ) + return constraints.some(({ def }) => def.includes("missed_policy") && def.includes("'skip'")) + } + const constraints = await connection.all<{ clause: string }>( + `SELECT cc.CHECK_CLAUSE AS clause + FROM information_schema.TABLE_CONSTRAINTS tc + JOIN information_schema.CHECK_CONSTRAINTS cc + ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME + WHERE tc.TABLE_SCHEMA = DATABASE() AND tc.TABLE_NAME = ? AND tc.CONSTRAINT_TYPE = 'CHECK'`, + [table], + ) + return constraints.some( + ({ clause }) => clause.includes("missed_policy") && clause.includes("'skip'"), + ) +} + +async function replaceMissedPolicyCheck(options: { + connection: DatabaseConnection + family: DatabaseFamily + table: string + prefix: string +}): Promise { + const { connection, family, table, prefix } = options + const constraintName = `${prefix}reminders_missed_policy` + if (family === "postgresql") { + const constraints = await connection.all<{ name: string; def: string }>( + `SELECT conname AS name, pg_get_constraintdef(oid) AS def FROM pg_constraint + WHERE conrelid = ?::regclass AND contype = 'c'`, + [table], + ) + for (const constraint of constraints) { + if (!constraint.def.includes("missed_policy")) continue + await connection.run(`ALTER TABLE ${table} DROP CONSTRAINT IF EXISTS ${constraint.name}`) + } + await connection.run( + `ALTER TABLE ${table} ADD CONSTRAINT ${constraintName} CHECK (${MISSED_POLICY_CHECK})`, + ) + return + } + const constraints = await connection.all<{ name: string; clause: string }>( + `SELECT tc.CONSTRAINT_NAME AS name, cc.CHECK_CLAUSE AS clause + FROM information_schema.TABLE_CONSTRAINTS tc + JOIN information_schema.CHECK_CONSTRAINTS cc + ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME + WHERE tc.TABLE_SCHEMA = DATABASE() AND tc.TABLE_NAME = ? AND tc.CONSTRAINT_TYPE = 'CHECK'`, + [table], + ) + for (const constraint of constraints) { + if (!constraint.clause.includes("missed_policy")) continue + await connection.run(`ALTER TABLE ${table} DROP CHECK ${constraint.name}`) + } + await connection.run( + `ALTER TABLE ${table} ADD CONSTRAINT ${constraintName} CHECK (${MISSED_POLICY_CHECK})`, + ) +} + +async function rebuildSqliteReminders(options: { + connection: DatabaseConnection + table: (name: string) => string + prefix: string +}): Promise { + const { connection, table, prefix } = options + const reminders = table("reminders") + const rebuilt = table("reminders_skip") + const columns = await connection.all<{ name: string }>(`PRAGMA table_info(${reminders})`) + const names = new Set(columns.map(({ name }) => name)) + await connection.run(`CREATE TABLE ${rebuilt} ( + id TEXT PRIMARY KEY, + instance_id TEXT NOT NULL, + operation TEXT NOT NULL, + run_at_ms INTEGER NOT NULL, + arguments TEXT NOT NULL, + interval_ms INTEGER, + missed_policy TEXT NOT NULL CHECK (${MISSED_POLICY_CHECK}), + occurrence INTEGER NOT NULL DEFAULT 0, + status TEXT NOT NULL CHECK (status IN ('scheduled', 'paused', 'completed')), + claimed_by TEXT, + claimed_at_ms INTEGER, + error TEXT, + message_operation TEXT, + last_run_at_ms INTEGER, + UNIQUE (instance_id, operation), + FOREIGN KEY (instance_id) REFERENCES ${table("instances")}(id) ON DELETE CASCADE + ) STRICT`) + const selectColumn = (name: string) => (names.has(name) ? name : `NULL AS ${name}`) + await connection.run( + `INSERT INTO ${rebuilt} ( + id, instance_id, operation, run_at_ms, arguments, interval_ms, missed_policy, occurrence, + status, claimed_by, claimed_at_ms, error, message_operation, last_run_at_ms + ) + SELECT id, instance_id, operation, run_at_ms, arguments, interval_ms, missed_policy, occurrence, + status, claimed_by, claimed_at_ms, error, ${selectColumn("message_operation")}, + ${selectColumn("last_run_at_ms")} + FROM ${reminders}`, + ) + await connection.run(`DROP TABLE ${reminders}`) + await connection.run(`ALTER TABLE ${rebuilt} RENAME TO ${reminders}`) + await createIndex({ + connection, + family: "sqlite", + table: reminders, + name: `${prefix}reminders_due`, + columns: "status, run_at_ms, id", + }) +} + async function addEffectPosition(options: { connection: DatabaseConnection family: DatabaseFamily diff --git a/src/types.ts b/src/types.ts index 8414e59..e1ac797 100644 --- a/src/types.ts +++ b/src/types.ts @@ -14,9 +14,12 @@ export interface ScheduledReminder { readonly key: string | null readonly runAtMilliseconds: number readonly intervalMilliseconds: number | null - readonly missedPolicy: "all" | "latest" + readonly missedPolicy: "latest" | "all" | "skip" readonly status: ReminderStatus readonly handle: ReminderHandle + readonly lastRunAtMilliseconds: number | null + readonly occurrence: number + readonly errorName: string | null } export type ReminderReader = () => Promise diff --git a/test/cloudflare/contract.test.ts b/test/cloudflare/contract.test.ts index 5122f55..cf338c9 100644 --- a/test/cloudflare/contract.test.ts +++ b/test/cloudflare/contract.test.ts @@ -1,10 +1,134 @@ -import { env } from "cloudflare:test" -import { describe } from "vitest" +import { env, evictDurableObject, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test" +import { describe, expect } from "vitest" import { createRuntime, durableObjects } from "../../src/cloudflare/index.js" +import type { Reminder } from "../../src/cloudflare/records.js" +import { PortableReminders } from "../support/portable-reminders.js" import { portableRuntimeContract } from "../support/portable-runtime-contract.js" +import { portableSchedulingContract } from "../support/portable-scheduling-contract.js" + +const authorizationContext = "allowed" +const runtime = () => createRuntime({ backend: durableObjects({ namespace: env.ACTORS }) }) +const stubOf = (actorId: string) => + env.ACTORS.getByName(JSON.stringify(["PortableReminders", actorId])) describe("Durable Objects portable runtime contract", () => { portableRuntimeContract(() => createRuntime({ backend: durableObjects({ namespace: env.ACTORS }) }), ) }) + +describe("Durable Objects portable scheduling contract", () => { + portableSchedulingContract(runtime, { + async driveDueWork(actorId: string) { + const stub = stubOf(actorId) + await runDurableObjectAlarm(stub) + for (let pass = 0; pass < 20; pass += 1) { + const snapshot = await runtime() + .ref(PortableReminders, actorId) + .snapshot({ authorizationContext }) + const reminder = snapshot.scheduledTick + if ( + reminder && + reminder.status === "scheduled" && + reminder.runAtMilliseconds <= Date.now() + ) { + await runDurableObjectAlarm(stub) + continue + } + break + } + }, + + async pauseArmedReminder(actorId: string) { + await runtime().ref(PortableReminders, actorId).with({ authorizationContext }).armFailNext() + const stub = stubOf(actorId) + await runInDurableObject(stub, (_object, state) => { + const row = state.storage.sql + .exec<{ record: string }>("SELECT record FROM reminders WHERE name = ?", "tick") + .one() + const reminder = JSON.parse(row.record) as Reminder + reminder.at = Date.now() - 1_000 + state.storage.sql.exec( + "UPDATE reminders SET due_at = ?, record = ? WHERE name = ?", + reminder.at, + JSON.stringify(reminder), + "tick", + ) + }) + await this.driveDueWork(actorId) + }, + + async interruptClaim(actorId: string) { + await evictDurableObject(stubOf(actorId)) + }, + + async assertAlarmContract(actorId: string) { + const stub = stubOf(actorId) + const alarmAfterArm = await runInDurableObject(stub, (_object, state) => + state.storage.getAlarm(), + ) + expect(alarmAfterArm).not.toBeNull() + + await runInDurableObject(stub, (_object, state) => state.storage.deleteAlarm()) + await evictDurableObject(stub) + expect( + await runInDurableObject(stub, (_object, state) => state.storage.getAlarm()), + ).toBeNull() + + await runInDurableObject(stub, (object) => hostAlarm(object)) + expect( + await runInDurableObject(stub, (_object, state) => state.storage.getAlarm()), + ).not.toBeNull() + + await runInDurableObject(stub, async (object, state) => { + state.storage.sql.exec("DELETE FROM reminders") + state.storage.sql.exec("DELETE FROM messages") + state.storage.sql.exec("DELETE FROM outboxes") + state.storage.sql.exec("DELETE FROM subscriptions") + state.storage.sql.exec("DELETE FROM metadata WHERE key = 'receiptCleanupPending'") + await hostAlarm(object) + }) + expect( + await runInDurableObject(stub, (_object, state) => state.storage.getAlarm()), + ).toBeNull() + + const before = Date.now() + await expect( + runInDurableObject(stub, async (object, state) => { + state.storage.sql.exec( + "INSERT INTO reminders(name, status, due_at, record) VALUES (?, ?, ?, ?)", + "tick", + "scheduled", + Date.now(), + "not-json", + ) + await hostAlarm(object) + }), + ).rejects.toThrow() + const retryAt = await runInDurableObject(stub, (_object, state) => state.storage.getAlarm()) + expect(retryAt).not.toBeNull() + expect(retryAt!).toBeLessThanOrEqual(before + 30_000 + 1_000) + await runInDurableObject(stub, (_object, state) => { + state.storage.sql.exec("DELETE FROM reminders WHERE name = ?", "tick") + }) + }, + + async resumePausedReminder(actorId: string, runAt: Date) { + await runtime() + .actorAdministration({ + actorType: "PortableReminders", + actorId, + authorizationContext, + }) + .resumeReminder({ name: "tick", runAt }) + }, + }) +}) + +async function hostAlarm(object: object): Promise { + const alarm = (object as { alarm?: () => void | Promise }).alarm + if (typeof alarm !== "function") { + throw new Error("expected the Durable Object host to expose alarm()") + } + await alarm.call(object) +} diff --git a/test/cloudflare/worker.ts b/test/cloudflare/worker.ts index 441de6e..402d72a 100644 --- a/test/cloudflare/worker.ts +++ b/test/cloudflare/worker.ts @@ -9,6 +9,7 @@ import { type JsonObject, } from "../../src/core.js" import { PortableCounter } from "../support/portable-actor.js" +import { PortableReminders } from "../support/portable-reminders.js" import { createDurableObjectsHost, createDurableObjectsSessionHost, @@ -141,7 +142,7 @@ export class Counter extends Actor { this.commitAction("database-write") } - armRecurring(options: { at: number; interval: number; missed: "all" | "latest" }): void { + armRecurring(options: { at: number; interval: number; missed: "latest" | "all" | "skip" }): void { this.schedule({ at: new Date(options.at), everyMilliseconds: options.interval, @@ -221,7 +222,7 @@ export class EffectCallbacks extends Actor { } export class Actors extends createDurableObjectsHost({ - actors: [Counter, PortableCounter, VersionedCounter, EffectCallbacks], + actors: [Counter, PortableCounter, PortableReminders, VersionedCounter, EffectCallbacks], configure: (environment) => ({ backend: durableObjects({ namespace: { diff --git a/test/dead-letters.test.ts b/test/dead-letters.test.ts index a71ae47..eee043b 100644 --- a/test/dead-letters.test.ts +++ b/test/dead-letters.test.ts @@ -225,6 +225,118 @@ describe("schema migrations", () => { .run({ source: "legacy" }) expect(duplicate.id).toBe(message.id) }) + + it("accepts skip and records last run on a database that already has the current schema", async () => { + const directory = mkdtempSync(join(tmpdir(), "solid-objects-schema-")) + temporaryDirectories.push(directory) + const path = join(directory, "database.sqlite3") + runtime = configuredRuntime({ database: sqlite({ path }) }) + await runtime.install() + await runtime.settings.database.transaction(async (connection) => { + const now = await connection.nowMilliseconds() + await connection.run( + `INSERT INTO solid_objects_instances + (id, actor_type, actor_id, state, state_version, created_at_ms, updated_at_ms) + VALUES (?, ?, ?, '{}', 1, ?, ?)`, + ["instance-skip", "SchemaReminderActor", "one", now, now], + ) + for (const [id, name, missed] of [ + ["reminder-latest", "ping", "latest"], + ["reminder-all", "ping:all", "all"], + ] as const) { + await connection.run( + `INSERT INTO solid_objects_reminders + (id, instance_id, operation, message_operation, run_at_ms, arguments, interval_ms, + missed_policy, occurrence, status) + VALUES (?, ?, ?, ?, ?, '{}', ?, ?, 0, 'scheduled')`, + [id, "instance-skip", name, "ping", now + 60_000, 60_000, missed], + ) + } + }) + await runtime.close() + runtime = undefined + + const database = new DatabaseSync(path) + database.exec(` + DELETE FROM solid_objects_schema_migrations WHERE version = 15; + CREATE TABLE solid_objects_reminders_previous ( + id TEXT PRIMARY KEY, + instance_id TEXT NOT NULL, + operation TEXT NOT NULL, + run_at_ms INTEGER NOT NULL, + arguments TEXT NOT NULL, + interval_ms INTEGER, + missed_policy TEXT NOT NULL CHECK (missed_policy IN ('latest', 'all')), + occurrence INTEGER NOT NULL DEFAULT 0, + status TEXT NOT NULL CHECK (status IN ('scheduled', 'paused', 'completed')), + claimed_by TEXT, + claimed_at_ms INTEGER, + error TEXT, + message_operation TEXT, + UNIQUE (instance_id, operation), + FOREIGN KEY (instance_id) REFERENCES solid_objects_instances(id) ON DELETE CASCADE + ) STRICT; + INSERT INTO solid_objects_reminders_previous + (id, instance_id, operation, run_at_ms, arguments, interval_ms, missed_policy, occurrence, + status, claimed_by, claimed_at_ms, error, message_operation) + SELECT id, instance_id, operation, run_at_ms, arguments, interval_ms, missed_policy, occurrence, + status, claimed_by, claimed_at_ms, error, message_operation + FROM solid_objects_reminders; + DROP TABLE solid_objects_reminders; + ALTER TABLE solid_objects_reminders_previous RENAME TO solid_objects_reminders; + CREATE INDEX solid_objects_reminders_due ON solid_objects_reminders (status, run_at_ms, id); + `) + database.close() + + runtime = configuredRuntime({ database: sqlite({ path }) }) + await runtime.install() + await runtime.install() + + const versions = await runtime.settings.database.connection((connection) => + connection.all<{ version: number | bigint }>( + "SELECT version FROM solid_objects_schema_migrations ORDER BY version", + ), + ) + const columns = await runtime.settings.database.connection((connection) => + connection.all<{ name: string }>("PRAGMA table_info(solid_objects_reminders)"), + ) + const sql = await runtime.settings.database.connection((connection) => + connection.get<{ sql: string }>( + "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'solid_objects_reminders'", + ), + ) + const preserved = await runtime.settings.database.connection((connection) => + connection.all<{ id: string; missed_policy: string; occurrence: number | bigint }>( + "SELECT id, missed_policy, occurrence FROM solid_objects_reminders ORDER BY id", + ), + ) + await runtime.settings.database.transaction(async (connection) => { + const now = await connection.nowMilliseconds() + await connection.run( + `INSERT INTO solid_objects_reminders + (id, instance_id, operation, message_operation, run_at_ms, arguments, interval_ms, + missed_policy, occurrence, status) + VALUES (?, ?, ?, ?, ?, '{}', ?, 'skip', 0, 'scheduled')`, + ["reminder-skip", "instance-skip", "ping:skip", "ping", now + 60_000, 60_000], + ) + }) + const skipRow = await runtime.settings.database.connection((connection) => + connection.get<{ missed_policy: string; last_run_at_ms: number | bigint | null }>( + "SELECT missed_policy, last_run_at_ms FROM solid_objects_reminders WHERE id = ?", + ["reminder-skip"], + ), + ) + + expect(versions.map(({ version }) => Number(version))).toEqual([...SCHEMA_VERSIONS]) + expect(columns.map(({ name }) => name)).toContain("last_run_at_ms") + expect(sql?.sql).toContain("'skip'") + expect(preserved.map((row) => ({ ...row, occurrence: Number(row.occurrence) }))).toEqual([ + { id: "reminder-all", missed_policy: "all", occurrence: 0 }, + { id: "reminder-latest", missed_policy: "latest", occurrence: 0 }, + ]) + expect(skipRow).toEqual({ missed_policy: "skip", last_run_at_ms: null }) + expect(await installedPollingIndexes(runtime)).toEqual(POLLING_INDEX_COLUMNS) + }) }) const POLLING_INDEX_COLUMNS = { diff --git a/test/portable-runtime.test.ts b/test/portable-runtime.test.ts index fd28d96..4973cd0 100644 --- a/test/portable-runtime.test.ts +++ b/test/portable-runtime.test.ts @@ -2,7 +2,12 @@ import { afterEach, beforeEach, describe } from "vitest" import { sqlite } from "../src/database/sqlite.js" import { createRuntime, type SolidObjectsRuntime } from "../src/runtime.js" import { PortableCounter } from "./support/portable-actor.js" +import { PortableReminders } from "./support/portable-reminders.js" import { portableRuntimeContract } from "./support/portable-runtime-contract.js" +import { portableSchedulingContract } from "./support/portable-scheduling-contract.js" + +const authorizeAllowed = (input: { authorizationContext?: unknown }) => + input.authorizationContext === "allowed" describe("SQL portable runtime contract", () => { let runtime: SolidObjectsRuntime @@ -11,13 +16,14 @@ describe("SQL portable runtime contract", () => { beforeEach(async () => { runtime = createRuntime({ database: sqlite({ path: ":memory:" }), - authorizeMessage: (input) => input.authorizationContext === "allowed", - authorizeQuery: (input) => input.authorizationContext === "allowed", - authorizeDestroy: (input) => input.authorizationContext === "allowed", + authorizeMessage: authorizeAllowed, + authorizeQuery: authorizeAllowed, + authorizeDestroy: authorizeAllowed, syncPollingIntervalMilliseconds: 1, pollingIntervalMilliseconds: 1, }) runtime.register(PortableCounter) + runtime.register(PortableReminders) await runtime.install() controller = new AbortController() running = runtime.run(controller.signal) @@ -29,3 +35,89 @@ describe("SQL portable runtime contract", () => { }) portableRuntimeContract(() => runtime) }) + +describe("SQL portable scheduling contract", () => { + let runtime: SolidObjectsRuntime + beforeEach(async () => { + runtime = createRuntime({ + database: sqlite({ path: ":memory:" }), + authorizeMessage: authorizeAllowed, + authorizeQuery: authorizeAllowed, + authorizeDestroy: authorizeAllowed, + syncPollingIntervalMilliseconds: 1, + pollingIntervalMilliseconds: 1, + }) + runtime.register(PortableCounter) + runtime.register(PortableReminders) + await runtime.install() + }) + afterEach(async () => { + await runtime?.close() + }) + + portableSchedulingContract(() => runtime, { + async driveDueWork() { + const scheduler = runtime.reminderScheduler() + const worker = runtime.worker() + try { + await scheduler.runUntilIdle() + await worker.runUntilIdle() + } finally { + await scheduler.stop() + await worker.stop() + } + }, + + async pauseArmedReminder(actorId: string) { + await runtime.settings.database.transaction(async (connection) => { + const now = await connection.nowMilliseconds() + await connection.run( + `UPDATE ${runtime.repository.table("reminders")} + SET message_operation = 'notAnOperation', run_at_ms = ? + WHERE operation = 'tick' AND instance_id = ( + SELECT id FROM ${runtime.repository.table("instances")} + WHERE actor_type = ? AND actor_id = ? + )`, + [now, "PortableReminders", actorId], + ) + }) + await this.driveDueWork(actorId) + }, + + async interruptClaim(actorId: string) { + await runtime.settings.database.transaction(async (connection) => { + const now = await connection.nowMilliseconds() + await connection.run( + `UPDATE ${runtime.repository.table("reminders")} + SET claimed_by = ?, claimed_at_ms = ? + WHERE operation = 'tick' AND instance_id = ( + SELECT id FROM ${runtime.repository.table("instances")} + WHERE actor_type = ? AND actor_id = ? + )`, + ["missing-owner", now, "PortableReminders", actorId], + ) + }) + }, + + async assertAlarmContract(actorId: string) { + await this.driveDueWork(actorId) + }, + + async resumePausedReminder(actorId: string, runAt: Date) { + const reminder = await runtime.settings.database.connection((connection) => + connection.get<{ id: string }>( + `SELECT reminders.id AS id FROM ${runtime.repository.table("reminders")} reminders + JOIN ${runtime.repository.table("instances")} instances + ON instances.id = reminders.instance_id + WHERE reminders.operation = 'tick' AND instances.actor_type = ? AND instances.actor_id = ?`, + ["PortableReminders", actorId], + ), + ) + if (!reminder) throw new Error(`expected a paused reminder for ${actorId}`) + await runtime.repository.resumeReminder({ + id: reminder.id, + runAtMilliseconds: runAt.getTime(), + }) + }, + }) +}) diff --git a/test/reminder-cancellation.test.ts b/test/reminder-cancellation.test.ts index e09a641..7f836e3 100644 --- a/test/reminder-cancellation.test.ts +++ b/test/reminder-cancellation.test.ts @@ -267,6 +267,9 @@ describe("reminder cancellation", () => { missedPolicy: "latest", status: "scheduled", handle: { name: "trialExpired" }, + lastRunAtMilliseconds: null, + occurrence: 0, + errorName: null, }) }) diff --git a/test/support/portable-reminders.ts b/test/support/portable-reminders.ts new file mode 100644 index 0000000..ad75887 --- /dev/null +++ b/test/support/portable-reminders.ts @@ -0,0 +1,90 @@ +import { + Actor, + NonRetryableError, + type ReminderOptions, + type ScheduledReminder, +} from "../../src/core.js" + +export type SchedulingMissed = NonNullable + +export class PortableReminders extends Actor { + static override readonly actorType = "PortableReminders" + + count = 0 + failNextTick = false + + tick(): number { + if (this.failNextTick) throw new NonRetryableError("permanent failure") + this.count += 1 + return this.count + } + + failPermanently(): void { + throw new NonRetryableError("permanent failure") + } + + arm(options: { at: number; everyMilliseconds?: number; missed?: SchedulingMissed }): void { + this.schedule(scheduleOptions(options)).tick() + } + + armWithoutOperation(options: { at: number }): void { + this.schedule({ at: new Date(options.at) }) + } + + armFailNext(): void { + this.failNextTick = true + } + + get scheduledTick(): Promise { + return this.reminder("tick").then((reminder) => reminder ?? null) + } + + async inspect(): Promise { + return (await this.reminder("tick")) ?? null + } + + async inspectAll(): Promise { + return await this.reminders("tick") + } + + async replaceAndInspect(options: { + at: number + everyMilliseconds?: number + missed?: SchedulingMissed + }): Promise { + this.schedule(scheduleOptions(options)).tick() + return (await this.reminder("tick")) ?? null + } + + cancelTick(): unknown { + return this.unschedule("tick") + } + + async cancelThenInspect(): Promise { + this.unschedule("tick") + return (await this.reminder("tick")) ?? null + } + + async scheduleThenInspect(options: { + at: number + everyMilliseconds?: number + missed?: SchedulingMissed + }): Promise { + this.schedule(scheduleOptions(options)).tick() + return (await this.reminder("tick")) ?? null + } +} + +function scheduleOptions(options: { + at: number + everyMilliseconds?: number + missed?: SchedulingMissed +}): ReminderOptions { + return { + at: new Date(options.at), + ...(options.everyMilliseconds === undefined + ? {} + : { everyMilliseconds: options.everyMilliseconds }), + ...(options.missed === undefined ? {} : { missed: options.missed }), + } +} diff --git a/test/support/portable-scheduling-contract.ts b/test/support/portable-scheduling-contract.ts new file mode 100644 index 0000000..1f09d47 --- /dev/null +++ b/test/support/portable-scheduling-contract.ts @@ -0,0 +1,317 @@ +import { expect, it } from "vitest" +import type { ActorRuntime } from "../../src/core.js" +import type { ScheduledReminder } from "../../src/core.js" +import { PortableReminders, type SchedulingMissed } from "./portable-reminders.js" + +const authorizationContext = "allowed" +const INTERVAL = 60_000 + +export interface PortableSchedulingHooks { + driveDueWork(actorId: string): Promise + pauseArmedReminder(actorId: string): Promise + interruptClaim(actorId: string): Promise + assertAlarmContract(actorId: string): Promise + resumePausedReminder(actorId: string, runAt: Date): Promise +} + +export function portableSchedulingContract( + runtime: () => ActorRuntime, + hooks: PortableSchedulingHooks, +): void { + const referenceOf = (actorId: string) => + runtime().ref(PortableReminders, actorId).with({ authorizationContext }) + + const inspect = async (actorId: string): Promise => { + const snapshot = await runtime() + .ref(PortableReminders, actorId) + .snapshot({ authorizationContext }) + return snapshot.scheduledTick + } + + const countOf = async (actorId: string): Promise => { + const snapshot = await runtime() + .ref(PortableReminders, actorId) + .snapshot({ authorizationContext }) + return snapshot.count + } + + it("arms one reminder, requires an operation, and round-trips missed policies", async () => { + const actorId = "scheduling-create" + const reference = referenceOf(actorId) + const at = Date.now() + INTERVAL + + await expect( + referenceOf(`${actorId}-without-operation`).armWithoutOperation({ at }), + ).rejects.toMatchObject({ + details: { name: "ScheduleWithoutOperation" }, + }) + + await reference.arm({ at }) + const defaulted = await inspect(actorId) + expect(defaulted).toMatchObject({ + name: "tick", + operation: "tick", + runAtMilliseconds: at, + intervalMilliseconds: null, + missedPolicy: "latest", + status: "scheduled", + lastRunAtMilliseconds: null, + occurrence: 0, + errorName: null, + }) + expect(await reference.inspectAll()).toEqual([defaulted]) + + for (const missed of ["latest", "all", "skip"] as const) { + await reference.arm({ at, everyMilliseconds: INTERVAL, missed }) + expect(await inspect(actorId)).toMatchObject({ + missedPolicy: missed, + intervalMilliseconds: INTERVAL, + lastRunAtMilliseconds: null, + occurrence: 0, + errorName: null, + status: "scheduled", + }) + } + }) + + it("keeps last run and occurrence on replace, including the in-turn read", async () => { + const actorId = "scheduling-replace" + const reference = referenceOf(actorId) + const firstAt = Date.now() - 1_000 + await reference.arm({ at: firstAt, everyMilliseconds: INTERVAL, missed: "latest" }) + await hooks.driveDueWork(actorId) + const afterRun = await inspect(actorId) + expect(afterRun?.occurrence).toBe(1) + expect(afterRun?.lastRunAtMilliseconds).toEqual(expect.any(Number)) + expect(afterRun?.errorName).toBeNull() + expect(await countOf(actorId)).toBe(1) + + const movedAt = Date.now() + INTERVAL + const inTurn = await reference.replaceAndInspect({ + at: movedAt, + everyMilliseconds: INTERVAL, + missed: "skip", + }) + expect(inTurn).toMatchObject({ + runAtMilliseconds: movedAt, + intervalMilliseconds: INTERVAL, + missedPolicy: "skip", + status: "scheduled", + lastRunAtMilliseconds: afterRun!.lastRunAtMilliseconds, + occurrence: 1, + errorName: null, + }) + const stored = await inspect(actorId) + expect(stored).toEqual(inTurn) + expect(await reference.inspectAll()).toHaveLength(1) + }) + + it("cancels as an intent that returns nothing and still reads this turn's intents", async () => { + const actorId = "scheduling-cancel" + const reference = referenceOf(actorId) + expect([null, undefined]).toContain(await reference.cancelTick()) + expect(await inspect(actorId)).toBeNull() + + const at = Date.now() + INTERVAL + await reference.arm({ at }) + expect(await reference.cancelThenInspect()).toBeNull() + expect(await inspect(actorId)).toBeNull() + expect([null, undefined]).toContain(await reference.cancelTick()) + + const staged = await reference.scheduleThenInspect({ at, missed: "all" }) + expect(staged).toMatchObject({ + runAtMilliseconds: at, + missedPolicy: "all", + status: "scheduled", + lastRunAtMilliseconds: null, + occurrence: 0, + errorName: null, + }) + expect(await inspect(actorId)).toEqual(staged) + }) + + it("re-arms a recurring reminder and completes a one-shot", async () => { + const actorId = "scheduling-execution" + const reference = referenceOf(actorId) + const recurringAt = Date.now() - 1_000 + await reference.arm({ at: recurringAt, everyMilliseconds: INTERVAL, missed: "latest" }) + await hooks.driveDueWork(actorId) + const recurring = await inspect(actorId) + expect(await countOf(actorId)).toBe(1) + expect(recurring).toMatchObject({ status: "scheduled", occurrence: 1 }) + expect(recurring!.runAtMilliseconds).toBe(recurringAt + INTERVAL) + expect(recurring!.runAtMilliseconds).toBeGreaterThan(Date.now()) + + const oneShotId = "scheduling-oneshot" + const oneShotAt = Date.now() - 1_000 + await referenceOf(oneShotId).arm({ at: oneShotAt, missed: "skip" }) + await hooks.driveDueWork(oneShotId) + expect(await countOf(oneShotId)).toBe(1) + expect(await inspect(oneShotId)).toBeNull() + await hooks.driveDueWork(oneShotId) + expect(await countOf(oneShotId)).toBe(1) + }) + + it("applies latest, all, and skip to a missed recurring window", async () => { + const slightlyLate = Date.now() - 1_000 + const onTimeId = "scheduling-skip-on-time" + await referenceOf(onTimeId).arm({ + at: slightlyLate, + everyMilliseconds: INTERVAL, + missed: "skip", + }) + await hooks.driveDueWork(onTimeId) + const skipOnTime = await inspect(onTimeId) + expect(await countOf(onTimeId)).toBe(1) + expect(skipOnTime).toMatchObject({ + status: "scheduled", + occurrence: 1, + missedPolicy: "skip", + }) + expect(skipOnTime!.lastRunAtMilliseconds).toEqual(expect.any(Number)) + expect(skipOnTime!.runAtMilliseconds).toBe(slightlyLate + INTERVAL) + expect(skipOnTime!.runAtMilliseconds).toBeGreaterThan(Date.now()) + + const late = Date.now() - 2.5 * INTERVAL + const skipId = "scheduling-skip-late" + await referenceOf(skipId).arm({ at: late, everyMilliseconds: INTERVAL, missed: "skip" }) + const beforeSkip = await inspect(skipId) + await hooks.driveDueWork(skipId) + const skipped = await inspect(skipId) + const skipNow = Date.now() + expect(await countOf(skipId)).toBe(0) + expect(skipped).toMatchObject({ + status: "scheduled", + occurrence: beforeSkip!.occurrence, + lastRunAtMilliseconds: beforeSkip!.lastRunAtMilliseconds, + missedPolicy: "skip", + }) + expect(beforeSkip).toMatchObject({ occurrence: 0, lastRunAtMilliseconds: null }) + expect(skipped!.runAtMilliseconds).toBe(alignedAfter(late, INTERVAL, skipNow)) + expect(skipped!.runAtMilliseconds).toBeGreaterThan(skipNow) + + const latestId = "scheduling-latest" + await referenceOf(latestId).arm({ at: late, everyMilliseconds: INTERVAL, missed: "latest" }) + await hooks.driveDueWork(latestId) + const latest = await inspect(latestId) + const latestNow = Date.now() + expect(await countOf(latestId)).toBe(1) + expect(latest).toMatchObject({ status: "scheduled", occurrence: 1, missedPolicy: "latest" }) + expect(latest!.runAtMilliseconds).toBe(alignedAfter(late, INTERVAL, latestNow)) + expect(latest!.runAtMilliseconds).toBeGreaterThan(latestNow) + + const allId = "scheduling-all" + await referenceOf(allId).arm({ at: late, everyMilliseconds: INTERVAL, missed: "all" }) + await hooks.driveDueWork(allId) + const caughtUp = await inspect(allId) + const allNow = Date.now() + expect(await countOf(allId)).toBe(3) + expect(caughtUp).toMatchObject({ status: "scheduled", occurrence: 3, missedPolicy: "all" }) + expect(caughtUp!.runAtMilliseconds).toBeGreaterThan(allNow) + expect((caughtUp!.runAtMilliseconds - late) % INTERVAL).toBe(0) + }) + + it("reports last run, occurrence, and error name, including after pause and replace", async () => { + const actorId = "scheduling-fields" + const reference = referenceOf(actorId) + const future = Date.now() + INTERVAL + + const neverEnqueued = await reference.scheduleThenInspect({ at: future }) + expect(neverEnqueued).toMatchObject({ + lastRunAtMilliseconds: null, + occurrence: 0, + errorName: null, + }) + expect(await inspect(actorId)).toEqual(neverEnqueued) + + await reference.arm({ at: Date.now() - 1_000, everyMilliseconds: INTERVAL, missed: "latest" }) + await hooks.driveDueWork(actorId) + const afterEnqueue = await inspect(actorId) + expect(afterEnqueue).toMatchObject({ occurrence: 1, errorName: null, status: "scheduled" }) + expect(afterEnqueue!.lastRunAtMilliseconds).toEqual(expect.any(Number)) + + const skipAt = Date.now() - 2.5 * INTERVAL + await reference.arm({ at: skipAt, everyMilliseconds: INTERVAL, missed: "skip" }) + await hooks.driveDueWork(actorId) + expect(await inspect(actorId)).toMatchObject({ + occurrence: 1, + lastRunAtMilliseconds: afterEnqueue!.lastRunAtMilliseconds, + missedPolicy: "skip", + status: "scheduled", + }) + expect(await countOf(actorId)).toBe(1) + + await hooks.pauseArmedReminder(actorId) + const paused = await inspect(actorId) + expect(paused?.status).toBe("paused") + expect(typeof paused!.errorName).toBe("string") + expect(paused!.errorName!.length).toBeGreaterThan(0) + expect(paused!.occurrence).toBeGreaterThanOrEqual(1) + expect(paused!.lastRunAtMilliseconds).toEqual(expect.any(Number)) + + await hooks.resumePausedReminder(actorId, new Date(future)) + const resumed = await inspect(actorId) + expect(resumed).toMatchObject({ + status: "scheduled", + occurrence: paused!.occurrence, + lastRunAtMilliseconds: paused!.lastRunAtMilliseconds, + errorName: null, + runAtMilliseconds: future, + }) + + const replaced = await reference.replaceAndInspect({ at: future + INTERVAL, missed: "all" }) + expect(replaced).toMatchObject({ + status: "scheduled", + occurrence: paused!.occurrence, + lastRunAtMilliseconds: paused!.lastRunAtMilliseconds, + errorName: null, + missedPolicy: "all", + runAtMilliseconds: future + INTERVAL, + }) + }) + + it("recovers a due reminder after an interrupted claim and keeps the alarm contract", async () => { + const actorId = "scheduling-restart" + const reference = referenceOf(actorId) + await reference.arm({ at: Date.now() - 1_000 }) + await hooks.interruptClaim(actorId) + await hooks.driveDueWork(actorId) + expect(await countOf(actorId)).toBe(1) + expect(await inspect(actorId)).toBeNull() + + const alarmId = "scheduling-alarm" + await referenceOf(alarmId).arm({ at: Date.now() + INTERVAL }) + expect(await inspect(alarmId)).toMatchObject({ status: "scheduled", occurrence: 0 }) + await hooks.assertAlarmContract(alarmId) + expect(await countOf(alarmId)).toBe(0) + }) + + it("fires an internal reminder without authorizeMessage and still authorizes an external enqueue", async () => { + const actorId = "scheduling-auth" + const reference = referenceOf(actorId) + await reference.arm({ at: Date.now() - 1_000 }) + await hooks.driveDueWork(actorId) + expect(await countOf(actorId)).toBe(1) + + await expect(runtime().ref(PortableReminders, actorId).tick()).rejects.toMatchObject({ + name: "Unauthorized", + }) + expect(await reference.tick()).toBe(2) + }) + + it("does not deliver a fired reminder twice", async () => { + const actorId = "scheduling-once" + await referenceOf(actorId).arm({ at: Date.now() - 1_000 }) + await hooks.driveDueWork(actorId) + expect(await countOf(actorId)).toBe(1) + await hooks.driveDueWork(actorId) + expect(await countOf(actorId)).toBe(1) + expect(await inspect(actorId)).toBeNull() + }) +} + +function alignedAfter(scheduledAt: number, interval: number, now: number): number { + return scheduledAt + (Math.floor((now - scheduledAt) / interval) + 1) * interval +} + +export type { SchedulingMissed }