Open History to see the last commit
1import {
2 ConnectionCatalogDocument,
3 type ConnectionCatalogDocument as ConnectionCatalogDocumentType,
4 EMPTY_CONNECTION_CATALOG_DOCUMENT,
5 ORCHESTRATION_CACHE_SCHEMA_VERSION,
6 StoredOrchestrationShellSnapshot,
7 StoredOrchestrationThreadSnapshot,
8 decodeOrDiscardOrchestrationCache,
9 putRemoteDpopTokenInCatalog,
10 registerConnectionInCatalog,
11 removeCatalogValue,
12 removeConnectionFromCatalog,
13 setConnectionEnabledInCatalog,
14 setRoutesInCatalog,
15 replaceCatalogValue,
16 Persistence,
17 ThreadTriageOutboxStore,
18 makeStoredShellSnapshotEncoder,
19 makeStoredThreadSnapshotEncoder,
20 makeThreadCacheWriteOrder,
21} from "@t3tools/client-runtime/platform";
22import { TokenStore } from "@t3tools/client-runtime/authorization";
23import { msg } from "gt-react";
24import {
25 ConnectionTransientError,
26 ConnectionBlockedError,
27 CredentialStore,
28 ProfileStore,
29 PullRequestRoutingPermissions,
30 StoredPullRequestRoutingPermission,
31 pullRequestRoutingConnectionKey,
32 pullRequestRoutingPermissionFor,
33} from "@t3tools/client-runtime/connection";
34import { EnvironmentQueryStore } from "@t3tools/client-runtime/state/query-persistence";
35import { EnvironmentId, ServerConfig, ThreadId, VcsListRefsResult } from "@t3tools/contracts";
36import * as Clock from "effect/Clock";
37import * as Context from "effect/Context";
38import * as Effect from "effect/Effect";
39import * as Layer from "effect/Layer";
40import * as Option from "effect/Option";
41import * as Ref from "effect/Ref";
42import * as Queue from "effect/Queue";
43import * as Schema from "effect/Schema";
44import * as Semaphore from "effect/Semaphore";
45import * as Stream from "effect/Stream";
46import { m } from "../i18n/messages";
47import { projectFaviconCache } from "../assets/projectFaviconCache";
48import { browserThreadTriageOutboxStore } from "./threadTriageOutboxStore";
49
50const DATABASE_NAME = "t3code:connection-runtime";
51const DATABASE_VERSION = 5;
52const CATALOG_STORE_NAME = "catalog";
53const SHELL_STORE_NAME = "shell";
54const THREAD_STORE_NAME = "thread";
55const SERVER_CONFIG_STORE_NAME = "server-config";
56const VCS_REFS_STORE_NAME = "vcs-refs";
57const QUERY_STORE_NAME = "query";
58const QUERY_UPDATED_INDEX_NAME = "environment-updated";
59const QUERY_MAX_ROWS = 256;
60const QUERY_MAX_BYTES = 32 * 1024 * 1024;
61const QUERY_MAX_PAYLOAD_BYTES = 4 * 1024 * 1024;
62const QUERY_MAX_AGE_MS = 30 * 24 * 60 * 60_000;
63// A stats answer saves one row per listed PR, so the bounds index is walked once per batch of
64// saves. Each walk trims a batch below the caps, so the caps hold between walks. The batch count
65// lives in the database, so tabs sharing it share one count.
66const QUERY_PRUNE_BATCH_ROWS = 32;
67const QUERY_PRUNE_BATCH_BYTES = 1024 * 1024;
68const CATALOG_KEY = "document";
69const StoredShellSnapshot = StoredOrchestrationShellSnapshot;
70const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
71const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot;
72const StoredThreadSnapshotJson = Schema.fromJsonString(StoredThreadSnapshot);
73const StoredServerConfig = Schema.Struct({
74 schemaVersion: Schema.Literal(1),
75 environmentId: EnvironmentId,
76 config: ServerConfig,
77});
78const StoredServerConfigJson = Schema.fromJsonString(StoredServerConfig);
79const StoredVcsRefs = Schema.Struct({
80 schemaVersion: Schema.Literal(1),
81 environmentId: EnvironmentId,
82 cwd: Schema.String,
83 refs: VcsListRefsResult,
84});
85const StoredVcsRefsJson = Schema.fromJsonString(StoredVcsRefs);
86const isStoredQuery = Schema.is(
87 Schema.Struct({ environmentId: Schema.String, payload: Schema.String, updatedAt: Schema.Number }),
88);
89const isQueryBatch = Schema.is(Schema.Struct({ rows: Schema.Number, bytes: Schema.Number }));
90const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
91const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson);
92const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
93const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(StoredShellSnapshotJson);
94const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredThreadSnapshotJson);
95const decodeStoredServerConfig = Schema.decodeUnknownEffect(StoredServerConfigJson);
96const encodeStoredServerConfig = Schema.encodeEffect(StoredServerConfigJson);
97const decodeStoredVcsRefs = Schema.decodeUnknownEffect(StoredVcsRefsJson);
98const encodeStoredVcsRefs = Schema.encodeEffect(StoredVcsRefsJson);
99
100const CATALOG_FAILURE = {
101 open: ({ cause }: { cause: string }) =>
102 msg`Could not open the local connection catalog: ${{ cause }}`,
103 read: ({ cause }: { cause: string }) =>
104 msg`Could not read the local connection catalog: ${{ cause }}`,
105 write: ({ cause }: { cause: string }) =>
106 msg`Could not write the local connection catalog: ${{ cause }}`,
107 remove: ({ cause }: { cause: string }) =>
108 msg`Could not remove the local connection catalog: ${{ cause }}`,
109 decode: ({ cause }: { cause: string }) =>
110 msg`Could not decode the local connection catalog: ${{ cause }}`,
111 encode: ({ cause }: { cause: string }) =>
112 msg`Could not encode the local connection catalog: ${{ cause }}`,
113 load: ({ cause }: { cause: string }) =>
114 msg`Could not load the local connection catalog: ${{ cause }}`,
115 save: ({ cause }: { cause: string }) =>
116 msg`Could not save the local connection catalog: ${{ cause }}`,
117 "save pull request routing permissions in": ({ cause }: { cause: string }) =>
118 msg`Could not save pull request routing permissions in the local connection catalog: ${{ cause }}`,
119};
120
121function catalogError(operation: keyof typeof CATALOG_FAILURE, cause: unknown) {
122 return new ConnectionTransientError({
123 reason: "remote-unavailable",
124 detail: m(CATALOG_FAILURE[operation]({ cause: String(cause) })),
125 });
126}
127
128const PERSISTENCE_FAILURE = {
129 "list-targets": ({ cause }: { cause: string }) => msg`Could not list targets: ${{ cause }}`,
130 "list-disabled-targets": ({ cause }: { cause: string }) =>
131 msg`Could not list disabled targets: ${{ cause }}`,
132 "register-connection": ({ cause }: { cause: string }) =>
133 msg`Could not register connection: ${{ cause }}`,
134 "set-connection-routes": ({ cause }: { cause: string }) =>
135 msg`Could not set connection routes: ${{ cause }}`,
136 "remove-connection": ({ cause }: { cause: string }) =>
137 msg`Could not remove connection: ${{ cause }}`,
138 "set-connection-enabled": ({ cause }: { cause: string }) =>
139 msg`Could not set connection enabled: ${{ cause }}`,
140 "load-shell": ({ cause }: { cause: string }) => msg`Could not load shell: ${{ cause }}`,
141 "save-shell": ({ cause }: { cause: string }) => msg`Could not save shell: ${{ cause }}`,
142 "load-thread": ({ cause }: { cause: string }) => msg`Could not load thread: ${{ cause }}`,
143 "save-thread": ({ cause }: { cause: string }) => msg`Could not save thread: ${{ cause }}`,
144 "remove-thread": ({ cause }: { cause: string }) => msg`Could not remove thread: ${{ cause }}`,
145 "load-server-config": ({ cause }: { cause: string }) =>
146 msg`Could not load server config: ${{ cause }}`,
147 "save-server-config": ({ cause }: { cause: string }) =>
148 msg`Could not save server config: ${{ cause }}`,
149 "load-vcs-refs": ({ cause }: { cause: string }) => msg`Could not load vcs refs: ${{ cause }}`,
150 "save-vcs-refs": ({ cause }: { cause: string }) => msg`Could not save vcs refs: ${{ cause }}`,
151 "remove-vcs-refs": ({ cause }: { cause: string }) => msg`Could not remove vcs refs: ${{ cause }}`,
152 "clear-vcs-refs": ({ cause }: { cause: string }) => msg`Could not clear vcs refs: ${{ cause }}`,
153 "clear-environment": ({ cause }: { cause: string }) =>
154 msg`Could not clear environment: ${{ cause }}`,
155};
156
157function persistenceError(operation: keyof typeof PERSISTENCE_FAILURE, cause: unknown) {
158 return new Persistence.ConnectionPersistenceError({
159 operation,
160 message: m(PERSISTENCE_FAILURE[operation]({ cause: String(cause) })),
161 });
162}
163
164const openDatabase = Effect.fn("web.connectionStorage.openDatabase")(function* () {
165 return yield* Effect.callback<IDBDatabase, ConnectionTransientError>((resume) => {
166 if (typeof indexedDB === "undefined") {
167 resume(
168 Effect.fail(
169 catalogError("open", m(msg("IndexedDB is unavailable in this browser context."))),
170 ),
171 );
172 return;
173 }
174 try {
175 const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
176 request.addEventListener("upgradeneeded", () => {
177 if (!request.result.objectStoreNames.contains(CATALOG_STORE_NAME)) {
178 request.result.createObjectStore(CATALOG_STORE_NAME);
179 }
180 if (!request.result.objectStoreNames.contains(SHELL_STORE_NAME)) {
181 request.result.createObjectStore(SHELL_STORE_NAME);
182 }
183 if (!request.result.objectStoreNames.contains(THREAD_STORE_NAME)) {
184 request.result.createObjectStore(THREAD_STORE_NAME);
185 }
186 if (!request.result.objectStoreNames.contains(SERVER_CONFIG_STORE_NAME)) {
187 request.result.createObjectStore(SERVER_CONFIG_STORE_NAME);
188 }
189 if (!request.result.objectStoreNames.contains(VCS_REFS_STORE_NAME)) {
190 request.result.createObjectStore(VCS_REFS_STORE_NAME);
191 }
192 if (!request.result.objectStoreNames.contains(QUERY_STORE_NAME)) {
193 request.result
194 .createObjectStore(QUERY_STORE_NAME)
195 .createIndex(QUERY_UPDATED_INDEX_NAME, ["environmentId", "updatedAt", "bytes"]);
196 }
197 });
198 request.addEventListener("error", () => {
199 resume(
200 Effect.fail(catalogError("open", request.error ?? m(msg("Unknown IndexedDB error")))),
201 );
202 });
203 request.addEventListener("success", () => {
204 resume(Effect.succeed(request.result));
205 });
206 } catch (cause) {
207 resume(Effect.fail(catalogError("open", cause)));
208 }
209 });
210});
211
212interface DatabaseHandle {
213 readonly get: Effect.Effect<IDBDatabase, ConnectionTransientError>;
214 readonly invalidate: (database: IDBDatabase) => Effect.Effect<void>;
215}
216
217const makeDatabaseHandle = Effect.fn("web.connectionStorage.makeDatabaseHandle")(function* () {
218 const lock = yield* Semaphore.make(1);
219 let current: IDBDatabase | null = null;
220 const forget = (database: IDBDatabase) => {
221 if (current === database) current = null;
222 };
223 const get = Effect.suspend(() =>
224 current !== null
225 ? Effect.succeed(current)
226 : lock.withPermits(1)(
227 Effect.gen(function* () {
228 if (current !== null) return current;
229 const opened = yield* openDatabase();
230 current = opened;
231 opened.addEventListener("close", () => forget(opened));
232 // Another tab upgrading the schema waits on this connection.
233 opened.addEventListener("versionchange", () => {
234 forget(opened);
235 opened.close();
236 });
237 return opened;
238 }),
239 ),
240 );
241 const close = lock.withPermits(1)(
242 Effect.sync(() => {
243 current?.close();
244 current = null;
245 }),
246 );
247 const handle: DatabaseHandle = {
248 get,
249 invalidate: (database) => Effect.sync(() => forget(database)),
250 };
251 return { handle, close };
252});
253
254// Browsers can omit close events; retry InvalidStateError with a fresh connection.
255function withDatabase<A>(
256 database: DatabaseHandle,
257 use: (opened: IDBDatabase) => Effect.Effect<A, ConnectionTransientError>,
258) {
259 const closedConnection = Symbol("closedConnection");
260 const attempt = Effect.flatMap(database.get, (opened) =>
261 use(opened).pipe(
262 Effect.catchIf(
263 (error) => error.detail.includes("InvalidStateError"),
264 (error) =>
265 database
266 .invalidate(opened)
267 .pipe(Effect.andThen(Effect.fail({ [closedConnection]: error } as const))),
268 ),
269 ),
270 );
271 return attempt.pipe(
272 Effect.catchIf(
273 (error): error is { readonly [closedConnection]: ConnectionTransientError } =>
274 closedConnection in error,
275 () => Effect.flatMap(database.get, use),
276 ),
277 );
278}
279
280function readDatabaseValueOnConnection(database: IDBDatabase, storeName: string, key: IDBValidKey) {
281 return Effect.callback<unknown, ConnectionTransientError>((resume) => {
282 try {
283 const request = database.transaction(storeName, "readonly").objectStore(storeName).get(key);
284 request.addEventListener("error", () => {
285 resume(
286 Effect.fail(
287 catalogError("read", request.error ?? m(msg("Unknown IndexedDB read error"))),
288 ),
289 );
290 });
291 request.addEventListener("success", () => {
292 resume(Effect.succeed(request.result));
293 });
294 } catch (cause) {
295 resume(Effect.fail(catalogError("read", cause)));
296 }
297 }).pipe(Effect.withSpan("web.connectionStorage.readDatabaseValue"));
298}
299
300function writeDatabaseValueOnConnection(
301 database: IDBDatabase,
302 storeName: string,
303 key: IDBValidKey,
304 value: unknown,
305) {
306 return Effect.callback<void, ConnectionTransientError>((resume) => {
307 try {
308 const transaction = database.transaction(storeName, "readwrite");
309 // Commit failures can fire abort without error; every failed write fires abort.
310 transaction.addEventListener("abort", () => {
311 resume(
312 Effect.fail(
313 catalogError("write", transaction.error ?? m(msg("Unknown IndexedDB write error"))),
314 ),
315 );
316 });
317 transaction.addEventListener("complete", () => {
318 resume(Effect.void);
319 });
320 transaction.objectStore(storeName).put(value, key);
321 } catch (cause) {
322 resume(Effect.fail(catalogError("write", cause)));
323 }
324 }).pipe(Effect.withSpan("web.connectionStorage.writeDatabaseValue"));
325}
326
327function removeDatabaseValueOnConnection(
328 database: IDBDatabase,
329 storeName: string,
330 key: IDBValidKey,
331) {
332 return Effect.callback<void, ConnectionTransientError>((resume) => {
333 try {
334 const transaction = database.transaction(storeName, "readwrite");
335 transaction.addEventListener("abort", () => {
336 resume(
337 Effect.fail(
338 catalogError("remove", transaction.error ?? m(msg("Unknown IndexedDB remove error"))),
339 ),
340 );
341 });
342 transaction.addEventListener("complete", () => {
343 resume(Effect.void);
344 });
345 transaction.objectStore(storeName).delete(key);
346 } catch (cause) {
347 resume(Effect.fail(catalogError("remove", cause)));
348 }
349 }).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValue"));
350}
351
352function removeDatabaseValuesInRangeOnConnection(
353 database: IDBDatabase,
354 storeName: string,
355 range: IDBKeyRange,
356) {
357 return Effect.callback<void, ConnectionTransientError>((resume) => {
358 try {
359 const transaction = database.transaction(storeName, "readwrite");
360 transaction.addEventListener("abort", () => {
361 resume(
362 Effect.fail(
363 catalogError("remove", transaction.error ?? m(msg("Unknown IndexedDB cursor error"))),
364 ),
365 );
366 });
367 transaction.addEventListener("complete", () => {
368 resume(Effect.void);
369 });
370 const request = transaction.objectStore(storeName).openCursor(range);
371 request.addEventListener("error", () => {
372 resume(
373 Effect.fail(
374 catalogError("remove", request.error ?? m(msg("Unknown IndexedDB cursor error"))),
375 ),
376 );
377 });
378 request.addEventListener("success", () => {
379 const cursor = request.result;
380 if (cursor === null) {
381 return;
382 }
383 try {
384 cursor.delete();
385 cursor.continue();
386 } catch (cause) {
387 resume(Effect.fail(catalogError("remove", cause)));
388 }
389 });
390 } catch (cause) {
391 resume(Effect.fail(catalogError("remove", cause)));
392 }
393 }).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValuesInRange"));
394}
395
396// Mirrors mobile's pull-request cache bounds, per environment.
397function saveQueryOnConnection(
398 database: IDBDatabase,
399 environmentId: EnvironmentId,
400 key: string,
401 payload: string,
402 updatedAt: number,
403) {
404 return Effect.callback<void, ConnectionTransientError>((resume) => {
405 try {
406 const bytes = new TextEncoder().encode(payload).length;
407 const transaction = database.transaction(QUERY_STORE_NAME, "readwrite");
408 transaction.addEventListener("abort", () => {
409 resume(
410 Effect.fail(
411 catalogError("write", transaction.error ?? m(msg("Unknown IndexedDB write error"))),
412 ),
413 );
414 });
415 transaction.addEventListener("complete", () => {
416 resume(Effect.void);
417 });
418 const store = transaction.objectStore(QUERY_STORE_NAME);
419 // An answer too large to keep must not leave its older copy to paint on the next start.
420 if (bytes > QUERY_MAX_PAYLOAD_BYTES) {
421 store.delete(queryCacheKey(environmentId, key));
422 return;
423 }
424 store.put({ environmentId, payload, updatedAt, bytes }, queryCacheKey(environmentId, key));
425 const batchKey = queryBatchKey(environmentId);
426 const batchRequest = store.get(batchKey);
427 batchRequest.addEventListener("success", () => {
428 const batch: unknown = batchRequest.result;
429 const rows = (isQueryBatch(batch) ? batch.rows : 0) + 1;
430 const written = (isQueryBatch(batch) ? batch.bytes : 0) + bytes;
431 if (
432 isQueryBatch(batch) &&
433 rows < QUERY_PRUNE_BATCH_ROWS &&
434 written < QUERY_PRUNE_BATCH_BYTES
435 ) {
436 store.put({ rows, bytes: written }, batchKey);
437 return;
438 }
439 store.put({ rows: 0, bytes: 0 }, batchKey);
440 const request = store
441 .index(QUERY_UPDATED_INDEX_NAME)
442 .openKeyCursor(IDBKeyRange.bound([environmentId], [environmentId, []]), "prev");
443 let kept = 0;
444 let totalBytes = 0;
445 request.addEventListener("success", () => {
446 const cursor = request.result;
447 if (cursor === null) return;
448 const [, rowUpdatedAt, rowBytes] = cursor.key as [string, number, number];
449 kept += 1;
450 totalBytes += rowBytes;
451 if (
452 kept > QUERY_MAX_ROWS - QUERY_PRUNE_BATCH_ROWS ||
453 totalBytes > QUERY_MAX_BYTES - QUERY_PRUNE_BATCH_BYTES ||
454 rowUpdatedAt < updatedAt - QUERY_MAX_AGE_MS
455 ) {
456 store.delete(cursor.primaryKey);
457 }
458 cursor.continue();
459 });
460 });
461 } catch (cause) {
462 resume(Effect.fail(catalogError("write", cause)));
463 }
464 }).pipe(Effect.withSpan("web.connectionStorage.saveQuery"));
465}
466
467function readDatabaseValue(database: DatabaseHandle, storeName: string, key: IDBValidKey) {
468 return withDatabase(database, (opened) => readDatabaseValueOnConnection(opened, storeName, key));
469}
470
471function writeDatabaseValue(
472 database: DatabaseHandle,
473 storeName: string,
474 key: IDBValidKey,
475 value: unknown,
476) {
477 return withDatabase(database, (opened) =>
478 writeDatabaseValueOnConnection(opened, storeName, key, value),
479 );
480}
481
482function removeDatabaseValue(database: DatabaseHandle, storeName: string, key: IDBValidKey) {
483 return withDatabase(database, (opened) =>
484 removeDatabaseValueOnConnection(opened, storeName, key),
485 );
486}
487
488function removeDatabaseValuesInRange(
489 database: DatabaseHandle,
490 storeName: string,
491 range: IDBKeyRange,
492) {
493 return withDatabase(database, (opened) =>
494 removeDatabaseValuesInRangeOnConnection(opened, storeName, range),
495 );
496}
497
498function threadCacheKey(environmentId: EnvironmentId, threadId: ThreadId) {
499 return `${environmentId}:${threadId}`;
500}
501
502function queryCacheKey(environmentId: EnvironmentId, key: string) {
503 return `${environmentId}:v1:${key}`;
504}
505
506function queryBatchKey(environmentId: EnvironmentId) {
507 return `${environmentId}:batch`;
508}
509
510function vcsRefsCacheKey(environmentId: EnvironmentId, cwd: string) {
511 return `${environmentId}:${cwd}`;
512}
513
514const decodeCatalog = Effect.fn("web.connectionStorage.decodeCatalog")(function* (raw: string) {
515 return yield* decodeConnectionCatalogDocument(raw).pipe(
516 Effect.mapError((cause) => catalogError("decode", cause)),
517 );
518});
519
520const encodeCatalog = Effect.fn("web.connectionStorage.encodeCatalog")(function* (
521 catalog: ConnectionCatalogDocumentType,
522) {
523 return yield* encodeConnectionCatalogDocument(catalog).pipe(
524 Effect.mapError((cause) => catalogError("encode", cause)),
525 );
526});
527
528export interface CatalogBackend {
529 readonly read: Effect.Effect<string | null, ConnectionTransientError>;
530 readonly write: (
531 raw: string,
532 sshTunnelClaim?: string,
533 ) => Effect.Effect<void, ConnectionTransientError>;
534 readonly quarantine?: (raw: string) => Effect.Effect<void, ConnectionTransientError>;
535}
536
537export function makeCatalogBackend(database: DatabaseHandle): CatalogBackend {
538 const bridge = window.desktopBridge;
539 if (bridge !== undefined) {
540 return {
541 read: Effect.tryPromise({
542 try: () => bridge.getConnectionCatalog(),
543 catch: (cause) => catalogError("load", cause),
544 }),
545 write: (raw, sshTunnelClaim) =>
546 Effect.tryPromise({
547 try: () => bridge.setConnectionCatalog(raw, sshTunnelClaim),
548 catch: (cause) => catalogError("save", cause),
549 }).pipe(
550 Effect.flatMap((stored) =>
551 stored
552 ? Effect.void
553 : Effect.fail(
554 catalogError(
555 "save",
556 m(msg("Desktop secure storage is unavailable in this system context.")),
557 ),
558 ),
559 ),
560 ),
561 };
562 }
563
564 return {
565 read: readDatabaseValue(database, CATALOG_STORE_NAME, CATALOG_KEY).pipe(
566 Effect.map((value) => (typeof value === "string" ? value : null)),
567 ),
568 write: (raw) => writeDatabaseValue(database, CATALOG_STORE_NAME, CATALOG_KEY, raw),
569 quarantine: (raw) =>
570 writeDatabaseValue(database, CATALOG_STORE_NAME, `${CATALOG_KEY}:corrupt:${Date.now()}`, raw),
571 };
572}
573
574interface CatalogStore {
575 readonly read: Effect.Effect<ConnectionCatalogDocumentType, ConnectionTransientError>;
576 readonly update: (
577 transform: (catalog: ConnectionCatalogDocumentType) => ConnectionCatalogDocumentType,
578 sshTunnelClaim?: string,
579 ) => Effect.Effect<void, ConnectionTransientError>;
580}
581
582export const makeCatalogStore = Effect.fn("web.connectionStorage.makeCatalogStore")(function* (
583 backend: CatalogBackend,
584) {
585 const state = yield* Ref.make<Option.Option<ConnectionCatalogDocumentType>>(Option.none());
586 const lock = yield* Semaphore.make(1);
587
588 const loadUnlocked = Effect.fn("web.connectionStorage.loadCatalog")(function* () {
589 const cached = yield* Ref.get(state);
590 if (Option.isSome(cached)) {
591 return cached.value;
592 }
593 const raw = yield* backend.read;
594 let catalog = EMPTY_CONNECTION_CATALOG_DOCUMENT;
595 if (raw !== null && raw.trim() !== "") {
596 catalog = yield* decodeCatalog(raw).pipe(
597 Effect.catch((error) =>
598 Effect.gen(function* () {
599 yield* Effect.logWarning("Discarding a corrupt web connection catalog.", {
600 error: error.message,
601 });
602 if (backend.quarantine !== undefined) {
603 yield* backend.quarantine(raw).pipe(
604 Effect.catch((cause) =>
605 Effect.logWarning("Could not quarantine the corrupt web connection catalog.", {
606 error: cause.message,
607 }),
608 ),
609 );
610 }
611 const encoded = yield* encodeCatalog(EMPTY_CONNECTION_CATALOG_DOCUMENT);
612 yield* backend.write(encoded).pipe(
613 Effect.catch((cause) =>
614 Effect.logWarning("Could not persist the recovered web connection catalog.", {
615 error: cause.message,
616 }),
617 ),
618 );
619 return EMPTY_CONNECTION_CATALOG_DOCUMENT;
620 }),
621 ),
622 );
623 }
624 yield* Ref.set(state, Option.some(catalog));
625 return catalog;
626 });
627
628 const read = lock.withPermits(1)(loadUnlocked());
629 const update: CatalogStore["update"] = Effect.fn("web.connectionStorage.updateCatalog")(
630 function* (transform, sshTunnelClaim) {
631 yield* lock.withPermits(1)(
632 Effect.gen(function* () {
633 const next = transform(yield* loadUnlocked());
634 yield* backend.write(yield* encodeCatalog(next), sshTunnelClaim);
635 yield* Ref.set(state, Option.some(next));
636 }),
637 );
638 },
639 );
640
641 return { read, update } satisfies CatalogStore;
642});
643
644// The stored names predate the rename and stay, so a tab still on an older version and an
645// updated one read and revoke the same grants.
646const PULL_REQUEST_ROUTING_KEY_PREFIX = "t3code:github-routing:";
647const PULL_REQUEST_ROUTING_CHANGED = "t3code:github-routing-changed";
648const isStoredPullRequestRoutingPermission = Schema.is(StoredPullRequestRoutingPermission);
649const encodeStoredPullRequestRoutingPermission = Schema.encodeSync(
650 Schema.fromJsonString(StoredPullRequestRoutingPermission),
651);
652
653/** Each grant has its own key so stale tabs and unrelated catalog saves cannot restore trust. */
654export function makeBrowserPullRequestRoutingPermissions(
655 browser: Pick<Window, "localStorage"> & EventTarget = window,
656) {
657 const read = (key: string): StoredPullRequestRoutingPermission | null => {
658 try {
659 const raw = browser.localStorage.getItem(key);
660 const value: unknown = raw === null ? null : JSON.parse(raw);
661 return isStoredPullRequestRoutingPermission(value) &&
662 key === `${PULL_REQUEST_ROUTING_KEY_PREFIX}${value.environmentId}`
663 ? value
664 : null;
665 } catch {
666 return null;
667 }
668 };
669 const readAll = (): ReadonlyArray<StoredPullRequestRoutingPermission> => {
670 try {
671 const values: StoredPullRequestRoutingPermission[] = [];
672 const storage = browser.localStorage;
673 for (let index = 0; index < storage.length; index++) {
674 const key = storage.key(index);
675 if (key?.startsWith(PULL_REQUEST_ROUTING_KEY_PREFIX)) {
676 const value = read(key);
677 if (value !== null) values.push(value);
678 }
679 }
680 return values;
681 } catch {
682 return [];
683 }
684 };
685 const write = (environmentId: EnvironmentId, value: StoredPullRequestRoutingPermission | null) =>
686 Effect.try({
687 try: () => {
688 const key = `${PULL_REQUEST_ROUTING_KEY_PREFIX}${environmentId}`;
689 if (value === null) browser.localStorage.removeItem(key);
690 else browser.localStorage.setItem(key, encodeStoredPullRequestRoutingPermission(value));
691 browser.dispatchEvent(new Event(PULL_REQUEST_ROUTING_CHANGED));
692 },
693 catch: (cause) => catalogError("save pull request routing permissions in", cause),
694 });
695 return PullRequestRoutingPermissions.of({
696 get: Effect.fn("PullRequestRoutingPermissions.get")(function (entry) {
697 return Effect.sync(() => {
698 const value = read(`${PULL_REQUEST_ROUTING_KEY_PREFIX}${entry.target.environmentId}`);
699 return pullRequestRoutingPermissionFor(entry, value === null ? [] : [value]);
700 });
701 }),
702 changes: Stream.callback<ReadonlyArray<StoredPullRequestRoutingPermission>>((queue) =>
703 Effect.acquireRelease(
704 Effect.sync(() => {
705 const listener = (event: Event) => {
706 if (event.type === "storage") {
707 const key = (event as StorageEvent).key;
708 if (key !== null && !key?.startsWith(PULL_REQUEST_ROUTING_KEY_PREFIX)) return;
709 }
710 Queue.offerUnsafe(queue, readAll());
711 };
712 browser.addEventListener("storage", listener);
713 browser.addEventListener(PULL_REQUEST_ROUTING_CHANGED, listener);
714 Queue.offerUnsafe(queue, readAll());
715 return listener;
716 }),
717 (listener) =>
718 Effect.sync(() => {
719 browser.removeEventListener("storage", listener);
720 browser.removeEventListener(PULL_REQUEST_ROUTING_CHANGED, listener);
721 }),
722 ).pipe(Effect.asVoid),
723 ),
724 set: Effect.fn("PullRequestRoutingPermissions.set")(function* (entry, permission) {
725 const connectionKey = pullRequestRoutingConnectionKey(entry);
726 if (connectionKey === null)
727 return yield* new ConnectionBlockedError({
728 reason: "configuration",
729 detail: m(msg("This environment does not have a saved connection endpoint.")),
730 });
731 return yield* write(
732 entry.target.environmentId,
733 permission === "off"
734 ? null
735 : {
736 environmentId: entry.target.environmentId,
737 connectionKey,
738 permission,
739 },
740 );
741 }),
742 forget: Effect.fn("PullRequestRoutingPermissions.forget")(function (environmentId) {
743 return write(environmentId, null);
744 }),
745 });
746}
747
748// MessageChannel yields without nested-timer clamping or background throttling.
749const yieldToBrowserTask = Effect.callback<void>((resume) => {
750 const { port1, port2 } = new MessageChannel();
751 port1.addEventListener(
752 "message",
753 () => {
754 port1.close();
755 resume(Effect.void);
756 },
757 { once: true },
758 );
759 port1.start();
760 port2.postMessage(null);
761 // A closed port delivers nothing, so interruption needs no listener bookkeeping.
762 return Effect.sync(() => port1.close());
763});
764
765export const layer = Layer.effectContext(
766 Effect.gen(function* () {
767 const { handle: database } = yield* Effect.acquireRelease(
768 makeDatabaseHandle(),
769 (owned) => owned.close,
770 );
771 const catalog = yield* makeCatalogStore(makeCatalogBackend(database));
772 const pullRequestRoutingPermissions = makeBrowserPullRequestRoutingPermissions();
773 // Remembers each thread row's encoding, so a save only encodes rows that changed.
774 const encodeStoredShellSnapshot = makeStoredShellSnapshotEncoder({
775 yieldToHost: yieldToBrowserTask,
776 });
777 const encodeStoredThreadSnapshot = makeStoredThreadSnapshotEncoder({
778 format: "full",
779 yieldToHost: yieldToBrowserTask,
780 });
781 const threadWriteOrder = makeThreadCacheWriteOrder();
782
783 const targetStore = Persistence.ConnectionTargetStore.of({
784 list: catalog.read.pipe(
785 Effect.map((document) => document.targets),
786 Effect.mapError((cause) => persistenceError("list-targets", cause)),
787 ),
788 listDisabled: catalog.read.pipe(
789 Effect.map((document) => document.disabledEnvironmentIds),
790 Effect.mapError((cause) => persistenceError("list-disabled-targets", cause)),
791 ),
792 });
793 const registrationStore = Persistence.ConnectionRegistrationStore.of({
794 register: Effect.fn("Persistence.ConnectionRegistrationStore.register")(
795 function (registration, routes, sshTunnelClaim) {
796 return catalog
797 .update(
798 (document) => registerConnectionInCatalog(document, registration, routes),
799 sshTunnelClaim,
800 )
801 .pipe(Effect.mapError((cause) => persistenceError("register-connection", cause)));
802 },
803 ),
804 setRoutes: Effect.fn("Persistence.ConnectionRegistrationStore.setRoutes")(
805 function (environmentId, routes) {
806 return catalog
807 .update((document) => setRoutesInCatalog(document, environmentId, routes))
808 .pipe(Effect.mapError((cause) => persistenceError("set-connection-routes", cause)));
809 },
810 ),
811 remove: Effect.fn("Persistence.ConnectionRegistrationStore.remove")(function (environmentId) {
812 return catalog
813 .update((document) => removeConnectionFromCatalog(document, environmentId))
814 .pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause)));
815 }),
816 setEnabled: Effect.fn("Persistence.ConnectionRegistrationStore.setEnabled")(
817 function (environmentId, enabled) {
818 return catalog
819 .update((document) => setConnectionEnabledInCatalog(document, environmentId, enabled))
820 .pipe(Effect.mapError((cause) => persistenceError("set-connection-enabled", cause)));
821 },
822 ),
823 });
824 const profileStore = ProfileStore.make({
825 get: (connectionId) =>
826 catalog.read.pipe(
827 Effect.map((document) =>
828 Option.fromUndefinedOr(
829 document.profiles.find((profile) => profile.connectionId === connectionId),
830 ),
831 ),
832 ),
833 put: (profile) =>
834 catalog.update((document) => ({
835 ...document,
836 profiles: replaceCatalogValue(document.profiles, (value) => value.connectionId, profile),
837 })),
838 remove: (connectionId) =>
839 catalog.update((document) => ({
840 ...document,
841 profiles: removeCatalogValue(
842 document.profiles,
843 (value) => value.connectionId,
844 connectionId,
845 ),
846 })),
847 });
848 const credentialStore = CredentialStore.make({
849 get: (connectionId) =>
850 catalog.read.pipe(
851 Effect.map((document) =>
852 Option.fromUndefinedOr(
853 document.credentials.find((entry) => entry.connectionId === connectionId)?.credential,
854 ),
855 ),
856 ),
857 put: (connectionId, credential) =>
858 catalog.update((document) => ({
859 ...document,
860 credentials: replaceCatalogValue(document.credentials, (value) => value.connectionId, {
861 connectionId,
862 credential,
863 }),
864 })),
865 remove: (connectionId) =>
866 catalog.update((document) => ({
867 ...document,
868 credentials: removeCatalogValue(
869 document.credentials,
870 (value) => value.connectionId,
871 connectionId,
872 ),
873 })),
874 });
875 const remoteTokenStore = TokenStore.make({
876 get: (environmentId) =>
877 catalog.read.pipe(
878 Effect.map((document) =>
879 Option.fromUndefinedOr(
880 document.remoteDpopTokens.find((token) => token.environmentId === environmentId),
881 ),
882 ),
883 ),
884 put: (token) => catalog.update((document) => putRemoteDpopTokenInCatalog(document, token)),
885 remove: (environmentId) =>
886 catalog.update((document) => ({
887 ...document,
888 remoteDpopTokens: removeCatalogValue(
889 document.remoteDpopTokens,
890 (value) => value.environmentId,
891 environmentId,
892 ),
893 })),
894 });
895 const cacheStore = Persistence.EnvironmentCacheStore.of({
896 loadShell: Effect.fn("Persistence.EnvironmentCacheStore.loadShell")(function (environmentId) {
897 return readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
898 Effect.tap(() => Effect.promise(() => projectFaviconCache.hydrate())),
899 Effect.flatMap((raw) => {
900 if (typeof raw !== "string") {
901 return Effect.succeedNone;
902 }
903 return decodeOrDiscardOrchestrationCache(
904 decodeStoredShellSnapshot(raw).pipe(
905 Effect.mapError((cause) => persistenceError("load-shell", cause)),
906 Effect.map((stored) =>
907 stored.environmentId === environmentId
908 ? Option.some(
909 stored.origin === undefined
910 ? stored.snapshot
911 : { ...stored.snapshot, origin: stored.origin },
912 )
913 : Option.none(),
914 ),
915 ),
916 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
917 );
918 }),
919 Effect.mapError((cause) => persistenceError("load-shell", cause)),
920 );
921 }),
922 saveShell: Effect.fn("storage.saveShell")(
923 function* (environmentId, snapshot, origin) {
924 const encoded = yield* encodeStoredShellSnapshot({
925 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
926 environmentId,
927 snapshot,
928 ...(origin === undefined ? {} : { origin }),
929 }).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
930 yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
931 },
932 Effect.mapError((cause) =>
933 cause._tag === "ConnectionPersistenceError"
934 ? cause
935 : persistenceError("save-shell", cause),
936 ),
937 ),
938 loadServerConfig: Effect.fn("Persistence.EnvironmentCacheStore.loadServerConfig")(
939 function (environmentId) {
940 return readDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId).pipe(
941 Effect.flatMap((raw) => {
942 if (typeof raw !== "string") {
943 return Effect.succeedNone;
944 }
945 return decodeStoredServerConfig(raw).pipe(
946 Effect.mapError((cause) => persistenceError("load-server-config", cause)),
947 Effect.map((stored) =>
948 stored.environmentId === environmentId
949 ? Option.some(stored.config)
950 : Option.none(),
951 ),
952 );
953 }),
954 Effect.mapError((cause) =>
955 cause._tag === "ConnectionPersistenceError"
956 ? cause
957 : persistenceError("load-server-config", cause),
958 ),
959 );
960 },
961 ),
962 saveServerConfig: Effect.fn("storage.saveServerConfig")(
963 function* (environmentId, config) {
964 const encoded = yield* encodeStoredServerConfig({
965 schemaVersion: 1,
966 environmentId,
967 config,
968 }).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));
969 yield* writeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId, encoded);
970 },
971 Effect.mapError((cause) =>
972 cause._tag === "ConnectionPersistenceError"
973 ? cause
974 : persistenceError("save-server-config", cause),
975 ),
976 ),
977 loadThread: Effect.fn("Persistence.EnvironmentCacheStore.loadThread")(
978 function (environmentId, threadId) {
979 return readDatabaseValue(
980 database,
981 THREAD_STORE_NAME,
982 threadCacheKey(environmentId, threadId),
983 ).pipe(
984 Effect.flatMap((raw) => {
985 if (typeof raw !== "string") {
986 return Effect.succeedNone;
987 }
988 return decodeOrDiscardOrchestrationCache(
989 decodeStoredThreadSnapshot(raw).pipe(
990 Effect.mapError((cause) => persistenceError("load-thread", cause)),
991 Effect.map((stored) =>
992 stored.environmentId === environmentId && stored.threadId === threadId
993 ? Option.some(stored.snapshot)
994 : Option.none(),
995 ),
996 ),
997 removeDatabaseValue(
998 database,
999 THREAD_STORE_NAME,
1000 threadCacheKey(environmentId, threadId),
1001 ),
1002 );
1003 }),
1004 Effect.mapError((cause) => persistenceError("load-thread", cause)),
1005 );
1006 },
1007 ),
1008 saveThread: Effect.fn("storage.saveThread")(
1009 function* (environmentId, snapshot) {
1010 const key = threadCacheKey(environmentId, snapshot.projection.thread.id);
1011 const isLatest = threadWriteOrder.beginSave(environmentId, snapshot.projection.thread.id);
1012 const encoded = yield* encodeStoredThreadSnapshot({
1013 environmentId,
1014 threadId: snapshot.projection.thread.id,
1015 snapshot,
1016 }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
1017 if (!isLatest()) return;
1018 // An older copy of a thread now too large to keep would paint stale on reopen.
1019 yield* Option.match(encoded, {
1020 onNone: () => removeDatabaseValue(database, THREAD_STORE_NAME, key),
1021 onSome: (payload) => writeDatabaseValue(database, THREAD_STORE_NAME, key, payload),
1022 });
1023 },
1024 Effect.mapError((cause) =>
1025 cause._tag === "ConnectionPersistenceError"
1026 ? cause
1027 : persistenceError("save-thread", cause),
1028 ),
1029 ),
1030 loadVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.loadVcsRefs")(
1031 function (environmentId, cwd) {
1032 return readDatabaseValue(
1033 database,
1034 VCS_REFS_STORE_NAME,
1035 vcsRefsCacheKey(environmentId, cwd),
1036 ).pipe(
1037 Effect.flatMap((raw) => {
1038 if (typeof raw !== "string") {
1039 return Effect.succeedNone;
1040 }
1041 return decodeStoredVcsRefs(raw).pipe(
1042 Effect.mapError((cause) => persistenceError("load-vcs-refs", cause)),
1043 Effect.map((stored) =>
1044 stored.environmentId === environmentId && stored.cwd === cwd
1045 ? Option.some(stored.refs)
1046 : Option.none(),
1047 ),
1048 );
1049 }),
1050 Effect.mapError((cause) =>
1051 cause._tag === "ConnectionPersistenceError"
1052 ? cause
1053 : persistenceError("load-vcs-refs", cause),
1054 ),
1055 );
1056 },
1057 ),
1058 saveVcsRefs: Effect.fn("storage.saveVcsRefs")(
1059 function* (environmentId, cwd, refs) {
1060 const encoded = yield* encodeStoredVcsRefs({
1061 schemaVersion: 1,
1062 environmentId,
1063 cwd,
1064 refs,
1065 }).pipe(Effect.mapError((cause) => persistenceError("save-vcs-refs", cause)));
1066 yield* writeDatabaseValue(
1067 database,
1068 VCS_REFS_STORE_NAME,
1069 vcsRefsCacheKey(environmentId, cwd),
1070 encoded,
1071 );
1072 },
1073 Effect.mapError((cause) =>
1074 cause._tag === "ConnectionPersistenceError"
1075 ? cause
1076 : persistenceError("save-vcs-refs", cause),
1077 ),
1078 ),
1079 removeVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.removeVcsRefs")(
1080 function (environmentId, cwd) {
1081 return removeDatabaseValue(
1082 database,
1083 VCS_REFS_STORE_NAME,
1084 vcsRefsCacheKey(environmentId, cwd),
1085 ).pipe(Effect.mapError((cause) => persistenceError("remove-vcs-refs", cause)));
1086 },
1087 ),
1088 clearVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.clearVcsRefs")(
1089 function (environmentId) {
1090 return removeDatabaseValuesInRange(
1091 database,
1092 VCS_REFS_STORE_NAME,
1093 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1094 ).pipe(Effect.mapError((cause) => persistenceError("clear-vcs-refs", cause)));
1095 },
1096 ),
1097 removeThread: Effect.fn("Persistence.EnvironmentCacheStore.removeThread")(
1098 function (environmentId, threadId) {
1099 threadWriteOrder.removeThread(environmentId, threadId);
1100 return removeDatabaseValue(
1101 database,
1102 THREAD_STORE_NAME,
1103 threadCacheKey(environmentId, threadId),
1104 ).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause)));
1105 },
1106 ),
1107 clear: Effect.fn("Persistence.EnvironmentCacheStore.clear")(function (environmentId) {
1108 threadWriteOrder.clearEnvironment(environmentId);
1109 return Effect.all(
1110 [
1111 Effect.promise(() => projectFaviconCache.clearEnvironment(environmentId)),
1112 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
1113 removeDatabaseValuesInRange(
1114 database,
1115 THREAD_STORE_NAME,
1116 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1117 ),
1118 removeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId),
1119 removeDatabaseValuesInRange(
1120 database,
1121 VCS_REFS_STORE_NAME,
1122 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1123 ),
1124 removeDatabaseValuesInRange(
1125 database,
1126 QUERY_STORE_NAME,
1127 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1128 ),
1129 ],
1130 { concurrency: "unbounded", discard: true },
1131 ).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause)));
1132 }),
1133 });
1134
1135 const queryStore: NonNullable<typeof EnvironmentQueryStore.Service> = {
1136 load: Effect.fn("EnvironmentQueryStore.load")(
1137 function* (environmentId, key) {
1138 const stored = yield* readDatabaseValue(
1139 database,
1140 QUERY_STORE_NAME,
1141 queryCacheKey(environmentId, key),
1142 );
1143 const now = yield* Clock.currentTimeMillis;
1144 return isStoredQuery(stored) &&
1145 stored.environmentId === environmentId &&
1146 stored.updatedAt >= now - QUERY_MAX_AGE_MS
1147 ? Option.some(stored.payload)
1148 : Option.none();
1149 },
1150 Effect.catch(() => Effect.succeedNone),
1151 ),
1152 save: (environmentId, key, payload) =>
1153 Clock.currentTimeMillis.pipe(
1154 Effect.flatMap((now) =>
1155 withDatabase(database, (opened) =>
1156 saveQueryOnConnection(opened, environmentId, key, payload, now),
1157 ),
1158 ),
1159 Effect.catch(() => Effect.logWarning("Offline query database save failed")),
1160 ),
1161 };
1162
1163 return Context.make(Persistence.ConnectionTargetStore, targetStore).pipe(
1164 Context.add(PullRequestRoutingPermissions, pullRequestRoutingPermissions),
1165 Context.add(Persistence.ConnectionRegistrationStore, registrationStore),
1166 Context.add(ProfileStore.ConnectionProfileStore, profileStore),
1167 Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
1168 Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
1169 Context.add(Persistence.EnvironmentCacheStore, cacheStore),
1170 Context.add(ThreadTriageOutboxStore, browserThreadTriageOutboxStore),
1171 Context.add(EnvironmentQueryStore, queryStore),
1172 );
1173 }),
1174);