Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6693a8816 | ||
|
|
be56fa43b0 | ||
|
|
eb5eb0d9fa | ||
|
|
621616268a | ||
|
|
630df6b986 | ||
|
|
569b3e5959 | ||
|
|
d7ff7e7333 | ||
|
|
bd8e3ee008 | ||
|
|
c1d8a22f07 | ||
|
|
7b791895ad | ||
|
|
4c16c66368 | ||
|
|
4407a5a6b7 | ||
|
|
c7b375e9b0 | ||
|
|
abc253d97d | ||
|
|
ce11e6facd |
No files matched your search
@@ -393,7 +393,21 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
|
||||
yield* Ref.set(failDecrypt, true);
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
|
||||
);
|
||||
assert.equal(error.operation, "decrypt-catalog");
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
|
||||
assert.instanceOf(decryptError.cause, Error);
|
||||
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, decryptError.message);
|
||||
yield* Ref.set(failDecrypt, false);
|
||||
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
|
||||
@@ -53,8 +53,6 @@ const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
|
||||
"write-temporary-file",
|
||||
"replace-catalog-file",
|
||||
]);
|
||||
type DesktopConnectionCatalogStoreWriteOperation =
|
||||
typeof DesktopConnectionCatalogStoreWriteOperation.Type;
|
||||
|
||||
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
|
||||
"read-legacy-registry",
|
||||
@@ -62,8 +60,12 @@ const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
|
||||
"encode-catalog",
|
||||
"persist-catalog",
|
||||
]);
|
||||
type DesktopConnectionCatalogStoreMigrationOperation =
|
||||
typeof DesktopConnectionCatalogStoreMigrationOperation.Type;
|
||||
|
||||
const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
|
||||
"check-encryption-availability",
|
||||
"encrypt-catalog",
|
||||
"decrypt-catalog",
|
||||
]);
|
||||
|
||||
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
|
||||
"DesktopConnectionCatalogStoreWriteError",
|
||||
@@ -78,17 +80,6 @@ export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorC
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopConnectionCatalogStoreWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopConnectionCatalogStoreWriteError =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation,
|
||||
path,
|
||||
cause,
|
||||
});
|
||||
|
||||
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
|
||||
"DesktopConnectionCatalogStoreDecodeError",
|
||||
{
|
||||
@@ -142,18 +133,18 @@ export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedEr
|
||||
}
|
||||
}
|
||||
|
||||
const migrationError = (
|
||||
operation: DesktopConnectionCatalogStoreMigrationOperation,
|
||||
catalogPath: string,
|
||||
cause: unknown,
|
||||
environmentId?: string,
|
||||
): DesktopConnectionCatalogStoreMigrationError =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation,
|
||||
catalogPath,
|
||||
...(environmentId === undefined ? {} : { environmentId }),
|
||||
cause,
|
||||
});
|
||||
export class DesktopConnectionCatalogStoreProtectionError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreProtectionError>()(
|
||||
"DesktopConnectionCatalogStoreProtectionError",
|
||||
{
|
||||
operation: DesktopConnectionCatalogStoreProtectionOperation,
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop connection catalog protection failed during ${this.operation} at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStore extends Context.Service<
|
||||
DesktopConnectionCatalogStore,
|
||||
@@ -164,13 +155,13 @@ export class DesktopConnectionCatalogStore extends Context.Service<
|
||||
| DesktopConnectionCatalogStoreDocumentDecodeError
|
||||
| DesktopConnectionCatalogStoreDecodeError
|
||||
| DesktopConnectionCatalogStoreMigrationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageError
|
||||
| DesktopConnectionCatalogStoreProtectionError
|
||||
>;
|
||||
readonly set: (
|
||||
catalog: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
DesktopConnectionCatalogStoreWriteError | ElectronSafeStorage.ElectronSafeStorageError
|
||||
DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
@@ -236,20 +227,46 @@ const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(
|
||||
const directory = input.path.dirname(input.catalogPath);
|
||||
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe(
|
||||
Effect.mapError((cause) => writeError("encode-document", input.catalogPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "encode-document",
|
||||
path: input.catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem
|
||||
.makeDirectory(directory, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
|
||||
yield* Effect.gen(function* () {
|
||||
yield* input.fileSystem
|
||||
.writeFileString(tempPath, `${encoded}\n`)
|
||||
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.rename(tempPath, input.catalogPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-catalog-file", input.catalogPath, cause)),
|
||||
);
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.catalogPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "replace-catalog-file",
|
||||
path: input.catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
input.fileSystem.remove(tempPath, { force: true }).pipe(
|
||||
@@ -330,13 +347,17 @@ const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
}),
|
||||
);
|
||||
const token = yield* savedEnvironments
|
||||
.getSecret(record.environmentId)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
migrationError("read-legacy-secret", catalogPath, cause, record.environmentId),
|
||||
),
|
||||
);
|
||||
const token = yield* savedEnvironments.getSecret(record.environmentId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "read-legacy-secret",
|
||||
catalogPath,
|
||||
environmentId: record.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (Option.isSome(token)) {
|
||||
credentials.push({
|
||||
connectionId: id,
|
||||
@@ -362,13 +383,41 @@ export const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
|
||||
const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "check-encryption-availability",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
|
||||
catalog: string,
|
||||
) {
|
||||
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
|
||||
const encryptedCatalog = Encoding.encodeBase64(
|
||||
yield* safeStorage.encryptString(catalog).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "encrypt-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => writeError("create-temporary-file-name", catalogPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
@@ -380,21 +429,42 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const migrateLegacyCatalog = Effect.gen(function* () {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const records = yield* savedEnvironments.getRegistry.pipe(
|
||||
Effect.mapError((cause) => migrationError("read-legacy-registry", catalogPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "read-legacy-registry",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (records.length === 0) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);
|
||||
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
|
||||
Effect.mapError((cause) => migrationError("encode-catalog", catalogPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "encode-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* writeCatalog(encoded).pipe(
|
||||
Effect.mapError((cause) => migrationError("persist-catalog", catalogPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "persist-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return Option.some(encoded);
|
||||
});
|
||||
@@ -405,16 +475,27 @@ export const make = Effect.gen(function* () {
|
||||
if (Option.isNone(document)) {
|
||||
return yield* migrateLegacyCatalog;
|
||||
}
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
|
||||
Effect.flatMap(safeStorage.decryptString),
|
||||
Effect.flatMap((encryptedCatalog) =>
|
||||
safeStorage.decryptString(encryptedCatalog).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "decrypt-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return Option.some(decrypted);
|
||||
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
|
||||
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
yield* writeCatalog(catalog);
|
||||
|
||||
@@ -1,26 +1,39 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import type * as Electron from "electron";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { appFocusMock, getAllWindowsMock } = vi.hoisted(() => ({
|
||||
appFocusMock: vi.fn(),
|
||||
getAllWindowsMock: vi.fn(),
|
||||
}));
|
||||
const { appFocusMock, browserWindowMock, getAllWindowsMock, getFocusedWindowMock } = vi.hoisted(
|
||||
() => ({
|
||||
appFocusMock: vi.fn(),
|
||||
browserWindowMock: vi.fn(function BrowserWindowMock() {}),
|
||||
getAllWindowsMock: vi.fn(),
|
||||
getFocusedWindowMock: vi.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: {
|
||||
focus: appFocusMock,
|
||||
},
|
||||
BrowserWindow: {
|
||||
BrowserWindow: Object.assign(browserWindowMock, {
|
||||
getAllWindows: getAllWindowsMock,
|
||||
},
|
||||
getFocusedWindow: getFocusedWindowMock,
|
||||
}),
|
||||
}));
|
||||
|
||||
import * as ElectronWindow from "./ElectronWindow.ts";
|
||||
|
||||
function makeBrowserWindow(input: { readonly destroyed: boolean }) {
|
||||
const TestLayer = ElectronWindow.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
|
||||
function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boolean }) {
|
||||
return {
|
||||
id: input.id,
|
||||
isDestroyed: vi.fn(() => input.destroyed),
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
}
|
||||
@@ -28,13 +41,78 @@ function makeBrowserWindow(input: { readonly destroyed: boolean }) {
|
||||
describe("ElectronWindow", () => {
|
||||
beforeEach(() => {
|
||||
appFocusMock.mockReset();
|
||||
browserWindowMock.mockReset();
|
||||
getAllWindowsMock.mockReset();
|
||||
getFocusedWindowMock.mockReset();
|
||||
});
|
||||
|
||||
it.effect("preserves schema-safe creation context and the Electron cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("native BrowserWindow construction failed");
|
||||
browserWindowMock.mockImplementationOnce(function BrowserWindowFailure() {
|
||||
throw cause;
|
||||
});
|
||||
const options = {
|
||||
title: "T3 Code",
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
modal: false,
|
||||
frame: true,
|
||||
transparent: false,
|
||||
backgroundColor: "#101010",
|
||||
icon: {} as Electron.NativeImage,
|
||||
webPreferences: {
|
||||
preload: "/tmp/preload.js",
|
||||
partition: "persist:t3code-preview-test",
|
||||
sandbox: true,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
webviewTag: true,
|
||||
spellcheck: true,
|
||||
},
|
||||
} satisfies Electron.BrowserWindowConstructorOptions;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
|
||||
const error = yield* electronWindow.create(options).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowCreateError);
|
||||
assert.isTrue(ElectronWindow.isElectronWindowCreateError(error));
|
||||
assert.deepEqual(error.options, {
|
||||
title: "T3 Code",
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
modal: false,
|
||||
frame: true,
|
||||
transparent: false,
|
||||
backgroundColor: "#101010",
|
||||
webPreferences: {
|
||||
preload: "/tmp/preload.js",
|
||||
partition: "persist:t3code-preview-test",
|
||||
sandbox: true,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
webviewTag: true,
|
||||
},
|
||||
});
|
||||
assert.isFalse("icon" in error.options);
|
||||
assert.isFalse("spellcheck" in error.options.webPreferences);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, 'Failed to create Electron BrowserWindow "T3 Code" (1100x780).');
|
||||
assert.notInclude(error.message, cause.message);
|
||||
assert.deepEqual(browserWindowMock.mock.calls, [[options]]);
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("skips windows destroyed before appearance sync runs", () =>
|
||||
Effect.gen(function* () {
|
||||
const liveWindow = makeBrowserWindow({ destroyed: false });
|
||||
const destroyedWindow = makeBrowserWindow({ destroyed: true });
|
||||
const liveWindow = makeBrowserWindow({ id: 1, destroyed: false });
|
||||
const destroyedWindow = makeBrowserWindow({ id: 2, destroyed: true });
|
||||
getAllWindowsMock.mockReturnValue([destroyedWindow, liveWindow]);
|
||||
|
||||
const syncedWindows: Electron.BrowserWindow[] = [];
|
||||
@@ -46,6 +124,112 @@ describe("ElectronWindow", () => {
|
||||
);
|
||||
|
||||
assert.deepEqual(syncedWindows, [liveWindow]);
|
||||
}).pipe(Effect.provide(ElectronWindow.layer)),
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves window enumeration failures as structured defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("window enumeration failed");
|
||||
getAllWindowsMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.currentMainOrFirst);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "list-windows");
|
||||
assert.equal(error.platform, "linux");
|
||||
assert.isNull(error.windowId);
|
||||
assert.isNull(error.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves reveal failures with the target window", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("window restore failed");
|
||||
const window = {
|
||||
id: 41,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isMinimized: vi.fn(() => true),
|
||||
restore: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.reveal(window));
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "reveal-window");
|
||||
assert.equal(error.windowId, 41);
|
||||
assert.isNull(error.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves message delivery failures with window and channel context", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("renderer send failed");
|
||||
const window = {
|
||||
id: 42,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
webContents: {
|
||||
send: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
},
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
getAllWindowsMock.mockReturnValueOnce([window]);
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.sendAll("desktop:update", { ready: true }));
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "send-window-message");
|
||||
assert.equal(error.windowId, 42);
|
||||
assert.equal(error.channel, "desktop:update");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves destroy failures with the target window", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("window destroy failed");
|
||||
const window = {
|
||||
id: 43,
|
||||
destroy: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
getAllWindowsMock.mockReturnValueOnce([window]);
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.destroyAll);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "destroy-window");
|
||||
assert.equal(error.windowId, 43);
|
||||
assert.isNull(error.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
});
|
||||
@@ -8,14 +8,69 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
const ElectronWindowCreateOptions = Schema.Struct({
|
||||
title: Schema.NullOr(Schema.String),
|
||||
width: Schema.NullOr(Schema.Number),
|
||||
height: Schema.NullOr(Schema.Number),
|
||||
minWidth: Schema.NullOr(Schema.Number),
|
||||
minHeight: Schema.NullOr(Schema.Number),
|
||||
show: Schema.NullOr(Schema.Boolean),
|
||||
modal: Schema.NullOr(Schema.Boolean),
|
||||
frame: Schema.NullOr(Schema.Boolean),
|
||||
transparent: Schema.NullOr(Schema.Boolean),
|
||||
backgroundColor: Schema.NullOr(Schema.String),
|
||||
webPreferences: Schema.Struct({
|
||||
preload: Schema.NullOr(Schema.String),
|
||||
partition: Schema.NullOr(Schema.String),
|
||||
sandbox: Schema.NullOr(Schema.Boolean),
|
||||
contextIsolation: Schema.NullOr(Schema.Boolean),
|
||||
nodeIntegration: Schema.NullOr(Schema.Boolean),
|
||||
webviewTag: Schema.NullOr(Schema.Boolean),
|
||||
}),
|
||||
});
|
||||
|
||||
const ElectronWindowOperation = Schema.Literals([
|
||||
"list-windows",
|
||||
"get-focused-window",
|
||||
"inspect-window",
|
||||
"reveal-window",
|
||||
"send-window-message",
|
||||
"destroy-window",
|
||||
]);
|
||||
|
||||
export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronWindowCreateError>()(
|
||||
"ElectronWindowCreateError",
|
||||
{
|
||||
options: ElectronWindowCreateOptions,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to create Electron BrowserWindow.";
|
||||
const title = this.options.title === null ? "" : ` "${this.options.title}"`;
|
||||
const dimensions =
|
||||
this.options.width === null || this.options.height === null
|
||||
? ""
|
||||
: ` (${this.options.width}x${this.options.height})`;
|
||||
return `Failed to create Electron BrowserWindow${title}${dimensions}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const isElectronWindowCreateError = Schema.is(ElectronWindowCreateError);
|
||||
|
||||
export class ElectronWindowOperationError extends Schema.TaggedErrorClass<ElectronWindowOperationError>()(
|
||||
"ElectronWindowOperationError",
|
||||
{
|
||||
operation: ElectronWindowOperation,
|
||||
platform: Schema.String,
|
||||
windowId: Schema.NullOr(Schema.Number),
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
|
||||
const channel = this.channel === null ? "" : ` on channel ${JSON.stringify(this.channel)}`;
|
||||
return `Electron window operation ${JSON.stringify(this.operation)} failed${window}${channel} on ${this.platform}.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,9 +98,38 @@ export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
|
||||
const liveMain = Ref.get(mainWindowRef).pipe(
|
||||
Effect.map(Option.filter((value) => !value.isDestroyed())),
|
||||
);
|
||||
const listWindows = Effect.try({
|
||||
try: () => Electron.BrowserWindow.getAllWindows(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "list-windows",
|
||||
platform,
|
||||
windowId: null,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
|
||||
const isWindowDestroyed = (window: Electron.BrowserWindow) =>
|
||||
Effect.try({
|
||||
try: () => window.isDestroyed(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "inspect-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
|
||||
const liveMain = Effect.gen(function* () {
|
||||
const main = yield* Ref.get(mainWindowRef);
|
||||
if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
|
||||
return Option.none<Electron.BrowserWindow>();
|
||||
}
|
||||
return main;
|
||||
});
|
||||
|
||||
const currentMainOrFirst = Effect.gen(function* () {
|
||||
const main = yield* liveMain;
|
||||
@@ -53,27 +137,60 @@ export const make = Effect.gen(function* () {
|
||||
return main;
|
||||
}
|
||||
|
||||
return Option.fromNullishOr(Electron.BrowserWindow.getAllWindows()[0] ?? null).pipe(
|
||||
Option.filter((window) => !window.isDestroyed()),
|
||||
);
|
||||
const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);
|
||||
if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
|
||||
return Option.none<Electron.BrowserWindow>();
|
||||
}
|
||||
return first;
|
||||
});
|
||||
|
||||
const focusedMainOrFirst = Effect.sync(() =>
|
||||
Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null).pipe(
|
||||
Option.filter((window) => !window.isDestroyed()),
|
||||
),
|
||||
).pipe(
|
||||
Effect.flatMap((focused) =>
|
||||
Option.isSome(focused) ? Effect.succeed(focused) : currentMainOrFirst,
|
||||
),
|
||||
);
|
||||
const focusedMainOrFirst = Effect.gen(function* () {
|
||||
const focused = yield* Effect.try({
|
||||
try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "get-focused-window",
|
||||
platform,
|
||||
windowId: null,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
|
||||
return focused;
|
||||
}
|
||||
return yield* currentMainOrFirst;
|
||||
});
|
||||
|
||||
return ElectronWindow.of({
|
||||
create: (options) =>
|
||||
Effect.try({
|
||||
create: (options) => {
|
||||
const webPreferences = options.webPreferences;
|
||||
const diagnosticOptions = {
|
||||
title: options.title ?? null,
|
||||
width: options.width ?? null,
|
||||
height: options.height ?? null,
|
||||
minWidth: options.minWidth ?? null,
|
||||
minHeight: options.minHeight ?? null,
|
||||
show: options.show ?? null,
|
||||
modal: options.modal ?? null,
|
||||
frame: options.frame ?? null,
|
||||
transparent: options.transparent ?? null,
|
||||
backgroundColor: options.backgroundColor ?? null,
|
||||
webPreferences: {
|
||||
preload: webPreferences?.preload ?? null,
|
||||
partition: webPreferences?.partition ?? null,
|
||||
sandbox: webPreferences?.sandbox ?? null,
|
||||
contextIsolation: webPreferences?.contextIsolation ?? null,
|
||||
nodeIntegration: webPreferences?.nodeIntegration ?? null,
|
||||
webviewTag: webPreferences?.webviewTag ?? null,
|
||||
},
|
||||
} satisfies typeof ElectronWindowCreateOptions.Type;
|
||||
|
||||
return Effect.try({
|
||||
try: () => new Electron.BrowserWindow(options),
|
||||
catch: (cause) => new ElectronWindowCreateError({ cause }),
|
||||
}),
|
||||
catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
|
||||
});
|
||||
},
|
||||
main: liveMain,
|
||||
currentMainOrFirst,
|
||||
focusedMainOrFirst,
|
||||
@@ -89,45 +206,75 @@ export const make = Effect.gen(function* () {
|
||||
return Option.none();
|
||||
}),
|
||||
reveal: (window) =>
|
||||
Effect.sync(() => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
|
||||
if (!window.isVisible()) {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
|
||||
window.focus();
|
||||
}),
|
||||
sendAll: (channel, ...args) =>
|
||||
Effect.sync(() => {
|
||||
for (const window of Electron.BrowserWindow.getAllWindows()) {
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
|
||||
if (!window.isVisible()) {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
|
||||
window.focus();
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "reveal-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
sendAll: (channel, ...args) =>
|
||||
Effect.gen(function* () {
|
||||
for (const window of yield* listWindows) {
|
||||
if (yield* isWindowDestroyed(window)) {
|
||||
continue;
|
||||
}
|
||||
window.webContents.send(channel, ...args);
|
||||
yield* Effect.try({
|
||||
try: () => window.webContents.send(channel, ...args),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "send-window-message",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
}
|
||||
}),
|
||||
destroyAll: Effect.sync(() => {
|
||||
for (const window of Electron.BrowserWindow.getAllWindows()) {
|
||||
window.destroy();
|
||||
destroyAll: Effect.gen(function* () {
|
||||
for (const window of yield* listWindows) {
|
||||
yield* Effect.try({
|
||||
try: () => window.destroy(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "destroy-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
}
|
||||
}),
|
||||
syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
|
||||
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
|
||||
) {
|
||||
const windows = Electron.BrowserWindow.getAllWindows();
|
||||
const windows = yield* listWindows;
|
||||
for (const window of windows) {
|
||||
if (window.isDestroyed()) {
|
||||
if (yield* isWindowDestroyed(window)) {
|
||||
continue;
|
||||
}
|
||||
yield* sync(window);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { fromPartition, sessions } = vi.hoisted(() => ({
|
||||
@@ -59,6 +61,64 @@ describe("BrowserSession", () => {
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves partition scope and the platform failure chain", () => {
|
||||
const nativeCause = new Error("native digest failed");
|
||||
const platformCause = PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "Crypto",
|
||||
method: "digest",
|
||||
cause: nativeCause,
|
||||
});
|
||||
const failingCryptoLayer = Layer.succeed(
|
||||
Crypto.Crypto,
|
||||
Crypto.make({
|
||||
randomBytes: (size) => new Uint8Array(size),
|
||||
digest: () => Effect.fail(platformCause),
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(error));
|
||||
assert.equal(error.scope, "environment-a");
|
||||
assert.strictEqual(error.cause, platformCause);
|
||||
assert.strictEqual(error.cause.reason.cause, nativeCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to derive a desktop preview browser partition for scope environment-a.",
|
||||
);
|
||||
assert.notInclude(error.message, nativeCause.message);
|
||||
}).pipe(Effect.provide(BrowserSession.layer.pipe(Layer.provide(failingCryptoLayer))));
|
||||
});
|
||||
|
||||
it.effect("preserves session scope, partition, and the Electron failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("Electron session failed");
|
||||
fromPartition.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
const partition = yield* browserSessions.getPartition("environment-b");
|
||||
const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(error));
|
||||
assert.equal(error.scope, "environment-b");
|
||||
assert.equal(error.partition, partition);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("clears storage and cache for every created session", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
@@ -80,4 +140,52 @@ describe("BrowserSession", () => {
|
||||
}
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("correlates clear failures while still attempting every session", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
yield* browserSessions.getSession("scope-a");
|
||||
yield* browserSessions.getSession("scope-b");
|
||||
const firstPartition = yield* browserSessions.getPartition("scope-a");
|
||||
const secondPartition = yield* browserSessions.getPartition("scope-b");
|
||||
const firstSession = sessions.get(firstPartition);
|
||||
const secondSession = sessions.get(secondPartition);
|
||||
assert.isDefined(firstSession);
|
||||
assert.isDefined(secondSession);
|
||||
|
||||
const storageCause = new Error("storage clear failed");
|
||||
secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
|
||||
const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(storageError));
|
||||
assert.equal(storageError.partition, secondPartition);
|
||||
assert.strictEqual(storageError.cause, storageCause);
|
||||
assert.equal(
|
||||
storageError.message,
|
||||
`Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
|
||||
);
|
||||
assert.notInclude(storageError.message, storageCause.message);
|
||||
for (const browserSession of sessions.values()) {
|
||||
assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
|
||||
}
|
||||
|
||||
const cacheCause = new Error("cache clear failed");
|
||||
firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
|
||||
const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(cacheError));
|
||||
assert.equal(cacheError.partition, firstPartition);
|
||||
assert.strictEqual(cacheError.cause, cacheCause);
|
||||
assert.equal(
|
||||
cacheError.message,
|
||||
`Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
|
||||
);
|
||||
assert.notInclude(cacheError.message, cacheCause.message);
|
||||
for (const browserSession of sessions.values()) {
|
||||
assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
|
||||
}
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -5,31 +5,87 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
|
||||
|
||||
export class BrowserSessionError extends Schema.TaggedErrorClass<BrowserSessionError>()(
|
||||
"BrowserSessionError",
|
||||
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
|
||||
"BrowserSessionPartitionDerivationError",
|
||||
{
|
||||
operation: Schema.Literals(["getPartition", "getSession", "clearCookies", "clearCache"]),
|
||||
scope: Schema.String,
|
||||
cause: Schema.instanceOf(PlatformError.PlatformError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionCreationError extends Schema.TaggedErrorClass<BrowserSessionCreationError>()(
|
||||
"BrowserSessionCreationError",
|
||||
{
|
||||
scope: Schema.String,
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop preview browser session operation failed: ${this.operation}`;
|
||||
return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionStorageClearError extends Schema.TaggedErrorClass<BrowserSessionStorageClearError>()(
|
||||
"BrowserSessionStorageClearError",
|
||||
{
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionCacheClearError extends Schema.TaggedErrorClass<BrowserSessionCacheClearError>()(
|
||||
"BrowserSessionCacheClearError",
|
||||
{
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BrowserSessionGetSessionError = Schema.Union([
|
||||
BrowserSessionPartitionDerivationError,
|
||||
BrowserSessionCreationError,
|
||||
]);
|
||||
export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
|
||||
export const isBrowserSessionGetSessionError = Schema.is(BrowserSessionGetSessionError);
|
||||
|
||||
export const BrowserSessionError = Schema.Union([
|
||||
BrowserSessionPartitionDerivationError,
|
||||
BrowserSessionCreationError,
|
||||
BrowserSessionStorageClearError,
|
||||
BrowserSessionCacheClearError,
|
||||
]);
|
||||
export type BrowserSessionError = typeof BrowserSessionError.Type;
|
||||
export const isBrowserSessionError = Schema.is(BrowserSessionError);
|
||||
|
||||
export class BrowserSession extends Context.Service<
|
||||
BrowserSession,
|
||||
{
|
||||
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
|
||||
readonly getPartition: (
|
||||
scope?: string,
|
||||
) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
|
||||
readonly isPartition: (partition: string) => boolean;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
|
||||
}
|
||||
>()("@t3tools/desktop/preview/BrowserSession") {}
|
||||
|
||||
@@ -38,11 +94,15 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
|
||||
|
||||
const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
|
||||
const digest = yield* crypto
|
||||
.digest("SHA-256", new TextEncoder().encode(scope))
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new BrowserSessionError({ operation: "getPartition", cause })),
|
||||
);
|
||||
const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(scope)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BrowserSessionPartitionDerivationError({
|
||||
scope,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
|
||||
});
|
||||
|
||||
@@ -67,7 +127,12 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
next.set(partition, browserSession);
|
||||
return [browserSession, next] as const;
|
||||
},
|
||||
catch: (cause) => new BrowserSessionError({ operation: "getSession", cause }),
|
||||
catch: (cause) =>
|
||||
new BrowserSessionCreationError({
|
||||
scope,
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -79,13 +144,17 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.values()].map((browserSession) =>
|
||||
[...sessions.entries()].map(([partition, browserSession]) =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
browserSession.clearStorageData({
|
||||
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
|
||||
}),
|
||||
catch: (cause) => new BrowserSessionError({ operation: "clearCookies", cause }),
|
||||
catch: (cause) =>
|
||||
new BrowserSessionStorageClearError({
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
@@ -94,10 +163,14 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.values()].map((browserSession) =>
|
||||
[...sessions.entries()].map(([partition, browserSession]) =>
|
||||
Effect.tryPromise({
|
||||
try: () => browserSession.clearCache(),
|
||||
catch: (cause) => new BrowserSessionError({ operation: "clearCache", cause }),
|
||||
catch: (cause) =>
|
||||
new BrowserSessionCacheClearError({
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
|
||||
@@ -271,10 +271,11 @@ describe("DesktopSavedEnvironments", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces typed safe storage availability failures", () => {
|
||||
it.effect("adds saved-environment context to safe storage availability failures", () => {
|
||||
const cause = new Error("safe storage unavailable");
|
||||
return withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
|
||||
|
||||
@@ -285,8 +286,22 @@ describe("DesktopSavedEnvironments", () => {
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
|
||||
assert.equal(error.cause, cause);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentSecretProtectionError,
|
||||
);
|
||||
assert.equal(error.operation, "check-encryption-availability");
|
||||
assert.equal(error.environmentId, savedRegistryRecord.environmentId);
|
||||
assert.equal(error.registryPath, environment.savedEnvironmentRegistryPath);
|
||||
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
|
||||
const availabilityError =
|
||||
error.cause as ElectronSafeStorage.ElectronSafeStorageAvailabilityError;
|
||||
assert.strictEqual(availabilityError.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop saved-environment secret protection failed during check-encryption-availability for environment ${savedRegistryRecord.environmentId} at ${environment.savedEnvironmentRegistryPath}.`,
|
||||
);
|
||||
assert.notEqual(error.message, availabilityError.message);
|
||||
}),
|
||||
{ availabilityError: cause },
|
||||
);
|
||||
|
||||
@@ -77,7 +77,12 @@ const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([
|
||||
"write-temporary-file",
|
||||
"replace-registry-file",
|
||||
]);
|
||||
type DesktopSavedEnvironmentsWriteOperation = typeof DesktopSavedEnvironmentsWriteOperation.Type;
|
||||
|
||||
const DesktopSavedEnvironmentSecretProtectionOperation = Schema.Literals([
|
||||
"check-encryption-availability",
|
||||
"encrypt-secret",
|
||||
"decrypt-secret",
|
||||
]);
|
||||
|
||||
export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsWriteError>()(
|
||||
"DesktopSavedEnvironmentsWriteError",
|
||||
@@ -92,17 +97,6 @@ export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopSavedEnvironmentsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopSavedEnvironmentsWriteError =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation,
|
||||
path,
|
||||
cause,
|
||||
});
|
||||
|
||||
export class DesktopSavedEnvironmentsReadError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsReadError>()(
|
||||
"DesktopSavedEnvironmentsReadError",
|
||||
{
|
||||
@@ -141,6 +135,20 @@ export class DesktopSavedEnvironmentSecretDecodeError extends Schema.TaggedError
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironmentSecretProtectionError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentSecretProtectionError>()(
|
||||
"DesktopSavedEnvironmentSecretProtectionError",
|
||||
{
|
||||
operation: DesktopSavedEnvironmentSecretProtectionOperation,
|
||||
environmentId: Schema.String,
|
||||
registryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop saved-environment secret protection failed during ${this.operation} for environment ${this.environmentId} at ${this.registryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopSavedEnvironmentsReadRegistryError =
|
||||
| DesktopSavedEnvironmentsReadError
|
||||
| DesktopSavedEnvironmentsDocumentDecodeError;
|
||||
@@ -152,11 +160,11 @@ export type DesktopSavedEnvironmentsMutationError =
|
||||
export type DesktopSavedEnvironmentsGetSecretError =
|
||||
| DesktopSavedEnvironmentsReadRegistryError
|
||||
| DesktopSavedEnvironmentSecretDecodeError
|
||||
| ElectronSafeStorage.ElectronSafeStorageError;
|
||||
| DesktopSavedEnvironmentSecretProtectionError;
|
||||
|
||||
export type DesktopSavedEnvironmentsSetSecretError =
|
||||
| DesktopSavedEnvironmentsMutationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageError;
|
||||
| DesktopSavedEnvironmentSecretProtectionError;
|
||||
|
||||
export class DesktopSavedEnvironments extends Context.Service<
|
||||
DesktopSavedEnvironments,
|
||||
@@ -276,19 +284,45 @@ const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistry
|
||||
const directory = input.path.dirname(input.registryPath);
|
||||
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document).pipe(
|
||||
Effect.mapError((cause) => writeError("encode-registry", input.registryPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "encode-registry",
|
||||
path: input.registryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.registryPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "replace-registry-file",
|
||||
path: input.registryPath,
|
||||
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.registryPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-registry-file", input.registryPath, cause)),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -341,8 +375,13 @@ export const make = Effect.gen(function* () {
|
||||
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.savedEnvironmentRegistryPath, cause),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeRegistryDocument({
|
||||
@@ -396,7 +435,21 @@ export const make = Effect.gen(function* () {
|
||||
document.records.find((record) => record.environmentId === environmentId)
|
||||
?.encryptedBearerToken,
|
||||
);
|
||||
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
|
||||
if (Option.isNone(encoded)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "check-encryption-availability",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!encryptionAvailable) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
|
||||
@@ -405,7 +458,19 @@ export const make = Effect.gen(function* () {
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
encoded.value,
|
||||
);
|
||||
return Option.some(yield* safeStorage.decryptString(secretBytes));
|
||||
return Option.some(
|
||||
yield* safeStorage.decryptString(secretBytes).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "decrypt-secret",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
|
||||
const { environmentId, secret } = input;
|
||||
@@ -415,11 +480,34 @@ export const make = Effect.gen(function* () {
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "check-encryption-availability",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!encryptionAvailable) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const encryptedBearerToken = Encoding.encodeBase64(yield* safeStorage.encryptString(secret));
|
||||
const encryptedBearerToken = Encoding.encodeBase64(
|
||||
yield* safeStorage.encryptString(secret).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "encrypt-secret",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
let found = false;
|
||||
const nextDocument: SavedEnvironmentRegistryDocument = {
|
||||
version: document.version,
|
||||
|
||||
@@ -23,6 +23,7 @@ describe("sshEnvironment", () => {
|
||||
const cause = new DesktopSshPasswordPrompts.DesktopSshPromptPresentationError({
|
||||
requestId: "prompt-1",
|
||||
destination: "devbox",
|
||||
operation: "send-prompt-request",
|
||||
cause: new Error("renderer send failed"),
|
||||
});
|
||||
|
||||
|
||||
@@ -17,7 +17,13 @@ interface SentMessage {
|
||||
readonly args: readonly unknown[];
|
||||
}
|
||||
|
||||
function makeTestWindow() {
|
||||
function makeTestWindow(
|
||||
options: {
|
||||
readonly isDestroyedError?: unknown;
|
||||
readonly isMinimizedError?: unknown;
|
||||
readonly sendError?: unknown;
|
||||
} = {},
|
||||
) {
|
||||
const listeners = new Map<string, Set<() => void>>();
|
||||
const sentMessages: SentMessage[] = [];
|
||||
let destroyed = false;
|
||||
@@ -26,8 +32,18 @@ function makeTestWindow() {
|
||||
let focused = false;
|
||||
|
||||
const window = {
|
||||
isDestroyed: () => destroyed,
|
||||
isMinimized: () => minimized,
|
||||
isDestroyed: () => {
|
||||
if (options.isDestroyedError !== undefined) {
|
||||
throw options.isDestroyedError;
|
||||
}
|
||||
return destroyed;
|
||||
},
|
||||
isMinimized: () => {
|
||||
if (options.isMinimizedError !== undefined) {
|
||||
throw options.isMinimizedError;
|
||||
}
|
||||
return minimized;
|
||||
},
|
||||
restore: () => {
|
||||
restored = true;
|
||||
minimized = false;
|
||||
@@ -45,7 +61,11 @@ function makeTestWindow() {
|
||||
},
|
||||
webContents: {
|
||||
send: (channel: string, ...args: readonly unknown[]) => {
|
||||
sentMessages.push({ channel, args });
|
||||
const message = { channel, args };
|
||||
sentMessages.push(message);
|
||||
if (options.sendError !== undefined) {
|
||||
throw options.sendError;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -55,6 +75,7 @@ function makeTestWindow() {
|
||||
sentMessages,
|
||||
isRestored: () => restored,
|
||||
isFocused: () => focused,
|
||||
closedListenerCount: () => listeners.get("closed")?.size ?? 0,
|
||||
close: () => {
|
||||
destroyed = true;
|
||||
const closedListeners = [...(listeners.get("closed") ?? [])];
|
||||
@@ -107,6 +128,7 @@ describe("DesktopSshPasswordPrompts", () => {
|
||||
})
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(testWindow.sentMessages.length, 1);
|
||||
const sent = testWindow.sentMessages[0];
|
||||
@@ -143,4 +165,85 @@ describe("DesktopSshPasswordPrompts", () => {
|
||||
assert.equal(error.destination, "devbox");
|
||||
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("cleans up a prompt that fails during renderer delivery", () => {
|
||||
const cause = new Error("renderer unavailable");
|
||||
const testWindow = makeTestWindow({ sendError: cause });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
|
||||
const error = yield* prompts
|
||||
.request({
|
||||
destination: "devbox",
|
||||
username: "julius",
|
||||
prompt: "Enter the SSH password.",
|
||||
attempt: 1,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError);
|
||||
assert.equal(error.operation, "send-prompt-request");
|
||||
assert.equal(error.destination, "devbox");
|
||||
const requestId = error.requestId;
|
||||
if (requestId === null) {
|
||||
assert.fail("renderer delivery failures must retain their request id");
|
||||
}
|
||||
assert.equal(testWindow.closedListenerCount(), 0);
|
||||
|
||||
const resolveError = yield* prompts
|
||||
.resolve({ requestId, password: "secret" })
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(resolveError, DesktopSshPasswordPrompts.DesktopSshPromptExpiredError);
|
||||
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("keeps a submitted password when a later presentation step fails", () => {
|
||||
const testWindow = makeTestWindow({
|
||||
isMinimizedError: new Error("failed to read minimized state"),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
|
||||
const requestFiber = yield* prompts
|
||||
.request({
|
||||
destination: "devbox",
|
||||
username: "julius",
|
||||
prompt: "Enter the SSH password.",
|
||||
attempt: 1,
|
||||
})
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
const sent = testWindow.sentMessages[0];
|
||||
assert.ok(sent);
|
||||
const request = sent.args[0] as { readonly requestId: string };
|
||||
yield* prompts.resolve({ requestId: request.requestId, password: "secret" });
|
||||
const password = yield* Fiber.join(requestFiber);
|
||||
|
||||
assert.equal(password, "secret");
|
||||
assert.equal(testWindow.isFocused(), false);
|
||||
assert.equal(testWindow.closedListenerCount(), 0);
|
||||
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("classifies a failed initial window availability check", () => {
|
||||
const testWindow = makeTestWindow({ isDestroyedError: new Error("window unavailable") });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
|
||||
const error = yield* prompts
|
||||
.request({
|
||||
destination: "devbox",
|
||||
username: "julius",
|
||||
prompt: "Enter the SSH password.",
|
||||
attempt: 1,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError);
|
||||
assert.equal(error.operation, "check-window-before-request");
|
||||
assert.equal(error.requestId, null);
|
||||
assert.deepEqual(testWindow.sentMessages, []);
|
||||
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
|
||||
});
|
||||
});
|
||||
@@ -20,7 +20,26 @@ const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
|
||||
type DesktopSshPasswordPromptResolutionInput =
|
||||
typeof DesktopSshPasswordPromptResolutionInputSchema.Type;
|
||||
|
||||
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
|
||||
const DesktopSshPromptWindowAvailabilityStage = Schema.Literals([
|
||||
"before-request",
|
||||
"before-presentation",
|
||||
"after-send",
|
||||
"after-restore",
|
||||
]);
|
||||
|
||||
const DesktopSshPromptPresentationOperation = Schema.Literals([
|
||||
"check-window-before-request",
|
||||
"check-window-before-presentation",
|
||||
"register-window-close-listener",
|
||||
"send-prompt-request",
|
||||
"check-window-after-send",
|
||||
"check-window-minimized",
|
||||
"restore-window",
|
||||
"check-window-after-restore",
|
||||
"focus-window",
|
||||
"remove-window-close-listener",
|
||||
]);
|
||||
type DesktopSshPromptPresentationOperation = typeof DesktopSshPromptPresentationOperation.Type;
|
||||
|
||||
export class DesktopSshPromptRequestIdGenerationError extends Schema.TaggedErrorClass<DesktopSshPromptRequestIdGenerationError>()(
|
||||
"DesktopSshPromptRequestIdGenerationError",
|
||||
@@ -38,20 +57,22 @@ export class DesktopSshPromptWindowUnavailableError extends Schema.TaggedErrorCl
|
||||
"DesktopSshPromptWindowUnavailableError",
|
||||
{
|
||||
destination: Schema.String,
|
||||
requestId: Schema.NullOr(Schema.String),
|
||||
stage: DesktopSshPromptWindowAvailabilityStage,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return WINDOW_UNAVAILABLE_MESSAGE;
|
||||
const request = this.requestId === null ? "before a request id was assigned" : this.requestId;
|
||||
return `T3 Code window is unavailable during ${this.stage} for SSH authentication to ${this.destination} (request: ${request}).`;
|
||||
}
|
||||
}
|
||||
|
||||
const isDesktopSshPromptWindowUnavailableError = Schema.is(DesktopSshPromptWindowUnavailableError);
|
||||
|
||||
export class DesktopSshPromptPresentationError extends Schema.TaggedErrorClass<DesktopSshPromptPresentationError>()(
|
||||
"DesktopSshPromptPresentationError",
|
||||
{
|
||||
requestId: Schema.String,
|
||||
requestId: Schema.NullOr(Schema.String),
|
||||
destination: Schema.String,
|
||||
operation: DesktopSshPromptPresentationOperation,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
@@ -263,9 +284,29 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
"desktop.sshPasswordPrompts.request",
|
||||
)(function* (input) {
|
||||
const window = yield* electronWindow.main;
|
||||
if (Option.isNone(window) || window.value.isDestroyed()) {
|
||||
if (Option.isNone(window)) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId: null,
|
||||
stage: "before-request",
|
||||
});
|
||||
}
|
||||
|
||||
const unavailableBeforeRequest = yield* Effect.try({
|
||||
try: () => window.value.isDestroyed(),
|
||||
catch: (cause) =>
|
||||
new DesktopSshPromptPresentationError({
|
||||
requestId: null,
|
||||
destination: input.destination,
|
||||
operation: "check-window-before-request",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
if (unavailableBeforeRequest) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId: null,
|
||||
stage: "before-request",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -319,11 +360,25 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
),
|
||||
);
|
||||
};
|
||||
const cleanup = Effect.sync(() => {
|
||||
const runPresentationOperation = <A>(
|
||||
operation: DesktopSshPromptPresentationOperation,
|
||||
evaluate: () => A,
|
||||
) =>
|
||||
Effect.try({
|
||||
try: evaluate,
|
||||
catch: (cause) =>
|
||||
new DesktopSshPromptPresentationError({
|
||||
requestId,
|
||||
destination: input.destination,
|
||||
operation,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const cleanup = runPresentationOperation("remove-window-close-listener", () => {
|
||||
if (!window.value.isDestroyed()) {
|
||||
window.value.removeListener("closed", cancelOnWindowClosed);
|
||||
}
|
||||
}).pipe(Effect.andThen(removePending(pendingRef, requestId)), Effect.asVoid);
|
||||
}).pipe(Effect.orDie, Effect.ensuring(removePending(pendingRef, requestId)), Effect.asVoid);
|
||||
const waitForPassword = Deferred.await(deferred).pipe(
|
||||
Effect.timeoutOption(Duration.millis(passwordPromptTimeoutMs)),
|
||||
Effect.flatMap(
|
||||
@@ -339,40 +394,73 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
}),
|
||||
),
|
||||
);
|
||||
const preferSubmittedPassword = (error: DesktopSshPasswordPromptRequestError) =>
|
||||
Deferred.poll(deferred).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: (completion) => completion,
|
||||
onNone: () =>
|
||||
Ref.get(pendingRef).pipe(
|
||||
Effect.flatMap((entries) =>
|
||||
entries.has(requestId) ? Effect.fail(error) : Deferred.await(deferred),
|
||||
),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* Effect.try({
|
||||
try: () => {
|
||||
if (window.value.isDestroyed()) {
|
||||
throw new DesktopSshPromptWindowUnavailableError({
|
||||
return yield* Effect.gen(function* () {
|
||||
const unavailableBeforePresentation = yield* runPresentationOperation(
|
||||
"check-window-before-presentation",
|
||||
() => window.value.isDestroyed(),
|
||||
);
|
||||
if (unavailableBeforePresentation) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId,
|
||||
stage: "before-presentation",
|
||||
});
|
||||
}
|
||||
yield* runPresentationOperation("register-window-close-listener", () =>
|
||||
window.value.once("closed", cancelOnWindowClosed),
|
||||
);
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runPresentationOperation("send-prompt-request", () =>
|
||||
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest),
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
const unavailableAfterSend = yield* runPresentationOperation(
|
||||
"check-window-after-send",
|
||||
() => window.value.isDestroyed(),
|
||||
);
|
||||
if (unavailableAfterSend) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId,
|
||||
stage: "after-send",
|
||||
});
|
||||
}
|
||||
window.value.once("closed", cancelOnWindowClosed);
|
||||
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
|
||||
if (window.value.isDestroyed()) {
|
||||
throw new DesktopSshPromptWindowUnavailableError({
|
||||
const minimized = yield* runPresentationOperation("check-window-minimized", () =>
|
||||
window.value.isMinimized(),
|
||||
);
|
||||
if (minimized) {
|
||||
yield* runPresentationOperation("restore-window", () => window.value.restore());
|
||||
}
|
||||
const unavailableAfterRestore = yield* runPresentationOperation(
|
||||
"check-window-after-restore",
|
||||
() => window.value.isDestroyed(),
|
||||
);
|
||||
if (unavailableAfterRestore) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId,
|
||||
stage: "after-restore",
|
||||
});
|
||||
}
|
||||
if (window.value.isMinimized()) {
|
||||
window.value.restore();
|
||||
}
|
||||
if (window.value.isDestroyed()) {
|
||||
throw new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
});
|
||||
}
|
||||
window.value.focus();
|
||||
},
|
||||
catch: (cause) =>
|
||||
isDesktopSshPromptWindowUnavailableError(cause)
|
||||
? cause
|
||||
: new DesktopSshPromptPresentationError({
|
||||
requestId,
|
||||
destination: input.destination,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.andThen(waitForPassword), Effect.ensuring(cleanup));
|
||||
yield* runPresentationOperation("focus-window", () => window.value.focus());
|
||||
return yield* waitForPassword;
|
||||
}).pipe(Effect.catch(preferSubmittedPassword));
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
return DesktopSshPasswordPrompts.of({
|
||||
|
||||
@@ -173,6 +173,8 @@ function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
|
||||
}
|
||||
throw new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd,
|
||||
detail: `Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
|
||||
});
|
||||
}
|
||||
@@ -480,6 +482,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
? error
|
||||
: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail:
|
||||
error instanceof Error
|
||||
? `Failed to simulate gh checkout: ${error.message}`
|
||||
@@ -496,6 +500,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
return Effect.fail(
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: `Unexpected repository lookup: ${repository}`,
|
||||
}),
|
||||
);
|
||||
@@ -516,6 +522,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
return Effect.fail(
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: `Unexpected gh command: ${args.join(" ")}`,
|
||||
}),
|
||||
);
|
||||
@@ -595,6 +603,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
Effect.fail(
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "createRepository",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: `Unexpected repository create: ${input.repository}`,
|
||||
}),
|
||||
),
|
||||
@@ -1333,6 +1343,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
@@ -2471,6 +2483,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
@@ -2500,6 +2514,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import type { SqlError } from "effect/unstable/sql/SqlError";
|
||||
|
||||
import { runMigrations } from "../Migrations.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
@@ -13,7 +14,7 @@ type RuntimeSqliteLayerConfig = {
|
||||
};
|
||||
|
||||
type Loader = {
|
||||
layer: (config: RuntimeSqliteLayerConfig) => Layer.Layer<SqlClient.SqlClient>;
|
||||
layer: (config: RuntimeSqliteLayerConfig) => Layer.Layer<SqlClient.SqlClient, SqlError>;
|
||||
};
|
||||
const defaultSqliteClientLoaders = {
|
||||
bun: () => import("@effect/sql-sqlite-bun/SqliteClient"),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import * as SqliteClient from "./NodeSqliteClient.ts";
|
||||
@@ -27,4 +28,25 @@ layer("NodeSqliteClient", (it) => {
|
||||
assert.equal(values[1]?.[1], "beta");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a typed failure when an unprepared statement cannot be prepared", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const error = yield* Effect.flip(sql.unsafe("SELECT FROM").unprepared);
|
||||
|
||||
assert.equal(error._tag, "SqlError");
|
||||
assert.equal(error.reason.operation, "prepare");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("returns a typed failure when the database cannot be opened", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
Layer.build(SqliteClient.layer({ filename: "\0" })).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
assert.equal(error._tag, "SqlError");
|
||||
assert.equal(error.reason.operation, "open");
|
||||
}),
|
||||
);
|
||||
@@ -13,6 +13,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import { identity } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Context from "effect/Context";
|
||||
@@ -45,6 +46,27 @@ export interface SqliteMemoryClientConfig extends Omit<
|
||||
"filename" | "readonly"
|
||||
> {}
|
||||
|
||||
export class UnsupportedNodeSqliteVersionError extends Schema.TaggedErrorClass<UnsupportedNodeSqliteVersionError>()(
|
||||
"UnsupportedNodeSqliteVersionError",
|
||||
{
|
||||
nodeVersion: Schema.String,
|
||||
requirement: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Node.js ${this.nodeVersion} is missing required node:sqlite APIs. Upgrade to ${this.requirement}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class UnsupportedNodeSqliteOperationError extends Schema.TaggedErrorClass<UnsupportedNodeSqliteOperationError>()(
|
||||
"UnsupportedNodeSqliteOperationError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Node SQLite does not support executeStream.";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that the current Node.js version includes the `node:sqlite` APIs
|
||||
* used by `NodeSqliteClient` — specifically `StatementSync.columns()` (added
|
||||
@@ -60,8 +82,10 @@ const checkNodeSqliteCompat = () => {
|
||||
|
||||
if (!supported) {
|
||||
return Effect.die(
|
||||
`Node.js ${process.versions.node} is missing required node:sqlite APIs ` +
|
||||
`(StatementSync.columns). Upgrade to Node.js >=22.16, >=23.11, or >=24.`,
|
||||
new UnsupportedNodeSqliteVersionError({
|
||||
nodeVersion: process.versions.node,
|
||||
requirement: "Node.js >=22.16, >=23.11, or >=24",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.void;
|
||||
@@ -70,7 +94,7 @@ const checkNodeSqliteCompat = () => {
|
||||
const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
options: SqliteClientConfig,
|
||||
openDatabase: () => NodeSqlite.DatabaseSync,
|
||||
): Effect.fn.Return<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> {
|
||||
): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
|
||||
yield* checkNodeSqliteCompat();
|
||||
|
||||
const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
|
||||
@@ -80,10 +104,28 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
|
||||
const makeConnection = Effect.gen(function* () {
|
||||
const scope = yield* Effect.scope;
|
||||
const db = openDatabase();
|
||||
const db = yield* Effect.try({
|
||||
try: openDatabase,
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to open database",
|
||||
operation: "open",
|
||||
}),
|
||||
}),
|
||||
});
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Effect.sync(() => db.close()),
|
||||
Effect.try({
|
||||
try: () => db.close(),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to close database",
|
||||
operation: "close",
|
||||
}),
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
|
||||
const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
|
||||
@@ -119,8 +161,8 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
raw: boolean,
|
||||
) =>
|
||||
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
|
||||
statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
|
||||
try {
|
||||
statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
|
||||
if (hasRows(statement)) {
|
||||
return Effect.succeed(statement.all(...(params as any)));
|
||||
}
|
||||
@@ -166,11 +208,20 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
}),
|
||||
}),
|
||||
(statement) =>
|
||||
Effect.sync(() => {
|
||||
if (hasRows(statement)) {
|
||||
statement.setReturnArrays(false);
|
||||
}
|
||||
}),
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (hasRows(statement)) {
|
||||
statement.setReturnArrays(false);
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to reset statement result mode",
|
||||
operation: "resetResultMode",
|
||||
}),
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
|
||||
return identity<Connection>({
|
||||
@@ -184,11 +235,20 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
return runValues(sql, params);
|
||||
},
|
||||
executeUnprepared(sql, params, rowTransform) {
|
||||
const effect = runStatement(db.prepare(sql), params ?? [], false);
|
||||
const effect = Effect.try({
|
||||
try: () => db.prepare(sql),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to prepare statement",
|
||||
operation: "prepare",
|
||||
}),
|
||||
}),
|
||||
}).pipe(Effect.flatMap((statement) => runStatement(statement, params ?? [], false)));
|
||||
return rowTransform ? Effect.map(effect, rowTransform) : effect;
|
||||
},
|
||||
executeStream(_sql, _params) {
|
||||
return Stream.die("executeStream not implemented");
|
||||
return Stream.die(new UnsupportedNodeSqliteOperationError());
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -220,7 +280,7 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
|
||||
const make = (
|
||||
options: SqliteClientConfig,
|
||||
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
|
||||
): Effect.Effect<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
|
||||
makeWithDatabase(
|
||||
options,
|
||||
() =>
|
||||
@@ -232,7 +292,7 @@ const make = (
|
||||
|
||||
const makeMemory = (
|
||||
config: SqliteMemoryClientConfig = {},
|
||||
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
|
||||
): Effect.Effect<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
|
||||
makeWithDatabase(
|
||||
{
|
||||
...config,
|
||||
@@ -249,13 +309,15 @@ const makeMemory = (
|
||||
|
||||
export const layerConfig = (
|
||||
config: Config.Wrap<SqliteClientConfig>,
|
||||
): Layer.Layer<Client.SqlClient, Config.ConfigError> =>
|
||||
): Layer.Layer<Client.SqlClient, Config.ConfigError | SqlError> =>
|
||||
Layer.effect(Client.SqlClient, Config.unwrap(config).pipe(Effect.flatMap(make))).pipe(
|
||||
Layer.provide(Reactivity.layer),
|
||||
);
|
||||
|
||||
export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient> =>
|
||||
export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
|
||||
Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));
|
||||
|
||||
export const layerMemory = (config: SqliteMemoryClientConfig = {}): Layer.Layer<Client.SqlClient> =>
|
||||
export const layerMemory = (
|
||||
config: SqliteMemoryClientConfig = {},
|
||||
): Layer.Layer<Client.SqlClient, SqlError> =>
|
||||
Layer.effect(Client.SqlClient, makeMemory(config)).pipe(Layer.provide(Reactivity.layer));
|
||||
@@ -3,11 +3,13 @@ import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { CodexSettings } from "@t3tools/contracts";
|
||||
import {
|
||||
CodexShadowHomeError,
|
||||
CodexShadowHomeEntryConflictError,
|
||||
CodexShadowHomePathConflictError,
|
||||
materializeCodexShadowHome,
|
||||
resolveCodexHomeLayout,
|
||||
} from "./CodexHomeLayout.ts";
|
||||
@@ -184,7 +186,14 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => {
|
||||
|
||||
const error = yield* materializeCodexShadowHome(layout).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CodexShadowHomeError);
|
||||
expect(error).toBeInstanceOf(CodexShadowHomePathConflictError);
|
||||
expect(error).toMatchObject({
|
||||
sharedHomePath: sharedHome,
|
||||
effectiveHomePath: sharedHome,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
`Codex shadow home path '${sharedHome}' must be different from the shared home path '${sharedHome}'.`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -206,7 +215,52 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => {
|
||||
|
||||
const error = yield* materializeCodexShadowHome(layout).pipe(Effect.flip);
|
||||
|
||||
expect(error.detail).toContain("already exists and is not a symlink");
|
||||
expect(error).toBeInstanceOf(CodexShadowHomeEntryConflictError);
|
||||
expect(error).toMatchObject({
|
||||
sharedHomePath: sharedHome,
|
||||
effectiveHomePath: shadowHome,
|
||||
entryName: "config.toml",
|
||||
linkPath: path.join(shadowHome, "config.toml"),
|
||||
targetPath: path.join(sharedHome, "config.toml"),
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
`Cannot create Codex shadow home entry 'config.toml' because '${path.join(shadowHome, "config.toml")}' already exists and is not a symlink.`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves filesystem operation, paths, and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const sharedRoot = yield* makeTempDir("t3code-codex-shared-root-");
|
||||
const sharedHome = path.join(sharedRoot, "shared-home");
|
||||
const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-");
|
||||
const shadowHome = path.join(shadowRoot, "shadow");
|
||||
yield* writeTextFile(sharedHome, "not a directory\n");
|
||||
|
||||
const layout = yield* resolveCodexHomeLayout(
|
||||
decodeCodexSettings({
|
||||
homePath: sharedHome,
|
||||
shadowHomePath: shadowHome,
|
||||
}),
|
||||
);
|
||||
|
||||
const error = yield* materializeCodexShadowHome(layout).pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("CodexShadowHomeFileSystemError");
|
||||
if (error._tag !== "CodexShadowHomeFileSystemError") {
|
||||
return expect.fail("Expected CodexShadowHomeFileSystemError");
|
||||
}
|
||||
expect(error).toMatchObject({
|
||||
operation: "makeDirectory",
|
||||
sharedHomePath: sharedHome,
|
||||
effectiveHomePath: shadowHome,
|
||||
});
|
||||
expect(error.path.startsWith(sharedHome)).toBe(true);
|
||||
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
|
||||
expect(error.message).toBe(
|
||||
`Codex shadow home filesystem operation 'makeDirectory' failed for '${error.path}'.`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -63,18 +63,71 @@ export const resolveCodexHomeLayout = Effect.fn("resolveCodexHomeLayout")(functi
|
||||
};
|
||||
});
|
||||
|
||||
export class CodexShadowHomeError extends Schema.TaggedErrorClass<CodexShadowHomeError>()(
|
||||
"CodexShadowHomeError",
|
||||
const CodexShadowHomeContext = {
|
||||
sharedHomePath: Schema.String,
|
||||
effectiveHomePath: Schema.String,
|
||||
};
|
||||
|
||||
export class CodexShadowHomeFileSystemError extends Schema.TaggedErrorClass<CodexShadowHomeFileSystemError>()(
|
||||
"CodexShadowHomeFileSystemError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Unknown),
|
||||
...CodexShadowHomeContext,
|
||||
operation: Schema.Literals(["readLink", "makeDirectory", "readDirectory", "remove", "symlink"]),
|
||||
path: Schema.String,
|
||||
targetPath: Schema.optional(Schema.String),
|
||||
entryName: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.detail;
|
||||
const target = this.targetPath === undefined ? "" : ` to '${this.targetPath}'`;
|
||||
return `Codex shadow home filesystem operation '${this.operation}' failed for '${this.path}'${target}.`;
|
||||
}
|
||||
}
|
||||
const isCodexShadowHomeError = Schema.is(CodexShadowHomeError);
|
||||
|
||||
export class CodexShadowHomePathConflictError extends Schema.TaggedErrorClass<CodexShadowHomePathConflictError>()(
|
||||
"CodexShadowHomePathConflictError",
|
||||
CodexShadowHomeContext,
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Codex shadow home path '${this.effectiveHomePath}' must be different from the shared home path '${this.sharedHomePath}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CodexShadowHomeEntryConflictError extends Schema.TaggedErrorClass<CodexShadowHomeEntryConflictError>()(
|
||||
"CodexShadowHomeEntryConflictError",
|
||||
{
|
||||
...CodexShadowHomeContext,
|
||||
entryName: Schema.String,
|
||||
linkPath: Schema.String,
|
||||
targetPath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Cannot create Codex shadow home entry '${this.entryName}' because '${this.linkPath}' already exists and is not a symlink.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CodexShadowHomePrivateEntrySymlinkError extends Schema.TaggedErrorClass<CodexShadowHomePrivateEntrySymlinkError>()(
|
||||
"CodexShadowHomePrivateEntrySymlinkError",
|
||||
{
|
||||
...CodexShadowHomeContext,
|
||||
entryName: Schema.String,
|
||||
path: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Codex shadow home private entry '${this.entryName}' at '${this.path}' must be a real file, not a symlink.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const CodexShadowHomeError = Schema.Union([
|
||||
CodexShadowHomeFileSystemError,
|
||||
CodexShadowHomePathConflictError,
|
||||
CodexShadowHomeEntryConflictError,
|
||||
CodexShadowHomePrivateEntrySymlinkError,
|
||||
]);
|
||||
export type CodexShadowHomeError = typeof CodexShadowHomeError.Type;
|
||||
|
||||
type LinkState =
|
||||
| {
|
||||
@@ -88,21 +141,6 @@ type LinkState =
|
||||
readonly target: string;
|
||||
};
|
||||
|
||||
function toShadowHomeError(cause: unknown): CodexShadowHomeError {
|
||||
return isCodexShadowHomeError(cause)
|
||||
? cause
|
||||
: new CodexShadowHomeError({
|
||||
detail: "Failed to materialize Codex shadow home.",
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeShadowHomeError<A, E, R>(
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
): Effect.Effect<A, CodexShadowHomeError, R> {
|
||||
return effect.pipe(Effect.mapError(toShadowHomeError));
|
||||
}
|
||||
|
||||
function isNotSymlinkError(error: PlatformError.PlatformError): boolean {
|
||||
const cause = error.reason.cause;
|
||||
return (
|
||||
@@ -114,78 +152,151 @@ function isNotSymlinkError(error: PlatformError.PlatformError): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
const readLinkState = Effect.fn("CodexHomeLayout.readLinkState")(function* (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
linkPath: string,
|
||||
): Effect.fn.Return<LinkState, CodexShadowHomeError> {
|
||||
return yield* fileSystem.readLink(linkPath).pipe(
|
||||
const readLinkState = Effect.fn("CodexHomeLayout.readLinkState")(function* (input: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly sharedHomePath: string;
|
||||
readonly effectiveHomePath: string;
|
||||
readonly entryName: string;
|
||||
readonly linkPath: string;
|
||||
}): Effect.fn.Return<LinkState, CodexShadowHomeError> {
|
||||
return yield* input.fileSystem.readLink(input.linkPath).pipe(
|
||||
Effect.map((target): LinkState => ({ _tag: "Symlink", target })),
|
||||
Effect.catch((error) => {
|
||||
if (error.reason._tag === "NotFound") {
|
||||
return Effect.succeed<LinkState>({ _tag: "Missing" });
|
||||
}
|
||||
if (isNotSymlinkError(error)) {
|
||||
return Effect.succeed<LinkState>({ _tag: "NotSymlink" });
|
||||
}
|
||||
return Effect.fail(toShadowHomeError(error));
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) => {
|
||||
if (cause.reason._tag === "NotFound") {
|
||||
return Effect.succeed<LinkState>({ _tag: "Missing" });
|
||||
}
|
||||
if (isNotSymlinkError(cause)) {
|
||||
return Effect.succeed<LinkState>({ _tag: "NotSymlink" });
|
||||
}
|
||||
return new CodexShadowHomeFileSystemError({
|
||||
sharedHomePath: input.sharedHomePath,
|
||||
effectiveHomePath: input.effectiveHomePath,
|
||||
operation: "readLink",
|
||||
path: input.linkPath,
|
||||
entryName: input.entryName,
|
||||
cause,
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const removePrivateSymlink = Effect.fn("CodexHomeLayout.removePrivateSymlink")(function* (input: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly shadowPath: string;
|
||||
readonly sharedHomePath: string;
|
||||
readonly effectiveHomePath: string;
|
||||
readonly entryName: string;
|
||||
}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
|
||||
const path = yield* Path.Path;
|
||||
const privatePath = path.join(input.shadowPath, input.entryName);
|
||||
const state = yield* readLinkState(input.fileSystem, privatePath);
|
||||
const privatePath = path.join(input.effectiveHomePath, input.entryName);
|
||||
const state = yield* readLinkState({
|
||||
...input,
|
||||
linkPath: privatePath,
|
||||
});
|
||||
if (state._tag === "Symlink") {
|
||||
yield* normalizeShadowHomeError(input.fileSystem.remove(privatePath));
|
||||
yield* input.fileSystem.remove(privatePath).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
new CodexShadowHomeFileSystemError({
|
||||
sharedHomePath: input.sharedHomePath,
|
||||
effectiveHomePath: input.effectiveHomePath,
|
||||
operation: "remove",
|
||||
path: privatePath,
|
||||
entryName: input.entryName,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (input: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly shadowPath: string;
|
||||
readonly sharedPath: string;
|
||||
readonly sharedHomePath: string;
|
||||
readonly effectiveHomePath: string;
|
||||
readonly entryName: string;
|
||||
}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
|
||||
const path = yield* Path.Path;
|
||||
const target = path.join(input.sharedPath, input.entryName);
|
||||
const link = path.join(input.shadowPath, input.entryName);
|
||||
const state = yield* readLinkState(input.fileSystem, link);
|
||||
const target = path.join(input.sharedHomePath, input.entryName);
|
||||
const link = path.join(input.effectiveHomePath, input.entryName);
|
||||
const state = yield* readLinkState({
|
||||
...input,
|
||||
linkPath: link,
|
||||
});
|
||||
|
||||
if (state._tag === "NotSymlink") {
|
||||
return yield* new CodexShadowHomeError({
|
||||
detail: `Cannot create Codex shadow home because '${link}' already exists and is not a symlink.`,
|
||||
return yield* new CodexShadowHomeEntryConflictError({
|
||||
sharedHomePath: input.sharedHomePath,
|
||||
effectiveHomePath: input.effectiveHomePath,
|
||||
entryName: input.entryName,
|
||||
linkPath: link,
|
||||
targetPath: target,
|
||||
});
|
||||
}
|
||||
|
||||
const createLink = input.fileSystem.symlink(target, link).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
new CodexShadowHomeFileSystemError({
|
||||
sharedHomePath: input.sharedHomePath,
|
||||
effectiveHomePath: input.effectiveHomePath,
|
||||
operation: "symlink",
|
||||
path: link,
|
||||
targetPath: target,
|
||||
entryName: input.entryName,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
if (state._tag === "Missing") {
|
||||
return yield* normalizeShadowHomeError(input.fileSystem.symlink(target, link));
|
||||
return yield* createLink;
|
||||
}
|
||||
|
||||
const resolvedExisting = path.resolve(path.dirname(link), state.target);
|
||||
if (resolvedExisting !== target) {
|
||||
yield* normalizeShadowHomeError(input.fileSystem.remove(link));
|
||||
yield* normalizeShadowHomeError(input.fileSystem.symlink(target, link));
|
||||
yield* input.fileSystem.remove(link).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
new CodexShadowHomeFileSystemError({
|
||||
sharedHomePath: input.sharedHomePath,
|
||||
effectiveHomePath: input.effectiveHomePath,
|
||||
operation: "remove",
|
||||
path: link,
|
||||
entryName: input.entryName,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
yield* createLink;
|
||||
}
|
||||
});
|
||||
|
||||
const ensureShadowAuthIsPrivate = Effect.fn("CodexHomeLayout.ensureShadowAuthIsPrivate")(function* (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
shadowPath: string,
|
||||
): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
|
||||
const path = yield* Path.Path;
|
||||
const authPath = path.join(shadowPath, "auth.json");
|
||||
const state = yield* readLinkState(fileSystem, authPath);
|
||||
if (state._tag === "Symlink") {
|
||||
return yield* new CodexShadowHomeError({
|
||||
detail: `Codex shadow auth file '${authPath}' must be a real file, not a symlink.`,
|
||||
const ensureShadowAuthIsPrivate = Effect.fn("CodexHomeLayout.ensureShadowAuthIsPrivate")(
|
||||
function* (input: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly sharedHomePath: string;
|
||||
readonly effectiveHomePath: string;
|
||||
}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
|
||||
const path = yield* Path.Path;
|
||||
const entryName = "auth.json";
|
||||
const authPath = path.join(input.effectiveHomePath, entryName);
|
||||
const state = yield* readLinkState({
|
||||
...input,
|
||||
entryName,
|
||||
linkPath: authPath,
|
||||
});
|
||||
}
|
||||
});
|
||||
if (state._tag === "Symlink") {
|
||||
return yield* new CodexShadowHomePrivateEntrySymlinkError({
|
||||
sharedHomePath: input.sharedHomePath,
|
||||
effectiveHomePath: input.effectiveHomePath,
|
||||
entryName,
|
||||
path: authPath,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const materializeCodexShadowHome = Effect.fn("materializeCodexShadowHome")(function* (
|
||||
layout: CodexHomeLayout,
|
||||
@@ -194,31 +305,51 @@ export const materializeCodexShadowHome = Effect.fn("materializeCodexShadowHome"
|
||||
const effectiveHomePath = layout.effectiveHomePath;
|
||||
if (!effectiveHomePath) return;
|
||||
if (layout.sharedHomePath === effectiveHomePath) {
|
||||
return yield* new CodexShadowHomeError({
|
||||
detail: "Codex shadow home path must be different from the shared home path.",
|
||||
return yield* new CodexShadowHomePathConflictError({
|
||||
sharedHomePath: layout.sharedHomePath,
|
||||
effectiveHomePath,
|
||||
});
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
yield* normalizeShadowHomeError(
|
||||
Effect.all(
|
||||
[
|
||||
fileSystem.makeDirectory(layout.sharedHomePath, { recursive: true }),
|
||||
fileSystem.makeDirectory(effectiveHomePath, { recursive: true }),
|
||||
...KNOWN_SHARED_DIRECTORIES.map((directory) =>
|
||||
fileSystem.makeDirectory(path.join(layout.sharedHomePath, directory), {
|
||||
recursive: true,
|
||||
const makeDirectory = (directoryPath: string) =>
|
||||
fileSystem.makeDirectory(directoryPath, { recursive: true }).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
new CodexShadowHomeFileSystemError({
|
||||
sharedHomePath: layout.sharedHomePath,
|
||||
effectiveHomePath,
|
||||
operation: "makeDirectory",
|
||||
path: directoryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Effect.all(
|
||||
[
|
||||
makeDirectory(layout.sharedHomePath),
|
||||
makeDirectory(effectiveHomePath),
|
||||
...KNOWN_SHARED_DIRECTORIES.map((directory) =>
|
||||
makeDirectory(path.join(layout.sharedHomePath, directory)),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const sharedEntryNames = yield* normalizeShadowHomeError(
|
||||
fileSystem.readDirectory(layout.sharedHomePath),
|
||||
const sharedEntryNames = yield* fileSystem.readDirectory(layout.sharedHomePath).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
new CodexShadowHomeFileSystemError({
|
||||
sharedHomePath: layout.sharedHomePath,
|
||||
effectiveHomePath,
|
||||
operation: "readDirectory",
|
||||
path: layout.sharedHomePath,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const entries = new Set<string>(KNOWN_SHARED_DIRECTORIES);
|
||||
for (const entryName of sharedEntryNames) {
|
||||
@@ -234,7 +365,8 @@ export const materializeCodexShadowHome = Effect.fn("materializeCodexShadowHome"
|
||||
? Effect.void
|
||||
: removePrivateSymlink({
|
||||
fileSystem,
|
||||
shadowPath: effectiveHomePath,
|
||||
sharedHomePath: layout.sharedHomePath,
|
||||
effectiveHomePath,
|
||||
entryName,
|
||||
}),
|
||||
{ discard: true },
|
||||
@@ -248,15 +380,19 @@ export const materializeCodexShadowHome = Effect.fn("materializeCodexShadowHome"
|
||||
}
|
||||
return ensureSymlink({
|
||||
fileSystem,
|
||||
shadowPath: effectiveHomePath,
|
||||
sharedPath: layout.sharedHomePath,
|
||||
sharedHomePath: layout.sharedHomePath,
|
||||
effectiveHomePath,
|
||||
entryName,
|
||||
});
|
||||
},
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
yield* ensureShadowAuthIsPrivate(fileSystem, effectiveHomePath);
|
||||
yield* ensureShadowAuthIsPrivate({
|
||||
fileSystem,
|
||||
sharedHomePath: layout.sharedHomePath,
|
||||
effectiveHomePath,
|
||||
});
|
||||
});
|
||||
|
||||
export function codexContinuationIdentity(layout: CodexHomeLayout) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import * as NodeSocket from "@effect/platform-node/NodeSocket";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import {
|
||||
AuthAccessTokenType,
|
||||
@@ -4541,6 +4542,39 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("reports workspace root stat failures without relabeling them as missing", () =>
|
||||
Effect.gen(function* () {
|
||||
if ((yield* HostProcessPlatform) === "win32") return;
|
||||
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const blockedRoot = yield* fs.makeTempDirectoryScoped({
|
||||
prefix: "t3-ws-workspace-stat-error-",
|
||||
});
|
||||
const workspaceRoot = path.join(blockedRoot, "workspace");
|
||||
yield* fs.makeDirectory(workspaceRoot);
|
||||
yield* fs.chmod(blockedRoot, 0o000);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
return yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.projectsListEntries]({ cwd: workspaceRoot }).pipe(Effect.result),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.ensuring(fs.chmod(blockedRoot, 0o700).pipe(Effect.ignore)));
|
||||
|
||||
if (result._tag !== "Failure" || result.failure._tag !== "ProjectListEntriesError") {
|
||||
assert.fail("Expected a ProjectListEntriesError");
|
||||
}
|
||||
const error = result.failure;
|
||||
assert.equal(error.failure, "workspace_root_stat_failed");
|
||||
assert.equal(error.normalizedCwd, workspaceRoot);
|
||||
assert.equal(error.detail, "validate-existing");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc projects.writeFile", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { VcsProcessExitError } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
|
||||
@@ -329,4 +330,26 @@ describe("AzureDevOpsCli.layer", () => {
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves VCS causes without copying upstream details into messages", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new VcsProcessExitError({
|
||||
operation: "AzureDevOpsCli.execute",
|
||||
command: "az repos list --organization sensitive-upstream-detail",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "sensitive-upstream-detail",
|
||||
});
|
||||
mockRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
|
||||
|
||||
assert.strictEqual(error.command, "az");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.detail, "Azure DevOps CLI command failed.");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes("sensitive-upstream-detail"), false);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -3,7 +3,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
import {
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlRepositoryVisibility,
|
||||
@@ -14,7 +13,6 @@ import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import {
|
||||
decodeAzureDevOpsPullRequestJson,
|
||||
decodeAzureDevOpsPullRequestListJson,
|
||||
formatAzureDevOpsJsonDecodeError,
|
||||
type NormalizedAzureDevOpsPullRequestRecord,
|
||||
} from "./azureDevOpsPullRequests.ts";
|
||||
import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
@@ -25,6 +23,8 @@ export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliE
|
||||
"AzureDevOpsCliError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
cwd: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
@@ -32,6 +32,57 @@ export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliE
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
|
||||
static fromVcsError(
|
||||
context: {
|
||||
readonly operation: "execute";
|
||||
readonly command: "az";
|
||||
readonly cwd: string;
|
||||
},
|
||||
error: VcsError | unknown,
|
||||
): AzureDevOpsCliError {
|
||||
const lower = errorText(error).toLowerCase();
|
||||
|
||||
if (lower.includes("command not found: az") || lower.includes("enoent")) {
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail:
|
||||
"Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("az devops login") ||
|
||||
lower.includes("please run az login") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("unauthorized")
|
||||
) {
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("pull request") &&
|
||||
(lower.includes("not found") || lower.includes("does not exist"))
|
||||
) {
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Azure DevOps CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export interface AzureDevOpsRepositoryCloneUrls {
|
||||
@@ -106,54 +157,6 @@ function errorText(error: VcsError | unknown): string {
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function normalizeAzureDevOpsCliError(
|
||||
operation: "execute",
|
||||
error: VcsError | unknown,
|
||||
): AzureDevOpsCliError {
|
||||
const text = errorText(error);
|
||||
const lower = text.toLowerCase();
|
||||
|
||||
if (lower.includes("command not found: az") || lower.includes("enoent")) {
|
||||
return new AzureDevOpsCliError({
|
||||
operation,
|
||||
detail:
|
||||
"Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("az devops login") ||
|
||||
lower.includes("please run az login") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("unauthorized")
|
||||
) {
|
||||
return new AzureDevOpsCliError({
|
||||
operation,
|
||||
detail: "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("pull request") &&
|
||||
(lower.includes("not found") || lower.includes("does not exist"))
|
||||
) {
|
||||
return new AzureDevOpsCliError({
|
||||
operation,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new AzureDevOpsCliError({
|
||||
operation,
|
||||
detail: text,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeChangeRequestId(reference: string): string {
|
||||
const trimmed = reference.trim().replace(/^#/, "");
|
||||
const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
|
||||
@@ -224,13 +227,16 @@ function decodeAzureDevOpsJson<S extends Schema.Top>(
|
||||
schema: S,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
|
||||
invalidDetail: string,
|
||||
cwd: string,
|
||||
): Effect.Effect<S["Type"], AzureDevOpsCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new AzureDevOpsCliError({
|
||||
operation,
|
||||
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
|
||||
command: "az",
|
||||
cwd,
|
||||
detail: invalidDetail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
@@ -249,7 +255,14 @@ export const make = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => normalizeAzureDevOpsCliError("execute", error)));
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
AzureDevOpsCliError.fromVcsError(
|
||||
{ operation: "execute", command: "az", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const executeJson = (input: Parameters<AzureDevOpsCli["Service"]["execute"]>[0]) =>
|
||||
execute({
|
||||
@@ -286,7 +299,9 @@ export const make = Effect.gen(function* () {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsCliError({
|
||||
operation: "listPullRequests",
|
||||
detail: `Azure DevOps CLI returned invalid PR list JSON: ${formatAzureDevOpsJsonDecodeError(decoded.failure)}`,
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
detail: "Azure DevOps CLI returned invalid PR list JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -318,7 +333,9 @@ export const make = Effect.gen(function* () {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsCliError({
|
||||
operation: "getPullRequest",
|
||||
detail: `Azure DevOps CLI returned invalid pull request JSON: ${formatAzureDevOpsJsonDecodeError(decoded.failure)}`,
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
detail: "Azure DevOps CLI returned invalid pull request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -341,6 +358,7 @@ export const make = Effect.gen(function* () {
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
@@ -370,6 +388,7 @@ export const make = Effect.gen(function* () {
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"createRepository",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
@@ -407,6 +426,7 @@ export const make = Effect.gen(function* () {
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"getDefaultBranch",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
|
||||
|
||||
@@ -46,6 +46,46 @@ it.effect("maps Azure DevOps PR summaries into provider-neutral change requests"
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("adds change-request context while retaining Azure CLI causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new AzureDevOpsCli.AzureDevOpsCliError({
|
||||
operation: "execute",
|
||||
command: "az",
|
||||
cwd: "/repo",
|
||||
detail: "Azure DevOps CLI command failed.",
|
||||
cause: new Error("raw upstream detail that should remain in the cause"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
checkoutPullRequest: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
const error = yield* provider
|
||||
.checkoutChangeRequest({ cwd: "/repo", reference: "#42" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
{
|
||||
provider: error.provider,
|
||||
operation: error.operation,
|
||||
command: error.command,
|
||||
cwd: error.cwd,
|
||||
reference: error.reference,
|
||||
detail: error.detail,
|
||||
},
|
||||
{
|
||||
provider: "azure-devops",
|
||||
operation: "checkoutChangeRequest",
|
||||
command: "az",
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
detail: "Azure DevOps CLI command failed.",
|
||||
},
|
||||
);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes("raw upstream detail"), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates Azure DevOps PRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let createInput:
|
||||
|
||||
@@ -12,18 +12,6 @@ import {
|
||||
type SourceControlCliDiscoverySpec,
|
||||
} from "./SourceControlProviderDiscovery.ts";
|
||||
|
||||
function providerError(
|
||||
operation: string,
|
||||
cause: AzureDevOpsCli.AzureDevOpsCliError,
|
||||
): SourceControlProviderError {
|
||||
return new SourceControlProviderError({
|
||||
provider: "azure-devops",
|
||||
operation,
|
||||
detail: cause.detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function parseAzureAuth(input: SourceControlAuthProbeInput) {
|
||||
const account = input.stdout.trim().split(/\r?\n/)[0]?.trim();
|
||||
|
||||
@@ -101,13 +89,39 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((items) => items.map(toChangeRequest)),
|
||||
Effect.mapError((error) => providerError("listChangeRequests", error)),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "azure-devops",
|
||||
operation: "listChangeRequests",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
getChangeRequest: (input) =>
|
||||
azure.getPullRequest(input).pipe(
|
||||
Effect.map(toChangeRequest),
|
||||
Effect.mapError((error) => providerError("getChangeRequest", error)),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "azure-devops",
|
||||
operation: "getChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.reference,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
createChangeRequest: (input) => {
|
||||
const source = SourceControlProvider.sourceControlRefFromInput(input);
|
||||
@@ -121,20 +135,71 @@ export const make = Effect.gen(function* () {
|
||||
title: input.title,
|
||||
bodyFile: input.bodyFile,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("createChangeRequest", error)));
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "azure-devops",
|
||||
operation: "createChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
azure
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
azure.getRepositoryCloneUrls(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "azure-devops",
|
||||
operation: "getRepositoryCloneUrls",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.repository,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
createRepository: (input) =>
|
||||
azure
|
||||
.createRepository(input)
|
||||
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
|
||||
azure.createRepository(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "azure-devops",
|
||||
operation: "createRepository",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.repository,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
getDefaultBranch: (input) =>
|
||||
azure
|
||||
.getDefaultBranch({ cwd: input.cwd })
|
||||
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
|
||||
azure.getDefaultBranch({ cwd: input.cwd }).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "azure-devops",
|
||||
operation: "getDefaultBranch",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
checkoutChangeRequest: (input) =>
|
||||
azure
|
||||
.checkoutPullRequest({
|
||||
@@ -142,7 +207,22 @@ export const make = Effect.gen(function* () {
|
||||
reference: input.reference,
|
||||
...(input.context !== undefined ? { remoteName: input.context.remoteName } : {}),
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "azure-devops",
|
||||
operation: "checkoutChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.reference,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -51,6 +51,45 @@ it.effect("maps Bitbucket PR summaries into provider-neutral change requests", (
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("adds repository context while retaining Bitbucket API causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new BitbucketApi.BitbucketApiError({
|
||||
operation: "getRepository",
|
||||
detail: "upstream detail that should remain in the cause",
|
||||
status: 503,
|
||||
cause: new Error("raw upstream failure"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
getRepositoryCloneUrls: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
const error = yield* provider
|
||||
.getRepositoryCloneUrls({ cwd: "/repo", repository: "owner/repo" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
{
|
||||
provider: error.provider,
|
||||
operation: error.operation,
|
||||
command: error.command,
|
||||
cwd: error.cwd,
|
||||
repository: error.repository,
|
||||
detail: error.detail,
|
||||
},
|
||||
{
|
||||
provider: "bitbucket",
|
||||
operation: "getRepositoryCloneUrls",
|
||||
command: undefined,
|
||||
cwd: "/repo",
|
||||
repository: "owner/repo",
|
||||
detail: "Failed to get repository clone URLs.",
|
||||
},
|
||||
);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes(cause.detail), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lists Bitbucket PRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let listInput: Parameters<BitbucketApi.BitbucketApi["Service"]["listPullRequests"]>[0] | null =
|
||||
|
||||
@@ -8,18 +8,6 @@ import type { NormalizedBitbucketPullRequestRecord } from "./bitbucketPullReques
|
||||
import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
import type { SourceControlApiDiscoverySpec } from "./SourceControlProviderDiscovery.ts";
|
||||
|
||||
function providerError(
|
||||
operation: string,
|
||||
cause: BitbucketApi.BitbucketApiError,
|
||||
): SourceControlProviderError {
|
||||
return new SourceControlProviderError({
|
||||
provider: "bitbucket",
|
||||
operation,
|
||||
detail: cause.detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function toChangeRequest(summary: NormalizedBitbucketPullRequestRecord): ChangeRequest {
|
||||
return {
|
||||
provider: "bitbucket",
|
||||
@@ -60,13 +48,37 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((items) => items.map(toChangeRequest)),
|
||||
Effect.mapError((error) => providerError("listChangeRequests", error)),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "bitbucket",
|
||||
operation: "listChangeRequests",
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: "Failed to list change requests.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
getChangeRequest: (input) =>
|
||||
bitbucket.getPullRequest(input).pipe(
|
||||
Effect.map(toChangeRequest),
|
||||
Effect.mapError((error) => providerError("getChangeRequest", error)),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "bitbucket",
|
||||
operation: "getChangeRequest",
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.reference,
|
||||
),
|
||||
detail: "Failed to get change request.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
createChangeRequest: (input) => {
|
||||
const source = SourceControlProvider.sourceControlRefFromInput(input);
|
||||
@@ -81,23 +93,72 @@ export const make = Effect.gen(function* () {
|
||||
title: input.title,
|
||||
bodyFile: input.bodyFile,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("createChangeRequest", error)));
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "bitbucket",
|
||||
operation: "createChangeRequest",
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: "Failed to create change request.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
bitbucket
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
bitbucket.getRepositoryCloneUrls(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "bitbucket",
|
||||
operation: "getRepositoryCloneUrls",
|
||||
cwd: input.cwd,
|
||||
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.repository,
|
||||
),
|
||||
detail: "Failed to get repository clone URLs.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
createRepository: (input) =>
|
||||
bitbucket
|
||||
.createRepository(input)
|
||||
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
|
||||
bitbucket.createRepository(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "bitbucket",
|
||||
operation: "createRepository",
|
||||
cwd: input.cwd,
|
||||
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.repository,
|
||||
),
|
||||
detail: "Failed to create repository.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
getDefaultBranch: (input) =>
|
||||
bitbucket
|
||||
.getDefaultBranch({
|
||||
cwd: input.cwd,
|
||||
...(input.context ? { context: input.context } : {}),
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "bitbucket",
|
||||
operation: "getDefaultBranch",
|
||||
cwd: input.cwd,
|
||||
detail: "Failed to get default branch.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
checkoutChangeRequest: (input) =>
|
||||
bitbucket
|
||||
.checkoutPullRequest({
|
||||
@@ -106,7 +167,21 @@ export const make = Effect.gen(function* () {
|
||||
reference: input.reference,
|
||||
...(input.force !== undefined ? { force: input.force } : {}),
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "bitbucket",
|
||||
operation: "checkoutChangeRequest",
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.reference,
|
||||
),
|
||||
detail: "Failed to check out change request.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -269,18 +269,15 @@ describe("GitHubCli.layer", () => {
|
||||
|
||||
it.effect("surfaces a friendly error when the pull request is not found", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.fail(
|
||||
new VcsProcessExitError({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh pr view",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail:
|
||||
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
|
||||
}),
|
||||
),
|
||||
);
|
||||
const cause = new VcsProcessExitError({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh pr view",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail:
|
||||
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
|
||||
});
|
||||
mockRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const error = yield* gh
|
||||
@@ -291,6 +288,10 @@ describe("GitHubCli.layer", () => {
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Pull request not found"), true);
|
||||
assert.strictEqual(error.command, "gh");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes(cause.detail), false);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -3,7 +3,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
|
||||
import {
|
||||
TrimmedNonEmptyString,
|
||||
@@ -15,19 +14,71 @@ import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import {
|
||||
decodeGitHubPullRequestJson,
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "./gitHubPullRequests.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
cwd: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
|
||||
static fromVcsError(
|
||||
context: {
|
||||
readonly operation: "execute";
|
||||
readonly command: "gh";
|
||||
readonly cwd: string;
|
||||
},
|
||||
error: VcsError | unknown,
|
||||
): GitHubCliError {
|
||||
const lower = errorText(error).toLowerCase();
|
||||
|
||||
if (lower.includes("command not found: gh") || lower.includes("enoent")) {
|
||||
return new GitHubCliError({
|
||||
...context,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("gh auth login") ||
|
||||
lower.includes("no oauth token")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
...context,
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("could not resolve to a pullrequest") ||
|
||||
lower.includes("repository.pullrequest") ||
|
||||
lower.includes("no pull requests found for branch") ||
|
||||
lower.includes("pull request not found")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
...context,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitHubCliError({
|
||||
...context,
|
||||
detail: "GitHub CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export interface GitHubPullRequestSummary {
|
||||
@@ -110,54 +161,6 @@ function errorText(error: VcsError | unknown): string {
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function normalizeGitHubCliError(
|
||||
operation: "execute" | "stdout",
|
||||
error: VcsError | unknown,
|
||||
): GitHubCliError {
|
||||
const text = errorText(error);
|
||||
const lower = text.toLowerCase();
|
||||
|
||||
if (lower.includes("command not found: gh") || lower.includes("enoent")) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("gh auth login") ||
|
||||
lower.includes("no oauth token")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("could not resolve to a pullrequest") ||
|
||||
lower.includes("repository.pullrequest") ||
|
||||
lower.includes("no pull requests found for branch") ||
|
||||
lower.includes("pull request not found")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: text,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
nameWithOwner: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
@@ -216,13 +219,16 @@ function decodeGitHubJson<S extends Schema.Top>(
|
||||
schema: S,
|
||||
operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
|
||||
invalidDetail: string,
|
||||
cwd: string,
|
||||
): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new GitHubCliError({
|
||||
operation,
|
||||
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
|
||||
command: "gh",
|
||||
cwd,
|
||||
detail: invalidDetail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
@@ -241,7 +247,14 @@ export const make = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => normalizeGitHubCliError("execute", error)));
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
GitHubCliError.fromVcsError(
|
||||
{ operation: "execute", command: "gh", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return GitHubCli.of({
|
||||
execute,
|
||||
@@ -271,7 +284,9 @@ export const make = Effect.gen(function* () {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "listOpenPullRequests",
|
||||
detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: "GitHub CLI returned invalid PR list JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -303,7 +318,9 @@ export const make = Effect.gen(function* () {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "getPullRequest",
|
||||
detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: "GitHub CLI returned invalid pull request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -328,6 +345,7 @@ export const make = Effect.gen(function* () {
|
||||
RawGitHubRepositoryCloneUrlsSchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"GitHub CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
|
||||
@@ -68,6 +68,49 @@ it.effect("maps GitHub PR summaries into provider-neutral change requests", () =
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("adds safe request context while retaining GitHub CLI causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: "/repo",
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: new Error("raw upstream detail that should remain in the cause"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
getPullRequest: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
const error = yield* provider
|
||||
.getChangeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "https://user:[email protected]/pingdotgg/t3code/pull/42?token=secret#diff",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
{
|
||||
provider: error.provider,
|
||||
operation: error.operation,
|
||||
command: error.command,
|
||||
cwd: error.cwd,
|
||||
reference: error.reference,
|
||||
detail: error.detail,
|
||||
},
|
||||
{
|
||||
provider: "github",
|
||||
operation: "getChangeRequest",
|
||||
command: "gh",
|
||||
cwd: "/repo",
|
||||
reference: "https://github.com/pingdotgg/t3code/pull/42",
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
},
|
||||
);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes("raw upstream detail"), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses gh json listing for non-open change request state queries", () =>
|
||||
Effect.gen(function* () {
|
||||
let executeArgs: ReadonlyArray<string> = [];
|
||||
|
||||
@@ -2,7 +2,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
SourceControlProviderError,
|
||||
type ChangeRequest,
|
||||
@@ -20,19 +19,6 @@ import {
|
||||
type SourceControlAuthProbeInput,
|
||||
type SourceControlCliDiscoverySpec,
|
||||
} from "./SourceControlProviderDiscovery.ts";
|
||||
const isSourceControlProviderError = Schema.is(SourceControlProviderError);
|
||||
|
||||
function providerError(
|
||||
operation: string,
|
||||
cause: GitHubCli.GitHubCliError,
|
||||
): SourceControlProviderError {
|
||||
return new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation,
|
||||
detail: cause.detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeRequest {
|
||||
return {
|
||||
@@ -122,7 +108,20 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((items) => items.map(toChangeRequest)),
|
||||
Effect.mapError((error) => providerError("listChangeRequests", error)),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "listChangeRequests",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -162,6 +161,11 @@ export const make = Effect.gen(function* () {
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "listChangeRequests",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: "GitHub CLI returned invalid change request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
@@ -169,11 +173,20 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.mapError((error) =>
|
||||
isSourceControlProviderError(error)
|
||||
? error
|
||||
: providerError("listChangeRequests", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
GitHubCliError: (error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "listChangeRequests",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -183,7 +196,20 @@ export const make = Effect.gen(function* () {
|
||||
getChangeRequest: (input) =>
|
||||
github.getPullRequest(input).pipe(
|
||||
Effect.map(toChangeRequest),
|
||||
Effect.mapError((error) => providerError("getChangeRequest", error)),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "getChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.reference,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
createChangeRequest: (input) =>
|
||||
github
|
||||
@@ -194,23 +220,87 @@ export const make = Effect.gen(function* () {
|
||||
title: input.title,
|
||||
bodyFile: input.bodyFile,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("createChangeRequest", error))),
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "createChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
github
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
github.getRepositoryCloneUrls(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "getRepositoryCloneUrls",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.repository,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
createRepository: (input) =>
|
||||
github
|
||||
.createRepository(input)
|
||||
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
|
||||
github.createRepository(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "createRepository",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.repository,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
getDefaultBranch: (input) =>
|
||||
github
|
||||
.getDefaultBranch(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
|
||||
github.getDefaultBranch(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "getDefaultBranch",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
checkoutChangeRequest: (input) =>
|
||||
github
|
||||
.checkoutPullRequest(input)
|
||||
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
|
||||
github.checkoutPullRequest(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "checkoutChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.reference,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -313,17 +313,14 @@ layer("GitLabCli.layer", (it) => {
|
||||
|
||||
it.effect("surfaces a friendly error when the merge request is not found", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(
|
||||
Effect.fail(
|
||||
new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab mr view 4888",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 merge request not found",
|
||||
}),
|
||||
),
|
||||
);
|
||||
const cause = new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab mr view 4888",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 merge request not found",
|
||||
});
|
||||
mockedRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
@@ -334,6 +331,10 @@ layer("GitLabCli.layer", (it) => {
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Merge request not found"), true);
|
||||
assert.strictEqual(error.command, "glab");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes(cause.detail), false);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -4,16 +4,18 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
import type * as DateTime from "effect/DateTime";
|
||||
|
||||
import { TrimmedNonEmptyString, type SourceControlRepositoryVisibility } from "@t3tools/contracts";
|
||||
import {
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlRepositoryVisibility,
|
||||
type VcsError,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import {
|
||||
decodeGitLabMergeRequestJson,
|
||||
decodeGitLabMergeRequestListJson,
|
||||
formatGitLabJsonDecodeError,
|
||||
} from "./gitLabMergeRequests.ts";
|
||||
import type * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
|
||||
@@ -21,12 +23,64 @@ const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
cwd: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
|
||||
static fromVcsError(
|
||||
context: {
|
||||
readonly operation: "execute";
|
||||
readonly command: "glab";
|
||||
readonly cwd: string;
|
||||
},
|
||||
error: VcsError | unknown,
|
||||
): GitLabCliError {
|
||||
const lower = errorText(error).toLowerCase();
|
||||
|
||||
if (lower.includes("command not found: glab") || isVcsProcessSpawnError(error)) {
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "GitLab CLI (`glab`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("glab auth login") ||
|
||||
lower.includes("token")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("merge request not found") ||
|
||||
lower.includes("not found") ||
|
||||
lower.includes("404")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "Merge request not found. Check the MR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "GitLab CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export interface GitLabMergeRequestSummary {
|
||||
@@ -48,6 +102,17 @@ export interface GitLabRepositoryCloneUrls {
|
||||
readonly sshUrl: string;
|
||||
}
|
||||
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
if (typeof error === "object" && error !== null) {
|
||||
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
|
||||
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
|
||||
const message = "message" in error && typeof error.message === "string" ? error.message : "";
|
||||
return [tag, detail, message].filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
export class GitLabCli extends Context.Service<
|
||||
GitLabCli,
|
||||
{
|
||||
@@ -112,56 +177,6 @@ function isVcsProcessSpawnError(error: unknown): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeGitLabCliError(operation: "execute" | "stdout", error: unknown): GitLabCliError {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes("Command not found: glab") || isVcsProcessSpawnError(error)) {
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "GitLab CLI (`glab`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("glab auth login") ||
|
||||
lower.includes("token")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("merge request not found") ||
|
||||
lower.includes("not found") ||
|
||||
lower.includes("404")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "Merge request not found. Check the MR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: `GitLab CLI command failed: ${error.message}`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "GitLab CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
path_with_namespace: TrimmedNonEmptyString,
|
||||
web_url: TrimmedNonEmptyString,
|
||||
@@ -192,13 +207,16 @@ function decodeGitLabJson<S extends Schema.Top>(
|
||||
schema: S,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
|
||||
invalidDetail: string,
|
||||
cwd: string,
|
||||
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new GitLabCliError({
|
||||
operation,
|
||||
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
|
||||
command: "glab",
|
||||
cwd,
|
||||
detail: invalidDetail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
@@ -274,7 +292,14 @@ export const make = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => normalizeGitLabCliError("execute", error)));
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
GitLabCliError.fromVcsError(
|
||||
{ operation: "execute", command: "glab", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return GitLabCli.of({
|
||||
execute,
|
||||
@@ -303,7 +328,9 @@ export const make = Effect.gen(function* () {
|
||||
return Effect.fail(
|
||||
new GitLabCliError({
|
||||
operation: "listMergeRequests",
|
||||
detail: `GitLab CLI returned invalid MR list JSON: ${formatGitLabJsonDecodeError(decoded.failure)}`,
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
detail: "GitLab CLI returned invalid MR list JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -327,7 +354,9 @@ export const make = Effect.gen(function* () {
|
||||
return Effect.fail(
|
||||
new GitLabCliError({
|
||||
operation: "getMergeRequest",
|
||||
detail: `GitLab CLI returned invalid merge request JSON: ${formatGitLabJsonDecodeError(decoded.failure)}`,
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
detail: "GitLab CLI returned invalid merge request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -350,6 +379,7 @@ export const make = Effect.gen(function* () {
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
@@ -368,6 +398,7 @@ export const make = Effect.gen(function* () {
|
||||
RawGitLabNamespaceSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid namespace JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map((namespace) => namespace.id),
|
||||
@@ -402,6 +433,7 @@ export const make = Effect.gen(function* () {
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
@@ -440,6 +472,7 @@ export const make = Effect.gen(function* () {
|
||||
RawGitLabDefaultBranchSchema,
|
||||
"getDefaultBranch",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map((value) => value.default_branch ?? null),
|
||||
|
||||
@@ -52,6 +52,50 @@ it.effect("maps GitLab MR summaries into provider-neutral change requests", () =
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("adds repository context while retaining GitLab CLI causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new GitLabCli.GitLabCliError({
|
||||
operation: "execute",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
detail: "GitLab CLI command failed.",
|
||||
cause: new Error("raw upstream detail that should remain in the cause"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
createRepository: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
const error = yield* provider
|
||||
.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "owner/repo",
|
||||
visibility: "private",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
{
|
||||
provider: error.provider,
|
||||
operation: error.operation,
|
||||
command: error.command,
|
||||
cwd: error.cwd,
|
||||
repository: error.repository,
|
||||
detail: error.detail,
|
||||
},
|
||||
{
|
||||
provider: "gitlab",
|
||||
operation: "createRepository",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
repository: "owner/repo",
|
||||
detail: "GitLab CLI command failed.",
|
||||
},
|
||||
);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes("raw upstream detail"), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lists GitLab MRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let listInput: Parameters<GitLabCli.GitLabCli["Service"]["listMergeRequests"]>[0] | null = null;
|
||||
|
||||
@@ -17,18 +17,6 @@ import {
|
||||
} from "./SourceControlProviderDiscovery.ts";
|
||||
import { findAuthenticatedGitLabHost, parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts";
|
||||
|
||||
function providerError(
|
||||
operation: string,
|
||||
cause: GitLabCli.GitLabCliError,
|
||||
): SourceControlProviderError {
|
||||
return new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation,
|
||||
detail: cause.detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function toChangeRequest(summary: GitLabCli.GitLabMergeRequestSummary): ChangeRequest {
|
||||
return {
|
||||
provider: "gitlab",
|
||||
@@ -129,13 +117,39 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((items) => items.map(toChangeRequest)),
|
||||
Effect.mapError((error) => providerError("listChangeRequests", error)),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "listChangeRequests",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
getChangeRequest: (input) =>
|
||||
gitlab.getMergeRequest(input).pipe(
|
||||
Effect.map(toChangeRequest),
|
||||
Effect.mapError((error) => providerError("getChangeRequest", error)),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "getChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.reference,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
createChangeRequest: (input) => {
|
||||
const source = SourceControlProvider.sourceControlRefFromInput(input);
|
||||
@@ -149,24 +163,88 @@ export const make = Effect.gen(function* () {
|
||||
title: input.title,
|
||||
bodyFile: input.bodyFile,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("createChangeRequest", error)));
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "createChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
gitlab
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
gitlab.getRepositoryCloneUrls(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "getRepositoryCloneUrls",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.repository,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
createRepository: (input) =>
|
||||
gitlab
|
||||
.createRepository(input)
|
||||
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
|
||||
gitlab.createRepository(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "createRepository",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.repository,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
getDefaultBranch: (input) =>
|
||||
gitlab
|
||||
.getDefaultBranch(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
|
||||
gitlab.getDefaultBranch(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "getDefaultBranch",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
checkoutChangeRequest: (input) =>
|
||||
gitlab
|
||||
.checkoutMergeRequest(input)
|
||||
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
|
||||
gitlab.checkoutMergeRequest(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "checkoutChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.reference,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { transportSafeSourceControlErrorValue } from "./SourceControlProvider.ts";
|
||||
|
||||
it("removes URL credentials, query parameters, and fragments from error transport values", () => {
|
||||
assert.strictEqual(
|
||||
transportSafeSourceControlErrorValue(
|
||||
"https://user:[email protected]/org/repo/pull/42?token=secret#discussion",
|
||||
),
|
||||
"https://example.test/org/repo/pull/42",
|
||||
);
|
||||
});
|
||||
|
||||
it("normalizes control characters and bounds error transport values", () => {
|
||||
assert.strictEqual(
|
||||
transportSafeSourceControlErrorValue(` owner/repo\n\t${"x".repeat(300)} `),
|
||||
`owner/repo ${"x".repeat(245)}`,
|
||||
);
|
||||
});
|
||||
@@ -22,6 +22,36 @@ export interface SourceControlRefSelector {
|
||||
readonly repository?: string;
|
||||
}
|
||||
|
||||
const MAX_ERROR_TRANSPORT_VALUE_LENGTH = 256;
|
||||
|
||||
/**
|
||||
* Sanitizes user-provided source-control identifiers before attaching them to
|
||||
* contract errors. This is intentionally narrower than request validation: it
|
||||
* only strips URL secrets and bounds diagnostic values sent over transport.
|
||||
*/
|
||||
export function transportSafeSourceControlErrorValue(value: string): string {
|
||||
let printable = "";
|
||||
for (const character of value) {
|
||||
const codePoint = character.codePointAt(0);
|
||||
printable += codePoint !== undefined && (codePoint < 32 || codePoint === 127) ? " " : character;
|
||||
}
|
||||
const normalized = printable.trim().replace(/\s+/gu, " ");
|
||||
|
||||
let safe = normalized;
|
||||
try {
|
||||
const url = new URL(normalized);
|
||||
url.username = "";
|
||||
url.password = "";
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
safe = url.toString();
|
||||
} catch {
|
||||
// Plain repository and change-request identifiers are not URLs.
|
||||
}
|
||||
|
||||
return safe.slice(0, MAX_ERROR_TRANSPORT_VALUE_LENGTH);
|
||||
}
|
||||
|
||||
export function parseSourceControlOwnerRef(
|
||||
headSelector: string,
|
||||
): SourceControlRefSelector | undefined {
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { VcsRepositoryDetectionError } from "@t3tools/contracts";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import type * as VcsDriver from "../vcs/VcsDriver.ts";
|
||||
@@ -38,6 +39,7 @@ function makeRegistry(input: {
|
||||
readonly url: string;
|
||||
}>;
|
||||
readonly process?: Partial<VcsProcess.VcsProcess["Service"]>;
|
||||
readonly resolve?: VcsDriverRegistry.VcsDriverRegistry["Service"]["resolve"];
|
||||
}) {
|
||||
const driver = {
|
||||
listRemotes: () =>
|
||||
@@ -57,21 +59,23 @@ function makeRegistry(input: {
|
||||
|
||||
const registryLayer = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
|
||||
get: () => Effect.succeed(driver as unknown as VcsDriver.VcsDriver["Service"]),
|
||||
resolve: () =>
|
||||
Effect.succeed({
|
||||
kind: "git",
|
||||
repository: {
|
||||
resolve:
|
||||
input.resolve ??
|
||||
(() =>
|
||||
Effect.succeed({
|
||||
kind: "git",
|
||||
rootPath: "/repo",
|
||||
metadataPath: null,
|
||||
freshness: {
|
||||
source: "live-local" as const,
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
repository: {
|
||||
kind: "git",
|
||||
rootPath: "/repo",
|
||||
metadataPath: null,
|
||||
freshness: {
|
||||
source: "live-local" as const,
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
},
|
||||
},
|
||||
driver: driver as unknown as VcsDriver.VcsDriver["Service"],
|
||||
}),
|
||||
driver: driver as unknown as VcsDriver.VcsDriver["Service"],
|
||||
})),
|
||||
});
|
||||
|
||||
const processLayer = Layer.mock(VcsProcess.VcsProcess)({
|
||||
@@ -120,6 +124,46 @@ it.effect("routes directly by provider kind for remote-first workflows", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("includes the request cwd when an unregistered provider is used", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* makeRegistry({ remotes: [] });
|
||||
const provider = yield* registry.get("unknown");
|
||||
|
||||
const error = yield* provider
|
||||
.getChangeRequest({ cwd: "/repo", reference: "#42" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.strictEqual(error.provider, "unknown");
|
||||
assert.strictEqual(error.operation, "getChangeRequest");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.reference, "#42");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retains VCS detection failures with structured cwd context", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new VcsRepositoryDetectionError({
|
||||
operation: "resolve",
|
||||
cwd: "/repo",
|
||||
detail: "raw VCS detection failure",
|
||||
cause: new Error("raw nested failure"),
|
||||
});
|
||||
const registry = yield* makeRegistry({
|
||||
remotes: [],
|
||||
resolve: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
const error = yield* registry.resolve({ cwd: "/repo" }).pipe(Effect.flip);
|
||||
|
||||
assert.strictEqual(error.provider, "unknown");
|
||||
assert.strictEqual(error.operation, "detectProvider");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.detail, "Failed to detect source control provider.");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes(cause.message), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes GitLab remotes to the GitLab provider", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* makeRegistry({
|
||||
|
||||
@@ -64,33 +64,62 @@ export class SourceControlProviderRegistry extends Context.Service<
|
||||
function unsupportedProvider(
|
||||
kind: SourceControlProviderKind,
|
||||
): SourceControlProvider.SourceControlProvider["Service"] {
|
||||
const unsupported = (operation: string) =>
|
||||
Effect.fail(
|
||||
new SourceControlProviderError({
|
||||
provider: kind,
|
||||
operation,
|
||||
detail: `No ${kind} source control provider is registered.`,
|
||||
}),
|
||||
);
|
||||
|
||||
return SourceControlProvider.SourceControlProvider.of({
|
||||
kind,
|
||||
listChangeRequests: () => unsupported("listChangeRequests"),
|
||||
getChangeRequest: () => unsupported("getChangeRequest"),
|
||||
createChangeRequest: () => unsupported("createChangeRequest"),
|
||||
getRepositoryCloneUrls: () => unsupported("getRepositoryCloneUrls"),
|
||||
createRepository: () => unsupported("createRepository"),
|
||||
getDefaultBranch: () => unsupported("getDefaultBranch"),
|
||||
checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
|
||||
});
|
||||
}
|
||||
|
||||
function providerDetectionError(operation: string, cwd: string, cause: unknown) {
|
||||
return new SourceControlProviderError({
|
||||
provider: "unknown",
|
||||
operation,
|
||||
detail: `Failed to detect source control provider for ${cwd}.`,
|
||||
cause,
|
||||
listChangeRequests: (input) =>
|
||||
new SourceControlProviderError({
|
||||
provider: kind,
|
||||
operation: "listChangeRequests",
|
||||
cwd: input.cwd,
|
||||
detail: `No ${kind} source control provider is registered.`,
|
||||
}),
|
||||
getChangeRequest: (input) =>
|
||||
new SourceControlProviderError({
|
||||
provider: kind,
|
||||
operation: "getChangeRequest",
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.reference),
|
||||
detail: `No ${kind} source control provider is registered.`,
|
||||
}),
|
||||
createChangeRequest: (input) =>
|
||||
new SourceControlProviderError({
|
||||
provider: kind,
|
||||
operation: "createChangeRequest",
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.headSelector),
|
||||
detail: `No ${kind} source control provider is registered.`,
|
||||
}),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
new SourceControlProviderError({
|
||||
provider: kind,
|
||||
operation: "getRepositoryCloneUrls",
|
||||
cwd: input.cwd,
|
||||
repository: SourceControlProvider.transportSafeSourceControlErrorValue(input.repository),
|
||||
detail: `No ${kind} source control provider is registered.`,
|
||||
}),
|
||||
createRepository: (input) =>
|
||||
new SourceControlProviderError({
|
||||
provider: kind,
|
||||
operation: "createRepository",
|
||||
cwd: input.cwd,
|
||||
repository: SourceControlProvider.transportSafeSourceControlErrorValue(input.repository),
|
||||
detail: `No ${kind} source control provider is registered.`,
|
||||
}),
|
||||
getDefaultBranch: (input) =>
|
||||
new SourceControlProviderError({
|
||||
provider: kind,
|
||||
operation: "getDefaultBranch",
|
||||
cwd: input.cwd,
|
||||
detail: `No ${kind} source control provider is registered.`,
|
||||
}),
|
||||
checkoutChangeRequest: (input) =>
|
||||
new SourceControlProviderError({
|
||||
provider: kind,
|
||||
operation: "checkoutChangeRequest",
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.reference),
|
||||
detail: `No ${kind} source control provider is registered.`,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -180,12 +209,30 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
|
||||
|
||||
const detectProviderContext = Effect.fn("SourceControlProviderRegistry.detectProviderContext")(
|
||||
function* (cwd: string) {
|
||||
const handle = yield* vcsRegistry
|
||||
.resolve({ cwd })
|
||||
.pipe(Effect.mapError((error) => providerDetectionError("detectProvider", cwd, error)));
|
||||
const remotes = yield* handle.driver
|
||||
.listRemotes(cwd)
|
||||
.pipe(Effect.mapError((error) => providerDetectionError("detectProvider", cwd, error)));
|
||||
const handle = yield* vcsRegistry.resolve({ cwd }).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "unknown",
|
||||
operation: "detectProvider",
|
||||
cwd,
|
||||
detail: "Failed to detect source control provider.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const remotes = yield* handle.driver.listRemotes(cwd).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "unknown",
|
||||
operation: "detectProvider",
|
||||
cwd,
|
||||
detail: "Failed to detect source control provider.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const context = selectProviderContext(remotes.remotes);
|
||||
|
||||
return yield* refineUnknownRemoteProvider({
|
||||
|
||||
@@ -234,28 +234,30 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
);
|
||||
|
||||
const envelope = yield* decodeClaudeOutputEnvelope(rawStdout).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Claude CLI returned unexpected output format.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SchemaError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Claude CLI returned unexpected output format.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const decodeOutput = Schema.decodeEffect(outputSchemaJson);
|
||||
return yield* decodeOutput(envelope.structured_output).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Claude returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SchemaError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Claude returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -281,15 +281,16 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
}),
|
||||
),
|
||||
Effect.flatMap(decodeOutput),
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Codex returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SchemaError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Codex returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
@@ -28,30 +28,7 @@ import {
|
||||
|
||||
const CURSOR_TIMEOUT_MS = 180_000;
|
||||
|
||||
function mapCursorAcpError(
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
detail: string,
|
||||
cause: unknown,
|
||||
): TextGenerationError {
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail,
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function isTextGenerationError(error: unknown): error is TextGenerationError {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
error._tag === "TextGenerationError"
|
||||
);
|
||||
}
|
||||
const isTextGenerationError = Schema.is(TextGenerationError);
|
||||
|
||||
/**
|
||||
* Build a Cursor text-generation closure bound to a specific `CursorSettings`
|
||||
@@ -111,13 +88,14 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
model: modelSelection.model,
|
||||
selections: modelSelection.options,
|
||||
mapError: ({ cause, configId, step }) =>
|
||||
mapCursorAcpError(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
step === "set-config-option"
|
||||
? `Failed to set Cursor ACP config option "${configId}" for text generation.`
|
||||
: "Failed to set Cursor ACP base model for text generation.",
|
||||
detail:
|
||||
step === "set-config-option"
|
||||
? `Failed to set Cursor ACP config option "${configId}" for text generation.`
|
||||
: "Failed to set Cursor ACP base model for text generation.",
|
||||
cause,
|
||||
),
|
||||
}),
|
||||
});
|
||||
|
||||
return yield* runtime.prompt({
|
||||
@@ -140,7 +118,11 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
Effect.mapError((cause) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: mapCursorAcpError(operation, "Cursor ACP request failed.", cause),
|
||||
: new TextGenerationError({
|
||||
operation,
|
||||
detail: "Cursor ACP request failed.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -157,21 +139,26 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
|
||||
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
|
||||
return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Cursor Agent returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SchemaError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Cursor Agent returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: mapCursorAcpError(operation, "Cursor ACP text generation failed.", cause),
|
||||
: new TextGenerationError({
|
||||
operation,
|
||||
detail: "Cursor ACP text generation failed.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
|
||||
@@ -31,30 +31,7 @@ import {
|
||||
|
||||
const GROK_TIMEOUT_MS = 180_000;
|
||||
|
||||
function mapGrokAcpError(
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
detail: string,
|
||||
cause: unknown,
|
||||
): TextGenerationError {
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail,
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function isTextGenerationError(error: unknown): error is TextGenerationError {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
error._tag === "TextGenerationError"
|
||||
);
|
||||
}
|
||||
const isTextGenerationError = Schema.is(TextGenerationError);
|
||||
|
||||
export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(function* (
|
||||
grokSettings: GrokSettings,
|
||||
@@ -109,11 +86,11 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
currentModelId: currentGrokModelIdFromSessionSetup(started.sessionSetupResult),
|
||||
requestedModelId: resolvedModel,
|
||||
mapError: (cause) =>
|
||||
mapGrokAcpError(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
"Failed to set Grok ACP base model for text generation.",
|
||||
detail: "Failed to set Grok ACP base model for text generation.",
|
||||
cause,
|
||||
),
|
||||
}),
|
||||
});
|
||||
|
||||
return yield* runtime.prompt({
|
||||
@@ -133,7 +110,11 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
Effect.mapError((cause: EffectAcpErrors.AcpError | TextGenerationError) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: mapGrokAcpError(operation, "Grok ACP request failed.", cause),
|
||||
: new TextGenerationError({
|
||||
operation,
|
||||
detail: "Grok ACP request failed.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -150,21 +131,26 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
|
||||
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
|
||||
return yield* decodeOutput(extractJsonObject(trimmed)).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Grok Agent returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SchemaError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Grok Agent returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: mapGrokAcpError(operation, "Grok ACP text generation failed.", cause),
|
||||
: new TextGenerationError({
|
||||
operation,
|
||||
detail: "Grok ACP text generation failed.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
|
||||
@@ -348,15 +348,16 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
|
||||
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson));
|
||||
return yield* decodeOutput(extractJsonObject(rawOutput)).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: "OpenCode returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SchemaError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: "OpenCode returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -190,4 +190,16 @@ describe("normalizeCliError", () => {
|
||||
expect(result).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.detail).toBe("fallback");
|
||||
});
|
||||
|
||||
it("does not expose CLI failure details in the public error message", () => {
|
||||
const result = normalizeCliError(
|
||||
"codex",
|
||||
"generateCommitMessage",
|
||||
new Error("request failed with access_token=secret-token"),
|
||||
"Failed to generate a commit message",
|
||||
);
|
||||
|
||||
expect(result.detail).toBe("Failed to generate a commit message");
|
||||
expect(result.message).not.toContain("secret-token");
|
||||
});
|
||||
});
|
||||
@@ -99,7 +99,7 @@ export function normalizeCliError(
|
||||
}
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: `${fallback}: ${error.message}`,
|
||||
detail: fallback,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -73,6 +73,7 @@ export type WorkspaceEntriesBrowseError = typeof WorkspaceEntriesBrowseError.Typ
|
||||
export const WorkspaceEntriesError = Schema.Union([
|
||||
WorkspacePaths.WorkspaceRootNotExistsError,
|
||||
WorkspacePaths.WorkspaceRootCreateFailedError,
|
||||
WorkspacePaths.WorkspaceRootStatFailedError,
|
||||
WorkspacePaths.WorkspaceRootNotDirectoryError,
|
||||
WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed,
|
||||
WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut,
|
||||
|
||||
@@ -4,6 +4,7 @@ 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 WorkspacePaths from "./WorkspacePaths.ts";
|
||||
|
||||
@@ -91,6 +92,79 @@ it.layer(TestLayer)("WorkspacePathsLive", (it) => {
|
||||
expect(error.message).toContain("Workspace root is not a directory:");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves non-NotFound stat failures while validating the root", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const workspacePaths = yield* WorkspacePaths.make.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, {
|
||||
...fileSystem,
|
||||
stat: (path) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "stat",
|
||||
pathOrDescriptor: String(path),
|
||||
description: "Test PermissionDenied stat failure.",
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
const path = yield* Path.Path;
|
||||
const workspaceRoot = " ./permission-denied ";
|
||||
const normalizedWorkspaceRoot = path.resolve(workspaceRoot.trim());
|
||||
|
||||
const error = yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(WorkspacePaths.WorkspaceRootStatFailedError);
|
||||
expect(error).toMatchObject({
|
||||
workspaceRoot,
|
||||
normalizedWorkspaceRoot,
|
||||
phase: "validate-existing",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves stat failures while verifying a newly created root", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
let statCalls = 0;
|
||||
const workspacePaths = yield* WorkspacePaths.make.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, {
|
||||
...fileSystem,
|
||||
stat: (path) => {
|
||||
statCalls += 1;
|
||||
const reason = statCalls === 1 ? "NotFound" : "PermissionDenied";
|
||||
return Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: reason,
|
||||
module: "FileSystem",
|
||||
method: "stat",
|
||||
pathOrDescriptor: String(path),
|
||||
description: `Test ${reason} stat failure.`,
|
||||
}),
|
||||
);
|
||||
},
|
||||
makeDirectory: () => Effect.void,
|
||||
}),
|
||||
);
|
||||
const path = yield* Path.Path;
|
||||
const workspaceRoot = " ./created-then-unreadable ";
|
||||
const normalizedWorkspaceRoot = path.resolve(workspaceRoot.trim());
|
||||
|
||||
const error = yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(workspaceRoot, { createIfMissing: true })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(WorkspacePaths.WorkspaceRootStatFailedError);
|
||||
expect(error).toMatchObject({
|
||||
workspaceRoot,
|
||||
normalizedWorkspaceRoot,
|
||||
phase: "verify-created",
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("resolveRelativePathWithinRoot", () => {
|
||||
|
||||
@@ -40,6 +40,20 @@ export class WorkspaceRootCreateFailedError extends Schema.TaggedErrorClass<Work
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceRootStatFailedError extends Schema.TaggedErrorClass<WorkspaceRootStatFailedError>()(
|
||||
"WorkspaceRootStatFailedError",
|
||||
{
|
||||
workspaceRoot: Schema.String,
|
||||
normalizedWorkspaceRoot: Schema.String,
|
||||
phase: Schema.Literals(["validate-existing", "verify-created"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to stat workspace root '${this.normalizedWorkspaceRoot}' during '${this.phase}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceRootNotDirectoryError extends Schema.TaggedErrorClass<WorkspaceRootNotDirectoryError>()(
|
||||
"WorkspaceRootNotDirectoryError",
|
||||
{
|
||||
@@ -67,6 +81,7 @@ export class WorkspacePathOutsideRootError extends Schema.TaggedErrorClass<Works
|
||||
export const WorkspacePathsError = Schema.Union([
|
||||
WorkspaceRootNotExistsError,
|
||||
WorkspaceRootCreateFailedError,
|
||||
WorkspaceRootStatFailedError,
|
||||
WorkspaceRootNotDirectoryError,
|
||||
WorkspacePathOutsideRootError,
|
||||
]);
|
||||
@@ -82,7 +97,10 @@ export class WorkspacePaths extends Context.Service<
|
||||
options?: { readonly createIfMissing?: boolean },
|
||||
) => Effect.Effect<
|
||||
string,
|
||||
WorkspaceRootNotExistsError | WorkspaceRootCreateFailedError | WorkspaceRootNotDirectoryError
|
||||
| WorkspaceRootNotExistsError
|
||||
| WorkspaceRootCreateFailedError
|
||||
| WorkspaceRootStatFailedError
|
||||
| WorkspaceRootNotDirectoryError
|
||||
>;
|
||||
/**
|
||||
* Resolve a relative path within a validated workspace root.
|
||||
@@ -117,13 +135,38 @@ export const make = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const statWorkspaceRoot = Effect.fn("WorkspacePaths.statWorkspaceRoot")(function* (
|
||||
workspaceRoot: string,
|
||||
normalizedWorkspaceRoot: string,
|
||||
phase: WorkspaceRootStatFailedError["phase"],
|
||||
) {
|
||||
return yield* fileSystem.stat(normalizedWorkspaceRoot).pipe(
|
||||
Effect.matchEffect({
|
||||
onFailure: (cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(null)
|
||||
: Effect.fail(
|
||||
new WorkspaceRootStatFailedError({
|
||||
workspaceRoot,
|
||||
normalizedWorkspaceRoot,
|
||||
phase,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
onSuccess: Effect.succeed,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const normalizeWorkspaceRoot: WorkspacePaths["Service"]["normalizeWorkspaceRoot"] = Effect.fn(
|
||||
"WorkspacePaths.normalizeWorkspaceRoot",
|
||||
)(function* (workspaceRoot, options) {
|
||||
const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path));
|
||||
let workspaceStat = yield* fileSystem
|
||||
.stat(normalizedWorkspaceRoot)
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
let workspaceStat = yield* statWorkspaceRoot(
|
||||
workspaceRoot,
|
||||
normalizedWorkspaceRoot,
|
||||
"validate-existing",
|
||||
);
|
||||
if (!workspaceStat && options?.createIfMissing) {
|
||||
yield* fileSystem.makeDirectory(normalizedWorkspaceRoot, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
@@ -135,9 +178,11 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
),
|
||||
);
|
||||
workspaceStat = yield* fileSystem
|
||||
.stat(normalizedWorkspaceRoot)
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
workspaceStat = yield* statWorkspaceRoot(
|
||||
workspaceRoot,
|
||||
normalizedWorkspaceRoot,
|
||||
"verify-created",
|
||||
);
|
||||
}
|
||||
if (!workspaceStat) {
|
||||
return yield* new WorkspaceRootNotExistsError({
|
||||
|
||||
@@ -149,6 +149,12 @@ function projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesEr
|
||||
failure: "workspace_root_create_failed",
|
||||
normalizedCwd: error.normalizedWorkspaceRoot,
|
||||
};
|
||||
case "WorkspaceRootStatFailedError":
|
||||
return {
|
||||
failure: "workspace_root_stat_failed",
|
||||
normalizedCwd: error.normalizedWorkspaceRoot,
|
||||
detail: error.phase,
|
||||
};
|
||||
case "WorkspaceRootNotDirectoryError":
|
||||
return {
|
||||
failure: "workspace_root_not_directory",
|
||||
|
||||
@@ -1,14 +1,34 @@
|
||||
import type { ScopedProjectRef } from "@t3tools/contracts";
|
||||
import { createContext, use, type ReactNode } from "react";
|
||||
import type { SidebarProjectRevealRequest } from "./sidebarProjectReveal";
|
||||
|
||||
const OpenAddProjectCommandPaletteContext = createContext<(() => void) | null>(null);
|
||||
const SidebarProjectRevealRequestContext = createContext<
|
||||
SidebarProjectRevealRequest | null | undefined
|
||||
>(undefined);
|
||||
const RequestSidebarProjectRevealContext = createContext<
|
||||
((projectRef: ScopedProjectRef) => void) | null
|
||||
>(null);
|
||||
const CompleteSidebarProjectRevealContext = createContext<((requestId: number) => void) | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
export function OpenAddProjectCommandPaletteProvider(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly openAddProject: () => void;
|
||||
readonly sidebarProjectRevealRequest: SidebarProjectRevealRequest | null;
|
||||
readonly requestSidebarProjectReveal: (projectRef: ScopedProjectRef) => void;
|
||||
readonly completeSidebarProjectReveal: (requestId: number) => void;
|
||||
}) {
|
||||
return (
|
||||
<OpenAddProjectCommandPaletteContext value={props.openAddProject}>
|
||||
{props.children}
|
||||
<SidebarProjectRevealRequestContext value={props.sidebarProjectRevealRequest}>
|
||||
<RequestSidebarProjectRevealContext value={props.requestSidebarProjectReveal}>
|
||||
<CompleteSidebarProjectRevealContext value={props.completeSidebarProjectReveal}>
|
||||
{props.children}
|
||||
</CompleteSidebarProjectRevealContext>
|
||||
</RequestSidebarProjectRevealContext>
|
||||
</SidebarProjectRevealRequestContext>
|
||||
</OpenAddProjectCommandPaletteContext>
|
||||
);
|
||||
}
|
||||
@@ -21,6 +41,30 @@ export function useOpenAddProjectCommandPalette(): () => void {
|
||||
return openAddProject;
|
||||
}
|
||||
|
||||
export function useSidebarProjectRevealRequest(): SidebarProjectRevealRequest | null {
|
||||
const request = use(SidebarProjectRevealRequestContext);
|
||||
if (request === undefined) {
|
||||
throw new Error("Command palette actions must be used inside CommandPalette");
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
export function useRequestSidebarProjectReveal(): (projectRef: ScopedProjectRef) => void {
|
||||
const requestSidebarProjectReveal = use(RequestSidebarProjectRevealContext);
|
||||
if (!requestSidebarProjectReveal) {
|
||||
throw new Error("Command palette actions must be used inside CommandPalette");
|
||||
}
|
||||
return requestSidebarProjectReveal;
|
||||
}
|
||||
|
||||
export function useCompleteSidebarProjectReveal(): (requestId: number) => void {
|
||||
const completeSidebarProjectReveal = use(CompleteSidebarProjectRevealContext);
|
||||
if (!completeSidebarProjectReveal) {
|
||||
throw new Error("Command palette actions must be used inside CommandPalette");
|
||||
}
|
||||
return completeSidebarProjectReveal;
|
||||
}
|
||||
|
||||
/** Read at event time so the chat tree does not subscribe to transient dialog state. */
|
||||
export function isCommandPaletteOpen(): boolean {
|
||||
return (
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
type FilesystemBrowseResult,
|
||||
type ProjectId,
|
||||
ProviderInstanceId,
|
||||
type ScopedProjectRef,
|
||||
type SourceControlDiscoveryResult,
|
||||
type SourceControlProviderKind,
|
||||
type SourceControlRepositoryInfo,
|
||||
@@ -43,7 +44,10 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { OpenAddProjectCommandPaletteProvider } from "../commandPaletteContext";
|
||||
import {
|
||||
OpenAddProjectCommandPaletteProvider,
|
||||
useRequestSidebarProjectReveal,
|
||||
} from "../commandPaletteContext";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { readLocalApi } from "../localApi";
|
||||
@@ -116,6 +120,7 @@ import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
|
||||
import type { ChatComposerHandle } from "./chat/ChatComposer";
|
||||
import type { SidebarProjectRevealRequest } from "../sidebarProjectReveal";
|
||||
|
||||
const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = [];
|
||||
|
||||
@@ -368,6 +373,21 @@ export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
const clearOpenIntent = useCallback(() => dispatch({ _tag: "ClearOpenIntent" }), []);
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
|
||||
const nextSidebarProjectRevealRequestIdRef = useRef(0);
|
||||
const [sidebarProjectRevealRequest, setSidebarProjectRevealRequest] =
|
||||
useState<SidebarProjectRevealRequest | null>(null);
|
||||
const requestSidebarProjectReveal = useCallback((projectRef: ScopedProjectRef): void => {
|
||||
nextSidebarProjectRevealRequestIdRef.current += 1;
|
||||
setSidebarProjectRevealRequest({
|
||||
requestId: nextSidebarProjectRevealRequestIdRef.current,
|
||||
projectRef,
|
||||
});
|
||||
}, []);
|
||||
const completeSidebarProjectReveal = useCallback((requestId: number): void => {
|
||||
setSidebarProjectRevealRequest((current) =>
|
||||
current?.requestId === requestId ? null : current,
|
||||
);
|
||||
}, []);
|
||||
const routeTarget = useParams({
|
||||
strict: false,
|
||||
select: (params) => resolveThreadRouteTarget(params),
|
||||
@@ -400,7 +420,12 @@ export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
}, [keybindings, terminalOpen, toggleOpen]);
|
||||
|
||||
return (
|
||||
<OpenAddProjectCommandPaletteProvider openAddProject={openAddProject}>
|
||||
<OpenAddProjectCommandPaletteProvider
|
||||
openAddProject={openAddProject}
|
||||
sidebarProjectRevealRequest={sidebarProjectRevealRequest}
|
||||
requestSidebarProjectReveal={requestSidebarProjectReveal}
|
||||
completeSidebarProjectReveal={completeSidebarProjectReveal}
|
||||
>
|
||||
<ComposerHandleContext value={composerHandleRef}>
|
||||
<CommandDialog open={state.open} onOpenChange={setOpen}>
|
||||
{children}
|
||||
@@ -441,6 +466,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
readonly clearOpenIntent: () => void;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const requestSidebarProjectReveal = useRequestSidebarProjectReveal();
|
||||
const { clearOpenIntent, openIntent, setOpen } = props;
|
||||
const composerHandleRef = useComposerHandleContext();
|
||||
const [query, setQuery] = useState("");
|
||||
@@ -584,6 +610,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
|
||||
const openProjectFromSearch = useMemo(
|
||||
() => async (project: (typeof projects)[number]) => {
|
||||
requestSidebarProjectReveal(scopeProjectRef(project.environmentId, project.id));
|
||||
const latestThread = getLatestThreadForProject(
|
||||
threads.filter((thread) => thread.environmentId === project.environmentId),
|
||||
project.id,
|
||||
@@ -601,7 +628,13 @@ function OpenCommandPaletteDialog(props: {
|
||||
|
||||
await handleNewThread(scopeProjectRef(project.environmentId, project.id));
|
||||
},
|
||||
[handleNewThread, navigate, clientSettings.sidebarThreadSortOrder, threads],
|
||||
[
|
||||
handleNewThread,
|
||||
navigate,
|
||||
requestSidebarProjectReveal,
|
||||
clientSettings.sidebarThreadSortOrder,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
const projectSearchItems = useMemo(
|
||||
@@ -635,6 +668,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
/>
|
||||
),
|
||||
runProject: async (project) => {
|
||||
requestSidebarProjectReveal(scopeProjectRef(project.environmentId, project.id));
|
||||
await startNewThreadInProjectFromContext(
|
||||
{
|
||||
activeDraftThread,
|
||||
@@ -646,7 +680,14 @@ function OpenCommandPaletteDialog(props: {
|
||||
);
|
||||
},
|
||||
}),
|
||||
[activeDraftThread, activeThread, defaultProjectRef, handleNewThread, projects],
|
||||
[
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
projects,
|
||||
requestSidebarProjectReveal,
|
||||
],
|
||||
);
|
||||
|
||||
const allThreadItems = useMemo(
|
||||
@@ -1050,6 +1091,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
cwd,
|
||||
);
|
||||
if (existing) {
|
||||
requestSidebarProjectReveal(scopeProjectRef(existing.environmentId, existing.id));
|
||||
const latestThread = getLatestThreadForProject(
|
||||
threads.filter((thread) => thread.environmentId === existing.environmentId),
|
||||
existing.id,
|
||||
@@ -1110,6 +1152,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
requestSidebarProjectReveal(scopeProjectRef(browseEnvironmentId, projectId));
|
||||
const navigationResult = await settlePromise(() =>
|
||||
handleNewThread(scopeProjectRef(browseEnvironmentId, projectId)),
|
||||
);
|
||||
@@ -1134,6 +1177,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
createProject,
|
||||
navigate,
|
||||
projects,
|
||||
requestSidebarProjectReveal,
|
||||
setOpen,
|
||||
clientSettings.sidebarThreadSortOrder,
|
||||
threads,
|
||||
|
||||
@@ -178,7 +178,11 @@ import {
|
||||
useSidebar,
|
||||
} from "./ui/sidebar";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";
|
||||
import {
|
||||
useCompleteSidebarProjectReveal,
|
||||
useOpenAddProjectCommandPalette,
|
||||
useSidebarProjectRevealRequest,
|
||||
} from "../commandPaletteContext";
|
||||
import {
|
||||
getSidebarThreadIdsToPrewarm,
|
||||
resolveAdjacentThreadId,
|
||||
@@ -217,6 +221,10 @@ import {
|
||||
type SidebarProjectSnapshot,
|
||||
} from "../sidebarProjectGrouping";
|
||||
import { SidebarProviderUpdatePill } from "./sidebar/SidebarProviderUpdatePill";
|
||||
import {
|
||||
resolveSidebarProjectRevealKey,
|
||||
scrollSidebarProjectIntoView,
|
||||
} from "../sidebarProjectReveal";
|
||||
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
|
||||
updated_at: "Last user message",
|
||||
created_at: "Created at",
|
||||
@@ -1065,6 +1073,8 @@ interface SidebarProjectItemProps {
|
||||
suppressProjectClickForContextMenuRef: React.RefObject<boolean>;
|
||||
isManualProjectSorting: boolean;
|
||||
dragHandleProps: SortableProjectHandleProps | null;
|
||||
projectRevealRequestId: number | null;
|
||||
completeProjectReveal: (requestId: number) => void;
|
||||
}
|
||||
|
||||
const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjectItemProps) {
|
||||
@@ -1085,7 +1095,10 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
suppressProjectClickForContextMenuRef,
|
||||
isManualProjectSorting,
|
||||
dragHandleProps,
|
||||
projectRevealRequestId,
|
||||
completeProjectReveal,
|
||||
} = props;
|
||||
const projectHeaderRef = useRef<HTMLDivElement | null>(null);
|
||||
const threadSortOrder = useClientSettings<SidebarThreadSortOrder>(
|
||||
(settings) => settings.sidebarThreadSortOrder,
|
||||
);
|
||||
@@ -1160,6 +1173,47 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
},
|
||||
});
|
||||
const openPrLink = useOpenPrLink();
|
||||
|
||||
useEffect(() => {
|
||||
if (projectRevealRequestId === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestId = projectRevealRequestId;
|
||||
let cancelled = false;
|
||||
let frame: number | null = null;
|
||||
let attempts = 0;
|
||||
|
||||
const tryReveal = () => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projectHeader = projectHeaderRef.current;
|
||||
if (projectHeader) {
|
||||
scrollSidebarProjectIntoView(projectHeader);
|
||||
completeProjectReveal(requestId);
|
||||
return;
|
||||
}
|
||||
|
||||
attempts += 1;
|
||||
if (attempts >= 20) {
|
||||
completeProjectReveal(requestId);
|
||||
return;
|
||||
}
|
||||
|
||||
frame = window.requestAnimationFrame(tryReveal);
|
||||
};
|
||||
|
||||
frame = window.requestAnimationFrame(tryReveal);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (frame !== null) {
|
||||
window.cancelAnimationFrame(frame);
|
||||
}
|
||||
};
|
||||
}, [completeProjectReveal, projectRevealRequestId]);
|
||||
const sidebarThreads = useThreadShellsForProjectRefs(project.memberProjectRefs);
|
||||
const sidebarThreadByKey = useMemo(
|
||||
() =>
|
||||
@@ -2186,7 +2240,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="group/project-header relative">
|
||||
<div ref={projectHeaderRef} className="group/project-header relative">
|
||||
<SidebarMenuButton
|
||||
ref={isManualProjectSorting ? dragHandleProps?.setActivatorNodeRef : undefined}
|
||||
size="sm"
|
||||
@@ -2773,6 +2827,8 @@ interface SidebarProjectsContentProps {
|
||||
suppressProjectClickForContextMenuRef: React.RefObject<boolean>;
|
||||
attachProjectListAutoAnimateRef: (node: HTMLElement | null) => void;
|
||||
projectsLength: number;
|
||||
projectRevealTarget: { readonly projectKey: string; readonly requestId: number } | null;
|
||||
completeProjectReveal: (requestId: number) => void;
|
||||
}
|
||||
|
||||
const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
@@ -2814,6 +2870,8 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
suppressProjectClickForContextMenuRef,
|
||||
attachProjectListAutoAnimateRef,
|
||||
projectsLength,
|
||||
projectRevealTarget,
|
||||
completeProjectReveal,
|
||||
} = props;
|
||||
|
||||
const handleProjectSortOrderChange = useCallback(
|
||||
@@ -2962,6 +3020,12 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
}
|
||||
isManualProjectSorting={isManualProjectSorting}
|
||||
dragHandleProps={dragHandleProps}
|
||||
projectRevealRequestId={
|
||||
projectRevealTarget?.projectKey === project.projectKey
|
||||
? projectRevealTarget.requestId
|
||||
: null
|
||||
}
|
||||
completeProjectReveal={completeProjectReveal}
|
||||
/>
|
||||
)}
|
||||
</SortableProjectItem>
|
||||
@@ -2992,6 +3056,12 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
suppressProjectClickForContextMenuRef={suppressProjectClickForContextMenuRef}
|
||||
isManualProjectSorting={isManualProjectSorting}
|
||||
dragHandleProps={null}
|
||||
projectRevealRequestId={
|
||||
projectRevealTarget?.projectKey === project.projectKey
|
||||
? projectRevealTarget.requestId
|
||||
: null
|
||||
}
|
||||
completeProjectReveal={completeProjectReveal}
|
||||
/>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
@@ -3037,6 +3107,8 @@ export default function Sidebar() {
|
||||
);
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const openAddProjectCommandPalette = useOpenAddProjectCommandPalette();
|
||||
const sidebarProjectRevealRequest = useSidebarProjectRevealRequest();
|
||||
const completeSidebarProjectReveal = useCompleteSidebarProjectReveal();
|
||||
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
|
||||
ReadonlySet<string>
|
||||
>(() => new Set());
|
||||
@@ -3103,6 +3175,17 @@ export default function Sidebar() {
|
||||
() => new Map(sidebarProjects.map((project) => [project.projectKey, project] as const)),
|
||||
[sidebarProjects],
|
||||
);
|
||||
const projectRevealKey = sidebarProjectRevealRequest
|
||||
? resolveSidebarProjectRevealKey({
|
||||
projectRef: sidebarProjectRevealRequest.projectRef,
|
||||
physicalProjectKeyByScopedRef: projectPhysicalKeyByScopedRef,
|
||||
physicalToLogicalKey,
|
||||
})
|
||||
: null;
|
||||
const projectRevealTarget =
|
||||
projectRevealKey && sidebarProjectRevealRequest
|
||||
? { projectKey: projectRevealKey, requestId: sidebarProjectRevealRequest.requestId }
|
||||
: null;
|
||||
const sidebarThreadByKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
@@ -3629,6 +3712,8 @@ export default function Sidebar() {
|
||||
suppressProjectClickForContextMenuRef={suppressProjectClickForContextMenuRef}
|
||||
attachProjectListAutoAnimateRef={attachProjectListAutoAnimateRef}
|
||||
projectsLength={projects.length}
|
||||
projectRevealTarget={projectRevealTarget}
|
||||
completeProjectReveal={completeSidebarProjectReveal}
|
||||
/>
|
||||
|
||||
<SidebarSeparator />
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
|
||||
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import {
|
||||
resolveSidebarProjectRevealKey,
|
||||
scrollSidebarProjectIntoView,
|
||||
} from "./sidebarProjectReveal";
|
||||
|
||||
const projectRef = scopeProjectRef(
|
||||
EnvironmentId.make("environment-local"),
|
||||
ProjectId.make("project-1"),
|
||||
);
|
||||
|
||||
describe("resolveSidebarProjectRevealKey", () => {
|
||||
it("resolves a physical project to its grouped sidebar row", () => {
|
||||
expect(
|
||||
resolveSidebarProjectRevealKey({
|
||||
projectRef,
|
||||
physicalProjectKeyByScopedRef: new Map([
|
||||
[scopedProjectKey(projectRef), "physical-project"],
|
||||
]),
|
||||
physicalToLogicalKey: new Map([["physical-project", "logical-project"]]),
|
||||
}),
|
||||
).toBe("logical-project");
|
||||
});
|
||||
|
||||
it("uses the physical row key when the project is not grouped", () => {
|
||||
expect(
|
||||
resolveSidebarProjectRevealKey({
|
||||
projectRef,
|
||||
physicalProjectKeyByScopedRef: new Map([
|
||||
[scopedProjectKey(projectRef), "physical-project"],
|
||||
]),
|
||||
physicalToLogicalKey: new Map(),
|
||||
}),
|
||||
).toBe("physical-project");
|
||||
});
|
||||
|
||||
it("waits until the requested project is available in the sidebar", () => {
|
||||
expect(
|
||||
resolveSidebarProjectRevealKey({
|
||||
projectRef,
|
||||
physicalProjectKeyByScopedRef: new Map(),
|
||||
physicalToLogicalKey: new Map(),
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("scrollSidebarProjectIntoView", () => {
|
||||
it("smoothly centers the selected project header", () => {
|
||||
const scrollIntoView = vi.fn();
|
||||
|
||||
scrollSidebarProjectIntoView({ scrollIntoView });
|
||||
|
||||
expect(scrollIntoView).toHaveBeenCalledWith({
|
||||
behavior: "smooth",
|
||||
block: "center",
|
||||
inline: "nearest",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { scopedProjectKey } from "@t3tools/client-runtime/environment";
|
||||
import type { ScopedProjectRef } from "@t3tools/contracts";
|
||||
|
||||
export interface SidebarProjectRevealRequest {
|
||||
readonly requestId: number;
|
||||
readonly projectRef: ScopedProjectRef;
|
||||
}
|
||||
|
||||
export function scrollSidebarProjectIntoView(
|
||||
projectHeader: Pick<HTMLElement, "scrollIntoView">,
|
||||
): void {
|
||||
projectHeader.scrollIntoView({
|
||||
behavior: "smooth",
|
||||
block: "center",
|
||||
inline: "nearest",
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveSidebarProjectRevealKey(input: {
|
||||
readonly projectRef: ScopedProjectRef;
|
||||
readonly physicalProjectKeyByScopedRef: ReadonlyMap<string, string>;
|
||||
readonly physicalToLogicalKey: ReadonlyMap<string, string>;
|
||||
}): string | null {
|
||||
const physicalKey = input.physicalProjectKeyByScopedRef.get(scopedProjectKey(input.projectRef));
|
||||
if (!physicalKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return input.physicalToLogicalKey.get(physicalKey) ?? physicalKey;
|
||||
}
|
||||
@@ -96,4 +96,30 @@ describe("DpopProofReplay", () => {
|
||||
Effect.provide(DpopProofs.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("retains the prune cutoff and database failure", () => {
|
||||
const cause = new Error("database unavailable");
|
||||
const fakeDb = {
|
||||
delete: (table: unknown) => {
|
||||
expect(table).toBe(relayDpopProofs);
|
||||
return {
|
||||
where: () => Effect.fail(cause),
|
||||
};
|
||||
},
|
||||
} as unknown as RelayDb.RelayDb["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const replay = yield* DpopProofs.DpopProofReplay;
|
||||
const error = yield* Effect.flip(replay.pruneExpired);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "DpopProofReplayPersistenceError",
|
||||
operation: "prune-expired",
|
||||
});
|
||||
expect(Date.parse(error.expiresBefore ?? "")).not.toBeNaN();
|
||||
expect(error.cause).toBe(cause);
|
||||
}).pipe(
|
||||
Effect.provide(DpopProofs.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -13,11 +13,16 @@ import { relayDpopProofs } from "../persistence/schema.ts";
|
||||
export class DpopProofReplayPersistenceError extends Schema.TaggedErrorClass<DpopProofReplayPersistenceError>()(
|
||||
"DpopProofReplayPersistenceError",
|
||||
{
|
||||
operation: Schema.Literals(["consume", "prune-expired"]),
|
||||
thumbprint: Schema.optionalKey(Schema.String),
|
||||
jti: Schema.optionalKey(Schema.String),
|
||||
iat: Schema.optionalKey(Schema.Number),
|
||||
expiresBefore: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist DPoP proof replay state";
|
||||
return `Failed to persist DPoP proof replay state during '${this.operation}'`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,10 +63,21 @@ const make = Effect.gen(function* () {
|
||||
createdAt,
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning({ jti: relayDpopProofs.jti });
|
||||
.returning({ jti: relayDpopProofs.jti })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DpopProofReplayPersistenceError({
|
||||
operation: "consume",
|
||||
thumbprint: input.thumbprint,
|
||||
jti: input.jti,
|
||||
iat: input.iat,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return inserted.length > 0;
|
||||
},
|
||||
Effect.mapError((cause) => new DpopProofReplayPersistenceError({ cause })),
|
||||
);
|
||||
|
||||
const verifyAndConsume: DpopProofReplay["Service"]["verifyAndConsume"] = Effect.fn(
|
||||
@@ -114,11 +130,20 @@ const make = Effect.gen(function* () {
|
||||
const pruneExpired: DpopProofReplay["Service"]["pruneExpired"] = Effect.gen(function* () {
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* Effect.annotateCurrentSpan({ "relay.dpop_prune.before": now });
|
||||
yield* db.delete(relayDpopProofs).where(lt(relayDpopProofs.expiresAt, now));
|
||||
}).pipe(
|
||||
Effect.withSpan("relay.dpop_proofs.prune_expired"),
|
||||
Effect.mapError((cause) => new DpopProofReplayPersistenceError({ cause })),
|
||||
);
|
||||
yield* db
|
||||
.delete(relayDpopProofs)
|
||||
.where(lt(relayDpopProofs.expiresAt, now))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DpopProofReplayPersistenceError({
|
||||
operation: "prune-expired",
|
||||
expiresBefore: now,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.withSpan("relay.dpop_proofs.prune_expired"));
|
||||
|
||||
return DpopProofReplay.of({
|
||||
verifyAndConsume,
|
||||
|
||||
@@ -163,7 +163,7 @@ describe("DpopProofReplay.verifyAndConsume", () => {
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
jti: "proof-persistence-failure",
|
||||
});
|
||||
const cause = "database unavailable";
|
||||
const cause = { _tag: "DatabaseUnavailable" } as const;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const replay = yield* DpopProofs.DpopProofReplay;
|
||||
@@ -177,8 +177,16 @@ describe("DpopProofReplay.verifyAndConsume", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error).toEqual(new DpopProofs.DpopProofReplayPersistenceError({ cause }));
|
||||
}).pipe(Effect.provide(layer(() => Effect.fail({ _tag: cause }))));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "DpopProofReplayPersistenceError",
|
||||
operation: "consume",
|
||||
thumbprint: proof.thumbprint,
|
||||
jti: "proof-persistence-failure",
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("proof");
|
||||
}).pipe(Effect.provide(layer(() => Effect.fail(cause))));
|
||||
});
|
||||
|
||||
it.effect("accepts proofs bound to the access token hash", () => {
|
||||
|
||||
@@ -9,6 +9,88 @@ import { relayEnvironmentCredentials } from "../persistence/schema.ts";
|
||||
import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
|
||||
|
||||
describe("EnvironmentCredentials", () => {
|
||||
it.effect("reports the credential creation persistence stage and preserves its cause", () => {
|
||||
const cause = new Error("database unavailable");
|
||||
const fakeDb = {
|
||||
insert: (table: unknown) => {
|
||||
expect(table).toBe(relayEnvironmentCredentials);
|
||||
return {
|
||||
values: () => Effect.void,
|
||||
};
|
||||
},
|
||||
update: (table: unknown) => {
|
||||
expect(table).toBe(relayEnvironmentCredentials);
|
||||
return {
|
||||
set: () => ({
|
||||
where: () => Effect.fail(cause),
|
||||
}),
|
||||
};
|
||||
},
|
||||
} as unknown as RelayDb.RelayDb["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
|
||||
const error = yield* Effect.flip(
|
||||
credentials.create({
|
||||
environmentId: "env_test",
|
||||
environmentPublicKey: "sensitive-public-key-material",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentCredentialCreatePersistenceError",
|
||||
stage: "revoke-previous-credentials",
|
||||
environmentId: "env_test",
|
||||
});
|
||||
expect(error.credentialId).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("environmentPublicKey");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
EnvironmentCredentials.layer.pipe(
|
||||
Layer.provide(NodeCryptoLayer.layer),
|
||||
Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("does not retain credential tokens when lookup persistence fails", () => {
|
||||
const cause = new Error("database unavailable");
|
||||
const token = "t3env_sensitive-credential-token";
|
||||
const fakeDb = {
|
||||
select: () => ({
|
||||
from: (table: unknown) => {
|
||||
expect(table).toBe(relayEnvironmentCredentials);
|
||||
return {
|
||||
where: () => ({
|
||||
limit: () => Effect.fail(cause),
|
||||
}),
|
||||
};
|
||||
},
|
||||
}),
|
||||
} as unknown as RelayDb.RelayDb["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
|
||||
const error = yield* Effect.flip(credentials.authenticate(token));
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentCredentialAuthenticatePersistenceError",
|
||||
stage: "lookup-credential",
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("token");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
EnvironmentCredentials.layer.pipe(
|
||||
Layer.provide(NodeCryptoLayer.layer),
|
||||
Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"creates opaque credentials and revokes only older credentials for the same key",
|
||||
() => {
|
||||
|
||||
@@ -13,28 +13,44 @@ import { relayEnvironmentCredentials, relayEnvironmentLinks } from "../persisten
|
||||
|
||||
export class EnvironmentCredentialCreatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialCreatePersistenceError>()(
|
||||
"EnvironmentCredentialCreatePersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
stage: Schema.Literals([
|
||||
"generate-credential",
|
||||
"hash-token",
|
||||
"insert-credential",
|
||||
"revoke-previous-credentials",
|
||||
]),
|
||||
environmentId: Schema.String,
|
||||
credentialId: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist environment credential";
|
||||
return `Environment credential creation failed during '${this.stage}' for environment '${this.environmentId}'${this.credentialId === undefined ? "" : `, credential '${this.credentialId}'`}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentCredentialAuthenticatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialAuthenticatePersistenceError>()(
|
||||
"EnvironmentCredentialAuthenticatePersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
stage: Schema.Literals(["hash-token", "lookup-credential"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to authenticate environment credential";
|
||||
return `Environment credential authentication failed during '${this.stage}'`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentCredentialRevokePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialRevokePersistenceError>()(
|
||||
"EnvironmentCredentialRevokePersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke environment credential";
|
||||
return `Failed to revoke credentials for environment '${this.environmentId}'`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,13 +101,33 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return EnvironmentCredentials.of({
|
||||
create: Effect.fn("relay.environment_credentials.create")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
|
||||
const credential = yield* makeCredential();
|
||||
const credentialHash = yield* hashToken(credential.token);
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* db.insert(relayEnvironmentCredentials).values({
|
||||
create: Effect.fn("relay.environment_credentials.create")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
|
||||
const credential = yield* makeCredential().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentCredentialCreatePersistenceError({
|
||||
stage: "generate-credential",
|
||||
environmentId: input.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const credentialHash = yield* hashToken(credential.token).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentCredentialCreatePersistenceError({
|
||||
stage: "hash-token",
|
||||
environmentId: input.environmentId,
|
||||
credentialId: credential.credentialId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* db
|
||||
.insert(relayEnvironmentCredentials)
|
||||
.values({
|
||||
credentialId: credential.credentialId,
|
||||
environmentId: input.environmentId,
|
||||
environmentPublicKey: input.environmentPublicKey,
|
||||
@@ -99,96 +135,136 @@ const make = Effect.gen(function* () {
|
||||
revokedAt: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
yield* db
|
||||
.update(relayEnvironmentCredentials)
|
||||
.set({
|
||||
revokedAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(relayEnvironmentCredentials.environmentId, input.environmentId),
|
||||
eq(relayEnvironmentCredentials.environmentPublicKey, input.environmentPublicKey),
|
||||
ne(relayEnvironmentCredentials.credentialId, credential.credentialId),
|
||||
isNull(relayEnvironmentCredentials.revokedAt),
|
||||
),
|
||||
);
|
||||
return credential.token;
|
||||
},
|
||||
Effect.mapError((cause) => new EnvironmentCredentialCreatePersistenceError({ cause })),
|
||||
),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentCredentialCreatePersistenceError({
|
||||
stage: "insert-credential",
|
||||
environmentId: input.environmentId,
|
||||
credentialId: credential.credentialId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* db
|
||||
.update(relayEnvironmentCredentials)
|
||||
.set({
|
||||
revokedAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(relayEnvironmentCredentials.environmentId, input.environmentId),
|
||||
eq(relayEnvironmentCredentials.environmentPublicKey, input.environmentPublicKey),
|
||||
ne(relayEnvironmentCredentials.credentialId, credential.credentialId),
|
||||
isNull(relayEnvironmentCredentials.revokedAt),
|
||||
),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentCredentialCreatePersistenceError({
|
||||
stage: "revoke-previous-credentials",
|
||||
environmentId: input.environmentId,
|
||||
credentialId: credential.credentialId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return credential.token;
|
||||
}),
|
||||
|
||||
authenticate: Effect.fn("relay.environment_credentials.authenticate")(
|
||||
function* (token) {
|
||||
const credentialHash = yield* hashToken(token);
|
||||
const rows = yield* db
|
||||
.select({
|
||||
credentialId: relayEnvironmentCredentials.credentialId,
|
||||
environmentId: relayEnvironmentCredentials.environmentId,
|
||||
environmentPublicKey: relayEnvironmentCredentials.environmentPublicKey,
|
||||
authenticate: Effect.fn("relay.environment_credentials.authenticate")(function* (token) {
|
||||
const credentialHash = yield* hashToken(token).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentCredentialAuthenticatePersistenceError({
|
||||
stage: "hash-token",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const rows = yield* db
|
||||
.select({
|
||||
credentialId: relayEnvironmentCredentials.credentialId,
|
||||
environmentId: relayEnvironmentCredentials.environmentId,
|
||||
environmentPublicKey: relayEnvironmentCredentials.environmentPublicKey,
|
||||
})
|
||||
.from(relayEnvironmentCredentials)
|
||||
.where(
|
||||
and(
|
||||
eq(relayEnvironmentCredentials.credentialHash, credentialHash),
|
||||
isNull(relayEnvironmentCredentials.revokedAt),
|
||||
),
|
||||
)
|
||||
.limit(1)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentCredentialAuthenticatePersistenceError({
|
||||
stage: "lookup-credential",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const row = rows[0];
|
||||
if (row) {
|
||||
yield* Effect.annotateCurrentSpan({ "relay.environment_id": row.environmentId });
|
||||
}
|
||||
return row
|
||||
? Option.some({
|
||||
credentialId: row.credentialId,
|
||||
environmentId: row.environmentId,
|
||||
environmentPublicKey: row.environmentPublicKey,
|
||||
})
|
||||
.from(relayEnvironmentCredentials)
|
||||
.where(
|
||||
and(
|
||||
eq(relayEnvironmentCredentials.credentialHash, credentialHash),
|
||||
isNull(relayEnvironmentCredentials.revokedAt),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
const row = rows[0];
|
||||
if (row) {
|
||||
yield* Effect.annotateCurrentSpan({ "relay.environment_id": row.environmentId });
|
||||
}
|
||||
return row
|
||||
? Option.some({
|
||||
credentialId: row.credentialId,
|
||||
environmentId: row.environmentId,
|
||||
environmentPublicKey: row.environmentPublicKey,
|
||||
})
|
||||
: Option.none();
|
||||
},
|
||||
Effect.mapError((cause) => new EnvironmentCredentialAuthenticatePersistenceError({ cause })),
|
||||
),
|
||||
: Option.none();
|
||||
}),
|
||||
|
||||
revokeForEnvironmentPublicKey: Effect.fn(
|
||||
"relay.environment_credentials.revoke_for_environment_public_key",
|
||||
)(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
|
||||
const revokedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const rows = yield* db
|
||||
.update(relayEnvironmentCredentials)
|
||||
.set({
|
||||
revokedAt,
|
||||
updatedAt: revokedAt,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(relayEnvironmentCredentials.environmentId, input.environmentId),
|
||||
eq(relayEnvironmentCredentials.environmentPublicKey, input.environmentPublicKey),
|
||||
isNull(relayEnvironmentCredentials.revokedAt),
|
||||
notExists(
|
||||
db
|
||||
.select({ userId: relayEnvironmentLinks.userId })
|
||||
.from(relayEnvironmentLinks)
|
||||
.where(
|
||||
and(
|
||||
eq(relayEnvironmentLinks.environmentId, input.environmentId),
|
||||
eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
|
||||
isNull(relayEnvironmentLinks.revokedAt),
|
||||
),
|
||||
)(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
|
||||
const revokedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const rows = yield* db
|
||||
.update(relayEnvironmentCredentials)
|
||||
.set({
|
||||
revokedAt,
|
||||
updatedAt: revokedAt,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(relayEnvironmentCredentials.environmentId, input.environmentId),
|
||||
eq(relayEnvironmentCredentials.environmentPublicKey, input.environmentPublicKey),
|
||||
isNull(relayEnvironmentCredentials.revokedAt),
|
||||
notExists(
|
||||
db
|
||||
.select({ userId: relayEnvironmentLinks.userId })
|
||||
.from(relayEnvironmentLinks)
|
||||
.where(
|
||||
and(
|
||||
eq(relayEnvironmentLinks.environmentId, input.environmentId),
|
||||
eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
|
||||
isNull(relayEnvironmentLinks.revokedAt),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.returning({
|
||||
credentialId: relayEnvironmentCredentials.credentialId,
|
||||
});
|
||||
return rows.length > 0;
|
||||
},
|
||||
Effect.mapError((cause) => new EnvironmentCredentialRevokePersistenceError({ cause })),
|
||||
),
|
||||
),
|
||||
)
|
||||
.returning({
|
||||
credentialId: relayEnvironmentCredentials.credentialId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentCredentialRevokePersistenceError({
|
||||
environmentId: input.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return rows.length > 0;
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -8,6 +8,76 @@ import { relayEnvironmentLinks } from "../persistence/schema.ts";
|
||||
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
|
||||
|
||||
describe("EnvironmentLinks", () => {
|
||||
it.effect("retains link lookup failures with user and environment identity", () => {
|
||||
const cause = new Error("database unavailable");
|
||||
const fakeDb = {
|
||||
select: () => ({
|
||||
from: (table: unknown) => {
|
||||
expect(table).toBe(relayEnvironmentLinks);
|
||||
return {
|
||||
where: () => ({
|
||||
limit: () => Effect.fail(cause),
|
||||
}),
|
||||
};
|
||||
},
|
||||
}),
|
||||
} as unknown as RelayDb.RelayDb["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const links = yield* EnvironmentLinks.EnvironmentLinks;
|
||||
const error = yield* Effect.flip(
|
||||
links.getForUser({ userId: "user-1", environmentId: "env-1" }),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentLinkLookupPersistenceError",
|
||||
userId: "user-1",
|
||||
environmentId: "env-1",
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
EnvironmentLinks.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("identifies delivery-user list failures without retaining key material", () => {
|
||||
const cause = new Error("database unavailable");
|
||||
const fakeDb = {
|
||||
select: () => ({
|
||||
from: (table: unknown) => {
|
||||
expect(table).toBe(relayEnvironmentLinks);
|
||||
return {
|
||||
where: () => Effect.fail(cause),
|
||||
};
|
||||
},
|
||||
}),
|
||||
} as unknown as RelayDb.RelayDb["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const links = yield* EnvironmentLinks.EnvironmentLinks;
|
||||
const error = yield* Effect.flip(
|
||||
links.listDeliveryUsersForEnvironment({
|
||||
environmentId: "env-1",
|
||||
environmentPublicKey: "sensitive-public-key-material",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentLinkUserListPersistenceError",
|
||||
operation: "list-delivery-users",
|
||||
environmentId: "env-1",
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("environmentPublicKey");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
EnvironmentLinks.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("selects users when either notifications or Live Activities are enabled", () => {
|
||||
const whereConditions: Array<unknown> = [];
|
||||
const fakeDb = {
|
||||
|
||||
@@ -26,55 +26,78 @@ export interface AgentAwarenessDeliveryUserRecord {
|
||||
|
||||
export class EnvironmentLinkUpsertPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkUpsertPersistenceError>()(
|
||||
"EnvironmentLinkUpsertPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
userId: Schema.String,
|
||||
environmentId: Schema.String,
|
||||
deviceId: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist environment link";
|
||||
return `Failed to persist environment link for user '${this.userId}', environment '${this.environmentId}'`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentLinkUserListPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkUserListPersistenceError>()(
|
||||
"EnvironmentLinkUserListPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
operation: Schema.Literals(["list-users", "list-delivery-users"]),
|
||||
environmentId: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list users linked to environment";
|
||||
return `Environment link user query '${this.operation}' failed for environment '${this.environmentId}'`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentPublicKeyListPersistenceError extends Schema.TaggedErrorClass<EnvironmentPublicKeyListPersistenceError>()(
|
||||
"EnvironmentPublicKeyListPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list environment public keys";
|
||||
return `Failed to list public keys for environment '${this.environmentId}'`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentLinkListPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkListPersistenceError>()(
|
||||
"EnvironmentLinkListPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
userId: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list environment links";
|
||||
return `Failed to list environment links for user '${this.userId}'`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentLinkLookupPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkLookupPersistenceError>()(
|
||||
"EnvironmentLinkLookupPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
userId: Schema.String,
|
||||
environmentId: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to look up environment link";
|
||||
return `Failed to look up environment link for user '${this.userId}', environment '${this.environmentId}'`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentLinkRevokePersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkRevokePersistenceError>()(
|
||||
"EnvironmentLinkRevokePersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
userId: Schema.String,
|
||||
environmentId: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke environment link";
|
||||
return `Failed to revoke environment link for user '${this.userId}', environment '${this.environmentId}'`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,22 +165,37 @@ const make = Effect.gen(function* () {
|
||||
const db = yield* RelayDb.RelayDb;
|
||||
|
||||
return EnvironmentLinks.of({
|
||||
upsert: Effect.fn("relay.environment_links.upsert")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.environment_id": input.proof.environmentId,
|
||||
});
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
const { request, proof } = input;
|
||||
const environmentId = proof.environmentId;
|
||||
const { endpoint } = input;
|
||||
yield* db
|
||||
.insert(relayEnvironmentLinks)
|
||||
.values({
|
||||
userId: input.userId,
|
||||
environmentId,
|
||||
environmentLabel: proof.descriptor.label,
|
||||
upsert: Effect.fn("relay.environment_links.upsert")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.environment_id": input.proof.environmentId,
|
||||
});
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
const { request, proof } = input;
|
||||
const environmentId = proof.environmentId;
|
||||
const { endpoint } = input;
|
||||
yield* db
|
||||
.insert(relayEnvironmentLinks)
|
||||
.values({
|
||||
userId: input.userId,
|
||||
environmentId,
|
||||
environmentLabel: proof.descriptor.label,
|
||||
environmentPublicKey: proof.environmentPublicKey,
|
||||
endpointHttpBaseUrl: endpoint.httpBaseUrl,
|
||||
endpointWsBaseUrl: endpoint.wsBaseUrl,
|
||||
endpointProviderKind: endpoint.providerKind,
|
||||
notificationsEnabled: request.notificationsEnabled,
|
||||
liveActivitiesEnabled: request.liveActivitiesEnabled,
|
||||
managedTunnelsEnabled: request.managedTunnelsEnabled,
|
||||
createdByDeviceId: request.deviceId ?? null,
|
||||
revokedAt: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId],
|
||||
set: {
|
||||
environmentPublicKey: proof.environmentPublicKey,
|
||||
environmentLabel: proof.descriptor.label,
|
||||
endpointHttpBaseUrl: endpoint.httpBaseUrl,
|
||||
endpointWsBaseUrl: endpoint.wsBaseUrl,
|
||||
endpointProviderKind: endpoint.providerKind,
|
||||
@@ -166,28 +204,21 @@ const make = Effect.gen(function* () {
|
||||
managedTunnelsEnabled: request.managedTunnelsEnabled,
|
||||
createdByDeviceId: request.deviceId ?? null,
|
||||
revokedAt: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId],
|
||||
set: {
|
||||
environmentPublicKey: proof.environmentPublicKey,
|
||||
environmentLabel: proof.descriptor.label,
|
||||
endpointHttpBaseUrl: endpoint.httpBaseUrl,
|
||||
endpointWsBaseUrl: endpoint.wsBaseUrl,
|
||||
endpointProviderKind: endpoint.providerKind,
|
||||
notificationsEnabled: request.notificationsEnabled,
|
||||
liveActivitiesEnabled: request.liveActivitiesEnabled,
|
||||
managedTunnelsEnabled: request.managedTunnelsEnabled,
|
||||
createdByDeviceId: request.deviceId ?? null,
|
||||
revokedAt: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
},
|
||||
Effect.mapError((cause) => new EnvironmentLinkUpsertPersistenceError({ cause })),
|
||||
),
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentLinkUpsertPersistenceError({
|
||||
userId: input.userId,
|
||||
environmentId,
|
||||
...(request.deviceId === undefined ? {} : { deviceId: request.deviceId }),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
listUsersForEnvironment: Effect.fn("relay.environment_links.list_users_for_environment")(
|
||||
function* (input) {
|
||||
@@ -198,7 +229,14 @@ const make = Effect.gen(function* () {
|
||||
.where(agentAwarenessDeliveryUserCondition(input.environmentId))
|
||||
.pipe(
|
||||
Effect.map((rows) => rows.map((row) => row.userId)),
|
||||
Effect.mapError((cause) => new EnvironmentLinkUserListPersistenceError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentLinkUserListPersistenceError({
|
||||
operation: "list-users",
|
||||
environmentId: input.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
@@ -223,7 +261,14 @@ const make = Effect.gen(function* () {
|
||||
liveActivitiesEnabled: row.liveActivitiesEnabled,
|
||||
})),
|
||||
),
|
||||
Effect.mapError((cause) => new EnvironmentLinkUserListPersistenceError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentLinkUserListPersistenceError({
|
||||
operation: "list-delivery-users",
|
||||
environmentId: input.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -244,7 +289,13 @@ const make = Effect.gen(function* () {
|
||||
Effect.map((rows) => [
|
||||
...new Set(rows.map((row) => row.environmentPublicKey).filter((key) => key.length > 0)),
|
||||
]),
|
||||
Effect.mapError((cause) => new EnvironmentPublicKeyListPersistenceError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentPublicKeyListPersistenceError({
|
||||
environmentId: input.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -280,7 +331,13 @@ const make = Effect.gen(function* () {
|
||||
linkedAt: row.createdAt,
|
||||
})),
|
||||
),
|
||||
Effect.mapError((cause) => new EnvironmentLinkListPersistenceError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentLinkListPersistenceError({
|
||||
userId: input.userId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -328,34 +385,48 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
: null;
|
||||
}),
|
||||
Effect.mapError((cause) => new EnvironmentLinkLookupPersistenceError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentLinkLookupPersistenceError({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
revokeForUser: Effect.fn("relay.environment_links.revoke_for_user")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.environment_id": input.environmentId,
|
||||
});
|
||||
const revokedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const rows = yield* db
|
||||
.update(relayEnvironmentLinks)
|
||||
.set({
|
||||
revokedAt,
|
||||
updatedAt: revokedAt,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(relayEnvironmentLinks.userId, input.userId),
|
||||
eq(relayEnvironmentLinks.environmentId, input.environmentId),
|
||||
isNull(relayEnvironmentLinks.revokedAt),
|
||||
),
|
||||
)
|
||||
.returning({ environmentId: relayEnvironmentLinks.environmentId });
|
||||
return rows.length > 0;
|
||||
},
|
||||
Effect.mapError((cause) => new EnvironmentLinkRevokePersistenceError({ cause })),
|
||||
),
|
||||
revokeForUser: Effect.fn("relay.environment_links.revoke_for_user")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.environment_id": input.environmentId,
|
||||
});
|
||||
const revokedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const rows = yield* db
|
||||
.update(relayEnvironmentLinks)
|
||||
.set({
|
||||
revokedAt,
|
||||
updatedAt: revokedAt,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(relayEnvironmentLinks.userId, input.userId),
|
||||
eq(relayEnvironmentLinks.environmentId, input.environmentId),
|
||||
isNull(relayEnvironmentLinks.revokedAt),
|
||||
),
|
||||
)
|
||||
.returning({ environmentId: relayEnvironmentLinks.environmentId })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentLinkRevokePersistenceError({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return rows.length > 0;
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as RelayDb from "../db.ts";
|
||||
import { relayManagedEndpointAllocations } from "../persistence/schema.ts";
|
||||
import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
|
||||
|
||||
const layerWithDb = (db: RelayDb.RelayDb["Service"]) =>
|
||||
ManagedEndpointAllocations.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, db)));
|
||||
|
||||
describe("ManagedEndpointAllocations", () => {
|
||||
it.effect("retains database failures with allocation operation and identity", () => {
|
||||
const cause = new Error("database unavailable");
|
||||
const fakeDb = {
|
||||
select: () => ({
|
||||
from: (table: unknown) => {
|
||||
expect(table).toBe(relayManagedEndpointAllocations);
|
||||
return {
|
||||
where: () => ({
|
||||
limit: () => Effect.fail(cause),
|
||||
}),
|
||||
};
|
||||
},
|
||||
}),
|
||||
} as unknown as RelayDb.RelayDb["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
|
||||
const error = yield* Effect.flip(
|
||||
allocations.get({ userId: "user-1", environmentId: "environment-1" }),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "ManagedEndpointAllocationPersistenceError",
|
||||
operation: "get",
|
||||
stage: "database-request",
|
||||
userId: "user-1",
|
||||
environmentId: "environment-1",
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
}).pipe(Effect.provide(layerWithDb(fakeDb)));
|
||||
});
|
||||
|
||||
it.effect("reports an unresolved reservation without manufacturing a cause", () => {
|
||||
const fakeDb = {
|
||||
insert: (table: unknown) => {
|
||||
expect(table).toBe(relayManagedEndpointAllocations);
|
||||
return {
|
||||
values: () => ({
|
||||
onConflictDoNothing: () => ({
|
||||
returning: () => Effect.succeed([]),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
},
|
||||
select: () => ({
|
||||
from: (table: unknown) => {
|
||||
expect(table).toBe(relayManagedEndpointAllocations);
|
||||
return {
|
||||
where: () => ({
|
||||
limit: () => Effect.succeed([]),
|
||||
}),
|
||||
};
|
||||
},
|
||||
}),
|
||||
} as unknown as RelayDb.RelayDb["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
|
||||
const error = yield* Effect.flip(
|
||||
allocations.reserve({
|
||||
userId: "user-1",
|
||||
environmentId: "environment-1",
|
||||
hostname: "environment-1.example.test",
|
||||
tunnelName: "environment-1-tunnel",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "ManagedEndpointAllocationPersistenceError",
|
||||
operation: "reserve",
|
||||
stage: "resolve-reservation",
|
||||
userId: "user-1",
|
||||
environmentId: "environment-1",
|
||||
hostname: "environment-1.example.test",
|
||||
tunnelName: "environment-1-tunnel",
|
||||
});
|
||||
expect(error.cause).toBeUndefined();
|
||||
expect(error.message).toContain("'resolve-reservation'");
|
||||
}).pipe(Effect.provide(layerWithDb(fakeDb)));
|
||||
});
|
||||
});
|
||||
@@ -38,15 +38,29 @@ export function resolveReadyManagedEndpoint(input: {
|
||||
|
||||
export class ManagedEndpointAllocationPersistenceError extends Schema.TaggedErrorClass<ManagedEndpointAllocationPersistenceError>()(
|
||||
"ManagedEndpointAllocationPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"get",
|
||||
"reserve",
|
||||
"record-tunnel",
|
||||
"record-dns",
|
||||
"mark-ready",
|
||||
"remove",
|
||||
]),
|
||||
stage: Schema.Literals(["database-request", "resolve-reservation"]),
|
||||
userId: Schema.String,
|
||||
environmentId: Schema.String,
|
||||
hostname: Schema.optionalKey(Schema.String),
|
||||
tunnelName: Schema.optionalKey(Schema.String),
|
||||
tunnelId: Schema.optionalKey(Schema.String),
|
||||
dnsRecordId: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist managed endpoint allocation";
|
||||
return `Managed endpoint allocation '${this.operation}' failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
|
||||
}
|
||||
}
|
||||
const isManagedEndpointAllocationPersistenceError = Schema.is(
|
||||
ManagedEndpointAllocationPersistenceError,
|
||||
);
|
||||
|
||||
interface ManagedEndpointAllocationKey {
|
||||
readonly userId: string;
|
||||
@@ -106,12 +120,7 @@ const whereAllocation = (input: ManagedEndpointAllocationKey) =>
|
||||
eq(relayManagedEndpointAllocations.environmentId, input.environmentId),
|
||||
);
|
||||
|
||||
const persistenceError = (cause: unknown) =>
|
||||
isManagedEndpointAllocationPersistenceError(cause)
|
||||
? cause
|
||||
: new ManagedEndpointAllocationPersistenceError({ cause });
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const db = yield* RelayDb.RelayDb;
|
||||
|
||||
return ManagedEndpointAllocations.of({
|
||||
@@ -125,7 +134,15 @@ const make = Effect.gen(function* () {
|
||||
.limit(1)
|
||||
.pipe(
|
||||
Effect.map((rows) => rows[0] ?? null),
|
||||
Effect.mapError(persistenceError),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointAllocationPersistenceError({
|
||||
operation: "get",
|
||||
stage: "database-request",
|
||||
...input,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
reserve: Effect.fn("relay.managed_endpoint_allocations.reserve")(function* (
|
||||
@@ -140,7 +157,18 @@ const make = Effect.gen(function* () {
|
||||
updatedAt: now,
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning(allocationSelection);
|
||||
.returning(allocationSelection)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointAllocationPersistenceError({
|
||||
operation: "reserve",
|
||||
stage: "database-request",
|
||||
...input,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const allocation =
|
||||
inserted[0] ??
|
||||
@@ -149,16 +177,29 @@ const make = Effect.gen(function* () {
|
||||
.from(relayManagedEndpointAllocations)
|
||||
.where(whereAllocation(input))
|
||||
.limit(1)
|
||||
.pipe(Effect.map((rows) => rows[0])));
|
||||
.pipe(
|
||||
Effect.map((rows) => rows[0]),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointAllocationPersistenceError({
|
||||
operation: "reserve",
|
||||
stage: "database-request",
|
||||
...input,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
));
|
||||
|
||||
if (allocation === undefined) {
|
||||
return yield* new ManagedEndpointAllocationPersistenceError({
|
||||
cause: new Error("Managed endpoint allocation was not persisted."),
|
||||
operation: "reserve",
|
||||
stage: "resolve-reservation",
|
||||
...input,
|
||||
});
|
||||
}
|
||||
|
||||
return allocation;
|
||||
}, Effect.mapError(persistenceError)),
|
||||
}),
|
||||
recordTunnel: Effect.fn("relay.managed_endpoint_allocations.record_tunnel")(function* (
|
||||
input: RecordManagedEndpointTunnelInput,
|
||||
) {
|
||||
@@ -168,8 +209,19 @@ const make = Effect.gen(function* () {
|
||||
tunnelId: input.tunnelId,
|
||||
updatedAt: DateTime.formatIso(yield* DateTime.now),
|
||||
})
|
||||
.where(whereAllocation(input));
|
||||
}, Effect.mapError(persistenceError)),
|
||||
.where(whereAllocation(input))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointAllocationPersistenceError({
|
||||
operation: "record-tunnel",
|
||||
stage: "database-request",
|
||||
...input,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
recordDns: Effect.fn("relay.managed_endpoint_allocations.record_dns")(function* (
|
||||
input: RecordManagedEndpointDnsInput,
|
||||
) {
|
||||
@@ -179,8 +231,19 @@ const make = Effect.gen(function* () {
|
||||
dnsRecordId: input.dnsRecordId,
|
||||
updatedAt: DateTime.formatIso(yield* DateTime.now),
|
||||
})
|
||||
.where(whereAllocation(input));
|
||||
}, Effect.mapError(persistenceError)),
|
||||
.where(whereAllocation(input))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointAllocationPersistenceError({
|
||||
operation: "record-dns",
|
||||
stage: "database-request",
|
||||
...input,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
markReady: Effect.fn("relay.managed_endpoint_allocations.mark_ready")(function* (
|
||||
input: ManagedEndpointAllocationKey,
|
||||
) {
|
||||
@@ -191,13 +254,37 @@ const make = Effect.gen(function* () {
|
||||
readyAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(whereAllocation(input));
|
||||
}, Effect.mapError(persistenceError)),
|
||||
.where(whereAllocation(input))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointAllocationPersistenceError({
|
||||
operation: "mark-ready",
|
||||
stage: "database-request",
|
||||
...input,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
remove: Effect.fn("relay.managed_endpoint_allocations.remove")(function* (
|
||||
input: ManagedEndpointAllocationKey,
|
||||
) {
|
||||
yield* db.delete(relayManagedEndpointAllocations).where(whereAllocation(input));
|
||||
}, Effect.mapError(persistenceError)),
|
||||
yield* db
|
||||
.delete(relayManagedEndpointAllocations)
|
||||
.where(whereAllocation(input))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointAllocationPersistenceError({
|
||||
operation: "remove",
|
||||
stage: "database-request",
|
||||
...input,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -130,7 +130,10 @@ function makeDnsClient(
|
||||
calls.push({ operation: "updateRecord", input: { dnsRecordId, request } });
|
||||
if (!currentRecords.some((record) => record.id === dnsRecordId)) {
|
||||
return yield* new ManagedEndpointProvider.ManagedEndpointDnsClientError({
|
||||
cause: `DNS record ${dnsRecordId} does not exist.`,
|
||||
operation: "update-record",
|
||||
hostname: request.name,
|
||||
dnsRecordId,
|
||||
cause: { _tag: "NotFound", dnsRecordId },
|
||||
});
|
||||
}
|
||||
}),
|
||||
@@ -398,7 +401,13 @@ describe("ManagedEndpointProvider", () => {
|
||||
expect(dnsCalls).toHaveLength(0);
|
||||
expect(result._tag).toBe("Failure");
|
||||
if (result._tag === "Failure") {
|
||||
expect(result.failure._tag).toBe("ManagedEndpointOriginNotAllowed");
|
||||
expect(result.failure).toMatchObject({
|
||||
_tag: "ManagedEndpointOriginNotAllowed",
|
||||
userId: "user_ABC",
|
||||
environmentId: "env_ABC",
|
||||
host: "192.168.1.10",
|
||||
port: 3773,
|
||||
});
|
||||
}
|
||||
}).pipe(Effect.provide(providerLayer(makeTunnelClient(), makeDnsClient(dnsCalls))));
|
||||
});
|
||||
@@ -522,6 +531,59 @@ describe("ManagedEndpointProvider", () => {
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("does not hide non-not-found checkpoint update failures", () => {
|
||||
const dnsCalls: DnsCall[] = [];
|
||||
const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({
|
||||
operation: "update-record",
|
||||
dnsRecordId: "created-record-id",
|
||||
cause: new Error("Cloudflare DNS unavailable"),
|
||||
});
|
||||
let records: ReadonlyArray<{ readonly id: string }> = [];
|
||||
const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
|
||||
listRecords: (hostname) =>
|
||||
Effect.sync(() => {
|
||||
dnsCalls.push({ operation: "listRecords", input: hostname });
|
||||
return records;
|
||||
}),
|
||||
createRecord: (request) =>
|
||||
Effect.sync(() => {
|
||||
dnsCalls.push({ operation: "createRecord", input: request });
|
||||
const record = { id: "created-record-id" };
|
||||
records = [record];
|
||||
return record;
|
||||
}),
|
||||
updateRecord: (dnsRecordId, request) =>
|
||||
Effect.sync(() => {
|
||||
dnsCalls.push({ operation: "updateRecord", input: { dnsRecordId, request } });
|
||||
}).pipe(Effect.andThen(Effect.fail(failure))),
|
||||
deleteRecord: () => Effect.void,
|
||||
});
|
||||
const layer = providerLayer(makePersistentTunnelClient(), dnsClient, makeAllocations());
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
|
||||
const request = {
|
||||
userId: "user_ABC",
|
||||
environmentId: "env_ABC",
|
||||
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
|
||||
} as const;
|
||||
yield* provider.provision(request);
|
||||
const error = yield* Effect.flip(provider.provision(request));
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "ManagedEndpointProvisioningFailed",
|
||||
stage: "ensure-dns-record",
|
||||
userId: "user_ABC",
|
||||
environmentId: "env_ABC",
|
||||
});
|
||||
expect(dnsCalls.map((call) => call.operation)).toEqual([
|
||||
"listRecords",
|
||||
"createRecord",
|
||||
"updateRecord",
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"deprovisions checkpointed DNS and tunnel resources before removing the allocation",
|
||||
() => {
|
||||
@@ -593,6 +655,8 @@ describe("ManagedEndpointProvider", () => {
|
||||
const tunnelCalls: TunnelCall[] = [];
|
||||
let deleteAttempts = 0;
|
||||
const failure = new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
|
||||
operation: "delete",
|
||||
tunnelId: "tunnel-id",
|
||||
cause: "Cloudflare tunnel deletion failed",
|
||||
});
|
||||
const tunnels = makePersistentTunnelClient(tunnelCalls);
|
||||
@@ -618,6 +682,16 @@ describe("ManagedEndpointProvider", () => {
|
||||
});
|
||||
const first = yield* Effect.result(provider.deprovision(key));
|
||||
expect(first._tag).toBe("Failure");
|
||||
if (first._tag === "Failure") {
|
||||
expect(first.failure).toMatchObject({
|
||||
_tag: "ManagedEndpointDeprovisioningFailed",
|
||||
stage: "delete-tunnel",
|
||||
userId: key.userId,
|
||||
environmentId: key.environmentId,
|
||||
tunnelId: "tunnel-id",
|
||||
});
|
||||
expect(first.failure.cause).toBe(failure);
|
||||
}
|
||||
yield* provider.deprovision(key);
|
||||
|
||||
expect(allocationCalls.map((call) => call.operation)).toEqual([
|
||||
@@ -639,13 +713,23 @@ describe("ManagedEndpointProvider", () => {
|
||||
...makeTunnelClient(),
|
||||
delete: () =>
|
||||
Effect.fail(
|
||||
new ManagedEndpointProvider.ManagedEndpointTunnelClientError({ cause: notFound }),
|
||||
new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
|
||||
operation: "delete",
|
||||
tunnelId: "tunnel-id",
|
||||
cause: notFound,
|
||||
}),
|
||||
),
|
||||
});
|
||||
const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
|
||||
...makeDnsClient(),
|
||||
deleteRecord: () =>
|
||||
Effect.fail(new ManagedEndpointProvider.ManagedEndpointDnsClientError({ cause: notFound })),
|
||||
Effect.fail(
|
||||
new ManagedEndpointProvider.ManagedEndpointDnsClientError({
|
||||
operation: "delete-record",
|
||||
dnsRecordId: "created-record-id",
|
||||
cause: notFound,
|
||||
}),
|
||||
),
|
||||
});
|
||||
const layer = providerLayer(tunnelClient, dnsClient, makeAllocations(allocationCalls));
|
||||
|
||||
@@ -690,6 +774,8 @@ describe("ManagedEndpointProvider", () => {
|
||||
it.effect("recovers when DNS creation reports failure after the record became visible", () => {
|
||||
const dnsCalls: DnsCall[] = [];
|
||||
const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({
|
||||
operation: "create-record",
|
||||
hostname: expectedManagedHostname("env_ABC"),
|
||||
cause: "ambiguous Cloudflare DNS response",
|
||||
});
|
||||
let records: ReadonlyArray<{ readonly id: string }> = [];
|
||||
@@ -732,8 +818,44 @@ describe("ManagedEndpointProvider", () => {
|
||||
}).pipe(Effect.provide(providerLayer(makeTunnelClient(), dnsClient)));
|
||||
});
|
||||
|
||||
it.effect("reports mismatched tunnel responses without manufacturing a cause", () => {
|
||||
const dnsCalls: DnsCall[] = [];
|
||||
const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
|
||||
...makeTunnelClient(),
|
||||
create: () => Effect.succeed({ id: "returned-tunnel-id", name: "unexpected-tunnel" }),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
|
||||
const error = yield* Effect.flip(
|
||||
provider.provision({
|
||||
userId: "user_ABC",
|
||||
environmentId: "env_ABC",
|
||||
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "ManagedEndpointProvisioningFailed",
|
||||
stage: "validate-tunnel-response",
|
||||
userId: "user_ABC",
|
||||
environmentId: "env_ABC",
|
||||
hostname: expectedManagedHostname("env_ABC"),
|
||||
tunnelName: expectedManagedTunnelName("env_ABC"),
|
||||
returnedTunnelId: "returned-tunnel-id",
|
||||
returnedTunnelName: "unexpected-tunnel",
|
||||
});
|
||||
if (error._tag === "ManagedEndpointProvisioningFailed") {
|
||||
expect(error.cause).toBeUndefined();
|
||||
}
|
||||
expect(dnsCalls).toHaveLength(0);
|
||||
}).pipe(Effect.provide(providerLayer(tunnelClient, makeDnsClient(dnsCalls))));
|
||||
});
|
||||
|
||||
it.effect("fails provisioning when the DNS client fails", () => {
|
||||
const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({
|
||||
operation: "list-records",
|
||||
hostname: expectedManagedHostname("env_ABC"),
|
||||
cause: "Cloudflare DNS failure",
|
||||
});
|
||||
const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
|
||||
@@ -753,8 +875,18 @@ describe("ManagedEndpointProvider", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error._tag).toBe("ManagedEndpointProvisioningFailed");
|
||||
expect(error.cause).toBe(failure);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "ManagedEndpointProvisioningFailed",
|
||||
stage: "ensure-dns-record",
|
||||
userId: "user_ABC",
|
||||
environmentId: "env_ABC",
|
||||
hostname: expectedManagedHostname("env_ABC"),
|
||||
tunnelName: expectedManagedTunnelName("env_ABC"),
|
||||
tunnelId: "tunnel-id",
|
||||
});
|
||||
if (error._tag === "ManagedEndpointProvisioningFailed") {
|
||||
expect(error.cause).toBe(failure);
|
||||
}
|
||||
}).pipe(Effect.provide(providerLayer(makeTunnelClient(), dnsClient)));
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import type {
|
||||
@@ -27,40 +26,86 @@ import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
|
||||
|
||||
export class ManagedEndpointProvisioningNotConfigured extends Schema.TaggedErrorClass<ManagedEndpointProvisioningNotConfigured>()(
|
||||
"ManagedEndpointProvisioningNotConfigured",
|
||||
{},
|
||||
{
|
||||
userId: Schema.String,
|
||||
environmentId: Schema.String,
|
||||
missingSettings: Schema.Array(
|
||||
Schema.Literals(["managedEndpointBaseDomain", "managedEndpointNamespace"]),
|
||||
),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint provisioning is not configured";
|
||||
return `Managed endpoint provisioning is not configured for user '${this.userId}', environment '${this.environmentId}': missing ${this.missingSettings.join(", ")}`;
|
||||
}
|
||||
}
|
||||
|
||||
const ManagedEndpointProvisioningStage = Schema.Literals([
|
||||
"derive-environment-hash",
|
||||
"reserve-allocation",
|
||||
"ensure-tunnel",
|
||||
"validate-tunnel-response",
|
||||
"record-tunnel",
|
||||
"configure-tunnel",
|
||||
"ensure-dns-record",
|
||||
"record-dns",
|
||||
"get-tunnel-token",
|
||||
"mark-allocation-ready",
|
||||
]);
|
||||
|
||||
export class ManagedEndpointProvisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointProvisioningFailed>()(
|
||||
"ManagedEndpointProvisioningFailed",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
stage: ManagedEndpointProvisioningStage,
|
||||
userId: Schema.String,
|
||||
environmentId: Schema.String,
|
||||
hostname: Schema.optionalKey(Schema.String),
|
||||
tunnelName: Schema.optionalKey(Schema.String),
|
||||
tunnelId: Schema.optionalKey(Schema.String),
|
||||
dnsRecordId: Schema.optionalKey(Schema.String),
|
||||
returnedTunnelName: Schema.optionalKey(Schema.String),
|
||||
returnedTunnelId: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint provisioning failed";
|
||||
return `Managed endpoint provisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
|
||||
}
|
||||
}
|
||||
|
||||
const ManagedEndpointDeprovisioningStage = Schema.Literals([
|
||||
"load-allocation",
|
||||
"delete-dns-record",
|
||||
"delete-tunnel",
|
||||
"remove-allocation",
|
||||
]);
|
||||
|
||||
export class ManagedEndpointDeprovisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointDeprovisioningFailed>()(
|
||||
"ManagedEndpointDeprovisioningFailed",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
stage: ManagedEndpointDeprovisioningStage,
|
||||
userId: Schema.String,
|
||||
environmentId: Schema.String,
|
||||
tunnelId: Schema.optionalKey(Schema.String),
|
||||
dnsRecordId: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint deprovisioning failed";
|
||||
return `Managed endpoint deprovisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ManagedEndpointOriginNotAllowed extends Schema.TaggedErrorClass<ManagedEndpointOriginNotAllowed>()(
|
||||
"ManagedEndpointOriginNotAllowed",
|
||||
{
|
||||
userId: Schema.String,
|
||||
environmentId: Schema.String,
|
||||
host: Schema.String,
|
||||
port: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Managed endpoint origin '${this.host}:${this.port}' is not allowed`;
|
||||
return `Managed endpoint origin '${this.host}:${this.port}' is not allowed for user '${this.userId}', environment '${this.environmentId}'`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,12 +139,26 @@ interface ManagedEndpointTunnel {
|
||||
readonly name?: string | null;
|
||||
}
|
||||
|
||||
const ManagedEndpointTunnelClientOperation = Schema.Literals([
|
||||
"list",
|
||||
"create",
|
||||
"put-configuration",
|
||||
"get-token",
|
||||
"delete",
|
||||
]);
|
||||
|
||||
export class ManagedEndpointTunnelClientError extends Schema.TaggedErrorClass<ManagedEndpointTunnelClientError>()(
|
||||
"ManagedEndpointTunnelClientError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
operation: ManagedEndpointTunnelClientOperation,
|
||||
tunnelName: Schema.optionalKey(Schema.String),
|
||||
tunnelId: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint tunnel provider request failed";
|
||||
const target = this.tunnelId ?? this.tunnelName;
|
||||
return `Managed endpoint tunnel provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,11 +192,8 @@ export class ManagedEndpointTunnelClient extends Context.Service<
|
||||
}
|
||||
>()("t3code-relay/environments/ManagedEndpointProvider/ManagedEndpointTunnelClient") {}
|
||||
|
||||
export const makeTunnelClient = (client: ManagedEndpointTunnelClient["Service"]) =>
|
||||
ManagedEndpointTunnelClient.of(client);
|
||||
|
||||
export const layerTunnelClient = (client: ManagedEndpointTunnelClient["Service"]) =>
|
||||
Layer.succeed(ManagedEndpointTunnelClient, makeTunnelClient(client));
|
||||
Layer.succeed(ManagedEndpointTunnelClient, client);
|
||||
|
||||
interface ManagedEndpointCnameRecordInput {
|
||||
readonly type: "CNAME";
|
||||
@@ -147,12 +203,25 @@ interface ManagedEndpointCnameRecordInput {
|
||||
readonly proxied: true;
|
||||
}
|
||||
|
||||
const ManagedEndpointDnsClientOperation = Schema.Literals([
|
||||
"list-records",
|
||||
"create-record",
|
||||
"update-record",
|
||||
"delete-record",
|
||||
]);
|
||||
|
||||
export class ManagedEndpointDnsClientError extends Schema.TaggedErrorClass<ManagedEndpointDnsClientError>()(
|
||||
"ManagedEndpointDnsClientError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
operation: ManagedEndpointDnsClientOperation,
|
||||
hostname: Schema.optionalKey(Schema.String),
|
||||
dnsRecordId: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint DNS provider request failed";
|
||||
const target = this.dnsRecordId ?? this.hostname;
|
||||
return `Managed endpoint DNS provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,21 +244,31 @@ export class ManagedEndpointDnsClient extends Context.Service<
|
||||
}
|
||||
>()("t3code-relay/environments/ManagedEndpointProvider/ManagedEndpointDnsClient") {}
|
||||
|
||||
export const makeDnsClient = (client: ManagedEndpointDnsClient["Service"]) =>
|
||||
ManagedEndpointDnsClient.of(client);
|
||||
|
||||
export const layerDnsClient = (client: ManagedEndpointDnsClient["Service"]) =>
|
||||
Layer.succeed(ManagedEndpointDnsClient, makeDnsClient(client));
|
||||
Layer.succeed(ManagedEndpointDnsClient, client);
|
||||
|
||||
const requireCloudflareSettings = Effect.fnUntraced(function* (
|
||||
settings: RelayConfiguration.RelayConfiguration["Service"],
|
||||
input: { readonly userId: string; readonly environmentId: string },
|
||||
) {
|
||||
if (!settings.managedEndpointBaseDomain || !settings.managedEndpointNamespace) {
|
||||
return yield* new ManagedEndpointProvisioningNotConfigured();
|
||||
const baseDomain = settings.managedEndpointBaseDomain;
|
||||
const namespace = settings.managedEndpointNamespace;
|
||||
const missingSettings: Array<"managedEndpointBaseDomain" | "managedEndpointNamespace"> = [];
|
||||
if (!baseDomain) {
|
||||
missingSettings.push("managedEndpointBaseDomain");
|
||||
}
|
||||
if (!namespace) {
|
||||
missingSettings.push("managedEndpointNamespace");
|
||||
}
|
||||
if (!baseDomain || !namespace) {
|
||||
return yield* new ManagedEndpointProvisioningNotConfigured({
|
||||
...input,
|
||||
missingSettings,
|
||||
});
|
||||
}
|
||||
return {
|
||||
baseDomain: settings.managedEndpointBaseDomain,
|
||||
namespace: settings.managedEndpointNamespace,
|
||||
baseDomain,
|
||||
namespace,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -231,13 +310,22 @@ function isNotFoundCause(cause: unknown): boolean {
|
||||
return "cause" in cause && isNotFoundCause(cause.cause);
|
||||
}
|
||||
|
||||
const ignoreNotFound = <A, E>(effect: Effect.Effect<A, E>): Effect.Effect<void, E> =>
|
||||
type ManagedEndpointClientError = ManagedEndpointTunnelClientError | ManagedEndpointDnsClientError;
|
||||
|
||||
const ignoreNotFound = <A>(
|
||||
effect: Effect.Effect<A, ManagedEndpointClientError>,
|
||||
): Effect.Effect<void, ManagedEndpointClientError> =>
|
||||
effect.pipe(
|
||||
Effect.asVoid,
|
||||
Effect.catch((cause) => (isNotFoundCause(cause) ? Effect.void : Effect.fail(cause))),
|
||||
Effect.catchTags({
|
||||
ManagedEndpointTunnelClientError: (error) =>
|
||||
isNotFoundCause(error.cause) ? Effect.void : Effect.fail(error),
|
||||
ManagedEndpointDnsClientError: (error) =>
|
||||
isNotFoundCause(error.cause) ? Effect.void : Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const config = yield* RelayConfiguration.RelayConfiguration;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const tunnels = yield* ManagedEndpointTunnelClient;
|
||||
@@ -272,7 +360,10 @@ const make = Effect.gen(function* () {
|
||||
.updateRecord(preferredDnsRecordId, dnsRecord)
|
||||
.pipe(
|
||||
Effect.as(true),
|
||||
Effect.orElseSucceed(() => false),
|
||||
Effect.catchTags({
|
||||
ManagedEndpointDnsClientError: (error) =>
|
||||
isNotFoundCause(error.cause) ? Effect.succeed(false) : Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
if (checkpointedRecordUpdated) {
|
||||
return preferredDnsRecordId;
|
||||
@@ -289,25 +380,26 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
return yield* dns.createRecord(dnsRecord).pipe(
|
||||
Effect.map((record) => record.id),
|
||||
Effect.catch((createError) =>
|
||||
Effect.gen(function* () {
|
||||
let records = yield* dns.listRecords(hostname);
|
||||
for (let attempt = 0; records.length === 0 && attempt < 4; attempt++) {
|
||||
yield* Effect.sleep("200 millis");
|
||||
records = yield* dns.listRecords(hostname);
|
||||
}
|
||||
return records;
|
||||
}).pipe(
|
||||
Effect.flatMap((records) =>
|
||||
records.length > 0
|
||||
? updateExistingDnsRecords(records, preferredDnsRecordId, dnsRecord)
|
||||
: Effect.fail(createError),
|
||||
Effect.catchTags({
|
||||
ManagedEndpointDnsClientError: (createError) =>
|
||||
Effect.gen(function* () {
|
||||
let records = yield* dns.listRecords(hostname);
|
||||
for (let attempt = 0; records.length === 0 && attempt < 4; attempt++) {
|
||||
yield* Effect.sleep("200 millis");
|
||||
records = yield* dns.listRecords(hostname);
|
||||
}
|
||||
return records;
|
||||
}).pipe(
|
||||
Effect.flatMap((records) =>
|
||||
records.length > 0
|
||||
? updateExistingDnsRecords(records, preferredDnsRecordId, dnsRecord)
|
||||
: Effect.fail(createError),
|
||||
),
|
||||
Effect.flatMap((dnsRecordId) =>
|
||||
dnsRecordId === null ? Effect.fail(createError) : Effect.succeed(dnsRecordId),
|
||||
),
|
||||
),
|
||||
Effect.flatMap((dnsRecordId) =>
|
||||
dnsRecordId === null ? Effect.fail(createError) : Effect.succeed(dnsRecordId),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -317,25 +409,59 @@ const make = Effect.gen(function* () {
|
||||
"relay.user_id": input.userId,
|
||||
"relay.environment_id": input.environmentId,
|
||||
});
|
||||
const allocation = yield* allocations
|
||||
.get(input)
|
||||
.pipe(Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })));
|
||||
const allocation = yield* allocations.get(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointDeprovisioningFailed({
|
||||
...input,
|
||||
stage: "load-allocation",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (allocation === null) {
|
||||
return;
|
||||
}
|
||||
if (allocation.dnsRecordId !== null) {
|
||||
yield* ignoreNotFound(dns.deleteRecord(allocation.dnsRecordId)).pipe(
|
||||
Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })),
|
||||
const dnsRecordId = allocation.dnsRecordId;
|
||||
if (dnsRecordId !== null) {
|
||||
yield* ignoreNotFound(dns.deleteRecord(dnsRecordId)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointDeprovisioningFailed({
|
||||
...input,
|
||||
stage: "delete-dns-record",
|
||||
dnsRecordId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (allocation.tunnelId !== null) {
|
||||
yield* ignoreNotFound(tunnels.delete(allocation.tunnelId)).pipe(
|
||||
Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })),
|
||||
const tunnelId = allocation.tunnelId;
|
||||
if (tunnelId !== null) {
|
||||
yield* ignoreNotFound(tunnels.delete(tunnelId)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointDeprovisioningFailed({
|
||||
...input,
|
||||
stage: "delete-tunnel",
|
||||
tunnelId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
yield* allocations
|
||||
.remove(input)
|
||||
.pipe(Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })));
|
||||
yield* allocations.remove(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointDeprovisioningFailed({
|
||||
...input,
|
||||
stage: "remove-allocation",
|
||||
...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),
|
||||
...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
provision: Effect.fn("relay.managed_endpoint_provider.provision")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
@@ -346,11 +472,13 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
if (!isLoopbackOrigin(input.origin)) {
|
||||
return yield* new ManagedEndpointOriginNotAllowed({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
host: input.origin.localHttpHost,
|
||||
port: input.origin.localHttpPort,
|
||||
});
|
||||
}
|
||||
const cf = yield* requireCloudflareSettings(config);
|
||||
const cf = yield* requireCloudflareSettings(config, input);
|
||||
const environmentHash = yield* crypto
|
||||
.digest(
|
||||
"SHA-256",
|
||||
@@ -360,19 +488,45 @@ const make = Effect.gen(function* () {
|
||||
)
|
||||
.pipe(
|
||||
Effect.map(Encoding.encodeHex),
|
||||
Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointProvisioningFailed({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
stage: "derive-environment-hash",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const requestedHostname = managedEndpointHostname(
|
||||
cf.namespace,
|
||||
cf.baseDomain,
|
||||
environmentHash,
|
||||
);
|
||||
const requestedTunnelName = managedEndpointTunnelName(cf.namespace, environmentHash);
|
||||
const allocation = yield* allocations
|
||||
.reserve({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
hostname: managedEndpointHostname(cf.namespace, cf.baseDomain, environmentHash),
|
||||
tunnelName: managedEndpointTunnelName(cf.namespace, environmentHash),
|
||||
hostname: requestedHostname,
|
||||
tunnelName: requestedTunnelName,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointProvisioningFailed({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
stage: "reserve-allocation",
|
||||
hostname: requestedHostname,
|
||||
tunnelName: requestedTunnelName,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const { hostname, tunnelName } = allocation;
|
||||
|
||||
const tunnel = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe(
|
||||
const tunnelResponse = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe(
|
||||
Effect.map((tunnels) => tunnels.result),
|
||||
Effect.map(Arr.findFirst((tunnel) => tunnel.name === tunnelName)),
|
||||
Effect.flatMap(
|
||||
@@ -381,20 +535,50 @@ const make = Effect.gen(function* () {
|
||||
onNone: () => tunnels.create({ name: tunnelName, configSrc: "cloudflare" }),
|
||||
}),
|
||||
),
|
||||
Effect.filterMapOrFail((tunnel) =>
|
||||
tunnel.id && tunnel.name
|
||||
? Result.succeed({ id: tunnel.id, name: tunnel.name })
|
||||
: Result.fail(new ManagedEndpointProvisioningFailed({ cause: tunnel })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointProvisioningFailed({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
stage: "ensure-tunnel",
|
||||
hostname,
|
||||
tunnelName,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })),
|
||||
);
|
||||
if (!tunnelResponse.id || tunnelResponse.name !== tunnelName) {
|
||||
return yield* new ManagedEndpointProvisioningFailed({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
stage: "validate-tunnel-response",
|
||||
hostname,
|
||||
tunnelName,
|
||||
...(tunnelResponse.id ? { returnedTunnelId: tunnelResponse.id } : {}),
|
||||
...(tunnelResponse.name ? { returnedTunnelName: tunnelResponse.name } : {}),
|
||||
});
|
||||
}
|
||||
const tunnel = { id: tunnelResponse.id, name: tunnelResponse.name };
|
||||
yield* allocations
|
||||
.recordTunnel({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
tunnelId: tunnel.id,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointProvisioningFailed({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
stage: "record-tunnel",
|
||||
hostname,
|
||||
tunnelName,
|
||||
tunnelId: tunnel.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* tunnels
|
||||
.putConfiguration(tunnel.id, {
|
||||
@@ -406,7 +590,20 @@ const make = Effect.gen(function* () {
|
||||
{ service: "http_status:404" },
|
||||
],
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointProvisioningFailed({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
stage: "configure-tunnel",
|
||||
hostname,
|
||||
tunnelName,
|
||||
tunnelId: tunnel.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const dnsRecord = {
|
||||
type: "CNAME",
|
||||
@@ -417,7 +614,19 @@ const make = Effect.gen(function* () {
|
||||
} as const;
|
||||
|
||||
const dnsRecordId = yield* ensureDnsRecord(hostname, allocation.dnsRecordId, dnsRecord).pipe(
|
||||
Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointProvisioningFailed({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
stage: "ensure-dns-record",
|
||||
hostname,
|
||||
tunnelName,
|
||||
tunnelId: tunnel.id,
|
||||
...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* allocations
|
||||
.recordDns({
|
||||
@@ -425,17 +634,57 @@ const make = Effect.gen(function* () {
|
||||
environmentId: input.environmentId,
|
||||
dnsRecordId,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointProvisioningFailed({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
stage: "record-dns",
|
||||
hostname,
|
||||
tunnelName,
|
||||
tunnelId: tunnel.id,
|
||||
dnsRecordId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const connectorToken = yield* tunnels
|
||||
.getToken(tunnel.id)
|
||||
.pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
|
||||
const connectorToken = yield* tunnels.getToken(tunnel.id).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointProvisioningFailed({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
stage: "get-tunnel-token",
|
||||
hostname,
|
||||
tunnelName,
|
||||
tunnelId: tunnel.id,
|
||||
dnsRecordId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* allocations
|
||||
.markReady({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointProvisioningFailed({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
stage: "mark-allocation-ready",
|
||||
hostname,
|
||||
tunnelName,
|
||||
tunnelId: tunnel.id,
|
||||
dnsRecordId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
endpoint: managedEndpointForHostname(hostname),
|
||||
@@ -460,67 +709,127 @@ export const layerCloudflareBindings = (
|
||||
layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
layerTunnelClient(
|
||||
ManagedEndpointTunnelClient.of({
|
||||
list: (request) =>
|
||||
tunnelClient.list(request).pipe(
|
||||
Effect.mapError((cause) => new ManagedEndpointTunnelClientError({ cause })),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
layerTunnelClient({
|
||||
list: (request) =>
|
||||
tunnelClient.list(request).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointTunnelClientError({
|
||||
operation: "list",
|
||||
tunnelName: request.name,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
create: (request) =>
|
||||
tunnelClient.create(request).pipe(
|
||||
Effect.mapError((cause) => new ManagedEndpointTunnelClientError({ cause })),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
),
|
||||
create: (request) =>
|
||||
tunnelClient.create(request).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointTunnelClientError({
|
||||
operation: "create",
|
||||
tunnelName: request.name,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
putConfiguration: (tunnelId, config) =>
|
||||
tunnelClient.putConfiguration(tunnelId, config).pipe(
|
||||
Effect.mapError((cause) => new ManagedEndpointTunnelClientError({ cause })),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
),
|
||||
putConfiguration: (tunnelId, config) =>
|
||||
tunnelClient.putConfiguration(tunnelId, config).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointTunnelClientError({
|
||||
operation: "put-configuration",
|
||||
tunnelId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
getToken: (tunnelId) =>
|
||||
tunnelClient.getToken(tunnelId).pipe(
|
||||
Effect.mapError((cause) => new ManagedEndpointTunnelClientError({ cause })),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
),
|
||||
getToken: (tunnelId) =>
|
||||
tunnelClient.getToken(tunnelId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointTunnelClientError({
|
||||
operation: "get-token",
|
||||
tunnelId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
delete: (tunnelId) =>
|
||||
tunnelClient.delete(tunnelId).pipe(
|
||||
Effect.mapError((cause) => new ManagedEndpointTunnelClientError({ cause })),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
),
|
||||
delete: (tunnelId) =>
|
||||
tunnelClient.delete(tunnelId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointTunnelClientError({
|
||||
operation: "delete",
|
||||
tunnelId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
layerDnsClient(
|
||||
ManagedEndpointDnsClient.of({
|
||||
listRecords: (hostname) =>
|
||||
dnsClient.listDnsRecords({ search: hostname }).pipe(
|
||||
Effect.map((response) =>
|
||||
response.result.filter(
|
||||
(record): record is typeof record & { readonly id: string } =>
|
||||
typeof record.id === "string" &&
|
||||
normalizeHostname(record.name) === normalizeHostname(hostname),
|
||||
),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
),
|
||||
}),
|
||||
layerDnsClient({
|
||||
listRecords: (hostname) =>
|
||||
dnsClient.listDnsRecords({ search: hostname }).pipe(
|
||||
Effect.map((response) =>
|
||||
response.result.filter(
|
||||
(record): record is typeof record & { readonly id: string } =>
|
||||
typeof record.id === "string" &&
|
||||
normalizeHostname(record.name) === normalizeHostname(hostname),
|
||||
),
|
||||
Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
),
|
||||
createRecord: (request) =>
|
||||
dnsClient.createDnsRecord(request).pipe(
|
||||
Effect.map((response) => ({ id: response.id })),
|
||||
Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointDnsClientError({
|
||||
operation: "list-records",
|
||||
hostname,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
updateRecord: (dnsRecordId, request) =>
|
||||
dnsClient.updateDnsRecord(dnsRecordId, request).pipe(
|
||||
Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
),
|
||||
createRecord: (request) =>
|
||||
dnsClient.createDnsRecord(request).pipe(
|
||||
Effect.map((response) => ({ id: response.id })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointDnsClientError({
|
||||
operation: "create-record",
|
||||
hostname: request.name,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
deleteRecord: (dnsRecordId) =>
|
||||
dnsClient.deleteDnsRecord(dnsRecordId).pipe(
|
||||
Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
),
|
||||
updateRecord: (dnsRecordId, request) =>
|
||||
dnsClient.updateDnsRecord(dnsRecordId, request).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointDnsClientError({
|
||||
operation: "update-record",
|
||||
hostname: request.name,
|
||||
dnsRecordId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
),
|
||||
deleteRecord: (dnsRecordId) =>
|
||||
dnsClient.deleteDnsRecord(dnsRecordId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedEndpointDnsClientError({
|
||||
operation: "delete-record",
|
||||
dnsRecordId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -108,6 +108,7 @@ describe("relay client authentication", () => {
|
||||
describe("relay environment authentication", () => {
|
||||
it.effect("preserves credential lookup persistence failures as internal errors", () => {
|
||||
const failure = new EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError({
|
||||
stage: "lookup-credential",
|
||||
cause: "database unavailable",
|
||||
});
|
||||
const credentials: EnvironmentCredentials.EnvironmentCredentials["Service"] = {
|
||||
|
||||
+71
-25
@@ -238,13 +238,12 @@ export const relayEnvironmentAuthLayer = Layer.effect(
|
||||
{ credential },
|
||||
) {
|
||||
const token = readHttpAuthorizationCredential(credential);
|
||||
const principal = yield* credentials
|
||||
.authenticate(token)
|
||||
.pipe(
|
||||
Effect.catchTag("EnvironmentCredentialAuthenticatePersistenceError", () =>
|
||||
const principal = yield* credentials.authenticate(token).pipe(
|
||||
Effect.catchTags({
|
||||
EnvironmentCredentialAuthenticatePersistenceError: () =>
|
||||
relayInternalErrorResponse("persistence_failed"),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
if (principal._tag === "None") {
|
||||
return yield* relayAuthInvalidError("not_authorized");
|
||||
}
|
||||
@@ -777,17 +776,72 @@ export const serverApi = HttpApiBuilder.group(
|
||||
reason: "persistence_failed",
|
||||
traceId,
|
||||
}),
|
||||
ApnsDeliveryJobQueuePayloadInvalid: mapApnsDeliveryJobInternalError,
|
||||
ApnsDeliveryJobLiveActivityAggregateMissing: mapApnsDeliveryJobInternalError,
|
||||
ApnsDeliveryJobLiveActivityNotificationUnexpected: mapApnsDeliveryJobInternalError,
|
||||
ApnsDeliveryJobPushNotificationMissing: mapApnsDeliveryJobInternalError,
|
||||
ApnsDeliveryJobPushNotificationAggregateUnexpected: mapApnsDeliveryJobInternalError,
|
||||
ApnsDeliveryJobCreatedAtInvalid: mapApnsDeliveryJobInternalError,
|
||||
ApnsDeliveryJobExpiresAtInvalid: mapApnsDeliveryJobInternalError,
|
||||
ApnsDeliveryJobTimeWindowInvalid: mapApnsDeliveryJobInternalError,
|
||||
ApnsDeliveryJobTimeWindowTooLong: mapApnsDeliveryJobInternalError,
|
||||
ApnsDeliveryJobSignatureInvalid: mapApnsDeliveryJobInternalError,
|
||||
ApnsDeliveryJobExpired: mapApnsDeliveryJobInternalError,
|
||||
ApnsDeliveryJobQueuePayloadInvalid: (_error, traceId) =>
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "internal_error",
|
||||
traceId,
|
||||
}),
|
||||
ApnsDeliveryJobLiveActivityAggregateMissing: (_error, traceId) =>
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "internal_error",
|
||||
traceId,
|
||||
}),
|
||||
ApnsDeliveryJobLiveActivityNotificationUnexpected: (_error, traceId) =>
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "internal_error",
|
||||
traceId,
|
||||
}),
|
||||
ApnsDeliveryJobPushNotificationMissing: (_error, traceId) =>
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "internal_error",
|
||||
traceId,
|
||||
}),
|
||||
ApnsDeliveryJobPushNotificationAggregateUnexpected: (_error, traceId) =>
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "internal_error",
|
||||
traceId,
|
||||
}),
|
||||
ApnsDeliveryJobCreatedAtInvalid: (_error, traceId) =>
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "internal_error",
|
||||
traceId,
|
||||
}),
|
||||
ApnsDeliveryJobExpiresAtInvalid: (_error, traceId) =>
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "internal_error",
|
||||
traceId,
|
||||
}),
|
||||
ApnsDeliveryJobTimeWindowInvalid: (_error, traceId) =>
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "internal_error",
|
||||
traceId,
|
||||
}),
|
||||
ApnsDeliveryJobTimeWindowTooLong: (_error, traceId) =>
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "internal_error",
|
||||
traceId,
|
||||
}),
|
||||
ApnsDeliveryJobSignatureInvalid: (_error, traceId) =>
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "internal_error",
|
||||
traceId,
|
||||
}),
|
||||
ApnsDeliveryJobExpired: (_error, traceId) =>
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "internal_error",
|
||||
traceId,
|
||||
}),
|
||||
ApnsDeliveryJobClaimInFlight: (_error, traceId) =>
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
@@ -892,14 +946,6 @@ function mapRelayCommonApiErrors(authReason: RelayAuthInvalidReason) {
|
||||
): Effect.Effect<A, MapRelayCommonApiError<E>, R> => effect.pipe(Effect.catch(mapError));
|
||||
}
|
||||
|
||||
function mapApnsDeliveryJobInternalError(_error: unknown, traceId: string) {
|
||||
return new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "internal_error",
|
||||
traceId,
|
||||
});
|
||||
}
|
||||
|
||||
type TaggedErrorTag<E> = Extract<E, { readonly _tag: string }>["_tag"];
|
||||
|
||||
type MapErrorTagCases<E> = {
|
||||
|
||||
@@ -40,6 +40,7 @@ export type ProjectListEntriesResult = typeof ProjectListEntriesResult.Type;
|
||||
export const ProjectEntriesFailure = Schema.Literals([
|
||||
"workspace_root_not_found",
|
||||
"workspace_root_create_failed",
|
||||
"workspace_root_stat_failed",
|
||||
"workspace_root_not_directory",
|
||||
"search_index_create_failed",
|
||||
"search_index_scan_timed_out",
|
||||
|
||||
@@ -155,6 +155,10 @@ export class SourceControlProviderError extends Schema.TaggedErrorClass<SourceCo
|
||||
{
|
||||
provider: SourceControlProviderKind,
|
||||
operation: Schema.String,
|
||||
cwd: Schema.String,
|
||||
command: Schema.optional(Schema.String),
|
||||
repository: Schema.optional(Schema.String),
|
||||
reference: Schema.optional(Schema.String),
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
|
||||
@@ -1,30 +1,29 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
import { RpcClientError } from "effect/unstable/rpc";
|
||||
|
||||
import * as AcpSchema from "../_generated/schema.gen.ts";
|
||||
import * as AcpError from "../errors.ts";
|
||||
const isError = Schema.is(AcpSchema.Error);
|
||||
const isAcpRequestError = Schema.is(AcpError.AcpRequestError);
|
||||
|
||||
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
|
||||
|
||||
export const callRpc = <A>(
|
||||
method: string,
|
||||
effect: Effect.Effect<A, RpcClientError.RpcClientError | AcpSchema.Error>,
|
||||
): Effect.Effect<A, AcpError.AcpError> =>
|
||||
effect.pipe(
|
||||
Effect.catchTag("RpcClientError", (error) =>
|
||||
Effect.fail(
|
||||
new AcpError.AcpTransportError({
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catchIf(isError, (error) =>
|
||||
Effect.fail(AcpError.AcpRequestError.fromProtocolError(error)),
|
||||
),
|
||||
Effect.catchTags({
|
||||
RpcClientError: (cause) =>
|
||||
Effect.fail(
|
||||
new AcpError.AcpTransportError({
|
||||
operation: "call-rpc",
|
||||
method,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
export const runHandler = Effect.fnUntraced(function* <A, B>(
|
||||
@@ -37,9 +36,7 @@ export const runHandler = Effect.fnUntraced(function* <A, B>(
|
||||
}
|
||||
return yield* handler(payload).pipe(
|
||||
Effect.mapError((error) =>
|
||||
isAcpRequestError(error)
|
||||
? error.toProtocolError()
|
||||
: AcpError.AcpRequestError.internalError(error.message).toProtocolError(),
|
||||
AcpError.AcpRequestError.fromCoreHandlerError(error, method).toProtocolError(),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -51,12 +48,7 @@ export function decodeExtRequestRegistration<A, I>(
|
||||
) {
|
||||
return (params: unknown): Effect.Effect<unknown, AcpError.AcpError> =>
|
||||
Schema.decodeUnknownEffect(payload)(params).pipe(
|
||||
Effect.mapError((error) =>
|
||||
AcpError.AcpRequestError.invalidParams(
|
||||
`Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`,
|
||||
{ issue: error.issue },
|
||||
),
|
||||
),
|
||||
Effect.mapError((error) => AcpError.AcpRequestError.invalidExtensionPayload(method, error)),
|
||||
Effect.flatMap((decoded) => handler(decoded)),
|
||||
);
|
||||
}
|
||||
@@ -68,12 +60,12 @@ export function decodeExtNotificationRegistration<A, I>(
|
||||
) {
|
||||
return (params: unknown): Effect.Effect<void, AcpError.AcpError> =>
|
||||
Schema.decodeUnknownEffect(payload)(params).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new AcpError.AcpProtocolParseError({
|
||||
detail: `Invalid ${method} notification payload: ${formatSchemaIssue(error.issue)}`,
|
||||
cause: error,
|
||||
}),
|
||||
Effect.mapError((error) =>
|
||||
AcpError.AcpProtocolParseError.fromSchemaError(
|
||||
"decode-notification-payload",
|
||||
method,
|
||||
error,
|
||||
),
|
||||
),
|
||||
Effect.flatMap((decoded) => handler(decoded)),
|
||||
);
|
||||
|
||||
@@ -50,7 +50,7 @@ export const makeTerminationError = (
|
||||
Effect.match(handle.exitCode, {
|
||||
onFailure: (cause) =>
|
||||
new AcpError.AcpTransportError({
|
||||
detail: "Failed to determine ACP process exit status",
|
||||
operation: "read-process-exit-status",
|
||||
cause,
|
||||
}),
|
||||
onSuccess: (code) => new AcpError.AcpProcessExitedError({ code }),
|
||||
|
||||
@@ -288,12 +288,12 @@ export const make = Effect.fn("effect-acp/AcpAgent.make")(function* (
|
||||
notification.method === AGENT_METHODS.session_cancel
|
||||
) {
|
||||
return decodeCancelNotification(notification.params).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new AcpError.AcpProtocolParseError({
|
||||
detail: `Invalid ${AGENT_METHODS.session_cancel} notification payload`,
|
||||
cause: error,
|
||||
}),
|
||||
Effect.mapError((error) =>
|
||||
AcpError.AcpProtocolParseError.fromSchemaError(
|
||||
"decode-notification-payload",
|
||||
AGENT_METHODS.session_cancel,
|
||||
error,
|
||||
),
|
||||
),
|
||||
Effect.flatMap((decoded) =>
|
||||
Effect.forEach(cancelHandlers, (handler) => handler(decoded), { discard: true }),
|
||||
@@ -376,41 +376,55 @@ export const make = Effect.fn("effect-acp/AcpAgent.make")(function* (
|
||||
},
|
||||
client: {
|
||||
requestPermission: (payload) =>
|
||||
callRpc(rpc[CLIENT_METHODS.session_request_permission](payload)),
|
||||
elicit: (payload) => callRpc(rpc[CLIENT_METHODS.session_elicitation](payload)),
|
||||
readTextFile: (payload) => callRpc(rpc[CLIENT_METHODS.fs_read_text_file](payload)),
|
||||
writeTextFile: (payload) => callRpc(rpc[CLIENT_METHODS.fs_write_text_file](payload)),
|
||||
callRpc(
|
||||
CLIENT_METHODS.session_request_permission,
|
||||
rpc[CLIENT_METHODS.session_request_permission](payload),
|
||||
),
|
||||
elicit: (payload) =>
|
||||
callRpc(
|
||||
CLIENT_METHODS.session_elicitation,
|
||||
rpc[CLIENT_METHODS.session_elicitation](payload),
|
||||
),
|
||||
readTextFile: (payload) =>
|
||||
callRpc(CLIENT_METHODS.fs_read_text_file, rpc[CLIENT_METHODS.fs_read_text_file](payload)),
|
||||
writeTextFile: (payload) =>
|
||||
callRpc(CLIENT_METHODS.fs_write_text_file, rpc[CLIENT_METHODS.fs_write_text_file](payload)),
|
||||
createTerminal: (payload) =>
|
||||
callRpc(rpc[CLIENT_METHODS.terminal_create](payload)).pipe(
|
||||
Effect.map((response) =>
|
||||
AcpTerminal.makeTerminal({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
output: callRpc(
|
||||
rpc[CLIENT_METHODS.terminal_output]({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
}),
|
||||
),
|
||||
waitForExit: callRpc(
|
||||
rpc[CLIENT_METHODS.terminal_wait_for_exit]({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
}),
|
||||
),
|
||||
kill: callRpc(
|
||||
rpc[CLIENT_METHODS.terminal_kill]({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
}),
|
||||
),
|
||||
release: callRpc(
|
||||
rpc[CLIENT_METHODS.terminal_release]({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
callRpc(CLIENT_METHODS.terminal_create, rpc[CLIENT_METHODS.terminal_create](payload)).pipe(
|
||||
Effect.map(
|
||||
(response) =>
|
||||
({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
output: callRpc(
|
||||
CLIENT_METHODS.terminal_output,
|
||||
rpc[CLIENT_METHODS.terminal_output]({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
}),
|
||||
),
|
||||
waitForExit: callRpc(
|
||||
CLIENT_METHODS.terminal_wait_for_exit,
|
||||
rpc[CLIENT_METHODS.terminal_wait_for_exit]({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
}),
|
||||
),
|
||||
kill: callRpc(
|
||||
CLIENT_METHODS.terminal_kill,
|
||||
rpc[CLIENT_METHODS.terminal_kill]({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
}),
|
||||
),
|
||||
release: callRpc(
|
||||
CLIENT_METHODS.terminal_release,
|
||||
rpc[CLIENT_METHODS.terminal_release]({
|
||||
sessionId: payload.sessionId,
|
||||
terminalId: response.terminalId,
|
||||
}),
|
||||
),
|
||||
}) satisfies AcpTerminal.AcpTerminal,
|
||||
),
|
||||
),
|
||||
sessionUpdate: (payload) => transport.notify(CLIENT_METHODS.session_update, payload),
|
||||
|
||||
@@ -147,7 +147,7 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"returns formatted invalid params when a typed extension request payload is wrong",
|
||||
"returns structured invalid params without exposing values from typed extension request payloads",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const handle = yield* makeHandle({ ACP_MOCK_BAD_TYPED_REQUEST: "1" });
|
||||
@@ -213,8 +213,8 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
|
||||
assert.fail("Expected prompt to fail for invalid typed extension payload");
|
||||
}
|
||||
const rendered = Cause.pretty(result.cause);
|
||||
assert.include(rendered, "Invalid x/typed_request payload:");
|
||||
assert.include(rendered, "Expected string, got 123");
|
||||
assert.include(rendered, "Invalid payload for ACP extension method 'x/typed_request'.");
|
||||
assert.notInclude(rendered, "Expected string, got 123");
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -462,19 +462,32 @@ export const make = Effect.fn("effect-acp/AcpClient.make")(function* (
|
||||
notify: transport.notify,
|
||||
},
|
||||
agent: {
|
||||
initialize: (payload) => callRpc(rpc[AGENT_METHODS.initialize](payload)),
|
||||
authenticate: (payload) => callRpc(rpc[AGENT_METHODS.authenticate](payload)),
|
||||
logout: (payload) => callRpc(rpc[AGENT_METHODS.logout](payload)),
|
||||
createSession: (payload) => callRpc(rpc[AGENT_METHODS.session_new](payload)),
|
||||
loadSession: (payload) => callRpc(rpc[AGENT_METHODS.session_load](payload)),
|
||||
listSessions: (payload) => callRpc(rpc[AGENT_METHODS.session_list](payload)),
|
||||
forkSession: (payload) => callRpc(rpc[AGENT_METHODS.session_fork](payload)),
|
||||
resumeSession: (payload) => callRpc(rpc[AGENT_METHODS.session_resume](payload)),
|
||||
closeSession: (payload) => callRpc(rpc[AGENT_METHODS.session_close](payload)),
|
||||
setSessionModel: (payload) => callRpc(rpc[AGENT_METHODS.session_set_model](payload)),
|
||||
initialize: (payload) =>
|
||||
callRpc(AGENT_METHODS.initialize, rpc[AGENT_METHODS.initialize](payload)),
|
||||
authenticate: (payload) =>
|
||||
callRpc(AGENT_METHODS.authenticate, rpc[AGENT_METHODS.authenticate](payload)),
|
||||
logout: (payload) => callRpc(AGENT_METHODS.logout, rpc[AGENT_METHODS.logout](payload)),
|
||||
createSession: (payload) =>
|
||||
callRpc(AGENT_METHODS.session_new, rpc[AGENT_METHODS.session_new](payload)),
|
||||
loadSession: (payload) =>
|
||||
callRpc(AGENT_METHODS.session_load, rpc[AGENT_METHODS.session_load](payload)),
|
||||
listSessions: (payload) =>
|
||||
callRpc(AGENT_METHODS.session_list, rpc[AGENT_METHODS.session_list](payload)),
|
||||
forkSession: (payload) =>
|
||||
callRpc(AGENT_METHODS.session_fork, rpc[AGENT_METHODS.session_fork](payload)),
|
||||
resumeSession: (payload) =>
|
||||
callRpc(AGENT_METHODS.session_resume, rpc[AGENT_METHODS.session_resume](payload)),
|
||||
closeSession: (payload) =>
|
||||
callRpc(AGENT_METHODS.session_close, rpc[AGENT_METHODS.session_close](payload)),
|
||||
setSessionModel: (payload) =>
|
||||
callRpc(AGENT_METHODS.session_set_model, rpc[AGENT_METHODS.session_set_model](payload)),
|
||||
setSessionConfigOption: (payload) =>
|
||||
callRpc(rpc[AGENT_METHODS.session_set_config_option](payload)),
|
||||
prompt: (payload) => callRpc(rpc[AGENT_METHODS.session_prompt](payload)),
|
||||
callRpc(
|
||||
AGENT_METHODS.session_set_config_option,
|
||||
rpc[AGENT_METHODS.session_set_config_option](payload),
|
||||
),
|
||||
prompt: (payload) =>
|
||||
callRpc(AGENT_METHODS.session_prompt, rpc[AGENT_METHODS.session_prompt](payload)),
|
||||
cancel: (payload) => transport.notify(AGENT_METHODS.session_cancel, payload),
|
||||
},
|
||||
handleRequestPermission: (handler) =>
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as RpcClientError from "effect/unstable/rpc/RpcClientError";
|
||||
|
||||
import * as AcpSchema from "./_generated/schema.gen.ts";
|
||||
import { callRpc, runHandler } from "./_internal/shared.ts";
|
||||
import * as AcpError from "./errors.ts";
|
||||
|
||||
const decodeNestedNumberPayload = Schema.decodeUnknownEffect(
|
||||
Schema.Struct({ profile: Schema.Struct({ token: Schema.Number }) }),
|
||||
);
|
||||
const encodeUnknownJson = Schema.encodeSync(Schema.UnknownFromJsonString);
|
||||
|
||||
describe("effect-acp errors", () => {
|
||||
it.effect("retains RPC method and cause without deriving the message from the cause", () => {
|
||||
const rootCause = new Error("connection details that must not become the public message");
|
||||
const failure = new RpcClientError.RpcClientError({
|
||||
reason: new RpcClientError.RpcClientDefect({
|
||||
message: rootCause.message,
|
||||
cause: rootCause,
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* callRpc("session/new", Effect.fail(failure)).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "AcpTransportError",
|
||||
operation: "call-rpc",
|
||||
method: "session/new",
|
||||
cause: failure,
|
||||
});
|
||||
expect(error.message).toBe("ACP transport operation call-rpc failed for method session/new.");
|
||||
expect(error.message).not.toContain(rootCause.message);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("preserves protocol request errors as request errors", () => {
|
||||
const failure = AcpSchema.Error.make({
|
||||
code: -32602,
|
||||
message: "Invalid params",
|
||||
data: { field: "sessionId" },
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* callRpc("session/load", Effect.fail(failure)).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "AcpRequestError",
|
||||
code: -32602,
|
||||
errorMessage: "Invalid params",
|
||||
data: { field: "sessionId" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("does not expose legacy diagnostic detail as the transport message", () => {
|
||||
const cause = new Error("connection refused at a private endpoint");
|
||||
const error = new AcpError.AcpTransportError({
|
||||
detail: cause.message,
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error.message).toBe("ACP transport operation failed.");
|
||||
expect(error.cause).toBe(cause);
|
||||
});
|
||||
|
||||
it("preserves structured extension handler failures behind stable request errors", () => {
|
||||
const cause = new AcpError.AcpTransportError({
|
||||
operation: "read-input-stream",
|
||||
cause: new Error("private transport diagnostics"),
|
||||
});
|
||||
const error = AcpError.AcpRequestError.fromExtensionHandlerError(cause, "x/test");
|
||||
|
||||
expect(error).toMatchObject({
|
||||
code: -32603,
|
||||
method: "x/test",
|
||||
operation: "handle-extension-request",
|
||||
cause,
|
||||
});
|
||||
expect(error.message).toBe("ACP extension request handler failed for method 'x/test'");
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
});
|
||||
|
||||
it.effect("uses the structured mapper for core handler failures", () => {
|
||||
const cause = new AcpError.AcpTransportError({
|
||||
operation: "read-input-stream",
|
||||
cause: new Error("private transport diagnostics"),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* runHandler(() => Effect.fail(cause), {}, "fs/read_text_file").pipe(
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
code: -32603,
|
||||
message: "ACP request handler failed for method 'fs/read_text_file'",
|
||||
});
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("keeps invalid extension payload values only in the exact schema cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const secret = "acp-schema-payload-secret";
|
||||
const cause = yield* decodeNestedNumberPayload({ profile: { token: secret } }).pipe(
|
||||
Effect.flip,
|
||||
);
|
||||
const error = AcpError.AcpRequestError.invalidExtensionPayload("x/private", cause);
|
||||
const { cause: directCause, ...directDiagnostics } = error;
|
||||
|
||||
expect(directCause).toBe(cause);
|
||||
expect(error).toMatchObject({
|
||||
method: "x/private",
|
||||
operation: "decode-extension-request-payload",
|
||||
maximumPathDepth: 2,
|
||||
});
|
||||
expect(error.issueCount).toBeGreaterThan(0);
|
||||
expect(error.issueKinds).toContain("Pointer");
|
||||
expect(error.message).toBe("Invalid payload for ACP extension method 'x/private'.");
|
||||
expect(error.message).not.toContain(secret);
|
||||
expect(encodeUnknownJson(directDiagnostics)).not.toContain(secret);
|
||||
expect(encodeUnknownJson(error.toProtocolError())).not.toContain(secret);
|
||||
|
||||
const protocolError = AcpError.AcpProtocolParseError.fromSchemaError(
|
||||
"decode-notification-payload",
|
||||
"x/private",
|
||||
cause,
|
||||
);
|
||||
const { cause: protocolCause, ...protocolDiagnostics } = protocolError;
|
||||
expect(protocolCause).toBe(cause);
|
||||
expect(protocolError).toMatchObject({
|
||||
method: "x/private",
|
||||
operation: "decode-notification-payload",
|
||||
maximumPathDepth: 2,
|
||||
});
|
||||
expect(protocolError.message).not.toContain(secret);
|
||||
expect(encodeUnknownJson(protocolDiagnostics)).not.toContain(secret);
|
||||
expect("detail" in protocolError).toBe(false);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,7 +1,77 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as SchemaIssue from "effect/SchemaIssue";
|
||||
|
||||
import * as AcpSchema from "./_generated/schema.gen.ts";
|
||||
|
||||
export const AcpRequestOperation = Schema.Literals([
|
||||
"decode-extension-request-payload",
|
||||
"handle-request",
|
||||
"handle-extension-request",
|
||||
]);
|
||||
export type AcpRequestOperation = typeof AcpRequestOperation.Type;
|
||||
|
||||
export const AcpSchemaIssueKind = Schema.Literals([
|
||||
"Filter",
|
||||
"Encoding",
|
||||
"Pointer",
|
||||
"Composite",
|
||||
"AnyOf",
|
||||
"InvalidType",
|
||||
"InvalidValue",
|
||||
"MissingKey",
|
||||
"UnexpectedKey",
|
||||
"Forbidden",
|
||||
"OneOf",
|
||||
]);
|
||||
export type AcpSchemaIssueKind = typeof AcpSchemaIssueKind.Type;
|
||||
|
||||
export interface AcpSchemaIssueDiagnostics {
|
||||
readonly issueCount: number;
|
||||
readonly issueKinds: ReadonlyArray<AcpSchemaIssueKind>;
|
||||
readonly maximumPathDepth: number;
|
||||
}
|
||||
|
||||
const schemaIssueDiagnostics = (root: SchemaIssue.Issue): AcpSchemaIssueDiagnostics => {
|
||||
let issueCount = 0;
|
||||
let maximumPathDepth = 0;
|
||||
const issueKinds = new Set<AcpSchemaIssueKind>();
|
||||
|
||||
const visit = (issue: SchemaIssue.Issue, pathDepth: number): void => {
|
||||
issueCount += 1;
|
||||
issueKinds.add(issue._tag);
|
||||
maximumPathDepth = Math.max(maximumPathDepth, pathDepth);
|
||||
switch (issue._tag) {
|
||||
case "Filter":
|
||||
case "Encoding":
|
||||
visit(issue.issue, pathDepth);
|
||||
break;
|
||||
case "Pointer":
|
||||
visit(issue.issue, pathDepth + issue.path.length);
|
||||
break;
|
||||
case "Composite":
|
||||
case "AnyOf":
|
||||
for (const child of issue.issues) visit(child, pathDepth);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
visit(root, 0);
|
||||
return {
|
||||
issueCount,
|
||||
issueKinds: [...issueKinds],
|
||||
maximumPathDepth,
|
||||
};
|
||||
};
|
||||
|
||||
export interface AcpRequestDiagnostics {
|
||||
readonly method?: string;
|
||||
readonly operation?: AcpRequestOperation;
|
||||
readonly cause?: unknown;
|
||||
readonly issueCount?: number;
|
||||
readonly issueKinds?: ReadonlyArray<AcpSchemaIssueKind>;
|
||||
readonly maximumPathDepth?: number;
|
||||
}
|
||||
|
||||
export class AcpSpawnError extends Schema.TaggedErrorClass<AcpSpawnError>()("AcpSpawnError", {
|
||||
command: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
@@ -27,27 +97,68 @@ export class AcpProcessExitedError extends Schema.TaggedErrorClass<AcpProcessExi
|
||||
}
|
||||
}
|
||||
|
||||
export const AcpProtocolParseOperation = Schema.Literals([
|
||||
"encode-message",
|
||||
"decode-wire-message",
|
||||
"decode-notification-payload",
|
||||
]);
|
||||
export type AcpProtocolParseOperation = typeof AcpProtocolParseOperation.Type;
|
||||
|
||||
export class AcpProtocolParseError extends Schema.TaggedErrorClass<AcpProtocolParseError>()(
|
||||
"AcpProtocolParseError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
operation: AcpProtocolParseOperation,
|
||||
method: Schema.optionalKey(Schema.String),
|
||||
issueCount: Schema.optionalKey(Schema.Number),
|
||||
issueKinds: Schema.optionalKey(Schema.Array(AcpSchemaIssueKind)),
|
||||
maximumPathDepth: Schema.optionalKey(Schema.Number),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Failed to parse ACP protocol message: ${this.detail}`;
|
||||
const method = this.method === undefined ? "" : ` for method '${this.method}'`;
|
||||
return `ACP protocol operation '${this.operation}' failed${method}.`;
|
||||
}
|
||||
|
||||
static fromSchemaError(
|
||||
operation: AcpProtocolParseOperation,
|
||||
method: string,
|
||||
cause: Schema.SchemaError,
|
||||
) {
|
||||
return new AcpProtocolParseError({
|
||||
operation,
|
||||
method,
|
||||
...schemaIssueDiagnostics(cause.issue),
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class AcpTransportError extends Schema.TaggedErrorClass<AcpTransportError>()(
|
||||
"AcpTransportError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
operation: Schema.optional(
|
||||
Schema.Literals(["call-rpc", "read-input-stream", "read-process-exit-status"]),
|
||||
),
|
||||
method: Schema.optional(Schema.String),
|
||||
detail: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return this.detail;
|
||||
const method = this.method ? ` for method ${this.method}` : "";
|
||||
return this.operation
|
||||
? `ACP transport operation ${this.operation} failed${method}.`
|
||||
: "ACP transport operation failed.";
|
||||
}
|
||||
}
|
||||
|
||||
export class AcpInputStreamEndedError extends Schema.TaggedErrorClass<AcpInputStreamEndedError>()(
|
||||
"AcpInputStreamEndedError",
|
||||
{},
|
||||
) {
|
||||
override get message() {
|
||||
return "ACP input stream ended.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +166,12 @@ export class AcpRequestError extends Schema.TaggedErrorClass<AcpRequestError>()(
|
||||
code: AcpSchema.ErrorCode,
|
||||
errorMessage: Schema.String,
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
method: Schema.optionalKey(Schema.String),
|
||||
operation: Schema.optionalKey(AcpRequestOperation),
|
||||
issueCount: Schema.optionalKey(Schema.Number),
|
||||
issueKinds: Schema.optionalKey(Schema.Array(AcpSchemaIssueKind)),
|
||||
maximumPathDepth: Schema.optionalKey(Schema.Number),
|
||||
cause: Schema.optionalKey(Schema.Defect()),
|
||||
}) {
|
||||
override get message() {
|
||||
return this.errorMessage;
|
||||
@@ -68,6 +185,36 @@ export class AcpRequestError extends Schema.TaggedErrorClass<AcpRequestError>()(
|
||||
});
|
||||
}
|
||||
|
||||
static fromCoreHandlerError(error: AcpError, method: string) {
|
||||
if (error._tag === "AcpRequestError") {
|
||||
return error;
|
||||
}
|
||||
return AcpRequestError.internalError(
|
||||
`ACP request handler failed for method '${method}'`,
|
||||
undefined,
|
||||
{
|
||||
method,
|
||||
operation: "handle-request",
|
||||
cause: error,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
static fromExtensionHandlerError(error: AcpError, method: string) {
|
||||
if (error._tag === "AcpRequestError") {
|
||||
return error;
|
||||
}
|
||||
return AcpRequestError.internalError(
|
||||
`ACP extension request handler failed for method '${method}'`,
|
||||
undefined,
|
||||
{
|
||||
method,
|
||||
operation: "handle-extension-request",
|
||||
cause: error,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
static parseError(message = "Parse error", data?: unknown) {
|
||||
return new AcpRequestError({
|
||||
code: -32700,
|
||||
@@ -99,11 +246,29 @@ export class AcpRequestError extends Schema.TaggedErrorClass<AcpRequestError>()(
|
||||
});
|
||||
}
|
||||
|
||||
static internalError(message = "Internal error", data?: unknown) {
|
||||
static invalidExtensionPayload(method: string, cause: Schema.SchemaError) {
|
||||
const diagnostics = schemaIssueDiagnostics(cause.issue);
|
||||
return new AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: `Invalid payload for ACP extension method '${method}'.`,
|
||||
data: diagnostics,
|
||||
method,
|
||||
operation: "decode-extension-request-payload",
|
||||
...diagnostics,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
static internalError(
|
||||
message = "Internal error",
|
||||
data?: unknown,
|
||||
diagnostics: AcpRequestDiagnostics = {},
|
||||
) {
|
||||
return new AcpRequestError({
|
||||
code: -32603,
|
||||
errorMessage: message,
|
||||
...(data !== undefined ? { data } : {}),
|
||||
...diagnostics,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -138,6 +303,7 @@ export const AcpError = Schema.Union([
|
||||
AcpProcessExitedError,
|
||||
AcpProtocolParseError,
|
||||
AcpTransportError,
|
||||
AcpInputStreamEndedError,
|
||||
]);
|
||||
|
||||
export type AcpError = typeof AcpError.Type;
|
||||
@@ -48,6 +48,8 @@ const decodeExtRequest = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
|
||||
const decodeRequestPermissionResponse = Schema.decodeEffect(
|
||||
Schema.fromJsonString(RequestPermissionResponse),
|
||||
);
|
||||
const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
|
||||
const encoder = new TextEncoder();
|
||||
const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
|
||||
path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
|
||||
);
|
||||
@@ -132,6 +134,49 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps invalid core notification values only in the schema cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const secret = "acp-core-notification-secret-sentinel";
|
||||
const { stdio, input } = yield* makeInMemoryStdio();
|
||||
const termination = yield* Deferred.make<AcpError.AcpError>();
|
||||
yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio,
|
||||
serverRequestMethods: new Set(),
|
||||
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
|
||||
});
|
||||
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
encoder.encode(
|
||||
`${encodeUnknownJsonString({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: { secret },
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [],
|
||||
},
|
||||
},
|
||||
})}\n`,
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* Deferred.await(termination);
|
||||
assert.instanceOf(error, AcpError.AcpProtocolParseError);
|
||||
const parseError = error as AcpError.AcpProtocolParseError;
|
||||
const { cause, ...directDiagnostics } = parseError;
|
||||
assert.equal(parseError.operation, "decode-notification-payload");
|
||||
assert.equal(parseError.method, "session/update");
|
||||
assert.isAbove(parseError.issueCount ?? 0, 0);
|
||||
assert.include(parseError.issueKinds ?? [], "Pointer");
|
||||
assert.isAbove(parseError.maximumPathDepth ?? 0, 0);
|
||||
assert.isTrue(Schema.isSchemaError(cause));
|
||||
assert.notInclude(parseError.message, secret);
|
||||
assert.notInclude(encodeUnknownJsonString(directDiagnostics), secret);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio } = yield* makeInMemoryStdio();
|
||||
@@ -172,6 +217,38 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs decode failures without copying the cause or wire payload", () =>
|
||||
Effect.gen(function* () {
|
||||
const secret = "acp-wire-secret-sentinel";
|
||||
const { stdio, input } = yield* makeInMemoryStdio();
|
||||
const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
|
||||
const termination = yield* Deferred.make<AcpError.AcpError>();
|
||||
yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio,
|
||||
serverRequestMethods: new Set(),
|
||||
logIncoming: true,
|
||||
logger: (event) =>
|
||||
Effect.sync(() => {
|
||||
events.push(event);
|
||||
}),
|
||||
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
|
||||
});
|
||||
|
||||
yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
|
||||
yield* Deferred.await(termination);
|
||||
|
||||
const event = events.find(({ stage }) => stage === "decode_failed");
|
||||
assert.deepEqual(event, {
|
||||
direction: "incoming",
|
||||
stage: "decode_failed",
|
||||
payload: {
|
||||
operation: "decode-wire-message",
|
||||
},
|
||||
});
|
||||
assert.notInclude(encodeUnknownJsonString(event), secret);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails notification encoding through the declared ACP error channel", () =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio } = yield* makeInMemoryStdio();
|
||||
@@ -182,13 +259,16 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
|
||||
const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
|
||||
assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
|
||||
assert.equal(bigintError.detail, "Failed to encode ACP message");
|
||||
assert.equal(bigintError.operation, "encode-message");
|
||||
assert.instanceOf(bigintError.cause, TypeError);
|
||||
assert.equal(bigintError.message, "ACP protocol operation 'encode-message' failed.");
|
||||
|
||||
const circular: Record<string, unknown> = {};
|
||||
circular.self = circular;
|
||||
const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
|
||||
assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
|
||||
assert.equal(circularError.detail, "Failed to encode ACP message");
|
||||
assert.equal(circularError.operation, "encode-message");
|
||||
assert.instanceOf(circularError.cause, TypeError);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -381,14 +461,35 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
|
||||
const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
|
||||
readonly _tag: string;
|
||||
readonly message: string;
|
||||
readonly cause: unknown;
|
||||
};
|
||||
assert.equal(defect._tag, "RpcClientDefect");
|
||||
assert.equal(defect.message, "ACP protocol terminated.");
|
||||
assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
|
||||
assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("classifies an input stream ending without inventing a cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio, input } = yield* makeInMemoryStdio();
|
||||
const termination = yield* Deferred.make<AcpError.AcpError>();
|
||||
yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio,
|
||||
serverRequestMethods: new Set(),
|
||||
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
|
||||
});
|
||||
|
||||
yield* Queue.end(input);
|
||||
|
||||
const error = yield* Deferred.await(termination);
|
||||
assert.instanceOf(error, AcpError.AcpInputStreamEndedError);
|
||||
assert.equal(error.message, "ACP input stream ended.");
|
||||
assert.equal("cause" in error, false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not emit a second process-exit error after a decode failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const handle = yield* makeHandle({
|
||||
@@ -413,9 +514,40 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
|
||||
const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
|
||||
readonly _tag: string;
|
||||
readonly message: string;
|
||||
readonly cause: unknown;
|
||||
};
|
||||
assert.equal(defect._tag, "RpcClientDefect");
|
||||
assert.equal(defect.message, "ACP protocol terminated.");
|
||||
assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps client send failure messages independent from the cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio } = yield* makeInMemoryStdio();
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio,
|
||||
serverRequestMethods: new Set(),
|
||||
});
|
||||
|
||||
const failure = yield* transport.clientProtocol
|
||||
.send(0, {
|
||||
_tag: "Request",
|
||||
id: "request-1",
|
||||
tag: "x/test",
|
||||
payload: 1n,
|
||||
headers: [],
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
const defect = failure.reason as {
|
||||
readonly _tag: string;
|
||||
readonly message: string;
|
||||
readonly cause: unknown;
|
||||
};
|
||||
|
||||
assert.equal(defect._tag, "RpcClientDefect");
|
||||
assert.equal(defect.message, "Failed to send ACP protocol message.");
|
||||
assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -17,7 +17,6 @@ import * as AcpSchema from "./_generated/schema.gen.ts";
|
||||
import { CLIENT_METHODS } from "./_generated/meta.gen.ts";
|
||||
import * as AcpError from "./errors.ts";
|
||||
const isAcpError = Schema.is(AcpError.AcpError);
|
||||
const isAcpRequestError = Schema.is(AcpError.AcpRequestError);
|
||||
|
||||
export interface AcpProtocolLogEvent {
|
||||
readonly direction: "incoming" | "outgoing";
|
||||
@@ -114,7 +113,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
try: () => parser.encode(message),
|
||||
catch: (cause) =>
|
||||
new AcpError.AcpProtocolParseError({
|
||||
detail: "Failed to encode ACP message",
|
||||
operation: "encode-message",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
@@ -184,7 +183,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
_tag: "ClientProtocolError",
|
||||
error: new RpcClientError.RpcClientError({
|
||||
reason: new RpcClientError.RpcClientDefect({
|
||||
message: error.message,
|
||||
message: "ACP protocol terminated.",
|
||||
cause: error,
|
||||
}),
|
||||
}),
|
||||
@@ -243,7 +242,11 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
}
|
||||
return options.onExtRequest(message.tag, message.payload).pipe(
|
||||
Effect.matchEffect({
|
||||
onFailure: (error) => respondWithError(message.id, normalizeToRequestError(error)),
|
||||
onFailure: (error) =>
|
||||
respondWithError(
|
||||
message.id,
|
||||
AcpError.AcpRequestError.fromExtensionHandlerError(error, message.tag),
|
||||
),
|
||||
onSuccess: (value) => respondWithSuccess(message.id, value),
|
||||
}),
|
||||
);
|
||||
@@ -261,12 +264,12 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
params,
|
||||
}) satisfies AcpIncomingNotification,
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AcpError.AcpProtocolParseError({
|
||||
detail: `Invalid ${CLIENT_METHODS.session_update} notification payload`,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
AcpError.AcpProtocolParseError.fromSchemaError(
|
||||
"decode-notification-payload",
|
||||
CLIENT_METHODS.session_update,
|
||||
cause,
|
||||
),
|
||||
),
|
||||
Effect.flatMap(dispatchNotification),
|
||||
);
|
||||
@@ -281,12 +284,12 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
params,
|
||||
}) satisfies AcpIncomingNotification,
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AcpError.AcpProtocolParseError({
|
||||
detail: `Invalid ${CLIENT_METHODS.session_elicitation_complete} notification payload`,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
AcpError.AcpProtocolParseError.fromSchemaError(
|
||||
"decode-notification-payload",
|
||||
CLIENT_METHODS.session_elicitation_complete,
|
||||
cause,
|
||||
),
|
||||
),
|
||||
Effect.flatMap(dispatchNotification),
|
||||
);
|
||||
@@ -379,7 +382,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
>,
|
||||
catch: (cause) =>
|
||||
new AcpError.AcpProtocolParseError({
|
||||
detail: "Failed to decode ACP wire message",
|
||||
operation: "decode-wire-message",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
@@ -396,8 +399,13 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
direction: "incoming",
|
||||
stage: "decode_failed",
|
||||
payload: {
|
||||
detail: error.detail,
|
||||
cause: error.cause,
|
||||
operation: error.operation,
|
||||
...(error.method === undefined ? {} : { method: error.method }),
|
||||
...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),
|
||||
...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),
|
||||
...(error.maximumPathDepth === undefined
|
||||
? {}
|
||||
: { maximumPathDepth: error.maximumPathDepth }),
|
||||
},
|
||||
}),
|
||||
),
|
||||
@@ -413,7 +421,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
const normalized: AcpError.AcpError = isAcpError(error)
|
||||
? error
|
||||
: new AcpError.AcpTransportError({
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
operation: "read-input-stream",
|
||||
cause: error,
|
||||
});
|
||||
return handleTermination(() => Effect.succeed(normalized));
|
||||
@@ -421,13 +429,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
onSuccess: () =>
|
||||
handleTermination(
|
||||
() =>
|
||||
options.terminationError ??
|
||||
Effect.succeed(
|
||||
new AcpError.AcpTransportError({
|
||||
detail: "ACP input stream ended",
|
||||
cause: new Error("ACP input stream ended"),
|
||||
}),
|
||||
),
|
||||
options.terminationError ?? Effect.succeed(new AcpError.AcpInputStreamEndedError({})),
|
||||
),
|
||||
}),
|
||||
Effect.forkScoped,
|
||||
@@ -441,7 +443,18 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
Stream.runForEach((message) => f(message)),
|
||||
Effect.forever,
|
||||
),
|
||||
send: (_clientId, request) => offerOutgoing(request).pipe(Effect.mapError(toRpcClientError)),
|
||||
send: (_clientId, request) =>
|
||||
offerOutgoing(request).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new RpcClientError.RpcClientError({
|
||||
reason: new RpcClientError.RpcClientDefect({
|
||||
message: "Failed to send ACP protocol message.",
|
||||
cause: error,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
supportsAck: true,
|
||||
supportsTransferables: false,
|
||||
});
|
||||
@@ -521,16 +534,3 @@ function isProtocolError(
|
||||
typeof value.message === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeToRequestError(error: AcpError.AcpError): AcpError.AcpRequestError {
|
||||
return isAcpRequestError(error) ? error : AcpError.AcpRequestError.internalError(error.message);
|
||||
}
|
||||
|
||||
function toRpcClientError(error: AcpError.AcpError): RpcClientError.RpcClientError {
|
||||
return new RpcClientError.RpcClientError({
|
||||
reason: new RpcClientError.RpcClientDefect({
|
||||
message: error.message,
|
||||
cause: error,
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -23,23 +23,3 @@ export interface AcpTerminal {
|
||||
*/
|
||||
readonly release: Effect.Effect<AcpSchema.ReleaseTerminalResponse, AcpError.AcpError>;
|
||||
}
|
||||
|
||||
export interface MakeTerminalOptions {
|
||||
readonly sessionId: string;
|
||||
readonly terminalId: string;
|
||||
readonly output: Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>;
|
||||
readonly waitForExit: Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>;
|
||||
readonly kill: Effect.Effect<AcpSchema.KillTerminalResponse, AcpError.AcpError>;
|
||||
readonly release: Effect.Effect<AcpSchema.ReleaseTerminalResponse, AcpError.AcpError>;
|
||||
}
|
||||
|
||||
export function makeTerminal(options: MakeTerminalOptions): AcpTerminal {
|
||||
return {
|
||||
sessionId: options.sessionId,
|
||||
terminalId: options.terminalId,
|
||||
output: options.output,
|
||||
waitForExit: options.waitForExit,
|
||||
kill: options.kill,
|
||||
release: options.release,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user