That's what I was thinking. You could get almost all of this pretty directly in Javascript by putting a callback function in an AsyncLocalStorage instance or, in other languages, in a thread local variable.