Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/core/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1859,3 +1859,8 @@ function isErrorEvent(event: Event): event is ErrorEvent {
function isTransactionEvent(event: Event): event is TransactionEvent {
return event.type === 'transaction';
}

/** Whether the event is an error event with an exception. */
export function isExceptionEvent(event: Event): boolean {
return isErrorEvent(event) && !!event.exception?.values?.length;
}
41 changes: 35 additions & 6 deletions packages/core/src/integrations/http/record-request-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,7 @@ export function startRequestSession(
client.emit('startRequestSession');

let ended = false;
return () => {
if (ended) {
return;
}
ended = true;
const record = (sendNow: boolean): void => {
const requestSession = requestIsolationScope.getScopeData().sdkProcessingMetadata.requestSession;

if (client && requestSession) {
Expand All @@ -78,10 +74,19 @@ export function startRequestSession(
const roundedDate = new Date(safeDateNow());
roundedDate.setSeconds(0, 0);
const dateBucketKey = roundedDate.toISOString();
const statusKey = ({ ok: 'exited', crashed: 'crashed', errored: 'errored' } as const)[requestSession.status];

if (sendNow) {
DEBUG_BUILD && debug.log('Sending request session that settled during a client flush');
client.sendSession({
aggregates: [{ started: dateBucketKey, exited: 0, errored: 0, crashed: 0, [statusKey]: 1 }],
});
return;
}

const existingClientAggregate = clientToRequestSessionAggregatesMap.get(client);
const bucket = existingClientAggregate?.[dateBucketKey] || { exited: 0, crashed: 0, errored: 0 };
bucket[({ ok: 'exited', crashed: 'crashed', errored: 'errored' } as const)[requestSession.status]]++;
bucket[statusKey]++;

if (existingClientAggregate) {
existingClientAggregate[dateBucketKey] = bucket;
Expand Down Expand Up @@ -118,4 +123,28 @@ export function startRequestSession(
}
}
};

return () => {
if (ended) {
return;
}
ended = true;

const pendingErrors = requestIsolationScope.getScopeData().sdkProcessingMetadata.requestSession?.pendingErrors;
if (!pendingErrors?.size) {
record(false);
return;
}

// A flush that starts while the errors settle waits for them, but its `flush` hook runs before this session
// is recorded. Such a session is sent at once, so that the flush includes it.
let isFlushing = false;
const unregisterFlushHook = client.on('flush', () => {
isFlushing = true;
});
void Promise.allSettled(pendingErrors).then(() => {
unregisterFlushHook();
record(isFlushing);
});
};
}
2 changes: 2 additions & 0 deletions packages/core/src/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ export interface SdkProcessingMetadata {
[key: string]: unknown;
requestSession?: {
status: 'ok' | 'errored' | 'crashed';
/** Error events of the request that are still in the event pipeline. */
pendingErrors?: Set<PromiseLike<unknown>>;
};
normalizedRequest?: RequestEventData;
dynamicSamplingContext?: Partial<DynamicSamplingContext>;
Expand Down
21 changes: 20 additions & 1 deletion packages/core/src/server-runtime-client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { SERVER_ADDRESS } from '@sentry/conventions/attributes';
import { createCheckInEnvelope } from './checkin';
import { Client } from './client';
import { Client, isExceptionEvent } from './client';
import { getIsolationScope } from './currentScopes';
import { DEBUG_BUILD } from './debug-build';
import {
Expand All @@ -19,6 +19,7 @@ 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 { makePromiseBuffer } from './utils/promisebuffer';
import { resolvedSyncPromise } from './utils/syncpromise';
import { _getTraceInfoFromScope } from './utils/trace-info';
Expand Down Expand Up @@ -109,6 +110,24 @@ export class ServerRuntimeClient<
return super.captureEvent(event, hint, scope);
}

/**
* @inheritDoc
*/
protected override _processEvent(
event: Event,
hint: EventHint,
currentScope: Scope,
isolationScope: Scope,
): PromiseLike<Event> {
if (!isExceptionEvent(event)) {
return super._processEvent(event, hint, currentScope, isolationScope);
}

const processedEvent = super._processEvent(event, hint, currentScope, isolationScope);
addPendingRequestSessionError(isolationScope, processedEvent);
return processedEvent;
}

/**
* Create a cron monitor check in and send it to Sentry.
*
Expand Down
22 changes: 22 additions & 0 deletions packages/core/src/utils/requestSession.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { Scope, SdkProcessingMetadata } from '../scope';

type RequestSession = NonNullable<SdkProcessingMetadata['requestSession']>;

export function getRequestSession(isolationScope: Scope): RequestSession | undefined {
return isolationScope.getScopeData().sdkProcessingMetadata.requestSession;
}

/** Tracks an error of the request that is still in the event pipeline, so the session waits for it. */
export function addPendingRequestSessionError(isolationScope: Scope, processing: PromiseLike<unknown>): void {
const requestSession = getRequestSession(isolationScope);
if (!requestSession) {
return;
}

const pendingErrors = (requestSession.pendingErrors ||= new Set());
const settle = (): void => {
pendingErrors.delete(processing);
};
pendingErrors.add(processing);
processing.then(settle, settle);
}
57 changes: 54 additions & 3 deletions packages/core/test/lib/server-runtime-client.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { describe, expect, it, test, vi } from 'vitest';
import { applySdkMetadata, createTransport, Scope } from '../../src';
import { beforeEach, describe, expect, it, test, vi } from 'vitest';
import { applySdkMetadata, createTransport, getIsolationScope, Scope } from '../../src';
import { startRequestSession } from '../../src/integrations/http/record-request-session';
import { captureMetricEvent, getMetricBuffer } from '../../src/metrics/internal';
import type { ServerRuntimeClientOptions } from '../../src/server-runtime-client';
import { ServerRuntimeClient } from '../../src/server-runtime-client';
import type { Event, EventHint } from '../../src/types/event';
import type { ErrorEvent, Event, EventHint } from '../../src/types/event';
import { resetGlobals } from '../testutils';

const PUBLIC_DSN = 'https://username@domain/123';

Expand All @@ -16,6 +18,10 @@ function getDefaultClientOptions(options: Partial<ServerRuntimeClientOptions> =
};
}

function delayed(event: ErrorEvent): Promise<ErrorEvent> {
return new Promise(resolve => setTimeout(() => resolve(event), 10));
}

describe('ServerRuntimeClient', () => {
let client: ServerRuntimeClient;

Expand Down Expand Up @@ -183,6 +189,51 @@ describe('ServerRuntimeClient', () => {
});
});

describe('request sessions', () => {
beforeEach(() => {
resetGlobals();
});

it('sends a session that settles during a flush, also when another request opened an aggregate', async () => {
client = new ServerRuntimeClient(
getDefaultClientOptions({
dsn: PUBLIC_DSN,
beforeSend: delayed,
}),
);
const sendSessionSpy = vi.spyOn(client, 'sendSession');
const endErroredRequestSession = startRequestSession(client, { requestIsolationScope: getIsolationScope() });
client.captureException(new Error('foo'));
endErroredRequestSession();

const flushed = client.flush();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[m] packages/core/test/lib/server-runtime-client.test.ts:209: Both new tests pass without the change

The new path in startRequestSession isn't proven by a test. That path waits on pendingErrors, then sends at once if a flush ran in the meantime. captureException still sets the status synchronously. So on the base, the session goes into the aggregate at endErroredRequestSession() and the flush hook sends it, which gives the same sendSession calls in both tests. I reverted the four src files to the base (f8f90a3), and both tests in request sessions still pass.

This assertion checks that nothing is sent while beforeSend is still pending. With it, the first test fails on the base and passes on this head:

Suggested change
const flushed = client.flush();
const flushed = client.flush();
expect(sendSessionSpy).not.toHaveBeenCalled();

The second test (aggregates a session that settles after the request ended when no flush runs) has the same gap.

startRequestSession(client, { requestIsolationScope: new Scope() })();
await flushed;

expect(sendSessionSpy).toHaveBeenCalledExactlyOnceWith({
aggregates: [{ started: expect.any(String), exited: 0, errored: 1, crashed: 0 }],
});
});

it('aggregates a session that settles after the request ended when no flush runs', async () => {
vi.useFakeTimers();
client = new ServerRuntimeClient(getDefaultClientOptions({ dsn: PUBLIC_DSN, beforeSend: delayed }));
const sendSessionSpy = vi.spyOn(client, 'sendSession');
const endErroredRequestSession = startRequestSession(client, { requestIsolationScope: getIsolationScope() });
client.captureException(new Error('foo'));
endErroredRequestSession();
await vi.advanceTimersByTimeAsync(10);
vi.useRealTimers();

startRequestSession(client, { requestIsolationScope: new Scope() })();
await client.flush();

expect(sendSessionSpy).toHaveBeenCalledExactlyOnceWith({
aggregates: [{ started: expect.any(String), exited: 1, errored: 1, crashed: 0 }],
});
});
});

describe('captureMessage', () => {
it('sends a message event with level info', () => {
const options = getDefaultClientOptions({ dsn: PUBLIC_DSN });
Expand Down
Loading