@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 144 lines 6.09 KB
Raw
1 import { DurableObjectState } from "@alchemy.run/cloudflare/Workers/DurableObjectState";
2 import type { SqlMigrations } from "@alchemy.run/cloudflare/Workers/SqlMigrations";
3 import * as SqliteDoClient from "@effect/sql-sqlite-do/SqliteClient";
4 import type { AnyRelations, EmptyRelations } from "drizzle-orm";
5 import * as SQLiteDoDrizzle from "drizzle-orm/effect-sqlite-do";
6 import { migrate } from "drizzle-orm/effect-sqlite-do/migrator";
7 import * as Context from "effect/Context";
8 import * as Effect from "effect/Effect";
9 import * as Layer from "effect/Layer";
10 import * as Scheduler from "effect/Scheduler";
11
12 /**
13 * Migrations for {@link DurableObject} — the shape of the `migrations.js`
14 * bundle `drizzle-kit generate` emits for `driver: "durable-sqlite"`
15 * (each migration's `.sql` file imported as a text module).
16 */
17 export interface DurableObjectMigrations {
18 readonly migrations: Record<string, string>;
19 readonly migrationsTable?: string | undefined;
20 }
21
22 export interface DurableObjectConfig<
23 TRelations extends AnyRelations = EmptyRelations,
24 > extends SQLiteDoDrizzle.EffectDrizzleSQLiteDoConfig<TRelations> {
25 /**
26 * Migrations applied before the database is returned. Prefer a snapshot
27 * from `Cloudflare.SqlMigrations(dir)`: SQL is read during construction
28 * and applied with Alchemy's `__alchemy_migrations` bookkeeping.
29 * The generated Drizzle `migrations.js` input remains supported and uses
30 * Drizzle's own migrator; its SQL imports still require loader support.
31 */
32 readonly migrations?: SqlMigrations | DurableObjectMigrations | undefined;
33 }
34
35 /**
36 * Open a Drizzle database over the current Durable Object's SQLite
37 * storage using the `drizzle-orm/effect-sqlite-do` integration (driven by
38 * `@effect/sql-sqlite-do`'s `SqliteClient`), applying migrations first
39 * when provided. `Cloudflare.SqlMigrations` captures a SQL directory during
40 * construction without importing `.sql` files. Each instance applies pending
41 * files on activation using Alchemy's shared migration history.
42 *
43 * Every query is an Effect with a typed error channel — drizzle's
44 * `EffectDrizzleQueryError` (query + params + cause, wrapping the
45 * underlying effect-sql `SqlError`) — so failures are handled with
46 * `Effect.catchTag` instead of leaking as defects. Transactions add
47 * `SqlError` to the union. Opening the db itself never fails: a
48 * migration that cannot apply dies, since the instance is unusable
49 * without its schema.
50 *
51 * Yield it in the object's inner (instance) Effect — it runs when the
52 * instance activates, before any request reaches its methods:
53 *
54 * ```typescript
55 * // schema.ts
56 * import { defineRelations } from "drizzle-orm";
57 * import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
58 *
59 * export const users = sqliteTable("users", {
60 * id: integer("id").primaryKey({ autoIncrement: true }),
61 * name: text("name").notNull(),
62 * });
63 *
64 * export const posts = sqliteTable("posts", {
65 * id: integer("id").primaryKey({ autoIncrement: true }),
66 * userId: integer("user_id").notNull().references(() => users.id),
67 * title: text("title").notNull(),
68 * });
69 *
70 * export const relations = defineRelations({ users, posts }, (t) => ({
71 * users: { posts: t.many.posts() },
72 * posts: { author: t.one.users({ from: t.posts.userId, to: t.users.id }) },
73 * }));
74 * ```
75 *
76 * ```typescript
77 * import * as Drizzle from "@alchemy.run/drizzle/Cloudflare";
78 * import { posts, relations, users } from "./schema.ts";
79 *
80 * export class Users extends Cloudflare.DurableObject<Users>()(
81 * "Users",
82 * Effect.gen(function* () {
83 * const migrations = yield* Cloudflare.SqlMigrations("./drizzle");
84 * return Effect.gen(function* () {
85 * const db = yield* Drizzle.DurableObject({ migrations, relations });
86 *
87 * return {
88 * addUser: (name: string) => db.insert(users).values({ name }),
89 * listUsers: () => db.select().from(users),
90 * listUsersWithPosts: () =>
91 * db.query.users.findMany({ with: { posts: true } }),
92 * // typed error handling per operation:
93 * tryAddUser: (name: string) =>
94 * db
95 * .insert(users)
96 * .values({ name })
97 * .pipe(
98 * Effect.catchTag("EffectDrizzleQueryError", () =>
99 * Effect.succeed(undefined),
100 * ),
101 * ),
102 * };
103 * });
104 * }),
105 * ) {}
106 * ```
107 *
108 * @binding
109 */
110 export const DurableObject = Effect.fn("Drizzle.DurableObject")(function* <
111 TRelations extends AnyRelations = EmptyRelations,
112 >(config?: DurableObjectConfig<TRelations>) {
113 const state = yield* DurableObjectState;
114 const storage = state.raw.storage;
115 const { migrations, ...drizzleConfig } = config ?? {};
116 // Built on the ambient (instance) Scope — the client wraps the DO's
117 // local SQLite storage, so there is no disposable resource behind it.
118 const services = yield* Layer.build(SqliteDoClient.layer({ storage }));
119 const client = Context.get(services, SqliteDoClient.SqliteClient);
120 const original = client.withTransaction;
121 const scheduler = new Scheduler.MixedScheduler("sync");
122 const withTransaction: typeof client.withTransaction = (body) =>
123 original(body).pipe(Effect.provideService(Scheduler.Scheduler, scheduler));
124 // A parent input-gate timer can block later transaction timers. Yield through
125 // microtasks while retaining the adapter's client, SQL permit, and context.
126 yield* Effect.sync(() => Object.assign(client, { withTransaction }));
127 const db = yield* SQLiteDoDrizzle.makeWithDefaults(drizzleConfig).pipe(
128 Effect.provideContext(services),
129 );
130 if (migrations !== undefined && "_tag" in migrations) {
131 yield* migrations.apply().pipe(Effect.orDie);
132 } else if (migrations !== undefined) {
133 // A migration that cannot apply leaves the instance unusable — there
134 // is no meaningful recovery at init, so it dies rather than forcing
135 // every caller to handle (or orDie) an error channel.
136 yield* migrate(db, {
137 migrations: migrations.migrations,
138 ...(migrations.migrationsTable !== undefined
139 ? { migrationsTable: migrations.migrationsTable }
140 : {}),
141 }).pipe(Effect.orDie);
142 }
143 return db;
144 });