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

mobile-database.ts

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