Skip to content
1 change: 1 addition & 0 deletions dev-packages/bun-integration-tests/node-suites/excludes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
];
Expand Down
Original file line number Diff line number Diff line change
@@ -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();
});
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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(),
],
});
Original file line number Diff line number Diff line change
@@ -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();
});
Original file line number Diff line number Diff line change
Expand Up @@ -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);
25 changes: 21 additions & 4 deletions packages/core/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ interface InternalError {
[INTERNAL_ERROR_SYMBOL]: true;
}

interface DoNotSendEventError {
export interface DoNotSendEventError {
message: string;
[DO_NOT_SEND_EVENT_SYMBOL]: true;
}
Expand All @@ -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,
Expand Down Expand Up @@ -273,6 +274,7 @@ export abstract class Client<O extends ClientOptions = ClientOptions> {
.then(event => this._captureEvent(event, hintWithEventId, scope))
.then(res => res),
'error',
hintWithEventId,
);

return hintWithEventId.event_id;
Expand Down Expand Up @@ -342,6 +344,8 @@ export abstract class Client<O extends ClientOptions = ClientOptions> {
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;
Expand Down Expand Up @@ -1310,7 +1314,7 @@ export abstract class Client<O extends ClientOptions = ClientOptions> {

/**
* 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();
Expand All @@ -1333,6 +1337,11 @@ export abstract class Client<O extends ClientOptions = ClientOptions> {
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.
Expand All @@ -1350,6 +1359,11 @@ export abstract class Client<O extends ClientOptions = ClientOptions> {

// 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');
Expand Down Expand Up @@ -1662,7 +1676,7 @@ export abstract class Client<O extends ClientOptions = ClientOptions> {
/**
* Occupies the client with processing and event
*/
protected _process<T>(taskProducer: () => PromiseLike<T>, dataCategory: DataCategory): void {
protected _process<T>(taskProducer: () => PromiseLike<T>, dataCategory: DataCategory, errorHint?: EventHint): void {
this._numProcessing++;

void this._promiseBuffer.add(taskProducer).then(
Expand All @@ -1675,6 +1689,9 @@ export abstract class Client<O extends ClientOptions = ClientOptions> {

if (reason === SENTRY_BUFFER_FULL_ERROR) {
this.recordDroppedEvent('queue_overflow', dataCategory);
if (errorHint) {
this._onQueueOverflow(errorHint);
}
}

return reason;
Expand Down
14 changes: 14 additions & 0 deletions packages/core/src/integrations/dedupe.ts
Original file line number Diff line number Diff line change
@@ -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<Scope>();

return {
name: INTEGRATION_NAME,
Expand All @@ -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);
},
};
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/integrations/http/record-request-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
Loading
Loading