Skip to content

feat(node): Add abnormal session support for ANR #9268

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 17, 2023
Merged
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/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ export function updateSession(session: Session, context: SessionContext = {}): v

session.timestamp = context.timestamp || timestampInSeconds();

if (context.abnormal_mechanism) {
session.abnormal_mechanism = context.abnormal_mechanism;
}

if (context.ignoreDuration) {
session.ignoreDuration = context.ignoreDuration;
}
Expand Down Expand Up @@ -143,6 +147,7 @@ function sessionToJSON(session: Session): SerializedSession {
errors: session.errors,
did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,
duration: session.duration,
abnormal_mechanism: session.abnormal_mechanism,
attrs: {
release: session.release,
environment: session.environment,
Expand Down
31 changes: 31 additions & 0 deletions packages/node-integration-tests/suites/anr/basic-session.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const crypto = require('crypto');

const Sentry = require('@sentry/node');

const { transport } = require('./test-transport.js');

// close both processes after 5 seconds
setTimeout(() => {
process.exit();
}, 5000);

Sentry.init({
dsn: 'https://[email protected]/1337',
release: '1.0',
debug: true,
transport,
});

Sentry.enableAnrDetection({ captureStackTrace: true, anrThreshold: 200 }).then(() => {
function longWork() {
for (let i = 0; i < 100; i++) {
const salt = crypto.randomBytes(128).toString('base64');
// eslint-disable-next-line no-unused-vars
const hash = crypto.pbkdf2Sync('myPassword', salt, 10000, 512, 'sha512');
}
}

setTimeout(() => {
longWork();
}, 1000);
});
8 changes: 4 additions & 4 deletions packages/node-integration-tests/suites/anr/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const crypto = require('crypto');

const Sentry = require('@sentry/node');

const { transport } = require('./test-transport.js');

// close both processes after 5 seconds
setTimeout(() => {
process.exit();
Expand All @@ -11,10 +13,8 @@ Sentry.init({
dsn: 'https://[email protected]/1337',
release: '1.0',
debug: true,
beforeSend: event => {
// eslint-disable-next-line no-console
console.log(JSON.stringify(event));
},
autoSessionTracking: false,
transport,
});

Sentry.enableAnrDetection({ captureStackTrace: true, anrThreshold: 200 }).then(() => {
Expand Down
8 changes: 4 additions & 4 deletions packages/node-integration-tests/suites/anr/basic.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import * as crypto from 'crypto';

import * as Sentry from '@sentry/node';

const { transport } = await import('./test-transport.js');

// close both processes after 5 seconds
setTimeout(() => {
process.exit();
Expand All @@ -11,10 +13,8 @@ Sentry.init({
dsn: 'https://[email protected]/1337',
release: '1.0',
debug: true,
beforeSend: event => {
// eslint-disable-next-line no-console
console.log(JSON.stringify(event));
},
autoSessionTracking: false,
transport,
});

await Sentry.enableAnrDetection({ captureStackTrace: true, anrThreshold: 200 });
Expand Down
8 changes: 4 additions & 4 deletions packages/node-integration-tests/suites/anr/forked.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const crypto = require('crypto');

const Sentry = require('@sentry/node');

const { transport } = require('./test-transport.js');

// close both processes after 5 seconds
setTimeout(() => {
process.exit();
Expand All @@ -11,10 +13,8 @@ Sentry.init({
dsn: 'https://[email protected]/1337',
release: '1.0',
debug: true,
beforeSend: event => {
// eslint-disable-next-line no-console
console.log(JSON.stringify(event));
},
autoSessionTracking: false,
transport,
});

Sentry.enableAnrDetection({ captureStackTrace: true, anrThreshold: 200 }).then(() => {
Expand Down
17 changes: 17 additions & 0 deletions packages/node-integration-tests/suites/anr/test-transport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const { TextEncoder, TextDecoder } = require('util');

const { createTransport } = require('@sentry/core');
const { parseEnvelope } = require('@sentry/utils');

const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();

// A transport that just logs the envelope payloads to console for checking in tests
exports.transport = () => {
return createTransport({ recordDroppedEvent: () => {}, textEncoder }, async request => {
const env = parseEnvelope(request.body, textEncoder, textDecoder);
// eslint-disable-next-line no-console
console.log(JSON.stringify(env[1][0][1]));
return { statusCode: 200 };
});
};
69 changes: 50 additions & 19 deletions packages/node-integration-tests/suites/anr/test.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,40 @@
import type { Event } from '@sentry/node';
import type { SerializedSession } from '@sentry/types';
import { parseSemver } from '@sentry/utils';
import * as childProcess from 'child_process';
import * as path from 'path';

const NODE_VERSION = parseSemver(process.versions.node).major || 0;

/** The output will contain logging so we need to find the line that parses as JSON */
function parseJsonLine<T>(input: string): T {
return (
input
.split('\n')
.map(line => {
try {
return JSON.parse(line) as T;
} catch {
return undefined;
}
})
.filter(a => a) as T[]
)[0];
function parseJsonLines<T extends unknown[]>(input: string, expected: number): T {
const results = input
.split('\n')
.map(line => {
try {
return JSON.parse(line) as T;
} catch {
return undefined;
}
})
.filter(a => a) as T;

expect(results.length).toEqual(expected);

return results;
}

describe('should report ANR when event loop blocked', () => {
test('CJS', done => {
// The stack trace is different when node < 12
const testFramesDetails = NODE_VERSION >= 12;

expect.assertions(testFramesDetails ? 6 : 4);
expect.assertions(testFramesDetails ? 7 : 5);

const testScriptPath = path.resolve(__dirname, 'basic.js');

childProcess.exec(`node ${testScriptPath}`, { encoding: 'utf8' }, (_, stdout) => {
const event = parseJsonLine<Event>(stdout);
const [event] = parseJsonLines<[Event]>(stdout, 1);

expect(event.exception?.values?.[0].mechanism).toEqual({ type: 'ANR' });
expect(event.exception?.values?.[0].type).toEqual('ApplicationNotResponding');
Expand All @@ -53,12 +56,12 @@ describe('should report ANR when event loop blocked', () => {
return;
}

expect.assertions(6);
expect.assertions(7);

const testScriptPath = path.resolve(__dirname, 'basic.mjs');

childProcess.exec(`node ${testScriptPath}`, { encoding: 'utf8' }, (_, stdout) => {
const event = parseJsonLine<Event>(stdout);
const [event] = parseJsonLines<[Event]>(stdout, 1);

expect(event.exception?.values?.[0].mechanism).toEqual({ type: 'ANR' });
expect(event.exception?.values?.[0].type).toEqual('ApplicationNotResponding');
Expand All @@ -71,16 +74,44 @@ describe('should report ANR when event loop blocked', () => {
});
});

test('With session', done => {
// The stack trace is different when node < 12
const testFramesDetails = NODE_VERSION >= 12;

expect.assertions(testFramesDetails ? 9 : 7);

const testScriptPath = path.resolve(__dirname, 'basic-session.js');

childProcess.exec(`node ${testScriptPath}`, { encoding: 'utf8' }, (_, stdout) => {

Check warning

Code scanning / CodeQL

Shell command built from environment values

This shell command depends on an uncontrolled [absolute path](1).
const [session, event] = parseJsonLines<[SerializedSession, Event]>(stdout, 2);

expect(event.exception?.values?.[0].mechanism).toEqual({ type: 'ANR' });
expect(event.exception?.values?.[0].type).toEqual('ApplicationNotResponding');
expect(event.exception?.values?.[0].value).toEqual('Application Not Responding for at least 200 ms');
expect(event.exception?.values?.[0].stacktrace?.frames?.length).toBeGreaterThan(4);

if (testFramesDetails) {
expect(event.exception?.values?.[0].stacktrace?.frames?.[2].function).toEqual('?');
expect(event.exception?.values?.[0].stacktrace?.frames?.[3].function).toEqual('longWork');
}

expect(session.status).toEqual('abnormal');
expect(session.abnormal_mechanism).toEqual('anr_foreground');

done();
});
});

test('from forked process', done => {
// The stack trace is different when node < 12
const testFramesDetails = NODE_VERSION >= 12;

expect.assertions(testFramesDetails ? 6 : 4);
expect.assertions(testFramesDetails ? 7 : 5);

const testScriptPath = path.resolve(__dirname, 'forker.js');

childProcess.exec(`node ${testScriptPath}`, { encoding: 'utf8' }, (_, stdout) => {
const event = parseJsonLine<Event>(stdout);
const [event] = parseJsonLines<[Event]>(stdout, 1);

expect(event.exception?.values?.[0].mechanism).toEqual({ type: 'ANR' });
expect(event.exception?.values?.[0].type).toEqual('ApplicationNotResponding');
Expand Down
Loading