proposal-async-context icon indicating copy to clipboard operation
proposal-async-context copied to clipboard

Clean Context

Open martinheidegger opened this issue 1 year ago • 3 comments

Having complex systems with various variables could result in leaking unintended values to subsystems. It might be reasonable to have something like AsyncContext.sandbox(() => {... }) which reset's all the state, preventing parents to interfere.

const asyncVar = new AsyncContext.Variable();

// Sets the current value to 'top', and executes the `main` function.
asyncVar.run("top", main);

function main() {
    AsyncContext.sandbox(() => {
      console.log(asyncVar.get()); // => undefined
    });
}

martinheidegger avatar Oct 07 '24 16:10 martinheidegger

Just for context, in Node.js this is store.exit(() => {}).

Qard avatar Oct 10 '24 13:10 Qard

the sandbox() feature can be implemented by creating a snapshot from the global scope. no?

const asyncVar = new AsyncContext.Variable();
const sandbox = new AsyncContext.Snapshot()

// Sets the current value to 'top', and executes the `main` function.
asyncVar.run("top", main);

function main() {
    sandbox.run(() => {
      console.log(asyncVar.get()); // => undefined
    });
}

iliasbhal avatar Jan 21 '25 18:01 iliasbhal

the sandbox() feature can be implemented by creating a snapshot from the global scope. no?

Yes, but CommonJS libraries in Node.js would not have access to the global scope.

In the web integration, we are proposing that some event listeners (e.g. for a user-caused click event) would have a clean context. We are also proposing that ES modules would be run with a clean context, because each module is only ever run once, and @nicolo-ribaudo argues that they shouldn't be able to observe what caused the module to be imported. Given that, each ES module would have access to the clean context, and there might be other ways for CommonJS modules and regular <script>s to get it.

andreubotella avatar Jan 21 '25 18:01 andreubotella