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

storage.ts

792 lines29.7 KB

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