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

storage.ts

943 lines34.6 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 PullRequestRoutingPermissions,
27 StoredPullRequestRoutingPermission,
28 pullRequestRoutingConnectionKey,
29 pullRequestRoutingPermissionFor,
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​
499// The stored names predate the rename and stay, so a tab still on an older version and an
500// updated one read and revoke the same grants.
501const PULL_REQUEST_ROUTING_KEY_PREFIX = "t3code:github-routing:";
502const PULL_REQUEST_ROUTING_CHANGED = "t3code:github-routing-changed";
503const isStoredPullRequestRoutingPermission = Schema.is(StoredPullRequestRoutingPermission);
504const encodeStoredPullRequestRoutingPermission = Schema.encodeSync(
505 Schema.fromJsonString(StoredPullRequestRoutingPermission),
506);
507​
508/** Each grant has its own key so stale tabs and unrelated catalog saves cannot restore trust. */
509export function makeBrowserPullRequestRoutingPermissions(
510 browser: Pick<Window, "localStorage"> & EventTarget = window,
511) {
512 const read = (key: string): StoredPullRequestRoutingPermission | null => {
513 try {
514 const raw = browser.localStorage.getItem(key);
515 const value: unknown = raw === null ? null : JSON.parse(raw);
516 return isStoredPullRequestRoutingPermission(value) &&
517 key === `${PULL_REQUEST_ROUTING_KEY_PREFIX}${value.environmentId}`
518 ? value
519 : null;
520 } catch {
521 return null;
522 }
523 };
524 const readAll = (): ReadonlyArray<StoredPullRequestRoutingPermission> => {
525 try {
526 const values: StoredPullRequestRoutingPermission[] = [];
527 const storage = browser.localStorage;
528 for (let index = 0; index < storage.length; index++) {
529 const key = storage.key(index);
530 if (key?.startsWith(PULL_REQUEST_ROUTING_KEY_PREFIX)) {
531 const value = read(key);
532 if (value !== null) values.push(value);
533 }
534 }
535 return values;
536 } catch {
537 return [];
538 }
539 };
540 const write = (environmentId: EnvironmentId, value: StoredPullRequestRoutingPermission | null) =>
541 Effect.try({
542 try: () => {
543 const key = `${PULL_REQUEST_ROUTING_KEY_PREFIX}${environmentId}`;
544 if (value === null) browser.localStorage.removeItem(key);
545 else browser.localStorage.setItem(key, encodeStoredPullRequestRoutingPermission(value));
546 browser.dispatchEvent(new Event(PULL_REQUEST_ROUTING_CHANGED));
547 },
548 catch: (cause) => catalogError("save pull request routing permissions in", cause),
549 });
550 return PullRequestRoutingPermissions.of({
551 get: (entry) =>
552 Effect.sync(() => {
553 const value = read(`${PULL_REQUEST_ROUTING_KEY_PREFIX}${entry.target.environmentId}`);
554 return pullRequestRoutingPermissionFor(entry, value === null ? [] : [value]);
555 }),
556 changes: Stream.callback<ReadonlyArray<StoredPullRequestRoutingPermission>>((queue) =>
557 Effect.acquireRelease(
558 Effect.sync(() => {
559 const listener = (event: Event) => {
560 if (event.type === "storage") {
561 const key = (event as StorageEvent).key;
562 if (key !== null && !key?.startsWith(PULL_REQUEST_ROUTING_KEY_PREFIX)) return;
563 }
564 Queue.offerUnsafe(queue, readAll());
565 };
566 browser.addEventListener("storage", listener);
567 browser.addEventListener(PULL_REQUEST_ROUTING_CHANGED, listener);
568 Queue.offerUnsafe(queue, readAll());
569 return listener;
570 }),
571 (listener) =>
572 Effect.sync(() => {
573 browser.removeEventListener("storage", listener);
574 browser.removeEventListener(PULL_REQUEST_ROUTING_CHANGED, listener);
575 }),
576 ).pipe(Effect.asVoid),
577 ),
578 set: (entry, permission) => {
579 const connectionKey = pullRequestRoutingConnectionKey(entry);
580 if (connectionKey === null)
581 return Effect.fail(
582 new ConnectionBlockedError({
583 reason: "configuration",
584 detail: "This environment does not have a saved connection endpoint.",
585 }),
586 );
587 return write(
588 entry.target.environmentId,
589 permission === "off"
590 ? null
591 : {
592 environmentId: entry.target.environmentId,
593 connectionKey,
594 permission,
595 },
596 );
597 },
598 forget: (environmentId) => write(environmentId, null),
599 });
601​
602// A posted message resumes in a fresh task, so input and rendering get a turn between
603// encoding chunks. A zero-delay timer would not do: browsers clamp nested timers to
604// 4 ms and throttle them to once a second or less in a background tab.
605const yieldToBrowserTask = Effect.callback<void>((resume) => {
606 const { port1, port2 } = new MessageChannel();
607 port1.addEventListener(
608 "message",
609 () => {
610 port1.close();
611 resume(Effect.void);
612 },
613 { once: true },
614 );
615 port1.start();
616 port2.postMessage(null);
617 // A closed port delivers nothing, so interruption needs no listener bookkeeping.
618 return Effect.sync(() => port1.close());
619});
620​
621export const layer = Layer.effectContext(
622 Effect.gen(function* () {
623 const { handle: database } = yield* Effect.acquireRelease(
624 makeDatabaseHandle(),
625 (owned) => owned.close,
626 );
627 const catalog = yield* makeCatalogStore(makeCatalogBackend(database));
628 const pullRequestRoutingPermissions = makeBrowserPullRequestRoutingPermissions();
629 // Remembers each thread row's encoding, so a save only encodes rows that changed.
630 const encodeStoredShellSnapshot = makeStoredShellSnapshotEncoder({
631 yieldToHost: yieldToBrowserTask,
632 });
633​
634 const targetStore = Persistence.ConnectionTargetStore.of({
635 list: catalog.read.pipe(
636 Effect.map((document) => document.targets),
637 Effect.mapError((cause) => persistenceError("list-targets", cause)),
638 ),
639 listDisabled: catalog.read.pipe(
640 Effect.map((document) => document.disabledEnvironmentIds),
641 Effect.mapError((cause) => persistenceError("list-disabled-targets", cause)),
642 ),
643 });
644 const registrationStore = Persistence.ConnectionRegistrationStore.of({
645 register: (registration, routes) =>
646 catalog
647 .update((document) => registerConnectionInCatalog(document, registration, routes))
648 .pipe(Effect.mapError((cause) => persistenceError("register-connection", cause))),
649 setRoutes: (environmentId, routes) =>
650 catalog
651 .update((document) => setRoutesInCatalog(document, environmentId, routes))
652 .pipe(Effect.mapError((cause) => persistenceError("set-connection-routes", cause))),
653 remove: (environmentId) =>
654 catalog
655 .update((document) => removeConnectionFromCatalog(document, environmentId))
656 .pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause))),
657 setEnabled: (environmentId, enabled) =>
658 catalog
659 .update((document) => setConnectionEnabledInCatalog(document, environmentId, enabled))
660 .pipe(Effect.mapError((cause) => persistenceError("set-connection-enabled", cause))),
661 });
662 const profileStore = ProfileStore.make({
663 get: (connectionId) =>
664 catalog.read.pipe(
665 Effect.map((document) =>
666 Option.fromUndefinedOr(
667 document.profiles.find((profile) => profile.connectionId === connectionId),
668 ),
669 ),
670 ),
671 put: (profile) =>
672 catalog.update((document) => ({
673 ...document,
674 profiles: replaceCatalogValue(document.profiles, (value) => value.connectionId, profile),
675 })),
676 remove: (connectionId) =>
677 catalog.update((document) => ({
678 ...document,
679 profiles: removeCatalogValue(
680 document.profiles,
681 (value) => value.connectionId,
682 connectionId,
683 ),
684 })),
685 });
686 const credentialStore = CredentialStore.make({
687 get: (connectionId) =>
688 catalog.read.pipe(
689 Effect.map((document) =>
690 Option.fromUndefinedOr(
691 document.credentials.find((entry) => entry.connectionId === connectionId)?.credential,
692 ),
693 ),
694 ),
695 put: (connectionId, credential) =>
696 catalog.update((document) => ({
697 ...document,
698 credentials: replaceCatalogValue(document.credentials, (value) => value.connectionId, {
699 connectionId,
700 credential,
701 }),
702 })),
703 remove: (connectionId) =>
704 catalog.update((document) => ({
705 ...document,
706 credentials: removeCatalogValue(
707 document.credentials,
708 (value) => value.connectionId,
709 connectionId,
710 ),
711 })),
712 });
713 const remoteTokenStore = TokenStore.make({
714 get: (environmentId) =>
715 catalog.read.pipe(
716 Effect.map((document) =>
717 Option.fromUndefinedOr(
718 document.remoteDpopTokens.find((token) => token.environmentId === environmentId),
719 ),
720 ),
721 ),
722 put: (token) => catalog.update((document) => putRemoteDpopTokenInCatalog(document, token)),
723 remove: (environmentId) =>
724 catalog.update((document) => ({
725 ...document,
726 remoteDpopTokens: removeCatalogValue(
727 document.remoteDpopTokens,
728 (value) => value.environmentId,
729 environmentId,
730 ),
731 })),
732 });
733 const cacheStore = Persistence.EnvironmentCacheStore.of({
734 loadShell: (environmentId) =>
735 readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
736 Effect.tap(() => Effect.promise(() => projectFaviconCache.hydrate())),
737 Effect.flatMap((raw) => {
738 if (typeof raw !== "string") {
739 return Effect.succeedNone;
740 }
741 return decodeOrDiscardOrchestrationCache(
742 decodeStoredShellSnapshot(raw).pipe(
743 Effect.mapError((cause) => persistenceError("load-shell", cause)),
744 Effect.map((stored) =>
745 stored.environmentId === environmentId
746 ? Option.some(stored.snapshot)
747 : Option.none(),
748 ),
749 ),
750 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
751 );
752 }),
753 Effect.mapError((cause) => persistenceError("load-shell", cause)),
754 ),
755 saveShell: Effect.fn("storage.saveShell")(
756 function* (environmentId, snapshot) {
757 const encoded = yield* encodeStoredShellSnapshot({
758 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
759 environmentId,
760 snapshot,
761 }).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
762 yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
763 },
764 Effect.mapError((cause) =>
765 cause._tag === "ConnectionPersistenceError"
766 ? cause
767 : persistenceError("save-shell", cause),
768 ),
769 ),
770 loadServerConfig: (environmentId) =>
771 readDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId).pipe(
772 Effect.flatMap((raw) => {
773 if (typeof raw !== "string") {
774 return Effect.succeedNone;
775 }
776 return decodeStoredServerConfig(raw).pipe(
777 Effect.mapError((cause) => persistenceError("load-server-config", cause)),
778 Effect.map((stored) =>
779 stored.environmentId === environmentId ? Option.some(stored.config) : Option.none(),
780 ),
781 );
782 }),
783 Effect.mapError((cause) =>
784 cause._tag === "ConnectionPersistenceError"
785 ? cause
786 : persistenceError("load-server-config", cause),
787 ),
788 ),
789 saveServerConfig: Effect.fn("storage.saveServerConfig")(
790 function* (environmentId, config) {
791 const encoded = yield* encodeStoredServerConfig({
792 schemaVersion: 1,
793 environmentId,
794 config,
795 }).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));
796 yield* writeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId, encoded);
797 },
798 Effect.mapError((cause) =>
799 cause._tag === "ConnectionPersistenceError"
800 ? cause
801 : persistenceError("save-server-config", cause),
802 ),
803 ),
804 loadThread: (environmentId, threadId) =>
805 readDatabaseValue(
806 database,
807 THREAD_STORE_NAME,
808 threadCacheKey(environmentId, threadId),
809 ).pipe(
810 Effect.flatMap((raw) => {
811 if (typeof raw !== "string") {
812 return Effect.succeedNone;
813 }
814 return decodeOrDiscardOrchestrationCache(
815 decodeStoredThreadSnapshot(raw).pipe(
816 Effect.mapError((cause) => persistenceError("load-thread", cause)),
817 Effect.map((stored) =>
818 stored.environmentId === environmentId && stored.threadId === threadId
819 ? Option.some(stored.snapshot)
820 : Option.none(),
821 ),
822 ),
823 removeDatabaseValue(
824 database,
825 THREAD_STORE_NAME,
826 threadCacheKey(environmentId, threadId),
827 ),
828 );
829 }),
830 Effect.mapError((cause) => persistenceError("load-thread", cause)),
831 ),
832 saveThread: Effect.fn("storage.saveThread")(
833 function* (environmentId, snapshot) {
834 const encoded = yield* encodeStoredThreadSnapshot({
835 schemaVersion: ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION,
836 environmentId,
837 threadId: snapshot.projection.thread.id,
838 snapshot,
839 }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
840 yield* writeDatabaseValue(
841 database,
842 THREAD_STORE_NAME,
843 threadCacheKey(environmentId, snapshot.projection.thread.id),
844 encoded,
845 );
846 },
847 Effect.mapError((cause) =>
848 cause._tag === "ConnectionPersistenceError"
849 ? cause
850 : persistenceError("save-thread", cause),
851 ),
852 ),
853 loadVcsRefs: (environmentId, cwd) =>
854 readDatabaseValue(database, VCS_REFS_STORE_NAME, vcsRefsCacheKey(environmentId, cwd)).pipe(
855 Effect.flatMap((raw) => {
856 if (typeof raw !== "string") {
857 return Effect.succeedNone;
858 }
859 return decodeStoredVcsRefs(raw).pipe(
860 Effect.mapError((cause) => persistenceError("load-vcs-refs", cause)),
861 Effect.map((stored) =>
862 stored.environmentId === environmentId && stored.cwd === cwd
863 ? Option.some(stored.refs)
864 : Option.none(),
865 ),
866 );
867 }),
868 Effect.mapError((cause) =>
869 cause._tag === "ConnectionPersistenceError"
870 ? cause
871 : persistenceError("load-vcs-refs", cause),
872 ),
873 ),
874 saveVcsRefs: Effect.fn("storage.saveVcsRefs")(
875 function* (environmentId, cwd, refs) {
876 const encoded = yield* encodeStoredVcsRefs({
877 schemaVersion: 1,
878 environmentId,
879 cwd,
880 refs,
881 }).pipe(Effect.mapError((cause) => persistenceError("save-vcs-refs", cause)));
882 yield* writeDatabaseValue(
883 database,
884 VCS_REFS_STORE_NAME,
885 vcsRefsCacheKey(environmentId, cwd),
886 encoded,
887 );
888 },
889 Effect.mapError((cause) =>
890 cause._tag === "ConnectionPersistenceError"
891 ? cause
892 : persistenceError("save-vcs-refs", cause),
893 ),
894 ),
895 removeVcsRefs: (environmentId, cwd) =>
896 removeDatabaseValue(
897 database,
898 VCS_REFS_STORE_NAME,
899 vcsRefsCacheKey(environmentId, cwd),
900 ).pipe(Effect.mapError((cause) => persistenceError("remove-vcs-refs", cause))),
901 clearVcsRefs: (environmentId) =>
902 removeDatabaseValuesInRange(
903 database,
904 VCS_REFS_STORE_NAME,
905 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
906 ).pipe(Effect.mapError((cause) => persistenceError("clear-vcs-refs", cause))),
907 removeThread: (environmentId, threadId) =>
908 removeDatabaseValue(
909 database,
910 THREAD_STORE_NAME,
911 threadCacheKey(environmentId, threadId),
912 ).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause))),
913 clear: (environmentId) =>
914 Effect.all(
915 [
916 Effect.promise(() => projectFaviconCache.clearEnvironment(environmentId)),
917 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
918 removeDatabaseValuesInRange(
919 database,
920 THREAD_STORE_NAME,
921 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
922 ),
923 removeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId),
924 removeDatabaseValuesInRange(
925 database,
926 VCS_REFS_STORE_NAME,
927 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
928 ),
929 ],
930 { concurrency: "unbounded", discard: true },
931 ).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause))),
932 });
933​
934 return Context.make(Persistence.ConnectionTargetStore, targetStore).pipe(
935 Context.add(PullRequestRoutingPermissions, pullRequestRoutingPermissions),
936 Context.add(Persistence.ConnectionRegistrationStore, registrationStore),
937 Context.add(ProfileStore.ConnectionProfileStore, profileStore),
938 Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
939 Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
940 Context.add(Persistence.EnvironmentCacheStore, cacheStore),
941 );
942 }),
943);