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

main
ts 545 lines 20.5 KB
Raw
1 import type * as cf from "@cloudflare/workers-types";
2 import type { RuntimeContext } from "alchemy/RuntimeContext";
3 import * as Context from "effect/Context";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as Exit from "effect/Exit";
7 import * as Fiber from "effect/Fiber";
8 import * as Pipeable from "effect/Pipeable";
9 import * as Scheduler from "effect/Scheduler";
10 import * as Stream from "effect/Stream";
11 import { flushDurableObjectAlarm } from "./DurableObjectAlarmStorage.ts";
12 import {
13 ActiveStorageTransactions,
14 type ActiveStorageTransaction,
15 } from "./DurableObjectTransactionContext.ts";
16
17 /** A native transaction failure or invalid use of a transaction's owner. */
18 export class DurableObjectStorageError extends Data.TaggedError("DurableObjectStorageError")<{
19 readonly operation: string;
20 readonly message: string;
21 readonly cause?: unknown;
22 }> {}
23
24 // Pre-existing sibling fibers do not inherit the transaction's context.
25 const activeStorageTransactions = new WeakMap<cf.DurableObjectStorage, ActiveStorageTransaction>();
26
27 const checkTransactionOwner = (transaction: ActiveStorageTransaction, allowRolledBack = false) =>
28 Effect.withFiber((fiber) =>
29 transaction.active &&
30 transaction.owner === fiber &&
31 (allowRolledBack || !transaction.rolledBack)
32 ? Effect.void
33 : Effect.fail(
34 new DurableObjectStorageError({
35 operation: "transaction",
36 message: !transaction.active
37 ? "The storage transaction callback has already finished"
38 : transaction.owner !== fiber
39 ? "A storage transaction cannot be used by another fiber"
40 : "The storage transaction has been rolled back",
41 }),
42 ),
43 );
44
45 /** @internal Joins an owned transaction, or starts a native transaction. */
46 function withStorageTransaction<A, E, R>(
47 storage: cf.DurableObjectStorage,
48 effect: Effect.Effect<A, E, R>,
49 ): Effect.Effect<A, E | DurableObjectStorageError, R>;
50 function withStorageTransaction<A, E, R>(
51 storage: cf.DurableObjectStorage,
52 closure: (txn: DurableObjectTransaction) => Effect.Effect<A, E, R>,
53 ): Effect.Effect<A, E | DurableObjectStorageError, R>;
54 function withStorageTransaction<A, E, R>(
55 storage: cf.DurableObjectStorage,
56 body: Effect.Effect<A, E, R> | ((txn: DurableObjectTransaction) => Effect.Effect<A, E, R>),
57 ): Effect.Effect<A, E | DurableObjectStorageError, R> {
58 return Effect.gen(function* () {
59 const transactions = yield* ActiveStorageTransactions;
60 const existing = transactions.get(storage) ?? activeStorageTransactions.get(storage);
61 const evaluate = (transaction: ActiveStorageTransaction) =>
62 Effect.suspend(() =>
63 typeof body === "function"
64 ? body(
65 makeDurableObjectTransaction(
66 transaction.transaction,
67 checkTransactionOwner(transaction).pipe(Effect.orDie),
68 checkTransactionOwner(transaction, true).pipe(
69 Effect.andThen(() =>
70 Effect.sync(() => {
71 if (!transaction.rolledBack) {
72 transaction.transaction.rollback();
73 transaction.rolledBack = true;
74 }
75 }),
76 ),
77 Effect.orDie,
78 ),
79 flushDurableObjectAlarm(storage),
80 ),
81 )
82 : body,
83 );
84
85 if (existing !== undefined) {
86 yield* checkTransactionOwner(existing);
87 return yield* evaluate(existing);
88 }
89
90 const context = yield* Effect.context<R>();
91 // Native input gates can block timers; fiber yields must use microtasks.
92 const scheduler = new Scheduler.MixedScheduler("sync");
93
94 return yield* Effect.scoped(
95 Effect.gen(function* () {
96 let cancelled = false;
97 let native: Promise<A> | undefined;
98 let failure: Exit.Failure<A, E> | undefined;
99 let currentTransaction: ActiveStorageTransaction | undefined;
100 const release = () => {
101 if (currentTransaction !== undefined) {
102 currentTransaction.active = false;
103 if (activeStorageTransactions.get(storage) === currentTransaction) {
104 activeStorageTransactions.delete(storage);
105 }
106 }
107 };
108
109 yield* Effect.addFinalizer(
110 Effect.fn(function* () {
111 cancelled = true;
112 // The synchronous scheduler can re-enter this finalizer before
113 // runForkWith returns. The callback publishes its owner first.
114 const owner = currentTransaction?.owner;
115 if (owner !== undefined) {
116 yield* Fiber.interrupt(owner);
117 }
118 const settlement = native;
119 if (settlement !== undefined) {
120 // The callback must finish before waiting for native rollback.
121 yield* Effect.promise(() =>
122 settlement.then(
123 () => undefined,
124 () => undefined,
125 ),
126 );
127 }
128 }),
129 );
130
131 return yield* Effect.callback<A, E | DurableObjectStorageError>((resume) => {
132 const reject = (cause: unknown) => {
133 release();
134 resume(
135 failure !== undefined && cause === failure
136 ? Effect.failCause(failure.cause)
137 : Effect.fail(
138 new DurableObjectStorageError({
139 operation: "transaction",
140 message: "The native storage transaction failed",
141 cause,
142 }),
143 ),
144 );
145 };
146
147 try {
148 native = storage.transaction((txn) => {
149 if (cancelled) {
150 throw new DurableObjectStorageError({
151 operation: "transaction",
152 message: "The storage transaction caller was interrupted",
153 });
154 }
155 const transaction: ActiveStorageTransaction = {
156 transaction: txn,
157 owner: undefined,
158 active: true,
159 rolledBack: false,
160 alarmTablesEnsured: false,
161 alarmDirty: false,
162 };
163 currentTransaction = transaction;
164 activeStorageTransactions.set(storage, transaction);
165 const callbackContext = Context.add(
166 context,
167 ActiveStorageTransactions,
168 new Map(transactions).set(storage, transaction),
169 );
170
171 return new Promise<A>((resolve, rejectCallback) => {
172 const callbackFiber = Effect.runForkWith(callbackContext)(
173 Effect.withFiber((fiber) => {
174 transaction.owner = fiber;
175 return evaluate(transaction).pipe(
176 Effect.scoped,
177 Effect.tap(() => flushDurableObjectAlarm(storage)),
178 );
179 }),
180 { scheduler },
181 );
182 callbackFiber.addObserver((exit) => {
183 transaction.active = false;
184 if (Exit.isSuccess(exit)) {
185 resolve(exit.value);
186 } else {
187 failure = exit;
188 rejectCallback(exit);
189 }
190 });
191 });
192 });
193 native.then((value) => {
194 release();
195 resume(Effect.succeed(value));
196 }, reject);
197 } catch (cause) {
198 reject(cause);
199 }
200 });
201 }),
202 );
203 });
204 }
205
206 // ---------------------------------------------------------------------------
207 // SqlStorage — Effect-native wrapper around cf.SqlStorage
208 // ---------------------------------------------------------------------------
209
210 export type SqlStorageValue = cf.SqlStorageValue;
211
212 export interface SqlCursor<T extends Record<string, SqlStorageValue>> extends Stream.Stream<T> {
213 next(): Effect.Effect<
214 { done?: false; value: T } | { done: true; value?: never },
215 never,
216 RuntimeContext
217 >;
218 toArray(): Effect.Effect<T[], never, RuntimeContext>;
219 one(): Effect.Effect<T, never, RuntimeContext>;
220 raw<U extends SqlStorageValue[]>(): Stream.Stream<U, never, RuntimeContext>;
221 readonly columnNames: string[];
222 readonly rowsRead: Effect.Effect<number, never, RuntimeContext>;
223 readonly rowsWritten: Effect.Effect<number, never, RuntimeContext>;
224 }
225
226 export interface SqlStorage {
227 /**
228 * The raw underlying Cloudflare SqlStorage binding.
229 *
230 * Use this when you need direct access for libraries that already support
231 * Cloudflare Durable Object SQLite storage.
232 */
233 readonly raw: cf.SqlStorage;
234 exec<T extends Record<string, SqlStorageValue>>(
235 query: string,
236 ...bindings: any[]
237 ): Effect.Effect<SqlCursor<T>, never, RuntimeContext>;
238 readonly databaseSize: number;
239 }
240
241 const defineCursorField = <A>(self: object, key: string, value: A): A => {
242 Object.defineProperty(self, key, { value, enumerable: true, configurable: true, writable: true });
243 return value;
244 };
245
246 // Writes commonly discard the cursor. Keep its Stream, bound methods, and
247 // statistic Effects lazy so those writes allocate only this wrapper.
248 class SqlCursorImpl<T extends Record<string, SqlStorageValue>>
249 extends Pipeable.Class
250 implements SqlCursor<T>
251 {
252 #cursor: cf.SqlStorageCursor<T>;
253
254 constructor(cursor: cf.SqlStorageCursor<T>) {
255 super();
256 this.#cursor = cursor;
257 }
258
259 get [Stream.TypeId](): Stream.VarianceStruct<T, never, never> {
260 return Stream.empty[Stream.TypeId];
261 }
262
263 get channel(): Stream.Stream<T>["channel"] {
264 return defineCursorField(this, "channel", Stream.toChannel(Stream.fromIterable(this.#cursor)));
265 }
266
267 get next(): SqlCursor<T>["next"] {
268 const cursor = this.#cursor;
269 return defineCursorField(this, "next", () => Effect.sync(() => cursor.next()));
270 }
271
272 get toArray(): SqlCursor<T>["toArray"] {
273 const cursor = this.#cursor;
274 return defineCursorField(this, "toArray", () => Effect.sync(() => cursor.toArray()));
275 }
276
277 get one(): SqlCursor<T>["one"] {
278 const cursor = this.#cursor;
279 return defineCursorField(this, "one", () => Effect.sync(() => cursor.one()));
280 }
281
282 get raw(): SqlCursor<T>["raw"] {
283 const cursor = this.#cursor;
284 return defineCursorField(this, "raw", <U extends SqlStorageValue[]>() =>
285 Stream.fromIterableEffect(Effect.sync(() => cursor.raw<U>())),
286 );
287 }
288
289 get columnNames(): string[] {
290 return defineCursorField(this, "columnNames", this.#cursor.columnNames);
291 }
292
293 get rowsRead(): SqlCursor<T>["rowsRead"] {
294 const cursor = this.#cursor;
295 return defineCursorField(
296 this,
297 "rowsRead",
298 Effect.sync(() => cursor.rowsRead),
299 );
300 }
301
302 get rowsWritten(): SqlCursor<T>["rowsWritten"] {
303 const cursor = this.#cursor;
304 return defineCursorField(
305 this,
306 "rowsWritten",
307 Effect.sync(() => cursor.rowsWritten),
308 );
309 }
310 }
311
312 const fromSqlCursor = <T extends Record<string, SqlStorageValue>>(
313 cursor: cf.SqlStorageCursor<T>,
314 ): SqlCursor<T> => new SqlCursorImpl(cursor);
315
316 const fromSqlStorage = (sql: cf.SqlStorage, checkOwner: Effect.Effect<void>): SqlStorage => ({
317 raw: sql,
318 exec: <T extends Record<string, SqlStorageValue>>(
319 query: string,
320 ...bindings: any[]
321 ): Effect.Effect<SqlCursor<T>> =>
322 Effect.andThen(
323 checkOwner,
324 Effect.sync(() => fromSqlCursor(sql.exec<T>(query, ...bindings))),
325 ),
326 get databaseSize() {
327 return sql.databaseSize;
328 },
329 });
330
331 // ---------------------------------------------------------------------------
332 // DurableObjectTransaction
333 // ---------------------------------------------------------------------------
334
335 export interface DurableObjectTransaction {
336 get<T = unknown>(
337 key: string,
338 options?: cf.DurableObjectGetOptions,
339 ): Effect.Effect<T | undefined, never, RuntimeContext>;
340 get<T = unknown>(
341 keys: string[],
342 options?: cf.DurableObjectGetOptions,
343 ): Effect.Effect<Map<string, T>, never, RuntimeContext>;
344 list<T = unknown>(
345 options?: cf.DurableObjectListOptions,
346 ): Effect.Effect<Map<string, T>, never, RuntimeContext>;
347 put<T>(
348 key: string,
349 value: T,
350 options?: cf.DurableObjectPutOptions,
351 ): Effect.Effect<void, never, RuntimeContext>;
352 put<T>(
353 entries: Record<string, T>,
354 options?: cf.DurableObjectPutOptions,
355 ): Effect.Effect<void, never, RuntimeContext>;
356 delete(
357 key: string,
358 options?: cf.DurableObjectPutOptions,
359 ): Effect.Effect<boolean, never, RuntimeContext>;
360 delete(
361 keys: string[],
362 options?: cf.DurableObjectPutOptions,
363 ): Effect.Effect<number, never, RuntimeContext>;
364 rollback(): Effect.Effect<void, never, RuntimeContext>;
365 getAlarm(
366 options?: cf.DurableObjectGetAlarmOptions,
367 ): Effect.Effect<number | null, never, RuntimeContext>;
368 setAlarm(
369 scheduledTime: number | Date,
370 options?: cf.DurableObjectSetAlarmOptions,
371 ): Effect.Effect<void, never, RuntimeContext>;
372 deleteAlarm(
373 options?: cf.DurableObjectSetAlarmOptions,
374 ): Effect.Effect<void, never, RuntimeContext>;
375 }
376
377 // ---------------------------------------------------------------------------
378 // DurableObjectStorage
379 // ---------------------------------------------------------------------------
380
381 export interface DurableObjectStorage {
382 get<T = unknown>(
383 key: string,
384 options?: cf.DurableObjectGetOptions,
385 ): Effect.Effect<T | undefined, never, RuntimeContext>;
386 get<T = unknown>(
387 keys: string[],
388 options?: cf.DurableObjectGetOptions,
389 ): Effect.Effect<Map<string, T>, never, RuntimeContext>;
390 list<T = unknown>(
391 options?: cf.DurableObjectListOptions,
392 ): Effect.Effect<Map<string, T>, never, RuntimeContext>;
393 put<T>(
394 key: string,
395 value: T,
396 options?: cf.DurableObjectPutOptions,
397 ): Effect.Effect<void, never, RuntimeContext>;
398 put<T>(
399 entries: Record<string, T>,
400 options?: cf.DurableObjectPutOptions,
401 ): Effect.Effect<void, never, RuntimeContext>;
402 delete(
403 key: string,
404 options?: cf.DurableObjectPutOptions,
405 ): Effect.Effect<boolean, never, RuntimeContext>;
406 delete(
407 keys: string[],
408 options?: cf.DurableObjectPutOptions,
409 ): Effect.Effect<number, never, RuntimeContext>;
410 deleteAll(options?: cf.DurableObjectPutOptions): Effect.Effect<void, never, RuntimeContext>;
411 /**
412 * Run an Effect inside a native storage transaction with the caller's context.
413 * On SQLite-backed storage, SQL, KV, and alarm writes to this storage commit
414 * together. Typed failures, defects, and interruption roll back the transaction.
415 * Interruption waits for the callback fiber and native rollback to finish.
416 * Nested calls on the same fiber join the active transaction; transaction
417 * handles cannot be used by another fiber or after the callback finishes.
418 */
419 transaction<A, E = never, R = never>(
420 effect: Effect.Effect<A, E, R>,
421 ): Effect.Effect<A, E | DurableObjectStorageError, R | RuntimeContext>;
422 transaction<A, E = never, R = never>(
423 closure: (txn: DurableObjectTransaction) => Effect.Effect<A, E, R>,
424 ): Effect.Effect<A, E | DurableObjectStorageError, R | RuntimeContext>;
425 getAlarm(
426 options?: cf.DurableObjectGetAlarmOptions,
427 ): Effect.Effect<number | null, never, RuntimeContext>;
428 setAlarm(
429 scheduledTime: number | Date,
430 options?: cf.DurableObjectSetAlarmOptions,
431 ): Effect.Effect<void, never, RuntimeContext>;
432 deleteAlarm(
433 options?: cf.DurableObjectSetAlarmOptions,
434 ): Effect.Effect<void, never, RuntimeContext>;
435 sync(): Effect.Effect<void, never, RuntimeContext>;
436 sql: SqlStorage;
437 kv: cf.SyncKvStorage;
438 getCurrentBookmark(): Effect.Effect<string, never, RuntimeContext>;
439 getBookmarkForTime(timestamp: number | Date): Effect.Effect<string, never, RuntimeContext>;
440 onNextSessionRestoreBookmark(bookmark: string): Effect.Effect<string, never, RuntimeContext>;
441 }
442
443 // ---------------------------------------------------------------------------
444 // Constructors from raw Cloudflare types
445 // ---------------------------------------------------------------------------
446
447 export const fromDurableObjectTransaction = (
448 txn: cf.DurableObjectTransaction,
449 ): DurableObjectTransaction => makeDurableObjectTransaction(txn, Effect.void);
450
451 const makeDurableObjectTransaction = (
452 txn: cf.DurableObjectTransaction,
453 checkOwner: Effect.Effect<void>,
454 rollback = Effect.andThen(
455 checkOwner,
456 Effect.sync(() => txn.rollback()),
457 ),
458 flushAlarm: Effect.Effect<void> = Effect.void,
459 ): DurableObjectTransaction => {
460 const use = <A>(effect: Effect.Effect<A>) => Effect.andThen(checkOwner, effect);
461 const useAlarm = <A>(effect: Effect.Effect<A>) => use(Effect.andThen(flushAlarm, effect));
462
463 return {
464 get: ((keyOrKeys: string | string[], options?: cf.DurableObjectGetOptions) =>
465 use(Effect.promise(() => txn.get(keyOrKeys as any, options)))) as any,
466 list: (options?: cf.DurableObjectListOptions) => use(Effect.promise(() => txn.list(options))),
467 put: ((
468 keyOrEntries: string | Record<string, unknown>,
469 valueOrOptions?: unknown,
470 maybeOptions?: cf.DurableObjectPutOptions,
471 ) =>
472 use(
473 typeof keyOrEntries === "string"
474 ? Effect.promise(() => txn.put(keyOrEntries, valueOrOptions, maybeOptions))
475 : Effect.promise(() =>
476 txn.put(keyOrEntries, valueOrOptions as cf.DurableObjectPutOptions | undefined),
477 ),
478 )) as any,
479 delete: ((keyOrKeys: string | string[], options?: cf.DurableObjectPutOptions) =>
480 use(Effect.promise(() => txn.delete(keyOrKeys as any, options)))) as any,
481 rollback: () => rollback,
482 getAlarm: (options?: cf.DurableObjectGetAlarmOptions) =>
483 useAlarm(Effect.promise(() => txn.getAlarm(options))),
484 setAlarm: (scheduledTime: number | Date, options?: cf.DurableObjectSetAlarmOptions) =>
485 useAlarm(Effect.promise(() => txn.setAlarm(scheduledTime, options))),
486 deleteAlarm: (options?: cf.DurableObjectSetAlarmOptions) =>
487 useAlarm(Effect.promise(() => txn.deleteAlarm(options))),
488 };
489 };
490
491 export const fromDurableObjectStorage = (
492 storage: cf.DurableObjectStorage,
493 ): DurableObjectStorage => {
494 const checkOwner = Effect.withFiber((fiber) => {
495 const transaction =
496 fiber.getRef(ActiveStorageTransactions).get(storage) ??
497 activeStorageTransactions.get(storage);
498 return transaction === undefined
499 ? Effect.void
500 : checkTransactionOwner(transaction).pipe(Effect.orDie);
501 });
502 const use = <A>(effect: Effect.Effect<A>) => Effect.andThen(checkOwner, effect);
503 const useAlarm = <A>(effect: Effect.Effect<A>) =>
504 use(Effect.andThen(flushDurableObjectAlarm(storage), effect));
505
506 return {
507 get: ((keyOrKeys: string | string[], options?: cf.DurableObjectGetOptions) =>
508 use(Effect.promise(() => storage.get(keyOrKeys as any, options)))) as any,
509 list: (options?: cf.DurableObjectListOptions) =>
510 use(Effect.promise(() => storage.list(options))),
511 put: ((
512 keyOrEntries: string | Record<string, unknown>,
513 valueOrOptions?: unknown,
514 maybeOptions?: cf.DurableObjectPutOptions,
515 ) =>
516 use(
517 typeof keyOrEntries === "string"
518 ? Effect.promise(() => storage.put(keyOrEntries, valueOrOptions, maybeOptions))
519 : Effect.promise(() =>
520 storage.put(keyOrEntries, valueOrOptions as cf.DurableObjectPutOptions | undefined),
521 ),
522 )) as any,
523 delete: ((keyOrKeys: string | string[], options?: cf.DurableObjectPutOptions) =>
524 use(Effect.promise(() => storage.delete(keyOrKeys as any, options)))) as any,
525 deleteAll: (options?: cf.DurableObjectPutOptions) =>
526 use(Effect.promise(() => storage.deleteAll(options))),
527 transaction: <A, E, R>(
528 body: Effect.Effect<A, E, R> | ((txn: DurableObjectTransaction) => Effect.Effect<A, E, R>),
529 ) => withStorageTransaction(storage, (txn) => (typeof body === "function" ? body(txn) : body)),
530 getAlarm: (options?: cf.DurableObjectGetAlarmOptions) =>
531 useAlarm(Effect.promise(() => storage.getAlarm(options))),
532 setAlarm: (scheduledTime: number | Date, options?: cf.DurableObjectSetAlarmOptions) =>
533 useAlarm(Effect.promise(() => storage.setAlarm(scheduledTime, options))),
534 deleteAlarm: (options?: cf.DurableObjectSetAlarmOptions) =>
535 useAlarm(Effect.promise(() => storage.deleteAlarm(options))),
536 sync: () => use(Effect.promise(() => storage.sync())),
537 sql: fromSqlStorage(storage.sql, checkOwner),
538 kv: storage.kv,
539 getCurrentBookmark: () => use(Effect.promise(() => storage.getCurrentBookmark())),
540 getBookmarkForTime: (timestamp: number | Date) =>
541 use(Effect.promise(() => storage.getBookmarkForTime(timestamp))),
542 onNextSessionRestoreBookmark: (bookmark: string) =>
543 use(Effect.promise(() => storage.onNextSessionRestoreBookmark(bookmark))),
544 };
545 };