Open History to see the last commit
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 });
84}
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 });
112}
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>;
156}
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// Browsers can omit close events; retry InvalidStateError with a fresh connection.
196function withDatabase<A>(
197 database: DatabaseHandle,
198 use: (opened: IDBDatabase) => Effect.Effect<A, ConnectionTransientError>,
199) {
200 const closedConnection = Symbol("closedConnection");
201 const attempt = Effect.flatMap(database.get, (opened) =>
202 use(opened).pipe(
203 Effect.catchIf(
204 (error) => error.detail.includes("InvalidStateError"),
205 (error) =>
206 database
207 .invalidate(opened)
208 .pipe(Effect.andThen(Effect.fail({ [closedConnection]: error } as const))),
209 ),
210 ),
211 );
212 return attempt.pipe(
213 Effect.catchIf(
214 (error): error is { readonly [closedConnection]: ConnectionTransientError } =>
215 closedConnection in error,
216 () => Effect.flatMap(database.get, use),
217 ),
218 );
219}
220
221function readDatabaseValueOnConnection(database: IDBDatabase, storeName: string, key: IDBValidKey) {
222 return Effect.callback<unknown, ConnectionTransientError>((resume) => {
223 try {
224 const request = database.transaction(storeName, "readonly").objectStore(storeName).get(key);
225 request.addEventListener("error", () => {
226 resume(Effect.fail(catalogError("read", request.error ?? "Unknown IndexedDB read error")));
227 });
228 request.addEventListener("success", () => {
229 resume(Effect.succeed(request.result));
230 });
231 } catch (cause) {
232 resume(Effect.fail(catalogError("read", cause)));
233 }
234 }).pipe(Effect.withSpan("web.connectionStorage.readDatabaseValue"));
235}
236
237function writeDatabaseValueOnConnection(
238 database: IDBDatabase,
239 storeName: string,
240 key: IDBValidKey,
241 value: unknown,
242) {
243 return Effect.callback<void, ConnectionTransientError>((resume) => {
244 try {
245 const transaction = database.transaction(storeName, "readwrite");
246 // Commit failures can fire abort without error; every failed write fires abort.
247 transaction.addEventListener("abort", () => {
248 resume(
249 Effect.fail(catalogError("write", transaction.error ?? "Unknown IndexedDB write error")),
250 );
251 });
252 transaction.addEventListener("complete", () => {
253 resume(Effect.void);
254 });
255 transaction.objectStore(storeName).put(value, key);
256 } catch (cause) {
257 resume(Effect.fail(catalogError("write", cause)));
258 }
259 }).pipe(Effect.withSpan("web.connectionStorage.writeDatabaseValue"));
260}
261
262function removeDatabaseValueOnConnection(
263 database: IDBDatabase,
264 storeName: string,
265 key: IDBValidKey,
266) {
267 return Effect.callback<void, ConnectionTransientError>((resume) => {
268 try {
269 const transaction = database.transaction(storeName, "readwrite");
270 transaction.addEventListener("abort", () => {
271 resume(
272 Effect.fail(
273 catalogError("remove", transaction.error ?? "Unknown IndexedDB remove error"),
274 ),
275 );
276 });
277 transaction.addEventListener("complete", () => {
278 resume(Effect.void);
279 });
280 transaction.objectStore(storeName).delete(key);
281 } catch (cause) {
282 resume(Effect.fail(catalogError("remove", cause)));
283 }
284 }).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValue"));
285}
286
287function removeDatabaseValuesInRangeOnConnection(
288 database: IDBDatabase,
289 storeName: string,
290 range: IDBKeyRange,
291) {
292 return Effect.callback<void, ConnectionTransientError>((resume) => {
293 try {
294 const transaction = database.transaction(storeName, "readwrite");
295 transaction.addEventListener("abort", () => {
296 resume(
297 Effect.fail(
298 catalogError("remove", transaction.error ?? "Unknown IndexedDB cursor error"),
299 ),
300 );
301 });
302 transaction.addEventListener("complete", () => {
303 resume(Effect.void);
304 });
305 const request = transaction.objectStore(storeName).openCursor(range);
306 request.addEventListener("error", () => {
307 resume(
308 Effect.fail(catalogError("remove", request.error ?? "Unknown IndexedDB cursor error")),
309 );
310 });
311 request.addEventListener("success", () => {
312 const cursor = request.result;
313 if (cursor === null) {
314 return;
315 }
316 try {
317 cursor.delete();
318 cursor.continue();
319 } catch (cause) {
320 resume(Effect.fail(catalogError("remove", cause)));
321 }
322 });
323 } catch (cause) {
324 resume(Effect.fail(catalogError("remove", cause)));
325 }
326 }).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValuesInRange"));
327}
328
329function readDatabaseValue(database: DatabaseHandle, storeName: string, key: IDBValidKey) {
330 return withDatabase(database, (opened) => readDatabaseValueOnConnection(opened, storeName, key));
331}
332
333function writeDatabaseValue(
334 database: DatabaseHandle,
335 storeName: string,
336 key: IDBValidKey,
337 value: unknown,
338) {
339 return withDatabase(database, (opened) =>
340 writeDatabaseValueOnConnection(opened, storeName, key, value),
341 );
342}
343
344function removeDatabaseValue(database: DatabaseHandle, storeName: string, key: IDBValidKey) {
345 return withDatabase(database, (opened) =>
346 removeDatabaseValueOnConnection(opened, storeName, key),
347 );
348}
349
350function removeDatabaseValuesInRange(
351 database: DatabaseHandle,
352 storeName: string,
353 range: IDBKeyRange,
354) {
355 return withDatabase(database, (opened) =>
356 removeDatabaseValuesInRangeOnConnection(opened, storeName, range),
357 );
358}
359
360function threadCacheKey(environmentId: EnvironmentId, threadId: ThreadId) {
361 return `${environmentId}:${threadId}`;
362}
363
364function vcsRefsCacheKey(environmentId: EnvironmentId, cwd: string) {
365 return `${environmentId}:${cwd}`;
366}
367
368const decodeCatalog = Effect.fn("web.connectionStorage.decodeCatalog")(function* (raw: string) {
369 return yield* decodeConnectionCatalogDocument(raw).pipe(
370 Effect.mapError((cause) => catalogError("decode", cause)),
371 );
372});
373
374const encodeCatalog = Effect.fn("web.connectionStorage.encodeCatalog")(function* (
375 catalog: ConnectionCatalogDocumentType,
376) {
377 return yield* encodeConnectionCatalogDocument(catalog).pipe(
378 Effect.mapError((cause) => catalogError("encode", cause)),
379 );
380});
381
382export interface CatalogBackend {
383 readonly read: Effect.Effect<string | null, ConnectionTransientError>;
384 readonly write: (raw: string) => Effect.Effect<void, ConnectionTransientError>;
385 readonly quarantine?: (raw: string) => Effect.Effect<void, ConnectionTransientError>;
386}
387
388export function makeCatalogBackend(database: DatabaseHandle): CatalogBackend {
389 const bridge = window.desktopBridge;
390 if (bridge !== undefined) {
391 return {
392 read: Effect.tryPromise({
393 try: () => bridge.getConnectionCatalog(),
394 catch: (cause) => catalogError("load", cause),
395 }),
396 write: (raw) =>
397 Effect.tryPromise({
398 try: () => bridge.setConnectionCatalog(raw),
399 catch: (cause) => catalogError("save", cause),
400 }).pipe(
401 Effect.flatMap((stored) =>
402 stored
403 ? Effect.void
404 : Effect.fail(
405 catalogError(
406 "save",
407 "Desktop secure storage is unavailable in this system context.",
408 ),
409 ),
410 ),
411 ),
412 };
413 }
414
415 return {
416 read: readDatabaseValue(database, CATALOG_STORE_NAME, CATALOG_KEY).pipe(
417 Effect.map((value) => (typeof value === "string" ? value : null)),
418 ),
419 write: (raw) => writeDatabaseValue(database, CATALOG_STORE_NAME, CATALOG_KEY, raw),
420 quarantine: (raw) =>
421 writeDatabaseValue(database, CATALOG_STORE_NAME, `${CATALOG_KEY}:corrupt:${Date.now()}`, raw),
422 };
423}
424
425interface CatalogStore {
426 readonly read: Effect.Effect<ConnectionCatalogDocumentType, ConnectionTransientError>;
427 readonly update: (
428 transform: (catalog: ConnectionCatalogDocumentType) => ConnectionCatalogDocumentType,
429 ) => Effect.Effect<void, ConnectionTransientError>;
430}
431
432export const makeCatalogStore = Effect.fn("web.connectionStorage.makeCatalogStore")(function* (
433 backend: CatalogBackend,
434) {
435 const state = yield* Ref.make<Option.Option<ConnectionCatalogDocumentType>>(Option.none());
436 const lock = yield* Semaphore.make(1);
437
438 const loadUnlocked = Effect.fn("web.connectionStorage.loadCatalog")(function* () {
439 const cached = yield* Ref.get(state);
440 if (Option.isSome(cached)) {
441 return cached.value;
442 }
443 const raw = yield* backend.read;
444 let catalog = EMPTY_CONNECTION_CATALOG_DOCUMENT;
445 if (raw !== null && raw.trim() !== "") {
446 catalog = yield* decodeCatalog(raw).pipe(
447 Effect.catch((error) =>
448 Effect.gen(function* () {
449 yield* Effect.logWarning("Discarding a corrupt web connection catalog.", {
450 error: error.message,
451 });
452 if (backend.quarantine !== undefined) {
453 yield* backend.quarantine(raw).pipe(
454 Effect.catch((cause) =>
455 Effect.logWarning("Could not quarantine the corrupt web connection catalog.", {
456 error: cause.message,
457 }),
458 ),
459 );
460 }
461 const encoded = yield* encodeCatalog(EMPTY_CONNECTION_CATALOG_DOCUMENT);
462 yield* backend.write(encoded).pipe(
463 Effect.catch((cause) =>
464 Effect.logWarning("Could not persist the recovered web connection catalog.", {
465 error: cause.message,
466 }),
467 ),
468 );
469 return EMPTY_CONNECTION_CATALOG_DOCUMENT;
470 }),
471 ),
472 );
473 }
474 yield* Ref.set(state, Option.some(catalog));
475 return catalog;
476 });
477
478 const read = lock.withPermits(1)(loadUnlocked());
479 const update: CatalogStore["update"] = Effect.fn("web.connectionStorage.updateCatalog")(
480 function* (transform) {
481 yield* lock.withPermits(1)(
482 Effect.gen(function* () {
483 const next = transform(yield* loadUnlocked());
484 yield* backend.write(yield* encodeCatalog(next));
485 yield* Ref.set(state, Option.some(next));
486 }),
487 );
488 },
489 );
490
491 return { read, update } satisfies CatalogStore;
492});
493
494// The stored names predate the rename and stay, so a tab still on an older version and an
495// updated one read and revoke the same grants.
496const PULL_REQUEST_ROUTING_KEY_PREFIX = "t3code:github-routing:";
497const PULL_REQUEST_ROUTING_CHANGED = "t3code:github-routing-changed";
498const isStoredPullRequestRoutingPermission = Schema.is(StoredPullRequestRoutingPermission);
499const encodeStoredPullRequestRoutingPermission = Schema.encodeSync(
500 Schema.fromJsonString(StoredPullRequestRoutingPermission),
501);
502
503/** Each grant has its own key so stale tabs and unrelated catalog saves cannot restore trust. */
504export function makeBrowserPullRequestRoutingPermissions(
505 browser: Pick<Window, "localStorage"> & EventTarget = window,
506) {
507 const read = (key: string): StoredPullRequestRoutingPermission | null => {
508 try {
509 const raw = browser.localStorage.getItem(key);
510 const value: unknown = raw === null ? null : JSON.parse(raw);
511 return isStoredPullRequestRoutingPermission(value) &&
512 key === `${PULL_REQUEST_ROUTING_KEY_PREFIX}${value.environmentId}`
513 ? value
514 : null;
515 } catch {
516 return null;
517 }
518 };
519 const readAll = (): ReadonlyArray<StoredPullRequestRoutingPermission> => {
520 try {
521 const values: StoredPullRequestRoutingPermission[] = [];
522 const storage = browser.localStorage;
523 for (let index = 0; index < storage.length; index++) {
524 const key = storage.key(index);
525 if (key?.startsWith(PULL_REQUEST_ROUTING_KEY_PREFIX)) {
526 const value = read(key);
527 if (value !== null) values.push(value);
528 }
529 }
530 return values;
531 } catch {
532 return [];
533 }
534 };
535 const write = (environmentId: EnvironmentId, value: StoredPullRequestRoutingPermission | null) =>
536 Effect.try({
537 try: () => {
538 const key = `${PULL_REQUEST_ROUTING_KEY_PREFIX}${environmentId}`;
539 if (value === null) browser.localStorage.removeItem(key);
540 else browser.localStorage.setItem(key, encodeStoredPullRequestRoutingPermission(value));
541 browser.dispatchEvent(new Event(PULL_REQUEST_ROUTING_CHANGED));
542 },
543 catch: (cause) => catalogError("save pull request routing permissions in", cause),
544 });
545 return PullRequestRoutingPermissions.of({
546 get: Effect.fn("PullRequestRoutingPermissions.get")(function (entry) {
547 return Effect.sync(() => {
548 const value = read(`${PULL_REQUEST_ROUTING_KEY_PREFIX}${entry.target.environmentId}`);
549 return pullRequestRoutingPermissionFor(entry, value === null ? [] : [value]);
550 });
551 }),
552 changes: Stream.callback<ReadonlyArray<StoredPullRequestRoutingPermission>>((queue) =>
553 Effect.acquireRelease(
554 Effect.sync(() => {
555 const listener = (event: Event) => {
556 if (event.type === "storage") {
557 const key = (event as StorageEvent).key;
558 if (key !== null && !key?.startsWith(PULL_REQUEST_ROUTING_KEY_PREFIX)) return;
559 }
560 Queue.offerUnsafe(queue, readAll());
561 };
562 browser.addEventListener("storage", listener);
563 browser.addEventListener(PULL_REQUEST_ROUTING_CHANGED, listener);
564 Queue.offerUnsafe(queue, readAll());
565 return listener;
566 }),
567 (listener) =>
568 Effect.sync(() => {
569 browser.removeEventListener("storage", listener);
570 browser.removeEventListener(PULL_REQUEST_ROUTING_CHANGED, listener);
571 }),
572 ).pipe(Effect.asVoid),
573 ),
574 set: Effect.fn("PullRequestRoutingPermissions.set")(function* (entry, permission) {
575 const connectionKey = pullRequestRoutingConnectionKey(entry);
576 if (connectionKey === null)
577 return yield* new ConnectionBlockedError({
578 reason: "configuration",
579 detail: "This environment does not have a saved connection endpoint.",
580 });
581 return yield* write(
582 entry.target.environmentId,
583 permission === "off"
584 ? null
585 : {
586 environmentId: entry.target.environmentId,
587 connectionKey,
588 permission,
589 },
590 );
591 }),
592 forget: Effect.fn("PullRequestRoutingPermissions.forget")(function (environmentId) {
593 return write(environmentId, null);
594 }),
595 });
596}
597
598// MessageChannel yields without nested-timer clamping or background throttling.
599const yieldToBrowserTask = Effect.callback<void>((resume) => {
600 const { port1, port2 } = new MessageChannel();
601 port1.addEventListener(
602 "message",
603 () => {
604 port1.close();
605 resume(Effect.void);
606 },
607 { once: true },
608 );
609 port1.start();
610 port2.postMessage(null);
611 // A closed port delivers nothing, so interruption needs no listener bookkeeping.
612 return Effect.sync(() => port1.close());
613});
614
615export const layer = Layer.effectContext(
616 Effect.gen(function* () {
617 const { handle: database } = yield* Effect.acquireRelease(
618 makeDatabaseHandle(),
619 (owned) => owned.close,
620 );
621 const catalog = yield* makeCatalogStore(makeCatalogBackend(database));
622 const pullRequestRoutingPermissions = makeBrowserPullRequestRoutingPermissions();
623 // Remembers each thread row's encoding, so a save only encodes rows that changed.
624 const encodeStoredShellSnapshot = makeStoredShellSnapshotEncoder({
625 yieldToHost: yieldToBrowserTask,
626 });
627
628 const targetStore = Persistence.ConnectionTargetStore.of({
629 list: catalog.read.pipe(
630 Effect.map((document) => document.targets),
631 Effect.mapError((cause) => persistenceError("list-targets", cause)),
632 ),
633 listDisabled: catalog.read.pipe(
634 Effect.map((document) => document.disabledEnvironmentIds),
635 Effect.mapError((cause) => persistenceError("list-disabled-targets", cause)),
636 ),
637 });
638 const registrationStore = Persistence.ConnectionRegistrationStore.of({
639 register: Effect.fn("Persistence.ConnectionRegistrationStore.register")(
640 function (registration, routes) {
641 return catalog
642 .update((document) => registerConnectionInCatalog(document, registration, routes))
643 .pipe(Effect.mapError((cause) => persistenceError("register-connection", cause)));
644 },
645 ),
646 setRoutes: Effect.fn("Persistence.ConnectionRegistrationStore.setRoutes")(
647 function (environmentId, routes) {
648 return catalog
649 .update((document) => setRoutesInCatalog(document, environmentId, routes))
650 .pipe(Effect.mapError((cause) => persistenceError("set-connection-routes", cause)));
651 },
652 ),
653 remove: Effect.fn("Persistence.ConnectionRegistrationStore.remove")(function (environmentId) {
654 return catalog
655 .update((document) => removeConnectionFromCatalog(document, environmentId))
656 .pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause)));
657 }),
658 setEnabled: Effect.fn("Persistence.ConnectionRegistrationStore.setEnabled")(
659 function (environmentId, enabled) {
660 return catalog
661 .update((document) => setConnectionEnabledInCatalog(document, environmentId, enabled))
662 .pipe(Effect.mapError((cause) => persistenceError("set-connection-enabled", cause)));
663 },
664 ),
665 });
666 const profileStore = ProfileStore.make({
667 get: (connectionId) =>
668 catalog.read.pipe(
669 Effect.map((document) =>
670 Option.fromUndefinedOr(
671 document.profiles.find((profile) => profile.connectionId === connectionId),
672 ),
673 ),
674 ),
675 put: (profile) =>
676 catalog.update((document) => ({
677 ...document,
678 profiles: replaceCatalogValue(document.profiles, (value) => value.connectionId, profile),
679 })),
680 remove: (connectionId) =>
681 catalog.update((document) => ({
682 ...document,
683 profiles: removeCatalogValue(
684 document.profiles,
685 (value) => value.connectionId,
686 connectionId,
687 ),
688 })),
689 });
690 const credentialStore = CredentialStore.make({
691 get: (connectionId) =>
692 catalog.read.pipe(
693 Effect.map((document) =>
694 Option.fromUndefinedOr(
695 document.credentials.find((entry) => entry.connectionId === connectionId)?.credential,
696 ),
697 ),
698 ),
699 put: (connectionId, credential) =>
700 catalog.update((document) => ({
701 ...document,
702 credentials: replaceCatalogValue(document.credentials, (value) => value.connectionId, {
703 connectionId,
704 credential,
705 }),
706 })),
707 remove: (connectionId) =>
708 catalog.update((document) => ({
709 ...document,
710 credentials: removeCatalogValue(
711 document.credentials,
712 (value) => value.connectionId,
713 connectionId,
714 ),
715 })),
716 });
717 const remoteTokenStore = TokenStore.make({
718 get: (environmentId) =>
719 catalog.read.pipe(
720 Effect.map((document) =>
721 Option.fromUndefinedOr(
722 document.remoteDpopTokens.find((token) => token.environmentId === environmentId),
723 ),
724 ),
725 ),
726 put: (token) => catalog.update((document) => putRemoteDpopTokenInCatalog(document, token)),
727 remove: (environmentId) =>
728 catalog.update((document) => ({
729 ...document,
730 remoteDpopTokens: removeCatalogValue(
731 document.remoteDpopTokens,
732 (value) => value.environmentId,
733 environmentId,
734 ),
735 })),
736 });
737 const cacheStore = Persistence.EnvironmentCacheStore.of({
738 loadShell: Effect.fn("Persistence.EnvironmentCacheStore.loadShell")(function (environmentId) {
739 return readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
740 Effect.tap(() => Effect.promise(() => projectFaviconCache.hydrate())),
741 Effect.flatMap((raw) => {
742 if (typeof raw !== "string") {
743 return Effect.succeedNone;
744 }
745 return decodeOrDiscardOrchestrationCache(
746 decodeStoredShellSnapshot(raw).pipe(
747 Effect.mapError((cause) => persistenceError("load-shell", cause)),
748 Effect.map((stored) =>
749 stored.environmentId === environmentId
750 ? Option.some(stored.snapshot)
751 : Option.none(),
752 ),
753 ),
754 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
755 );
756 }),
757 Effect.mapError((cause) => persistenceError("load-shell", cause)),
758 );
759 }),
760 saveShell: Effect.fn("storage.saveShell")(
761 function* (environmentId, snapshot) {
762 const encoded = yield* encodeStoredShellSnapshot({
763 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
764 environmentId,
765 snapshot,
766 }).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
767 yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
768 },
769 Effect.mapError((cause) =>
770 cause._tag === "ConnectionPersistenceError"
771 ? cause
772 : persistenceError("save-shell", cause),
773 ),
774 ),
775 loadServerConfig: Effect.fn("Persistence.EnvironmentCacheStore.loadServerConfig")(
776 function (environmentId) {
777 return readDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId).pipe(
778 Effect.flatMap((raw) => {
779 if (typeof raw !== "string") {
780 return Effect.succeedNone;
781 }
782 return decodeStoredServerConfig(raw).pipe(
783 Effect.mapError((cause) => persistenceError("load-server-config", cause)),
784 Effect.map((stored) =>
785 stored.environmentId === environmentId
786 ? Option.some(stored.config)
787 : Option.none(),
788 ),
789 );
790 }),
791 Effect.mapError((cause) =>
792 cause._tag === "ConnectionPersistenceError"
793 ? cause
794 : persistenceError("load-server-config", cause),
795 ),
796 );
797 },
798 ),
799 saveServerConfig: Effect.fn("storage.saveServerConfig")(
800 function* (environmentId, config) {
801 const encoded = yield* encodeStoredServerConfig({
802 schemaVersion: 1,
803 environmentId,
804 config,
805 }).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));
806 yield* writeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId, encoded);
807 },
808 Effect.mapError((cause) =>
809 cause._tag === "ConnectionPersistenceError"
810 ? cause
811 : persistenceError("save-server-config", cause),
812 ),
813 ),
814 loadThread: Effect.fn("Persistence.EnvironmentCacheStore.loadThread")(
815 function (environmentId, threadId) {
816 return readDatabaseValue(
817 database,
818 THREAD_STORE_NAME,
819 threadCacheKey(environmentId, threadId),
820 ).pipe(
821 Effect.flatMap((raw) => {
822 if (typeof raw !== "string") {
823 return Effect.succeedNone;
824 }
825 return decodeOrDiscardOrchestrationCache(
826 decodeStoredThreadSnapshot(raw).pipe(
827 Effect.mapError((cause) => persistenceError("load-thread", cause)),
828 Effect.map((stored) =>
829 stored.environmentId === environmentId && stored.threadId === threadId
830 ? Option.some(stored.snapshot)
831 : Option.none(),
832 ),
833 ),
834 removeDatabaseValue(
835 database,
836 THREAD_STORE_NAME,
837 threadCacheKey(environmentId, threadId),
838 ),
839 );
840 }),
841 Effect.mapError((cause) => persistenceError("load-thread", cause)),
842 );
843 },
844 ),
845 saveThread: Effect.fn("storage.saveThread")(
846 function* (environmentId, snapshot) {
847 const encoded = yield* encodeStoredThreadSnapshot({
848 schemaVersion: ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION,
849 environmentId,
850 threadId: snapshot.projection.thread.id,
851 snapshot,
852 }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
853 yield* writeDatabaseValue(
854 database,
855 THREAD_STORE_NAME,
856 threadCacheKey(environmentId, snapshot.projection.thread.id),
857 encoded,
858 );
859 },
860 Effect.mapError((cause) =>
861 cause._tag === "ConnectionPersistenceError"
862 ? cause
863 : persistenceError("save-thread", cause),
864 ),
865 ),
866 loadVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.loadVcsRefs")(
867 function (environmentId, cwd) {
868 return readDatabaseValue(
869 database,
870 VCS_REFS_STORE_NAME,
871 vcsRefsCacheKey(environmentId, cwd),
872 ).pipe(
873 Effect.flatMap((raw) => {
874 if (typeof raw !== "string") {
875 return Effect.succeedNone;
876 }
877 return decodeStoredVcsRefs(raw).pipe(
878 Effect.mapError((cause) => persistenceError("load-vcs-refs", cause)),
879 Effect.map((stored) =>
880 stored.environmentId === environmentId && stored.cwd === cwd
881 ? Option.some(stored.refs)
882 : Option.none(),
883 ),
884 );
885 }),
886 Effect.mapError((cause) =>
887 cause._tag === "ConnectionPersistenceError"
888 ? cause
889 : persistenceError("load-vcs-refs", cause),
890 ),
891 );
892 },
893 ),
894 saveVcsRefs: Effect.fn("storage.saveVcsRefs")(
895 function* (environmentId, cwd, refs) {
896 const encoded = yield* encodeStoredVcsRefs({
897 schemaVersion: 1,
898 environmentId,
899 cwd,
900 refs,
901 }).pipe(Effect.mapError((cause) => persistenceError("save-vcs-refs", cause)));
902 yield* writeDatabaseValue(
903 database,
904 VCS_REFS_STORE_NAME,
905 vcsRefsCacheKey(environmentId, cwd),
906 encoded,
907 );
908 },
909 Effect.mapError((cause) =>
910 cause._tag === "ConnectionPersistenceError"
911 ? cause
912 : persistenceError("save-vcs-refs", cause),
913 ),
914 ),
915 removeVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.removeVcsRefs")(
916 function (environmentId, cwd) {
917 return removeDatabaseValue(
918 database,
919 VCS_REFS_STORE_NAME,
920 vcsRefsCacheKey(environmentId, cwd),
921 ).pipe(Effect.mapError((cause) => persistenceError("remove-vcs-refs", cause)));
922 },
923 ),
924 clearVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.clearVcsRefs")(
925 function (environmentId) {
926 return removeDatabaseValuesInRange(
927 database,
928 VCS_REFS_STORE_NAME,
929 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
930 ).pipe(Effect.mapError((cause) => persistenceError("clear-vcs-refs", cause)));
931 },
932 ),
933 removeThread: Effect.fn("Persistence.EnvironmentCacheStore.removeThread")(
934 function (environmentId, threadId) {
935 return removeDatabaseValue(
936 database,
937 THREAD_STORE_NAME,
938 threadCacheKey(environmentId, threadId),
939 ).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause)));
940 },
941 ),
942 clear: Effect.fn("Persistence.EnvironmentCacheStore.clear")(function (environmentId) {
943 return Effect.all(
944 [
945 Effect.promise(() => projectFaviconCache.clearEnvironment(environmentId)),
946 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
947 removeDatabaseValuesInRange(
948 database,
949 THREAD_STORE_NAME,
950 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
951 ),
952 removeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId),
953 removeDatabaseValuesInRange(
954 database,
955 VCS_REFS_STORE_NAME,
956 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
957 ),
958 ],
959 { concurrency: "unbounded", discard: true },
960 ).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause)));
961 }),
962 });
963
964 return Context.make(Persistence.ConnectionTargetStore, targetStore).pipe(
965 Context.add(PullRequestRoutingPermissions, pullRequestRoutingPermissions),
966 Context.add(Persistence.ConnectionRegistrationStore, registrationStore),
967 Context.add(ProfileStore.ConnectionProfileStore, profileStore),
968 Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
969 Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
970 Context.add(Persistence.EnvironmentCacheStore, cacheStore),
971 );
972 }),
973);