Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bed9031f02 |
No files matched your search
@@ -3,6 +3,7 @@ import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
@@ -10,6 +11,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const encodeJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
|
||||
|
||||
function mockHandle(result: {
|
||||
readonly stdout?: string;
|
||||
@@ -193,9 +195,8 @@ describe("ProcessDiagnostics", () => {
|
||||
Effect.gen(function* () {
|
||||
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
|
||||
[];
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
|
||||
spawn: (command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
@@ -209,8 +210,8 @@ describe("ProcessDiagnostics", () => {
|
||||
].join("\n"),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
|
||||
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
@@ -231,13 +232,12 @@ describe("ProcessDiagnostics", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes Windows process rows from schema-backed JSON", () =>
|
||||
it.effect("decodes Windows process rows through Schema JSON parsing", () =>
|
||||
Effect.gen(function* () {
|
||||
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
|
||||
[];
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
|
||||
spawn: (command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
@@ -245,17 +245,26 @@ describe("ProcessDiagnostics", () => {
|
||||
commands.push({ command: childProcess.command, args: childProcess.args });
|
||||
return Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
"[",
|
||||
'{"ProcessId":4242,"ParentProcessId":1,"Name":"node.exe","CommandLine":"node server.js","Status":"Running","WorkingSetSize":2048,"PercentProcessorTime":12.5},',
|
||||
'{"ProcessId":4243,"ParentProcessId":4242,"Name":"fallback.exe","CommandLine":"","Status":"","WorkingSetSize":-5,"PercentProcessorTime":-1},',
|
||||
'{"ProcessId":0,"ParentProcessId":4242,"Name":"ignored.exe"}',
|
||||
"]",
|
||||
].join(""),
|
||||
stdout: encodeJsonString([
|
||||
{
|
||||
ProcessId: 4242,
|
||||
ParentProcessId: 100,
|
||||
Name: "node.exe",
|
||||
CommandLine: "node server.js",
|
||||
Status: "Running",
|
||||
WorkingSetSize: 2048,
|
||||
PercentProcessorTime: 12.5,
|
||||
},
|
||||
{
|
||||
ProcessId: 0,
|
||||
ParentProcessId: 100,
|
||||
Name: "invalid.exe",
|
||||
},
|
||||
]),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const rows = yield* ProcessDiagnostics.readProcessRows("win32").pipe(
|
||||
Effect.provide(spawnerLayer),
|
||||
@@ -264,7 +273,7 @@ describe("ProcessDiagnostics", () => {
|
||||
assert.deepEqual(rows, [
|
||||
{
|
||||
pid: 4242,
|
||||
ppid: 1,
|
||||
ppid: 100,
|
||||
pgid: null,
|
||||
status: "Running",
|
||||
cpuPercent: 12.5,
|
||||
@@ -272,27 +281,15 @@ describe("ProcessDiagnostics", () => {
|
||||
elapsed: "",
|
||||
command: "node server.js",
|
||||
},
|
||||
{
|
||||
pid: 4243,
|
||||
ppid: 4242,
|
||||
pgid: null,
|
||||
status: "Live",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 0,
|
||||
elapsed: "",
|
||||
command: "fallback.exe",
|
||||
},
|
||||
]);
|
||||
assert.equal(commands[0]?.command, "powershell.exe");
|
||||
assert.match(commands[0]?.args.join(" ") ?? "", /Get-CimInstance Win32_Process/);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not allow signaling the diagnostics query process", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
|
||||
spawn: () =>
|
||||
Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
@@ -301,8 +298,7 @@ describe("ProcessDiagnostics", () => {
|
||||
].join("\n"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
|
||||
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
|
||||
@@ -43,35 +43,73 @@ export class ProcessDiagnostics extends Context.Service<
|
||||
ProcessDiagnosticsShape
|
||||
>()("t3/diagnostics/ProcessDiagnostics") {}
|
||||
|
||||
class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnosticsError>()(
|
||||
"ProcessDiagnosticsError",
|
||||
class ProcessQueryError extends Schema.TaggedErrorClass<ProcessQueryError>()("ProcessQueryError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
|
||||
class ProcessQueryTimeoutError extends Schema.TaggedErrorClass<ProcessQueryTimeoutError>()(
|
||||
"ProcessQueryTimeoutError",
|
||||
{
|
||||
message: Schema.String,
|
||||
timeoutMillis: Schema.Number,
|
||||
},
|
||||
) {}
|
||||
|
||||
class ProcessCommandExitError extends Schema.TaggedErrorClass<ProcessCommandExitError>()(
|
||||
"ProcessCommandExitError",
|
||||
{
|
||||
message: Schema.String,
|
||||
command: Schema.String,
|
||||
exitCode: Schema.Number,
|
||||
stderr: Schema.String,
|
||||
},
|
||||
) {}
|
||||
|
||||
class ProcessSignalRejectedError extends Schema.TaggedErrorClass<ProcessSignalRejectedError>()(
|
||||
"ProcessSignalRejectedError",
|
||||
{
|
||||
message: Schema.String,
|
||||
pid: Schema.Number,
|
||||
reason: Schema.String,
|
||||
},
|
||||
) {}
|
||||
|
||||
class ProcessSignalFailedError extends Schema.TaggedErrorClass<ProcessSignalFailedError>()(
|
||||
"ProcessSignalFailedError",
|
||||
{
|
||||
message: Schema.String,
|
||||
pid: Schema.Number,
|
||||
signal: Schema.Literals(["SIGINT", "SIGKILL"]),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
|
||||
|
||||
const WindowsProcessRecordJson = Schema.Struct({
|
||||
ProcessId: Schema.optional(Schema.Number),
|
||||
ParentProcessId: Schema.optional(Schema.Number),
|
||||
Name: Schema.optional(Schema.String),
|
||||
CommandLine: Schema.optional(Schema.String),
|
||||
Status: Schema.optional(Schema.String),
|
||||
WorkingSetSize: Schema.optional(Schema.Number),
|
||||
PercentProcessorTime: Schema.optional(Schema.Number),
|
||||
});
|
||||
type WindowsProcessRecordJson = typeof WindowsProcessRecordJson.Type;
|
||||
const WindowsProcessJson = Schema.Union([
|
||||
WindowsProcessRecordJson,
|
||||
Schema.Array(WindowsProcessRecordJson),
|
||||
]);
|
||||
const decodeWindowsProcessJson = Schema.decodeUnknownOption(
|
||||
Schema.fromJsonString(WindowsProcessJson),
|
||||
);
|
||||
type ProcessDiagnosticsError =
|
||||
| ProcessQueryError
|
||||
| ProcessQueryTimeoutError
|
||||
| ProcessCommandExitError
|
||||
| ProcessSignalRejectedError
|
||||
| ProcessSignalFailedError;
|
||||
|
||||
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
|
||||
return new ProcessDiagnosticsError({
|
||||
const isProcessQueryError = Schema.is(ProcessQueryError);
|
||||
const isProcessQueryTimeoutError = Schema.is(ProcessQueryTimeoutError);
|
||||
const isProcessCommandExitError = Schema.is(ProcessCommandExitError);
|
||||
const isProcessSignalRejectedError = Schema.is(ProcessSignalRejectedError);
|
||||
const isProcessSignalFailedError = Schema.is(ProcessSignalFailedError);
|
||||
|
||||
function isProcessDiagnosticsError(error: unknown): error is ProcessDiagnosticsError {
|
||||
return (
|
||||
isProcessQueryError(error) ||
|
||||
isProcessQueryTimeoutError(error) ||
|
||||
isProcessCommandExitError(error) ||
|
||||
isProcessSignalRejectedError(error) ||
|
||||
isProcessSignalFailedError(error)
|
||||
);
|
||||
}
|
||||
|
||||
function makeProcessQueryError(message: string, cause?: unknown): ProcessQueryError {
|
||||
return new ProcessQueryError({
|
||||
message,
|
||||
...(cause === undefined ? {} : { cause }),
|
||||
});
|
||||
@@ -92,13 +130,21 @@ function parseNumber(value: string): number | null {
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
function finiteNumberOption(value: number | undefined): Option.Option<number> {
|
||||
return typeof value === "number" && Number.isFinite(value) ? Option.some(value) : Option.none();
|
||||
}
|
||||
const WindowsProcessRowSchema = Schema.Struct({
|
||||
ProcessId: Schema.optional(Schema.Number),
|
||||
ParentProcessId: Schema.optional(Schema.Number),
|
||||
CommandLine: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
Name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
Status: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
WorkingSetSize: Schema.optional(Schema.Number),
|
||||
PercentProcessorTime: Schema.optional(Schema.Number),
|
||||
});
|
||||
type WindowsProcessRow = typeof WindowsProcessRowSchema.Type;
|
||||
|
||||
function nonEmptyStringOption(value: string | undefined): Option.Option<string> {
|
||||
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
|
||||
}
|
||||
const WindowsProcessRowsJsonSchema = Schema.fromJsonString(
|
||||
Schema.Union([Schema.Array(WindowsProcessRowSchema), WindowsProcessRowSchema]),
|
||||
);
|
||||
const decodeWindowsProcessRowsJsonOption = Schema.decodeUnknownOption(WindowsProcessRowsJsonSchema);
|
||||
|
||||
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
const rows: ProcessRow[] = [];
|
||||
@@ -165,51 +211,47 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
|
||||
return rows;
|
||||
}
|
||||
|
||||
function normalizeWindowsProcessRow(record: WindowsProcessRecordJson): Option.Option<ProcessRow> {
|
||||
const pid = finiteNumberOption(record.ProcessId).pipe(Option.filter((value) => value > 0));
|
||||
const ppid = finiteNumberOption(record.ParentProcessId).pipe(
|
||||
Option.filter((value) => value >= 0),
|
||||
);
|
||||
const commandLine = nonEmptyStringOption(record.CommandLine).pipe(
|
||||
Option.orElse(() => nonEmptyStringOption(record.Name)),
|
||||
);
|
||||
function normalizeWindowsProcessRow(record: WindowsProcessRow): ProcessRow | null {
|
||||
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
|
||||
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
|
||||
const commandLine =
|
||||
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
|
||||
? record.CommandLine
|
||||
: typeof record.Name === "string"
|
||||
? record.Name
|
||||
: null;
|
||||
const workingSet =
|
||||
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
|
||||
? Math.max(0, Math.round(record.WorkingSetSize))
|
||||
: 0;
|
||||
const cpuPercent =
|
||||
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
|
||||
? Math.max(0, record.PercentProcessorTime)
|
||||
: 0;
|
||||
|
||||
if (Option.isNone(pid) || Option.isNone(ppid) || Option.isNone(commandLine)) {
|
||||
return Option.none();
|
||||
}
|
||||
|
||||
const workingSet = finiteNumberOption(record.WorkingSetSize).pipe(
|
||||
Option.map((value) => Math.max(0, Math.round(value))),
|
||||
Option.getOrElse(() => 0),
|
||||
);
|
||||
const cpuPercent = finiteNumberOption(record.PercentProcessorTime).pipe(
|
||||
Option.map((value) => Math.max(0, value)),
|
||||
Option.getOrElse(() => 0),
|
||||
);
|
||||
const status = nonEmptyStringOption(record.Status).pipe(Option.getOrElse(() => "Live"));
|
||||
|
||||
return Option.some({
|
||||
pid: pid.value,
|
||||
ppid: ppid.value,
|
||||
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
|
||||
return {
|
||||
pid,
|
||||
ppid,
|
||||
pgid: null,
|
||||
status,
|
||||
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
|
||||
cpuPercent,
|
||||
rssBytes: workingSet,
|
||||
elapsed: "",
|
||||
command: commandLine.value,
|
||||
});
|
||||
command: commandLine,
|
||||
};
|
||||
}
|
||||
|
||||
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
if (output.trim().length === 0) return [];
|
||||
const decoded = decodeWindowsProcessJson(output);
|
||||
if (Option.isNone(decoded)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const decoded = decodeWindowsProcessRowsJsonOption(output);
|
||||
if (Option.isNone(decoded)) return [];
|
||||
|
||||
const records = Array.isArray(decoded.value) ? decoded.value : [decoded.value];
|
||||
return records.flatMap((record) => {
|
||||
const row = normalizeWindowsProcessRow(record);
|
||||
return Option.isSome(row) ? [row.value] : [];
|
||||
return row ? [row] : [];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -339,14 +381,18 @@ const runProcess = Effect.fn("runProcess")(
|
||||
Effect.timeoutOption(PROCESS_QUERY_TIMEOUT),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ProcessQueryTimeoutError({
|
||||
message: `${input.errorMessage} timed out.`,
|
||||
timeoutMillis: Duration.toMillis(PROCESS_QUERY_TIMEOUT),
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
isProcessDiagnosticsError(cause)
|
||||
? cause
|
||||
: toProcessDiagnosticsError(input.errorMessage, cause),
|
||||
isProcessDiagnosticsError(cause) ? cause : makeProcessQueryError(input.errorMessage, cause),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -363,7 +409,14 @@ function readPosixProcessRows(): Effect.Effect<
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(toProcessDiagnosticsError(result.stderr.trim() || "ps failed."))
|
||||
? Effect.fail(
|
||||
new ProcessCommandExitError({
|
||||
message: result.stderr.trim() || "ps failed.",
|
||||
command: "ps",
|
||||
exitCode: result.exitCode,
|
||||
stderr: result.stderr,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parsePosixProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
@@ -390,7 +443,12 @@ function readWindowsProcessRows(): Effect.Effect<
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(
|
||||
toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
|
||||
new ProcessCommandExitError({
|
||||
message: result.stderr.trim() || "PowerShell process query failed.",
|
||||
command: "powershell.exe",
|
||||
exitCode: result.exitCode,
|
||||
stderr: result.stderr,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
|
||||
),
|
||||
@@ -412,7 +470,13 @@ function assertDescendantPid(
|
||||
pid: number,
|
||||
): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
if (pid === process.pid) {
|
||||
return Effect.fail(toProcessDiagnosticsError("Refusing to signal the T3 server process."));
|
||||
return Effect.fail(
|
||||
new ProcessSignalRejectedError({
|
||||
message: "Refusing to signal the T3 server process.",
|
||||
pid,
|
||||
reason: "self",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return readProcessRows().pipe(
|
||||
@@ -424,7 +488,11 @@ function assertDescendantPid(
|
||||
return descendant
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
toProcessDiagnosticsError(`Process ${pid} is not a live descendant of the T3 server.`),
|
||||
new ProcessSignalRejectedError({
|
||||
message: `Process ${pid} is not a live descendant of the T3 server.`,
|
||||
pid,
|
||||
reason: "not-descendant",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -465,10 +533,12 @@ export const make = Effect.fn("makeProcessDiagnostics")(function* () {
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
toProcessDiagnosticsError(
|
||||
`Failed to signal process ${input.pid} with ${input.signal}.`,
|
||||
new ProcessSignalFailedError({
|
||||
message: `Failed to signal process ${input.pid} with ${input.signal}.`,
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
cause,
|
||||
),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
|
||||
@@ -5,9 +5,12 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as TraceDiagnostics from "./TraceDiagnostics.ts";
|
||||
|
||||
const encodeTraceRecordJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
|
||||
|
||||
function ns(ms: number): string {
|
||||
return String(BigInt(ms) * 1_000_000n);
|
||||
}
|
||||
@@ -21,7 +24,7 @@ function record(input: {
|
||||
readonly exit?: { readonly _tag: "Success" | "Failure" | "Interrupted"; readonly cause?: string };
|
||||
readonly events?: ReadonlyArray<unknown>;
|
||||
}) {
|
||||
return JSON.stringify({
|
||||
return encodeTraceRecordJson({
|
||||
type: "effect-span",
|
||||
name: input.name,
|
||||
traceId: input.traceId,
|
||||
|
||||
@@ -16,23 +16,6 @@ import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
interface TraceRecordLike {
|
||||
readonly name?: unknown;
|
||||
readonly traceId?: unknown;
|
||||
readonly spanId?: unknown;
|
||||
readonly startTimeUnixNano?: unknown;
|
||||
readonly endTimeUnixNano?: unknown;
|
||||
readonly durationMs?: unknown;
|
||||
readonly exit?: unknown;
|
||||
readonly events?: unknown;
|
||||
}
|
||||
|
||||
interface TraceEventLike {
|
||||
readonly name?: unknown;
|
||||
readonly timeUnixNano?: unknown;
|
||||
readonly attributes?: unknown;
|
||||
}
|
||||
|
||||
export interface TraceDiagnosticsOptions {
|
||||
readonly traceFilePath: string;
|
||||
readonly maxFiles: number;
|
||||
@@ -66,7 +49,34 @@ interface TraceDiagnosticsErrorSummary {
|
||||
const DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000;
|
||||
const TOP_LIMIT = 10;
|
||||
const RECENT_LIMIT = 20;
|
||||
const decodeTraceRecordJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
|
||||
|
||||
const TraceExitSchema = Schema.Struct({
|
||||
_tag: Schema.optional(Schema.Unknown),
|
||||
cause: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
type TraceExit = typeof TraceExitSchema.Type;
|
||||
const decodeTraceExitOption = Schema.decodeUnknownOption(TraceExitSchema);
|
||||
|
||||
const TraceEventSchema = Schema.Struct({
|
||||
name: Schema.optional(Schema.Unknown),
|
||||
timeUnixNano: Schema.optional(Schema.Unknown),
|
||||
attributes: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
});
|
||||
const decodeTraceEventOption = Schema.decodeUnknownOption(TraceEventSchema);
|
||||
|
||||
const TraceRecordJsonSchema = Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
name: Schema.optional(Schema.Unknown),
|
||||
traceId: Schema.optional(Schema.Unknown),
|
||||
spanId: Schema.optional(Schema.Unknown),
|
||||
startTimeUnixNano: Schema.optional(Schema.Unknown),
|
||||
endTimeUnixNano: Schema.optional(Schema.Unknown),
|
||||
durationMs: Schema.optional(Schema.Unknown),
|
||||
exit: Schema.optional(Schema.Unknown),
|
||||
events: Schema.optional(Schema.Array(Schema.Unknown)),
|
||||
}),
|
||||
);
|
||||
const decodeTraceRecordJsonOption = Schema.decodeUnknownOption(TraceRecordJsonSchema);
|
||||
|
||||
function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyArray<string> {
|
||||
const backupCount = Math.max(0, Math.floor(maxFiles));
|
||||
@@ -77,47 +87,55 @@ function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyA
|
||||
return [...backups, traceFilePath];
|
||||
}
|
||||
|
||||
function isRecordObject(value: unknown): value is TraceRecordLike {
|
||||
return typeof value === "object" && value !== null;
|
||||
function toStringOption(value: unknown): Option.Option<string> {
|
||||
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
|
||||
}
|
||||
|
||||
function toStringValue(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
||||
function toNumberOption(value: unknown): Option.Option<number> {
|
||||
return typeof value === "number" && Number.isFinite(value) ? Option.some(value) : Option.none();
|
||||
}
|
||||
|
||||
function toNumberValue(value: unknown): number | null {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
function unixNanoToDateTime(value: unknown): DateTime.Utc | null {
|
||||
const text = toStringValue(value);
|
||||
if (!text) return null;
|
||||
function unixNanoToDateTime(value: unknown): Option.Option<DateTime.Utc> {
|
||||
const text = toStringOption(value);
|
||||
if (Option.isNone(text)) return Option.none();
|
||||
try {
|
||||
const millis = Number(BigInt(text) / 1_000_000n);
|
||||
return Option.getOrNull(DateTime.make(millis));
|
||||
const millis = Number(BigInt(text.value) / 1_000_000n);
|
||||
return DateTime.make(millis);
|
||||
} catch {
|
||||
return null;
|
||||
return Option.none();
|
||||
}
|
||||
}
|
||||
|
||||
function readExitTag(exit: unknown): string | null {
|
||||
if (!isRecordObject(exit) || !("_tag" in exit)) return null;
|
||||
return toStringValue(exit._tag);
|
||||
function decodeTraceExit(exit: unknown): Option.Option<TraceExit> {
|
||||
return decodeTraceExitOption(exit);
|
||||
}
|
||||
|
||||
function readExitTag(exit: unknown): Option.Option<string> {
|
||||
return Option.flatMap(decodeTraceExit(exit), (parsedExit) => toStringOption(parsedExit._tag));
|
||||
}
|
||||
|
||||
function readExitCause(exit: unknown): string {
|
||||
if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
|
||||
return toStringValue(exit.cause)?.trim() ?? "Failure";
|
||||
return Option.getOrElse(
|
||||
Option.flatMap(decodeTraceExit(exit), (parsedExit) => toStringOption(parsedExit.cause)),
|
||||
() => "Failure",
|
||||
).trim();
|
||||
}
|
||||
|
||||
function isTraceEvent(value: unknown): value is TraceEventLike {
|
||||
return typeof value === "object" && value !== null;
|
||||
function minDateTimeOption(
|
||||
current: Option.Option<DateTime.Utc>,
|
||||
candidate: Option.Option<DateTime.Utc>,
|
||||
): Option.Option<DateTime.Utc> {
|
||||
if (Option.isNone(candidate)) return current;
|
||||
if (Option.isNone(current)) return candidate;
|
||||
return DateTime.isLessThan(candidate.value, current.value) ? candidate : current;
|
||||
}
|
||||
|
||||
function readEventAttributes(event: TraceEventLike): Readonly<Record<string, unknown>> {
|
||||
return typeof event.attributes === "object" && event.attributes !== null
|
||||
? (event.attributes as Readonly<Record<string, unknown>>)
|
||||
: {};
|
||||
function maxDateTime(
|
||||
current: Option.Option<DateTime.Utc>,
|
||||
candidate: DateTime.Utc,
|
||||
): Option.Option<DateTime.Utc> {
|
||||
if (Option.isNone(current)) return Option.some(candidate);
|
||||
return DateTime.isGreaterThan(candidate, current.value) ? Option.some(candidate) : current;
|
||||
}
|
||||
|
||||
function makeEmptyDiagnostics(input: {
|
||||
@@ -202,8 +220,8 @@ export function aggregateTraceDiagnostics(
|
||||
let failureCount = 0;
|
||||
let interruptionCount = 0;
|
||||
let slowSpanCount = 0;
|
||||
let firstSpanAt: DateTime.Utc | null = null;
|
||||
let lastSpanAt: DateTime.Utc | null = null;
|
||||
let firstSpanAt = Option.none<DateTime.Utc>();
|
||||
let lastSpanAt = Option.none<DateTime.Utc>();
|
||||
|
||||
const spansByName = new Map<
|
||||
string,
|
||||
@@ -220,41 +238,42 @@ export function aggregateTraceDiagnostics(
|
||||
for (const line of lines) {
|
||||
if (line.trim().length === 0) continue;
|
||||
|
||||
const decoded = decodeTraceRecordJson(line);
|
||||
if (Option.isNone(decoded)) {
|
||||
const decodedRecord = decodeTraceRecordJsonOption(line);
|
||||
if (Option.isNone(decodedRecord)) {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
const parsed = decodedRecord.value;
|
||||
|
||||
const parsed = decoded.value;
|
||||
if (!isRecordObject(parsed)) {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = toStringValue(parsed.name);
|
||||
const traceId = toStringValue(parsed.traceId);
|
||||
const spanId = toStringValue(parsed.spanId);
|
||||
const durationMs = toNumberValue(parsed.durationMs);
|
||||
const nameOption = toStringOption(parsed.name);
|
||||
const traceIdOption = toStringOption(parsed.traceId);
|
||||
const spanIdOption = toStringOption(parsed.spanId);
|
||||
const durationMsOption = toNumberOption(parsed.durationMs);
|
||||
const endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);
|
||||
const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);
|
||||
|
||||
if (!name || !traceId || !spanId || durationMs === null || !endedAt) {
|
||||
if (
|
||||
Option.isNone(nameOption) ||
|
||||
Option.isNone(traceIdOption) ||
|
||||
Option.isNone(spanIdOption) ||
|
||||
Option.isNone(durationMsOption) ||
|
||||
Option.isNone(endedAt)
|
||||
) {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
const name = nameOption.value;
|
||||
const traceId = traceIdOption.value;
|
||||
const spanId = spanIdOption.value;
|
||||
const durationMs = durationMsOption.value;
|
||||
|
||||
recordCount += 1;
|
||||
firstSpanAt =
|
||||
startedAt && (firstSpanAt === null || DateTime.isLessThan(startedAt, firstSpanAt))
|
||||
? startedAt
|
||||
: firstSpanAt;
|
||||
lastSpanAt =
|
||||
lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
|
||||
firstSpanAt = minDateTimeOption(firstSpanAt, startedAt);
|
||||
lastSpanAt = maxDateTime(lastSpanAt, endedAt.value);
|
||||
|
||||
const exitTag = readExitTag(parsed.exit);
|
||||
const isFailure = exitTag === "Failure";
|
||||
const isInterrupted = exitTag === "Interrupted";
|
||||
const isFailure = Option.contains(exitTag, "Failure");
|
||||
const isInterrupted = Option.contains(exitTag, "Interrupted");
|
||||
if (isFailure) failureCount += 1;
|
||||
if (isInterrupted) interruptionCount += 1;
|
||||
|
||||
@@ -270,7 +289,7 @@ export function aggregateTraceDiagnostics(
|
||||
if (isFailure) spanSummary.failureCount += 1;
|
||||
spansByName.set(name, spanSummary);
|
||||
|
||||
const spanItem = { name, durationMs, endedAt, traceId, spanId };
|
||||
const spanItem = { name, durationMs, endedAt: endedAt.value, traceId, spanId };
|
||||
if (durationMs >= slowSpanThresholdMs) {
|
||||
slowSpanCount += 1;
|
||||
}
|
||||
@@ -282,12 +301,13 @@ export function aggregateTraceDiagnostics(
|
||||
|
||||
const failureKey = `${name}\0${cause}`;
|
||||
const existing = failuresByKey.get(failureKey);
|
||||
const isLatestFailure = !existing || DateTime.isGreaterThan(endedAt, existing.lastSeenAt);
|
||||
const isLatestFailure =
|
||||
!existing || DateTime.isGreaterThan(endedAt.value, existing.lastSeenAt);
|
||||
failuresByKey.set(failureKey, {
|
||||
name,
|
||||
cause,
|
||||
count: (existing?.count ?? 0) + 1,
|
||||
lastSeenAt: isLatestFailure ? endedAt : existing!.lastSeenAt,
|
||||
lastSeenAt: isLatestFailure ? endedAt.value : existing!.lastSeenAt,
|
||||
traceId: isLatestFailure ? traceId : existing!.traceId,
|
||||
spanId: isLatestFailure ? spanId : existing!.spanId,
|
||||
});
|
||||
@@ -295,10 +315,15 @@ export function aggregateTraceDiagnostics(
|
||||
|
||||
if (Array.isArray(parsed.events)) {
|
||||
for (const rawEvent of parsed.events) {
|
||||
if (!isTraceEvent(rawEvent)) continue;
|
||||
const attributes = readEventAttributes(rawEvent);
|
||||
const level = toStringValue(attributes["effect.logLevel"]);
|
||||
if (!level) continue;
|
||||
const event = decodeTraceEventOption(rawEvent);
|
||||
if (Option.isNone(event)) continue;
|
||||
const attributes = Option.getOrElse(
|
||||
Option.fromUndefinedOr(event.value.attributes),
|
||||
() => ({}) as Readonly<Record<string, unknown>>,
|
||||
);
|
||||
const levelOption = toStringOption(attributes["effect.logLevel"]);
|
||||
if (Option.isNone(levelOption)) continue;
|
||||
const level = levelOption.value;
|
||||
|
||||
logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
|
||||
const normalizedLevel = level.toLowerCase();
|
||||
@@ -311,8 +336,14 @@ export function aggregateTraceDiagnostics(
|
||||
continue;
|
||||
}
|
||||
|
||||
const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
|
||||
const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
|
||||
const seenAt = Option.getOrElse(
|
||||
unixNanoToDateTime(event.value.timeUnixNano),
|
||||
() => endedAt.value,
|
||||
);
|
||||
const message = Option.getOrElse(
|
||||
Option.map(toStringOption(event.value.name), (name) => name.trim()),
|
||||
() => "Log event",
|
||||
);
|
||||
latestWarningAndErrorLogs.push({
|
||||
spanName: name,
|
||||
level,
|
||||
@@ -344,8 +375,8 @@ export function aggregateTraceDiagnostics(
|
||||
readAt,
|
||||
recordCount,
|
||||
parseErrorCount,
|
||||
firstSpanAt: Option.fromNullishOr(firstSpanAt),
|
||||
lastSpanAt: Option.fromNullishOr(lastSpanAt),
|
||||
firstSpanAt,
|
||||
lastSpanAt,
|
||||
failureCount,
|
||||
interruptionCount,
|
||||
slowSpanThresholdMs,
|
||||
|
||||
Reference in new issue
Block a user