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