Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

storage.ts

536 lines19.2 KB

1import {
2 ConnectionCatalogDocument,
3 type ConnectionCatalogDocument as ConnectionCatalogDocumentType,
4 ConnectionPersistenceError,
5 ConnectionRegistrationStore,
6 ConnectionTargetStore,
7 EMPTY_CONNECTION_CATALOG_DOCUMENT,
8 EnvironmentCacheStore,
9 registerConnectionInCatalog,
10 removeCatalogValue,
11 removeConnectionFromCatalog,
12 replaceCatalogValue,
13} from "@t3tools/client-runtime/platform";
14import { TokenStore } from "@t3tools/client-runtime/authorization";
15import {
16 ConnectionTransientError,
17 CredentialStore,
18 ProfileStore,
19} from "@t3tools/client-runtime/connection";
20import {
21 EnvironmentId,
22 OrchestrationShellSnapshot,
23 OrchestrationThread,
24 ThreadId,
25} from "@t3tools/contracts";
26import * as Context from "effect/Context";
27import * as Effect from "effect/Effect";
28import * as Layer from "effect/Layer";
29import * as Option from "effect/Option";
30import * as Ref from "effect/Ref";
31import * as Schema from "effect/Schema";
32import * as Semaphore from "effect/Semaphore";
33​
34const DATABASE_NAME = "t3code:connection-runtime";
35const DATABASE_VERSION = 2;
36const CATALOG_STORE_NAME = "catalog";
37const SHELL_STORE_NAME = "shell";
38const THREAD_STORE_NAME = "thread";
39const CATALOG_KEY = "document";
40const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
41​
42const StoredShellSnapshot = Schema.Struct({
43 schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
44 environmentId: EnvironmentId,
45 snapshot: OrchestrationShellSnapshot,
46});
47const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
48const StoredThreadSnapshot = Schema.Struct({
49 schemaVersion: Schema.Literal(1),
50 environmentId: EnvironmentId,
51 threadId: ThreadId,
52 thread: OrchestrationThread,
53});
54const StoredThreadSnapshotJson = Schema.fromJsonString(StoredThreadSnapshot);
55const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
56const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson);
57const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
58const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(StoredShellSnapshotJson);
59const encodeStoredShellSnapshot = Schema.encodeEffect(StoredShellSnapshotJson);
60const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredThreadSnapshotJson);
61const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshotJson);
62​
63function catalogError(operation: string, cause: unknown) {
64 return new ConnectionTransientError({
65 reason: "remote-unavailable",
66 detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
67 });
69​
70function persistenceError(
71 operation:
72 | "list-targets"
73 | "register-connection"
74 | "remove-connection"
75 | "load-shell"
76 | "save-shell"
77 | "load-thread"
78 | "save-thread"
79 | "remove-thread"
80 | "clear-environment",
81 cause: unknown,
82) {
83 return new ConnectionPersistenceError({
84 operation,
85 message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
86 });
88​
89const openDatabase = Effect.fn("web.connectionStorage.openDatabase")(function* () {
90 return yield* Effect.callback<IDBDatabase, ConnectionTransientError>((resume) => {
91 if (typeof indexedDB === "undefined") {
92 resume(
93 Effect.fail(catalogError("open", "IndexedDB is unavailable in this browser context.")),
94 );
95 return;
96 }
97 const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
98 request.addEventListener("upgradeneeded", () => {
99 if (!request.result.objectStoreNames.contains(CATALOG_STORE_NAME)) {
100 request.result.createObjectStore(CATALOG_STORE_NAME);
101 }
102 if (!request.result.objectStoreNames.contains(SHELL_STORE_NAME)) {
103 request.result.createObjectStore(SHELL_STORE_NAME);
104 }
105 if (!request.result.objectStoreNames.contains(THREAD_STORE_NAME)) {
106 request.result.createObjectStore(THREAD_STORE_NAME);
107 }
108 });
109 request.addEventListener("error", () => {
110 resume(Effect.fail(catalogError("open", request.error ?? "Unknown IndexedDB error")));
111 });
112 request.addEventListener("success", () => {
113 resume(Effect.succeed(request.result));
114 });
115 });
116});
117​
118function readDatabaseValue(database: IDBDatabase, storeName: string, key: IDBValidKey) {
119 return Effect.callback<unknown, ConnectionTransientError>((resume) => {
120 const request = database.transaction(storeName, "readonly").objectStore(storeName).get(key);
121 request.addEventListener("error", () => {
122 resume(Effect.fail(catalogError("read", request.error ?? "Unknown IndexedDB read error")));
123 });
124 request.addEventListener("success", () => {
125 resume(Effect.succeed(request.result));
126 });
127 }).pipe(Effect.withSpan("web.connectionStorage.readDatabaseValue"));
129​
130function writeDatabaseValue(
131 database: IDBDatabase,
132 storeName: string,
133 key: IDBValidKey,
134 value: unknown,
135) {
136 return Effect.callback<void, ConnectionTransientError>((resume) => {
137 const transaction = database.transaction(storeName, "readwrite");
138 transaction.addEventListener("error", () => {
139 resume(
140 Effect.fail(catalogError("write", transaction.error ?? "Unknown IndexedDB write error")),
141 );
142 });
143 transaction.addEventListener("complete", () => {
144 resume(Effect.void);
145 });
146 transaction.objectStore(storeName).put(value, key);
147 }).pipe(Effect.withSpan("web.connectionStorage.writeDatabaseValue"));
149​
150function removeDatabaseValue(database: IDBDatabase, storeName: string, key: IDBValidKey) {
151 return Effect.callback<void, ConnectionTransientError>((resume) => {
152 const transaction = database.transaction(storeName, "readwrite");
153 transaction.addEventListener("error", () => {
154 resume(
155 Effect.fail(catalogError("remove", transaction.error ?? "Unknown IndexedDB remove error")),
156 );
157 });
158 transaction.addEventListener("complete", () => {
159 resume(Effect.void);
160 });
161 transaction.objectStore(storeName).delete(key);
162 }).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValue"));
164​
165function removeDatabaseValuesInRange(database: IDBDatabase, storeName: string, range: IDBKeyRange) {
166 return Effect.callback<void, ConnectionTransientError>((resume) => {
167 const transaction = database.transaction(storeName, "readwrite");
168 transaction.addEventListener("error", () => {
169 resume(
170 Effect.fail(catalogError("remove", transaction.error ?? "Unknown IndexedDB cursor error")),
171 );
172 });
173 transaction.addEventListener("complete", () => {
174 resume(Effect.void);
175 });
176 const request = transaction.objectStore(storeName).openCursor(range);
177 request.addEventListener("error", () => {
178 resume(
179 Effect.fail(catalogError("remove", request.error ?? "Unknown IndexedDB cursor error")),
180 );
181 });
182 request.addEventListener("success", () => {
183 const cursor = request.result;
184 if (cursor === null) {
185 return;
186 }
187 cursor.delete();
188 cursor.continue();
189 });
190 }).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValuesInRange"));
192​
193function threadCacheKey(environmentId: EnvironmentId, threadId: ThreadId) {
194 return `${environmentId}:${threadId}`;
196​
197const decodeCatalog = Effect.fn("web.connectionStorage.decodeCatalog")(function* (raw: string) {
198 return yield* decodeConnectionCatalogDocument(raw).pipe(
199 Effect.mapError((cause) => catalogError("decode", cause)),
200 );
201});
202​
203const encodeCatalog = Effect.fn("web.connectionStorage.encodeCatalog")(function* (
204 catalog: ConnectionCatalogDocumentType,
205) {
206 return yield* encodeConnectionCatalogDocument(catalog).pipe(
207 Effect.mapError((cause) => catalogError("encode", cause)),
208 );
209});
210​
211export interface CatalogBackend {
212 readonly read: Effect.Effect<string | null, ConnectionTransientError>;
213 readonly write: (raw: string) => Effect.Effect<void, ConnectionTransientError>;
214 readonly quarantine?: (raw: string) => Effect.Effect<void, ConnectionTransientError>;
216​
217export function makeCatalogBackend(database: IDBDatabase): CatalogBackend {
218 const bridge = window.desktopBridge;
219 if (bridge?.getConnectionCatalog !== undefined && bridge.setConnectionCatalog !== undefined) {
220 return {
221 read: Effect.tryPromise({
222 try: () => bridge.getConnectionCatalog!(),
223 catch: (cause) => catalogError("load", cause),
224 }),
225 write: (raw) =>
226 Effect.tryPromise({
227 try: () => bridge.setConnectionCatalog!(raw),
228 catch: (cause) => catalogError("save", cause),
229 }).pipe(
230 Effect.flatMap((stored) =>
231 stored
232 ? Effect.void
233 : Effect.fail(
234 catalogError(
235 "save",
236 "Desktop secure storage is unavailable in this system context.",
237 ),
238 ),
239 ),
240 ),
241 };
242 }
243​
244 return {
245 read: readDatabaseValue(database, CATALOG_STORE_NAME, CATALOG_KEY).pipe(
246 Effect.map((value) => (typeof value === "string" ? value : null)),
247 ),
248 write: (raw) => writeDatabaseValue(database, CATALOG_STORE_NAME, CATALOG_KEY, raw),
249 quarantine: (raw) =>
250 writeDatabaseValue(database, CATALOG_STORE_NAME, `${CATALOG_KEY}:corrupt:${Date.now()}`, raw),
251 };
253​
254interface CatalogStore {
255 readonly read: Effect.Effect<ConnectionCatalogDocumentType, ConnectionTransientError>;
256 readonly update: (
257 transform: (catalog: ConnectionCatalogDocumentType) => ConnectionCatalogDocumentType,
258 ) => Effect.Effect<void, ConnectionTransientError>;
260​
261export const makeCatalogStore = Effect.fn("web.connectionStorage.makeCatalogStore")(function* (
262 backend: CatalogBackend,
263) {
264 const state = yield* Ref.make<Option.Option<ConnectionCatalogDocumentType>>(Option.none());
265 const lock = yield* Semaphore.make(1);
266​
267 const loadUnlocked = Effect.fn("web.connectionStorage.loadCatalog")(function* () {
268 const cached = yield* Ref.get(state);
269 if (Option.isSome(cached)) {
270 return cached.value;
271 }
272 const raw = yield* backend.read;
273 let catalog = EMPTY_CONNECTION_CATALOG_DOCUMENT;
274 if (raw !== null && raw.trim() !== "") {
275 catalog = yield* decodeCatalog(raw).pipe(
276 Effect.catch((error) =>
277 Effect.gen(function* () {
278 yield* Effect.logWarning("Discarding a corrupt web connection catalog.", {
279 error: error.message,
280 });
281 if (backend.quarantine !== undefined) {
282 yield* backend.quarantine(raw).pipe(
283 Effect.catch((cause) =>
284 Effect.logWarning("Could not quarantine the corrupt web connection catalog.", {
285 error: cause.message,
286 }),
287 ),
288 );
289 }
290 const encoded = yield* encodeCatalog(EMPTY_CONNECTION_CATALOG_DOCUMENT);
291 yield* backend.write(encoded).pipe(
292 Effect.catch((cause) =>
293 Effect.logWarning("Could not persist the recovered web connection catalog.", {
294 error: cause.message,
295 }),
296 ),
297 );
298 return EMPTY_CONNECTION_CATALOG_DOCUMENT;
299 }),
300 ),
301 );
302 }
303 yield* Ref.set(state, Option.some(catalog));
304 return catalog;
305 });
306​
307 const read = lock.withPermits(1)(loadUnlocked());
308 const update: CatalogStore["update"] = Effect.fn("web.connectionStorage.updateCatalog")(
309 function* (transform) {
310 yield* lock.withPermits(1)(
311 Effect.gen(function* () {
312 const next = transform(yield* loadUnlocked());
313 yield* backend.write(yield* encodeCatalog(next));
314 yield* Ref.set(state, Option.some(next));
315 }),
316 );
317 },
318 );
319​
320 return { read, update } satisfies CatalogStore;
321});
322​
323export const connectionStorageLayer = Layer.effectContext(
324 Effect.gen(function* () {
325 const database = yield* Effect.acquireRelease(openDatabase(), (database) =>
326 Effect.sync(() => database.close()),
327 );
328 const catalog = yield* makeCatalogStore(makeCatalogBackend(database));
329​
330 const targetStore = ConnectionTargetStore.of({
331 list: catalog.read.pipe(
332 Effect.map((document) => document.targets),
333 Effect.mapError((cause) => persistenceError("list-targets", cause)),
334 ),
335 });
336 const registrationStore = ConnectionRegistrationStore.of({
337 register: (registration) =>
338 catalog
339 .update((document) => registerConnectionInCatalog(document, registration))
340 .pipe(Effect.mapError((cause) => persistenceError("register-connection", cause))),
341 remove: (target) =>
342 catalog
343 .update((document) => removeConnectionFromCatalog(document, target))
344 .pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause))),
345 });
346 const profileStore = ProfileStore.make({
347 get: (connectionId) =>
348 catalog.read.pipe(
349 Effect.map((document) =>
350 Option.fromUndefinedOr(
351 document.profiles.find((profile) => profile.connectionId === connectionId),
352 ),
353 ),
354 ),
355 put: (profile) =>
356 catalog.update((document) => ({
357 ...document,
358 profiles: replaceCatalogValue(document.profiles, (value) => value.connectionId, profile),
359 })),
360 remove: (connectionId) =>
361 catalog.update((document) => ({
362 ...document,
363 profiles: removeCatalogValue(
364 document.profiles,
365 (value) => value.connectionId,
366 connectionId,
367 ),
368 })),
369 });
370 const credentialStore = CredentialStore.make({
371 get: (connectionId) =>
372 catalog.read.pipe(
373 Effect.map((document) =>
374 Option.fromUndefinedOr(
375 document.credentials.find((entry) => entry.connectionId === connectionId)?.credential,
376 ),
377 ),
378 ),
379 put: (connectionId, credential) =>
380 catalog.update((document) => ({
381 ...document,
382 credentials: replaceCatalogValue(document.credentials, (value) => value.connectionId, {
383 connectionId,
384 credential,
385 }),
386 })),
387 remove: (connectionId) =>
388 catalog.update((document) => ({
389 ...document,
390 credentials: removeCatalogValue(
391 document.credentials,
392 (value) => value.connectionId,
393 connectionId,
394 ),
395 })),
396 });
397 const remoteTokenStore = TokenStore.make({
398 get: (environmentId) =>
399 catalog.read.pipe(
400 Effect.map((document) =>
401 Option.fromUndefinedOr(
402 document.remoteDpopTokens.find((token) => token.environmentId === environmentId),
403 ),
404 ),
405 ),
406 put: (token) =>
407 catalog.update((document) => ({
408 ...document,
409 remoteDpopTokens: replaceCatalogValue(
410 document.remoteDpopTokens,
411 (value) => value.environmentId,
412 token,
413 ),
414 })),
415 remove: (environmentId) =>
416 catalog.update((document) => ({
417 ...document,
418 remoteDpopTokens: removeCatalogValue(
419 document.remoteDpopTokens,
420 (value) => value.environmentId,
421 environmentId,
422 ),
423 })),
424 });
425 const cacheStore = EnvironmentCacheStore.of({
426 loadShell: (environmentId) =>
427 readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
428 Effect.flatMap((raw) => {
429 if (typeof raw !== "string") {
430 return Effect.succeed(Option.none());
431 }
432 return decodeStoredShellSnapshot(raw).pipe(
433 Effect.mapError((cause) => persistenceError("load-shell", cause)),
434 Effect.map((stored) =>
435 stored.environmentId === environmentId
436 ? Option.some(stored.snapshot)
437 : Option.none(),
438 ),
439 );
440 }),
441 Effect.mapError((cause) =>
442 cause._tag === "ConnectionPersistenceError"
443 ? cause
444 : persistenceError("load-shell", cause),
445 ),
446 ),
447 saveShell: (environmentId, snapshot) =>
448 Effect.gen(function* () {
449 const encoded = yield* encodeStoredShellSnapshot({
450 schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
451 environmentId,
452 snapshot,
453 }).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
454 yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
455 }).pipe(
456 Effect.mapError((cause) =>
457 cause._tag === "ConnectionPersistenceError"
458 ? cause
459 : persistenceError("save-shell", cause),
460 ),
461 ),
462 loadThread: (environmentId, threadId) =>
463 readDatabaseValue(
464 database,
465 THREAD_STORE_NAME,
466 threadCacheKey(environmentId, threadId),
467 ).pipe(
468 Effect.flatMap((raw) => {
469 if (typeof raw !== "string") {
470 return Effect.succeed(Option.none());
471 }
472 return decodeStoredThreadSnapshot(raw).pipe(
473 Effect.mapError((cause) => persistenceError("load-thread", cause)),
474 Effect.map((stored) =>
475 stored.environmentId === environmentId && stored.threadId === threadId
476 ? Option.some(stored.thread)
477 : Option.none(),
478 ),
479 );
480 }),
481 Effect.mapError((cause) =>
482 cause._tag === "ConnectionPersistenceError"
483 ? cause
484 : persistenceError("load-thread", cause),
485 ),
486 ),
487 saveThread: (environmentId, thread) =>
488 Effect.gen(function* () {
489 const encoded = yield* encodeStoredThreadSnapshot({
490 schemaVersion: 1,
491 environmentId,
492 threadId: thread.id,
493 thread,
494 }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
495 yield* writeDatabaseValue(
496 database,
497 THREAD_STORE_NAME,
498 threadCacheKey(environmentId, thread.id),
499 encoded,
500 );
501 }).pipe(
502 Effect.mapError((cause) =>
503 cause._tag === "ConnectionPersistenceError"
504 ? cause
505 : persistenceError("save-thread", cause),
506 ),
507 ),
508 removeThread: (environmentId, threadId) =>
509 removeDatabaseValue(
510 database,
511 THREAD_STORE_NAME,
512 threadCacheKey(environmentId, threadId),
513 ).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause))),
514 clear: (environmentId) =>
515 Effect.all(
516 [
517 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
518 removeDatabaseValuesInRange(
519 database,
520 THREAD_STORE_NAME,
521 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
522 ),
523 ],
524 { concurrency: "unbounded", discard: true },
525 ).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause))),
526 });
527​
528 return Context.make(ConnectionTargetStore, targetStore).pipe(
529 Context.add(ConnectionRegistrationStore, registrationStore),
530 Context.add(ProfileStore.ConnectionProfileStore, profileStore),
531 Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
532 Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
533 Context.add(EnvironmentCacheStore, cacheStore),
534 );
535 }),
536);