Skip to content

Commit 8ab9c61

Browse files
juliusmarmingecodex
andcommitted
Structure OTLP export diagnostics
Co-authored-by: codex <[email protected]>
1 parent ef9ed1e commit 8ab9c61

3 files changed

Lines changed: 232 additions & 21 deletions

File tree

‎apps/server/src/http.test.ts‎

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
import { describe, expect, it } from "vite-plus/test";
22

3-
import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
3+
import {
4+
BrowserOtlpTraceCollectionError,
5+
BrowserOtlpTraceDecodeError,
6+
BrowserOtlpTraceExportError,
7+
isLoopbackHostname,
8+
resolveDevRedirectUrl,
9+
} from "./http.ts";
410

511
describe("http dev routing", () => {
612
it("treats localhost and loopback addresses as local", () => {
@@ -25,3 +31,73 @@ describe("http dev routing", () => {
2531
);
2632
});
2733
});
34+
35+
describe("browser OTLP diagnostics", () => {
36+
it("retains decode causes without retaining the trace payload", () => {
37+
const cause = new Error("private trace payload detail");
38+
const error = BrowserOtlpTraceDecodeError.fromPayload({ resourceSpans: [] }, cause);
39+
40+
expect(error).toMatchObject({
41+
resourceSpanCount: 0,
42+
cause,
43+
message: "Failed to decode browser OTLP payload with 0 resource spans.",
44+
});
45+
expect(error.cause).toBe(cause);
46+
expect(error).not.toHaveProperty("bodyJson");
47+
});
48+
49+
it("describes malformed trace payloads without inspecting unsafe fields", () => {
50+
const cause = new Error("private malformed trace payload detail");
51+
const error = BrowserOtlpTraceDecodeError.fromPayload(
52+
{ resourceSpans: "private malformed resource spans" },
53+
cause,
54+
);
55+
56+
expect(error).toMatchObject({
57+
resourceSpanCount: 0,
58+
cause,
59+
message: "Failed to decode browser OTLP payload with 0 resource spans.",
60+
});
61+
expect(error.cause).toBe(cause);
62+
expect(error).not.toHaveProperty("resourceSpans");
63+
});
64+
65+
it("retains local collection causes with a structural record count", () => {
66+
const records = [{ type: "private trace record" }];
67+
const cause = new Error("private local collector detail");
68+
const error = BrowserOtlpTraceCollectionError.fromRecords(records, cause);
69+
70+
expect(error).toMatchObject({
71+
recordCount: 1,
72+
cause,
73+
message: "Failed to collect 1 browser OTLP trace records locally.",
74+
});
75+
expect(error.cause).toBe(cause);
76+
expect(error).not.toHaveProperty("records");
77+
});
78+
79+
it("redacts collector URL credentials while retaining the exact cause", () => {
80+
const collectorUrl =
81+
"https://collector-user:[email protected]/private/v1/traces?access_token=collector-secret#collector-fragment";
82+
const cause = new Error("collector transport failed");
83+
const error = BrowserOtlpTraceExportError.fromCollectorUrl(collectorUrl, cause);
84+
85+
expect(error).toMatchObject({
86+
collectorUrlInputLength: collectorUrl.length,
87+
collectorUrlProtocol: "https:",
88+
collectorUrlHostname: "traces.example.test",
89+
cause,
90+
});
91+
expect(error.cause).toBe(cause);
92+
expect(error).not.toHaveProperty("collectorUrl");
93+
for (const secret of [
94+
"collector-user",
95+
"collector-password",
96+
"/private/v1/traces",
97+
"collector-secret",
98+
"collector-fragment",
99+
]) {
100+
expect(error.message).not.toContain(secret);
101+
}
102+
});
103+
});

‎apps/server/src/http.ts‎

Lines changed: 130 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ import {
55
EnvironmentHttpApi,
66
} from "@t3tools/contracts";
77
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
8-
import * as Data from "effect/Data";
8+
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
99
import * as Effect from "effect/Effect";
1010
import * as FileSystem from "effect/FileSystem";
1111
import * as Layer from "effect/Layer";
1212
import * as Option from "effect/Option";
1313
import * as Path from "effect/Path";
14+
import * as Schema from "effect/Schema";
1415
import { cast } from "effect/Function";
1516
import {
1617
HttpBody,
@@ -108,10 +109,95 @@ export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
108109
}),
109110
);
110111

