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