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