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

storage.ts

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