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

storage.ts

1,159 lines44.0 KB

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 });
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 });
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>;
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 );
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"));
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"));
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"));
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"));
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"));
451​
452function readDatabaseValue(database: DatabaseHandle, storeName: string, key: IDBValidKey) {
453 return withDatabase(database, (opened) => readDatabaseValueOnConnection(opened, storeName, key));
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 );
466​
467function removeDatabaseValue(database: DatabaseHandle, storeName: string, key: IDBValidKey) {
468 return withDatabase(database, (opened) =>
469 removeDatabaseValueOnConnection(opened, storeName, key),
470 );
472​
473function removeDatabaseValuesInRange(
474 database: DatabaseHandle,
475 storeName: string,
476 range: IDBKeyRange,
477) {
478 return withDatabase(database, (opened) =>
479 removeDatabaseValuesInRangeOnConnection(opened, storeName, range),
480 );
482​
483function threadCacheKey(environmentId: EnvironmentId, threadId: ThreadId) {
484 return `${environmentId}:${threadId}`;
486​
487function queryCacheKey(environmentId: EnvironmentId, key: string) {
488 return `${environmentId}:v1:${key}`;
490​
491function queryBatchKey(environmentId: EnvironmentId) {
492 return `${environmentId}:batch`;
494​
495function vcsRefsCacheKey(environmentId: EnvironmentId, cwd: string) {
496 return `${environmentId}:${cwd}`;
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: (
516 raw: string,
517 sshTunnelClaim?: string,
518 ) => Effect.Effect<void, ConnectionTransientError>;
519 readonly quarantine?: (raw: string) => Effect.Effect<void, ConnectionTransientError>;
521​
522export function makeCatalogBackend(database: DatabaseHandle): CatalogBackend {
523 const bridge = window.desktopBridge;
524 if (bridge !== undefined) {
525 return {
526 read: Effect.tryPromise({
527 try: () => bridge.getConnectionCatalog(),
528 catch: (cause) => catalogError("load", cause),
529 }),
530 write: (raw, sshTunnelClaim) =>
531 Effect.tryPromise({
532 try: () => bridge.setConnectionCatalog(raw, sshTunnelClaim),
533 catch: (cause) => catalogError("save", cause),
534 }).pipe(
535 Effect.flatMap((stored) =>
536 stored
537 ? Effect.void
538 : Effect.fail(
539 catalogError(
540 "save",
541 m(msg("Desktop secure storage is unavailable in this system context.")),
542 ),
543 ),
544 ),
545 ),
546 };
547 }
548​
549 return {
550 read: readDatabaseValue(database, CATALOG_STORE_NAME, CATALOG_KEY).pipe(
551 Effect.map((value) => (typeof value === "string" ? value : null)),
552 ),
553 write: (raw) => writeDatabaseValue(database, CATALOG_STORE_NAME, CATALOG_KEY, raw),
554 quarantine: (raw) =>
555 writeDatabaseValue(database, CATALOG_STORE_NAME, `${CATALOG_KEY}:corrupt:${Date.now()}`, raw),
556 };
558​
559interface CatalogStore {
560 readonly read: Effect.Effect<ConnectionCatalogDocumentType, ConnectionTransientError>;
561 readonly update: (
562 transform: (catalog: ConnectionCatalogDocumentType) => ConnectionCatalogDocumentType,
563 sshTunnelClaim?: string,
564 ) => Effect.Effect<void, ConnectionTransientError>;
566​
567export const makeCatalogStore = Effect.fn("web.connectionStorage.makeCatalogStore")(function* (
568 backend: CatalogBackend,
569) {
570 const state = yield* Ref.make<Option.Option<ConnectionCatalogDocumentType>>(Option.none());
571 const lock = yield* Semaphore.make(1);
572​
573 const loadUnlocked = Effect.fn("web.connectionStorage.loadCatalog")(function* () {
574 const cached = yield* Ref.get(state);
575 if (Option.isSome(cached)) {
576 return cached.value;
577 }
578 const raw = yield* backend.read;
579 let catalog = EMPTY_CONNECTION_CATALOG_DOCUMENT;
580 if (raw !== null && raw.trim() !== "") {
581 catalog = yield* decodeCatalog(raw).pipe(
582 Effect.catch((error) =>
583 Effect.gen(function* () {
584 yield* Effect.logWarning("Discarding a corrupt web connection catalog.", {
585 error: error.message,
586 });
587 if (backend.quarantine !== undefined) {
588 yield* backend.quarantine(raw).pipe(
589 Effect.catch((cause) =>
590 Effect.logWarning("Could not quarantine the corrupt web connection catalog.", {
591 error: cause.message,
592 }),
593 ),
594 );
595 }
596 const encoded = yield* encodeCatalog(EMPTY_CONNECTION_CATALOG_DOCUMENT);
597 yield* backend.write(encoded).pipe(
598 Effect.catch((cause) =>
599 Effect.logWarning("Could not persist the recovered web connection catalog.", {
600 error: cause.message,
601 }),
602 ),
603 );
604 return EMPTY_CONNECTION_CATALOG_DOCUMENT;
605 }),
606 ),
607 );
608 }
609 yield* Ref.set(state, Option.some(catalog));
610 return catalog;
611 });
612​
613 const read = lock.withPermits(1)(loadUnlocked());
614 const update: CatalogStore["update"] = Effect.fn("web.connectionStorage.updateCatalog")(
615 function* (transform, sshTunnelClaim) {
616 yield* lock.withPermits(1)(
617 Effect.gen(function* () {
618 const next = transform(yield* loadUnlocked());
619 yield* backend.write(yield* encodeCatalog(next), sshTunnelClaim);
620 yield* Ref.set(state, Option.some(next));
621 }),
622 );
623 },
624 );
625​
626 return { read, update } satisfies CatalogStore;
627});
628​
629// The stored names predate the rename and stay, so a tab still on an older version and an
630// updated one read and revoke the same grants.
631const PULL_REQUEST_ROUTING_KEY_PREFIX = "t3code:github-routing:";
632const PULL_REQUEST_ROUTING_CHANGED = "t3code:github-routing-changed";
633const isStoredPullRequestRoutingPermission = Schema.is(StoredPullRequestRoutingPermission);
634const encodeStoredPullRequestRoutingPermission = Schema.encodeSync(
635 Schema.fromJsonString(StoredPullRequestRoutingPermission),
636);
637​
638/** Each grant has its own key so stale tabs and unrelated catalog saves cannot restore trust. */
639export function makeBrowserPullRequestRoutingPermissions(
640 browser: Pick<Window, "localStorage"> & EventTarget = window,
641) {
642 const read = (key: string): StoredPullRequestRoutingPermission | null => {
643 try {
644 const raw = browser.localStorage.getItem(key);
645 const value: unknown = raw === null ? null : JSON.parse(raw);
646 return isStoredPullRequestRoutingPermission(value) &&
647 key === `${PULL_REQUEST_ROUTING_KEY_PREFIX}${value.environmentId}`
648 ? value
649 : null;
650 } catch {
651 return null;
652 }
653 };
654 const readAll = (): ReadonlyArray<StoredPullRequestRoutingPermission> => {
655 try {
656 const values: StoredPullRequestRoutingPermission[] = [];
657 const storage = browser.localStorage;
658 for (let index = 0; index < storage.length; index++) {
659 const key = storage.key(index);
660 if (key?.startsWith(PULL_REQUEST_ROUTING_KEY_PREFIX)) {
661 const value = read(key);
662 if (value !== null) values.push(value);
663 }
664 }
665 return values;
666 } catch {
667 return [];
668 }
669 };
670 const write = (environmentId: EnvironmentId, value: StoredPullRequestRoutingPermission | null) =>
671 Effect.try({
672 try: () => {
673 const key = `${PULL_REQUEST_ROUTING_KEY_PREFIX}${environmentId}`;
674 if (value === null) browser.localStorage.removeItem(key);
675 else browser.localStorage.setItem(key, encodeStoredPullRequestRoutingPermission(value));
676 browser.dispatchEvent(new Event(PULL_REQUEST_ROUTING_CHANGED));
677 },
678 catch: (cause) => catalogError("save pull request routing permissions in", cause),
679 });
680 return PullRequestRoutingPermissions.of({
681 get: Effect.fn("PullRequestRoutingPermissions.get")(function (entry) {
682 return Effect.sync(() => {
683 const value = read(`${PULL_REQUEST_ROUTING_KEY_PREFIX}${entry.target.environmentId}`);
684 return pullRequestRoutingPermissionFor(entry, value === null ? [] : [value]);
685 });
686 }),
687 changes: Stream.callback<ReadonlyArray<StoredPullRequestRoutingPermission>>((queue) =>
688 Effect.acquireRelease(
689 Effect.sync(() => {
690 const listener = (event: Event) => {
691 if (event.type === "storage") {
692 const key = (event as StorageEvent).key;
693 if (key !== null && !key?.startsWith(PULL_REQUEST_ROUTING_KEY_PREFIX)) return;
694 }
695 Queue.offerUnsafe(queue, readAll());
696 };
697 browser.addEventListener("storage", listener);
698 browser.addEventListener(PULL_REQUEST_ROUTING_CHANGED, listener);
699 Queue.offerUnsafe(queue, readAll());
700 return listener;
701 }),
702 (listener) =>
703 Effect.sync(() => {
704 browser.removeEventListener("storage", listener);
705 browser.removeEventListener(PULL_REQUEST_ROUTING_CHANGED, listener);
706 }),
707 ).pipe(Effect.asVoid),
708 ),
709 set: Effect.fn("PullRequestRoutingPermissions.set")(function* (entry, permission) {
710 const connectionKey = pullRequestRoutingConnectionKey(entry);
711 if (connectionKey === null)
712 return yield* new ConnectionBlockedError({
713 reason: "configuration",
714 detail: m(msg("This environment does not have a saved connection endpoint.")),
715 });
716 return yield* write(
717 entry.target.environmentId,
718 permission === "off"
719 ? null
720 : {
721 environmentId: entry.target.environmentId,
722 connectionKey,
723 permission,
724 },
725 );
726 }),
727 forget: Effect.fn("PullRequestRoutingPermissions.forget")(function (environmentId) {
728 return write(environmentId, null);
729 }),
730 });
732​
733// MessageChannel yields without nested-timer clamping or background throttling.
734const yieldToBrowserTask = Effect.callback<void>((resume) => {
735 const { port1, port2 } = new MessageChannel();
736 port1.addEventListener(
737 "message",
738 () => {
739 port1.close();
740 resume(Effect.void);
741 },
742 { once: true },
743 );
744 port1.start();
745 port2.postMessage(null);
746 // A closed port delivers nothing, so interruption needs no listener bookkeeping.
747 return Effect.sync(() => port1.close());
748});
749​
750export const layer = Layer.effectContext(
751 Effect.gen(function* () {
752 const { handle: database } = yield* Effect.acquireRelease(
753 makeDatabaseHandle(),
754 (owned) => owned.close,
755 );
756 const catalog = yield* makeCatalogStore(makeCatalogBackend(database));
757 const pullRequestRoutingPermissions = makeBrowserPullRequestRoutingPermissions();
758 // Remembers each thread row's encoding, so a save only encodes rows that changed.
759 const encodeStoredShellSnapshot = makeStoredShellSnapshotEncoder({
760 yieldToHost: yieldToBrowserTask,
761 });
762 const encodeStoredThreadSnapshot = makeStoredThreadSnapshotEncoder({
763 format: "full",
764 yieldToHost: yieldToBrowserTask,
765 });
766 const threadWriteOrder = makeThreadCacheWriteOrder();
767​
768 const targetStore = Persistence.ConnectionTargetStore.of({
769 list: catalog.read.pipe(
770 Effect.map((document) => document.targets),
771 Effect.mapError((cause) => persistenceError("list-targets", cause)),
772 ),
773 listDisabled: catalog.read.pipe(
774 Effect.map((document) => document.disabledEnvironmentIds),
775 Effect.mapError((cause) => persistenceError("list-disabled-targets", cause)),
776 ),
777 });
778 const registrationStore = Persistence.ConnectionRegistrationStore.of({
779 register: Effect.fn("Persistence.ConnectionRegistrationStore.register")(
780 function (registration, routes, sshTunnelClaim) {
781 return catalog
782 .update(
783 (document) => registerConnectionInCatalog(document, registration, routes),
784 sshTunnelClaim,
785 )
786 .pipe(Effect.mapError((cause) => persistenceError("register-connection", cause)));
787 },
788 ),
789 setRoutes: Effect.fn("Persistence.ConnectionRegistrationStore.setRoutes")(
790 function (environmentId, routes) {
791 return catalog
792 .update((document) => setRoutesInCatalog(document, environmentId, routes))
793 .pipe(Effect.mapError((cause) => persistenceError("set-connection-routes", cause)));
794 },
795 ),
796 remove: Effect.fn("Persistence.ConnectionRegistrationStore.remove")(function (environmentId) {
797 return catalog
798 .update((document) => removeConnectionFromCatalog(document, environmentId))
799 .pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause)));
800 }),
801 setEnabled: Effect.fn("Persistence.ConnectionRegistrationStore.setEnabled")(
802 function (environmentId, enabled) {
803 return catalog
804 .update((document) => setConnectionEnabledInCatalog(document, environmentId, enabled))
805 .pipe(Effect.mapError((cause) => persistenceError("set-connection-enabled", cause)));
806 },
807 ),
808 });
809 const profileStore = ProfileStore.make({
810 get: (connectionId) =>
811 catalog.read.pipe(
812 Effect.map((document) =>
813 Option.fromUndefinedOr(
814 document.profiles.find((profile) => profile.connectionId === connectionId),
815 ),
816 ),
817 ),
818 put: (profile) =>
819 catalog.update((document) => ({
820 ...document,
821 profiles: replaceCatalogValue(document.profiles, (value) => value.connectionId, profile),
822 })),
823 remove: (connectionId) =>
824 catalog.update((document) => ({
825 ...document,
826 profiles: removeCatalogValue(
827 document.profiles,
828 (value) => value.connectionId,
829 connectionId,
830 ),
831 })),
832 });
833 const credentialStore = CredentialStore.make({
834 get: (connectionId) =>
835 catalog.read.pipe(
836 Effect.map((document) =>
837 Option.fromUndefinedOr(
838 document.credentials.find((entry) => entry.connectionId === connectionId)?.credential,
839 ),
840 ),
841 ),
842 put: (connectionId, credential) =>
843 catalog.update((document) => ({
844 ...document,
845 credentials: replaceCatalogValue(document.credentials, (value) => value.connectionId, {
846 connectionId,
847 credential,
848 }),
849 })),
850 remove: (connectionId) =>
851 catalog.update((document) => ({
852 ...document,
853 credentials: removeCatalogValue(
854 document.credentials,
855 (value) => value.connectionId,
856 connectionId,
857 ),
858 })),
859 });
860 const remoteTokenStore = TokenStore.make({
861 get: (environmentId) =>
862 catalog.read.pipe(
863 Effect.map((document) =>
864 Option.fromUndefinedOr(
865 document.remoteDpopTokens.find((token) => token.environmentId === environmentId),
866 ),
867 ),
868 ),
869 put: (token) => catalog.update((document) => putRemoteDpopTokenInCatalog(document, token)),
870 remove: (environmentId) =>
871 catalog.update((document) => ({
872 ...document,
873 remoteDpopTokens: removeCatalogValue(
874 document.remoteDpopTokens,
875 (value) => value.environmentId,
876 environmentId,
877 ),
878 })),
879 });
880 const cacheStore = Persistence.EnvironmentCacheStore.of({
881 loadShell: Effect.fn("Persistence.EnvironmentCacheStore.loadShell")(function (environmentId) {
882 return readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
883 Effect.tap(() => Effect.promise(() => projectFaviconCache.hydrate())),
884 Effect.flatMap((raw) => {
885 if (typeof raw !== "string") {
886 return Effect.succeedNone;
887 }
888 return decodeOrDiscardOrchestrationCache(
889 decodeStoredShellSnapshot(raw).pipe(
890 Effect.mapError((cause) => persistenceError("load-shell", cause)),
891 Effect.map((stored) =>
892 stored.environmentId === environmentId
893 ? Option.some(
894 stored.origin === undefined
895 ? stored.snapshot
896 : { ...stored.snapshot, origin: stored.origin },
897 )
898 : Option.none(),
899 ),
900 ),
901 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
902 );
903 }),
904 Effect.mapError((cause) => persistenceError("load-shell", cause)),
905 );
906 }),
907 saveShell: Effect.fn("storage.saveShell")(
908 function* (environmentId, snapshot, origin) {
909 const encoded = yield* encodeStoredShellSnapshot({
910 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
911 environmentId,
912 snapshot,
913 ...(origin === undefined ? {} : { origin }),
914 }).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
915 yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
916 },
917 Effect.mapError((cause) =>
918 cause._tag === "ConnectionPersistenceError"
919 ? cause
920 : persistenceError("save-shell", cause),
921 ),
922 ),
923 loadServerConfig: Effect.fn("Persistence.EnvironmentCacheStore.loadServerConfig")(
924 function (environmentId) {
925 return readDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId).pipe(
926 Effect.flatMap((raw) => {
927 if (typeof raw !== "string") {
928 return Effect.succeedNone;
929 }
930 return decodeStoredServerConfig(raw).pipe(
931 Effect.mapError((cause) => persistenceError("load-server-config", cause)),
932 Effect.map((stored) =>
933 stored.environmentId === environmentId
934 ? Option.some(stored.config)
935 : Option.none(),
936 ),
937 );
938 }),
939 Effect.mapError((cause) =>
940 cause._tag === "ConnectionPersistenceError"
941 ? cause
942 : persistenceError("load-server-config", cause),
943 ),
944 );
945 },
946 ),
947 saveServerConfig: Effect.fn("storage.saveServerConfig")(
948 function* (environmentId, config) {
949 const encoded = yield* encodeStoredServerConfig({
950 schemaVersion: 1,
951 environmentId,
952 config,
953 }).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));
954 yield* writeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId, encoded);
955 },
956 Effect.mapError((cause) =>
957 cause._tag === "ConnectionPersistenceError"
958 ? cause
959 : persistenceError("save-server-config", cause),
960 ),
961 ),
962 loadThread: Effect.fn("Persistence.EnvironmentCacheStore.loadThread")(
963 function (environmentId, threadId) {
964 return readDatabaseValue(
965 database,
966 THREAD_STORE_NAME,
967 threadCacheKey(environmentId, threadId),
968 ).pipe(
969 Effect.flatMap((raw) => {
970 if (typeof raw !== "string") {
971 return Effect.succeedNone;
972 }
973 return decodeOrDiscardOrchestrationCache(
974 decodeStoredThreadSnapshot(raw).pipe(
975 Effect.mapError((cause) => persistenceError("load-thread", cause)),
976 Effect.map((stored) =>
977 stored.environmentId === environmentId && stored.threadId === threadId
978 ? Option.some(stored.snapshot)
979 : Option.none(),
980 ),
981 ),
982 removeDatabaseValue(
983 database,
984 THREAD_STORE_NAME,
985 threadCacheKey(environmentId, threadId),
986 ),
987 );
988 }),
989 Effect.mapError((cause) => persistenceError("load-thread", cause)),
990 );
991 },
992 ),
993 saveThread: Effect.fn("storage.saveThread")(
994 function* (environmentId, snapshot) {
995 const key = threadCacheKey(environmentId, snapshot.projection.thread.id);
996 const isLatest = threadWriteOrder.beginSave(environmentId, snapshot.projection.thread.id);
997 const encoded = yield* encodeStoredThreadSnapshot({
998 environmentId,
999 threadId: snapshot.projection.thread.id,
1000 snapshot,
1001 }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
1002 if (!isLatest()) return;
1003 // An older copy of a thread now too large to keep would paint stale on reopen.
1004 yield* Option.match(encoded, {
1005 onNone: () => removeDatabaseValue(database, THREAD_STORE_NAME, key),
1006 onSome: (payload) => writeDatabaseValue(database, THREAD_STORE_NAME, key, payload),
1007 });
1008 },
1009 Effect.mapError((cause) =>
1010 cause._tag === "ConnectionPersistenceError"
1011 ? cause
1012 : persistenceError("save-thread", cause),
1013 ),
1014 ),
1015 loadVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.loadVcsRefs")(
1016 function (environmentId, cwd) {
1017 return readDatabaseValue(
1018 database,
1019 VCS_REFS_STORE_NAME,
1020 vcsRefsCacheKey(environmentId, cwd),
1021 ).pipe(
1022 Effect.flatMap((raw) => {
1023 if (typeof raw !== "string") {
1024 return Effect.succeedNone;
1026 return decodeStoredVcsRefs(raw).pipe(
1027 Effect.mapError((cause) => persistenceError("load-vcs-refs", cause)),
1028 Effect.map((stored) =>
1029 stored.environmentId === environmentId && stored.cwd === cwd
1030 ? Option.some(stored.refs)
1031 : Option.none(),
1032 ),
1033 );
1034 }),
1035 Effect.mapError((cause) =>
1036 cause._tag === "ConnectionPersistenceError"
1037 ? cause
1038 : persistenceError("load-vcs-refs", cause),
1039 ),
1040 );
1041 },
1042 ),
1043 saveVcsRefs: Effect.fn("storage.saveVcsRefs")(
1044 function* (environmentId, cwd, refs) {
1045 const encoded = yield* encodeStoredVcsRefs({
1046 schemaVersion: 1,
1047 environmentId,
1048 cwd,
1049 refs,
1050 }).pipe(Effect.mapError((cause) => persistenceError("save-vcs-refs", cause)));
1051 yield* writeDatabaseValue(
1052 database,
1053 VCS_REFS_STORE_NAME,
1054 vcsRefsCacheKey(environmentId, cwd),
1055 encoded,
1056 );
1057 },
1058 Effect.mapError((cause) =>
1059 cause._tag === "ConnectionPersistenceError"
1060 ? cause
1061 : persistenceError("save-vcs-refs", cause),
1062 ),
1063 ),
1064 removeVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.removeVcsRefs")(
1065 function (environmentId, cwd) {
1066 return removeDatabaseValue(
1067 database,
1068 VCS_REFS_STORE_NAME,
1069 vcsRefsCacheKey(environmentId, cwd),
1070 ).pipe(Effect.mapError((cause) => persistenceError("remove-vcs-refs", cause)));
1071 },
1072 ),
1073 clearVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.clearVcsRefs")(
1074 function (environmentId) {
1075 return removeDatabaseValuesInRange(
1076 database,
1077 VCS_REFS_STORE_NAME,
1078 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1079 ).pipe(Effect.mapError((cause) => persistenceError("clear-vcs-refs", cause)));
1080 },
1081 ),
1082 removeThread: Effect.fn("Persistence.EnvironmentCacheStore.removeThread")(
1083 function (environmentId, threadId) {
1084 threadWriteOrder.removeThread(environmentId, threadId);
1085 return removeDatabaseValue(
1086 database,
1087 THREAD_STORE_NAME,
1088 threadCacheKey(environmentId, threadId),
1089 ).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause)));
1090 },
1091 ),
1092 clear: Effect.fn("Persistence.EnvironmentCacheStore.clear")(function (environmentId) {
1093 threadWriteOrder.clearEnvironment(environmentId);
1094 return Effect.all(
1096 Effect.promise(() => projectFaviconCache.clearEnvironment(environmentId)),
1097 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
1098 removeDatabaseValuesInRange(
1099 database,
1100 THREAD_STORE_NAME,
1101 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1102 ),
1103 removeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId),
1104 removeDatabaseValuesInRange(
1105 database,
1106 VCS_REFS_STORE_NAME,
1107 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1108 ),
1109 removeDatabaseValuesInRange(
1110 database,
1111 QUERY_STORE_NAME,
1112 IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1113 ),
1114 ],
1115 { concurrency: "unbounded", discard: true },
1116 ).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause)));
1117 }),
1118 });
1119​
1120 const queryStore: NonNullable<typeof EnvironmentQueryStore.Service> = {
1121 load: Effect.fn("EnvironmentQueryStore.load")(
1122 function* (environmentId, key) {
1123 const stored = yield* readDatabaseValue(
1124 database,
1125 QUERY_STORE_NAME,
1126 queryCacheKey(environmentId, key),
1127 );
1128 const now = yield* Clock.currentTimeMillis;
1129 return isStoredQuery(stored) &&
1130 stored.environmentId === environmentId &&
1131 stored.updatedAt >= now - QUERY_MAX_AGE_MS
1132 ? Option.some(stored.payload)
1133 : Option.none();
1134 },
1135 Effect.catch(() => Effect.succeedNone),
1136 ),
1137 save: (environmentId, key, payload) =>
1138 Clock.currentTimeMillis.pipe(
1139 Effect.flatMap((now) =>
1140 withDatabase(database, (opened) =>
1141 saveQueryOnConnection(opened, environmentId, key, payload, now),
1142 ),
1143 ),
1144 Effect.catch(() => Effect.logWarning("Offline query database save failed")),
1145 ),
1146 };
1147​
1148 return Context.make(Persistence.ConnectionTargetStore, targetStore).pipe(
1149 Context.add(PullRequestRoutingPermissions, pullRequestRoutingPermissions),
1150 Context.add(Persistence.ConnectionRegistrationStore, registrationStore),
1151 Context.add(ProfileStore.ConnectionProfileStore, profileStore),
1152 Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
1153 Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
1154 Context.add(Persistence.EnvironmentCacheStore, cacheStore),
1155 Context.add(ThreadTriageOutboxStore, browserThreadTriageOutboxStore),
1156 Context.add(EnvironmentQueryStore, queryStore),
1157 );
1158 }),