Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions event-loop-spinner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const async_hooks = require('async_hooks');

class EventLoopSpinner{
constructor() {
this.hooksMap = {};
this.blockedSince = Date.now();

const asyncHook = async_hooks.createHook({
init: (asyncId, type, triggerAsyncId, resource) => {
this.hooksMap[asyncId] = {type};
},
before: (asyncId) => {
if (asyncId === 0) {
return;
}
if (!['TickObject', 'Microtask', 'PROMISE'].includes(this.hooksMap[asyncId].type)) {
this.blockedSince = Date.now();
}
},
destroy: (asyncId) => {
delete this.hooksMap[asyncId];
}
});
asyncHook.enable();
}

isStarving(thresholdMs = 100) {
return Date.now() - this.blockedSince > thresholdMs;
}

async spin() {
return new Promise(setImmediate);
}
}

const eventLoopSpinner = new EventLoopSpinner();

module.exports = {
eventLoopSpinner,
}
15 changes: 15 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const express = require('express');
const crypto = require('crypto');

const {eventLoopSpinner} = require('./event-loop-spinner');

const PID = process.pid;

function log(msg) {
Expand Down Expand Up @@ -74,6 +76,19 @@ app.get('/compute-with-set-immediate', async function computeWSetImmediate(req,
res.send(hash.digest('hex') + '\n');
});

app.get('/compute-with-spinner', async function computeWSetImmediate(req, res) {
log('computing async with event-loop-spinner!');

const hash = crypto.createHash('sha256');
for (let i = 0; i < 10e6; i++) {
hash.update(randomString());
if (eventLoopSpinner.isStarving()) {
await eventLoopSpinner.spin();
}
}
res.send(hash.digest('hex') + '\n');
});

app.get('/compute-with-next-tick', async function computeWNextTick (req, res) {
log('computing async with nextTick!');

Expand Down