Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import { vi } from "vite-plus/test";
5
6const openDatabaseAsync = vi.hoisted(() => vi.fn());
7
8vi.mock("expo-sqlite", () => ({ openDatabaseAsync }));
9
10import * as MobileDatabase from "./mobile-database";
11
12describe("mobile database legacy cache migration", () => {
13 it.effect("keeps acquisition failures typed on database operations", () =>
14 Effect.scoped(
15 Effect.gen(function* () {
16 openDatabaseAsync.mockRejectedValueOnce(new Error("SQLite unavailable"));
17
18 const database = yield* MobileDatabase.make;
19 const result = yield* Effect.result(database.loadPreferencesJson);
20
21 expect(result).toMatchObject({
22 _tag: "Failure",
23 failure: { _tag: "MobileDatabaseError", operation: "open" },
24 });
25 }),
26 ),
27 );
28
29 it("maps legacy thread records to their SQLite identity", () => {
30 const payload = JSON.stringify({
31 schemaVersion: 2,
32 environmentId: "environment-1",
33 threadId: "thread-1",
34 snapshot: {},
35 });
36
37 expect(MobileDatabase.decodeLegacyCacheRecord("connection-thread-snapshots", payload)).toEqual({
38 environmentId: "environment-1",
39 kind: "thread",
40 cacheKey: "thread-1",
41 schemaVersion: 2,
42 payload,
43 });
44 });
45
46 it("preserves the old shell payload for schema decoding after migration", () => {
47 const payload = JSON.stringify({
48 schemaVersion: 1,
49 environmentId: "environment-1",
50 snapshotReceivedAt: "2026-07-01T00:00:00.000Z",
51 snapshot: {},
52 });
53
54 expect(MobileDatabase.decodeLegacyCacheRecord("shell-snapshots", payload)).toEqual({
55 environmentId: "environment-1",
56 kind: "shell",
57 cacheKey: "snapshot",
58 schemaVersion: 1,
59 payload,
60 });
61 });
62
63 it("skips malformed legacy records", () => {
64 expect(MobileDatabase.decodeLegacyCacheRecord("connection-vcs-refs", "{not-json")).toBeNull();
65 expect(
66 MobileDatabase.decodeLegacyCacheRecord(
67 "connection-vcs-refs",
68 JSON.stringify({ schemaVersion: 1, environmentId: "environment-1" }),
69 ),
70 ).toBeNull();
71 });
72});
73
74describe("offline pull request cache", () => {
75 const environmentId = "cached-environment" as import("@t3tools/contracts").EnvironmentId;
76 const otherEnvironment = "other-environment" as import("@t3tools/contracts").EnvironmentId;
77
78 async function sqliteDatabase() {
79 const { DatabaseSync } = await import("node:sqlite");
80 const sqlite = new DatabaseSync(":memory:");
81 sqlite.exec("PRAGMA user_version = 1");
82 const database = {
83 execAsync: async (sql: string) => {
84 sqlite.exec(sql);
85 },
86 runAsync: async (sql: string, ...args: Array<string | number>) =>
87 sqlite.prepare(sql).run(...args),
88 getFirstAsync: async (sql: string, ...args: Array<string | number>) =>
89 sqlite.prepare(sql).get(...args),
90 getAllAsync: async (sql: string, ...args: Array<string | number>) =>
91 sqlite.prepare(sql).all(...args),
92 withExclusiveTransactionAsync: async (run: (transaction: unknown) => Promise<void>) => {
93 await run(database);
94 },
95 closeAsync: async () => {
96 sqlite.close();
97 },
98 };
99 openDatabaseAsync.mockResolvedValueOnce(database);
100 return sqlite;
101 }
102
103 it.effect("restores saved records and clears them with the environment", () =>
104 Effect.scoped(
105 Effect.gen(function* () {
106 yield* Effect.promise(sqliteDatabase);
107 const database = yield* MobileDatabase.make;
108 yield* database.saveCache(environmentId, "pull-request", "v1:list", 1, '{"entries":[]}');
109 yield* database.saveCache(otherEnvironment, "pull-request", "v1:list", 1, "other");
110 expect(yield* database.loadCache(environmentId, "pull-request", "v1:list")).toEqual(
111 Option.some('{"entries":[]}'),
112 );
113 yield* database.clearEnvironmentCache(environmentId);
114 expect((yield* database.loadCache(environmentId, "pull-request", "v1:list"))._tag).toBe(
115 "None",
116 );
117 expect((yield* database.loadCache(otherEnvironment, "pull-request", "v1:list"))._tag).toBe(
118 "Some",
119 );
120 }),
121 ),
122 );
123
124 it.effect(
125 "expires old records and bounds count and payload size without evicting other cache kinds",
126 () =>
127 Effect.scoped(
128 Effect.gen(function* () {
129 const sqlite = yield* Effect.promise(sqliteDatabase);
130 const database = yield* MobileDatabase.make;
131 yield* database.saveCache(environmentId, "thread", "thread", 1, "thread");
132 yield* database.saveCache(environmentId, "pull-request", "old", 1, "old");
133 sqlite.prepare("UPDATE client_cache SET updated_at = 0 WHERE cache_key = 'old'").run();
134 expect((yield* database.loadCache(environmentId, "pull-request", "old"))._tag).toBe(
135 "None",
136 );
137 for (let i = 0; i < 260; i++)
138 yield* database.saveCache(environmentId, "pull-request", `page-${i}`, 1, "page");
139 expect((yield* database.listCache("pull-request")).length).toBe(256);
140 const large = "x".repeat(4 * 1024 * 1024);
141 for (let i = 0; i < 10; i++)
142 yield* database.saveCache(environmentId, "pull-request", `diff-${i}`, 1, large);
143 const summary = yield* database.inspectCaches;
144 const prs = summary.find((row) => row.kind === "pull-request");
145 expect(prs?.payloadBytes).toBeLessThanOrEqual(32 * 1024 * 1024);
146 expect(prs?.recordCount).toBeLessThanOrEqual(256);
147 expect((yield* database.loadCache(environmentId, "thread", "thread"))._tag).toBe("Some");
148 yield* database.saveCache(environmentId, "pull-request", "oversized", 1, large + "x");
149 expect((yield* database.loadCache(environmentId, "pull-request", "oversized"))._tag).toBe(
150 "None",
151 );
152 }),
153 ),
154 );
155});