node/lib/internal/async_context_frame.js
Bryan English ef6b9ffc8d
async_hooks: add an InactiveAsyncContextFrame class
This gives a class prototype for AsyncContextFrame that contains the
required methods, so that when we swap the prototype,
ActiveAsyncContextFrame methods are used instead. Previously, the
methods were defined in AsyncContextFrame, so swapping the prototype
didn't swap those static methods.

Also, make the ActiveAsyncContextFrame extend from Map.

Fixes: https://github.com/nodejs/node/issues/54503
PR-URL: https://github.com/nodejs/node/pull/54510
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Mohammed Keyvanzadeh <mohammadkeyvanzade94@gmail.com>
Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de>
2024-08-30 20:27:28 +00:00

77 lines
1.5 KiB
JavaScript

'use strict';
const {
ObjectSetPrototypeOf,
} = primordials;
const {
getContinuationPreservedEmbedderData,
setContinuationPreservedEmbedderData,
} = internalBinding('async_context_frame');
let enabled_;
class ActiveAsyncContextFrame extends Map {
static get enabled() {
return true;
}
static current() {
return getContinuationPreservedEmbedderData();
}
static set(frame) {
setContinuationPreservedEmbedderData(frame);
}
static exchange(frame) {
const prior = this.current();
this.set(frame);
return prior;
}
static disable(store) {
const frame = this.current();
frame?.disable(store);
}
}
function checkEnabled() {
const enabled = require('internal/options')
.getOptionValue('--experimental-async-context-frame');
// If enabled, swap to active prototype so we don't need to check status
// on every interaction with the async context frame.
if (enabled) {
// eslint-disable-next-line no-use-before-define
ObjectSetPrototypeOf(AsyncContextFrame, ActiveAsyncContextFrame);
}
return enabled;
}
class InactiveAsyncContextFrame extends Map {
static get enabled() {
enabled_ ??= checkEnabled();
return enabled_;
}
static current() {}
static set(frame) {}
static exchange(frame) {}
static disable(store) {}
}
class AsyncContextFrame extends InactiveAsyncContextFrame {
constructor(store, data) {
super(AsyncContextFrame.current());
this.set(store, data);
}
disable(store) {
this.delete(store);
}
}
module.exports = AsyncContextFrame;