Skip to content

feat(core): Add lifecycle hooks #7370

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 11 commits into from
Mar 8, 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
36 changes: 36 additions & 0 deletions packages/core/src/baseclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type {
SessionAggregates,
Severity,
SeverityLevel,
Transaction,
TransactionEvent,
Transport,
} from '@sentry/types';
Expand Down Expand Up @@ -97,6 +98,9 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
/** Holds flushable */
private _outcomes: { [key: string]: number } = {};

// eslint-disable-next-line @typescript-eslint/ban-types
private _hooks: Record<string, Function[]> = {};

/**
* Initializes this client instance.
*
Expand Down Expand Up @@ -351,6 +355,38 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
}
}

// Keep on() & emit() signatures in sync with types' client.ts interface

/** @inheritdoc */
public on(hook: 'startTransaction' | 'finishTransaction', callback: (transaction: Transaction) => void): void;

/** @inheritdoc */
public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;

/** @inheritdoc */
public on(hook: string, callback: unknown): void {
if (!this._hooks[hook]) {
this._hooks[hook] = [];
}

// @ts-ignore We assue the types are correct
this._hooks[hook].push(callback);
}

/** @inheritdoc */
public emit(hook: 'startTransaction' | 'finishTransaction', transaction: Transaction): void;

/** @inheritdoc */
public emit(hook: 'beforeEnvelope', envelope: Envelope): void;

/** @inheritdoc */
public emit(hook: string, ...rest: unknown[]): void {
if (this._hooks[hook]) {
// @ts-ignore we cannot enforce the callback to match the hook
this._hooks[hook].forEach(callback => callback(...rest));
}
}

/** Updates existing session based on the provided event */
protected _updateSessionFromEvent(session: Session, event: Event): void {
let crashed = false;
Expand Down
45 changes: 44 additions & 1 deletion packages/core/test/lib/base.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Event, Span } from '@sentry/types';
import type { Client, Envelope, Event, Span, Transaction } from '@sentry/types';
import { dsnToString, logger, SentryError, SyncPromise } from '@sentry/utils';

import { Hub, makeSession, Scope } from '../../src';
Expand Down Expand Up @@ -1730,4 +1730,47 @@ describe('BaseClient', () => {
expect(clearedOutcomes4.length).toEqual(0);
});
});

describe('hooks', () => {
const options = getDefaultTestClientOptions({ dsn: PUBLIC_DSN });

// Make sure types work for both Client & BaseClient
const scenarios = [
['BaseClient', new TestClient(options)],
['Client', new TestClient(options) as Client],
] as const;

describe.each(scenarios)('with client %s', (_, client) => {
it('should call a startTransaction hook', () => {
expect.assertions(1);

const mockTransaction = {
traceId: '86f39e84263a4de99c326acab3bfe3bd',
} as Transaction;

client.on?.('startTransaction', transaction => {
expect(transaction).toEqual(mockTransaction);
});

client.emit?.('startTransaction', mockTransaction);
});

it('should call a beforeEnvelope hook', () => {
expect.assertions(1);

const mockEnvelope = [
{
event_id: '12345',
},
{},
] as Envelope;

client.on?.('beforeEnvelope', envelope => {
expect(envelope).toEqual(mockEnvelope);
});

client.emit?.('beforeEnvelope', mockEnvelope);
});
});
});
});
27 changes: 27 additions & 0 deletions packages/types/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import type { EventDropReason } from './clientreport';
import type { DataCategory } from './datacategory';
import type { DsnComponents } from './dsn';
import type { Envelope } from './envelope';
import type { Event, EventHint } from './event';
import type { Integration, IntegrationClass } from './integration';
import type { ClientOptions } from './options';
import type { Scope } from './scope';
import type { SdkMetadata } from './sdkmetadata';
import type { Session, SessionAggregates } from './session';
import type { Severity, SeverityLevel } from './severity';
import type { Transaction } from './transaction';
import type { Transport } from './transport';

/**
Expand Down Expand Up @@ -147,4 +149,29 @@ export interface Client<O extends ClientOptions = ClientOptions> {
* @param event The dropped event.
*/
recordDroppedEvent(reason: EventDropReason, dataCategory: DataCategory, event?: Event): void;

// HOOKS
// TODO(v8): Make the hooks non-optional.

/**
* Register a callback for transaction start and finish.
*/
on?(hook: 'startTransaction' | 'finishTransaction', callback: (transaction: Transaction) => void): void;

/**
* Register a callback for transaction start and finish.
*/
on?(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;

/**
* Fire a hook event for transaction start and finish. Expects to be given a transaction as the
* second argument.
*/
emit?(hook: 'startTransaction' | 'finishTransaction', transaction: Transaction): void;

/*
* Fire a hook event for envelope creation and sending. Expects to be given an envelope as the
* second argument.
*/
emit?(hook: 'beforeEnvelope', envelope: Envelope): void;
}