diff --git a/apps/cli-docs/src/fragments/commands/local.md b/apps/cli-docs/src/fragments/commands/local.md index c57d44973..5e9fea47d 100644 --- a/apps/cli-docs/src/fragments/commands/local.md +++ b/apps/cli-docs/src/fragments/commands/local.md @@ -213,6 +213,9 @@ Events with an exception type are `"type":"error"` records. Events without one, such as `captureMessage` calls and Python `logging` records, are `"type":"message"`. `-f error` returns both, so a script that keeps errors with `jq 'select(.type=="error")'` should also keep `"message"` if it wants them. +An event whose payload is not JSON is a `"type":"invalid"` record with +`"level":"invalid"`, in this stream and in `event list`. `-f error` still shows +it, but `--verify` does not count it as an event from your app. In JSON mode, event records are versioned NDJSON on standard output. Startup, connection, and shutdown messages stay on standard error, so an agent can pipe diff --git a/docs/cli/local-control-plane.md b/docs/cli/local-control-plane.md index 78cb5d3c3..d832de100 100644 --- a/docs/cli/local-control-plane.md +++ b/docs/cli/local-control-plane.md @@ -393,13 +393,16 @@ sampled function rows are not counted. Receiver ingestion bounds encoded bodies to 10 MiB and decoded bodies to 32 MiB. Accepted envelopes get 200 with `{"id":""}`, or `{}` when the header has no event ID, as Relay answers; sentry-elixir retries anything else. -Invalid compression returns 400, oversized bodies 413, unsupported media or +A body that is empty, whose first line is not a JSON object, or that fails to +decompress gets 400 with an `{"error":"…"}` reason, and the receiver keeps +nothing for it. Oversized bodies get 413, unsupported media or encoding 415, and temporary admission overload 503. SDKs drop an envelope that gets 413 without retrying, so `local run` and `local serve` print a warning in their tail when that happens, at most one line every five seconds. Drops in between are counted and printed as one line when the five seconds end. Session tails -get the notice from the daemon as a `sentry.local.oversized` stream event. Malformed envelopes remain -available for raw inspection and byte-exact download through their receiver IDs. +get the notice from the daemon as a `sentry.local.oversized` stream event. Envelopes whose items +are malformed remain available for raw inspection and byte-exact download through +their receiver IDs. An event item that is not JSON shows as `invalid`, not as an error. Receivers drop `http.client` spans and breadcrumbs for requests to their own loopback `/_local/` and `/stream` routes on the same port, which SDKs record for their own deliveries, and do not retain an envelope that has nothing else left. diff --git a/packages/cli/src/commands/local/control-plane.ts b/packages/cli/src/commands/local/control-plane.ts index 8d96427d2..0bc515f0d 100644 --- a/packages/cli/src/commands/local/control-plane.ts +++ b/packages/cli/src/commands/local/control-plane.ts @@ -572,7 +572,8 @@ export function createLocalControlPlane({ return result; }); if (outcome === 410) return closed(); - if (typeof outcome === "object") sessionStore.recordActivity(id); + if (typeof outcome === "object" && outcome.status === 200) + sessionStore.recordActivity(id); return ingestResponse(c, outcome); }; for (const path of SESSION_INGEST_PATHS) app.post(path, ingest); diff --git a/packages/cli/src/commands/local/envelope.ts b/packages/cli/src/commands/local/envelope.ts index 10ab2ea67..3e96da34c 100644 --- a/packages/cli/src/commands/local/envelope.ts +++ b/packages/cli/src/commands/local/envelope.ts @@ -418,8 +418,10 @@ export function withoutOwnDeliveries( * that DSN holds the ingest capability, and session envelopes reach holders of * the read capability, so drop the key. Only the header line is rewritten. */ -export function withoutDsnHeader(body: Buffer): Buffer { - const parsed = readEnvelopeHeader(body); +export function withoutDsnHeader( + body: Buffer, + parsed = readEnvelopeHeader(body), +): Buffer { if (!parsed || !("dsn" in parsed.header)) return body; delete parsed.header["dsn"]; return Buffer.concat([ @@ -432,20 +434,24 @@ export function withoutDsnHeader(body: Buffer): Buffer { * The envelope header's `event_id` as Relay prints it: 32 lowercase hex digits * without hyphens. Undefined when the header has no valid event id. */ -export function envelopeEventId(body: Buffer): string | undefined { - const eventId = readEnvelopeHeader(body)?.header["event_id"]; +export function envelopeEventId( + header: Record, +): string | undefined { + const eventId = header["event_id"]; if (typeof eventId !== "string") return; const simple = eventId.replaceAll("-", "").toLowerCase(); return /^[0-9a-f]{32}$/.test(simple) ? simple : undefined; } +/** The parsed first line of an envelope and where that line ends. */ +export type EnvelopeHeader = { header: Record; end: number }; + /** * Parse only the first line, without frame(): it would parse every item and - * reject envelopes that still have a usable header. + * reject envelopes that still have a usable header. Undefined when that line + * is not a JSON object, which Relay also rejects. */ -function readEnvelopeHeader( - body: Buffer, -): { header: Record; end: number } | undefined { +export function readEnvelopeHeader(body: Buffer): EnvelopeHeader | undefined { const newline = body.indexOf(10); const end = newline < 0 ? body.length : newline; let header: unknown; diff --git a/packages/cli/src/commands/local/event-kind.ts b/packages/cli/src/commands/local/event-kind.ts index 79df5a86c..d8789ab2e 100644 --- a/packages/cli/src/commands/local/event-kind.ts +++ b/packages/cli/src/commands/local/event-kind.ts @@ -30,6 +30,15 @@ export function readMessageText(value: unknown): string | undefined { return undefined; } +/** + * Whether an `event` item could not be decoded. The receiver keeps an item + * that is not JSON as `{ data }`, without the `type` it adds to every decoded + * item, so it is neither an exception nor a message. + */ +export function isUndecodedEvent(event: Record): boolean { + return !("type" in event) && typeof event["data"] === "string"; +} + /** How an event reads: its kind, thrown type, and the text to show for it. */ export type EventDescription = { kind: "exception" | "message" | undefined; diff --git a/packages/cli/src/commands/local/receiver-ingest.ts b/packages/cli/src/commands/local/receiver-ingest.ts index 61f1dc3a1..b534b0c22 100644 --- a/packages/cli/src/commands/local/receiver-ingest.ts +++ b/packages/cli/src/commands/local/receiver-ingest.ts @@ -5,6 +5,7 @@ import { logger } from "../../lib/logger.js"; import { createReceiverEnvelope, envelopeEventId, + readEnvelopeHeader, type ReceiverBuffer, withoutDsnHeader, withoutOwnDeliveries, @@ -28,10 +29,21 @@ type ReceiverState = { requests: Set>; }; /** - * Relay's body for an accepted envelope. SDKs such as sentry-elixir accept a + * An accepted envelope gets Relay's body. SDKs such as sentry-elixir accept a * delivery only on HTTP 200 with this JSON, and retry anything else. */ -type ReceiverAccepted = { id?: string }; +type ReceiverAccepted = { status: 200; body: { id?: string } }; +/** A body that is not an envelope: its JSON has the shape of Local's 410 body. */ +type ReceiverRejected = { status: 400; body: { error: string } }; +/** How the receiver answers a delivery: a JSON response or a bare status. */ +export type IngestResult = + | ReceiverAccepted + | ReceiverRejected + | 400 + | 410 + | 413 + | 415 + | 503; const receivers = new WeakMap(); const oversizedListeners = new WeakMap void>>(); @@ -52,22 +64,23 @@ export function onOversizedEnvelope( /** Tell this receiver's listeners when a delivery got HTTP 413. */ export function reportIngestStatus( buffer: ReceiverBuffer, - result: number | ReceiverAccepted, + result: IngestResult, ): void { if (result !== 413) return; for (const listener of oversizedListeners.get(buffer) ?? []) listener(); } -/** Answer an ingest request: 200 with the accepted JSON, otherwise the bare status. */ -export function ingestResponse( - c: Context, - result: ReceiverAccepted | 400 | 410 | 413 | 415 | 503, -): Response { - if (typeof result === "object") return c.json(result); +/** Answer an ingest request with its JSON body, or with the bare status. */ +export function ingestResponse(c: Context, result: IngestResult): Response { + if (typeof result === "object") return c.json(result.body, result.status); if (result === 503) c.header("Retry-After", "1"); return c.body(null, result); } +function rejected(error: string): ReceiverRejected { + return { status: 400, body: { error } }; +} + /** Stop consuming chunked input as soon as its encoded body exceeds the limit. */ export async function readReceiverBody( request: Request, @@ -175,7 +188,7 @@ export function ingestReceiverEnvelope( */ closed?: boolean; }, -): Promise { +): Promise> { const contentType = input.contentType?.split(";")[0]?.trim().toLowerCase(); if ( contentType && @@ -190,7 +203,7 @@ export function ingestReceiverEnvelope( if (state.pending.size >= MAX_PENDING) return Promise.resolve(503); const generation = state.generation; const operation = state.queue.then( - async (): Promise => { + async (): Promise> => { if (generation !== state.generation) return 503; let body = input.body; if (encoding && encoding !== "identity") { @@ -211,15 +224,22 @@ export function ingestReceiverEnvelope( "code" in error && error.code === "ERR_BUFFER_TOO_LARGE" ? 413 - : 400; + : rejected("The body could not be decompressed."); } } if (generation !== state.generation) return 503; if (body.length > MAX_DECODED_BYTES) return 413; if (input.closed) return 410; - const eventId = envelopeEventId(body); - const accepted = eventId ? { id: eventId } : {}; - if (input.dropDsnHeader) body = withoutDsnHeader(body); + // Reject bodies that are not envelopes, as Relay does, and retain nothing. + if (!body.length) return rejected("The envelope is empty."); + const header = readEnvelopeHeader(body); + if (!header) return rejected("The envelope header is not a JSON object."); + const eventId = envelopeEventId(header.header); + const accepted: ReceiverAccepted = { + status: 200, + body: eventId ? { id: eventId } : {}, + }; + if (input.dropDsnHeader) body = withoutDsnHeader(body, header); const delivery = input.receiverUrl ? withoutOwnDeliveries(body, input.receiverUrl) : body; diff --git a/packages/cli/src/lib/formatters/local.ts b/packages/cli/src/lib/formatters/local.ts index 5140c67bb..2c12ccba6 100644 --- a/packages/cli/src/lib/formatters/local.ts +++ b/packages/cli/src/lib/formatters/local.ts @@ -1,6 +1,9 @@ /** Tail formatters for the local dev server. */ -import { describeEvent } from "../../commands/local/event-kind.js"; +import { + describeEvent, + isUndecodedEvent, +} from "../../commands/local/event-kind.js"; import { exceptionValues, frameFile, @@ -377,12 +380,14 @@ type ExceptionValue = { * * `kind` is `message` for events with no typed exception: `captureMessage`, * Python `logging` records, and JavaScript messages that carry only a - * synthetic stack. It is `error` otherwise, with the exception type in - * `errorType` (`Error` when the event names none). + * synthetic stack. It is `invalid`, with level `invalid`, when the payload is + * not JSON, and `error` otherwise, with the exception type in `errorType` + * (`Error` when the event names none). */ type EventSummary = ( | { kind: "message" } | { kind: "error"; errorType: string } + | { kind: "invalid" } ) & { /** Event level (`fatal`, `error`, `warning`, `info`, `debug`); `error` when unset. */ level: string; @@ -396,6 +401,13 @@ type EventSummary = ( /** Summarize an `event` item for its tail line, JSON record, or `event list` entry. */ export function summarizeEvent(event: Record): EventSummary { + if (isUndecodedEvent(event)) { + return { + kind: "invalid", + level: "invalid", + text: "Event payload is not JSON", + }; + } // Exceptions are ordered oldest→newest; the last one is what was thrown. const last = exceptionValues(event["exception"]).at(-1) as | ExceptionValue @@ -1195,7 +1207,8 @@ function formatJsonObservation( /** * Format an `event` item as a JSON object, including the best stack frame. * Exceptions get `type: "error"` and an `error_type`; messages get - * `type: "message"` and no `error_type`. + * `type: "message"` and no `error_type`. An item that is not JSON gets + * `type: "invalid"` and `level: "invalid"`. */ function formatErrorJson( payload: Record, @@ -1539,7 +1552,8 @@ const NOT_TELEMETRY_ITEM_TYPES = new Set([ /** * Whether an envelope shows the app is set up: it holds an item the active * filters let through, or, with no filters, any item that is not - * housekeeping. + * housekeeping. An event that is not JSON never counts, even though the tail + * shows it under `-f error`. */ export function envelopeHasTelemetry( container: { @@ -1550,11 +1564,15 @@ export function envelopeHasTelemetry( activeFilters: ReadonlySet, ): boolean { const items = container.getParsedEnvelope()?.envelope[1] ?? []; - return items.some(([{ type }, payload]) => - activeFilters.size > 0 - ? isItemIncluded(type, activeFilters, payload as Record) - : type !== undefined && !NOT_TELEMETRY_ITEM_TYPES.has(type), - ); + return items.some(([{ type }, payload]) => { + const item = payload as Record; + if (ERROR_TYPES.has(type ?? "") && isUndecodedEvent(item)) { + return false; + } + return activeFilters.size > 0 + ? isItemIncluded(type, activeFilters, item) + : type !== undefined && !NOT_TELEMETRY_ITEM_TYPES.has(type); + }); } /** diff --git a/packages/cli/test/commands/local/control-plane.test.ts b/packages/cli/test/commands/local/control-plane.test.ts index 9b7c1dbf1..3104aae3e 100644 --- a/packages/cli/test/commands/local/control-plane.test.ts +++ b/packages/cli/test/commands/local/control-plane.test.ts @@ -267,6 +267,36 @@ describe("Local control plane", () => { expect(await gzipped.json()).toEqual({}); }); + test("session ingest answers 200 with the id, and 400 to bodies that are not envelopes", async () => { + const plane = createLocalControlPlane({ controlToken: CONTROL_TOKEN }); + const created = await plane.app.request("/_local/v1/sessions", { + method: "POST", + headers: controlHeaders(), + body: JSON.stringify({ label: "malformed", cwd: "/malformed" }), + }); + const { id, ingestUrl } = await created.json(); + const post = (body: string) => + plane.app.request(ingestUrl, { + method: "POST", + headers: { "Content-Type": "application/x-sentry-envelope" }, + body, + }); + const eventId = "0b6e5f9cb8d44f4e9a6f3e1c2d7a8b90"; + const valid = await post( + `{"event_id":"${eventId}"}\n{"type":"event"}\n{"message":"ok"}`, + ); + expect(valid.status).toBe(200); + expect(await valid.json()).toEqual({ id: eventId }); + for (const body of ["", '{not json\n{"type":"event"}\n{}']) { + const response = await post(body); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ error: expect.any(String) }); + } + expect(plane.sessionStore.getBuffer(id).read({ all: true })).toHaveLength( + 1, + ); + }); + test("replaces expired clientId sessions with usable fresh capabilities on creation", async () => { let now = 1000; const sessionStore = createLocalSessionStore({ now: () => now }); diff --git a/packages/cli/test/commands/local/receiver-ingest.test.ts b/packages/cli/test/commands/local/receiver-ingest.test.ts index 874a11703..9969692d9 100644 --- a/packages/cli/test/commands/local/receiver-ingest.test.ts +++ b/packages/cli/test/commands/local/receiver-ingest.test.ts @@ -26,7 +26,7 @@ test.each([1, 2])( await ingestReceiverEnvelope(retention.buffer, { body: Buffer.from(at(bodies, 0)), }), - ).toEqual({}); + ).toEqual({ status: 200, body: {} }); const frames: { id?: string; data: string }[] = []; const reader = retention.buffer.subscribe( buildSSEHandler({ @@ -43,7 +43,7 @@ test.each([1, 2])( }), ), ); - expect(statuses).toEqual(Array(7).fill({})); + expect(statuses).toEqual(Array(7).fill({ status: 200, body: {} })); await new Promise((resolve) => setImmediate(resolve)); expect( frames.map((frame) => JSON.parse(frame.data)[1][0][1].message), @@ -112,7 +112,7 @@ test("raw ingress assigns identity independently of an untrusted envelope header `{"__spotlight_envelope_id":"${forgedId}"}\n{"type":"event"}\n{}`, ); expect(await ingestReceiverEnvelope(retention.buffer, { body: raw })).toEqual( - {}, + { status: 200, body: {} }, ); const container = at(retention.buffer.read({ all: true }), 0); const id = receiverEnvelopeId(container); @@ -449,9 +449,9 @@ describe.each([false, true])("own ingest telemetry (scoped: %s)", (scoped) => { }); test.each([ - "not-json", - '1\n{"type":"event"}\n{}', - '[]\n{"type":"event"}\n{}', + "{}\nnot-an-item-header\n{}", + '{}\n{"type":"event","length":99}\n{}', + "{}\n[]\n{}", '{}\n{"type":"event"}\nfalse', ])( "retains malformed raw delivery %j with a downloadable stable ID", @@ -517,7 +517,7 @@ test("clear cancels preceding admissions and preserves live subscribers and sett await ingestReceiverEnvelope(retention.buffer, { body: Buffer.from(after), }), - ).toEqual({}); + ).toEqual({ status: 200, body: {} }); retention.buffer.stream(reader); retention.buffer.stream(reader); expect(seen).toEqual([after]); @@ -552,7 +552,7 @@ test.each(["clear", "reset"] as const)( await ingestReceiverEnvelope(retention.buffer, { body: Buffer.from(envelope), }), - ).toEqual({}); + ).toEqual({ status: 200, body: {} }); }, ); @@ -565,7 +565,10 @@ test("retention changes include preceding compressed admissions and preserve cur }), ); await expect(retention.resize(1)).rejects.toThrow(/2 retained envelopes/); - expect(await Promise.all(writes)).toEqual([{}, {}]); + expect(await Promise.all(writes)).toEqual([ + { status: 200, body: {} }, + { status: 200, body: {} }, + ]); const history = retention.buffer.read({ all: true }); const cursor = receiverEnvelopeId(at(history, 1)); const seen: string[] = []; @@ -596,7 +599,7 @@ test("close drains an admitted decode before its final SSE lifecycle frame", asy encoding: "gzip", }); plane.sessionStore.close(session.id); - expect(await writing).toEqual({}); + expect(await writing).toEqual({ status: 200, body: {} }); const text = await reading; expect(text).toContain("received"); expect(text.indexOf("received")).toBeLessThan( @@ -613,12 +616,15 @@ test("raw attachments remain byte exact and malformed SSE remains inspectable wi ), attachment, ]); - expect(await ingestReceiverEnvelope(retention.buffer, { body })).toEqual({}); + expect(await ingestReceiverEnvelope(retention.buffer, { body })).toEqual({ + status: 200, + body: {}, + }); expect(at(retention.buffer.read({ all: true }), 0).getData()).toEqual(body); - const malformed = Buffer.from("not-an-envelope"); + const malformed = Buffer.from("{}\nnot-an-item-header\n"); expect( await ingestReceiverEnvelope(retention.buffer, { body: malformed }), - ).toEqual({}); + ).toEqual({ status: 200, body: {} }); const latest = at(retention.buffer.read({ all: true }), 0); const frames: { id?: string; data: string }[] = []; const handler = buildSSEHandler({ @@ -645,7 +651,10 @@ test("malformed exception metadata cannot break raw filename queries", async () const body = Buffer.from( '{}\n{"type":"event"}\n{"exception":{"values":"malformed"}}', ); - expect(await ingestReceiverEnvelope(retention.buffer, { body })).toEqual({}); + expect(await ingestReceiverEnvelope(retention.buffer, { body })).toEqual({ + status: 200, + body: {}, + }); expect(retention.buffer.read({ filename: "app.ts" })).toEqual([]); expect(at(retention.buffer.read({ all: true }), 0).getData()).toEqual(body); }); @@ -660,7 +669,7 @@ test("SSE falls back to raw data if deeply nested decoded JSON cannot serialize" "}"; expect( await ingestReceiverEnvelope(retention.buffer, { body: Buffer.from(raw) }), - ).toEqual({}); + ).toEqual({ status: 200, body: {} }); const frames: { data: string }[] = []; buildSSEHandler({ writeSSE: async (frame) => { diff --git a/packages/cli/test/commands/local/run.test.ts b/packages/cli/test/commands/local/run.test.ts index 59d9f025e..9773f2fbc 100644 --- a/packages/cli/test/commands/local/run.test.ts +++ b/packages/cli/test/commands/local/run.test.ts @@ -1397,6 +1397,64 @@ describe("sentry local run --verify receiver", () => { } }); + /** An app that posts one envelope with these item lines, then idles. */ + function sendItemLines(...lines: string[]): string[] { + return [ + "-e", + `fetch(process.env.SENTRY_SPOTLIGHT, { method: 'POST', body: ${JSON.stringify(["{}", ...lines].join("\n"))} }).then(() => setTimeout(() => {}, 30000));`, + ]; + } + const invalidEvent = ['{"type":"event","length":8}', "not-json"]; + const session = ['{"type":"session"}', "{}"]; + const transaction = ['{"type":"transaction"}', '{"type":"transaction"}']; + const validEvent = ['{"type":"event"}', '{"message":"verify me"}']; + + async function verifyWithItems( + filter: NonNullable[0]["filter"]>, + lines: string[], + ): Promise { + const warn = vi.spyOn(logger, "warn").mockImplementation(() => {}); + const info = vi.spyOn(logger, "info").mockImplementation(() => {}); + try { + const func = (await runCommand.loader()) as unknown as RunFunc; + return await func + .call( + makeContext(), + { port: 0, host: "127.0.0.1", verify: true, timeout: 2, filter }, + process.execPath, + ...sendItemLines(...lines), + ) + .catch((err: unknown) => err); + } finally { + warn.mockRestore(); + info.mockRestore(); + } + } + + test.each([ + ["alone", [], invalidEvent], + ["with a session", [], [...invalidEvent, ...session]], + ["with a session under -f error", ["error"], [...invalidEvent, ...session]], + [ + "with filtered-out telemetry", + ["error"], + [...invalidEvent, ...transaction], + ], + ] as const)( + "does not verify on an event that is not JSON %s", + async (_name, filter, lines) => { + const error = await verifyWithItems([...filter], [...lines]); + expect(error).toBeInstanceOf(VerifyFailedError); + expect((error as Error).message).toContain("Verification timed out"); + }, + ); + + test("verifies on a valid error next to an event that is not JSON", async () => { + expect( + await verifyWithItems(["error"], [...invalidEvent, ...validEvent]), + ).toBeUndefined(); + }); + test.each([ { sent: ["session", "client_report"], diff --git a/packages/cli/test/commands/local/server.test.ts b/packages/cli/test/commands/local/server.test.ts index c64ccaadc..c85ec0c3c 100644 --- a/packages/cli/test/commands/local/server.test.ts +++ b/packages/cli/test/commands/local/server.test.ts @@ -767,6 +767,48 @@ describe("buildApp", () => { expect(buffer.read({ all: true })).toEqual([]); }); + test("ingest answers 200 with the id, and 400 to bodies that are not envelopes", async () => { + const buffer = createLocalRetentionBuffer(10).buffer; + const app = buildApp(buffer); + const post = ( + body: string | ReturnType, + encoding?: string, + ) => + app.request("/stream", { + method: "POST", + headers: { + "Content-Type": SENTRY_CONTENT_TYPE, + ...(encoding ? { "Content-Encoding": encoding } : {}), + }, + body, + }); + for (const body of [ + "", + '{not json\n{"type":"event"}\n{}', + '[]\n{"type":"event"}\n{}', + "not-an-envelope", + ]) { + const res = await post(body); + expect(res.status, JSON.stringify(body)).toBe(400); + expect(await res.json()).toEqual({ error: expect.any(String) }); + } + expect((await post(gzipSync("{not json\n"), "gzip")).status).toBe(400); + expect(buffer.read({ all: true })).toEqual([]); + const id = "9ec79c33ec9942ab8353589fcb2e04dc"; + const valid = await post( + `{"event_id":"${id}"}\n{"type":"event"}\n{"message":"ok"}`, + ); + expect(valid.status).toBe(200); + expect(await valid.json()).toEqual({ id }); + // Like Relay, unknown item types and items without `length` are fine. + const unknown = await post( + '{}\n{"type":"future_item"}\n{"x":1}\n{"type":"event"}\n{"message":"ok"}', + ); + expect(unknown.status).toBe(200); + expect(await unknown.json()).toEqual({}); + expect(buffer.read({ all: true })).toHaveLength(2); + }); + test("ingest answers like Relay, with the envelope header event_id", async () => { const buffer = createLocalRetentionBuffer(10).buffer; const app = buildApp(buffer); diff --git a/packages/cli/test/lib/formatters/local.test.ts b/packages/cli/test/lib/formatters/local.test.ts index ddf85cb06..43292761a 100644 --- a/packages/cli/test/lib/formatters/local.test.ts +++ b/packages/cli/test/lib/formatters/local.test.ts @@ -12,6 +12,8 @@ import { envelopeHasTelemetry, extractTraceId, formatAttributeTable, + formatEnvelopeLines, + formatEnvelopeLinesJson, formatErrorItem, formatItem, formatItemJson, @@ -24,6 +26,8 @@ import { isItemIncluded, itemTypeToFilterCategory, } from "../../../src/lib/formatters/local.js"; +import { createReceiverEnvelope } from "../../../src/commands/local/envelope.js"; +import { summarizeEnvelope } from "../../../src/commands/local/event-summary.js"; import { parseEventTimestamp } from "../../../src/commands/local/timestamp.js"; import { stripAnsi } from "../../../src/lib/formatters/plain-detect.js"; import { at } from "../../helpers.js"; @@ -1499,6 +1503,22 @@ describe("sentry-python ISO 8601 timestamps", () => { }); }); +test("an event item that is not JSON never shows as an error", () => { + const container = createReceiverEnvelope({ + body: Buffer.from('{}\n{"type":"event"}\nnot-json\n'), + }); + const parsed = container.getParsedEnvelope(); + if (!parsed) throw new Error("expected the envelope to decode"); + const [line] = formatEnvelopeLines(container, new Set()); + expect(stripAnsi(line ?? "")).not.toMatch(/ERROR|Unknown error/); + expect(stripAnsi(line ?? "")).toContain("[INVALID]"); + const [json] = formatEnvelopeLinesJson(container, new Set()); + expect(JSON.parse(json ?? "{}")).toMatchObject({ type: "invalid" }); + expect(summarizeEnvelope(parsed)).toMatchObject({ type: "invalid" }); + // The tail keeps it under -f error. + expect(formatEnvelopeLines(container, new Set(["error"]))).toHaveLength(1); +}); + describe("envelopeHasTelemetry", () => { const envelope = (...items: [string, unknown][]) => ({ getParsedEnvelope: () => ({