-
Notifications
You must be signed in to change notification settings - Fork 328
/
Copy pathscope.js
63 lines (45 loc) · 1.29 KB
/
scope.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
'use strict'
const { storage } = require('../../datadog-core')
// TODO: refactor bind to use shimmer once the new internal tracer lands
const originals = new WeakMap()
class Scope {
active () {
const store = storage('legacy').getStore()
return (store && store.span) || null
}
activate (span, callback) {
if (typeof callback !== 'function') return callback
const oldStore = storage('legacy').getStore()
const newStore = span ? storage('legacy').getStore(span._store) : oldStore
storage('legacy').enterWith({ ...newStore, span })
try {
return callback()
} catch (e) {
if (span && typeof span.setTag === 'function') {
span.setTag('error', e)
}
throw e
} finally {
storage('legacy').enterWith(oldStore)
}
}
bind (fn, span) {
if (typeof fn !== 'function') return fn
const scope = this
const spanOrActive = this._spanOrActive(span)
const bound = function () {
return scope.activate(spanOrActive, () => {
return fn.apply(this, arguments)
})
}
originals.set(bound, fn)
return bound
}
_spanOrActive (span) {
return span !== undefined ? span : this.active()
}
_isPromise (promise) {
return promise && typeof promise.then === 'function'
}
}
module.exports = Scope