Open History to see the last commit
1import {
2 ConnectionPersistenceError,
3 EnvironmentCacheStore,
4} from "@t3tools/client-runtime/platform";
5import {
6 type EnvironmentId,
7 OrchestrationShellSnapshot,
8 OrchestrationThreadDetailSnapshot,
9 ServerConfig,
10 VcsListRefsResult,
11} from "@t3tools/contracts";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Schema from "effect/Schema";
16
17import * as MobileDatabase from "../persistence/mobile-database";
18import {
19 attachProjectFaviconDatabase,
20 projectFaviconDatabaseCache,
21} from "../lib/projectFaviconDatabaseCache";
22
23const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
24// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
25// makes pre-pagination clients discard the record instead of decoding a
26// partial thread as complete (rollback safety).
27// v4 reloads pre-thinking caches whose system-role fallback would otherwise
28// survive afterSequence resume and hide settled reasoning messages.
29const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 4;
30const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
31const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
32
33const StoredShellSnapshot = Schema.Struct({
34 schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
35 environmentId: Schema.String,
36 snapshot: OrchestrationShellSnapshot,
37});
38const StoredThreadSnapshot = Schema.Struct({
39 schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
40 environmentId: Schema.String,
41 threadId: Schema.String,
42 snapshot: OrchestrationThreadDetailSnapshot,
43});
44const StoredServerConfig = Schema.Struct({
45 schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
46 environmentId: Schema.String,
47 config: ServerConfig,
48});
49const StoredVcsRefs = Schema.Struct({
50 schemaVersion: Schema.Literal(VCS_REFS_CACHE_SCHEMA_VERSION),
51 environmentId: Schema.String,
52 cwd: Schema.String,
53 refs: VcsListRefsResult,
54});
55
56const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(
57 Schema.fromJsonString(StoredShellSnapshot),
58);
59const encodeStoredShellSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredShellSnapshot));
60const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(
61 Schema.fromJsonString(StoredThreadSnapshot),
62);
63const encodeStoredThreadSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredThreadSnapshot));
64const decodeStoredServerConfig = Schema.decodeUnknownEffect(
65 Schema.fromJsonString(StoredServerConfig),
66);
67const encodeStoredServerConfig = Schema.encodeEffect(Schema.fromJsonString(StoredServerConfig));
68const decodeStoredVcsRefs = Schema.decodeUnknownEffect(Schema.fromJsonString(StoredVcsRefs));
69const encodeStoredVcsRefs = Schema.encodeEffect(Schema.fromJsonString(StoredVcsRefs));
70
71type CacheOperation = ConnectionPersistenceError["operation"];
72
73function persistenceError(operation: CacheOperation, cause: unknown) {
74 return new ConnectionPersistenceError({
75 operation,
76 message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
77 });
78}
79
80function mapDatabaseError(operation: CacheOperation) {
81 return (error: MobileDatabase.MobileDatabaseError) => persistenceError(operation, error);
82}
83
84function loadDecodedCache<A, B>(input: {
85 readonly database: MobileDatabase.MobileDatabase["Service"];
86 readonly environmentId: EnvironmentId;
87 readonly kind: MobileDatabase.ClientCacheKind;
88 readonly cacheKey: string;
89 readonly operation: CacheOperation;
90 readonly decode: (raw: string) => Effect.Effect<A, unknown>;
91 readonly select: (value: A) => Option.Option<B>;
92}): Effect.Effect<Option.Option<B>, ConnectionPersistenceError> {
93 return input.database.loadCache(input.environmentId, input.kind, input.cacheKey).pipe(
94 Effect.mapError(mapDatabaseError(input.operation)),
95 Effect.flatMap(
96 Option.match({
97 onNone: () => Effect.succeed(Option.none<B>()),
98 onSome: (raw) =>
99 input.decode(raw).pipe(
100 Effect.map(input.select),
101 Effect.catch((cause) =>
102 Effect.logWarning("Discarding corrupt mobile client cache record.", {
103 environmentId: input.environmentId,
104 kind: input.kind,
105 cacheKey: input.cacheKey,
106 cause: String(cause),
107 }).pipe(
108 Effect.andThen(
109 input.database
110 .removeCache(input.environmentId, input.kind, input.cacheKey)
111 .pipe(Effect.catch(() => Effect.void)),
112 ),
113 Effect.as(Option.none<B>()),
114 ),
115 ),
116 ),
117 }),
118 ),
119 );
120}
121
122export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
123 const database = yield* MobileDatabase.MobileDatabase;
124 attachProjectFaviconDatabase(database);
125 return EnvironmentCacheStore.of({
126 loadShell: Effect.fn("MobileEnvironmentCache.loadShell")((environmentId) =>
127 loadDecodedCache({
128 database,
129 environmentId,
130 kind: "shell",
131 cacheKey: "snapshot",
132 operation: "load-shell",
133 decode: decodeStoredShellSnapshot,
134 select: (stored) =>
135 stored.environmentId === environmentId ? Option.some(stored.snapshot) : Option.none(),
136 }).pipe(Effect.tap(() => Effect.promise(() => projectFaviconDatabaseCache.hydrate()))),
137 ),
138 saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) {
139 const payload = yield* encodeStoredShellSnapshot({
140 schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
141 environmentId,
142 snapshot,
143 }).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
144 yield* database
145 .saveCache(environmentId, "shell", "snapshot", SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
146 .pipe(Effect.mapError(mapDatabaseError("save-shell")));
147 }),
148 loadThread: Effect.fn("MobileEnvironmentCache.loadThread")((environmentId, threadId) =>
149 loadDecodedCache({
150 database,
151 environmentId,
152 kind: "thread",
153 cacheKey: threadId,
154 operation: "load-thread",
155 decode: decodeStoredThreadSnapshot,
156 select: (stored) =>
157 stored.environmentId === environmentId && stored.threadId === threadId
158 ? Option.some(stored.snapshot)
159 : Option.none(),
160 }),
161 ),
162 saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) {
163 const threadId = snapshot.thread.id;
164 const payload = yield* encodeStoredThreadSnapshot({
165 schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
166 environmentId,
167 threadId,
168 snapshot,
169 }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
170 yield* database
171 .saveCache(environmentId, "thread", threadId, THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
172 .pipe(Effect.mapError(mapDatabaseError("save-thread")));
173 }),
174 removeThread: Effect.fn("MobileEnvironmentCache.removeThread")((environmentId, threadId) =>
175 database
176 .removeCache(environmentId, "thread", threadId)
177 .pipe(Effect.mapError(mapDatabaseError("remove-thread"))),
178 ),
179 loadServerConfig: Effect.fn("MobileEnvironmentCache.loadServerConfig")((environmentId) =>
180 loadDecodedCache({
181 database,
182 environmentId,
183 kind: "server-config",
184 cacheKey: "config",
185 operation: "load-server-config",
186 decode: decodeStoredServerConfig,
187 select: (stored) =>
188 stored.environmentId === environmentId ? Option.some(stored.config) : Option.none(),
189 }),
190 ),
191 saveServerConfig: Effect.fn("MobileEnvironmentCache.saveServerConfig")(
192 function* (environmentId, config) {
193 const payload = yield* encodeStoredServerConfig({
194 schemaVersion: SERVER_CONFIG_CACHE_SCHEMA_VERSION,
195 environmentId,
196 config,
197 }).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));
198 yield* database
199 .saveCache(
200 environmentId,
201 "server-config",
202 "config",
203 SERVER_CONFIG_CACHE_SCHEMA_VERSION,
204 payload,
205 )
206 .pipe(Effect.mapError(mapDatabaseError("save-server-config")));
207 },
208 ),
209 loadVcsRefs: Effect.fn("MobileEnvironmentCache.loadVcsRefs")((environmentId, cwd) =>
210 loadDecodedCache({
211 database,
212 environmentId,
213 kind: "vcs-refs",
214 cacheKey: cwd,
215 operation: "load-vcs-refs",
216 decode: decodeStoredVcsRefs,
217 select: (stored) =>
218 stored.environmentId === environmentId && stored.cwd === cwd
219 ? Option.some(stored.refs)
220 : Option.none(),
221 }),
222 ),
223 saveVcsRefs: Effect.fn("MobileEnvironmentCache.saveVcsRefs")(
224 function* (environmentId, cwd, refs) {
225 const payload = yield* encodeStoredVcsRefs({
226 schemaVersion: VCS_REFS_CACHE_SCHEMA_VERSION,
227 environmentId,
228 cwd,
229 refs,
230 }).pipe(Effect.mapError((cause) => persistenceError("save-vcs-refs", cause)));
231 yield* database
232 .saveCache(environmentId, "vcs-refs", cwd, VCS_REFS_CACHE_SCHEMA_VERSION, payload)
233 .pipe(Effect.mapError(mapDatabaseError("save-vcs-refs")));
234 },
235 ),
236 removeVcsRefs: Effect.fn("MobileEnvironmentCache.removeVcsRefs")((environmentId, cwd) =>
237 database
238 .removeCache(environmentId, "vcs-refs", cwd)
239 .pipe(Effect.mapError(mapDatabaseError("remove-vcs-refs"))),
240 ),
241 clearVcsRefs: Effect.fn("MobileEnvironmentCache.clearVcsRefs")((environmentId) =>
242 database
243 .clearCacheKind(environmentId, "vcs-refs")
244 .pipe(Effect.mapError(mapDatabaseError("clear-vcs-refs"))),
245 ),
246 clear: Effect.fn("MobileEnvironmentCache.clear")((environmentId) =>
247 Effect.promise(() => projectFaviconDatabaseCache.clearEnvironment(environmentId)).pipe(
248 Effect.andThen(database.clearEnvironmentCache(environmentId)),
249 Effect.mapError(mapDatabaseError("clear-environment")),
250 ),
251 ),
252 });
253});
254
255export const layer = Layer.effect(EnvironmentCacheStore, make());