Open History to see the last commit
1import {
2 ConnectionPersistenceError,
3 ConnectionRegistrationStore,
4 ConnectionTargetStore,
5 EnvironmentCacheStore,
6 registerConnectionInCatalog,
7 removeConnectionFromCatalog,
8 removeCatalogValue,
9 replaceCatalogValue,
10} from "@t3tools/client-runtime/platform";
11import { TokenStore } from "@t3tools/client-runtime/authorization";
12import {
13 ConnectionTransientError,
14 CredentialStore,
15 ProfileStore,
16} from "@t3tools/client-runtime/connection";
17import {
18 EnvironmentId,
19 OrchestrationShellSnapshot,
20 OrchestrationThreadDetailSnapshot,
21 ThreadId,
22} from "@t3tools/contracts";
23import * as Context from "effect/Context";
24import * as Effect from "effect/Effect";
25import * as Layer from "effect/Layer";
26import * as Option from "effect/Option";
27import * as Schema from "effect/Schema";
28import * as SecureStore from "expo-secure-store";
29
30import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
31
32const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
33const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
34const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
35// v2 stores the snapshot sequence alongside the thread so a warm cache can
36// resume via `afterSequence` instead of re-downloading the full thread body.
37// Older v1 entries (no sequence) fail to decode and are treated as a cold cache.
38const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
39const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
40
41const StoredShellSnapshot = Schema.Struct({
42 schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
43 environmentId: EnvironmentId,
44 snapshot: OrchestrationShellSnapshot,
45});
46
47const StoredThreadSnapshot = Schema.Struct({
48 schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
49 environmentId: EnvironmentId,
50 threadId: ThreadId,
51 snapshot: OrchestrationThreadDetailSnapshot,
52});
53
54const LegacyStoredShellSnapshot = Schema.Struct({
55 schemaVersion: Schema.Literal(1),
56 environmentId: EnvironmentId,
57 snapshotReceivedAt: Schema.String,
58 snapshot: OrchestrationShellSnapshot,
59});
60
61function catalogError(operation: string, cause: unknown) {
62 return new ConnectionTransientError({
63 reason: "remote-unavailable",
64 detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
65 });
66}
67
68function shellPersistenceError(
69 operation:
70 | "load-shell"
71 | "save-shell"
72 | "load-thread"
73 | "save-thread"
74 | "remove-thread"
75 | "clear-environment",
76 cause: unknown,
77) {
78 return new ConnectionPersistenceError({
79 operation,
80 message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
81 });
82}
83
84function threadSnapshotFileName(threadId: ThreadId): string {
85 return `${encodeURIComponent(threadId)}.json`;
86}
87
88const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")(
89 function* (
90 environmentId: EnvironmentId,
91 operation: "load-thread" | "save-thread" | "remove-thread" | "clear-environment",
92 ) {
93 return yield* Effect.tryPromise({
94 try: async () => {
95 const { Directory, Paths } = await import("expo-file-system");
96 const directory = new Directory(
97 Paths.document,
98 THREAD_SNAPSHOT_CACHE_DIRECTORY,
99 encodeURIComponent(environmentId),
100 );
101 if (operation !== "clear-environment") {
102 directory.create({ idempotent: true, intermediates: true });
103 }
104 return directory;
105 },
106 catch: (cause) => shellPersistenceError(operation, cause),
107 });
108 },
109);
110
111const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFile")(function* (
112 environmentId: EnvironmentId,
113 threadId: ThreadId,
114 operation: "load-thread" | "save-thread" | "remove-thread",
115) {
116 const { File } = yield* Effect.promise(() => import("expo-file-system"));
117 return new File(
118 yield* threadSnapshotDirectory(environmentId, operation),
119 threadSnapshotFileName(threadId),
120 );
121});
122
123function targetPersistenceError(
124 operation: "list-targets" | "register-connection" | "remove-connection",
125 error: ConnectionTransientError,
126) {
127 return new ConnectionPersistenceError({
128 operation,
129 message: error.message,
130 });
131}
132
133const secureCatalogStorage: SecureCatalogStorage = {
134 getItem: (key) =>
135 Effect.tryPromise({
136 try: () => SecureStore.getItemAsync(key),
137 catch: (cause) => catalogError("load", cause),
138 }),
139 setItem: (key, value) =>
140 Effect.tryPromise({
141 try: () => SecureStore.setItemAsync(key, value),
142 catch: (cause) => catalogError("save", cause),
143 }),
144 deleteItem: (key) =>
145 Effect.tryPromise({
146 try: () => SecureStore.deleteItemAsync(key),
147 catch: (cause) => catalogError("delete", cause),
148 }),
149};
150
151function shellSnapshotFileName(environmentId: EnvironmentId): string {
152 return `${encodeURIComponent(environmentId)}.json`;
153}
154
155const shellSnapshotFileInDirectory = Effect.fn(
156 "mobile.connectionStorage.shellSnapshotFileInDirectory",
157)(function* (
158 environmentId: EnvironmentId,
159 operation: "load-shell" | "save-shell" | "clear-environment",
160 directoryName: string,
161) {
162 return yield* Effect.tryPromise({
163 try: async () => {
164 const { Directory, File, Paths } = await import("expo-file-system");
165 const directory = new Directory(Paths.document, directoryName);
166 directory.create({ idempotent: true, intermediates: true });
167 return new File(directory, shellSnapshotFileName(environmentId));
168 },
169 catch: (cause) => shellPersistenceError(operation, cause),
170 });
171});
172
173const shellSnapshotFile = (
174 environmentId: EnvironmentId,
175 operation: "load-shell" | "save-shell" | "clear-environment",
176) => shellSnapshotFileInDirectory(environmentId, operation, SHELL_SNAPSHOT_CACHE_DIRECTORY);
177
178const legacyShellSnapshotFile = (
179 environmentId: EnvironmentId,
180 operation: "load-shell" | "clear-environment",
181) => shellSnapshotFileInDirectory(environmentId, operation, LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY);
182
183export const connectionStorageLayer = Layer.effectContext(
184 Effect.gen(function* () {
185 const catalog = yield* makeCatalogStore(secureCatalogStorage);
186
187 const targetStore = ConnectionTargetStore.of({
188 list: catalog.read.pipe(
189 Effect.map((document) => document.targets),
190 Effect.mapError((error) => targetPersistenceError("list-targets", error)),
191 ),
192 });
193 const registrationStore = ConnectionRegistrationStore.of({
194 register: (registration) =>
195 catalog
196 .update((document) => registerConnectionInCatalog(document, registration))
197 .pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
198 remove: (target) =>
199 catalog
200 .update((document) => removeConnectionFromCatalog(document, target))
201 .pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
202 });
203 const profileStore = ProfileStore.make({
204 get: (connectionId) =>
205 catalog.read.pipe(
206 Effect.map((document) =>
207 Option.fromUndefinedOr(
208 document.profiles.find((candidate) => candidate.connectionId === connectionId),
209 ),
210 ),
211 ),
212 put: (profile) =>
213 catalog.update((document) => ({
214 ...document,
215 profiles: replaceCatalogValue(document.profiles, (value) => value.connectionId, profile),
216 })),
217 remove: (connectionId) =>
218 catalog.update((document) => ({
219 ...document,
220 profiles: removeCatalogValue(
221 document.profiles,
222 (value) => value.connectionId,
223 connectionId,
224 ),
225 })),
226 });
227 const credentialStore = CredentialStore.make({
228 get: (connectionId) =>
229 catalog.read.pipe(
230 Effect.map((document) =>
231 Option.fromUndefinedOr(
232 document.credentials.find((entry) => entry.connectionId === connectionId)?.credential,
233 ),
234 ),
235 ),
236 put: (connectionId, credential) =>
237 catalog.update((document) => ({
238 ...document,
239 credentials: replaceCatalogValue(document.credentials, (value) => value.connectionId, {
240 connectionId,
241 credential,
242 }),
243 })),
244 remove: (connectionId) =>
245 catalog.update((document) => ({
246 ...document,
247 credentials: removeCatalogValue(
248 document.credentials,
249 (value) => value.connectionId,
250 connectionId,
251 ),
252 })),
253 });
254 const remoteTokenStore = TokenStore.make({
255 get: (environmentId) =>
256 catalog.read.pipe(
257 Effect.map((document) =>
258 Option.fromUndefinedOr(
259 document.remoteDpopTokens.find((token) => token.environmentId === environmentId),
260 ),
261 ),
262 ),
263 put: (token) =>
264 catalog.update((document) => ({
265 ...document,
266 remoteDpopTokens: replaceCatalogValue(
267 document.remoteDpopTokens,
268 (value) => value.environmentId,
269 token,
270 ),
271 })),
272 remove: (environmentId) =>
273 catalog.update((document) => ({
274 ...document,
275 remoteDpopTokens: removeCatalogValue(
276 document.remoteDpopTokens,
277 (value) => value.environmentId,
278 environmentId,
279 ),
280 })),
281 });
282 const cacheStore = EnvironmentCacheStore.of({
283 loadShell: (environmentId) =>
284 Effect.gen(function* () {
285 const file = yield* shellSnapshotFile(environmentId, "load-shell");
286 if (file.exists) {
287 const raw = yield* Effect.tryPromise({
288 try: () => file.text(),
289 catch: (cause) => shellPersistenceError("load-shell", cause),
290 });
291 const parsed = yield* Effect.try({
292 try: () => JSON.parse(raw) as unknown,
293 catch: (cause) => shellPersistenceError("load-shell", cause),
294 });
295 const stored = yield* Effect.fromResult(
296 Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
297 ).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
298 return stored.environmentId === environmentId
299 ? Option.some(stored.snapshot)
300 : Option.none();
301 }
302
303 const legacyFile = yield* legacyShellSnapshotFile(environmentId, "load-shell");
304 if (!legacyFile.exists) {
305 return Option.none();
306 }
307 const legacyRaw = yield* Effect.tryPromise({
308 try: () => legacyFile.text(),
309 catch: (cause) => shellPersistenceError("load-shell", cause),
310 });
311 const legacyParsed = yield* Effect.try({
312 try: () => JSON.parse(legacyRaw) as unknown,
313 catch: (cause) => shellPersistenceError("load-shell", cause),
314 });
315 const legacyStored = yield* Effect.fromResult(
316 Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
317 ).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
318 return legacyStored.environmentId === environmentId
319 ? Option.some(legacyStored.snapshot)
320 : Option.none();
321 }),
322 saveShell: (environmentId, snapshot) =>
323 Effect.gen(function* () {
324 const file = yield* shellSnapshotFile(environmentId, "save-shell");
325 const stored = {
326 schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
327 environmentId,
328 snapshot,
329 } as const;
330 const encoded = yield* Effect.fromResult(
331 Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
332 ).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
333 yield* Effect.try({
334 try: () => {
335 if (!file.exists) {
336 file.create({ intermediates: true, overwrite: true });
337 }
338 file.write(JSON.stringify(encoded));
339 },
340 catch: (cause) => shellPersistenceError("save-shell", cause),
341 });
342 }),
343 loadThread: (environmentId, threadId) =>
344 Effect.gen(function* () {
345 const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread");
346 if (!file.exists) {
347 return Option.none();
348 }
349 const raw = yield* Effect.tryPromise({
350 try: () => file.text(),
351 catch: (cause) => shellPersistenceError("load-thread", cause),
352 });
353 const parsed = yield* Effect.try({
354 try: () => JSON.parse(raw) as unknown,
355 catch: (cause) => shellPersistenceError("load-thread", cause),
356 });
357 const stored = yield* Effect.fromResult(
358 Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
359 ).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
360 return stored.environmentId === environmentId && stored.threadId === threadId
361 ? Option.some(stored.snapshot)
362 : Option.none();
363 }),
364 saveThread: (environmentId, snapshot) =>
365 Effect.gen(function* () {
366 const file = yield* threadSnapshotFile(environmentId, snapshot.thread.id, "save-thread");
367 const encoded = yield* Effect.fromResult(
368 Schema.encodeUnknownResult(StoredThreadSnapshot)({
369 schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
370 environmentId,
371 threadId: snapshot.thread.id,
372 snapshot,
373 }),
374 ).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
375 yield* Effect.try({
376 try: () => {
377 if (!file.exists) {
378 file.create({ intermediates: true, overwrite: true });
379 }
380 file.write(JSON.stringify(encoded));
381 },
382 catch: (cause) => shellPersistenceError("save-thread", cause),
383 });
384 }),
385 removeThread: (environmentId, threadId) =>
386 Effect.gen(function* () {
387 const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
388 if (file.exists) {
389 file.delete();
390 }
391 }).pipe(
392 Effect.mapError((cause) =>
393 cause._tag === "ConnectionPersistenceError"
394 ? cause
395 : shellPersistenceError("remove-thread", cause),
396 ),
397 ),
398 clear: (environmentId) =>
399 Effect.gen(function* () {
400 const file = yield* shellSnapshotFile(environmentId, "clear-environment");
401 if (file.exists) {
402 yield* Effect.try({
403 try: () => file.delete(),
404 catch: (cause) => shellPersistenceError("clear-environment", cause),
405 });
406 }
407 const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
408 if (legacyFile.exists) {
409 yield* Effect.try({
410 try: () => legacyFile.delete(),
411 catch: (cause) => shellPersistenceError("clear-environment", cause),
412 });
413 }
414 const threadDirectory = yield* threadSnapshotDirectory(
415 environmentId,
416 "clear-environment",
417 );
418 if (threadDirectory.exists) {
419 yield* Effect.try({
420 try: () => threadDirectory.delete(),
421 catch: (cause) => shellPersistenceError("clear-environment", cause),
422 });
423 }
424 }),
425 });
426
427 return Context.make(ConnectionTargetStore, targetStore).pipe(
428 Context.add(ConnectionRegistrationStore, registrationStore),
429 Context.add(ProfileStore.ConnectionProfileStore, profileStore),
430 Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
431 Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
432 Context.add(EnvironmentCacheStore, cacheStore),
433 );
434 }),
435);