[codex] Structure connection persistence failures (#3255)

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-20 19:21:42 -07:00
1 parent 72191777b4
commit 96e4579244
11 files changed
+870 -235

No files matched your search

+49 -28
View File
@@ -3,7 +3,10 @@ import {
type ConnectionCatalogDocument as ConnectionCatalogDocumentType,
EMPTY_CONNECTION_CATALOG_DOCUMENT,
} from "@t3tools/client-runtime/platform";
import { ConnectionTransientError } from "@t3tools/client-runtime/connection";
import {
ConnectionStorageOperationError,
ConnectionTransientError,
} from "@t3tools/client-runtime/connection";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
@@ -15,30 +18,38 @@ import { migrateLegacyConnectionCatalog } from "./migration";
export const CONNECTION_CATALOG_KEY = "t3code.connection-catalog.v1";
export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson);
const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
const decodeCatalog = Effect.fn("mobile.connectionStorage.decodeCatalog")(function* (raw: string) {
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => catalogError("decode", cause),
});
return yield* Effect.fromResult(
Schema.decodeUnknownResult(ConnectionCatalogDocument)(parsed),
).pipe(Effect.mapError((cause) => catalogError("decode", cause)));
return yield* decodeConnectionCatalogDocument(raw).pipe(
Effect.mapError((cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "decode",
backend: "schema",
cause,
}),
),
),
);
});
const encodeCatalog = Effect.fn("mobile.connectionStorage.encodeCatalog")(function* (
catalog: ConnectionCatalogDocumentType,
) {
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(ConnectionCatalogDocument)(catalog),
).pipe(Effect.mapError((cause) => catalogError("encode", cause)));
return JSON.stringify(encoded);
return yield* encodeConnectionCatalogDocument(catalog).pipe(
Effect.mapError((cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "encode",
backend: "schema",
cause,
}),
),
),
);
});
interface CatalogStore {
@@ -66,12 +77,21 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS
legacyRaw === null || legacyRaw.trim() === ""
? EMPTY_CONNECTION_CATALOG_DOCUMENT
: yield* migrateLegacyConnectionCatalog(legacyRaw).pipe(
Effect.mapError((cause) => catalogError("migrate", cause)),
Effect.catch((error) =>
Effect.logWarning("Discarding corrupt legacy mobile connections", error).pipe(
Effect.as(EMPTY_CONNECTION_CATALOG_DOCUMENT),
Effect.mapError((cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "migrate",
backend: "legacy-migration",
cause,
}),
),
),
Effect.catchTags({
ConnectionTransientError: (error) =>
Effect.logWarning("Discarding corrupt legacy mobile connections", error).pipe(
Effect.as(EMPTY_CONNECTION_CATALOG_DOCUMENT),
),
}),
);
if (legacyRaw !== null && legacyRaw.trim() !== "") {
const encoded = yield* encodeCatalog(catalog);
@@ -90,12 +110,13 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS
let catalog: ConnectionCatalogDocumentType;
if (raw !== null && raw.trim() !== "") {
catalog = yield* decodeCatalog(raw).pipe(
Effect.catch((error) =>
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
Effect.andThen(loadLegacyCatalog()),
),
),
Effect.catchTags({
ConnectionTransientError: (error) =>
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
Effect.andThen(loadLegacyCatalog()),
),
}),
);
} else {
catalog = yield* loadLegacyCatalog();
+25 -1
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { migrateLegacyConnectionCatalog } from "./migration";
import { LegacyConnectionMigrationError, migrateLegacyConnectionCatalog } from "./migration";
describe("migrateLegacyConnectionCatalog", () => {
it.effect("migrates bearer and relay-managed connections into the new catalog", () =>
@@ -75,4 +75,28 @@ describe("migrateLegacyConnectionCatalog", () => {
expect(catalog.targets).toEqual([]);
}),
);
it.effect("preserves parse failures with a stable structural error", () =>
Effect.gen(function* () {
const error = yield* migrateLegacyConnectionCatalog("{not-json").pipe(Effect.flip);
expect(error).toBeInstanceOf(LegacyConnectionMigrationError);
expect(error.stage).toBe("parse");
expect(error.cause).toBeInstanceOf(SyntaxError);
expect(error.message).toBe("Could not parse the legacy mobile connection catalog.");
}),
);
it.effect("distinguishes catalog decoding failures", () =>
Effect.gen(function* () {
const error = yield* migrateLegacyConnectionCatalog('{"connections":"invalid"}').pipe(
Effect.flip,
);
expect(error).toBeInstanceOf(LegacyConnectionMigrationError);
expect(error.stage).toBe("decode");
expect(error.cause).toBeDefined();
expect(error.message).toBe("Could not decode the legacy mobile connection catalog.");
}),
);
});
+9 -12
View File
@@ -36,9 +36,14 @@ const decodeLegacyConnectionDocument = Schema.decodeUnknownEffect(LegacyConnecti
export class LegacyConnectionMigrationError extends Schema.TaggedErrorClass<LegacyConnectionMigrationError>()(
"LegacyConnectionMigrationError",
{
message: Schema.String,
stage: Schema.Literals(["parse", "decode"]),
cause: Schema.Defect(),
},
) {}
) {
override get message(): string {
return `Could not ${this.stage} the legacy mobile connection catalog.`;
}
}
function isRelayManaged(connection: typeof LegacySavedRemoteConnection.Type): boolean {
return connection.relayManaged === true || connection.authenticationMethod === "dpop";
@@ -92,18 +97,10 @@ export const migrateLegacyConnectionCatalog = Effect.fn(
)(function* (raw: string) {
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) =>
new LegacyConnectionMigrationError({
message: `Could not parse the legacy mobile connection catalog: ${String(cause)}`,
}),
catch: (cause) => new LegacyConnectionMigrationError({ stage: "parse", cause }),
});
const legacy = yield* decodeLegacyConnectionDocument(parsed).pipe(
Effect.mapError(
(cause) =>
new LegacyConnectionMigrationError({
message: `Could not decode the legacy mobile connection catalog: ${String(cause)}`,
}),
),
Effect.mapError((cause) => new LegacyConnectionMigrationError({ stage: "decode", cause })),
);
return (legacy.connections ?? []).reduce(migrateConnection, EMPTY_CONNECTION_CATALOG_DOCUMENT);
+288 -85
View File
@@ -10,6 +10,7 @@ import {
} from "@t3tools/client-runtime/platform";
import { TokenStore } from "@t3tools/client-runtime/authorization";
import {
ConnectionStorageOperationError,
ConnectionTransientError,
CredentialStore,
ProfileStore,
@@ -54,29 +55,11 @@ const LegacyStoredShellSnapshot = Schema.Struct({
snapshotReceivedAt: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
function shellPersistenceError(
operation:
| "load-shell"
| "save-shell"
| "load-thread"
| "save-thread"
| "remove-thread"
| "clear-environment",
cause: unknown,
) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
});
}
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(StoredShellSnapshot);
const encodeStoredShellSnapshot = Schema.encodeEffect(StoredShellSnapshot);
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredThreadSnapshot);
const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshot);
const decodeLegacyStoredShellSnapshot = Schema.decodeUnknownEffect(LegacyStoredShellSnapshot);
function threadSnapshotFileName(threadId: ThreadId): string {
return `${encodeURIComponent(threadId)}.json`;
@@ -100,7 +83,14 @@ const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapsh
}
return directory;
},
catch: (cause) => shellPersistenceError(operation, cause),
catch: (cause) =>
new ConnectionPersistenceError({
operation,
stage: "resolve",
resource: "thread-cache",
environmentId,
cause,
}),
});
},
);
@@ -110,38 +100,63 @@ const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFil
threadId: ThreadId,
operation: "load-thread" | "save-thread" | "remove-thread",
) {
const { File } = yield* Effect.promise(() => import("expo-file-system"));
return new File(
yield* threadSnapshotDirectory(environmentId, operation),
threadSnapshotFileName(threadId),
);
});
function targetPersistenceError(
operation: "list-targets" | "register-connection" | "remove-connection",
error: ConnectionTransientError,
) {
return new ConnectionPersistenceError({
operation,
message: error.message,
const directory = yield* threadSnapshotDirectory(environmentId, operation);
return yield* Effect.tryPromise({
try: async () => {
const { File } = await import("expo-file-system");
return new File(directory, threadSnapshotFileName(threadId));
},
catch: (cause) =>
new ConnectionPersistenceError({
operation,
stage: "resolve",
resource: "thread-cache",
environmentId,
threadId,
cause,
}),
});
}
});
const secureCatalogStorage: SecureCatalogStorage = {
getItem: (key) =>
Effect.tryPromise({
try: () => SecureStore.getItemAsync(key),
catch: (cause) => catalogError("load", cause),
catch: (cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "load",
backend: "mobile-secure-storage",
key,
cause,
}),
),
}),
setItem: (key, value) =>
Effect.tryPromise({
try: () => SecureStore.setItemAsync(key, value),
catch: (cause) => catalogError("save", cause),
catch: (cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "save",
backend: "mobile-secure-storage",
key,
cause,
}),
),
}),
deleteItem: (key) =>
Effect.tryPromise({
try: () => SecureStore.deleteItemAsync(key),
catch: (cause) => catalogError("delete", cause),
catch: (cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "delete",
backend: "mobile-secure-storage",
key,
cause,
}),
),
}),
};
@@ -156,6 +171,8 @@ const shellSnapshotFileInDirectory = Effect.fn(
operation: "load-shell" | "save-shell" | "clear-environment",
directoryName: string,
) {
const resource =
directoryName === LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY ? "legacy-shell-cache" : "shell-cache";
return yield* Effect.tryPromise({
try: async () => {
const { Directory, File, Paths } = await import("expo-file-system");
@@ -163,7 +180,14 @@ const shellSnapshotFileInDirectory = Effect.fn(
directory.create({ idempotent: true, intermediates: true });
return new File(directory, shellSnapshotFileName(environmentId));
},
catch: (cause) => shellPersistenceError(operation, cause),
catch: (cause) =>
new ConnectionPersistenceError({
operation,
stage: "resolve",
resource,
environmentId,
cause,
}),
});
});
@@ -184,18 +208,48 @@ export const connectionStorageLayer = Layer.effectContext(
const targetStore = ConnectionTargetStore.of({
list: catalog.read.pipe(
Effect.map((document) => document.targets),
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "list-targets",
stage: "read",
resource: "connection-catalog",
cause,
}),
),
),
});
const registrationStore = ConnectionRegistrationStore.of({
register: (registration) =>
catalog
.update((document) => registerConnectionInCatalog(document, registration))
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
.pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "register-connection",
stage: "write",
resource: "connection-catalog",
environmentId: registration.target.environmentId,
cause,
}),
),
),
remove: (target) =>
catalog
.update((document) => removeConnectionFromCatalog(document, target))
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
.pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "remove-connection",
stage: "write",
resource: "connection-catalog",
environmentId: target.environmentId,
cause,
}),
),
),
});
const profileStore = ProfileStore.make({
get: (connectionId) =>
@@ -283,15 +337,41 @@ export const connectionStorageLayer = Layer.effectContext(
if (file.exists) {
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "read",
resource: "shell-cache",
environmentId,
path: file.uri,
cause,
}),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "parse",
resource: "shell-cache",
environmentId,
path: file.uri,
cause,
}),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
const stored = yield* decodeStoredShellSnapshot(parsed).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "decode",
resource: "shell-cache",
environmentId,
path: file.uri,
cause,
}),
),
);
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
@@ -303,15 +383,41 @@ export const connectionStorageLayer = Layer.effectContext(
}
const legacyRaw = yield* Effect.tryPromise({
try: () => legacyFile.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "read",
resource: "legacy-shell-cache",
environmentId,
path: legacyFile.uri,
cause,
}),
});
const legacyParsed = yield* Effect.try({
try: () => JSON.parse(legacyRaw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "parse",
resource: "legacy-shell-cache",
environmentId,
path: legacyFile.uri,
cause,
}),
});
const legacyStored = yield* Effect.fromResult(
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
const legacyStored = yield* decodeLegacyStoredShellSnapshot(legacyParsed).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "decode",
resource: "legacy-shell-cache",
environmentId,
path: legacyFile.uri,
cause,
}),
),
);
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
: Option.none();
@@ -324,9 +430,19 @@ export const connectionStorageLayer = Layer.effectContext(
environmentId,
snapshot,
} as const;
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
const encoded = yield* encodeStoredShellSnapshot(stored).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "save-shell",
stage: "encode",
resource: "shell-cache",
environmentId,
path: file.uri,
cause,
}),
),
);
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -334,7 +450,15 @@ export const connectionStorageLayer = Layer.effectContext(
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-shell", cause),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "save-shell",
stage: "write",
resource: "shell-cache",
environmentId,
path: file.uri,
cause,
}),
});
}),
loadThread: (environmentId, threadId) =>
@@ -345,15 +469,44 @@ export const connectionStorageLayer = Layer.effectContext(
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-thread", cause),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "load-thread",
stage: "read",
resource: "thread-cache",
environmentId,
threadId,
path: file.uri,
cause,
}),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-thread", cause),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "load-thread",
stage: "parse",
resource: "thread-cache",
environmentId,
threadId,
path: file.uri,
cause,
}),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
const stored = yield* decodeStoredThreadSnapshot(parsed).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "load-thread",
stage: "decode",
resource: "thread-cache",
environmentId,
threadId,
path: file.uri,
cause,
}),
),
);
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
: Option.none();
@@ -361,14 +514,25 @@ export const connectionStorageLayer = Layer.effectContext(
saveThread: (environmentId, thread) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredThreadSnapshot)({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId: thread.id,
thread,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
const encoded = yield* encodeStoredThreadSnapshot({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId: thread.id,
thread,
}).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "save-thread",
stage: "encode",
resource: "thread-cache",
environmentId,
threadId: thread.id,
path: file.uri,
cause,
}),
),
);
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -376,36 +540,67 @@ export const connectionStorageLayer = Layer.effectContext(
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-thread", cause),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "save-thread",
stage: "write",
resource: "thread-cache",
environmentId,
threadId: thread.id,
path: file.uri,
cause,
}),
});
}),
removeThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
if (file.exists) {
file.delete();
yield* Effect.try({
try: () => file.delete(),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "remove-thread",
stage: "remove",
resource: "thread-cache",
environmentId,
threadId,
path: file.uri,
cause,
}),
});
}
}).pipe(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: shellPersistenceError("remove-thread", cause),
),
),
}),
clear: (environmentId) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "clear-environment");
if (file.exists) {
yield* Effect.try({
try: () => file.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "clear-environment",
stage: "remove",
resource: "shell-cache",
environmentId,
path: file.uri,
cause,
}),
});
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
if (legacyFile.exists) {
yield* Effect.try({
try: () => legacyFile.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "clear-environment",
stage: "remove",
resource: "legacy-shell-cache",
environmentId,
path: legacyFile.uri,
cause,
}),
});
}
const threadDirectory = yield* threadSnapshotDirectory(
@@ -415,7 +610,15 @@ export const connectionStorageLayer = Layer.effectContext(
if (threadDirectory.exists) {
yield* Effect.try({
try: () => threadDirectory.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "clear-environment",
stage: "remove",
resource: "thread-cache",
environmentId,
path: threadDirectory.uri,
cause,
}),
});
}
}),
+25
View File
@@ -71,7 +71,32 @@ describe("makeCatalogBackend", () => {
expect(error).toBeInstanceOf(ConnectionTransientError);
expect(error.message).toContain("Desktop secure storage is unavailable");
expect(error.cause).toMatchObject({ _tag: "DesktopSecureStorageUnavailableError" });
expect(setConnectionCatalog).toHaveBeenCalledWith("{}");
}),
);
it.effect("preserves secure-storage write failures without exposing them in the message", () =>
Effect.gen(function* () {
const cause = new Error("credential vault path leaked");
vi.stubGlobal("window", {
desktopBridge: {
getConnectionCatalog: vi.fn().mockResolvedValue(null),
setConnectionCatalog: vi.fn().mockRejectedValue(cause),
},
});
const backend = makeCatalogBackend({} as IDBDatabase);
const error = yield* backend.write("{}").pipe(Effect.flip);
expect(error.cause).toMatchObject({
_tag: "ConnectionStorageOperationError",
operation: "save",
backend: "desktop-secure-storage",
cause,
});
expect(error.message).toBe("Could not save local connection data.");
expect(error.message).not.toContain(cause.message);
}),
);
});
+300 -104
View File
@@ -13,8 +13,11 @@ import {
} from "@t3tools/client-runtime/platform";
import { TokenStore } from "@t3tools/client-runtime/authorization";
import {
ConnectionStorageOperationError,
ConnectionTransientError,
CredentialStore,
DesktopSecureStorageUnavailableError,
IndexedDbUnavailableError,
ProfileStore,
} from "@t3tools/client-runtime/connection";
import {
@@ -60,37 +63,11 @@ const encodeStoredShellSnapshot = Schema.encodeEffect(StoredShellSnapshotJson);
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredThreadSnapshotJson);
const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshotJson);
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
function persistenceError(
operation:
| "list-targets"
| "register-connection"
| "remove-connection"
| "load-shell"
| "save-shell"
| "load-thread"
| "save-thread"
| "remove-thread"
| "clear-environment",
cause: unknown,
) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
});
}
const openDatabase = Effect.fn("web.connectionStorage.openDatabase")(function* () {
return yield* Effect.callback<IDBDatabase, ConnectionTransientError>((resume) => {
if (typeof indexedDB === "undefined") {
resume(
Effect.fail(catalogError("open", "IndexedDB is unavailable in this browser context.")),
Effect.fail(ConnectionTransientError.fromStorageFailure(new IndexedDbUnavailableError())),
);
return;
}
@@ -106,8 +83,18 @@ const openDatabase = Effect.fn("web.connectionStorage.openDatabase")(function* (
request.result.createObjectStore(THREAD_STORE_NAME);
}
});
request.addEventListener("error", () => {
resume(Effect.fail(catalogError("open", request.error ?? "Unknown IndexedDB error")));
request.addEventListener("error", (event) => {
resume(
Effect.fail(
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "open",
backend: "indexed-db",
cause: request.error ?? event,
}),
),
),
);
});
request.addEventListener("success", () => {
resume(Effect.succeed(request.result));
@@ -118,8 +105,20 @@ const openDatabase = Effect.fn("web.connectionStorage.openDatabase")(function* (
function readDatabaseValue(database: IDBDatabase, storeName: string, key: IDBValidKey) {
return Effect.callback<unknown, ConnectionTransientError>((resume) => {
const request = database.transaction(storeName, "readonly").objectStore(storeName).get(key);
request.addEventListener("error", () => {
resume(Effect.fail(catalogError("read", request.error ?? "Unknown IndexedDB read error")));
request.addEventListener("error", (event) => {
resume(
Effect.fail(
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "read",
backend: "indexed-db",
storeName,
key,
cause: request.error ?? event,
}),
),
),
);
});
request.addEventListener("success", () => {
resume(Effect.succeed(request.result));
@@ -135,9 +134,19 @@ function writeDatabaseValue(
) {
return Effect.callback<void, ConnectionTransientError>((resume) => {
const transaction = database.transaction(storeName, "readwrite");
transaction.addEventListener("error", () => {
transaction.addEventListener("error", (event) => {
resume(
Effect.fail(catalogError("write", transaction.error ?? "Unknown IndexedDB write error")),
Effect.fail(
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "write",
backend: "indexed-db",
storeName,
key,
cause: transaction.error ?? event,
}),
),
),
);
});
transaction.addEventListener("complete", () => {
@@ -150,9 +159,19 @@ function writeDatabaseValue(
function removeDatabaseValue(database: IDBDatabase, storeName: string, key: IDBValidKey) {
return Effect.callback<void, ConnectionTransientError>((resume) => {
const transaction = database.transaction(storeName, "readwrite");
transaction.addEventListener("error", () => {
transaction.addEventListener("error", (event) => {
resume(
Effect.fail(catalogError("remove", transaction.error ?? "Unknown IndexedDB remove error")),
Effect.fail(
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "remove",
backend: "indexed-db",
storeName,
key,
cause: transaction.error ?? event,
}),
),
),
);
});
transaction.addEventListener("complete", () => {
@@ -165,18 +184,36 @@ function removeDatabaseValue(database: IDBDatabase, storeName: string, key: IDBV
function removeDatabaseValuesInRange(database: IDBDatabase, storeName: string, range: IDBKeyRange) {
return Effect.callback<void, ConnectionTransientError>((resume) => {
const transaction = database.transaction(storeName, "readwrite");
transaction.addEventListener("error", () => {
transaction.addEventListener("error", (event) => {
resume(
Effect.fail(catalogError("remove", transaction.error ?? "Unknown IndexedDB cursor error")),
Effect.fail(
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "remove",
backend: "indexed-db",
storeName,
cause: transaction.error ?? event,
}),
),
),
);
});
transaction.addEventListener("complete", () => {
resume(Effect.void);
});
const request = transaction.objectStore(storeName).openCursor(range);
request.addEventListener("error", () => {
request.addEventListener("error", (event) => {
resume(
Effect.fail(catalogError("remove", request.error ?? "Unknown IndexedDB cursor error")),
Effect.fail(
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "remove",
backend: "indexed-db",
storeName,
cause: request.error ?? event,
}),
),
),
);
});
request.addEventListener("success", () => {
@@ -196,7 +233,15 @@ function threadCacheKey(environmentId: EnvironmentId, threadId: ThreadId) {
const decodeCatalog = Effect.fn("web.connectionStorage.decodeCatalog")(function* (raw: string) {
return yield* decodeConnectionCatalogDocument(raw).pipe(
Effect.mapError((cause) => catalogError("decode", cause)),
Effect.mapError((cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "decode",
backend: "schema",
cause,
}),
),
),
);
});
@@ -204,7 +249,15 @@ const encodeCatalog = Effect.fn("web.connectionStorage.encodeCatalog")(function*
catalog: ConnectionCatalogDocumentType,
) {
return yield* encodeConnectionCatalogDocument(catalog).pipe(
Effect.mapError((cause) => catalogError("encode", cause)),
Effect.mapError((cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "encode",
backend: "schema",
cause,
}),
),
),
);
});
@@ -220,20 +273,33 @@ export function makeCatalogBackend(database: IDBDatabase): CatalogBackend {
return {
read: Effect.tryPromise({
try: () => bridge.getConnectionCatalog!(),
catch: (cause) => catalogError("load", cause),
catch: (cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "load",
backend: "desktop-secure-storage",
cause,
}),
),
}),
write: (raw) =>
Effect.tryPromise({
try: () => bridge.setConnectionCatalog!(raw),
catch: (cause) => catalogError("save", cause),
catch: (cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "save",
backend: "desktop-secure-storage",
cause,
}),
),
}).pipe(
Effect.flatMap((stored) =>
stored
? Effect.void
: Effect.fail(
catalogError(
"save",
"Desktop secure storage is unavailable in this system context.",
ConnectionTransientError.fromStorageFailure(
new DesktopSecureStorageUnavailableError(),
),
),
),
@@ -273,31 +339,33 @@ export const makeCatalogStore = Effect.fn("web.connectionStorage.makeCatalogStor
let catalog = EMPTY_CONNECTION_CATALOG_DOCUMENT;
if (raw !== null && raw.trim() !== "") {
catalog = yield* decodeCatalog(raw).pipe(
Effect.catch((error) =>
Effect.gen(function* () {
yield* Effect.logWarning("Discarding a corrupt web connection catalog.", {
error: error.message,
});
if (backend.quarantine !== undefined) {
yield* backend.quarantine(raw).pipe(
Effect.catch((cause) =>
Effect.logWarning("Could not quarantine the corrupt web connection catalog.", {
error: cause.message,
Effect.catchTags({
ConnectionTransientError: (error) =>
Effect.gen(function* () {
yield* Effect.logWarning("Discarding a corrupt web connection catalog.", { error });
if (backend.quarantine !== undefined) {
yield* backend.quarantine(raw).pipe(
Effect.catchTags({
ConnectionTransientError: (error) =>
Effect.logWarning(
"Could not quarantine the corrupt web connection catalog.",
{ error },
),
}),
),
);
}
const encoded = yield* encodeCatalog(EMPTY_CONNECTION_CATALOG_DOCUMENT);
yield* backend.write(encoded).pipe(
Effect.catch((cause) =>
Effect.logWarning("Could not persist the recovered web connection catalog.", {
error: cause.message,
);
}
const encoded = yield* encodeCatalog(EMPTY_CONNECTION_CATALOG_DOCUMENT);
yield* backend.write(encoded).pipe(
Effect.catchTags({
ConnectionTransientError: (error) =>
Effect.logWarning("Could not persist the recovered web connection catalog.", {
error,
}),
}),
),
);
return EMPTY_CONNECTION_CATALOG_DOCUMENT;
}),
),
);
return EMPTY_CONNECTION_CATALOG_DOCUMENT;
}),
}),
);
}
yield* Ref.set(state, Option.some(catalog));
@@ -330,18 +398,48 @@ export const connectionStorageLayer = Layer.effectContext(
const targetStore = ConnectionTargetStore.of({
list: catalog.read.pipe(
Effect.map((document) => document.targets),
Effect.mapError((cause) => persistenceError("list-targets", cause)),
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "list-targets",
stage: "read",
resource: "connection-catalog",
cause,
}),
),
),
});
const registrationStore = ConnectionRegistrationStore.of({
register: (registration) =>
catalog
.update((document) => registerConnectionInCatalog(document, registration))
.pipe(Effect.mapError((cause) => persistenceError("register-connection", cause))),
.pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "register-connection",
stage: "write",
resource: "connection-catalog",
environmentId: registration.target.environmentId,
cause,
}),
),
),
remove: (target) =>
catalog
.update((document) => removeConnectionFromCatalog(document, target))
.pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause))),
.pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "remove-connection",
stage: "write",
resource: "connection-catalog",
environmentId: target.environmentId,
cause,
}),
),
),
});
const profileStore = ProfileStore.make({
get: (connectionId) =>
@@ -425,12 +523,31 @@ export const connectionStorageLayer = Layer.effectContext(
const cacheStore = EnvironmentCacheStore.of({
loadShell: (environmentId) =>
readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "read",
resource: "shell-cache",
environmentId,
cause,
}),
),
Effect.flatMap((raw) => {
if (typeof raw !== "string") {
return Effect.succeed(Option.none());
}
return decodeStoredShellSnapshot(raw).pipe(
Effect.mapError((cause) => persistenceError("load-shell", cause)),
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "decode",
resource: "shell-cache",
environmentId,
cause,
}),
),
Effect.map((stored) =>
stored.environmentId === environmentId
? Option.some(stored.snapshot)
@@ -438,11 +555,6 @@ export const connectionStorageLayer = Layer.effectContext(
),
);
}),
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: persistenceError("load-shell", cause),
),
),
saveShell: (environmentId, snapshot) =>
Effect.gen(function* () {
@@ -450,27 +562,64 @@ export const connectionStorageLayer = Layer.effectContext(
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
snapshot,
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
}).pipe(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: persistenceError("save-shell", cause),
),
),
}).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "save-shell",
stage: "encode",
resource: "shell-cache",
environmentId,
cause,
}),
),
);
yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "save-shell",
stage: "write",
resource: "shell-cache",
environmentId,
cause,
}),
),
);
}),
loadThread: (environmentId, threadId) =>
readDatabaseValue(
database,
THREAD_STORE_NAME,
threadCacheKey(environmentId, threadId),
).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "load-thread",
stage: "read",
resource: "thread-cache",
environmentId,
threadId,
cause,
}),
),
Effect.flatMap((raw) => {
if (typeof raw !== "string") {
return Effect.succeed(Option.none());
}
return decodeStoredThreadSnapshot(raw).pipe(
Effect.mapError((cause) => persistenceError("load-thread", cause)),
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "load-thread",
stage: "decode",
resource: "thread-cache",
environmentId,
threadId,
cause,
}),
),
Effect.map((stored) =>
stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
@@ -478,11 +627,6 @@ export const connectionStorageLayer = Layer.effectContext(
),
);
}),
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: persistenceError("load-thread", cause),
),
),
saveThread: (environmentId, thread) =>
Effect.gen(function* () {
@@ -491,38 +635,90 @@ export const connectionStorageLayer = Layer.effectContext(
environmentId,
threadId: thread.id,
thread,
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
}).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "save-thread",
stage: "encode",
resource: "thread-cache",
environmentId,
threadId: thread.id,
cause,
}),
),
);
yield* writeDatabaseValue(
database,
THREAD_STORE_NAME,
threadCacheKey(environmentId, thread.id),
encoded,
).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "save-thread",
stage: "write",
resource: "thread-cache",
environmentId,
threadId: thread.id,
cause,
}),
),
);
}).pipe(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: persistenceError("save-thread", cause),
),
),
}),
removeThread: (environmentId, threadId) =>
removeDatabaseValue(
database,
THREAD_STORE_NAME,
threadCacheKey(environmentId, threadId),
).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause))),
).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "remove-thread",
stage: "remove",
resource: "thread-cache",
environmentId,
threadId,
cause,
}),
),
),
clear: (environmentId) =>
Effect.all(
[
removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
removeDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "clear-environment",
stage: "remove",
resource: "shell-cache",
environmentId,
cause,
}),
),
),
removeDatabaseValuesInRange(
database,
THREAD_STORE_NAME,
IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "clear-environment",
stage: "remove",
resource: "thread-cache",
environmentId,
cause,
}),
),
),
],
{ concurrency: "unbounded", discard: true },
).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause))),
),
});
return Context.make(ConnectionTargetStore, targetStore).pipe(
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vite-plus/test";
import {
ConnectionStorageOperationError,
ConnectionTransientError,
IndexedDbUnavailableError,
} from "./model.ts";
describe("ConnectionTransientError.fromStorageFailure", () => {
it("preserves structured operation context and the complete failure chain", () => {
const storageCause = new Error("quota exceeded");
const storageOperationCause = new ConnectionStorageOperationError({
operation: "write",
backend: "indexed-db",
storeName: "catalog",
cause: storageCause,
});
const error = ConnectionTransientError.fromStorageFailure(storageOperationCause);
expect(error).toMatchObject({
reason: "remote-unavailable",
cause: {
_tag: "ConnectionStorageOperationError",
operation: "write",
backend: "indexed-db",
storeName: "catalog",
cause: storageCause,
},
});
expect(error.message).toBe("Could not write local connection data.");
});
it("maps a cause-free availability failure without inventing a defect", () => {
const error = ConnectionTransientError.fromStorageFailure(new IndexedDbUnavailableError());
expect(error.cause).toMatchObject({ _tag: "IndexedDbUnavailableError" });
expect((error.cause as IndexedDbUnavailableError).cause).toBeUndefined();
});
});
@@ -75,6 +75,69 @@ export const ConnectionBlockedReason = Schema.Literals([
]);
export type ConnectionBlockedReason = typeof ConnectionBlockedReason.Type;
export const ConnectionStorageOperation = Schema.Literals([
"open",
"read",
"write",
"remove",
"load",
"save",
"delete",
"decode",
"encode",
"migrate",
]);
export type ConnectionStorageOperation = typeof ConnectionStorageOperation.Type;
export const ConnectionStorageBackend = Schema.Literals([
"indexed-db",
"desktop-secure-storage",
"mobile-secure-storage",
"legacy-migration",
"schema",
]);
export type ConnectionStorageBackend = typeof ConnectionStorageBackend.Type;
export class ConnectionStorageOperationError extends Schema.TaggedErrorClass<ConnectionStorageOperationError>()(
"ConnectionStorageOperationError",
{
operation: ConnectionStorageOperation,
backend: ConnectionStorageBackend,
storeName: Schema.optionalKey(Schema.String),
key: Schema.optionalKey(Schema.Unknown),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Could not ${this.operation} local connection data.`;
}
}
export class IndexedDbUnavailableError extends Schema.TaggedErrorClass<IndexedDbUnavailableError>()(
"IndexedDbUnavailableError",
{},
) {
override get message(): string {
return "IndexedDB is unavailable in this browser context.";
}
}
export class DesktopSecureStorageUnavailableError extends Schema.TaggedErrorClass<DesktopSecureStorageUnavailableError>()(
"DesktopSecureStorageUnavailableError",
{},
) {
override get message(): string {
return "Desktop secure storage is unavailable in this system context.";
}
}
export const ConnectionStorageFailure = Schema.Union([
ConnectionStorageOperationError,
IndexedDbUnavailableError,
DesktopSecureStorageUnavailableError,
]);
export type ConnectionStorageFailure = typeof ConnectionStorageFailure.Type;
export class ConnectionTransientError extends Schema.TaggedErrorClass<ConnectionTransientError>()(
"ConnectionTransientError",
{
@@ -84,6 +147,26 @@ export class ConnectionTransientError extends Schema.TaggedErrorClass<Connection
cause: Schema.optional(Schema.Defect()),
},
) {
static fromStorageFailure(cause: ConnectionStorageFailure): ConnectionTransientError {
let detail: string;
switch (cause._tag) {
case "ConnectionStorageOperationError":
detail = `Could not ${cause.operation} local connection data.`;
break;
case "IndexedDbUnavailableError":
detail = "IndexedDB is unavailable in this browser context.";
break;
case "DesktopSecureStorageUnavailableError":
detail = "Desktop secure storage is unavailable in this system context.";
break;
}
return new ConnectionTransientError({
reason: "remote-unavailable",
detail,
cause,
});
}
override get message(): string {
return this.detail;
}
@@ -694,7 +694,10 @@ describe("EnvironmentRegistry", () => {
Effect.fail(
new Persistence.ConnectionPersistenceError({
operation: "remove-connection",
message: "Storage is unavailable.",
stage: "write",
resource: "connection-catalog",
environmentId: RELAY_TARGET.environmentId,
cause: new Error("Storage is unavailable."),
}),
),
});
@@ -0,0 +1,25 @@
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import { ConnectionPersistenceError } from "./persistence.ts";
describe("ConnectionPersistenceError", () => {
it("retains storage context and cause without deriving its message from the cause", () => {
const cause = new Error("sensitive filesystem detail");
const error = new ConnectionPersistenceError({
operation: "load-thread",
stage: "decode",
resource: "thread-cache",
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-1"),
path: "file:///cache/thread-1.json",
cause,
});
expect(error.cause).toBe(cause);
expect(error.message).toBe(
"Could not load thread: thread cache decode failed for environment environment-1 and thread thread-1 at file:///cache/thread-1.json.",
);
expect(error.message).not.toContain(cause.message);
});
});
@@ -1,8 +1,8 @@
import {
type EnvironmentId,
EnvironmentId,
type OrchestrationThread,
type OrchestrationShellSnapshot,
type ThreadId,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -26,9 +26,27 @@ export class ConnectionPersistenceError extends Schema.TaggedErrorClass<Connecti
"remove-thread",
"clear-environment",
]),
message: Schema.String,
stage: Schema.Literals(["resolve", "read", "parse", "decode", "encode", "write", "remove"]),
resource: Schema.Literals([
"connection-catalog",
"shell-cache",
"legacy-shell-cache",
"thread-cache",
]),
environmentId: Schema.optionalKey(EnvironmentId),
threadId: Schema.optionalKey(ThreadId),
path: Schema.optionalKey(Schema.String),
cause: Schema.Defect(),
},
) {}
) {
override get message(): string {
const environment =
this.environmentId === undefined ? "" : ` for environment ${this.environmentId}`;
const thread = this.threadId === undefined ? "" : ` and thread ${this.threadId}`;
const path = this.path === undefined ? "" : ` at ${this.path}`;
return `Could not ${this.operation.replaceAll("-", " ")}: ${this.resource.replaceAll("-", " ")} ${this.stage} failed${environment}${thread}${path}.`;
}
}
export class ConnectionTargetStore extends Context.Service<
ConnectionTargetStore,