Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96f192e97a | ||
|
|
2418121e05 | ||
|
|
bf555bd9fa | ||
|
|
5b77097027 |
No files matched your search
@@ -1,9 +1,11 @@
|
|||||||
import { describe, expect, it } from "@effect/vitest";
|
import { describe, expect, it } from "@effect/vitest";
|
||||||
import { vi } from "vite-plus/test";
|
import { vi } from "vite-plus/test";
|
||||||
|
import * as Cause from "effect/Cause";
|
||||||
import * as Deferred from "effect/Deferred";
|
import * as Deferred from "effect/Deferred";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
import * as Fiber from "effect/Fiber";
|
import * as Fiber from "effect/Fiber";
|
||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
|
import * as Logger from "effect/Logger";
|
||||||
import * as Option from "effect/Option";
|
import * as Option from "effect/Option";
|
||||||
import * as PlatformError from "effect/PlatformError";
|
import * as PlatformError from "effect/PlatformError";
|
||||||
import * as Sink from "effect/Sink";
|
import * as Sink from "effect/Sink";
|
||||||
@@ -31,23 +33,26 @@ const relayClientAvailableLayer = Layer.succeed(
|
|||||||
const runtimeDependencies = (
|
const runtimeDependencies = (
|
||||||
spawner: ReturnType<typeof ChildProcessSpawner.make>,
|
spawner: ReturnType<typeof ChildProcessSpawner.make>,
|
||||||
relayClientLayer = relayClientAvailableLayer,
|
relayClientLayer = relayClientAvailableLayer,
|
||||||
|
getSecret: ServerSecretStore.ServerSecretStore["Service"]["get"] = () =>
|
||||||
|
Effect.succeed(Option.none()),
|
||||||
) =>
|
) =>
|
||||||
Layer.mergeAll(
|
Layer.mergeAll(
|
||||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||||
relayClientLayer,
|
relayClientLayer,
|
||||||
Layer.mock(ServerSecretStore.ServerSecretStore)({
|
Layer.mock(ServerSecretStore.ServerSecretStore)({
|
||||||
get: () => Effect.succeed(Option.none()),
|
get: getSecret,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
const buildCloudManagedEndpointRuntime = (
|
const buildCloudManagedEndpointRuntime = (
|
||||||
spawner: ReturnType<typeof ChildProcessSpawner.make>,
|
spawner: ReturnType<typeof ChildProcessSpawner.make>,
|
||||||
relayClientLayer = relayClientAvailableLayer,
|
relayClientLayer = relayClientAvailableLayer,
|
||||||
|
getSecret?: ServerSecretStore.ServerSecretStore["Service"]["get"],
|
||||||
) =>
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const context = yield* Layer.build(
|
const context = yield* Layer.build(
|
||||||
ManagedEndpointRuntime.layer.pipe(
|
ManagedEndpointRuntime.layer.pipe(
|
||||||
Layer.provide(runtimeDependencies(spawner, relayClientLayer)),
|
Layer.provide(runtimeDependencies(spawner, relayClientLayer, getSecret)),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
return yield* Effect.service(ManagedEndpointRuntime.CloudManagedEndpointRuntime).pipe(
|
return yield* Effect.service(ManagedEndpointRuntime.CloudManagedEndpointRuntime).pipe(
|
||||||
@@ -59,12 +64,15 @@ function makeHandle(input: {
|
|||||||
readonly pid: number;
|
readonly pid: number;
|
||||||
readonly onKill: () => void;
|
readonly onKill: () => void;
|
||||||
readonly isRunning?: () => boolean;
|
readonly isRunning?: () => boolean;
|
||||||
|
readonly isRunningEffect?: ChildProcessSpawner.ChildProcessHandle["isRunning"];
|
||||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||||
|
readonly output?: string;
|
||||||
|
readonly all?: ChildProcessSpawner.ChildProcessHandle["all"];
|
||||||
}) {
|
}) {
|
||||||
return ChildProcessSpawner.makeHandle({
|
return ChildProcessSpawner.makeHandle({
|
||||||
pid: ChildProcessSpawner.ProcessId(input.pid),
|
pid: ChildProcessSpawner.ProcessId(input.pid),
|
||||||
exitCode: input.exitCode ?? Effect.never,
|
exitCode: input.exitCode ?? Effect.never,
|
||||||
isRunning: Effect.sync(() => input.isRunning?.() ?? true),
|
isRunning: input.isRunningEffect ?? Effect.sync(() => input.isRunning?.() ?? true),
|
||||||
kill: () =>
|
kill: () =>
|
||||||
Effect.sync(() => {
|
Effect.sync(() => {
|
||||||
input.onKill();
|
input.onKill();
|
||||||
@@ -73,7 +81,11 @@ function makeHandle(input: {
|
|||||||
stdin: Sink.drain,
|
stdin: Sink.drain,
|
||||||
stdout: Stream.empty,
|
stdout: Stream.empty,
|
||||||
stderr: Stream.empty,
|
stderr: Stream.empty,
|
||||||
all: Stream.empty,
|
all:
|
||||||
|
input.all ??
|
||||||
|
(input.output === undefined
|
||||||
|
? Stream.empty
|
||||||
|
: Stream.make(new TextEncoder().encode(input.output))),
|
||||||
getInputFd: () => Sink.drain,
|
getInputFd: () => Sink.drain,
|
||||||
getOutputFd: () => Stream.empty,
|
getOutputFd: () => Stream.empty,
|
||||||
});
|
});
|
||||||
@@ -193,18 +205,29 @@ describe("CloudManagedEndpointRuntime", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("restarts the connector when the active process has exited", () =>
|
it.effect("restarts after exit or a failed active-process probe", () => {
|
||||||
Effect.gen(function* () {
|
const logMessages: unknown[] = [];
|
||||||
|
const logger = Logger.make(({ message }) => {
|
||||||
|
logMessages.push(message);
|
||||||
|
});
|
||||||
|
|
||||||
|
return Effect.gen(function* () {
|
||||||
const spawned: Array<number> = [];
|
const spawned: Array<number> = [];
|
||||||
const killed: Array<number> = [];
|
const killed: Array<number> = [];
|
||||||
let firstRunning = true;
|
const probeCause = PlatformError.systemError({
|
||||||
|
_tag: "PermissionDenied",
|
||||||
|
module: "ChildProcess",
|
||||||
|
method: "isRunning",
|
||||||
|
description: "process state is unavailable",
|
||||||
|
});
|
||||||
|
let activeProbe: ChildProcessSpawner.ChildProcessHandle["isRunning"] = Effect.succeed(true);
|
||||||
const spawner = ChildProcessSpawner.make(() =>
|
const spawner = ChildProcessSpawner.make(() =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const pid = spawned.length === 0 ? 300 : 301;
|
const pid = 300 + spawned.length;
|
||||||
spawned.push(pid);
|
spawned.push(pid);
|
||||||
const handle = makeHandle({
|
const handle = makeHandle({
|
||||||
pid,
|
pid,
|
||||||
isRunning: () => (pid === 300 ? firstRunning : true),
|
isRunningEffect: Effect.suspend(() => activeProbe),
|
||||||
onKill: () => {
|
onKill: () => {
|
||||||
killed.push(pid);
|
killed.push(pid);
|
||||||
},
|
},
|
||||||
@@ -221,15 +244,130 @@ describe("CloudManagedEndpointRuntime", () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const first = yield* runtime.applyConfig(config);
|
const first = yield* runtime.applyConfig(config);
|
||||||
firstRunning = false;
|
activeProbe = Effect.succeed(false);
|
||||||
const second = yield* runtime.applyConfig(config);
|
const second = yield* runtime.applyConfig(config);
|
||||||
|
activeProbe = Effect.fail(probeCause);
|
||||||
|
const third = yield* runtime.applyConfig(config);
|
||||||
|
|
||||||
expect(first).toMatchObject({ status: "running", pid: 300 });
|
expect(first).toMatchObject({ status: "running", pid: 300 });
|
||||||
expect(second).toMatchObject({ status: "running", pid: 301 });
|
expect(second).toMatchObject({ status: "running", pid: 301 });
|
||||||
expect(spawned).toEqual([300, 301]);
|
expect(third).toMatchObject({ status: "running", pid: 302 });
|
||||||
expect(killed).toEqual([300]);
|
expect(spawned).toEqual([300, 301, 302]);
|
||||||
}),
|
expect(killed).toEqual([300, 301]);
|
||||||
);
|
|
||||||
|
const warning = logMessages.find(
|
||||||
|
(message) =>
|
||||||
|
Array.isArray(message) && message[0] === "Failed to inspect relay client process",
|
||||||
|
);
|
||||||
|
expect(warning).toBeDefined();
|
||||||
|
if (!Array.isArray(warning)) return;
|
||||||
|
expect(warning[1]).toMatchObject({
|
||||||
|
errorTag: "PlatformError",
|
||||||
|
reasonTag: "PermissionDenied",
|
||||||
|
errorModule: "ChildProcess",
|
||||||
|
errorMethod: "isRunning",
|
||||||
|
pid: 301,
|
||||||
|
tunnelId: "tunnel-1",
|
||||||
|
});
|
||||||
|
expect(warning[1]).not.toHaveProperty("cause");
|
||||||
|
expect(warning[1]).not.toHaveProperty("description");
|
||||||
|
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
|
||||||
|
});
|
||||||
|
|
||||||
|
it.effect("does not report connector scope interruption as a runtime failure", () => {
|
||||||
|
const logMessages: unknown[] = [];
|
||||||
|
const logger = Logger.make(({ message }) => {
|
||||||
|
logMessages.push(message);
|
||||||
|
});
|
||||||
|
const spawner = ChildProcessSpawner.make(() =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const handle = makeHandle({
|
||||||
|
pid: 325,
|
||||||
|
all: Stream.never,
|
||||||
|
onKill: () => undefined,
|
||||||
|
});
|
||||||
|
yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
|
||||||
|
return handle;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
|
||||||
|
yield* runtime.applyConfig({
|
||||||
|
providerKind: "cloudflare_tunnel",
|
||||||
|
connectorToken: "token",
|
||||||
|
tunnelId: "tunnel-1",
|
||||||
|
});
|
||||||
|
yield* runtime.applyConfig(null);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
logMessages.some(
|
||||||
|
(message) =>
|
||||||
|
Array.isArray(message) &&
|
||||||
|
(message[0] === "Relay client supervisor failed" ||
|
||||||
|
message[0] === "Relay client output observer failed"),
|
||||||
|
),
|
||||||
|
).toBe(false);
|
||||||
|
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
|
||||||
|
});
|
||||||
|
|
||||||
|
it.effect("does not copy relay client output into log annotations", () => {
|
||||||
|
const connectorToken = "connector-token-sentinel";
|
||||||
|
const signedUrl = "https://user:[email protected]/private?token=secret#fragment";
|
||||||
|
const output = `ERR failed request ${signedUrl} ${connectorToken}`;
|
||||||
|
const logMessages: unknown[] = [];
|
||||||
|
let resolveObserved!: () => void;
|
||||||
|
const observed = new Promise<void>((resolve) => {
|
||||||
|
resolveObserved = resolve;
|
||||||
|
});
|
||||||
|
const logger = Logger.make(({ message }) => {
|
||||||
|
logMessages.push(message);
|
||||||
|
if (Array.isArray(message) && message[0] === "Relay client reported a transport warning") {
|
||||||
|
resolveObserved();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const spawner = ChildProcessSpawner.make(() =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const handle = makeHandle({
|
||||||
|
pid: 350,
|
||||||
|
output,
|
||||||
|
onKill: () => undefined,
|
||||||
|
});
|
||||||
|
yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
|
||||||
|
return handle;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
|
||||||
|
yield* runtime.applyConfig({
|
||||||
|
providerKind: "cloudflare_tunnel",
|
||||||
|
connectorToken,
|
||||||
|
tunnelId: "tunnel-1",
|
||||||
|
});
|
||||||
|
yield* Effect.promise(() => observed);
|
||||||
|
|
||||||
|
const warning = logMessages.find(
|
||||||
|
(message) =>
|
||||||
|
Array.isArray(message) && message[0] === "Relay client reported a transport warning",
|
||||||
|
);
|
||||||
|
expect(warning).toBeDefined();
|
||||||
|
if (!Array.isArray(warning)) return;
|
||||||
|
expect(warning[1]).toMatchObject({
|
||||||
|
pid: 350,
|
||||||
|
tunnelId: "tunnel-1",
|
||||||
|
outputLength: output.length,
|
||||||
|
});
|
||||||
|
expect(warning[1]).not.toHaveProperty("output");
|
||||||
|
const diagnosticText = Object.values(warning[1] as Record<string, unknown>)
|
||||||
|
.map(String)
|
||||||
|
.join("\n");
|
||||||
|
expect(diagnosticText).not.toContain(connectorToken);
|
||||||
|
expect(diagnosticText).not.toContain(signedUrl);
|
||||||
|
expect(diagnosticText).not.toContain("user:password");
|
||||||
|
expect(diagnosticText).not.toContain("token=secret");
|
||||||
|
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
|
||||||
|
});
|
||||||
|
|
||||||
it.effect("supervises the active connector and restarts it after process exit", () =>
|
it.effect("supervises the active connector and restarts it after process exit", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
@@ -324,18 +462,21 @@ describe("CloudManagedEndpointRuntime", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("reports connector spawn failures", () =>
|
it.effect("reports connector spawn failures without logging nested details", () => {
|
||||||
Effect.gen(function* () {
|
const logMessages: unknown[] = [];
|
||||||
const spawner = ChildProcessSpawner.make(() =>
|
const logger = Logger.make(({ message }) => {
|
||||||
Effect.fail(
|
logMessages.push(message);
|
||||||
PlatformError.systemError({
|
});
|
||||||
_tag: "NotFound",
|
const spawnCause = PlatformError.systemError({
|
||||||
module: "ChildProcess",
|
_tag: "NotFound",
|
||||||
method: "spawn",
|
module: "ChildProcess",
|
||||||
description: "cloudflared missing",
|
method: "spawn",
|
||||||
}),
|
description: "private cloudflared path was missing",
|
||||||
),
|
cause: new Error("private nested spawn failure"),
|
||||||
);
|
});
|
||||||
|
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const spawner = ChildProcessSpawner.make(() => Effect.fail(spawnCause));
|
||||||
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
|
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
|
||||||
|
|
||||||
const status = yield* runtime.applyConfig({
|
const status = yield* runtime.applyConfig({
|
||||||
@@ -347,10 +488,98 @@ describe("CloudManagedEndpointRuntime", () => {
|
|||||||
expect(status).toMatchObject({
|
expect(status).toMatchObject({
|
||||||
status: "failed",
|
status: "failed",
|
||||||
providerKind: "cloudflare_tunnel",
|
providerKind: "cloudflare_tunnel",
|
||||||
|
reason: "Failed to start the relay client.",
|
||||||
tunnelId: "tunnel-1",
|
tunnelId: "tunnel-1",
|
||||||
});
|
});
|
||||||
}),
|
const warning = logMessages.find(
|
||||||
);
|
(message) => Array.isArray(message) && message[0] === "Failed to start relay client",
|
||||||
|
);
|
||||||
|
expect(warning).toEqual([
|
||||||
|
"Failed to start relay client",
|
||||||
|
{
|
||||||
|
errorTag: "PlatformError",
|
||||||
|
reasonTag: "NotFound",
|
||||||
|
errorModule: "ChildProcess",
|
||||||
|
errorMethod: "spawn",
|
||||||
|
tunnelId: "tunnel-1",
|
||||||
|
tunnelName: undefined,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(spawnCause.reason.cause).toBeInstanceOf(Error);
|
||||||
|
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
|
||||||
|
});
|
||||||
|
|
||||||
|
it.effect("retains malformed persisted runtime configuration diagnostics", () => {
|
||||||
|
const logMessages: unknown[] = [];
|
||||||
|
const logger = Logger.make(({ message }) => {
|
||||||
|
logMessages.push(message);
|
||||||
|
});
|
||||||
|
const spawn = vi.fn();
|
||||||
|
const spawner = ChildProcessSpawner.make(spawn);
|
||||||
|
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
yield* buildCloudManagedEndpointRuntime(spawner, relayClientAvailableLayer, () =>
|
||||||
|
Effect.succeed(Option.some(new TextEncoder().encode("not-json"))),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(spawn).not.toHaveBeenCalled();
|
||||||
|
const warning = logMessages.find(
|
||||||
|
(message) =>
|
||||||
|
Array.isArray(message) && message[0] === "Failed to read managed endpoint runtime config",
|
||||||
|
);
|
||||||
|
expect(warning).toBeDefined();
|
||||||
|
if (!Array.isArray(warning)) return;
|
||||||
|
expect(warning[1]).toMatchObject({
|
||||||
|
errorTag: "CloudManagedEndpointRuntimeConfigDecodeError",
|
||||||
|
resource: "cloud-endpoint-runtime-config",
|
||||||
|
causeTag: "SchemaError",
|
||||||
|
});
|
||||||
|
expect(warning[1]).not.toHaveProperty("cause");
|
||||||
|
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("retains exact causes on managed endpoint runtime configuration errors", () => {
|
||||||
|
const readCause = new Error("private read failure");
|
||||||
|
const decodeCause = new Error("private decode failure");
|
||||||
|
|
||||||
|
expect(
|
||||||
|
new ManagedEndpointRuntime.CloudManagedEndpointRuntimeConfigReadError({
|
||||||
|
resource: "cloud-endpoint-runtime-config",
|
||||||
|
cause: readCause,
|
||||||
|
}).cause,
|
||||||
|
).toBe(readCause);
|
||||||
|
expect(
|
||||||
|
new ManagedEndpointRuntime.CloudManagedEndpointRuntimeConfigDecodeError({
|
||||||
|
resource: "cloud-endpoint-runtime-config",
|
||||||
|
cause: decodeCause,
|
||||||
|
}).cause,
|
||||||
|
).toBe(decodeCause);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("summarizes managed endpoint causes without nested failure details", () => {
|
||||||
|
const nestedCause = new Error("private nested platform failure");
|
||||||
|
const platformFailure = PlatformError.systemError({
|
||||||
|
_tag: "PermissionDenied",
|
||||||
|
module: "ChildProcess",
|
||||||
|
method: "kill",
|
||||||
|
description: "private process description",
|
||||||
|
cause: nestedCause,
|
||||||
|
});
|
||||||
|
const cause = Cause.combine(
|
||||||
|
Cause.fail(platformFailure),
|
||||||
|
Cause.die(new TypeError("private defect detail")),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(ManagedEndpointRuntime.managedEndpointCauseDiagnostics(cause)).toEqual({
|
||||||
|
reasonCount: 2,
|
||||||
|
failureCount: 1,
|
||||||
|
failureTags: ["PlatformError"],
|
||||||
|
defectCount: 1,
|
||||||
|
defectTags: ["TypeError"],
|
||||||
|
interruptionCount: 0,
|
||||||
|
});
|
||||||
|
expect(platformFailure.reason.cause).toBe(nestedCause);
|
||||||
|
});
|
||||||
|
|
||||||
it.effect("reports a missing relay client executable without spawning", () =>
|
it.effect("reports a missing relay client executable without spawning", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
|
import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
|
||||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||||
|
import * as Cause from "effect/Cause";
|
||||||
import * as Context from "effect/Context";
|
import * as Context from "effect/Context";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
import * as Exit from "effect/Exit";
|
import * as Exit from "effect/Exit";
|
||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
import * as Option from "effect/Option";
|
import * as Option from "effect/Option";
|
||||||
|
import * as PlatformError from "effect/PlatformError";
|
||||||
import * as Ref from "effect/Ref";
|
import * as Ref from "effect/Ref";
|
||||||
import * as Result from "effect/Result";
|
import * as Result from "effect/Result";
|
||||||
|
import * as Schema from "effect/Schema";
|
||||||
import * as Semaphore from "effect/Semaphore";
|
import * as Semaphore from "effect/Semaphore";
|
||||||
import * as Scope from "effect/Scope";
|
import * as Scope from "effect/Scope";
|
||||||
import * as Stream from "effect/Stream";
|
import * as Stream from "effect/Stream";
|
||||||
@@ -16,17 +19,150 @@ import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawne
|
|||||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||||
import { CLOUD_ENDPOINT_RUNTIME_CONFIG, decodeRuntimeConfig } from "./config.ts";
|
import { CLOUD_ENDPOINT_RUNTIME_CONFIG, decodeRuntimeConfig } from "./config.ts";
|
||||||
|
|
||||||
|
const MAX_CAUSE_DIAGNOSTIC_TAGS = 8;
|
||||||
|
const MAX_DIAGNOSTIC_VALUE_LENGTH = 128;
|
||||||
|
|
||||||
|
function boundedDiagnosticValue(value: string): string {
|
||||||
|
return value.slice(0, MAX_DIAGNOSTIC_VALUE_LENGTH);
|
||||||
|
}
|
||||||
|
|
||||||
|
function diagnosticValueTag(value: unknown): string {
|
||||||
|
try {
|
||||||
|
if (
|
||||||
|
typeof value === "object" &&
|
||||||
|
value !== null &&
|
||||||
|
"_tag" in value &&
|
||||||
|
typeof value._tag === "string"
|
||||||
|
) {
|
||||||
|
return boundedDiagnosticValue(value._tag);
|
||||||
|
}
|
||||||
|
if (value instanceof Error) {
|
||||||
|
return boundedDiagnosticValue(value.name);
|
||||||
|
}
|
||||||
|
return typeof value;
|
||||||
|
} catch {
|
||||||
|
return "Uninspectable";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function addUniqueDiagnosticTag(tags: Array<string>, tag: string): void {
|
||||||
|
if (tags.length < MAX_CAUSE_DIAGNOSTIC_TAGS && !tags.includes(tag)) {
|
||||||
|
tags.push(tag);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function managedEndpointCauseDiagnostics(cause: Cause.Cause<unknown>) {
|
||||||
|
const failureTags: Array<string> = [];
|
||||||
|
const defectTags: Array<string> = [];
|
||||||
|
let failureCount = 0;
|
||||||
|
let defectCount = 0;
|
||||||
|
let interruptionCount = 0;
|
||||||
|
|
||||||
|
for (const reason of cause.reasons) {
|
||||||
|
if (Cause.isFailReason(reason)) {
|
||||||
|
failureCount += 1;
|
||||||
|
addUniqueDiagnosticTag(failureTags, diagnosticValueTag(reason.error));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (Cause.isDieReason(reason)) {
|
||||||
|
defectCount += 1;
|
||||||
|
addUniqueDiagnosticTag(defectTags, diagnosticValueTag(reason.defect));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
interruptionCount += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
reasonCount: cause.reasons.length,
|
||||||
|
failureCount,
|
||||||
|
failureTags,
|
||||||
|
defectCount,
|
||||||
|
defectTags,
|
||||||
|
interruptionCount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function logManagedEndpointCause(
|
||||||
|
message: string,
|
||||||
|
cause: Cause.Cause<unknown>,
|
||||||
|
attributes: Readonly<Record<string, unknown>>,
|
||||||
|
) {
|
||||||
|
const interruptionReasons = cause.reasons.filter(Cause.isInterruptReason);
|
||||||
|
if (interruptionReasons.length > 0 && interruptionReasons.length === cause.reasons.length) {
|
||||||
|
return Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
|
||||||
|
}
|
||||||
|
const log = Effect.logWarning(message, {
|
||||||
|
...attributes,
|
||||||
|
...managedEndpointCauseDiagnostics(cause),
|
||||||
|
});
|
||||||
|
if (interruptionReasons.length > 0) {
|
||||||
|
return log.pipe(
|
||||||
|
Effect.andThen(Effect.failCause(Cause.fromReasons<never>(interruptionReasons))),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return log;
|
||||||
|
}
|
||||||
|
|
||||||
|
function platformErrorDiagnostics(error: PlatformError.PlatformError) {
|
||||||
|
return {
|
||||||
|
errorTag: error._tag,
|
||||||
|
reasonTag: error.reason._tag,
|
||||||
|
errorModule: boundedDiagnosticValue(error.reason.module),
|
||||||
|
errorMethod: boundedDiagnosticValue(error.reason.method),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CloudManagedEndpointRuntimeConfigReadError extends Schema.TaggedErrorClass<CloudManagedEndpointRuntimeConfigReadError>()(
|
||||||
|
"CloudManagedEndpointRuntimeConfigReadError",
|
||||||
|
{
|
||||||
|
resource: Schema.Literal(CLOUD_ENDPOINT_RUNTIME_CONFIG),
|
||||||
|
cause: Schema.Defect(),
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
override get message(): string {
|
||||||
|
return `Failed to read managed endpoint runtime configuration from ${this.resource}.`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CloudManagedEndpointRuntimeConfigDecodeError extends Schema.TaggedErrorClass<CloudManagedEndpointRuntimeConfigDecodeError>()(
|
||||||
|
"CloudManagedEndpointRuntimeConfigDecodeError",
|
||||||
|
{
|
||||||
|
resource: Schema.Literal(CLOUD_ENDPOINT_RUNTIME_CONFIG),
|
||||||
|
cause: Schema.Defect(),
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
override get message(): string {
|
||||||
|
return `Failed to decode managed endpoint runtime configuration from ${this.resource}.`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function bytesToString(bytes: Uint8Array): string {
|
function bytesToString(bytes: Uint8Array): string {
|
||||||
return new TextDecoder().decode(bytes);
|
return new TextDecoder().decode(bytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
const readRuntimeConfig = Effect.gen(function* () {
|
const readRuntimeConfig = Effect.gen(function* () {
|
||||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||||
const bytes = yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);
|
const bytes = yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG).pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
(cause) =>
|
||||||
|
new CloudManagedEndpointRuntimeConfigReadError({
|
||||||
|
resource: CLOUD_ENDPOINT_RUNTIME_CONFIG,
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
if (Option.isNone(bytes)) {
|
if (Option.isNone(bytes)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return Option.getOrNull(decodeRuntimeConfig(bytesToString(bytes.value)));
|
return yield* decodeRuntimeConfig(bytesToString(bytes.value)).pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
(cause) =>
|
||||||
|
new CloudManagedEndpointRuntimeConfigDecodeError({
|
||||||
|
resource: CLOUD_ENDPOINT_RUNTIME_CONFIG,
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
export type CloudManagedEndpointRuntimeStatus =
|
export type CloudManagedEndpointRuntimeStatus =
|
||||||
@@ -92,7 +228,13 @@ const stopConnector = (connector: ActiveConnector | null) =>
|
|||||||
pid: Number(connector.child.pid),
|
pid: Number(connector.child.pid),
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
Effect.ignore,
|
Effect.catchCause((cause) =>
|
||||||
|
logManagedEndpointCause("Failed to stop relay client", cause, {
|
||||||
|
pid: Number(connector.child.pid),
|
||||||
|
tunnelId: connector.config.tunnelId,
|
||||||
|
tunnelName: connector.config.tunnelName,
|
||||||
|
}),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
: Effect.void;
|
: Effect.void;
|
||||||
|
|
||||||
@@ -137,7 +279,12 @@ export const make = Effect.gen(function* () {
|
|||||||
pid: Number(connector.child.pid),
|
pid: Number(connector.child.pid),
|
||||||
...(Result.isSuccess(result)
|
...(Result.isSuccess(result)
|
||||||
? { exitCode: Number(result.success) }
|
? { exitCode: Number(result.success) }
|
||||||
: { cause: result.failure }),
|
: {
|
||||||
|
exitErrorTag: result.failure._tag,
|
||||||
|
exitReasonTag: result.failure.reason._tag,
|
||||||
|
exitErrorModule: boundedDiagnosticValue(result.failure.reason.module),
|
||||||
|
exitErrorMethod: boundedDiagnosticValue(result.failure.reason.method),
|
||||||
|
}),
|
||||||
tunnelId: connector.config.tunnelId,
|
tunnelId: connector.config.tunnelId,
|
||||||
tunnelName: connector.config.tunnelName,
|
tunnelName: connector.config.tunnelName,
|
||||||
});
|
});
|
||||||
@@ -145,7 +292,9 @@ export const make = Effect.gen(function* () {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),
|
Effect.catchCause((cause) =>
|
||||||
|
logManagedEndpointCause("Relay client supervisor failed", cause, {}),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
const observeConnectorOutput = (connector: ActiveConnector) =>
|
const observeConnectorOutput = (connector: ActiveConnector) =>
|
||||||
@@ -155,12 +304,11 @@ export const make = Effect.gen(function* () {
|
|||||||
Stream.map((line) => line.trim()),
|
Stream.map((line) => line.trim()),
|
||||||
Stream.filter((line) => line.length > 0),
|
Stream.filter((line) => line.length > 0),
|
||||||
Stream.runForEach((line) => {
|
Stream.runForEach((line) => {
|
||||||
const output = line.replaceAll(connector.config.connectorToken, "<redacted>");
|
|
||||||
const attributes = {
|
const attributes = {
|
||||||
pid: Number(connector.child.pid),
|
pid: Number(connector.child.pid),
|
||||||
tunnelId: connector.config.tunnelId,
|
tunnelId: connector.config.tunnelId,
|
||||||
tunnelName: connector.config.tunnelName,
|
tunnelName: connector.config.tunnelName,
|
||||||
output,
|
outputLength: line.length,
|
||||||
};
|
};
|
||||||
switch (classifyRelayClientOutput(line)) {
|
switch (classifyRelayClientOutput(line)) {
|
||||||
case "connected":
|
case "connected":
|
||||||
@@ -172,8 +320,7 @@ export const make = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
Effect.catchCause((cause) =>
|
Effect.catchCause((cause) =>
|
||||||
Effect.logWarning("Relay client output observer failed", {
|
logManagedEndpointCause("Relay client output observer failed", cause, {
|
||||||
cause,
|
|
||||||
pid: Number(connector.child.pid),
|
pid: Number(connector.child.pid),
|
||||||
tunnelId: connector.config.tunnelId,
|
tunnelId: connector.config.tunnelId,
|
||||||
tunnelName: connector.config.tunnelName,
|
tunnelName: connector.config.tunnelName,
|
||||||
@@ -192,7 +339,17 @@ export const make = Effect.gen(function* () {
|
|||||||
const nextConfigKey = runtimeConfigKey(config);
|
const nextConfigKey = runtimeConfigKey(config);
|
||||||
const active = yield* Ref.get(activeRef);
|
const active = yield* Ref.get(activeRef);
|
||||||
if (active?.configKey === nextConfigKey) {
|
if (active?.configKey === nextConfigKey) {
|
||||||
const isRunning = yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false));
|
const isRunning = yield* active.child.isRunning.pipe(
|
||||||
|
Effect.catchTags({
|
||||||
|
PlatformError: (error) =>
|
||||||
|
Effect.logWarning("Failed to inspect relay client process", {
|
||||||
|
...platformErrorDiagnostics(error),
|
||||||
|
pid: Number(active.child.pid),
|
||||||
|
tunnelId: active.config.tunnelId,
|
||||||
|
tunnelName: active.config.tunnelName,
|
||||||
|
}).pipe(Effect.as(false)),
|
||||||
|
}),
|
||||||
|
);
|
||||||
if (isRunning) {
|
if (isRunning) {
|
||||||
return {
|
return {
|
||||||
status: "running",
|
status: "running",
|
||||||
@@ -243,22 +400,23 @@ export const make = Effect.gen(function* () {
|
|||||||
tunnelName: config.tunnelName,
|
tunnelName: config.tunnelName,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
Effect.catch((cause) =>
|
Effect.catchTags({
|
||||||
Effect.logWarning("Failed to start relay client", {
|
PlatformError: (error) =>
|
||||||
cause,
|
Effect.logWarning("Failed to start relay client", {
|
||||||
tunnelId: config.tunnelId,
|
...platformErrorDiagnostics(error),
|
||||||
tunnelName: config.tunnelName,
|
tunnelId: config.tunnelId,
|
||||||
}).pipe(
|
tunnelName: config.tunnelName,
|
||||||
Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)),
|
}).pipe(
|
||||||
Effect.as({
|
Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)),
|
||||||
status: "failed",
|
Effect.as({
|
||||||
providerKind: "cloudflare_tunnel",
|
status: "failed",
|
||||||
reason: String(cause),
|
providerKind: "cloudflare_tunnel",
|
||||||
...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
|
reason: "Failed to start the relay client.",
|
||||||
...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
|
...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
|
||||||
} satisfies CloudManagedEndpointRuntimeStatus),
|
...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
|
||||||
),
|
} satisfies CloudManagedEndpointRuntimeStatus),
|
||||||
),
|
),
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
if ("status" in child && child.status === "failed") {
|
if ("status" in child && child.status === "failed") {
|
||||||
@@ -304,12 +462,21 @@ export const make = Effect.gen(function* () {
|
|||||||
applyConfig,
|
applyConfig,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const recoverRuntimeConfigError = (
|
||||||
|
error:
|
||||||
|
| CloudManagedEndpointRuntimeConfigReadError
|
||||||
|
| CloudManagedEndpointRuntimeConfigDecodeError,
|
||||||
|
) =>
|
||||||
|
Effect.logWarning("Failed to read managed endpoint runtime config", {
|
||||||
|
errorTag: error._tag,
|
||||||
|
resource: error.resource,
|
||||||
|
causeTag: diagnosticValueTag(error.cause),
|
||||||
|
}).pipe(Effect.as(null));
|
||||||
const initialConfig = yield* readRuntimeConfig.pipe(
|
const initialConfig = yield* readRuntimeConfig.pipe(
|
||||||
Effect.catch((cause) =>
|
Effect.catchTags({
|
||||||
Effect.logWarning("Failed to read managed endpoint runtime config", { cause }).pipe(
|
CloudManagedEndpointRuntimeConfigReadError: recoverRuntimeConfigError,
|
||||||
Effect.as(null),
|
CloudManagedEndpointRuntimeConfigDecodeError: recoverRuntimeConfigError,
|
||||||
),
|
}),
|
||||||
),
|
|
||||||
);
|
);
|
||||||
yield* runtime.applyConfig(initialConfig);
|
yield* runtime.applyConfig(initialConfig);
|
||||||
yield* Effect.addFinalizer(() => runtime.applyConfig(null));
|
yield* Effect.addFinalizer(() => runtime.applyConfig(null));
|
||||||
|
|||||||
@@ -13,6 +13,6 @@ export const encodeEndpointRuntimeConfigJson = Schema.encodeEffect(
|
|||||||
Schema.fromJsonString(RelayManagedEndpointRuntimeConfig),
|
Schema.fromJsonString(RelayManagedEndpointRuntimeConfig),
|
||||||
);
|
);
|
||||||
|
|
||||||
export const decodeRuntimeConfig = Schema.decodeUnknownOption(
|
export const decodeRuntimeConfig = Schema.decodeUnknownEffect(
|
||||||
Schema.fromJsonString(RelayManagedEndpointRuntimeConfig),
|
Schema.fromJsonString(RelayManagedEndpointRuntimeConfig),
|
||||||
);
|
);
|
||||||
Reference in new issue
Block a user