111-
class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
112-
readonly cause: unknown;
113-
readonly bodyJson: OtlpTracer.TraceData;
114-
}> {}
112+
function errorDiagnosticTag(cause: unknown): string {
113+
if (
114+
typeof cause === "object" &&
115+
cause !== null &&
116+
"_tag" in cause &&
117+
typeof cause._tag === "string"
118+
) {
119+
return cause._tag;
120+
}
121+
if (cause instanceof Error) return cause.name;
122+
return typeof cause;
123+
}
124+
125+
export class BrowserOtlpTraceDecodeError extends Schema.TaggedErrorClass<BrowserOtlpTraceDecodeError>()(
126+
"BrowserOtlpTraceDecodeError",
127+
{
128+
resourceSpanCount: Schema.Number,
129+
cause: Schema.Defect(),
130+
},
131+
) {
132+
static fromPayload(payload: unknown, cause: unknown): BrowserOtlpTraceDecodeError {
133+
const resourceSpanCount =
134+
typeof payload === "object" &&
135+
payload !== null &&
136+
"resourceSpans" in payload &&
137+
Array.isArray(payload.resourceSpans)
138+
? payload.resourceSpans.length
139+
: 0;
140+
141+
return new BrowserOtlpTraceDecodeError({
142+
resourceSpanCount,
143+
cause,
144+
});
145+
}
146+
147+
override get message(): string {
148+
return `Failed to decode browser OTLP payload with ${this.resourceSpanCount} resource spans.`;
149+
}
150+
}
151+
152+
export class BrowserOtlpTraceCollectionError extends Schema.TaggedErrorClass<BrowserOtlpTraceCollectionError>()(
153+
"BrowserOtlpTraceCollectionError",
154+
{
155+
recordCount: Schema.Number,
156+
cause: Schema.Defect(),
157+
},
158+
) {
159+
static fromRecords(
160+
records: ReadonlyArray<unknown>,
161+
cause: unknown,
162+
): BrowserOtlpTraceCollectionError {
163+
return new BrowserOtlpTraceCollectionError({
164+
recordCount: records.length,
165+
cause,
166+
});
167+
}
168+
169+
override get message(): string {
170+
return `Failed to collect ${this.recordCount} browser OTLP trace records locally.`;
171+
}
172+
}
173+
174+
export class BrowserOtlpTraceExportError extends Schema.TaggedErrorClass<BrowserOtlpTraceExportError>()(
175+
"BrowserOtlpTraceExportError",
176+
{
177+
collectorUrlInputLength: Schema.Number,
178+
collectorUrlProtocol: Schema.optionalKey(Schema.String),
179+
collectorUrlHostname: Schema.optionalKey(Schema.String),
180+
cause: Schema.Defect(),
181+
},
182+
) {
183+
static fromCollectorUrl(collectorUrl: string, cause: unknown): BrowserOtlpTraceExportError {
184+
const diagnostics = getUrlDiagnostics(collectorUrl);
185+
return new BrowserOtlpTraceExportError({
186+
collectorUrlInputLength: diagnostics.inputLength,
187+
...(diagnostics.protocol === undefined ? {} : { collectorUrlProtocol: diagnostics.protocol }),
188+
...(diagnostics.hostname === undefined ? {} : { collectorUrlHostname: diagnostics.hostname }),
189+
cause,
190+
});
191+
}
192+
193+
override get message(): string {
194+
const collector =
195+
this.collectorUrlHostname === undefined
196+
? "the configured collector"
197+
: this.collectorUrlHostname;
198+
return `Failed to export browser OTLP traces to ${collector} (collector URL input length ${this.collectorUrlInputLength}).`;
199+
}
200+
}
115201

