Skip to content

feat: Provide normalizeDepth option and sensible default for scope methods #2404

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 1 commit into from
Feb 3, 2020
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: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@

## Unreleased

- [core] feat: Provide `normalizeDepth` option and sensible default for scope methods (#2404)
- [browser] fix: Export `EventHint` type (#2407)

## 5.11.2

- [apm] fix: Add new option to `Tracing` `maxTransactionTimeout` determines the max length of a transaction
- [hub] ref: Always also set transaction name on the top span in the scope
- [core] fix: Use event_id from hint given by top-level hub calls
- [core] fix: Use `event_id` from hint given by top-level hub calls

## 5.11.1

Expand Down
4 changes: 2 additions & 2 deletions packages/browser/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { captureException, withScope } from '@sentry/core';
import { Event as SentryEvent, Mechanism, Scope, WrappedFunction } from '@sentry/types';
import { addExceptionMechanism, addExceptionTypeValue, normalize } from '@sentry/utils';
import { addExceptionMechanism, addExceptionTypeValue } from '@sentry/utils';

let ignoreOnError: number = 0;

Expand Down Expand Up @@ -98,7 +98,7 @@ export function wrap(

processedEvent.extra = {
...processedEvent.extra,
arguments: normalize(args, 3),
arguments: args,
};

return processedEvent;
Expand Down
7 changes: 2 additions & 5 deletions packages/browser/src/integrations/breadcrumbs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
getGlobalObject,
htmlTreeAsString,
logger,
normalize,
parseUrl,
safeJoin,
} from '@sentry/utils';
Expand Down Expand Up @@ -75,9 +74,7 @@ export class Breadcrumbs implements Integration {
const breadcrumb = {
category: 'console',
data: {
extra: {
arguments: normalize(handlerData.args, 3),
},
arguments: handlerData.args,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is "kinda" breaking if someone is relying on such an odd data point, but if we won't change it, it'll have same issue as the one described for ExtractErrorData

logger: 'console',
},
level: Severity.fromString(handlerData.level),
Expand All @@ -87,7 +84,7 @@ export class Breadcrumbs implements Integration {
if (handlerData.level === 'assert') {
if (handlerData.args[0] === false) {
breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;
breadcrumb.data.extra.arguments = normalize(handlerData.args.slice(1), 3);
breadcrumb.data.arguments = handlerData.args.slice(1);
} else {
// Don't capture a breadcrumb for passed assertions
return;
Expand Down
50 changes: 47 additions & 3 deletions packages/core/src/baseclient.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Scope } from '@sentry/hub';
import { Client, Event, EventHint, Integration, IntegrationClass, Options, SdkInfo, Severity } from '@sentry/types';
import { Dsn, isPrimitive, isThenable, logger, SyncPromise, truncate, uuid4 } from '@sentry/utils';
import { Dsn, isPrimitive, isThenable, logger, normalize, SyncPromise, truncate, uuid4 } from '@sentry/utils';

import { Backend, BackendClass } from './basebackend';
import { IntegrationIndex, setupIntegrations } from './integration';
Expand Down Expand Up @@ -256,7 +256,7 @@ export abstract class BaseClient<B extends Backend, O extends Options> implement
* @returns A new event with more information.
*/
protected _prepareEvent(event: Event, scope?: Scope, hint?: EventHint): PromiseLike<Event | null> {
const { environment, release, dist, maxValueLength = 250 } = this.getOptions();
const { environment, release, dist, maxValueLength = 250, normalizeDepth = 3 } = this.getOptions();

const prepared: Event = { ...event };
if (prepared.environment === undefined && environment !== undefined) {
Expand Down Expand Up @@ -300,7 +300,51 @@ export abstract class BaseClient<B extends Backend, O extends Options> implement
result = scope.applyToEvent(prepared, hint);
}

return result;
return result.then(evt => {
// tslint:disable-next-line:strict-type-predicates
if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {
return this._normalizeEvent(evt, normalizeDepth);
}
return evt;
});
}

/**
* Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.
* Normalized keys:
* - `breadcrumbs.data`
* - `user`
* - `contexts`
* - `extra`
* @param event Event
* @returns Normalized event
*/
protected _normalizeEvent(event: Event | null, depth: number): Event | null {
if (!event) {
return null;
}

// tslint:disable:no-unsafe-any
return {
...event,
...(event.breadcrumbs && {
breadcrumbs: event.breadcrumbs.map(b => ({
...b,
...(b.data && {
data: normalize(b.data, depth),
}),
})),
}),
...(event.user && {
user: normalize(event.user, depth),
}),
...(event.contexts && {
contexts: normalize(event.contexts, depth),
}),
...(event.extra && {
extra: normalize(event.extra, depth),
}),
};
}

/**
Expand Down
137 changes: 137 additions & 0 deletions packages/core/test/lib/base.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,143 @@ describe('BaseClient', () => {
});
});

test('normalizes event with default depth of 3', () => {
expect.assertions(1);
const client = new TestClient({ dsn: PUBLIC_DSN });
const fourLevelsObject = {
a: {
b: {
c: 'wat',
d: {
e: 'wat',
},
},
},
};
const normalizedObject = {
a: {
b: {
c: 'wat',
d: '[Object]',
},
},
};
const fourLevelBreadcrumb = {
data: fourLevelsObject,
message: 'wat',
};
const normalizedBreadcrumb = {
data: normalizedObject,
message: 'wat',
};
client.captureEvent({
breadcrumbs: [fourLevelBreadcrumb, fourLevelBreadcrumb, fourLevelBreadcrumb],
contexts: fourLevelsObject,
extra: fourLevelsObject,
user: fourLevelsObject,
});
expect(TestBackend.instance!.event!).toEqual({
breadcrumbs: [normalizedBreadcrumb, normalizedBreadcrumb, normalizedBreadcrumb],
contexts: normalizedObject,
event_id: '42',
extra: normalizedObject,
user: normalizedObject,
});
});

test('normalization respects `normalizeDepth` option', () => {
expect.assertions(1);
const client = new TestClient({
dsn: PUBLIC_DSN,
normalizeDepth: 2,
});
const fourLevelsObject = {
a: {
b: {
c: 'wat',
d: {
e: 'wat',
},
},
},
};
const normalizedObject = {
a: {
b: '[Object]',
},
};
const fourLevelBreadcrumb = {
data: fourLevelsObject,
message: 'wat',
};
const normalizedBreadcrumb = {
data: normalizedObject,
message: 'wat',
};
client.captureEvent({
breadcrumbs: [fourLevelBreadcrumb, fourLevelBreadcrumb, fourLevelBreadcrumb],
contexts: fourLevelsObject,
extra: fourLevelsObject,
user: fourLevelsObject,
});
expect(TestBackend.instance!.event!).toEqual({
breadcrumbs: [normalizedBreadcrumb, normalizedBreadcrumb, normalizedBreadcrumb],
contexts: normalizedObject,
event_id: '42',
extra: normalizedObject,
user: normalizedObject,
});
});

test('skips normalization when `normalizeDepth: 0`', () => {
expect.assertions(1);
const client = new TestClient({
dsn: PUBLIC_DSN,
normalizeDepth: 0,
});
const fourLevelsObject = {
a: {
b: {
c: 'wat',
d: {
e: 'wat',
},
},
},
};
const normalizedObject = {
a: {
b: {
c: 'wat',
d: {
e: 'wat',
},
},
},
};
const fourLevelBreadcrumb = {
data: fourLevelsObject,
message: 'wat',
};
const normalizedBreadcrumb = {
data: normalizedObject,
message: 'wat',
};
client.captureEvent({
breadcrumbs: [fourLevelBreadcrumb, fourLevelBreadcrumb, fourLevelBreadcrumb],
contexts: fourLevelsObject,
extra: fourLevelsObject,
user: fourLevelsObject,
});
expect(TestBackend.instance!.event!).toEqual({
breadcrumbs: [normalizedBreadcrumb, normalizedBreadcrumb, normalizedBreadcrumb],
contexts: normalizedObject,
event_id: '42',
extra: normalizedObject,
user: normalizedObject,
});
});

test('calls beforeSend and uses original event without any changes', () => {
expect.assertions(1);
const beforeSend = jest.fn(event => event);
Expand Down
32 changes: 17 additions & 15 deletions packages/hub/src/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
Span,
User,
} from '@sentry/types';
import { getGlobalObject, isThenable, normalize, SyncPromise, timestampWithMs } from '@sentry/utils';
import { getGlobalObject, isThenable, SyncPromise, timestampWithMs } from '@sentry/utils';

/**
* Holds additional event information. {@link Scope.applyToEvent} will be
Expand Down Expand Up @@ -115,7 +115,7 @@ export class Scope implements ScopeInterface {
* @inheritDoc
*/
public setUser(user: User | null): this {
this._user = normalize(user);
this._user = user || {};
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The implementation here was incorrect from the beginning. normalize returned any, so we did this._user = <any>, which shouldn't be allowed, as this._user is a non-optional User type. Also, clear sets it to {} not null.

this._notifyScopeListeners();
return this;
}
Expand All @@ -126,7 +126,7 @@ export class Scope implements ScopeInterface {
public setTags(tags: { [key: string]: string }): this {
this._tags = {
...this._tags,
...normalize(tags),
...tags,
};
this._notifyScopeListeners();
return this;
Expand All @@ -136,18 +136,18 @@ export class Scope implements ScopeInterface {
* @inheritDoc
*/
public setTag(key: string, value: string): this {
this._tags = { ...this._tags, [key]: normalize(value) };
this._tags = { ...this._tags, [key]: value };
this._notifyScopeListeners();
return this;
}

/**
* @inheritDoc
*/
public setExtras(extra: { [key: string]: any }): this {
public setExtras(extras: { [key: string]: any }): this {
this._extra = {
...this._extra,
...normalize(extra),
...extras,
};
this._notifyScopeListeners();
return this;
Expand All @@ -157,7 +157,7 @@ export class Scope implements ScopeInterface {
* @inheritDoc
*/
public setExtra(key: string, extra: any): this {
this._extra = { ...this._extra, [key]: normalize(extra) };
this._extra = { ...this._extra, [key]: extra };
this._notifyScopeListeners();
return this;
}
Expand All @@ -166,7 +166,7 @@ export class Scope implements ScopeInterface {
* @inheritDoc
*/
public setFingerprint(fingerprint: string[]): this {
this._fingerprint = normalize(fingerprint);
this._fingerprint = fingerprint;
this._notifyScopeListeners();
return this;
}
Expand All @@ -175,7 +175,7 @@ export class Scope implements ScopeInterface {
* @inheritDoc
*/
public setLevel(level: Severity): this {
this._level = normalize(level);
this._level = level;
this._notifyScopeListeners();
return this;
}
Expand All @@ -195,8 +195,8 @@ export class Scope implements ScopeInterface {
/**
* @inheritDoc
*/
public setContext(name: string, context: { [key: string]: any } | null): this {
this._context[name] = context ? normalize(context) : undefined;
public setContext(key: string, context: { [key: string]: any } | null): this {
this._context = { ...this._context, [key]: context };
this._notifyScopeListeners();
return this;
}
Expand Down Expand Up @@ -260,13 +260,15 @@ export class Scope implements ScopeInterface {
* @inheritDoc
*/
public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {
const timestamp = timestampWithMs();
const mergedBreadcrumb = { timestamp, ...breadcrumb };
const mergedBreadcrumb = {
timestamp: timestampWithMs(),
...breadcrumb,
};

this._breadcrumbs =
maxBreadcrumbs !== undefined && maxBreadcrumbs >= 0
? [...this._breadcrumbs, normalize(mergedBreadcrumb)].slice(-maxBreadcrumbs)
: [...this._breadcrumbs, normalize(mergedBreadcrumb)];
? [...this._breadcrumbs, mergedBreadcrumb].slice(-maxBreadcrumbs)
: [...this._breadcrumbs, mergedBreadcrumb];
this._notifyScopeListeners();
return this;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/hub/test/scope.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ describe('Scope', () => {
const scope = new Scope();
scope.setExtra('a', 1);
scope.setExtras({ a: undefined });
expect((scope as any)._extra).toEqual({ a: '[undefined]' });
expect((scope as any)._extra).toEqual({ a: undefined });
});
});

Expand Down Expand Up @@ -63,7 +63,7 @@ describe('Scope', () => {
const scope = new Scope();
scope.setUser({ id: '1' });
scope.setUser(null);
expect((scope as any)._user).toEqual(null);
expect((scope as any)._user).toEqual({});
});
});

Expand Down
Loading