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