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