Commit e5278b7

Browse files
mcollinaaduh95
authored andcommitted
timers: do not retain a reference to the async store after firing
After firing timers, we can clean them up by iterating over all active stores and setting the relevant symbols to undefined. Fixes#53408 Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #53443 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Paolo Insogna <paolo@cowtech.it> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Gerhard StΓΆbich <deb2001-github@yahoo.de>
1 parent a5ce44d commit e5278b7

5 files changed

Lines changed: 281 additions & 22 deletions

File tree

β€Žlib/internal/async_hooks.jsβ€Ž

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ const before_symbol = Symbol('before');
104104
constafter_symbol=Symbol('after');
105105
constdestroy_symbol=Symbol('destroy');
106106
constpromise_resolve_symbol=Symbol('promiseResolve');
107+
constasync_local_storage_context_symbol=Symbol('kAsyncLocalStorageContext');
107108
constemitBeforeNative=emitHookFactory(before_symbol,'emitBeforeNative');
108109
constemitAfterNative=emitHookFactory(after_symbol,'emitAfterNative');
109110
constemitDestroyNative=emitHookFactory(destroy_symbol,'emitDestroyNative');
@@ -594,7 +595,8 @@ module.exports = {
594595
symbols: {
595596
async_id_symbol, trigger_async_id_symbol,
596597
init_symbol, before_symbol, after_symbol, destroy_symbol,
597-
promise_resolve_symbol, owner_symbol,
598+
promise_resolve_symbol, async_local_storage_context_symbol,
599+
owner_symbol,
598600
},
599601
constants: {
600602
kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,

β€Žlib/internal/async_local_storage/async_hooks.jsβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ const {
1212
const{
1313
validateObject,
1414
}=require('internal/validators');
15+
const{
16+
symbols: {
17+
async_local_storage_context_symbol,
18+
},
19+
}=require('internal/async_hooks');
1520

1621
const{
1722
AsyncResource,
@@ -20,6 +25,11 @@ const {
2025
}=require('async_hooks');
2126

2227
conststorageList=[];
28+
29+
functiongetOrCreateResourceStore(resource){
30+
returnresource[async_local_storage_context_symbol]??={__proto__: null};
31+
}
32+
2333
conststorageHook=createHook({
2434
init(asyncId,type,triggerAsyncId,resource){
2535
constcurrentResource=executionAsyncResource();
@@ -88,16 +98,18 @@ class AsyncLocalStorage {
8898

8999
// Propagate the context from a parent resource to a child one
90100
_propagate(resource,triggerResource,type){
91-
conststore=triggerResource[this.kResourceStore];
101+
conststore=triggerResource[async_local_storage_context_symbol]?.[this.kResourceStore];
92102
if(this.enabled){
93-
resource[this.kResourceStore]=store;
103+
constresourceStore=getOrCreateResourceStore(resource);
104+
resourceStore[this.kResourceStore]=store;
94105
}
95106
}
96107

97108
enterWith(store){
98109
this._enable();
99110
constresource=executionAsyncResource();
100-
resource[this.kResourceStore]=store;
111+
constresourceStore=getOrCreateResourceStore(resource);
112+
resourceStore[this.kResourceStore]=store;
101113
}
102114

103115
run(store,callback, ...args){
@@ -109,14 +121,15 @@ class AsyncLocalStorage {
109121
this._enable();
110122

111123
constresource=executionAsyncResource();
112-
constoldStore=resource[this.kResourceStore];
124+
constresourceStore=getOrCreateResourceStore(resource);
125+
constoldStore=resourceStore[this.kResourceStore];
113126

114-
resource[this.kResourceStore]=store;
127+
resourceStore[this.kResourceStore]=store;
115128

116129
try{
117130
returnReflectApply(callback,null,args);
118131
}finally{
119-
resource[this.kResourceStore]=oldStore;
132+
resourceStore[this.kResourceStore]=oldStore;
120133
}
121134
}
122135

@@ -135,10 +148,11 @@ class AsyncLocalStorage {
135148
getStore(){
136149
if(this.enabled){
137150
constresource=executionAsyncResource();
138-
if(!(this.kResourceStoreinresource)){
151+
constresourceStore=resource[async_local_storage_context_symbol];
152+
if(resourceStore===undefined||!(this.kResourceStoreinresourceStore)){
139153
returnthis.#defaultValue;
140154
}
141-
returnresource[this.kResourceStore];
155+
returnresourceStore[this.kResourceStore];
142156
}
143157
returnthis.#defaultValue;
144158
}

β€Žlib/internal/timers.jsβ€Ž

Lines changed: 79 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@ const {
8787
immediateInfo,
8888
timeoutInfo,
8989
}=binding;
90+
const{
91+
enqueueMicrotask,
92+
}=internalBinding('task_queue');
9093

9194
const{
9295
getDefaultTriggerAsyncId,
@@ -97,6 +100,9 @@ const {
97100
emitBefore,
98101
emitAfter,
99102
emitDestroy,
103+
symbols: {
104+
async_local_storage_context_symbol,
105+
},
100106
}=require('internal/async_hooks');
101107

102108
// Symbols for storing async id state.
@@ -125,6 +131,39 @@ const AsyncContextFrame = require('internal/async_context_frame');
125131

126132
constasync_context_frame=Symbol('kAsyncContextFrame');
127133

134+
functionremoveStoresFromResource(resource){
135+
if(AsyncContextFrame.enabled){
136+
if(resource[async_context_frame]!==undefined){
137+
resource[async_context_frame]=undefined;
138+
}
139+
}elseif(resource[async_local_storage_context_symbol]!==undefined){
140+
resource[async_local_storage_context_symbol]=undefined;
141+
}
142+
}
143+
144+
functioncleanTimer(timer){
145+
removeStoresFromResource(timer);
146+
timer._onTimeout=undefined;
147+
timer._timerArgs=undefined;
148+
}
149+
150+
functioncleanImmediate(immediate){
151+
removeStoresFromResource(immediate);
152+
immediate._onImmediate=undefined;
153+
immediate._argv=undefined;
154+
}
155+
156+
functionenqueueRemoveStoresFromResource(resource){
157+
enqueueMicrotask(()=>removeStoresFromResource(resource));
158+
}
159+
160+
functionenqueueRemoveStoresIfNotReinserted(resource){
161+
enqueueMicrotask(()=>{
162+
if(!resource._idleNext&&!resource._idlePrev)
163+
removeStoresFromResource(resource);
164+
});
165+
}
166+
128167
// *Must* match Environment::ImmediateInfo::Fields in src/env.h.
129168
constkCount=0;
130169
constkRefCount=1;
@@ -528,14 +567,22 @@ function getTimerCallbacks(runNextTicks) {
528567
constasyncId=immediate[async_id_symbol];
529568
emitBefore(asyncId,immediate[trigger_async_id_symbol],immediate);
530569

570+
letthrew=true;
531571
try{
532572
constargv=immediate._argv;
533573
if(!argv)
534574
immediate._onImmediate();
535575
else
536576
immediate._onImmediate(...argv);
577+
threw=false;
537578
}finally{
538-
immediate._onImmediate=null;
579+
if(threw){
580+
immediate._onImmediate=undefined;
581+
immediate._argv=undefined;
582+
enqueueRemoveStoresFromResource(immediate);
583+
}else{
584+
cleanImmediate(immediate);
585+
}
539586

540587
emitDestroy(asyncId);
541588

@@ -607,6 +654,8 @@ function getTimerCallbacks(runNextTicks) {
607654
if(!timer._destroyed){
608655
timer._destroyed=true;
609656

657+
cleanTimer(timer);
658+
610659
if(timer[kHasPrimitive])
611660
deleteknownTimersById[asyncId];
612661

@@ -629,26 +678,42 @@ function getTimerCallbacks(runNextTicks) {
629678
start=binding.getLibuvNow();
630679
}
631680

681+
letthrew=true;
632682
try{
633683
constargs=timer._timerArgs;
634684
if(args===undefined)
635685
timer._onTimeout();
636686
else
637687
ReflectApply(timer._onTimeout,timer,args);
688+
threw=false;
638689
}finally{
639690
if(timer._repeat&&timer._idleTimeout!==-1){
640691
timer._idleTimeout=timer._repeat;
641692
insert(timer,timer._idleTimeout,start);
642-
}elseif(!timer._idleNext&&!timer._idlePrev&&!timer._destroyed){
643-
timer._destroyed=true;
644-
645-
if(timer[kHasPrimitive])
646-
deleteknownTimersById[asyncId];
647-
648-
if(timer[kRefed])
649-
timeoutInfo[0]--;
650-
651-
emitDestroy(asyncId);
693+
}elseif(!timer._idleNext&&!timer._idlePrev){
694+
if(timer._destroyed){
695+
timer._onTimeout=undefined;
696+
timer._timerArgs=undefined;
697+
if(threw)
698+
enqueueRemoveStoresIfNotReinserted(timer);
699+
else
700+
removeStoresFromResource(timer);
701+
}else{
702+
if(threw)
703+
enqueueRemoveStoresIfNotReinserted(timer);
704+
else
705+
removeStoresFromResource(timer);
706+
707+
timer._destroyed=true;
708+
709+
if(timer[kHasPrimitive])
710+
deleteknownTimersById[asyncId];
711+
712+
if(timer[kRefed])
713+
timeoutInfo[0]--;
714+
715+
emitDestroy(asyncId);
716+
}
652717
}
653718
}
654719

@@ -728,8 +793,11 @@ module.exports = {
728793
kTimeout: Symbol('timeout'),// For hiding Timeouts on other internals.
729794
async_id_symbol,
730795
trigger_async_id_symbol,
796+
async_context_frame,
731797
Timeout,
732798
Immediate,
799+
cleanImmediate,
800+
cleanTimer,
733801
kRefed,
734802
kHasPrimitive,
735803
initAsyncResource,

β€Žlib/timers.jsβ€Ž

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ const {
3838
async_id_symbol,
3939
Timeout,
4040
Immediate,
41+
cleanTimer,
42+
cleanImmediate,
4143
decRefCount,
4244
immediateInfoFields: {
4345
kCount,
@@ -69,9 +71,12 @@ const {
6971

7072
// Remove a timer. Cancels the timeout and resets the relevant timer properties.
7173
functionunenroll(item){
72-
if(item._destroyed)
74+
if(item._destroyed){
75+
cleanTimer(item);
7376
return;
77+
}
7478

79+
constwasEnrolled=item._idleNext!==null||item._idlePrev!==null;
7580
item._destroyed=true;
7681

7782
if(item[kHasPrimitive])
@@ -99,6 +104,9 @@ function unenroll(item) {
99104
decRefCount();
100105
}
101106

107+
if(wasEnrolled)
108+
cleanTimer(item);
109+
102110
// If active is called later, then we want to make sure not to insert again
103111
item._idleTimeout=-1;
104112
}
@@ -238,7 +246,7 @@ function clearImmediate(immediate) {
238246

239247
emitDestroy(immediate[async_id_symbol]);
240248

241-
immediate._onImmediate=null;
249+
cleanImmediate(immediate);
242250

243251
immediateQueue.remove(immediate);
244252
}

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit e5278b7

Browse files
mcollinaaduh95
authored andcommitted
timers: do not retain a reference to the async store after firing
After firing timers, we can clean them up by iterating over all active stores and setting the relevant symbols to undefined. Fixes#53408 Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #53443 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Paolo Insogna <paolo@cowtech.it> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Gerhard StΓΆbich <deb2001-github@yahoo.de>
1 parent a5ce44d commit e5278b7

5 files changed

Lines changed: 281 additions & 22 deletions

File tree

β€Žlib/internal/async_hooks.jsβ€Ž

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ const before_symbol = Symbol('before');
104104
constafter_symbol=Symbol('after');
105105
constdestroy_symbol=Symbol('destroy');
106106
constpromise_resolve_symbol=Symbol('promiseResolve');
107+
constasync_local_storage_context_symbol=Symbol('kAsyncLocalStorageContext');
107108
constemitBeforeNative=emitHookFactory(before_symbol,'emitBeforeNative');
108109
constemitAfterNative=emitHookFactory(after_symbol,'emitAfterNative');
109110
constemitDestroyNative=emitHookFactory(destroy_symbol,'emitDestroyNative');
@@ -594,7 +595,8 @@ module.exports = {
594595
symbols: {
595596
async_id_symbol, trigger_async_id_symbol,
596597
init_symbol, before_symbol, after_symbol, destroy_symbol,
597-
promise_resolve_symbol, owner_symbol,
598+
promise_resolve_symbol, async_local_storage_context_symbol,
599+
owner_symbol,
598600
},
599601
constants: {
600602
kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,

β€Žlib/internal/async_local_storage/async_hooks.jsβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ const {
1212
const{
1313
validateObject,
1414
}=require('internal/validators');
15+
const{
16+
symbols: {
17+
async_local_storage_context_symbol,
18+
},
19+
}=require('internal/async_hooks');
1520

1621
const{
1722
AsyncResource,
@@ -20,6 +25,11 @@ const {
2025
}=require('async_hooks');
2126

2227
conststorageList=[];
28+
29+
functiongetOrCreateResourceStore(resource){
30+
returnresource[async_local_storage_context_symbol]??={__proto__: null};
31+
}
32+
2333
conststorageHook=createHook({
2434
init(asyncId,type,triggerAsyncId,resource){
2535
constcurrentResource=executionAsyncResource();
@@ -88,16 +98,18 @@ class AsyncLocalStorage {
8898

8999
// Propagate the context from a parent resource to a child one
90100
_propagate(resource,triggerResource,type){
91-
conststore=triggerResource[this.kResourceStore];
101+
conststore=triggerResource[async_local_storage_context_symbol]?.[this.kResourceStore];
92102
if(this.enabled){
93-
resource[this.kResourceStore]=store;
103+
constresourceStore=getOrCreateResourceStore(resource);
104+
resourceStore[this.kResourceStore]=store;
94105
}
95106
}
96107

97108
enterWith(store){
98109
this._enable();
99110
constresource=executionAsyncResource();
100-
resource[this.kResourceStore]=store;
111+
constresourceStore=getOrCreateResourceStore(resource);
112+
resourceStore[this.kResourceStore]=store;
101113
}
102114

103115
run(store,callback, ...args){
@@ -109,14 +121,15 @@ class AsyncLocalStorage {
109121
this._enable();
110122

111123
constresource=executionAsyncResource();
112-
constoldStore=resource[this.kResourceStore];
124+
constresourceStore=getOrCreateResourceStore(resource);
125+
constoldStore=resourceStore[this.kResourceStore];
113126

114-
resource[this.kResourceStore]=store;
127+
resourceStore[this.kResourceStore]=store;
115128

116129
try{
117130
returnReflectApply(callback,null,args);
118131
}finally{
119-
resource[this.kResourceStore]=oldStore;
132+
resourceStore[this.kResourceStore]=oldStore;
120133
}
121134
}
122135

@@ -135,10 +148,11 @@ class AsyncLocalStorage {
135148
getStore(){
136149
if(this.enabled){
137150
constresource=executionAsyncResource();
138-
if(!(this.kResourceStoreinresource)){
151+
constresourceStore=resource[async_local_storage_context_symbol];
152+
if(resourceStore===undefined||!(this.kResourceStoreinresourceStore)){
139153
returnthis.#defaultValue;
140154
}
141-
returnresource[this.kResourceStore];
155+
returnresourceStore[this.kResourceStore];
142156
}
143157
returnthis.#defaultValue;
144158
}

β€Žlib/internal/timers.jsβ€Ž

Lines changed: 79 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@ const {
8787
immediateInfo,
8888
timeoutInfo,
8989
}=binding;
90+
const{
91+
enqueueMicrotask,
92+
}=internalBinding('task_queue');
9093

9194
const{
9295
getDefaultTriggerAsyncId,
@@ -97,6 +100,9 @@ const {
97100
emitBefore,
98101
emitAfter,
99102
emitDestroy,
103+
symbols: {
104+
async_local_storage_context_symbol,
105+
},
100106
}=require('internal/async_hooks');
101107

102108
// Symbols for storing async id state.
@@ -125,6 +131,39 @@ const AsyncContextFrame = require('internal/async_context_frame');
125131

126132
constasync_context_frame=Symbol('kAsyncContextFrame');
127133

134+
functionremoveStoresFromResource(resource){
135+
if(AsyncContextFrame.enabled){
136+
if(resource[async_context_frame]!==undefined){
137+
resource[async_context_frame]=undefined;
138+
}
139+
}elseif(resource[async_local_storage_context_symbol]!==undefined){
140+
resource[async_local_storage_context_symbol]=undefined;
141+
}
142+
}
143+
144+
functioncleanTimer(timer){
145+
removeStoresFromResource(timer);
146+
timer._onTimeout=undefined;
147+
timer._timerArgs=undefined;
148+
}
149+
150+
functioncleanImmediate(immediate){
151+
removeStoresFromResource(immediate);
152+
immediate._onImmediate=undefined;
153+
immediate._argv=undefined;
154+
}
155+
156+
functionenqueueRemoveStoresFromResource(resource){
157+
enqueueMicrotask(()=>removeStoresFromResource(resource));
158+
}
159+
160+
functionenqueueRemoveStoresIfNotReinserted(resource){
161+
enqueueMicrotask(()=>{
162+
if(!resource._idleNext&&!resource._idlePrev)
163+
removeStoresFromResource(resource);
164+
});
165+
}
166+
128167
// *Must* match Environment::ImmediateInfo::Fields in src/env.h.
129168
constkCount=0;
130169
constkRefCount=1;
@@ -528,14 +567,22 @@ function getTimerCallbacks(runNextTicks) {
528567
constasyncId=immediate[async_id_symbol];
529568
emitBefore(asyncId,immediate[trigger_async_id_symbol],immediate);
530569

570+
letthrew=true;
531571
try{
532572
constargv=immediate._argv;
533573
if(!argv)
534574
immediate._onImmediate();
535575
else
536576
immediate._onImmediate(...argv);
577+
threw=false;
537578
}finally{
538-
immediate._onImmediate=null;
579+
if(threw){
580+
immediate._onImmediate=undefined;
581+
immediate._argv=undefined;
582+
enqueueRemoveStoresFromResource(immediate);
583+
}else{
584+
cleanImmediate(immediate);
585+
}
539586

540587
emitDestroy(asyncId);
541588

@@ -607,6 +654,8 @@ function getTimerCallbacks(runNextTicks) {
607654
if(!timer._destroyed){
608655
timer._destroyed=true;
609656

657+
cleanTimer(timer);
658+
610659
if(timer[kHasPrimitive])
611660
deleteknownTimersById[asyncId];
612661

@@ -629,26 +678,42 @@ function getTimerCallbacks(runNextTicks) {
629678
start=binding.getLibuvNow();
630679
}
631680

681+
letthrew=true;
632682
try{
633683
constargs=timer._timerArgs;
634684
if(args===undefined)
635685
timer._onTimeout();
636686
else
637687
ReflectApply(timer._onTimeout,timer,args);
688+
threw=false;
638689
}finally{
639690
if(timer._repeat&&timer._idleTimeout!==-1){
640691
timer._idleTimeout=timer._repeat;
641692
insert(timer,timer._idleTimeout,start);
642-
}elseif(!timer._idleNext&&!timer._idlePrev&&!timer._destroyed){
643-
timer._destroyed=true;
644-
645-
if(timer[kHasPrimitive])
646-
deleteknownTimersById[asyncId];
647-
648-
if(timer[kRefed])
649-
timeoutInfo[0]--;
650-
651-
emitDestroy(asyncId);
693+
}elseif(!timer._idleNext&&!timer._idlePrev){
694+
if(timer._destroyed){
695+
timer._onTimeout=undefined;
696+
timer._timerArgs=undefined;
697+
if(threw)
698+
enqueueRemoveStoresIfNotReinserted(timer);
699+
else
700+
removeStoresFromResource(timer);
701+
}else{
702+
if(threw)
703+
enqueueRemoveStoresIfNotReinserted(timer);
704+
else
705+
removeStoresFromResource(timer);
706+
707+
timer._destroyed=true;
708+
709+
if(timer[kHasPrimitive])
710+
deleteknownTimersById[asyncId];
711+
712+
if(timer[kRefed])
713+
timeoutInfo[0]--;
714+
715+
emitDestroy(asyncId);
716+
}
652717
}
653718
}
654719

@@ -728,8 +793,11 @@ module.exports = {
728793
kTimeout: Symbol('timeout'),// For hiding Timeouts on other internals.
729794
async_id_symbol,
730795
trigger_async_id_symbol,
796+
async_context_frame,
731797
Timeout,
732798
Immediate,
799+
cleanImmediate,
800+
cleanTimer,
733801
kRefed,
734802
kHasPrimitive,
735803
initAsyncResource,

β€Žlib/timers.jsβ€Ž

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ const {
3838
async_id_symbol,
3939
Timeout,
4040
Immediate,
41+
cleanTimer,
42+
cleanImmediate,
4143
decRefCount,
4244
immediateInfoFields: {
4345
kCount,
@@ -69,9 +71,12 @@ const {
6971

7072
// Remove a timer. Cancels the timeout and resets the relevant timer properties.
7173
functionunenroll(item){
72-
if(item._destroyed)
74+
if(item._destroyed){
75+
cleanTimer(item);
7376
return;
77+
}
7478

79+
constwasEnrolled=item._idleNext!==null||item._idlePrev!==null;
7580
item._destroyed=true;
7681

7782
if(item[kHasPrimitive])
@@ -99,6 +104,9 @@ function unenroll(item) {
99104
decRefCount();
100105
}
101106

107+
if(wasEnrolled)
108+
cleanTimer(item);
109+
102110
// If active is called later, then we want to make sure not to insert again
103111
item._idleTimeout=-1;
104112
}
@@ -238,7 +246,7 @@ function clearImmediate(immediate) {
238246

239247
emitDestroy(immediate[async_id_symbol]);
240248

241-
immediate._onImmediate=null;
249+
cleanImmediate(immediate);
242250

243251
immediateQueue.remove(immediate);
244252
}

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit e5278b7

Browse files
mcollinaaduh95
authored andcommitted
timers: do not retain a reference to the async store after firing
After firing timers, we can clean them up by iterating over all active stores and setting the relevant symbols to undefined. Fixes#53408 Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #53443 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Paolo Insogna <paolo@cowtech.it> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Gerhard StΓΆbich <deb2001-github@yahoo.de>
1 parent a5ce44d commit e5278b7

5 files changed

Lines changed: 281 additions & 22 deletions

File tree

β€Žlib/internal/async_hooks.jsβ€Ž

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ const before_symbol = Symbol('before');
104104
constafter_symbol=Symbol('after');
105105
constdestroy_symbol=Symbol('destroy');
106106
constpromise_resolve_symbol=Symbol('promiseResolve');
107+
constasync_local_storage_context_symbol=Symbol('kAsyncLocalStorageContext');
107108
constemitBeforeNative=emitHookFactory(before_symbol,'emitBeforeNative');
108109
constemitAfterNative=emitHookFactory(after_symbol,'emitAfterNative');
109110
constemitDestroyNative=emitHookFactory(destroy_symbol,'emitDestroyNative');
@@ -594,7 +595,8 @@ module.exports = {
594595
symbols: {
595596
async_id_symbol, trigger_async_id_symbol,
596597
init_symbol, before_symbol, after_symbol, destroy_symbol,
597-
promise_resolve_symbol, owner_symbol,
598+
promise_resolve_symbol, async_local_storage_context_symbol,
599+
owner_symbol,
598600
},
599601
constants: {
600602
kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,

β€Žlib/internal/async_local_storage/async_hooks.jsβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ const {
1212
const{
1313
validateObject,
1414
}=require('internal/validators');
15+
const{
16+
symbols: {
17+
async_local_storage_context_symbol,
18+
},
19+
}=require('internal/async_hooks');
1520

1621
const{
1722
AsyncResource,
@@ -20,6 +25,11 @@ const {
2025
}=require('async_hooks');
2126

2227
conststorageList=[];
28+
29+
functiongetOrCreateResourceStore(resource){
30+
returnresource[async_local_storage_context_symbol]??={__proto__: null};
31+
}
32+
2333
conststorageHook=createHook({
2434
init(asyncId,type,triggerAsyncId,resource){
2535
constcurrentResource=executionAsyncResource();
@@ -88,16 +98,18 @@ class AsyncLocalStorage {
8898

8999
// Propagate the context from a parent resource to a child one
90100
_propagate(resource,triggerResource,type){
91-
conststore=triggerResource[this.kResourceStore];
101+
conststore=triggerResource[async_local_storage_context_symbol]?.[this.kResourceStore];
92102
if(this.enabled){
93-
resource[this.kResourceStore]=store;
103+
constresourceStore=getOrCreateResourceStore(resource);
104+
resourceStore[this.kResourceStore]=store;
94105
}
95106
}
96107

97108
enterWith(store){
98109
this._enable();
99110
constresource=executionAsyncResource();
100-
resource[this.kResourceStore]=store;
111+
constresourceStore=getOrCreateResourceStore(resource);
112+
resourceStore[this.kResourceStore]=store;
101113
}
102114

103115
run(store,callback, ...args){
@@ -109,14 +121,15 @@ class AsyncLocalStorage {
109121
this._enable();
110122

111123
constresource=executionAsyncResource();
112-
constoldStore=resource[this.kResourceStore];
124+
constresourceStore=getOrCreateResourceStore(resource);
125+
constoldStore=resourceStore[this.kResourceStore];
113126

114-
resource[this.kResourceStore]=store;
127+
resourceStore[this.kResourceStore]=store;
115128

116129
try{
117130
returnReflectApply(callback,null,args);
118131
}finally{
119-
resource[this.kResourceStore]=oldStore;
132+
resourceStore[this.kResourceStore]=oldStore;
120133
}
121134
}
122135

@@ -135,10 +148,11 @@ class AsyncLocalStorage {
135148
getStore(){
136149
if(this.enabled){
137150
constresource=executionAsyncResource();
138-
if(!(this.kResourceStoreinresource)){
151+
constresourceStore=resource[async_local_storage_context_symbol];
152+
if(resourceStore===undefined||!(this.kResourceStoreinresourceStore)){
139153
returnthis.#defaultValue;
140154
}
141-
returnresource[this.kResourceStore];
155+
returnresourceStore[this.kResourceStore];
142156
}
143157
returnthis.#defaultValue;
144158
}

β€Žlib/internal/timers.jsβ€Ž

Lines changed: 79 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@ const {
8787
immediateInfo,
8888
timeoutInfo,
8989
}=binding;
90+
const{
91+
enqueueMicrotask,
92+
}=internalBinding('task_queue');
9093

9194
const{
9295
getDefaultTriggerAsyncId,
@@ -97,6 +100,9 @@ const {
97100
emitBefore,
98101
emitAfter,
99102
emitDestroy,
103+
symbols: {
104+
async_local_storage_context_symbol,
105+
},
100106
}=require('internal/async_hooks');
101107

102108
// Symbols for storing async id state.
@@ -125,6 +131,39 @@ const AsyncContextFrame = require('internal/async_context_frame');
125131

126132
constasync_context_frame=Symbol('kAsyncContextFrame');
127133

134+
functionremoveStoresFromResource(resource){
135+
if(AsyncContextFrame.enabled){
136+
if(resource[async_context_frame]!==undefined){
137+
resource[async_context_frame]=undefined;
138+
}
139+
}elseif(resource[async_local_storage_context_symbol]!==undefined){
140+
resource[async_local_storage_context_symbol]=undefined;
141+
}
142+
}
143+
144+
functioncleanTimer(timer){
145+
removeStoresFromResource(timer);
146+
timer._onTimeout=undefined;
147+
timer._timerArgs=undefined;
148+
}
149+
150+
functioncleanImmediate(immediate){
151+
removeStoresFromResource(immediate);
152+
immediate._onImmediate=undefined;
153+
immediate._argv=undefined;
154+
}
155+
156+
functionenqueueRemoveStoresFromResource(resource){
157+
enqueueMicrotask(()=>removeStoresFromResource(resource));
158+
}
159+
160+
functionenqueueRemoveStoresIfNotReinserted(resource){
161+
enqueueMicrotask(()=>{
162+
if(!resource._idleNext&&!resource._idlePrev)
163+
removeStoresFromResource(resource);
164+
});
165+
}
166+
128167
// *Must* match Environment::ImmediateInfo::Fields in src/env.h.
129168
constkCount=0;
130169
constkRefCount=1;
@@ -528,14 +567,22 @@ function getTimerCallbacks(runNextTicks) {
528567
constasyncId=immediate[async_id_symbol];
529568
emitBefore(asyncId,immediate[trigger_async_id_symbol],immediate);
530569

570+
letthrew=true;
531571
try{
532572
constargv=immediate._argv;
533573
if(!argv)
534574
immediate._onImmediate();
535575
else
536576
immediate._onImmediate(...argv);
577+
threw=false;
537578
}finally{
538-
immediate._onImmediate=null;
579+
if(threw){
580+
immediate._onImmediate=undefined;
581+
immediate._argv=undefined;
582+
enqueueRemoveStoresFromResource(immediate);
583+
}else{
584+
cleanImmediate(immediate);
585+
}
539586

540587
emitDestroy(asyncId);
541588

@@ -607,6 +654,8 @@ function getTimerCallbacks(runNextTicks) {
607654
if(!timer._destroyed){
608655
timer._destroyed=true;
609656

657+
cleanTimer(timer);
658+
610659
if(timer[kHasPrimitive])
611660
deleteknownTimersById[asyncId];
612661

@@ -629,26 +678,42 @@ function getTimerCallbacks(runNextTicks) {
629678
start=binding.getLibuvNow();
630679
}
631680

681+
letthrew=true;
632682
try{
633683
constargs=timer._timerArgs;
634684
if(args===undefined)
635685
timer._onTimeout();
636686
else
637687
ReflectApply(timer._onTimeout,timer,args);
688+
threw=false;
638689
}finally{
639690
if(timer._repeat&&timer._idleTimeout!==-1){
640691
timer._idleTimeout=timer._repeat;
641692
insert(timer,timer._idleTimeout,start);
642-
}elseif(!timer._idleNext&&!timer._idlePrev&&!timer._destroyed){
643-
timer._destroyed=true;
644-
645-
if(timer[kHasPrimitive])
646-
deleteknownTimersById[asyncId];
647-
648-
if(timer[kRefed])
649-
timeoutInfo[0]--;
650-
651-
emitDestroy(asyncId);
693+
}elseif(!timer._idleNext&&!timer._idlePrev){
694+
if(timer._destroyed){
695+
timer._onTimeout=undefined;
696+
timer._timerArgs=undefined;
697+
if(threw)
698+
enqueueRemoveStoresIfNotReinserted(timer);
699+
else
700+
removeStoresFromResource(timer);
701+
}else{
702+
if(threw)
703+
enqueueRemoveStoresIfNotReinserted(timer);
704+
else
705+
removeStoresFromResource(timer);
706+
707+
timer._destroyed=true;
708+
709+
if(timer[kHasPrimitive])
710+
deleteknownTimersById[asyncId];
711+
712+
if(timer[kRefed])
713+
timeoutInfo[0]--;
714+
715+
emitDestroy(asyncId);
716+
}
652717
}
653718
}
654719

@@ -728,8 +793,11 @@ module.exports = {
728793
kTimeout: Symbol('timeout'),// For hiding Timeouts on other internals.
729794
async_id_symbol,
730795
trigger_async_id_symbol,
796+
async_context_frame,
731797
Timeout,
732798
Immediate,
799+
cleanImmediate,
800+
cleanTimer,
733801
kRefed,
734802
kHasPrimitive,
735803
initAsyncResource,

β€Žlib/timers.jsβ€Ž

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ const {
3838
async_id_symbol,
3939
Timeout,
4040
Immediate,
41+
cleanTimer,
42+
cleanImmediate,
4143
decRefCount,
4244
immediateInfoFields: {
4345
kCount,
@@ -69,9 +71,12 @@ const {
6971

7072
// Remove a timer. Cancels the timeout and resets the relevant timer properties.
7173
functionunenroll(item){
72-
if(item._destroyed)
74+
if(item._destroyed){
75+
cleanTimer(item);
7376
return;
77+
}
7478

79+
constwasEnrolled=item._idleNext!==null||item._idlePrev!==null;
7580
item._destroyed=true;
7681

7782
if(item[kHasPrimitive])
@@ -99,6 +104,9 @@ function unenroll(item) {
99104
decRefCount();
100105
}
101106

107+
if(wasEnrolled)
108+
cleanTimer(item);
109+
102110
// If active is called later, then we want to make sure not to insert again
103111
item._idleTimeout=-1;
104112
}
@@ -238,7 +246,7 @@ function clearImmediate(immediate) {
238246

239247
emitDestroy(immediate[async_id_symbol]);
240248

241-
immediate._onImmediate=null;
249+
cleanImmediate(immediate);
242250

243251
immediateQueue.remove(immediate);
244252
}

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit e5278b7

Browse files
mcollinaaduh95
authored andcommitted
timers: do not retain a reference to the async store after firing
After firing timers, we can clean them up by iterating over all active stores and setting the relevant symbols to undefined. Fixes#53408 Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #53443 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Paolo Insogna <paolo@cowtech.it> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Gerhard StΓΆbich <deb2001-github@yahoo.de>
1 parent a5ce44d commit e5278b7

5 files changed

Lines changed: 281 additions & 22 deletions

File tree

β€Žlib/internal/async_hooks.jsβ€Ž

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ const before_symbol = Symbol('before');
104104
constafter_symbol=Symbol('after');
105105
constdestroy_symbol=Symbol('destroy');
106106
constpromise_resolve_symbol=Symbol('promiseResolve');
107+
constasync_local_storage_context_symbol=Symbol('kAsyncLocalStorageContext');
107108
constemitBeforeNative=emitHookFactory(before_symbol,'emitBeforeNative');
108109
constemitAfterNative=emitHookFactory(after_symbol,'emitAfterNative');
109110
constemitDestroyNative=emitHookFactory(destroy_symbol,'emitDestroyNative');
@@ -594,7 +595,8 @@ module.exports = {
594595
symbols: {
595596
async_id_symbol, trigger_async_id_symbol,
596597
init_symbol, before_symbol, after_symbol, destroy_symbol,
597-
promise_resolve_symbol, owner_symbol,
598+
promise_resolve_symbol, async_local_storage_context_symbol,
599+
owner_symbol,
598600
},
599601
constants: {
600602
kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,

β€Žlib/internal/async_local_storage/async_hooks.jsβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ const {
1212
const{
1313
validateObject,
1414
}=require('internal/validators');
15+
const{
16+
symbols: {
17+
async_local_storage_context_symbol,
18+
},
19+
}=require('internal/async_hooks');
1520

1621
const{
1722
AsyncResource,
@@ -20,6 +25,11 @@ const {
2025
}=require('async_hooks');
2126

2227
conststorageList=[];
28+
29+
functiongetOrCreateResourceStore(resource){
30+
returnresource[async_local_storage_context_symbol]??={__proto__: null};
31+
}
32+
2333
conststorageHook=createHook({
2434
init(asyncId,type,triggerAsyncId,resource){
2535
constcurrentResource=executionAsyncResource();
@@ -88,16 +98,18 @@ class AsyncLocalStorage {
8898

8999
// Propagate the context from a parent resource to a child one
90100
_propagate(resource,triggerResource,type){
91-
conststore=triggerResource[this.kResourceStore];
101+
conststore=triggerResource[async_local_storage_context_symbol]?.[this.kResourceStore];
92102
if(this.enabled){
93-
resource[this.kResourceStore]=store;
103+
constresourceStore=getOrCreateResourceStore(resource);
104+
resourceStore[this.kResourceStore]=store;
94105
}
95106
}
96107

97108
enterWith(store){
98109
this._enable();
99110
constresource=executionAsyncResource();
100-
resource[this.kResourceStore]=store;
111+
constresourceStore=getOrCreateResourceStore(resource);
112+
resourceStore[this.kResourceStore]=store;
101113
}
102114

103115
run(store,callback, ...args){
@@ -109,14 +121,15 @@ class AsyncLocalStorage {
109121
this._enable();
110122

111123
constresource=executionAsyncResource();
112-
constoldStore=resource[this.kResourceStore];
124+
constresourceStore=getOrCreateResourceStore(resource);
125+
constoldStore=resourceStore[this.kResourceStore];
113126

114-
resource[this.kResourceStore]=store;
127+
resourceStore[this.kResourceStore]=store;
115128

116129
try{
117130
returnReflectApply(callback,null,args);
118131
}finally{
119-
resource[this.kResourceStore]=oldStore;
132+
resourceStore[this.kResourceStore]=oldStore;
120133
}
121134
}
122135

@@ -135,10 +148,11 @@ class AsyncLocalStorage {
135148
getStore(){
136149
if(this.enabled){
137150
constresource=executionAsyncResource();
138-
if(!(this.kResourceStoreinresource)){
151+
constresourceStore=resource[async_local_storage_context_symbol];
152+
if(resourceStore===undefined||!(this.kResourceStoreinresourceStore)){
139153
returnthis.#defaultValue;
140154
}
141-
returnresource[this.kResourceStore];
155+
returnresourceStore[this.kResourceStore];
142156
}
143157
returnthis.#defaultValue;
144158
}

β€Žlib/internal/timers.jsβ€Ž

Lines changed: 79 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@ const {
8787
immediateInfo,
8888
timeoutInfo,
8989
}=binding;
90+
const{
91+
enqueueMicrotask,
92+
}=internalBinding('task_queue');
9093

9194
const{
9295
getDefaultTriggerAsyncId,
@@ -97,6 +100,9 @@ const {
97100
emitBefore,
98101
emitAfter,
99102
emitDestroy,
103+
symbols: {
104+
async_local_storage_context_symbol,
105+
},
100106
}=require('internal/async_hooks');
101107

102108
// Symbols for storing async id state.
@@ -125,6 +131,39 @@ const AsyncContextFrame = require('internal/async_context_frame');
125131

126132
constasync_context_frame=Symbol('kAsyncContextFrame');
127133

134+
functionremoveStoresFromResource(resource){
135+
if(AsyncContextFrame.enabled){
136+
if(resource[async_context_frame]!==undefined){
137+
resource[async_context_frame]=undefined;
138+
}
139+
}elseif(resource[async_local_storage_context_symbol]!==undefined){
140+
resource[async_local_storage_context_symbol]=undefined;
141+
}
142+
}
143+
144+
functioncleanTimer(timer){
145+
removeStoresFromResource(timer);
146+
timer._onTimeout=undefined;
147+
timer._timerArgs=undefined;
148+
}
149+
150+
functioncleanImmediate(immediate){
151+
removeStoresFromResource(immediate);
152+
immediate._onImmediate=undefined;
153+
immediate._argv=undefined;
154+
}
155+
156+
functionenqueueRemoveStoresFromResource(resource){
157+
enqueueMicrotask(()=>removeStoresFromResource(resource));
158+
}
159+
160+
functionenqueueRemoveStoresIfNotReinserted(resource){
161+
enqueueMicrotask(()=>{
162+
if(!resource._idleNext&&!resource._idlePrev)
163+
removeStoresFromResource(resource);
164+
});
165+
}
166+
128167
// *Must* match Environment::ImmediateInfo::Fields in src/env.h.
129168
constkCount=0;
130169
constkRefCount=1;
@@ -528,14 +567,22 @@ function getTimerCallbacks(runNextTicks) {
528567
constasyncId=immediate[async_id_symbol];
529568
emitBefore(asyncId,immediate[trigger_async_id_symbol],immediate);
530569

570+
letthrew=true;
531571
try{
532572
constargv=immediate._argv;
533573
if(!argv)
534574
immediate._onImmediate();
535575
else
536576
immediate._onImmediate(...argv);
577+
threw=false;
537578
}finally{
538-
immediate._onImmediate=null;
579+
if(threw){
580+
immediate._onImmediate=undefined;
581+
immediate._argv=undefined;
582+
enqueueRemoveStoresFromResource(immediate);
583+
}else{
584+
cleanImmediate(immediate);
585+
}
539586

540587
emitDestroy(asyncId);
541588

@@ -607,6 +654,8 @@ function getTimerCallbacks(runNextTicks) {
607654
if(!timer._destroyed){
608655
timer._destroyed=true;
609656

657+
cleanTimer(timer);
658+
610659
if(timer[kHasPrimitive])
611660
deleteknownTimersById[asyncId];
612661

@@ -629,26 +678,42 @@ function getTimerCallbacks(runNextTicks) {
629678
start=binding.getLibuvNow();
630679
}
631680

681+
letthrew=true;
632682
try{
633683
constargs=timer._timerArgs;
634684
if(args===undefined)
635685
timer._onTimeout();
636686
else
637687
ReflectApply(timer._onTimeout,timer,args);
688+
threw=false;
638689
}finally{
639690
if(timer._repeat&&timer._idleTimeout!==-1){
640691
timer._idleTimeout=timer._repeat;
641692
insert(timer,timer._idleTimeout,start);
642-
}elseif(!timer._idleNext&&!timer._idlePrev&&!timer._destroyed){
643-
timer._destroyed=true;
644-
645-
if(timer[kHasPrimitive])
646-
deleteknownTimersById[asyncId];
647-
648-
if(timer[kRefed])
649-
timeoutInfo[0]--;
650-
651-
emitDestroy(asyncId);
693+
}elseif(!timer._idleNext&&!timer._idlePrev){
694+
if(timer._destroyed){
695+
timer._onTimeout=undefined;
696+
timer._timerArgs=undefined;
697+
if(threw)
698+
enqueueRemoveStoresIfNotReinserted(timer);
699+
else
700+
removeStoresFromResource(timer);
701+
}else{
702+
if(threw)
703+
enqueueRemoveStoresIfNotReinserted(timer);
704+
else
705+
removeStoresFromResource(timer);
706+
707+
timer._destroyed=true;
708+
709+
if(timer[kHasPrimitive])
710+
deleteknownTimersById[asyncId];
711+
712+
if(timer[kRefed])
713+
timeoutInfo[0]--;
714+
715+
emitDestroy(asyncId);
716+
}
652717
}
653718
}
654719

@@ -728,8 +793,11 @@ module.exports = {
728793
kTimeout: Symbol('timeout'),// For hiding Timeouts on other internals.
729794
async_id_symbol,
730795
trigger_async_id_symbol,
796+
async_context_frame,
731797
Timeout,
732798
Immediate,
799+
cleanImmediate,
800+
cleanTimer,
733801
kRefed,
734802
kHasPrimitive,
735803
initAsyncResource,

β€Žlib/timers.jsβ€Ž

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ const {
3838
async_id_symbol,
3939
Timeout,
4040
Immediate,
41+
cleanTimer,
42+
cleanImmediate,
4143
decRefCount,
4244
immediateInfoFields: {
4345
kCount,
@@ -69,9 +71,12 @@ const {
6971

7072
// Remove a timer. Cancels the timeout and resets the relevant timer properties.
7173
functionunenroll(item){
72-
if(item._destroyed)
74+
if(item._destroyed){
75+
cleanTimer(item);
7376
return;
77+
}
7478

79+
constwasEnrolled=item._idleNext!==null||item._idlePrev!==null;
7580
item._destroyed=true;
7681

7782
if(item[kHasPrimitive])
@@ -99,6 +104,9 @@ function unenroll(item) {
99104
decRefCount();
100105
}
101106

107+
if(wasEnrolled)
108+
cleanTimer(item);
109+
102110
// If active is called later, then we want to make sure not to insert again
103111
item._idleTimeout=-1;
104112
}
@@ -238,7 +246,7 @@ function clearImmediate(immediate) {
238246

239247
emitDestroy(immediate[async_id_symbol]);
240248

241-
immediate._onImmediate=null;
249+
cleanImmediate(immediate);
242250

243251
immediateQueue.remove(immediate);
244252
}

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit e5278b7

Browse files
mcollinaaduh95
authored andcommitted
timers: do not retain a reference to the async store after firing
After firing timers, we can clean them up by iterating over all active stores and setting the relevant symbols to undefined. Fixes#53408 Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #53443 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Paolo Insogna <paolo@cowtech.it> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Gerhard StΓΆbich <deb2001-github@yahoo.de>
1 parent a5ce44d commit e5278b7

5 files changed

Lines changed: 281 additions & 22 deletions

File tree

β€Žlib/internal/async_hooks.jsβ€Ž

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ const before_symbol = Symbol('before');
104104
constafter_symbol=Symbol('after');
105105
constdestroy_symbol=Symbol('destroy');
106106
constpromise_resolve_symbol=Symbol('promiseResolve');
107+
constasync_local_storage_context_symbol=Symbol('kAsyncLocalStorageContext');
107108
constemitBeforeNative=emitHookFactory(before_symbol,'emitBeforeNative');
108109
constemitAfterNative=emitHookFactory(after_symbol,'emitAfterNative');
109110
constemitDestroyNative=emitHookFactory(destroy_symbol,'emitDestroyNative');
@@ -594,7 +595,8 @@ module.exports = {
594595
symbols: {
595596
async_id_symbol, trigger_async_id_symbol,
596597
init_symbol, before_symbol, after_symbol, destroy_symbol,
597-
promise_resolve_symbol, owner_symbol,
598+
promise_resolve_symbol, async_local_storage_context_symbol,
599+
owner_symbol,
598600
},
599601
constants: {
600602
kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,

β€Žlib/internal/async_local_storage/async_hooks.jsβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ const {
1212
const{
1313
validateObject,
1414
}=require('internal/validators');
15+
const{
16+
symbols: {
17+
async_local_storage_context_symbol,
18+
},
19+
}=require('internal/async_hooks');
1520

1621
const{
1722
AsyncResource,
@@ -20,6 +25,11 @@ const {
2025
}=require('async_hooks');
2126

2227
conststorageList=[];
28+
29+
functiongetOrCreateResourceStore(resource){
30+
returnresource[async_local_storage_context_symbol]??={__proto__: null};
31+
}
32+
2333
conststorageHook=createHook({
2434
init(asyncId,type,triggerAsyncId,resource){
2535
constcurrentResource=executionAsyncResource();
@@ -88,16 +98,18 @@ class AsyncLocalStorage {
8898

8999
// Propagate the context from a parent resource to a child one
90100
_propagate(resource,triggerResource,type){
91-
conststore=triggerResource[this.kResourceStore];
101+
conststore=triggerResource[async_local_storage_context_symbol]?.[this.kResourceStore];
92102
if(this.enabled){
93-
resource[this.kResourceStore]=store;
103+
constresourceStore=getOrCreateResourceStore(resource);
104+
resourceStore[this.kResourceStore]=store;
94105
}
95106
}
96107

97108
enterWith(store){
98109
this._enable();
99110
constresource=executionAsyncResource();
100-
resource[this.kResourceStore]=store;
111+
constresourceStore=getOrCreateResourceStore(resource);
112+
resourceStore[this.kResourceStore]=store;
101113
}
102114

103115
run(store,callback, ...args){
@@ -109,14 +121,15 @@ class AsyncLocalStorage {
109121
this._enable();
110122

111123
constresource=executionAsyncResource();
112-
constoldStore=resource[this.kResourceStore];
124+
constresourceStore=getOrCreateResourceStore(resource);
125+
constoldStore=resourceStore[this.kResourceStore];
113126

114-
resource[this.kResourceStore]=store;
127+
resourceStore[this.kResourceStore]=store;
115128

116129
try{
117130
returnReflectApply(callback,null,args);
118131
}finally{
119-
resource[this.kResourceStore]=oldStore;
132+
resourceStore[this.kResourceStore]=oldStore;
120133
}
121134
}
122135

@@ -135,10 +148,11 @@ class AsyncLocalStorage {
135148
getStore(){
136149
if(this.enabled){
137150
constresource=executionAsyncResource();
138-
if(!(this.kResourceStoreinresource)){
151+
constresourceStore=resource[async_local_storage_context_symbol];
152+
if(resourceStore===undefined||!(this.kResourceStoreinresourceStore)){
139153
returnthis.#defaultValue;
140154
}
141-
returnresource[this.kResourceStore];
155+
returnresourceStore[this.kResourceStore];
142156
}
143157
returnthis.#defaultValue;
144158
}

β€Žlib/internal/timers.jsβ€Ž

Lines changed: 79 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@ const {
8787
immediateInfo,
8888
timeoutInfo,
8989
}=binding;
90+
const{
91+
enqueueMicrotask,
92+
}=internalBinding('task_queue');
9093

9194
const{
9295
getDefaultTriggerAsyncId,
@@ -97,6 +100,9 @@ const {
97100
emitBefore,
98101
emitAfter,
99102
emitDestroy,
103+
symbols: {
104+
async_local_storage_context_symbol,
105+
},
100106
}=require('internal/async_hooks');
101107

102108
// Symbols for storing async id state.
@@ -125,6 +131,39 @@ const AsyncContextFrame = require('internal/async_context_frame');
125131

126132
constasync_context_frame=Symbol('kAsyncContextFrame');
127133

134+
functionremoveStoresFromResource(resource){
135+
if(AsyncContextFrame.enabled){
136+
if(resource[async_context_frame]!==undefined){
137+
resource[async_context_frame]=undefined;
138+
}
139+
}elseif(resource[async_local_storage_context_symbol]!==undefined){
140+
resource[async_local_storage_context_symbol]=undefined;
141+
}
142+
}
143+
144+
functioncleanTimer(timer){
145+
removeStoresFromResource(timer);
146+
timer._onTimeout=undefined;
147+
timer._timerArgs=undefined;
148+
}
149+
150+
functioncleanImmediate(immediate){
151+
removeStoresFromResource(immediate);
152+
immediate._onImmediate=undefined;
153+
immediate._argv=undefined;
154+
}
155+
156+
functionenqueueRemoveStoresFromResource(resource){
157+
enqueueMicrotask(()=>removeStoresFromResource(resource));
158+
}
159+
160+
functionenqueueRemoveStoresIfNotReinserted(resource){
161+
enqueueMicrotask(()=>{
162+
if(!resource._idleNext&&!resource._idlePrev)
163+
removeStoresFromResource(resource);
164+
});
165+
}
166+
128167
// *Must* match Environment::ImmediateInfo::Fields in src/env.h.
129168
constkCount=0;
130169
constkRefCount=1;
@@ -528,14 +567,22 @@ function getTimerCallbacks(runNextTicks) {
528567
constasyncId=immediate[async_id_symbol];
529568
emitBefore(asyncId,immediate[trigger_async_id_symbol],immediate);
530569

570+
letthrew=true;
531571
try{
532572
constargv=immediate._argv;
533573
if(!argv)
534574
immediate._onImmediate();
535575
else
536576
immediate._onImmediate(...argv);
577+
threw=false;
537578
}finally{
538-
immediate._onImmediate=null;
579+
if(threw){
580+
immediate._onImmediate=undefined;
581+
immediate._argv=undefined;
582+
enqueueRemoveStoresFromResource(immediate);
583+
}else{
584+
cleanImmediate(immediate);
585+
}
539586

540587
emitDestroy(asyncId);
541588

@@ -607,6 +654,8 @@ function getTimerCallbacks(runNextTicks) {
607654
if(!timer._destroyed){
608655
timer._destroyed=true;
609656

657+
cleanTimer(timer);
658+
610659
if(timer[kHasPrimitive])
611660
deleteknownTimersById[asyncId];
612661

@@ -629,26 +678,42 @@ function getTimerCallbacks(runNextTicks) {
629678
start=binding.getLibuvNow();
630679
}
631680

681+
letthrew=true;
632682
try{
633683
constargs=timer._timerArgs;
634684
if(args===undefined)
635685
timer._onTimeout();
636686
else
637687
ReflectApply(timer._onTimeout,timer,args);
688+
threw=false;
638689
}finally{
639690
if(timer._repeat&&timer._idleTimeout!==-1){
640691
timer._idleTimeout=timer._repeat;
641692
insert(timer,timer._idleTimeout,start);
642-
}elseif(!timer._idleNext&&!timer._idlePrev&&!timer._destroyed){
643-
timer._destroyed=true;
644-
645-
if(timer[kHasPrimitive])
646-
deleteknownTimersById[asyncId];
647-
648-
if(timer[kRefed])
649-
timeoutInfo[0]--;
650-
651-
emitDestroy(asyncId);
693+
}elseif(!timer._idleNext&&!timer._idlePrev){
694+
if(timer._destroyed){
695+
timer._onTimeout=undefined;
696+
timer._timerArgs=undefined;
697+
if(threw)
698+
enqueueRemoveStoresIfNotReinserted(timer);
699+
else
700+
removeStoresFromResource(timer);
701+
}else{
702+
if(threw)
703+
enqueueRemoveStoresIfNotReinserted(timer);
704+
else
705+
removeStoresFromResource(timer);
706+
707+
timer._destroyed=true;
708+
709+
if(timer[kHasPrimitive])
710+
deleteknownTimersById[asyncId];
711+
712+
if(timer[kRefed])
713+
timeoutInfo[0]--;
714+
715+
emitDestroy(asyncId);
716+
}
652717
}
653718
}
654719

@@ -728,8 +793,11 @@ module.exports = {
728793
kTimeout: Symbol('timeout'),// For hiding Timeouts on other internals.
729794
async_id_symbol,
730795
trigger_async_id_symbol,
796+
async_context_frame,
731797
Timeout,
732798
Immediate,
799+
cleanImmediate,
800+
cleanTimer,
733801
kRefed,
734802
kHasPrimitive,
735803
initAsyncResource,

β€Žlib/timers.jsβ€Ž

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ const {
3838
async_id_symbol,
3939
Timeout,
4040
Immediate,
41+
cleanTimer,
42+
cleanImmediate,
4143
decRefCount,
4244
immediateInfoFields: {
4345
kCount,
@@ -69,9 +71,12 @@ const {
6971

7072
// Remove a timer. Cancels the timeout and resets the relevant timer properties.
7173
functionunenroll(item){
72-
if(item._destroyed)
74+
if(item._destroyed){
75+
cleanTimer(item);
7376
return;
77+
}
7478

79+
constwasEnrolled=item._idleNext!==null||item._idlePrev!==null;
7580
item._destroyed=true;
7681

7782
if(item[kHasPrimitive])
@@ -99,6 +104,9 @@ function unenroll(item) {
99104
decRefCount();
100105
}
101106

107+
if(wasEnrolled)
108+
cleanTimer(item);
109+
102110
// If active is called later, then we want to make sure not to insert again
103111
item._idleTimeout=-1;
104112
}
@@ -238,7 +246,7 @@ function clearImmediate(immediate) {
238246

239247
emitDestroy(immediate[async_id_symbol]);
240248

241-
immediate._onImmediate=null;
249+
cleanImmediate(immediate);
242250

243251
immediateQueue.remove(immediate);
244252
}

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit e5278b7

Browse files
mcollinaaduh95
authored andcommitted
timers: do not retain a reference to the async store after firing
After firing timers, we can clean them up by iterating over all active stores and setting the relevant symbols to undefined. Fixes#53408 Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #53443 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Paolo Insogna <paolo@cowtech.it> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Gerhard StΓΆbich <deb2001-github@yahoo.de>
1 parent a5ce44d commit e5278b7

5 files changed

Lines changed: 281 additions & 22 deletions

File tree

β€Žlib/internal/async_hooks.jsβ€Ž

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ const before_symbol = Symbol('before');
104104
constafter_symbol=Symbol('after');
105105
constdestroy_symbol=Symbol('destroy');
106106
constpromise_resolve_symbol=Symbol('promiseResolve');
107+
constasync_local_storage_context_symbol=Symbol('kAsyncLocalStorageContext');
107108
constemitBeforeNative=emitHookFactory(before_symbol,'emitBeforeNative');
108109
constemitAfterNative=emitHookFactory(after_symbol,'emitAfterNative');
109110
constemitDestroyNative=emitHookFactory(destroy_symbol,'emitDestroyNative');
@@ -594,7 +595,8 @@ module.exports = {
594595
symbols: {
595596
async_id_symbol, trigger_async_id_symbol,
596597
init_symbol, before_symbol, after_symbol, destroy_symbol,
597-
promise_resolve_symbol, owner_symbol,
598+
promise_resolve_symbol, async_local_storage_context_symbol,
599+
owner_symbol,
598600
},
599601
constants: {
600602
kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,

β€Žlib/internal/async_local_storage/async_hooks.jsβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ const {
1212
const{
1313
validateObject,
1414
}=require('internal/validators');
15+
const{
16+
symbols: {
17+
async_local_storage_context_symbol,
18+
},
19+
}=require('internal/async_hooks');
1520

1621
const{
1722
AsyncResource,
@@ -20,6 +25,11 @@ const {
2025
}=require('async_hooks');
2126

2227
conststorageList=[];
28+
29+
functiongetOrCreateResourceStore(resource){
30+
returnresource[async_local_storage_context_symbol]??={__proto__: null};
31+
}
32+
2333
conststorageHook=createHook({
2434
init(asyncId,type,triggerAsyncId,resource){
2535
constcurrentResource=executionAsyncResource();
@@ -88,16 +98,18 @@ class AsyncLocalStorage {
8898

8999
// Propagate the context from a parent resource to a child one
90100
_propagate(resource,triggerResource,type){
91-
conststore=triggerResource[this.kResourceStore];
101+
conststore=triggerResource[async_local_storage_context_symbol]?.[this.kResourceStore];
92102
if(this.enabled){
93-
resource[this.kResourceStore]=store;
103+
constresourceStore=getOrCreateResourceStore(resource);
104+
resourceStore[this.kResourceStore]=store;
94105
}
95106
}
96107

97108
enterWith(store){
98109
this._enable();
99110
constresource=executionAsyncResource();
100-
resource[this.kResourceStore]=store;
111+
constresourceStore=getOrCreateResourceStore(resource);
112+
resourceStore[this.kResourceStore]=store;
101113
}
102114

103115
run(store,callback, ...args){
@@ -109,14 +121,15 @@ class AsyncLocalStorage {
109121
this._enable();
110122

111123
constresource=executionAsyncResource();
112-
constoldStore=resource[this.kResourceStore];
124+
constresourceStore=getOrCreateResourceStore(resource);
125+
constoldStore=resourceStore[this.kResourceStore];
113126

114-
resource[this.kResourceStore]=store;
127+
resourceStore[this.kResourceStore]=store;
115128

116129
try{
117130
returnReflectApply(callback,null,args);
118131
}finally{
119-
resource[this.kResourceStore]=oldStore;
132+
resourceStore[this.kResourceStore]=oldStore;
120133
}
121134
}
122135

@@ -135,10 +148,11 @@ class AsyncLocalStorage {
135148
getStore(){
136149
if(this.enabled){
137150
constresource=executionAsyncResource();
138-
if(!(this.kResourceStoreinresource)){
151+
constresourceStore=resource[async_local_storage_context_symbol];
152+
if(resourceStore===undefined||!(this.kResourceStoreinresourceStore)){
139153
returnthis.#defaultValue;
140154
}
141-
returnresource[this.kResourceStore];
155+
returnresourceStore[this.kResourceStore];
142156
}
143157
returnthis.#defaultValue;
144158
}

β€Žlib/internal/timers.jsβ€Ž

Lines changed: 79 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@ const {
8787
immediateInfo,
8888
timeoutInfo,
8989
}=binding;
90+
const{
91+
enqueueMicrotask,
92+
}=internalBinding('task_queue');
9093

9194
const{
9295
getDefaultTriggerAsyncId,
@@ -97,6 +100,9 @@ const {
97100
emitBefore,
98101
emitAfter,
99102
emitDestroy,
103+
symbols: {
104+
async_local_storage_context_symbol,
105+
},
100106
}=require('internal/async_hooks');
101107

102108
// Symbols for storing async id state.
@@ -125,6 +131,39 @@ const AsyncContextFrame = require('internal/async_context_frame');
125131

126132
constasync_context_frame=Symbol('kAsyncContextFrame');
127133

134+
functionremoveStoresFromResource(resource){
135+
if(AsyncContextFrame.enabled){
136+
if(resource[async_context_frame]!==undefined){
137+
resource[async_context_frame]=undefined;
138+
}
139+
}elseif(resource[async_local_storage_context_symbol]!==undefined){
140+
resource[async_local_storage_context_symbol]=undefined;
141+
}
142+
}
143+
144+
functioncleanTimer(timer){
145+
removeStoresFromResource(timer);
146+
timer._onTimeout=undefined;
147+
timer._timerArgs=undefined;
148+
}
149+
150+
functioncleanImmediate(immediate){
151+
removeStoresFromResource(immediate);
152+
immediate._onImmediate=undefined;
153+
immediate._argv=undefined;
154+
}
155+
156+
functionenqueueRemoveStoresFromResource(resource){
157+
enqueueMicrotask(()=>removeStoresFromResource(resource));
158+
}
159+
160+
functionenqueueRemoveStoresIfNotReinserted(resource){
161+
enqueueMicrotask(()=>{
162+
if(!resource._idleNext&&!resource._idlePrev)
163+
removeStoresFromResource(resource);
164+
});
165+
}
166+
128167
// *Must* match Environment::ImmediateInfo::Fields in src/env.h.
129168
constkCount=0;
130169
constkRefCount=1;
@@ -528,14 +567,22 @@ function getTimerCallbacks(runNextTicks) {
528567
constasyncId=immediate[async_id_symbol];
529568
emitBefore(asyncId,immediate[trigger_async_id_symbol],immediate);
530569

570+
letthrew=true;
531571
try{
532572
constargv=immediate._argv;
533573
if(!argv)
534574
immediate._onImmediate();
535575
else
536576
immediate._onImmediate(...argv);
577+
threw=false;
537578
}finally{
538-
immediate._onImmediate=null;
579+
if(threw){
580+
immediate._onImmediate=undefined;
581+
immediate._argv=undefined;
582+
enqueueRemoveStoresFromResource(immediate);
583+
}else{
584+
cleanImmediate(immediate);
585+
}
539586

540587
emitDestroy(asyncId);
541588

@@ -607,6 +654,8 @@ function getTimerCallbacks(runNextTicks) {
607654
if(!timer._destroyed){
608655
timer._destroyed=true;
609656

657+
cleanTimer(timer);
658+
610659
if(timer[kHasPrimitive])
611660
deleteknownTimersById[asyncId];
612661

@@ -629,26 +678,42 @@ function getTimerCallbacks(runNextTicks) {
629678
start=binding.getLibuvNow();
630679
}
631680

681+
letthrew=true;
632682
try{
633683
constargs=timer._timerArgs;
634684
if(args===undefined)
635685
timer._onTimeout();
636686
else
637687
ReflectApply(timer._onTimeout,timer,args);
688+
threw=false;
638689
}finally{
639690
if(timer._repeat&&timer._idleTimeout!==-1){
640691
timer._idleTimeout=timer._repeat;
641692
insert(timer,timer._idleTimeout,start);
642-
}elseif(!timer._idleNext&&!timer._idlePrev&&!timer._destroyed){
643-
timer._destroyed=true;
644-
645-
if(timer[kHasPrimitive])
646-
deleteknownTimersById[asyncId];
647-
648-
if(timer[kRefed])
649-
timeoutInfo[0]--;
650-
651-
emitDestroy(asyncId);
693+
}elseif(!timer._idleNext&&!timer._idlePrev){
694+
if(timer._destroyed){
695+
timer._onTimeout=undefined;
696+
timer._timerArgs=undefined;
697+
if(threw)
698+
enqueueRemoveStoresIfNotReinserted(timer);
699+
else
700+
removeStoresFromResource(timer);
701+
}else{
702+
if(threw)
703+
enqueueRemoveStoresIfNotReinserted(timer);
704+
else
705+
removeStoresFromResource(timer);
706+
707+
timer._destroyed=true;
708+
709+
if(timer[kHasPrimitive])
710+
deleteknownTimersById[asyncId];
711+
712+
if(timer[kRefed])
713+
timeoutInfo[0]--;
714+
715+
emitDestroy(asyncId);
716+
}
652717
}
653718
}
654719

@@ -728,8 +793,11 @@ module.exports = {
728793
kTimeout: Symbol('timeout'),// For hiding Timeouts on other internals.
729794
async_id_symbol,
730795
trigger_async_id_symbol,
796+
async_context_frame,
731797
Timeout,
732798
Immediate,
799+
cleanImmediate,
800+
cleanTimer,
733801
kRefed,
734802
kHasPrimitive,
735803
initAsyncResource,

β€Žlib/timers.jsβ€Ž

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ const {
3838
async_id_symbol,
3939
Timeout,
4040
Immediate,
41+
cleanTimer,
42+
cleanImmediate,
4143
decRefCount,
4244
immediateInfoFields: {
4345
kCount,
@@ -69,9 +71,12 @@ const {
6971

7072
// Remove a timer. Cancels the timeout and resets the relevant timer properties.
7173
functionunenroll(item){
72-
if(item._destroyed)
74+
if(item._destroyed){
75+
cleanTimer(item);
7376
return;
77+
}
7478

79+
constwasEnrolled=item._idleNext!==null||item._idlePrev!==null;
7580
item._destroyed=true;
7681

7782
if(item[kHasPrimitive])
@@ -99,6 +104,9 @@ function unenroll(item) {
99104
decRefCount();
100105
}
101106

107+
if(wasEnrolled)
108+
cleanTimer(item);
109+
102110
// If active is called later, then we want to make sure not to insert again
103111
item._idleTimeout=-1;
104112
}
@@ -238,7 +246,7 @@ function clearImmediate(immediate) {
238246

239247
emitDestroy(immediate[async_id_symbol]);
240248

241-
immediate._onImmediate=null;
249+
cleanImmediate(immediate);
242250

243251
immediateQueue.remove(immediate);
244252
}

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit e5278b7

Browse files
mcollinaaduh95
authored andcommitted
timers: do not retain a reference to the async store after firing
After firing timers, we can clean them up by iterating over all active stores and setting the relevant symbols to undefined. Fixes#53408 Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #53443 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Paolo Insogna <paolo@cowtech.it> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Gerhard StΓΆbich <deb2001-github@yahoo.de>
1 parent a5ce44d commit e5278b7

5 files changed

Lines changed: 281 additions & 22 deletions

File tree

β€Žlib/internal/async_hooks.jsβ€Ž

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ const before_symbol = Symbol('before');
104104
constafter_symbol=Symbol('after');
105105
constdestroy_symbol=Symbol('destroy');
106106
constpromise_resolve_symbol=Symbol('promiseResolve');
107+
constasync_local_storage_context_symbol=Symbol('kAsyncLocalStorageContext');
107108
constemitBeforeNative=emitHookFactory(before_symbol,'emitBeforeNative');
108109
constemitAfterNative=emitHookFactory(after_symbol,'emitAfterNative');
109110
constemitDestroyNative=emitHookFactory(destroy_symbol,'emitDestroyNative');
@@ -594,7 +595,8 @@ module.exports = {
594595
symbols: {
595596
async_id_symbol, trigger_async_id_symbol,
596597
init_symbol, before_symbol, after_symbol, destroy_symbol,
597-
promise_resolve_symbol, owner_symbol,
598+
promise_resolve_symbol, async_local_storage_context_symbol,
599+
owner_symbol,
598600
},
599601
constants: {
600602
kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,

β€Žlib/internal/async_local_storage/async_hooks.jsβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ const {
1212
const{
1313
validateObject,
1414
}=require('internal/validators');
15+
const{
16+
symbols: {
17+
async_local_storage_context_symbol,
18+
},
19+
}=require('internal/async_hooks');
1520

1621
const{
1722
AsyncResource,
@@ -20,6 +25,11 @@ const {
2025
}=require('async_hooks');
2126

2227
conststorageList=[];
28+
29+
functiongetOrCreateResourceStore(resource){
30+
returnresource[async_local_storage_context_symbol]??={__proto__: null};
31+
}
32+
2333
conststorageHook=createHook({
2434
init(asyncId,type,triggerAsyncId,resource){
2535
constcurrentResource=executionAsyncResource();
@@ -88,16 +98,18 @@ class AsyncLocalStorage {
8898

8999
// Propagate the context from a parent resource to a child one
90100
_propagate(resource,triggerResource,type){
91-
conststore=triggerResource[this.kResourceStore];
101+
conststore=triggerResource[async_local_storage_context_symbol]?.[this.kResourceStore];
92102
if(this.enabled){
93-
resource[this.kResourceStore]=store;
103+
constresourceStore=getOrCreateResourceStore(resource);
104+
resourceStore[this.kResourceStore]=store;
94105
}
95106
}
96107

97108
enterWith(store){
98109
this._enable();
99110
constresource=executionAsyncResource();
100-
resource[this.kResourceStore]=store;
111+
constresourceStore=getOrCreateResourceStore(resource);
112+
resourceStore[this.kResourceStore]=store;
101113
}
102114

103115
run(store,callback, ...args){
@@ -109,14 +121,15 @@ class AsyncLocalStorage {
109121
this._enable();
110122

111123
constresource=executionAsyncResource();
112-
constoldStore=resource[this.kResourceStore];
124+
constresourceStore=getOrCreateResourceStore(resource);
125+
constoldStore=resourceStore[this.kResourceStore];
113126

114-
resource[this.kResourceStore]=store;
127+
resourceStore[this.kResourceStore]=store;
115128

116129
try{
117130
returnReflectApply(callback,null,args);
118131
}finally{
119-
resource[this.kResourceStore]=oldStore;
132+
resourceStore[this.kResourceStore]=oldStore;
120133
}
121134
}
122135

@@ -135,10 +148,11 @@ class AsyncLocalStorage {
135148
getStore(){
136149
if(this.enabled){
137150
constresource=executionAsyncResource();
138-
if(!(this.kResourceStoreinresource)){
151+
constresourceStore=resource[async_local_storage_context_symbol];
152+
if(resourceStore===undefined||!(this.kResourceStoreinresourceStore)){
139153
returnthis.#defaultValue;
140154
}
141-
returnresource[this.kResourceStore];
155+
returnresourceStore[this.kResourceStore];
142156
}
143157
returnthis.#defaultValue;
144158
}

β€Žlib/internal/timers.jsβ€Ž

Lines changed: 79 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@ const {
8787
immediateInfo,
8888
timeoutInfo,
8989
}=binding;
90+
const{
91+
enqueueMicrotask,
92+
}=internalBinding('task_queue');
9093

9194
const{
9295
getDefaultTriggerAsyncId,
@@ -97,6 +100,9 @@ const {
97100
emitBefore,
98101
emitAfter,
99102
emitDestroy,
103+
symbols: {
104+
async_local_storage_context_symbol,
105+
},
100106
}=require('internal/async_hooks');
101107

102108
// Symbols for storing async id state.
@@ -125,6 +131,39 @@ const AsyncContextFrame = require('internal/async_context_frame');
125131

126132
constasync_context_frame=Symbol('kAsyncContextFrame');
127133

134+
functionremoveStoresFromResource(resource){
135+
if(AsyncContextFrame.enabled){
136+
if(resource[async_context_frame]!==undefined){
137+
resource[async_context_frame]=undefined;
138+
}
139+
}elseif(resource[async_local_storage_context_symbol]!==undefined){
140+
resource[async_local_storage_context_symbol]=undefined;
141+
}
142+
}
143+
144+
functioncleanTimer(timer){
145+
removeStoresFromResource(timer);
146+
timer._onTimeout=undefined;
147+
timer._timerArgs=undefined;
148+
}
149+
150+
functioncleanImmediate(immediate){
151+
removeStoresFromResource(immediate);
152+
immediate._onImmediate=undefined;
153+
immediate._argv=undefined;
154+
}
155+
156+
functionenqueueRemoveStoresFromResource(resource){
157+
enqueueMicrotask(()=>removeStoresFromResource(resource));
158+
}
159+
160+
functionenqueueRemoveStoresIfNotReinserted(resource){
161+
enqueueMicrotask(()=>{
162+
if(!resource._idleNext&&!resource._idlePrev)
163+
removeStoresFromResource(resource);
164+
});
165+
}
166+
128167
// *Must* match Environment::ImmediateInfo::Fields in src/env.h.
129168
constkCount=0;
130169
constkRefCount=1;
@@ -528,14 +567,22 @@ function getTimerCallbacks(runNextTicks) {
528567
constasyncId=immediate[async_id_symbol];
529568
emitBefore(asyncId,immediate[trigger_async_id_symbol],immediate);
530569

570+
letthrew=true;
531571
try{
532572
constargv=immediate._argv;
533573
if(!argv)
534574
immediate._onImmediate();
535575
else
536576
immediate._onImmediate(...argv);
577+
threw=false;
537578
}finally{
538-
immediate._onImmediate=null;
579+
if(threw){
580+
immediate._onImmediate=undefined;
581+
immediate._argv=undefined;
582+
enqueueRemoveStoresFromResource(immediate);
583+
}else{
584+
cleanImmediate(immediate);
585+
}
539586

540587
emitDestroy(asyncId);
541588

@@ -607,6 +654,8 @@ function getTimerCallbacks(runNextTicks) {
607654
if(!timer._destroyed){
608655
timer._destroyed=true;
609656

657+
cleanTimer(timer);
658+
610659
if(timer[kHasPrimitive])
611660
deleteknownTimersById[asyncId];
612661

@@ -629,26 +678,42 @@ function getTimerCallbacks(runNextTicks) {
629678
start=binding.getLibuvNow();
630679
}
631680

681+
letthrew=true;
632682
try{
633683
constargs=timer._timerArgs;
634684
if(args===undefined)
635685
timer._onTimeout();
636686
else
637687
ReflectApply(timer._onTimeout,timer,args);
688+
threw=false;
638689
}finally{
639690
if(timer._repeat&&timer._idleTimeout!==-1){
640691
timer._idleTimeout=timer._repeat;
641692
insert(timer,timer._idleTimeout,start);
642-
}elseif(!timer._idleNext&&!timer._idlePrev&&!timer._destroyed){
643-
timer._destroyed=true;
644-
645-
if(timer[kHasPrimitive])
646-
deleteknownTimersById[asyncId];
647-
648-
if(timer[kRefed])
649-
timeoutInfo[0]--;
650-
651-
emitDestroy(asyncId);
693+
}elseif(!timer._idleNext&&!timer._idlePrev){
694+
if(timer._destroyed){
695+
timer._onTimeout=undefined;
696+
timer._timerArgs=undefined;
697+
if(threw)
698+
enqueueRemoveStoresIfNotReinserted(timer);
699+
else
700+
removeStoresFromResource(timer);
701+
}else{
702+
if(threw)
703+
enqueueRemoveStoresIfNotReinserted(timer);
704+
else
705+
removeStoresFromResource(timer);
706+
707+
timer._destroyed=true;
708+
709+
if(timer[kHasPrimitive])
710+
deleteknownTimersById[asyncId];
711+
712+
if(timer[kRefed])
713+
timeoutInfo[0]--;
714+
715+
emitDestroy(asyncId);
716+
}
652717
}
653718
}
654719

@@ -728,8 +793,11 @@ module.exports = {
728793
kTimeout: Symbol('timeout'),// For hiding Timeouts on other internals.
729794
async_id_symbol,
730795
trigger_async_id_symbol,
796+
async_context_frame,
731797
Timeout,
732798
Immediate,
799+
cleanImmediate,
800+
cleanTimer,
733801
kRefed,
734802
kHasPrimitive,
735803
initAsyncResource,

β€Žlib/timers.jsβ€Ž

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ const {
3838
async_id_symbol,
3939
Timeout,
4040
Immediate,
41+
cleanTimer,
42+
cleanImmediate,
4143
decRefCount,
4244
immediateInfoFields: {
4345
kCount,
@@ -69,9 +71,12 @@ const {
6971

7072
// Remove a timer. Cancels the timeout and resets the relevant timer properties.
7173
functionunenroll(item){
72-
if(item._destroyed)
74+
if(item._destroyed){
75+
cleanTimer(item);
7376
return;
77+
}
7478

79+
constwasEnrolled=item._idleNext!==null||item._idlePrev!==null;
7580
item._destroyed=true;
7681

7782
if(item[kHasPrimitive])
@@ -99,6 +104,9 @@ function unenroll(item) {
99104
decRefCount();
100105
}
101106

107+
if(wasEnrolled)
108+
cleanTimer(item);
109+
102110
// If active is called later, then we want to make sure not to insert again
103111
item._idleTimeout=-1;
104112
}
@@ -238,7 +246,7 @@ function clearImmediate(immediate) {
238246

239247
emitDestroy(immediate[async_id_symbol]);
240248

241-
immediate._onImmediate=null;
249+
cleanImmediate(immediate);
242250

243251
immediateQueue.remove(immediate);
244252
}

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit e5278b7

Browse files
mcollinaaduh95
authored andcommitted
timers: do not retain a reference to the async store after firing
After firing timers, we can clean them up by iterating over all active stores and setting the relevant symbols to undefined. Fixes#53408 Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #53443 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Paolo Insogna <paolo@cowtech.it> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Gerhard StΓΆbich <deb2001-github@yahoo.de>
1 parent a5ce44d commit e5278b7

5 files changed

Lines changed: 281 additions & 22 deletions

File tree

β€Žlib/internal/async_hooks.jsβ€Ž

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ const before_symbol = Symbol('before');
104104
constafter_symbol=Symbol('after');
105105
constdestroy_symbol=Symbol('destroy');
106106
constpromise_resolve_symbol=Symbol('promiseResolve');
107+
constasync_local_storage_context_symbol=Symbol('kAsyncLocalStorageContext');
107108
constemitBeforeNative=emitHookFactory(before_symbol,'emitBeforeNative');
108109
constemitAfterNative=emitHookFactory(after_symbol,'emitAfterNative');
109110
constemitDestroyNative=emitHookFactory(destroy_symbol,'emitDestroyNative');
@@ -594,7 +595,8 @@ module.exports = {
594595
symbols: {
595596
async_id_symbol, trigger_async_id_symbol,
596597
init_symbol, before_symbol, after_symbol, destroy_symbol,
597-
promise_resolve_symbol, owner_symbol,
598+
promise_resolve_symbol, async_local_storage_context_symbol,
599+
owner_symbol,
598600
},
599601
constants: {
600602
kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,

β€Žlib/internal/async_local_storage/async_hooks.jsβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ const {
1212
const{
1313
validateObject,
1414
}=require('internal/validators');
15+
const{
16+
symbols: {
17+
async_local_storage_context_symbol,
18+
},
19+
}=require('internal/async_hooks');
1520

1621
const{
1722
AsyncResource,
@@ -20,6 +25,11 @@ const {
2025
}=require('async_hooks');
2126

2227
conststorageList=[];
28+
29+
functiongetOrCreateResourceStore(resource){
30+
returnresource[async_local_storage_context_symbol]??={__proto__: null};
31+
}
32+
2333
conststorageHook=createHook({
2434
init(asyncId,type,triggerAsyncId,resource){
2535
constcurrentResource=executionAsyncResource();
@@ -88,16 +98,18 @@ class AsyncLocalStorage {
8898

8999
// Propagate the context from a parent resource to a child one
90100
_propagate(resource,triggerResource,type){
91-
conststore=triggerResource[this.kResourceStore];
101+
conststore=triggerResource[async_local_storage_context_symbol]?.[this.kResourceStore];
92102
if(this.enabled){
93-
resource[this.kResourceStore]=store;
103+
constresourceStore=getOrCreateResourceStore(resource);
104+
resourceStore[this.kResourceStore]=store;
94105
}
95106
}
96107

97108
enterWith(store){
98109
this._enable();
99110
constresource=executionAsyncResource();
100-
resource[this.kResourceStore]=store;
111+
constresourceStore=getOrCreateResourceStore(resource);
112+
resourceStore[this.kResourceStore]=store;
101113
}
102114

103115
run(store,callback, ...args){
@@ -109,14 +121,15 @@ class AsyncLocalStorage {
109121
this._enable();
110122

111123
constresource=executionAsyncResource();
112-
constoldStore=resource[this.kResourceStore];
124+
constresourceStore=getOrCreateResourceStore(resource);
125+
constoldStore=resourceStore[this.kResourceStore];
113126

114-
resource[this.kResourceStore]=store;
127+
resourceStore[this.kResourceStore]=store;
115128

116129
try{
117130
returnReflectApply(callback,null,args);
118131
}finally{
119-
resource[this.kResourceStore]=oldStore;
132+
resourceStore[this.kResourceStore]=oldStore;
120133
}
121134
}
122135

@@ -135,10 +148,11 @@ class AsyncLocalStorage {
135148
getStore(){
136149
if(this.enabled){
137150
constresource=executionAsyncResource();
138-
if(!(this.kResourceStoreinresource)){
151+
constresourceStore=resource[async_local_storage_context_symbol];
152+
if(resourceStore===undefined||!(this.kResourceStoreinresourceStore)){
139153
returnthis.#defaultValue;
140154
}
141-
returnresource[this.kResourceStore];
155+
returnresourceStore[this.kResourceStore];
142156
}
143157
returnthis.#defaultValue;
144158
}

β€Žlib/internal/timers.jsβ€Ž

Lines changed: 79 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@ const {
8787
immediateInfo,
8888
timeoutInfo,
8989
}=binding;
90+
const{
91+
enqueueMicrotask,
92+
}=internalBinding('task_queue');
9093

9194
const{
9295
getDefaultTriggerAsyncId,
@@ -97,6 +100,9 @@ const {
97100
emitBefore,
98101
emitAfter,
99102
emitDestroy,
103+
symbols: {
104+
async_local_storage_context_symbol,
105+
},
100106
}=require('internal/async_hooks');
101107

102108
// Symbols for storing async id state.
@@ -125,6 +131,39 @@ const AsyncContextFrame = require('internal/async_context_frame');
125131

126132
constasync_context_frame=Symbol('kAsyncContextFrame');
127133

134+
functionremoveStoresFromResource(resource){
135+
if(AsyncContextFrame.enabled){
136+
if(resource[async_context_frame]!==undefined){
137+
resource[async_context_frame]=undefined;
138+
}
139+
}elseif(resource[async_local_storage_context_symbol]!==undefined){
140+
resource[async_local_storage_context_symbol]=undefined;
141+
}
142+
}
143+
144+
functioncleanTimer(timer){
145+
removeStoresFromResource(timer);
146+
timer._onTimeout=undefined;
147+
timer._timerArgs=undefined;
148+
}
149+
150+
functioncleanImmediate(immediate){
151+
removeStoresFromResource(immediate);
152+
immediate._onImmediate=undefined;
153+
immediate._argv=undefined;
154+
}
155+
156+
functionenqueueRemoveStoresFromResource(resource){
157+
enqueueMicrotask(()=>removeStoresFromResource(resource));
158+
}
159+
160+
functionenqueueRemoveStoresIfNotReinserted(resource){
161+
enqueueMicrotask(()=>{
162+
if(!resource._idleNext&&!resource._idlePrev)
163+
removeStoresFromResource(resource);
164+
});
165+
}
166+
128167
// *Must* match Environment::ImmediateInfo::Fields in src/env.h.
129168
constkCount=0;
130169
constkRefCount=1;
@@ -528,14 +567,22 @@ function getTimerCallbacks(runNextTicks) {
528567
constasyncId=immediate[async_id_symbol];
529568
emitBefore(asyncId,immediate[trigger_async_id_symbol],immediate);
530569

570+
letthrew=true;
531571
try{
532572
constargv=immediate._argv;
533573
if(!argv)
534574
immediate._onImmediate();
535575
else
536576
immediate._onImmediate(...argv);
577+
threw=false;
537578
}finally{
538-
immediate._onImmediate=null;
579+
if(threw){
580+
immediate._onImmediate=undefined;
581+
immediate._argv=undefined;
582+
enqueueRemoveStoresFromResource(immediate);
583+
}else{
584+
cleanImmediate(immediate);
585+
}
539586

540587
emitDestroy(asyncId);
541588

@@ -607,6 +654,8 @@ function getTimerCallbacks(runNextTicks) {
607654
if(!timer._destroyed){
608655
timer._destroyed=true;
609656

657+
cleanTimer(timer);
658+
610659
if(timer[kHasPrimitive])
611660
deleteknownTimersById[asyncId];
612661

@@ -629,26 +678,42 @@ function getTimerCallbacks(runNextTicks) {
629678
start=binding.getLibuvNow();
630679
}
631680

681+
letthrew=true;
632682
try{
633683
constargs=timer._timerArgs;
634684
if(args===undefined)
635685
timer._onTimeout();
636686
else
637687
ReflectApply(timer._onTimeout,timer,args);
688+
threw=false;
638689
}finally{
639690
if(timer._repeat&&timer._idleTimeout!==-1){
640691
timer._idleTimeout=timer._repeat;
641692
insert(timer,timer._idleTimeout,start);
642-
}elseif(!timer._idleNext&&!timer._idlePrev&&!timer._destroyed){
643-
timer._destroyed=true;
644-
645-
if(timer[kHasPrimitive])
646-
deleteknownTimersById[asyncId];
647-
648-
if(timer[kRefed])
649-
timeoutInfo[0]--;
650-
651-
emitDestroy(asyncId);
693+
}elseif(!timer._idleNext&&!timer._idlePrev){
694+
if(timer._destroyed){
695+
timer._onTimeout=undefined;
696+
timer._timerArgs=undefined;
697+
if(threw)
698+
enqueueRemoveStoresIfNotReinserted(timer);
699+
else
700+
removeStoresFromResource(timer);
701+
}else{
702+
if(threw)
703+
enqueueRemoveStoresIfNotReinserted(timer);
704+
else
705+
removeStoresFromResource(timer);
706+
707+
timer._destroyed=true;
708+
709+
if(timer[kHasPrimitive])
710+
deleteknownTimersById[asyncId];
711+
712+
if(timer[kRefed])
713+
timeoutInfo[0]--;
714+
715+
emitDestroy(asyncId);
716+
}
652717
}
653718
}
654719

@@ -728,8 +793,11 @@ module.exports = {
728793
kTimeout: Symbol('timeout'),// For hiding Timeouts on other internals.
729794
async_id_symbol,
730795
trigger_async_id_symbol,
796+
async_context_frame,
731797
Timeout,
732798
Immediate,
799+
cleanImmediate,
800+
cleanTimer,
733801
kRefed,
734802
kHasPrimitive,
735803
initAsyncResource,

β€Žlib/timers.jsβ€Ž

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ const {
3838
async_id_symbol,
3939
Timeout,
4040
Immediate,
41+
cleanTimer,
42+
cleanImmediate,
4143
decRefCount,
4244
immediateInfoFields: {
4345
kCount,
@@ -69,9 +71,12 @@ const {
6971

7072
// Remove a timer. Cancels the timeout and resets the relevant timer properties.
7173
functionunenroll(item){
72-
if(item._destroyed)
74+
if(item._destroyed){
75+
cleanTimer(item);
7376
return;
77+
}
7478

79+
constwasEnrolled=item._idleNext!==null||item._idlePrev!==null;
7580
item._destroyed=true;
7681

7782
if(item[kHasPrimitive])
@@ -99,6 +104,9 @@ function unenroll(item) {
99104
decRefCount();
100105
}
101106

107+
if(wasEnrolled)
108+
cleanTimer(item);
109+
102110
// If active is called later, then we want to make sure not to insert again
103111
item._idleTimeout=-1;
104112
}
@@ -238,7 +246,7 @@ function clearImmediate(immediate) {
238246

239247
emitDestroy(immediate[async_id_symbol]);
240248

241-
immediate._onImmediate=null;
249+
cleanImmediate(immediate);
242250

243251
immediateQueue.remove(immediate);
244252
}

0 commit comments

Comments
Β (0)