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

storage.ts

800 lines30.1 KB

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