Repository navigation
Expand file tree
/
Copy pathserver-runtime-client.ts
More file actions
260 lines (227 loc) · 8.37 KB
/
Copy pathserver-runtime-client.ts
File metadata and controls
260 lines (227 loc) · 8.37 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
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
import type {
BaseTransportOptions,
CheckIn,
ClientOptions,
DynamicSamplingContext,
Event,
EventHint,
MonitorConfig,
SerializedCheckIn,
Severity,
SeverityLevel,
TraceContext,
} from '@sentry/types';
import { eventFromMessage, eventFromUnknownInput, logger, resolvedSyncPromise, uuid4 } from '@sentry/utils';
import { BaseClient } from './baseclient';
import { createCheckInEnvelope } from './checkin';
import { DEBUG_BUILD } from './debug-build';
import { getCurrentHub } from './hub';
import type { Scope } from './scope';
import { SessionFlusher } from './sessionflusher';
import { addTracingExtensions, getDynamicSamplingContextFromClient } from './tracing';
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 BaseClient<O> {
protected _sessionFlusher: SessionFlusher | undefined;
/**
* Creates a new Edge SDK instance.
* @param options Configuration options for this SDK.
*/
public constructor(options: O) {
// Server clients always support tracing
addTracingExtensions();
super(options);
}
/**
* @inheritDoc
*/
public eventFromException(exception: unknown, hint?: EventHint): PromiseLike<Event> {
return resolvedSyncPromise(eventFromUnknownInput(getCurrentHub, this._options.stackParser, exception, hint));
}
/**
* @inheritDoc
*/
public eventFromMessage(
message: string,
// eslint-disable-next-line deprecation/deprecation
level: Severity | SeverityLevel = 'info',
hint?: EventHint,
): PromiseLike<Event> {
return resolvedSyncPromise(
eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace),
);
}
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {
// Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only
// when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload
// sent to the Server only when the `requestHandler` middleware is used
if (this._options.autoSessionTracking && this._sessionFlusher && scope) {
const requestSession = scope.getRequestSession();
// Necessary checks to ensure this is code block is executed only within a request
// Should override the status only if `requestSession.status` is `Ok`, which is its initial stage
if (requestSession && requestSession.status === 'ok') {
requestSession.status = 'errored';
}
}
return super.captureException(exception, hint, scope);
}
/**
* @inheritDoc
*/
public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {
// Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only
// when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload
// sent to the Server only when the `requestHandler` middleware is used
if (this._options.autoSessionTracking && this._sessionFlusher && scope) {
const eventType = event.type || 'exception';
const isException =
eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0;
// If the event is of type Exception, then a request session should be captured
if (isException) {
const requestSession = scope.getRequestSession();
// Ensure that this is happening within the bounds of a request, and make sure not to override
// Session Status if Errored / Crashed
if (requestSession && requestSession.status === 'ok') {
requestSession.status = 'errored';
}
}
}
return super.captureEvent(event, hint, scope);
}
/**
*
* @inheritdoc
*/
public close(timeout?: number): PromiseLike<boolean> {
if (this._sessionFlusher) {
this._sessionFlusher.close();
}
return super.close(timeout);
}
/** Method that initialises an instance of SessionFlusher on Client */
public initSessionFlusher(): void {
const { release, environment } = this._options;
if (!release) {
DEBUG_BUILD && logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!');
} else {
this._sessionFlusher = new SessionFlusher(this, {
release,
environment,
});
}
}
/**
* 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 checkin.');
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,
};
}
const [dynamicSamplingContext, traceContext] = this._getTraceInfoFromScope(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);
void this._sendEnvelope(envelope);
return id;
}
/**
* Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment
* appropriate session aggregates bucket
*/
protected _captureRequestSession(): void {
if (!this._sessionFlusher) {
DEBUG_BUILD && logger.warn('Discarded request mode session because autoSessionTracking option was disabled');
} else {
this._sessionFlusher.incrementSessionStatusCount();
}
}
/**
* @inheritDoc
*/
protected _prepareEvent(event: Event, hint: EventHint, scope?: 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, scope);
}
/** Extract trace information from scope */
private _getTraceInfoFromScope(
scope: Scope | undefined,
): [dynamicSamplingContext: Partial<DynamicSamplingContext> | undefined, traceContext: TraceContext | undefined] {
if (!scope) {
return [undefined, undefined];
}
const span = scope.getSpan();
if (span) {
const samplingContext = span.transaction ? span.transaction.getDynamicSamplingContext() : undefined;
return [samplingContext, span.getTraceContext()];
}
const { traceId, spanId, parentSpanId, dsc } = scope.getPropagationContext();
const traceContext: TraceContext = {
trace_id: traceId,
span_id: spanId,
parent_span_id: parentSpanId,
};
if (dsc) {
return [dsc, traceContext];
}
return [getDynamicSamplingContextFromClient(traceId, this, scope), traceContext];
}
}