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