-
Notifications
You must be signed in to change notification settings - Fork 225
/
transaction.js
418 lines (361 loc) · 12.5 KB
/
transaction.js
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
'use strict'
var util = require('util')
var ObjectIdentityMap = require('object-identity-map')
const constants = require('../constants')
var getPathFromRequest = require('./express-utils').getPathFromRequest
var GenericSpan = require('./generic-span')
var parsers = require('../parsers')
var Span = require('./span')
var symbols = require('../symbols')
var { TransactionIds } = require('./ids')
module.exports = Transaction
util.inherits(Transaction, GenericSpan)
function Transaction (agent, name, ...args) {
GenericSpan.call(this, agent, ...args)
const verb = this.parentId ? 'continue' : 'start'
agent.logger.debug('%s trace %o', verb, { trans: this.id, parent: this.parentId, trace: this.traceId, name: this.name, type: this.type, subtype: this.subtype, action: this.action })
this._defaultName = name || ''
this._customName = ''
this._user = null
this._custom = null
this._result = constants.RESULT_SUCCESS
this._builtSpans = 0
this._droppedSpans = 0
this._breakdownTimings = new ObjectIdentityMap()
this._faas = undefined
this._service = undefined
this._message = undefined
this._cloud = undefined
this.outcome = constants.OUTCOME_UNKNOWN
}
Object.defineProperty(Transaction.prototype, 'name', {
configurable: true,
enumerable: true,
get () {
// Fall back to a somewhat useful name in case no _defaultName is set.
// This might happen if res.writeHead wasn't called.
return this._customName ||
this._defaultName ||
(this.req ? this.req.method + ' unknown route (unnamed)' : 'unnamed')
},
set (name) {
if (this.ended) {
this._agent.logger.debug('tried to set transaction.name on already ended transaction %o', { trans: this.id, parent: this.parentId, trace: this.traceId })
return
}
this._agent.logger.debug('setting transaction name %o', { trans: this.id, parent: this.parentId, trace: this.traceId, name: name })
this._customName = name
}
})
Object.defineProperty(Transaction.prototype, 'result', {
configurable: true,
enumerable: true,
get () {
return this._result
},
set (result) {
if (this.ended) {
this._agent.logger.debug('tried to set transaction.result on already ended transaction %o', { trans: this.id, parent: this.parentId, trace: this.traceId })
return
}
this._agent.logger.debug('setting transaction result %o', { trans: this.id, parent: this.parentId, trace: this.traceId, result: result })
this._result = result
}
})
Object.defineProperty(Transaction.prototype, 'ids', {
get () {
return this._ids === null
? (this._ids = new TransactionIds(this))
: this._ids
}
})
Transaction.prototype.toString = function () {
return this.ids.toString()
}
Transaction.prototype.setUserContext = function (context) {
if (!context) return
this._user = Object.assign(this._user || {}, context)
}
Transaction.prototype.setServiceContext = function (serviceContext) {
if (!serviceContext) return
this._service = Object.assign(this._service || {}, serviceContext)
}
Transaction.prototype.setMessageContext = function (messageContext) {
if (!messageContext) return
this._message = Object.assign(this._message || {}, messageContext)
}
Transaction.prototype.setFaas = function (faasFields) {
if (!faasFields) return
this._faas = Object.assign(this._faas || {}, faasFields)
}
Transaction.prototype.setCustomContext = function (context) {
if (!context) return
this._custom = Object.assign(this._custom || {}, context)
}
Transaction.prototype.setCloudContext = function (cloudContext) {
if (!cloudContext) return
this._cloud = Object.assign(this._cloud || {}, cloudContext)
}
// Create a span on this transaction and make it the current span.
Transaction.prototype.startSpan = function (...args) {
const span = this.createSpan(...args)
if (span) {
this._agent._instrumentation.supersedeWithSpanRunContext(span)
}
return span
}
// Create a span on this transaction.
//
// This does *not* replace the current run context to make this span the
// "current" one. This allows instrumentations to avoid impacting the run
// context of the calling code. Compare to `startSpan`.
Transaction.prototype.createSpan = function (...args) {
if (!this.sampled) {
return null
}
if (this.ended) {
this._agent.logger.debug('transaction already ended - cannot build new span %o', { trans: this.id, parent: this.parentId, trace: this.traceId }) // TODO: Should this be supported in the new API?
return null
}
if (this._builtSpans >= this._agent._conf.transactionMaxSpans) {
this._droppedSpans++
return null
}
// Exit spans must not have child spans (unless of the same type and subtype).
// https://github.com/elastic/apm/blob/master/specs/agents/tracing-spans.md#child-spans-of-exit-spans
const opts = typeof args[args.length - 1] === 'object'
? (args.pop() || {})
: {}
const [_name, type, subtype] = args // eslint-disable-line no-unused-vars
opts.childOf = opts.childOf || this._agent._instrumentation.currSpan() || this
const childOf = opts.childOf
if (childOf instanceof Span && childOf._exitSpan &&
!(childOf.type === type && childOf.subtype === subtype)) {
this._agent.logger.trace({ exitSpanId: childOf.id, newSpanArgs: args },
'createSpan: drop child span of exit span')
return null
}
this._builtSpans++
return new Span(this, ...args, opts)
}
// Note that this only returns a complete result when called *during* the call
// to `transaction.end()`.
Transaction.prototype.toJSON = function () {
var payload = {
id: this.id,
trace_id: this.traceId,
parent_id: this.parentId,
name: this.name,
type: this.type || 'custom',
duration: this._duration,
timestamp: this.timestamp,
result: String(this.result),
sampled: this.sampled,
context: undefined,
span_count: {
started: this._builtSpans
},
outcome: this.outcome,
faas: this._faas
}
if (this.sampled) {
payload.context = {
user: Object.assign(
{},
this.req && parsers.getUserContextFromRequest(this.req),
this._user
),
tags: this._labels || {},
custom: this._custom || {},
service: this._service || {},
cloud: this._cloud || {},
message: this._message || {}
}
// Only include dropped count when spans have been dropped.
if (this._droppedSpans > 0) {
payload.span_count.dropped = this._droppedSpans
}
var conf = this._agent._conf
if (this.req) {
payload.context.request = parsers.getContextFromRequest(this.req, conf, 'transactions')
}
if (this.res) {
payload.context.response = parsers.getContextFromResponse(this.res, conf)
}
}
// add sample_rate to transaction
// https://github.com/elastic/apm/blob/main/specs/agents/tracing-sampling.md
// Only set sample_rate on transaction payload if a valid trace state
// variable is set.
//
// "If there is no tracestate or no valid es entry with an s attribute,
// then the agent must omit sample_rate from non-root transactions and
// their spans."
const sampleRate = this.sampleRate
if (sampleRate !== null) {
payload.sample_rate = sampleRate
}
return payload
}
// Note that this only returns a complete result when called *during* the call
// to `transaction.end()`.
Transaction.prototype._encode = function () {
if (!this.ended) {
this._agent.logger.error('cannot encode un-ended transaction: %o', { trans: this.id, parent: this.parentId, trace: this.traceId })
return null
}
return this.toJSON()
}
Transaction.prototype.setDefaultName = function (name) {
this._agent.logger.debug('setting default transaction name: %s %o', name, { trans: this.id, parent: this.parentId, trace: this.traceId })
this._defaultName = name
}
Transaction.prototype.setDefaultNameFromRequest = function () {
var req = this.req
var path = getPathFromRequest(req, false, this._agent._conf.usePathAsTransactionName)
if (!path) {
this._agent.logger.debug('could not extract route name from request %o', {
url: req.url,
type: typeof path,
null: path === null, // because typeof null === 'object'
route: !!req.route,
regex: req.route ? !!req.route.regexp : false,
mountstack: req[symbols.expressMountStack] ? req[symbols.expressMountStack].length : false,
trans: this.id,
parent: this.parentId,
trace: this.traceId
})
path = 'unknown route'
}
this.setDefaultName(req.method + ' ' + path)
}
Transaction.prototype.ensureParentId = function () {
return this._context.ensureParentId()
}
Transaction.prototype.end = function (result, endTime) {
if (this.ended) {
this._agent.logger.debug('tried to call transaction.end() on already ended transaction %o', { trans: this.id, parent: this.parentId, trace: this.traceId })
return
}
if (result !== undefined && result !== null) {
this.result = result
}
if (!this._defaultName && this.req) this.setDefaultNameFromRequest()
this._timer.end(endTime)
this._duration = this._timer.duration
this._captureBreakdown(this)
this.ended = true
this._agent._instrumentation.addEndedTransaction(this)
this._agent.logger.debug({ trans: this.id, name: this.name, parent: this.parentId, trace: this.traceId, type: this.type, result: this.result, duration: this._duration },
'ended transaction')
// Reduce this transaction's memory usage by dropping references except to
// fields required to support `interface Transaction`.
// Transaction fields:
this._customName = this.name // Short-circuit the `name` getter.
this._defaultName = ''
this.req = null
this.res = null
this._user = null
this._custom = null
this._breakdownTimings = null
this._faas = undefined
this._service = undefined
this._message = undefined
this._cloud = undefined
// GenericSpan fields:
// - Cannot drop `this._context` because it is used for `traceparent`, `ids`,
// and `.sampled` (when capturing breakdown metrics for child spans).
this._timer = null
this._labels = null
}
Transaction.prototype.setOutcome = function (outcome) {
if (!this._isValidOutcome(outcome)) {
this._agent.logger.trace(
'Unknown outcome [%s] seen in Transaction.setOutcome, ignoring',
outcome
)
return
}
if (this.ended) {
this._agent.logger.debug(
'tried to call Transaction.setOutcome() on already ended transaction %o',
{ trans: this.id, parent: this.parentId, trace: this.traceId })
return
}
this._freezeOutcome()
this.outcome = outcome
}
Transaction.prototype._setOutcomeFromHttpStatusCode = function (statusCode) {
// if an outcome's been set from the API we
// honor its value
if (this._isOutcomeFrozen) {
return
}
if (statusCode >= 500) {
this.outcome = constants.OUTCOME_FAILURE
} else {
this.outcome = constants.OUTCOME_SUCCESS
}
}
Transaction.prototype._captureBreakdown = function (span) {
if (this.ended) {
return
}
const agent = this._agent
const metrics = agent._metrics
const conf = agent._conf
// Avoid unneeded breakdown metrics processing if only propagating trace context.
if (conf.contextPropagationOnly) {
return
}
// Record span data
if (this.sampled && conf.breakdownMetrics) {
captureBreakdown(this, {
transaction: transactionBreakdownDetails(this),
span: spanBreakdownDetails(span)
}, span._timer.selfTime)
}
// Record transaction data
if (span instanceof Transaction) {
for (const { labels, time, count } of this._breakdownTimings.values()) {
const flattenedLabels = flattenBreakdown(labels)
metrics.incrementCounter('span.self_time.count', flattenedLabels, count)
metrics.incrementCounter('span.self_time.sum.us', flattenedLabels, time)
}
}
}
function transactionBreakdownDetails ({ name, type } = {}) {
return {
name,
type
}
}
function spanBreakdownDetails (span) {
if (span instanceof Transaction) {
return {
type: 'app'
}
}
const { type, subtype } = span
return {
type,
subtype
}
}
function captureBreakdown (transaction, labels, time) {
const build = () => ({ labels, count: 0, time: 0 })
const counter = transaction._breakdownTimings.ensure(labels, build)
counter.time += time
counter.count++
}
function flattenBreakdown (source, target = {}, prefix = '') {
for (const [key, value] of Object.entries(source)) {
if (typeof value === 'undefined' || value === null) continue
if (typeof value === 'object') {
flattenBreakdown(value, target, `${prefix}${key}::`)
} else {
target[`${prefix}${key}`] = value
}
}
return target
}