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