@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, 04:45 UTC

main
ts 361 lines 12.7 KB
Raw
1 import type { EnvironmentId } from "@t3tools/contracts";
2 import * as Clock from "effect/Clock";
3 import * as Context from "effect/Context";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
7 import * as Schema from "effect/Schema";
8 import type { SQLiteDatabase } from "expo-sqlite";
9
10 const DATABASE_NAME = "t3code-client.db";
11 const DATABASE_SCHEMA_VERSION = 1;
12
13 export const ClientCacheKind = Schema.Literals([
14 "shell",
15 "thread",
16 "server-config",
17 "vcs-refs",
18 "project-favicon",
19 "pull-request",
20 ]);
21 export type ClientCacheKind = typeof ClientCacheKind.Type;
22
23 export interface ClientCacheSummaryRow {
24 readonly environmentId: EnvironmentId;
25 readonly kind: ClientCacheKind;
26 readonly recordCount: number;
27 readonly payloadBytes: number;
28 }
29
30 export interface StoredPreferencesJson {
31 readonly payload: string;
32 readonly updatedAt: number;
33 }
34
35 const ClientCacheSummaryRows = Schema.Array(
36 Schema.Struct({
37 environmentId: Schema.String,
38 kind: ClientCacheKind,
39 recordCount: Schema.Number,
40 payloadBytes: Schema.Number,
41 }),
42 );
43
44 const MobileDatabaseOperation = Schema.Literals([
45 "open",
46 "close",
47 "migrate",
48 "load-cache",
49 "list-cache",
50 "save-cache",
51 "remove-cache",
52 "clear-cache-kind",
53 "clear-environment-cache",
54 "clear-all-caches",
55 "inspect-caches",
56 "load-preferences",
57 "save-preferences",
58 ]);
59
60 export class MobileDatabaseError extends Schema.TaggedError<MobileDatabaseError>()(
61 "MobileDatabaseError",
62 {
63 operation: MobileDatabaseOperation,
64 cause: Schema.Defect(),
65 },
66 ) {
67 override get message(): string {
68 return `Mobile database operation failed: ${this.operation}.`;
69 }
70 }
71
72 function databaseError(operation: typeof MobileDatabaseOperation.Type) {
73 return (cause: unknown) => new MobileDatabaseError({ operation, cause });
74 }
75
76 export class MobileDatabase extends Context.Service<
77 MobileDatabase,
78 {
79 readonly loadCache: (
80 environmentId: EnvironmentId,
81 kind: ClientCacheKind,
82 cacheKey: string,
83 ) => Effect.Effect<Option.Option<string>, MobileDatabaseError>;
84 readonly listCache: (
85 kind: ClientCacheKind,
86 ) => Effect.Effect<ReadonlyArray<string>, MobileDatabaseError>;
87 readonly saveCache: (
88 environmentId: EnvironmentId,
89 kind: ClientCacheKind,
90 cacheKey: string,
91 schemaVersion: number,
92 payload: string,
93 ) => Effect.Effect<void, MobileDatabaseError>;
94 readonly removeCache: (
95 environmentId: EnvironmentId,
96 kind: ClientCacheKind,
97 cacheKey: string,
98 ) => Effect.Effect<void, MobileDatabaseError>;
99 readonly clearCacheKind: (
100 environmentId: EnvironmentId,
101 kind: ClientCacheKind,
102 ) => Effect.Effect<void, MobileDatabaseError>;
103 readonly clearEnvironmentCache: (
104 environmentId: EnvironmentId,
105 ) => Effect.Effect<void, MobileDatabaseError>;
106 readonly clearAllCaches: Effect.Effect<void, MobileDatabaseError>;
107 readonly inspectCaches: Effect.Effect<
108 ReadonlyArray<ClientCacheSummaryRow>,
109 MobileDatabaseError
110 >;
111 readonly loadPreferencesJson: Effect.Effect<
112 Option.Option<StoredPreferencesJson>,
113 MobileDatabaseError
114 >;
115 readonly savePreferencesJson: (
116 payload: string,
117 updatedAt: number,
118 ) => Effect.Effect<void, MobileDatabaseError>;
119 }
120 >()("@t3tools/mobile/persistence/mobile-database/MobileDatabase") {}
121
122 const makeAvailable = Effect.gen(function* () {
123 const database = yield* Effect.acquireRelease(
124 Effect.tryPromise({
125 try: async () => {
126 const SQLite = await import("expo-sqlite");
127 return SQLite.openDatabaseAsync(DATABASE_NAME);
128 },
129 catch: databaseError("open"),
130 }),
131 (openDatabase) =>
132 Effect.tryPromise({
133 try: () => openDatabase.closeAsync(),
134 catch: databaseError("close"),
135 }).pipe(Effect.ignore),
136 );
137
138 yield* Effect.tryPromise({
139 try: async () => {
140 await database.execAsync("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
141 const schema = await database.getFirstAsync<{ readonly user_version: number }>(
142 "PRAGMA user_version",
143 );
144 await database.withExclusiveTransactionAsync(async (transaction) => {
145 await transaction.execAsync(`
146 CREATE TABLE IF NOT EXISTS client_cache (
147 environment_id TEXT NOT NULL,
148 kind TEXT NOT NULL,
149 cache_key TEXT NOT NULL,
150 schema_version INTEGER NOT NULL,
151 payload TEXT NOT NULL,
152 updated_at INTEGER NOT NULL,
153 PRIMARY KEY (environment_id, kind, cache_key)
154 ) WITHOUT ROWID;
155
156 CREATE INDEX IF NOT EXISTS client_cache_environment_updated
157 ON client_cache (environment_id, updated_at DESC);
158
159 CREATE TABLE IF NOT EXISTS client_preferences (
160 singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1),
161 payload TEXT NOT NULL,
162 updated_at INTEGER NOT NULL
163 );
164 `);
165 });
166 if ((schema?.user_version ?? 0) < DATABASE_SCHEMA_VERSION) {
167 await database.execAsync(`PRAGMA user_version = ${DATABASE_SCHEMA_VERSION};`);
168 }
169 },
170 catch: databaseError("migrate"),
171 });
172
173 return MobileDatabase.of({
174 loadCache: Effect.fn("MobileDatabase.loadCache")(function* (environmentId, kind, cacheKey) {
175 const now = yield* Clock.currentTimeMillis;
176 const row = yield* Effect.tryPromise({
177 try: () =>
178 database.getFirstAsync<{ readonly payload: string }>(
179 `SELECT payload
180 FROM client_cache
181 WHERE environment_id = ? AND kind = ? AND cache_key = ?
182 AND (kind != 'pull-request' OR updated_at >= ?)`,
183 environmentId,
184 kind,
185 cacheKey,
186 now - 30 * 24 * 60 * 60_000,
187 ),
188 catch: databaseError("load-cache"),
189 });
190 return Option.fromNullishOr(row?.payload);
191 }),
192 listCache: Effect.fn("MobileDatabase.listCache")((kind) =>
193 Effect.tryPromise({
194 try: () =>
195 database.getAllAsync<{ readonly payload: string }>(
196 "SELECT payload FROM client_cache WHERE kind = ? ORDER BY updated_at",
197 kind,
198 ),
199 catch: databaseError("list-cache"),
200 }).pipe(Effect.map((rows) => rows.map((row) => row.payload))),
201 ),
202 saveCache: Effect.fn("MobileDatabase.saveCache")(
203 (environmentId, kind, cacheKey, schemaVersion, payload) =>
204 Effect.tryPromise({
205 try: async () => {
206 // Bound offline PR caches to 32 MiB and 256 responses per environment; reject huge diffs that would evict everything.
207 if (
208 kind === "pull-request" &&
209 new TextEncoder().encode(payload).length > 4 * 1024 * 1024
210 )
211 return;
212 const save = async (transaction: SQLiteDatabase) => {
213 await transaction.runAsync(
214 `INSERT INTO client_cache
215 (environment_id, kind, cache_key, schema_version, payload, updated_at)
216 VALUES (?, ?, ?, ?, ?, ?)
217 ON CONFLICT (environment_id, kind, cache_key) DO UPDATE SET
218 schema_version = excluded.schema_version,
219 payload = excluded.payload,
220 updated_at = excluded.updated_at`,
221 environmentId,
222 kind,
223 cacheKey,
224 schemaVersion,
225 payload,
226 Date.now(),
227 );
228 if (kind === "pull-request") {
229 await transaction.runAsync(
230 `DELETE FROM client_cache WHERE environment_id = ? AND kind = 'pull-request'
231 AND cache_key IN (
232 SELECT cache_key FROM (
233 SELECT cache_key, updated_at,
234 ROW_NUMBER() OVER (ORDER BY updated_at DESC, cache_key) AS position,
235 SUM(LENGTH(CAST(payload AS BLOB))) OVER (
236 ORDER BY updated_at DESC, cache_key
237 ) AS total_bytes
238 FROM client_cache WHERE environment_id = ? AND kind = 'pull-request'
239 ) WHERE position > 256 OR total_bytes > 33554432 OR updated_at < ?
240 )`,
241 environmentId,
242 environmentId,
243 Date.now() - 30 * 24 * 60 * 60_000,
244 );
245 }
246 };
247 await save(database);
248 },
249 catch: databaseError("save-cache"),
250 }).pipe(Effect.asVoid),
251 ),
252 removeCache: Effect.fn("MobileDatabase.removeCache")((environmentId, kind, cacheKey) =>
253 Effect.tryPromise({
254 try: () =>
255 database.runAsync(
256 `DELETE FROM client_cache
257 WHERE environment_id = ? AND kind = ? AND cache_key = ?`,
258 environmentId,
259 kind,
260 cacheKey,
261 ),
262 catch: databaseError("remove-cache"),
263 }).pipe(Effect.asVoid),
264 ),
265 clearCacheKind: Effect.fn("MobileDatabase.clearCacheKind")((environmentId, kind) =>
266 Effect.tryPromise({
267 try: () =>
268 database.runAsync(
269 "DELETE FROM client_cache WHERE environment_id = ? AND kind = ?",
270 environmentId,
271 kind,
272 ),
273 catch: databaseError("clear-cache-kind"),
274 }).pipe(Effect.asVoid),
275 ),
276 clearEnvironmentCache: Effect.fn("MobileDatabase.clearEnvironmentCache")((environmentId) =>
277 Effect.tryPromise({
278 try: () =>
279 database.runAsync("DELETE FROM client_cache WHERE environment_id = ?", environmentId),
280 catch: databaseError("clear-environment-cache"),
281 }).pipe(Effect.asVoid),
282 ),
283 clearAllCaches: Effect.tryPromise({
284 try: () => database.runAsync("DELETE FROM client_cache"),
285 catch: databaseError("clear-all-caches"),
286 }).pipe(Effect.asVoid),
287 inspectCaches: Effect.tryPromise({
288 try: () =>
289 database.getAllAsync<unknown>(`
290 SELECT
291 environment_id AS environmentId,
292 kind,
293 COUNT(*) AS recordCount,
294 COALESCE(SUM(LENGTH(CAST(payload AS BLOB))), 0) AS payloadBytes
295 FROM client_cache
296 GROUP BY environment_id, kind
297 ORDER BY environment_id, kind
298 `),
299 catch: databaseError("inspect-caches"),
300 }).pipe(
301 Effect.flatMap(Schema.decodeUnknownEffect(ClientCacheSummaryRows)),
302 Effect.mapError(databaseError("inspect-caches")),
303 Effect.map((rows): ReadonlyArray<ClientCacheSummaryRow> =>
304 rows.map((row) => ({
305 environmentId: row.environmentId as EnvironmentId,
306 kind: row.kind,
307 recordCount: row.recordCount,
308 payloadBytes: row.payloadBytes,
309 })),
310 ),
311 ),
312 loadPreferencesJson: Effect.tryPromise({
313 try: () =>
314 database.getFirstAsync<StoredPreferencesJson>(
315 `SELECT payload, updated_at AS updatedAt
316 FROM client_preferences
317 WHERE singleton = 1`,
318 ),
319 catch: databaseError("load-preferences"),
320 }).pipe(Effect.map(Option.fromNullishOr)),
321 savePreferencesJson: Effect.fn("MobileDatabase.savePreferencesJson")((payload, updatedAt) =>
322 Effect.tryPromise({
323 try: () =>
324 database.runAsync(
325 `INSERT INTO client_preferences (singleton, payload, updated_at)
326 VALUES (1, ?, ?)
327 ON CONFLICT (singleton) DO UPDATE SET
328 payload = excluded.payload,
329 updated_at = excluded.updated_at`,
330 payload,
331 updatedAt,
332 ),
333 catch: databaseError("save-preferences"),
334 }).pipe(Effect.asVoid),
335 ),
336 });
337 });
338
339 function makeUnavailable(error: MobileDatabaseError): MobileDatabase["Service"] {
340 const fail = Effect.fail(error);
341 return MobileDatabase.of({
342 loadCache: Effect.fn("MobileDatabase.loadCache")(() => fail),
343 listCache: Effect.fn("MobileDatabase.listCache")(() => fail),
344 saveCache: Effect.fn("MobileDatabase.saveCache")(() => fail),
345 removeCache: Effect.fn("MobileDatabase.removeCache")(() => fail),
346 clearCacheKind: Effect.fn("MobileDatabase.clearCacheKind")(() => fail),
347 clearEnvironmentCache: Effect.fn("MobileDatabase.clearEnvironmentCache")(() => fail),
348 clearAllCaches: fail,
349 inspectCaches: fail,
350 loadPreferencesJson: fail,
351 savePreferencesJson: Effect.fn("MobileDatabase.savePreferencesJson")(() => fail),
352 });
353 }
354
355 export const make = Effect.result(makeAvailable).pipe(
356 Effect.map((result) =>
357 result._tag === "Success" ? result.success : makeUnavailable(result.failure),
358 ),
359 );
360
361 export const layer = Layer.effect(MobileDatabase, make);