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