-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathserver-runtime-client.ts
266 lines (230 loc) · 7.89 KB
/
server-runtime-client.ts
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import type {
BaseTransportOptions,
CheckIn,
ClientOptions,
Event,
EventHint,
Log,
MonitorConfig,
ParameterizedString,
Primitive,
SerializedCheckIn,
SeverityLevel,
} from './types-hoist';
import { createCheckInEnvelope } from './checkin';
import { Client, _getTraceInfoFromScope } from './client';
import { getIsolationScope } from './currentScopes';
import { DEBUG_BUILD } from './debug-build';
import type { Scope } from './scope';
import { registerSpanErrorInstrumentation } from './tracing';
import { eventFromMessage, eventFromUnknownInput } from './utils-hoist/eventbuilder';
import { logger } from './utils-hoist/logger';
import { uuid4 } from './utils-hoist/misc';
import { resolvedSyncPromise } from './utils-hoist/syncpromise';
import { _INTERNAL_flushLogsBuffer } from './logs';
import { isPrimitive } from './utils-hoist';
export interface ServerRuntimeClientOptions extends ClientOptions<BaseTransportOptions> {
platform?: string;
runtime?: { name: string; version?: string };
serverName?: string;
}
/**
* The Sentry Server Runtime Client SDK.
*/
export class ServerRuntimeClient<
O extends ClientOptions & ServerRuntimeClientOptions = ServerRuntimeClientOptions,
> extends Client<O> {
private _logWeight: number;
/**
* Creates a new Edge SDK instance.
* @param options Configuration options for this SDK.
*/
public constructor(options: O) {
// Server clients always support tracing
registerSpanErrorInstrumentation();
super(options);
this._logWeight = 0;
// eslint-disable-next-line @typescript-eslint/no-this-alias
const client = this;
this.on('flush', () => {
_INTERNAL_flushLogsBuffer(client);
});
this.on('afterCaptureLog', log => {
client._logWeight += estimateLogSizeInBytes(log);
// We flush the logs buffer if it exceeds 0.8 MB
// The log weight is a rough estimate, so we flush way before
// the payload gets too big.
if (client._logWeight > 800_000) {
_INTERNAL_flushLogsBuffer(client);
client._logWeight = 0;
}
});
}
/**
* @inheritDoc
*/
public eventFromException(exception: unknown, hint?: EventHint): PromiseLike<Event> {
const event = eventFromUnknownInput(this, this._options.stackParser, exception, hint);
event.level = 'error';
return resolvedSyncPromise(event);
}
/**
* @inheritDoc
*/
public eventFromMessage(
message: ParameterizedString,
level: SeverityLevel = 'info',
hint?: EventHint,
): PromiseLike<Event> {
return resolvedSyncPromise(
eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace),
);
}
/**
* @inheritDoc
*/
public captureException(exception: unknown, hint?: EventHint, scope?: Scope): string {
setCurrentRequestSessionErroredOrCrashed(hint);
return super.captureException(exception, hint, scope);
}
/**
* @inheritDoc
*/
public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string {
// If the event is of type Exception, then a request session should be captured
const isException = !event.type && event.exception?.values && event.exception.values.length > 0;
if (isException) {
setCurrentRequestSessionErroredOrCrashed(hint);
}
return super.captureEvent(event, hint, scope);
}
/**
* Create a cron monitor check in and send it to Sentry.
*
* @param checkIn An object that describes a check in.
* @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want
* to create a monitor automatically when sending a check in.
*/
public captureCheckIn(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string {
const id = 'checkInId' in checkIn && checkIn.checkInId ? checkIn.checkInId : uuid4();
if (!this._isEnabled()) {
DEBUG_BUILD && logger.warn('SDK not enabled, will not capture check-in.');
return id;
}
const options = this.getOptions();
const { release, environment, tunnel } = options;
const serializedCheckIn: SerializedCheckIn = {
check_in_id: id,
monitor_slug: checkIn.monitorSlug,
status: checkIn.status,
release,
environment,
};
if ('duration' in checkIn) {
serializedCheckIn.duration = checkIn.duration;
}
if (monitorConfig) {
serializedCheckIn.monitor_config = {
schedule: monitorConfig.schedule,
checkin_margin: monitorConfig.checkinMargin,
max_runtime: monitorConfig.maxRuntime,
timezone: monitorConfig.timezone,
failure_issue_threshold: monitorConfig.failureIssueThreshold,
recovery_threshold: monitorConfig.recoveryThreshold,
};
}
const [dynamicSamplingContext, traceContext] = _getTraceInfoFromScope(this, scope);
if (traceContext) {
serializedCheckIn.contexts = {
trace: traceContext,
};
}
const envelope = createCheckInEnvelope(
serializedCheckIn,
dynamicSamplingContext,
this.getSdkMetadata(),
tunnel,
this.getDsn(),
);
DEBUG_BUILD && logger.info('Sending checkin:', checkIn.monitorSlug, checkIn.status);
// sendEnvelope should not throw
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.sendEnvelope(envelope);
return id;
}
/**
* @inheritDoc
*/
protected _prepareEvent(
event: Event,
hint: EventHint,
currentScope: Scope,
isolationScope: Scope,
): PromiseLike<Event | null> {
if (this._options.platform) {
event.platform = event.platform || this._options.platform;
}
if (this._options.runtime) {
event.contexts = {
...event.contexts,
runtime: event.contexts?.runtime || this._options.runtime,
};
}
if (this._options.serverName) {
event.server_name = event.server_name || this._options.serverName;
}
return super._prepareEvent(event, hint, currentScope, isolationScope);
}
}
function setCurrentRequestSessionErroredOrCrashed(eventHint?: EventHint): void {
const requestSession = getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession;
if (requestSession) {
// We mutate instead of doing `setSdkProcessingMetadata` because the http integration stores away a particular
// isolationScope. If that isolation scope is forked, setting the processing metadata here will not mutate the
// original isolation scope that the http integration stored away.
const isHandledException = eventHint?.mechanism?.handled ?? true;
// A request session can go from "errored" -> "crashed" but not "crashed" -> "errored".
// Crashed (unhandled exception) is worse than errored (handled exception).
if (isHandledException && requestSession.status !== 'crashed') {
requestSession.status = 'errored';
} else if (!isHandledException) {
requestSession.status = 'crashed';
}
}
}
/**
* Estimate the size of a log in bytes.
*
* @param log - The log to estimate the size of.
* @returns The estimated size of the log in bytes.
*/
function estimateLogSizeInBytes(log: Log): number {
let weight = 0;
// Estimate byte size of 2 bytes per character. This is a rough estimate JS strings are stored as UTF-16.
if (log.message) {
weight += log.message.length * 2;
}
if (log.attributes) {
Object.values(log.attributes).forEach(value => {
if (Array.isArray(value)) {
weight += value.length * estimatePrimitiveSizeInBytes(value[0]);
} else if (isPrimitive(value)) {
weight += estimatePrimitiveSizeInBytes(value);
} else {
// For objects values, we estimate the size of the object as 100 bytes
weight += 100;
}
});
}
return weight;
}
function estimatePrimitiveSizeInBytes(value: Primitive): number {
if (typeof value === 'string') {
return value.length * 2;
} else if (typeof value === 'number') {
return 8;
} else if (typeof value === 'boolean') {
return 4;
}
return 0;
}