All files / lib async_hooks.js

99.45% Statements 366/368
98.73% Branches 78/79
100% Functions 21/21
99.45% Lines 366/368

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 36938x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 3943x 3943x 3943x 3943x 3943x 3943x 3943x 3943x 3943x 3943x 3888x 3888x 3888x 3888x 3888x 3888x 3943x 38x 38x 2936x 2936x 2936x 2936x 2936x 2936x 2936x 2936x 2936x 2754x 2754x 2754x 2754x 2754x 2754x 2754x 2754x 2754x 2754x 2754x 2754x 2754x 2754x 2936x 466x 466x 2754x 2754x 2754x 2754x 2936x 38x 38x 2481x 2481x 2481x 2481x 2481x 2472x 2472x 2472x 2472x 2472x 2472x 2472x 2472x 2472x 2472x 2472x 2481x 178x 178x 2472x 2472x 2481x 38x 38x 38x 3943x 3943x 3943x 38x 38x 38x 38x 38x 38x 38x 38x 4243x 4243x 4243x 4243x 4243x 4231x 4231x 4231x 4231x 4235x 4235x 4235x 4243x 3x 3x 4232x 4232x 4232x 4232x 4232x 4232x 2492x 1x 1x 2491x 2491x 2491x 4230x 4243x 2486x 2486x 2486x 2486x 2486x 4243x 38x 38x 1918x 1918x 1918x 1918x 1918x 1918x 1918x 1918x 1918x 1917x 1917x 1917x 1918x 38x 38x 536x 12x 12x 536x 536x 536x 38x 38x 2019x 2019x 38x 38x 2007x 2007x 38x 38x 11x 11x 11x 4x 4x 5x 5x 4x 11x 2x 2x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 11x 38x 38x 1x 1x 1x 38x 38x 38x 38x 38x 914x 914x 914x 921x 921x 914x 38x 38x 38x 38x 25x 25x 25x 38x 38x 106x 106x 106x 106x 106x 106x 105x 105x 106x 106x 38x 38x 1248x 130x 130x 130x 130x 1248x 38x 38x 38x 921x 921x 921x 921x 921x 38x 38x 2x 2x 2x 2x 38x 38x 1142x 1142x     1142x 1142x 1142x 1142x 1142x 1142x 1142x 1142x 1142x 1142x 1142x 1142x 1142x 1142x 38x 38x 105x 1x 1x 104x 104x 104x 104x 104x 104x 105x 38x 38x 1414x 1284x 1284x 1284x 1414x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x  
'use strict';
 
const {
  ArrayPrototypeIncludes,
  ArrayPrototypeIndexOf,
  ArrayPrototypePush,
  ArrayPrototypeSplice,
  ArrayPrototypeUnshift,
  FunctionPrototypeBind,
  NumberIsSafeInteger,
  ObjectDefineProperties,
  ObjectIs,
  ReflectApply,
  Symbol,
  ObjectFreeze,
} = primordials;
 
const {
  ERR_ASYNC_CALLBACK,
  ERR_ASYNC_TYPE,
  ERR_INVALID_ASYNC_ID
} = require('internal/errors').codes;
const { kEmptyObject } = require('internal/util');
const {
  validateFunction,
  validateString,
} = require('internal/validators');
const internal_async_hooks = require('internal/async_hooks');
 
// Get functions
// For userland AsyncResources, make sure to emit a destroy event when the
// resource gets gced.
const { registerDestroyHook } = internal_async_hooks;
const {
  asyncWrap,
  executionAsyncId,
  triggerAsyncId,
  // Private API
  hasAsyncIdStack,
  getHookArrays,
  enableHooks,
  disableHooks,
  updatePromiseHookMode,
  executionAsyncResource,
  // Internal Embedder API
  newAsyncId,
  getDefaultTriggerAsyncId,
  emitInit,
  emitBefore,
  emitAfter,
  emitDestroy,
  enabledHooksExist,
  initHooksExist,
  destroyHooksExist,
} = internal_async_hooks;
 
// Get symbols
const {
  async_id_symbol, trigger_async_id_symbol,
  init_symbol, before_symbol, after_symbol, destroy_symbol,
  promise_resolve_symbol
} = internal_async_hooks.symbols;
 
// Get constants
const {
  kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,
} = internal_async_hooks.constants;
 
// Listener API //
 
