From 7cff1e14bab190bf7632f740e3985b4afd57f1ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gerhard=20St=C3=B6bich?= Date: Tue, 15 Nov 2022 13:27:03 +0100 Subject: [PATCH] async_hooks: add hook to stop propagation Add hook to AsyncLocalStorage to allow user to stop propagation. This is needed to avoid leaking a store if e.g. the store indicates that its operations are finished or it reached its time to live. PR-URL: https://github.com/nodejs/node/pull/45386 Reviewed-By: Stephen Belanger Reviewed-By: Minwoo Jung Reviewed-By: Chengzhong Wu --- doc/api/async_context.md | 21 +++++++- lib/async_hooks.js | 23 +++++++-- ...st-async-local-storage-stop-propagation.js | 50 +++++++++++++++++++ 3 files changed, 89 insertions(+), 5 deletions(-) create mode 100644 test/async-hooks/test-async-local-storage-stop-propagation.js diff --git a/doc/api/async_context.md b/doc/api/async_context.md index a41b73ce67697e..2d76d41392a525 100644 --- a/doc/api/async_context.md +++ b/doc/api/async_context.md @@ -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])` +> Stability: 1 - `options.onPropagate` is experimental. + +* `options` {Object} + * `onPropagate` {Function} Optional callback invoked before a store is + 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 `onPropagate` 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()`