Skip to content

Commit

Permalink
feat(core): Add new transports to base backend (#4752)
Browse files Browse the repository at this point in the history
Adds new transports to base backend in core. For now, they are gated behind `options._experiments.newTransport = true`. The reason this is gated is because client reports does not work with the new transports.

The next step is to add new transports for fetch, xhr (browser) as well as http, https (node). We can do this in any order!
  • Loading branch information
AbhiPrasad authored Mar 23, 2022
1 parent 5f6335d commit 69c6874
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 18 deletions.
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);
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

0 comments on commit 69c6874

Please sign in to comment.