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