Open History to see the last commit
1import {
2 ConnectionPersistenceError,
3 EnvironmentCacheStore,
4 encodeShellSnapshotForCache,
5} from "@t3tools/client-runtime/platform";
6import {
7 type EnvironmentId,
8 OrchestrationShellSnapshot,
9 OrchestrationThreadDetailSnapshot,
10 ServerConfig,
11 VcsListRefsResult,
12} from "@t3tools/contracts";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Schema from "effect/Schema";
17
18import * as MobileDatabase from "../persistence/mobile-database";
19import {
20 attachProjectFaviconDatabase,
21 projectFaviconDatabaseCache,
22} from "../lib/projectFaviconDatabaseCache";
23
24const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
25// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
26// makes pre-pagination clients discard the record instead of decoding a
27// partial thread as complete (rollback safety).
28// v4 reloads pre-thinking caches whose system-role fallback would otherwise
29// survive afterSequence resume and hide settled reasoning messages.
30const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 4;
31const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
32const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
33
34const StoredShellSnapshot = Schema.Struct({
35 schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
36 environmentId: Schema.String,
37 snapshot: OrchestrationShellSnapshot,
38});
39const StoredThreadSnapshot = Schema.Struct({
40 schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
41 environmentId: Schema.String,
42 threadId: Schema.String,
43 snapshot: OrchestrationThreadDetailSnapshot,
44});
45const StoredServerConfig = Schema.Struct({
46 schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
47 environmentId: Schema.String,
48 config: ServerConfig,
49});
50const StoredVcsRefs = Schema.Struct({
51 schemaVersion: Schema.Literal(VCS_REFS_CACHE_SCHEMA_VERSION),
52 environmentId: Schema.String,
53 cwd: Schema.String,
54 refs: VcsListRefsResult,
55});
56
57const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(
58 Schema.fromJsonString(StoredShellSnapshot),
59);
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 encodedSnapshot = yield* encodeShellSnapshotForCache(snapshot).pipe(
140 Effect.mapError((cause) => persistenceError("save-shell", cause)),
141 );
142 const payload = yield* Effect.try({
143 try: () =>
144 JSON.stringify({
145 schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
146 environmentId,
147 snapshot: encodedSnapshot,
148 } satisfies typeof StoredShellSnapshot.Encoded),
149 catch: (cause) => persistenceError("save-shell", cause),
150 });
151 yield* database
152 .saveCache(environmentId, "shell", "snapshot", SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
153 .pipe(Effect.mapError(mapDatabaseError("save-shell")));
154 }),
155 loadThread: Effect.fn("MobileEnvironmentCache.loadThread")((environmentId, threadId) =>
156 loadDecodedCache({
157 database,
158 environmentId,
159 kind: "thread",
160 cacheKey: threadId,
161 operation: "load-thread",
162 decode: decodeStoredThreadSnapshot,
163 select: (stored) =>
164 stored.environmentId === environmentId && stored.threadId === threadId
165 ? Option.some(stored.snapshot)
166 : Option.none(),
167 }),
168 ),
169 saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) {
170 const threadId = snapshot.thread.id;
171 const payload = yield* encodeStoredThreadSnapshot({
172 schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
173 environmentId,
174 threadId,
175 snapshot,
176 }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
177 yield* database
178 .saveCache(environmentId, "thread", threadId, THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
179 .pipe(Effect.mapError(mapDatabaseError("save-thread")));
180 }),
181 removeThread: Effect.fn("MobileEnvironmentCache.removeThread")((environmentId, threadId) =>
182 database
183 .removeCache(environmentId, "thread", threadId)
184 .pipe(Effect.mapError(mapDatabaseError("remove-thread"))),
185 ),
186 loadServerConfig: Effect.fn("MobileEnvironmentCache.loadServerConfig")((environmentId) =>
187 loadDecodedCache({
188 database,
189 environmentId,
190 kind: "server-config",
191 cacheKey: "config",
192 operation: "load-server-config",
193 decode: decodeStoredServerConfig,
194 select: (stored) =>
195 stored.environmentId === environmentId ? Option.some(stored.config) : Option.none(),
196 }),
197 ),
198 saveServerConfig: Effect.fn("MobileEnvironmentCache.saveServerConfig")(
199 function* (environmentId, config) {
200 const payload = yield* encodeStoredServerConfig({
201 schemaVersion: SERVER_CONFIG_CACHE_SCHEMA_VERSION,
202 environmentId,
203 config,
204 }).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));
205 yield* database
206 .saveCache(
207 environmentId,
208 "server-config",
209 "config",
210 SERVER_CONFIG_CACHE_SCHEMA_VERSION,
211 payload,
212 )
213 .pipe(Effect.mapError(mapDatabaseError("save-server-config")));
214 },
215 ),
216 loadVcsRefs: Effect.fn("MobileEnvironmentCache.loadVcsRefs")((environmentId, cwd) =>
217 loadDecodedCache({
218 database,
219 environmentId,
220 kind: "vcs-refs",
221 cacheKey: cwd,
222 operation: "load-vcs-refs",
223 decode: decodeStoredVcsRefs,
224 select: (stored) =>
225 stored.environmentId === environmentId && stored.cwd === cwd
226 ? Option.some(stored.refs)
227 : Option.none(),
228 }),
229 ),
230 saveVcsRefs: Effect.fn("MobileEnvironmentCache.saveVcsRefs")(
231 function* (environmentId, cwd, refs) {
232 const payload = yield* encodeStoredVcsRefs({
233 schemaVersion: VCS_REFS_CACHE_SCHEMA_VERSION,
234 environmentId,
235 cwd,
236 refs,
237 }).pipe(Effect.mapError((cause) => persistenceError("save-vcs-refs", cause)));
238 yield* database
239 .saveCache(environmentId, "vcs-refs", cwd, VCS_REFS_CACHE_SCHEMA_VERSION, payload)
240 .pipe(Effect.mapError(mapDatabaseError("save-vcs-refs")));
241 },
242 ),
243 removeVcsRefs: Effect.fn("MobileEnvironmentCache.removeVcsRefs")((environmentId, cwd) =>
244 database
245 .removeCache(environmentId, "vcs-refs", cwd)
246 .pipe(Effect.mapError(mapDatabaseError("remove-vcs-refs"))),
247 ),
248 clearVcsRefs: Effect.fn("MobileEnvironmentCache.clearVcsRefs")((environmentId) =>
249 database
250 .clearCacheKind(environmentId, "vcs-refs")
251 .pipe(Effect.mapError(mapDatabaseError("clear-vcs-refs"))),
252 ),
253 clear: Effect.fn("MobileEnvironmentCache.clear")((environmentId) =>
254 Effect.promise(() => projectFaviconDatabaseCache.clearEnvironment(environmentId)).pipe(
255 Effect.andThen(database.clearEnvironmentCache(environmentId)),
256 Effect.mapError(mapDatabaseError("clear-environment")),
257 ),
258 ),
259 });
260});
261
262export const layer = Layer.effect(EnvironmentCacheStore, make());