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