-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathsendReplayRequest.ts
More file actions
165 lines (145 loc) · 4.99 KB
/
sendReplayRequest.ts
File metadata and controls
165 lines (145 loc) · 4.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import type { RateLimits, ReplayEvent, TransportMakeRequestResponse } from '@sentry/core';
import { getClient, getCurrentScope, isRateLimited, updateRateLimits } from '@sentry/core';
import { REPLAY_EVENT_NAME, UNABLE_TO_SEND_REPLAY } from '../constants';
import { DEBUG_BUILD } from '../debug-build';
import type { SendReplayData } from '../types';
import { createReplayEnvelope } from './createReplayEnvelope';
import { debug } from './logger';
import { prepareRecordingData } from './prepareRecordingData';
import { prepareReplayEvent } from './prepareReplayEvent';
/**
* Send replay attachment using `fetch()`
*/
export async function sendReplayRequest({
recordingData,
replayId,
segmentId: segment_id,
eventContext,
timestamp,
session,
}: SendReplayData): Promise<TransportMakeRequestResponse> {
const preparedRecordingData = prepareRecordingData({
recordingData,
headers: {
segment_id,
},
});
const { urls, errorIds, traceIds, initialTimestamp } = eventContext;
const client = getClient();
const scope = getCurrentScope();
const transport = client?.getTransport();
const dsn = client?.getDsn();
if (!client || !transport || !dsn || !session.sampled) {
return Promise.resolve({});
}
const uniqueTraceIds = Array.from(new Set(traceIds.map(([_ts, traceId]) => traceId)));
const baseEvent: ReplayEvent = {
type: REPLAY_EVENT_NAME,
replay_start_timestamp: initialTimestamp / 1000,
timestamp: timestamp / 1000,
error_ids: errorIds,
trace_ids: uniqueTraceIds,
traces_by_timestamp: traceIds.map(([ts, traceId]) => [ts, traceId]),
urls,
replay_id: replayId,
segment_id,
replay_type: session.sampled,
};
const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });
if (!replayEvent) {
// Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions
client.recordDroppedEvent('event_processor', 'replay');
DEBUG_BUILD && debug.log('An event processor returned `null`, will not send event.');
return Promise.resolve({});
}
/*
For reference, the fully built event looks something like this:
{
"type": "replay_event",
"timestamp": 1670837008.634,
"error_ids": [
"errorId"
],
"trace_ids": [
"traceId"
],
"urls": [
"https://example.com"
],
"replay_id": "eventId",
"segment_id": 3,
"replay_type": "error",
"platform": "javascript",
"event_id": "eventId",
"environment": "production",
"sdk": {
"integrations": [
"BrowserTracing",
"Replay"
],
"name": "sentry.javascript.browser",
"version": "7.25.0"
},
"sdkProcessingMetadata": {},
"contexts": {
},
}
*/
// Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to
// sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may
// have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid
// of this `delete`, lest we miss putting it back in the next time the property is in use.)
delete replayEvent.sdkProcessingMetadata;
const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel);
let response: TransportMakeRequestResponse;
try {
response = await transport.send(envelope);
} catch (err) {
const error = new Error(UNABLE_TO_SEND_REPLAY);
try {
// In case browsers don't allow this property to be writable
// @ts-expect-error This needs lib es2022 and newer
error.cause = err;
} catch {
// nothing to do
}
throw error;
}
// Check for rate limiting first (handles 429 and rate limit headers)
const rateLimits = updateRateLimits({}, response);
if (isRateLimited(rateLimits, 'replay')) {
throw new RateLimitError(rateLimits);
}
// If the status code is invalid, we want to immediately stop & not retry
if (typeof response.statusCode === 'number' && (response.statusCode < 200 || response.statusCode >= 300)) {
throw new TransportStatusCodeError(response.statusCode);
}
return response;
}
/**
* This error indicates that the transport returned an invalid status code.
*/
export class TransportStatusCodeError extends Error {
public constructor(statusCode: number) {
super(`Transport returned status code ${statusCode}`);
}
}
/**
* This error indicates that we hit a rate limit API error.
*/
export class RateLimitError extends Error {
public rateLimits: RateLimits;
public constructor(rateLimits: RateLimits) {
super('Rate limit hit');
this.rateLimits = rateLimits;
}
}
/**
* This error indicates that the replay duration limit was exceeded and the session is too long.
*
*/
export class ReplayDurationLimitError extends Error {
public constructor() {
super('Session is too long, not sending replay');
}
}