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

storage.ts

771 lines29.2 KB

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