Skip to content

feat(integrations): Introduce processEvent hook on Integration #9015

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

Closed
wants to merge 1 commit into from
Closed
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
46 changes: 21 additions & 25 deletions packages/browser/src/integrations/dedupe.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Event, EventProcessor, Exception, Hub, Integration, StackFrame } from '@sentry/types';
import type { Event, Exception, Integration, StackFrame } from '@sentry/types';
import { logger } from '@sentry/utils';

/** Deduplication filter */
Expand All @@ -22,36 +22,32 @@ export class Dedupe implements Integration {
this.name = Dedupe.id;
}

/** @inheritDoc */
public setupOnce(_addGlobaleventProcessor: unknown, _getCurrentHub: unknown): void {
// noop
}

/**
* @inheritDoc
*/
public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {
const eventProcessor: EventProcessor = currentEvent => {
// We want to ignore any non-error type events, e.g. transactions or replays
// These should never be deduped, and also not be compared against as _previousEvent.
if (currentEvent.type) {
return currentEvent;
}
public processEvent(currentEvent: Event): Event | null {
// We want to ignore any non-error type events, e.g. transactions or replays
// These should never be deduped, and also not be compared against as _previousEvent.
if (currentEvent.type) {
return currentEvent;
}

const self = getCurrentHub().getIntegration(Dedupe);
if (self) {
// Juuust in case something goes wrong
try {
if (_shouldDropEvent(currentEvent, self._previousEvent)) {
__DEBUG_BUILD__ && logger.warn('Event dropped due to being a duplicate of previously captured event.');
return null;
}
} catch (_oO) {
return (self._previousEvent = currentEvent);
}

return (self._previousEvent = currentEvent);
// Juuust in case something goes wrong
try {
if (_shouldDropEvent(currentEvent, this._previousEvent)) {
__DEBUG_BUILD__ && logger.warn('Event dropped due to being a duplicate of previously captured event.');
return null;
}
return currentEvent;
};
} catch (_oO) {
return (this._previousEvent = currentEvent);
}

eventProcessor.id = this.name;
addGlobalEventProcessor(eventProcessor);
return (this._previousEvent = currentEvent);
}
}

Expand Down
45 changes: 22 additions & 23 deletions packages/browser/src/integrations/httpcontext.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';
import type { Event, Integration } from '@sentry/types';

import { WINDOW } from '../helpers';
Expand All @@ -23,28 +22,28 @@ export class HttpContext implements Integration {
* @inheritDoc
*/
public setupOnce(): void {
addGlobalEventProcessor((event: Event) => {
if (getCurrentHub().getIntegration(HttpContext)) {
// if none of the information we want exists, don't bother
if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {
return event;
}

// grab as much info as exists and add it to the event
const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);
const { referrer } = WINDOW.document || {};
const { userAgent } = WINDOW.navigator || {};

const headers = {
...(event.request && event.request.headers),
...(referrer && { Referer: referrer }),
...(userAgent && { 'User-Agent': userAgent }),
};
const request = { ...event.request, ...(url && { url }), headers };

return { ...event, request };
}
// noop
}

/** @inheritDoc */
public processEvent(event: Event): Event {
// if none of the information we want exists, don't bother
if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {
return event;
});
}

// grab as much info as exists and add it to the event
const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);
const { referrer } = WINDOW.document || {};
const { userAgent } = WINDOW.navigator || {};

const headers = {
...(event.request && event.request.headers),
...(referrer && { Referer: referrer }),
...(userAgent && { 'User-Agent': userAgent }),
};
const request = { ...event.request, ...(url && { url }), headers };

return { ...event, request };
}
}
2 changes: 1 addition & 1 deletion packages/browser/src/profiling/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export class BrowserProfilingIntegration implements Integration {
/**
* @inheritDoc
*/
public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {
public setupOnce(_addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {
this.getCurrentHub = getCurrentHub;
const client = this.getCurrentHub().getClient() as BrowserClient;

Expand Down
69 changes: 42 additions & 27 deletions packages/core/src/baseclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
Event,
EventDropReason,
EventHint,
EventProcessor,
Integration,
IntegrationClass,
Outcome,
Expand Down Expand Up @@ -43,6 +44,7 @@ import {

import { getEnvelopeEndpointWithUrlEncodedAuth } from './api';
import { createEventEnvelope, createSessionEnvelope } from './envelope';
import { notifyEventProcessors } from './eventProcessors';
import type { IntegrationIndex } from './integration';
import { setupIntegration, setupIntegrations } from './integration';
import type { Scope } from './scope';
Expand Down Expand Up @@ -107,6 +109,8 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
// eslint-disable-next-line @typescript-eslint/ban-types
private _hooks: Record<string, Function[]>;

private _eventProcessors: EventProcessor[];

/**
* Initializes this client instance.
*
Expand All @@ -119,6 +123,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
this._numProcessing = 0;
this._outcomes = {};
this._hooks = {};
this._eventProcessors = [];

if (options.dsn) {
this._dsn = makeDsn(options.dsn);
Expand Down Expand Up @@ -280,6 +285,11 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
});
}

/** @inheritDoc */
public addEventProcessor(eventProcessor: EventProcessor): void {
this._eventProcessors.push(eventProcessor);
}

/**
* Sets up the integrations
*/
Expand Down Expand Up @@ -545,36 +555,41 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {

this.emit('preprocessEvent', event, hint);

return prepareEvent(options, event, hint, scope).then(evt => {
if (evt === null) {
return evt;
}
return prepareEvent(options, event, hint, scope)
.then(evt => {
// Process client-scoped event processors
return notifyEventProcessors(this._eventProcessors, evt, hint);
})
.then(evt => {
if (evt === null) {
return evt;
}

// If a trace context is not set on the event, we use the propagationContext set on the event to
// generate a trace context. If the propagationContext does not have a dynamic sampling context, we
// also generate one for it.
const { propagationContext } = evt.sdkProcessingMetadata || {};
const trace = evt.contexts && evt.contexts.trace;
if (!trace && propagationContext) {
const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext as PropagationContext;
evt.contexts = {
trace: {
trace_id,
span_id: spanId,
parent_span_id: parentSpanId,
},
...evt.contexts,
};
// If a trace context is not set on the event, we use the propagationContext set on the event to
// generate a trace context. If the propagationContext does not have a dynamic sampling context, we
// also generate one for it.
const { propagationContext } = evt.sdkProcessingMetadata || {};
const trace = evt.contexts && evt.contexts.trace;
if (!trace && propagationContext) {
const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext as PropagationContext;
evt.contexts = {
trace: {
trace_id,
span_id: spanId,
parent_span_id: parentSpanId,
},
...evt.contexts,
};

const dynamicSamplingContext = dsc ? dsc : getDynamicSamplingContextFromClient(trace_id, this, scope);
const dynamicSamplingContext = dsc ? dsc : getDynamicSamplingContextFromClient(trace_id, this, scope);

evt.sdkProcessingMetadata = {
dynamicSamplingContext,
...evt.sdkProcessingMetadata,
};
}
return evt;
});
evt.sdkProcessingMetadata = {
dynamicSamplingContext,
...evt.sdkProcessingMetadata,
};
}
return evt;
});
}

/**
Expand Down
51 changes: 51 additions & 0 deletions packages/core/src/eventProcessors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import type { Event, EventHint, EventProcessor } from '@sentry/types';
import { getGlobalSingleton, isThenable, logger, SyncPromise } from '@sentry/utils';

/**
* Returns the global event processors.
*/
export function getGlobalEventProcessors(): EventProcessor[] {
return getGlobalSingleton<EventProcessor[]>('globalEventProcessors', () => []);
}

/**
* Add a EventProcessor to be kept globally.
* @param callback EventProcessor to add
*/
export function addGlobalEventProcessor(callback: EventProcessor): void {
getGlobalEventProcessors().push(callback);
}

/**
* Process an array of event processors, returning the processed event (or `null` if the event was dropped).
*/
export function notifyEventProcessors(
processors: EventProcessor[],
event: Event | null,
hint: EventHint,
index: number = 0,
): PromiseLike<Event | null> {
return new SyncPromise<Event | null>((resolve, reject) => {
const processor = processors[index];
if (event === null || typeof processor !== 'function') {
resolve(event);
} else {
const result = processor({ ...event }, hint) as Event | null;

__DEBUG_BUILD__ &&
processor.id &&
result === null &&
logger.log(`Event processor "${processor.id}" dropped event`);

if (isThenable(result)) {
void result
.then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))
.then(null, reject);
} else {
void notifyEventProcessors(processors, result, hint, index + 1)
.then(resolve)
.then(null, reject);
}
}
});
}
3 changes: 2 additions & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ export {
} from './hub';
export { makeSession, closeSession, updateSession } from './session';
export { SessionFlusher } from './sessionflusher';
export { addGlobalEventProcessor, Scope } from './scope';
export { Scope } from './scope';
export { addGlobalEventProcessor } from './eventProcessors';
export { getEnvelopeEndpointWithUrlEncodedAuth, getReportDialogEndpoint } from './api';
export { BaseClient } from './baseclient';
export { ServerRuntimeClient } from './server-runtime-client';
Expand Down
16 changes: 13 additions & 3 deletions packages/core/src/integration.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { Client, Integration, Options } from '@sentry/types';
import type { Client, Event, EventHint, Integration, Options } from '@sentry/types';
import { arrayify, logger } from '@sentry/utils';

import { addGlobalEventProcessor } from './eventProcessors';
import { getCurrentHub } from './hub';
import { addGlobalEventProcessor } from './scope';

declare module '@sentry/types' {
interface Integration {
Expand Down Expand Up @@ -107,10 +107,20 @@ export function setupIntegration(client: Client, integration: Integration, integ
}

if (client.on && typeof integration.preprocessEvent === 'function') {
const callback = integration.preprocessEvent.bind(integration);
const callback = integration.preprocessEvent.bind(integration) as typeof integration.preprocessEvent;
client.on('preprocessEvent', (event, hint) => callback(event, hint, client));
}

if (client.addEventProcessor && typeof integration.processEvent === 'function') {
const callback = integration.processEvent.bind(integration) as typeof integration.processEvent;

const processor = Object.assign((event: Event, hint: EventHint) => callback(event, hint, client), {
id: integration.name,
});

client.addEventProcessor(processor);
}

__DEBUG_BUILD__ && logger.log(`Integration installed: ${integration.name}`);
}

Expand Down
26 changes: 9 additions & 17 deletions packages/core/src/integrations/inboundfilters.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types';
import type { Client, Event, EventHint, Integration, StackFrame } from '@sentry/types';
import { getEventDescription, logger, stringMatchesSomePattern } from '@sentry/utils';

// "Script error." is hard coded into browsers for errors that it can't read.
Expand Down Expand Up @@ -48,23 +48,15 @@ export class InboundFilters implements Integration {
/**
* @inheritDoc
*/
public setupOnce(addGlobalEventProcessor: (processor: EventProcessor) => void, getCurrentHub: () => Hub): void {
const eventProcess: EventProcessor = (event: Event) => {
const hub = getCurrentHub();
if (hub) {
const self = hub.getIntegration(InboundFilters);
if (self) {
const client = hub.getClient();
const clientOptions = client ? client.getOptions() : {};
const options = _mergeOptions(self._options, clientOptions);
return _shouldDropEvent(event, options) ? null : event;
}
}
return event;
};
public setupOnce(_addGlobaleventProcessor: unknown, _getCurrentHub: unknown): void {
// noop
}

eventProcess.id = this.name;
addGlobalEventProcessor(eventProcess);
/** @inheritDoc */
public processEvent(event: Event, _eventHint: EventHint, client: Client): Event | null {
const clientOptions = client.getOptions();
const options = _mergeOptions(this._options, clientOptions);
return _shouldDropEvent(event, options) ? null : event;
}
}

Expand Down
Loading