116202
export const otlpTracesProxyRouteLayer = HttpRouter.add(
117203
"POST",
@@ -127,15 +213,31 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
127213

128214
yield* Effect.try({
129215
try: () => decodeOtlpTraceRecords(bodyJson),
130-
catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
216+
catch: (cause) => BrowserOtlpTraceDecodeError.fromPayload(bodyJson, cause),
131217
}).pipe(
132-
Effect.flatMap((records) => browserTraceCollector.record(records)),
133-
Effect.catch((cause) =>
134-
Effect.logWarning("Failed to decode browser OTLP traces", {
135-
cause,
136-
bodyJson,
137-
}),
218+
Effect.flatMap((records) =>
219+
browserTraceCollector
220+
.record(records)
221+
.pipe(
222+
Effect.catchDefect((cause) =>
223+
Effect.fail(BrowserOtlpTraceCollectionError.fromRecords(records, cause)),
224+
),
225+
),
138226
),
227+
Effect.catchTags({
228+
BrowserOtlpTraceDecodeError: (error) =>
229+
Effect.logWarning(error.message, {
230+
errorTag: error._tag,
231+
resourceSpanCount: error.resourceSpanCount,
232+
causeTag: errorDiagnosticTag(error.cause),
233+
}),
234+
BrowserOtlpTraceCollectionError: (error) =>
235+
Effect.logWarning(error.message, {
236+
errorTag: error._tag,
237+
recordCount: error.recordCount,
238+
causeTag: errorDiagnosticTag(error.cause),
239+
}),
240+
}),
139241
);
140242

141243
if (otlpTracesUrl === undefined) {
@@ -149,15 +251,23 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
149251
.pipe(
150252
Effect.flatMap(HttpClientResponse.filterStatusOk),
151253
Effect.as(HttpServerResponse.empty({ status: 204 })),
152-
Effect.tapError((cause) =>
153-
Effect.logWarning("Failed to export browser OTLP traces", {
154-
cause,
155-
otlpTracesUrl,
156-
}),
157-
),
158-
Effect.orElseSucceed(() =>
159-
HttpServerResponse.text("Trace export failed.", { status: 502 }),
254+
Effect.mapError((cause) =>
255+
BrowserOtlpTraceExportError.fromCollectorUrl(otlpTracesUrl, cause),
160256
),
257+
Effect.catchTags({
258+
BrowserOtlpTraceExportError: (error) =>
259+
Effect.logWarning(error.message, {
260+
errorTag: error._tag,
261+
collectorUrlInputLength: error.collectorUrlInputLength,
262+
...(error.collectorUrlProtocol === undefined
263+
? {}
264+
: { collectorUrlProtocol: error.collectorUrlProtocol }),
265+
...(error.collectorUrlHostname === undefined
266+
? {}
267+
: { collectorUrlHostname: error.collectorUrlHostname }),
268+
causeTag: errorDiagnosticTag(error.cause),
269+
}).pipe(Effect.as(HttpServerResponse.text("Trace export failed.", { status: 502 }))),
270+
}),
161271
);
162272
}).pipe(
163273
Effect.catchTags({

‎apps/server/src/server.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4026,6 +4026,31 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
40264026
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
40274027
);
40284028

4029+
it.effect("continues browser OTLP requests when local trace collection defects", () =>
4030+
Effect.gen(function* () {
4031+
const payload = yield* makeBrowserOtlpPayload("client.test");
4032+
4033+
yield* buildAppUnderTest({
4034+
layers: {
4035+
browserTraceCollector: {
4036+
record: () => Effect.die(new Error("private local collector failure")),
4037+
},
4038+
},
4039+
});
4040+
4041+
const response = yield* HttpClient.post("/api/observability/v1/traces", {
4042+
headers: {
4043+
cookie: yield* getAuthenticatedSessionCookieHeader(),
4044+
"content-type": "application/json",
4045+
},
4046+
// @effect-diagnostics-next-line preferSchemaOverJson:off
4047+
body: HttpBody.text(JSON.stringify(payload), "application/json"),
4048+
});
4049+
4050+
assert.equal(response.status, 204);
4051+
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
4052+
);
4053+
40294054
it.effect("routes websocket rpc server.upsertKeybinding", () =>
40304055
Effect.gen(function* () {
40314056
const rule: KeybindingRule = {

0 commit comments

Comments
 (0)