-
Notifications
You must be signed in to change notification settings - Fork 189
Expand file tree
/
Copy pathapi.ts
More file actions
343 lines (299 loc) · 9.96 KB
/
Copy pathapi.ts
File metadata and controls
343 lines (299 loc) · 9.96 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import type { Batch, Context } from '@datadog/browser-core'
import { timeStampNow, display, buildTag, generateUUID, getGlobalObject } from '@datadog/browser-core'
import type { BrowserWindow, DebuggerInitConfiguration } from '../entries/main'
import { capture, captureFields } from './capture'
import type { CaptureContext } from './capture'
import type { InitializedProbe } from './probes'
import { checkGlobalSnapshotBudget, resetProbeBudgetConfiguration, setProbeBudgetConfiguration } from './probes'
import type { ActiveEntry } from './activeEntries'
import { active } from './activeEntries'
import { captureStackTrace, parseStackTrace } from './stacktrace'
import { evaluateProbeMessage } from './template'
import { evaluateProbeCondition } from './condition'
const globalObj = getGlobalObject<BrowserWindow>() // eslint-disable-line local-rules/disallow-side-effects
const threadName = detectThreadName() // eslint-disable-line local-rules/disallow-side-effects
const SNAPSHOT_TIMEOUT_MS = 10
let debuggerBatch: Batch | undefined
let debuggerConfig: DebuggerInitConfiguration | undefined
let cachedDDtags: string | undefined
export function initDebuggerTransport(config: DebuggerInitConfiguration, batch: Batch): void {
debuggerConfig = config
debuggerBatch = batch
cachedDDtags = undefined
setProbeBudgetConfiguration(config)
}
export function resetDebuggerTransport(): void {
debuggerBatch = undefined
debuggerConfig = undefined
cachedDDtags = undefined
active.clear()
resetProbeBudgetConfiguration()
}
/**
* Called when entering an instrumented function
*
* @param probes - Array of probes for this function
* @param self - The 'this' context
* @param args - Function arguments
*/
export function onEntry(probes: InitializedProbe[], self: any, args: Record<string, any> = {}): void {
const start = performance.now()
const captureCtx: CaptureContext = { deadline: start + SNAPSHOT_TIMEOUT_MS, timedOut: false }
// TODO: A lot of repeated work performed for each probe that could be shared between probes
for (const probe of probes) {
let stack = active.get(probe.id) // TODO: Should we use the functionId instead?
if (!stack) {
stack = []
active.set(probe.id, stack)
}
// Skip if sampling budget is exceeded
if (
start - probe.lastCaptureMs < probe.msBetweenSampling ||
!checkGlobalSnapshotBudget(start, probe.captureSnapshot)
) {
stack.push(null)
continue
}
// Update last capture time
probe.lastCaptureMs = start
let timestamp: number | undefined
let message: string | undefined
if (probe.evaluateAt === 'ENTRY') {
// Build context for condition and message evaluation
const context = { ...args, this: self }
// Check condition - if it fails, don't evaluate or capture anything
if (!evaluateProbeCondition(probe, context)) {
// Still push to stack so onReturn/onThrow can pop it, but mark as skipped
stack.push(null)
continue
}
timestamp = timeStampNow()
message = evaluateProbeMessage(probe, context)
}
// Special case for evaluateAt=EXIT with a condition: we only capture the return snapshot
const shouldCaptureEntrySnapshot = probe.captureSnapshot && (probe.evaluateAt === 'ENTRY' || !probe.condition)
let entry: { arguments: Record<string, any> } | undefined
if (shouldCaptureEntrySnapshot) {
entry = {
arguments: {
...captureFields(args, probe.capture, captureCtx),
this: capture(self, probe.capture, captureCtx),
},
}
if (captureCtx.timedOut) {
stack.push(null)
continue
}
}
stack.push({
start,
timestamp,
message,
entry,
stack: probe.captureSnapshot ? captureStackTrace(1) : undefined,
})
}
}
/**
* Called when exiting an instrumented function normally
*
* @param probes - Array of probes for this function
* @param value - Return value
* @param self - The 'this' context
* @param args - Function arguments
* @param locals - Local variables
* @returns The return value (passed through)
*/
export function onReturn(
probes: InitializedProbe[],
value: any,
self: any,
args: Record<string, any> = {},
locals: Record<string, any> = {}
): any {
const end = performance.now()
const captureCtx: CaptureContext = { deadline: performance.now() + SNAPSHOT_TIMEOUT_MS, timedOut: false }
// TODO: A lot of repeated work performed for each probe that could be shared between probes
for (const probe of probes) {
const stack = active.get(probe.id) // TODO: Should we use the functionId instead?
if (!stack) {
continue // TODO: This shouldn't be possible, do we need it? Should we warn?
}
const result = stack.pop()
if (stack.length === 0) {
active.delete(probe.id)
}
if (!result) {
continue
}
result.duration = end - result.start
if (probe.evaluateAt === 'EXIT') {
result.timestamp = timeStampNow()
const context = {
...args,
...locals,
this: self,
$dd_duration: result.duration,
$dd_return: value,
}
if (!evaluateProbeCondition(probe, context)) {
continue
}
result.message = evaluateProbeMessage(probe, context)
}
if (probe.captureSnapshot) {
result.return = {
arguments: {
...captureFields(args, probe.capture, captureCtx),
this: capture(self, probe.capture, captureCtx),
},
locals: {
...captureFields(locals, probe.capture, captureCtx),
'@return': capture(value, probe.capture, captureCtx),
},
}
if (captureCtx.timedOut) {
continue
}
}
sendDebuggerSnapshot(probe, result)
}
return value
}
/**
* Called when exiting an instrumented function via exception
*
* @param probes - Array of probes for this function
* @param error - The thrown error
* @param self - The 'this' context
* @param args - Function arguments
*/
export function onThrow(probes: InitializedProbe[], error: Error, self: any, args: Record<string, any> = {}): void {
const end = performance.now()
const captureCtx: CaptureContext = { deadline: performance.now() + SNAPSHOT_TIMEOUT_MS, timedOut: false }
// TODO: A lot of repeated work performed for each probe that could be shared between probes
for (const probe of probes) {
const stack = active.get(probe.id) // TODO: Should we use the functionId instead?
if (!stack) {
continue // TODO: This shouldn't be possible, do we need it? Should we warn?
}
const result = stack.pop()
if (stack.length === 0) {
active.delete(probe.id)
}
if (!result) {
continue
}
result.duration = end - result.start
result.exception = error
if (probe.evaluateAt === 'EXIT') {
result.timestamp = timeStampNow()
const context = {
...args,
this: self,
$dd_duration: result.duration,
$dd_exception: error,
}
if (!evaluateProbeCondition(probe, context)) {
continue
}
result.message = evaluateProbeMessage(probe, context)
}
let throwArguments: Record<string, any> | undefined
if (probe.captureSnapshot) {
throwArguments = {
...captureFields(args, probe.capture, captureCtx),
this: capture(self, probe.capture, captureCtx),
}
if (captureCtx.timedOut) {
continue
}
}
result.return = {
arguments: throwArguments,
throwable: {
message: error.message,
stacktrace: parseStackTrace(error),
},
}
sendDebuggerSnapshot(probe, result)
}
}
/**
* Send a debugger snapshot to Datadog via the debugger's own transport.
*
* @param probe - The probe that was executed
* @param result - The result of the probe execution
*/
function sendDebuggerSnapshot(probe: InitializedProbe, result: ActiveEntry): void {
if (!debuggerBatch || !debuggerConfig) {
display.warn('Debugger transport is not initialized. Make sure DD_DEBUGGER.init() has been called.')
return
}
const version = globalObj.DD_DEBUGGER!.version
const payload: Context = {
message: result.message,
service: debuggerConfig.service,
ddtags: getDebuggerDDtags(version),
// TODO: Fill out logger with the right information
logger: {
name: probe.where.typeName,
method: probe.where.methodName,
version,
// thread_id: 1,
thread_name: threadName,
},
debugger: {
snapshot: {
id: generateUUID(),
timestamp: result.timestamp!,
probe: {
id: probe.id,
version: probe.version,
location: {
// TODO: Are our hardcoded where.* keys correct according to the spec?
method: probe.where.methodName,
type: probe.where.typeName,
},
},
stack: result.stack,
language: 'javascript',
duration: result.duration! * 1e6, // to nanoseconds
captures:
result.entry || result.return
? {
entry: result.entry,
return: result.return,
}
: undefined,
},
},
}
debuggerBatch.add(payload)
}
function getDebuggerDDtags(debuggerVersion: string): string {
if (!cachedDDtags) {
cachedDDtags = [
buildTag('sdk_version', debuggerVersion),
buildTag('debugger_version', debuggerVersion),
buildTag('env', debuggerConfig?.env),
buildTag('service', debuggerConfig?.service),
buildTag('version', debuggerConfig?.version),
].join(',')
}
return cachedDDtags
}
function detectThreadName() {
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return 'main'
}
if (typeof ServiceWorkerGlobalScope !== 'undefined' && self instanceof ServiceWorkerGlobalScope) {
return 'service-worker'
}
if (typeof importScripts === 'function') {
return 'web-worker'
}
return 'unknown'
}
declare const ServiceWorkerGlobalScope: typeof EventTarget
declare function importScripts(...urls: string[]): void