Skip to content

Commit d82f916

Browse files
committed
Code review patches
1 parent bb2968a commit d82f916

File tree

11 files changed

+51
-46
lines changed

11 files changed

+51
-46
lines changed

packages/browser/src/sdk.ts

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -181,31 +181,33 @@ export function wrap(fn: (...args: any) => any): any {
181181
function startSessionTracking(): void {
182182
const window = getGlobalObject<Window>();
183183
const hub = getCurrentHub();
184+
185+
/**
186+
* We should be using `Promise.all([windowLoaded, firstContentfulPaint])` here,
187+
* but, as always, it's not available in the IE10-11. Thanks IE.
188+
*/
189+
let loadResolved = document.readyState === 'complete';
184190
let fcpResolved = false;
185-
let loadResolved = false;
186191
const possiblyEndSession = (): void => {
187192
if (fcpResolved && loadResolved) {
188193
hub.endSession();
189194
}
190195
};
196+
const resolveWindowLoaded = (): void => {
197+
loadResolved = true;
198+
possiblyEndSession();
199+
window.removeEventListener('load', resolveWindowLoaded);
200+
};
191201

192202
hub.startSession();
193203

194-
window.addEventListener('load', () => {
195-
loadResolved = true;
196-
possiblyEndSession();
197-
});
204+
if (!loadResolved) {
205+
// IE doesn't support `{ once: true }` for event listeners, so we have to manually
206+
// attach and then detach it once completed.
207+
window.addEventListener('load', resolveWindowLoaded);
208+
}
198209

199210
try {
200-
let firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity;
201-
document.addEventListener(
202-
'visibilitychange',
203-
event => {
204-
firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp);
205-
},
206-
{ once: true },
207-
);
208-
209211
const po = new PerformanceObserver((entryList, po) => {
210212
entryList.getEntries().forEach(entry => {
211213
if (entry.name === 'first-contentful-paint' && entry.startTime < firstHiddenTime) {
@@ -216,6 +218,17 @@ function startSessionTracking(): void {
216218
});
217219
});
218220

221+
// There's no need to even attach this listener if `PerformanceObserver` constructor will fail,
222+
// so we do it below here.
223+
let firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity;
224+
document.addEventListener(
225+
'visibilitychange',
226+
event => {
227+
firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp);
228+
},
229+
{ once: true },
230+
);
231+
219232
po.observe({
220233
type: 'paint',
221234
buffered: true,

packages/browser/src/transports/fetch.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,13 @@ export class FetchTransport extends BaseTransport {
2424

2525
/**
2626
* @param sentryRequest Prepared SentryRequest to be delivered
27-
* @param event original payload used to create SentryRequest
27+
* @param originalPayload Original payload used to create SentryRequest
2828
*/
29-
private _sendRequest(sentryRequest: SentryRequest, event: Event | Session): PromiseLike<Response> {
29+
private _sendRequest(sentryRequest: SentryRequest, originalPayload: Event | Session): PromiseLike<Response> {
3030
if (this._isRateLimited(sentryRequest.type)) {
3131
return Promise.reject({
32-
event,
32+
event: originalPayload,
33+
type: sentryRequest.type,
3334
reason: `Transport locked till ${this._disabledUntil(sentryRequest.type)} due to too many requests.`,
3435
status: 429,
3536
});

packages/browser/src/transports/xhr.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,13 @@ export class XHRTransport extends BaseTransport {
2222

2323
/**
2424
* @param sentryRequest Prepared SentryRequest to be delivered
25-
* @param event original payload used to create SentryRequest
25+
* @param originalPayload Original payload used to create SentryRequest
2626
*/
27-
private _sendRequest(sentryRequest: SentryRequest, event: Event | Session): PromiseLike<Response> {
27+
private _sendRequest(sentryRequest: SentryRequest, originalPayload: Event | Session): PromiseLike<Response> {
2828
if (this._isRateLimited(sentryRequest.type)) {
2929
return Promise.reject({
30-
event,
30+
event: originalPayload,
31+
type: sentryRequest.type,
3132
reason: `Transport locked till ${this._disabledUntil(sentryRequest.type)} due to too many requests.`,
3233
status: 429,
3334
});

packages/core/src/basebackend.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ export abstract class BaseBackend<O extends Options> implements Backend {
101101
*/
102102
public sendSession(session: Session): void {
103103
if (!this._transport.sendSession) {
104-
logger.warn('sendSession not implemented for a transport used');
104+
logger.warn("Dropping session because custom transport doesn't implement sendSession");
105105
return;
106106
}
107107

packages/core/src/baseclient.ts

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -494,16 +494,14 @@ export abstract class BaseClient<B extends Backend, O extends Options> implement
494494

495495
let finalEvent: Event | null = prepared;
496496

497-
const isInternalException =
498-
hint && hint.data && (hint.data as { [key: string]: unknown }).__sentry__ === true;
499-
// We skip beforeSend in case of transactions
500-
501-
if (isInternalException || !beforeSend || isTransaction) {
502-
if (!isTransaction) {
503-
const session = scope && scope.getSession();
504-
if (session) {
505-
this._updateSessionFromEvent(session, finalEvent);
506-
}
497+
const isInternalException = hint && hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;
498+
const shouldSkipBeforeSend = isInternalException || isTransaction || !beforeSend;
499+
const session = scope && scope.getSession();
500+
501+
if (shouldSkipBeforeSend) {
502+
// If this is a generic error event and we have a session available, update it.
503+
if (!isTransaction && session) {
504+
this._updateSessionFromEvent(session, finalEvent);
507505
}
508506

509507
this._sendEvent(finalEvent);
@@ -525,7 +523,6 @@ export abstract class BaseClient<B extends Backend, O extends Options> implement
525523
return;
526524
}
527525

528-
const session = scope && scope.getSession();
529526
if (session) {
530527
this._updateSessionFromEvent(session, finalEvent);
531528
}

packages/core/src/request.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
import { Event, SentryRequest, Session } from '@sentry/types';
2-
import { timestampWithMs } from '@sentry/utils';
32

43
import { API } from './api';
54

65
/** Creates a SentryRequest from an event. */
76
export function sessionToSentryRequest(session: Session, api: API): SentryRequest {
87
const envelopeHeaders = JSON.stringify({
9-
sent_at: new Date(timestampWithMs() * 1000).toISOString(),
8+
sent_at: new Date().toISOString(),
109
});
1110
const itemHeaders = JSON.stringify({
1211
type: 'session',

packages/hub/src/session.ts

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,6 @@ export class Session implements SessionInterface {
8080
this.update({ status });
8181
} else if (this.status === SessionStatus.Ok) {
8282
this.update({ status: SessionStatus.Exited });
83-
} else {
84-
// Calling `update` alone updates session.timestamp to the current time and session.duration.
85-
this.update();
8683
}
8784
}
8885

packages/tracing/src/browser/browsertracing.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,6 @@ export class BrowserTracing implements Integration {
190190

191191
// eslint-disable-next-line @typescript-eslint/unbound-method
192192
const { beforeNavigate, idleTimeout, maxTransactionDuration } = this.options;
193-
const hub = this._getCurrentHub();
194193
const parentContextFromHeader = context.op === 'pageload' ? getHeaderContext() : undefined;
195194

196195
const expandedContext = {
@@ -208,6 +207,7 @@ export class BrowserTracing implements Integration {
208207
logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);
209208
}
210209

210+
const hub = this._getCurrentHub();
211211
const idleTransaction = startIdleTransaction(hub, finalContext, idleTimeout, true);
212212
logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);
213213
idleTransaction.registerBeforeFinishCallback((transaction, endTimestamp) => {

packages/types/src/hub.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ export interface Hub {
208208
* To finish a `session`, it has to be passed directly to `client.captureSession`, which is done automatically
209209
* when using `hub.endSession()` for the session currently stored on the scope.
210210
*
211-
* When there's already an existing session on the scope, it'll be autmatically ended.
211+
* When there's already an existing session on the scope, it'll be automatically ended.
212212
*
213213
* @param context Optional properties of the new `Session`.
214214
*

packages/types/src/request.ts

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,6 @@ export interface SentryRequest {
66
body: string;
77
type: SentryRequestType;
88
url: string;
9-
// headers would contain auth & content-type headers for @sentry/node, but
10-
// since @sentry/browser avoids custom headers to prevent CORS preflight
11-
// requests, we can use the same approach for @sentry/browser and @sentry/node
12-
// for simplicity -- no headers involved.
13-
// headers: { [key: string]: string };
149
}
1510

1611
/** Request data included in an event as sent to Sentry */

packages/types/src/response.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
import { Event } from './event';
1+
import { Event, EventType } from './event';
2+
import { Session } from './session';
23
import { Status } from './status';
34

45
/** JSDoc */
56
export interface Response {
67
status: Status;
7-
event?: Event;
8+
event?: Event | Session;
9+
type?: EventType;
810
reason?: string;
911
}

0 commit comments

Comments
 (0)