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