|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +const http = require('http'); |
| 4 | +const EventEmitter = require('events'); |
| 5 | + |
| 6 | +const PORT = process.env.PORT || 5000; |
| 7 | +const Events = new EventEmitter(); |
| 8 | + |
| 9 | +// This will block the event loop for ~lengths of time |
| 10 | +function blockCpuFor(ms) { |
| 11 | + return new Promise((resolve, reject) => { |
| 12 | + setTimeout(() => { |
| 13 | + console.log(`blocking the event loop for ${ms}ms`); |
| 14 | + let now = new Date().getTime(); |
| 15 | + let result = 0 |
| 16 | + while(true) { |
| 17 | + result += Math.random() * Math.random(); |
| 18 | + if (new Date().getTime() > now + ms) |
| 19 | + break; |
| 20 | + } |
| 21 | + resolve(); |
| 22 | + }, 100); |
| 23 | + }); |
| 24 | +} |
| 25 | + |
| 26 | +function getNextMetricsEvent() { |
| 27 | + return new Promise((resolve, reject) => Events.once('metrics', resolve)); |
| 28 | +} |
| 29 | + |
| 30 | +const server = http.createServer((req, res) => { |
| 31 | + // wait for the next metrics event |
| 32 | + getNextMetricsEvent() |
| 33 | + .then(blockCpuFor(2000)) |
| 34 | + .then(blockCpuFor(100)) |
| 35 | + .then(blockCpuFor(100)) |
| 36 | + .then(blockCpuFor(100)) |
| 37 | + .then(blockCpuFor(100)) |
| 38 | + .then(blockCpuFor(100)) |
| 39 | + .then(blockCpuFor(100)) |
| 40 | + .then(blockCpuFor(100)) |
| 41 | + .then(blockCpuFor(100)) |
| 42 | + .then(blockCpuFor(100)) |
| 43 | + .then(blockCpuFor(100)) |
| 44 | + // gather the next metrics data which should include these pauses |
| 45 | + .then(getNextMetricsEvent()) |
| 46 | + .then(data => { |
| 47 | + res.setHeader('Content-Type', 'application/json'); |
| 48 | + res.end(data); |
| 49 | + }) |
| 50 | + .catch(() => { |
| 51 | + res.statusCode = 500; |
| 52 | + res.end("Something went wrong"); |
| 53 | + }); |
| 54 | +}); |
| 55 | + |
| 56 | +server.listen(PORT, () => console.log(`Listening on ${PORT}`)); |
| 57 | + |
| 58 | +// Create a second server that intercepts the HTTP requests |
| 59 | +// sent by the metrics plugin |
| 60 | +const metricsListener = http.createServer((req, res) => { |
| 61 | + if (req.method == 'POST') { |
| 62 | + let body = ''; |
| 63 | + req.on('data', (data) => body += data); |
| 64 | + req.on('end', () => { |
| 65 | + res.statusCode = 200; |
| 66 | + res.end(); |
| 67 | + Events.emit('metrics', body) |
| 68 | + }); |
| 69 | + } |
| 70 | +}); |
| 71 | + |
| 72 | +metricsListener.listen(3000, () => console.log('Listening for metrics on 3000')); |
0 commit comments