Created
October 11, 2017 23:41
-
-
Save NatalieWolfe/eb1fb8fd27609f0c1bde77ddb34535ab to your computer and use it in GitHub Desktop.
Simple async-hook server use.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
var asyncHooks = require('async_hooks') | |
var ids = new Map() | |
var toReturn | |
var noopHook = asyncHooks.createHook({ | |
init: function initHook(id, type) { | |
if (type !== 'PROMISE') { | |
return | |
} | |
ids.set(id, {}) | |
}, | |
before: function beforeHook(id) { | |
var hookSegment = ids.get(id) | |
if (!hookSegment) { | |
return | |
} | |
toReturn = hookSegment | |
ids.set(id, null) | |
}, | |
after: function afterHook(id) { | |
var hookSegment = ids.get(id) | |
// hookSegment is the segment that was active before the promise | |
// executed. If the promise is executing before a segment has been | |
// restored, hookSegment will be null and should be restored. Thus | |
// undefined is the only invalid value here. | |
if (hookSegment === undefined) { | |
return | |
} | |
ids.set(id, toReturn) | |
toReturn = hookSegment | |
}, | |
destroy: function destHook(id) { | |
ids.delete(id) | |
} | |
}) | |
var http = require('http') | |
var lastCPUSample = process.cpuUsage() | |
var server = http.createServer(function(req, res) { | |
req.resume() | |
if (req.url === '/health') { | |
res.writeHead(200, 'Content-Type', 'application/json') | |
res.write(JSON.stringify(healthCheck())) | |
res.end() | |
} else if (req.url === '/guid') { | |
res.writeHead(200, 'Content-Type', 'application/json') | |
res.write(JSON.stringify({ guid: GUID })) | |
res.end() | |
} else if (req.url === '/stats') { | |
var cpuDiff = process.cpuUsage(lastCPUSample) | |
lastCPUSample = process.cpuUsage() | |
var memorySample = process.memoryUsage() | |
res.writeHead(200, 'Content-Type', 'application/json') | |
res.write(JSON.stringify({ | |
cpu: { | |
user: cpuDiff.user, | |
system: cpuDiff.system | |
}, | |
memory: { | |
heapUsed: memorySample.heapUsed, | |
heapFree: memorySample.heapTotal - memorySample.heapUsed, | |
nonHeap: memorySample.rss - memorySample.heapTotal | |
} | |
})) | |
res.end() | |
} else if (req.url === '/') { | |
var p = Promise.resolve(1) | |
for (var i = 0; i < 1000; ++i) { | |
p = p.then(result => { | |
return 1 | |
}) | |
} | |
p.then(result => { | |
res.write('ok') | |
res.end() | |
}, error => { | |
res.write(error) | |
res.end() | |
}) | |
} | |
}) | |
var server = server.listen(process.env.PORT, function serverReady () { | |
var port = server.address().port | |
console.log('listening on ' + port) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment