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