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