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

storage.ts

651 lines24.5 KB

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 replaceCatalogValue,
18} from "@t3tools/client-runtime/platform";
19import { TokenStore } from "@t3tools/client-runtime/authorization";
20import {
21 ConnectionTransientError,
22 CredentialStore,
23 ProfileStore,
24} from "@t3tools/client-runtime/connection";
25import { EnvironmentId, ServerConfig, ThreadId, VcsListRefsResult } from "@t3tools/contracts";
26import * as Context from "effect/Context";
27import * as Effect from "effect/Effect";
28import * as Layer from "effect/Layer";
29import * as Option from "effect/Option";
30import * as Ref from "effect/Ref";
31import * as Schema from "effect/Schema";
32import * as Semaphore from "effect/Semaphore";
33import { projectFaviconCache } from "../assets/projectFaviconCache";
34​
35const DATABASE_NAME = "t3code:connection-runtime";
36const DATABASE_VERSION = 4;
37const CATALOG_STORE_NAME = "catalog";
38const SHELL_STORE_NAME = "shell";
39const THREAD_STORE_NAME = "thread";
40const SERVER_CONFIG_STORE_NAME = "server-config";
41const VCS_REFS_STORE_NAME = "vcs-refs";
42const CATALOG_KEY = "document";
43const StoredShellSnapshot = StoredOrchestrationShellSnapshot;
44const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
45const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot;
46const StoredThreadSnapshotJson = Schema.fromJsonString(StoredThreadSnapshot);
47const StoredServerConfig = Schema.Struct({
48 schemaVersion: Schema.Literal(1),
49 environmentId: EnvironmentId,
50 config: ServerConfig,
51});
52const StoredServerConfigJson = Schema.fromJsonString(StoredServerConfig);
53const StoredVcsRefs = Schema.Struct({
54 schemaVersion: Schema.Literal(1),
55 environmentId: EnvironmentId,
56 cwd: Schema.String,
57 refs: VcsListRefsResult,
58});
59const StoredVcsRefsJson = Schema.fromJsonString(StoredVcsRefs);
60const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
61const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson);
62const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
63const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(StoredShellSnapshotJson);
64const encodeStoredShellSnapshot = Schema.encodeEffect(StoredShellSnapshotJson);
65const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredThreadSnapshotJson);
66const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshotJson);
67const decodeStoredServerConfig = Schema.decodeUnknownEffect(StoredServerConfigJson);
68const encodeStoredServerConfig = Schema.encodeEffect(StoredServerConfigJson);
69const decodeStoredVcsRefs = Schema.decodeUnknownEffect(StoredVcsRefsJson);
70const encodeStoredVcsRefs = Schema.encodeEffect(StoredVcsRefsJson);
71​
72function catalogError(operation: string, cause: unknown) {
73 return new ConnectionTransientError({
74 reason: "remote-unavailable",
75 detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
76 });
78​
79function persistenceError(
80 operation:
81 | "list-targets"
82 | "register-connection"
83 | "remove-connection"
84 | "load-shell"
85 | "save-shell"
86 | "load-thread"
87 | "save-thread"
88 | "remove-thread"
89 | "load-server-config"
90 | "save-server-config"
91 | "load-vcs-refs"
92 | "save-vcs-refs"
93 | "remove-vcs-refs"
94 | "clear-vcs-refs"
95 | "clear-environment",
96 cause: unknown,
97) {
98 return new ConnectionPersistenceError({
99 operation,
100 message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
101 });
103​
104const openDatabase = Effect.fn("web.connectionStorage.openDatabase")(function* () {
105 return yield* Effect.callback<IDBDatabase, ConnectionTransientError>((resume) => {
106 if (typeof indexedDB === "undefined") {
107 resume(
108 Effect.fail(catalogError("open", "IndexedDB is unavailable in this browser context.")),
109 );
110 return;
111 }
112 const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
113 request.addEventListener("upgradeneeded", () => {
114 if (!request.result.objectStoreNames.contains(CATALOG_STORE_NAME)) {
115 request.result.createObjectStore(CATALOG_STORE_NAME);
116 }
117 if (!request.result.objectStoreNames.contains(SHELL_STORE_NAME)) {
118 request.result.createObjectStore(SHELL_STORE_NAME);
119 }
120 if (!request.result.objectStoreNames.contains(THREAD_STORE_NAME)) {
121 request.result.createObjectStore(THREAD_STORE_NAME);
122 }
123 if (!request.result.objectStoreNames.contains(SERVER_CONFIG_STORE_NAME)) {
124 request.result.createObjectStore(SERVER_CONFIG_STORE_NAME);
125 }
126 if (!request.result.objectStoreNames.contains(VCS_REFS_STORE_NAME)) {
127 request.result.createObjectStore(VCS_REFS_STORE_NAME);
128 }
129 });
130 request.addEventListener("error", () => {
131 resume(Effect.fail(catalogError("open", request.error ?? "Unknown IndexedDB error")));
132 });
133 request.addEventListener("success", () => {
134 resume(Effect.succeed(request.result));
135 });
136 });
137});
138​
139function readDatabaseValue(database: IDBDatabase, storeName: string, key: IDBValidKey) {
140 return Effect.callback<unknown, ConnectionTransientError>((resume) => {
141 const request = database.transaction(storeName, "readonly").objectStore(storeName).get(key);
142 request.addEventListener("error", () => {
143 resume(Effect.fail(catalogError("read", request.error ?? "Unknown IndexedDB read error")));
144 });
145 request.addEventListener("success", () => {
146 resume(Effect.succeed(request.result));
147 });
148 }).pipe(Effect.withSpan("web.connectionStorage.readDatabaseValue"));
150​
151function writeDatabaseValue(
152 database: IDBDatabase,
153 storeName: string,
154 key: IDBValidKey,
155 value: unknown,
156) {
157 return Effect.callback<void, ConnectionTransientError>((resume) => {
158 const transaction = database.transaction(storeName, "readwrite");
159 transaction.addEventListener("error", () => {
160 resume(
161 Effect.fail(catalogError("write", transaction.error ?? "Unknown IndexedDB write error")),
162 );
163 });
164 transaction.addEventListener("complete", () => {
165 resume(Effect.void);
166 });
167 transaction.objectStore(storeName).put(value, key);
168 }).pipe(Effect.withSpan("web.connectionStorage.writeDatabaseValue"));
170​
171function removeDatabaseValue(database: IDBDatabase, storeName: string, key: IDBValidKey) {
172 return Effect.callback<void, ConnectionTransientError>((resume) => {
173 const transaction = database.transaction(storeName, "readwrite");
174 transaction.addEventListener("error", () => {
175 resume(
176 Effect.fail(catalogError("remove", transaction.error ?? "Unknown IndexedDB remove error")),
177 );
178 });
179 transaction.addEventListener("complete", () => {
180 resume(Effect.void);
181 });
182 transaction.objectStore(storeName).delete(key);
183 }).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValue"));
185​
186function removeDatabaseValuesInRange(database: IDBDatabase, storeName: string, range: IDBKeyRange) {
187 return Effect.callback<void, ConnectionTransientError>((resume) => {
188 const transaction = database.transaction(storeName, "readwrite");
189 transaction.addEventListener("error", () => {
190 resume(
191 Effect.fail(catalogError("remove", transaction.error ?? "Unknown IndexedDB cursor error")),
192 );
193 });
194 transaction.addEventListener("complete", () => {
195 resume(Effect.void);
196 });
197 const request = transaction.objectStore(storeName).openCursor(range);
198 request.addEventListener("error", () => {
199 resume(
200 Effect.fail(catalogError("remove", request.error ?? "Unknown IndexedDB cursor error")),
201 );
202 });
203 request.addEventListener("success", () => {
204 const cursor = request.result;
205 if (cursor === null) {
206 return;
207 }
208 cursor.delete();
209 cursor.continue();
210 });
211 }).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValuesInRange"));
213​
214function threadCacheKey(environmentId: EnvironmentId, threadId: ThreadId) {
215 return `${environmentId}:${threadId}`;
217​
218function vcsRefsCacheKey(environmentId: EnvironmentId, cwd: string) {
219 return `${environmentId}:${cwd}`;
221​
222const decodeCatalog = Effect.fn("web.connectionStorage.decodeCatalog")(function* (raw: string) {
223 return yield* decodeConnectionCatalogDocument(raw).pipe(
224 Effect.mapError((cause) => catalogError("decode", cause)),
225 );
226});
227​
228const encodeCatalog = Effect.fn("web.connectionStorage.encodeCatalog")(function* (
229 catalog: ConnectionCatalogDocumentType,
230) {
231 return yield* encodeConnectionCatalogDocument(catalog).pipe(
232 Effect.mapError((cause) => catalogError("encode", cause)),
233 );
234});
235​
236export interface CatalogBackend {
237 readonly read: Effect.Effect<string | null, ConnectionTransientError>;
238 readonly write: (raw: string) => Effect.Effect<void, ConnectionTransientError>;
239 readonly quarantine?: (raw: string) => Effect.Effect<void, ConnectionTransientError>;
241​
242export function makeCatalogBackend(database: IDBDatabase): CatalogBackend {
243 const bridge = window.desktopBridge;
244 if (bridge?.getConnectionCatalog !== undefined && bridge.setConnectionCatalog !== undefined) {
245 return {
246 read: Effect.tryPromise({
247 try: () => bridge.getConnectionCatalog!(),
248 catch: (cause) => catalogError("load", cause),
249 }),
250 write: (raw) =>
251 Effect.tryPromise({
252 try: () => bridge.setConnectionCatalog!(raw),
253 catch: (cause) => catalogError("save", cause),
254 }).pipe(
255 Effect.flatMap((stored) =>
256 stored
257 ? Effect.void
258 : Effect.fail(
259 catalogError(
260 "save",
261 "Desktop secure storage is unavailable in this system context.",
262 ),
263 ),
264 ),
265 ),
266 };
267 }
268​
269 return {
270 read: readDatabaseValue(database, CATALOG_STORE_NAME, CATALOG_KEY).pipe(
271 Effect.map((value) => (typeof value === "string" ? value : null)),
272 ),
273 write: (raw) => writeDatabaseValue(database, CATALOG_STORE_NAME, CATALOG_KEY, raw),
274 quarantine: (raw) =>
275 writeDatabaseValue(database, CATALOG_STORE_NAME, `${CATALOG_KEY}:corrupt:${Date.now()}`, raw),
276 };
278​
279interface CatalogStore {
280 readonly read: Effect.Effect<ConnectionCatalogDocumentType, ConnectionTransientError>;
281 readonly update: (
282 transform: (catalog: ConnectionCatalogDocumentType) => ConnectionCatalogDocumentType,
283 ) => Effect.Effect<void, ConnectionTransientError>;
285​
286export const makeCatalogStore = Effect.fn("web.connectionStorage.makeCatalogStore")(function* (
287 backend: CatalogBackend,
288) {
289 const state = yield* Ref.make<Option.Option<ConnectionCatalogDocumentType>>(Option.none());
290 const lock = yield* Semaphore.make(1);
291​
292 const loadUnlocked = Effect.fn("web.connectionStorage.loadCatalog")(function* () {
293 const cached = yield* Ref.get(state);
294 if (Option.isSome(cached)) {
295 return cached.value;
296 }
297 const raw = yield* backend.read;
298 let catalog = EMPTY_CONNECTION_CATALOG_DOCUMENT;
299 if (raw !== null && raw.trim() !== "") {
300 catalog = yield* decodeCatalog(raw).pipe(
301 Effect.catch((error) =>
302 Effect.gen(function* () {
303 yield* Effect.logWarning("Discarding a corrupt web connection catalog.", {
304 error: error.message,
305 });
306 if (backend.quarantine !== undefined) {
307 yield* backend.quarantine(raw).pipe(
308 Effect.catch((cause) =>
309 Effect.logWarning("Could not quarantine the corrupt web connection catalog.", {
310 error: cause.message,
311 }),
312 ),
313 );
314 }
315 const encoded = yield* encodeCatalog(EMPTY_CONNECTION_CATALOG_DOCUMENT);
316 yield* backend.write(encoded).pipe(
317 Effect.catch((cause) =>
318 Effect.logWarning("Could not persist the recovered web connection catalog.", {
319 error: cause.message,
320 }),
321 ),
322 );
323 return EMPTY_CONNECTION_CATALOG_DOCUMENT;
324 }),
325 ),
326 );
327 }
328 yield* Ref.set(state, Option.some(catalog));
329 return catalog;
330 });
331​
332 const read = lock.withPermits(1)(loadUnlocked());
333 const update: CatalogStore["update"] = Effect.fn("web.connectionStorage.updateCatalog")(
334 function* (transform) {
335 yield* lock.withPermits(1)(
336 Effect.gen(function* () {
337 const next = transform(yield* loadUnlocked());
338 yield* backend.write(yield* encodeCatalog(next));
339 yield* Ref.set(state, Option.some(next));
340 }),
341 );
342 },
343 );
344​
345 return { read, update } satisfies CatalogStore;
346});
347​
348export const connectionStorageLayer = Layer.effectContext(
349 Effect.gen(function* () {
350 const database = yield* Effect.acquireRelease(openDatabase(), (database) =>
351 Effect.sync(() => database.close()),
352 );
353 const catalog = yield* makeCatalogStore(makeCatalogBackend(database));
354​
355 const targetStore = ConnectionTargetStore.of({
356 list: catalog.read.pipe(
357 Effect.map((document) => document.targets),
358 Effect.mapError((cause) => persistenceError("list-targets", cause)),
359 ),
360 });
361 const registrationStore = ConnectionRegistrationStore.of({
362 register: (registration) =>
363 catalog
364 .update((document) => registerConnectionInCatalog(document, registration))
365 .pipe(Effect.mapError((cause) => persistenceError("register-connection", cause))),
366 remove: (target) =>
367 catalog
368 .update((document) => removeConnectionFromCatalog(document, target))
369 .pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause))),
370 });
371 const profileStore = ProfileStore.make({
372 get: (connectionId) =>
373 catalog.read.pipe(
374 Effect.map((document) =>
375 Option.fromUndefinedOr(
376 document.profiles.find((profile) => profile.connectionId === connectionId),
377 ),
378 ),
379 ),
380 put: (profile) =>
381 catalog.update((document) => ({
382 ...document,
383 profiles: replaceCatalogValue(document.profiles, (value) => value.connectionId, profile),
384 })),
385 remove: (connectionId) =>
386 catalog.update((document) => ({
387 ...document,
388 profiles: removeCatalogValue(
389 document.profiles,
390 (value) => value.connectionId,
391 connectionId,
392 ),
393 })),
394 });
395 const credentialStore = CredentialStore.make({
396 get: (connectionId) =>
397 catalog.read.pipe(
398 Effect.map((document) =>
399 Option.fromUndefinedOr(
400 document.credentials.find((entry) => entry.connectionId === connectionId)?.credential,
401 ),
402 ),
403 ),
404 put: (connectionId, credential) =>
405 catalog.update((document) => ({
406 ...document,
407 credentials: replaceCatalogValue(document.credentials, (value) => value.connectionId, {
408 connectionId,
409 credential,
410 }),
411 })),
412 remove: (connectionId) =>
413 catalog.update((document) => ({
414 ...document,
415 credentials: removeCatalogValue(
416 document.credentials,
417 (value) => value.connectionId,
418 connectionId,
419 ),
420 })),
421 });
422 const remoteTokenStore = TokenStore.make({
423 get: (environmentId) =>
424 catalog.read.pipe(
425 Effect.map((document) =>
426 Option.fromUndefinedOr(
427 document.remoteDpopTokens.find((token) => token.environmentId === environmentId),
428 ),
429 ),
430 ),
431 put: (token) => catalog.update((document) => putRemoteDpopTokenInCatalog(document, token)),
432 remove: (environmentId) =>
433 catalog.update((document) => ({
434 ...document,
435 remoteDpopTokens: removeCatalogValue(
436 document.remoteDpopTokens,
437 (value) => value.environmentId,
438 environmentId,
439 ),
440 })),
441 });
442 const cacheStore = EnvironmentCacheStore.of({
443 loadShell: (environmentId) =>
444 readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
445 Effect.tap(() => Effect.promise(() => projectFaviconCache.hydrate())),
446 Effect.flatMap((raw) => {
447 if (typeof raw !== "string") {
448 return Effect.succeed(Option.none());
449 }
450 return decodeOrDiscardOrchestrationCache(
451 decodeStoredShellSnapshot(raw).pipe(
452 Effect.mapError((cause) => persistenceError("load-shell", cause)),
453 Effect.map((stored) =>
454 stored.environmentId === environmentId
455 ? Option.some(stored.snapshot)
456 : Option.none(),
457 ),
458 ),
459 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
460 );
461 }),
462 Effect.mapError((cause) => persistenceError("load-shell", cause)),
463 ),
464 saveShell: (environmentId, snapshot) =>
465 Effect.gen(function* () {
466 const encoded = yield* encodeStoredShellSnapshot({
467 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
468 environmentId,
469 snapshot,
470 }).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
471 yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
472 }).pipe(
473 Effect.mapError((cause) =>
474 cause._tag === "ConnectionPersistenceError"
475 ? cause
476 : persistenceError("save-shell", cause),
477 ),
478 ),
479 loadServerConfig: (environmentId) =>
480 readDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId).pipe(
481 Effect.flatMap((raw) => {
482 if (typeof raw !== "string") {
483 return Effect.succeed(Option.none());
484 }
485 return decodeStoredServerConfig(raw).pipe(
486 Effect.mapError((cause) => persistenceError("load-server-config", cause)),
487 Effect.map((stored) =>
488 stored.environmentId === environmentId ? Option.some(stored.config) : Option.none(),
489 ),
490 );
491 }),
492 Effect.mapError((cause) =>
493 cause._tag === "ConnectionPersistenceError"
494 ? cause
495 : persistenceError("load-server-config", cause),
496 ),
497 ),
498 saveServerConfig: (environmentId, config) =>
499 Effect.gen(function* () {
500 const encoded = yield* encodeStoredServerConfig({
501 schemaVersion: 1,
502 environmentId,
503 config,
504 }).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));
505 yield* writeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId, encoded);
506 }).pipe(
507 Effect.mapError((cause) =>
508 cause._tag === "ConnectionPersistenceError"
509 ? cause
510 : persistenceError("save-server-config", cause),
511 ),
512 ),
513 loadThread: (environmentId, threadId) =>
514 readDatabaseValue(
515 database,
516 THREAD_STORE_NAME,
517 threadCacheKey(environmentId, threadId),
518 ).pipe(
519 Effect.flatMap((raw) => {
520 if (typeof raw !== "string") {
521 return Effect.succeed(Option.none());
522 }
523 return decodeOrDiscardOrchestrationCache(
524 decodeStoredThreadSnapshot(raw).pipe(
525 Effect.mapError((cause) => persistenceError("load-thread", cause)),
526 Effect.map((stored) =>
527 stored.environmentId === environmentId && stored.threadId === threadId
528 ? Option.some(stored.snapshot)
529 : Option.none(),
530 ),
531 ),
532 removeDatabaseValue(
533 database,
534 THREAD_STORE_NAME,
535 threadCacheKey(environmentId, threadId),
536 ),
537 );
538 }),
539 Effect.mapError((cause) => persistenceError("load-thread", cause)),
540 ),
541 saveThread: (environmentId, snapshot) =>
542 Effect.gen(function* () {
543 const encoded = yield* encodeStoredThreadSnapshot({
544 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
545 environmentId,
546 threadId: snapshot.projection.thread.id,
547 snapshot,
548 }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
549 yield* writeDatabaseValue(
550 database,
551 THREAD_STORE_NAME,
552 threadCacheKey(environmentId, snapshot.projection.thread.id),
553 encoded,
554 );
555 }).pipe(
556 Effect.mapError((cause) =>
557 cause._tag === "ConnectionPersistenceError"
558 ? cause
559 : persistenceError("save-thread", cause),
560 ),
561 ),
562 loadVcsRefs: (environmentId, cwd) =>
563 readDatabaseValue(database, VCS_REFS_STORE_NAME, vcsRefsCacheKey(environmentId, cwd)).pipe(
564 Effect.flatMap((raw) => {
565 if (typeof raw !== "string") {
566 return Effect.succeed(Option.none());
567 }
568 return decodeStoredVcsRefs(raw).pipe(
569 Effect.mapError((cause) => persistenceError("load-vcs-refs", cause)),
570 Effect.map((stored) =>
571 stored.environmentId === environmentId && stored.cwd === cwd
572 ? Option.some(stored.refs)
573 : Option.none(),
574 ),
575 );
576 }),
577 Effect.mapError((cause) =>
578 cause._tag === "ConnectionPersistenceError"
579 ? cause
580 : persistenceError("load-vcs-refs", cause),
581 ),
582 ),
583 saveVcsRefs: (environmentId, cwd, refs) =>
584 Effect.gen(function* () {
585 const encoded = yield* encodeStoredVcsRefs({
586 schemaVersion: 1,
587 environmentId,
588 cwd,
589 refs,
590 }).pipe(Effect.mapError((cause) => persistenceError("save-vcs-refs", cause)));
591 yield* writeDatabaseValue(
592 database,
593 VCS_REFS_STORE_NAME,
594 vcsRefsCacheKey(environmentId, cwd),
595 encoded,
596 );
597 }).pipe(
598 Effect.mapError((cause) =>
599 cause._tag === "ConnectionPersistenceError"
600 ? cause
601 : persistenceError("save-vcs-refs", cause),
602 ),
603 ),
604 removeVcsRefs: (environmentId, cwd) =>
605 removeDatabaseValue(
606 database,
607 VCS_REFS_STORE_NAME,
608 vcsRefsCacheKey(environmentId, cwd),
609 ).pipe(Effect.mapError((cause) => persistenceError("remove-vcs-refs", cause))),
610 clearVcsRefs: (environmentId) =>
611 removeDatabaseValuesInRange(
612 database,
613 VCS_REFS_STORE_NAME,
614 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
615 ).pipe(Effect.mapError((cause) => persistenceError("clear-vcs-refs", cause))),
616 removeThread: (environmentId, threadId) =>
617 removeDatabaseValue(
618 database,
619 THREAD_STORE_NAME,
620 threadCacheKey(environmentId, threadId),
621 ).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause))),
622 clear: (environmentId) =>
623 Effect.all(
624 [
625 Effect.promise(() => projectFaviconCache.clearEnvironment(environmentId)),
626 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
627 removeDatabaseValuesInRange(
628 database,
629 THREAD_STORE_NAME,
630 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
631 ),
632 removeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId),
633 removeDatabaseValuesInRange(
634 database,
635 VCS_REFS_STORE_NAME,
636 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
637 ),
638 ],
639 { concurrency: "unbounded", discard: true },
640 ).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause))),
641 });
642​
643 return Context.make(ConnectionTargetStore, targetStore).pipe(
644 Context.add(ConnectionRegistrationStore, registrationStore),
645 Context.add(ProfileStore.ConnectionProfileStore, profileStore),
646 Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
647 Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
648 Context.add(EnvironmentCacheStore, cacheStore),
649 );
650 }),
651);