From 657b5512831dfe714e79f7d68cdf3e436534a74e Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:59:39 +0000 Subject: [PATCH 1/3] fix(cli): Answer accepted envelopes with 200 and the event ID sentry-elixir only treats a delivery as sent when it gets HTTP 200 with a JSON body that has an id. It retries anything else at 1, 2, 4 and 8 seconds, which blocks its queue, so one event arrived five times and the rest were lost. Answer the way Relay does: 200 with {"id":""} from the envelope header, or {} when there is none, on every plain and session ingest path. Other status codes are unchanged. Co-Authored-By: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com> --- docs/cli/local-control-plane.md | 2 + .../cli/src/commands/local/control-plane.ts | 13 ++-- packages/cli/src/commands/local/envelope.ts | 40 +++++++++--- .../cli/src/commands/local/receiver-ingest.ts | 20 ++++-- packages/cli/src/commands/local/server.ts | 9 +-- .../test/commands/local/control-plane.test.ts | 54 +++++++++++++--- .../test/commands/local/management.test.ts | 4 +- .../commands/local/receiver-ingest.test.ts | 42 ++++++------ .../cli/test/commands/local/server.test.ts | 64 +++++++++++-------- .../commands/local/session-lifecycle.test.ts | 4 +- packages/cli/test/e2e/local.test.ts | 6 +- 11 files changed, 171 insertions(+), 87 deletions(-) diff --git a/docs/cli/local-control-plane.md b/docs/cli/local-control-plane.md index 04a530ce4..59496d3eb 100644 --- a/docs/cli/local-control-plane.md +++ b/docs/cli/local-control-plane.md @@ -385,6 +385,8 @@ segments, like the tail's `[N spans]`: the transaction or segment span itself an 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 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 diff --git a/packages/cli/src/commands/local/control-plane.ts b/packages/cli/src/commands/local/control-plane.ts index cc7fc2202..c92c371ae 100644 --- a/packages/cli/src/commands/local/control-plane.ts +++ b/packages/cli/src/commands/local/control-plane.ts @@ -509,7 +509,7 @@ export function createLocalControlPlane({ // Close can occur while the body is being read or decoded. Tracking the // request lets close drain it, so a 413 reaches readers before the closing // frame. Retention still stops at the close. - const status = await trackReceiverRequest(buffer, async () => { + const outcome = await trackReceiverRequest(buffer, async () => { const body = await readReceiverBody(c.req.raw, MAX_BODY_BYTES); const result = typeof body === "number" @@ -530,10 +530,13 @@ export function createLocalControlPlane({ reportIngestStatus(buffer, result); return result; }); - if (status === 410) return closed(); - if (status === 503) c.header("Retry-After", "1"); - if (status === 204) sessionStore.recordActivity(reference); - return c.body(null, status); + if (typeof outcome === "object") { + sessionStore.recordActivity(reference); + return c.json(outcome); + } + if (outcome === 410) return closed(); + if (outcome === 503) c.header("Retry-After", "1"); + return c.body(null, outcome); }; for (const path of SESSION_INGEST_PATHS) app.post(path, ingest); app.post(`${CONTROL_PLANE_PREFIX}/sessions/:id/stream`, ingest); diff --git a/packages/cli/src/commands/local/envelope.ts b/packages/cli/src/commands/local/envelope.ts index 629b90a76..10ab2ea67 100644 --- a/packages/cli/src/commands/local/envelope.ts +++ b/packages/cli/src/commands/local/envelope.ts @@ -419,8 +419,33 @@ export function withoutOwnDeliveries( * the read capability, so drop the key. Only the header line is rewritten. */ export function withoutDsnHeader(body: Buffer): Buffer { - // Only the first line is needed, so skip frame(): it would parse every item - // and reject envelopes that still have a usable header. + const parsed = readEnvelopeHeader(body); + if (!parsed || !("dsn" in parsed.header)) return body; + delete parsed.header["dsn"]; + return Buffer.concat([ + Buffer.from(JSON.stringify(parsed.header)), + body.subarray(parsed.end), + ]); +} + +/** + * 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"]; + if (typeof eventId !== "string") return; + const simple = eventId.replaceAll("-", "").toLowerCase(); + return /^[0-9a-f]{32}$/.test(simple) ? simple : undefined; +} + +/** + * Parse only the first line, without frame(): it would parse every item and + * reject envelopes that still have a usable header. + */ +function readEnvelopeHeader( + body: Buffer, +): { header: Record; end: number } | undefined { const newline = body.indexOf(10); const end = newline < 0 ? body.length : newline; let header: unknown; @@ -433,15 +458,10 @@ export function withoutDsnHeader(body: Buffer): Buffer { ); } catch { // Malformed envelopes stay byte-exact for raw inspection. - logger.debug("Local receiver kept an undecodable envelope header."); - return body; + logger.debug("Local receiver could not parse an envelope header."); + return; } - if (!isEnvelopeObject(header) || !("dsn" in header)) return body; - delete header["dsn"]; - return Buffer.concat([ - Buffer.from(JSON.stringify(header)), - body.subarray(end), - ]); + return isEnvelopeObject(header) ? { header, end } : undefined; } /** Retain raw bytes synchronously; decode lazily without allowing parse errors out. */ diff --git a/packages/cli/src/commands/local/receiver-ingest.ts b/packages/cli/src/commands/local/receiver-ingest.ts index bd2989343..3d1f65df9 100644 --- a/packages/cli/src/commands/local/receiver-ingest.ts +++ b/packages/cli/src/commands/local/receiver-ingest.ts @@ -3,6 +3,7 @@ import { brotliDecompress, gunzip, inflate } from "node:zlib"; import { logger } from "../../lib/logger.js"; import { createReceiverEnvelope, + envelopeEventId, type ReceiverBuffer, withoutDsnHeader, withoutOwnDeliveries, @@ -25,6 +26,11 @@ type ReceiverState = { /** Requests still reading their body or reporting their status. */ requests: Set>; }; +/** + * Relay's body for an accepted envelope. SDKs such as sentry-elixir accept a + * delivery only on HTTP 200 with this JSON, and retry anything else. + */ +type ReceiverAccepted = { id?: string }; const receivers = new WeakMap(); const oversizedListeners = new WeakMap void>>(); @@ -45,9 +51,9 @@ export function onOversizedEnvelope( /** Tell this receiver's listeners when a delivery got HTTP 413. */ export function reportIngestStatus( buffer: ReceiverBuffer, - status: number, + result: number | ReceiverAccepted, ): void { - if (status !== 413) return; + if (result !== 413) return; for (const listener of oversizedListeners.get(buffer) ?? []) listener(); } @@ -158,7 +164,7 @@ export function ingestReceiverEnvelope( */ closed?: boolean; }, -): Promise<204 | 400 | 410 | 413 | 415 | 503> { +): Promise { const contentType = input.contentType?.split(";")[0]?.trim().toLowerCase(); if ( contentType && @@ -173,7 +179,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<204 | 400 | 410 | 413 | 503> => { + async (): Promise => { if (generation !== state.generation) return 503; let body = input.body; if (encoding && encoding !== "identity") { @@ -200,12 +206,14 @@ export function ingestReceiverEnvelope( 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); const delivery = input.receiverUrl ? withoutOwnDeliveries(body, input.receiverUrl) : body; // Envelopes with only Local's own delivery telemetry use no retention. - if (!delivery) return 204; + if (!delivery) return accepted; buffer.put( createReceiverEnvelope({ body: delivery, @@ -213,7 +221,7 @@ export function ingestReceiverEnvelope( userAgent: input.userAgent, }), ); - return 204; + return accepted; }, ); state.pending.add(operation); diff --git a/packages/cli/src/commands/local/server.ts b/packages/cli/src/commands/local/server.ts index f4ead07b3..c6e5105b7 100644 --- a/packages/cli/src/commands/local/server.ts +++ b/packages/cli/src/commands/local/server.ts @@ -516,7 +516,7 @@ export function buildApp( const contentEncoding = c.req.header("content-encoding"); const userAgent = c.req.header("user-agent"); - const status = await ingestReceiverEnvelope(buffer, { + const result = await ingestReceiverEnvelope(buffer, { body, encoding: contentEncoding, contentType, @@ -524,9 +524,10 @@ export function buildApp( userAgent, }); - reportIngestStatus(buffer, status); - if (status === 503) c.header("Retry-After", "1"); - return c.body(null, status); + reportIngestStatus(buffer, result); + if (typeof result === "object") return c.json(result); + if (result === 503) c.header("Retry-After", "1"); + return c.body(null, result); }; app.post("/stream", ingest); diff --git a/packages/cli/test/commands/local/control-plane.test.ts b/packages/cli/test/commands/local/control-plane.test.ts index 76c34cdd9..7b3f5f1e7 100644 --- a/packages/cli/test/commands/local/control-plane.test.ts +++ b/packages/cli/test/commands/local/control-plane.test.ts @@ -230,6 +230,42 @@ describe("Local control plane", () => { ); }); + test("session ingest answers like Relay on every ingest path", async () => { + const plane = createLocalControlPlane({ controlToken: CONTROL_TOKEN }); + const created = await plane.app.request("/_local/v1/sessions", { + method: "POST", + headers: controlHeaders(), + body: JSON.stringify({ label: "phoenix", cwd: "/phoenix" }), + }); + const { ingestUrl } = await created.json(); + const id = "0b6e5f9cb8d44f4e9a6f3e1c2d7a8b90"; + const envelope = `{"event_id":"${id}"}\n{"type":"event"}\n{"message":"boom"}`; + for (const url of [ + ingestUrl, + `${ingestUrl}/stream`, + `${ingestUrl}/api/0/envelope/`, + `${ingestUrl}/api/0/envelope`, + ]) { + const response = await plane.app.request(url, { + method: "POST", + headers: { "Content-Type": "application/x-sentry-envelope" }, + body: envelope, + }); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ id }); + } + const gzipped = await plane.app.request(ingestUrl, { + method: "POST", + headers: { + "Content-Type": "application/x-sentry-envelope", + "Content-Encoding": "gzip", + }, + body: gzipSync('{}\n{"type":"log"}\n{"items":[]}'), + }); + expect(gzipped.status).toBe(200); + expect(await gzipped.json()).toEqual({}); + }); + test("replaces expired clientId sessions with usable fresh capabilities on creation", async () => { let now = 1000; const sessionStore = createLocalSessionStore({ now: () => now }); @@ -267,7 +303,7 @@ describe("Local control plane", () => { headers: { "Content-Type": "application/x-sentry-envelope" }, body: '{}\n{"type":"event"}\n{"event_id":"fresh","message":"fresh capture"}', }); - expect(ingested.status).toBe(204); + expect(ingested.status).toBe(200); expect( sessionStore.getBuffer(replacement.id).read({ all: true }), ).toHaveLength(1); @@ -546,7 +582,7 @@ describe("Local control plane", () => { headers: { "Content-Type": "application/x-sentry-envelope" }, body: envelope, }); - expect(ingested.status).toBe(204); + expect(ingested.status).toBe(200); expect( controlPlane.sessionStore.getBuffer(session.id).read({ all: true }), ).toHaveLength(1); @@ -579,7 +615,7 @@ describe("Local control plane", () => { // `/api//envelope/` from a DSN. for (const suffix of ["/stream", "/api/0/envelope/", "/api/0/envelope"]) { expect((await post(`${ingest}/${caps.ingest}${suffix}`)).status).toBe( - 204, + 200, ); expect((await post(`${ingest}/wrong${suffix}`)).status).toBe(401); expect((await post(`${ingest}/${caps.stream}${suffix}`)).status).toBe( @@ -640,7 +676,7 @@ describe("Local control plane", () => { body, }, ); - expect(posted.status).toBe(204); + expect(posted.status).toBe(200); } const stored = plane.sessionStore @@ -838,7 +874,7 @@ describe("Local control plane", () => { .join("\n"), }, ); - expect(response.status).toBe(204); + expect(response.status).toBe(200); } const listed = await plane.app.request( @@ -876,7 +912,7 @@ describe("Local control plane", () => { body: lines.map((line) => JSON.stringify(line)).join("\n"), }, ); - expect(response.status).toBe(204); + expect(response.status).toBe(200); }; const before = Date.now(); @@ -1088,7 +1124,7 @@ describe("Local control plane", () => { .join("\n"), }, ); - expect(response.status).toBe(204); + expect(response.status).toBe(200); const listed = await plane.app.request( `/_local/v1/sessions/${session.id}/events`, { headers: controlHeaders() }, @@ -1264,7 +1300,7 @@ describe("Local daemon receiver compatibility", () => { ), }, ); - expect(response.status).toBe(204); + expect(response.status).toBe(200); const events = await plane.app.request( `/_local/v1/sessions/${session.id}/events/compressed`, { headers: controlHeaders() }, @@ -1292,7 +1328,7 @@ describe("Local daemon receiver compatibility", () => { body: '{"event_id":"browser"}\n{"type":"event"}\n{"message":"browser SDK"}', }, ); - expect(ingested.status).toBe(204); + expect(ingested.status).toBe(200); const response = await plane.app.request( `/_local/v1/sessions/${session.id}/events/browser`, { headers: controlHeaders() }, diff --git a/packages/cli/test/commands/local/management.test.ts b/packages/cli/test/commands/local/management.test.ts index fe70baa0a..fe7d0eb8d 100644 --- a/packages/cli/test/commands/local/management.test.ts +++ b/packages/cli/test/commands/local/management.test.ts @@ -88,7 +88,7 @@ async function ingestEvent( body: `${JSON.stringify({ event_id: eventId })}\n{"type":"event"}\n${JSON.stringify({ event_id: eventId, level: "error", message })}`, }, ); - expect(response.status).toBe(204); + expect(response.status).toBe(200); } /** Send one replay segment envelope; its event ID is `:`. */ @@ -116,7 +116,7 @@ async function ingestReplaySegment( .join("\n"), }, ); - expect(response.status).toBe(204); + expect(response.status).toBe(200); } /** Run `local session view` and return what it throws. */ diff --git a/packages/cli/test/commands/local/receiver-ingest.test.ts b/packages/cli/test/commands/local/receiver-ingest.test.ts index 1191ca185..874a11703 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)), }), - ).toBe(204); + ).toEqual({}); 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(204)); + expect(statuses).toEqual(Array(7).fill({})); await new Promise((resolve) => setImmediate(resolve)); expect( frames.map((frame) => JSON.parse(frame.data)[1][0][1].message), @@ -111,8 +111,8 @@ test("raw ingress assigns identity independently of an untrusted envelope header const raw = Buffer.from( `{"__spotlight_envelope_id":"${forgedId}"}\n{"type":"event"}\n{}`, ); - expect(await ingestReceiverEnvelope(retention.buffer, { body: raw })).toBe( - 204, + expect(await ingestReceiverEnvelope(retention.buffer, { body: raw })).toEqual( + {}, ); const container = at(retention.buffer.read({ all: true }), 0); const id = receiverEnvelopeId(container); @@ -177,7 +177,7 @@ describe.each([false, true])("bounded receiver (scoped: %s)", (scoped) => { headers: contentType ? { "Content-Type": contentType } : {}, body: new Uint8Array(Buffer.from(envelope)), }); - expect(response.status).toBe(204); + expect(response.status).toBe(200); expect(fixture.buffer.read({ all: true })).toHaveLength(1); expect(at(fixture.buffer.read({ all: true }), 0).getContentType()).toBe( "application/x-sentry-envelope", @@ -291,7 +291,7 @@ describe.each([false, true])("own ingest telemetry (scoped: %s)", (scoped) => { fixture, spanEnvelope([fetchSpan("2222222222222222", self)]), ); - expect(response.status).toBe(204); + expect(response.status).toBe(200); // Legacy standalone spans name the full URL and keep it in `data`. const legacy = JSON.stringify({ op: "http.client", @@ -301,7 +301,7 @@ describe.each([false, true])("own ingest telemetry (scoped: %s)", (scoped) => { data: { "http.method": "POST", url: self }, }); expect((await post(fixture, `{}\n{"type":"span"}\n${legacy}`)).status).toBe( - 204, + 200, ); expect(fixture.buffer.read({ all: true })).toHaveLength(0); }); @@ -321,7 +321,7 @@ describe.each([false, true])("own ingest telemetry (scoped: %s)", (scoped) => { }, ]), ); - expect(response.status).toBe(204); + expect(response.status).toBe(200); const container = at(fixture.buffer.read({ all: true }), 0); const [, items] = container.getParsedEnvelope()!.envelope; expect(items).toHaveLength(1); @@ -337,7 +337,7 @@ describe.each([false, true])("own ingest telemetry (scoped: %s)", (scoped) => { test("keeps a malformed envelope that mentions its routes byte-exact", async () => { const fixture = receiver(scoped); const body = `{}\n{"type":"span"}\n{"name":"POST ${receiverOrigin}${fixture.path}"`; - expect((await post(fixture, body)).status).toBe(204); + expect((await post(fixture, body)).status).toBe(200); const container = at(fixture.buffer.read({ all: true }), 0); expect(container.getData().toString()).toBe(body); }); @@ -367,7 +367,7 @@ describe.each([false, true])("own ingest telemetry (scoped: %s)", (scoped) => { '{"type":"event"}', event, ].join("\n"); - expect((await post(fixture, body)).status).toBe(204); + expect((await post(fixture, body)).status).toBe(200); const container = at(fixture.buffer.read({ all: true }), 0); expect(container.getData().toString()).not.toContain(self); const parsedItems = container.getParsedEnvelope()!.envelope[1]; @@ -434,7 +434,7 @@ describe.each([false, true])("own ingest telemetry (scoped: %s)", (scoped) => { `{"type":"transaction","length":${Buffer.byteLength(transaction)}}`, transaction, ].join("\n"); - expect((await post(fixture, body)).status).toBe(204); + expect((await post(fixture, body)).status).toBe(200); const container = at(fixture.buffer.read({ all: true }), 0); expect(container.getData().toString()).not.toContain(self); const parsedItems2 = container.getParsedEnvelope()!.envelope[1]; @@ -465,7 +465,7 @@ test.each([ body, }); - expect(response.status).toBe(204); + expect(response.status).toBe(200); const headers = { Authorization: "Bearer raw-test" }; const base = `/_local/v1/sessions/${session.id}`; const listing = await plane.app.request(`${base}/envelopes`, { headers }); @@ -494,7 +494,7 @@ test.each([ headers: { "Content-Type": "application/x-sentry-envelope" }, body: envelope, }); - expect(accepted.status).toBe(204); + expect(accepted.status).toBe(200); expect( plane.sessionStore.getBuffer(session.id).read({ all: true }), ).toHaveLength(2); @@ -517,7 +517,7 @@ test("clear cancels preceding admissions and preserves live subscribers and sett await ingestReceiverEnvelope(retention.buffer, { body: Buffer.from(after), }), - ).toBe(204); + ).toEqual({}); 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), }), - ).toBe(204); + ).toEqual({}); }, ); @@ -565,7 +565,7 @@ 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([204, 204]); + expect(await Promise.all(writes)).toEqual([{}, {}]); const history = retention.buffer.read({ all: true }); const cursor = receiverEnvelopeId(at(history, 1)); const seen: string[] = []; @@ -596,7 +596,7 @@ test("close drains an admitted decode before its final SSE lifecycle frame", asy encoding: "gzip", }); plane.sessionStore.close(session.id); - expect(await writing).toBe(204); + expect(await writing).toEqual({}); const text = await reading; expect(text).toContain("received"); expect(text.indexOf("received")).toBeLessThan( @@ -613,12 +613,12 @@ test("raw attachments remain byte exact and malformed SSE remains inspectable wi ), attachment, ]); - expect(await ingestReceiverEnvelope(retention.buffer, { body })).toBe(204); + expect(await ingestReceiverEnvelope(retention.buffer, { body })).toEqual({}); expect(at(retention.buffer.read({ all: true }), 0).getData()).toEqual(body); const malformed = Buffer.from("not-an-envelope"); expect( await ingestReceiverEnvelope(retention.buffer, { body: malformed }), - ).toBe(204); + ).toEqual({}); const latest = at(retention.buffer.read({ all: true }), 0); const frames: { id?: string; data: string }[] = []; const handler = buildSSEHandler({ @@ -645,7 +645,7 @@ 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 })).toBe(204); + expect(await ingestReceiverEnvelope(retention.buffer, { body })).toEqual({}); expect(retention.buffer.read({ filename: "app.ts" })).toEqual([]); expect(at(retention.buffer.read({ all: true }), 0).getData()).toEqual(body); }); @@ -660,7 +660,7 @@ test("SSE falls back to raw data if deeply nested decoded JSON cannot serialize" "}"; expect( await ingestReceiverEnvelope(retention.buffer, { body: Buffer.from(raw) }), - ).toBe(204); + ).toEqual({}); const frames: { data: string }[] = []; buildSSEHandler({ writeSSE: async (frame) => { diff --git a/packages/cli/test/commands/local/server.test.ts b/packages/cli/test/commands/local/server.test.ts index 6c20fe88e..3bc5e331d 100644 --- a/packages/cli/test/commands/local/server.test.ts +++ b/packages/cli/test/commands/local/server.test.ts @@ -8,6 +8,7 @@ import { createLocalControlPlane } from "../../../src/commands/local/control-plane.js"; import { createLocalRetentionBuffer } from "../../../src/commands/local/retention-buffer.js"; import { logger } from "../../../src/lib/logger.js"; +import { gzipSync } from "node:zlib"; import { Hono } from "hono"; import { afterEach, @@ -765,32 +766,45 @@ describe("buildApp", () => { expect(buffer.read({ all: true })).toEqual([]); }); - test("ingest endpoint accepts envelopes and returns 204", async () => { + test("ingest answers like Relay, with the envelope header event_id", async () => { const buffer = createLocalRetentionBuffer(10).buffer; const app = buildApp(buffer); - - const envelope = - '{"sdk":{"name":"sentry.node"}}\n{"type":"event"}\n{"message":"test"}'; - const res = await app.request("/stream", { - method: "POST", - headers: { "Content-Type": SENTRY_CONTENT_TYPE }, - body: envelope, - }); - expect(res.status).toBe(204); - }); - - test("ingest via /api/:projectId/envelope/ returns 204", async () => { - const buffer = createLocalRetentionBuffer(10).buffer; - const app = buildApp(buffer); - - const envelope = - '{"sdk":{"name":"sentry.node"}}\n{"type":"event"}\n{"message":"test"}'; - const res = await app.request("/api/123/envelope/", { - method: "POST", - headers: { "Content-Type": SENTRY_CONTENT_TYPE }, - body: envelope, - }); - expect(res.status).toBe(204); + const id = "9ec79c33ec9942ab8353589fcb2e04dc"; + const withId = `{"event_id":"${id}","sdk":{"name":"sentry.elixir"}}\n{"type":"event"}\n{"message":"test"}`; + const post = ( + path: string, + body: string | ReturnType, + encoding?: string, + ) => + app.request(path, { + method: "POST", + headers: { + "Content-Type": SENTRY_CONTENT_TYPE, + ...(encoding ? { "Content-Encoding": encoding } : {}), + }, + body, + }); + for (const path of ["/stream", "/api/0/envelope/", "/api/0/envelope"]) { + const res = await post(path, withId); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toContain("application/json"); + expect(await res.json()).toEqual({ id }); + } + const gzipped = await post("/stream", gzipSync(withId), "gzip"); + expect(await gzipped.json()).toEqual({ id }); + // Relay prints the id without hyphens. + const hyphenated = await post( + "/stream", + '{"event_id":"9EC79C33-EC99-42AB-8353-589FCB2E04DC"}\n{"type":"event"}\n{}', + ); + expect(await hyphenated.json()).toEqual({ id }); + // Envelopes without an event, such as sessions or logs, get an empty object. + const withoutId = await post( + "/stream", + '{"sdk":{"name":"sentry.node"}}\n{"type":"session"}\n{}', + ); + expect(withoutId.status).toBe(200); + expect(await withoutId.json()).toEqual({}); }); test("plain receivers keep the envelope header dsn", async () => { @@ -803,7 +817,7 @@ describe("buildApp", () => { headers: { "Content-Type": SENTRY_CONTENT_TYPE }, body: envelope, }); - expect(res.status).toBe(204); + expect(res.status).toBe(200); expect(buffer.read({ all: true })[0]?.getData().toString("utf8")).toBe( envelope, ); diff --git a/packages/cli/test/commands/local/session-lifecycle.test.ts b/packages/cli/test/commands/local/session-lifecycle.test.ts index f22429d38..2070d0495 100644 --- a/packages/cli/test/commands/local/session-lifecycle.test.ts +++ b/packages/cli/test/commands/local/session-lifecycle.test.ts @@ -54,7 +54,7 @@ async function fixture() { describe("Local session lifecycle", () => { test("close freezes ingestion and expiry while preserving saved envelopes", async () => { const f = await fixture(); - expect((await f.ingest("saved")).status).toBe(204); + expect((await f.ingest("saved")).status).toBe(200); const closed = await (await f.action("close")).json(); f.advance(1000); expect((await f.ingest("late")).status).toBe(410); @@ -163,7 +163,7 @@ describe("Local session lifecycle", () => { // delivery is decoding. await new Promise((resolve) => setImmediate(resolve)); await f.action("close"); - expect((await pending).status).toBe(204); + expect((await pending).status).toBe(200); expect( f.store.getRetention(f.session.id).getSettings().retainedEnvelopes, ).toBe(1); diff --git a/packages/cli/test/e2e/local.test.ts b/packages/cli/test/e2e/local.test.ts index 08b75d7ac..5e88ec9c6 100644 --- a/packages/cli/test/e2e/local.test.ts +++ b/packages/cli/test/e2e/local.test.ts @@ -93,7 +93,7 @@ async function ingest(session: Session, eventId: string, message: string) { headers: { "Content-Type": "application/x-sentry-envelope" }, body: `${JSON.stringify({ event_id: eventId })}\n{"type":"event"}\n${JSON.stringify({ event_id: eventId, message })}`, }); - expect(response.status).toBe(204); + expect(response.status).toBe(200); } afterEach(async () => { @@ -698,7 +698,7 @@ describe("Local daemon E2E", () => { .map((value) => JSON.stringify(value)) .join("\n"), }); - expect(response.status).toBe(204); + expect(response.status).toBe(200); } const listed = await cli("event", "list", session.id); expect(listed.exitCode, listed.stderr).toBe(0); @@ -752,7 +752,7 @@ describe("Local daemon E2E", () => { if (url !== process.env.VITE_SENTRY_SPOTLIGHT) process.exit(2); fetch(url, {method:'POST', headers:{'Content-Type':'application/x-sentry-envelope'}, body:'{"event_id":"${"c".repeat(32)}"}\\n{"type":"event"}\\n{"message":"wrapped app"}'}) - .then(r => {if (r.status !== 204) process.exitCode=3; console.error('app completed');}) + .then(async r => {const b = await r.json(); if (r.status !== 200 || b.id !== '${"c".repeat(32)}') process.exitCode=3; console.error('app completed');}) .catch(() => {process.exitCode=4;});`, ); const result = await runCli( From 5ff03781bdb2d59343af2147af0324f64ab1e545 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:20:57 +0000 Subject: [PATCH 2/3] test(local): Expect 200 from receiver ingest in viewer tests The viewer integration tests post to a real receiver, which now answers accepted envelopes with 200 and the event ID. Co-Authored-By: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com> --- apps/local/src/App.integration.test.tsx | 8 ++++---- apps/local/src/App.sessions.integration.test.tsx | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/local/src/App.integration.test.tsx b/apps/local/src/App.integration.test.tsx index fec86d1c6..c3e3e6ba4 100644 --- a/apps/local/src/App.integration.test.tsx +++ b/apps/local/src/App.integration.test.tsx @@ -100,7 +100,7 @@ async function sendEnvelope( headers: { "Content-Type": SENTRY_CONTENT_TYPE }, body: envelope(transaction, options), }); - expect(response.status).toBe(204); + expect(response.status).toBe(200); } async function sendLog( @@ -124,7 +124,7 @@ async function sendLog( "", ].join("\n"), }); - expect(response.status).toBe(204); + expect(response.status).toBe(200); } function renderViewer(port: number, path = "/") { @@ -493,7 +493,7 @@ describe("local receiver to viewer integration", () => { "\n", ), }); - expect(response.status).toBe(204); + expect(response.status).toBe(200); const row = await screen.findByRole("button", { name: /^View event:/, }); @@ -845,7 +845,7 @@ describe("local receiver to viewer integration", () => { headers: { "Content-Type": SENTRY_CONTENT_TYPE }, body: `{}\n${JSON.stringify(header)}\n${content}\n`, }); - expect(response.status).toBe(204); + expect(response.status).toBe(200); const wire = JSON.parse(await received) as [ unknown, [[unknown, { data: string }]], diff --git a/apps/local/src/App.sessions.integration.test.tsx b/apps/local/src/App.sessions.integration.test.tsx index 8eb61264d..763af5efe 100644 --- a/apps/local/src/App.sessions.integration.test.tsx +++ b/apps/local/src/App.sessions.integration.test.tsx @@ -78,7 +78,7 @@ async function startDaemon(now = Date.now, preferredPort = 0) { body: `${JSON.stringify({ event_id: crypto.randomUUID() })}\n{"type":"transaction"}\n${JSON.stringify({ transaction })}\n`, }) ).status, - ).toBe(204); + ).toBe(200); }; return { port, From 5dccba825bb5b38136a226353ee10652991173fb Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:53:01 +0000 Subject: [PATCH 3/3] ref(cli): Share the ingest response between both receivers Co-Authored-By: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com> --- packages/cli/src/commands/local/control-plane.ts | 9 +++------ packages/cli/src/commands/local/receiver-ingest.ts | 11 +++++++++++ packages/cli/src/commands/local/server.ts | 5 ++--- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/packages/cli/src/commands/local/control-plane.ts b/packages/cli/src/commands/local/control-plane.ts index c92c371ae..28f8d3fab 100644 --- a/packages/cli/src/commands/local/control-plane.ts +++ b/packages/cli/src/commands/local/control-plane.ts @@ -10,6 +10,7 @@ import { Buffer } from "node:buffer"; import { drainReceiver, ingestReceiverEnvelope, + ingestResponse, onOversizedEnvelope, readReceiverBody, receiverEnvelopeId, @@ -530,13 +531,9 @@ export function createLocalControlPlane({ reportIngestStatus(buffer, result); return result; }); - if (typeof outcome === "object") { - sessionStore.recordActivity(reference); - return c.json(outcome); - } if (outcome === 410) return closed(); - if (outcome === 503) c.header("Retry-After", "1"); - return c.body(null, outcome); + if (typeof outcome === "object") sessionStore.recordActivity(reference); + return ingestResponse(c, outcome); }; for (const path of SESSION_INGEST_PATHS) app.post(path, ingest); app.post(`${CONTROL_PLANE_PREFIX}/sessions/:id/stream`, ingest); diff --git a/packages/cli/src/commands/local/receiver-ingest.ts b/packages/cli/src/commands/local/receiver-ingest.ts index 3d1f65df9..61f1dc3a1 100644 --- a/packages/cli/src/commands/local/receiver-ingest.ts +++ b/packages/cli/src/commands/local/receiver-ingest.ts @@ -1,5 +1,6 @@ /** Bounded HTTP decoding and raw delivery identity for the Local receiver. */ import { brotliDecompress, gunzip, inflate } from "node:zlib"; +import type { Context } from "hono"; import { logger } from "../../lib/logger.js"; import { createReceiverEnvelope, @@ -57,6 +58,16 @@ export function reportIngestStatus( 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); + if (result === 503) c.header("Retry-After", "1"); + return c.body(null, result); +} + /** Stop consuming chunked input as soon as its encoded body exceeds the limit. */ export async function readReceiverBody( request: Request, diff --git a/packages/cli/src/commands/local/server.ts b/packages/cli/src/commands/local/server.ts index c6e5105b7..f7bfb331a 100644 --- a/packages/cli/src/commands/local/server.ts +++ b/packages/cli/src/commands/local/server.ts @@ -31,6 +31,7 @@ import { setTimeout as sleep } from "node:timers/promises"; import { serve } from "@hono/node-server"; import { ingestReceiverEnvelope, + ingestResponse, MAX_DECODED_BYTES, onOversizedEnvelope, readReceiverBody, @@ -525,9 +526,7 @@ export function buildApp( }); reportIngestStatus(buffer, result); - if (typeof result === "object") return c.json(result); - if (result === 503) c.header("Retry-After", "1"); - return c.body(null, result); + return ingestResponse(c, result); }; app.post("/stream", ingest);