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

storage.ts

941 lines34.3 KB

1import {
2 ConnectionCatalogDocument,
3 type ConnectionCatalogDocument as ConnectionCatalogDocumentType,
4 EMPTY_CONNECTION_CATALOG_DOCUMENT,
5 ORCHESTRATION_CACHE_SCHEMA_VERSION,
6 ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION,
7 StoredOrchestrationShellSnapshot,
8 StoredOrchestrationThreadSnapshot,
9 decodeOrDiscardOrchestrationCache,
10 putRemoteDpopTokenInCatalog,
11 registerConnectionInCatalog,
12 removeCatalogValue,
13 removeConnectionFromCatalog,
14 setConnectionEnabledInCatalog,
15 setRoutesInCatalog,
16 replaceCatalogValue,
17 Persistence,
18 makeStoredShellSnapshotEncoder,
19} from "@t3tools/client-runtime/platform";
20import { TokenStore } from "@t3tools/client-runtime/authorization";
21import {
22 ConnectionTransientError,
23 ConnectionBlockedError,
24 CredentialStore,
25 ProfileStore,
26 GitHubRoutingPermissions,
27 StoredGitHubRoutingPermission,
28 gitHubRoutingConnectionKey,
29 gitHubRoutingPermissionFor,
30} from "@t3tools/client-runtime/connection";
31import { EnvironmentId, ServerConfig, ThreadId, VcsListRefsResult } from "@t3tools/contracts";
32import * as Context from "effect/Context";
33import * as Effect from "effect/Effect";
34import * as Layer from "effect/Layer";
35import * as Option from "effect/Option";
36import * as Ref from "effect/Ref";
37import * as Queue from "effect/Queue";
38import * as Schema from "effect/Schema";
39import * as Semaphore from "effect/Semaphore";
40import * as Stream from "effect/Stream";
41import { projectFaviconCache } from "../assets/projectFaviconCache";
42​
43const DATABASE_NAME = "t3code:connection-runtime";
44const DATABASE_VERSION = 4;
45const CATALOG_STORE_NAME = "catalog";
46const SHELL_STORE_NAME = "shell";
47const THREAD_STORE_NAME = "thread";
48const SERVER_CONFIG_STORE_NAME = "server-config";
49const VCS_REFS_STORE_NAME = "vcs-refs";
50const CATALOG_KEY = "document";
51const StoredShellSnapshot = StoredOrchestrationShellSnapshot;
52const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
53const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot;
54const StoredThreadSnapshotJson = Schema.fromJsonString(StoredThreadSnapshot);
55const StoredServerConfig = Schema.Struct({
56 schemaVersion: Schema.Literal(1),
57 environmentId: EnvironmentId,
58 config: ServerConfig,
59});
60const StoredServerConfigJson = Schema.fromJsonString(StoredServerConfig);
61const StoredVcsRefs = Schema.Struct({
62 schemaVersion: Schema.Literal(1),
63 environmentId: EnvironmentId,
64 cwd: Schema.String,
65 refs: VcsListRefsResult,
66});
67const StoredVcsRefsJson = Schema.fromJsonString(StoredVcsRefs);
68const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
69const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson);
70const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
71const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(StoredShellSnapshotJson);
72const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredThreadSnapshotJson);
73const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshotJson);
74const decodeStoredServerConfig = Schema.decodeUnknownEffect(StoredServerConfigJson);
75const encodeStoredServerConfig = Schema.encodeEffect(StoredServerConfigJson);
76const decodeStoredVcsRefs = Schema.decodeUnknownEffect(StoredVcsRefsJson);
77const encodeStoredVcsRefs = Schema.encodeEffect(StoredVcsRefsJson);
78​
79function catalogError(operation: string, cause: unknown) {
80 return new ConnectionTransientError({
81 reason: "remote-unavailable",
82 detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
83 });
85​
86function persistenceError(
87 operation:
88 | "list-targets"
89 | "list-disabled-targets"
90 | "register-connection"
91 | "set-connection-routes"
92 | "remove-connection"
93 | "set-connection-enabled"
94 | "load-shell"
95 | "save-shell"
96 | "load-thread"
97 | "save-thread"
98 | "remove-thread"
99 | "load-server-config"
100 | "save-server-config"
101 | "load-vcs-refs"
102 | "save-vcs-refs"
103 | "remove-vcs-refs"
104 | "clear-vcs-refs"
105 | "clear-environment",
106 cause: unknown,
107) {
108 return new Persistence.ConnectionPersistenceError({
109 operation,
110 message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
111 });
113​
114const openDatabase = Effect.fn("web.connectionStorage.openDatabase")(function* () {
115 return yield* Effect.callback<IDBDatabase, ConnectionTransientError>((resume) => {
116 if (typeof indexedDB === "undefined") {
117 resume(
118 Effect.fail(catalogError("open", "IndexedDB is unavailable in this browser context.")),
119 );
120 return;
121 }
122 try {
123 const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
124 request.addEventListener("upgradeneeded", () => {
125 if (!request.result.objectStoreNames.contains(CATALOG_STORE_NAME)) {
126 request.result.createObjectStore(CATALOG_STORE_NAME);
127 }
128 if (!request.result.objectStoreNames.contains(SHELL_STORE_NAME)) {
129 request.result.createObjectStore(SHELL_STORE_NAME);
130 }
131 if (!request.result.objectStoreNames.contains(THREAD_STORE_NAME)) {
132 request.result.createObjectStore(THREAD_STORE_NAME);
133 }
134 if (!request.result.objectStoreNames.contains(SERVER_CONFIG_STORE_NAME)) {
135 request.result.createObjectStore(SERVER_CONFIG_STORE_NAME);
136 }
137 if (!request.result.objectStoreNames.contains(VCS_REFS_STORE_NAME)) {
138 request.result.createObjectStore(VCS_REFS_STORE_NAME);
139 }
140 });
141 request.addEventListener("error", () => {
142 resume(Effect.fail(catalogError("open", request.error ?? "Unknown IndexedDB error")));
143 });
144 request.addEventListener("success", () => {
145 resume(Effect.succeed(request.result));
146 });
147 } catch (cause) {
148 resume(Effect.fail(catalogError("open", cause)));
149 }
150 });
151});
152​
153interface DatabaseHandle {
154 readonly get: Effect.Effect<IDBDatabase, ConnectionTransientError>;
155 readonly invalidate: (database: IDBDatabase) => Effect.Effect<void>;
157​
158const makeDatabaseHandle = Effect.fn("web.connectionStorage.makeDatabaseHandle")(function* () {
159 const lock = yield* Semaphore.make(1);
160 let current: IDBDatabase | null = null;
161 const forget = (database: IDBDatabase) => {
162 if (current === database) current = null;
163 };
164 const get = Effect.suspend(() =>
165 current !== null
166 ? Effect.succeed(current)
167 : lock.withPermits(1)(
168 Effect.gen(function* () {
169 if (current !== null) return current;
170 const opened = yield* openDatabase();
171 current = opened;
172 opened.addEventListener("close", () => forget(opened));
173 // Another tab upgrading the schema waits on this connection.
174 opened.addEventListener("versionchange", () => {
175 forget(opened);
176 opened.close();
177 });
178 return opened;
179 }),
180 ),
181 );
182 const close = lock.withPermits(1)(
183 Effect.sync(() => {
184 current?.close();
185 current = null;
186 }),
187 );
188 const handle: DatabaseHandle = {
189 get,
190 invalidate: (database) => Effect.sync(() => forget(database)),
191 };
192 return { handle, close };
193});
194​
195/**
196 * A connection the browser already closed throws InvalidStateError even when no
197 * close event reached this tab, so drop it and retry once on a fresh one
198 * instead of failing every later operation.
199 */
200function withDatabase<A>(
201 database: DatabaseHandle,
202 use: (opened: IDBDatabase) => Effect.Effect<A, ConnectionTransientError>,
203) {
204 const closedConnection = Symbol("closedConnection");
205 const attempt = Effect.flatMap(database.get, (opened) =>
206 use(opened).pipe(
207 Effect.catchIf(
208 (error) => error.detail.includes("InvalidStateError"),
209 (error) =>
210 database
211 .invalidate(opened)
212 .pipe(Effect.andThen(Effect.fail({ [closedConnection]: error } as const))),
213 ),
214 ),
215 );
216 return attempt.pipe(
217 Effect.catchIf(
218 (error): error is { readonly [closedConnection]: ConnectionTransientError } =>
219 closedConnection in error,
220 () => Effect.flatMap(database.get, use),
221 ),
222 );
224​
225function readDatabaseValueOnConnection(database: IDBDatabase, storeName: string, key: IDBValidKey) {
226 return Effect.callback<unknown, ConnectionTransientError>((resume) => {
227 try {
228 const request = database.transaction(storeName, "readonly").objectStore(storeName).get(key);
229 request.addEventListener("error", () => {
230 resume(Effect.fail(catalogError("read", request.error ?? "Unknown IndexedDB read error")));
231 });
232 request.addEventListener("success", () => {
233 resume(Effect.succeed(request.result));
234 });
235 } catch (cause) {
236 resume(Effect.fail(catalogError("read", cause)));
237 }
238 }).pipe(Effect.withSpan("web.connectionStorage.readDatabaseValue"));
240​
241function writeDatabaseValueOnConnection(
242 database: IDBDatabase,
243 storeName: string,
244 key: IDBValidKey,
245 value: unknown,
246) {
247 return Effect.callback<void, ConnectionTransientError>((resume) => {
248 try {
249 const transaction = database.transaction(storeName, "readwrite");
250 // Every failed write fires "abort". A failed commit, such as
251 // QuotaExceededError, fires only "abort" and no "error".
252 transaction.addEventListener("abort", () => {
253 resume(
254 Effect.fail(catalogError("write", transaction.error ?? "Unknown IndexedDB write error")),
255 );
256 });
257 transaction.addEventListener("complete", () => {
258 resume(Effect.void);
259 });
260 transaction.objectStore(storeName).put(value, key);
261 } catch (cause) {
262 resume(Effect.fail(catalogError("write", cause)));
263 }
264 }).pipe(Effect.withSpan("web.connectionStorage.writeDatabaseValue"));
266​
267function removeDatabaseValueOnConnection(
268 database: IDBDatabase,
269 storeName: string,
270 key: IDBValidKey,
271) {
272 return Effect.callback<void, ConnectionTransientError>((resume) => {
273 try {
274 const transaction = database.transaction(storeName, "readwrite");
275 transaction.addEventListener("abort", () => {
276 resume(
277 Effect.fail(
278 catalogError("remove", transaction.error ?? "Unknown IndexedDB remove error"),
279 ),
280 );
281 });
282 transaction.addEventListener("complete", () => {
283 resume(Effect.void);
284 });
285 transaction.objectStore(storeName).delete(key);
286 } catch (cause) {
287 resume(Effect.fail(catalogError("remove", cause)));
288 }
289 }).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValue"));
291​
292function removeDatabaseValuesInRangeOnConnection(
293 database: IDBDatabase,
294 storeName: string,
295 range: IDBKeyRange,
296) {
297 return Effect.callback<void, ConnectionTransientError>((resume) => {
298 try {
299 const transaction = database.transaction(storeName, "readwrite");
300 transaction.addEventListener("abort", () => {
301 resume(
302 Effect.fail(
303 catalogError("remove", transaction.error ?? "Unknown IndexedDB cursor error"),
304 ),
305 );
306 });
307 transaction.addEventListener("complete", () => {
308 resume(Effect.void);
309 });
310 const request = transaction.objectStore(storeName).openCursor(range);
311 request.addEventListener("error", () => {
312 resume(
313 Effect.fail(catalogError("remove", request.error ?? "Unknown IndexedDB cursor error")),
314 );
315 });
316 request.addEventListener("success", () => {
317 const cursor = request.result;
318 if (cursor === null) {
319 return;
320 }
321 try {
322 cursor.delete();
323 cursor.continue();
324 } catch (cause) {
325 resume(Effect.fail(catalogError("remove", cause)));
326 }
327 });
328 } catch (cause) {
329 resume(Effect.fail(catalogError("remove", cause)));
330 }
331 }).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValuesInRange"));
333​
334function readDatabaseValue(database: DatabaseHandle, storeName: string, key: IDBValidKey) {
335 return withDatabase(database, (opened) => readDatabaseValueOnConnection(opened, storeName, key));
337​
338function writeDatabaseValue(
339 database: DatabaseHandle,
340 storeName: string,
341 key: IDBValidKey,
342 value: unknown,
343) {
344 return withDatabase(database, (opened) =>
345 writeDatabaseValueOnConnection(opened, storeName, key, value),
346 );
348​
349function removeDatabaseValue(database: DatabaseHandle, storeName: string, key: IDBValidKey) {
350 return withDatabase(database, (opened) =>
351 removeDatabaseValueOnConnection(opened, storeName, key),
352 );
354​
355function removeDatabaseValuesInRange(
356 database: DatabaseHandle,
357 storeName: string,
358 range: IDBKeyRange,
359) {
360 return withDatabase(database, (opened) =>
361 removeDatabaseValuesInRangeOnConnection(opened, storeName, range),
362 );
364​
365function threadCacheKey(environmentId: EnvironmentId, threadId: ThreadId) {
366 return `${environmentId}:${threadId}`;
368​
369function vcsRefsCacheKey(environmentId: EnvironmentId, cwd: string) {
370 return `${environmentId}:${cwd}`;
372​
373const decodeCatalog = Effect.fn("web.connectionStorage.decodeCatalog")(function* (raw: string) {
374 return yield* decodeConnectionCatalogDocument(raw).pipe(
375 Effect.mapError((cause) => catalogError("decode", cause)),
376 );
377});
378​
379const encodeCatalog = Effect.fn("web.connectionStorage.encodeCatalog")(function* (
380 catalog: ConnectionCatalogDocumentType,
381) {
382 return yield* encodeConnectionCatalogDocument(catalog).pipe(
383 Effect.mapError((cause) => catalogError("encode", cause)),
384 );
385});
386​
387export interface CatalogBackend {
388 readonly read: Effect.Effect<string | null, ConnectionTransientError>;
389 readonly write: (raw: string) => Effect.Effect<void, ConnectionTransientError>;
390 readonly quarantine?: (raw: string) => Effect.Effect<void, ConnectionTransientError>;
392​
393export function makeCatalogBackend(database: DatabaseHandle): CatalogBackend {
394 const bridge = window.desktopBridge;
395 if (bridge?.getConnectionCatalog !== undefined && bridge.setConnectionCatalog !== undefined) {
396 return {
397 read: Effect.tryPromise({
398 try: () => bridge.getConnectionCatalog!(),
399 catch: (cause) => catalogError("load", cause),
400 }),
401 write: (raw) =>
402 Effect.tryPromise({
403 try: () => bridge.setConnectionCatalog!(raw),
404 catch: (cause) => catalogError("save", cause),
405 }).pipe(
406 Effect.flatMap((stored) =>
407 stored
408 ? Effect.void
409 : Effect.fail(
410 catalogError(
411 "save",
412 "Desktop secure storage is unavailable in this system context.",
413 ),
414 ),
415 ),
416 ),
417 };
418 }
419​
420 return {
421 read: readDatabaseValue(database, CATALOG_STORE_NAME, CATALOG_KEY).pipe(
422 Effect.map((value) => (typeof value === "string" ? value : null)),
423 ),
424 write: (raw) => writeDatabaseValue(database, CATALOG_STORE_NAME, CATALOG_KEY, raw),
425 quarantine: (raw) =>
426 writeDatabaseValue(database, CATALOG_STORE_NAME, `${CATALOG_KEY}:corrupt:${Date.now()}`, raw),
427 };
429​
430interface CatalogStore {
431 readonly read: Effect.Effect<ConnectionCatalogDocumentType, ConnectionTransientError>;
432 readonly update: (
433 transform: (catalog: ConnectionCatalogDocumentType) => ConnectionCatalogDocumentType,
434 ) => Effect.Effect<void, ConnectionTransientError>;
436​
437export const makeCatalogStore = Effect.fn("web.connectionStorage.makeCatalogStore")(function* (
438 backend: CatalogBackend,
439) {
440 const state = yield* Ref.make<Option.Option<ConnectionCatalogDocumentType>>(Option.none());
441 const lock = yield* Semaphore.make(1);
442​
443 const loadUnlocked = Effect.fn("web.connectionStorage.loadCatalog")(function* () {
444 const cached = yield* Ref.get(state);
445 if (Option.isSome(cached)) {
446 return cached.value;
447 }
448 const raw = yield* backend.read;
449 let catalog = EMPTY_CONNECTION_CATALOG_DOCUMENT;
450 if (raw !== null && raw.trim() !== "") {
451 catalog = yield* decodeCatalog(raw).pipe(
452 Effect.catch((error) =>
453 Effect.gen(function* () {
454 yield* Effect.logWarning("Discarding a corrupt web connection catalog.", {
455 error: error.message,
456 });
457 if (backend.quarantine !== undefined) {
458 yield* backend.quarantine(raw).pipe(
459 Effect.catch((cause) =>
460 Effect.logWarning("Could not quarantine the corrupt web connection catalog.", {
461 error: cause.message,
462 }),
463 ),
464 );
465 }
466 const encoded = yield* encodeCatalog(EMPTY_CONNECTION_CATALOG_DOCUMENT);
467 yield* backend.write(encoded).pipe(
468 Effect.catch((cause) =>
469 Effect.logWarning("Could not persist the recovered web connection catalog.", {
470 error: cause.message,
471 }),
472 ),
473 );
474 return EMPTY_CONNECTION_CATALOG_DOCUMENT;
475 }),
476 ),
477 );
478 }
479 yield* Ref.set(state, Option.some(catalog));
480 return catalog;
481 });
482​
483 const read = lock.withPermits(1)(loadUnlocked());
484 const update: CatalogStore["update"] = Effect.fn("web.connectionStorage.updateCatalog")(
485 function* (transform) {
486 yield* lock.withPermits(1)(
487 Effect.gen(function* () {
488 const next = transform(yield* loadUnlocked());
489 yield* backend.write(yield* encodeCatalog(next));
490 yield* Ref.set(state, Option.some(next));
491 }),
492 );
493 },
494 );
495​
496 return { read, update } satisfies CatalogStore;
497});
498​
499const GITHUB_ROUTING_KEY_PREFIX = "t3code:github-routing:";
500const GITHUB_ROUTING_CHANGED = "t3code:github-routing-changed";
501const isStoredGitHubRoutingPermission = Schema.is(StoredGitHubRoutingPermission);
502const encodeStoredGitHubRoutingPermission = Schema.encodeSync(
503 Schema.fromJsonString(StoredGitHubRoutingPermission),
504);
505​
506/** Each grant has its own key so stale tabs and unrelated catalog saves cannot restore trust. */
507export function makeBrowserGitHubRoutingPermissions(
508 browser: Pick<Window, "localStorage"> & EventTarget = window,
509) {
510 const read = (key: string): StoredGitHubRoutingPermission | null => {
511 try {
512 const raw = browser.localStorage.getItem(key);
513 const value: unknown = raw === null ? null : JSON.parse(raw);
514 return isStoredGitHubRoutingPermission(value) &&
515 key === `${GITHUB_ROUTING_KEY_PREFIX}${value.environmentId}`
516 ? value
517 : null;
518 } catch {
519 return null;
520 }
521 };
522 const readAll = (): ReadonlyArray<StoredGitHubRoutingPermission> => {
523 try {
524 const values: StoredGitHubRoutingPermission[] = [];
525 const storage = browser.localStorage;
526 for (let index = 0; index < storage.length; index++) {
527 const key = storage.key(index);
528 if (key?.startsWith(GITHUB_ROUTING_KEY_PREFIX)) {
529 const value = read(key);
530 if (value !== null) values.push(value);
531 }
532 }
533 return values;
534 } catch {
535 return [];
536 }
537 };
538 const write = (environmentId: EnvironmentId, value: StoredGitHubRoutingPermission | null) =>
539 Effect.try({
540 try: () => {
541 const key = `${GITHUB_ROUTING_KEY_PREFIX}${environmentId}`;
542 if (value === null) browser.localStorage.removeItem(key);
543 else browser.localStorage.setItem(key, encodeStoredGitHubRoutingPermission(value));
544 browser.dispatchEvent(new Event(GITHUB_ROUTING_CHANGED));
545 },
546 catch: (cause) => catalogError("save GitHub routing permissions in", cause),
547 });
548 return GitHubRoutingPermissions.of({
549 get: (entry) =>
550 Effect.sync(() => {
551 const value = read(`${GITHUB_ROUTING_KEY_PREFIX}${entry.target.environmentId}`);
552 return gitHubRoutingPermissionFor(entry, value === null ? [] : [value]);
553 }),
554 changes: Stream.callback<ReadonlyArray<StoredGitHubRoutingPermission>>((queue) =>
555 Effect.acquireRelease(
556 Effect.sync(() => {
557 const listener = (event: Event) => {
558 if (event.type === "storage") {
559 const key = (event as StorageEvent).key;
560 if (key !== null && !key?.startsWith(GITHUB_ROUTING_KEY_PREFIX)) return;
561 }
562 Queue.offerUnsafe(queue, readAll());
563 };
564 browser.addEventListener("storage", listener);
565 browser.addEventListener(GITHUB_ROUTING_CHANGED, listener);
566 Queue.offerUnsafe(queue, readAll());
567 return listener;
568 }),
569 (listener) =>
570 Effect.sync(() => {
571 browser.removeEventListener("storage", listener);
572 browser.removeEventListener(GITHUB_ROUTING_CHANGED, listener);
573 }),
574 ).pipe(Effect.asVoid),
575 ),
576 set: (entry, permission) => {
577 const connectionKey = gitHubRoutingConnectionKey(entry);
578 if (connectionKey === null)
579 return Effect.fail(
580 new ConnectionBlockedError({
581 reason: "configuration",
582 detail: "This environment does not have a saved connection endpoint.",
583 }),
584 );
585 return write(
586 entry.target.environmentId,
587 permission === "off"
588 ? null
589 : {
590 environmentId: entry.target.environmentId,
591 connectionKey,
592 permission,
593 },
594 );
595 },
596 forget: (environmentId) => write(environmentId, null),
597 });
599​
600// A posted message resumes in a fresh task, so input and rendering get a turn between
601// encoding chunks. A zero-delay timer would not do: browsers clamp nested timers to
602// 4 ms and throttle them to once a second or less in a background tab.
603const yieldToBrowserTask = Effect.callback<void>((resume) => {
604 const { port1, port2 } = new MessageChannel();
605 port1.addEventListener(
606 "message",
607 () => {
608 port1.close();
609 resume(Effect.void);
610 },
611 { once: true },
612 );
613 port1.start();
614 port2.postMessage(null);
615 // A closed port delivers nothing, so interruption needs no listener bookkeeping.
616 return Effect.sync(() => port1.close());
617});
618​
619export const layer = Layer.effectContext(
620 Effect.gen(function* () {
621 const { handle: database } = yield* Effect.acquireRelease(
622 makeDatabaseHandle(),
623 (owned) => owned.close,
624 );
625 const catalog = yield* makeCatalogStore(makeCatalogBackend(database));
626 const githubRoutingPermissions = makeBrowserGitHubRoutingPermissions();
627 // Remembers each thread row's encoding, so a save only encodes rows that changed.
628 const encodeStoredShellSnapshot = makeStoredShellSnapshotEncoder({
629 yieldToHost: yieldToBrowserTask,
630 });
631​
632 const targetStore = Persistence.ConnectionTargetStore.of({
633 list: catalog.read.pipe(
634 Effect.map((document) => document.targets),
635 Effect.mapError((cause) => persistenceError("list-targets", cause)),
636 ),
637 listDisabled: catalog.read.pipe(
638 Effect.map((document) => document.disabledEnvironmentIds),
639 Effect.mapError((cause) => persistenceError("list-disabled-targets", cause)),
640 ),
641 });
642 const registrationStore = Persistence.ConnectionRegistrationStore.of({
643 register: (registration, routes) =>
644 catalog
645 .update((document) => registerConnectionInCatalog(document, registration, routes))
646 .pipe(Effect.mapError((cause) => persistenceError("register-connection", cause))),
647 setRoutes: (environmentId, routes) =>
648 catalog
649 .update((document) => setRoutesInCatalog(document, environmentId, routes))
650 .pipe(Effect.mapError((cause) => persistenceError("set-connection-routes", cause))),
651 remove: (environmentId) =>
652 catalog
653 .update((document) => removeConnectionFromCatalog(document, environmentId))
654 .pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause))),
655 setEnabled: (environmentId, enabled) =>
656 catalog
657 .update((document) => setConnectionEnabledInCatalog(document, environmentId, enabled))
658 .pipe(Effect.mapError((cause) => persistenceError("set-connection-enabled", cause))),
659 });
660 const profileStore = ProfileStore.make({
661 get: (connectionId) =>
662 catalog.read.pipe(
663 Effect.map((document) =>
664 Option.fromUndefinedOr(
665 document.profiles.find((profile) => profile.connectionId === connectionId),
666 ),
667 ),
668 ),
669 put: (profile) =>
670 catalog.update((document) => ({
671 ...document,
672 profiles: replaceCatalogValue(document.profiles, (value) => value.connectionId, profile),
673 })),
674 remove: (connectionId) =>
675 catalog.update((document) => ({
676 ...document,
677 profiles: removeCatalogValue(
678 document.profiles,
679 (value) => value.connectionId,
680 connectionId,
681 ),
682 })),
683 });
684 const credentialStore = CredentialStore.make({
685 get: (connectionId) =>
686 catalog.read.pipe(
687 Effect.map((document) =>
688 Option.fromUndefinedOr(
689 document.credentials.find((entry) => entry.connectionId === connectionId)?.credential,
690 ),
691 ),
692 ),
693 put: (connectionId, credential) =>
694 catalog.update((document) => ({
695 ...document,
696 credentials: replaceCatalogValue(document.credentials, (value) => value.connectionId, {
697 connectionId,
698 credential,
699 }),
700 })),
701 remove: (connectionId) =>
702 catalog.update((document) => ({
703 ...document,
704 credentials: removeCatalogValue(
705 document.credentials,
706 (value) => value.connectionId,
707 connectionId,
708 ),
709 })),
710 });
711 const remoteTokenStore = TokenStore.make({
712 get: (environmentId) =>
713 catalog.read.pipe(
714 Effect.map((document) =>
715 Option.fromUndefinedOr(
716 document.remoteDpopTokens.find((token) => token.environmentId === environmentId),
717 ),
718 ),
719 ),
720 put: (token) => catalog.update((document) => putRemoteDpopTokenInCatalog(document, token)),
721 remove: (environmentId) =>
722 catalog.update((document) => ({
723 ...document,
724 remoteDpopTokens: removeCatalogValue(
725 document.remoteDpopTokens,
726 (value) => value.environmentId,
727 environmentId,
728 ),
729 })),
730 });
731 const cacheStore = Persistence.EnvironmentCacheStore.of({
732 loadShell: (environmentId) =>
733 readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
734 Effect.tap(() => Effect.promise(() => projectFaviconCache.hydrate())),
735 Effect.flatMap((raw) => {
736 if (typeof raw !== "string") {
737 return Effect.succeedNone;
738 }
739 return decodeOrDiscardOrchestrationCache(
740 decodeStoredShellSnapshot(raw).pipe(
741 Effect.mapError((cause) => persistenceError("load-shell", cause)),
742 Effect.map((stored) =>
743 stored.environmentId === environmentId
744 ? Option.some(stored.snapshot)
745 : Option.none(),
746 ),
747 ),
748 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
749 );
750 }),
751 Effect.mapError((cause) => persistenceError("load-shell", cause)),
752 ),
753 saveShell: (environmentId, snapshot) =>
754 Effect.gen(function* () {
755 const encoded = yield* encodeStoredShellSnapshot({
756 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
757 environmentId,
758 snapshot,
759 }).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
760 yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
761 }).pipe(
762 Effect.mapError((cause) =>
763 cause._tag === "ConnectionPersistenceError"
764 ? cause
765 : persistenceError("save-shell", cause),
766 ),
767 ),
768 loadServerConfig: (environmentId) =>
769 readDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId).pipe(
770 Effect.flatMap((raw) => {
771 if (typeof raw !== "string") {
772 return Effect.succeedNone;
773 }
774 return decodeStoredServerConfig(raw).pipe(
775 Effect.mapError((cause) => persistenceError("load-server-config", cause)),
776 Effect.map((stored) =>
777 stored.environmentId === environmentId ? Option.some(stored.config) : Option.none(),
778 ),
779 );
780 }),
781 Effect.mapError((cause) =>
782 cause._tag === "ConnectionPersistenceError"
783 ? cause
784 : persistenceError("load-server-config", cause),
785 ),
786 ),
787 saveServerConfig: (environmentId, config) =>
788 Effect.gen(function* () {
789 const encoded = yield* encodeStoredServerConfig({
790 schemaVersion: 1,
791 environmentId,
792 config,
793 }).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));
794 yield* writeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId, encoded);
795 }).pipe(
796 Effect.mapError((cause) =>
797 cause._tag === "ConnectionPersistenceError"
798 ? cause
799 : persistenceError("save-server-config", cause),
800 ),
801 ),
802 loadThread: (environmentId, threadId) =>
803 readDatabaseValue(
804 database,
805 THREAD_STORE_NAME,
806 threadCacheKey(environmentId, threadId),
807 ).pipe(
808 Effect.flatMap((raw) => {
809 if (typeof raw !== "string") {
810 return Effect.succeedNone;
811 }
812 return decodeOrDiscardOrchestrationCache(
813 decodeStoredThreadSnapshot(raw).pipe(
814 Effect.mapError((cause) => persistenceError("load-thread", cause)),
815 Effect.map((stored) =>
816 stored.environmentId === environmentId && stored.threadId === threadId
817 ? Option.some(stored.snapshot)
818 : Option.none(),
819 ),
820 ),
821 removeDatabaseValue(
822 database,
823 THREAD_STORE_NAME,
824 threadCacheKey(environmentId, threadId),
825 ),
826 );
827 }),
828 Effect.mapError((cause) => persistenceError("load-thread", cause)),
829 ),
830 saveThread: (environmentId, snapshot) =>
831 Effect.gen(function* () {
832 const encoded = yield* encodeStoredThreadSnapshot({
833 schemaVersion: ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION,
834 environmentId,
835 threadId: snapshot.projection.thread.id,
836 snapshot,
837 }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
838 yield* writeDatabaseValue(
839 database,
840 THREAD_STORE_NAME,
841 threadCacheKey(environmentId, snapshot.projection.thread.id),
842 encoded,
843 );
844 }).pipe(
845 Effect.mapError((cause) =>
846 cause._tag === "ConnectionPersistenceError"
847 ? cause
848 : persistenceError("save-thread", cause),
849 ),
850 ),
851 loadVcsRefs: (environmentId, cwd) =>
852 readDatabaseValue(database, VCS_REFS_STORE_NAME, vcsRefsCacheKey(environmentId, cwd)).pipe(
853 Effect.flatMap((raw) => {
854 if (typeof raw !== "string") {
855 return Effect.succeedNone;
856 }
857 return decodeStoredVcsRefs(raw).pipe(
858 Effect.mapError((cause) => persistenceError("load-vcs-refs", cause)),
859 Effect.map((stored) =>
860 stored.environmentId === environmentId && stored.cwd === cwd
861 ? Option.some(stored.refs)
862 : Option.none(),
863 ),
864 );
865 }),
866 Effect.mapError((cause) =>
867 cause._tag === "ConnectionPersistenceError"
868 ? cause
869 : persistenceError("load-vcs-refs", cause),
870 ),
871 ),
872 saveVcsRefs: (environmentId, cwd, refs) =>
873 Effect.gen(function* () {
874 const encoded = yield* encodeStoredVcsRefs({
875 schemaVersion: 1,
876 environmentId,
877 cwd,
878 refs,
879 }).pipe(Effect.mapError((cause) => persistenceError("save-vcs-refs", cause)));
880 yield* writeDatabaseValue(
881 database,
882 VCS_REFS_STORE_NAME,
883 vcsRefsCacheKey(environmentId, cwd),
884 encoded,
885 );
886 }).pipe(
887 Effect.mapError((cause) =>
888 cause._tag === "ConnectionPersistenceError"
889 ? cause
890 : persistenceError("save-vcs-refs", cause),
891 ),
892 ),
893 removeVcsRefs: (environmentId, cwd) =>
894 removeDatabaseValue(
895 database,
896 VCS_REFS_STORE_NAME,
897 vcsRefsCacheKey(environmentId, cwd),
898 ).pipe(Effect.mapError((cause) => persistenceError("remove-vcs-refs", cause))),
899 clearVcsRefs: (environmentId) =>
900 removeDatabaseValuesInRange(
901 database,
902 VCS_REFS_STORE_NAME,
903 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
904 ).pipe(Effect.mapError((cause) => persistenceError("clear-vcs-refs", cause))),
905 removeThread: (environmentId, threadId) =>
906 removeDatabaseValue(
907 database,
908 THREAD_STORE_NAME,
909 threadCacheKey(environmentId, threadId),
910 ).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause))),
911 clear: (environmentId) =>
912 Effect.all(
913 [
914 Effect.promise(() => projectFaviconCache.clearEnvironment(environmentId)),
915 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
916 removeDatabaseValuesInRange(
917 database,
918 THREAD_STORE_NAME,
919 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
920 ),
921 removeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId),
922 removeDatabaseValuesInRange(
923 database,
924 VCS_REFS_STORE_NAME,
925 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
926 ),
927 ],
928 { concurrency: "unbounded", discard: true },
929 ).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause))),
930 });
931​
932 return Context.make(Persistence.ConnectionTargetStore, targetStore).pipe(
933 Context.add(GitHubRoutingPermissions, githubRoutingPermissions),
934 Context.add(Persistence.ConnectionRegistrationStore, registrationStore),
935 Context.add(ProfileStore.ConnectionProfileStore, profileStore),
936 Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
937 Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
938 Context.add(Persistence.EnvironmentCacheStore, cacheStore),
939 );
940 }),
941);