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