class AsyncHook {
  constructor({ init, before, after, destroy, promiseResolve }) {
    if (init !== undefined && typeof init !== 'function')
      throw new ERR_ASYNC_CALLBACK('hook.init');
    if (before !== undefined && typeof before !== 'function')
      throw new ERR_ASYNC_CALLBACK('hook.before');
    if (after !== undefined && typeof after !== 'function')
      throw new ERR_ASYNC_CALLBACK('hook.after');
    if (destroy !== undefined && typeof destroy !== 'function')
      throw new ERR_ASYNC_CALLBACK('hook.destroy');
    if (promiseResolve !== undefined && typeof promiseResolve !== 'function')
      throw new ERR_ASYNC_CALLBACK('hook.promiseResolve');
 
    this[init_symbol] = init;
    this[before_symbol] = before;
    this[after_symbol] = after;
    this[destroy_symbol] = destroy;
    this[promise_resolve_symbol] = promiseResolve;
  }
 
  enable() {
    // The set of callbacks for a hook should be the same regardless of whether
    // enable()/disable() are run during their execution. The following
    // references are reassigned to the tmp arrays if a hook is currently being
    // processed.
    const { 0: hooks_array, 1: hook_fields } = getHookArrays();
 
    // Each hook is only allowed to be added once.
    if (ArrayPrototypeIncludes(hooks_array, this))
      return this;
 
    const prev_kTotals = hook_fields[kTotals];
 
    // createHook() has already enforced that the callbacks are all functions,
    // so here simply increment the count of whether each callbacks exists or
    // not.
    hook_fields[kTotals] = hook_fields[kInit] += +!!this[init_symbol];
    hook_fields[kTotals] += hook_fields[kBefore] += +!!this[before_symbol];
    hook_fields[kTotals] += hook_fields[kAfter] += +!!this[after_symbol];
    hook_fields[kTotals] += hook_fields[kDestroy] += +!!this[destroy_symbol];
    hook_fields[kTotals] +=
        hook_fields[kPromiseResolve] += +!!this[promise_resolve_symbol];
    ArrayPrototypePush(hooks_array, this);
 
    if (prev_kTotals === 0 && hook_fields[kTotals] > 0) {
      enableHooks();
    }
 
    updatePromiseHookMode();
 
    return this;
  }
 
  disable() {
    const { 0: hooks_array, 1: hook_fields } = getHookArrays();
 
    const index = ArrayPrototypeIndexOf(hooks_array, this);
    if (index === -1)
      return this;
 
    const prev_kTotals = hook_fields[kTotals];
 
    hook_fields[kTotals] = hook_fields[kInit] -= +!!this[init_symbol];
    hook_fields[kTotals] += hook_fields[kBefore] -= +!!this[before_symbol];
    hook_fields[kTotals] += hook_fields[kAfter] -= +!!this[after_symbol];
    hook_fields[kTotals] += hook_fields[kDestroy] -= +!!this[destroy_symbol];
    hook_fields[kTotals] +=
        hook_fields[kPromiseResolve] -= +!!this[promise_resolve_symbol];
    ArrayPrototypeSplice(hooks_array, index, 1);
 
    if (prev_kTotals > 0 && hook_fields[kTotals] === 0) {
      disableHooks();
    }
 
    return this;
  }
}
 
 
function createHook(fns) {
  return new AsyncHook(fns);
}
 
 
// Embedder API //
 
const destroyedSymbol = Symbol('destroyed');
 
class AsyncResource {
  constructor(type, opts = kEmptyObject) {
    validateString(type, 'type');
 
    let triggerAsyncId = opts;
    let requireManualDestroy = false;
    if (typeof opts !== 'number') {
      triggerAsyncId = opts.triggerAsyncId === undefined ?
        getDefaultTriggerAsyncId() : opts.triggerAsyncId;
      requireManualDestroy = !!opts.requireManualDestroy;
    }
 
    // Unlike emitInitScript, AsyncResource doesn't supports null as the
    // triggerAsyncId.
    if (!NumberIsSafeInteger(triggerAsyncId) || triggerAsyncId < -1) {
      throw new ERR_INVALID_ASYNC_ID('triggerAsyncId', triggerAsyncId);
    }
 
    const asyncId = newAsyncId();
    this[async_id_symbol] = asyncId;
    this[trigger_async_id_symbol] = triggerAsyncId;
 
    if (initHooksExist()) {
      if (enabledHooksExist() && type.length === 0) {
        throw new ERR_ASYNC_TYPE(type);
      }
 
      emitInit(asyncId, type, triggerAsyncId, this);
    }
 
    if (!requireManualDestroy && destroyHooksExist()) {
      // This prop name (destroyed) has to be synchronized with C++
      const destroyed = { destroyed: false };
      this[destroyedSymbol] = destroyed;
      registerDestroyHook(this, asyncId, destroyed);
    }
  }
 
