diff --git a/dev-packages/bun-integration-tests/node-suites/excludes.ts b/dev-packages/bun-integration-tests/node-suites/excludes.ts index ec1db86b9fbe..ea616767bf8c 100644 --- a/dev-packages/bun-integration-tests/node-suites/excludes.ts +++ b/dev-packages/bun-integration-tests/node-suites/excludes.ts @@ -162,6 +162,7 @@ const NO_NATIVE_NODE_FETCH_INTEGRATION = [ // first request gets no spans after that. And an error that reaches the server does not mark // the request session as crashed. const HTTP_SERVER_SPANS_DIFFER = [ + 'suites/sessions/sampled-errors-session-aggregate/test.ts', 'suites/sessions/server-without-process-session/test.ts', 'suites/tracing/httpIntegration/test.ts', ]; diff --git a/dev-packages/node-integration-tests/suites/sessions/filtered-errors-session-aggregate/test.ts b/dev-packages/node-integration-tests/suites/sessions/filtered-errors-session-aggregate/test.ts new file mode 100644 index 000000000000..31afbac41a7f --- /dev/null +++ b/dev-packages/node-integration-tests/suites/sessions/filtered-errors-session-aggregate/test.ts @@ -0,0 +1,33 @@ +import { afterAll, expect, test } from 'vitest'; +import { join } from 'path'; +import { cleanupChildProcesses, createRunner } from '../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('does not count errors dropped by ignoreErrors or beforeSend', async () => { + const runner = createRunner(__dirname, '..', 'server.mjs') + .withInstrument(join(__dirname, '..', 'instrument.mjs')) + .ignore('span', 'event') + .unignore('sessions') + .expect({ + sessions: agg => { + // Sessions are bucketed by minute; tolerate splits across a minute boundary by summing. + const totals = agg.aggregates.reduce( + (acc, b) => ({ + exited: acc.exited + (b.exited ?? 0), + errored: acc.errored + (b.errored ?? 0), + crashed: acc.crashed + (b.crashed ?? 0), + }), + { exited: 0, errored: 0, crashed: 0 }, + ); + expect(totals).toEqual({ exited: 2, errored: 0, crashed: 0 }); + }, + }) + .start(); + + runner.makeRequest('get', '/test/error_ignored', { expectError: true }); + runner.makeRequest('get', '/test/error_dropped'); + await runner.completed(); +}); diff --git a/dev-packages/node-integration-tests/suites/sessions/instrument.mjs b/dev-packages/node-integration-tests/suites/sessions/instrument.mjs index 943afdd99206..87928b307f09 100644 --- a/dev-packages/node-integration-tests/suites/sessions/instrument.mjs +++ b/dev-packages/node-integration-tests/suites/sessions/instrument.mjs @@ -8,6 +8,8 @@ Sentry.init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', release: '1.0', transport: loggingTransport, + ignoreErrors: ['Ignored!'], + beforeSend: event => (event.exception?.values?.[0]?.value === 'Dropped!' ? null : event), integrations: [ httpIntegration({ // Flush after 2 seconds (to avoid waiting for the default 60s) diff --git a/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/instrument.mjs b/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/instrument.mjs new file mode 100644 index 000000000000..58656d36616b --- /dev/null +++ b/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/instrument.mjs @@ -0,0 +1,19 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +// `@sentry/deno` has the same options in `denoHttpIntegration`. +const httpIntegration = Sentry.httpIntegration ?? Sentry.denoHttpIntegration; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + transport: loggingTransport, + sampleRate: 0, + integrations: [ + httpIntegration({ + // Flush after 2 seconds (to avoid waiting for the default 60s) + sessionFlushingDelayMS: 2_000, + }), + Sentry.expressIntegration(), + ], +}); diff --git a/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/test.ts b/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/test.ts new file mode 100644 index 000000000000..c20347f93ba6 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/test.ts @@ -0,0 +1,33 @@ +import { afterAll, expect, test } from 'vitest'; +import { join } from 'path'; +import { cleanupChildProcesses, createRunner } from '../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('counts errors dropped by sampleRate', async () => { + const runner = createRunner(__dirname, '..', 'server.mjs') + .withInstrument(join(__dirname, 'instrument.mjs')) + .ignore('span', 'event') + .unignore('sessions') + .expect({ + sessions: agg => { + // Sessions are bucketed by minute; tolerate splits across a minute boundary by summing. + const totals = agg.aggregates.reduce( + (acc, b) => ({ + exited: acc.exited + (b.exited ?? 0), + errored: acc.errored + (b.errored ?? 0), + crashed: acc.crashed + (b.crashed ?? 0), + }), + { exited: 0, errored: 0, crashed: 0 }, + ); + expect(totals).toEqual({ exited: 0, errored: 1, crashed: 1 }); + }, + }) + .start(); + + runner.makeRequest('get', '/test/error_handled'); + runner.makeRequest('get', '/test/error_unhandled', { expectError: true }); + await runner.completed(); +}); diff --git a/dev-packages/node-integration-tests/suites/sessions/server.mjs b/dev-packages/node-integration-tests/suites/sessions/server.mjs index f2f8eb5bc05e..00823d7d4fe2 100644 --- a/dev-packages/node-integration-tests/suites/sessions/server.mjs +++ b/dev-packages/node-integration-tests/suites/sessions/server.mjs @@ -32,4 +32,13 @@ app.get('/test/error_handled', (_req, res) => { res.send('Crash!'); }); +app.get('/test/error_ignored', () => { + throw new Error('Ignored!'); +}); + +app.get('/test/error_dropped', (_req, res) => { + Sentry.captureException(new Error('Dropped!')); + res.send('Dropped!'); +}); + startExpressServerAndSendPortToRunner(app); diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index e890906173bb..4b50933962ea 100644 --- a/packages/core/src/client.ts +++ b/packages/core/src/client.ts @@ -80,7 +80,7 @@ interface InternalError { [INTERNAL_ERROR_SYMBOL]: true; } -interface DoNotSendEventError { +export interface DoNotSendEventError { message: string; [DO_NOT_SEND_EVENT_SYMBOL]: true; } @@ -92,7 +92,8 @@ function _makeInternalError(message: string): InternalError { }; } -function _makeDoNotSendEventError(message: string): DoNotSendEventError { +/** @internal */ +export function _makeDoNotSendEventError(message: string): DoNotSendEventError { return { message, [DO_NOT_SEND_EVENT_SYMBOL]: true, @@ -273,6 +274,7 @@ export abstract class Client { .then(event => this._captureEvent(event, hintWithEventId, scope)) .then(res => res), 'error', + hintWithEventId, ); return hintWithEventId.event_id; @@ -342,6 +344,8 @@ export abstract class Client { this._process( () => this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope, capturedSpanIsolationScope), dataCategory, + // Only exception events count in request sessions, so `_onQueueOverflow` gets the hint only for them. + isExceptionEvent(event) ? hintWithEventId : undefined, ); return hintWithEventId.event_id; @@ -1310,7 +1314,7 @@ export abstract class Client { /** * Updates the sessions that an error counts towards. Runs after event processors and `beforeSend` kept the error, - * also when sampling drops it: sampling only saves quota, so the error must still count. + * also when sampling or Dedupe drop it: these only save quota, so the error must still count. */ protected _updateSessions(event: Event, currentScope: Scope, isolationScope: Scope): void { const session = currentScope.getSession() || isolationScope.getSession(); @@ -1333,6 +1337,11 @@ export abstract class Client { return (currentScope.getSession() || isolationScope.getSession())?.status === 'ok'; } + /** Called for an error that never reaches the event pipeline, because the promise buffer is full. */ + protected _onQueueOverflow(_hint: EventHint): void { + // Sessions are updated in the event pipeline only. + } + /** * Counts a sampled-out error in sessions if the filters keep it, because sampling only saves quota. * Records the outcome of the error. @@ -1350,6 +1359,11 @@ export abstract class Client { // The error is never sent, so it must not make a later copy of it a duplicate. setDedupeContext(hint, { mode: 'ignore' }); + // The `_applyFilters` call below holds a promise buffer slot until it settles. With an async event processor or + // `beforeSend`, many sampled-out errors at the same time can fill the buffer. The client then drops errors that it + // would otherwise send, with `queue_overflow`. `ServerRuntimeClient` overrides this method to run the filters + // outside the buffer, because a server gets errors from many requests at the same time. The base client does not, + // to save browser bundle size. One browser user rarely causes that many errors at the same time. return this._applyFilters(event, hint, currentScope, isolationScope).then(processedEvent => { this._updateSessions(processedEvent, currentScope, isolationScope); this.recordDroppedEvent('sample_rate', 'error'); @@ -1662,7 +1676,7 @@ export abstract class Client { /** * Occupies the client with processing and event */ - protected _process(taskProducer: () => PromiseLike, dataCategory: DataCategory): void { + protected _process(taskProducer: () => PromiseLike, dataCategory: DataCategory, errorHint?: EventHint): void { this._numProcessing++; void this._promiseBuffer.add(taskProducer).then( @@ -1675,6 +1689,9 @@ export abstract class Client { if (reason === SENTRY_BUFFER_FULL_ERROR) { this.recordDroppedEvent('queue_overflow', dataCategory); + if (errorHint) { + this._onQueueOverflow(errorHint); + } } return reason; diff --git a/packages/core/src/integrations/dedupe.ts b/packages/core/src/integrations/dedupe.ts index 38f40af697aa..aed15cb77ef2 100644 --- a/packages/core/src/integrations/dedupe.ts +++ b/packages/core/src/integrations/dedupe.ts @@ -1,16 +1,20 @@ import { DEBUG_BUILD } from '../debug-build'; import { defineIntegration } from '../integration'; +import type { Scope } from '../scope'; import type { Event } from '../types/event'; import type { Exception } from '../types/exception'; import type { IntegrationFn } from '../types/integration'; import { debug } from '../utils/debug-logger'; import { getDedupeContext } from '../utils/dedupeContext'; +import { hasUnhandledException } from '../utils/misc'; import { getFramesFromEvent } from '../utils/stacktrace'; const INTEGRATION_NAME = 'Dedupe' as const; const _dedupeIntegration = (() => { let previousEvent: Event | undefined; + // Isolation scopes (e.g. requests) that already had a copy of the previous event. + let previousEventScopes = new WeakSet(); return { name: INTEGRATION_NAME, @@ -27,10 +31,20 @@ const _dedupeIntegration = (() => { try { if (_shouldDropEvent(currentEvent, previousEvent)) { DEBUG_BUILD && debug.warn('Event dropped due to being a duplicate of previously captured event.'); + // A later copy in the same isolation scope cannot change the session status, unless it is unhandled. + if ( + context?.mode === 'mark' && + (!previousEventScopes.has(context.isolationScope) || hasUnhandledException(currentEvent, hint)) + ) { + previousEventScopes.add(context.isolationScope); + context.isDuplicate = true; + return currentEvent; + } return null; } } catch {} // eslint-disable-line no-empty + previousEventScopes = new WeakSet(context ? [context.isolationScope] : []); return (previousEvent = currentEvent); }, }; diff --git a/packages/core/src/integrations/http/record-request-session.ts b/packages/core/src/integrations/http/record-request-session.ts index b6a652b294fa..4ef568abcf4f 100644 --- a/packages/core/src/integrations/http/record-request-session.ts +++ b/packages/core/src/integrations/http/record-request-session.ts @@ -130,6 +130,8 @@ export function startRequestSession( } ended = true; + // The event pipeline decides whether an error counts towards the session, and it can still run after the + // response ended (e.g. async event processors), so the status is final only once those errors settle. const pendingErrors = requestIsolationScope.getScopeData().sdkProcessingMetadata.requestSession?.pendingErrors; if (!pendingErrors?.size) { record(false); diff --git a/packages/core/src/scope.ts b/packages/core/src/scope.ts index 44ce0e4090ad..58b6c2f52630 100644 --- a/packages/core/src/scope.ts +++ b/packages/core/src/scope.ts @@ -74,6 +74,11 @@ export interface SdkProcessingMetadata { * defaults to `true`, so Replay does not treat them as errors in buffer mode. */ hasDefaultSyntheticStacktrace?: boolean; + /** + * Set on a `captureMessage` event that has exception values because of `attachStacktrace`. The exception values + * hold only the stack trace, so the event must not count as an error in request sessions. + */ + isMessageWithStacktrace?: boolean; } /** diff --git a/packages/core/src/server-runtime-client.ts b/packages/core/src/server-runtime-client.ts index a4aa6adb0a43..b09b6fba463e 100644 --- a/packages/core/src/server-runtime-client.ts +++ b/packages/core/src/server-runtime-client.ts @@ -1,6 +1,6 @@ import { SERVER_ADDRESS } from '@sentry/conventions/attributes'; import { createCheckInEnvelope } from './checkin'; -import { Client, isExceptionEvent } from './client'; +import { _makeDoNotSendEventError, Client, isExceptionEvent } from './client'; import { getIsolationScope } from './currentScopes'; import { DEBUG_BUILD } from './debug-build'; import { @@ -18,13 +18,21 @@ import type { SeverityLevel } from './types/severity'; import type { BaseTransportOptions, Transport } from './types/transport'; import { debug } from './utils/debug-logger'; import { eventFromMessage, eventFromUnknownInput } from './utils/eventbuilder'; -import { uuid4 } from './utils/misc'; -import { addPendingRequestSessionError } from './utils/requestSession'; +import { isMarkedDuplicate, setDedupeContext } from './utils/dedupeContext'; +import { hasUnhandledException, isAlreadyCaptured, uuid4 } from './utils/misc'; +import { + addPendingRequestSessionError, + crashRequestSessionIfErrored, + getRequestSession, + setRequestSessionErroredOrCrashed, +} from './utils/requestSession'; import { makePromiseBuffer } from './utils/promisebuffer'; -import { resolvedSyncPromise } from './utils/syncpromise'; +import { rejectedSyncPromise, resolvedSyncPromise } from './utils/syncpromise'; import { _getTraceInfoFromScope } from './utils/trace-info'; import { applyServerTunnelDefaults } from './utils/tunnelDefaults'; +const DUPLICATE_EVENT_ERROR = 'Event is a duplicate of the previously captured event, will not send event.'; + export interface ServerRuntimeClientOptions extends ClientOptions { platform?: string; runtime?: { name: string; version?: string }; @@ -41,6 +49,9 @@ export class ServerRuntimeClient< > extends Client { private _disposeCallbacks: (() => void)[] = []; + /** Number of errors that are never sent, but run through event processing to update sessions. */ + private _numCountingWithoutSlot = 0; + /** * Creates a new Edge SDK instance. * @param options Configuration options for this SDK. @@ -92,7 +103,9 @@ export class ServerRuntimeClient< * @inheritDoc */ public captureException(exception: unknown, hint?: EventHint, scope?: Scope): string { - setCurrentRequestSessionErroredOrCrashed(hint); + if (isAlreadyCaptured(exception)) { + onAlreadyCapturedError(hint); + } // oxlint-disable-next-line sdk/require-exception-mechanism -- passes the caller's hint through return super.captureException(exception, hint, scope); } @@ -101,12 +114,9 @@ export class ServerRuntimeClient< * @inheritDoc */ public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string { - // If the event is of type Exception, then a request session should be captured - const isException = !event.type && event.exception?.values && event.exception.values.length > 0; - if (isException) { - setCurrentRequestSessionErroredOrCrashed(hint); + if (isExceptionEvent(event) && isAlreadyCaptured(hint?.originalException)) { + onAlreadyCapturedError(hint); } - return super.captureEvent(event, hint, scope); } @@ -119,15 +129,109 @@ export class ServerRuntimeClient< currentScope: Scope, isolationScope: Scope, ): PromiseLike { - if (!isExceptionEvent(event)) { + if (!isRequestSessionError(event)) { return super._processEvent(event, hint, currentScope, isolationScope); } + const canCountDuplicate = + this._canCountWithoutSlot() && this._canErrorChangeSessions(event, hint, currentScope, isolationScope); + setDedupeContext( + hint, + canCountDuplicate ? { mode: 'mark', isolationScope, isDuplicate: false } : { mode: 'drop', isolationScope }, + ); const processedEvent = super._processEvent(event, hint, currentScope, isolationScope); addPendingRequestSessionError(isolationScope, processedEvent); return processedEvent; } + /** + * Hands a duplicate that Dedupe marked over to {@link ServerRuntimeClient._countWithoutSlot}. + */ + protected override _applyFilters( + event: Event, + hint: EventHint, + currentScope: Scope, + isolationScope: Scope, + ): PromiseLike { + const filtered = super._applyFilters(event, hint, currentScope, isolationScope); + const countDuplicate = (processedEvent: Event): void => { + this._updateSessions(processedEvent, currentScope, isolationScope); + this.recordDroppedEvent('event_processor', 'error'); + }; + + // The event processors before Dedupe are usually synchronous, so most duplicates are known here. + if (isMarkedDuplicate(hint)) { + // Reject at once to free the promise buffer slot. `filtered` keeps running and counts the duplicate outside + // the buffer. + this._countWithoutSlot(filtered.then(countDuplicate), isolationScope); + return rejectedSyncPromise(_makeDoNotSendEventError(DUPLICATE_EVENT_ERROR)); + } + + return filtered.then(processedEvent => { + // Dedupe ran after an asynchronous event processor. + if (isMarkedDuplicate(hint)) { + countDuplicate(processedEvent); + throw _makeDoNotSendEventError(DUPLICATE_EVENT_ERROR); + } + return processedEvent; + }); + } + + /** + * @inheritDoc + */ + protected override _countSampledOutError( + event: Event, + hint: EventHint, + currentScope: Scope, + isolationScope: Scope, + ): PromiseLike { + if (this._canCountWithoutSlot()) { + this._countWithoutSlot(super._countSampledOutError(event, hint, currentScope, isolationScope), isolationScope); + } else { + this.recordDroppedEvent('sample_rate', 'error'); + } + return resolvedSyncPromise(); + } + + /** + * @inheritDoc + */ + protected override _canErrorChangeSessions( + event: Event, + hint: EventHint, + currentScope: Scope, + isolationScope: Scope, + ): boolean { + if (super._canErrorChangeSessions(event, hint, currentScope, isolationScope)) { + return true; + } + if (!isRequestSessionError(event)) { + return false; + } + + const requestSessionStatus = getRequestSession(isolationScope)?.status; + return requestSessionStatus === 'ok' || (requestSessionStatus === 'errored' && hasUnhandledException(event, hint)); + } + + /** + * @inheritDoc + */ + protected override _updateSessions(event: Event, currentScope: Scope, isolationScope: Scope): void { + super._updateSessions(event, currentScope, isolationScope); + if (isRequestSessionError(event)) { + setRequestSessionErroredOrCrashed(isolationScope, hasUnhandledException(event)); + } + } + + /** + * @inheritDoc + */ + protected override _onQueueOverflow(hint: EventHint): void { + // Without the event pipeline, filters cannot drop the error, so it counts. + setRequestSessionErroredOrCrashed(getIsolationScope(), hint.mechanism?.handled === false); + } + /** * Create a cron monitor check in and send it to Sentry. * @@ -262,6 +366,30 @@ export class ServerRuntimeClient< return super._prepareEvent(event, hint, currentScope, isolationScope); } + /** + * Whether an error that is never sent can still run event processing to update sessions. Above the limit, the error + * does not update the session. So an error storm can lose a session count, but it never loses an error that is sent. + */ + private _canCountWithoutSlot(): boolean { + return this._numCountingWithoutSlot < (this._options.transportOptions?.bufferSize ?? DEFAULT_TRANSPORT_BUFFER_SIZE); + } + + /** + * Tracks the session update of an error that is never sent. It runs outside of the promise buffer, so that it + * never takes a slot from an error that is sent. + */ + private _countWithoutSlot(counting: PromiseLike, isolationScope: Scope): void { + // `flush()` waits until `_numProcessing` is 0, so it also waits for this session update. + this._numProcessing++; + this._numCountingWithoutSlot++; + const settle = (): void => { + this._numProcessing--; + this._numCountingWithoutSlot--; + }; + counting.then(settle, settle); + addPendingRequestSessionError(isolationScope, counting); + } + /** * Process a server-side metric before it is captured. */ @@ -277,19 +405,20 @@ export class ServerRuntimeClient< } } -function setCurrentRequestSessionErroredOrCrashed(eventHint?: EventHint): void { - const requestSession = getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession; - if (requestSession) { - // We mutate instead of doing `setSdkProcessingMetadata` because the http integration stores away a particular - // isolationScope. If that isolation scope is forked, setting the processing metadata here will not mutate the - // original isolation scope that the http integration stored away. - const isHandledException = eventHint?.mechanism?.handled ?? true; - // A request session can go from "errored" -> "crashed" but not "crashed" -> "errored". - // Crashed (unhandled exception) is worse than errored (handled exception). - if (isHandledException && requestSession.status !== 'crashed') { - requestSession.status = 'errored'; - } else if (!isHandledException) { - requestSession.status = 'crashed'; - } +/** + * Whether the event counts as an error in request sessions. The sessions spec says that a `captureMessage` event + * must never count, so this excludes a message that has exception values because of `attachStacktrace`. + */ +function isRequestSessionError(event: Event): boolean { + return isExceptionEvent(event) && !event.sdkProcessingMetadata?.isMessageWithStacktrace; +} + +/** + * An unhandled error that was captured before, e.g. captured as handled, then rethrown and captured again by a + * framework error handler, crashes the request session if the first capture counted. + */ +function onAlreadyCapturedError(hint: EventHint | undefined): void { + if (hint?.mechanism?.handled === false) { + crashRequestSessionIfErrored(getIsolationScope()); } } diff --git a/packages/core/src/utils/dedupeContext.ts b/packages/core/src/utils/dedupeContext.ts index d01081bc989d..ead07f6fca5f 100644 --- a/packages/core/src/utils/dedupeContext.ts +++ b/packages/core/src/utils/dedupeContext.ts @@ -1,11 +1,19 @@ +import type { Scope } from '../scope'; import type { EventHint } from '../types/event'; /** * How the Dedupe integration treats an error event. The client sets it before event processors run. * + * - `drop`: Dedupe drops a duplicate, like any other event processor. + * - `mark`: The duplicate can still change a session. If it is the first copy in its isolation scope (e.g. request), or + * if it is unhandled, Dedupe marks it and keeps it, so that it runs through all event processors and `beforeSend`. + * The client drops it after the session update, like a sampled-out error. * - `ignore`: The error is never sent. Dedupe does not compare it and does not remember it. */ -export type DedupeContext = { mode: 'ignore' }; +export type DedupeContext = + | { mode: 'ignore' } + | { mode: 'drop'; isolationScope: Scope } + | { mode: 'mark'; isolationScope: Scope; isDuplicate: boolean }; const dedupeContexts = new WeakMap(); @@ -18,3 +26,9 @@ export function setDedupeContext(hint: EventHint, context: DedupeContext): void export function getDedupeContext(hint: EventHint): DedupeContext | undefined { return dedupeContexts.get(hint); } + +/** Whether the Dedupe integration marked the error event of this hint as a duplicate. */ +export function isMarkedDuplicate(hint: EventHint): boolean { + const context = dedupeContexts.get(hint); + return context?.mode === 'mark' && context.isDuplicate; +} diff --git a/packages/core/src/utils/eventbuilder.ts b/packages/core/src/utils/eventbuilder.ts index 2e8445ed5878..1a57bf994e14 100644 --- a/packages/core/src/utils/eventbuilder.ts +++ b/packages/core/src/utils/eventbuilder.ts @@ -239,6 +239,9 @@ export function eventFromMessage( ], }; addExceptionMechanism(event, { synthetic: true }); + // With exception values, the message looks like an error. `ServerRuntimeClient` reads this flag to keep the + // message out of request sessions. + event.sdkProcessingMetadata = { isMessageWithStacktrace: true }; } } diff --git a/packages/core/src/utils/misc.ts b/packages/core/src/utils/misc.ts index 454e4a9ab95d..55e092cdee58 100644 --- a/packages/core/src/utils/misc.ts +++ b/packages/core/src/utils/misc.ts @@ -1,4 +1,4 @@ -import type { Event } from '../types/event'; +import type { Event, EventHint } from '../types/event'; import type { Exception } from '../types/exception'; import type { Mechanism } from '../types/mechanism'; import type { StackFrame } from '../types/stackframe'; @@ -133,6 +133,18 @@ export function addExceptionMechanismToCapturedException(event: Event, newMechan applyExceptionMechanism(capturedException, newMechanism); } +/** + * Whether an event has an unhandled exception. Before event processing, the mechanism can be only in the hint. + * + * @hidden + */ +export function hasUnhandledException(event: Event, hint?: EventHint): boolean { + return ( + hint?.mechanism?.handled === false || + !!event.exception?.values?.some(exception => exception.mechanism?.handled === false) + ); +} + function applyExceptionMechanism(exception: Exception, newMechanism?: Partial): void { const defaultMechanism = { type: 'generic', handled: true }; const currentMechanism = exception.mechanism; diff --git a/packages/core/src/utils/requestSession.ts b/packages/core/src/utils/requestSession.ts index c20d894e0ac1..69a61d8c2c54 100644 --- a/packages/core/src/utils/requestSession.ts +++ b/packages/core/src/utils/requestSession.ts @@ -20,3 +20,41 @@ export function addPendingRequestSessionError(isolationScope: Scope, processing: pendingErrors.add(processing); processing.then(settle, settle); } + +/** Marks the request session as errored, or as crashed for an unhandled error. */ +export function setRequestSessionErroredOrCrashed(isolationScope: Scope, isUnhandled: boolean): void { + const requestSession = getRequestSession(isolationScope); + if (!requestSession) { + return; + } + + // We mutate instead of doing `setSdkProcessingMetadata` because the http integration stores away a particular + // isolationScope. If that isolation scope is forked, setting the processing metadata here will not mutate the + // original isolation scope that the http integration stored away. + // A request session can go from "errored" -> "crashed" but not "crashed" -> "errored". + // Crashed (unhandled exception) is worse than errored (handled exception). + if (isUnhandled) { + requestSession.status = 'crashed'; + } else if (requestSession.status !== 'crashed') { + requestSession.status = 'errored'; + } +} + +/** Crashes the request session if an error counted. That error can still be in the event pipeline. */ +export function crashRequestSessionIfErrored(isolationScope: Scope): void { + const requestSession = getRequestSession(isolationScope); + if (!requestSession) { + return; + } + + const crashIfErrored = (): void => { + if (requestSession.status === 'errored') { + requestSession.status = 'crashed'; + } + }; + if (!requestSession.pendingErrors?.size) { + crashIfErrored(); + return; + } + addPendingRequestSessionError(isolationScope, Promise.allSettled(requestSession.pendingErrors).then(crashIfErrored)); +} diff --git a/packages/core/test/lib/server-runtime-client.test.ts b/packages/core/test/lib/server-runtime-client.test.ts index 85a73066bd5a..30528dbaeed8 100644 --- a/packages/core/test/lib/server-runtime-client.test.ts +++ b/packages/core/test/lib/server-runtime-client.test.ts @@ -1,7 +1,8 @@ import { beforeEach, describe, expect, it, test, vi } from 'vitest'; -import { applySdkMetadata, createTransport, getIsolationScope, Scope } from '../../src'; +import { applySdkMetadata, createTransport, dedupeIntegration, getIsolationScope, Scope } from '../../src'; import { startRequestSession } from '../../src/integrations/http/record-request-session'; import { captureMetricEvent, getMetricBuffer } from '../../src/metrics/internal'; +import { AsyncTestIntegration } from '../mocks/integration'; import type { ServerRuntimeClientOptions } from '../../src/server-runtime-client'; import { ServerRuntimeClient } from '../../src/server-runtime-client'; import type { ErrorEvent, Event, EventHint } from '../../src/types/event'; @@ -18,6 +19,25 @@ function getDefaultClientOptions(options: Partial = }; } +/** Captures an error in the isolation scope of a request, as the HTTP integration does in Node. */ +function captureErrorInScope(client: ServerRuntimeClient, message: string, requestIsolationScope: Scope): void { + client.captureEvent({ + exception: { values: [{ type: 'Error', value: message }] }, + sdkProcessingMetadata: { capturedSpanIsolationScope: requestIsolationScope }, + }); +} + +/** Captures equal errors in a request with its own isolation scope. */ +function captureErrorInRequest(client: ServerRuntimeClient, message: string, route = '/', count = 1): void { + const requestIsolationScope = new Scope(); + requestIsolationScope.setTag('route', route); + const endRequestSession = startRequestSession(client, { requestIsolationScope }); + for (let i = 0; i < count; i++) { + captureErrorInScope(client, message, requestIsolationScope); + } + endRequestSession(); +} + function delayed(event: ErrorEvent): Promise { return new Promise(resolve => setTimeout(() => resolve(event), 10)); } @@ -194,6 +214,303 @@ describe('ServerRuntimeClient', () => { resetGlobals(); }); + it.each([ + ['errored for a handled exception', {}, undefined, { errored: 1 }], + ['crashed for an unhandled exception', {}, { mechanism: { type: 'test', handled: false } }, { crashed: 1 }], + ['exited for an exception that `beforeSend` drops', { beforeSend: () => null }, undefined, { exited: 1 }], + ['errored for an exception that `sampleRate` drops', { sampleRate: 0 }, undefined, { errored: 1 }], + [ + 'errored for an exception that is processed after the request ended', + { beforeSend: delayed }, + undefined, + { errored: 1 }, + ], + ] as const)('records the session as %s', async (_, options, hint, counts) => { + client = new ServerRuntimeClient(getDefaultClientOptions({ dsn: PUBLIC_DSN, ...options })); + const sendSessionSpy = vi.spyOn(client, 'sendSession'); + const endRequestSession = startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + client.captureException(new Error('foo'), hint); + endRequestSession(); + await client.flush(); + + expect(sendSessionSpy).toHaveBeenCalledExactlyOnceWith({ + aggregates: [{ started: expect.any(String), exited: 0, errored: 0, crashed: 0, ...counts }], + }); + }); + + it('records sampled-out errors without taking a buffer slot from errors that are sent', async () => { + client = new ServerRuntimeClient( + getDefaultClientOptions({ + dsn: PUBLIC_DSN, + sampleRate: 0, + transportOptions: { bufferSize: 1 }, + beforeSend: delayed, + }), + ); + const sendEventSpy = vi.spyOn(client, 'sendEvent'); + const sendSessionSpy = vi.spyOn(client, 'sendSession'); + const endRequestSession = startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureException(new Error('sampled out')); + client.getOptions().sampleRate = 1; + client.captureException(new Error('sampled in')); + endRequestSession(); + await client.flush(); + + expect(sendEventSpy).toHaveBeenCalledOnce(); + expect(sendSessionSpy).toHaveBeenCalledExactlyOnceWith({ + aggregates: [{ started: expect.any(String), exited: 0, errored: 1, crashed: 0 }], + }); + }); + + it('limits how many errors that are never sent run event processing at the same time', async () => { + const beforeSend = vi.fn((event: ErrorEvent) => event); + client = new ServerRuntimeClient( + getDefaultClientOptions({ + dsn: PUBLIC_DSN, + sampleRate: 0, + beforeSend, + transportOptions: { bufferSize: 2 }, + integrations: [new AsyncTestIntegration()], + sendClientReports: true, + }), + ); + client.init(); + const sendEnvelopeSpy = vi.spyOn(client, 'sendEnvelope'); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureException(new Error('first')); + client.captureException(new Error('second')); + client.captureException(new Error('third')); + await client.flush(); + + expect(beforeSend).toHaveBeenCalledTimes(2); + expect(sendEnvelopeSpy).toHaveBeenCalledWith([ + expect.any(Object), + [ + [ + { type: 'client_report' }, + expect.objectContaining({ discarded_events: [{ reason: 'sample_rate', category: 'error', quantity: 3 }] }), + ], + ], + ]); + }); + + it.each([ + ['synchronous', [dedupeIntegration()]], + ['asynchronous', [new AsyncTestIntegration(), dedupeIntegration()]], + ])( + 'crashes the request session for an unhandled duplicate in the same request, with %s processors before Dedupe', + async (_, integrations) => { + client = new ServerRuntimeClient( + getDefaultClientOptions({ dsn: PUBLIC_DSN, integrations, sendClientReports: true }), + ); + client.init(); + const sendEventSpy = vi.spyOn(client, 'sendEvent'); + const sendEnvelopeSpy = vi.spyOn(client, 'sendEnvelope'); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureException(new Error('duplicate')); + client.captureException(new Error('duplicate'), { mechanism: { type: 'generic', handled: false } }); + await client.flush(); + + expect(sendEventSpy).toHaveBeenCalledOnce(); + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe('crashed'); + expect(sendEnvelopeSpy).toHaveBeenCalledWith([ + expect.any(Object), + [ + [ + { type: 'client_report' }, + expect.objectContaining({ + discarded_events: [{ reason: 'event_processor', category: 'error', quantity: 1 }], + }), + ], + ], + ]); + }, + ); + + it('drops sampled-out errors before event processing once the request session crashed', () => { + const beforeSend = vi.fn((event: ErrorEvent) => event); + client = new ServerRuntimeClient(getDefaultClientOptions({ dsn: PUBLIC_DSN, sampleRate: 0, beforeSend })); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureException(new Error('crash'), { mechanism: { type: 'test', handled: false } }); + client.captureException(new Error('after crash')); + + expect(beforeSend).toHaveBeenCalledOnce(); + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe('crashed'); + }); + + it('drops sampled-out handled errors before event processing once the request session errored', () => { + const beforeSend = vi.fn((event: ErrorEvent) => event); + client = new ServerRuntimeClient(getDefaultClientOptions({ dsn: PUBLIC_DSN, sampleRate: 0, beforeSend })); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureException(new Error('handled')); + client.captureException(new Error('handled again')); + client.captureException(new Error('crash'), { mechanism: { type: 'test', handled: false } }); + + expect(beforeSend).toHaveBeenCalledTimes(2); + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe('crashed'); + }); + + it('records each request that fails with the same error as errored, also when Dedupe drops the error', async () => { + client = new ServerRuntimeClient( + getDefaultClientOptions({ dsn: PUBLIC_DSN, integrations: [dedupeIntegration()] }), + ); + client.init(); + const sendEventSpy = vi.spyOn(client, 'sendEvent'); + const sendSessionSpy = vi.spyOn(client, 'sendSession'); + + for (let i = 0; i < 2; i++) { + captureErrorInRequest(client, 'same error'); + } + await client.flush(); + + expect(sendEventSpy).toHaveBeenCalledOnce(); + expect(sendSessionSpy).toHaveBeenCalledExactlyOnceWith({ + aggregates: [{ started: expect.any(String), exited: 0, errored: 2, crashed: 0 }], + }); + }); + + it('does not count a request whose duplicate error `beforeSend` drops', async () => { + client = new ServerRuntimeClient( + getDefaultClientOptions({ + dsn: PUBLIC_DSN, + integrations: [dedupeIntegration()], + beforeSend: event => (event.tags?.route === '/health' ? null : event), + }), + ); + client.init(); + const sendSessionSpy = vi.spyOn(client, 'sendSession'); + + captureErrorInRequest(client, 'same error', '/users'); + captureErrorInRequest(client, 'same error', '/health'); + await client.flush(); + + expect(sendSessionSpy).toHaveBeenCalledExactlyOnceWith({ + aggregates: [{ started: expect.any(String), exited: 1, errored: 1, crashed: 0 }], + }); + }); + + it('does not let duplicate errors from many requests push other errors out of the promise buffer', async () => { + client = new ServerRuntimeClient( + getDefaultClientOptions({ + dsn: PUBLIC_DSN, + integrations: [dedupeIntegration(), new AsyncTestIntegration()], + transportOptions: { bufferSize: 2 }, + }), + ); + client.init(); + const sendEventSpy = vi.spyOn(client, 'sendEvent'); + + for (let i = 0; i < 10; i++) { + captureErrorInRequest(client, 'same error'); + } + captureErrorInRequest(client, 'other error'); + await client.flush(); + + expect(sendEventSpy).toHaveBeenCalledTimes(2); + }); + + it('calls `beforeSend` once for equal errors in one request', async () => { + const beforeSend = vi.fn((event: ErrorEvent) => event); + client = new ServerRuntimeClient( + getDefaultClientOptions({ dsn: PUBLIC_DSN, integrations: [dedupeIntegration()], beforeSend }), + ); + client.init(); + + captureErrorInRequest(client, 'same error', '/users', 3); + await client.flush(); + + expect(beforeSend).toHaveBeenCalledOnce(); + }); + + it('calls `beforeSend` once per request for equal errors from requests that run at the same time', async () => { + const beforeSend = vi.fn(delayed); + client = new ServerRuntimeClient( + getDefaultClientOptions({ dsn: PUBLIC_DSN, integrations: [dedupeIntegration()], beforeSend }), + ); + client.init(); + const firstRequest = new Scope(); + const secondRequest = new Scope(); + startRequestSession(client, { requestIsolationScope: firstRequest }); + startRequestSession(client, { requestIsolationScope: secondRequest }); + + captureErrorInScope(client, 'same error', firstRequest); + captureErrorInScope(client, 'same error', secondRequest); + captureErrorInScope(client, 'same error', firstRequest); + captureErrorInScope(client, 'same error', secondRequest); + await client.flush(); + + expect(beforeSend).toHaveBeenCalledTimes(2); + }); + + it('does not run event processing for sampled-out messages', () => { + const beforeSend = vi.fn((event: ErrorEvent) => event); + client = new ServerRuntimeClient(getDefaultClientOptions({ dsn: PUBLIC_DSN, sampleRate: 0, beforeSend })); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureMessage('message'); + + expect(beforeSend).not.toHaveBeenCalled(); + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe('ok'); + }); + + it.each([ + ['a sent message', 1], + ['a sampled-out message', 0], + ])('does not count %s that has a synthetic stack trace', async (_, sampleRate) => { + const beforeSend = vi.fn((event: ErrorEvent) => event); + client = new ServerRuntimeClient( + getDefaultClientOptions({ + dsn: PUBLIC_DSN, + sampleRate, + beforeSend, + attachStacktrace: true, + stackParser: () => [{ filename: 'file.js', function: 'fn' }], + }), + ); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureMessage('message', 'error', { syntheticException: new Error('message') }); + await client.flush(); + + expect(beforeSend).toHaveBeenCalledTimes(sampleRate); + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe('ok'); + }); + + it.each([ + ['errored for a handled exception', undefined, 'errored'], + ['crashed for an unhandled exception', { mechanism: { type: 'test', handled: false } }, 'crashed'], + ] as const)('records a request whose error overflows the buffer as %s', (_, hint, status) => { + client = new ServerRuntimeClient( + getDefaultClientOptions({ dsn: PUBLIC_DSN, transportOptions: { bufferSize: 1 }, beforeSend: delayed }), + ); + captureErrorInScope(client, 'takes the only buffer slot', new Scope()); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureException(new Error('overflows'), hint); + + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe(status); + }); + + it.each([ + ['crashed when the first capture counted', delayed, 'crashed'], + ['ok when `beforeSend` dropped the first capture', () => null, 'ok'], + ] as const)('records a rethrown unhandled error as %s', async (_, beforeSend, status) => { + client = new ServerRuntimeClient(getDefaultClientOptions({ dsn: PUBLIC_DSN, beforeSend })); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + const error = new Error('rethrown'); + + client.captureException(error); + client.captureException(error, { mechanism: { type: 'test', handled: false } }); + await client.flush(); + + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe(status); + }); + it('sends a session that settles during a flush, also when another request opened an aggregate', async () => { client = new ServerRuntimeClient( getDefaultClientOptions({ diff --git a/packages/core/test/lib/utils/eventbuilder.test.ts b/packages/core/test/lib/utils/eventbuilder.test.ts index 5a2fcc003419..daddf2f6342b 100644 --- a/packages/core/test/lib/utils/eventbuilder.test.ts +++ b/packages/core/test/lib/utils/eventbuilder.test.ts @@ -213,6 +213,7 @@ describe('eventFromMessage', () => { }, level: 'info', message: 'Test Message', + sdkProcessingMetadata: { isMessageWithStacktrace: true }, }); });