Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

storage.ts

1,106 lines41.1 KB

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 });
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 });
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>;
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 );
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"));
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"));
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"));
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"));
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"));
419​
420function readDatabaseValue(database: DatabaseHandle, storeName: string, key: IDBValidKey) {
421 return withDatabase(database, (opened) => readDatabaseValueOnConnection(opened, storeName, key));
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 );
434​
435function removeDatabaseValue(database: DatabaseHandle, storeName: string, key: IDBValidKey) {
436 return withDatabase(database, (opened) =>
437 removeDatabaseValueOnConnection(opened, storeName, key),
438 );
440​
441function removeDatabaseValuesInRange(
442 database: DatabaseHandle,
443 storeName: string,
444 range: IDBKeyRange,
445) {
446 return withDatabase(database, (opened) =>
447 removeDatabaseValuesInRangeOnConnection(opened, storeName, range),
448 );
450​
451function threadCacheKey(environmentId: EnvironmentId, threadId: ThreadId) {
452 return `${environmentId}:${threadId}`;
454​
455function queryCacheKey(environmentId: EnvironmentId, key: string) {
456 return `${environmentId}:v1:${key}`;
458​
459function queryBatchKey(environmentId: EnvironmentId) {
460 return `${environmentId}:batch`;
462​
463function vcsRefsCacheKey(environmentId: EnvironmentId, cwd: string) {
464 return `${environmentId}:${cwd}`;
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>;
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 };
523​
524interface CatalogStore {
525 readonly read: Effect.Effect<ConnectionCatalogDocumentType, ConnectionTransientError>;
526 readonly update: (
527 transform: (catalog: ConnectionCatalogDocumentType) => ConnectionCatalogDocumentType,
528 ) => Effect.Effect<void, ConnectionTransientError>;
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 });
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(stored.snapshot)
850 : Option.none(),
851 ),
852 ),
853 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
854 );
855 }),
856 Effect.mapError((cause) => persistenceError("load-shell", cause)),
857 );
858 }),
859 saveShell: Effect.fn("storage.saveShell")(
860 function* (environmentId, snapshot) {
861 const encoded = yield* encodeStoredShellSnapshot({
862 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
863 environmentId,
864 snapshot,
865 }).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
866 yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
867 },
868 Effect.mapError((cause) =>
869 cause._tag === "ConnectionPersistenceError"
870 ? cause
871 : persistenceError("save-shell", cause),
872 ),
873 ),
874 loadServerConfig: Effect.fn("Persistence.EnvironmentCacheStore.loadServerConfig")(
875 function (environmentId) {
876 return readDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId).pipe(
877 Effect.flatMap((raw) => {
878 if (typeof raw !== "string") {
879 return Effect.succeedNone;
880 }
881 return decodeStoredServerConfig(raw).pipe(
882 Effect.mapError((cause) => persistenceError("load-server-config", cause)),
883 Effect.map((stored) =>
884 stored.environmentId === environmentId
885 ? Option.some(stored.config)
886 : Option.none(),
887 ),
888 );
889 }),
890 Effect.mapError((cause) =>
891 cause._tag === "ConnectionPersistenceError"
892 ? cause
893 : persistenceError("load-server-config", cause),
894 ),
895 );
896 },
897 ),
898 saveServerConfig: Effect.fn("storage.saveServerConfig")(
899 function* (environmentId, config) {
900 const encoded = yield* encodeStoredServerConfig({
901 schemaVersion: 1,
902 environmentId,
903 config,
904 }).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));
905 yield* writeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId, encoded);
906 },
907 Effect.mapError((cause) =>
908 cause._tag === "ConnectionPersistenceError"
909 ? cause
910 : persistenceError("save-server-config", cause),
911 ),
912 ),
913 loadThread: Effect.fn("Persistence.EnvironmentCacheStore.loadThread")(
914 function (environmentId, threadId) {
915 return readDatabaseValue(
916 database,
917 THREAD_STORE_NAME,
918 threadCacheKey(environmentId, threadId),
919 ).pipe(
920 Effect.flatMap((raw) => {
921 if (typeof raw !== "string") {
922 return Effect.succeedNone;
923 }
924 return decodeOrDiscardOrchestrationCache(
925 decodeStoredThreadSnapshot(raw).pipe(
926 Effect.mapError((cause) => persistenceError("load-thread", cause)),
927 Effect.map((stored) =>
928 stored.environmentId === environmentId && stored.threadId === threadId
929 ? Option.some(stored.snapshot)
930 : Option.none(),
931 ),
932 ),
933 removeDatabaseValue(
934 database,
935 THREAD_STORE_NAME,
936 threadCacheKey(environmentId, threadId),
937 ),
938 );
939 }),
940 Effect.mapError((cause) => persistenceError("load-thread", cause)),
941 );
942 },
943 ),
944 saveThread: Effect.fn("storage.saveThread")(
945 function* (environmentId, snapshot) {
946 const encoded = yield* encodeStoredThreadSnapshot({
947 schemaVersion: ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION,
948 environmentId,
949 threadId: snapshot.projection.thread.id,
950 snapshot,
951 }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
952 yield* writeDatabaseValue(
953 database,
954 THREAD_STORE_NAME,
955 threadCacheKey(environmentId, snapshot.projection.thread.id),
956 encoded,
957 );
958 },
959 Effect.mapError((cause) =>
960 cause._tag === "ConnectionPersistenceError"
961 ? cause
962 : persistenceError("save-thread", cause),
963 ),
964 ),
965 loadVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.loadVcsRefs")(
966 function (environmentId, cwd) {
967 return readDatabaseValue(
968 database,
969 VCS_REFS_STORE_NAME,
970 vcsRefsCacheKey(environmentId, cwd),
971 ).pipe(
972 Effect.flatMap((raw) => {
973 if (typeof raw !== "string") {
974 return Effect.succeedNone;
975 }
976 return decodeStoredVcsRefs(raw).pipe(
977 Effect.mapError((cause) => persistenceError("load-vcs-refs", cause)),
978 Effect.map((stored) =>
979 stored.environmentId === environmentId && stored.cwd === cwd
980 ? Option.some(stored.refs)
981 : Option.none(),
982 ),
983 );
984 }),
985 Effect.mapError((cause) =>
986 cause._tag === "ConnectionPersistenceError"
987 ? cause
988 : persistenceError("load-vcs-refs", cause),
989 ),
990 );
991 },
992 ),
993 saveVcsRefs: Effect.fn("storage.saveVcsRefs")(
994 function* (environmentId, cwd, refs) {
995 const encoded = yield* encodeStoredVcsRefs({
996 schemaVersion: 1,
997 environmentId,
998 cwd,
999 refs,
1000 }).pipe(Effect.mapError((cause) => persistenceError("save-vcs-refs", cause)));
1001 yield* writeDatabaseValue(
1002 database,
1003 VCS_REFS_STORE_NAME,
1004 vcsRefsCacheKey(environmentId, cwd),
1005 encoded,
1006 );
1007 },
1008 Effect.mapError((cause) =>
1009 cause._tag === "ConnectionPersistenceError"
1010 ? cause
1011 : persistenceError("save-vcs-refs", cause),
1012 ),
1013 ),
1014 removeVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.removeVcsRefs")(
1015 function (environmentId, cwd) {
1016 return removeDatabaseValue(
1017 database,
1018 VCS_REFS_STORE_NAME,
1019 vcsRefsCacheKey(environmentId, cwd),
1020 ).pipe(Effect.mapError((cause) => persistenceError("remove-vcs-refs", cause)));
1021 },
1022 ),
1023 clearVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.clearVcsRefs")(
1024 function (environmentId) {
1025 return removeDatabaseValuesInRange(
1026 database,
1027 VCS_REFS_STORE_NAME,
1028 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1029 ).pipe(Effect.mapError((cause) => persistenceError("clear-vcs-refs", cause)));
1030 },
1031 ),
1032 removeThread: Effect.fn("Persistence.EnvironmentCacheStore.removeThread")(
1033 function (environmentId, threadId) {
1034 return removeDatabaseValue(
1035 database,
1036 THREAD_STORE_NAME,
1037 threadCacheKey(environmentId, threadId),
1038 ).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause)));
1039 },
1040 ),
1041 clear: Effect.fn("Persistence.EnvironmentCacheStore.clear")(function (environmentId) {
1042 return Effect.all(
1044 Effect.promise(() => projectFaviconCache.clearEnvironment(environmentId)),
1045 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
1046 removeDatabaseValuesInRange(
1047 database,
1048 THREAD_STORE_NAME,
1049 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1050 ),
1051 removeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId),
1052 removeDatabaseValuesInRange(
1053 database,
1054 VCS_REFS_STORE_NAME,
1055 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1056 ),
1057 removeDatabaseValuesInRange(
1058 database,
1059 QUERY_STORE_NAME,
1060 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1061 ),
1062 ],
1063 { concurrency: "unbounded", discard: true },
1064 ).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause)));
1065 }),
1066 });
1067​
1068 const queryStore: NonNullable<typeof EnvironmentQueryStore.Service> = {
1069 load: Effect.fn("EnvironmentQueryStore.load")(
1070 function* (environmentId, key) {
1071 const stored = yield* readDatabaseValue(
1072 database,
1073 QUERY_STORE_NAME,
1074 queryCacheKey(environmentId, key),
1075 );
1076 const now = yield* Clock.currentTimeMillis;
1077 return isStoredQuery(stored) &&
1078 stored.environmentId === environmentId &&
1079 stored.updatedAt >= now - QUERY_MAX_AGE_MS
1080 ? Option.some(stored.payload)
1081 : Option.none();
1082 },
1083 Effect.catch(() => Effect.succeedNone),
1084 ),
1085 save: (environmentId, key, payload) =>
1086 Clock.currentTimeMillis.pipe(
1087 Effect.flatMap((now) =>
1088 withDatabase(database, (opened) =>
1089 saveQueryOnConnection(opened, environmentId, key, payload, now),
1090 ),
1091 ),
1092 Effect.catch(() => Effect.logWarning("Offline query database save failed")),
1093 ),
1094 };
1095​
1096 return Context.make(Persistence.ConnectionTargetStore, targetStore).pipe(
1097 Context.add(PullRequestRoutingPermissions, pullRequestRoutingPermissions),
1098 Context.add(Persistence.ConnectionRegistrationStore, registrationStore),
1099 Context.add(ProfileStore.ConnectionProfileStore, profileStore),
1100 Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
1101 Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
1102 Context.add(Persistence.EnvironmentCacheStore, cacheStore),
1103 Context.add(EnvironmentQueryStore, queryStore),
1104 );
1105 }),