  runInAsyncScope(fn, thisArg, ...args) {
    const asyncId = this[async_id_symbol];
    emitBefore(asyncId, this[trigger_async_id_symbol], this);
 
    try {
      const ret =
        ReflectApply(fn, thisArg, args);
 
      return ret;
    } finally {
      if (hasAsyncIdStack())
        emitAfter(asyncId);
    }
  }
 
  emitDestroy() {
    if (this[destroyedSymbol] !== undefined) {
      this[destroyedSymbol].destroyed = true;
    }
    emitDestroy(this[async_id_symbol]);
    return this;
  }
 
  asyncId() {
    return this[async_id_symbol];
  }
 
  triggerAsyncId() {
    return this[trigger_async_id_symbol];
  }
 
  bind(fn, thisArg) {
    validateFunction(fn, 'fn');
    let bound;
    if (thisArg === undefined) {
      const resource = this;
      bound = function(...args) {
        ArrayPrototypeUnshift(args, fn, this);
        return ReflectApply(resource.runInAsyncScope, resource, args);
      };
    } else {
      bound = FunctionPrototypeBind(this.runInAsyncScope, this, fn, thisArg);
    }
    ObjectDefineProperties(bound, {
      'length': {
        __proto__: null,
        configurable: true,
        enumerable: false,
        value: fn.length,
        writable: false,
      },
      'asyncResource': {
        __proto__: null,
        configurable: true,
        enumerable: true,
        value: this,
        writable: true,
      }
    });
    return bound;
  }
 
  static bind(fn, type, thisArg) {
    type = type || fn.name;
    return (new AsyncResource(type || 'bound-anonymous-fn')).bind(fn, thisArg);
  }
}
 
const storageList = [];
const storageHook = createHook({
  init(asyncId, type, triggerAsyncId, resource) {
    const currentResource = executionAsyncResource();
    // Value of currentResource is always a non null object
    for (let i = 0; i < storageList.length; ++i) {
      storageList[i]._propagate(resource, currentResource);
    }
  }
});
 
class AsyncLocalStorage {
  constructor() {
    this.kResourceStore = Symbol('kResourceStore');
    this.enabled = false;
  }
 
  disable() {
    if (this.enabled) {
      this.enabled = false;
      // If this.enabled, the instance must be in storageList
      ArrayPrototypeSplice(storageList,
                           ArrayPrototypeIndexOf(storageList, this), 1);
      if (storageList.length === 0) {
        storageHook.disable();
      }
    }
  }
 
  _enable() {
    if (!this.enabled) {
      this.enabled = true;
      ArrayPrototypePush(storageList, this);
      storageHook.enable();
    }
  }
 
  // Propagate the context from a parent resource to a child one
  _propagate(resource, triggerResource) {
    const store = triggerResource[this.kResourceStore];
    if (this.enabled) {
      resource[this.kResourceStore] = store;
    }
  }
 
  enterWith(store) {
    this._enable();
    const resource = executionAsyncResource();
    resource[this.kResourceStore] = store;
  }
 
  run(store, callback, ...args) {
    // Avoid creation of an AsyncResource if store is already active
    if (ObjectIs(store, this.getStore())) {
      return ReflectApply(callback, null, args);
    }
 
    this._enable();
 
    const resource = executionAsyncResource();
    const oldStore = resource[this.kResourceStore];
 
    resource[this.kResourceStore] = store;
 
    try {
      return ReflectApply(callback, null, args);
    } finally {
      resource[this.kResourceStore] = oldStore;
    }
  }
 
  exit(callback, ...args) {
    if (!this.enabled) {
      return ReflectApply(callback, null, args);
    }
    this.disable();
    try {
      return ReflectApply(callback, null, args);
    } finally {
      this._enable();
    }
  }
 
  getStore() {
    if (this.enabled) {
      const resource = executionAsyncResource();
      return resource[this.kResourceStore];
    }
  }
}
 
// Placing all exports down here because the exported classes won't export
// otherwise.
module.exports = {
  // Public API
  AsyncLocalStorage,
  createHook,
  executionAsyncId,
  triggerAsyncId,
  executionAsyncResource,
  asyncWrapProviders: ObjectFreeze({ __proto__: null, ...asyncWrap.Providers }),
  // Embedder API
  AsyncResource,
};