Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 7459311955 Make diagnostics parsing more idiomatic Effect
Co-authored-by: Julius Marminge <[email protected]>
2026-06-28 16:08:01 +00:00
3 changed files with 266 additions and 289 deletions

No files matched your search

@@ -1,9 +1,8 @@
import { assert, describe, it } from "@effect/vitest";
import { assert, describe, expect, it } from "@effect/vitest";
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";
@@ -12,7 +11,6 @@ import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
const encoder = new TextEncoder();
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
function mockHandle(result: {
readonly stdout?: string;
@@ -44,7 +42,7 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
);
assert.deepStrictEqual(rows, [
expect(rows).toEqual([
{
pid: 10,
ppid: 1,
@@ -128,21 +126,15 @@ describe("ProcessDiagnostics", () => {
],
});
assert.equal(diagnostics.serverPid, 100);
assert.equal(DateTime.formatIso(diagnostics.readAt), "2026-05-05T10:00:00.000Z");
assert.equal(diagnostics.processCount, 2);
assert.equal(diagnostics.totalRssBytes, 6_000);
assert.equal(diagnostics.totalCpuPercent, 4.75);
assert.deepStrictEqual(
diagnostics.processes.map((process) => process.pid),
[101, 102],
);
assert.deepStrictEqual(
diagnostics.processes.map((process) => process.depth),
[0, 1],
);
assert.equal(Option.getOrNull(diagnostics.processes[0]!.pgid), 100);
assert.deepStrictEqual(diagnostics.processes[0]?.childPids, [102]);
expect(diagnostics.serverPid).toBe(100);
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
expect(diagnostics.processCount).toBe(2);
expect(diagnostics.totalRssBytes).toBe(6_000);
expect(diagnostics.totalCpuPercent).toBe(4.75);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
}),
);
@@ -185,10 +177,7 @@ describe("ProcessDiagnostics", () => {
],
});
assert.deepStrictEqual(
diagnostics.processes.map((process) => process.pid),
[101, 102, 103],
);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
}),
);
@@ -221,11 +210,8 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
assert.deepStrictEqual(
diagnostics.processes.map((process) => process.pid),
[4242],
);
assert.deepStrictEqual(commands, [
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
expect(commands).toEqual([
{
command: "ps",
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
@@ -234,6 +220,84 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("queries Windows processes through schema-decoded PowerShell JSON", () =>
Effect.gen(function* () {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
[];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
commands.push({ command: childProcess.command, args: childProcess.args });
return Effect.succeed(
mockHandle({
stdout: JSON.stringify([
{
ProcessId: process.pid,
ParentProcessId: 1,
Name: "node.exe",
CommandLine: "t3 server",
Status: "Running",
WorkingSetSize: 1024,
PercentProcessorTime: 0,
},
{
ProcessId: 4242,
ParentProcessId: process.pid,
Name: "agent.exe",
CommandLine: "agent.exe --work",
Status: "Running",
WorkingSetSize: 4096.4,
PercentProcessorTime: 12.25,
},
{
ProcessId: "invalid",
ParentProcessId: process.pid,
Name: "ignored.exe",
},
]),
}),
);
}),
);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
Effect.flatMap((pd) => pd.read),
Effect.provide(layer),
Effect.provideService(HostProcessPlatform, "win32"),
);
assert.deepStrictEqual(
diagnostics.processes.map((process) => ({
pid: process.pid,
ppid: process.ppid,
command: process.command,
rssBytes: process.rssBytes,
cpuPercent: process.cpuPercent,
})),
[
{
pid: 4242,
ppid: process.pid,
command: "agent.exe --work",
rssBytes: 4096,
cpuPercent: 12.25,
},
],
);
assert.equal(commands[0]?.command, "powershell.exe");
assert.deepStrictEqual(commands[0]?.args.slice(0, 3), [
"-NoProfile",
"-NonInteractive",
"-Command",
]);
}),
);
it.effect("keeps bounded command diagnostics when the process query exits unsuccessfully", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
@@ -255,129 +319,23 @@ describe("ProcessDiagnostics", () => {
Effect.flip,
);
if (error._tag !== "ProcessDiagnosticsQueryFailedError") {
assert.fail(`Expected ProcessDiagnosticsQueryFailedError, got ${error._tag}`);
}
assert.deepStrictEqual(
{
command: error.command,
argCount: error.argCount,
cwd: error.cwd,
exitCode: error.exitCode,
stdoutBytes: error.stdoutBytes,
stderrBytes: error.stderrBytes,
stdoutTruncated: error.stdoutTruncated,
stderrTruncated: error.stderrTruncated,
},
{
command: "ps",
argCount: 2,
cwd: process.cwd(),
exitCode: 17,
stdoutBytes: 22,
stderrBytes: 21,
stdoutTruncated: false,
stderrTruncated: false,
},
);
assert.equal(
error.message,
expect(error).toMatchObject({
_tag: "ProcessDiagnosticsQueryFailedError",
command: "ps",
argCount: 2,
cwd: process.cwd(),
exitCode: 17,
stdoutBytes: 22,
stderrBytes: 21,
stdoutTruncated: false,
stderrTruncated: false,
});
expect(error.message).toBe(
`Process diagnostics query 'ps' failed with exit code 17 in '${process.cwd()}'.`,
);
}),
);
it.effect("decodes Windows process JSON through Schema and skips invalid records", () =>
Effect.gen(function* () {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
[];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
commands.push({ command: childProcess.command, args: childProcess.args });
return Effect.succeed(
mockHandle({
stdout: encodeUnknownJson([
{
ProcessId: process.pid,
ParentProcessId: 1,
Name: "node.exe",
CommandLine: "t3 server",
Status: "",
WorkingSetSize: 1024,
PercentProcessorTime: 0,
},
{
ProcessId: 4242,
ParentProcessId: process.pid,
Name: "agent.exe",
CommandLine: null,
Status: "Running",
WorkingSetSize: 2048.6,
PercentProcessorTime: 1.25,
},
{
ProcessId: "invalid",
ParentProcessId: process.pid,
Name: "bad.exe",
},
]),
}),
);
}),
);
const rows = yield* ProcessDiagnostics.readProcessRows.pipe(
Effect.provide(spawnerLayer),
Effect.provideService(HostProcessPlatform, "win32"),
);
assert.deepStrictEqual(commands, [
{
command: "powershell.exe",
args: [
"-NoProfile",
"-NonInteractive",
"-Command",
[
"$processes = Get-CimInstance Win32_Process | ForEach-Object {",
'$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess = $($_.ProcessId)" -ErrorAction SilentlyContinue;',
"[pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; Name = $_.Name; CommandLine = $_.CommandLine; Status = $_.Status; WorkingSetSize = $_.WorkingSetSize; PercentProcessorTime = if ($perf) { $perf.PercentProcessorTime } else { 0 } }",
"};",
"$processes | ConvertTo-Json -Compress -Depth 3",
].join(" "),
],
},
]);
assert.deepStrictEqual(rows, [
{
pid: process.pid,
ppid: 1,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 1024,
elapsed: "",
command: "t3 server",
},
{
pid: 4242,
ppid: process.pid,
pgid: null,
status: "Running",
cpuPercent: 1.25,
rssBytes: 2049,
elapsed: "",
command: "agent.exe",
},
]);
}),
);
it.effect("does not allow signaling the diagnostics query process", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
@@ -400,7 +358,7 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
assert.deepStrictEqual(result, {
expect(result).toEqual({
pid: 4242,
signal: "SIGINT",
signaled: false,
@@ -28,21 +28,21 @@ export interface ProcessRow {
readonly command: string;
}
const PROCESS_QUERY_TIMEOUT = Duration.seconds(1);
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
const WindowsProcessJson = Schema.fromJsonString(Schema.Unknown);
const WindowsProcessRecord = Schema.Struct({
ProcessId: Schema.Number,
ParentProcessId: Schema.Number,
CommandLine: Schema.optional(Schema.OptionFromNullOr(Schema.String)),
Name: Schema.optional(Schema.OptionFromNullOr(Schema.String)),
Status: Schema.optional(Schema.OptionFromNullOr(Schema.String)),
WorkingSetSize: Schema.optional(Schema.OptionFromNullOr(Schema.Number)),
PercentProcessorTime: Schema.optional(Schema.OptionFromNullOr(Schema.Number)),
ProcessId: Schema.Number.check(Schema.isFinite()),
ParentProcessId: Schema.Number.check(Schema.isFinite()),
CommandLine: Schema.optional(Schema.Unknown),
Name: Schema.optional(Schema.Unknown),
Status: Schema.optional(Schema.Unknown),
WorkingSetSize: Schema.optional(Schema.Unknown),
PercentProcessorTime: Schema.optional(Schema.Unknown),
});
type WindowsProcessRecord = typeof WindowsProcessRecord.Type;
const decodeWindowsProcessJson = Schema.decodeUnknownOption(WindowsProcessJson);
const WindowsProcessDocument = Schema.fromJsonString(Schema.Unknown);
const decodeWindowsProcessDocument = Schema.decodeUnknownOption(WindowsProcessDocument);
const decodeWindowsProcessRecord = Schema.decodeUnknownOption(WindowsProcessRecord);
export class ProcessDiagnostics extends Context.Service<
@@ -149,6 +149,14 @@ function parseNumber(value: string): number | null {
return Number.isFinite(parsed) ? parsed : null;
}
function finiteNumber(value: unknown): Option.Option<number> {
return typeof value === "number" && Number.isFinite(value) ? Option.some(value) : Option.none();
}
function nonBlankString(value: unknown): Option.Option<string> {
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
}
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
const rows: ProcessRow[] = [];
const rowPattern =
@@ -214,72 +222,58 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function optionFromOptional<T>(value: Option.Option<T> | undefined): Option.Option<T> {
return value ?? Option.none();
}
function normalizeWindowsProcessRow(value: unknown): Option.Option<ProcessRow> {
const recordOption = decodeWindowsProcessRecord(value);
if (Option.isNone(recordOption)) return Option.none();
const record = recordOption.value;
const pid = record.ProcessId;
const ppid = record.ParentProcessId;
const commandLineOption = nonBlankString(record.CommandLine).pipe(
Option.orElse(() => nonBlankString(record.Name)),
);
function nonEmptyString(value: Option.Option<string> | undefined): Option.Option<string> {
return optionFromOptional(value).pipe(Option.filter((text) => text.trim().length > 0));
}
function optionalNumberOrElse(
value: Option.Option<number> | undefined,
onSome: (value: number) => number,
): number {
return Option.match(optionFromOptional(value), {
onNone: () => 0,
onSome,
});
}
function normalizeWindowsProcessRecord(record: WindowsProcessRecord): Option.Option<ProcessRow> {
if (
!Number.isInteger(record.ProcessId) ||
record.ProcessId <= 0 ||
!Number.isInteger(record.ParentProcessId) ||
record.ParentProcessId < 0
!Number.isInteger(pid) ||
pid <= 0 ||
!Number.isInteger(ppid) ||
ppid < 0 ||
Option.isNone(commandLineOption)
) {
return Option.none();
}
const commandLine = nonEmptyString(record.CommandLine).pipe(
Option.orElse(() => nonEmptyString(record.Name)),
const workingSet = Option.getOrElse(
finiteNumber(record.WorkingSetSize).pipe(Option.map((bytes) => Math.max(0, Math.round(bytes)))),
() => 0,
);
const cpuPercent = Option.getOrElse(
finiteNumber(record.PercentProcessorTime).pipe(Option.map((percent) => Math.max(0, percent))),
() => 0,
);
if (Option.isNone(commandLine)) return Option.none();
return Option.some({
pid: record.ProcessId,
ppid: record.ParentProcessId,
pid,
ppid,
pgid: null,
status: Option.getOrElse(nonEmptyString(record.Status), () => "Live"),
cpuPercent: optionalNumberOrElse(record.PercentProcessorTime, (value) => Math.max(0, value)),
rssBytes: optionalNumberOrElse(record.WorkingSetSize, (value) =>
Math.max(0, Math.round(value)),
),
status: Option.getOrElse(nonBlankString(record.Status), () => "Live"),
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine.value,
});
}
function normalizeWindowsProcessRow(value: unknown): Option.Option<ProcessRow> {
return Option.match(decodeWindowsProcessRecord(value), {
onNone: () => Option.none(),
onSome: normalizeWindowsProcessRecord,
command: commandLineOption.value,
});
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
return Option.match(decodeWindowsProcessJson(output), {
onNone: () => [],
onSome: (parsed) =>
(Array.isArray(parsed) ? parsed : [parsed]).flatMap((record) =>
Option.match(normalizeWindowsProcessRow(record), {
onNone: () => [],
onSome: (row) => [row],
}),
),
});
const document = decodeWindowsProcessDocument(output);
if (Option.isNone(document)) return [];
const records = Array.isArray(document.value) ? document.value : [document.value];
return records.flatMap((record) =>
Option.match(normalizeWindowsProcessRow(record), {
onNone: () => [],
onSome: (row) => [row],
}),
);
}
export function buildDescendantEntries(
@@ -415,7 +409,7 @@ const runProcess = Effect.fn("runProcess")(function* (input: {
} satisfies ProcessOutput;
}).pipe(
Effect.scoped,
Effect.timeoutOption(PROCESS_QUERY_TIMEOUT),
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
@@ -424,7 +418,7 @@ const runProcess = Effect.fn("runProcess")(function* (input: {
command: input.command,
argCount: input.args.length,
cwd,
timeoutMillis: Duration.toMillis(PROCESS_QUERY_TIMEOUT),
timeoutMillis: PROCESS_QUERY_TIMEOUT_MS,
}),
),
onSome: Effect.succeed,
+104 -79
View File
@@ -17,22 +17,31 @@ import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
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;
}
const TraceRecordLine = Schema.Struct({
name: Schema.String,
traceId: Schema.String,
spanId: Schema.String,
startTimeUnixNano: Schema.optional(Schema.Unknown),
endTimeUnixNano: Schema.String,
durationMs: Schema.Number.check(Schema.isFinite()),
exit: Schema.optional(Schema.Unknown),
events: Schema.optional(Schema.Array(Schema.Unknown)),
});
const decodeTraceRecordLine = Schema.decodeUnknownOption(Schema.fromJsonString(TraceRecordLine));
interface TraceEventLike {
readonly name?: unknown;
readonly timeUnixNano?: unknown;
readonly attributes?: unknown;
}
const TraceExit = Schema.Struct({
_tag: Schema.String,
cause: Schema.optional(Schema.Unknown),
});
const decodeTraceExit = Schema.decodeUnknownOption(TraceExit);
const TraceEvent = Schema.Struct({
name: Schema.optional(Schema.Unknown),
timeUnixNano: Schema.optional(Schema.Unknown),
attributes: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
});
type TraceEvent = typeof TraceEvent.Type;
const decodeTraceEvent = Schema.decodeUnknownOption(TraceEvent);
export interface TraceDiagnosticsOptions {
readonly traceFilePath: string;
@@ -90,47 +99,38 @@ function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyA
return [...backups, traceFilePath];
}
function isRecordObject(value: unknown): value is TraceRecordLike {
return typeof value === "object" && value !== null;
function nonBlankString(value: string): Option.Option<string> {
return 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 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> {
if (typeof value !== "string" || value.trim().length === 0) return Option.none();
try {
const millis = Number(BigInt(text) / 1_000_000n);
return Option.getOrNull(DateTime.make(millis));
const millis = Number(BigInt(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 readExitTag(exit: unknown): Option.Option<string> {
return decodeTraceExit(exit).pipe(Option.flatMap((decoded) => nonBlankString(decoded._tag)));
}
function readExitCause(exit: unknown): string {
if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
return toStringValue(exit.cause)?.trim() ?? "Failure";
return Option.getOrElse(
decodeTraceExit(exit).pipe(
Option.flatMap((decoded) => Option.fromNullishOr(decoded.cause)),
Option.filter((cause): cause is string => typeof cause === "string"),
Option.map((cause) => cause.trim()),
Option.filter((cause) => cause.length > 0),
),
() => "Failure",
);
}
function isTraceEvent(value: unknown): value is TraceEventLike {
return typeof value === "object" && value !== null;
}
function readEventAttributes(event: TraceEventLike): Readonly<Record<string, unknown>> {
return typeof event.attributes === "object" && event.attributes !== null
? (event.attributes as Readonly<Record<string, unknown>>)
: {};
function readEventAttributes(event: TraceEvent): Readonly<Record<string, unknown>> {
return event.attributes ?? {};
}
function makeEmptyDiagnostics(input: {
@@ -211,8 +211,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,
@@ -229,40 +229,52 @@ export function aggregateTraceDiagnostics(
for (const line of lines) {
if (line.trim().length === 0) continue;
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
const parsedOption = decodeTraceRecordLine(line);
if (Option.isNone(parsedOption)) {
parseErrorCount += 1;
continue;
}
const parsed = parsedOption.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 endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);
const nameOption = nonBlankString(parsed.name);
const traceIdOption = nonBlankString(parsed.traceId);
const spanIdOption = nonBlankString(parsed.spanId);
const endedAtOption = 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(endedAtOption)
) {
parseErrorCount += 1;
continue;
}
const name = nameOption.value;
const traceId = traceIdOption.value;
const spanId = spanIdOption.value;
const endedAt = endedAtOption.value;
const durationMs = parsed.durationMs;
recordCount += 1;
firstSpanAt =
startedAt && (firstSpanAt === null || DateTime.isLessThan(startedAt, firstSpanAt))
? startedAt
: firstSpanAt;
lastSpanAt =
lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
firstSpanAt = Option.match(startedAt, {
onNone: () => firstSpanAt,
onSome: (spanStartedAt) =>
Option.match(firstSpanAt, {
onNone: () => Option.some(spanStartedAt),
onSome: (currentFirstSpanAt) =>
DateTime.isLessThan(spanStartedAt, currentFirstSpanAt)
? Option.some(spanStartedAt)
: firstSpanAt,
}),
});
lastSpanAt = Option.match(lastSpanAt, {
onNone: () => Option.some(endedAt),
onSome: (currentLastSpanAt) =>
DateTime.isGreaterThan(endedAt, currentLastSpanAt) ? Option.some(endedAt) : lastSpanAt,
});
const exitTag = readExitTag(parsed.exit);
const exitTag = Option.getOrNull(readExitTag(parsed.exit));
const isFailure = exitTag === "Failure";
const isInterrupted = exitTag === "Interrupted";
if (isFailure) failureCount += 1;
@@ -303,12 +315,18 @@ 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;
if (parsed.events) {
for (const encodedEvent of parsed.events) {
const eventOption = decodeTraceEvent(encodedEvent);
if (Option.isNone(eventOption)) continue;
const event = eventOption.value;
const attributes = readEventAttributes(event);
const levelOption =
typeof attributes["effect.logLevel"] === "string"
? nonBlankString(attributes["effect.logLevel"])
: Option.none<string>();
if (Option.isNone(levelOption)) continue;
const level = levelOption.value;
logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
const normalizedLevel = level.toLowerCase();
@@ -321,8 +339,15 @@ export function aggregateTraceDiagnostics(
continue;
}
const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
const seenAt = Option.getOrElse(unixNanoToDateTime(event.timeUnixNano), () => endedAt);
const message = Option.getOrElse(
Option.fromNullishOr(event.name).pipe(
Option.filter((name): name is string => typeof name === "string"),
Option.map((name) => name.trim()),
Option.filter((name) => name.length > 0),
),
() => "Log event",
);
latestWarningAndErrorLogs.push({
spanName: name,
level,
@@ -354,8 +379,8 @@ export function aggregateTraceDiagnostics(
readAt,
recordCount,
parseErrorCount,
firstSpanAt: Option.fromNullishOr(firstSpanAt),
lastSpanAt: Option.fromNullishOr(lastSpanAt),
firstSpanAt,
lastSpanAt,
failureCount,
interruptionCount,
slowSpanThresholdMs,