'use strict' const { randomUUID } = require('crypto') const { workerData: { probeSamplerBuffer, pauseDurationBuffer } } = require('worker_threads') const { version } = require('../../../../../package.json') const processTags = require('../../process-tags') const { INSPECT_SEGMENT_GLOBAL_PROPERTY, WORKER_ERROR_REASON } = require('../constants') const { EVENT_TYPE, INCOMPLETE_REASON } = require('../guardrail-metrics') const { PauseDurationHistogram } = require('../pause-duration-histogram') const { CONDITION_ERROR_FLAG, MAX_SAMPLED_PROBES_PER_PAUSE, SAMPLED_PROBE_COUNT_INDEX, SAMPLED_PROBE_INDEXES_START, SAMPLED_PROBE_OVERFLOW_INDEX, } = require('../probe_sampler_constants') const { getEvaluationTimedOutExpression, getTakeConditionErrorExpression } = require('./probe_sampler') const { breakpointToProbes, samplingIndexToProbe } = require('./state') const { refreshBreakpoints } = require('./breakpoints') const session = require('./session') const { getLocalStateForCallFrame, evaluateCaptureExpressions } = require('./snapshot') const send = require('./send') const { getStackFromCallFrames } = require('./state') const { ackEmitting } = require('./status') const WorkerError = require('./worker-error') const config = require('./config') const log = require('./log') require('./remote_config') /** @typedef {import('node:inspector').Debugger.EvaluateOnCallFrameReturnType} EvaluateOnCallFrameResult */ const templateExpressionSetupCode = 'const $dd_inspectSegment = ' + `globalThis[Symbol.for('dd-trace')][${JSON.stringify(INSPECT_SEGMENT_GLOBAL_PROPERTY)}];` // Expression to run on a call frame of the paused thread to get its active trace and span id. const getDDTagsExpression = `(() => { const context = globalThis._ddtrace.scope().active()?.context(); return { trace_id: context?.toTraceId(), span_id: context?.toSpanId() } })()` // There doesn't seem to be an official standard for the content of these fields, so we're just populating them with // something that should be useful to a Node.js developer. const threadId = config.parentThreadId === 0 ? `pid:${process.pid}` : `pid:${process.pid};tid:${config.parentThreadId}` const threadName = config.parentThreadId === 0 ? 'MainThread' : `WorkerThread:${config.parentThreadId}` const sampledProbeIndexes = new Int32Array(probeSamplerBuffer) const pauseDurations = new PauseDurationHistogram(pauseDurationBuffer) // WARNING: The code above the line `await session.post('Debugger.resume')` is highly optimized. Please edit with care! session.on('Debugger.paused', async ({ params }) => { const start = process.hrtime.bigint() if (params.reason !== 'other') { // This error should not be caught, and should exit the worker thread, effectively stopping the debugging session throw new WorkerError( `Unexpected Debugger.paused reason: ${params.reason}`, WORKER_ERROR_REASON.UNEXPECTED_PAUSE_REASON ) } let maxReferenceDepth = 0 let maxCollectionSize = 0 let maxFieldCount = 0 let maxLength = 0 let numberOfProbesWithSnapshots = 0 let probesWithCaptureExpressions = false let probesWithTemplates = false const probes = [] // Expressions evaluated on the paused frame in one round trip, in the order of `probes`: the evaluated template for // probes whose template requires evaluation, and the recorded error for probes paused to report a condition error let frameExpressions = '' /** @type {Set | undefined} */ let conditionErrorProbes // V8 doesn't allow setting more than one breakpoint at a specific location, however, it's possible to set two // breakpoints just next to each other that will "snap" to the same logical location, which in turn will be hit at the // same time. E.g. index.js:1:1 and index.js:1:2. const numberOfSampledProbeIndexes = Math.min( Atomics.exchange(sampledProbeIndexes, SAMPLED_PROBE_COUNT_INDEX, 0), MAX_SAMPLED_PROBES_PER_PAUSE ) if (Atomics.exchange(sampledProbeIndexes, SAMPLED_PROBE_OVERFLOW_INDEX, 0) === 1) { log.error( '[debugger:devtools_client] Too many probes sampled at the same breakpoint location; skipping excess probes' ) } // TODO: Investigate if it will improve performance to create a fast-path for when there's only a single breakpoint for (let i = 0; i < params.hitBreakpoints.length; i++) { const probesAtLocation = breakpointToProbes.get(params.hitBreakpoints[i]) if (probesAtLocation === undefined) { // This might happen due to a race condition where the breakpoint is in the process of being removed log.error('[debugger:devtools_client] No probes found for breakpoint %s', params.hitBreakpoints[i]) continue } for (let j = 0; j < numberOfSampledProbeIndexes; j++) { const sampledValue = Atomics.load(sampledProbeIndexes, SAMPLED_PROBE_INDEXES_START + j) const samplingIndex = sampledValue & ~CONDITION_ERROR_FLAG const probe = samplingIndexToProbe.get(samplingIndex) if (probe === undefined) { log.error('[debugger:devtools_client] No probe found for sampled probe index %d', samplingIndex) continue } if (!probesAtLocation.has(probe.id)) { log.error('[debugger:devtools_client] Sampled probe %s was not found at breakpoint %s', probe.id, params.hitBreakpoints[i]) continue } if ((sampledValue & CONDITION_ERROR_FLAG) !== 0) { // The condition threw, so there's nothing to capture. Only the recorded error is needed from the paused thread. conditionErrorProbes ??= new Set() conditionErrorProbes.add(probe) frameExpressions += `,${getTakeConditionErrorExpression(probe.id)}` probes.push(probe) continue } if (probe.captureSnapshot === true || probe.compiledCaptureExpressions !== undefined) { if (probe.captureSnapshot === true) { numberOfProbesWithSnapshots++ maxReferenceDepth = Math.max(probe.capture.maxReferenceDepth, maxReferenceDepth) maxCollectionSize = Math.max(probe.capture.maxCollectionSize, maxCollectionSize) maxFieldCount = Math.max(probe.capture.maxFieldCount, maxFieldCount) maxLength = Math.max(probe.capture.maxLength, maxLength) } else { probesWithCaptureExpressions = true } } if (probe.templateRequiresEvaluation) { probesWithTemplates = true frameExpressions += `,${probe.template}` } probes.push(probe) } } // This can happen if sampled probe indexes are inconsistent with the worker state. Those cases are logged above. if (probes.length === 0) { await session.post('Debugger.resume') reportPauseDuration(start) return } const timestamp = Date.now() let evalResults const evaluationStart = process.hrtime.bigint() const { result } = /** @type {EvaluateOnCallFrameResult} */ ( await session.post('Debugger.evaluateOnCallFrame', { callFrameId: params.callFrames[0].callFrameId, expression: frameExpressions.length === 0 ? `[${getDDTagsExpression}]` : `${templateExpressionSetupCode}[${getDDTagsExpression}${frameExpressions}]`, returnByValue: true, includeCommandLineAPI: true, }) ) // The templates of all probes at the location are evaluated together, so an exceeded budget is attributed to all of // them. Evaluation can't be interrupted, so the budget is enforced by reporting and throttling after the fact. const templatesTimedOut = probesWithTemplates && process.hrtime.bigint() - evaluationStart > config.dynamicInstrumentation.evaluationTimeoutNs if (result?.subtype === 'error') { log.error('[debugger:devtools_client] Error evaluating code on call frame: %s', result?.description) evalResults = [] } else { evalResults = result?.value ?? [] } // TODO: Create unique states for each affected probe based on that probes unique `capture` settings (DEBUG-2863) /** @type {Awaited> | undefined} */ let localState if (numberOfProbesWithSnapshots !== 0) { localState = await getLocalStateForCallFrame( params.callFrames[0], { maxReferenceDepth, maxCollectionSize, maxFieldCount, maxLength }, start + config.dynamicInstrumentation.captureTimeoutNs ) } // Evaluate capture expressions for probes that have them let captureExpressionResults = null if (probesWithCaptureExpressions === true) { captureExpressionResults = new Map() for (const probe of probes) { if (conditionErrorProbes?.has(probe) || probe.compiledCaptureExpressions === undefined) continue // eslint-disable-next-line no-await-in-loop captureExpressionResults.set(probe.id, await evaluateCaptureExpressions( params.callFrames[0], probe.compiledCaptureExpressions, start + config.dynamicInstrumentation.captureTimeoutNs, config.dynamicInstrumentation.evaluationTimeoutNs )) } } await session.post('Debugger.resume') reportPauseDuration(start) // Ideally these throttles would be installed before resuming so a tight loop could not sample the probe again before // the request is handled. That would keep the application paused for another inspector request even when the probe // does not immediately run again, so we deliberately resume first. If the race occurs, the probe can perform one // additional over-budget evaluation before the throttle takes effect, which is preferable to lengthening every // timeout pause. for (const probe of probes) { // Condition errors are already throttled synchronously by the sampler; preserve that state and its classification. if (conditionErrorProbes?.has(probe)) continue if ((probe.templateRequiresEvaluation && templatesTimedOut) || captureExpressionResults?.get(probe.id)?.timedOut === true) { // TODO: Batch all timed-out probes into a single Runtime.evaluate request. throttleProbe(probe) } } const logger = { // We can safely use `location.file` from the first probe in the array, since all probes hit by `hitBreakpoints` // must exist in the same file since the debugger can only pause the main thread in one location. name: probes[0].location.file, // name of the class/type/file emitting the snapshot method: params.callFrames[0].functionName, // name of the method/function emitting the snapshot version, thread_id: threadId, thread_name: threadName, } const stack = await getStackFromCallFrames(params.callFrames) const dd = processDD(evalResults[0]) // the first result is the dd tags, the rest are the frame expression results let messageIndex = 1 // The probes whose capture got permanently disabled during this pause, if any /** @type {object[] | undefined} */ let captureDisabledProbes // TODO: Send multiple probes in one HTTP request as an array (DEBUG-2848) for (const probe of probes) { const snapshot = { id: randomUUID(), timestamp, probe: { id: probe.id, version: probe.version, location: probe.location, }, stack, language: 'javascript', } // Which guardrail bucket the event belongs to, and which capture limits were enforced while producing it. The // snapshot module records the reasons, including runtime errors: a fatal error does not necessarily mean one, as // the collector also raises a fatal error to disable capture when it hits its large object safety threshold. /** @type {number} */ let eventType = EVENT_TYPE.LOG let incompleteReasons = 0 if (conditionErrorProbes?.has(probe)) { // Report the failing condition instead of a probe result, so the user can see why the probe doesn't fire const error = evalResults[messageIndex++] const message = typeof error === 'string' ? error : 'Unknown evaluation error' log.debug('[debugger:devtools_client] Condition of probe %s failed to evaluate: %s', probe.id, message) snapshot.evaluationErrors = [{ expr: probe.when.dsl, message }] ackEmitting(probe) send(message, logger, dd, snapshot, config.propagateProcessTags.enabled ? processTags.serialized : undefined, probe.captureSnapshot === true || probe.compiledCaptureExpressions !== undefined ? EVENT_TYPE.SNAPSHOT : EVENT_TYPE.LOG, 0) continue } if (probe.captureSnapshot) { eventType = EVENT_TYPE.SNAPSHOT const { processLocalState, fatalErrors, incomplete } = /** @type {NonNullable} */ (localState) if (fatalErrors.length > 0) { // There was an error collecting the snapshot for this probe, let's not try again probe.captureSnapshot = false probe.permanentEvaluationErrors = fatalErrors.map(error => ({ expr: '', message: error.message, })) captureDisabledProbes ??= [] captureDisabledProbes.push(probe) } snapshot.captures = { lines: { [probe.location.lines[0]]: { locals: processLocalState() } }, } incompleteReasons |= incomplete.reasons } else if (probe.compiledCaptureExpressions !== undefined) { eventType = EVENT_TYPE.SNAPSHOT const expressionResult = /** @type {Map} */ (captureExpressionResults).get(probe.id) if (expressionResult) { // Handle fatal capture errors - disable capture expressions for this probe permanently if (expressionResult.fatalErrors?.length > 0) { probe.compiledCaptureExpressions = undefined probe.permanentEvaluationErrors = expressionResult.fatalErrors.map(error => ({ expr: '', message: error.message, })) captureDisabledProbes ??= [] captureDisabledProbes.push(probe) } snapshot.captures = { lines: { [probe.location.lines[0]]: { captureExpressions: expressionResult.processCaptureExpressions() } }, } incompleteReasons |= expressionResult.incomplete.reasons // Handle transient evaluation errors - include in snapshot for this capture if (expressionResult.evaluationErrors?.length > 0) { if (snapshot.evaluationErrors === undefined) { snapshot.evaluationErrors = expressionResult.evaluationErrors } else { snapshot.evaluationErrors.push(...expressionResult.evaluationErrors) } } } else { log.error('[debugger:devtools_client] Missing capture expression results for probe %s (version: %s)', probe.id, probe.version) snapshot.evaluationErrors = [{ expr: '', message: 'Internal error: capture expression results not found', }] incompleteReasons |= INCOMPLETE_REASON.RUNTIME_ERROR } } if (probe.permanentEvaluationErrors !== undefined) { snapshot.evaluationErrors = [...probe.permanentEvaluationErrors] } let message = '' if (probe.templateRequiresEvaluation) { const results = evalResults[messageIndex++] if (results === undefined) { log.error('[debugger:devtools_client] No evaluation results for probe %s', probe.id) } else { for (const result of results) { if (typeof result === 'string') { message += result } else { // If `result` isn't a string, it's an evaluation error object if (snapshot.evaluationErrors === undefined) { snapshot.evaluationErrors = [result] } else { snapshot.evaluationErrors.push(result) } message += `{${result.message}}` } } if (probe.templateRedactionErrors !== undefined) { if (snapshot.evaluationErrors === undefined) { snapshot.evaluationErrors = [...probe.templateRedactionErrors] } else { snapshot.evaluationErrors.push(...probe.templateRedactionErrors) } } } if (templatesTimedOut) { const error = { expr: '', message: 'Template evaluation exceeded its time budget of ' + `${config.dynamicInstrumentation.evaluationTimeoutNs / 1_000_000n}ms`, } if (snapshot.evaluationErrors === undefined) { snapshot.evaluationErrors = [error] } else { snapshot.evaluationErrors.push(error) } } } else { message = probe.template } ackEmitting(probe) send(message, logger, dd, snapshot, config.propagateProcessTags.enabled ? processTags.serialized : undefined, eventType, incompleteReasons) } if (captureDisabledProbes !== undefined) { // The breakpoint condition bakes in whether each probe produces snapshots, which decides if a hit counts against // the global snapshot rate limit and how a skipped hit is classified. Rebuild the conditions now that this // changed. The disabled probes can be spread over more than one breakpoint, but each affected location is only // refreshed once. refreshBreakpoints(captureDisabledProbes).catch((err) => { // eslint-disable-next-line eslint-rules/eslint-log-printf-style log.error(() => { let ids = captureDisabledProbes[0].id for (let i = 1; i < captureDisabledProbes.length; i++) ids += `, ${captureDisabledProbes[i].id}` return `[debugger:devtools_client] Error refreshing breakpoints after disabling capture for probes: ${ids}` }, err) }) } }) /** * Called after resuming so reporting the elapsed time doesn't extend the pause. This measures from receipt of the * pause notification through the resume response, not the full time V8 suspends the instrumented thread. * * @param {bigint} start - Monotonic time when the pause notification was received, in nanoseconds. */ function reportPauseDuration (start) { const durationMs = Number(process.hrtime.bigint() - start) / 1_000_000 pauseDurations.record(durationMs) log.debug('[debugger:devtools_client] Finished processing breakpoints - instrumented thread paused for: ~%d ms', durationMs) } /** * Throttle a probe in the runtime sampler because its template or capture expressions exceeded the evaluation time * budget. The result has already been reported, so this only stops the probe from being evaluated again for a while. * * @param {{ id: string }} probe - The probe to throttle. */ function throttleProbe (probe) { log.debug('[debugger:devtools_client] Evaluation of probe %s exceeded its time budget; throttling probe', probe.id) session.post('Runtime.evaluate', { expression: getEvaluationTimedOutExpression(probe.id) }).catch((err) => { log.error('[debugger:devtools_client] Error throttling probe %s', probe.id, err) }) } function processDD (result) { return result?.trace_id === undefined ? undefined : result }