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

storage.ts

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