The best way to control Claude Code, Codex and more from any computer or phone

main
ts 129 lines 4.86 KB
Raw
1 import type * as cf from "@cloudflare/workers-types";
2 import * as Clock from "effect/Clock";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import { ActiveStorageTransactions } from "./DurableObjectTransactionContext.ts";
6
7 const SCHEMA_VERSION = 2;
8
9 export class UnsupportedAlarmSchemaVersion extends Data.TaggedError(
10 "UnsupportedAlarmSchemaVersion",
11 )<{
12 readonly version: number;
13 readonly supportedVersion: number;
14 }> {}
15
16 export const ensureAlarmTables = (storage: cf.DurableObjectStorage) =>
17 Effect.gen(function* () {
18 const transaction = (yield* ActiveStorageTransactions).get(storage);
19 if (transaction?.alarmTablesEnsured) return;
20 yield* initializeAlarmTables(storage);
21 if (transaction !== undefined) transaction.alarmTablesEnsured = true;
22 });
23
24 const initializeAlarmTables = (storage: cf.DurableObjectStorage) =>
25 Effect.sync(() => {
26 const hasVersion =
27 storage.sql
28 .exec<{ name: string }>(
29 "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'alchemy_alarm_schema'",
30 )
31 .toArray().length > 0;
32 const version = hasVersion
33 ? storage.sql
34 .exec<{ version: number }>("SELECT version FROM alchemy_alarm_schema WHERE id = 1")
35 .one().version
36 : 0;
37 if (version === SCHEMA_VERSION) return;
38 if (version !== 0 && version !== 1) {
39 throw new UnsupportedAlarmSchemaVersion({
40 version,
41 supportedVersion: SCHEMA_VERSION,
42 });
43 }
44
45 storage.transactionSync(() => {
46 if (version === 0) {
47 // Version 0 is the original, unversioned scheduleEvent schema.
48 storage.sql.exec(`
49 CREATE TABLE IF NOT EXISTS alchemy_scheduled_events (
50 id TEXT PRIMARY KEY,
51 run_at INTEGER NOT NULL,
52 repeat_ms INTEGER,
53 payload TEXT NOT NULL
54 );
55 CREATE INDEX IF NOT EXISTS idx_alchemy_scheduled_events_run_at
56 ON alchemy_scheduled_events (run_at);
57 CREATE TABLE alchemy_alarm_callbacks (
58 callback TEXT NOT NULL,
59 id TEXT NOT NULL,
60 version TEXT NOT NULL,
61 run_at INTEGER NOT NULL,
62 payload TEXT NOT NULL,
63 PRIMARY KEY (callback, id)
64 );
65 CREATE INDEX idx_alchemy_alarm_callbacks_run_at
66 ON alchemy_alarm_callbacks (run_at, callback, id);
67 CREATE TABLE IF NOT EXISTS alchemy_alarm_schema (
68 id INTEGER PRIMARY KEY CHECK (id = 1),
69 version INTEGER NOT NULL
70 );
71 INSERT INTO alchemy_alarm_schema (id, version) VALUES (1, 1)
72 ON CONFLICT (id) DO UPDATE SET version = excluded.version;
73 `);
74 }
75 // Keep run_at as the indexed effective wake deadline. Existing rows have
76 // no recoverable original deadline, so their current wake is the baseline.
77 storage.sql.exec(`
78 ALTER TABLE alchemy_alarm_callbacks ADD COLUMN scheduled_at INTEGER NOT NULL DEFAULT 0;
79 ALTER TABLE alchemy_alarm_callbacks ADD COLUMN retry_at INTEGER;
80 ALTER TABLE alchemy_alarm_callbacks ADD COLUMN attempts INTEGER NOT NULL DEFAULT 0;
81 ALTER TABLE alchemy_alarm_callbacks ADD COLUMN parked INTEGER NOT NULL DEFAULT 0;
82 ALTER TABLE alchemy_alarm_callbacks ADD COLUMN progress INTEGER NOT NULL DEFAULT -1;
83 UPDATE alchemy_alarm_callbacks SET scheduled_at = run_at;
84 UPDATE alchemy_alarm_schema SET version = 2 WHERE id = 1;
85 `);
86 });
87 });
88
89 // Both schedulers share the Durable Object's single native alarm.
90 export const reconcileDurableObjectAlarm = (storage: cf.DurableObjectStorage) =>
91 Effect.gen(function* () {
92 const transaction = (yield* ActiveStorageTransactions).get(storage);
93 if (transaction !== undefined) {
94 transaction.alarmDirty = true;
95 } else {
96 yield* reconcileAlarm(storage);
97 }
98 });
99
100 // Flush before commit or an explicit alarm operation, never after rollback.
101 export const flushDurableObjectAlarm = (storage: cf.DurableObjectStorage) =>
102 Effect.gen(function* () {
103 const transaction = (yield* ActiveStorageTransactions).get(storage);
104 if (transaction?.alarmDirty && !transaction.rolledBack) {
105 yield* reconcileAlarm(storage);
106 transaction.alarmDirty = false;
107 }
108 });
109
110 const reconcileAlarm = (storage: cf.DurableObjectStorage) =>
111 Effect.gen(function* () {
112 const next = yield* Effect.sync(
113 () =>
114 storage.sql
115 .exec<{ run_at: number | null }>(`
116 SELECT MIN(run_at) AS run_at FROM (
117 SELECT MIN(run_at) AS run_at FROM alchemy_scheduled_events
118 UNION ALL
119 SELECT MIN(run_at) AS run_at FROM alchemy_alarm_callbacks
120 )
121 `)
122 .one().run_at,
123 );
124 const now = yield* Clock.currentTimeMillis;
125 // A continuation must use a new timestamp, not the alarm currently being acknowledged.
126 yield* Effect.promise(() =>
127 next === null ? storage.deleteAlarm() : storage.setAlarm(Math.max(next, now + 1)),
128 );
129 });