Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6693a8816 |
No files matched your search
@@ -1,8 +1,8 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -33,24 +33,22 @@ const makeDesktopRunId = Crypto.Crypto.pipe(
|
||||
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
|
||||
);
|
||||
|
||||
export class DesktopBackendPortUnavailableError extends Schema.TaggedErrorClass<DesktopBackendPortUnavailableError>()(
|
||||
class DesktopBackendPortUnavailableError extends Data.TaggedError(
|
||||
"DesktopBackendPortUnavailableError",
|
||||
{
|
||||
startPort: Schema.Int,
|
||||
maxPort: Schema.Int,
|
||||
hosts: Schema.Array(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly startPort: number;
|
||||
readonly maxPort: number;
|
||||
readonly hosts: readonly string[];
|
||||
}> {
|
||||
override get message() {
|
||||
return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedErrorClass<DesktopDevelopmentBackendPortRequiredError>()(
|
||||
class DesktopDevelopmentBackendPortRequiredError extends Data.TaggedError(
|
||||
"DesktopDevelopmentBackendPortRequiredError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{}> {
|
||||
override get message() {
|
||||
return "T3CODE_PORT is required in desktop development.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
DesktopBackendPortUnavailableError,
|
||||
DesktopDevelopmentBackendPortRequiredError,
|
||||
} from "./DesktopApp.ts";
|
||||
|
||||
describe("DesktopApp errors", () => {
|
||||
it("preserves unavailable backend port context", () => {
|
||||
const error = new DesktopBackendPortUnavailableError({
|
||||
startPort: 3_773,
|
||||
maxPort: 65_535,
|
||||
hosts: ["127.0.0.1", "0.0.0.0", "::"],
|
||||
});
|
||||
|
||||
assert.equal(error.startPort, 3_773);
|
||||
assert.equal(error.maxPort, 65_535);
|
||||
assert.deepEqual(error.hosts, ["127.0.0.1", "0.0.0.0", "::"]);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"No desktop backend port is available on hosts 127.0.0.1, 0.0.0.0, :: between 3773 and 65535.",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports the required development port", () => {
|
||||
const error = new DesktopDevelopmentBackendPortRequiredError();
|
||||
|
||||
assert.equal(error.message, "T3CODE_PORT is required in desktop development.");
|
||||
});
|
||||
});
|
||||
@@ -1,122 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as DesktopBackendOutputLog from "./DesktopBackendOutputLog.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const LOG_FILE_PATH = "/Users/alice/.t3/userdata/logs/server-child.log";
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/dist-electron",
|
||||
homeDirectory: "/Users/alice",
|
||||
platform: "darwin",
|
||||
processArch: "arm64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(Layer.provide(Layer.merge(Path.layer, DesktopConfig.layerTest({}))));
|
||||
|
||||
const withOutputLog = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopBackendOutputLog.DesktopBackendOutputLog>,
|
||||
fileSystemLayer: Layer.Layer<FileSystem.FileSystem>,
|
||||
messages: Array<ReadonlyArray<unknown>>,
|
||||
) => {
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(Array.isArray(message) ? message : [message]);
|
||||
});
|
||||
const outputLogLayer = DesktopBackendOutputLog.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(fileSystemLayer, Path.layer, environmentLayer)),
|
||||
Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
|
||||
);
|
||||
return effect.pipe(Effect.provide(outputLogLayer));
|
||||
};
|
||||
|
||||
const loggedError = (messages: ReadonlyArray<ReadonlyArray<unknown>>): unknown =>
|
||||
messages.flat().find((value) => typeof value === "object" && value !== null && "error" in value)
|
||||
?.error;
|
||||
|
||||
describe("DesktopBackendOutputLog", () => {
|
||||
it.effect("logs setup failures with the log path and exact cause", () => {
|
||||
const messages: Array<ReadonlyArray<unknown>> = [];
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: "/Users/alice/.t3/userdata/logs",
|
||||
description: "private setup diagnostic",
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
makeDirectory: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
|
||||
assert.equal(error.logFilePath, LOG_FILE_PATH);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to initialize the desktop backend output log at ${LOG_FILE_PATH}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "private setup diagnostic");
|
||||
}),
|
||||
fileSystemLayer,
|
||||
messages,
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("logs record write failures with the operation and exact cause", () => {
|
||||
const messages: Array<ReadonlyArray<unknown>> = [];
|
||||
const missingCause = PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "stat",
|
||||
pathOrDescriptor: LOG_FILE_PATH,
|
||||
});
|
||||
const writeCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "writeFile",
|
||||
pathOrDescriptor: LOG_FILE_PATH,
|
||||
description: "private write diagnostic",
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
makeDirectory: () => Effect.void,
|
||||
stat: () => Effect.fail(missingCause),
|
||||
readDirectory: () => Effect.succeed([]),
|
||||
writeFile: () => Effect.fail(writeCause),
|
||||
});
|
||||
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
|
||||
assert.equal(error.operation, "write-record");
|
||||
assert.equal(error.logFilePath, LOG_FILE_PATH);
|
||||
assert.strictEqual(error.cause, writeCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop backend output log operation "write-record" failed at ${LOG_FILE_PATH}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "private write diagnostic");
|
||||
}),
|
||||
fileSystemLayer,
|
||||
messages,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -19,75 +19,8 @@ export const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
|
||||
interface RotatingLogFileWriter {
|
||||
readonly filePath: string;
|
||||
readonly writeBytes: (
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
|
||||
readonly writeText: (
|
||||
chunk: string,
|
||||
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
{
|
||||
option: Schema.Literals(["maxBytes", "maxFiles"]),
|
||||
value: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterRecoveryError extends Schema.TaggedErrorClass<DesktopLogFileWriterRecoveryError>()(
|
||||
"DesktopLogFileWriterRecoveryError",
|
||||
{
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
recoveryCause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to refresh desktop backend output log size after a write failure at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLogSetupError extends Schema.TaggedErrorClass<DesktopBackendOutputLogSetupError>()(
|
||||
"DesktopBackendOutputLogSetupError",
|
||||
{
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to initialize the desktop backend output log at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLogWriteError extends Schema.TaggedErrorClass<DesktopBackendOutputLogWriteError>()(
|
||||
"DesktopBackendOutputLogWriteError",
|
||||
{
|
||||
operation: Schema.Literals(["encode-record", "write-record"]),
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop backend output log operation "${this.operation}" failed at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<DesktopBackendConsoleWriteError>()(
|
||||
"DesktopBackendConsoleWriteError",
|
||||
{
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to mirror desktop backend output to ${this.streamName}.`;
|
||||
}
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
readonly writeText: (chunk: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
@@ -104,6 +37,18 @@ export class DesktopBackendOutputLog extends Context.Service<
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
|
||||
|
||||
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
{
|
||||
option: Schema.Literals(["maxBytes", "maxFiles"]),
|
||||
value: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
type DesktopLogFileWriterError =
|
||||
| DesktopLogFileWriterConfigurationError
|
||||
| PlatformError.PlatformError;
|
||||
@@ -140,13 +85,10 @@ const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").t
|
||||
const refreshFileSize = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
filePath: string,
|
||||
): Effect.Effect<number, PlatformError.PlatformError> =>
|
||||
): Effect.Effect<number, never> =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((stat) => Number(stat.size)),
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed(0) : Effect.fail(error),
|
||||
}),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
);
|
||||
|
||||
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
|
||||
@@ -184,52 +126,41 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
|
||||
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const recoverCurrentSize = (
|
||||
cause: PlatformError.PlatformError,
|
||||
): Effect.Effect<never, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.matchEffect({
|
||||
onFailure: (recoveryCause) =>
|
||||
Effect.fail(
|
||||
new DesktopLogFileWriterRecoveryError({
|
||||
logFilePath: input.filePath,
|
||||
cause,
|
||||
recoveryCause,
|
||||
}),
|
||||
),
|
||||
onSuccess: (size) => Ref.set(currentSize, size).pipe(Effect.andThen(Effect.fail(cause))),
|
||||
}),
|
||||
);
|
||||
|
||||
const pruneOverflowBackups = Effect.gen(function* () {
|
||||
const entries = yield* fileSystem.readDirectory(directory);
|
||||
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
|
||||
for (const entry of entries) {
|
||||
if (!entry.startsWith(`${baseName}.`)) continue;
|
||||
const suffix = Number(entry.slice(baseName.length + 1));
|
||||
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
|
||||
yield* fileSystem.remove(path.join(directory, entry), { force: true });
|
||||
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const rotate = Effect.gen(function* () {
|
||||
yield* fileSystem.remove(withSuffix(maxFiles), { force: true });
|
||||
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
|
||||
for (let index = maxFiles - 1; index >= 1; index -= 1) {
|
||||
const source = withSuffix(index);
|
||||
const sourceExists = yield* fileSystem.exists(source);
|
||||
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
|
||||
if (sourceExists) {
|
||||
yield* fileSystem.rename(source, withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
const currentExists = yield* fileSystem.exists(input.filePath);
|
||||
const currentExists = yield* fileSystem
|
||||
.exists(input.filePath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (currentExists) {
|
||||
yield* fileSystem.rename(input.filePath, withSuffix(1));
|
||||
}
|
||||
yield* Ref.set(currentSize, 0);
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const writeBytes = (
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> => {
|
||||
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
|
||||
if (chunk.byteLength === 0) return Effect.void;
|
||||
|
||||
return mutex.withPermits(1)(
|
||||
@@ -247,9 +178,11 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
|
||||
yield* rotate;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: recoverCurrentSize,
|
||||
}),
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -257,7 +190,6 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
|
||||
yield* pruneOverflowBackups;
|
||||
|
||||
return {
|
||||
filePath: input.filePath,
|
||||
writeBytes,
|
||||
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
|
||||
} satisfies RotatingLogFileWriter;
|
||||
@@ -267,17 +199,10 @@ const writeDevelopmentConsoleOutput = (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
},
|
||||
catch: (cause) => new DesktopBackendConsoleWriteError({ streamName, cause }),
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
DesktopBackendConsoleWriteError: (error) => Effect.logError(error.message, { error }),
|
||||
}),
|
||||
);
|
||||
Effect.sync(() => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
}).pipe(Effect.ignore);
|
||||
|
||||
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
|
||||
function* (
|
||||
@@ -297,47 +222,17 @@ const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackend
|
||||
annotations: input.annotations,
|
||||
spans: {},
|
||||
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopBackendOutputLogWriteError({
|
||||
operation: "encode-record",
|
||||
logFilePath: logFile.filePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* logFile.writeText(`${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopBackendOutputLogWriteError({
|
||||
operation: "write-record",
|
||||
logFilePath: logFile.filePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
DesktopBackendOutputLogWriteError: (error) => Effect.logError(error.message, { error }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
yield* logFile.writeText(`${encoded}\n`);
|
||||
}).pipe(Effect.ignore({ log: true }));
|
||||
},
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const logFilePath = environment.path.join(environment.logDir, "server-child.log");
|
||||
const writer = yield* makeRotatingLogFileWriter({
|
||||
filePath: logFilePath,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) => new DesktopBackendOutputLogSetupError({ logFilePath, cause })),
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
DesktopBackendOutputLogSetupError: (error) =>
|
||||
Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
|
||||
}),
|
||||
);
|
||||
filePath: environment.path.join(environment.logDir, "server-child.log"),
|
||||
}).pipe(Effect.option);
|
||||
|
||||
const service = Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
|
||||
@@ -3,15 +3,12 @@ import {
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -31,7 +28,6 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendBootstrap),
|
||||
);
|
||||
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
|
||||
|
||||
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
@@ -59,9 +55,9 @@ const configWithObservability: DesktopBackendBootstrapValue = {
|
||||
};
|
||||
|
||||
function makeProcess(options?: {
|
||||
readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
readonly stdout?: Stream.Stream<Uint8Array>;
|
||||
readonly stderr?: Stream.Stream<Uint8Array>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
|
||||
}): ChildProcessSpawner.ChildProcessHandle {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
@@ -149,23 +145,6 @@ function makeManagerLayer(input: {
|
||||
}
|
||||
|
||||
describe("DesktopBackendManager", () => {
|
||||
it("preserves the complete restart cause and schedule context", () => {
|
||||
const cause = Cause.combine(
|
||||
Cause.fail(new Error("start failed")),
|
||||
Cause.die(new Error("restart defect")),
|
||||
);
|
||||
const error = new DesktopBackendManager.DesktopBackendRestartError({
|
||||
reason: "backend exited with code 1",
|
||||
delayMs: 500,
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.reason, "backend exited with code 1");
|
||||
assert.equal(error.delayMs, 500);
|
||||
assert.equal(error.message, "Desktop backend restart failed after a scheduled 500ms delay.");
|
||||
});
|
||||
|
||||
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
|
||||
Effect.gen(function* () {
|
||||
let spawnedCommand: ChildProcess.Command | undefined;
|
||||
@@ -239,243 +218,6 @@ describe("DesktopBackendManager", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves the readiness timeout cause and process context", () =>
|
||||
Effect.gen(function* () {
|
||||
const requested = yield* Deferred.make<HttpClientRequest.HttpClientRequest>();
|
||||
const layer = Layer.merge(
|
||||
TestClock.layer(),
|
||||
httpClientLayer((request) =>
|
||||
Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const readiness = yield* DesktopBackendManager.waitForHttpReady({
|
||||
executablePath: baseConfig.executablePath,
|
||||
entryPath: baseConfig.entryPath,
|
||||
cwd: baseConfig.cwd,
|
||||
httpBaseUrl: baseConfig.httpBaseUrl,
|
||||
timeout: Duration.millis(50),
|
||||
}).pipe(Effect.flip, Effect.forkChild);
|
||||
|
||||
const request = yield* Deferred.await(requested);
|
||||
assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment");
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
const error = yield* Fiber.join(readiness);
|
||||
|
||||
assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError);
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment");
|
||||
assert.equal(error.timeoutMs, 50);
|
||||
assert.isTrue(Cause.isTimeoutError(error.cause));
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.",
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports bootstrap encoding failures with stable process context", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
bootstrap: {
|
||||
...baseConfig.bootstrap,
|
||||
port: 0,
|
||||
},
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessBootstrapEncodeError") {
|
||||
return assert.fail(`Expected bootstrap encode error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.isDefined(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.",
|
||||
);
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves spawn failures without deriving their message from the cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "ChildProcessSpawner",
|
||||
method: "spawn",
|
||||
pathOrDescriptor: baseConfig.executablePath,
|
||||
description: "low-level detail that must not become the public message",
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessSpawnError") {
|
||||
return assert.fail(`Expected backend spawn error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.strictEqual(error.cause, spawnCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to spawn desktop backend entry /server/bin.mjs with /electron.",
|
||||
);
|
||||
assert.notInclude(error.message, spawnCause.message);
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves exit-status failures without copying their detail into the message", () =>
|
||||
Effect.gen(function* () {
|
||||
const exitCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "ChildProcess",
|
||||
method: "exitCode",
|
||||
description: "exit-status-secret-sentinel",
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
exitCode: Effect.fail(exitCause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessExitStatusError") {
|
||||
return assert.fail(`Expected backend exit-status error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.strictEqual(error.cause, exitCause);
|
||||
assert.equal(error.message, "Failed to read the exit status of desktop backend process 123.");
|
||||
assert.notInclude(error.message, "exit-status-secret-sentinel");
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports output stream failures with process and stream context", () =>
|
||||
Effect.gen(function* () {
|
||||
const outputCause = PlatformError.systemError({
|
||||
_tag: "BadResource",
|
||||
module: "ChildProcess",
|
||||
method: "stdout",
|
||||
description: "output-stream-secret-sentinel",
|
||||
});
|
||||
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.fail(outputCause),
|
||||
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const exit = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
|
||||
const error = yield* Deferred.await(reported);
|
||||
|
||||
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
|
||||
if (error._tag !== "BackendProcessOutputReadError") {
|
||||
return assert.fail(`Expected output read error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.streamName, "stdout");
|
||||
assert.strictEqual(error.cause, outputCause);
|
||||
assert.equal(error.message, "Failed to read stdout from desktop backend process 123.");
|
||||
assert.notInclude(error.message, "output-stream-secret-sentinel");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports output handler failures separately from stream read failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const chunk = new TextEncoder().encode("backend output");
|
||||
const outputCause = new Error("output-handler-secret-sentinel");
|
||||
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.make(chunk),
|
||||
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const exit = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
onOutput: () => Effect.fail(outputCause),
|
||||
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
|
||||
const error = yield* Deferred.await(reported);
|
||||
|
||||
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
|
||||
if (error._tag !== "BackendProcessOutputHandlingError") {
|
||||
return assert.fail(`Expected output handling error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.streamName, "stdout");
|
||||
assert.equal(error.chunkByteLength, chunk.byteLength);
|
||||
assert.strictEqual(error.cause, outputCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`,
|
||||
);
|
||||
assert.notInclude(error.message, "output-handler-secret-sentinel");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retries HTTP readiness before reporting the backend ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestUrls: Array<string> = [];
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
@@ -42,145 +43,68 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
|
||||
|
||||
export type BackendProcessOutputStream = "stdout" | "stderr";
|
||||
|
||||
export interface BackendProcessContext {
|
||||
export interface DesktopBackendStartConfig {
|
||||
readonly executablePath: string;
|
||||
readonly entryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly httpBaseUrl: URL;
|
||||
}
|
||||
|
||||
export interface DesktopBackendStartConfig extends BackendProcessContext {
|
||||
readonly env: Record<string, string | undefined>;
|
||||
readonly bootstrap: DesktopBackendBootstrapValue;
|
||||
readonly httpBaseUrl: URL;
|
||||
readonly captureOutput: boolean;
|
||||
}
|
||||
|
||||
interface BackendProcessExit {
|
||||
readonly code: Option.Option<number>;
|
||||
readonly reason: string;
|
||||
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
}
|
||||
|
||||
const backendProcessContextSchema = {
|
||||
executablePath: Schema.String,
|
||||
entryPath: Schema.String,
|
||||
cwd: Schema.String,
|
||||
httpBaseUrl: Schema.URL,
|
||||
};
|
||||
|
||||
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
|
||||
"BackendReadinessTimeoutError",
|
||||
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
|
||||
"BackendTimeoutError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
readinessUrl: Schema.URL,
|
||||
timeoutMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
url: Schema.URL,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
|
||||
return `Timed out waiting for backend readiness at ${this.url.href}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
detail: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
|
||||
return `Failed to encode desktop backend bootstrap payload: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
"BackendProcessSpawnError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
detail: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
|
||||
return `Failed to spawn desktop backend process: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
|
||||
"BackendProcessOutputReadError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
|
||||
"BackendProcessOutputHandlingError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
chunkByteLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type BackendProcessOutputError =
|
||||
| BackendProcessOutputReadError
|
||||
| BackendProcessOutputHandlingError;
|
||||
|
||||
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
|
||||
"BackendProcessExitStatusError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendRestartError extends Schema.TaggedErrorClass<DesktopBackendRestartError>()(
|
||||
"DesktopBackendRestartError",
|
||||
{
|
||||
reason: Schema.String,
|
||||
delayMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop backend restart failed after a scheduled ${this.delayMs}ms delay.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BackendProcessError = Schema.Union([
|
||||
BackendProcessBootstrapEncodeError,
|
||||
BackendProcessSpawnError,
|
||||
BackendProcessExitStatusError,
|
||||
]);
|
||||
export type BackendProcessError = typeof BackendProcessError.Type;
|
||||
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
|
||||
|
||||
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
|
||||
readonly readinessTimeout?: Duration.Duration;
|
||||
readonly onStarted?: (pid: number) => Effect.Effect<void>;
|
||||
readonly onReady?: () => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
|
||||
readonly onOutput?: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, Error>;
|
||||
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface DesktopBackendSnapshot {
|
||||
@@ -259,10 +183,11 @@ const closeRun = (
|
||||
).pipe(Effect.ignore);
|
||||
};
|
||||
|
||||
export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
|
||||
options: BackendProcessContext & { readonly timeout: Duration.Duration },
|
||||
): Effect.fn.Return<void, BackendReadinessTimeoutError, HttpClient.HttpClient> {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
|
||||
const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
|
||||
baseUrl: URL,
|
||||
timeout: Duration.Duration,
|
||||
): Effect.fn.Return<void, BackendTimeoutError, HttpClient.HttpClient> {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
|
||||
const client = (yield* HttpClient.HttpClient).pipe(
|
||||
HttpClient.filterStatusOk,
|
||||
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
|
||||
@@ -271,64 +196,43 @@ export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpRea
|
||||
|
||||
yield* client.get(readinessUrl).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.timeout(options.timeout),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendReadinessTimeoutError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
readinessUrl,
|
||||
timeoutMs: Duration.toMillis(options.timeout),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.timeout(timeout),
|
||||
Effect.mapError(() => new BackendTimeoutError({ url: readinessUrl })),
|
||||
);
|
||||
});
|
||||
|
||||
function describeProcessExit(
|
||||
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
|
||||
): BackendProcessExit {
|
||||
if (Result.isSuccess(result)) {
|
||||
return {
|
||||
code: Option.some(result.success),
|
||||
reason: `code=${result.success}`,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
code: Option.none(),
|
||||
reason: result.failure.message,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
function drainBackendOutput(
|
||||
context: BackendProcessContext & { readonly pid: number },
|
||||
streamName: BackendProcessOutputStream,
|
||||
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
|
||||
onOutput: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, Error>,
|
||||
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
|
||||
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
|
||||
): Effect.Effect<void> {
|
||||
return stream.pipe(
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessOutputReadError({
|
||||
...context,
|
||||
streamName,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Stream.runForEach((chunk) =>
|
||||
onOutput(streamName, chunk).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessOutputHandlingError({
|
||||
...context,
|
||||
streamName,
|
||||
chunkByteLength: chunk.byteLength,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
BackendProcessOutputReadError: onOutputFailure,
|
||||
BackendProcessOutputHandlingError: onOutputFailure,
|
||||
}),
|
||||
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
|
||||
Effect.ignore,
|
||||
);
|
||||
}
|
||||
|
||||
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
|
||||
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
options: RunBackendProcessOptions,
|
||||
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
@@ -336,10 +240,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessBootstrapEncodeError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -372,10 +273,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessSpawnError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -383,60 +281,19 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (options.captureOutput) {
|
||||
const outputContext = {
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
pid: Number(handle.pid),
|
||||
};
|
||||
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stdout",
|
||||
handle.stdout,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stderr",
|
||||
handle.stderr,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
|
||||
}
|
||||
yield* waitForHttpReady({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
}).pipe(
|
||||
yield* waitForHttpReady(
|
||||
options.httpBaseUrl,
|
||||
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
).pipe(
|
||||
Effect.tap(() => options.onReady?.() ?? Effect.void),
|
||||
Effect.catchTags({
|
||||
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
|
||||
}),
|
||||
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const exitCode = yield* handle.exitCode.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessExitStatusError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
pid: Number(handle.pid),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
code: Option.some(exitCode),
|
||||
reason: `code=${exitCode}`,
|
||||
} satisfies BackendProcessExit;
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
@@ -494,7 +351,7 @@ export const make = Effect.gen(function* () {
|
||||
const config = yield* configuration.resolve.pipe(
|
||||
Effect.tapError((error) =>
|
||||
logBackendManagerError("failed to generate desktop backend configuration", {
|
||||
cause: error,
|
||||
cause: error.message,
|
||||
}),
|
||||
),
|
||||
Effect.option,
|
||||
@@ -632,26 +489,22 @@ export const make = Effect.gen(function* () {
|
||||
yield* desktopWindow.handleBackendReady.pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendManagerError("failed to open main window after backend readiness", {
|
||||
cause: error,
|
||||
message: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
onReadinessFailure: (error) =>
|
||||
logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
error,
|
||||
error: error.message,
|
||||
}),
|
||||
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
|
||||
onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Scope.provide(runScope),
|
||||
Effect.matchEffect({
|
||||
onFailure: (error) =>
|
||||
logBackendManagerError(error.message, { error }).pipe(
|
||||
Effect.andThen(finalizeRun(error.message)),
|
||||
),
|
||||
onFailure: (error) => finalizeRun(error.message),
|
||||
onSuccess: (exit) => finalizeRun(exit.reason),
|
||||
}),
|
||||
Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
|
||||
@@ -706,17 +559,11 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopBackendRestartError({
|
||||
reason,
|
||||
delayMs: Duration.toMillis(delay),
|
||||
cause,
|
||||
});
|
||||
return logBackendManagerError(error.message, { error });
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logBackendManagerError("desktop backend restart fiber failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
parentScope,
|
||||
);
|
||||
|
||||
@@ -46,49 +46,14 @@ describe("ElectronShell", () => {
|
||||
}).pipe(Effect.provide(ElectronShell.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves safe URL context and cause when Electron rejects openExternal", () =>
|
||||
it.effect("returns false when Electron rejects openExternal", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("open failed");
|
||||
openExternalMock.mockRejectedValue(cause);
|
||||
const externalUrl =
|
||||
"HTTPS://user:[email protected]:443/signed-secret-token/path?access_token=secret#fragment";
|
||||
openExternalMock.mockRejectedValue(new Error("open failed"));
|
||||
|
||||
const electronShell = yield* ElectronShell.ElectronShell;
|
||||
const error = yield* Effect.flip(electronShell.openExternal(externalUrl));
|
||||
const result = yield* electronShell.openExternal("https://example.com/path");
|
||||
|
||||
assert.instanceOf(error, ElectronShell.ElectronShellOpenExternalError);
|
||||
assert.isTrue(ElectronShell.isElectronShellError(error));
|
||||
assert.strictEqual(error.urlHostname, "example.com");
|
||||
assert.strictEqual(error.urlLength, externalUrl.length);
|
||||
assert.strictEqual(error.urlProtocol, "https:");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notProperty(error, "externalUrl");
|
||||
assert.notProperty(error, "requestTarget");
|
||||
assert.notMatch(
|
||||
error.message,
|
||||
/user|password|signed-secret-token|path|access_token|secret|fragment/,
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronShell.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves non-sensitive clipboard context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("clipboard failed");
|
||||
writeTextMock.mockImplementation(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronShell = yield* ElectronShell.ElectronShell;
|
||||
const error = yield* Effect.flip(electronShell.copyText("secret text"));
|
||||
|
||||
assert.instanceOf(error, ElectronShell.ElectronShellCopyTextError);
|
||||
assert.isTrue(ElectronShell.isElectronShellError(error));
|
||||
assert.strictEqual(error.textLength, 11);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "11 characters");
|
||||
assert.notInclude(error.message, "secret text");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
assert.equal(result, false);
|
||||
}).pipe(Effect.provide(ElectronShell.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,47 +1,12 @@
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
const SAFE_EXTERNAL_PROTOCOLS = new Set(["http:", "https:"]);
|
||||
|
||||
export class ElectronShellOpenExternalError extends Schema.TaggedErrorClass<ElectronShellOpenExternalError>()(
|
||||
"ElectronShellOpenExternalError",
|
||||
{
|
||||
urlHostname: Schema.String,
|
||||
urlLength: Schema.Number,
|
||||
urlProtocol: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to open external URL for ${this.urlHostname} (${this.urlProtocol}, input length ${this.urlLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronShellCopyTextError extends Schema.TaggedErrorClass<ElectronShellCopyTextError>()(
|
||||
"ElectronShellCopyTextError",
|
||||
{
|
||||
textLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to copy ${this.textLength} characters to the clipboard.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const ElectronShellError = Schema.Union([
|
||||
ElectronShellOpenExternalError,
|
||||
ElectronShellCopyTextError,
|
||||
]);
|
||||
export type ElectronShellError = typeof ElectronShellError.Type;
|
||||
export const isElectronShellError = Schema.is(ElectronShellError);
|
||||
|
||||
export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
|
||||
if (typeof rawUrl !== "string") {
|
||||
return Option.none();
|
||||
@@ -55,46 +20,29 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
|
||||
}
|
||||
}
|
||||
|
||||
function describeExternalUrl(externalUrl: string, inputLength: number) {
|
||||
const diagnostics = getUrlDiagnostics(externalUrl);
|
||||
return {
|
||||
urlHostname: diagnostics.hostname ?? "",
|
||||
urlLength: inputLength,
|
||||
urlProtocol: diagnostics.protocol ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
export class ElectronShell extends Context.Service<
|
||||
ElectronShell,
|
||||
{
|
||||
readonly openExternal: (
|
||||
rawUrl: unknown,
|
||||
) => Effect.Effect<boolean, ElectronShellOpenExternalError>;
|
||||
readonly copyText: (text: string) => Effect.Effect<void, ElectronShellCopyTextError>;
|
||||
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
|
||||
readonly copyText: (text: string) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronShell") {}
|
||||
|
||||
export const make = ElectronShell.of({
|
||||
openExternal: (rawUrl) => {
|
||||
const inputLength = typeof rawUrl === "string" ? rawUrl.length : 0;
|
||||
|
||||
return Option.match(parseSafeExternalUrl(rawUrl), {
|
||||
openExternal: (rawUrl) =>
|
||||
Option.match(parseSafeExternalUrl(rawUrl), {
|
||||
onNone: () => Effect.succeed(false),
|
||||
onSome: (externalUrl) =>
|
||||
Effect.tryPromise({
|
||||
try: () => Electron.shell.openExternal(externalUrl),
|
||||
catch: (cause) =>
|
||||
new ElectronShellOpenExternalError({
|
||||
...describeExternalUrl(externalUrl, inputLength),
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.as(true)),
|
||||
});
|
||||
},
|
||||
Effect.promise(() =>
|
||||
Electron.shell.openExternal(externalUrl).then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
),
|
||||
}),
|
||||
copyText: (text) =>
|
||||
Effect.try({
|
||||
try: () => Electron.clipboard.writeText(text),
|
||||
catch: (cause) => new ElectronShellCopyTextError({ textLength: text.length, cause }),
|
||||
Effect.sync(() => {
|
||||
Electron.clipboard.writeText(text);
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ export const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-st
|
||||
export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
|
||||
export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
|
||||
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
||||
export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
|
||||
export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
|
||||
export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webview";
|
||||
|
||||
@@ -19,30 +19,37 @@ import {
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import { BrowserWindow } from "electron";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as NodeURL from "node:url";
|
||||
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as PreviewManager from "../../preview/Manager.ts";
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(channel, ...args);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const installPreviewEventForwarding = Effect.fn(
|
||||
"desktop.ipc.preview.installEventForwarding",
|
||||
)(function* () {
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.subscribeStateChanges((tabId, state) =>
|
||||
electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state),
|
||||
);
|
||||
yield* manager.subscribeRecordingFrames((frame) =>
|
||||
electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame),
|
||||
);
|
||||
yield* manager.subscribePointerEvents((event) =>
|
||||
electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event),
|
||||
);
|
||||
yield* manager.subscribeStateChanges((tabId, state) => {
|
||||
broadcast(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
|
||||
});
|
||||
yield* manager.subscribeRecordingFrames((frame) => {
|
||||
broadcast(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
|
||||
});
|
||||
yield* manager.subscribePointerEvents((event) => {
|
||||
broadcast(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
|
||||
});
|
||||
});
|
||||
|
||||
export const createTab = DesktopIpc.makeIpcMethod({
|
||||
|
||||
@@ -1,28 +1,16 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
DesktopSshEnvironmentEnsureResultSchema,
|
||||
DesktopSshPasswordPromptCancellationError,
|
||||
} from "@t3tools/contracts";
|
||||
import { SshHttpBridgeError, SshPasswordPromptError } from "@t3tools/ssh/errors";
|
||||
import { SshHttpBridgeError } from "@t3tools/ssh/errors";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
DesktopSshEnvironmentRequestError,
|
||||
ensureSshEnvironment,
|
||||
fetchSshEnvironmentDescriptor,
|
||||
} from "./sshEnvironment.ts";
|
||||
import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";
|
||||
|
||||
const decodeDesktopSshEnvironmentEnsureResult = Schema.decodeUnknownEffect(
|
||||
DesktopSshEnvironmentEnsureResultSchema,
|
||||
);
|
||||
|
||||
function jsonResponse(request: HttpClientRequest.HttpClientRequest, body: unknown, status = 200) {
|
||||
return HttpClientResponse.fromWeb(
|
||||
@@ -46,44 +34,6 @@ function makeHttpClientLayer(
|
||||
}
|
||||
|
||||
describe("SSH environment IPC", () => {
|
||||
it.effect("encodes password prompt cancellations with structured context and their cause", () => {
|
||||
const promptCause = new DesktopSshPasswordPrompts.DesktopSshPromptWindowClosedError({
|
||||
requestId: "prompt-1",
|
||||
destination: "[email protected]",
|
||||
});
|
||||
const cause = new SshPasswordPromptError({
|
||||
message: promptCause.message,
|
||||
cause: promptCause,
|
||||
});
|
||||
const layer = Layer.succeed(
|
||||
DesktopSshEnvironment.DesktopSshEnvironment,
|
||||
DesktopSshEnvironment.DesktopSshEnvironment.of({
|
||||
discoverHosts: () => Effect.die("unexpected host discovery"),
|
||||
ensureEnvironment: () => Effect.fail(cause),
|
||||
disconnectEnvironment: () => Effect.die("unexpected disconnect"),
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const encoded = yield* ensureSshEnvironment.handler({
|
||||
target: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.test",
|
||||
username: "developer",
|
||||
port: 22,
|
||||
},
|
||||
});
|
||||
const error = yield* decodeDesktopSshEnvironmentEnsureResult(encoded);
|
||||
|
||||
assert.instanceOf(error, DesktopSshPasswordPromptCancellationError);
|
||||
assert.equal(error.reason, "window-closed");
|
||||
assert.equal(error.requestId, "prompt-1");
|
||||
assert.equal(error.destination, "[email protected]");
|
||||
assert.instanceOf(error.cause, Error);
|
||||
assert.instanceOf(error.cause.cause, Error);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("fetches and decodes the remote environment descriptor", () => {
|
||||
const requestUrls: string[] = [];
|
||||
const layer = makeHttpClientLayer((request) =>
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
bootstrapRemoteBearerSession,
|
||||
fetchRemoteSessionState,
|
||||
issueRemoteWebSocketTicket,
|
||||
isRemoteEnvironmentAuthUndeclaredStatusError,
|
||||
RemoteEnvironmentAuthUndeclaredStatusError,
|
||||
type RemoteEnvironmentAuthError,
|
||||
} from "@t3tools/client-runtime/authorization";
|
||||
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
DesktopSshEnvironmentEnsureResultSchema,
|
||||
DesktopSshEnvironmentTargetSchema,
|
||||
DesktopSshHttpBaseUrlInputSchema,
|
||||
DesktopSshPasswordPromptCancellationError,
|
||||
DesktopSshPasswordPromptCancelledType,
|
||||
DesktopSshPasswordPromptResolutionInputSchema,
|
||||
ExecutionEnvironmentDescriptor,
|
||||
EnvironmentInternalError,
|
||||
@@ -45,13 +45,6 @@ type DesktopSshEnvironmentRequestOperation =
|
||||
|
||||
type DesktopSshEnvironmentRequestCause = RemoteEnvironmentAuthError | SshHttpBridgeError;
|
||||
|
||||
const desktopSshPasswordPromptCancellationReasons = {
|
||||
DesktopSshPromptCancelledError: "user-cancelled",
|
||||
DesktopSshPromptWindowClosedError: "window-closed",
|
||||
DesktopSshPromptServiceStoppedError: "service-stopped",
|
||||
DesktopSshPromptTimedOutError: "timed-out",
|
||||
} as const;
|
||||
|
||||
const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
|
||||
const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
|
||||
const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);
|
||||
@@ -59,7 +52,10 @@ const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidErro
|
||||
const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);
|
||||
|
||||
function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {
|
||||
if (isRemoteEnvironmentAuthUndeclaredStatusError(cause) || cause instanceof SshHttpBridgeError) {
|
||||
if (
|
||||
cause instanceof RemoteEnvironmentAuthUndeclaredStatusError ||
|
||||
cause instanceof SshHttpBridgeError
|
||||
) {
|
||||
return cause.status ?? null;
|
||||
}
|
||||
if (isEnvironmentRequestInvalidError(cause)) {
|
||||
@@ -131,19 +127,14 @@ export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
|
||||
}) {
|
||||
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
|
||||
return yield* sshEnvironment.ensureEnvironment(target, options).pipe(
|
||||
Effect.catchTags({
|
||||
SshPasswordPromptError: (error) =>
|
||||
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error)
|
||||
? Effect.succeed(
|
||||
new DesktopSshPasswordPromptCancellationError({
|
||||
reason: desktopSshPasswordPromptCancellationReasons[error.cause._tag],
|
||||
requestId: error.cause.requestId,
|
||||
destination: error.cause.destination,
|
||||
cause: error,
|
||||
}),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
Effect.catch((error) =>
|
||||
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error)
|
||||
? Effect.succeed({
|
||||
type: DesktopSshPasswordPromptCancelledType,
|
||||
message: error.message,
|
||||
})
|
||||
: Effect.fail(error),
|
||||
),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
+12
-15
@@ -1,31 +1,28 @@
|
||||
import {
|
||||
DesktopSshPasswordPromptCancellationError,
|
||||
DesktopSshPasswordPromptCancellationErrorTag,
|
||||
type DesktopBridge,
|
||||
type DesktopPreviewPointerEvent,
|
||||
type DesktopPreviewRecordingFrame,
|
||||
type DesktopPreviewTabState,
|
||||
import type {
|
||||
DesktopBridge,
|
||||
DesktopPreviewPointerEvent,
|
||||
DesktopPreviewRecordingFrame,
|
||||
DesktopPreviewTabState,
|
||||
} from "@t3tools/contracts";
|
||||
import { exposeClerkBridge } from "@clerk/electron/preload";
|
||||
import { contextBridge, ipcRenderer } from "electron";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as IpcChannels from "./ipc/channels.ts";
|
||||
|
||||
exposeClerkBridge({ passkeys: true });
|
||||
|
||||
const decodeDesktopSshPasswordPromptCancellationError = Schema.decodeUnknownSync(
|
||||
DesktopSshPasswordPromptCancellationError,
|
||||
);
|
||||
|
||||
function unwrapEnsureSshEnvironmentResult(result: unknown) {
|
||||
if (
|
||||
typeof result === "object" &&
|
||||
result !== null &&
|
||||
"_tag" in result &&
|
||||
result._tag === DesktopSshPasswordPromptCancellationErrorTag
|
||||
"type" in result &&
|
||||
result.type === IpcChannels.SSH_PASSWORD_PROMPT_CANCELLED_RESULT
|
||||
) {
|
||||
throw decodeDesktopSshPasswordPromptCancellationError(result);
|
||||
const message =
|
||||
"message" in result && typeof result.message === "string"
|
||||
? result.message
|
||||
: "SSH authentication cancelled.";
|
||||
throw new Error(message);
|
||||
}
|
||||
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -14,7 +13,6 @@ import { TestClock } from "effect/testing";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
@@ -132,72 +130,6 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("isolates failed state listeners and continues delivery", () => {
|
||||
const loggedErrors: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
for (const value of Array.isArray(message) ? message : [message]) {
|
||||
if (typeof value === "object" && value !== null && "cause" in value) {
|
||||
loggedErrors.push(Cause.squash(value.cause as Cause.Cause<never>));
|
||||
}
|
||||
}
|
||||
});
|
||||
const deliveryError = new ElectronWindow.ElectronWindowOperationError({
|
||||
operation: "send-window-message",
|
||||
platform: "darwin",
|
||||
windowId: 42,
|
||||
channel: "preview:state-change",
|
||||
cause: new Error("renderer unavailable"),
|
||||
});
|
||||
const delivered = vi.fn();
|
||||
|
||||
return withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
yield* manager.subscribeStateChanges(() => Effect.die(deliveryError));
|
||||
yield* manager.subscribeStateChanges((tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
delivered(tabId, state);
|
||||
}),
|
||||
);
|
||||
|
||||
const state = yield* manager.createTab("tab_listener_failure");
|
||||
|
||||
expect(delivered).toHaveBeenCalledOnce();
|
||||
expect(delivered).toHaveBeenCalledWith("tab_listener_failure", state);
|
||||
expect(loggedErrors).toHaveLength(1);
|
||||
expect(loggedErrors[0]).toBeInstanceOf(ElectronWindow.ElectronWindowOperationError);
|
||||
expect(loggedErrors[0]).toMatchObject({
|
||||
operation: "send-window-message",
|
||||
windowId: 42,
|
||||
channel: "preview:state-change",
|
||||
});
|
||||
}),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Logger.layer([logger], {
|
||||
mergeWithExisting: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
effectIt.effect("does not swallow state listener interruption", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const exit = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* manager.subscribeStateChanges(() => Effect.interrupt);
|
||||
return yield* Effect.exit(manager.createTab("tab_interrupted_listener"));
|
||||
}),
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Cause.hasInterrupts(exit.cause)).toBe(true);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("queues navigation until the webview registers", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -479,11 +411,7 @@ describe("PreviewManager", () => {
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.subscribePointerEvents((event) =>
|
||||
Effect.sync(() => {
|
||||
activity.push(event.phase);
|
||||
}),
|
||||
);
|
||||
yield* manager.subscribePointerEvents((event) => activity.push(event.phase));
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
const click = yield* manager
|
||||
|
||||
@@ -281,8 +281,8 @@ const nextZoomLevel = (current: number, direction: "in" | "out"): number => {
|
||||
return ZOOM_LEVELS[Math.max(step - 1, 0)] ?? current;
|
||||
};
|
||||
|
||||
type Listener = (tabId: string, state: PreviewTabState) => Effect.Effect<void>;
|
||||
type RecordingFrameListener = (frame: DesktopPreviewRecordingFrame) => Effect.Effect<void>;
|
||||
type Listener = (tabId: string, state: PreviewTabState) => void;
|
||||
type RecordingFrameListener = (frame: DesktopPreviewRecordingFrame) => void;
|
||||
|
||||
type PreviewInputSignal =
|
||||
| { readonly kind: "pointer"; readonly x: number; readonly y: number; readonly button: number }
|
||||
@@ -313,7 +313,7 @@ interface BrowserDiagnostics {
|
||||
readonly requests: ReadonlyMap<string, { url: string; method: string }>;
|
||||
}
|
||||
|
||||
type PointerEventListener = (event: DesktopPreviewPointerEvent) => Effect.Effect<void>;
|
||||
type PointerEventListener = (event: DesktopPreviewPointerEvent) => void;
|
||||
|
||||
interface ExpectedAgentInput {
|
||||
readonly signal: PreviewInputSignal;
|
||||
@@ -442,28 +442,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return copy;
|
||||
};
|
||||
|
||||
const deliverEvent = (
|
||||
eventKind: "state-change" | "recording-frame" | "pointer-event",
|
||||
tabId: string,
|
||||
delivery: () => Effect.Effect<void>,
|
||||
) =>
|
||||
Effect.suspend(delivery).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterrupts(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logWarning("Desktop preview event listener failed.", {
|
||||
eventKind,
|
||||
tabId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const emit = Effect.fn("PreviewManager.emit")(function* (tabId: string, state: PreviewTabState) {
|
||||
const listeners = yield* Ref.get(listenersRef);
|
||||
yield* Effect.forEach(
|
||||
listeners,
|
||||
(listener) => deliverEvent("state-change", tabId, () => listener(tabId, state)),
|
||||
(listener) => Effect.sync(() => listener(tabId, state)).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
@@ -756,8 +739,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
};
|
||||
yield* Effect.forEach(
|
||||
listeners,
|
||||
(listener) =>
|
||||
deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
|
||||
(listener) => Effect.sync(() => listener(frame)).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
@@ -1936,7 +1918,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const listeners = yield* Ref.get(pointerEventListenersRef);
|
||||
yield* Effect.forEach(
|
||||
listeners,
|
||||
(listener) => deliverEvent("pointer-event", event.tabId, () => listener(event)),
|
||||
(listener) => Effect.sync(() => listener(event)).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
@@ -83,6 +83,12 @@ export class DesktopSettingsWriteError extends Schema.TaggedErrorClass<DesktopSe
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopSettingsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopSettingsWriteError => new DesktopSettingsWriteError({ operation, path, cause });
|
||||
|
||||
export class DesktopAppSettings extends Context.Service<
|
||||
DesktopAppSettings,
|
||||
{
|
||||
@@ -238,46 +244,18 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeDesktopSettingsJson(
|
||||
toDesktopSettingsDocument(input.settings, input.defaultSettings),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "encode-document",
|
||||
path: input.settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "replace-settings-file",
|
||||
path: input.settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => writeError("encode-document", input.settingsPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.makeDirectory(directory, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
|
||||
yield* input.fileSystem
|
||||
.writeFileString(tempPath, `${encoded}\n`)
|
||||
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.rename(tempPath, input.settingsPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-settings-file", input.settingsPath, cause)),
|
||||
);
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
@@ -298,13 +276,8 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: environment.desktopSettingsPath,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.desktopSettingsPath, cause),
|
||||
),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeSettings({
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
|
||||
|
||||
interface LogRecord {
|
||||
readonly message: unknown;
|
||||
readonly annotations: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
const baseDir = "/virtual-home";
|
||||
|
||||
function makeLayer(fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
|
||||
),
|
||||
);
|
||||
|
||||
return DesktopClientSettings.layer.pipe(
|
||||
Layer.provideMerge(Layer.mergeAll(environmentLayer, NodeServices.layer, fileSystemLayer)),
|
||||
);
|
||||
}
|
||||
|
||||
const readWithLogs = (fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) => {
|
||||
const records: Array<LogRecord> = [];
|
||||
const logger = Logger.make(({ fiber, message }) => {
|
||||
records.push({
|
||||
message,
|
||||
annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
|
||||
});
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
return {
|
||||
result: yield* settings.get,
|
||||
settingsPath: environment.clientSettingsPath,
|
||||
records,
|
||||
};
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
makeLayer(fileSystemLayer),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
describe("DesktopClientSettings diagnostics", () => {
|
||||
it.effect("treats a missing settings file as expected without warning", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* readWithLogs(FileSystem.layerNoop({}));
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
assert.deepEqual(result.records, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs non-missing filesystem failures with the settings path", () => {
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/userdata/client-settings.json`,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const result = yield* readWithLogs(
|
||||
FileSystem.layerNoop({
|
||||
readFileString: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
assert.equal(result.records.length, 1);
|
||||
assert.deepEqual(result.records[0]?.message, [
|
||||
"Could not read desktop client settings.",
|
||||
permissionError,
|
||||
]);
|
||||
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("logs malformed settings documents with the settings path", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* readWithLogs(
|
||||
FileSystem.layerNoop({
|
||||
readFileString: () => Effect.succeed("{not-json"),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
assert.equal(result.records.length, 1);
|
||||
const message = result.records[0]?.message;
|
||||
if (!Array.isArray(message)) {
|
||||
return assert.fail("expected structured warning arguments");
|
||||
}
|
||||
assert.equal(message[0], "Could not decode desktop client settings.");
|
||||
const schemaError = message[1];
|
||||
if (schemaError === null || typeof schemaError !== "object") {
|
||||
return assert.fail("expected the schema error in the warning");
|
||||
}
|
||||
assert.equal("_tag" in schemaError ? schemaError._tag : undefined, "SchemaError");
|
||||
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -67,29 +67,14 @@ const readClientSettings = (
|
||||
settingsPath: string,
|
||||
): Effect.Effect<Option.Option<ClientSettings>> =>
|
||||
fileSystem.readFileString(settingsPath).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(Option.none<string>())
|
||||
: Effect.logWarning("Could not read desktop client settings.", cause).pipe(
|
||||
Effect.annotateLogs({ settingsPath }),
|
||||
Effect.as(Option.none<string>()),
|
||||
),
|
||||
}),
|
||||
Effect.option,
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed(Option.none<ClientSettings>()),
|
||||
onSome: (raw) =>
|
||||
decodeClientSettingsJson(raw).pipe(
|
||||
Effect.map((settings) => Option.some(settings)),
|
||||
Effect.catchTags({
|
||||
SchemaError: (cause) =>
|
||||
Effect.logWarning("Could not decode desktop client settings.", cause).pipe(
|
||||
Effect.annotateLogs({ settingsPath }),
|
||||
Effect.as(Option.none<ClientSettings>()),
|
||||
),
|
||||
}),
|
||||
Effect.orElseSucceed(() => Option.none<ClientSettings>()),
|
||||
),
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -75,9 +75,7 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
|
||||
|
||||
export function isDesktopSshPasswordPromptCancellation(
|
||||
error: unknown,
|
||||
): error is SshPasswordPromptError & {
|
||||
readonly cause: DesktopSshPasswordPrompts.DesktopSshPasswordPromptCancellation;
|
||||
} {
|
||||
): error is SshPasswordPromptError {
|
||||
return (
|
||||
error instanceof SshPasswordPromptError &&
|
||||
DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause)
|
||||
|
||||
@@ -7,10 +7,7 @@ import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
|
||||
@@ -27,9 +24,6 @@ interface UpdatesHarnessOptions {
|
||||
void,
|
||||
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
|
||||
>;
|
||||
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
|
||||
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
|
||||
readonly stopBackend?: Effect.Effect<void>;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
}
|
||||
|
||||
@@ -73,7 +67,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
Effect.sync(() => {
|
||||
allowDowngrade = value;
|
||||
}),
|
||||
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
|
||||
setDisableDifferentialDownload: () => Effect.void,
|
||||
checkForUpdates: Effect.sync(() => {
|
||||
checkCount += 1;
|
||||
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
|
||||
@@ -109,7 +103,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
|
||||
const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
|
||||
start: Effect.void,
|
||||
stop: () => options.stopBackend ?? Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none()),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: false,
|
||||
@@ -144,23 +138,12 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
),
|
||||
);
|
||||
|
||||
const setUpdateChannelError = options.setUpdateChannelError;
|
||||
const settingsLayer = setUpdateChannelError
|
||||
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
|
||||
: DesktopAppSettings.layer;
|
||||
|
||||
const layer = DesktopUpdates.layer.pipe(
|
||||
Layer.provideMerge(updaterLayer),
|
||||
Layer.provideMerge(windowLayer),
|
||||
Layer.provideMerge(backendLayer),
|
||||
Layer.provideMerge(DesktopState.layer),
|
||||
Layer.provideMerge(settingsLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layer),
|
||||
Layer.provideMerge(
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
@@ -192,45 +175,6 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
}
|
||||
|
||||
describe("DesktopUpdates", () => {
|
||||
it("preserves complete causes for update poller and event failures", () => {
|
||||
const cause = Cause.combine(
|
||||
Cause.fail(new Error("updater failed")),
|
||||
Cause.die(new Error("updater defect")),
|
||||
);
|
||||
const pollerError = new DesktopUpdates.DesktopUpdatePollerError({
|
||||
poller: "startup",
|
||||
cause,
|
||||
});
|
||||
const eventError = new DesktopUpdates.DesktopUpdateEventHandlingError({
|
||||
event: "download-progress",
|
||||
cause,
|
||||
});
|
||||
const reportedError = new DesktopUpdates.DesktopUpdaterReportedError({
|
||||
operation: "download",
|
||||
cause,
|
||||
});
|
||||
const unexpectedActionError = new DesktopUpdates.DesktopUpdateUnexpectedActionError({
|
||||
action: "install",
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.strictEqual(pollerError.cause, cause);
|
||||
assert.equal(pollerError.poller, "startup");
|
||||
assert.equal(pollerError.message, "Desktop update startup poller failed.");
|
||||
assert.strictEqual(eventError.cause, cause);
|
||||
assert.equal(eventError.event, "download-progress");
|
||||
assert.equal(eventError.message, "Failed to handle desktop update download-progress event.");
|
||||
assert.strictEqual(reportedError.cause, cause);
|
||||
assert.equal(reportedError.operation, "download");
|
||||
assert.equal(reportedError.message, "Desktop updater download operation reported an error.");
|
||||
assert.strictEqual(unexpectedActionError.cause, cause);
|
||||
assert.equal(unexpectedActionError.action, "install");
|
||||
assert.equal(
|
||||
unexpectedActionError.message,
|
||||
"Desktop update install action failed unexpectedly.",
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("configures the updater and runs startup checks on the test clock", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
@@ -278,178 +222,6 @@ describe("DesktopUpdates", () => {
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("keeps raw updater event failures out of update state", () => {
|
||||
const harness = makeHarness();
|
||||
const cause = new Error(
|
||||
"request failed for https://user:[email protected]/update?token=secret",
|
||||
);
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
|
||||
harness.emit("error", cause);
|
||||
yield* flushCallbacks;
|
||||
|
||||
const state = yield* updates.getState;
|
||||
assert.equal(state.status, "error");
|
||||
assert.equal(state.message, "Desktop updater background operation reported an error.");
|
||||
assert.notInclude(state.message ?? "", "secret");
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("logs bounded updater failure context without exposing the cause", () => {
|
||||
const cause = new Error(
|
||||
"request failed for https://user:[email protected]/update?token=secret",
|
||||
);
|
||||
const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
|
||||
channel: null,
|
||||
cause,
|
||||
});
|
||||
const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
|
||||
const loggedAnnotations: Array<Record<string, unknown>> = [];
|
||||
const logger = Logger.make(({ fiber }) => {
|
||||
const annotations = fiber.getRef(References.CurrentLogAnnotations);
|
||||
if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
|
||||
loggedAnnotations.push(annotations);
|
||||
}
|
||||
});
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
|
||||
yield* updates.check("manual");
|
||||
|
||||
const state = yield* updates.getState;
|
||||
const loggedAnnotation = loggedAnnotations.at(-1);
|
||||
assert.isDefined(loggedAnnotation);
|
||||
assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
|
||||
assert.isNull(loggedAnnotation.channel);
|
||||
assert.notProperty(loggedAnnotation, "error");
|
||||
assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
|
||||
assert.equal(
|
||||
state.message,
|
||||
"Electron updater failed to check for updates on channel default.",
|
||||
);
|
||||
assert.notInclude(state.message ?? "", "secret");
|
||||
}),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
TestClock.layer(),
|
||||
harness.layer,
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("recovers download state after an unexpected setup failure", () => {
|
||||
let disableDifferentialCalls = 0;
|
||||
const harness = makeHarness({
|
||||
setDisableDifferentialDownload: Effect.suspend(() => {
|
||||
disableDifferentialCalls += 1;
|
||||
return disableDifferentialCalls === 1
|
||||
? Effect.void
|
||||
: Effect.die(new Error("download setup failed"));
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* flushCallbacks;
|
||||
|
||||
const result = yield* updates.download;
|
||||
assert.isTrue(result.accepted);
|
||||
assert.isFalse(result.completed);
|
||||
|
||||
const failedState = yield* updates.getState;
|
||||
assert.equal(failedState.status, "available");
|
||||
assert.equal(failedState.errorContext, "download");
|
||||
assert.equal(failedState.message, "Desktop update download action failed unexpectedly.");
|
||||
|
||||
const changedState = yield* updates.setChannel("nightly");
|
||||
assert.equal(changedState.channel, "nightly");
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("restores download state and permits retry after interruption", () =>
|
||||
Effect.gen(function* () {
|
||||
const actionStarted = yield* Deferred.make<void>();
|
||||
let disableDifferentialCalls = 0;
|
||||
const harness = makeHarness({
|
||||
setDisableDifferentialDownload: Effect.suspend(() => {
|
||||
disableDifferentialCalls += 1;
|
||||
if (disableDifferentialCalls === 1) {
|
||||
return Effect.void;
|
||||
}
|
||||
if (disableDifferentialCalls === 2) {
|
||||
return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
|
||||
}
|
||||
return Effect.void;
|
||||
}),
|
||||
});
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* flushCallbacks;
|
||||
|
||||
const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
|
||||
yield* Deferred.await(actionStarted);
|
||||
yield* Fiber.interrupt(downloadFiber);
|
||||
|
||||
const interruptedState = yield* updates.getState;
|
||||
assert.equal(interruptedState.status, "available");
|
||||
assert.isNull(interruptedState.message);
|
||||
|
||||
const retry = yield* updates.download;
|
||||
assert.isTrue(retry.accepted);
|
||||
assert.isTrue(retry.completed);
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears quitting state after an unexpected install setup failure", () => {
|
||||
const harness = makeHarness({
|
||||
stopBackend: Effect.die(new Error("backend stop failed")),
|
||||
});
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* flushCallbacks;
|
||||
|
||||
const result = yield* updates.install;
|
||||
assert.isTrue(result.accepted);
|
||||
assert.isFalse(result.completed);
|
||||
assert.isFalse(yield* Ref.get(desktopState.quitting));
|
||||
|
||||
const failedState = yield* updates.getState;
|
||||
assert.equal(failedState.status, "downloaded");
|
||||
assert.equal(failedState.errorContext, "install");
|
||||
assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
|
||||
|
||||
const changedState = yield* updates.setChannel("nightly");
|
||||
assert.equal(changedState.channel, "nightly");
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("persists channel changes through the settings service", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
@@ -512,7 +284,6 @@ describe("DesktopUpdates", () => {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError);
|
||||
assert.equal(error.action, "check");
|
||||
assert.equal(error.requestedChannel, "nightly");
|
||||
}
|
||||
|
||||
yield* Deferred.succeed(releaseCheck, undefined);
|
||||
@@ -521,31 +292,4 @@ describe("DesktopUpdates", () => {
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
|
||||
const diskFailure = new Error("disk exploded");
|
||||
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
|
||||
operation: "replace-settings-file",
|
||||
path: "/tmp/settings.json",
|
||||
cause: diskFailure,
|
||||
});
|
||||
const harness = makeHarness({ setUpdateChannelError: settingsFailure });
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
|
||||
const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
|
||||
assert.isTrue(DesktopUpdates.isDesktopUpdateSetChannelError(error));
|
||||
assert.equal(error.channel, "nightly");
|
||||
assert.strictEqual(error.cause, settingsFailure);
|
||||
assert.strictEqual(error.cause.cause, diskFailure);
|
||||
assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
|
||||
assert.notInclude(error.message, diskFailure.message);
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,9 @@
|
||||
import {
|
||||
DesktopUpdateChannelSchema,
|
||||
type DesktopRuntimeInfo,
|
||||
type DesktopUpdateActionResult,
|
||||
type DesktopUpdateChannel,
|
||||
type DesktopUpdateCheckResult,
|
||||
type DesktopUpdateState,
|
||||
import type {
|
||||
DesktopRuntimeInfo,
|
||||
DesktopUpdateActionResult,
|
||||
DesktopUpdateChannel,
|
||||
DesktopUpdateCheckResult,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
@@ -64,82 +63,30 @@ export class DesktopUpdateActionInProgressError extends Schema.TaggedErrorClass<
|
||||
"DesktopUpdateActionInProgressError",
|
||||
{
|
||||
action: Schema.Literals(["check", "download", "install"]),
|
||||
requestedChannel: DesktopUpdateChannelSchema,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Cannot change the desktop update channel to ${this.requestedChannel} while an update ${this.action} action is in progress.`;
|
||||
return `Cannot change update tracks while an update ${this.action} action is in progress.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopUpdateChannelPersistenceError extends Schema.TaggedErrorClass<DesktopUpdateChannelPersistenceError>()(
|
||||
"DesktopUpdateChannelPersistenceError",
|
||||
export class DesktopUpdatePersistenceError extends Schema.TaggedErrorClass<DesktopUpdatePersistenceError>()(
|
||||
"DesktopUpdatePersistenceError",
|
||||
{
|
||||
channel: DesktopUpdateChannelSchema,
|
||||
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to persist the ${this.channel} desktop update channel.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopUpdatePollerError extends Schema.TaggedErrorClass<DesktopUpdatePollerError>()(
|
||||
"DesktopUpdatePollerError",
|
||||
{
|
||||
poller: Schema.Literals(["startup", "poll"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop update ${this.poller} poller failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopUpdateEventHandlingError extends Schema.TaggedErrorClass<DesktopUpdateEventHandlingError>()(
|
||||
"DesktopUpdateEventHandlingError",
|
||||
{
|
||||
event: Schema.Literals(["update-available", "download-progress", "update-downloaded"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to handle desktop update ${this.event} event.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopUpdaterReportedError extends Schema.TaggedErrorClass<DesktopUpdaterReportedError>()(
|
||||
"DesktopUpdaterReportedError",
|
||||
{
|
||||
operation: Schema.Literals(["check", "download", "install", "background"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop updater ${this.operation} operation reported an error.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopUpdateUnexpectedActionError extends Schema.TaggedErrorClass<DesktopUpdateUnexpectedActionError>()(
|
||||
"DesktopUpdateUnexpectedActionError",
|
||||
{
|
||||
action: Schema.Literals(["download", "install"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop update ${this.action} action failed unexpectedly.`;
|
||||
const detail = this.cause instanceof Error ? this.cause.message : String(this.cause);
|
||||
return `Failed to persist desktop update settings: ${detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopUpdateConfigureError = never;
|
||||
|
||||
export const DesktopUpdateSetChannelError = Schema.Union([
|
||||
DesktopUpdateActionInProgressError,
|
||||
DesktopUpdateChannelPersistenceError,
|
||||
]);
|
||||
export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
|
||||
export const isDesktopUpdateSetChannelError = Schema.is(DesktopUpdateSetChannelError);
|
||||
export type DesktopUpdateSetChannelError =
|
||||
| DesktopUpdateActionInProgressError
|
||||
| DesktopUpdatePersistenceError;
|
||||
|
||||
export class DesktopUpdates extends Context.Service<
|
||||
DesktopUpdates,
|
||||
@@ -361,21 +308,16 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return yield* electronUpdater.checkForUpdates.pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchTags({
|
||||
ElectronUpdaterCheckForUpdatesError: Effect.fn(
|
||||
"desktop.updates.handleCheckForUpdatesFailure",
|
||||
)(function* (error) {
|
||||
Effect.catch(
|
||||
Effect.fn("desktop.updates.handleCheckForUpdatesFailure")(function* (error) {
|
||||
const failedAt = yield* currentIsoTimestamp;
|
||||
yield* updateState((current) =>
|
||||
reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
|
||||
);
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
channel: error.channel,
|
||||
});
|
||||
yield* logUpdaterError("failed to check for updates", { message: error.message });
|
||||
return true;
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.ensuring(Ref.set(updateCheckInFlightRef, false)),
|
||||
);
|
||||
});
|
||||
@@ -400,50 +342,19 @@ export const make = Effect.gen(function* () {
|
||||
yield* electronUpdater.downloadUpdate;
|
||||
return { accepted: true, completed: true };
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
ElectronUpdaterDownloadUpdateError: Effect.fn("desktop.updates.handleDownloadFailure")(
|
||||
function* (error) {
|
||||
yield* updateState((current) =>
|
||||
reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
|
||||
);
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
channel: error.channel,
|
||||
});
|
||||
return { accepted: true, completed: false };
|
||||
},
|
||||
),
|
||||
}),
|
||||
Effect.onInterrupt(() =>
|
||||
updateState((current) => (current.status === "downloading" ? state : current)).pipe(
|
||||
Effect.asVoid,
|
||||
),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
const error = new DesktopUpdateUnexpectedActionError({ action: "download", cause });
|
||||
return Effect.gen(function* () {
|
||||
Effect.catch(
|
||||
Effect.fn("desktop.updates.handleDownloadFailure")(function* (error) {
|
||||
yield* updateState((current) =>
|
||||
reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
|
||||
);
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
action: error.action,
|
||||
});
|
||||
yield* logUpdaterError("failed to download update", { message: error.message });
|
||||
return { accepted: true, completed: false };
|
||||
});
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.ensuring(Ref.set(updateDownloadInFlightRef, false)),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
|
||||
|
||||
const resetInstallAction = Effect.all(
|
||||
[Ref.set(updateInstallInFlightRef, false), Ref.set(desktopState.quitting, false)],
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
const installDownloadedUpdate = Effect.gen(function* () {
|
||||
const state = yield* Ref.get(updateStateRef);
|
||||
if (
|
||||
@@ -466,38 +377,14 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
return { accepted: true, completed: false };
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
|
||||
function* (error) {
|
||||
yield* resetInstallAction;
|
||||
yield* updateState((current) =>
|
||||
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
|
||||
);
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
channel: error.channel,
|
||||
isSilent: error.isSilent,
|
||||
isForceRunAfter: error.isForceRunAfter,
|
||||
});
|
||||
return { accepted: true, completed: false };
|
||||
},
|
||||
),
|
||||
}),
|
||||
Effect.onInterrupt(() => resetInstallAction),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.gen(function* () {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return yield* Effect.failCause(cause);
|
||||
}
|
||||
yield* resetInstallAction;
|
||||
const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
|
||||
Effect.catch(
|
||||
Effect.fn("desktop.updates.handleInstallFailure")(function* (error) {
|
||||
yield* Ref.set(updateInstallInFlightRef, false);
|
||||
yield* updateState((current) =>
|
||||
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
|
||||
);
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
action: error.action,
|
||||
});
|
||||
yield* Ref.set(desktopState.quitting, false);
|
||||
yield* logUpdaterError("failed to install update", { message: error.message });
|
||||
return { accepted: true, completed: false };
|
||||
}),
|
||||
),
|
||||
@@ -507,31 +394,17 @@ export const make = Effect.gen(function* () {
|
||||
const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
|
||||
yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
|
||||
Effect.andThen(checkForUpdates("startup")),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopUpdatePollerError({ poller: "startup", cause });
|
||||
return logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
poller: error.poller,
|
||||
});
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logUpdaterError("startup update check failed", { cause: Cause.pretty(cause) }),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
|
||||
Effect.andThen(checkForUpdates("poll")),
|
||||
Effect.forever,
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopUpdatePollerError({ poller: "poll", cause });
|
||||
return logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
poller: error.poller,
|
||||
});
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logUpdaterError("poll update check failed", { cause: Cause.pretty(cause) }),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.updates.startPollers"));
|
||||
@@ -562,16 +435,11 @@ export const make = Effect.gen(function* () {
|
||||
yield* logUpdaterInfo("update available", { version: info.version });
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
|
||||
return logUpdaterWarning(error.message, {
|
||||
errorTag: error._tag,
|
||||
event: error.event,
|
||||
});
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logUpdaterWarning("ignored malformed update-available event", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -584,23 +452,14 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
|
||||
|
||||
const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
|
||||
cause: unknown,
|
||||
error: unknown,
|
||||
) {
|
||||
const activeAction = yield* activeUpdateAction;
|
||||
const error = new DesktopUpdaterReportedError({
|
||||
operation: Option.getOrElse(activeAction, () => "background" as const),
|
||||
cause,
|
||||
});
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (yield* Ref.get(updateInstallInFlightRef)) {
|
||||
yield* Ref.set(updateInstallInFlightRef, false);
|
||||
yield* Ref.set(desktopState.quitting, false);
|
||||
yield* updateState((current) =>
|
||||
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
|
||||
);
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
operation: error.operation,
|
||||
});
|
||||
yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
|
||||
yield* logUpdaterError("updater error", { message });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -610,7 +469,7 @@ export const make = Effect.gen(function* () {
|
||||
yield* updateState((current) => ({
|
||||
...current,
|
||||
status: "error",
|
||||
message: error.message,
|
||||
message,
|
||||
checkedAt,
|
||||
downloadPercent: null,
|
||||
errorContext,
|
||||
@@ -618,10 +477,7 @@ export const make = Effect.gen(function* () {
|
||||
}));
|
||||
}
|
||||
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
operation: error.operation,
|
||||
});
|
||||
yield* logUpdaterError("updater error", { message });
|
||||
});
|
||||
|
||||
const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
|
||||
@@ -643,16 +499,11 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
|
||||
return logUpdaterWarning(error.message, {
|
||||
errorTag: error._tag,
|
||||
event: error.event,
|
||||
});
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logUpdaterWarning("ignored malformed download-progress event", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -667,16 +518,11 @@ export const make = Effect.gen(function* () {
|
||||
yield* logUpdaterInfo("update downloaded", { version: info.version });
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
|
||||
return logUpdaterWarning(error.message, {
|
||||
errorTag: error._tag,
|
||||
event: error.event,
|
||||
});
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logUpdaterWarning("ignored malformed update-downloaded event", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -752,10 +598,7 @@ export const make = Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel: nextChannel });
|
||||
const activeAction = yield* activeUpdateAction;
|
||||
if (Option.isSome(activeAction)) {
|
||||
return yield* new DesktopUpdateActionInProgressError({
|
||||
action: activeAction.value,
|
||||
requestedChannel: nextChannel,
|
||||
});
|
||||
return yield* new DesktopUpdateActionInProgressError({ action: activeAction.value });
|
||||
}
|
||||
|
||||
const state = yield* Ref.get(updateStateRef);
|
||||
@@ -765,11 +608,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
yield* desktopSettings
|
||||
.setUpdateChannel(nextChannel)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
|
||||
),
|
||||
);
|
||||
.pipe(Effect.mapError((cause) => new DesktopUpdatePersistenceError({ cause })));
|
||||
|
||||
const enabled = yield* shouldEnableAutoUpdates;
|
||||
yield* setState(createBaseUpdateState(nextChannel, enabled, environment));
|
||||
|
||||
@@ -226,9 +226,7 @@ export const make = Effect.gen(function* () {
|
||||
{
|
||||
label: "Copy Link",
|
||||
click: () => {
|
||||
void runPromise(
|
||||
electronShell.copyText(params.linkURL).pipe(Effect.ignore({ log: true })),
|
||||
);
|
||||
void runPromise(electronShell.copyText(params.linkURL));
|
||||
},
|
||||
},
|
||||
{ type: "separator" },
|
||||
@@ -255,7 +253,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
window.webContents.setWindowOpenHandler(({ url }) => {
|
||||
if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
|
||||
void runPromise(electronShell.openExternal(url).pipe(Effect.ignore({ log: true })));
|
||||
void runPromise(electronShell.openExternal(url));
|
||||
}
|
||||
return { action: "deny" };
|
||||
});
|
||||
@@ -271,7 +269,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
event.preventDefault();
|
||||
if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
|
||||
void runPromise(electronShell.openExternal(url).pipe(Effect.ignore({ log: true })));
|
||||
void runPromise(electronShell.openExternal(url));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -397,7 +397,7 @@ function CloudEnvironmentRowShell(props: {
|
||||
className={cn("text-xs leading-[16px] underline", statusClassName)}
|
||||
onLongPress={(event) => {
|
||||
event.stopPropagation();
|
||||
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
|
||||
copyTextWithHaptic(errorTraceId);
|
||||
}}
|
||||
onPress={(event) => {
|
||||
event.stopPropagation();
|
||||
@@ -441,7 +441,7 @@ function CopyTraceIdButton(props: { readonly traceId: string }) {
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => {
|
||||
copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
|
||||
copyTextWithHaptic(props.traceId);
|
||||
}}
|
||||
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
|
||||
>
|
||||
|
||||
@@ -3,10 +3,7 @@ import {
|
||||
type ConnectionCatalogDocument as ConnectionCatalogDocumentType,
|
||||
EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import {
|
||||
ConnectionStorageOperationError,
|
||||
ConnectionTransientError,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { ConnectionTransientError } from "@t3tools/client-runtime/connection";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
@@ -18,38 +15,30 @@ import { migrateLegacyConnectionCatalog } from "./migration";
|
||||
export const CONNECTION_CATALOG_KEY = "t3code.connection-catalog.v1";
|
||||
export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
|
||||
|
||||
const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
|
||||
const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson);
|
||||
const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
const decodeCatalog = Effect.fn("mobile.connectionStorage.decodeCatalog")(function* (raw: string) {
|
||||
return yield* decodeConnectionCatalogDocument(raw).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "decode",
|
||||
backend: "schema",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
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)));
|
||||
});
|
||||
|
||||
const encodeCatalog = Effect.fn("mobile.connectionStorage.encodeCatalog")(function* (
|
||||
catalog: ConnectionCatalogDocumentType,
|
||||
) {
|
||||
return yield* encodeConnectionCatalogDocument(catalog).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "encode",
|
||||
backend: "schema",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(ConnectionCatalogDocument)(catalog),
|
||||
).pipe(Effect.mapError((cause) => catalogError("encode", cause)));
|
||||
return JSON.stringify(encoded);
|
||||
});
|
||||
|
||||
interface CatalogStore {
|
||||
@@ -77,21 +66,12 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS
|
||||
legacyRaw === null || legacyRaw.trim() === ""
|
||||
? EMPTY_CONNECTION_CATALOG_DOCUMENT
|
||||
: yield* migrateLegacyConnectionCatalog(legacyRaw).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "migrate",
|
||||
backend: "legacy-migration",
|
||||
cause,
|
||||
}),
|
||||
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.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);
|
||||
@@ -110,13 +90,12 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS
|
||||
let catalog: ConnectionCatalogDocumentType;
|
||||
if (raw !== null && raw.trim() !== "") {
|
||||
catalog = yield* decodeCatalog(raw).pipe(
|
||||
Effect.catchTags({
|
||||
ConnectionTransientError: (error) =>
|
||||
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
|
||||
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
|
||||
Effect.andThen(loadLegacyCatalog()),
|
||||
),
|
||||
}),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
|
||||
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
|
||||
Effect.andThen(loadLegacyCatalog()),
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
catalog = yield* loadLegacyCatalog();
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { LegacyConnectionMigrationError, migrateLegacyConnectionCatalog } from "./migration";
|
||||
import { migrateLegacyConnectionCatalog } from "./migration";
|
||||
|
||||
describe("migrateLegacyConnectionCatalog", () => {
|
||||
it.effect("migrates bearer and relay-managed connections into the new catalog", () =>
|
||||
@@ -75,28 +75,4 @@ 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.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -36,14 +36,9 @@ const decodeLegacyConnectionDocument = Schema.decodeUnknownEffect(LegacyConnecti
|
||||
export class LegacyConnectionMigrationError extends Schema.TaggedErrorClass<LegacyConnectionMigrationError>()(
|
||||
"LegacyConnectionMigrationError",
|
||||
{
|
||||
stage: Schema.Literals(["parse", "decode"]),
|
||||
cause: Schema.Defect(),
|
||||
message: Schema.String,
|
||||
},
|
||||
) {
|
||||
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";
|
||||
@@ -97,10 +92,18 @@ export const migrateLegacyConnectionCatalog = Effect.fn(
|
||||
)(function* (raw: string) {
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => new LegacyConnectionMigrationError({ stage: "parse", cause }),
|
||||
catch: (cause) =>
|
||||
new LegacyConnectionMigrationError({
|
||||
message: `Could not parse the legacy mobile connection catalog: ${String(cause)}`,
|
||||
}),
|
||||
});
|
||||
const legacy = yield* decodeLegacyConnectionDocument(parsed).pipe(
|
||||
Effect.mapError((cause) => new LegacyConnectionMigrationError({ stage: "decode", cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new LegacyConnectionMigrationError({
|
||||
message: `Could not decode the legacy mobile connection catalog: ${String(cause)}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return (legacy.connections ?? []).reduce(migrateConnection, EMPTY_CONNECTION_CATALOG_DOCUMENT);
|
||||
|
||||
@@ -100,8 +100,7 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
(error) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "network",
|
||||
detail: "Could not read the T3 Cloud session token.",
|
||||
cause: error,
|
||||
detail: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -127,8 +126,7 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
catch: (cause) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: "Could not load the mobile device identity.",
|
||||
cause,
|
||||
detail: `Could not load the mobile device identity: ${String(cause)}`,
|
||||
}),
|
||||
}).pipe(Effect.map(Option.some)),
|
||||
}),
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import { TokenStore } from "@t3tools/client-runtime/authorization";
|
||||
import {
|
||||
ConnectionStorageOperationError,
|
||||
ConnectionTransientError,
|
||||
CredentialStore,
|
||||
ProfileStore,
|
||||
@@ -55,11 +54,29 @@ const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
snapshotReceivedAt: Schema.String,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
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 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)}`,
|
||||
});
|
||||
}
|
||||
|
||||
function threadSnapshotFileName(threadId: ThreadId): string {
|
||||
return `${encodeURIComponent(threadId)}.json`;
|
||||
@@ -83,14 +100,7 @@ const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapsh
|
||||
}
|
||||
return directory;
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation,
|
||||
stage: "resolve",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -100,63 +110,38 @@ const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFil
|
||||
threadId: ThreadId,
|
||||
operation: "load-thread" | "save-thread" | "remove-thread",
|
||||
) {
|
||||
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 { 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 secureCatalogStorage: SecureCatalogStorage = {
|
||||
getItem: (key) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.getItemAsync(key),
|
||||
catch: (cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "load",
|
||||
backend: "mobile-secure-storage",
|
||||
key,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
catch: (cause) => catalogError("load", cause),
|
||||
}),
|
||||
setItem: (key, value) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.setItemAsync(key, value),
|
||||
catch: (cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "save",
|
||||
backend: "mobile-secure-storage",
|
||||
key,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
catch: (cause) => catalogError("save", cause),
|
||||
}),
|
||||
deleteItem: (key) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.deleteItemAsync(key),
|
||||
catch: (cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "delete",
|
||||
backend: "mobile-secure-storage",
|
||||
key,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
catch: (cause) => catalogError("delete", cause),
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -171,8 +156,6 @@ 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");
|
||||
@@ -180,14 +163,7 @@ const shellSnapshotFileInDirectory = Effect.fn(
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
return new File(directory, shellSnapshotFileName(environmentId));
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation,
|
||||
stage: "resolve",
|
||||
resource,
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -208,45 +184,18 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
const targetStore = ConnectionTargetStore.of({
|
||||
list: catalog.read.pipe(
|
||||
Effect.map((document) => document.targets),
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionPersistenceError.fromStorageFailure({
|
||||
operation: "list-targets",
|
||||
fallbackStage: "read",
|
||||
resource: "connection-catalog",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
|
||||
),
|
||||
});
|
||||
const registrationStore = ConnectionRegistrationStore.of({
|
||||
register: (registration) =>
|
||||
catalog
|
||||
.update((document) => registerConnectionInCatalog(document, registration))
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionPersistenceError.fromStorageFailure({
|
||||
operation: "register-connection",
|
||||
fallbackStage: "write",
|
||||
resource: "connection-catalog",
|
||||
environmentId: registration.target.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
|
||||
remove: (target) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionPersistenceError.fromStorageFailure({
|
||||
operation: "remove-connection",
|
||||
fallbackStage: "write",
|
||||
resource: "connection-catalog",
|
||||
environmentId: target.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
|
||||
});
|
||||
const profileStore = ProfileStore.make({
|
||||
get: (connectionId) =>
|
||||
@@ -334,38 +283,15 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (file.exists) {
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "read",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "parse",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (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,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
return stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
@@ -377,38 +303,15 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
const legacyRaw = yield* Effect.tryPromise({
|
||||
try: () => legacyFile.text(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "read",
|
||||
resource: "legacy-shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const legacyParsed = yield* Effect.try({
|
||||
try: () => JSON.parse(legacyRaw) as unknown,
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "parse",
|
||||
resource: "legacy-shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (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,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const legacyStored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
return legacyStored.environmentId === environmentId
|
||||
? Option.some(legacyStored.snapshot)
|
||||
: Option.none();
|
||||
@@ -421,18 +324,9 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
environmentId,
|
||||
snapshot,
|
||||
} as const;
|
||||
const encoded = yield* encodeStoredShellSnapshot(stored).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-shell",
|
||||
stage: "encode",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
@@ -440,14 +334,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-shell",
|
||||
stage: "write",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => shellPersistenceError("save-shell", cause),
|
||||
});
|
||||
}),
|
||||
loadThread: (environmentId, threadId) =>
|
||||
@@ -458,41 +345,15 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-thread",
|
||||
stage: "read",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-thread",
|
||||
stage: "parse",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
catch: (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,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none();
|
||||
@@ -500,24 +361,14 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
saveThread: (environmentId, thread) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
|
||||
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,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
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)));
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
@@ -525,63 +376,36 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-thread",
|
||||
stage: "write",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => shellPersistenceError("save-thread", cause),
|
||||
});
|
||||
}),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
|
||||
if (file.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => file.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "remove-thread",
|
||||
stage: "remove",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
file.delete();
|
||||
}
|
||||
}),
|
||||
}).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) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "clear-environment",
|
||||
stage: "remove",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
|
||||
if (legacyFile.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => legacyFile.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "clear-environment",
|
||||
stage: "remove",
|
||||
resource: "legacy-shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const threadDirectory = yield* threadSnapshotDirectory(
|
||||
@@ -591,14 +415,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (threadDirectory.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => threadDirectory.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "clear-environment",
|
||||
stage: "remove",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import type { NotificationResponse } from "expo-notifications";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
extractAgentNotificationDeepLink,
|
||||
@@ -21,76 +18,6 @@ function responseWithData(data: Record<string, unknown>, identifier = "notificat
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("consumeLastAgentNotificationResponse", () => {
|
||||
it("reports which initial-response operation failed", async () => {
|
||||
const cause = new Error("notification lookup unavailable");
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
|
||||
await consumeLastAgentNotificationResponse({
|
||||
getLastResponse: () => Promise.reject(cause),
|
||||
clearLastResponse: () => Promise.resolve(),
|
||||
handleResponse: vi.fn(),
|
||||
});
|
||||
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
_tag: "NotificationNavigationError",
|
||||
operation: "read",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("routes a response before reporting a clear failure", async () => {
|
||||
const cause = new Error("notification clear unavailable");
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
const response = responseWithData({}, "notification-clear") as NotificationResponse;
|
||||
const handleResponse = vi.fn();
|
||||
|
||||
await consumeLastAgentNotificationResponse({
|
||||
getLastResponse: () => Promise.resolve(response),
|
||||
clearLastResponse: () => Promise.reject(cause),
|
||||
handleResponse,
|
||||
});
|
||||
|
||||
expect(handleResponse).toHaveBeenCalledWith(response);
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
_tag: "NotificationNavigationError",
|
||||
operation: "clear",
|
||||
notificationId: "notification-clear",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("reports routing failures before clearing the response", async () => {
|
||||
const cause = new Error("notification routing unavailable");
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
const response = responseWithData({}, "notification-route") as NotificationResponse;
|
||||
const clearLastResponse = vi.fn(() => Promise.resolve());
|
||||
|
||||
await consumeLastAgentNotificationResponse({
|
||||
getLastResponse: () => Promise.resolve(response),
|
||||
clearLastResponse,
|
||||
handleResponse: () => {
|
||||
throw cause;
|
||||
},
|
||||
});
|
||||
|
||||
expect(clearLastResponse).not.toHaveBeenCalled();
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
_tag: "NotificationNavigationError",
|
||||
operation: "route",
|
||||
notificationId: "notification-route",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractAgentNotificationDeepLink", () => {
|
||||
it("uses explicit deep links from APNs payload data", () => {
|
||||
expect(
|
||||
|
||||
@@ -3,7 +3,6 @@ import * as Notifications from "expo-notifications";
|
||||
import { useRouter } from "expo-router";
|
||||
|
||||
import { routeAgentNotificationResponseOnce } from "./notificationPayload";
|
||||
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
|
||||
|
||||
export function useAgentNotificationNavigation(): void {
|
||||
const router = useRouter();
|
||||
@@ -19,11 +18,15 @@ export function useAgentNotificationNavigation(): void {
|
||||
};
|
||||
|
||||
const subscription = Notifications.addNotificationResponseReceivedListener(handleResponse);
|
||||
void consumeLastAgentNotificationResponse({
|
||||
getLastResponse: () => Notifications.getLastNotificationResponseAsync(),
|
||||
clearLastResponse: () => Notifications.clearLastNotificationResponseAsync(),
|
||||
handleResponse,
|
||||
});
|
||||
void Notifications.getLastNotificationResponseAsync()
|
||||
.then((response) => {
|
||||
if (response) {
|
||||
handleResponse(response);
|
||||
return Notifications.clearLastNotificationResponseAsync();
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
|
||||
return () => {
|
||||
subscription.remove();
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import type { NotificationResponse } from "expo-notifications";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export class NotificationNavigationError extends Schema.TaggedErrorClass<NotificationNavigationError>()(
|
||||
"NotificationNavigationError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "route", "clear"]),
|
||||
notificationId: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to ${this.operation} the last notification response.`;
|
||||
}
|
||||
}
|
||||
|
||||
export async function consumeLastAgentNotificationResponse(input: {
|
||||
readonly getLastResponse: () => Promise<NotificationResponse | null>;
|
||||
readonly clearLastResponse: () => Promise<void>;
|
||||
readonly handleResponse: (response: NotificationResponse) => void;
|
||||
}): Promise<void> {
|
||||
let response: NotificationResponse | null;
|
||||
try {
|
||||
response = await input.getLastResponse();
|
||||
} catch (cause) {
|
||||
console.error(new NotificationNavigationError({ operation: "read", cause }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!response) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
input.handleResponse(response);
|
||||
} catch (cause) {
|
||||
console.error(
|
||||
new NotificationNavigationError({
|
||||
operation: "route",
|
||||
notificationId: response.notification.request.identifier,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await input.clearLastResponse();
|
||||
} catch (cause) {
|
||||
console.error(
|
||||
new NotificationNavigationError({
|
||||
operation: "clear",
|
||||
notificationId: response.notification.request.identifier,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@ import { cryptoLayer } from "../cloud/dpop";
|
||||
import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
|
||||
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
|
||||
import {
|
||||
AgentAwarenessOperationError,
|
||||
__resetAgentAwarenessRemoteRegistrationForTest,
|
||||
refreshActiveLiveActivityRemoteRegistration,
|
||||
refreshAgentAwarenessRegistration,
|
||||
@@ -268,28 +267,6 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("preserves Live Activity push-token lookup failures", () => {
|
||||
const cause = new Error("native token lookup failed");
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.reject(cause)),
|
||||
addPushTokenListener: vi.fn(),
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
registerLiveActivityPushToken({ activity: activity as never }),
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(AgentAwarenessOperationError);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "AgentAwarenessOperationError",
|
||||
operation: "read-live-activity-push-token",
|
||||
cause,
|
||||
message: "Agent awareness operation read-live-activity-push-token failed.",
|
||||
});
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"reports Live Activity token registration as skipped when relay auth is unavailable",
|
||||
() => {
|
||||
|
||||
@@ -2,7 +2,6 @@ import { addPushToStartTokenListener, type LiveActivity } from "expo-widgets";
|
||||
import Constants from "expo-constants";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Platform } from "react-native";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -29,33 +28,6 @@ import { resolveCloudPublicConfig } from "../cloud/publicConfig";
|
||||
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
|
||||
|
||||
const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;
|
||||
|
||||
const AgentAwarenessOperation = Schema.Literals([
|
||||
"read-notification-permissions",
|
||||
"read-native-push-token",
|
||||
"read-device-registration-relay-token",
|
||||
"read-device-unregistration-relay-token",
|
||||
"read-live-activity-registration-relay-token",
|
||||
"load-device-registration-identifier",
|
||||
"load-device-registration-preferences",
|
||||
"load-device-unregistration-identifier",
|
||||
"read-live-activity-push-token",
|
||||
"load-live-activity-registration-identifier",
|
||||
"list-active-live-activities",
|
||||
]);
|
||||
|
||||
export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentAwarenessOperationError>()(
|
||||
"AgentAwarenessOperationError",
|
||||
{
|
||||
operation: AgentAwarenessOperation,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Agent awareness operation ${this.operation} failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
|
||||
const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
|
||||
let pushToStartSubscription: { remove: () => void } | null = null;
|
||||
@@ -165,22 +137,14 @@ function nativePushTokenRegistration(observedPushToken?: string) {
|
||||
}
|
||||
const permissions = yield* Effect.tryPromise({
|
||||
try: () => Notifications.getPermissionsAsync(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "read-notification-permissions",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
});
|
||||
if (!permissions.granted) {
|
||||
return { notificationsEnabled: false, pushToken: null };
|
||||
}
|
||||
const token = yield* Effect.tryPromise({
|
||||
try: () => Notifications.getDevicePushTokenAsync(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "read-native-push-token",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
}).pipe(
|
||||
Effect.tapError((error) =>
|
||||
Effect.sync(() => {
|
||||
@@ -197,19 +161,16 @@ function nativePushTokenRegistration(observedPushToken?: string) {
|
||||
});
|
||||
}
|
||||
|
||||
const relayToken = (
|
||||
operation: "read-device-registration-relay-token" | "read-live-activity-registration-relay-token",
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const provider = relayTokenProvider;
|
||||
if (!provider) {
|
||||
return null;
|
||||
}
|
||||
return yield* Effect.tryPromise({
|
||||
try: provider,
|
||||
catch: (cause) => new AgentAwarenessOperationError({ operation, cause }),
|
||||
});
|
||||
const relayToken = Effect.gen(function* () {
|
||||
const provider = relayTokenProvider;
|
||||
if (!provider) {
|
||||
return null;
|
||||
}
|
||||
return yield* Effect.tryPromise({
|
||||
try: provider,
|
||||
catch: (error) => error,
|
||||
});
|
||||
});
|
||||
|
||||
function registerDeviceWithRelay(
|
||||
body: RelayDeviceRegistrationRequest,
|
||||
@@ -224,7 +185,7 @@ function registerDeviceWithRelay(
|
||||
return;
|
||||
}
|
||||
if (!readRelayConfig()) return;
|
||||
const token = yield* relayToken("read-device-registration-relay-token");
|
||||
const token = yield* relayToken;
|
||||
if (expectedGeneration !== deviceRegistrationGeneration) {
|
||||
logRegistrationDebug("device registration cancelled after auth lookup", {
|
||||
expectedGeneration,
|
||||
@@ -259,11 +220,7 @@ function unregisterDeviceWithRelay(input: {
|
||||
if (!readRelayConfig()) return;
|
||||
const token = yield* Effect.tryPromise({
|
||||
try: input.tokenProvider,
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "read-device-unregistration-relay-token",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
});
|
||||
if (!token) {
|
||||
logRegistrationDebug("relay device unregistration skipped; user is not signed in");
|
||||
@@ -283,7 +240,7 @@ function registerLiveActivityWithRelay(
|
||||
): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
if (!readRelayConfig()) return false;
|
||||
const token = yield* relayToken("read-live-activity-registration-relay-token");
|
||||
const token = yield* relayToken;
|
||||
if (!token) {
|
||||
logRegistrationDebug("relay live activity registration skipped; user is not signed in");
|
||||
return false;
|
||||
@@ -424,19 +381,11 @@ function registerDevice(
|
||||
const [deviceId, preferences] = yield* Effect.all([
|
||||
Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "load-device-registration-identifier",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
}),
|
||||
Effect.tryPromise({
|
||||
try: () => loadPreferences(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "load-device-registration-preferences",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
}),
|
||||
]);
|
||||
const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
|
||||
@@ -570,11 +519,7 @@ export function unregisterAgentAwarenessDeviceForCurrentUser(
|
||||
return Effect.gen(function* () {
|
||||
const deviceId = yield* Effect.tryPromise({
|
||||
try: () => loadAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "load-device-unregistration-identifier",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
});
|
||||
if (!deviceId) {
|
||||
return;
|
||||
@@ -599,11 +544,7 @@ export function registerLiveActivityPushToken(input: {
|
||||
|
||||
const activityPushToken = yield* Effect.tryPromise({
|
||||
try: () => input.activity.getPushToken(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "read-live-activity-push-token",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
});
|
||||
if (!activityPushToken) {
|
||||
if (activityPushTokenListeners.has(input.activity)) {
|
||||
@@ -651,11 +592,7 @@ function registerLiveActivityPushTokenValue(input: {
|
||||
return Effect.gen(function* () {
|
||||
const deviceId = yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "load-live-activity-registration-identifier",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
});
|
||||
const registered = yield* registerLiveActivityWithRelay({
|
||||
deviceId,
|
||||
@@ -696,11 +633,7 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
|
||||
|
||||
const activities = yield* Effect.try({
|
||||
try: () => AgentActivity.getInstances(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "list-active-live-activities",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => {
|
||||
|
||||
@@ -4,7 +4,6 @@ import { useState } from "react";
|
||||
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
|
||||
|
||||
export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }) {
|
||||
const { errors, fetchStatus, waitlist } = useWaitlist();
|
||||
@@ -22,14 +21,12 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
|
||||
setRequestError(null);
|
||||
try {
|
||||
await joinCloudWaitlist(waitlist, normalizedEmailAddress);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
setRequestError(
|
||||
error instanceof CloudWaitlistJoinRejectedError
|
||||
? "Could not join the waitlist. Check your email address and try again."
|
||||
: "Could not join the waitlist. Check your connection and try again.",
|
||||
);
|
||||
const { error } = await waitlist.join({ emailAddress: normalizedEmailAddress });
|
||||
if (error) {
|
||||
setRequestError("Could not join the waitlist. Check your email address and try again.");
|
||||
}
|
||||
} catch {
|
||||
setRequestError("Could not join the waitlist. Check your connection and try again.");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
CloudWaitlistJoinRejectedError,
|
||||
CloudWaitlistJoinRequestError,
|
||||
joinCloudWaitlist,
|
||||
} from "./cloudWaitlistJoin";
|
||||
|
||||
describe("joinCloudWaitlist", () => {
|
||||
it("submits the provided email address", async () => {
|
||||
const join = vi.fn().mockResolvedValue({ error: null });
|
||||
|
||||
await joinCloudWaitlist({ join }, "[email protected]");
|
||||
|
||||
expect(join).toHaveBeenCalledExactlyOnceWith({ emailAddress: "[email protected]" });
|
||||
});
|
||||
|
||||
it("preserves Clerk rejection details without exposing the email address", async () => {
|
||||
const cause = Object.assign(new Error("The enrollment was rejected."), {
|
||||
code: "form_identifier_invalid",
|
||||
});
|
||||
const join = vi.fn().mockResolvedValue({ error: cause });
|
||||
|
||||
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
|
||||
(error: unknown) => error,
|
||||
);
|
||||
|
||||
expect(failure).toBeInstanceOf(CloudWaitlistJoinRejectedError);
|
||||
expect(failure).toMatchObject({
|
||||
code: "form_identifier_invalid",
|
||||
cause,
|
||||
});
|
||||
expect(String(failure)).not.toContain("[email protected]");
|
||||
});
|
||||
|
||||
it("distinguishes request failures from rejected enrollments", async () => {
|
||||
const cause = new Error("network unavailable");
|
||||
const join = vi.fn().mockRejectedValue(cause);
|
||||
|
||||
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
|
||||
(error: unknown) => error,
|
||||
);
|
||||
|
||||
expect(failure).toBeInstanceOf(CloudWaitlistJoinRequestError);
|
||||
expect(failure).toMatchObject({ cause });
|
||||
expect(failure).not.toBeInstanceOf(CloudWaitlistJoinRejectedError);
|
||||
});
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
interface CloudWaitlistJoiner {
|
||||
readonly join: (input: { emailAddress: string }) => Promise<{
|
||||
readonly error: { readonly code: string } | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
export class CloudWaitlistJoinRejectedError extends Schema.TaggedErrorClass<CloudWaitlistJoinRejectedError>()(
|
||||
"CloudWaitlistJoinRejectedError",
|
||||
{
|
||||
code: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Cloud waitlist enrollment was rejected with code "${this.code}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudWaitlistJoinRequestError extends Schema.TaggedErrorClass<CloudWaitlistJoinRequestError>()(
|
||||
"CloudWaitlistJoinRequestError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Cloud waitlist enrollment request failed.";
|
||||
}
|
||||
}
|
||||
|
||||
export async function joinCloudWaitlist(
|
||||
waitlist: CloudWaitlistJoiner,
|
||||
emailAddress: string,
|
||||
): Promise<void> {
|
||||
const result = await waitlist.join({ emailAddress }).catch((cause) => {
|
||||
throw new CloudWaitlistJoinRequestError({ cause });
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
throw new CloudWaitlistJoinRejectedError({
|
||||
code: result.error.code,
|
||||
cause: result.error,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,8 @@ import * as Effect from "effect/Effect";
|
||||
import { verifyDpopProof } from "@t3tools/shared/dpop";
|
||||
|
||||
import {
|
||||
CloudDpopProofError,
|
||||
CloudDpopStorageError,
|
||||
createDpopProof,
|
||||
generateDpopProofKeyPair,
|
||||
isCloudDpopError,
|
||||
loadOrCreateDpopProofKeyPair,
|
||||
cryptoLayer,
|
||||
} from "./dpop";
|
||||
@@ -98,82 +95,7 @@ describe("mobile DPoP", () => {
|
||||
|
||||
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudDpopStorageError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "decode",
|
||||
storageKey: "t3code.cloud.dpop-proof-key",
|
||||
});
|
||||
expect(isCloudDpopError(error)).toBe(true);
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects stored key material whose public coordinates do not match", () =>
|
||||
Effect.gen(function* () {
|
||||
secureStore.clear();
|
||||
const generated = yield* generateDpopProofKeyPair();
|
||||
secureStore.set(
|
||||
"t3code.cloud.dpop-proof-key",
|
||||
JSON.stringify({ ...generated.privateJwk, x: generated.privateJwk.y }),
|
||||
);
|
||||
|
||||
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudDpopStorageError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "restore",
|
||||
storageKey: "t3code.cloud.dpop-proof-key",
|
||||
});
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves request context for an invalid proof URL", () =>
|
||||
Effect.gen(function* () {
|
||||
const proofKey = yield* generateDpopProofKeyPair();
|
||||
const error = yield* createDpopProof({
|
||||
method: "POST",
|
||||
url: "http://",
|
||||
proofKey,
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudDpopProofError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "normalize-url",
|
||||
method: "POST",
|
||||
requestTarget: "<invalid-url>",
|
||||
urlLength: "http://".length,
|
||||
thumbprint: proofKey.thumbprint,
|
||||
});
|
||||
expect(isCloudDpopError(error)).toBe(true);
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("redacts credentials and non-HTU URL components from proof failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const proofKey = yield* generateDpopProofKeyPair();
|
||||
const url = "https://user:[email protected]/oauth/token?access_token=secret#fragment";
|
||||
const error = yield* createDpopProof({
|
||||
method: "POST",
|
||||
url,
|
||||
proofKey: {
|
||||
...proofKey,
|
||||
privateJwk: { ...proofKey.privateJwk, d: "%" },
|
||||
},
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudDpopProofError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "import-private-key",
|
||||
method: "POST",
|
||||
requestTarget: "https://example.com/oauth/token",
|
||||
urlLength: url.length,
|
||||
thumbprint: proofKey.thumbprint,
|
||||
});
|
||||
expect(error).not.toHaveProperty("url");
|
||||
expect(error.message).not.toContain("user");
|
||||
expect(error.message).not.toContain("password");
|
||||
expect(error.message).not.toContain("access_token");
|
||||
expect(error.message).not.toContain("secret");
|
||||
expect(error.message).not.toContain("fragment");
|
||||
expect(error.message).toBe("Stored DPoP proof key is invalid.");
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ExpoCrypto from "expo-crypto";
|
||||
@@ -12,91 +12,19 @@ import {
|
||||
computeDpopAccessTokenHash,
|
||||
computeDpopJwkThumbprint,
|
||||
DpopPublicJwk,
|
||||
redactDpopRequestTarget,
|
||||
normalizeDpopHtu,
|
||||
} from "@t3tools/shared/dpop";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
export class CloudDpopStorageError extends Schema.TaggedErrorClass<CloudDpopStorageError>()(
|
||||
"CloudDpopStorageError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "decode", "restore", "encode", "write"]),
|
||||
storageKey: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Mobile DPoP key storage operation "${this.operation}" failed for key "${this.storageKey}".`;
|
||||
}
|
||||
export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
function cloudDpopError(message: string) {
|
||||
return (cause: unknown) => new CloudDpopError({ message, cause });
|
||||
}
|
||||
|
||||
export class CloudDpopKeyError extends Schema.TaggedErrorClass<CloudDpopKeyError>()(
|
||||
"CloudDpopKeyError",
|
||||
{
|
||||
operation: Schema.Literals(["generate-randomness", "derive-public-key"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Mobile DPoP key operation "${this.operation}" failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudDpopProofError extends Schema.TaggedErrorClass<CloudDpopProofError>()(
|
||||
"CloudDpopProofError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"import-private-key",
|
||||
"generate-id",
|
||||
"normalize-url",
|
||||
"encode-header",
|
||||
"encode-payload",
|
||||
"hash-signing-input",
|
||||
"sign",
|
||||
]),
|
||||
method: Schema.String,
|
||||
requestTarget: Schema.String,
|
||||
urlLength: Schema.Number,
|
||||
thumbprint: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Mobile DPoP proof operation "${this.operation}" failed for ${this.method.toUpperCase()} ${this.requestTarget}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DpopPublicKeyFormatError extends Schema.TaggedErrorClass<DpopPublicKeyFormatError>()(
|
||||
"DpopPublicKeyFormatError",
|
||||
{
|
||||
byteLength: Schema.Number,
|
||||
firstByte: Schema.optional(Schema.Number),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const prefix =
|
||||
this.firstByte === undefined
|
||||
? "no prefix byte"
|
||||
: `prefix 0x${this.firstByte.toString(16).padStart(2, "0")}`;
|
||||
return `Expected a 65-byte uncompressed P-256 public key beginning with 0x04; received ${this.byteLength} bytes with ${prefix}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DpopStoredPublicKeyMismatchError extends Schema.TaggedErrorClass<DpopStoredPublicKeyMismatchError>()(
|
||||
"DpopStoredPublicKeyMismatchError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Stored DPoP private and public key material do not match.";
|
||||
}
|
||||
}
|
||||
|
||||
export const CloudDpopError = Schema.Union([
|
||||
CloudDpopStorageError,
|
||||
CloudDpopKeyError,
|
||||
CloudDpopProofError,
|
||||
]);
|
||||
export type CloudDpopError = typeof CloudDpopError.Type;
|
||||
export const isCloudDpopError = Schema.is(CloudDpopError);
|
||||
|
||||
const DpopPrivateJwkSchema = Schema.Struct({
|
||||
...DpopPublicJwk.fields,
|
||||
d: Schema.String,
|
||||
@@ -169,12 +97,29 @@ function base64UrlToBytes(value: string): Uint8Array {
|
||||
return Result.getOrThrow(Encoding.decodeBase64Url(value));
|
||||
}
|
||||
|
||||
function sha256Digest(
|
||||
data: Uint8Array,
|
||||
message: string,
|
||||
): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
|
||||
return Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.digest("SHA-256", data)),
|
||||
Effect.mapError(cloudDpopError(message)),
|
||||
);
|
||||
}
|
||||
|
||||
function secureRandomBytes(
|
||||
byteCount: number,
|
||||
message: string,
|
||||
): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
|
||||
return Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomBytes(byteCount)),
|
||||
Effect.mapError(cloudDpopError(message)),
|
||||
);
|
||||
}
|
||||
|
||||
function publicJwkFromUncompressedPublicKey(publicKey: Uint8Array): DpopPublicJwk {
|
||||
if (publicKey.length !== 65 || publicKey[0] !== 0x04) {
|
||||
throw new DpopPublicKeyFormatError({
|
||||
byteLength: publicKey.length,
|
||||
...(publicKey[0] === undefined ? {} : { firstByte: publicKey[0] }),
|
||||
});
|
||||
throw new Error("Generated DPoP public key is not an uncompressed P-256 point.");
|
||||
}
|
||||
return {
|
||||
kty: "EC",
|
||||
@@ -199,16 +144,14 @@ export function generateDpopProofKeyPair(): Effect.Effect<
|
||||
return Effect.gen(function* () {
|
||||
let privateKey: Uint8Array;
|
||||
do {
|
||||
privateKey = yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomBytes(p256.CURVE.nByteLength)),
|
||||
Effect.mapError(
|
||||
(cause) => new CloudDpopKeyError({ operation: "generate-randomness", cause }),
|
||||
),
|
||||
privateKey = yield* secureRandomBytes(
|
||||
p256.CURVE.nByteLength,
|
||||
"Could not generate DPoP key pair randomness.",
|
||||
);
|
||||
} while (!p256.utils.isValidPrivateKey(privateKey));
|
||||
const publicJwk = yield* Effect.try({
|
||||
try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
|
||||
catch: (cause) => new CloudDpopKeyError({ operation: "derive-public-key", cause }),
|
||||
catch: cloudDpopError("Generated DPoP public key is invalid."),
|
||||
});
|
||||
const thumbprint = computeDpopJwkThumbprint(publicJwk);
|
||||
return {
|
||||
@@ -227,23 +170,11 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
|
||||
return Effect.gen(function* () {
|
||||
const stored = yield* Effect.tryPromise({
|
||||
try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY),
|
||||
catch: (cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "read",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudDpopError("Could not read the DPoP proof key."),
|
||||
});
|
||||
if (stored) {
|
||||
const storedPrivateJwk = yield* decodeDpopPrivateJwkJson(stored).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "decode",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(cloudDpopError("Stored DPoP proof key is invalid.")),
|
||||
);
|
||||
const restored = yield* Effect.try({
|
||||
try: () => {
|
||||
@@ -252,16 +183,11 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
|
||||
p256.getPublicKey(privateKey, false),
|
||||
);
|
||||
if (publicJwk.x !== storedPrivateJwk.x || publicJwk.y !== storedPrivateJwk.y) {
|
||||
throw new DpopStoredPublicKeyMismatchError();
|
||||
throw new Error("Stored DPoP key does not match its public key.");
|
||||
}
|
||||
return { privateJwk: storedPrivateJwk, publicJwk };
|
||||
},
|
||||
catch: (cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "restore",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudDpopError("Stored DPoP proof key is invalid."),
|
||||
});
|
||||
return {
|
||||
...restored,
|
||||
@@ -270,28 +196,23 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
|
||||
}
|
||||
const generated = yield* generateDpopProofKeyPair();
|
||||
const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "encode",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(cloudDpopError("Could not encode the DPoP proof key.")),
|
||||
);
|
||||
yield* Effect.tryPromise({
|
||||
try: () => SecureStore.setItemAsync(DPOP_PROOF_KEY_STORAGE_KEY, encodedPrivateJwk),
|
||||
catch: (cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "write",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudDpopError("Could not store the DPoP proof key."),
|
||||
});
|
||||
return generated;
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeHtu(url: string): Effect.Effect<string, CloudDpopError> {
|
||||
const normalized = normalizeDpopHtu(url);
|
||||
return normalized
|
||||
? Effect.succeed(normalized)
|
||||
: Effect.fail(new CloudDpopError({ message: "DPoP URL is invalid." }));
|
||||
}
|
||||
|
||||
export function createDpopProof(input: {
|
||||
readonly method: string;
|
||||
readonly url: string;
|
||||
@@ -304,69 +225,23 @@ export function createDpopProof(input: {
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair());
|
||||
const requestTarget = redactDpopRequestTarget(input.url);
|
||||
const urlLength = input.url.length;
|
||||
const privateKey = yield* Effect.try({
|
||||
try: () => base64UrlToBytes(keyPair.privateJwk.d),
|
||||
catch: (cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "import-private-key",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudDpopError("Could not import DPoP private key."),
|
||||
});
|
||||
const nowMs = yield* Clock.currentTimeMillis;
|
||||
const jti = yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "generate-id",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")),
|
||||
);
|
||||
const htu = yield* Effect.try({
|
||||
try: () => {
|
||||
const parsed = new URL(input.url);
|
||||
parsed.hash = "";
|
||||
parsed.search = "";
|
||||
return parsed.toString();
|
||||
},
|
||||
catch: (cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "normalize-url",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const htu = yield* normalizeHtu(input.url);
|
||||
const header = yield* encodeDpopJwtHeaderJson({
|
||||
typ: "dpop+jwt",
|
||||
alg: "ES256",
|
||||
jwk: keyPair.publicJwk,
|
||||
}).pipe(
|
||||
Effect.map(Encoding.encodeBase64Url),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "encode-header",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
|
||||
);
|
||||
const ath = input.accessToken ? computeDpopAccessTokenHash(input.accessToken) : null;
|
||||
const payload = yield* encodeDpopJwtPayloadJson({
|
||||
@@ -377,45 +252,15 @@ export function createDpopProof(input: {
|
||||
...(ath ? { ath } : {}),
|
||||
}).pipe(
|
||||
Effect.map(Encoding.encodeBase64Url),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "encode-payload",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")),
|
||||
);
|
||||
const signatureInputHash = yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) =>
|
||||
crypto.digest("SHA-256", new TextEncoder().encode(`${header}.${payload}`)),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "hash-signing-input",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
const signatureInputHash = yield* sha256Digest(
|
||||
new TextEncoder().encode(`${header}.${payload}`),
|
||||
"Could not hash DPoP signing input.",
|
||||
);
|
||||
const signature = yield* Effect.try({
|
||||
try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(),
|
||||
catch: (cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "sign",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudDpopError("Could not sign DPoP proof."),
|
||||
});
|
||||
return {
|
||||
proof: `${header}.${payload}.${Encoding.encodeBase64Url(signature)}`,
|
||||
|
||||
@@ -9,11 +9,9 @@ import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
CloudEnvironmentLinkOperationError,
|
||||
cloudEnvironmentsPendingStatus,
|
||||
linkEnvironmentToCloud,
|
||||
connectCloudEnvironment,
|
||||
isCloudEnvironmentLinkError,
|
||||
listCloudEnvironments,
|
||||
listCloudEnvironmentsWithStatus,
|
||||
normalizeRelayBaseUrl,
|
||||
@@ -150,46 +148,6 @@ describe("mobile cloud link environment client", () => {
|
||||
createProofMock.mockClear();
|
||||
});
|
||||
|
||||
it("keeps URL secrets out of operation error diagnostics", () => {
|
||||
const relayUrl =
|
||||
"https://relay-user:[email protected]/private/workspace?access_token=relay-secret#relay-fragment";
|
||||
const httpBaseUrl =
|
||||
"https://desktop-user:[email protected]/private/workspace?access_token=desktop-secret#desktop-fragment";
|
||||
const cause = new Error("request failed");
|
||||
|
||||
const error = CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "link the environment",
|
||||
cause,
|
||||
environmentId: "env-1",
|
||||
relayUrl,
|
||||
httpBaseUrl,
|
||||
});
|
||||
|
||||
expect(error).toMatchObject({
|
||||
relayUrlInputLength: relayUrl.length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
httpBaseUrlInputLength: httpBaseUrl.length,
|
||||
httpBaseUrlProtocol: "https:",
|
||||
httpBaseUrlHostname: "desktop.example.test",
|
||||
});
|
||||
const serialized = JSON.stringify(error);
|
||||
for (const secret of [
|
||||
"relay-user",
|
||||
"relay-password",
|
||||
"relay-secret",
|
||||
"relay-fragment",
|
||||
"/private/workspace",
|
||||
"desktop-user",
|
||||
"desktop-password",
|
||||
"desktop-secret",
|
||||
"desktop-fragment",
|
||||
]) {
|
||||
expect(serialized).not.toContain(secret);
|
||||
expect(error.message).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
|
||||
it("normalizes configured relay base URLs before building DPoP-bound requests", () => {
|
||||
expect(normalizeRelayBaseUrl(" https://relay.example.test/// ")).toBe(
|
||||
"https://relay.example.test",
|
||||
@@ -277,14 +235,9 @@ describe("mobile cloud link environment client", () => {
|
||||
listCloudEnvironments({ clerkToken: "clerk-token" }),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "list cloud environments",
|
||||
relayUrlInputLength: "https://relay.example.test".length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "https://relay.example.test/v1/environments failed",
|
||||
});
|
||||
expect(error.message).toBe("Could not list cloud environments.");
|
||||
expect(isCloudEnvironmentLinkError(error)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -545,7 +498,7 @@ describe("mobile cloud link environment client", () => {
|
||||
label: "Desktop",
|
||||
},
|
||||
status: null,
|
||||
statusError: 'Could not read cloud environment status for environment "env-1".',
|
||||
statusError: "https://relay.example.test/v1/environments/env-1/status failed",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
@@ -609,8 +562,7 @@ describe("mobile cloud link environment client", () => {
|
||||
label: "Desktop",
|
||||
},
|
||||
status: null,
|
||||
statusError:
|
||||
'The environment status response identified environment "env-other" instead of "env-1".',
|
||||
statusError: "Relay returned status for a different environment.",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
@@ -638,55 +590,13 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentIdMismatchError",
|
||||
source: "environment link response",
|
||||
expectedEnvironmentId: "env-1",
|
||||
actualEnvironmentId: "env-other",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports invalid endpoint URLs with redacted diagnostics", () =>
|
||||
Effect.gen(function* () {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(() => Promise.resolve(Response.json(validLinkChallengeResponse()))),
|
||||
);
|
||||
|
||||
const httpBaseUrl =
|
||||
"https://desktop-user:desktop-password@[invalid-host]/private/workspace?access_token=desktop-secret#desktop-fragment";
|
||||
const error = yield* withCloudServices(
|
||||
linkEnvironmentToCloud({
|
||||
clerkToken: "clerk-token",
|
||||
connection: {
|
||||
...savedConnection,
|
||||
httpBaseUrl,
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "derive the environment endpoint origin",
|
||||
environmentId: "env-1",
|
||||
httpBaseUrlInputLength: httpBaseUrl.length,
|
||||
});
|
||||
expect(error).not.toHaveProperty("httpBaseUrl");
|
||||
const serialized = JSON.stringify({ ...error, cause: undefined });
|
||||
for (const secret of [
|
||||
"desktop-user",
|
||||
"desktop-password",
|
||||
"/private/workspace",
|
||||
"desktop-secret",
|
||||
"desktop-fragment",
|
||||
]) {
|
||||
expect(serialized).not.toContain(secret);
|
||||
expect(error.message).not.toContain(secret);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves typed local environment failures while obtaining a link proof", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetchMock = vi.fn((url: string | URL) => {
|
||||
@@ -697,8 +607,7 @@ describe("mobile cloud link environment client", () => {
|
||||
Response.json(
|
||||
{
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
reason: "cloud_cli_authorization_required",
|
||||
message: "Run `t3 connect link` to authorize this environment.",
|
||||
message: "Invalid environment bearer session.",
|
||||
},
|
||||
{ status: 401 },
|
||||
),
|
||||
@@ -712,20 +621,9 @@ describe("mobile cloud link environment client", () => {
|
||||
connection: savedConnection,
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "obtain an environment link proof",
|
||||
environmentId: "env-1",
|
||||
httpBaseUrlInputLength: "https://desktop.example.test/".length,
|
||||
httpBaseUrlProtocol: "https:",
|
||||
httpBaseUrlHostname: "desktop.example.test",
|
||||
environmentError: {
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
reason: "cloud_cli_authorization_required",
|
||||
},
|
||||
});
|
||||
expect(error._tag).toBe("CloudEnvironmentLinkError");
|
||||
expect(error.message).toBe(
|
||||
'Could not obtain an environment link proof for environment "env-1".',
|
||||
"Could not obtain environment link proof: Invalid environment bearer session.",
|
||||
);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
}),
|
||||
@@ -761,19 +659,11 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "link the environment",
|
||||
environmentId: "env-1",
|
||||
relayUrlInputLength: "https://relay.example.test".length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message:
|
||||
"https://relay.example.test/v1/client/environment-links failed: Relay rejected the environment link proof (origin_not_allowed).",
|
||||
traceId: "trace-test",
|
||||
relayError: {
|
||||
_tag: "RelayEnvironmentLinkProofInvalidError",
|
||||
reason: "origin_not_allowed",
|
||||
},
|
||||
});
|
||||
expect(error.message).toBe('Could not link the environment for environment "env-1".');
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
);
|
||||
@@ -806,10 +696,8 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentEndpointProviderMismatchError",
|
||||
environmentId: "env-1",
|
||||
expectedProviderKind: "cloudflare_tunnel",
|
||||
actualProviderKind: "manual",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Relay returned credentials for a different endpoint provider.",
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
@@ -1074,10 +962,8 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentIdMismatchError",
|
||||
source: "environment connect response",
|
||||
expectedEnvironmentId: "env-1",
|
||||
actualEnvironmentId: "env-other",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1119,21 +1005,11 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "connect to the cloud environment",
|
||||
environmentId: "env-1",
|
||||
relayUrlInputLength: "https://relay.example.test".length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message:
|
||||
"https://relay.example.test/v1/environments/env-1/connect failed: Relay rejected the DPoP proof.",
|
||||
traceId: "trace-connect",
|
||||
relayError: {
|
||||
_tag: "RelayAuthInvalidError",
|
||||
reason: "invalid_dpop",
|
||||
},
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
'Could not connect to the cloud environment for environment "env-1".',
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1175,23 +1051,8 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentEndpointMismatchError",
|
||||
source: "environment connect response",
|
||||
environmentId: "env-1",
|
||||
expectedProviderKind: "cloudflare_tunnel",
|
||||
expectedHttpBaseUrlInputLength: "https://desktop.example.test/".length,
|
||||
expectedHttpBaseUrlProtocol: "https:",
|
||||
expectedHttpBaseUrlHostname: "desktop.example.test",
|
||||
expectedWsBaseUrlInputLength: "wss://desktop.example.test/ws".length,
|
||||
expectedWsBaseUrlProtocol: "wss:",
|
||||
expectedWsBaseUrlHostname: "desktop.example.test",
|
||||
actualProviderKind: "cloudflare_tunnel",
|
||||
actualHttpBaseUrlInputLength: "https://other-desktop.example.test/".length,
|
||||
actualHttpBaseUrlProtocol: "https:",
|
||||
actualHttpBaseUrlHostname: "other-desktop.example.test",
|
||||
actualWsBaseUrlInputLength: "wss://other-desktop.example.test/ws".length,
|
||||
actualWsBaseUrlProtocol: "wss:",
|
||||
actualWsBaseUrlHostname: "other-desktop.example.test",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Relay returned credentials for a different endpoint.",
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1244,10 +1105,8 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentIdMismatchError",
|
||||
source: "connected environment descriptor",
|
||||
expectedEnvironmentId: "env-1",
|
||||
actualEnvironmentId: "env-other",
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Connected endpoint descriptor does not match the selected environment.",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
@@ -16,17 +17,16 @@ import {
|
||||
RelayEnvironmentConnectScope,
|
||||
RelayEnvironmentStatusScope,
|
||||
type RelayDpopAccessTokenScope,
|
||||
type RelayProtectedError as RelayProtectedErrorType,
|
||||
type RelayClientEnvironmentRecord,
|
||||
type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType,
|
||||
RelayManagedEndpointProviderKind,
|
||||
RelayProtectedError,
|
||||
type RelayManagedEndpointProviderKind,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { exchangeRemoteDpopAccessToken } from "@t3tools/client-runtime/authorization";
|
||||
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
|
||||
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
|
||||
import { ManagedRelay } from "@t3tools/client-runtime/relay";
|
||||
import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
|
||||
import { authClientMetadata } from "../../lib/authClientMetadata";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
@@ -50,268 +50,11 @@ function readRelayUrl(): string | null {
|
||||
return resolveCloudPublicConfig().relay.url;
|
||||
}
|
||||
|
||||
const EnvironmentCloudApiError = Schema.Union([
|
||||
EnvironmentHttpBadRequestError,
|
||||
EnvironmentHttpUnauthorizedError,
|
||||
EnvironmentHttpForbiddenError,
|
||||
EnvironmentHttpConflictError,
|
||||
EnvironmentHttpInternalServerError,
|
||||
EnvironmentCloudEndpointUnavailableError,
|
||||
]);
|
||||
type EnvironmentCloudApiError = typeof EnvironmentCloudApiError.Type;
|
||||
const isEnvironmentCloudApiError = Schema.is(EnvironmentCloudApiError);
|
||||
const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError);
|
||||
|
||||
export const CloudEnvironmentLinkAction = Schema.Literals([
|
||||
"load the mobile device id",
|
||||
"load mobile notification preferences",
|
||||
"create an environment link challenge",
|
||||
"obtain an environment link proof",
|
||||
"link the environment",
|
||||
"configure environment relay access",
|
||||
"list cloud environments",
|
||||
"read cloud environment status",
|
||||
"connect to the cloud environment",
|
||||
"fetch the connected environment descriptor",
|
||||
"create a bootstrap DPoP proof",
|
||||
"exchange a managed endpoint DPoP access token",
|
||||
"derive the environment endpoint origin",
|
||||
"initialize the environment HTTP client",
|
||||
"parse the managed endpoint URL",
|
||||
]);
|
||||
export type CloudEnvironmentLinkAction = typeof CloudEnvironmentLinkAction.Type;
|
||||
|
||||
function relayUrlDiagnosticFields(relayUrl: string | undefined) {
|
||||
if (relayUrl === undefined) {
|
||||
return {};
|
||||
}
|
||||
const diagnostics = getUrlDiagnostics(relayUrl);
|
||||
return {
|
||||
relayUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { relayUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { relayUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
function httpBaseUrlDiagnosticFields(httpBaseUrl: string | undefined) {
|
||||
if (httpBaseUrl === undefined) {
|
||||
return {};
|
||||
}
|
||||
const diagnostics = getUrlDiagnostics(httpBaseUrl);
|
||||
return {
|
||||
httpBaseUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { httpBaseUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { httpBaseUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
export class CloudEnvironmentLinkOperationError extends Schema.TaggedErrorClass<CloudEnvironmentLinkOperationError>()(
|
||||
"CloudEnvironmentLinkOperationError",
|
||||
{
|
||||
action: CloudEnvironmentLinkAction,
|
||||
environmentId: Schema.optionalKey(Schema.String),
|
||||
relayUrlInputLength: Schema.optionalKey(Schema.Number),
|
||||
relayUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
relayUrlHostname: Schema.optionalKey(Schema.String),
|
||||
httpBaseUrlInputLength: Schema.optionalKey(Schema.Number),
|
||||
httpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
httpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
traceId: Schema.optionalKey(Schema.String),
|
||||
relayError: Schema.optionalKey(RelayProtectedError),
|
||||
environmentError: Schema.optionalKey(EnvironmentCloudApiError),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromCause(input: {
|
||||
readonly action: CloudEnvironmentLinkAction;
|
||||
readonly cause: unknown;
|
||||
readonly environmentId?: string;
|
||||
readonly relayUrl?: string;
|
||||
readonly httpBaseUrl?: string;
|
||||
}): CloudEnvironmentLinkOperationError {
|
||||
const relayFailure = isManagedRelayRequestFailedError(input.cause) ? input.cause : undefined;
|
||||
const environmentError = CloudEnvironmentLinkOperationError.findEnvironmentApiError(
|
||||
input.cause,
|
||||
);
|
||||
const traceId = relayFailure?.traceId ?? findErrorTraceId(input.cause);
|
||||
return new CloudEnvironmentLinkOperationError({
|
||||
action: input.action,
|
||||
cause: input.cause,
|
||||
...(input.environmentId === undefined ? {} : { environmentId: input.environmentId }),
|
||||
...relayUrlDiagnosticFields(input.relayUrl),
|
||||
...httpBaseUrlDiagnosticFields(input.httpBaseUrl),
|
||||
...(traceId === null || traceId === undefined ? {} : { traceId }),
|
||||
...(relayFailure?.relayError === undefined ? {} : { relayError: relayFailure.relayError }),
|
||||
...(environmentError === undefined ? {} : { environmentError }),
|
||||
});
|
||||
}
|
||||
|
||||
private static findEnvironmentApiError(cause: unknown): EnvironmentCloudApiError | undefined {
|
||||
const seen = new Set<unknown>();
|
||||
let current = cause;
|
||||
while (typeof current === "object" && current !== null && !seen.has(current)) {
|
||||
if (isEnvironmentCloudApiError(current)) {
|
||||
return current;
|
||||
}
|
||||
seen.add(current);
|
||||
current = "cause" in current ? current.cause : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const environment =
|
||||
this.environmentId === undefined ? "" : ` for environment "${this.environmentId}"`;
|
||||
return `Could not ${this.action}${environment}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudRelayUrlNotConfiguredError extends Schema.TaggedErrorClass<CloudRelayUrlNotConfiguredError>()(
|
||||
"CloudRelayUrlNotConfiguredError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Relay URL is not configured.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudEnvironmentLocalBearerRequiredError extends Schema.TaggedErrorClass<CloudEnvironmentLocalBearerRequiredError>()(
|
||||
"CloudEnvironmentLocalBearerRequiredError",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
httpBaseUrlInputLength: Schema.Number,
|
||||
httpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
httpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
},
|
||||
) {
|
||||
static fromConnection(input: {
|
||||
readonly environmentId: string;
|
||||
readonly httpBaseUrl: string;
|
||||
}): CloudEnvironmentLocalBearerRequiredError {
|
||||
const diagnostics = getUrlDiagnostics(input.httpBaseUrl);
|
||||
return new CloudEnvironmentLocalBearerRequiredError({
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { httpBaseUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { httpBaseUrlHostname: diagnostics.hostname }),
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "Only a locally paired bearer connection can be linked to the cloud.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudEnvironmentIdMismatchError extends Schema.TaggedErrorClass<CloudEnvironmentIdMismatchError>()(
|
||||
"CloudEnvironmentIdMismatchError",
|
||||
{
|
||||
source: Schema.Literals([
|
||||
"environment link response",
|
||||
"environment status response",
|
||||
"environment status descriptor",
|
||||
"environment connect response",
|
||||
"connected environment descriptor",
|
||||
]),
|
||||
expectedEnvironmentId: Schema.String,
|
||||
actualEnvironmentId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `The ${this.source} identified environment "${this.actualEnvironmentId}" instead of "${this.expectedEnvironmentId}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudEnvironmentEndpointMismatchError extends Schema.TaggedErrorClass<CloudEnvironmentEndpointMismatchError>()(
|
||||
"CloudEnvironmentEndpointMismatchError",
|
||||
{
|
||||
source: Schema.Literals(["environment status response", "environment connect response"]),
|
||||
environmentId: Schema.String,
|
||||
expectedProviderKind: RelayManagedEndpointProviderKind,
|
||||
expectedHttpBaseUrlInputLength: Schema.Number,
|
||||
expectedHttpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
expectedHttpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
expectedWsBaseUrlInputLength: Schema.Number,
|
||||
expectedWsBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
expectedWsBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
actualProviderKind: RelayManagedEndpointProviderKind,
|
||||
actualHttpBaseUrlInputLength: Schema.Number,
|
||||
actualHttpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
actualHttpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
actualWsBaseUrlInputLength: Schema.Number,
|
||||
actualWsBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
actualWsBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
},
|
||||
) {
|
||||
static fromEndpoints(input: {
|
||||
readonly source: "environment status response" | "environment connect response";
|
||||
readonly environmentId: string;
|
||||
readonly expectedEndpoint: RelayClientEnvironmentRecord["endpoint"];
|
||||
readonly actualEndpoint: RelayClientEnvironmentRecord["endpoint"];
|
||||
}): CloudEnvironmentEndpointMismatchError {
|
||||
const expectedHttp = getUrlDiagnostics(input.expectedEndpoint.httpBaseUrl);
|
||||
const expectedWs = getUrlDiagnostics(input.expectedEndpoint.wsBaseUrl);
|
||||
const actualHttp = getUrlDiagnostics(input.actualEndpoint.httpBaseUrl);
|
||||
const actualWs = getUrlDiagnostics(input.actualEndpoint.wsBaseUrl);
|
||||
return new CloudEnvironmentEndpointMismatchError({
|
||||
source: input.source,
|
||||
environmentId: input.environmentId,
|
||||
expectedProviderKind: input.expectedEndpoint.providerKind,
|
||||
expectedHttpBaseUrlInputLength: expectedHttp.inputLength,
|
||||
...(expectedHttp.protocol === undefined
|
||||
? {}
|
||||
: { expectedHttpBaseUrlProtocol: expectedHttp.protocol }),
|
||||
...(expectedHttp.hostname === undefined
|
||||
? {}
|
||||
: { expectedHttpBaseUrlHostname: expectedHttp.hostname }),
|
||||
expectedWsBaseUrlInputLength: expectedWs.inputLength,
|
||||
...(expectedWs.protocol === undefined
|
||||
? {}
|
||||
: { expectedWsBaseUrlProtocol: expectedWs.protocol }),
|
||||
...(expectedWs.hostname === undefined
|
||||
? {}
|
||||
: { expectedWsBaseUrlHostname: expectedWs.hostname }),
|
||||
actualProviderKind: input.actualEndpoint.providerKind,
|
||||
actualHttpBaseUrlInputLength: actualHttp.inputLength,
|
||||
...(actualHttp.protocol === undefined
|
||||
? {}
|
||||
: { actualHttpBaseUrlProtocol: actualHttp.protocol }),
|
||||
...(actualHttp.hostname === undefined
|
||||
? {}
|
||||
: { actualHttpBaseUrlHostname: actualHttp.hostname }),
|
||||
actualWsBaseUrlInputLength: actualWs.inputLength,
|
||||
...(actualWs.protocol === undefined ? {} : { actualWsBaseUrlProtocol: actualWs.protocol }),
|
||||
...(actualWs.hostname === undefined ? {} : { actualWsBaseUrlHostname: actualWs.hostname }),
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `The ${this.source} returned a different endpoint for environment "${this.environmentId}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudEnvironmentEndpointProviderMismatchError extends Schema.TaggedErrorClass<CloudEnvironmentEndpointProviderMismatchError>()(
|
||||
"CloudEnvironmentEndpointProviderMismatchError",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
expectedProviderKind: RelayManagedEndpointProviderKind,
|
||||
actualProviderKind: RelayManagedEndpointProviderKind,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Relay returned link credentials with endpoint provider "${this.actualProviderKind}" instead of "${this.expectedProviderKind}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export const CloudEnvironmentLinkError = Schema.Union([
|
||||
CloudEnvironmentLinkOperationError,
|
||||
CloudRelayUrlNotConfiguredError,
|
||||
CloudEnvironmentLocalBearerRequiredError,
|
||||
CloudEnvironmentIdMismatchError,
|
||||
CloudEnvironmentEndpointMismatchError,
|
||||
CloudEnvironmentEndpointProviderMismatchError,
|
||||
]);
|
||||
export type CloudEnvironmentLinkError = typeof CloudEnvironmentLinkError.Type;
|
||||
export const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError);
|
||||
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
readonly traceId?: string;
|
||||
}> {}
|
||||
|
||||
export interface CloudEnvironmentRecordWithStatus {
|
||||
readonly environment: RelayClientEnvironmentRecord;
|
||||
@@ -319,47 +62,132 @@ export interface CloudEnvironmentRecordWithStatus {
|
||||
readonly statusError: string | null;
|
||||
}
|
||||
|
||||
const isEnvironmentCloudApiError = Schema.is(
|
||||
Schema.Union([
|
||||
EnvironmentHttpBadRequestError,
|
||||
EnvironmentHttpUnauthorizedError,
|
||||
EnvironmentHttpForbiddenError,
|
||||
EnvironmentHttpConflictError,
|
||||
EnvironmentHttpInternalServerError,
|
||||
EnvironmentCloudEndpointUnavailableError,
|
||||
]),
|
||||
);
|
||||
|
||||
const MANAGED_ENDPOINT_PROVIDER_KIND =
|
||||
"cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
|
||||
|
||||
function cloudEnvironmentLinkError(message: string) {
|
||||
return (cause: unknown) => {
|
||||
const environmentError = findEnvironmentCloudApiError(cause);
|
||||
const traceId = findErrorTraceId(cause);
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: environmentError
|
||||
? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
|
||||
: withDevCause(message, cause),
|
||||
cause,
|
||||
...(traceId === null ? {} : { traceId }),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function isDevRuntime(): boolean {
|
||||
return typeof __DEV__ !== "undefined" && __DEV__;
|
||||
}
|
||||
|
||||
function causeMessage(cause: unknown): string | null {
|
||||
if (cause instanceof Error && cause.message) {
|
||||
return cause.message;
|
||||
}
|
||||
if (typeof cause === "object" && cause !== null) {
|
||||
const record = cause as { readonly message?: unknown; readonly cause?: unknown };
|
||||
if (typeof record.message === "string" && record.message.length > 0) {
|
||||
const nested = causeMessage(record.cause);
|
||||
return nested ? `${record.message}: ${nested}` : record.message;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function withDevCause(message: string, cause: unknown): string {
|
||||
if (!isDevRuntime()) {
|
||||
return message;
|
||||
}
|
||||
const detail = causeMessage(cause);
|
||||
return detail ? `${message} (${detail})` : message;
|
||||
}
|
||||
|
||||
function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
|
||||
switch (error._tag) {
|
||||
case "RelayAuthInvalidError":
|
||||
switch (error.reason) {
|
||||
case "missing_bearer":
|
||||
case "invalid_bearer":
|
||||
return "Relay rejected the cloud session token.";
|
||||
case "invalid_dpop":
|
||||
return "Relay rejected the DPoP proof.";
|
||||
case "not_authorized":
|
||||
return "Relay rejected the authenticated request.";
|
||||
}
|
||||
case "RelayEnvironmentLinkProofExpiredError":
|
||||
return "Relay rejected an expired environment link proof.";
|
||||
case "RelayEnvironmentLinkProofInvalidError":
|
||||
return `Relay rejected the environment link proof (${error.reason}).`;
|
||||
case "RelayEnvironmentConnectNotAuthorizedError":
|
||||
return "Relay rejected the environment connection request.";
|
||||
case "RelayEnvironmentEndpointUnavailableError":
|
||||
return `Relay could not reach the environment endpoint (${error.reason}).`;
|
||||
case "RelayEnvironmentEndpointTimedOutError":
|
||||
return "Relay timed out while contacting the environment endpoint.";
|
||||
case "RelayEnvironmentLinkFailedError":
|
||||
return `Relay could not link the environment (${error.reason}).`;
|
||||
case "RelayEnvironmentLinkUnavailableError":
|
||||
return `Relay cannot provision the managed endpoint (${error.reason}).`;
|
||||
case "RelayAgentActivityPublishProofExpiredError":
|
||||
return "Relay rejected an expired agent activity publish proof.";
|
||||
case "RelayAgentActivityPublishProofInvalidError":
|
||||
return `Relay rejected the agent activity publish proof (${error.reason}).`;
|
||||
case "RelayInternalError":
|
||||
return `Relay encountered an internal error (${error.reason}).`;
|
||||
}
|
||||
}
|
||||
|
||||
function decodedRelayClientError(message: string) {
|
||||
return (cause: ManagedRelay.ManagedRelayClientError) => {
|
||||
const relayError =
|
||||
cause._tag === "ManagedRelayRequestFailedError" ? cause.relayError : undefined;
|
||||
const traceId = cause._tag === "ManagedRelayRequestFailedError" ? cause.traceId : undefined;
|
||||
const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: detail ? `${message}: ${detail}` : message,
|
||||
cause,
|
||||
...(traceId ? { traceId } : {}),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
|
||||
if (isEnvironmentCloudApiError(cause)) {
|
||||
return cause;
|
||||
}
|
||||
if (typeof cause !== "object" || cause === null) {
|
||||
return null;
|
||||
}
|
||||
return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
|
||||
}
|
||||
|
||||
function requireRelayUrl(): Effect.Effect<string, CloudEnvironmentLinkError> {
|
||||
const relayUrl = readRelayUrl();
|
||||
return relayUrl ? Effect.succeed(relayUrl) : Effect.fail(new CloudRelayUrlNotConfiguredError());
|
||||
return relayUrl
|
||||
? Effect.succeed(relayUrl)
|
||||
: Effect.fail(new CloudEnvironmentLinkError({ message: "Relay URL is not configured." }));
|
||||
}
|
||||
|
||||
function endpointOrigin(input: { readonly environmentId: string; readonly httpBaseUrl: string }) {
|
||||
return Effect.try({
|
||||
try: () => {
|
||||
const url = new URL(input.httpBaseUrl);
|
||||
return {
|
||||
localHttpHost: "127.0.0.1",
|
||||
localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "derive the environment endpoint origin",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: input.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
function makeCloudEnvironmentHttpApiClient(input: {
|
||||
readonly environmentId: string;
|
||||
readonly httpBaseUrl: string;
|
||||
}) {
|
||||
return Effect.try({
|
||||
try: () => makeEnvironmentHttpApiClient(input.httpBaseUrl),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "initialize the environment HTTP client",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: input.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.flatten);
|
||||
function endpointOrigin(httpBaseUrl: string) {
|
||||
const url = new URL(httpBaseUrl);
|
||||
return {
|
||||
localHttpHost: "127.0.0.1",
|
||||
localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
|
||||
};
|
||||
}
|
||||
|
||||
function ensureLinkedEnvironmentMatches(input: {
|
||||
@@ -368,17 +196,13 @@ function ensureLinkedEnvironmentMatches(input: {
|
||||
readonly link: RelayEnvironmentLinkResponseType;
|
||||
}): Effect.Effect<void, CloudEnvironmentLinkError> {
|
||||
if (input.link.environmentId !== input.expectedEnvironmentId) {
|
||||
return new CloudEnvironmentIdMismatchError({
|
||||
source: "environment link response",
|
||||
expectedEnvironmentId: input.expectedEnvironmentId,
|
||||
actualEnvironmentId: input.link.environmentId,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
});
|
||||
}
|
||||
if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
|
||||
return new CloudEnvironmentEndpointProviderMismatchError({
|
||||
environmentId: input.expectedEnvironmentId,
|
||||
expectedProviderKind: input.expectedProviderKind,
|
||||
actualProviderKind: input.link.endpoint.providerKind,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different endpoint provider.",
|
||||
});
|
||||
}
|
||||
return Effect.void;
|
||||
@@ -400,28 +224,21 @@ function ensureStatusMatchesEnvironment(input: {
|
||||
readonly status: RelayEnvironmentStatusResponseType;
|
||||
}): Effect.Effect<void, CloudEnvironmentLinkError> {
|
||||
if (input.status.environmentId !== input.environment.environmentId) {
|
||||
return new CloudEnvironmentIdMismatchError({
|
||||
source: "environment status response",
|
||||
expectedEnvironmentId: input.environment.environmentId,
|
||||
actualEnvironmentId: input.status.environmentId,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned status for a different environment.",
|
||||
});
|
||||
}
|
||||
if (!endpointMatches(input.status.endpoint, input.environment.endpoint)) {
|
||||
return CloudEnvironmentEndpointMismatchError.fromEndpoints({
|
||||
source: "environment status response",
|
||||
environmentId: input.environment.environmentId,
|
||||
expectedEndpoint: input.environment.endpoint,
|
||||
actualEndpoint: input.status.endpoint,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned status for a different endpoint.",
|
||||
});
|
||||
}
|
||||
if (
|
||||
input.status.descriptor &&
|
||||
input.status.descriptor.environmentId !== input.environment.environmentId
|
||||
) {
|
||||
return new CloudEnvironmentIdMismatchError({
|
||||
source: "environment status descriptor",
|
||||
expectedEnvironmentId: input.environment.environmentId,
|
||||
actualEnvironmentId: input.status.descriptor.environmentId,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned status descriptor for a different environment.",
|
||||
});
|
||||
}
|
||||
return Effect.void;
|
||||
@@ -432,11 +249,8 @@ function ensureConnectEndpointMatchesEnvironment(input: {
|
||||
readonly connect: RelayEnvironmentConnectResponseType;
|
||||
}): Effect.Effect<void, CloudEnvironmentLinkError> {
|
||||
if (!endpointMatches(input.connect.endpoint, input.environment.endpoint)) {
|
||||
return CloudEnvironmentEndpointMismatchError.fromEndpoints({
|
||||
source: "environment connect response",
|
||||
environmentId: input.environment.environmentId,
|
||||
expectedEndpoint: input.environment.endpoint,
|
||||
actualEndpoint: input.connect.endpoint,
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different endpoint.",
|
||||
});
|
||||
}
|
||||
return Effect.void;
|
||||
@@ -452,9 +266,8 @@ export function linkEnvironmentToCloud(input: {
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
if (!input.connection.bearerToken) {
|
||||
return yield* CloudEnvironmentLocalBearerRequiredError.fromConnection({
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "Only a locally paired bearer connection can be linked to the cloud.",
|
||||
});
|
||||
}
|
||||
const localBearerToken = input.connection.bearerToken;
|
||||
@@ -462,21 +275,11 @@ export function linkEnvironmentToCloud(input: {
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
const deviceId = yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "load the mobile device id",
|
||||
environmentId: input.connection.environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
|
||||
});
|
||||
const preferences = yield* Effect.tryPromise({
|
||||
try: () => loadPreferences(),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "load mobile notification preferences",
|
||||
environmentId: input.connection.environmentId,
|
||||
cause,
|
||||
}),
|
||||
catch: cloudEnvironmentLinkError("Could not load mobile notification preferences."),
|
||||
});
|
||||
const liveActivitiesEnabled = preferences.liveActivitiesEnabled !== false;
|
||||
const challenge = yield* relayClient
|
||||
@@ -489,23 +292,11 @@ export function linkEnvironmentToCloud(input: {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "create an environment link challenge",
|
||||
environmentId: input.connection.environmentId,
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),
|
||||
),
|
||||
);
|
||||
const origin = yield* endpointOrigin({
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
});
|
||||
const environmentClient = yield* makeCloudEnvironmentHttpApiClient({
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
});
|
||||
const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
|
||||
const proof = yield* environmentClient.connect
|
||||
.linkProof({
|
||||
headers: { authorization: `Bearer ${localBearerToken}` },
|
||||
@@ -517,19 +308,10 @@ export function linkEnvironmentToCloud(input: {
|
||||
wsBaseUrl: input.connection.wsBaseUrl,
|
||||
providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
|
||||
},
|
||||
origin,
|
||||
origin: endpointOrigin(input.connection.httpBaseUrl),
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "obtain an environment link proof",
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof.")));
|
||||
const link = yield* relayClient
|
||||
.linkEnvironment({
|
||||
clerkToken: input.clerkToken,
|
||||
@@ -542,14 +324,7 @@ export function linkEnvironmentToCloud(input: {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "link the environment",
|
||||
environmentId: input.connection.environmentId,
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),
|
||||
);
|
||||
yield* ensureLinkedEnvironmentMatches({
|
||||
expectedEnvironmentId: input.connection.environmentId,
|
||||
@@ -570,14 +345,7 @@ export function linkEnvironmentToCloud(input: {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "configure environment relay access",
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -593,15 +361,11 @@ export function listCloudEnvironments(input: {
|
||||
const relayUrl = yield* requireRelayUrl();
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
|
||||
return yield* relayClient.listEnvironments({ clerkToken: input.clerkToken }).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "list cloud environments",
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* relayClient
|
||||
.listEnvironments({
|
||||
clerkToken: input.clerkToken,
|
||||
})
|
||||
.pipe(Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/environments failed`)));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -624,13 +388,10 @@ export function getCloudEnvironmentStatus(input: {
|
||||
environmentId: input.environment.environmentId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "read cloud environment status",
|
||||
environmentId: input.environment.environmentId,
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
decodedRelayClientError(
|
||||
`${relayUrl}/v1/environments/${encodeURIComponent(input.environment.environmentId)}/status failed`,
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* ensureStatusMatchesEnvironment({ environment: input.environment, status });
|
||||
@@ -697,19 +458,14 @@ export function listCloudEnvironmentsWithStatus(input: {
|
||||
});
|
||||
}
|
||||
|
||||
const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(function* (
|
||||
environmentId: string,
|
||||
) {
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "load the mobile device id",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
});
|
||||
const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(
|
||||
function* () {
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManagedEnvironment")(
|
||||
function* (input: {
|
||||
@@ -721,7 +477,7 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
const relayUrl = yield* requireRelayUrl();
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
|
||||
const deviceId = yield* loadAgentAwarenessDeviceId(input.environmentId);
|
||||
const deviceId = yield* loadAgentAwarenessDeviceId();
|
||||
const connect = yield* relayClient
|
||||
.connectEnvironment({
|
||||
clerkToken: input.clerkToken,
|
||||
@@ -730,20 +486,15 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
deviceId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "connect to the cloud environment",
|
||||
environmentId: input.environmentId,
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
decodedRelayClientError(
|
||||
`${relayUrl}/v1/environments/${encodeURIComponent(input.environmentId)}/connect failed`,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (connect.environmentId !== input.environmentId) {
|
||||
return yield* new CloudEnvironmentIdMismatchError({
|
||||
source: "environment connect response",
|
||||
expectedEnvironmentId: input.environmentId,
|
||||
actualEnvironmentId: connect.environmentId,
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
});
|
||||
}
|
||||
if (input.expectedEnvironment) {
|
||||
@@ -756,69 +507,39 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "fetch the connected environment descriptor",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),
|
||||
),
|
||||
);
|
||||
if (descriptor.environmentId !== connect.environmentId) {
|
||||
return yield* new CloudEnvironmentIdMismatchError({
|
||||
source: "connected environment descriptor",
|
||||
expectedEnvironmentId: connect.environmentId,
|
||||
actualEnvironmentId: descriptor.environmentId,
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "Connected endpoint descriptor does not match the selected environment.",
|
||||
});
|
||||
}
|
||||
const endpointUrl = yield* Effect.try({
|
||||
try: () => new URL(connect.endpoint.httpBaseUrl),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "parse the managed endpoint URL",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
|
||||
const bootstrapDpop = yield* signer
|
||||
.createProof({
|
||||
method: "POST",
|
||||
url: new URL("/oauth/token", endpointUrl).toString(),
|
||||
url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "create a bootstrap DPoP proof",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));
|
||||
const bootstrap = yield* exchangeRemoteDpopAccessToken({
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
credential: connect.credential,
|
||||
dpopProof: bootstrapDpop,
|
||||
clientMetadata: authClientMetadata(),
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "exchange a managed endpoint DPoP access token",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError(
|
||||
cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
|
||||
),
|
||||
);
|
||||
endpointUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
|
||||
const pairingUrl = new URL(connect.endpoint.httpBaseUrl);
|
||||
pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
|
||||
|
||||
return {
|
||||
environmentId: descriptor.environmentId,
|
||||
environmentLabel: descriptor.label,
|
||||
pairingUrl: stripPairingTokenFromUrl(endpointUrl).toString(),
|
||||
pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),
|
||||
displayUrl: connect.endpoint.httpBaseUrl,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
wsBaseUrl: connect.endpoint.wsBaseUrl,
|
||||
|
||||
@@ -28,24 +28,25 @@ const relayDpopSignerLayer = Layer.effect(
|
||||
),
|
||||
createProof: Effect.fn("mobile.managedRelayDpopSigner.createProof")(function* (input) {
|
||||
const proofKey = yield* loadProofKey.pipe(
|
||||
Effect.mapError((error) =>
|
||||
ManagedRelay.ManagedRelayDpopKeyLoadError.fromTarget({
|
||||
keyStore: "expo-secure-store",
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ManagedRelay.ManagedRelayDpopProofCreationError({
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* createDpopProof({ ...input, proofKey }).pipe(
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.map((proof) => proof.proof),
|
||||
Effect.mapError((error) =>
|
||||
ManagedRelay.ManagedRelayDpopProofCreationError.fromTarget({
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ManagedRelay.ManagedRelayDpopProofCreationError({
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
const secureStore = vi.hoisted(() => new Map<string, string>());
|
||||
@@ -18,10 +16,7 @@ vi.mock("expo-secure-store", () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
import {
|
||||
ManagedRelayTokenStoreError,
|
||||
managedRelayAccessTokenStore,
|
||||
} from "./managedRelayTokenStore";
|
||||
import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
|
||||
|
||||
it.effect("round-trips and clears persisted managed relay access tokens", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -54,32 +49,3 @@ it.effect("falls back to an empty cache when persisted data is invalid", () =>
|
||||
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs structured storage failures before falling back to an empty cache", () => {
|
||||
const messages: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(message);
|
||||
});
|
||||
const cause = new Error("secure store unavailable");
|
||||
vi.mocked(SecureStore.getItemAsync).mockRejectedValueOnce(cause);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
|
||||
|
||||
const message = messages.find(
|
||||
(candidate) =>
|
||||
Array.isArray(candidate) && candidate[0] === "Managed relay token store operation failed.",
|
||||
);
|
||||
expect(message).toBeDefined();
|
||||
const context = (message as ReadonlyArray<unknown>)[1] as {
|
||||
readonly cause: ManagedRelayTokenStoreError;
|
||||
};
|
||||
expect(context.cause).toBeInstanceOf(ManagedRelayTokenStoreError);
|
||||
expect(context.cause).toMatchObject({
|
||||
operation: "read",
|
||||
storageKey: "t3code.cloud.relay-access-tokens",
|
||||
cause,
|
||||
});
|
||||
expect(context.cause.message).not.toContain(cause.message);
|
||||
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ManagedRelay } from "@t3tools/client-runtime/relay";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
@@ -30,50 +31,36 @@ const decodeManagedRelayAccessTokenCache = Schema.decodeUnknownEffect(
|
||||
);
|
||||
const encodeManagedRelayAccessTokenCache = Schema.encodeEffect(ManagedRelayAccessTokenCacheSchema);
|
||||
|
||||
export class ManagedRelayTokenStoreError extends Schema.TaggedErrorClass<ManagedRelayTokenStoreError>()(
|
||||
"ManagedRelayTokenStoreError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "decode", "encode", "write", "clear"]),
|
||||
storageKey: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Managed relay token store operation "${this.operation}" failed for key "${this.storageKey}".`;
|
||||
}
|
||||
}
|
||||
export class ManagedRelayTokenStoreError extends Data.TaggedError("ManagedRelayTokenStoreError")<{
|
||||
readonly message: string;
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
function logStoreFailure(error: ManagedRelayTokenStoreError) {
|
||||
return Effect.logWarning("Managed relay token store operation failed.", {
|
||||
errorTag: error._tag,
|
||||
operation: error.operation,
|
||||
storageKey: error.storageKey,
|
||||
cause: error,
|
||||
});
|
||||
const storeError =
|
||||
(message: string) =>
|
||||
(cause: unknown): ManagedRelayTokenStoreError =>
|
||||
new ManagedRelayTokenStoreError({ message, cause });
|
||||
|
||||
function logStoreFailure(operation: string) {
|
||||
return (error: ManagedRelayTokenStoreError) =>
|
||||
Effect.logWarning(`Managed relay token store ${operation} failed.`).pipe(
|
||||
Effect.annotateLogs({
|
||||
errorTag: error._tag,
|
||||
message: error.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const loadManagedRelayAccessTokens = Effect.tryPromise({
|
||||
try: () => SecureStore.getItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
|
||||
catch: (cause) =>
|
||||
new ManagedRelayTokenStoreError({
|
||||
operation: "read",
|
||||
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
|
||||
cause,
|
||||
}),
|
||||
catch: storeError("Could not read persisted relay access tokens."),
|
||||
}).pipe(
|
||||
Effect.flatMap((encoded) =>
|
||||
encoded === null
|
||||
? Effect.succeed<ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry>>([])
|
||||
: decodeManagedRelayAccessTokenCache(encoded).pipe(
|
||||
Effect.map((cache) => cache.entries),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedRelayTokenStoreError({
|
||||
operation: "decode",
|
||||
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(storeError("Persisted relay access tokens are invalid.")),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -85,48 +72,34 @@ const saveManagedRelayAccessTokens = (
|
||||
version: MANAGED_RELAY_TOKEN_CACHE_VERSION,
|
||||
entries,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedRelayTokenStoreError({
|
||||
operation: "encode",
|
||||
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(storeError("Could not encode relay access tokens.")),
|
||||
Effect.flatMap((encoded) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.setItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY, encoded),
|
||||
catch: (cause) =>
|
||||
new ManagedRelayTokenStoreError({
|
||||
operation: "write",
|
||||
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
|
||||
cause,
|
||||
}),
|
||||
catch: storeError("Could not persist relay access tokens."),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const clearManagedRelayAccessTokens = Effect.tryPromise({
|
||||
try: () => SecureStore.deleteItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
|
||||
catch: (cause) =>
|
||||
new ManagedRelayTokenStoreError({
|
||||
operation: "clear",
|
||||
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
|
||||
cause,
|
||||
}),
|
||||
catch: storeError("Could not clear persisted relay access tokens."),
|
||||
});
|
||||
|
||||
export const managedRelayAccessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = {
|
||||
load: loadManagedRelayAccessTokens.pipe(
|
||||
Effect.tapError(logStoreFailure),
|
||||
Effect.tapError(logStoreFailure("load")),
|
||||
Effect.orElseSucceed(() => []),
|
||||
Effect.withSpan("mobile.managedRelayTokenStore.load"),
|
||||
),
|
||||
save: Effect.fn("mobile.managedRelayTokenStore.save")((entries) =>
|
||||
saveManagedRelayAccessTokens(entries).pipe(Effect.tapError(logStoreFailure), Effect.ignore),
|
||||
saveManagedRelayAccessTokens(entries).pipe(
|
||||
Effect.tapError(logStoreFailure("save")),
|
||||
Effect.ignore,
|
||||
),
|
||||
),
|
||||
clear: clearManagedRelayAccessTokens.pipe(
|
||||
Effect.tapError(logStoreFailure),
|
||||
Effect.tapError(logStoreFailure("clear")),
|
||||
Effect.ignore,
|
||||
Effect.withSpan("mobile.managedRelayTokenStore.clear"),
|
||||
),
|
||||
|
||||
@@ -101,7 +101,7 @@ export function ConnectionEnvironmentRow(props: {
|
||||
className="underline"
|
||||
onLongPress={(event) => {
|
||||
event.stopPropagation();
|
||||
copyTextWithHaptic(statusTraceId, { target: "connection-trace-id" });
|
||||
copyTextWithHaptic(statusTraceId);
|
||||
}}
|
||||
onPress={(event) => {
|
||||
event.stopPropagation();
|
||||
|
||||
@@ -85,11 +85,7 @@ export function EnvironmentConnectionNotice(props: {
|
||||
accessibilityHint="Copies the trace ID"
|
||||
accessibilityRole="button"
|
||||
className="underline decoration-dotted"
|
||||
onPress={() =>
|
||||
copyTextWithHaptic(props.connection.traceId!, {
|
||||
target: "connection-trace-id",
|
||||
})
|
||||
}
|
||||
onPress={() => copyTextWithHaptic(props.connection.traceId!)}
|
||||
>
|
||||
{props.connection.traceId}
|
||||
</Text>
|
||||
|
||||
@@ -58,7 +58,7 @@ export function useConnectionController() {
|
||||
environment: entry.environment,
|
||||
availability: entry.availability,
|
||||
status: Option.getOrNull(entry.status),
|
||||
error: Option.getOrNull(entry.error)?.detail ?? null,
|
||||
error: Option.getOrNull(entry.error)?.message ?? null,
|
||||
traceId: Option.getOrNull(entry.error)?.traceId ?? null,
|
||||
})),
|
||||
[discovery.environments],
|
||||
@@ -112,7 +112,7 @@ export function useConnectionController() {
|
||||
relayDiscovery: {
|
||||
isRefreshing: discovery.refreshing,
|
||||
isOffline: discovery.offline,
|
||||
error: Option.getOrNull(discovery.error)?.detail ?? null,
|
||||
error: Option.getOrNull(discovery.error)?.message ?? null,
|
||||
errorTraceId: Option.getOrNull(discovery.error)?.traceId ?? null,
|
||||
},
|
||||
connectPairingUrl,
|
||||
|
||||
@@ -8,7 +8,6 @@ import jsxLanguage from "@shikijs/langs/jsx";
|
||||
import tsxLanguage from "@shikijs/langs/tsx";
|
||||
import typescriptLanguage from "@shikijs/langs/typescript";
|
||||
import yamlLanguage from "@shikijs/langs/yaml";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import type { NativeReviewDiffFile, NativeReviewDiffLanguage } from "./nativeReviewDiffTypes";
|
||||
import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffSurface";
|
||||
@@ -16,32 +15,6 @@ import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewD
|
||||
export type NativeReviewDiffHighlightScheme = "light" | "dark";
|
||||
export type NativeReviewDiffHighlightEngine = "native" | "javascript";
|
||||
|
||||
export class NativeReviewDiffHighlighterUnavailableError extends Schema.TaggedErrorClass<NativeReviewDiffHighlighterUnavailableError>()(
|
||||
"NativeReviewDiffHighlighterUnavailableError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "The native review diff highlighter is unavailable in this build.";
|
||||
}
|
||||
}
|
||||
|
||||
export const isNativeReviewDiffHighlighterUnavailableError = Schema.is(
|
||||
NativeReviewDiffHighlighterUnavailableError,
|
||||
);
|
||||
|
||||
export class NativeReviewDiffHighlighterInitializationError extends Schema.TaggedErrorClass<NativeReviewDiffHighlighterInitializationError>()(
|
||||
"NativeReviewDiffHighlighterInitializationError",
|
||||
{
|
||||
requestedEngine: Schema.Literals(["native", "javascript"]),
|
||||
attemptedEngine: Schema.Literals(["native", "javascript"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to initialize the ${this.attemptedEngine} review diff highlighter requested as ${this.requestedEngine}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffHighlighterHandle {
|
||||
readonly engine: NativeReviewDiffHighlightEngine;
|
||||
readonly tokenize: (
|
||||
@@ -224,7 +197,7 @@ function normalizeTokens(
|
||||
async function createNativeReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
|
||||
const nativeEngineModule = await import("react-native-shiki-engine");
|
||||
if (!nativeEngineModule.isNativeEngineAvailable()) {
|
||||
throw new NativeReviewDiffHighlighterUnavailableError();
|
||||
throw new Error("Native Shiki engine is not available in this build.");
|
||||
}
|
||||
|
||||
const highlighter = await createHighlighterCore({
|
||||
@@ -256,52 +229,18 @@ export async function getNativeReviewDiffHighlighter(
|
||||
engine: NativeReviewDiffHighlightEngine = "native",
|
||||
): Promise<NativeReviewDiffHighlighterHandle> {
|
||||
if (engine === "javascript") {
|
||||
try {
|
||||
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
|
||||
return await javascriptHighlighterPromise;
|
||||
} catch (cause) {
|
||||
javascriptHighlighterPromise = null;
|
||||
throw new NativeReviewDiffHighlighterInitializationError({
|
||||
requestedEngine: engine,
|
||||
attemptedEngine: "javascript",
|
||||
cause,
|
||||
});
|
||||
}
|
||||
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
|
||||
return javascriptHighlighterPromise;
|
||||
}
|
||||
|
||||
nativeHighlighterPromise ??= createNativeReviewDiffHighlighter()
|
||||
.catch(async (cause: unknown) => {
|
||||
const nativeError = isNativeReviewDiffHighlighterUnavailableError(cause)
|
||||
? cause
|
||||
: new NativeReviewDiffHighlighterInitializationError({
|
||||
requestedEngine: engine,
|
||||
attemptedEngine: "native",
|
||||
cause,
|
||||
});
|
||||
console.warn("[debug-native-diff] native highlighter unavailable", {
|
||||
error: nativeError,
|
||||
});
|
||||
try {
|
||||
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
|
||||
return await javascriptHighlighterPromise;
|
||||
} catch (fallbackCause) {
|
||||
javascriptHighlighterPromise = null;
|
||||
throw new NativeReviewDiffHighlighterInitializationError({
|
||||
requestedEngine: engine,
|
||||
attemptedEngine: "javascript",
|
||||
cause: new AggregateError(
|
||||
[nativeError, fallbackCause],
|
||||
"Native and JavaScript review diff highlighter initialization failed.",
|
||||
{ cause: nativeError },
|
||||
),
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
nativeHighlighterPromise = null;
|
||||
throw error;
|
||||
nativeHighlighterPromise ??= createNativeReviewDiffHighlighter().catch((error: unknown) => {
|
||||
console.warn("[debug-native-diff] native highlighter unavailable", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return await nativeHighlighterPromise;
|
||||
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
|
||||
return javascriptHighlighterPromise;
|
||||
});
|
||||
return nativeHighlighterPromise;
|
||||
}
|
||||
|
||||
function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDiffLineRow {
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createSourceHighlightAtomFamily,
|
||||
SourceHighlightError,
|
||||
type SourceHighlightTokens,
|
||||
} from "./sourceHighlightingState";
|
||||
|
||||
@@ -102,29 +100,22 @@ describe("sourceHighlightingState", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("preserves highlighter failures with the source path and theme", async () => {
|
||||
const cause = new Error("highlight failed");
|
||||
const highlight = vi.fn(() => Promise.reject(cause));
|
||||
it("exposes highlighter errors as a failed async result", async () => {
|
||||
const highlight = vi.fn(async () => {
|
||||
throw new Error("highlight failed");
|
||||
});
|
||||
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight });
|
||||
const registry = AtomRegistry.make();
|
||||
const path = "src/example.ts";
|
||||
const theme = "light" as const;
|
||||
const atom = sourceHighlightAtom({
|
||||
path,
|
||||
path: "src/example.ts",
|
||||
contents: "const value = 1;",
|
||||
theme,
|
||||
theme: "light",
|
||||
});
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
|
||||
});
|
||||
const result = registry.get(atom);
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
const error = Cause.squash(result.cause);
|
||||
expect(error).toEqual(new SourceHighlightError({ path, theme, cause }));
|
||||
expect((error as SourceHighlightError).cause).toBe(cause);
|
||||
}
|
||||
|
||||
unmount();
|
||||
registry.dispose();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
@@ -23,18 +22,9 @@ type SourceHighlighter = (input: SourceHighlightInput) => Promise<SourceHighligh
|
||||
|
||||
class SourceHighlightCacheKey extends Data.Class<SourceHighlightInput> {}
|
||||
|
||||
export class SourceHighlightError extends Schema.TaggedErrorClass<SourceHighlightError>()(
|
||||
"SourceHighlightError",
|
||||
{
|
||||
path: Schema.String,
|
||||
theme: Schema.Literals(["light", "dark"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not highlight ${this.path} with the ${this.theme} theme.`;
|
||||
}
|
||||
}
|
||||
class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export function createSourceHighlightAtomFamily(options?: {
|
||||
readonly highlight?: SourceHighlighter;
|
||||
@@ -46,8 +36,7 @@ export function createSourceHighlightAtomFamily(options?: {
|
||||
Atom.make(
|
||||
Effect.tryPromise({
|
||||
try: () => highlight(request),
|
||||
catch: (cause) =>
|
||||
new SourceHighlightError({ path: request.path, theme: request.theme, cause }),
|
||||
catch: (cause) => new SourceHighlightError({ cause }),
|
||||
}),
|
||||
).pipe(
|
||||
Atom.setIdleTTL(idleTtlMs),
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Hash from "effect/Hash";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createWorkspaceFileImageAtomFamily,
|
||||
WorkspaceImagePrefetchFailedError,
|
||||
WorkspaceImagePrefetchUnavailableError,
|
||||
} from "./workspace-file-image-cache";
|
||||
import { createWorkspaceFileImageAtomFamily } from "./workspace-file-image-cache";
|
||||
|
||||
describe("workspaceFileImageAtom", () => {
|
||||
it("reuses a prefetched image across route remounts", async () => {
|
||||
@@ -54,65 +48,15 @@ describe("workspaceFileImageAtom", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("reports an unavailable image when prefetch completes without caching it", async () => {
|
||||
const uri = "https://example.test/api/assets/signed-secret-token/missing.png?signature=private";
|
||||
it("exposes prefetch failures", async () => {
|
||||
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: async () => false });
|
||||
const registry = AtomRegistry.make();
|
||||
const atom = imageAtom(uri);
|
||||
expect(atom.label?.[0]).not.toContain("signed-secret-token");
|
||||
expect(atom.label?.[0]).not.toContain("signature=private");
|
||||
const atom = imageAtom("https://example.test/missing.png");
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
|
||||
});
|
||||
const result = registry.get(atom);
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
const error = Cause.squash(result.cause);
|
||||
expect(error).toEqual(
|
||||
new WorkspaceImagePrefetchUnavailableError({
|
||||
uriHash: Hash.hash(uri),
|
||||
uriLength: uri.length,
|
||||
uriProtocol: "https:",
|
||||
}),
|
||||
);
|
||||
expect(error).not.toHaveProperty("uri");
|
||||
expect(String(error)).not.toContain("signed-secret-token");
|
||||
expect(String(error)).not.toContain("signature=private");
|
||||
}
|
||||
|
||||
unmount();
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("preserves rejected prefetch causes without retaining the signed image URI", async () => {
|
||||
const uri =
|
||||
"https://example.test/api/assets/signed-secret-token/rejected.png?signature=private";
|
||||
const cause = new Error("native image loader failed");
|
||||
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: () => Promise.reject(cause) });
|
||||
const registry = AtomRegistry.make();
|
||||
const atom = imageAtom(uri);
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
|
||||
});
|
||||
const result = registry.get(atom);
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
const error = Cause.squash(result.cause);
|
||||
expect(error).toEqual(
|
||||
new WorkspaceImagePrefetchFailedError({
|
||||
uriHash: Hash.hash(uri),
|
||||
uriLength: uri.length,
|
||||
uriProtocol: "https:",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
expect((error as WorkspaceImagePrefetchFailedError).cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("uri");
|
||||
expect(String(error)).not.toContain("signed-secret-token");
|
||||
expect(String(error)).not.toContain("signature=private");
|
||||
}
|
||||
|
||||
unmount();
|
||||
registry.dispose();
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Hash from "effect/Hash";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
const WORKSPACE_IMAGE_IDLE_TTL_MS = 30 * 60_000;
|
||||
@@ -11,77 +8,39 @@ type ImagePrefetch = (uri: string) => Promise<boolean>;
|
||||
|
||||
class WorkspaceImageCacheKey extends Data.Class<{ readonly uri: string }> {}
|
||||
|
||||
export class WorkspaceImagePrefetchUnavailableError extends Schema.TaggedErrorClass<WorkspaceImagePrefetchUnavailableError>()(
|
||||
"WorkspaceImagePrefetchUnavailableError",
|
||||
{
|
||||
uriHash: Schema.Number,
|
||||
uriLength: Schema.Number,
|
||||
uriProtocol: Schema.NullOr(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Image prefetch did not cache the requested ${this.uriProtocol ?? "unknown-protocol"} resource (URI length ${this.uriLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceImagePrefetchFailedError extends Schema.TaggedErrorClass<WorkspaceImagePrefetchFailedError>()(
|
||||
"WorkspaceImagePrefetchFailedError",
|
||||
{
|
||||
uriHash: Schema.Number,
|
||||
uriLength: Schema.Number,
|
||||
uriProtocol: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Image prefetch failed for the requested ${this.uriProtocol ?? "unknown-protocol"} resource (URI length ${this.uriLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export const WorkspaceImagePrefetchError = Schema.Union([
|
||||
WorkspaceImagePrefetchUnavailableError,
|
||||
WorkspaceImagePrefetchFailedError,
|
||||
]);
|
||||
export type WorkspaceImagePrefetchError = typeof WorkspaceImagePrefetchError.Type;
|
||||
export class WorkspaceImagePrefetchError extends Data.TaggedError("WorkspaceImagePrefetchError")<{
|
||||
readonly cause?: unknown;
|
||||
readonly uri: string;
|
||||
}> {}
|
||||
|
||||
async function prefetchWithNativeImage(uri: string): Promise<boolean> {
|
||||
const { Image } = await import("react-native");
|
||||
return Image.prefetch(uri);
|
||||
}
|
||||
|
||||
function describeWorkspaceImageUri(uri: string) {
|
||||
const diagnostics = getUrlDiagnostics(uri);
|
||||
return {
|
||||
uriHash: Hash.hash(uri),
|
||||
uriLength: diagnostics.inputLength,
|
||||
uriProtocol: diagnostics.protocol ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function createWorkspaceFileImageAtomFamily(options?: {
|
||||
readonly idleTtlMs?: number;
|
||||
readonly prefetch?: ImagePrefetch;
|
||||
}) {
|
||||
const idleTtlMs = options?.idleTtlMs ?? WORKSPACE_IMAGE_IDLE_TTL_MS;
|
||||
const prefetch = options?.prefetch ?? prefetchWithNativeImage;
|
||||
const family = Atom.family((key: WorkspaceImageCacheKey) => {
|
||||
const uriContext = describeWorkspaceImageUri(key.uri);
|
||||
return Atom.make(
|
||||
Effect.gen(function* () {
|
||||
const cached = yield* Effect.tryPromise({
|
||||
try: () => prefetch(key.uri),
|
||||
catch: (cause) => new WorkspaceImagePrefetchFailedError({ ...uriContext, cause }),
|
||||
});
|
||||
if (!cached) {
|
||||
return yield* new WorkspaceImagePrefetchUnavailableError(uriContext);
|
||||
}
|
||||
return key.uri;
|
||||
const family = Atom.family((key: WorkspaceImageCacheKey) =>
|
||||
Atom.make(
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const cached = await prefetch(key.uri);
|
||||
if (!cached) {
|
||||
throw new WorkspaceImagePrefetchError({ uri: key.uri });
|
||||
}
|
||||
return key.uri;
|
||||
},
|
||||
catch: (cause) =>
|
||||
cause instanceof WorkspaceImagePrefetchError
|
||||
? cause
|
||||
: new WorkspaceImagePrefetchError({ uri: key.uri, cause }),
|
||||
}),
|
||||
).pipe(
|
||||
Atom.setIdleTTL(idleTtlMs),
|
||||
Atom.withLabel(`mobile:workspace-image:${uriContext.uriHash.toString(36)}`),
|
||||
);
|
||||
});
|
||||
).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`mobile:workspace-image:${key.uri}`)),
|
||||
);
|
||||
|
||||
return (uri: string) => family(new WorkspaceImageCacheKey({ uri }));
|
||||
}
|
||||
|
||||
@@ -53,12 +53,11 @@ it("initializes review highlighter state once", async () => {
|
||||
});
|
||||
|
||||
it("stores initialization failures in atom state", async () => {
|
||||
const cause = new Error("load failed");
|
||||
const manager = createReviewHighlighterManager({
|
||||
getRegistry: () => registry,
|
||||
loader: {
|
||||
prepare: async () => {
|
||||
throw cause;
|
||||
throw new Error("load failed");
|
||||
},
|
||||
prepareLanguages: async () => undefined,
|
||||
getEngine: async () => "javascript",
|
||||
@@ -68,23 +67,9 @@ it("stores initialization failures in atom state", async () => {
|
||||
void manager.initialize();
|
||||
await flushAsyncWork();
|
||||
|
||||
const snapshot = manager.getSnapshot();
|
||||
assert.strictEqual(snapshot.engine, null);
|
||||
assert.strictEqual(snapshot.status, "error");
|
||||
assert.strictEqual(snapshot.error?._tag, "ReviewHighlighterManagerError");
|
||||
assert.strictEqual(snapshot.error?.operation, "prepare");
|
||||
assert.deepStrictEqual(snapshot.error?.languages, [
|
||||
"typescript",
|
||||
"tsx",
|
||||
"javascript",
|
||||
"jsx",
|
||||
"json",
|
||||
"yaml",
|
||||
"bash",
|
||||
]);
|
||||
assert.strictEqual(snapshot.error?.cause, cause);
|
||||
assert.strictEqual(
|
||||
snapshot.error?.message,
|
||||
"Review highlighter operation prepare failed for languages typescript, tsx, javascript, jsx, json, yaml, bash.",
|
||||
);
|
||||
assert.deepStrictEqual(manager.getSnapshot(), {
|
||||
engine: null,
|
||||
error: "load failed",
|
||||
status: "error",
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { useEffect } from "react";
|
||||
|
||||
@@ -13,22 +12,9 @@ import {
|
||||
|
||||
export type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";
|
||||
|
||||
export class ReviewHighlighterManagerError extends Schema.TaggedErrorClass<ReviewHighlighterManagerError>()(
|
||||
"ReviewHighlighterManagerError",
|
||||
{
|
||||
operation: Schema.Literals(["prepare", "prepare-languages", "resolve-engine"]),
|
||||
languages: Schema.Array(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Review highlighter operation ${this.operation} failed for languages ${this.languages.join(", ")}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ReviewHighlighterState {
|
||||
readonly engine: ReviewHighlighterEngine | null;
|
||||
readonly error: ReviewHighlighterManagerError | null;
|
||||
readonly error: string | null;
|
||||
readonly status: ReviewHighlighterStatus;
|
||||
}
|
||||
|
||||
@@ -115,35 +101,24 @@ export function createReviewHighlighterManager(config: {
|
||||
|
||||
inFlight = (async () => {
|
||||
const startedAt = performance.now();
|
||||
const languages = config.languages ?? REVIEW_INITIAL_LANGUAGES;
|
||||
let operation: ReviewHighlighterManagerError["operation"] = "prepare";
|
||||
let engine: ReviewHighlighterEngine;
|
||||
try {
|
||||
await config.loader.prepare();
|
||||
operation = "prepare-languages";
|
||||
await config.loader.prepareLanguages(languages);
|
||||
operation = "resolve-engine";
|
||||
engine = await config.loader.getEngine();
|
||||
} catch (cause) {
|
||||
const error = new ReviewHighlighterManagerError({
|
||||
operation,
|
||||
languages,
|
||||
cause,
|
||||
await config.loader.prepareLanguages(config.languages ?? REVIEW_INITIAL_LANGUAGES);
|
||||
const engine = await config.loader.getEngine();
|
||||
const durationMs = Math.round(performance.now() - startedAt);
|
||||
logReviewHighlighterProviderDiagnostic("initialized", {
|
||||
durationMs,
|
||||
engine,
|
||||
});
|
||||
logReviewHighlighterProviderDiagnostic("initialization failed", { error });
|
||||
setState({ engine: null, error, status: "error" });
|
||||
return;
|
||||
setState({ engine, error: null, status: "ready" });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });
|
||||
setState({ engine: null, error: message, status: "error" });
|
||||
} finally {
|
||||
inFlight = null;
|
||||
}
|
||||
|
||||
const durationMs = Math.round(performance.now() - startedAt);
|
||||
logReviewHighlighterProviderDiagnostic("initialized", {
|
||||
durationMs,
|
||||
engine,
|
||||
});
|
||||
setState({ engine, error: null, status: "ready" });
|
||||
})().finally(() => {
|
||||
inFlight = null;
|
||||
});
|
||||
})();
|
||||
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import yamlLanguage from "@shikijs/langs/yaml";
|
||||
import githubDarkDefault from "@shikijs/themes/github-dark-default";
|
||||
import githubLightDefault from "@shikijs/themes/github-light-default";
|
||||
import { getFiletypeFromFileName } from "@pierre/diffs/utils/getFiletypeFromFileName";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
resolveReviewHighlighterEngine,
|
||||
@@ -23,19 +22,6 @@ import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordD
|
||||
export type ReviewDiffTheme = "light" | "dark";
|
||||
export type { ReviewHighlighterEngine };
|
||||
|
||||
export class ReviewHighlighterEngineInitializationError extends Schema.TaggedErrorClass<ReviewHighlighterEngineInitializationError>()(
|
||||
"ReviewHighlighterEngineInitializationError",
|
||||
{
|
||||
preferredEngine: Schema.Literals(["native", "javascript"]),
|
||||
attemptedEngine: Schema.Literals(["native", "javascript"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to initialize the ${this.attemptedEngine} review highlighter with ${this.preferredEngine} preferred.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ReviewHighlightedToken {
|
||||
content: string;
|
||||
readonly color: string | null;
|
||||
@@ -241,6 +227,16 @@ function logReviewHighlighterDiagnosticError(message: string, error: unknown): v
|
||||
if (!isReviewHighlighterDebugLoggingEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
console.error(`[review-highlighter] ${message}`, {
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
stack: error.stack,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.error(`[review-highlighter] ${message}`, error);
|
||||
}
|
||||
|
||||
@@ -262,7 +258,6 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
if (!highlighterPromise) {
|
||||
const configuredHighlighterPromise = (async () => {
|
||||
let nativeEngineAvailable = false;
|
||||
let nativeInitializationError: ReviewHighlighterEngineInitializationError | undefined;
|
||||
|
||||
logReviewHighlighterDiagnostic("initializing", {
|
||||
configuredPreference: REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,
|
||||
@@ -294,14 +289,9 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
nativeInitializationError = new ReviewHighlighterEngineInitializationError({
|
||||
preferredEngine: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
|
||||
attemptedEngine: "native",
|
||||
cause: error,
|
||||
});
|
||||
logReviewHighlighterDiagnosticError(
|
||||
"native engine initialization failed; falling back to javascript",
|
||||
nativeInitializationError,
|
||||
error,
|
||||
);
|
||||
nativeEngineAvailable = false;
|
||||
}
|
||||
@@ -315,30 +305,11 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
|
||||
nativeEngineAvailable,
|
||||
);
|
||||
let highlighter: HighlighterCore;
|
||||
try {
|
||||
highlighter = await createHighlighterCore({
|
||||
themes,
|
||||
langs: REVIEW_INITIAL_LANGUAGE_MODULES,
|
||||
engine: createJavaScriptRegexEngine(),
|
||||
});
|
||||
} catch (cause) {
|
||||
const javascriptError = new ReviewHighlighterEngineInitializationError({
|
||||
preferredEngine: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
|
||||
attemptedEngine: "javascript",
|
||||
cause,
|
||||
});
|
||||
if (!nativeInitializationError) throw javascriptError;
|
||||
throw new ReviewHighlighterEngineInitializationError({
|
||||
preferredEngine: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
|
||||
attemptedEngine: "javascript",
|
||||
cause: new AggregateError(
|
||||
[nativeInitializationError, javascriptError],
|
||||
"Native and JavaScript review highlighter initialization failed.",
|
||||
{ cause: nativeInitializationError },
|
||||
),
|
||||
});
|
||||
}
|
||||
const highlighter = await createHighlighterCore({
|
||||
themes,
|
||||
langs: REVIEW_INITIAL_LANGUAGE_MODULES,
|
||||
engine: createJavaScriptRegexEngine(),
|
||||
});
|
||||
logReviewHighlighterDiagnostic("using javascript engine", {
|
||||
resolvedEngine: engine,
|
||||
});
|
||||
|
||||
@@ -108,11 +108,7 @@ export function useNativeReviewDiffHighlighting(input: {
|
||||
} catch (error) {
|
||||
if (!abortController.signal.aborted) {
|
||||
logReviewDiffDiagnostic("native visible highlight failed", {
|
||||
error,
|
||||
resetKey,
|
||||
scheme,
|
||||
firstRowIndex: requestRange.firstRowIndex,
|
||||
lastRowIndex: requestRange.lastRowIndex,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
@@ -30,7 +31,6 @@ import { TouchableOpacity } from "react-native-gesture-handler";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import {
|
||||
hasNativeSelectableMarkdownText,
|
||||
SelectableMarkdownText,
|
||||
@@ -1321,10 +1321,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}, []);
|
||||
|
||||
const onCopyWorkRow = useCallback((rowId: string, value: string) => {
|
||||
copyTextWithHaptic(value, {
|
||||
target: "thread-work-row",
|
||||
feedback: "selection",
|
||||
});
|
||||
void Clipboard.setStringAsync(value);
|
||||
void Haptics.selectionAsync();
|
||||
setInteractionState((current) => ({ ...current, copiedRowId: rowId }));
|
||||
if (copyFeedbackTimeoutRef.current) {
|
||||
clearTimeout(copyFeedbackTimeoutRef.current);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
|
||||
|
||||
const missingFileCause = new Error("missing file");
|
||||
const files = new Map<string, { base64: string; deleted: boolean }>();
|
||||
|
||||
vi.mock("expo-file-system", () => ({
|
||||
@@ -19,7 +18,7 @@ vi.mock("expo-file-system", () => ({
|
||||
async base64(): Promise<string> {
|
||||
const entry = files.get(this.uri);
|
||||
if (!entry || entry.deleted) {
|
||||
throw missingFileCause;
|
||||
throw new Error("missing file");
|
||||
}
|
||||
return entry.base64;
|
||||
}
|
||||
@@ -92,30 +91,4 @@ describe("native pasted image cleanup", () => {
|
||||
expect(files.get(overflow)?.deleted).toBe(true);
|
||||
expect(files.get(userOwned)?.deleted).toBe(false);
|
||||
});
|
||||
|
||||
it("reports structured context when reading a pasted image fails", async () => {
|
||||
const uri = "file:///private/var/mobile/photos/signed-secret-token/missing.png?token=private";
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
|
||||
await expect(
|
||||
convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 }),
|
||||
).resolves.toEqual([]);
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
"[composer-images] failed to read pasted image",
|
||||
expect.objectContaining({
|
||||
_tag: "ComposerImageOperationError",
|
||||
operation: "read-pasted-image",
|
||||
uriLength: uri.length,
|
||||
uriProtocol: "file:",
|
||||
cause: missingFileCause,
|
||||
message: `Composer image operation read-pasted-image failed for a file: URI (length ${uri.length}).`,
|
||||
}),
|
||||
);
|
||||
const error = warn.mock.calls[0]?.[1];
|
||||
expect(error).not.toHaveProperty("uri");
|
||||
expect(String(error)).not.toContain("signed-secret-token");
|
||||
expect(String(error)).not.toContain("token=private");
|
||||
|
||||
warn.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -3,8 +3,6 @@ import {
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type UploadChatImageAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { uuidv4 } from "./uuid";
|
||||
|
||||
export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
|
||||
@@ -14,31 +12,6 @@ export interface DraftComposerImageAttachment extends UploadChatImageAttachment
|
||||
|
||||
const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
|
||||
|
||||
export class ComposerImageOperationError extends Schema.TaggedErrorClass<ComposerImageOperationError>()(
|
||||
"ComposerImageOperationError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"load-image-picker",
|
||||
"request-media-library-permission",
|
||||
"launch-image-library",
|
||||
"load-clipboard",
|
||||
"check-clipboard-image",
|
||||
"read-clipboard-image",
|
||||
"check-clipboard-text",
|
||||
"read-clipboard-text",
|
||||
"read-pasted-image",
|
||||
"remove-pasted-image",
|
||||
]),
|
||||
uriLength: Schema.optional(Schema.Number),
|
||||
uriProtocol: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Composer image operation ${this.operation} failed${this.uriLength === undefined ? "" : ` for a ${this.uriProtocol ?? "unknown-protocol"} URI (length ${this.uriLength})`}.`;
|
||||
}
|
||||
}
|
||||
|
||||
function estimateBase64ByteSize(base64: string): number {
|
||||
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
|
||||
return Math.floor((base64.length * 3) / 4) - padding;
|
||||
@@ -47,22 +20,16 @@ function estimateBase64ByteSize(base64: string): number {
|
||||
async function loadImagePicker() {
|
||||
try {
|
||||
return await import("expo-image-picker");
|
||||
} catch (cause) {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "load-image-picker",
|
||||
cause,
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error("Image attachments are unavailable right now.", { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
async function loadClipboard() {
|
||||
try {
|
||||
return await import("expo-clipboard");
|
||||
} catch (cause) {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "load-clipboard",
|
||||
cause,
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error("Clipboard paste is unavailable right now.", { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,19 +49,14 @@ export async function pickComposerImages(input: { readonly existingCount: number
|
||||
try {
|
||||
imagePicker = await loadImagePicker();
|
||||
} catch (error) {
|
||||
console.warn("[composer-images] image picker unavailable", error);
|
||||
return {
|
||||
images: [],
|
||||
error: "Image attachments are unavailable right now.",
|
||||
error:
|
||||
error instanceof Error ? error.message : "Image attachments are unavailable right now.",
|
||||
};
|
||||
}
|
||||
|
||||
const permission = await imagePicker.requestMediaLibraryPermissionsAsync().catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "request-media-library-permission",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
const permission = await imagePicker.requestMediaLibraryPermissionsAsync();
|
||||
if (!permission.granted) {
|
||||
return {
|
||||
images: [],
|
||||
@@ -102,20 +64,13 @@ export async function pickComposerImages(input: { readonly existingCount: number
|
||||
};
|
||||
}
|
||||
|
||||
const result = await imagePicker
|
||||
.launchImageLibraryAsync({
|
||||
mediaTypes: ["images"],
|
||||
allowsMultipleSelection: true,
|
||||
selectionLimit: remainingSlots,
|
||||
base64: true,
|
||||
quality: 1,
|
||||
})
|
||||
.catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "launch-image-library",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
const result = await imagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: ["images"],
|
||||
allowsMultipleSelection: true,
|
||||
selectionLimit: remainingSlots,
|
||||
base64: true,
|
||||
quality: 1,
|
||||
});
|
||||
|
||||
if (result.canceled) {
|
||||
return {
|
||||
@@ -172,23 +127,16 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
|
||||
try {
|
||||
clipboard = await loadClipboard();
|
||||
} catch (error) {
|
||||
console.warn("[composer-images] clipboard unavailable", error);
|
||||
return {
|
||||
images: [],
|
||||
text: null,
|
||||
error: "Clipboard paste is unavailable right now.",
|
||||
error: error instanceof Error ? error.message : "Clipboard paste is unavailable right now.",
|
||||
};
|
||||
}
|
||||
|
||||
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
|
||||
|
||||
const hasImage = await clipboard.hasImageAsync().catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "check-clipboard-image",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
if (hasImage) {
|
||||
if (await clipboard.hasImageAsync()) {
|
||||
if (remainingSlots <= 0) {
|
||||
return {
|
||||
images: [],
|
||||
@@ -196,12 +144,7 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
|
||||
error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
|
||||
};
|
||||
}
|
||||
const image = await clipboard.getImageAsync({ format: "png" }).catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "read-clipboard-image",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
const image = await clipboard.getImageAsync({ format: "png" });
|
||||
if (!image) {
|
||||
return {
|
||||
images: [],
|
||||
@@ -237,19 +180,8 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
|
||||
};
|
||||
}
|
||||
|
||||
const hasText = await clipboard.hasStringAsync().catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "check-clipboard-text",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
if (hasText) {
|
||||
const text = await clipboard.getStringAsync().catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "read-clipboard-text",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
if (await clipboard.hasStringAsync()) {
|
||||
const text = await clipboard.getStringAsync();
|
||||
return {
|
||||
images: [],
|
||||
text: text.length > 0 ? text : null,
|
||||
@@ -298,14 +230,6 @@ export function isOwnedPastedImageUri(uri: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function describeComposerImageUri(uri: string) {
|
||||
const diagnostics = getUrlDiagnostics(uri);
|
||||
return {
|
||||
uriLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { uriProtocol: diagnostics.protocol }),
|
||||
};
|
||||
}
|
||||
|
||||
export async function convertPastedImagesToAttachments(input: {
|
||||
readonly uris: ReadonlyArray<string>;
|
||||
readonly existingCount: number;
|
||||
@@ -336,15 +260,8 @@ export async function convertPastedImagesToAttachments(input: {
|
||||
dataUrl: `data:${mimeType};base64,${base64}`,
|
||||
previewUri: ownedTemporaryFile ? `data:${mimeType};base64,${base64}` : uri,
|
||||
});
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[composer-images] failed to read pasted image",
|
||||
new ComposerImageOperationError({
|
||||
operation: "read-pasted-image",
|
||||
...describeComposerImageUri(uri),
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn("Failed to read pasted image", uri, error);
|
||||
} finally {
|
||||
if (ownedTemporaryFile) {
|
||||
try {
|
||||
@@ -352,15 +269,8 @@ export async function convertPastedImagesToAttachments(input: {
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[composer-images] failed to remove temporary pasted image",
|
||||
new ComposerImageOperationError({
|
||||
operation: "remove-pasted-image",
|
||||
...describeComposerImageUri(uri),
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn("Failed to remove temporary pasted image", uri, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
impactAsync: vi.fn(),
|
||||
selectionAsync: vi.fn(),
|
||||
setStringAsync: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -15,25 +14,15 @@ vi.mock("expo-haptics", () => ({
|
||||
Light: "light",
|
||||
},
|
||||
impactAsync: mocks.impactAsync,
|
||||
selectionAsync: mocks.selectionAsync,
|
||||
}));
|
||||
|
||||
import {
|
||||
CopyTextClipboardWriteError,
|
||||
CopyTextHapticFeedbackError,
|
||||
copyTextWithHaptic,
|
||||
} from "./copyTextWithHaptic";
|
||||
import { copyTextWithHaptic } from "./copyTextWithHaptic";
|
||||
|
||||
describe("copyTextWithHaptic", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.setStringAsync.mockReturnValue(new Promise<void>(() => undefined));
|
||||
mocks.impactAsync.mockResolvedValue(undefined);
|
||||
mocks.selectionAsync.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("triggers haptic feedback without waiting for the clipboard promise", () => {
|
||||
@@ -42,49 +31,4 @@ describe("copyTextWithHaptic", () => {
|
||||
expect(mocks.setStringAsync).toHaveBeenCalledWith("trace-123");
|
||||
expect(mocks.impactAsync).toHaveBeenCalledWith("light");
|
||||
});
|
||||
|
||||
it("preserves selection feedback for thread work rows", () => {
|
||||
copyTextWithHaptic("work output", {
|
||||
target: "thread-work-row",
|
||||
feedback: "selection",
|
||||
});
|
||||
|
||||
expect(mocks.setStringAsync).toHaveBeenCalledWith("work output");
|
||||
expect(mocks.selectionAsync).toHaveBeenCalledOnce();
|
||||
expect(mocks.impactAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports structured failures without including clipboard contents", async () => {
|
||||
const clipboardCause = new Error("native clipboard failure");
|
||||
const hapticCause = new Error("native haptic failure");
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
mocks.setStringAsync.mockRejectedValueOnce(clipboardCause);
|
||||
mocks.impactAsync.mockRejectedValueOnce(hapticCause);
|
||||
|
||||
copyTextWithHaptic("secret clipboard contents", { target: "connection-trace-id" });
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(consoleError).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
const failures = consoleError.mock.calls.map(([failure]) => failure);
|
||||
const clipboardError = failures.find(
|
||||
(failure) => failure instanceof CopyTextClipboardWriteError,
|
||||
);
|
||||
expect(clipboardError).toBeInstanceOf(CopyTextClipboardWriteError);
|
||||
expect(clipboardError).toMatchObject({
|
||||
target: "connection-trace-id",
|
||||
cause: clipboardCause,
|
||||
});
|
||||
expect((clipboardError as Error).message).not.toContain("secret clipboard contents");
|
||||
|
||||
const hapticError = failures.find((failure) => failure instanceof CopyTextHapticFeedbackError);
|
||||
expect(hapticError).toBeInstanceOf(CopyTextHapticFeedbackError);
|
||||
expect(hapticError).toMatchObject({
|
||||
target: "connection-trace-id",
|
||||
feedback: "light-impact",
|
||||
cause: hapticCause,
|
||||
});
|
||||
expect((hapticError as Error).message).not.toContain("secret clipboard contents");
|
||||
});
|
||||
});
|
||||
@@ -1,70 +1,7 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
import * as Haptics from "expo-haptics";
|
||||
|
||||
export class CopyTextClipboardWriteError extends Schema.TaggedErrorClass<CopyTextClipboardWriteError>()(
|
||||
"CopyTextClipboardWriteError",
|
||||
{
|
||||
target: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to copy ${this.target} to the clipboard.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CopyTextHapticFeedbackError extends Schema.TaggedErrorClass<CopyTextHapticFeedbackError>()(
|
||||
"CopyTextHapticFeedbackError",
|
||||
{
|
||||
target: Schema.String,
|
||||
feedback: Schema.Literals(["light-impact", "selection"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to trigger ${this.feedback} haptic feedback after copying ${this.target}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export function copyTextWithHaptic(
|
||||
value: string,
|
||||
options: {
|
||||
readonly target?: string;
|
||||
readonly feedback?: "light-impact" | "selection";
|
||||
} = {},
|
||||
): void {
|
||||
const target = options.target ?? "text";
|
||||
const feedback = options.feedback ?? "light-impact";
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
await Clipboard.setStringAsync(value);
|
||||
} catch (cause) {
|
||||
console.error(
|
||||
new CopyTextClipboardWriteError({
|
||||
target,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
})();
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
if (feedback === "selection") {
|
||||
await Haptics.selectionAsync();
|
||||
} else {
|
||||
await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
|
||||
}
|
||||
} catch (cause) {
|
||||
console.error(
|
||||
new CopyTextHapticFeedbackError({
|
||||
target,
|
||||
feedback,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
})();
|
||||
export function copyTextWithHaptic(value: string): void {
|
||||
void Clipboard.setStringAsync(value);
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type { EnvironmentId, MessageId } from "@t3tools/contracts";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
@@ -9,27 +8,6 @@ import {
|
||||
} from "./thread-outbox-model";
|
||||
import type { ThreadOutboxStorage } from "./thread-outbox-storage";
|
||||
|
||||
export class ThreadOutboxManagerError extends Schema.TaggedErrorClass<ThreadOutboxManagerError>()(
|
||||
"ThreadOutboxManagerError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"load",
|
||||
"enqueue",
|
||||
"remove",
|
||||
"clear-environment-load",
|
||||
"clear-environment-remove",
|
||||
]),
|
||||
environmentId: Schema.NullOr(EnvironmentId),
|
||||
threadId: Schema.NullOr(ThreadId),
|
||||
messageId: Schema.NullOr(MessageId),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Thread outbox operation ${this.operation} failed for environment ${this.environmentId ?? "unknown"}, thread ${this.threadId ?? "unknown"}, message ${this.messageId ?? "unknown"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ThreadOutboxManagerOptions {
|
||||
readonly registry: AtomRegistry.AtomRegistry;
|
||||
readonly storage: ThreadOutboxStorage;
|
||||
@@ -71,51 +49,22 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
loadPromise = serialize(async () => {
|
||||
const persistedMessages = await options.storage.load();
|
||||
setMessages([...persistedMessages, ...currentMessages()]);
|
||||
}).catch((cause) => {
|
||||
}).catch((error) => {
|
||||
loadPromise = null;
|
||||
warn(
|
||||
"[thread-outbox] failed to load persisted messages",
|
||||
new ThreadOutboxManagerError({
|
||||
operation: "load",
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
warn("[thread-outbox] failed to load persisted messages", error);
|
||||
});
|
||||
return loadPromise;
|
||||
};
|
||||
|
||||
const enqueue = (message: QueuedThreadMessage): Promise<void> =>
|
||||
serialize(async () => {
|
||||
try {
|
||||
await options.storage.write(message);
|
||||
} catch (cause) {
|
||||
throw new ThreadOutboxManagerError({
|
||||
operation: "enqueue",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
await options.storage.write(message);
|
||||
setMessages([...currentMessages(), message]);
|
||||
});
|
||||
|
||||
const remove = (message: QueuedThreadMessage): Promise<void> =>
|
||||
serialize(async () => {
|
||||
try {
|
||||
await options.storage.remove(message);
|
||||
} catch (cause) {
|
||||
throw new ThreadOutboxManagerError({
|
||||
operation: "remove",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
await options.storage.remove(message);
|
||||
setMessages(
|
||||
currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
|
||||
);
|
||||
@@ -123,17 +72,8 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
|
||||
const clearEnvironment = (environmentId: EnvironmentId): Promise<void> =>
|
||||
serialize(async () => {
|
||||
const persisted = await options.storage.load().catch((cause) => {
|
||||
warn(
|
||||
"[thread-outbox] failed to load messages while clearing environment",
|
||||
new ThreadOutboxManagerError({
|
||||
operation: "clear-environment-load",
|
||||
environmentId,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
const persisted = await options.storage.load().catch((error) => {
|
||||
warn("[thread-outbox] failed to load messages while clearing environment", error);
|
||||
return [];
|
||||
});
|
||||
const allMessages = flattenQueuedThreadMessages(
|
||||
@@ -148,17 +88,8 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
try {
|
||||
await options.storage.remove(message);
|
||||
removedMessageIds.add(message.messageId);
|
||||
} catch (cause) {
|
||||
warn(
|
||||
"[thread-outbox] failed to clear persisted message",
|
||||
new ThreadOutboxManagerError({
|
||||
operation: "clear-environment-remove",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
warn("[thread-outbox] failed to clear persisted message", error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
|
||||
import { isEnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc";
|
||||
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
|
||||
import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -110,9 +109,6 @@ function errorMessage(error: unknown): string | null {
|
||||
}
|
||||
|
||||
export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
|
||||
if (isEnvironmentRpcUnavailableError(error)) {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type { MessageId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
decodeQueuedThreadMessage,
|
||||
@@ -9,22 +8,6 @@ import {
|
||||
|
||||
const THREAD_OUTBOX_DIRECTORY = "thread-outbox";
|
||||
|
||||
export class ThreadOutboxStorageError extends Schema.TaggedErrorClass<ThreadOutboxStorageError>()(
|
||||
"ThreadOutboxStorageError",
|
||||
{
|
||||
operation: Schema.Literals(["load", "read-message", "write", "remove"]),
|
||||
environmentId: Schema.NullOr(EnvironmentId),
|
||||
threadId: Schema.NullOr(ThreadId),
|
||||
messageId: Schema.NullOr(MessageId),
|
||||
fileName: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Thread outbox storage operation ${this.operation} failed for environment ${this.environmentId ?? "unknown"}, thread ${this.threadId ?? "unknown"}, message ${this.messageId ?? "unknown"}, file ${this.fileName ?? "unknown"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ThreadOutboxStorage {
|
||||
readonly load: () => Promise<ReadonlyArray<QueuedThreadMessage>>;
|
||||
readonly write: (message: QueuedThreadMessage) => Promise<void>;
|
||||
@@ -49,78 +32,33 @@ async function getMessageFile(messageId: MessageId) {
|
||||
|
||||
export const expoThreadOutboxStorage: ThreadOutboxStorage = {
|
||||
load: async () => {
|
||||
const { File } = await import("expo-file-system");
|
||||
const directory = await getOutboxDirectory();
|
||||
const messages: QueuedThreadMessage[] = [];
|
||||
try {
|
||||
const { File } = await import("expo-file-system");
|
||||
const directory = await getOutboxDirectory();
|
||||
|
||||
for (const entry of directory.list()) {
|
||||
if (!(entry instanceof File) || !entry.name.endsWith(".json")) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
messages.push(decodeQueuedThreadMessage(JSON.parse(await entry.text()) as unknown));
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[thread-outbox] ignored invalid persisted message",
|
||||
new ThreadOutboxStorageError({
|
||||
operation: "read-message",
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
fileName: entry.name,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const entry of directory.list()) {
|
||||
if (!(entry instanceof File) || !entry.name.endsWith(".json")) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
messages.push(decodeQueuedThreadMessage(JSON.parse(await entry.text()) as unknown));
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] ignored invalid persisted message", entry.name, error);
|
||||
}
|
||||
} catch (cause) {
|
||||
throw new ThreadOutboxStorageError({
|
||||
operation: "load",
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
fileName: null,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
return messages;
|
||||
},
|
||||
write: async (message) => {
|
||||
const fileName = messageFileName(message.messageId);
|
||||
try {
|
||||
const file = await getMessageFile(message.messageId);
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(encodeQueuedThreadMessage(message)));
|
||||
} catch (cause) {
|
||||
throw new ThreadOutboxStorageError({
|
||||
operation: "write",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
fileName,
|
||||
cause,
|
||||
});
|
||||
const file = await getMessageFile(message.messageId);
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(encodeQueuedThreadMessage(message)));
|
||||
},
|
||||
remove: async (message) => {
|
||||
const fileName = messageFileName(message.messageId);
|
||||
try {
|
||||
const file = await getMessageFile(message.messageId);
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
} catch (cause) {
|
||||
throw new ThreadOutboxStorageError({
|
||||
operation: "remove",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
fileName,
|
||||
cause,
|
||||
});
|
||||
const file = await getMessageFile(message.messageId);
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -1,5 +1,4 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc";
|
||||
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
@@ -11,7 +10,7 @@ import {
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadMessage,
|
||||
} from "./thread-outbox-model";
|
||||
import { createThreadOutboxManager, ThreadOutboxManagerError } from "./thread-outbox-manager";
|
||||
import { createThreadOutboxManager } from "./thread-outbox-manager";
|
||||
import type { ThreadOutboxStorage } from "./thread-outbox-storage";
|
||||
|
||||
function queuedMessage(input: {
|
||||
@@ -150,48 +149,9 @@ describe("thread outbox", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("reports structured load failures and permits a retry", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const loadCause = new Error("storage unavailable");
|
||||
const warnings: Array<{ message: string; error: unknown }> = [];
|
||||
let loadCalls = 0;
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => {
|
||||
loadCalls += 1;
|
||||
if (loadCalls === 1) throw loadCause;
|
||||
return [];
|
||||
},
|
||||
write: async () => undefined,
|
||||
remove: async () => undefined,
|
||||
},
|
||||
warn: (message, error) => warnings.push({ message, error }),
|
||||
});
|
||||
|
||||
await manager.load();
|
||||
expect(warnings).toEqual([
|
||||
{
|
||||
message: "[thread-outbox] failed to load persisted messages",
|
||||
error: new ThreadOutboxManagerError({
|
||||
operation: "load",
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
cause: loadCause,
|
||||
}),
|
||||
},
|
||||
]);
|
||||
|
||||
await manager.load();
|
||||
expect(loadCalls).toBe(2);
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("keeps atom state aligned with durable writes and removals", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const stored = new Map<MessageId, QueuedThreadMessage>();
|
||||
const removalCause = new Error("remove failed");
|
||||
let failRemoval = true;
|
||||
const storage: ThreadOutboxStorage = {
|
||||
load: async () => [...stored.values()],
|
||||
@@ -200,7 +160,7 @@ describe("thread outbox", () => {
|
||||
},
|
||||
remove: async (message) => {
|
||||
if (failRemoval) {
|
||||
throw removalCause;
|
||||
throw new Error("remove failed");
|
||||
}
|
||||
stored.delete(message.messageId);
|
||||
},
|
||||
@@ -216,15 +176,7 @@ describe("thread outbox", () => {
|
||||
"environment-1:thread-1": [message],
|
||||
});
|
||||
|
||||
await expect(manager.remove(message)).rejects.toEqual(
|
||||
new ThreadOutboxManagerError({
|
||||
operation: "remove",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause: removalCause,
|
||||
}),
|
||||
);
|
||||
await expect(manager.remove(message)).rejects.toThrow("remove failed");
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [message],
|
||||
});
|
||||
@@ -263,15 +215,6 @@ describe("thread outbox", () => {
|
||||
});
|
||||
|
||||
it("retries transport failures but drops deterministic command failures", () => {
|
||||
expect(
|
||||
shouldRetryThreadOutboxDelivery(
|
||||
new EnvironmentRpcUnavailableError({
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
environmentLabel: "Test environment",
|
||||
method: "thread.turn.start",
|
||||
}),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(shouldRetryThreadOutboxDelivery(new Error("Socket is not connected"))).toBe(true);
|
||||
expect(
|
||||
shouldRetryThreadOutboxDelivery({
|
||||
|
||||
+24
-19
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Logger from "effect/Logger";
|
||||
@@ -19,14 +20,6 @@ import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
|
||||
import { fromYaml } from "@t3tools/shared/schemaYaml";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
import {
|
||||
ServerCliBuildAssetMissingError,
|
||||
ServerCliCommandExitError,
|
||||
ServerCliDevelopmentIconSourceMissingError,
|
||||
ServerCliDevelopmentIconTargetMissingError,
|
||||
ServerCliPublishIconSourceMissingError,
|
||||
ServerCliPublishIconTargetMissingError,
|
||||
} from "./cliErrors.ts";
|
||||
|
||||
interface PackageJson {
|
||||
name: string;
|
||||
@@ -54,6 +47,11 @@ const WorkspaceConfig = Schema.Struct({
|
||||
type WorkspaceConfig = typeof WorkspaceConfig.Type;
|
||||
const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
|
||||
|
||||
class CliError extends Data.TaggedError("CliError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const RepoRoot = Effect.service(Path.Path).pipe(
|
||||
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
|
||||
);
|
||||
@@ -66,17 +64,14 @@ const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () {
|
||||
return yield* decodeWorkspaceConfig(workspaceYaml);
|
||||
});
|
||||
|
||||
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.StandardCommand) {
|
||||
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(command);
|
||||
const exitCode = yield* child.exitCode;
|
||||
|
||||
if (exitCode !== 0) {
|
||||
return yield* new ServerCliCommandExitError({
|
||||
command: command.command,
|
||||
args: command.args,
|
||||
cwd: command.options.cwd,
|
||||
exitCode,
|
||||
return yield* new CliError({
|
||||
message: `Command exited with non-zero exit code (${exitCode})`,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -100,10 +95,14 @@ const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(functio
|
||||
const backupPath = `${targetPath}.publish-bak`;
|
||||
|
||||
if (!(yield* fs.exists(sourcePath))) {
|
||||
return yield* new ServerCliPublishIconSourceMissingError({ sourcePath });
|
||||
return yield* new CliError({
|
||||
message: `Missing publish icon source: ${sourcePath}`,
|
||||
});
|
||||
}
|
||||
if (!(yield* fs.exists(targetPath))) {
|
||||
return yield* new ServerCliPublishIconTargetMissingError({ targetPath });
|
||||
return yield* new CliError({
|
||||
message: `Missing publish icon target: ${targetPath}. Run the build subcommand first.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fs.copyFile(targetPath, backupPath);
|
||||
@@ -139,10 +138,14 @@ const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")
|
||||
const targetPath = path.join(serverDir, override.targetRelativePath);
|
||||
|
||||
if (!(yield* fs.exists(sourcePath))) {
|
||||
return yield* new ServerCliDevelopmentIconSourceMissingError({ sourcePath });
|
||||
return yield* new CliError({
|
||||
message: `Missing development icon source: ${sourcePath}`,
|
||||
});
|
||||
}
|
||||
if (!(yield* fs.exists(targetPath))) {
|
||||
return yield* new ServerCliDevelopmentIconTargetMissingError({ targetPath });
|
||||
return yield* new CliError({
|
||||
message: `Missing development icon target: ${targetPath}. Build web first.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fs.copyFile(sourcePath, targetPath);
|
||||
@@ -242,7 +245,9 @@ const publishCmd = Command.make(
|
||||
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
|
||||
const abs = path.join(serverDir, relPath);
|
||||
if (!(yield* fs.exists(abs))) {
|
||||
return yield* new ServerCliBuildAssetMissingError({ assetPath: abs });
|
||||
return yield* new CliError({
|
||||
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import { ServerCliBuildAssetMissingError, ServerCliCommandExitError } from "./cliErrors.ts";
|
||||
|
||||
describe("server CLI errors", () => {
|
||||
it("preserves failed command context without changing its message", () => {
|
||||
const error = new ServerCliCommandExitError({
|
||||
command: "vp",
|
||||
args: ["pm", "publish"],
|
||||
cwd: "/repo",
|
||||
exitCode: 17,
|
||||
});
|
||||
|
||||
assert.equal(error._tag, "ServerCliCommandExitError");
|
||||
assert.equal(error.command, "vp");
|
||||
assert.deepEqual(error.args, ["pm", "publish"]);
|
||||
assert.equal(error.cwd, "/repo");
|
||||
assert.equal(error.exitCode, 17);
|
||||
assert.equal(error.message, "Command exited with non-zero exit code (17)");
|
||||
});
|
||||
|
||||
it("preserves a representative missing asset path", () => {
|
||||
const error = new ServerCliBuildAssetMissingError({ assetPath: "/repo/server.mjs" });
|
||||
|
||||
assert.equal(error.assetPath, "/repo/server.mjs");
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Missing build asset: /repo/server.mjs. Run the build subcommand first.",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,70 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export class ServerCliCommandExitError extends Schema.TaggedErrorClass<ServerCliCommandExitError>()(
|
||||
"ServerCliCommandExitError",
|
||||
{
|
||||
command: Schema.String,
|
||||
args: Schema.Array(Schema.String),
|
||||
cwd: Schema.optional(Schema.String),
|
||||
exitCode: Schema.Int,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Command exited with non-zero exit code (${this.exitCode})`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerCliPublishIconSourceMissingError extends Schema.TaggedErrorClass<ServerCliPublishIconSourceMissingError>()(
|
||||
"ServerCliPublishIconSourceMissingError",
|
||||
{
|
||||
sourcePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Missing publish icon source: ${this.sourcePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerCliPublishIconTargetMissingError extends Schema.TaggedErrorClass<ServerCliPublishIconTargetMissingError>()(
|
||||
"ServerCliPublishIconTargetMissingError",
|
||||
{
|
||||
targetPath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Missing publish icon target: ${this.targetPath}. Run the build subcommand first.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerCliDevelopmentIconSourceMissingError extends Schema.TaggedErrorClass<ServerCliDevelopmentIconSourceMissingError>()(
|
||||
"ServerCliDevelopmentIconSourceMissingError",
|
||||
{
|
||||
sourcePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Missing development icon source: ${this.sourcePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerCliDevelopmentIconTargetMissingError extends Schema.TaggedErrorClass<ServerCliDevelopmentIconTargetMissingError>()(
|
||||
"ServerCliDevelopmentIconTargetMissingError",
|
||||
{
|
||||
targetPath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Missing development icon target: ${this.targetPath}. Build web first.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerCliBuildAssetMissingError extends Schema.TaggedErrorClass<ServerCliBuildAssetMissingError>()(
|
||||
"ServerCliBuildAssetMissingError",
|
||||
{
|
||||
assetPath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Missing build asset: ${this.assetPath}. Run the build subcommand first.`;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
@@ -86,58 +85,7 @@ describe("AssetAccess", () => {
|
||||
},
|
||||
workspaceRoot: root,
|
||||
}).pipe(Effect.flip);
|
||||
expect(error.message).toBe("Workspace file path must be relative to the project root.");
|
||||
expect(error).toMatchObject({
|
||||
_tag: "AssetWorkspacePathValidationError",
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: "thread-1",
|
||||
path: htmlPath,
|
||||
},
|
||||
});
|
||||
expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves non-missing canonical path failures when issuing asset URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-permission-root-",
|
||||
});
|
||||
const htmlPath = path.join(root, "report.html");
|
||||
yield* fileSystem.writeFileString(htmlPath, "<p>report</p>");
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "realPath",
|
||||
pathOrDescriptor: htmlPath,
|
||||
});
|
||||
const failingFileSystem = FileSystem.FileSystem.of({
|
||||
...fileSystem,
|
||||
realPath: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
path: htmlPath,
|
||||
},
|
||||
workspaceRoot: root,
|
||||
}).pipe(Effect.provideService(FileSystem.FileSystem, failingFileSystem), Effect.flip);
|
||||
|
||||
expect(error.message).toBe("Failed to inspect the workspace asset.");
|
||||
expect(error).toMatchObject({
|
||||
_tag: "AssetWorkspaceAssetInspectionError",
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: "thread-1",
|
||||
path: htmlPath,
|
||||
},
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error.message).toContain("relative to the project root");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
@@ -238,38 +186,4 @@ describe("AssetAccess", () => {
|
||||
).toEqual({ kind: "project-favicon-fallback" });
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves structured project favicon resolution causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-error-",
|
||||
});
|
||||
const platformCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "stat",
|
||||
});
|
||||
const resolutionCause = new ProjectFaviconResolver.ProjectFaviconResolutionError({
|
||||
operation: "stat-candidate",
|
||||
workspaceRoot: root,
|
||||
relativePath: "favicon.svg",
|
||||
cause: platformCause,
|
||||
});
|
||||
const resolver = ProjectFaviconResolver.ProjectFaviconResolver.of({
|
||||
resolvePath: () => Effect.fail(resolutionCause),
|
||||
});
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
}).pipe(
|
||||
Effect.provideService(ProjectFaviconResolver.ProjectFaviconResolver, resolver),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error.message).toBe("Failed to resolve project favicon.");
|
||||
expect(error._tag).toBe("AssetProjectFaviconResolutionError");
|
||||
expect(error.cause).toBe(resolutionCause);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
});
|
||||
@@ -1,18 +1,5 @@
|
||||
import type { AssetResource } from "@t3tools/contracts";
|
||||
import {
|
||||
AssetAttachmentNotFoundError,
|
||||
AssetPreviewTypeValidationError,
|
||||
AssetProjectFaviconInspectionError,
|
||||
AssetProjectFaviconNotFoundError,
|
||||
AssetProjectFaviconResolutionError,
|
||||
AssetSigningKeyLoadError,
|
||||
AssetWorkspaceAssetInspectionError,
|
||||
AssetWorkspaceAssetNotFoundError,
|
||||
AssetWorkspaceContextNotFoundError,
|
||||
AssetWorkspacePathValidationError,
|
||||
AssetWorkspaceResolutionError,
|
||||
AssetWorkspaceRootNormalizationError,
|
||||
} from "@t3tools/contracts";
|
||||
import { AssetAccessError } from "@t3tools/contracts";
|
||||
import {
|
||||
isWorkspaceImagePreviewPath,
|
||||
isWorkspacePreviewEntryPath,
|
||||
@@ -24,7 +11,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
@@ -111,59 +97,33 @@ function decodeRelativePath(value: string): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
const optionOnNotFound = <A, R>(
|
||||
effect: Effect.Effect<A, PlatformError.PlatformError, R>,
|
||||
): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
|
||||
effect.pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
const failAccess = (message: string, cause?: unknown) =>
|
||||
new AssetAccessError({ message, ...(cause === undefined ? {} : { cause }) });
|
||||
|
||||
const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
|
||||
function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
|
||||
const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
WorkspacePathOutsideRootError: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
);
|
||||
if (Option.isNone(resolved)) return null;
|
||||
const resolved = yield* workspacePaths
|
||||
.resolveRelativePathWithinRoot(input)
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!resolved) return null;
|
||||
|
||||
const [canonicalRoot, canonicalFile] = yield* Effect.all([
|
||||
optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),
|
||||
optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),
|
||||
fileSystem.realPath(input.workspaceRoot).pipe(Effect.orElseSucceed(() => null)),
|
||||
fileSystem.realPath(resolved.absolutePath).pipe(Effect.orElseSucceed(() => null)),
|
||||
]);
|
||||
if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;
|
||||
if (!canonicalRoot || !canonicalFile) return null;
|
||||
|
||||
const path = yield* Path.Path;
|
||||
const relative = path.relative(canonicalRoot.value, canonicalFile.value);
|
||||
const relative = path.relative(canonicalRoot, canonicalFile);
|
||||
if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
|
||||
|
||||
const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
|
||||
return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
|
||||
const info = yield* fileSystem.stat(canonicalFile).pipe(Effect.orElseSucceed(() => null));
|
||||
return info?.type === "File" ? canonicalFile : null;
|
||||
},
|
||||
);
|
||||
|
||||
const resolveCanonicalWorkspaceFileForRequest = (input: {
|
||||
readonly workspaceRoot: string;
|
||||
readonly relativePath: string;
|
||||
}) =>
|
||||
resolveCanonicalWorkspaceFile(input).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logError("Failed to resolve canonical asset path.", {
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
relativePath: input.relativePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
|
||||
export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
|
||||
readonly resource: AssetResource;
|
||||
readonly workspaceRoot?: string;
|
||||
@@ -178,64 +138,30 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
switch (input.resource._tag) {
|
||||
case "workspace-file": {
|
||||
if (!input.workspaceRoot) {
|
||||
return yield* new AssetWorkspaceContextNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
return yield* failAccess("Workspace context was not found.");
|
||||
}
|
||||
const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetWorkspaceRootNormalizationError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const workspaceRoot = yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(input.workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
|
||||
const relativePath = path.isAbsolute(input.resource.path)
|
||||
? path.relative(workspaceRoot, input.resource.path)
|
||||
: input.resource.path;
|
||||
const resolved = yield* workspacePaths
|
||||
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetWorkspacePathValidationError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
|
||||
if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
|
||||
return yield* new AssetPreviewTypeValidationError({
|
||||
resource: input.resource,
|
||||
});
|
||||
return yield* failAccess("Only browser documents and images can be previewed.");
|
||||
}
|
||||
const canonicalFile = yield* resolveCanonicalWorkspaceFile({
|
||||
workspaceRoot,
|
||||
relativePath: resolved.relativePath,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetWorkspaceAssetInspectionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
if (!canonicalFile) {
|
||||
return yield* new AssetWorkspaceAssetNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
return yield* failAccess("Workspace asset was not found.");
|
||||
}
|
||||
const canonicalWorkspaceRoot = yield* fileSystem.realPath(workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetWorkspaceResolutionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const canonicalWorkspaceRoot = yield* fileSystem
|
||||
.realPath(workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause)));
|
||||
claims = isWorkspaceImagePreviewPath(resolved.relativePath)
|
||||
? {
|
||||
version: 1,
|
||||
@@ -261,9 +187,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
attachmentId: input.resource.attachmentId,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new AssetAttachmentNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
return yield* failAccess("Attachment was not found.");
|
||||
}
|
||||
claims = {
|
||||
version: 1,
|
||||
@@ -275,54 +199,24 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
break;
|
||||
}
|
||||
case "project-favicon": {
|
||||
const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetWorkspaceRootNormalizationError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const workspaceRoot = yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(input.resource.cwd)
|
||||
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
|
||||
const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconResolutionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot);
|
||||
const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
|
||||
if (
|
||||
relativePath &&
|
||||
!(yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconInspectionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
))
|
||||
!(yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }))
|
||||
) {
|
||||
return yield* new AssetProjectFaviconNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
return yield* failAccess("Project favicon was not found.");
|
||||
}
|
||||
claims = {
|
||||
version: 1,
|
||||
kind: "project-favicon",
|
||||
workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetWorkspaceResolutionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
workspaceRoot: yield* fileSystem
|
||||
.realPath(workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause))),
|
||||
relativePath,
|
||||
expiresAt,
|
||||
};
|
||||
@@ -332,15 +226,9 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
}
|
||||
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetSigningKeyLoadError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const signingSecret = yield* secretStore
|
||||
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
|
||||
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
|
||||
const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
|
||||
const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
|
||||
return {
|
||||
@@ -357,10 +245,9 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
if (!encodedPayload || !signature) return null;
|
||||
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
|
||||
Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
const signingSecret = yield* secretStore
|
||||
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!signingSecret) return null;
|
||||
if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
|
||||
|
||||
@@ -375,17 +262,8 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
});
|
||||
if (!attachmentPath) return null;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const info = yield* optionOnNotFound(fileSystem.stat(attachmentPath)).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logError("Failed to inspect attachment asset.", {
|
||||
attachmentId: claims.attachmentId,
|
||||
path: attachmentPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() => Option.none()),
|
||||
);
|
||||
return Option.isSome(info) && info.value.type === "File"
|
||||
const info = yield* fileSystem.stat(attachmentPath).pipe(Effect.orElseSucceed(() => null));
|
||||
return info?.type === "File"
|
||||
? ({ kind: "file", path: attachmentPath } satisfies ResolvedAsset)
|
||||
: null;
|
||||
}
|
||||
@@ -394,7 +272,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
if (claims.relativePath === null) {
|
||||
return { kind: "project-favicon-fallback" } satisfies ResolvedAsset;
|
||||
}
|
||||
const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
|
||||
const faviconPath = yield* resolveCanonicalWorkspaceFile({
|
||||
workspaceRoot: claims.workspaceRoot,
|
||||
relativePath: claims.relativePath,
|
||||
});
|
||||
@@ -406,7 +284,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
const path = yield* Path.Path;
|
||||
if (claims.kind === "workspace-file-exact") {
|
||||
if (decodedPath !== path.basename(claims.relativePath)) return null;
|
||||
const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
|
||||
const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFile({
|
||||
workspaceRoot: claims.workspaceRoot,
|
||||
relativePath: claims.relativePath,
|
||||
});
|
||||
@@ -425,7 +303,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
}
|
||||
const joinedRelativePath =
|
||||
claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
|
||||
const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
|
||||
const workspaceFile = yield* resolveCanonicalWorkspaceFile({
|
||||
workspaceRoot: claims.workspaceRoot,
|
||||
relativePath: joinedRelativePath,
|
||||
});
|
||||
|
||||
@@ -114,16 +114,6 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("ServerAuthScopeNotGrantedError");
|
||||
if (error._tag === "ServerAuthScopeNotGrantedError") {
|
||||
expect(error.requestedScopes).toEqual(["orchestration:read", "access:write"]);
|
||||
expect(error.grantedScopes).toEqual([
|
||||
"orchestration:read",
|
||||
"orchestration:operate",
|
||||
"terminal:operate",
|
||||
"review:write",
|
||||
"relay:read",
|
||||
]);
|
||||
}
|
||||
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
|
||||
);
|
||||
|
||||
@@ -262,20 +252,4 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retains both session ids when rejecting self-revocation", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const issued = yield* serverAuth.issueSession();
|
||||
const error = yield* serverAuth
|
||||
.revokeClientSession(issued.sessionId, issued.sessionId)
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("ServerAuthForbiddenOperationError");
|
||||
if (error._tag === "ServerAuthForbiddenOperationError") {
|
||||
expect(error.currentSessionId).toBe(issued.sessionId);
|
||||
expect(error.targetSessionId).toBe(issued.sessionId);
|
||||
}
|
||||
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
|
||||
);
|
||||
});
|
||||
@@ -85,50 +85,44 @@ export class ServerAuthBootstrapCredentialValidationError extends Schema.TaggedE
|
||||
export class ServerAuthSessionCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthSessionCredentialValidationError>()(
|
||||
"ServerAuthSessionCredentialValidationError",
|
||||
{
|
||||
credentialKind: Schema.Literals(["session", "websocket-ticket"]),
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to validate ${this.credentialKind} credential.`;
|
||||
return "Failed to validate session credential.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthAuthenticatedSessionIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedSessionIssueError>()(
|
||||
"ServerAuthAuthenticatedSessionIssueError",
|
||||
{
|
||||
subject: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to issue authenticated session for ${this.subject}.`;
|
||||
return "Failed to issue authenticated session.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthAuthenticatedAccessTokenIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedAccessTokenIssueError>()(
|
||||
"ServerAuthAuthenticatedAccessTokenIssueError",
|
||||
{
|
||||
subject: Schema.String,
|
||||
scopes: Schema.Array(Schema.String),
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to issue authenticated access token for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
|
||||
return "Failed to issue authenticated access token.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthPairingLinkCreationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkCreationError>()(
|
||||
"ServerAuthPairingLinkCreationError",
|
||||
{
|
||||
subject: Schema.String,
|
||||
scopes: Schema.Array(Schema.String),
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to create pairing link for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
|
||||
return "Failed to create pairing link.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,25 +140,22 @@ export class ServerAuthPairingLinksListError extends Schema.TaggedErrorClass<Ser
|
||||
export class ServerAuthPairingLinkRevocationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkRevocationError>()(
|
||||
"ServerAuthPairingLinkRevocationError",
|
||||
{
|
||||
pairingLinkId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to revoke pairing link ${this.pairingLinkId}.`;
|
||||
return "Failed to revoke pairing link.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthSessionTokenIssueError extends Schema.TaggedErrorClass<ServerAuthSessionTokenIssueError>()(
|
||||
"ServerAuthSessionTokenIssueError",
|
||||
{
|
||||
subject: Schema.String,
|
||||
scopes: Schema.Array(Schema.String),
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to issue session token for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
|
||||
return "Failed to issue session token.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,63 +173,55 @@ export class ServerAuthSessionsListError extends Schema.TaggedErrorClass<ServerA
|
||||
export class ServerAuthSessionRevocationError extends Schema.TaggedErrorClass<ServerAuthSessionRevocationError>()(
|
||||
"ServerAuthSessionRevocationError",
|
||||
{
|
||||
sessionId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to revoke session ${this.sessionId}.`;
|
||||
return "Failed to revoke session.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthOtherSessionsRevocationError extends Schema.TaggedErrorClass<ServerAuthOtherSessionsRevocationError>()(
|
||||
"ServerAuthOtherSessionsRevocationError",
|
||||
{
|
||||
excludedSessionId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to revoke sessions other than ${this.excludedSessionId}.`;
|
||||
return "Failed to revoke other sessions.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthWebSocketTokenIssueError extends Schema.TaggedErrorClass<ServerAuthWebSocketTokenIssueError>()(
|
||||
"ServerAuthWebSocketTokenIssueError",
|
||||
{
|
||||
sessionId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to issue websocket token for session ${this.sessionId}.`;
|
||||
return "Failed to issue websocket token.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthDpopReplayStateRecordError extends Schema.TaggedErrorClass<ServerAuthDpopReplayStateRecordError>()(
|
||||
"ServerAuthDpopReplayStateRecordError",
|
||||
{
|
||||
proofKeyThumbprint: Schema.String,
|
||||
proofId: Schema.String,
|
||||
replayKey: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to record replay state for DPoP proof ${this.proofId} (${this.proofKeyThumbprint}).`;
|
||||
return "Failed to record DPoP proof replay state.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedErrorClass<ServerAuthDpopReplayKeyCalculationError>()(
|
||||
"ServerAuthDpopReplayKeyCalculationError",
|
||||
{
|
||||
proofKeyThumbprint: Schema.String,
|
||||
proofId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to calculate replay key for DPoP proof ${this.proofId} (${this.proofKeyThumbprint}).`;
|
||||
return "Failed to calculate DPoP replay key.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -377,6 +360,11 @@ export const ServerAuthCredentialError = Schema.Union([
|
||||
ServerAuthInvalidCredentialError,
|
||||
]);
|
||||
export type ServerAuthCredentialError = typeof ServerAuthCredentialError.Type;
|
||||
export const isServerAuthCredentialError = Schema.is(ServerAuthCredentialError);
|
||||
export const serverAuthCredentialReason = (
|
||||
error: ServerAuthCredentialError,
|
||||
): "missing_credential" | "invalid_credential" =>
|
||||
error._tag === "ServerAuthMissingCredentialError" ? "missing_credential" : "invalid_credential";
|
||||
|
||||
export class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerAuthInvalidScopeError>()(
|
||||
"ServerAuthInvalidScopeError",
|
||||
@@ -389,13 +377,10 @@ export class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerA
|
||||
|
||||
export class ServerAuthScopeNotGrantedError extends Schema.TaggedErrorClass<ServerAuthScopeNotGrantedError>()(
|
||||
"ServerAuthScopeNotGrantedError",
|
||||
{
|
||||
requestedScopes: Schema.Array(Schema.String),
|
||||
grantedScopes: Schema.Array(Schema.String),
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Requested scopes [${this.requestedScopes.join(", ")}] exceed granted scopes [${this.grantedScopes.join(", ")}].`;
|
||||
return "The requested authentication scope was not granted.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -404,35 +389,28 @@ export const ServerAuthInvalidRequestError = Schema.Union([
|
||||
ServerAuthScopeNotGrantedError,
|
||||
]);
|
||||
export type ServerAuthInvalidRequestError = typeof ServerAuthInvalidRequestError.Type;
|
||||
export const isServerAuthInvalidRequestError = Schema.is(ServerAuthInvalidRequestError);
|
||||
export const serverAuthInvalidRequestReason = (
|
||||
error: ServerAuthInvalidRequestError,
|
||||
): "invalid_scope" | "scope_not_granted" =>
|
||||
error._tag === "ServerAuthInvalidScopeError" ? "invalid_scope" : "scope_not_granted";
|
||||
|
||||
export class ServerAuthForbiddenOperationError extends Schema.TaggedErrorClass<ServerAuthForbiddenOperationError>()(
|
||||
"ServerAuthForbiddenOperationError",
|
||||
{
|
||||
currentSessionId: Schema.String,
|
||||
targetSessionId: Schema.String,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Authentication session ${this.currentSessionId} cannot revoke itself.`;
|
||||
return "The current authentication session cannot revoke itself.";
|
||||
}
|
||||
}
|
||||
|
||||
export type ServerAuthAuthenticationInternalError =
|
||||
| ServerAuthSessionCredentialValidationError
|
||||
| ServerAuthDpopReplayStateRecordError
|
||||
| ServerAuthDpopReplayKeyCalculationError;
|
||||
|
||||
export type ServerAuthAuthenticationError =
|
||||
| ServerAuthCredentialError
|
||||
| ServerAuthAuthenticationInternalError;
|
||||
|
||||
export class EnvironmentAuth extends Context.Service<
|
||||
EnvironmentAuth,
|
||||
{
|
||||
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
|
||||
readonly getSessionState: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthSessionState, ServerAuthAuthenticationInternalError>;
|
||||
) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;
|
||||
readonly createBrowserSession: (
|
||||
credential: string,
|
||||
requestMetadata: AuthClientMetadata,
|
||||
@@ -441,9 +419,7 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly response: AuthBrowserSessionResult;
|
||||
readonly sessionToken: string;
|
||||
},
|
||||
| ServerAuthInvalidCredentialError
|
||||
| ServerAuthBootstrapCredentialValidationError
|
||||
| ServerAuthAuthenticatedSessionIssueError
|
||||
ServerAuthInvalidCredentialError | ServerAuthInternalError
|
||||
>;
|
||||
readonly exchangeBootstrapCredentialForAccessToken: (
|
||||
credential: string,
|
||||
@@ -454,10 +430,7 @@ export class EnvironmentAuth extends Context.Service<
|
||||
},
|
||||
) => Effect.Effect<
|
||||
AuthAccessTokenResult,
|
||||
| ServerAuthInvalidCredentialError
|
||||
| ServerAuthScopeNotGrantedError
|
||||
| ServerAuthBootstrapCredentialValidationError
|
||||
| ServerAuthAuthenticatedAccessTokenIssueError
|
||||
ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError
|
||||
>;
|
||||
readonly createPairingLink: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
@@ -465,61 +438,56 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthPairingLinkCreationError>;
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
|
||||
readonly issuePairingCredential: (
|
||||
input?: AuthCreatePairingCredentialInput,
|
||||
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthPairingLinkCreationError>;
|
||||
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
|
||||
readonly issueStartupPairingCredential: () => Effect.Effect<
|
||||
AuthPairingCredentialResult,
|
||||
ServerAuthPairingLinkCreationError
|
||||
ServerAuthInternalError
|
||||
>;
|
||||
readonly listPairingLinks: (input?: {
|
||||
readonly excludeSubjects?: ReadonlyArray<string>;
|
||||
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthPairingLinksListError>;
|
||||
readonly revokePairingLink: (
|
||||
id: string,
|
||||
) => Effect.Effect<boolean, ServerAuthPairingLinkRevocationError>;
|
||||
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
|
||||
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;
|
||||
readonly issueSession: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly subject?: string;
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly label?: string;
|
||||
}) => Effect.Effect<IssuedBearerSession, ServerAuthSessionTokenIssueError>;
|
||||
}) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
|
||||
readonly listSessions: () => Effect.Effect<
|
||||
ReadonlyArray<AuthClientSession>,
|
||||
ServerAuthSessionsListError
|
||||
ServerAuthInternalError
|
||||
>;
|
||||
readonly revokeSession: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<boolean, ServerAuthSessionRevocationError>;
|
||||
) => Effect.Effect<boolean, ServerAuthInternalError>;
|
||||
readonly revokeOtherSessionsExcept: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, ServerAuthOtherSessionsRevocationError>;
|
||||
) => Effect.Effect<number, ServerAuthInternalError>;
|
||||
readonly listClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthSessionsListError>;
|
||||
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
|
||||
readonly revokeClientSession: (
|
||||
currentSessionId: AuthSessionId,
|
||||
targetSessionId: AuthSessionId,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
ServerAuthForbiddenOperationError | ServerAuthSessionRevocationError
|
||||
>;
|
||||
) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;
|
||||
readonly revokeOtherClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, ServerAuthOtherSessionsRevocationError>;
|
||||
) => Effect.Effect<number, ServerAuthInternalError>;
|
||||
readonly authenticateHttpRequest: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError>;
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
|
||||
readonly authenticateWebSocketUpgrade: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError>;
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
|
||||
readonly issueWebSocketTicket: (
|
||||
session: Pick<AuthenticatedSession, "sessionId">,
|
||||
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthWebSocketTokenIssueError>;
|
||||
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
|
||||
readonly issueStartupPairingUrl: (
|
||||
baseUrl: string,
|
||||
) => Effect.Effect<string, ServerAuthPairingLinkCreationError>;
|
||||
) => Effect.Effect<string, ServerAuthInternalError>;
|
||||
}
|
||||
>()("t3/auth/EnvironmentAuth") {}
|
||||
|
||||
@@ -546,7 +514,7 @@ const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) =>
|
||||
|
||||
export function toBootstrapExchangeError(
|
||||
cause: PairingGrantStore.BootstrapCredentialError,
|
||||
): ServerAuthInvalidCredentialError | ServerAuthBootstrapCredentialValidationError {
|
||||
): ServerAuthInvalidCredentialError | ServerAuthInternalError {
|
||||
if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {
|
||||
return new ServerAuthBootstrapCredentialValidationError({ cause });
|
||||
}
|
||||
@@ -558,17 +526,12 @@ export function toBootstrapExchangeError(
|
||||
|
||||
const mapSessionVerificationErrors = <A, R>(
|
||||
effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
|
||||
credentialKind: ServerAuthSessionCredentialValidationError["credentialKind"],
|
||||
): Effect.Effect<
|
||||
A,
|
||||
ServerAuthInvalidCredentialError | ServerAuthSessionCredentialValidationError,
|
||||
R
|
||||
> =>
|
||||
): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
|
||||
effect.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
SessionStore.isSessionCredentialInvalidError(cause)
|
||||
? new ServerAuthInvalidCredentialError({ cause })
|
||||
: new ServerAuthSessionCredentialValidationError({ credentialKind, cause }),
|
||||
: new ServerAuthSessionCredentialValidationError({ cause }),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -602,7 +565,7 @@ export const make = Effect.gen(function* () {
|
||||
token: string,
|
||||
): Effect.Effect<
|
||||
AuthenticatedSession,
|
||||
ServerAuthInvalidCredentialError | ServerAuthSessionCredentialValidationError
|
||||
ServerAuthInvalidCredentialError | ServerAuthInternalError
|
||||
> =>
|
||||
sessions.verify(token).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
@@ -622,12 +585,12 @@ export const make = Effect.gen(function* () {
|
||||
...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
(effect) => mapSessionVerificationErrors(effect, "session"),
|
||||
mapSessionVerificationErrors,
|
||||
);
|
||||
|
||||
const authenticateRequest = (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
): Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError> => {
|
||||
): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
|
||||
const cookieToken = request.cookies[sessions.cookieName];
|
||||
const bearerToken = parseBearerToken(request);
|
||||
const dpopToken = parseDpopToken(request);
|
||||
@@ -679,18 +642,12 @@ export const make = Effect.gen(function* () {
|
||||
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
|
||||
}) satisfies AuthSessionState,
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthMissingCredentialError: () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
}),
|
||||
Effect.catchIf(isServerAuthCredentialError, () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
),
|
||||
Effect.withSpan("EnvironmentAuth.getSessionState"),
|
||||
);
|
||||
|
||||
@@ -712,13 +669,7 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthAuthenticatedSessionIssueError({
|
||||
subject: grant.subject,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),
|
||||
),
|
||||
),
|
||||
Effect.map(
|
||||
@@ -744,10 +695,7 @@ export const make = Effect.gen(function* () {
|
||||
Effect.gen(function* () {
|
||||
const grantedScopes = requestedScopes ?? grant.scopes;
|
||||
if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {
|
||||
return yield* new ServerAuthScopeNotGrantedError({
|
||||
requestedScopes: grantedScopes,
|
||||
grantedScopes: grant.scopes,
|
||||
});
|
||||
return yield* new ServerAuthScopeNotGrantedError({});
|
||||
}
|
||||
return yield* sessions
|
||||
.issue({
|
||||
@@ -767,12 +715,7 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthAuthenticatedAccessTokenIssueError({
|
||||
subject: grant.subject,
|
||||
scopes: grantedScopes,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
|
||||
),
|
||||
);
|
||||
}),
|
||||
@@ -822,33 +765,28 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
|
||||
"EnvironmentAuth.createPairingLink",
|
||||
)(function* (input) {
|
||||
const scopes = input?.scopes ?? AuthStandardClientScopes;
|
||||
const subject = input?.subject ?? "one-time-token";
|
||||
const createdAt = yield* DateTime.now;
|
||||
const issued = yield* bootstrapCredentials
|
||||
.issueOneTimeToken({
|
||||
scopes,
|
||||
subject,
|
||||
)(
|
||||
function* (input) {
|
||||
const createdAt = yield* DateTime.now;
|
||||
const issued = yield* bootstrapCredentials.issueOneTimeToken({
|
||||
scopes: input?.scopes ?? AuthStandardClientScopes,
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthPairingLinkCreationError({ subject, scopes, cause }),
|
||||
),
|
||||
);
|
||||
return {
|
||||
id: issued.id,
|
||||
credential: issued.credential,
|
||||
scopes,
|
||||
subject,
|
||||
...(issued.label ? { label: issued.label } : {}),
|
||||
createdAt: DateTime.toUtc(createdAt),
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
} satisfies IssuedPairingLink;
|
||||
});
|
||||
});
|
||||
return {
|
||||
id: issued.id,
|
||||
credential: issued.credential,
|
||||
scopes: input?.scopes ?? AuthStandardClientScopes,
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(issued.label ? { label: issued.label } : {}),
|
||||
createdAt: DateTime.toUtc(createdAt),
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
} satisfies IssuedPairingLink;
|
||||
},
|
||||
Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
|
||||
);
|
||||
|
||||
const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
|
||||
bootstrapCredentials.listActive().pipe(
|
||||
@@ -868,20 +806,16 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
|
||||
bootstrapCredentials.revoke(id).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthPairingLinkRevocationError({ pairingLinkId: id, cause }),
|
||||
),
|
||||
Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.revokePairingLink"),
|
||||
);
|
||||
|
||||
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) => {
|
||||
const subject = input?.subject ?? DEFAULT_SESSION_SUBJECT;
|
||||
const scopes = input?.scopes ?? AuthAdministrativeScopes;
|
||||
return sessions
|
||||
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
|
||||
sessions
|
||||
.issue({
|
||||
subject,
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
method: "bearer-access-token",
|
||||
scopes,
|
||||
scopes: input?.scopes ?? AuthAdministrativeScopes,
|
||||
client: {
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
deviceType: "bot",
|
||||
@@ -896,17 +830,14 @@ export const make = Effect.gen(function* () {
|
||||
token: issued.token,
|
||||
method: "bearer-access-token",
|
||||
scopes: issued.scopes,
|
||||
subject,
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
client: issued.client,
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
}) satisfies IssuedBearerSession,
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthSessionTokenIssueError({ subject, scopes, cause }),
|
||||
),
|
||||
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.issueSession"),
|
||||
);
|
||||
};
|
||||
|
||||
const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
|
||||
sessions.listActive().pipe(
|
||||
@@ -917,7 +848,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
|
||||
sessions.revoke(sessionId).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ sessionId, cause })),
|
||||
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.revokeSession"),
|
||||
);
|
||||
|
||||
@@ -925,10 +856,7 @@ export const make = Effect.gen(function* () {
|
||||
sessionId,
|
||||
) =>
|
||||
sessions.revokeAllExcept(sessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthOtherSessionsRevocationError({ excludedSessionId: sessionId, cause }),
|
||||
),
|
||||
Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
|
||||
);
|
||||
|
||||
@@ -963,10 +891,7 @@ export const make = Effect.gen(function* () {
|
||||
"EnvironmentAuth.revokeClientSession",
|
||||
)(function* (currentSessionId, targetSessionId) {
|
||||
if (currentSessionId === targetSessionId) {
|
||||
return yield* new ServerAuthForbiddenOperationError({
|
||||
currentSessionId,
|
||||
targetSessionId,
|
||||
});
|
||||
return yield* new ServerAuthForbiddenOperationError({});
|
||||
}
|
||||
return yield* revokeSession(targetSessionId);
|
||||
});
|
||||
@@ -992,9 +917,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
|
||||
sessions.issueWebSocketToken(session.sessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthWebSocketTokenIssueError({ sessionId: session.sessionId, cause }),
|
||||
),
|
||||
Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
({
|
||||
@@ -1024,7 +947,7 @@ export const make = Effect.gen(function* () {
|
||||
scopes: session.scopes,
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
(effect) => mapSessionVerificationErrors(effect, "websocket-ticket"),
|
||||
mapSessionVerificationErrors,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,31 +45,6 @@ const makePermissionDeniedSecretStoreLayer = () =>
|
||||
Layer.provideMerge(PermissionDeniedFileSystemLayer),
|
||||
);
|
||||
|
||||
const DirectoryCreateFailureFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return {
|
||||
...fileSystem,
|
||||
makeDirectory: (path) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: String(path),
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeDirectoryCreateFailureSecretStoreLayer = (config: ServerConfig.ServerConfig["Service"]) =>
|
||||
ServerSecretStore.layer.pipe(
|
||||
Layer.provide(Layer.succeed(ServerConfig.ServerConfig, config)),
|
||||
Layer.provideMerge(DirectoryCreateFailureFileSystemLayer),
|
||||
);
|
||||
|
||||
const RenameFailureFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
@@ -170,56 +145,7 @@ const makeConcurrentCreateSecretStoreLayer = () =>
|
||||
Layer.provideMerge(ConcurrentReadMissFileSystemLayer),
|
||||
);
|
||||
|
||||
const ConcurrentCreationWithoutReadableSecretFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
readFile: (path) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "readFile",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
),
|
||||
open: (path) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "AlreadyExists",
|
||||
module: "FileSystem",
|
||||
method: "open",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeConcurrentCreationWithoutReadableSecretStoreLayer = () =>
|
||||
ServerSecretStore.layer.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(ConcurrentCreationWithoutReadableSecretFileSystemLayer),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
it.effect("preserves directory context when secret-store initialization fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig.pipe(Effect.provide(makeServerConfigLayer()));
|
||||
const error = yield* Layer.build(makeDirectoryCreateFailureSecretStoreLayer(config)).pipe(
|
||||
Effect.scoped,
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreDirectoryCreateError);
|
||||
assert.match(error.directoryPath, /secrets$/u);
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns Option.none when a secret file does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
@@ -260,25 +186,6 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
}).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("preserves the persist failure when a concurrent secret remains unreadable", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
|
||||
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreConcurrentReadError);
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to read secret session-signing-key after concurrent creation.",
|
||||
);
|
||||
assert.instanceOf(error.cause, ServerSecretStore.SecretStorePersistError);
|
||||
assert.equal(error.cause.operation, "create");
|
||||
assert.instanceOf(error.cause.cause, PlatformError.PlatformError);
|
||||
assert.equal(error.cause.cause.reason._tag, "AlreadyExists");
|
||||
}).pipe(Effect.provide(makeConcurrentCreationWithoutReadableSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("uses restrictive permissions for the secret directory and files", () =>
|
||||
Effect.gen(function* () {
|
||||
const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = [];
|
||||
@@ -325,8 +232,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreReadError);
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.match(error.secretPath, /session-signing-key\.bin$/u);
|
||||
assert.include(error.message, "Failed to read secret session-signing-key.");
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
|
||||
}).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
|
||||
@@ -341,9 +247,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStorePersistError);
|
||||
assert.equal(error.operation, "set");
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.match(error.secretPath, /session-signing-key\.bin$/u);
|
||||
assert.include(error.message, "Failed to persist secret session-signing-key.");
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
|
||||
}).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
|
||||
@@ -356,8 +260,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreRemoveError);
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.match(error.secretPath, /session-signing-key\.bin$/u);
|
||||
assert.include(error.message, "Failed to remove secret session-signing-key.");
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
|
||||
}).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
|
||||
|
||||
@@ -11,137 +11,114 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
|
||||
const storedSecretErrorContext = {
|
||||
secretName: Schema.String,
|
||||
secretPath: Schema.String,
|
||||
const secretStoreErrorContext = {
|
||||
resource: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class SecretStoreDirectoryCreateError extends Schema.TaggedErrorClass<SecretStoreDirectoryCreateError>()(
|
||||
"SecretStoreDirectoryCreateError",
|
||||
export class SecretStoreSecureError extends Schema.TaggedErrorClass<SecretStoreSecureError>()(
|
||||
"SecretStoreSecureError",
|
||||
{
|
||||
directoryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to create secret store directory ${this.directoryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreDirectorySecureError extends Schema.TaggedErrorClass<SecretStoreDirectorySecureError>()(
|
||||
"SecretStoreDirectorySecureError",
|
||||
{
|
||||
directoryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to secure secret store directory ${this.directoryPath}.`;
|
||||
return `Failed to secure ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreReadError extends Schema.TaggedErrorClass<SecretStoreReadError>()(
|
||||
"SecretStoreReadError",
|
||||
{
|
||||
...storedSecretErrorContext,
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read secret ${this.secretName} at ${this.secretPath}.`;
|
||||
return `Failed to read ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreTemporaryPathGenerationError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathGenerationError>()(
|
||||
"SecretStoreTemporaryPathGenerationError",
|
||||
export class SecretStoreTemporaryPathError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathError>()(
|
||||
"SecretStoreTemporaryPathError",
|
||||
{
|
||||
secretName: Schema.String,
|
||||
secretPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to generate a temporary path for secret ${this.secretName} at ${this.secretPath}.`;
|
||||
return `Failed to create temporary path for ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStorePersistError extends Schema.TaggedErrorClass<SecretStorePersistError>()(
|
||||
"SecretStorePersistError",
|
||||
{
|
||||
operation: Schema.Literals(["create", "set"]),
|
||||
...storedSecretErrorContext,
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to ${this.operation} secret ${this.secretName} at ${this.secretPath}.`;
|
||||
return `Failed to persist ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreRandomGenerationError extends Schema.TaggedErrorClass<SecretStoreRandomGenerationError>()(
|
||||
"SecretStoreRandomGenerationError",
|
||||
{
|
||||
secretName: Schema.String,
|
||||
byteCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to generate ${this.byteCount} random bytes for secret ${this.secretName}.`;
|
||||
return `Failed to generate random bytes for ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreConcurrentReadError extends Schema.TaggedErrorClass<SecretStoreConcurrentReadError>()(
|
||||
"SecretStoreConcurrentReadError",
|
||||
{
|
||||
secretName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
resource: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read secret ${this.secretName} after concurrent creation.`;
|
||||
return `Failed to read ${this.resource} after concurrent creation.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreRemoveError extends Schema.TaggedErrorClass<SecretStoreRemoveError>()(
|
||||
"SecretStoreRemoveError",
|
||||
{
|
||||
...storedSecretErrorContext,
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to remove secret ${this.secretName} at ${this.secretPath}.`;
|
||||
return `Failed to remove ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreDecodeError extends Schema.TaggedErrorClass<SecretStoreDecodeError>()(
|
||||
"SecretStoreDecodeError",
|
||||
{
|
||||
secretName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode secret ${this.secretName}.`;
|
||||
return `Failed to decode ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreEncodeError extends Schema.TaggedErrorClass<SecretStoreEncodeError>()(
|
||||
"SecretStoreEncodeError",
|
||||
{
|
||||
secretName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
...secretStoreErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode secret ${this.secretName}.`;
|
||||
return `Failed to encode ${this.resource}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const SecretStoreError = Schema.Union([
|
||||
SecretStoreDirectoryCreateError,
|
||||
SecretStoreDirectorySecureError,
|
||||
SecretStoreSecureError,
|
||||
SecretStoreReadError,
|
||||
SecretStoreTemporaryPathGenerationError,
|
||||
SecretStoreTemporaryPathError,
|
||||
SecretStorePersistError,
|
||||
SecretStoreRandomGenerationError,
|
||||
SecretStoreConcurrentReadError,
|
||||
@@ -161,26 +138,14 @@ export const isSecretAlreadyExistsError = (error: SecretStoreError): boolean =>
|
||||
export class ServerSecretStore extends Context.Service<
|
||||
ServerSecretStore,
|
||||
{
|
||||
readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreReadError>;
|
||||
readonly set: (
|
||||
name: string,
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<void, SecretStoreTemporaryPathGenerationError | SecretStorePersistError>;
|
||||
readonly create: (
|
||||
name: string,
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<void, SecretStorePersistError>;
|
||||
readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreError>;
|
||||
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
|
||||
readonly create: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
|
||||
readonly getOrCreateRandom: (
|
||||
name: string,
|
||||
bytes: number,
|
||||
) => Effect.Effect<
|
||||
Uint8Array,
|
||||
| SecretStoreReadError
|
||||
| SecretStoreRandomGenerationError
|
||||
| SecretStorePersistError
|
||||
| SecretStoreConcurrentReadError
|
||||
>;
|
||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreRemoveError>;
|
||||
) => Effect.Effect<Uint8Array, SecretStoreError>;
|
||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
|
||||
}
|
||||
>()("t3/auth/ServerSecretStore") {}
|
||||
|
||||
@@ -190,20 +155,12 @@ export const make = Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
|
||||
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreDirectoryCreateError({
|
||||
directoryPath: serverConfig.secretsDir,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
|
||||
yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreDirectorySecureError({
|
||||
directoryPath: serverConfig.secretsDir,
|
||||
new SecretStoreSecureError({
|
||||
resource: `secrets directory ${serverConfig.secretsDir}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -211,33 +168,29 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
|
||||
|
||||
const get: ServerSecretStore["Service"]["get"] = (name) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return fileSystem.readFile(secretPath).pipe(
|
||||
const get: ServerSecretStore["Service"]["get"] = (name) =>
|
||||
fileSystem.readFile(resolveSecretPath(name)).pipe(
|
||||
Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(Option.none())
|
||||
: Effect.fail(
|
||||
new SecretStoreReadError({
|
||||
secretName: name,
|
||||
secretPath,
|
||||
resource: `secret ${name}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.withSpan("ServerSecretStore.get"),
|
||||
);
|
||||
};
|
||||
|
||||
const set: ServerSecretStore["Service"]["set"] = (name, value) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreTemporaryPathGenerationError({
|
||||
secretName: name,
|
||||
secretPath,
|
||||
new SecretStoreTemporaryPathError({
|
||||
resource: `secret ${name}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -255,9 +208,7 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap(() =>
|
||||
Effect.fail(
|
||||
new SecretStorePersistError({
|
||||
operation: "set",
|
||||
secretName: name,
|
||||
secretPath,
|
||||
resource: `secret ${name}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -286,9 +237,7 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStorePersistError({
|
||||
operation: "create",
|
||||
secretName: name,
|
||||
secretPath,
|
||||
resource: `secret ${name}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -305,33 +254,30 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreRandomGenerationError({
|
||||
secretName: name,
|
||||
byteCount: bytes,
|
||||
resource: `secret ${name}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((generated) =>
|
||||
create(name, generated).pipe(
|
||||
Effect.as(Uint8Array.from(generated)),
|
||||
Effect.catchTags({
|
||||
SecretStorePersistError: (error) =>
|
||||
isSecretAlreadyExistsError(error)
|
||||
? get(name).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new SecretStoreConcurrentReadError({
|
||||
secretName: name,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
Effect.catchIf(isSecretStoreError, (error) =>
|
||||
isSecretAlreadyExistsError(error)
|
||||
? get(name).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new SecretStoreConcurrentReadError({
|
||||
resource: `secret ${name}`,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -340,23 +286,20 @@ export const make = Effect.gen(function* () {
|
||||
Effect.withSpan("ServerSecretStore.getOrCreateRandom"),
|
||||
);
|
||||
|
||||
const remove: ServerSecretStore["Service"]["remove"] = (name) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return fileSystem.remove(secretPath).pipe(
|
||||
const remove: ServerSecretStore["Service"]["remove"] = (name) =>
|
||||
fileSystem.remove(resolveSecretPath(name)).pipe(
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new SecretStoreRemoveError({
|
||||
secretName: name,
|
||||
secretPath,
|
||||
resource: `secret ${name}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.withSpan("ServerSecretStore.remove"),
|
||||
);
|
||||
};
|
||||
|
||||
return ServerSecretStore.of({
|
||||
get,
|
||||
|
||||
@@ -6,9 +6,7 @@ import { mapDpopReplayStoreError } from "./dpop.ts";
|
||||
|
||||
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
|
||||
new SecretStorePersistError({
|
||||
operation: "create",
|
||||
secretName: "DPoP proof",
|
||||
secretPath: "dpop-proof.bin",
|
||||
resource: "DPoP proof",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: tag,
|
||||
module: "FileSystem",
|
||||
@@ -17,16 +15,10 @@ const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
|
||||
}),
|
||||
});
|
||||
|
||||
const replayContext = {
|
||||
proofKeyThumbprint: "proof-key-thumbprint",
|
||||
proofId: "proof-id",
|
||||
replayKey: "replay-key",
|
||||
};
|
||||
|
||||
describe("mapDpopReplayStoreError", () => {
|
||||
it("reports replay conflicts as invalid credentials", () => {
|
||||
const cause = storeFailure("AlreadyExists");
|
||||
const error = mapDpopReplayStoreError(cause, replayContext);
|
||||
const error = mapDpopReplayStoreError(cause);
|
||||
|
||||
expect(error._tag).toBe("ServerAuthInvalidCredentialError");
|
||||
if (error._tag === "ServerAuthInvalidCredentialError") {
|
||||
@@ -35,18 +27,11 @@ describe("mapDpopReplayStoreError", () => {
|
||||
});
|
||||
|
||||
it("reports replay-store availability failures as internal errors", () => {
|
||||
const cause = storeFailure("PermissionDenied");
|
||||
const error = mapDpopReplayStoreError(cause, replayContext);
|
||||
const error = mapDpopReplayStoreError(storeFailure("PermissionDenied"));
|
||||
|
||||
expect(error._tag).toBe("ServerAuthDpopReplayStateRecordError");
|
||||
if (error._tag === "ServerAuthDpopReplayStateRecordError") {
|
||||
expect(error.message).toBe(
|
||||
"Failed to record replay state for DPoP proof proof-id (proof-key-thumbprint).",
|
||||
);
|
||||
expect(error.proofKeyThumbprint).toBe(replayContext.proofKeyThumbprint);
|
||||
expect(error.proofId).toBe(replayContext.proofId);
|
||||
expect(error.replayKey).toBe(replayContext.replayKey);
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error.message).toBe("Failed to record DPoP proof replay state.");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
ServerAuthDpopReplayKeyCalculationError,
|
||||
ServerAuthDpopReplayStateRecordError,
|
||||
ServerAuthInvalidCredentialError,
|
||||
type ServerAuthInternalError,
|
||||
} from "./EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
@@ -30,19 +31,13 @@ export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest)
|
||||
|
||||
export const mapDpopReplayStoreError = (
|
||||
error: ServerSecretStore.SecretStoreError,
|
||||
context: {
|
||||
readonly proofKeyThumbprint: string;
|
||||
readonly proofId: string;
|
||||
readonly replayKey: string;
|
||||
},
|
||||
): ServerAuthInvalidCredentialError | ServerAuthDpopReplayStateRecordError =>
|
||||
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? new ServerAuthInvalidCredentialError({
|
||||
diagnostic: "DPoP proof replayed.",
|
||||
cause: error,
|
||||
})
|
||||
: new ServerAuthDpopReplayStateRecordError({
|
||||
...context,
|
||||
cause: error,
|
||||
});
|
||||
|
||||
@@ -76,8 +71,6 @@ export const verifyRequestDpopProof = (input: {
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthDpopReplayKeyCalculationError({
|
||||
proofKeyThumbprint: result.thumbprint,
|
||||
proofId: result.jti,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -95,12 +88,8 @@ export const verifyRequestDpopProof = (input: {
|
||||
),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapDpopReplayStoreError(error, {
|
||||
proofKeyThumbprint: result.thumbprint,
|
||||
proofId: result.jti,
|
||||
replayKey,
|
||||
}),
|
||||
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
|
||||
Effect.fail(mapDpopReplayStoreError(error)),
|
||||
),
|
||||
);
|
||||
return result.thumbprint;
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentInternalError } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import * as AuthHttp from "./http.ts";
|
||||
|
||||
const encodeEnvironmentInternalError = Schema.encodeUnknownSync(EnvironmentInternalError);
|
||||
|
||||
const loggerLayer = (messages: Array<unknown>) =>
|
||||
Logger.layer(
|
||||
[
|
||||
Logger.make(({ message }) => {
|
||||
messages.push(message);
|
||||
}),
|
||||
],
|
||||
{ mergeWithExisting: false },
|
||||
);
|
||||
|
||||
describe("auth http diagnostics", () => {
|
||||
it.effect("logs and encodes bounded internal diagnostics without exposing secrets", () => {
|
||||
const messages: Array<unknown> = [];
|
||||
const cause = new Error("credential=secret-value");
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
AuthHttp.failEnvironmentInternal("browser_session_cookie_failed", cause),
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(AuthHttp.EnvironmentHttpInternalError);
|
||||
expect(error.failureTag).toBe("Error");
|
||||
expect(error.message).toBe(
|
||||
"Environment API operation failed (browser_session_cookie_failed).",
|
||||
);
|
||||
expect(encodeEnvironmentInternalError(error)).toEqual({
|
||||
_tag: "EnvironmentInternalError",
|
||||
code: "internal_error",
|
||||
reason: "browser_session_cookie_failed",
|
||||
traceId: error.traceId,
|
||||
});
|
||||
|
||||
expect(messages).toEqual([
|
||||
[
|
||||
"environment api operation failed",
|
||||
{
|
||||
reason: "browser_session_cookie_failed",
|
||||
traceId: error.traceId,
|
||||
failureTag: "Error",
|
||||
reasonCount: 1,
|
||||
failureCount: 1,
|
||||
defectCount: 0,
|
||||
interruptionCount: 0,
|
||||
},
|
||||
],
|
||||
]);
|
||||
}).pipe(Effect.provide(loggerLayer(messages)));
|
||||
});
|
||||
|
||||
it.effect("logs request failures without serializing their Error or Cause values", () => {
|
||||
const messages: Array<unknown> = [];
|
||||
const request = HttpServerRequest.fromWeb(
|
||||
new Request("https://environment.example.test/api/auth/session"),
|
||||
);
|
||||
const requestCause = Cause.combine(
|
||||
Cause.fail(new Error("credential=secret-value")),
|
||||
Cause.die(new Error("stderr=private-value")),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const exit = yield* Effect.exit(
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* AuthHttp.annotateEnvironmentRequest("auth.session");
|
||||
return yield* Effect.failCause(requestCause);
|
||||
}),
|
||||
).pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request)),
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
expect(messages).toEqual([
|
||||
[
|
||||
"environment api request failed",
|
||||
{
|
||||
endpoint: "auth.session",
|
||||
traceId: "unavailable",
|
||||
failureTag: "Error",
|
||||
reasonCount: 2,
|
||||
failureCount: 1,
|
||||
defectCount: 1,
|
||||
interruptionCount: 0,
|
||||
},
|
||||
],
|
||||
]);
|
||||
}).pipe(Effect.provide(loggerLayer(messages)));
|
||||
});
|
||||
|
||||
it.effect("re-propagates nested interruption causes without logging a synthetic 500", () => {
|
||||
const messages: Array<unknown> = [];
|
||||
const interruption = Cause.interrupt();
|
||||
const cause = new Error("cancelled", { cause: interruption });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const exit = yield* Effect.exit(AuthHttp.failEnvironmentInternal("internal_error", cause));
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
|
||||
expect(Option.isNone(Cause.findErrorOption(exit.cause))).toBe(true);
|
||||
}
|
||||
expect(messages).toEqual([]);
|
||||
}).pipe(Effect.provide(loggerLayer(messages)));
|
||||
});
|
||||
});
|
||||
+74
-183
@@ -23,12 +23,10 @@ import {
|
||||
import type { AuthEnvironmentScope } from "@t3tools/contracts";
|
||||
import { parseAllowedOAuthScope } from "@t3tools/shared/oauthScope";
|
||||
import { causeErrorTag } from "@t3tools/shared/observability";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { identity } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Cookies from "effect/unstable/http/Cookies";
|
||||
import * as HttpEffect from "effect/unstable/http/HttpEffect";
|
||||
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
@@ -45,72 +43,6 @@ const CREDENTIAL_RESPONSE_HEADERS = {
|
||||
pragma: "no-cache",
|
||||
} as const;
|
||||
|
||||
const MAX_FAILURE_TAG_LENGTH = 128;
|
||||
const MAX_CAUSE_CHAIN_DEPTH = 32;
|
||||
|
||||
const EnvironmentFailureTag = Schema.String.check(
|
||||
Schema.isMinLength(1),
|
||||
Schema.isMaxLength(MAX_FAILURE_TAG_LENGTH),
|
||||
);
|
||||
|
||||
function failureLogAttributes(input: unknown) {
|
||||
const cause = Cause.isCause(input) ? input : Cause.fail(input);
|
||||
let failureCount = 0;
|
||||
let defectCount = 0;
|
||||
let interruptionCount = 0;
|
||||
for (const reason of cause.reasons) {
|
||||
switch (reason._tag) {
|
||||
case "Fail":
|
||||
failureCount += 1;
|
||||
break;
|
||||
case "Die":
|
||||
defectCount += 1;
|
||||
break;
|
||||
case "Interrupt":
|
||||
interruptionCount += 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const unboundedFailureTag = causeErrorTag(cause).trim() || "Unknown";
|
||||
return {
|
||||
failureTag: unboundedFailureTag.slice(0, MAX_FAILURE_TAG_LENGTH),
|
||||
reasonCount: cause.reasons.length,
|
||||
failureCount,
|
||||
defectCount,
|
||||
interruptionCount,
|
||||
};
|
||||
}
|
||||
|
||||
function findInterruptCause(input: unknown): Cause.Cause<never> | undefined {
|
||||
const seen = new Set<object>();
|
||||
let current = input;
|
||||
for (let depth = 0; depth < MAX_CAUSE_CHAIN_DEPTH; depth += 1) {
|
||||
if (Cause.isCause(current)) {
|
||||
return Cause.hasInterruptsOnly(current) ? (current as Cause.Cause<never>) : undefined;
|
||||
}
|
||||
if (typeof current !== "object" || current === null || seen.has(current)) {
|
||||
return undefined;
|
||||
}
|
||||
seen.add(current);
|
||||
if (!("cause" in current)) {
|
||||
return undefined;
|
||||
}
|
||||
current = current.cause;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export class EnvironmentHttpInternalError extends EnvironmentInternalError.extend<EnvironmentHttpInternalError>(
|
||||
"EnvironmentHttpInternalError",
|
||||
)({
|
||||
failureTag: EnvironmentFailureTag,
|
||||
cause: Schema.Defect(),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `Environment API operation failed (${this.reason}).`;
|
||||
}
|
||||
}
|
||||
|
||||
const appendCredentialResponseHeaders = HttpEffect.appendPreResponseHandler((_request, response) =>
|
||||
Effect.succeed(HttpServerResponse.setHeaders(response, CREDENTIAL_RESPONSE_HEADERS)),
|
||||
);
|
||||
@@ -143,11 +75,12 @@ export function annotateEnvironmentRequest(endpoint: string) {
|
||||
const traceId = yield* currentEnvironmentTraceId;
|
||||
|
||||
yield* Effect.addFinalizer((exit) =>
|
||||
exit._tag === "Failure" && !Cause.hasInterruptsOnly(exit.cause)
|
||||
exit._tag === "Failure"
|
||||
? Effect.logWarning("environment api request failed", {
|
||||
endpoint,
|
||||
traceId,
|
||||
...failureLogAttributes(exit.cause),
|
||||
errorTag: causeErrorTag(exit.cause),
|
||||
cause: exit.cause,
|
||||
})
|
||||
: Effect.void,
|
||||
);
|
||||
@@ -204,44 +137,19 @@ function failEnvironmentOperationForbidden(reason: "current_session_revoke_not_a
|
||||
);
|
||||
}
|
||||
|
||||
export const failEnvironmentInternal = Effect.fn("environment.auth.failEnvironmentInternal")(
|
||||
function* (reason: EnvironmentInternalErrorReason, cause: unknown) {
|
||||
const interruptCause = findInterruptCause(cause);
|
||||
if (interruptCause !== undefined) {
|
||||
return yield* Effect.failCause(interruptCause);
|
||||
}
|
||||
export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {
|
||||
return Effect.gen(function* () {
|
||||
const traceId = yield* currentEnvironmentTraceId;
|
||||
const diagnostics = failureLogAttributes(cause);
|
||||
yield* Effect.logError("environment api operation failed", {
|
||||
reason,
|
||||
traceId,
|
||||
...diagnostics,
|
||||
});
|
||||
return yield* new EnvironmentHttpInternalError({
|
||||
code: "internal_error",
|
||||
reason,
|
||||
traceId,
|
||||
failureTag: diagnostics.failureTag,
|
||||
cause,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const failAuthenticationInternal = (error: EnvironmentAuth.ServerAuthAuthenticationInternalError) =>
|
||||
failEnvironmentInternal("internal_error", error);
|
||||
|
||||
export const catchEnvironmentAuthenticationErrors = <A, R>(
|
||||
effect: Effect.Effect<A, EnvironmentAuth.ServerAuthAuthenticationError, R>,
|
||||
) =>
|
||||
effect.pipe(
|
||||
Effect.catchTags({
|
||||
ServerAuthMissingCredentialError: () => failEnvironmentAuthInvalid("missing_credential"),
|
||||
ServerAuthInvalidCredentialError: () => failEnvironmentAuthInvalid("invalid_credential"),
|
||||
ServerAuthSessionCredentialValidationError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayStateRecordError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayKeyCalculationError: failAuthenticationInternal,
|
||||
}),
|
||||
);
|
||||
if (error !== undefined) {
|
||||
yield* Effect.logError("environment api operation failed", {
|
||||
reason,
|
||||
traceId,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId });
|
||||
});
|
||||
}
|
||||
|
||||
export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* (
|
||||
scope: AuthEnvironmentScope,
|
||||
@@ -260,8 +168,13 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
|
||||
return (httpEffect) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const session = yield* catchEnvironmentAuthenticationErrors(
|
||||
serverAuth.authenticateHttpRequest(request),
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
||||
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("internal_error", error),
|
||||
),
|
||||
);
|
||||
return yield* httpEffect.pipe(
|
||||
Effect.provideService(EnvironmentAuthenticatedPrincipal, {
|
||||
@@ -270,11 +183,7 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
|
||||
}),
|
||||
session.subject === "cloud-connect" ? traceAuthenticatedRelayRequest : identity,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
EnvironmentAuthInvalidError: appendDpopChallengeOnUnauthorized,
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.catchTag("EnvironmentAuthInvalidError", appendDpopChallengeOnUnauthorized));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -294,11 +203,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
return yield* serverAuth.getSessionState(request);
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthSessionCredentialValidationError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayStateRecordError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayKeyCalculationError: failAuthenticationInternal,
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("internal_error", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -318,12 +225,7 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
path: "/",
|
||||
sameSite: "lax",
|
||||
}),
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
CookieError: (cause) =>
|
||||
failEnvironmentInternal("browser_session_cookie_failed", cause),
|
||||
}),
|
||||
);
|
||||
).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")));
|
||||
|
||||
yield* HttpEffect.appendPreResponseHandler((_request, response) =>
|
||||
Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)),
|
||||
@@ -331,14 +233,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
yield* appendCredentialResponseHeaders;
|
||||
return result.response;
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
failEnvironmentAuthInvalid("invalid_credential"),
|
||||
ServerAuthBootstrapCredentialValidationError: (error) =>
|
||||
failEnvironmentInternal("browser_session_issuance_failed", error),
|
||||
ServerAuthAuthenticatedSessionIssueError: (error) =>
|
||||
failEnvironmentInternal("browser_session_issuance_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
||||
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("browser_session_issuance_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -368,16 +268,14 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
}
|
||||
const proofKeyThumbprint = args.headers.dpop
|
||||
? yield* verifyRequestDpopProof({ request }).pipe(
|
||||
Effect.catchTags({
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
appendDpopChallengeHeader.pipe(
|
||||
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
|
||||
),
|
||||
ServerAuthDpopReplayStateRecordError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
ServerAuthDpopReplayKeyCalculationError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, () =>
|
||||
appendDpopChallengeHeader.pipe(
|
||||
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
|
||||
),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
),
|
||||
)
|
||||
: undefined;
|
||||
yield* appendCredentialResponseHeaders;
|
||||
@@ -398,16 +296,15 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
);
|
||||
},
|
||||
traceRelayRequest,
|
||||
Effect.catchTags({
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
failEnvironmentAuthInvalid("invalid_credential"),
|
||||
ServerAuthScopeNotGrantedError: () =>
|
||||
failEnvironmentInvalidRequest("scope_not_granted"),
|
||||
ServerAuthBootstrapCredentialValidationError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
ServerAuthAuthenticatedAccessTokenIssueError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
||||
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>
|
||||
failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -419,10 +316,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
yield* appendCredentialResponseHeaders;
|
||||
return yield* serverAuth.issueWebSocketTicket(session);
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthWebSocketTokenIssueError: (error) =>
|
||||
failEnvironmentInternal("websocket_ticket_issuance_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("websocket_ticket_issuance_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -445,10 +341,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
}
|
||||
return yield* serverAuth.issuePairingCredential(args.payload);
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthPairingLinkCreationError: (error) =>
|
||||
failEnvironmentInternal("pairing_credential_issuance_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("pairing_credential_issuance_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -459,10 +354,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
yield* requireEnvironmentScope(AuthAccessReadScope);
|
||||
return yield* serverAuth.listPairingLinks();
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthPairingLinksListError: (error) =>
|
||||
failEnvironmentInternal("pairing_links_load_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("pairing_links_load_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -474,10 +368,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const revoked = yield* serverAuth.revokePairingLink(args.payload.id);
|
||||
return { revoked };
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthPairingLinkRevocationError: (error) =>
|
||||
failEnvironmentInternal("pairing_link_revoke_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("pairing_link_revoke_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -488,10 +381,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const session = yield* requireEnvironmentScope(AuthAccessReadScope);
|
||||
return yield* serverAuth.listClientSessions(session.sessionId);
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthSessionsListError: (error) =>
|
||||
failEnvironmentInternal("client_sessions_load_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("client_sessions_load_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -506,12 +398,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
);
|
||||
return { revoked };
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthForbiddenOperationError: () =>
|
||||
failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
|
||||
ServerAuthSessionRevocationError: (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
}),
|
||||
Effect.catchTag("ServerAuthForbiddenOperationError", () =>
|
||||
failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -523,10 +415,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
|
||||
return { revokedCount };
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthOtherSessionsRevocationError: (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -9,7 +9,6 @@ import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSn
|
||||
import { checkpointRefForThreadTurn } from "./Utils.ts";
|
||||
import * as CheckpointDiffQuery from "./CheckpointDiffQuery.ts";
|
||||
import * as CheckpointStore from "./CheckpointStore.ts";
|
||||
import { CheckpointThreadNotFoundError } from "./Errors.ts";
|
||||
|
||||
function makeThreadCheckpointContext(input: {
|
||||
readonly projectId: ProjectId;
|
||||
@@ -413,14 +412,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
});
|
||||
}).pipe(Effect.provide(layer), Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CheckpointThreadNotFoundError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "CheckpointDiffQuery.getTurnDiff",
|
||||
threadId,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"Checkpoint invariant violation in CheckpointDiffQuery.getTurnDiff: Thread 'thread-missing' not found.",
|
||||
);
|
||||
expect(error.message).toContain("Thread 'thread-missing' not found.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -22,13 +22,7 @@ import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
CheckpointDiffResultInvalidError,
|
||||
CheckpointRefUnavailableError,
|
||||
CheckpointThreadNotFoundError,
|
||||
CheckpointTurnRangeUnavailableError,
|
||||
CheckpointWorkspacePathMissingError,
|
||||
} from "./Errors.ts";
|
||||
import { CheckpointInvariantError, CheckpointUnavailableError } from "./Errors.ts";
|
||||
import type { CheckpointServiceError } from "./Errors.ts";
|
||||
import { checkpointRefForThreadTurn } from "./Utils.ts";
|
||||
import * as CheckpointStore from "./CheckpointStore.ts";
|
||||
@@ -98,9 +92,9 @@ export const make = Effect.gen(function* () {
|
||||
diff: "",
|
||||
};
|
||||
if (!isTurnDiffResult(emptyDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: "Computed turn diff result does not satisfy contract schema.",
|
||||
});
|
||||
}
|
||||
return emptyDiff;
|
||||
@@ -110,9 +104,9 @@ export const make = Effect.gen(function* () {
|
||||
.getThreadCheckpointContext(input.threadId)
|
||||
.pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));
|
||||
if (Option.isNone(threadContext)) {
|
||||
return yield* new CheckpointThreadNotFoundError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: `Thread '${input.threadId}' not found.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -121,19 +115,18 @@ export const make = Effect.gen(function* () {
|
||||
0,
|
||||
);
|
||||
if (input.toTurnCount > maxTurnCount) {
|
||||
return yield* new CheckpointTurnRangeUnavailableError({
|
||||
operation,
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
requestedTurnCount: input.toTurnCount,
|
||||
availableTurnCount: maxTurnCount,
|
||||
turnCount: input.toTurnCount,
|
||||
detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${maxTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
||||
if (!workspaceCwd) {
|
||||
return yield* new CheckpointWorkspacePathMissingError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: `Workspace path missing for thread '${input.threadId}' when computing turn diff.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -144,11 +137,10 @@ export const make = Effect.gen(function* () {
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!fromCheckpointRef) {
|
||||
return yield* new CheckpointRefUnavailableError({
|
||||
operation,
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.fromTurnCount,
|
||||
checkpoint: "from",
|
||||
detail: `Checkpoint ref is unavailable for turn ${input.fromTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -156,11 +148,10 @@ export const make = Effect.gen(function* () {
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!toCheckpointRef) {
|
||||
return yield* new CheckpointRefUnavailableError({
|
||||
operation,
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.toTurnCount,
|
||||
checkpoint: "to",
|
||||
detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -176,9 +167,9 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const turnDiff = buildTurnDiffResult(input, diff);
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: "Computed turn diff result does not satisfy contract schema.",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -209,9 +200,9 @@ export const make = Effect.gen(function* () {
|
||||
"",
|
||||
);
|
||||
if (!isTurnDiffResult(emptyDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: "Computed full thread diff result does not satisfy contract schema.",
|
||||
});
|
||||
}
|
||||
return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
|
||||
@@ -222,35 +213,33 @@ export const make = Effect.gen(function* () {
|
||||
.pipe(Effect.withSpan("checkpoint.fullThread.lookupContext"));
|
||||
|
||||
if (Option.isNone(threadContext)) {
|
||||
return yield* new CheckpointThreadNotFoundError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: `Thread '${input.threadId}' not found.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (input.toTurnCount > threadContext.value.latestCheckpointTurnCount) {
|
||||
return yield* new CheckpointTurnRangeUnavailableError({
|
||||
operation,
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
requestedTurnCount: input.toTurnCount,
|
||||
availableTurnCount: threadContext.value.latestCheckpointTurnCount,
|
||||
turnCount: input.toTurnCount,
|
||||
detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${threadContext.value.latestCheckpointTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
||||
if (!workspaceCwd) {
|
||||
return yield* new CheckpointWorkspacePathMissingError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: `Workspace path missing for thread '${input.threadId}' when computing full thread diff.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (!threadContext.value.toCheckpointRef) {
|
||||
return yield* new CheckpointRefUnavailableError({
|
||||
operation,
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.toTurnCount,
|
||||
checkpoint: "to",
|
||||
detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -273,9 +262,9 @@ export const make = Effect.gen(function* () {
|
||||
diff,
|
||||
);
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: "Computed full thread diff result does not satisfy contract schema.",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -93,27 +93,6 @@ function buildLargeText(lineCount = 5_000): string {
|
||||
}
|
||||
|
||||
it.layer(TestLayer)("CheckpointStore.layer", (it) => {
|
||||
describe("isGitRepository", () => {
|
||||
it.effect("returns false when no Git repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
|
||||
expect(yield* checkpointStore.isGitRepository(tmp)).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns true when a Git repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
|
||||
expect(yield* checkpointStore.isGitRepository(tmp)).toBe(true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("diffCheckpoints", () => {
|
||||
it.effect("returns full oversized checkpoint diffs without truncation", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -115,9 +115,10 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const isGitRepository: CheckpointStore["Service"]["isGitRepository"] = (cwd) =>
|
||||
vcsRegistry
|
||||
.detect({ cwd, requestedKind: "git" })
|
||||
.pipe(Effect.map((repository) => repository !== null));
|
||||
vcsRegistry.resolve({ cwd, requestedKind: "git" }).pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
const captureCheckpoint: CheckpointStore["Service"]["captureCheckpoint"] = Effect.fn(
|
||||
"captureCheckpoint",
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
CheckpointRefUnavailableError,
|
||||
CheckpointTurnRangeUnavailableError,
|
||||
CheckpointWorkspacePathMissingError,
|
||||
} from "./Errors.ts";
|
||||
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
|
||||
it("derives checkpoint messages from structured context", () => {
|
||||
const range = new CheckpointTurnRangeUnavailableError({
|
||||
operation: "CheckpointDiffQuery.getTurnDiff",
|
||||
threadId,
|
||||
requestedTurnCount: 4,
|
||||
availableTurnCount: 2,
|
||||
});
|
||||
const checkpoint = new CheckpointRefUnavailableError({
|
||||
operation: "CheckpointDiffQuery.getTurnDiff",
|
||||
threadId,
|
||||
turnCount: 2,
|
||||
checkpoint: "to",
|
||||
});
|
||||
const workspace = new CheckpointWorkspacePathMissingError({
|
||||
operation: "CheckpointDiffQuery.getFullThreadDiff",
|
||||
threadId,
|
||||
});
|
||||
|
||||
expect(range.message).toBe(
|
||||
"Checkpoint unavailable for thread thread-1 turn 4: Turn diff range exceeds current turn count: requested 4, current 2.",
|
||||
);
|
||||
expect(checkpoint.message).toBe(
|
||||
"Checkpoint unavailable for thread thread-1 turn 2: Checkpoint ref is unavailable for turn 2.",
|
||||
);
|
||||
expect(workspace.message).toBe(
|
||||
"Checkpoint invariant violation in CheckpointDiffQuery.getFullThreadDiff: Workspace path missing for thread 'thread-1' when computing full thread diff.",
|
||||
);
|
||||
});
|
||||
@@ -1,94 +1,40 @@
|
||||
import { NonNegativeInt, ThreadId, type VcsError } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
||||
import type { VcsError } from "@t3tools/contracts";
|
||||
|
||||
export const CheckpointDiffOperation = Schema.Literals([
|
||||
"CheckpointDiffQuery.getTurnDiff",
|
||||
"CheckpointDiffQuery.getFullThreadDiff",
|
||||
]);
|
||||
export type CheckpointDiffOperation = typeof CheckpointDiffOperation.Type;
|
||||
|
||||
/** The computed result does not satisfy the checkpoint RPC contract. */
|
||||
export class CheckpointDiffResultInvalidError extends Schema.TaggedErrorClass<CheckpointDiffResultInvalidError>()(
|
||||
"CheckpointDiffResultInvalidError",
|
||||
/**
|
||||
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
||||
*/
|
||||
export class CheckpointUnavailableError extends Schema.TaggedErrorClass<CheckpointUnavailableError>()(
|
||||
"CheckpointUnavailableError",
|
||||
{
|
||||
operation: CheckpointDiffOperation,
|
||||
threadId: ThreadId,
|
||||
threadId: Schema.String,
|
||||
turnCount: Schema.Number,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const result =
|
||||
this.operation === "CheckpointDiffQuery.getTurnDiff" ? "turn diff" : "full thread diff";
|
||||
return `Checkpoint invariant violation in ${this.operation}: Computed ${result} result does not satisfy contract schema.`;
|
||||
return `Checkpoint unavailable for thread ${this.threadId} turn ${this.turnCount}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Projection state no longer contains the requested checkpoint thread. */
|
||||
export class CheckpointThreadNotFoundError extends Schema.TaggedErrorClass<CheckpointThreadNotFoundError>()(
|
||||
"CheckpointThreadNotFoundError",
|
||||
/**
|
||||
* CheckpointInvariantError - Inconsistent provider/filesystem/catalog state.
|
||||
*/
|
||||
export class CheckpointInvariantError extends Schema.TaggedErrorClass<CheckpointInvariantError>()(
|
||||
"CheckpointInvariantError",
|
||||
{
|
||||
operation: CheckpointDiffOperation,
|
||||
threadId: ThreadId,
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Checkpoint invariant violation in ${this.operation}: Thread '${this.threadId}' not found.`;
|
||||
return `Checkpoint invariant violation in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** The checkpoint thread has no workspace path from which to compute a diff. */
|
||||
export class CheckpointWorkspacePathMissingError extends Schema.TaggedErrorClass<CheckpointWorkspacePathMissingError>()(
|
||||
"CheckpointWorkspacePathMissingError",
|
||||
{
|
||||
operation: CheckpointDiffOperation,
|
||||
threadId: ThreadId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const diff =
|
||||
this.operation === "CheckpointDiffQuery.getTurnDiff" ? "turn diff" : "full thread diff";
|
||||
return `Checkpoint invariant violation in ${this.operation}: Workspace path missing for thread '${this.threadId}' when computing ${diff}.`;
|
||||
}
|
||||
}
|
||||
export type CheckpointStoreError = VcsError | CheckpointInvariantError | CheckpointUnavailableError;
|
||||
|
||||
/** The requested turn lies beyond the latest available checkpoint. */
|
||||
export class CheckpointTurnRangeUnavailableError extends Schema.TaggedErrorClass<CheckpointTurnRangeUnavailableError>()(
|
||||
"CheckpointTurnRangeUnavailableError",
|
||||
{
|
||||
operation: CheckpointDiffOperation,
|
||||
threadId: ThreadId,
|
||||
requestedTurnCount: NonNegativeInt,
|
||||
availableTurnCount: NonNegativeInt,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Checkpoint unavailable for thread ${this.threadId} turn ${this.requestedTurnCount}: Turn diff range exceeds current turn count: requested ${this.requestedTurnCount}, current ${this.availableTurnCount}.`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Expected checkpoint metadata does not contain the requested Git ref. */
|
||||
export class CheckpointRefUnavailableError extends Schema.TaggedErrorClass<CheckpointRefUnavailableError>()(
|
||||
"CheckpointRefUnavailableError",
|
||||
{
|
||||
operation: CheckpointDiffOperation,
|
||||
threadId: ThreadId,
|
||||
turnCount: NonNegativeInt,
|
||||
checkpoint: Schema.Literals(["from", "to"]),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Checkpoint unavailable for thread ${this.threadId} turn ${this.turnCount}: Checkpoint ref is unavailable for turn ${this.turnCount}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type CheckpointStoreError = VcsError;
|
||||
|
||||
export type CheckpointServiceError =
|
||||
| CheckpointStoreError
|
||||
| ProjectionRepositoryError
|
||||
| CheckpointDiffResultInvalidError
|
||||
| CheckpointThreadNotFoundError
|
||||
| CheckpointWorkspacePathMissingError
|
||||
| CheckpointTurnRangeUnavailableError
|
||||
| CheckpointRefUnavailableError;
|
||||
export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError;
|
||||
@@ -1,14 +1,9 @@
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
|
||||
import { acquireRelayClientForLink, reportCloudDisconnectResults } from "./connect.ts";
|
||||
import { acquireRelayClientForLink } from "./connect.ts";
|
||||
|
||||
const managedExecutable = {
|
||||
status: "available",
|
||||
@@ -105,51 +100,3 @@ it.effect("reuses an available relay client executable without prompting", () =>
|
||||
assert.equal(promptCalls, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps disconnect causes in structured logs and out of console warnings", () => {
|
||||
const warnings: ReadonlyArray<unknown>[] = [];
|
||||
const logs: Readonly<Record<string, unknown>>[] = [];
|
||||
const testConsole = {
|
||||
...globalThis.console,
|
||||
warn: (...args: ReadonlyArray<unknown>) => {
|
||||
warnings.push(args);
|
||||
},
|
||||
} satisfies Console.Console;
|
||||
const logger = Logger.make(({ fiber }) => {
|
||||
logs.push(fiber.getRef(References.CurrentLogAnnotations));
|
||||
});
|
||||
const liveFailure = "live unlink private diagnostic";
|
||||
const relayFailure = "relay revoke private diagnostic";
|
||||
|
||||
return reportCloudDisconnectResults({
|
||||
clearAuthorization: true,
|
||||
liveResult: {
|
||||
status: "failed",
|
||||
cause: Cause.fail(new Error(liveFailure)),
|
||||
},
|
||||
relayResult: Exit.failCause(Cause.die(new Error(relayFailure))),
|
||||
}).pipe(
|
||||
Effect.provideService(Console.Console, testConsole),
|
||||
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
assert.lengthOf(warnings, 2);
|
||||
const warningText = warnings.flat().map(String).join("\n");
|
||||
assert.include(warningText, "running server could not stop its tunnel");
|
||||
assert.include(warningText, "Could not revoke the relay-side environment record");
|
||||
assert.notInclude(warningText, liveFailure);
|
||||
assert.notInclude(warningText, relayFailure);
|
||||
assert.deepEqual(
|
||||
logs.map(({ operation, clearAuthorization }) => ({ operation, clearAuthorization })),
|
||||
[
|
||||
{ operation: "live-server-unlink", clearAuthorization: true },
|
||||
{ operation: "relay-environment-unlink", clearAuthorization: true },
|
||||
],
|
||||
);
|
||||
const loggedCauses = logs.map((log) => String(log.cause)).join("\n");
|
||||
assert.include(loggedCauses, liveFailure);
|
||||
assert.include(loggedCauses, relayFailure);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
import { RelayOkResponse } from "@t3tools/contracts/relay";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -180,7 +179,7 @@ const withCloudCliSessionToken = <A, E, R>(
|
||||
type LiveCloudActionResult =
|
||||
| { readonly status: "not-running" }
|
||||
| { readonly status: "succeeded" }
|
||||
| { readonly status: "failed"; readonly cause: Cause.Cause<unknown> };
|
||||
| { readonly status: "failed"; readonly cause: unknown };
|
||||
|
||||
const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
@@ -212,21 +211,6 @@ type RelayUnlinkResult =
|
||||
| { readonly status: "revoked" }
|
||||
| { readonly status: "not-linked" };
|
||||
|
||||
type CloudDisconnectOperation = "live-server-unlink" | "relay-environment-unlink";
|
||||
|
||||
const logCloudDisconnectFailure = (
|
||||
operation: CloudDisconnectOperation,
|
||||
clearAuthorization: boolean,
|
||||
cause: Cause.Cause<unknown>,
|
||||
) =>
|
||||
Effect.logWarning("T3 Connect disconnect operation failed.").pipe(
|
||||
Effect.annotateLogs({
|
||||
operation,
|
||||
clearAuthorization,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
);
|
||||
|
||||
const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(function* () {
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
const token = yield* tokens.getExisting;
|
||||
@@ -252,42 +236,6 @@ const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(f
|
||||
: ({ status: "not-linked" } satisfies RelayUnlinkResult);
|
||||
});
|
||||
|
||||
export const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_results")(
|
||||
function* (input: {
|
||||
readonly clearAuthorization: boolean;
|
||||
readonly liveResult: LiveCloudActionResult;
|
||||
readonly relayResult: Exit.Exit<RelayUnlinkResult, unknown>;
|
||||
}) {
|
||||
if (input.liveResult.status === "failed") {
|
||||
yield* logCloudDisconnectFailure(
|
||||
"live-server-unlink",
|
||||
input.clearAuthorization,
|
||||
input.liveResult.cause,
|
||||
);
|
||||
yield* Console.warn(
|
||||
"T3 Connect is disabled, but the running server could not stop its tunnel.\nRestart that server to stop the connector.",
|
||||
);
|
||||
} else {
|
||||
yield* Console.log("T3 Connect is disabled locally.");
|
||||
}
|
||||
|
||||
if (Exit.isFailure(input.relayResult)) {
|
||||
yield* logCloudDisconnectFailure(
|
||||
"relay-environment-unlink",
|
||||
input.clearAuthorization,
|
||||
input.relayResult.cause,
|
||||
);
|
||||
yield* Console.warn(
|
||||
input.clearAuthorization
|
||||
? "Could not revoke the relay-side environment record before signing out.\nThe stored CLI authorization was still removed locally."
|
||||
: "Could not revoke the relay-side environment record yet.\nRun `t3 connect unlink` again when the relay is reachable.",
|
||||
);
|
||||
} else if (input.relayResult.value.status === "revoked") {
|
||||
yield* Console.log("Revoked the relay-side environment record.");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
|
||||
readonly clearAuthorization: boolean;
|
||||
}) {
|
||||
@@ -301,11 +249,23 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
|
||||
yield* tokens.clear;
|
||||
}
|
||||
|
||||
yield* reportCloudDisconnectResults({
|
||||
clearAuthorization: options.clearAuthorization,
|
||||
liveResult,
|
||||
relayResult,
|
||||
});
|
||||
if (liveResult.status === "failed") {
|
||||
yield* Console.warn(
|
||||
`T3 Connect is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`,
|
||||
);
|
||||
} else {
|
||||
yield* Console.log("T3 Connect is disabled locally.");
|
||||
}
|
||||
|
||||
if (Exit.isFailure(relayResult)) {
|
||||
yield* Console.warn(
|
||||
options.clearAuthorization
|
||||
? `Could not revoke the relay-side environment record before signing out: ${String(relayResult.cause)}\nThe stored CLI authorization was still removed locally.`
|
||||
: `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 connect unlink\` again when the relay is reachable.`,
|
||||
);
|
||||
} else if (relayResult.value.status === "revoked") {
|
||||
yield* Console.log("Revoked the relay-side environment record.");
|
||||
}
|
||||
|
||||
if (options.clearAuthorization) {
|
||||
yield* Console.log("Signed out of T3 Connect locally.");
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { EnvironmentInternalError } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
ProjectLiveServerDeclaredResponseError,
|
||||
ProjectLiveServerRequestError,
|
||||
projectCommandErrorFromLiveServerRequest,
|
||||
} from "./project.ts";
|
||||
|
||||
it("maps declared server failures into structural project command errors", () => {
|
||||
const cause = new EnvironmentInternalError({
|
||||
code: "internal_error",
|
||||
reason: "orchestration_snapshot_failed",
|
||||
traceId: "trace-123",
|
||||
});
|
||||
|
||||
const error = projectCommandErrorFromLiveServerRequest(cause);
|
||||
|
||||
assert.instanceOf(error, ProjectLiveServerDeclaredResponseError);
|
||||
assert.strictEqual(error.operation, "callLiveServer");
|
||||
assert.strictEqual(error.code, "internal_error");
|
||||
assert.strictEqual(error.traceId, "trace-123");
|
||||
assert.strictEqual(error.message, "Server request failed (internal_error, trace trace-123).");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
});
|
||||
|
||||
it("preserves unexpected server failures without deriving the message from them", () => {
|
||||
const cause = new Error("credential abc123 was rejected");
|
||||
|
||||
const error = projectCommandErrorFromLiveServerRequest(cause);
|
||||
|
||||
assert.instanceOf(error, ProjectLiveServerRequestError);
|
||||
assert.strictEqual(error.operation, "callLiveServer");
|
||||
assert.strictEqual(error.message, "Failed to call the running server.");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
});
|
||||
+46
-178
@@ -9,9 +9,11 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -50,150 +52,16 @@ type ProjectCliDispatchCommand = Extract<
|
||||
{ type: "project.create" | "project.meta.update" | "project.delete" }
|
||||
>;
|
||||
|
||||
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
|
||||
|
||||
export class ProjectCommandIdGenerationError extends Schema.TaggedErrorClass<ProjectCommandIdGenerationError>()(
|
||||
"ProjectCommandIdGenerationError",
|
||||
{
|
||||
operation: Schema.Literal("generateProjectCommandId"),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to generate a project command identifier.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedErrorClass<ProjectLiveServerDeclaredResponseError>()(
|
||||
"ProjectLiveServerDeclaredResponseError",
|
||||
{
|
||||
operation: Schema.Literal("callLiveServer"),
|
||||
code: Schema.String,
|
||||
traceId: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Server request failed (${this.code}, trace ${this.traceId}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedErrorClass<ProjectLiveServerUndeclaredStatusError>()(
|
||||
"ProjectLiveServerUndeclaredStatusError",
|
||||
{
|
||||
operation: Schema.Literal("callLiveServer"),
|
||||
status: Schema.Int,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Server request failed with undeclared status ${this.status}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectLiveServerRequestError extends Schema.TaggedErrorClass<ProjectLiveServerRequestError>()(
|
||||
"ProjectLiveServerRequestError",
|
||||
{
|
||||
operation: Schema.Literal("callLiveServer"),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to call the running server.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectTitleEmptyError extends Schema.TaggedErrorClass<ProjectTitleEmptyError>()(
|
||||
"ProjectTitleEmptyError",
|
||||
{
|
||||
operation: Schema.Literal("validateProjectTitle"),
|
||||
title: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Project title cannot be empty.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectIdentifierEmptyError extends Schema.TaggedErrorClass<ProjectIdentifierEmptyError>()(
|
||||
"ProjectIdentifierEmptyError",
|
||||
{
|
||||
operation: Schema.Literal("resolveProjectTarget"),
|
||||
identifier: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Project identifier cannot be empty.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(
|
||||
"ProjectNotFoundError",
|
||||
{
|
||||
operation: Schema.Literal("resolveProjectTarget"),
|
||||
identifier: Schema.String,
|
||||
normalizedWorkspaceRoot: Schema.optional(Schema.String),
|
||||
activeProjectCount: Schema.Number,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `No active project found for '${this.identifier}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectAlreadyExistsError extends Schema.TaggedErrorClass<ProjectAlreadyExistsError>()(
|
||||
"ProjectAlreadyExistsError",
|
||||
{
|
||||
operation: Schema.Literal("addProject"),
|
||||
projectId: ProjectId,
|
||||
workspaceRoot: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `An active project already exists for '${this.workspaceRoot}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const ProjectCommandError = Schema.Union([
|
||||
ProjectCommandIdGenerationError,
|
||||
ProjectLiveServerDeclaredResponseError,
|
||||
ProjectLiveServerUndeclaredStatusError,
|
||||
ProjectLiveServerRequestError,
|
||||
ProjectTitleEmptyError,
|
||||
ProjectIdentifierEmptyError,
|
||||
ProjectNotFoundError,
|
||||
ProjectAlreadyExistsError,
|
||||
]);
|
||||
export type ProjectCommandError = typeof ProjectCommandError.Type;
|
||||
|
||||
export function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
|
||||
if (isEnvironmentHttpCommonError(cause)) {
|
||||
return new ProjectLiveServerDeclaredResponseError({
|
||||
operation: "callLiveServer",
|
||||
code: cause.code,
|
||||
traceId: cause.traceId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
|
||||
return new ProjectLiveServerUndeclaredStatusError({
|
||||
operation: "callLiveServer",
|
||||
status: cause.response.status,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
|
||||
}
|
||||
class ProjectCommandError extends Data.TaggedError("ProjectCommandError")<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
|
||||
const projectCommandUuid = Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectCommandIdGenerationError({
|
||||
operation: "generateProjectCommandId",
|
||||
cause,
|
||||
() =>
|
||||
new ProjectCommandError({
|
||||
message: "Failed to generate a project command identifier.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -207,6 +75,7 @@ const ProjectCliRuntimeLive = Layer.mergeAll(
|
||||
);
|
||||
|
||||
const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
|
||||
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
|
||||
const withProjectCliSessionToken = <A, E, R>(
|
||||
environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
|
||||
run: (token: string) => Effect.Effect<A, E, R>,
|
||||
@@ -223,6 +92,28 @@ const withProjectCliSessionToken = <A, E, R>(
|
||||
const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
|
||||
|
||||
const failLiveServerRequest = (cause: unknown) => {
|
||||
if (isEnvironmentHttpCommonError(cause)) {
|
||||
return Effect.fail(
|
||||
new ProjectCommandError({
|
||||
message: `Server request failed (${cause.code}, trace ${cause.traceId}).`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
|
||||
return Effect.fail(
|
||||
new ProjectCommandError({
|
||||
message: `Server request failed with undeclared status ${cause.response.status}.`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.fail(
|
||||
new ProjectCommandError({
|
||||
message: `Failed to call running server: ${String(cause)}.`,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const makeLiveServerClient = (origin: string) =>
|
||||
HttpApiClient.make(EnvironmentHttpApi, {
|
||||
baseUrl: origin,
|
||||
@@ -244,10 +135,7 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
|
||||
if (trimmed.length > 0) {
|
||||
return trimmed;
|
||||
}
|
||||
return yield* new ProjectTitleEmptyError({
|
||||
operation: "validateProjectTitle",
|
||||
title: explicitTitle,
|
||||
});
|
||||
return yield* new ProjectCommandError({ message: "Project title cannot be empty." });
|
||||
}
|
||||
|
||||
const path = yield* Path.Path;
|
||||
@@ -261,10 +149,7 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
|
||||
}) {
|
||||
const trimmedIdentifier = input.identifier.trim();
|
||||
if (trimmedIdentifier.length === 0) {
|
||||
return yield* new ProjectIdentifierEmptyError({
|
||||
operation: "resolveProjectTarget",
|
||||
identifier: input.identifier,
|
||||
});
|
||||
return yield* new ProjectCommandError({ message: "Project identifier cannot be empty." });
|
||||
}
|
||||
|
||||
const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
|
||||
@@ -277,11 +162,12 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
|
||||
} satisfies ProjectMutationTarget;
|
||||
}
|
||||
|
||||
const normalizedWorkspaceRootResult = yield* Effect.result(
|
||||
const normalizedWorkspaceRootResult = yield* Effect.exit(
|
||||
normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
|
||||
);
|
||||
const normalizedWorkspaceRoot =
|
||||
normalizedWorkspaceRootResult._tag === "Success" ? normalizedWorkspaceRootResult.success : null;
|
||||
const normalizedWorkspaceRoot = Exit.isSuccess(normalizedWorkspaceRootResult)
|
||||
? normalizedWorkspaceRootResult.value
|
||||
: null;
|
||||
|
||||
const exactWorkspaceMatch =
|
||||
normalizedWorkspaceRoot === null
|
||||
@@ -290,14 +176,8 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
|
||||
|
||||
const resolved = exactWorkspaceMatch;
|
||||
if (!resolved) {
|
||||
return yield* new ProjectNotFoundError({
|
||||
operation: "resolveProjectTarget",
|
||||
identifier: trimmedIdentifier,
|
||||
activeProjectCount: activeProjects.length,
|
||||
...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),
|
||||
...(normalizedWorkspaceRootResult._tag === "Failure"
|
||||
? { cause: normalizedWorkspaceRootResult.failure }
|
||||
: {}),
|
||||
return yield* new ProjectCommandError({
|
||||
message: `No active project found for '${trimmedIdentifier}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -314,10 +194,7 @@ const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
|
||||
return yield* client.orchestration.snapshot({
|
||||
headers: { authorization: `Bearer ${bearerToken}` },
|
||||
});
|
||||
}).pipe(
|
||||
withProjectCliLiveServerTimeout,
|
||||
Effect.mapError(projectCommandErrorFromLiveServerRequest),
|
||||
);
|
||||
}).pipe(withProjectCliLiveServerTimeout, Effect.catch(failLiveServerRequest));
|
||||
|
||||
const dispatchLiveOrchestrationCommand = (
|
||||
origin: string,
|
||||
@@ -330,10 +207,7 @@ const dispatchLiveOrchestrationCommand = (
|
||||
headers: { authorization: `Bearer ${bearerToken}` },
|
||||
payload: command,
|
||||
} as Parameters<typeof client.orchestration.dispatch>[0]);
|
||||
}).pipe(
|
||||
withProjectCliLiveServerTimeout,
|
||||
Effect.mapError(projectCommandErrorFromLiveServerRequest),
|
||||
);
|
||||
}).pipe(withProjectCliLiveServerTimeout, Effect.catch(failLiveServerRequest));
|
||||
|
||||
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
@@ -358,15 +232,11 @@ const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecu
|
||||
),
|
||||
);
|
||||
|
||||
const attempted = yield* Effect.result(attempt);
|
||||
if (attempted._tag === "Success") {
|
||||
return Option.some(attempted.success);
|
||||
const attempted = yield* Effect.exit(attempt);
|
||||
if (Exit.isSuccess(attempted)) {
|
||||
return Option.some(attempted.value);
|
||||
}
|
||||
|
||||
yield* Effect.logDebug("Failed to connect to the persisted project CLI server.", {
|
||||
origin: runtimeState.value.origin,
|
||||
cause: attempted.failure,
|
||||
});
|
||||
yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
|
||||
return Option.none<{ readonly origin: string }>();
|
||||
},
|
||||
@@ -464,10 +334,8 @@ const projectAddCommand = Command.make("add", {
|
||||
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
|
||||
);
|
||||
if (existingProject) {
|
||||
return yield* new ProjectAlreadyExistsError({
|
||||
operation: "addProject",
|
||||
projectId: existingProject.id,
|
||||
workspaceRoot,
|
||||
return yield* new ProjectCommandError({
|
||||
message: `An active project already exists for '${workspaceRoot}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,184 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
|
||||
const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
|
||||
|
||||
function makeSecretStore(
|
||||
overrides: Partial<ServerSecretStore.ServerSecretStore["Service"]>,
|
||||
): ServerSecretStore.ServerSecretStore["Service"] {
|
||||
return {
|
||||
get: unusedSecretStoreOperation,
|
||||
set: unusedSecretStoreOperation,
|
||||
create: unusedSecretStoreOperation,
|
||||
getOrCreateRandom: unusedSecretStoreOperation,
|
||||
remove: unusedSecretStoreOperation,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeTokenManager(secretStore: ServerSecretStore.ServerSecretStore["Service"]) {
|
||||
return CliTokenManager.make.pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
Layer.succeed(ServerSecretStore.ServerSecretStore, secretStore),
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => Effect.die("unused HTTP client")),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe("CloudCliTokenManager", () => {
|
||||
it("redacts OAuth endpoint credentials while retaining exact causes", () => {
|
||||
const tokenEndpoint =
|
||||
"https://user:[email protected]/private/token?client_secret=secret#fragment";
|
||||
const redirectUri =
|
||||
"https://callback-user:callback-password@localhost/private/callback?code=secret#fragment";
|
||||
const cause = new Error("exchange failed");
|
||||
|
||||
const refreshError = CliTokenManager.CloudCliCredentialRefreshError.fromStage({
|
||||
stage: "exchange-token",
|
||||
tokenEndpoint,
|
||||
cause,
|
||||
});
|
||||
const authorizationError = CliTokenManager.CloudCliAuthorizationError.fromStage({
|
||||
stage: "exchange-token",
|
||||
tokenEndpoint,
|
||||
redirectUri,
|
||||
cause,
|
||||
});
|
||||
const timeoutError = CliTokenManager.CloudCliAuthorizationTimeoutError.fromRedirectUri({
|
||||
redirectUri,
|
||||
timeoutMillis: 1000,
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(refreshError).toMatchObject({
|
||||
tokenEndpointInputLength: tokenEndpoint.length,
|
||||
tokenEndpointProtocol: "https:",
|
||||
tokenEndpointHostname: "auth.example.test",
|
||||
cause,
|
||||
});
|
||||
expect(authorizationError).toMatchObject({
|
||||
tokenEndpointInputLength: tokenEndpoint.length,
|
||||
tokenEndpointHostname: "auth.example.test",
|
||||
redirectUriInputLength: redirectUri.length,
|
||||
redirectUriHostname: "localhost",
|
||||
cause,
|
||||
});
|
||||
expect(timeoutError).toMatchObject({
|
||||
redirectUriInputLength: redirectUri.length,
|
||||
redirectUriHostname: "localhost",
|
||||
cause,
|
||||
});
|
||||
expect(refreshError.cause).toBe(cause);
|
||||
expect(authorizationError.cause).toBe(cause);
|
||||
expect(timeoutError.cause).toBe(cause);
|
||||
for (const error of [refreshError, authorizationError, timeoutError]) {
|
||||
expect(error).not.toHaveProperty("tokenEndpoint");
|
||||
expect(error).not.toHaveProperty("redirectUri");
|
||||
const serialized = JSON.stringify(error);
|
||||
for (const secret of [
|
||||
"user:password",
|
||||
"callback-user:callback-password",
|
||||
"/private/",
|
||||
"client_secret=secret",
|
||||
"code=secret",
|
||||
"#fragment",
|
||||
]) {
|
||||
expect(error.message).not.toContain(secret);
|
||||
expect(serialized).not.toContain(secret);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it.effect("retains secret context and cause when credential removal fails", () => {
|
||||
const failure = new ServerSecretStore.SecretStoreRemoveError({
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
secretPath: "/tmp/secrets/cloud-cli-oauth-token.bin",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "remove",
|
||||
pathOrDescriptor: "/tmp/secrets/cloud-cli-oauth-token.bin",
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const tokens = yield* makeTokenManager(
|
||||
makeSecretStore({ remove: () => Effect.fail(failure) }),
|
||||
);
|
||||
const error = yield* Effect.flip(tokens.clear);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudCliCredentialRemovalError",
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
cause: failure,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"Could not remove the stored T3 Connect CLI credential cloud-cli-oauth-token.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("classifies credential read failures without replacing the cause", () => {
|
||||
const failure = new ServerSecretStore.SecretStoreReadError({
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
secretPath: "/tmp/secrets/cloud-cli-oauth-token.bin",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFile",
|
||||
pathOrDescriptor: "/tmp/secrets/cloud-cli-oauth-token.bin",
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const tokens = yield* makeTokenManager(makeSecretStore({ get: () => Effect.fail(failure) }));
|
||||
const error = yield* Effect.flip(tokens.hasCredential);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudCliCredentialReadError",
|
||||
stage: "read-credential",
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
cause: failure,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"Could not inspect the stored T3 Connect CLI credential cloud-cli-oauth-token during read-credential.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("classifies malformed persisted credentials as refresh decode failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const tokens = yield* makeTokenManager(
|
||||
makeSecretStore({
|
||||
get: () =>
|
||||
Effect.succeed(Option.some(new TextEncoder().encode("not valid credential JSON"))),
|
||||
}),
|
||||
);
|
||||
const error = yield* Effect.flip(tokens.getExisting);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudCliCredentialRefreshError",
|
||||
stage: "decode-credential",
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
cause: { _tag: "SchemaError" },
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"Could not refresh the T3 Connect CLI credential cloud-cli-oauth-token during decode-credential.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -20,7 +20,6 @@ import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts";
|
||||
@@ -28,8 +27,6 @@ import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts
|
||||
const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
|
||||
const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
|
||||
const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
|
||||
const CLOUD_CLI_OAUTH_CALLBACK_HOST = "127.0.0.1";
|
||||
const CLOUD_CLI_OAUTH_CALLBACK_PORT = 34338;
|
||||
|
||||
const PersistedToken = Schema.Struct({
|
||||
accessToken: Schema.String,
|
||||
@@ -49,223 +46,48 @@ const OAuthTokenResponse = Schema.Struct({
|
||||
token_type: Schema.String,
|
||||
});
|
||||
|
||||
type CredentialReadFailure = ServerSecretStore.SecretStoreReadError | Schema.SchemaError;
|
||||
|
||||
type CredentialPersistFailure =
|
||||
| Schema.SchemaError
|
||||
| ServerSecretStore.SecretStoreTemporaryPathGenerationError
|
||||
| ServerSecretStore.SecretStorePersistError;
|
||||
|
||||
const CloudCliCredentialRefreshStage = Schema.Literals([
|
||||
"read-credential",
|
||||
"decode-credential",
|
||||
"load-oauth-config",
|
||||
"exchange-token",
|
||||
"encode-credential",
|
||||
"persist-credential",
|
||||
]);
|
||||
type CloudCliCredentialRefreshStage = typeof CloudCliCredentialRefreshStage.Type;
|
||||
|
||||
const CloudCliAuthorizationStage = Schema.Literals([
|
||||
"load-oauth-config",
|
||||
"prepare-pkce",
|
||||
"start-callback-server",
|
||||
"exchange-token",
|
||||
"encode-credential",
|
||||
"persist-credential",
|
||||
]);
|
||||
type CloudCliAuthorizationStage = typeof CloudCliAuthorizationStage.Type;
|
||||
|
||||
function tokenEndpointDiagnosticFields(tokenEndpoint: string | undefined) {
|
||||
if (tokenEndpoint === undefined) return {};
|
||||
const diagnostics = getUrlDiagnostics(tokenEndpoint);
|
||||
return {
|
||||
tokenEndpointInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { tokenEndpointProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { tokenEndpointHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
function redirectUriDiagnosticFields(redirectUri: string | undefined) {
|
||||
if (redirectUri === undefined) return {};
|
||||
const diagnostics = getUrlDiagnostics(redirectUri);
|
||||
return {
|
||||
redirectUriInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { redirectUriProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { redirectUriHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(
|
||||
"CloudCliCredentialRemovalError",
|
||||
{
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not remove the stored T3 Connect CLI credential ${this.secretName}.`;
|
||||
return "Could not remove the stored T3 Connect CLI credential.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliCredentialRefreshError extends Schema.TaggedErrorClass<CloudCliCredentialRefreshError>()(
|
||||
"CloudCliCredentialRefreshError",
|
||||
{
|
||||
stage: CloudCliCredentialRefreshStage,
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
tokenEndpointInputLength: Schema.optionalKey(Schema.Number),
|
||||
tokenEndpointProtocol: Schema.optionalKey(Schema.String),
|
||||
tokenEndpointHostname: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
static fromStage(input: {
|
||||
readonly stage: CloudCliCredentialRefreshStage;
|
||||
readonly cause: unknown;
|
||||
readonly tokenEndpoint?: string;
|
||||
}): CloudCliCredentialRefreshError {
|
||||
return new CloudCliCredentialRefreshError({
|
||||
stage: input.stage,
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
...tokenEndpointDiagnosticFields(input.tokenEndpoint),
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
static fromCredentialRead(cause: CredentialReadFailure): CloudCliCredentialRefreshError {
|
||||
return new CloudCliCredentialRefreshError({
|
||||
stage: cause._tag === "SecretStoreReadError" ? "read-credential" : "decode-credential",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
static fromCredentialPersist(cause: CredentialPersistFailure): CloudCliCredentialRefreshError {
|
||||
return new CloudCliCredentialRefreshError({
|
||||
stage: cause._tag === "SchemaError" ? "encode-credential" : "persist-credential",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const tokenEndpoint =
|
||||
this.tokenEndpointInputLength === undefined
|
||||
? ""
|
||||
: ` using the token endpoint${this.tokenEndpointHostname ? ` at ${this.tokenEndpointHostname}` : ""} (input length ${this.tokenEndpointInputLength})`;
|
||||
return `Could not refresh the T3 Connect CLI credential ${this.secretName} during ${this.stage}${tokenEndpoint}.`;
|
||||
return "Could not refresh the T3 Connect CLI credential.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliCredentialReadError extends Schema.TaggedErrorClass<CloudCliCredentialReadError>()(
|
||||
"CloudCliCredentialReadError",
|
||||
{
|
||||
stage: Schema.Literals(["read-credential", "decode-credential"]),
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
static fromCredentialRead(cause: CredentialReadFailure): CloudCliCredentialReadError {
|
||||
return new CloudCliCredentialReadError({
|
||||
stage: cause._tag === "SecretStoreReadError" ? "read-credential" : "decode-credential",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Could not inspect the stored T3 Connect CLI credential ${this.secretName} during ${this.stage}.`;
|
||||
return "Could not read the stored T3 Connect CLI credential.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliAuthorizationError extends Schema.TaggedErrorClass<CloudCliAuthorizationError>()(
|
||||
"CloudCliAuthorizationError",
|
||||
{
|
||||
stage: CloudCliAuthorizationStage,
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
tokenEndpointInputLength: Schema.optionalKey(Schema.Number),
|
||||
tokenEndpointProtocol: Schema.optionalKey(Schema.String),
|
||||
tokenEndpointHostname: Schema.optionalKey(Schema.String),
|
||||
redirectUriInputLength: Schema.optionalKey(Schema.Number),
|
||||
redirectUriProtocol: Schema.optionalKey(Schema.String),
|
||||
redirectUriHostname: Schema.optionalKey(Schema.String),
|
||||
callbackHost: Schema.optional(Schema.String),
|
||||
callbackPort: Schema.optional(Schema.Number),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
static fromStage(input: {
|
||||
readonly stage: CloudCliAuthorizationStage;
|
||||
readonly cause: unknown;
|
||||
readonly tokenEndpoint?: string;
|
||||
readonly redirectUri?: string;
|
||||
readonly callbackHost?: string;
|
||||
readonly callbackPort?: number;
|
||||
}): CloudCliAuthorizationError {
|
||||
return new CloudCliAuthorizationError({
|
||||
stage: input.stage,
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
...tokenEndpointDiagnosticFields(input.tokenEndpoint),
|
||||
...redirectUriDiagnosticFields(input.redirectUri),
|
||||
...(input.callbackHost === undefined ? {} : { callbackHost: input.callbackHost }),
|
||||
...(input.callbackPort === undefined ? {} : { callbackPort: input.callbackPort }),
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
static fromCredentialPersist(cause: CredentialPersistFailure): CloudCliAuthorizationError {
|
||||
return new CloudCliAuthorizationError({
|
||||
stage: cause._tag === "SchemaError" ? "encode-credential" : "persist-credential",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const tokenEndpoint =
|
||||
this.tokenEndpointInputLength === undefined
|
||||
? ""
|
||||
: ` using the token endpoint${this.tokenEndpointHostname ? ` at ${this.tokenEndpointHostname}` : ""} (input length ${this.tokenEndpointInputLength})`;
|
||||
const redirectUri =
|
||||
this.redirectUriInputLength === undefined
|
||||
? ""
|
||||
: ` with a callback URI input of length ${this.redirectUriInputLength}`;
|
||||
const callbackAddress =
|
||||
this.callbackHost && this.callbackPort !== undefined
|
||||
? ` on ${this.callbackHost}:${this.callbackPort}`
|
||||
: "";
|
||||
return `Could not authorize the T3 Connect CLI credential ${this.secretName} during ${this.stage}${tokenEndpoint}${redirectUri}${callbackAddress}.`;
|
||||
return "Could not authorize the T3 Connect CLI.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliAuthorizationTimeoutError extends Schema.TaggedErrorClass<CloudCliAuthorizationTimeoutError>()(
|
||||
"CloudCliAuthorizationTimeoutError",
|
||||
{
|
||||
redirectUriInputLength: Schema.Number,
|
||||
redirectUriProtocol: Schema.optionalKey(Schema.String),
|
||||
redirectUriHostname: Schema.optionalKey(Schema.String),
|
||||
timeoutMillis: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
static fromRedirectUri(input: {
|
||||
readonly redirectUri: string;
|
||||
readonly timeoutMillis: number;
|
||||
readonly cause: unknown;
|
||||
}): CloudCliAuthorizationTimeoutError {
|
||||
const diagnostics = getUrlDiagnostics(input.redirectUri);
|
||||
return new CloudCliAuthorizationTimeoutError({
|
||||
redirectUriInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { redirectUriProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { redirectUriHostname: diagnostics.hostname }),
|
||||
timeoutMillis: input.timeoutMillis,
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const callback = this.redirectUriHostname ? ` for ${this.redirectUriHostname}` : "";
|
||||
return `Timed out after ${this.timeoutMillis}ms waiting for T3 Connect authorization${callback} (callback URI input length ${this.redirectUriInputLength}).`;
|
||||
return "Timed out waiting for T3 Connect authorization.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,21 +103,18 @@ export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
|
||||
export class CloudCliTokenManager extends Context.Service<
|
||||
CloudCliTokenManager,
|
||||
{
|
||||
readonly get: Effect.Effect<
|
||||
PersistedToken,
|
||||
| CloudCliCredentialRefreshError
|
||||
| CloudCliAuthorizationError
|
||||
| CloudCliAuthorizationTimeoutError
|
||||
>;
|
||||
readonly getExisting: Effect.Effect<
|
||||
Option.Option<PersistedToken>,
|
||||
CloudCliCredentialRefreshError
|
||||
>;
|
||||
readonly hasCredential: Effect.Effect<boolean, CloudCliCredentialReadError>;
|
||||
readonly clear: Effect.Effect<void, CloudCliCredentialRemovalError>;
|
||||
readonly get: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
|
||||
readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
|
||||
readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
|
||||
readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
|
||||
}
|
||||
>()("t3/cloud/CliTokenManager/CloudCliTokenManager") {}
|
||||
|
||||
const wrapError =
|
||||
<WrappedError extends CloudCliTokenManagerError>(makeError: (cause: unknown) => WrappedError) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, WrappedError, R> =>
|
||||
effect.pipe(Effect.mapError(makeError));
|
||||
|
||||
function stringToBytes(value: string): Uint8Array {
|
||||
return new TextEncoder().encode(value);
|
||||
}
|
||||
@@ -315,15 +134,9 @@ export const make = Effect.gen(function* () {
|
||||
return token;
|
||||
});
|
||||
|
||||
const clear = secrets.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudCliCredentialRemovalError({
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const clear = secrets
|
||||
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
|
||||
.pipe(wrapError((cause) => new CloudCliCredentialRemovalError({ cause })));
|
||||
|
||||
const read = Effect.fn("cloud.cli_token.read")(function* () {
|
||||
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
|
||||
@@ -349,54 +162,21 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
|
||||
const metadata = yield* cloudCliOAuthConfig.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliCredentialRefreshError.fromStage({
|
||||
stage: "load-oauth-config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const metadata = yield* cloudCliOAuthConfig;
|
||||
return yield* exchangeToken(metadata, {
|
||||
grant_type: "refresh_token",
|
||||
refresh_token: token.refreshToken,
|
||||
client_id: metadata.clientId,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliCredentialRefreshError.fromStage({
|
||||
stage: "exchange-token",
|
||||
tokenEndpoint: metadata.tokenEndpoint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const login = Effect.fn("cloud.cli_token.login")(function* () {
|
||||
const metadata = yield* cloudCliOAuthConfig.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliAuthorizationError.fromStage({
|
||||
stage: "load-oauth-config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const { challenge, state, verifier } = yield* Effect.gen(function* () {
|
||||
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
|
||||
const challenge = Encoding.encodeBase64Url(
|
||||
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
|
||||
);
|
||||
const state = yield* crypto.randomUUIDv4;
|
||||
return { challenge, state, verifier };
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliAuthorizationError.fromStage({
|
||||
stage: "prepare-pkce",
|
||||
redirectUri: metadata.redirectUri,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
const metadata = yield* cloudCliOAuthConfig;
|
||||
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
|
||||
const challenge = Encoding.encodeBase64Url(
|
||||
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
|
||||
);
|
||||
const state = yield* crypto.randomUUIDv4;
|
||||
const callback = yield* Deferred.make<string>();
|
||||
const callbackRoute = HttpRouter.add(
|
||||
"GET",
|
||||
@@ -427,21 +207,12 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: CLOUD_CLI_OAUTH_CALLBACK_HOST,
|
||||
port: CLOUD_CLI_OAUTH_CALLBACK_PORT,
|
||||
host: "127.0.0.1",
|
||||
port: 34338,
|
||||
disablePreemptiveShutdown: true,
|
||||
}),
|
||||
),
|
||||
Layer.build,
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliAuthorizationError.fromStage({
|
||||
stage: "start-callback-server",
|
||||
redirectUri: metadata.redirectUri,
|
||||
callbackHost: CLOUD_CLI_OAUTH_CALLBACK_HOST,
|
||||
callbackPort: CLOUD_CLI_OAUTH_CALLBACK_PORT,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const authorizationUrl = new URL(metadata.authorizationEndpoint);
|
||||
authorizationUrl.searchParams.set("client_id", metadata.clientId);
|
||||
@@ -454,16 +225,13 @@ export const make = Effect.gen(function* () {
|
||||
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
|
||||
const code = yield* Deferred.await(callback).pipe(
|
||||
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
|
||||
Effect.catchTags({
|
||||
TimeoutError: (cause) =>
|
||||
Effect.fail(
|
||||
CloudCliAuthorizationTimeoutError.fromRedirectUri({
|
||||
redirectUri: metadata.redirectUri,
|
||||
timeoutMillis: Duration.toMillis(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
Effect.catchTag("TimeoutError", (cause) =>
|
||||
Effect.fail(
|
||||
new CloudCliAuthorizationTimeoutError({
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* exchangeToken(metadata, {
|
||||
grant_type: "authorization_code",
|
||||
@@ -471,43 +239,26 @@ export const make = Effect.gen(function* () {
|
||||
redirect_uri: metadata.redirectUri,
|
||||
client_id: metadata.clientId,
|
||||
code_verifier: verifier,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliAuthorizationError.fromStage({
|
||||
stage: "exchange-token",
|
||||
tokenEndpoint: metadata.tokenEndpoint,
|
||||
redirectUri: metadata.redirectUri,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
|
||||
const token = yield* read().pipe(
|
||||
Effect.mapError(CloudCliCredentialRefreshError.fromCredentialRead),
|
||||
);
|
||||
const token = yield* read();
|
||||
if (Option.isNone(token)) return token;
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
|
||||
return token;
|
||||
}
|
||||
return Option.some(
|
||||
yield* refresh(token.value).pipe(
|
||||
Effect.flatMap((refreshed) =>
|
||||
persist(refreshed).pipe(
|
||||
Effect.mapError(CloudCliCredentialRefreshError.fromCredentialPersist),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));
|
||||
});
|
||||
|
||||
const getExisting = semaphore.withPermits(1)(getExistingNoLock());
|
||||
const getExisting = semaphore.withPermits(1)(
|
||||
getExistingNoLock().pipe(wrapError((cause) => new CloudCliCredentialRefreshError({ cause }))),
|
||||
);
|
||||
const hasCredential = semaphore.withPermits(1)(
|
||||
read().pipe(
|
||||
Effect.map(Option.isSome),
|
||||
Effect.mapError(CloudCliCredentialReadError.fromCredentialRead),
|
||||
wrapError((cause) => new CloudCliCredentialReadError({ cause })),
|
||||
),
|
||||
);
|
||||
const get = semaphore.withPermits(1)(
|
||||
@@ -515,14 +266,8 @@ export const make = Effect.gen(function* () {
|
||||
const token = yield* getExistingNoLock();
|
||||
return Option.isSome(token)
|
||||
? token.value
|
||||
: yield* Effect.scoped(login()).pipe(
|
||||
Effect.flatMap((authorized) =>
|
||||
persist(authorized).pipe(
|
||||
Effect.mapError(CloudCliAuthorizationError.fromCredentialPersist),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
|
||||
}).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))),
|
||||
);
|
||||
|
||||
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
|
||||
|
||||
@@ -66,9 +66,7 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
|
||||
Effect.flatMap(() =>
|
||||
Effect.fail(
|
||||
new ServerSecretStore.SecretStorePersistError({
|
||||
operation: "create",
|
||||
secretName: "cloud-link-ed25519-key-pair",
|
||||
secretPath: "cloud-link-ed25519-key-pair.bin",
|
||||
resource: "environment signing key pair",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "AlreadyExists",
|
||||
module: "FileSystem",
|
||||
@@ -89,24 +87,4 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retains the secret name and decode cause for malformed keypairs", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = {
|
||||
get: () => Effect.succeed(Option.some(new TextEncoder().encode("not-json"))),
|
||||
set: unusedSecretStoreOperation,
|
||||
create: unusedSecretStoreOperation,
|
||||
getOrCreateRandom: unusedSecretStoreOperation,
|
||||
remove: unusedSecretStoreOperation,
|
||||
} satisfies ServerSecretStore.ServerSecretStore["Service"];
|
||||
|
||||
const error = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore).pipe(
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreDecodeError);
|
||||
assert.equal(error.secretName, "cloud-link-ed25519-key-pair");
|
||||
assert.exists(error.cause);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -27,6 +27,17 @@ function stringToBytes(value: string): Uint8Array {
|
||||
return new TextEncoder().encode(value);
|
||||
}
|
||||
|
||||
const KEY_PAIR_RESOURCE = "environment signing key pair";
|
||||
|
||||
const keyPairDecodeError = (cause: unknown): ServerSecretStore.SecretStoreDecodeError =>
|
||||
new ServerSecretStore.SecretStoreDecodeError({ resource: KEY_PAIR_RESOURCE, cause });
|
||||
|
||||
const keyPairEncodeError = (cause: unknown): ServerSecretStore.SecretStoreEncodeError =>
|
||||
new ServerSecretStore.SecretStoreEncodeError({ resource: KEY_PAIR_RESOURCE, cause });
|
||||
|
||||
const keyPairConcurrentReadError = (): ServerSecretStore.SecretStoreConcurrentReadError =>
|
||||
new ServerSecretStore.SecretStoreConcurrentReadError({ resource: KEY_PAIR_RESOURCE });
|
||||
|
||||
const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (
|
||||
secrets: ServerSecretStore.ServerSecretStore["Service"],
|
||||
) {
|
||||
@@ -35,13 +46,7 @@ const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (
|
||||
return Option.none<EnvironmentKeyPair>();
|
||||
}
|
||||
const decoded = yield* decodeEnvironmentKeyPair(bytesToString(encoded.value)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSecretStore.SecretStoreDecodeError({
|
||||
secretName: CLOUD_LINK_KEY_PAIR,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(keyPairDecodeError),
|
||||
);
|
||||
return Option.some(decoded);
|
||||
});
|
||||
@@ -51,35 +56,22 @@ const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(functio
|
||||
keyPair: EnvironmentKeyPair,
|
||||
) {
|
||||
const encoded = yield* encodeEnvironmentKeyPair(keyPair).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSecretStore.SecretStoreEncodeError({
|
||||
secretName: CLOUD_LINK_KEY_PAIR,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(keyPairEncodeError),
|
||||
);
|
||||
return yield* secrets.create(CLOUD_LINK_KEY_PAIR, stringToBytes(encoded)).pipe(
|
||||
Effect.as(keyPair),
|
||||
Effect.catchTags({
|
||||
SecretStorePersistError: (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? readEnvironmentKeyPair(secrets).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ServerSecretStore.SecretStoreConcurrentReadError({
|
||||
secretName: CLOUD_LINK_KEY_PAIR,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? readEnvironmentKeyPair(secrets).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () => Effect.fail(keyPairConcurrentReadError()),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,45 +1,23 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientError from "effect/unstable/http/HttpClientError";
|
||||
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import { EnvironmentHttpInternalServerError } from "@t3tools/contracts";
|
||||
import { HttpClient, HttpServerRequest } from "effect/unstable/http";
|
||||
|
||||
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
import {
|
||||
CloudRelayRequestError,
|
||||
consumeCloudReplayGuards,
|
||||
reconcileDesiredCloudLink,
|
||||
} from "./http.ts";
|
||||
import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
|
||||
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
|
||||
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
|
||||
|
||||
const encodeEnvironmentHttpInternalServerError = Schema.encodeUnknownSync(
|
||||
EnvironmentHttpInternalServerError,
|
||||
);
|
||||
const decodeEnvironmentHttpInternalServerError = Schema.decodeUnknownSync(
|
||||
EnvironmentHttpInternalServerError,
|
||||
);
|
||||
|
||||
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
|
||||
new ServerSecretStore.SecretStorePersistError({
|
||||
operation: "create",
|
||||
secretName: "cloud replay guard",
|
||||
secretPath: "cloud-replay-guard.bin",
|
||||
resource: "cloud replay guard",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: tag,
|
||||
module: "FileSystem",
|
||||
@@ -62,56 +40,6 @@ function makeSecretStore(
|
||||
};
|
||||
}
|
||||
|
||||
function reconcileWith(input: {
|
||||
readonly getExisting: CliTokenManager.CloudCliTokenManager["Service"]["getExisting"];
|
||||
readonly httpClient?: HttpClient.HttpClient;
|
||||
readonly secretStore?: ServerSecretStore.ServerSecretStore["Service"];
|
||||
readonly env?: Readonly<Record<string, string>>;
|
||||
}) {
|
||||
return reconcileDesiredCloudLink("http://127.0.0.1:3774").pipe(
|
||||
Effect.provideService(
|
||||
ServerSecretStore.ServerSecretStore,
|
||||
input.secretStore ?? makeSecretStore(unusedSecretStoreOperation),
|
||||
),
|
||||
Effect.provideService(
|
||||
ServerEnvironment.ServerEnvironment,
|
||||
ServerEnvironment.ServerEnvironment.of({
|
||||
getEnvironmentId: unusedSecretStoreOperation(),
|
||||
getDescriptor: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
|
||||
applyConfig: unusedSecretStoreOperation,
|
||||
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
EnvironmentAuth.EnvironmentAuth,
|
||||
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
CliTokenManager.CloudCliTokenManager,
|
||||
CliTokenManager.CloudCliTokenManager.of({
|
||||
get: unusedSecretStoreOperation(),
|
||||
getExisting: input.getExisting,
|
||||
hasCredential: unusedSecretStoreOperation(),
|
||||
clear: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
HttpClient.HttpClient,
|
||||
input.httpClient ?? HttpClient.make(() => unusedSecretStoreOperation()),
|
||||
),
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it("preserves messages surfaced by cloud 500 responses", () => {
|
||||
const cause = new Error("cloud operation failed");
|
||||
|
||||
@@ -165,84 +93,6 @@ describe("consumeCloudReplayGuards", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("CloudRelayRequestError", () => {
|
||||
it("classifies response failures without deriving its message from the cause", () => {
|
||||
const requestUrl =
|
||||
"https://relay-user:[email protected]/private/environment-links?token=relay-secret#relay-fragment";
|
||||
const request = HttpClientRequest.post(requestUrl);
|
||||
const response = HttpClientResponse.fromWeb(
|
||||
request,
|
||||
new Response("sensitive upstream response", { status: 502 }),
|
||||
);
|
||||
const upstreamCause = new Error("sensitive upstream response details");
|
||||
const cause = new HttpClientError.HttpClientError({
|
||||
reason: new HttpClientError.StatusCodeError({
|
||||
request,
|
||||
response,
|
||||
cause: upstreamCause,
|
||||
}),
|
||||
});
|
||||
|
||||
const error = CloudRelayRequestError.fromClientFailure({
|
||||
operation: "create-environment-link",
|
||||
url: request.url,
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error).toMatchObject({
|
||||
operation: "create-environment-link",
|
||||
phase: "check-response-status",
|
||||
method: "POST",
|
||||
requestUrlInputLength: requestUrl.length,
|
||||
requestUrlProtocol: "https:",
|
||||
requestUrlHostname: "relay.example.test",
|
||||
responseStatus: 502,
|
||||
cause,
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("url");
|
||||
expect(error.message).toBe(
|
||||
"T3 Connect relay create-environment-link failed during check-response-status with response status 502.",
|
||||
);
|
||||
expect(error.message).not.toContain(upstreamCause.message);
|
||||
for (const secret of [
|
||||
"relay-user",
|
||||
"relay-password",
|
||||
"/private/environment-links",
|
||||
"relay-secret",
|
||||
"relay-fragment",
|
||||
]) {
|
||||
expect(error.message).not.toContain(secret);
|
||||
expect(Object.values(error).join(" ")).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps internal causes out of encoded HTTP error bodies", () => {
|
||||
const cause = new Error("private upstream detail");
|
||||
const error = new EnvironmentHttpInternalServerError({
|
||||
operation: "generate_link_proof",
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(encodeEnvironmentHttpInternalServerError(error)).toEqual({
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
operation: "generate_link_proof",
|
||||
message: "Could not generate environment link proof.",
|
||||
});
|
||||
});
|
||||
|
||||
it("decodes legacy message-only HTTP errors during rolling deployments", () => {
|
||||
const error = decodeEnvironmentHttpInternalServerError({
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
message: "Legacy environment server failure.",
|
||||
});
|
||||
|
||||
expect(error.operation).toBeUndefined();
|
||||
expect(error.message).toBe("Legacy environment server failure.");
|
||||
});
|
||||
|
||||
describe("relay request tracing", () => {
|
||||
it.effect("does not accept an unauthenticated request trace parent", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -310,127 +160,48 @@ describe("relay request tracing", () => {
|
||||
describe("reconcileDesiredCloudLink", () => {
|
||||
it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
reconcileWith({ getExisting: Effect.succeed(Option.none()) }),
|
||||
);
|
||||
const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
reason: "cloud_cli_authorization_required",
|
||||
message: "Run `t3 connect link` to authorize this environment.",
|
||||
});
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
ServerSecretStore.ServerSecretStore,
|
||||
makeSecretStore(unusedSecretStoreOperation),
|
||||
),
|
||||
Effect.provideService(
|
||||
ServerEnvironment.ServerEnvironment,
|
||||
ServerEnvironment.ServerEnvironment.of({
|
||||
getEnvironmentId: unusedSecretStoreOperation(),
|
||||
getDescriptor: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
|
||||
applyConfig: unusedSecretStoreOperation,
|
||||
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
EnvironmentAuth.EnvironmentAuth,
|
||||
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
CliTokenManager.CloudCliTokenManager,
|
||||
CliTokenManager.CloudCliTokenManager.of({
|
||||
get: unusedSecretStoreOperation(),
|
||||
getExisting: Effect.succeed(Option.none()),
|
||||
hasCredential: unusedSecretStoreOperation(),
|
||||
clear: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => unusedSecretStoreOperation()),
|
||||
),
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("attributes link-proof secret failures to proof generation", () => {
|
||||
const cause = new Error("private secret-store detail");
|
||||
const secretFailure = new ServerSecretStore.SecretStoreReadError({
|
||||
secretName: "environment-key-pair",
|
||||
secretPath: "environment-key-pair.json",
|
||||
cause,
|
||||
});
|
||||
const httpClient = HttpClient.make((request) =>
|
||||
Effect.succeed(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
challenge: "relay-link-challenge",
|
||||
expiresAt: "2099-01-01T00:00:00.000Z",
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const secretStore = makeSecretStore(unusedSecretStoreOperation);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
reconcileWith({
|
||||
getExisting: Effect.succeed(
|
||||
Option.some({
|
||||
accessToken: "access-token",
|
||||
refreshToken: "refresh-token",
|
||||
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
|
||||
}),
|
||||
),
|
||||
httpClient,
|
||||
secretStore: {
|
||||
...secretStore,
|
||||
get: () => Effect.fail(secretFailure),
|
||||
},
|
||||
env: { T3CODE_RELAY_URL: "https://relay.example.test" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
operation: "generate_link_proof",
|
||||
cause: secretFailure,
|
||||
});
|
||||
expect(error.message).toBe("Could not generate environment link proof.");
|
||||
expect(error.cause).toBe(secretFailure);
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("redacts relay transport failures behind a stable structural message", () => {
|
||||
const transportCause = new Error("upstream included a sensitive database password");
|
||||
const capturedLogs: Array<ReadonlyArray<unknown>> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
capturedLogs.push(Array.isArray(message) ? message : [message]);
|
||||
});
|
||||
const httpClient = HttpClient.make((request) =>
|
||||
Effect.fail(
|
||||
new HttpClientError.HttpClientError({
|
||||
reason: new HttpClientError.TransportError({ request, cause: transportCause }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
reconcileWith({
|
||||
getExisting: Effect.succeed(
|
||||
Option.some({
|
||||
accessToken: "access-token",
|
||||
refreshToken: "refresh-token",
|
||||
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
|
||||
}),
|
||||
),
|
||||
httpClient,
|
||||
env: { T3CODE_RELAY_URL: "https://relay.example.test" },
|
||||
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
operation: "relay_request",
|
||||
relayOperation: "create-link-challenge",
|
||||
relayPhase: "send-request",
|
||||
message: "T3 Connect relay create-link-challenge failed during send-request.",
|
||||
cause: {
|
||||
_tag: "CloudRelayRequestError",
|
||||
operation: "create-link-challenge",
|
||||
phase: "send-request",
|
||||
},
|
||||
});
|
||||
expect(error.message).not.toContain(transportCause.message);
|
||||
expect(capturedLogs).toHaveLength(1);
|
||||
const logFields = capturedLogs[0]?.find(
|
||||
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
||||
);
|
||||
expect(logFields).toMatchObject({
|
||||
operation: "relay_request",
|
||||
relayOperation: "create-link-challenge",
|
||||
relayPhase: "send-request",
|
||||
causeTag: "CloudRelayRequestError",
|
||||
});
|
||||
expect(logFields).not.toHaveProperty("cause");
|
||||
expect(capturedLogs[0]?.filter((value) => typeof value === "string").join(" ")).not.toContain(
|
||||
transportCause.message,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
+116
-333
@@ -9,10 +9,7 @@ import {
|
||||
EnvironmentHttpApi,
|
||||
EnvironmentHttpBadRequestError,
|
||||
EnvironmentHttpConflictError,
|
||||
type EnvironmentHttpInternalOperation,
|
||||
EnvironmentHttpInternalServerError,
|
||||
EnvironmentHttpRelayOperation,
|
||||
EnvironmentHttpRelayPhase,
|
||||
EnvironmentHttpUnauthorizedError,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -44,7 +41,6 @@ import {
|
||||
verifyRelayJwt,
|
||||
} from "@t3tools/shared/relayJwt";
|
||||
import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -52,13 +48,8 @@ import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpEffect from "effect/unstable/http/HttpEffect";
|
||||
import * as HttpBody from "effect/unstable/http/HttpBody";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientError from "effect/unstable/http/HttpClientError";
|
||||
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
@@ -94,145 +85,26 @@ const CLOUD_CREDENTIAL_RESPONSE_HEADERS = {
|
||||
pragma: "no-cache",
|
||||
} as const;
|
||||
|
||||
export class CloudRelayConfigurationError extends Schema.TaggedErrorClass<CloudRelayConfigurationError>()(
|
||||
"CloudRelayConfigurationError",
|
||||
{
|
||||
configKey: Schema.Literal("T3CODE_RELAY_URL"),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.configKey} must be configured as a secure absolute HTTPS origin.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudRelayRequestError extends Schema.TaggedErrorClass<CloudRelayRequestError>()(
|
||||
"CloudRelayRequestError",
|
||||
{
|
||||
operation: EnvironmentHttpRelayOperation,
|
||||
phase: EnvironmentHttpRelayPhase,
|
||||
method: Schema.Literal("POST"),
|
||||
requestUrlInputLength: Schema.Number,
|
||||
requestUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
requestUrlHostname: Schema.optionalKey(Schema.String),
|
||||
responseStatus: Schema.optional(Schema.Number),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromClientFailure(input: {
|
||||
readonly operation: CloudRelayRequestError["operation"];
|
||||
readonly url: string;
|
||||
readonly cause: HttpBody.HttpBodyError | HttpClientError.HttpClientError | Schema.SchemaError;
|
||||
readonly responseStatus?: number;
|
||||
}): CloudRelayRequestError {
|
||||
const diagnostics = getUrlDiagnostics(input.url);
|
||||
const context = {
|
||||
operation: input.operation,
|
||||
method: "POST" as const,
|
||||
requestUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { requestUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { requestUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
if (input.cause._tag === "SchemaError") {
|
||||
return new CloudRelayRequestError({
|
||||
...context,
|
||||
phase: "decode-response",
|
||||
...(input.responseStatus === undefined ? {} : { responseStatus: input.responseStatus }),
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
if (!HttpClientError.isHttpClientError(input.cause)) {
|
||||
return new CloudRelayRequestError({
|
||||
...context,
|
||||
phase: "encode-request",
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
const phase: CloudRelayRequestError["phase"] = (() => {
|
||||
switch (input.cause.reason._tag) {
|
||||
case "EncodeError":
|
||||
return "encode-request";
|
||||
case "TransportError":
|
||||
case "InvalidUrlError":
|
||||
return "send-request";
|
||||
case "StatusCodeError":
|
||||
return "check-response-status";
|
||||
case "DecodeError":
|
||||
case "EmptyBodyError":
|
||||
return "decode-response";
|
||||
}
|
||||
})();
|
||||
|
||||
return new CloudRelayRequestError({
|
||||
...context,
|
||||
phase,
|
||||
...(input.cause.response === undefined
|
||||
? input.responseStatus === undefined
|
||||
? {}
|
||||
: { responseStatus: input.responseStatus }
|
||||
: { responseStatus: input.cause.response.status }),
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const responseStatus =
|
||||
this.responseStatus === undefined ? "" : ` with response status ${this.responseStatus}`;
|
||||
return `T3 Connect relay ${this.operation} failed during ${this.phase}${responseStatus}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const appendCloudCredentialResponseHeaders = HttpEffect.appendPreResponseHandler(
|
||||
(_request, response) =>
|
||||
Effect.succeed(HttpServerResponse.setHeaders(response, CLOUD_CREDENTIAL_RESPONSE_HEADERS)),
|
||||
);
|
||||
|
||||
function errorDiagnosticTag(cause: unknown): string {
|
||||
if (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"_tag" in cause &&
|
||||
typeof cause._tag === "string"
|
||||
) {
|
||||
return cause._tag;
|
||||
}
|
||||
if (cause instanceof Error) return cause.name;
|
||||
return typeof cause;
|
||||
}
|
||||
|
||||
type EnvironmentCloudInternalErrorContext =
|
||||
| Exclude<EnvironmentHttpInternalOperation, "relay_request">
|
||||
| {
|
||||
readonly operation: "relay_request";
|
||||
readonly relayOperation: CloudRelayRequestError["operation"];
|
||||
readonly relayPhase: CloudRelayRequestError["phase"];
|
||||
readonly responseStatus?: number;
|
||||
};
|
||||
|
||||
const failEnvironmentCloudInternalError =
|
||||
(context: EnvironmentCloudInternalErrorContext) =>
|
||||
(cause: unknown): Effect.Effect<never, EnvironmentHttpInternalServerError> => {
|
||||
const error =
|
||||
typeof context === "string"
|
||||
? new EnvironmentHttpInternalServerError({ operation: context, cause })
|
||||
: new EnvironmentHttpInternalServerError({ ...context, cause });
|
||||
const logContext =
|
||||
typeof context === "string"
|
||||
? { operation: context, causeTag: errorDiagnosticTag(cause) }
|
||||
: { ...context, causeTag: errorDiagnosticTag(cause) };
|
||||
return Effect.logError(error.message, logContext).pipe(
|
||||
Effect.flatMap(() => Effect.fail(error)),
|
||||
(message: string) =>
|
||||
(cause: unknown): Effect.Effect<never, EnvironmentHttpInternalServerError> =>
|
||||
Effect.logError(message, { cause }).pipe(
|
||||
Effect.flatMap(() => Effect.fail(new EnvironmentHttpInternalServerError({ message }))),
|
||||
);
|
||||
};
|
||||
|
||||
const failCloudCliTokenManagerError = (error: CliTokenManager.CloudCliTokenManagerError) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error);
|
||||
|
||||
const requireRelayUrl = relayUrlConfig.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudRelayConfigurationError({
|
||||
configKey: "T3CODE_RELAY_URL",
|
||||
cause,
|
||||
() =>
|
||||
new EnvironmentHttpInternalServerError({
|
||||
message: "T3CODE_RELAY_URL must be configured as a secure absolute HTTPS origin.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -254,12 +126,11 @@ export function consumeCloudReplayGuards(input: {
|
||||
input.names.map((name) =>
|
||||
input.secrets.create(name, input.value).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchTags({
|
||||
SecretStorePersistError: (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? Effect.succeed(false)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? Effect.succeed(false)
|
||||
: Effect.fail(error),
|
||||
),
|
||||
),
|
||||
),
|
||||
{ concurrency: input.names.length },
|
||||
@@ -282,10 +153,9 @@ function validateCloudMintPublicKey(
|
||||
): Effect.Effect<void, EnvironmentHttpBadRequestError> {
|
||||
return Effect.try({
|
||||
try: () => NodeCrypto.createPublicKey(publicKey.replace(/\\n/g, "\n")),
|
||||
catch: (cause) =>
|
||||
catch: () =>
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_cloud_mint_public_key",
|
||||
cause,
|
||||
message: "Cloud mint public key must be a valid Ed25519 public key.",
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.flatMap((key) =>
|
||||
@@ -293,7 +163,7 @@ function validateCloudMintPublicKey(
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_cloud_mint_public_key",
|
||||
message: "Cloud mint public key must be a valid Ed25519 public key.",
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -306,28 +176,28 @@ function validateRelayConfigPayload(
|
||||
if (!isSecureRelayUrl(payload.relayUrl)) {
|
||||
return Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_relay_url",
|
||||
message: "Relay URL must be a secure absolute HTTPS URL.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (payload.relayIssuer !== undefined && !isSecureRelayUrl(payload.relayIssuer)) {
|
||||
return Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_relay_issuer",
|
||||
message: "Relay issuer must be a secure absolute HTTPS URL.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (payload.environmentCredential.trim().length === 0) {
|
||||
return Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "missing_relay_environment_credential",
|
||||
message: "Relay environment credential is required.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (payload.cloudUserId.trim().length === 0) {
|
||||
return Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "missing_cloud_user_id",
|
||||
message: "Cloud user id is required.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -337,7 +207,7 @@ function validateRelayConfigPayload(
|
||||
function validateLinkedCloudUser(input: {
|
||||
readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
|
||||
readonly cloudUserId: string;
|
||||
}) {
|
||||
}): Effect.Effect<void, EnvironmentAuth.ServerAuthInternalError | EnvironmentHttpConflictError> {
|
||||
return input.secrets.get(CLOUD_LINKED_USER_ID).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -354,14 +224,17 @@ function validateLinkedCloudUser(input: {
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new EnvironmentHttpConflictError({
|
||||
reason: "linked_to_different_cloud_account",
|
||||
message:
|
||||
"This environment is already linked to a different cloud account. Unlink it before switching accounts.",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function readInstalledCloudUserId(secrets: ServerSecretStore.ServerSecretStore["Service"]) {
|
||||
function readInstalledCloudUserId(
|
||||
secrets: ServerSecretStore.ServerSecretStore["Service"],
|
||||
): Effect.Effect<string, EnvironmentAuth.ServerAuthInternalError> {
|
||||
return secrets.get(CLOUD_LINKED_USER_ID).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -486,7 +359,7 @@ const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function
|
||||
})
|
||||
) {
|
||||
return yield* new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_managed_endpoint_origin",
|
||||
message: "Invalid managed endpoint origin.",
|
||||
});
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
@@ -529,23 +402,24 @@ const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")(
|
||||
const requestUrl = requestAbsoluteUrl(httpRequest);
|
||||
if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {
|
||||
return yield* new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_managed_endpoint_origin",
|
||||
message: "Invalid managed endpoint origin.",
|
||||
});
|
||||
}
|
||||
const proof = yield* makeCloudLinkProof(dependencies, request, requestUrl);
|
||||
yield* appendCloudCredentialResponseHeaders;
|
||||
return proof satisfies RelayEnvironmentLinkProof;
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthCloudLinkJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError("sign_cloud_link_jwt")(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
PlatformError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not generate environment link proof."),
|
||||
),
|
||||
Effect.catchTag(
|
||||
"PlatformError",
|
||||
failEnvironmentCloudInternalError("Could not generate environment link proof."),
|
||||
),
|
||||
);
|
||||
|
||||
const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* (
|
||||
@@ -565,6 +439,7 @@ const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(fu
|
||||
endpointRuntimeStatus.status === "disabled" || endpointRuntimeStatus.status === "running";
|
||||
if (!ok) {
|
||||
return yield* new EnvironmentCloudEndpointUnavailableError({
|
||||
message: "Managed endpoint runtime could not be started.",
|
||||
endpointRuntimeStatus,
|
||||
});
|
||||
}
|
||||
@@ -597,22 +472,22 @@ const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(
|
||||
yield* requireEnvironmentScope(AuthRelayWriteScope);
|
||||
return yield* applyCloudRelayConfig(dependencies, payload);
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthLinkedCloudAccountVerificationError: (error) =>
|
||||
failEnvironmentCloudInternalError("verify_linked_cloud_account")(error),
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"persist_relay_configuration",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
SchemaError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
|
||||
),
|
||||
Effect.catchTag(
|
||||
"SchemaError",
|
||||
failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
|
||||
),
|
||||
);
|
||||
|
||||
const relayClientRequest = <A>(
|
||||
dependencies: CloudHttpDependencies,
|
||||
input: {
|
||||
readonly operation: CloudRelayRequestError["operation"];
|
||||
readonly url: string;
|
||||
readonly token: string;
|
||||
readonly payload: unknown;
|
||||
@@ -622,46 +497,14 @@ const relayClientRequest = <A>(
|
||||
HttpClientRequest.post(input.url).pipe(
|
||||
HttpClientRequest.bearerToken(input.token),
|
||||
HttpClientRequest.bodyJson(input.payload),
|
||||
Effect.mapError((cause) =>
|
||||
CloudRelayRequestError.fromClientFailure({
|
||||
operation: input.operation,
|
||||
url: input.url,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((request) =>
|
||||
dependencies.httpClient.execute(request).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudRelayRequestError.fromClientFailure({
|
||||
operation: input.operation,
|
||||
url: input.url,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.flatMap((response) =>
|
||||
HttpClientResponse.filterStatusOk(response).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudRelayRequestError.fromClientFailure({
|
||||
operation: input.operation,
|
||||
url: input.url,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.flatMap((response) =>
|
||||
HttpClientResponse.schemaBodyJson(input.schema)(response).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudRelayRequestError.fromClientFailure({
|
||||
operation: input.operation,
|
||||
url: input.url,
|
||||
responseStatus: response.status,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.flatMap(dependencies.httpClient.execute),
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.flatMap(HttpClientResponse.schemaBodyJson(input.schema)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentHttpInternalServerError({
|
||||
message: `T3 Connect relay request failed: ${String(cause)}`,
|
||||
}),
|
||||
),
|
||||
withRelayClientTracing,
|
||||
);
|
||||
@@ -670,15 +513,14 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
function* (dependencies: CloudHttpDependencies, localOrigin: string) {
|
||||
const localUrl = yield* Effect.try({
|
||||
try: () => new URL(localOrigin),
|
||||
catch: (cause) =>
|
||||
catch: () =>
|
||||
new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_local_environment_origin",
|
||||
cause,
|
||||
message: "Could not resolve local environment origin.",
|
||||
}),
|
||||
});
|
||||
if (localUrl.origin !== localOrigin) {
|
||||
return yield* new EnvironmentHttpBadRequestError({
|
||||
reason: "invalid_local_environment_origin",
|
||||
message: "Could not resolve local environment origin.",
|
||||
});
|
||||
}
|
||||
const localWsOrigin = localOrigin.replace(/^http/u, "ws");
|
||||
@@ -688,7 +530,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new EnvironmentHttpUnauthorizedError({
|
||||
reason: "cloud_cli_authorization_required",
|
||||
message: "Run `t3 connect link` to authorize this environment.",
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
@@ -697,7 +539,6 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
);
|
||||
const relayUrl = yield* requireRelayUrl;
|
||||
const challenge = yield* relayClientRequest(dependencies, {
|
||||
operation: "create-link-challenge",
|
||||
url: `${relayUrl}/v1/client/environment-link-challenges`,
|
||||
token: token.accessToken,
|
||||
payload: {
|
||||
@@ -723,20 +564,8 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
},
|
||||
},
|
||||
localOrigin,
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
ServerAuthCloudLinkJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError("sign_cloud_link_jwt")(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
PlatformError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
}),
|
||||
);
|
||||
const link = yield* relayClientRequest(dependencies, {
|
||||
operation: "create-environment-link",
|
||||
url: `${relayUrl}/v1/client/environment-links`,
|
||||
token: token.accessToken,
|
||||
payload: {
|
||||
@@ -747,15 +576,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
},
|
||||
schema: RelayEnvironmentLinkResponse,
|
||||
});
|
||||
yield* setCliDesiredCloudLink(true).pipe(
|
||||
Effect.catchTags({
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"persist_desired_link_state",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("persist_desired_link_state"),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError("persist_desired_link_state"),
|
||||
}),
|
||||
);
|
||||
yield* setCliDesiredCloudLink(true);
|
||||
return yield* applyCloudRelayConfig(dependencies, {
|
||||
relayUrl,
|
||||
relayIssuer: link.relayIssuer,
|
||||
@@ -763,31 +584,18 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
environmentCredential: link.environmentCredential,
|
||||
cloudMintPublicKey: link.cloudMintPublicKey,
|
||||
endpointRuntime: link.endpointRuntime,
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
ServerAuthLinkedCloudAccountVerificationError: (error) =>
|
||||
failEnvironmentCloudInternalError("verify_linked_cloud_account")(error),
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"persist_relay_configuration",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
SchemaError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
}),
|
||||
);
|
||||
});
|
||||
},
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not persist desired T3 Connect link state."),
|
||||
),
|
||||
Effect.catchTags({
|
||||
CloudRelayConfigurationError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_relay_url_configuration")(error),
|
||||
CloudRelayRequestError: (error) =>
|
||||
failEnvironmentCloudInternalError({
|
||||
operation: "relay_request",
|
||||
relayOperation: error.operation,
|
||||
relayPhase: error.phase,
|
||||
...(error.responseStatus === undefined ? {} : { responseStatus: error.responseStatus }),
|
||||
})(error),
|
||||
CloudCliCredentialRefreshError: (error) =>
|
||||
failEnvironmentCloudInternalError("refresh_cloud_cli_credential")(error),
|
||||
CloudCliCredentialRemovalError: failCloudCliTokenManagerError,
|
||||
CloudCliCredentialRefreshError: failCloudCliTokenManagerError,
|
||||
CloudCliCredentialReadError: failCloudCliTokenManagerError,
|
||||
CloudCliAuthorizationError: failCloudCliTokenManagerError,
|
||||
CloudCliAuthorizationTimeoutError: failCloudCliTokenManagerError,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -825,9 +633,10 @@ const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
|
||||
yield* requireEnvironmentScope(AuthRelayReadScope);
|
||||
return yield* readCloudLinkState(dependencies);
|
||||
},
|
||||
Effect.catchTags({
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("read_relay_configuration"),
|
||||
}),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not read environment relay configuration."),
|
||||
),
|
||||
);
|
||||
|
||||
const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
|
||||
@@ -849,13 +658,10 @@ const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
|
||||
yield* setCliDesiredCloudLink(false);
|
||||
return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
|
||||
},
|
||||
Effect.catchTags({
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"remove_relay_configuration",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("remove_relay_configuration"),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError("remove_relay_configuration"),
|
||||
}),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not remove environment relay configuration."),
|
||||
),
|
||||
);
|
||||
|
||||
const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
|
||||
@@ -870,13 +676,10 @@ const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
|
||||
);
|
||||
return yield* readCloudLinkState(dependencies);
|
||||
},
|
||||
Effect.catchTags({
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("persist_cloud_preferences"),
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"persist_cloud_preferences",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("persist_cloud_preferences"),
|
||||
}),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
|
||||
),
|
||||
);
|
||||
|
||||
const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
@@ -927,7 +730,7 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
!hasExactScope({ scopes: proofOption.value.scope, expected: "environment:status" })
|
||||
) {
|
||||
return yield* new EnvironmentHttpUnauthorizedError({
|
||||
reason: "invalid_cloud_health_request",
|
||||
message: "Invalid cloud health request.",
|
||||
});
|
||||
}
|
||||
const proof = proofOption.value;
|
||||
@@ -941,7 +744,7 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
});
|
||||
if (!consumedReplayGuards) {
|
||||
return yield* new EnvironmentHttpConflictError({
|
||||
reason: "cloud_health_request_replayed",
|
||||
message: "Cloud health request was already consumed.",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -984,26 +787,17 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
yield* appendCloudCredentialResponseHeaders;
|
||||
return response;
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthLinkedCloudAccountReadError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_linked_cloud_account")(error),
|
||||
ServerAuthLinkedCloudAccountMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("require_linked_cloud_account")(error),
|
||||
ServerAuthCloudMintPublicKeyMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_cloud_mint_public_key")(error),
|
||||
ServerAuthCloudRelayIssuerMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_cloud_relay_issuer")(error),
|
||||
ServerAuthCloudHealthJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError("sign_cloud_health_jwt")(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
|
||||
"answer_cloud_health_request",
|
||||
),
|
||||
PlatformError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not answer cloud health request."),
|
||||
),
|
||||
Effect.catchTag(
|
||||
"PlatformError",
|
||||
failEnvironmentCloudInternalError("Could not answer cloud health request."),
|
||||
),
|
||||
);
|
||||
|
||||
const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")(
|
||||
@@ -1055,7 +849,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
|
||||
!hasExactScope({ scopes: proofOption.value.scope, expected: "environment:connect" })
|
||||
) {
|
||||
return yield* new EnvironmentHttpUnauthorizedError({
|
||||
reason: "invalid_cloud_mint_request",
|
||||
message: "Invalid cloud mint request.",
|
||||
});
|
||||
}
|
||||
const proof = proofOption.value;
|
||||
@@ -1069,7 +863,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
|
||||
});
|
||||
if (!consumedReplayGuards) {
|
||||
return yield* new EnvironmentHttpConflictError({
|
||||
reason: "cloud_mint_request_replayed",
|
||||
message: "Cloud mint request was already consumed.",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1114,28 +908,17 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
|
||||
yield* appendCloudCredentialResponseHeaders;
|
||||
return response;
|
||||
},
|
||||
Effect.catchTags({
|
||||
ServerAuthLinkedCloudAccountReadError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_linked_cloud_account")(error),
|
||||
ServerAuthLinkedCloudAccountMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("require_linked_cloud_account")(error),
|
||||
ServerAuthCloudMintPublicKeyMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_cloud_mint_public_key")(error),
|
||||
ServerAuthCloudRelayIssuerMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_cloud_relay_issuer")(error),
|
||||
ServerAuthPairingLinkCreationError: (error) =>
|
||||
failEnvironmentCloudInternalError("create_cloud_pairing_link")(error),
|
||||
ServerAuthCloudMintJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError("sign_cloud_mint_jwt")(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
|
||||
"issue_cloud_connection_credential",
|
||||
),
|
||||
PlatformError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
}),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
|
||||
),
|
||||
Effect.catchTag(
|
||||
"PlatformError",
|
||||
failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
|
||||
),
|
||||
);
|
||||
|
||||
export const connectHttpApiLayer = HttpApiBuilder.group(
|
||||
|
||||
@@ -3,10 +3,8 @@ import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
|
||||
import * as TraceDiagnostics from "./TraceDiagnostics.ts";
|
||||
|
||||
@@ -189,17 +187,18 @@ describe("TraceDiagnostics", () => {
|
||||
it.effect("keeps loaded trace data when one rotated trace file fails to read", () =>
|
||||
Effect.gen(function* () {
|
||||
const traceFilePath = "/tmp/server.trace.ndjson";
|
||||
const readFailure = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
description: "permission denied",
|
||||
pathOrDescriptor: `${traceFilePath}.1`,
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
readFileString: (path) =>
|
||||
path === `${traceFilePath}.1`
|
||||
? Effect.fail(readFailure)
|
||||
? Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
description: "permission denied",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(
|
||||
record({
|
||||
name: "server.getConfig",
|
||||
@@ -210,44 +209,20 @@ describe("TraceDiagnostics", () => {
|
||||
}),
|
||||
),
|
||||
});
|
||||
const logAnnotations: Array<Record<string, unknown>> = [];
|
||||
const logger = Logger.make<unknown, void>((options) => {
|
||||
logAnnotations.push({ ...options.fiber.getRef(References.CurrentLogAnnotations) });
|
||||
});
|
||||
|
||||
const diagnostics = yield* TraceDiagnostics.readTraceDiagnostics({
|
||||
traceFilePath,
|
||||
maxFiles: 1,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
TraceDiagnostics.layer.pipe(Layer.provide(fileSystemLayer)),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.provide(TraceDiagnostics.layer.pipe(Layer.provide(fileSystemLayer))));
|
||||
|
||||
assert.equal(diagnostics.recordCount, 1);
|
||||
assert.equal(
|
||||
Option.getOrElse(diagnostics.partialFailure, () => false),
|
||||
true,
|
||||
);
|
||||
assert.deepStrictEqual(Option.getOrUndefined(diagnostics.error), {
|
||||
kind: "trace-file-read-failed",
|
||||
message: `Failed to read local trace file '${traceFilePath}.1'.`,
|
||||
});
|
||||
assert.equal(Option.getOrUndefined(diagnostics.error)?.kind, "trace-file-read-failed");
|
||||
assert.deepStrictEqual(diagnostics.scannedFilePaths, [`${traceFilePath}.1`, traceFilePath]);
|
||||
|
||||
const failureLog = logAnnotations.find(
|
||||
(annotations) => annotations.traceFilePath === `${traceFilePath}.1`,
|
||||
);
|
||||
assert.exists(failureLog);
|
||||
assert.deepStrictEqual(failureLog, {
|
||||
traceFilePath: `${traceFilePath}.1`,
|
||||
errorTag: "TraceFileReadError",
|
||||
causeTag: "PermissionDenied",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -14,8 +14,6 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
interface TraceRecordLike {
|
||||
readonly name?: unknown;
|
||||
@@ -41,19 +39,6 @@ export interface TraceDiagnosticsOptions {
|
||||
readonly readAt?: DateTime.Utc;
|
||||
}
|
||||
|
||||
export class TraceFileReadError extends Schema.TaggedErrorClass<TraceFileReadError>()(
|
||||
"TraceFileReadError",
|
||||
{
|
||||
traceFilePath: Schema.String,
|
||||
causeTag: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read local trace file '${this.traceFilePath}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class TraceDiagnostics extends Context.Service<
|
||||
TraceDiagnostics,
|
||||
{
|
||||
@@ -168,6 +153,10 @@ function isNotFoundError(error: PlatformError.PlatformError): boolean {
|
||||
return error.reason._tag === "NotFound";
|
||||
}
|
||||
|
||||
function platformErrorMessage(error: PlatformError.PlatformError): string {
|
||||
return error.message || String(error);
|
||||
}
|
||||
|
||||
function insertBoundedSlowestSpan(
|
||||
slowestSpans: ServerTraceDiagnosticsSpanOccurrence[],
|
||||
span: ServerTraceDiagnosticsSpanOccurrence,
|
||||
@@ -388,26 +377,22 @@ export function aggregateTraceDiagnostics(
|
||||
|
||||
type TraceFileReadResult =
|
||||
| { readonly _tag: "Loaded"; readonly path: string; readonly text: string }
|
||||
| { readonly _tag: "Missing"; readonly path: string };
|
||||
| { readonly _tag: "Missing"; readonly path: string }
|
||||
| { readonly _tag: "Failed"; readonly path: string; readonly message: string };
|
||||
|
||||
function readTraceFile(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
path: string,
|
||||
): Effect.Effect<TraceFileReadResult, TraceFileReadError> {
|
||||
): Effect.Effect<TraceFileReadResult> {
|
||||
return fileSystem.readFileString(path).pipe(
|
||||
Effect.map((text): TraceFileReadResult => ({ _tag: "Loaded", path, text })),
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
isNotFoundError(cause)
|
||||
? Effect.succeed<TraceFileReadResult>({ _tag: "Missing", path })
|
||||
: Effect.fail(
|
||||
new TraceFileReadError({
|
||||
traceFilePath: path,
|
||||
causeTag: cause.reason._tag,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
Effect.map((text) => ({ _tag: "Loaded" as const, path, text })),
|
||||
Effect.catch((error: PlatformError.PlatformError) =>
|
||||
Effect.succeed(
|
||||
isNotFoundError(error)
|
||||
? { _tag: "Missing" as const, path }
|
||||
: { _tag: "Failed" as const, path, message: platformErrorMessage(error) },
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -420,34 +405,19 @@ export const make = Effect.gen(function* () {
|
||||
const slowSpanThresholdMs = options.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
|
||||
const paths = toRotatedTracePaths(options.traceFilePath, options.maxFiles);
|
||||
const results = yield* Effect.all(
|
||||
paths.map((path) =>
|
||||
readTraceFile(fileSystem, path).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logWarning("Failed to read local trace file.").pipe(
|
||||
Effect.annotateLogs({
|
||||
traceFilePath: cause.traceFilePath,
|
||||
errorTag: cause._tag,
|
||||
causeTag: cause.causeTag,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.result,
|
||||
),
|
||||
),
|
||||
paths.map((path) => readTraceFile(fileSystem, path)),
|
||||
{
|
||||
concurrency: 1,
|
||||
},
|
||||
);
|
||||
const files = results.flatMap((result) =>
|
||||
Result.isSuccess(result) && result.success._tag === "Loaded"
|
||||
? [{ path: result.success.path, text: result.success.text }]
|
||||
: [],
|
||||
result._tag === "Loaded" ? [{ path: result.path, text: result.text }] : [],
|
||||
);
|
||||
const readFailure = results.find(Result.isFailure);
|
||||
const readFailure = results.find((result) => result._tag === "Failed");
|
||||
const readFailureError = readFailure
|
||||
? ({
|
||||
kind: "trace-file-read-failed",
|
||||
message: readFailure.failure.message,
|
||||
message: readFailure.message.trim() || `Failed to read ${readFailure.path}.`,
|
||||
} satisfies TraceDiagnosticsErrorSummary)
|
||||
: undefined;
|
||||
|
||||
|
||||
@@ -2,28 +2,12 @@ import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HostProcessHostname, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import * as ServerEnvironmentLabel from "./ServerEnvironmentLabel.ts";
|
||||
|
||||
const isServerEnvironmentLabelFileError = Schema.is(
|
||||
ServerEnvironmentLabel.ServerEnvironmentLabelFileError,
|
||||
);
|
||||
const isServerEnvironmentLabelCommandError = Schema.is(
|
||||
ServerEnvironmentLabel.ServerEnvironmentLabelCommandError,
|
||||
);
|
||||
|
||||
interface CapturedLog {
|
||||
readonly message: unknown;
|
||||
readonly annotations: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
|
||||
const runMock = vi.fn<ProcessRunner.ProcessRunner["Service"]["run"]>();
|
||||
|
||||
@@ -63,7 +47,7 @@ afterEach(() => {
|
||||
describe("resolveServerEnvironmentLabel", () => {
|
||||
it.effect("uses hostname fallback regardless of launch mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
}).pipe(Effect.provide(withHostPlatform(TestLayer, "win32", "macbook-pro")));
|
||||
|
||||
@@ -84,7 +68,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
}).pipe(Effect.provide(withHostPlatform(TestLayer, "darwin", "macbook-pro")));
|
||||
|
||||
@@ -101,7 +85,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
|
||||
it.effect("prefers Linux PRETTY_HOSTNAME from machine-info", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
}).pipe(Effect.provide(withHostPlatform(LinuxMachineInfoLayer, "linux", "buildbox")));
|
||||
|
||||
@@ -123,7 +107,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
}).pipe(Effect.provide(withHostPlatform(TestLayer, "linux", "runner-01")));
|
||||
|
||||
@@ -140,7 +124,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
|
||||
it.effect("falls back to the hostname when friendly labels are unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
}).pipe(Effect.provide(withHostPlatform(TestLayer, "win32", "JULIUS-LAPTOP")));
|
||||
|
||||
@@ -148,111 +132,25 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to the hostname when the friendly-label command is missing", () => {
|
||||
const logs: CapturedLog[] = [];
|
||||
const logger = Logger.make(({ fiber, message }) => {
|
||||
logs.push({
|
||||
message,
|
||||
annotations: fiber.getRef(References.CurrentLogAnnotations),
|
||||
});
|
||||
});
|
||||
const spawnCause = new Error("spawn scutil ENOENT");
|
||||
const processError = new ProcessRunner.ProcessSpawnError({
|
||||
command: "scutil",
|
||||
argumentCount: 2,
|
||||
cause: spawnCause,
|
||||
});
|
||||
runMock.mockReturnValueOnce(Effect.fail(processError));
|
||||
it.effect("falls back to the hostname when the friendly-label command is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
runMock.mockReturnValueOnce(
|
||||
Effect.fail(
|
||||
new ProcessRunner.ProcessSpawnError({
|
||||
command: "scutil",
|
||||
argumentCount: 2,
|
||||
cause: new Error("spawn scutil ENOENT"),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
});
|
||||
}).pipe(Effect.provide(withHostPlatform(TestLayer, "darwin", "macbook-pro")));
|
||||
|
||||
expect(result).toBe("macbook-pro");
|
||||
expect(logs[0]?.message).toEqual([
|
||||
"Failed to run environment-label probe 'macos-computer-name' with scutil.",
|
||||
]);
|
||||
const error = logs[0]?.annotations.cause;
|
||||
expect(isServerEnvironmentLabelCommandError(error)).toBe(true);
|
||||
if (isServerEnvironmentLabelCommandError(error)) {
|
||||
expect(error.probe).toBe("macos-computer-name");
|
||||
expect(error.executable).toBe("scutil");
|
||||
expect(error.argumentCount).toBe(2);
|
||||
expect(error).not.toHaveProperty("args");
|
||||
expect(error.message).not.toContain("--get");
|
||||
expect(error.message).not.toContain("ComputerName");
|
||||
expect(error.cause).toBe(processError);
|
||||
expect(processError.cause).toBe(spawnCause);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
withHostPlatform(TestLayer, "darwin", "macbook-pro"),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
Layer.succeed(References.MinimumLogLevel, "Debug"),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("continues to hostnamectl after a machine-info inspect failure", () => {
|
||||
const logs: CapturedLog[] = [];
|
||||
const logger = Logger.make(({ fiber, message }) => {
|
||||
logs.push({
|
||||
message,
|
||||
annotations: fiber.getRef(References.CurrentLogAnnotations),
|
||||
});
|
||||
});
|
||||
const fileCause = new Error("permission denied");
|
||||
const platformError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "exists",
|
||||
pathOrDescriptor: "/etc/machine-info",
|
||||
cause: fileCause,
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
exists: () => Effect.fail(platformError),
|
||||
});
|
||||
runMock.mockReturnValueOnce(
|
||||
Effect.succeed({
|
||||
stdout: "CI Runner\n",
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
});
|
||||
|
||||
expect(result).toBe("CI Runner");
|
||||
expect(logs[0]?.message).toEqual([
|
||||
"Failed to inspect environment-label file at /etc/machine-info.",
|
||||
]);
|
||||
const error = logs[0]?.annotations.cause;
|
||||
expect(isServerEnvironmentLabelFileError(error)).toBe(true);
|
||||
if (isServerEnvironmentLabelFileError(error)) {
|
||||
expect(error.operation).toBe("inspect");
|
||||
expect(error.path).toBe("/etc/machine-info");
|
||||
expect(error.cause).toBe(platformError);
|
||||
expect(platformError.cause).toBe(fileCause);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
withHostPlatform(Layer.merge(ProcessRunnerTest, fileSystemLayer), "linux", "buildbox"),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
Layer.succeed(References.MinimumLogLevel, "Debug"),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to the cwd basename when the hostname is blank", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -267,7 +165,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
}).pipe(Effect.provide(withHostPlatform(TestLayer, "linux", " ")));
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ import { HostProcessHostname, HostProcessPlatform } from "@t3tools/shared/hostPr
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
|
||||
@@ -10,39 +9,6 @@ interface ResolveServerEnvironmentLabelInput {
|
||||
readonly cwdBaseName: string;
|
||||
}
|
||||
|
||||
const ServerEnvironmentLabelCommandProbe = Schema.Literals([
|
||||
"macos-computer-name",
|
||||
"linux-pretty-hostname",
|
||||
]);
|
||||
type ServerEnvironmentLabelCommandProbe = typeof ServerEnvironmentLabelCommandProbe.Type;
|
||||
|
||||
export class ServerEnvironmentLabelFileError extends Schema.TaggedErrorClass<ServerEnvironmentLabelFileError>()(
|
||||
"ServerEnvironmentLabelFileError",
|
||||
{
|
||||
operation: Schema.Literals(["inspect", "read"]),
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to ${this.operation} environment-label file at ${this.path}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerEnvironmentLabelCommandError extends Schema.TaggedErrorClass<ServerEnvironmentLabelCommandError>()(
|
||||
"ServerEnvironmentLabelCommandError",
|
||||
{
|
||||
probe: ServerEnvironmentLabelCommandProbe,
|
||||
executable: Schema.String,
|
||||
argumentCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to run environment-label probe '${this.probe}' with ${this.executable}.`;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeLabel(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed && trimmed.length > 0 ? trimmed : null;
|
||||
@@ -68,80 +34,30 @@ function parseMachineInfoValue(raw: string, key: string): string | null {
|
||||
|
||||
const readLinuxMachineInfo = Effect.fn("readLinuxMachineInfo")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const machineInfoPath = "/etc/machine-info";
|
||||
return yield* fileSystem.exists(machineInfoPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerEnvironmentLabelFileError({
|
||||
operation: "inspect",
|
||||
path: machineInfoPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((exists) =>
|
||||
exists
|
||||
? fileSystem.readFileString(machineInfoPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerEnvironmentLabelFileError({
|
||||
operation: "read",
|
||||
path: machineInfoPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.succeed(null),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerEnvironmentLabelFileError: (error) =>
|
||||
Effect.logDebug(error.message).pipe(
|
||||
Effect.annotateLogs({
|
||||
operation: error.operation,
|
||||
path: error.path,
|
||||
cause: error,
|
||||
}),
|
||||
Effect.as(null),
|
||||
),
|
||||
}),
|
||||
);
|
||||
const exists = yield* fileSystem
|
||||
.exists("/etc/machine-info")
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return yield* fileSystem
|
||||
.readFileString("/etc/machine-info")
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
});
|
||||
|
||||
const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (input: {
|
||||
readonly probe: ServerEnvironmentLabelCommandProbe;
|
||||
readonly command: string;
|
||||
readonly args: readonly string[];
|
||||
}) {
|
||||
const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
) {
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
const result = yield* processRunner
|
||||
.run({
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
command,
|
||||
args,
|
||||
timeoutBehavior: "timedOutResult",
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerEnvironmentLabelCommandError({
|
||||
probe: input.probe,
|
||||
executable: input.command,
|
||||
argumentCount: input.args.length,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
ServerEnvironmentLabelCommandError: (error) =>
|
||||
Effect.logDebug(error.message).pipe(
|
||||
Effect.annotateLogs({
|
||||
probe: error.probe,
|
||||
executable: error.executable,
|
||||
argumentCount: error.argumentCount,
|
||||
cause: error,
|
||||
}),
|
||||
Effect.as(Option.none()),
|
||||
),
|
||||
}),
|
||||
);
|
||||
.pipe(Effect.option);
|
||||
|
||||
if (Option.isNone(result) || result.value.code !== 0) {
|
||||
return null;
|
||||
@@ -153,11 +69,7 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
|
||||
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
if (platform === "darwin") {
|
||||
return yield* runFriendlyLabelCommand({
|
||||
probe: "macos-computer-name",
|
||||
command: "scutil",
|
||||
args: ["--get", "ComputerName"],
|
||||
});
|
||||
return yield* runFriendlyLabelCommand("scutil", ["--get", "ComputerName"]);
|
||||
}
|
||||
|
||||
if (platform === "linux") {
|
||||
@@ -169,11 +81,7 @@ const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function*
|
||||
}
|
||||
}
|
||||
|
||||
return yield* runFriendlyLabelCommand({
|
||||
probe: "linux-pretty-hostname",
|
||||
command: "hostnamectl",
|
||||
args: ["--pretty"],
|
||||
});
|
||||
return yield* runFriendlyLabelCommand("hostnamectl", ["--pretty"]);
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -171,8 +171,20 @@ function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
|
||||
if (result.status === 0) {
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
`Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
|
||||
throw new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd,
|
||||
detail: `Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
|
||||
});
|
||||
}
|
||||
|
||||
function isGitHubCliError(error: unknown): error is GitHubCli.GitHubCliError {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
(error as { _tag?: unknown })._tag === "GitHubCliError"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -466,12 +478,16 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
return fakeGhOutput("");
|
||||
},
|
||||
catch: (error) =>
|
||||
GitHubCli.isGitHubCliError(error)
|
||||
isGitHubCliError(error)
|
||||
? error
|
||||
: new GitHubCli.GitHubCliCommandError({
|
||||
: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: error,
|
||||
detail:
|
||||
error instanceof Error
|
||||
? `Failed to simulate gh checkout: ${error.message}`
|
||||
: "Failed to simulate gh checkout.",
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -482,10 +498,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
const cloneUrls = scenario.repositoryCloneUrls?.[repository];
|
||||
if (!cloneUrls) {
|
||||
return Effect.fail(
|
||||
new GitHubCli.GitHubCliCommandError({
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: new Error(`Unexpected repository lookup: ${repository}`),
|
||||
detail: `Unexpected repository lookup: ${repository}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -503,10 +520,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}
|
||||
|
||||
return Effect.fail(
|
||||
new GitHubCli.GitHubCliCommandError({
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: new Error(`Unexpected gh command: ${args.join(" ")}`),
|
||||
detail: `Unexpected gh command: ${args.join(" ")}`,
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -583,10 +601,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
|
||||
createRepository: (input) =>
|
||||
Effect.fail(
|
||||
new GitHubCli.GitHubCliCommandError({
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "createRepository",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: new Error(`Unexpected repository create: ${input.repository}`),
|
||||
detail: `Unexpected repository create: ${input.repository}`,
|
||||
}),
|
||||
),
|
||||
checkoutPullRequest: (input) =>
|
||||
@@ -1322,10 +1341,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("gh is not available on PATH"),
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -1569,18 +1589,16 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* initRepo(repoDir);
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const error = yield* runStackedAction(manager, {
|
||||
const errorMessage = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
featureBranch: true,
|
||||
}).pipe(Effect.flip);
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => error.message),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "GitManagerError",
|
||||
operation: "runFeatureBranchStep",
|
||||
cwd: repoDir,
|
||||
});
|
||||
expect(error.message).toContain("no changes to commit");
|
||||
expect(errorMessage).toContain("no changes to commit");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -2463,10 +2481,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("gh is not available on PATH"),
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -2493,10 +2512,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliAuthenticationError({
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("gh is not authenticated"),
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -2735,65 +2755,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves both branch materialization failures when the fallback also fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const originDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
|
||||
const missingForkDir = NodePath.join(repoDir, "missing-fork.git");
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 93,
|
||||
title: "Missing fork branch",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/93",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/missing-fork-branch",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
},
|
||||
repositoryCloneUrls: {
|
||||
"octocat/codething-mvp": {
|
||||
url: missingForkDir,
|
||||
sshUrl: missingForkDir,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const error = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "93",
|
||||
mode: "worktree",
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
if (error._tag !== "GitPullRequestMaterializationError") {
|
||||
return yield* Effect.die(error);
|
||||
}
|
||||
expect(error).toMatchObject({
|
||||
cwd: repoDir,
|
||||
pullRequestNumber: 93,
|
||||
headRepository: "octocat/codething-mvp",
|
||||
headBranch: "feature/missing-fork-branch",
|
||||
localBranch: "t3code/pr-93/feature/missing-fork-branch",
|
||||
});
|
||||
if (!(error.cause instanceof AggregateError)) {
|
||||
return yield* Effect.die(error.cause);
|
||||
}
|
||||
expect(error.cause.errors).toHaveLength(2);
|
||||
expect(error.cause.errors).toEqual([
|
||||
expect.objectContaining({ _tag: "GitCommandError" }),
|
||||
expect.objectContaining({ _tag: "GitCommandError" }),
|
||||
]);
|
||||
expect(error.cause.cause).toBe(error.cause.errors[0]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("launches setup only when creating a new PR worktree", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
|
||||
@@ -41,7 +41,7 @@ import {
|
||||
type ChangeRequestTerminology,
|
||||
} from "@t3tools/shared/sourceControl";
|
||||
|
||||
import { GitManagerError, GitPullRequestMaterializationError } from "@t3tools/contracts";
|
||||
import { GitManagerError } from "@t3tools/contracts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
|
||||
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
|
||||
@@ -320,6 +320,14 @@ function toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {
|
||||
};
|
||||
}
|
||||
|
||||
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
|
||||
return new GitManagerError({
|
||||
operation,
|
||||
detail,
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function limitContext(value: string, maxChars: number): string {
|
||||
if (value.length <= maxChars) return value;
|
||||
return `${value.slice(0, maxChars)}\n\n[truncated]`;
|
||||
@@ -527,27 +535,17 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
|
||||
const serverSettingsService = yield* ServerSettings.ServerSettingsService;
|
||||
const randomUUIDv4 = (cwd: string) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitManagerError({
|
||||
operation: "randomUUIDv4",
|
||||
cwd,
|
||||
detail: "Failed to generate Git operation identifier.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
gitManagerError("randomUUIDv4", "Failed to generate Git operation identifier.", cause),
|
||||
),
|
||||
);
|
||||
|
||||
const createProgressEmitter = (
|
||||
input: { cwd: string; action: GitStackedAction },
|
||||
options?: GitRunStackedActionOptions,
|
||||
) =>
|
||||
(options?.actionId === undefined
|
||||
? randomUUIDv4(input.cwd)
|
||||
: Effect.succeed(options.actionId)
|
||||
).pipe(
|
||||
(options?.actionId === undefined ? randomUUIDv4 : Effect.succeed(options.actionId)).pipe(
|
||||
Effect.map((actionId) => {
|
||||
const reporter = options?.progressReporter;
|
||||
const emit = (event: GitActionProgressPayload) =>
|
||||
@@ -631,12 +629,9 @@ export const make = Effect.gen(function* () {
|
||||
) =>
|
||||
configurePullRequestHeadUpstreamBase(cwd, pullRequest, localBranch).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("GitManager.configurePullRequestHeadUpstream failed", {
|
||||
cwd,
|
||||
localBranch,
|
||||
headBranch: pullRequest.headBranch,
|
||||
cause: error,
|
||||
}).pipe(Effect.asVoid),
|
||||
Effect.logWarning(
|
||||
`GitManager.configurePullRequestHeadUpstream: failed to configure upstream for ${localBranch} -> ${pullRequest.headBranch} in ${cwd}: ${error.message}`,
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -694,30 +689,12 @@ export const make = Effect.gen(function* () {
|
||||
localBranch = pullRequest.headBranch,
|
||||
) =>
|
||||
materializePullRequestHeadBranchBase(cwd, pullRequest, localBranch).pipe(
|
||||
Effect.catch((primaryCause) =>
|
||||
gitCore
|
||||
.fetchPullRequestBranch({
|
||||
cwd,
|
||||
prNumber: pullRequest.number,
|
||||
branch: localBranch,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(fallbackCause) =>
|
||||
new GitPullRequestMaterializationError({
|
||||
cwd,
|
||||
pullRequestNumber: pullRequest.number,
|
||||
headRepository: resolveHeadRepositoryNameWithOwner(pullRequest),
|
||||
headBranch: pullRequest.headBranch,
|
||||
localBranch,
|
||||
cause: new AggregateError(
|
||||
[primaryCause, fallbackCause],
|
||||
`Repository-head and pull-request-ref fetches both failed for pull request #${pullRequest.number}.`,
|
||||
{ cause: primaryCause },
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catch(() =>
|
||||
gitCore.fetchPullRequestBranch({
|
||||
cwd,
|
||||
prNumber: pullRequest.number,
|
||||
branch: localBranch,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -1307,18 +1284,16 @@ export const make = Effect.gen(function* () {
|
||||
const details = yield* gitCore.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
if (!branch) {
|
||||
return yield* new GitManagerError({
|
||||
operation: "runPrStep",
|
||||
cwd,
|
||||
detail: "Cannot create a pull request from detached HEAD.",
|
||||
});
|
||||
return yield* gitManagerError(
|
||||
"runPrStep",
|
||||
"Cannot create a pull request from detached HEAD.",
|
||||
);
|
||||
}
|
||||
if (!details.hasUpstream) {
|
||||
return yield* new GitManagerError({
|
||||
operation: "runPrStep",
|
||||
cwd,
|
||||
detail: "Current branch has not been pushed. Push before creating a PR.",
|
||||
});
|
||||
return yield* gitManagerError(
|
||||
"runPrStep",
|
||||
"Current branch has not been pushed. Push before creating a PR.",
|
||||
);
|
||||
}
|
||||
|
||||
const headContext = yield* resolveBranchHeadContext(cwd, {
|
||||
@@ -1357,21 +1332,14 @@ export const make = Effect.gen(function* () {
|
||||
modelSelection,
|
||||
});
|
||||
|
||||
const bodyFile = path.join(
|
||||
tempDir,
|
||||
`t3code-pr-body-${process.pid}-${yield* randomUUIDv4(cwd)}.md`,
|
||||
);
|
||||
yield* fileSystem.writeFileString(bodyFile, generated.body).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitManagerError({
|
||||
operation: "runPrStep",
|
||||
cwd,
|
||||
detail: "Failed to write pull request body temp file.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${yield* randomUUIDv4}.md`);
|
||||
yield* fileSystem
|
||||
.writeFileString(bodyFile, generated.body)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause),
|
||||
),
|
||||
);
|
||||
yield* emit({
|
||||
kind: "phase_started",
|
||||
phase: "pr",
|
||||
@@ -1473,11 +1441,9 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("GitManager.preparePullRequestThread setup script failed", {
|
||||
threadId: input.threadId,
|
||||
worktreePath,
|
||||
cause: error,
|
||||
}).pipe(Effect.asVoid),
|
||||
Effect.logWarning(
|
||||
`GitManager.preparePullRequestThread: failed to launch worktree setup script for thread ${input.threadId} in ${worktreePath}: ${error.message}`,
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -1575,12 +1541,10 @@ export const make = Effect.gen(function* () {
|
||||
};
|
||||
}
|
||||
if (existingBranchBeforeFetchPath === rootWorktreePath) {
|
||||
return yield* new GitManagerError({
|
||||
operation: "preparePullRequestThread",
|
||||
cwd: input.cwd,
|
||||
detail:
|
||||
"This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
|
||||
});
|
||||
return yield* gitManagerError(
|
||||
"preparePullRequestThread",
|
||||
"This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
|
||||
);
|
||||
}
|
||||
|
||||
yield* materializePullRequestHeadBranch(
|
||||
@@ -1605,12 +1569,10 @@ export const make = Effect.gen(function* () {
|
||||
};
|
||||
}
|
||||
if (existingBranchAfterFetchPath === rootWorktreePath) {
|
||||
return yield* new GitManagerError({
|
||||
operation: "preparePullRequestThread",
|
||||
cwd: input.cwd,
|
||||
detail:
|
||||
"This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
|
||||
});
|
||||
return yield* gitManagerError(
|
||||
"preparePullRequestThread",
|
||||
"This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
|
||||
);
|
||||
}
|
||||
|
||||
const worktree = yield* gitCore.createWorktree({
|
||||
@@ -1645,11 +1607,10 @@ export const make = Effect.gen(function* () {
|
||||
modelSelection,
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* new GitManagerError({
|
||||
operation: "runFeatureBranchStep",
|
||||
cwd,
|
||||
detail: "Cannot create a feature branch because there are no changes to commit.",
|
||||
});
|
||||
return yield* gitManagerError(
|
||||
"runFeatureBranchStep",
|
||||
"Cannot create a feature branch because there are no changes to commit.",
|
||||
);
|
||||
}
|
||||
|
||||
const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);
|
||||
@@ -1686,18 +1647,16 @@ export const make = Effect.gen(function* () {
|
||||
const wantsPr = input.action === "create_pr" || input.action === "commit_push_pr";
|
||||
|
||||
if (input.featureBranch && !wantsCommit) {
|
||||
return yield* new GitManagerError({
|
||||
operation: "runStackedAction",
|
||||
cwd: input.cwd,
|
||||
detail: "Feature-branch checkout is only supported for commit actions.",
|
||||
});
|
||||
return yield* gitManagerError(
|
||||
"runStackedAction",
|
||||
"Feature-branch checkout is only supported for commit actions.",
|
||||
);
|
||||
}
|
||||
if (input.action === "create_pr" && initialStatus.hasWorkingTreeChanges) {
|
||||
return yield* new GitManagerError({
|
||||
operation: "runStackedAction",
|
||||
cwd: input.cwd,
|
||||
detail: "Commit local changes before creating a PR.",
|
||||
});
|
||||
return yield* gitManagerError(
|
||||
"runStackedAction",
|
||||
"Commit local changes before creating a PR.",
|
||||
);
|
||||
}
|
||||
|
||||
const phases: GitActionProgressPhase[] = [
|
||||
@@ -1713,18 +1672,13 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
|
||||
return yield* new GitManagerError({
|
||||
operation: "runStackedAction",
|
||||
cwd: input.cwd,
|
||||
detail: "Cannot push from detached HEAD.",
|
||||
});
|
||||
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
|
||||
}
|
||||
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
|
||||
return yield* new GitManagerError({
|
||||
operation: "runStackedAction",
|
||||
cwd: input.cwd,
|
||||
detail: "Cannot create a pull request from detached HEAD.",
|
||||
});
|
||||
return yield* gitManagerError(
|
||||
"runStackedAction",
|
||||
"Cannot create a pull request from detached HEAD.",
|
||||
);
|
||||
}
|
||||
|
||||
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
|
||||
@@ -1733,14 +1687,8 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const modelSelection = yield* serverSettingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.textGenerationModelSelection),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitManagerError({
|
||||
operation: "runStackedAction",
|
||||
cwd: input.cwd,
|
||||
detail: "Failed to get server settings.",
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
gitManagerError("runStackedAction", "Failed to get server settings.", cause),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { assert, describe, expect, it, vi } from "@effect/vitest";
|
||||
import { assert, describe, it, vi } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { VcsRepositoryDetectionError } from "@t3tools/contracts";
|
||||
|
||||
import * as GitManager from "./GitManager.ts";
|
||||
import * as GitWorkflowService from "./GitWorkflowService.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
@@ -134,59 +132,4 @@ describe("GitWorkflowService", () => {
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("structures workflow detection failures without exposing upstream details", () => {
|
||||
const cause = new VcsRepositoryDetectionError({
|
||||
operation: "VcsDriverRegistry.detect",
|
||||
cwd: "/repo",
|
||||
detail: "upstream detail must stay in the cause chain",
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
const error = yield* workflow.status({ cwd: "/repo" }).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "GitManagerError",
|
||||
operation: "GitWorkflowService.status",
|
||||
cwd: "/repo",
|
||||
detail: "Failed to detect a VCS repository for this Git workflow.",
|
||||
});
|
||||
expect(error.message).not.toContain(cause.detail);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
detect: () => Effect.fail(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("structures command detection failures without exposing upstream details", () => {
|
||||
const cause = new VcsRepositoryDetectionError({
|
||||
operation: "VcsDriverRegistry.detect",
|
||||
cwd: "/repo",
|
||||
detail: "upstream command detail must stay in the cause chain",
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
const error = yield* workflow.listRefs({ cwd: "/repo" }).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "GitCommandError",
|
||||
operation: "GitWorkflowService.listRefs",
|
||||
command: "vcs-route",
|
||||
cwd: "/repo",
|
||||
detail: "Failed to detect a VCS repository for this Git command.",
|
||||
});
|
||||
expect(error.message).not.toContain(cause.detail);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
detect: () => Effect.fail(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 285 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user