Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
25 changes: 22 additions & 3 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
15 changes: 10 additions & 5 deletions src/actor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export interface ReminderIntent {
atMilliseconds: number
arguments: JsonObject
intervalMilliseconds?: number
missedPolicy: "all" | "latest"
missedPolicy: "latest" | "all" | "skip"
}

export interface UnscheduleIntent {
Expand Down Expand Up @@ -159,7 +159,7 @@ export interface ActorClass<ActorType extends Actor = Actor> {
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
}
Expand Down Expand Up @@ -221,6 +221,7 @@ function applyReminderIntent(view: Map<string, ScheduledReminder>, intent: Remin
return
}

const existing = view.get(intent.name)
view.set(intent.name, {
name: intent.name,
operation: intent.operation,
Expand All @@ -230,6 +231,9 @@ function applyReminderIntent(view: Map<string, ScheduledReminder>, intent: Remin
missedPolicy: intent.missedPolicy,
status: "scheduled",
handle: { name: intent.name },
lastRunAtMilliseconds: existing?.lastRunAtMilliseconds ?? null,
occurrence: existing?.occurrence ?? 0,
errorName: null,
})
}

Expand Down Expand Up @@ -464,10 +468,11 @@ export abstract class Actor {
throw new TypeError("reading reminders is not available outside an actor turn")
}
const view = new Map<string, ScheduledReminder>()
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
}

Expand Down
61 changes: 50 additions & 11 deletions src/cloudflare/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -404,7 +411,7 @@ export class ActorEngine {
}

private readReminders = async (): Promise<ScheduledReminder[]> =>
this.store.rows<Reminder>("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:
Expand All @@ -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<Reminder>(query, parameters).map(storedReminder)
}

private async snapshot(identity: ActorIdentity): Promise<JsonObject> {
const { definition, instance, state } = this.committed(identity)
const actor = hydrateActor({
Expand Down Expand Up @@ -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(),
Expand All @@ -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
Expand Down Expand Up @@ -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<Reminder>(
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",
Expand All @@ -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) {
Expand All @@ -1054,7 +1091,7 @@ export class ActorEngine {

private completeReminder(message: Message): void {
if (!message.reminder) return
const reminder = this.store.rows<Reminder>("SELECT record FROM reminders WHERE name = ?", [
const reminder = this.reminderRows("SELECT record FROM reminders WHERE name = ?", [
message.reminder.name,
])[0]
if (
Expand All @@ -1064,21 +1101,22 @@ 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)
}

private pauseReminder(message: Message): void {
if (!message.reminder) return
const reminder = this.store.rows<Reminder>("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)
}

Expand Down Expand Up @@ -1137,7 +1175,7 @@ export class ActorEngine {
return normalizeJson(outbox)
}
if (action === "resumeReminder") {
const reminder = this.store.rows<Reminder>("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")
Expand All @@ -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) {
Expand Down
15 changes: 14 additions & 1 deletion src/cloudflare/records.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 2 additions & 1 deletion src/records.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion src/reminder-administration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
43 changes: 31 additions & 12 deletions src/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1900,7 +1900,7 @@ export class Repository {

async enqueueReminder(
reminder: ReminderRow,
options: { nowMilliseconds?: number } = {},
options: { nowMilliseconds?: number; beforeEnqueue?: (reminder: ReminderRow) => void } = {},
): Promise<MessageRow | undefined> {
return this.settings.database.transaction(async (connection) => {
const now = options.nowMilliseconds ?? (await connection.nowMilliseconds())
Expand All @@ -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
Expand All @@ -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,
],
Expand Down Expand Up @@ -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
Expand Down
Loading