Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async_hooks: add hook to stop propagation #45386

Merged
merged 8 commits into from
Nov 15, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
21 changes: 20 additions & 1 deletion doc/api/async_context.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,17 +116,35 @@ Each instance of `AsyncLocalStorage` maintains an independent storage context.
Multiple instances can safely exist simultaneously without risk of interfering
with each other's data.

### `new AsyncLocalStorage()`
### `new AsyncLocalStorage([options])`

<!-- YAML
added:
- v13.10.0
- v12.17.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/45386
description: Add option onPropagateCb.
-->

> Stability: 1 - `options.onPropagateCb` is experimental.

* `options` {Object}
* `onPropagateCb` {Function} Optional callback invoked before a store is
Flarna marked this conversation as resolved.
Show resolved Hide resolved
propagated to a new async resource. Returning `true` allows propagation,
returning `false` avoids it. Default is to propagate always.

Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
`run()` call or after an `enterWith()` call.

The `onPropagateCb` is called during creation of an async resource. Throwing at
this time will print the stack trace and exit. See
[`async_hooks` Error handling][] for details.

Creating an async resource within the `onPropagate` callback will result in
a recursive call to `onPropagate`.

### `asyncLocalStorage.disable()`

<!-- YAML
Expand Down Expand Up @@ -816,4 +834,5 @@ const server = createServer((req, res) => {
[`EventEmitter`]: events.md#class-eventemitter
[`Stream`]: stream.md#stream
[`Worker`]: worker_threads.md#class-worker
[`async_hooks` Error handling]: async_hooks.md#error-handling
[`util.promisify()`]: util.md#utilpromisifyoriginal
25 changes: 21 additions & 4 deletions lib/async_hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const {
const {
ERR_ASYNC_CALLBACK,
ERR_ASYNC_TYPE,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ASYNC_ID
} = require('internal/errors').codes;
const { kEmptyObject } = require('internal/util');
Expand Down Expand Up @@ -268,15 +269,27 @@ const storageHook = createHook({
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);
storageList[i]._propagate(resource, currentResource, type);
}
}
});

class AsyncLocalStorage {
constructor() {
constructor(options = {}) {
Flarna marked this conversation as resolved.
Show resolved Hide resolved
if (typeof options !== 'object' || options === null) {
throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
}

const { onPropagateCb = null } = options;
if (onPropagateCb !== null && typeof onPropagateCb !== 'function') {
throw new ERR_INVALID_ARG_TYPE('options.onPropagateCb',
'function',
onPropagateCb);
}

this.kResourceStore = Symbol('kResourceStore');
this.enabled = false;
this._onPropagateCb = onPropagateCb;
}

disable() {
Expand All @@ -300,10 +313,14 @@ class AsyncLocalStorage {
}

// Propagate the context from a parent resource to a child one
_propagate(resource, triggerResource) {
_propagate(resource, triggerResource, type) {
const store = triggerResource[this.kResourceStore];
if (this.enabled) {
resource[this.kResourceStore] = store;
if (this._onPropagateCb === null || this._onPropagateCb(type, store)) {
resource[this.kResourceStore] = store;
} else {
resource[this.kResourceStore] = undefined;
Flarna marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

Expand Down
38 changes: 38 additions & 0 deletions test/async-hooks/test-async-local-storage-stop-propagation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const { AsyncLocalStorage, AsyncResource } = require('async_hooks');

let cnt = 0;
function onPropagate(type, store) {
assert.strictEqual(als.getStore(), store);
cnt++;
if (cnt === 1) {
assert.strictEqual(type, 'r1');
return true;
}
if (cnt === 2) {
assert.strictEqual(type, 'r2');
return false;
}
}

const als = new AsyncLocalStorage({
onPropagateCb: common.mustCall(onPropagate, 2)
});

const myStore = {};

als.run(myStore, common.mustCall(() => {
const r1 = new AsyncResource('r1');
const r2 = new AsyncResource('r2');
r1.runInAsyncScope(common.mustCall(() => {
assert.strictEqual(als.getStore(), myStore);
}));
r2.runInAsyncScope(common.mustCall(() => {
assert.strictEqual(als.getStore(), undefined);
r1.runInAsyncScope(common.mustCall(() => {
assert.strictEqual(als.getStore(), myStore);
}));
}));
}));