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