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

main
ts 195 lines 6.89 KB
Raw
1 import { Credentials, DEFAULT_API_BASE_URL } from "@distilled.cloud/turso/Credentials";
2 import * as turso from "@distilled.cloud/turso/turso";
3 import * as Binding from "alchemy/Binding";
4 import type { RuntimeContext } from "alchemy/RuntimeContext";
5 import * as Effect from "effect/Effect";
6 import * as FetchHttpClient from "effect/http/FetchHttpClient";
7 import type * as HttpClient from "effect/http/HttpClient";
8 import * as Layer from "effect/Layer";
9 import { ApiToken } from "./ApiToken.ts";
10 import type { ConnectClient } from "./Connect.ts";
11 import type { DatabaseSeed } from "./Database.ts";
12 import type { Group } from "./Group.ts";
13 import { GroupToken } from "./GroupToken.ts";
14
15 /** A database in the managed group. */
16 export interface ManagedDatabase {
17 /** Database name. */
18 name: string;
19 /** Database UUID. */
20 dbId: string;
21 /** DNS hostname of the database. */
22 hostname: string;
23 /** libSQL URL (`libsql://<hostname>`). */
24 url: string;
25 }
26
27 export interface CreateManagedDatabaseOptions {
28 /** Seed the new database from an existing database (e.g. a template). */
29 seed?: DatabaseSeed;
30 /** Maximum size of the database, e.g. `"256mb"`. */
31 sizeLimit?: string;
32 }
33
34 export interface ManageDatabasesClient {
35 /** Create a database in the group. */
36 create(
37 name: string,
38 options?: CreateManagedDatabaseOptions,
39 ): Effect.Effect<ManagedDatabase, turso.CreateDatabaseError, RuntimeContext>;
40 /** Look up a database by name; `undefined` when it doesn't exist. */
41 get(
42 name: string,
43 ): Effect.Effect<ManagedDatabase | undefined, turso.GetDatabaseError, RuntimeContext>;
44 /** List every database in the group. */
45 list(): Effect.Effect<ManagedDatabase[], turso.ListDatabasesError, RuntimeContext>;
46 /** Delete a database. Deleting a missing database succeeds. */
47 delete(name: string): Effect.Effect<void, turso.DeleteDatabaseError, RuntimeContext>;
48 /**
49 * libSQL connection accessors for a database in the group, authorized by
50 * a group-wide SQL token. Pass to `SQL.LibSQL` or `Drizzle.LibSQL`.
51 */
52 connect(name: string): ConnectClient;
53 }
54
55 /**
56 * Let a Worker create, list, delete, and query databases in one Turso
57 * {@link Group}. Use it to give each customer their own database.
58 *
59 * The Worker gets an {@link ApiToken} that only works on that group, and a
60 * {@link GroupToken} for running SQL. It can't touch databases in any other
61 * group, and your own Turso API token stays on your machine.
62 *
63 * ### Database per tenant
64 * **Example:** Create a tenant database on signup and query it
65 * ```typescript
66 * Effect.gen(function* () {
67 * const tenants = yield* Turso.ManageDatabases(Tenants);
68 * return {
69 * fetch: Effect.gen(function* () {
70 * const db = yield* tenants.create("acme");
71 * const sql = yield* SQL.LibSQL(tenants.connect(db.name));
72 * yield* sql`CREATE TABLE IF NOT EXISTS notes (body TEXT)`;
73 * return HttpServerResponse.text(db.url);
74 * }),
75 * };
76 * }).pipe(Effect.provide(Turso.ManageDatabasesHttp));
77 * ```
78 *
79 * @binding
80 * @product Group
81 */
82 export interface ManageDatabases extends Binding.Service<
83 ManageDatabases,
84 "Turso.ManageDatabases",
85 (group: Group) => Effect.Effect<ManageDatabasesClient>
86 > {}
87
88 export const ManageDatabases = Binding.Service<ManageDatabases>("Turso.ManageDatabases");
89
90 /** Implementation over the Turso Platform API, usable from any Platform host. */
91 export const ManageDatabasesHttp = Layer.effect(
92 ManageDatabases,
93 Effect.gen(function* () {
94 const PlatformToken = yield* ApiToken;
95 const SqlToken = yield* GroupToken;
96 return Effect.fn(function* (group: Group) {
97 const host = yield* Binding.Host;
98 const prefix = `${host?.LogicalId ?? ""}${group.LogicalId}`;
99 const apiToken = yield* PlatformToken(`${prefix}ManageToken`, {
100 group: group.name,
101 scopes: ["read", "db:create", "db:delete", "db:configure"],
102 });
103 const sqlToken = yield* SqlToken(`${prefix}SqlToken`, {
104 group: group.name,
105 });
106 const apiKey = yield* apiToken.token;
107 const authToken = yield* sqlToken.token;
108 const organization = yield* group.organization;
109 const groupName = yield* group.name;
110 const location = yield* group.location;
111
112 const authorize = <A, E>(
113 effect: Effect.Effect<A, E, Credentials | HttpClient.HttpClient>,
114 ): Effect.Effect<A, E, RuntimeContext> =>
115 effect.pipe(
116 Effect.provide(
117 Layer.mergeAll(
118 Layer.succeed(
119 Credentials,
120 Effect.map(apiKey, (key) => ({ apiKey: key, apiBaseUrl: DEFAULT_API_BASE_URL })),
121 ),
122 FetchHttpClient.layer,
123 ),
124 ),
125 );
126
127 const toManaged = (db: {
128 Name?: string;
129 DbId?: string;
130 Hostname?: string;
131 }): ManagedDatabase => ({
132 name: db.Name ?? "",
133 dbId: db.DbId ?? "",
134 hostname: db.Hostname ?? "",
135 url: `libsql://${db.Hostname}`,
136 });
137
138 const client: ManageDatabasesClient = {
139 create: (name, options) =>
140 authorize(
141 Effect.gen(function* () {
142 const { database } = yield* turso.createDatabase({
143 organizationSlug: yield* organization,
144 name,
145 group: yield* groupName,
146 seed: options?.seed,
147 size_limit: options?.sizeLimit,
148 });
149 return toManaged(database ?? {});
150 }),
151 ),
152 get: (name) =>
153 authorize(
154 Effect.gen(function* () {
155 const { database } = yield* turso.getDatabase({
156 organizationSlug: yield* organization,
157 databaseName: name,
158 });
159 return database && database.group === (yield* groupName)
160 ? toManaged(database)
161 : undefined;
162 }).pipe(Effect.catchTag("NotFound", () => Effect.undefined)),
163 ),
164 list: () =>
165 authorize(
166 Effect.gen(function* () {
167 const { databases } = yield* turso.listDatabases({
168 organizationSlug: yield* organization,
169 group: yield* groupName,
170 });
171 return (databases ?? []).map(toManaged);
172 }),
173 ),
174 delete: (name) =>
175 authorize(
176 Effect.gen(function* () {
177 yield* turso.deleteDatabase({
178 organizationSlug: yield* organization,
179 databaseName: name,
180 });
181 }).pipe(Effect.catchTag("NotFound", () => Effect.void)),
182 ),
183 connect: (name) => ({
184 // Turso hostnames are `<database>-<organization>.<location>.turso.io`,
185 // so the URL is derived without a Platform API round-trip.
186 url: Effect.gen(function* () {
187 return `libsql://${name}-${yield* organization}.${yield* location}.turso.io`;
188 }),
189 authToken,
190 }),
191 };
192 return client;
193 });
194 }),
195 );