The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
| 1 | import type { RuntimeContext } from "alchemy/RuntimeContext"; |
| 2 | import * as Clock from "effect/Clock"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Stream from "effect/Stream"; |
| 5 | import { ensureAlarmTables, reconcileDurableObjectAlarm } from "./DurableObjectAlarmStorage.ts"; |
| 6 | import { DurableObjectState } from "./DurableObjectState.ts"; |
| 7 | import type { SqlStorageValue } from "./DurableObjectStorage.ts"; |
| 8 | |
| 9 | // --------------------------------------------------------------------------- |
| 10 | // Scheduled Events — SQLite-backed cron/timer for Durable Objects |
| 11 | // --------------------------------------------------------------------------- |
| 12 | |
| 13 | const ensureTable = Effect.gen(function* () { |
| 14 | const ctx = yield* DurableObjectState; |
| 15 | yield* ensureAlarmTables(ctx.raw.storage); |
| 16 | }); |
| 17 | |
| 18 | const inTransaction = <A, R>(effect: Effect.Effect<A, never, R>) => |
| 19 | Effect.gen(function* () { |
| 20 | const ctx = yield* DurableObjectState; |
| 21 | return yield* ctx.storage.transaction(effect).pipe(Effect.orDie); |
| 22 | }); |
| 23 | |
| 24 | export interface ScheduledEvent { |
| 25 | id: string; |
| 26 | runAt: Date; |
| 27 | repeatMs?: number; |
| 28 | payload: unknown; |
| 29 | } |
| 30 | |
| 31 | interface EventRow extends Record<string, SqlStorageValue> { |
| 32 | id: string; |
| 33 | run_at: number; |
| 34 | repeat_ms: number | null; |
| 35 | payload: string; |
| 36 | } |
| 37 | |
| 38 | const toScheduledEvent = (row: EventRow): ScheduledEvent => ({ |
| 39 | id: row.id, |
| 40 | runAt: new Date(row.run_at), |
| 41 | repeatMs: row.repeat_ms ?? undefined, |
| 42 | payload: JSON.parse(row.payload) as unknown, |
| 43 | }); |
| 44 | |
| 45 | /** |
| 46 | * Schedule (or reschedule) a named event on the current Durable Object. |
| 47 | * |
| 48 | * The event is persisted in a SQLite table and the DO alarm is set to |
| 49 | * the earliest pending `runAt`. If an event with the same `id` already |
| 50 | * exists it is replaced (upsert). |
| 51 | * |
| 52 | * @param id Stable identifier for the event (used for upsert / cancel). |
| 53 | * @param runAt When the event should fire. |
| 54 | * @param payload Arbitrary JSON-serialisable data delivered to the alarm handler. |
| 55 | * @param repeatMs If set, the event re-schedules itself this many ms after each fire. |
| 56 | */ |
| 57 | export const scheduleEvent = Effect.fn(function* ( |
| 58 | id: string, |
| 59 | runAt: Date, |
| 60 | payload: unknown, |
| 61 | repeatMs?: number, |
| 62 | ) { |
| 63 | yield* ensureTable; |
| 64 | const ctx = yield* DurableObjectState; |
| 65 | |
| 66 | yield* ctx.storage.sql |
| 67 | .exec( |
| 68 | `INSERT OR REPLACE INTO alchemy_scheduled_events (id, run_at, repeat_ms, payload) |
| 69 | VALUES (?, ?, ?, ?)`, |
| 70 | id, |
| 71 | runAt.getTime(), |
| 72 | repeatMs ?? null, |
| 73 | JSON.stringify(payload), |
| 74 | ) |
| 75 | .pipe(Effect.asVoid); |
| 76 | |
| 77 | yield* reconcileAlarm; |
| 78 | }, inTransaction); |
| 79 | |
| 80 | /** |
| 81 | * Cancel a previously scheduled event by id. No-op if the event does not exist. |
| 82 | */ |
| 83 | export const cancelEvent = Effect.fn(function* (id: string) { |
| 84 | yield* ensureTable; |
| 85 | const ctx = yield* DurableObjectState; |
| 86 | |
| 87 | yield* ctx.storage.sql |
| 88 | .exec(`DELETE FROM alchemy_scheduled_events WHERE id = ?`, id) |
| 89 | .pipe(Effect.asVoid); |
| 90 | |
| 91 | yield* reconcileAlarm; |
| 92 | }, inTransaction); |
| 93 | |
| 94 | /** |
| 95 | * List all currently scheduled events, ordered by `runAt` ascending. |
| 96 | */ |
| 97 | export const listEvents: Effect.Effect< |
| 98 | ScheduledEvent[], |
| 99 | never, |
| 100 | DurableObjectState | RuntimeContext |
| 101 | > = Effect.gen(function* () { |
| 102 | yield* ensureTable; |
| 103 | const ctx = yield* DurableObjectState; |
| 104 | |
| 105 | const cursor = yield* ctx.storage.sql.exec<EventRow>( |
| 106 | `SELECT id, run_at, repeat_ms, payload FROM alchemy_scheduled_events ORDER BY run_at ASC`, |
| 107 | ); |
| 108 | |
| 109 | return yield* cursor.pipe(Stream.map(toScheduledEvent), Stream.runCollect); |
| 110 | }); |
| 111 | |
| 112 | /** |
| 113 | * Process all events whose `runAt` <= now. Returns the fired events. |
| 114 | * |
| 115 | * - One-shot events are deleted after firing. |
| 116 | * - Repeating events have their `runAt` bumped by `repeatMs`. |
| 117 | * - The DO alarm is re-set to the next pending event (if any). |
| 118 | * |
| 119 | * Call this from your Durable Object's `alarm` handler: |
| 120 | * |
| 121 | * ```ts |
| 122 | * alarm: () => Effect.gen(function* () { |
| 123 | * const fired = yield* Cloudflare.Workers.processScheduledEvents; |
| 124 | * for (const event of fired) { |
| 125 | * // handle each event |
| 126 | * } |
| 127 | * }) |
| 128 | * ``` |
| 129 | */ |
| 130 | export const processScheduledEvents: Effect.Effect< |
| 131 | ScheduledEvent[], |
| 132 | never, |
| 133 | DurableObjectState | RuntimeContext |
| 134 | > = Effect.gen(function* () { |
| 135 | yield* ensureTable; |
| 136 | const ctx = yield* DurableObjectState; |
| 137 | const now = yield* Clock.currentTimeMillis; |
| 138 | |
| 139 | const cursor = yield* ctx.storage.sql.exec<EventRow>( |
| 140 | `SELECT id, run_at, repeat_ms, payload FROM alchemy_scheduled_events WHERE run_at <= ? ORDER BY run_at ASC`, |
| 141 | now, |
| 142 | ); |
| 143 | |
| 144 | const rows = yield* cursor.toArray(); |
| 145 | // The native transaction holds the snapshot stable while these statements |
| 146 | // run. Cross the SQL/Effect boundary once per category, rather than per row. |
| 147 | if (rows.some((row) => row.repeat_ms === null)) { |
| 148 | yield* Effect.asVoid( |
| 149 | ctx.storage.sql.exec( |
| 150 | `DELETE FROM alchemy_scheduled_events WHERE run_at <= ? AND repeat_ms IS NULL`, |
| 151 | now, |
| 152 | ), |
| 153 | ); |
| 154 | } |
| 155 | if (rows.some((row) => row.repeat_ms !== null)) { |
| 156 | yield* Effect.asVoid( |
| 157 | ctx.storage.sql.exec( |
| 158 | // Force binary64 addition, matching the former JavaScript now + repeat_ms |
| 159 | // even when an integral result is beyond Number.MAX_SAFE_INTEGER. |
| 160 | `UPDATE alchemy_scheduled_events |
| 161 | SET run_at = CAST(? AS REAL) + CAST(repeat_ms AS REAL) |
| 162 | WHERE run_at <= ? AND repeat_ms IS NOT NULL`, |
| 163 | now, |
| 164 | now, |
| 165 | ), |
| 166 | ); |
| 167 | } |
| 168 | // Parse before reconciling the alarm: malformed payloads still roll back all |
| 169 | // row mutations and leave the native alarm unchanged. |
| 170 | const fired = rows.map(toScheduledEvent); |
| 171 | |
| 172 | yield* reconcileAlarm; |
| 173 | return fired; |
| 174 | }).pipe(inTransaction); |
| 175 | |
| 176 | /** |
| 177 | * Set the DO alarm to the earliest pending event, or clear it if none remain. |
| 178 | */ |
| 179 | const reconcileAlarm: Effect.Effect<void, never, DurableObjectState | RuntimeContext> = Effect.gen( |
| 180 | function* () { |
| 181 | const ctx = yield* DurableObjectState; |
| 182 | |
| 183 | yield* reconcileDurableObjectAlarm(ctx.raw.storage); |
| 184 | }, |
| 185 | ); |