Skip to content

feat(core): Add new transports to base backend #4752

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 8 commits into from
Mar 23, 2022
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
46 changes: 40 additions & 6 deletions packages/core/src/basebackend.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Event, EventHint, Options, Session, Severity, Transport } from '@sentry/types';
import { isDebugBuild, logger, SentryError } from '@sentry/utils';

import { initAPIDetails } from './api';
import { createEventEnvelope, createSessionEnvelope } from './request';
import { NewTransport } from './transports/base';
import { NoopTransport } from './transports/noop';

/**
Expand Down Expand Up @@ -63,6 +66,9 @@ export abstract class BaseBackend<O extends Options> implements Backend {
/** Cached transport used internally. */
protected _transport: Transport;

/** New v7 Transport that is initialized alongside the old one */
protected _newTransport?: NewTransport;

/** Creates a new backend instance. */
public constructor(options: O) {
this._options = options;
Expand Down Expand Up @@ -91,9 +97,23 @@ export abstract class BaseBackend<O extends Options> implements Backend {
* @inheritDoc
*/
public sendEvent(event: Event): void {
void this._transport.sendEvent(event).then(null, reason => {
isDebugBuild() && logger.error('Error while sending event:', reason);
});
// TODO(v7): Remove the if-else
if (
this._newTransport &&
this._options.dsn &&
this._options._experiments &&
this._options._experiments.newTransport
) {
const api = initAPIDetails(this._options.dsn, this._options._metadata, this._options.tunnel);
Copy link
Member Author

Choose a reason for hiding this comment

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

it's annoying to do this, but considering that the client has access to API, won't be needed in the future!

const env = createEventEnvelope(event, api);
void this._newTransport.send(env).then(null, reason => {
isDebugBuild() && logger.error('Error while sending event:', reason);
});
} else {
void this._transport.sendEvent(event).then(null, reason => {
isDebugBuild() && logger.error('Error while sending event:', reason);
});
}
}

/**
Expand All @@ -105,9 +125,23 @@ export abstract class BaseBackend<O extends Options> implements Backend {
return;
}

void this._transport.sendSession(session).then(null, reason => {
isDebugBuild() && logger.error('Error while sending session:', reason);
});
// TODO(v7): Remove the if-else
if (
this._newTransport &&
this._options.dsn &&
this._options._experiments &&
this._options._experiments.newTransport
) {
const api = initAPIDetails(this._options.dsn, this._options._metadata, this._options.tunnel);
const [env] = createSessionEnvelope(session, api);
void this._newTransport.send(env).then(null, reason => {
isDebugBuild() && logger.error('Error while sending session:', reason);
});
} else {
void this._transport.sendSession(session).then(null, reason => {
isDebugBuild() && logger.error('Error while sending session:', reason);
});
}
}

/**
Expand Down
41 changes: 39 additions & 2 deletions packages/core/src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,11 @@ function enhanceEventWithSdkInfo(event: Event, sdkInfo?: SdkInfo): Event {
return event;
}

/** Creates a SentryRequest from a Session. */
export function sessionToSentryRequest(session: Session | SessionAggregates, api: APIDetails): SentryRequest {
/** Creates an envelope from a Session */
export function createSessionEnvelope(
session: Session | SessionAggregates,
api: APIDetails,
): [SessionEnvelope, SentryRequestType] {
const sdkInfo = getSdkMetadataForEnvelopeHeader(api);
const envelopeHeaders = {
sent_at: new Date().toISOString(),
Expand All @@ -54,13 +57,47 @@ export function sessionToSentryRequest(session: Session | SessionAggregates, api
// TODO (v7) Have to cast type because envelope items do not accept a `SentryRequestType`
const envelopeItem = [{ type } as { type: 'session' | 'sessions' }, session] as SessionItem;
const envelope = createEnvelope<SessionEnvelope>(envelopeHeaders, [envelopeItem]);

return [envelope, type];
}

/** Creates a SentryRequest from a Session. */
export function sessionToSentryRequest(session: Session | SessionAggregates, api: APIDetails): SentryRequest {
const [envelope, type] = createSessionEnvelope(session, api);
return {
body: serializeEnvelope(envelope),
type,
url: getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel),
};
}

/**
* Create an Envelope from an event. Note that this is duplicated from below,
* but on purpose as this will be refactored in v7.
*/
export function createEventEnvelope(event: Event, api: APIDetails): EventEnvelope {
const sdkInfo = getSdkMetadataForEnvelopeHeader(api);
const eventType = event.type || 'event';

const { transactionSampling } = event.sdkProcessingMetadata || {};
const { method: samplingMethod, rate: sampleRate } = transactionSampling || {};

const envelopeHeaders = {
event_id: event.event_id as string,
sent_at: new Date().toISOString(),
...(sdkInfo && { sdk: sdkInfo }),
...(!!api.tunnel && { dsn: dsnToString(api.dsn) }),
};
const eventItem: EventItem = [
{
type: eventType,
sample_rates: [{ id: samplingMethod, rate: sampleRate }],
},
event,
];
return createEnvelope<EventEnvelope>(envelopeHeaders, [eventItem]);
}

/** Creates a SentryRequest from an event. */
export function eventToSentryRequest(event: Event, api: APIDetails): SentryRequest {
const sdkInfo = getSdkMetadataForEnvelopeHeader(api);
Expand Down
5 changes: 0 additions & 5 deletions packages/core/src/transports/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,6 @@ export interface NodeTransportOptions extends BaseTransportOptions {
}

export interface NewTransport {
// If `$` is set, we know that this is a new transport.
// TODO(v7): Remove this as we will no longer have split between
// old and new transports.
$: boolean;
send(request: Envelope): PromiseLike<TransportResponse>;
flush(timeout?: number): PromiseLike<boolean>;
}
Expand Down Expand Up @@ -144,7 +140,6 @@ export function createTransport(
}

return {
$: true,
send,
flush,
};
Expand Down
5 changes: 0 additions & 5 deletions packages/core/test/lib/transports/base.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,6 @@ const TRANSACTION_ENVELOPE = createEnvelope<EventEnvelope>(
);

describe('createTransport', () => {
it('has $ property', () => {
const transport = createTransport({}, _ => resolvedSyncPromise({ statusCode: 200 }));
expect(transport.$).toBeDefined();
});

it('flushes the buffer', async () => {
const mockBuffer: PromiseBuffer<TransportResponse> = {
$: [],
Expand Down