Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

mobile-database.ts

426 lines13.9 KB

1import type { EnvironmentId } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import type { SQLiteDatabase } from "expo-sqlite";
8​
9const DATABASE_NAME = "t3code-client.db";
10const DATABASE_SCHEMA_VERSION = 1;
11const LEGACY_CACHE_DIRECTORIES = [
12 "connection-shell-snapshots",
13 "shell-snapshots",
14 "connection-thread-snapshots",
15 "connection-server-configs",
16 "connection-vcs-refs",
17] as const;
18​
19export const ClientCacheKind = Schema.Literals(["shell", "thread", "server-config", "vcs-refs"]);
20export type ClientCacheKind = typeof ClientCacheKind.Type;
21​
22export interface ClientCacheSummaryRow {
23 readonly environmentId: EnvironmentId;
24 readonly kind: ClientCacheKind;
25 readonly recordCount: number;
26 readonly payloadBytes: number;
28​
29export interface StoredPreferencesJson {
30 readonly payload: string;
31 readonly updatedAt: number;
33​
34const ClientCacheSummaryRows = Schema.Array(
35 Schema.Struct({
36 environmentId: Schema.String,
37 kind: ClientCacheKind,
38 recordCount: Schema.Number,
39 payloadBytes: Schema.Number,
40 }),
41);
42​
43const MobileDatabaseOperation = Schema.Literals([
44 "open",
45 "migrate",
46 "load-cache",
47 "save-cache",
48 "remove-cache",
49 "clear-cache-kind",
50 "clear-environment-cache",
51 "clear-all-caches",
52 "inspect-caches",
53 "load-preferences",
54 "save-preferences",
55]);
56​
57export class MobileDatabaseError extends Schema.TaggedErrorClass<MobileDatabaseError>()(
58 "MobileDatabaseError",
59 {
60 operation: MobileDatabaseOperation,
61 cause: Schema.Defect(),
62 },
63) {
64 override get message(): string {
65 return `Mobile database operation failed: ${this.operation}.`;
66 }
68​
69function databaseError(operation: typeof MobileDatabaseOperation.Type) {
70 return (cause: unknown) => new MobileDatabaseError({ operation, cause });
72​
73interface LegacyCacheRecord {
74 readonly environmentId: string;
75 readonly kind: ClientCacheKind;
76 readonly cacheKey: string;
77 readonly schemaVersion: number;
78 readonly payload: string;
80​
81function objectRecord(value: unknown): Record<string, unknown> | null {
82 return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : null;
84​
85export function decodeLegacyCacheRecord(
86 directoryName: (typeof LEGACY_CACHE_DIRECTORIES)[number],
87 payload: string,
88): LegacyCacheRecord | null {
89 let parsed: Record<string, unknown> | null;
90 try {
91 parsed = objectRecord(JSON.parse(payload));
92 } catch {
93 return null;
94 }
95 if (
96 parsed === null ||
97 typeof parsed.environmentId !== "string" ||
98 typeof parsed.schemaVersion !== "number"
99 ) {
100 return null;
101 }
102​
103 switch (directoryName) {
104 case "connection-shell-snapshots":
105 case "shell-snapshots":
106 return {
107 environmentId: parsed.environmentId,
108 kind: "shell",
109 cacheKey: "snapshot",
110 schemaVersion: parsed.schemaVersion,
111 payload,
112 };
113 case "connection-thread-snapshots":
114 return typeof parsed.threadId === "string"
115 ? {
116 environmentId: parsed.environmentId,
117 kind: "thread",
118 cacheKey: parsed.threadId,
119 schemaVersion: parsed.schemaVersion,
120 payload,
121 }
122 : null;
123 case "connection-server-configs":
124 return {
125 environmentId: parsed.environmentId,
126 kind: "server-config",
127 cacheKey: "config",
128 schemaVersion: parsed.schemaVersion,
129 payload,
130 };
131 case "connection-vcs-refs":
132 return typeof parsed.cwd === "string"
133 ? {
134 environmentId: parsed.environmentId,
135 kind: "vcs-refs",
136 cacheKey: parsed.cwd,
137 schemaVersion: parsed.schemaVersion,
138 payload,
139 }
140 : null;
141 }
143​
144async function migrateLegacyFileCaches(database: SQLiteDatabase): Promise<boolean> {
145 try {
146 const { Directory, File, Paths } = await import("expo-file-system");
147 let complete = true;
148 const listFiles = (
149 directory: InstanceType<typeof Directory>,
150 ): Array<InstanceType<typeof File>> =>
151 directory.list().flatMap((entry) => (entry instanceof File ? [entry] : listFiles(entry)));
152​
153 for (const directoryName of LEGACY_CACHE_DIRECTORIES) {
154 try {
155 const directory = new Directory(Paths.document, directoryName);
156 if (!directory.exists) continue;
157 for (const file of listFiles(directory)) {
158 const payload = await file.text();
159 const record = decodeLegacyCacheRecord(directoryName, payload);
160 if (record === null) continue;
161 await database.runAsync(
162 `INSERT INTO client_cache
163 (environment_id, kind, cache_key, schema_version, payload, updated_at)
164 VALUES (?, ?, ?, ?, ?, ?)
165 ON CONFLICT (environment_id, kind, cache_key) DO NOTHING`,
166 record.environmentId,
167 record.kind,
168 record.cacheKey,
169 record.schemaVersion,
170 record.payload,
171 Date.now(),
172 );
173 }
174 directory.delete();
175 } catch (cause) {
176 complete = false;
177 console.warn(`[mobile-database] could not migrate legacy cache ${directoryName}`, cause);
178 }
179 }
180 return complete;
181 } catch (cause) {
182 console.warn("[mobile-database] could not load legacy cache migration", cause);
183 return false;
184 }
186​
187export class MobileDatabase extends Context.Service<
188 MobileDatabase,
189 {
190 readonly loadCache: (
191 environmentId: EnvironmentId,
192 kind: ClientCacheKind,
193 cacheKey: string,
194 ) => Effect.Effect<Option.Option<string>, MobileDatabaseError>;
195 readonly saveCache: (
196 environmentId: EnvironmentId,
197 kind: ClientCacheKind,
198 cacheKey: string,
199 schemaVersion: number,
200 payload: string,
201 ) => Effect.Effect<void, MobileDatabaseError>;
202 readonly removeCache: (
203 environmentId: EnvironmentId,
204 kind: ClientCacheKind,
205 cacheKey: string,
206 ) => Effect.Effect<void, MobileDatabaseError>;
207 readonly clearCacheKind: (
208 environmentId: EnvironmentId,
209 kind: ClientCacheKind,
210 ) => Effect.Effect<void, MobileDatabaseError>;
211 readonly clearEnvironmentCache: (
212 environmentId: EnvironmentId,
213 ) => Effect.Effect<void, MobileDatabaseError>;
214 readonly clearAllCaches: Effect.Effect<void, MobileDatabaseError>;
215 readonly inspectCaches: Effect.Effect<
216 ReadonlyArray<ClientCacheSummaryRow>,
217 MobileDatabaseError
218 >;
219 readonly loadPreferencesJson: Effect.Effect<
220 Option.Option<StoredPreferencesJson>,
221 MobileDatabaseError
222 >;
223 readonly savePreferencesJson: (
224 payload: string,
225 updatedAt: number,
226 ) => Effect.Effect<void, MobileDatabaseError>;
227 }
228>()("@t3tools/mobile/persistence/MobileDatabase") {}
229​
230const makeAvailable = Effect.gen(function* () {
231 const database = yield* Effect.acquireRelease(
232 Effect.tryPromise({
233 try: async () => {
234 const SQLite = await import("expo-sqlite");
235 return SQLite.openDatabaseAsync(DATABASE_NAME);
236 },
237 catch: databaseError("open"),
238 }),
239 (openDatabase) => Effect.promise(() => openDatabase.closeAsync()).pipe(Effect.ignore),
240 );
241​
242 yield* Effect.tryPromise({
243 try: async () => {
244 await database.execAsync("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
245 const schema = await database.getFirstAsync<{ readonly user_version: number }>(
246 "PRAGMA user_version",
247 );
248 await database.withExclusiveTransactionAsync(async (transaction) => {
249 await transaction.execAsync(`
250 CREATE TABLE IF NOT EXISTS client_cache (
251 environment_id TEXT NOT NULL,
252 kind TEXT NOT NULL,
253 cache_key TEXT NOT NULL,
254 schema_version INTEGER NOT NULL,
255 payload TEXT NOT NULL,
256 updated_at INTEGER NOT NULL,
257 PRIMARY KEY (environment_id, kind, cache_key)
258 ) WITHOUT ROWID;
259​
260 CREATE INDEX IF NOT EXISTS client_cache_environment_updated
261 ON client_cache (environment_id, updated_at DESC);
262​
263 CREATE TABLE IF NOT EXISTS client_preferences (
264 singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1),
265 payload TEXT NOT NULL,
266 updated_at INTEGER NOT NULL
267 );
268 `);
269 });
270 if ((schema?.user_version ?? 0) < DATABASE_SCHEMA_VERSION) {
271 const migrated = await migrateLegacyFileCaches(database);
272 if (migrated) {
273 await database.execAsync(`PRAGMA user_version = ${DATABASE_SCHEMA_VERSION};`);
274 }
275 }
276 },
277 catch: databaseError("migrate"),
278 });
279​
280 return MobileDatabase.of({
281 loadCache: Effect.fn("MobileDatabase.loadCache")((environmentId, kind, cacheKey) =>
282 Effect.tryPromise({
283 try: () =>
284 database.getFirstAsync<{ readonly payload: string }>(
285 `SELECT payload
286 FROM client_cache
287 WHERE environment_id = ? AND kind = ? AND cache_key = ?`,
288 environmentId,
289 kind,
290 cacheKey,
291 ),
292 catch: databaseError("load-cache"),
293 }).pipe(Effect.map((row) => Option.fromNullishOr(row?.payload))),
294 ),
295 saveCache: Effect.fn("MobileDatabase.saveCache")(
296 (environmentId, kind, cacheKey, schemaVersion, payload) =>
297 Effect.tryPromise({
298 try: () =>
299 database.runAsync(
300 `INSERT INTO client_cache
301 (environment_id, kind, cache_key, schema_version, payload, updated_at)
302 VALUES (?, ?, ?, ?, ?, ?)
303 ON CONFLICT (environment_id, kind, cache_key) DO UPDATE SET
304 schema_version = excluded.schema_version,
305 payload = excluded.payload,
306 updated_at = excluded.updated_at`,
307 environmentId,
308 kind,
309 cacheKey,
310 schemaVersion,
311 payload,
312 Date.now(),
313 ),
314 catch: databaseError("save-cache"),
315 }).pipe(Effect.asVoid),
316 ),
317 removeCache: Effect.fn("MobileDatabase.removeCache")((environmentId, kind, cacheKey) =>
318 Effect.tryPromise({
319 try: () =>
320 database.runAsync(
321 `DELETE FROM client_cache
322 WHERE environment_id = ? AND kind = ? AND cache_key = ?`,
323 environmentId,
324 kind,
325 cacheKey,
326 ),
327 catch: databaseError("remove-cache"),
328 }).pipe(Effect.asVoid),
329 ),
330 clearCacheKind: Effect.fn("MobileDatabase.clearCacheKind")((environmentId, kind) =>
331 Effect.tryPromise({
332 try: () =>
333 database.runAsync(
334 "DELETE FROM client_cache WHERE environment_id = ? AND kind = ?",
335 environmentId,
336 kind,
337 ),
338 catch: databaseError("clear-cache-kind"),
339 }).pipe(Effect.asVoid),
340 ),
341 clearEnvironmentCache: Effect.fn("MobileDatabase.clearEnvironmentCache")((environmentId) =>
342 Effect.tryPromise({
343 try: () =>
344 database.runAsync("DELETE FROM client_cache WHERE environment_id = ?", environmentId),
345 catch: databaseError("clear-environment-cache"),
346 }).pipe(Effect.asVoid),
347 ),
348 clearAllCaches: Effect.tryPromise({
349 try: () => database.runAsync("DELETE FROM client_cache"),
350 catch: databaseError("clear-all-caches"),
351 }).pipe(Effect.asVoid),
352 inspectCaches: Effect.tryPromise({
353 try: () =>
354 database.getAllAsync<unknown>(`
355 SELECT
356 environment_id AS environmentId,
357 kind,
358 COUNT(*) AS recordCount,
359 COALESCE(SUM(LENGTH(CAST(payload AS BLOB))), 0) AS payloadBytes
360 FROM client_cache
361 GROUP BY environment_id, kind
362 ORDER BY environment_id, kind
363 `),
364 catch: databaseError("inspect-caches"),
365 }).pipe(
366 Effect.flatMap(Schema.decodeUnknownEffect(ClientCacheSummaryRows)),
367 Effect.mapError(databaseError("inspect-caches")),
368 Effect.map(
369 (rows): ReadonlyArray<ClientCacheSummaryRow> =>
370 rows.map((row) => ({
371 environmentId: row.environmentId as EnvironmentId,
372 kind: row.kind,
373 recordCount: row.recordCount,
374 payloadBytes: row.payloadBytes,
375 })),
376 ),
377 ),
378 loadPreferencesJson: Effect.tryPromise({
379 try: () =>
380 database.getFirstAsync<StoredPreferencesJson>(
381 `SELECT payload, updated_at AS updatedAt
382 FROM client_preferences
383 WHERE singleton = 1`,
384 ),
385 catch: databaseError("load-preferences"),
386 }).pipe(Effect.map(Option.fromNullishOr)),
387 savePreferencesJson: Effect.fn("MobileDatabase.savePreferencesJson")((payload, updatedAt) =>
388 Effect.tryPromise({
389 try: () =>
390 database.runAsync(
391 `INSERT INTO client_preferences (singleton, payload, updated_at)
392 VALUES (1, ?, ?)
393 ON CONFLICT (singleton) DO UPDATE SET
394 payload = excluded.payload,
395 updated_at = excluded.updated_at`,
396 payload,
397 updatedAt,
398 ),
399 catch: databaseError("save-preferences"),
400 }).pipe(Effect.asVoid),
401 ),
402 });
403});
404​
405function makeUnavailable(error: MobileDatabaseError): MobileDatabase["Service"] {
406 const fail = Effect.fail(error);
407 return MobileDatabase.of({
408 loadCache: () => fail,
409 saveCache: () => fail,
410 removeCache: () => fail,
411 clearCacheKind: () => fail,
412 clearEnvironmentCache: () => fail,
413 clearAllCaches: fail,
414 inspectCaches: fail,
415 loadPreferencesJson: fail,
416 savePreferencesJson: () => fail,
417 });
419​
420export const make = Effect.result(makeAvailable).pipe(
421 Effect.map((result) =>
422 result._tag === "Success" ? result.success : makeUnavailable(result.failure),
423 ),
424);
425​
426export const layer = Layer.effect(MobileDatabase, make);