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