Skip to content
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

feat(core): Add lifecycle hooks #7370

Merged
merged 11 commits into from
Mar 8, 2023
Merged
25 changes: 25 additions & 0 deletions packages/core/src/baseclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import type {
Event,
EventDropReason,
EventHint,
Hook,
HookStore,
Integration,
IntegrationClass,
Outcome,
Expand Down Expand Up @@ -97,6 +99,8 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
/** Holds flushable */
private _outcomes: { [key: string]: number } = {};

private _hooks: HookStore = {};

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

/**
* @inheritDoc
*/
public on<HookType extends Hook>(hook: HookType['name'], callback: HookType['callback']): void {
if (!this._hooks[hook]) {
this._hooks[hook] = [];
}

(this._hooks[hook] as HookType['callback'][]).push(callback);
}

/**
* @inheritDoc
*/
public emit<HookType extends Hook>(hook: HookType['name'], ...args: Parameters<HookType['callback']>): void {
if (this._hooks[hook]) {
// @ts-ignore it does not like ...args, but we know this is correct
(this._hooks[hook] as HookType['callback'][]).forEach(callback => callback(...args));
}
}

/** Updates existing session based on the provided event */
protected _updateSessionFromEvent(session: Session, event: Event): void {
let crashed = false;
Expand Down
41 changes: 40 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 { Event, Span, Transaction, TransactionHook, EnvelopeHook, Envelope } from '@sentry/types';
import { dsnToString, logger, SentryError, SyncPromise } from '@sentry/utils';

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

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

const options = getDefaultTestClientOptions({ dsn: PUBLIC_DSN });
const client = new TestClient(options);

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

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

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

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

const options = getDefaultTestClientOptions({ dsn: PUBLIC_DSN });
const client = new TestClient(options);

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

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

client?.emit<EnvelopeHook>('beforeEnvelope', mockEnvelope);
});
});
});
15 changes: 15 additions & 0 deletions packages/types/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { EventDropReason } from './clientreport';
import type { DataCategory } from './datacategory';
import type { DsnComponents } from './dsn';
import type { Event, EventHint } from './event';
import type { Hook } from './hooks';
import type { Integration, IntegrationClass } from './integration';
import type { ClientOptions } from './options';
import type { Scope } from './scope';
Expand Down Expand Up @@ -147,4 +148,18 @@ 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?<HookType extends Hook>(hook: HookType['name'], callback: HookType['callback']): void;

/*
* Fire a hook event for envelope creation and sending. Expects to be given an envelope as the
* second argument.
*/
emit?<HookType extends Hook>(hook: HookType['name'], ...args: Parameters<HookType['callback']>): void;
}
20 changes: 20 additions & 0 deletions packages/types/src/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import type { Envelope } from './envelope';
import type { Transaction } from './transaction';

// Hooks related to transaction start/finish
export type TransactionHook = {
name: 'startTransaction' | 'transactionFinish';
callback: (transaction: Transaction) => void;
};

// Hooks related to envelope create and send
export type EnvelopeHook = {
name: 'beforeEnvelope';
callback: (envelope: Envelope) => void;
};

export type Hook = TransactionHook | EnvelopeHook;

type HookStoreItem<T extends Hook> = Partial<Record<T['name'], T['callback'][]>>;

export type HookStore = HookStoreItem<EnvelopeHook> & HookStoreItem<TransactionHook>;
1 change: 1 addition & 0 deletions packages/types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,4 @@ export type { WrappedFunction } from './wrappedfunction';
export type { Instrumenter } from './instrumenter';

export type { BrowserClientReplayOptions } from './browseroptions';
export type { HookStore, Hook, TransactionHook, EnvelopeHook } from './hooks';