Skip to content

Instantly share code, notes, and snippets.

View deepal's full-sized avatar

Deepal Jayasekara deepal

  • CompareTheMarket.com
  • London, United Kingdom
View GitHub Profile
@deepal
deepal / pool.js
Created October 7, 2019 18:25
Worker Threads Pool
const {EventEmitter} = require('events');
const {Worker, MessageChannel, parentPort} = require('worker_threads');
const WORKER_STATUS = {
IDLE: Symbol('idle'),
BUSY: Symbol('busy'),
};
module.exports.WorkerPool = class WorkerPool extends EventEmitter{
constructor(script, size) {
const workspacePath = '/some/workspace/path';
const workspaceModulesDir = path.join(workspacePath, 'node_modules');
function installModule(moduleName) {
execSync(`npm install --silent ${moduleName}`, { cwd: workspacePath });
}
function wrapRequire() {
const originalRequire = Module.prototype.require;
Module.prototype.require = function (moduleName) {
global.baapan = async (requiredModule) => {
const [moduleName] = parsePath(requiredModule);
if (!moduleName) {
return console.error('Invalid module name provided!');
}
return new Promise((resolve, reject) => {
try {
resolve(require(requiredModule));
@deepal
deepal / babel-register-config.json
Created June 17, 2019 13:27
@babel/register configuration in package.json
{
"babel": {
"env": {
"test": {
"plugins": [
"istanbul"
]
}
},
"presets": [
@deepal
deepal / callback.cc
Created June 16, 2019 00:37
Async Hooks: After
InternalCallbackScope::~InternalCallbackScope() {
Close();
}
void InternalCallbackScope::Close() {
// ...redacted
if (async_context_.async_id != 0) {
AsyncWrap::EmitAfter(env_, async_context_.async_id);
}
@deepal
deepal / async_wrap.cc
Created June 15, 2019 23:46
Triggering JS init() hooks from c++ async_hooks_init_function
void AsyncWrap::EmitAsyncInit(Environment* env,
Local<Object> object,
Local<String> type,
double async_id,
double trigger_async_id) {
CHECK(!object.IsEmpty());
CHECK(!type.IsEmpty());
AsyncHooks* async_hooks = env->async_hooks();
// Nothing to execute, so can continue normally.
@deepal
deepal / async_wrap.cc
Created June 15, 2019 23:43
AH1: Initializing async hooks (bindings between c++ and JS contexts)
static void SetupHooks(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
CHECK(args[0]->IsObject());
// All of init, before, after, destroy are supplied by async_hooks
// internally, so this should every only be called once. At which time all
// the functions should be set. Detect this by checking if init !IsEmpty().
CHECK(env->async_hooks_init_function().IsEmpty());
// Constructor of Async resource
AsyncResource::AsyncResource(Isolate* isolate,
Local<Object> resource,
const char* name,
async_id trigger_async_id)
: env_(Environment::GetCurrent(isolate)),
resource_(isolate, resource) {
async_context_ = EmitAsyncInit(isolate, resource, name,
trigger_async_id);
}
@deepal
deepal / restify-request-logger.js
Last active September 25, 2019 15:20
Restify middleware for request logging including response code and response time
this.server.pre((req, res, next) => {
this.logger.debug(`Start ${req.method} ${req.url}`);
const requestStart = process.hrtime();
res.on('finish', () => {
const [reqTimeS, reqTimeNS] = process.hrtime(requestStart),
requestDurationMS = (reqTimeS * 1e3 + reqTimeNS / 1e9).toFixed(2);
this.logger.debug(`End ${req.method} ${req.url} (status=${res.statusCode} duration=${requestDurationMS}ms)`);
});
next();
});
if (err instanceof AuthenticationError) {
return res.status(401).send('not authenticated');
}
if (err instanceof UnauthorizedError) {
return res.status(403).send('forbidden');
}
if (err instanceof InvalidInputError) {
return res.status(400).send('bad request');