forked from iopipe/iopipe-js-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
106 lines (88 loc) · 2.55 KB
/
index.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
'use strict'
const dns = require('dns')
const setConfig = require('./src/config.js')
const Context = require('./src/context.js')
const Callback = require('./src/callback.js')
const Report = require('./src/report.js')
const globals = require('./src/globals')
function makeDnsPromise(host) {
return new Promise((resolve, reject) => {
dns.lookup(host, (err, address) => {
if (err) {
reject(err)
}
resolve(address)
})
})
}
function setupTimeoutCapture(config, report, context) {
if (config.timeoutWindow < 1) {
return
}
var endTime = 599900 /* Maximum execution: 100ms short of 5 minutes */
if (config.timeoutWindow > 0 && context && context.getRemainingTimeInMillis) {
endTime = Math.max(0, context.getRemainingTimeInMillis() - config.timeoutWindow)
}
return setTimeout(() => {
report.send(new Error("Timeout Exceeded."), function noop() {})
}, endTime)
}
module.exports = function(options) {
var fn = function(func) {
fn.metricsQueue = []
const config = setConfig(options)
if (!config.clientId) {
// No-op if user doesn't set an IOpipe token.
return func
}
/* resolve DNS early on coldstarts */
var dnsPromise = makeDnsPromise(config.host)
return function() {
fn.metricsQueue = []
var args = [].slice.call(arguments)
if (!globals.COLDSTART) {
/* Get an updated DNS record. */
dnsPromise = makeDnsPromise(config.host)
}
var startTime = process.hrtime()
const report = new Report(config, args[1], startTime, fn.metricsQueue, dnsPromise)
var timeout = setupTimeoutCapture(config, report, args[1])
var callback = (err, cb) => {
if (timeout) { clearTimeout(timeout) }
report.send(err, cb)
}
/* Mangle arguments, wrapping callbacks. */
args[1] = Context(callback, args[1])
args[2] = Callback(callback, args[2])
try {
return func.apply(this, args)
}
catch (err) {
clearTimeout(timeout)
report.send(err, function noop() {})
return undefined
}
}
}
// Alias decorate to the wrapper function
fn.decorate = fn
fn.log = function(name, value) {
var numberValue, stringValue
if (typeof value === 'number') {
numberValue = value
} else {
if(typeof value === 'object') {
JSON.stringify(value)
} else {
stringValue = String(value)
}
}
fn.metricsQueue.push({
name: name,
n: numberValue,
s: stringValue
})
fn.VERSION = globals.VERSION
}
return fn
}