Nicolò Ribaudo
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# AsyncContext & events: alternative proposal The current web integration draft for AsyncContext proposes that event handlers run using the context that was active when `.addEventListener` was called (the "registration context"). This is because it is significantly easier to specify and to implement: the change is limited to the `EventTarget` interface, that is responsible for capturing the async context snapshot and then restoring it when running the callback. Unfortunately for that proposal, many AsyncContext use cases require access to the context that was active when the event was dispatched (or when the action that caused the event to be dispatched was started): the proposal thus leaves the door open to expose that as a property on the event. This approach however: - brings back the complexity to browsers and specs, since they still need to track the dispatch-time context - does not actually help with the use cases for having the dispatch-time context, since it requires that the user explicitly forwards it to whatever library/framework is using AsyncContext. AsyncContext is meant to be something that most developers do not have to think about, but that libraries can rely on thanks to it being implicitly propagated the correct way. I propose that instead we run event handlers using the context that was active when the event was _dispatched_, instead of the one when the handler was _registered_. Events that have no dispatch-time context would fallback to the top-level root context. This document goes through how it can be done. ## Three types of events To better understand the problem space, we need to divide events in three cathegories: - events that are dispatched synchronously as a consequence of JS code - events that are dispatched asynchronously as a consequence of JS code - events that are dispatched as a consequence something triggered outside of the page, such as user interaction in the browser of incoming HTTP requests on the server A single (target, event type) pair can fall under multiple cathegories, however every specific fired event will be only in one. ### Events dispatched synchronously from JS Example: events dispatched through `eventTarget.dispatchEvent()`, `element.click()`, or `abortController.abort()`. For events that fall in this cathegory, propagating the dispatch context is trivial: there is nothing to do. The "dispatch context" is the one stored in the surrounding agent, which will be the same surrounding agent used to run the callback, and (unless some spec algorithm _explicitly_ changes it) the async context remains the same. Propagating the registration context on the other hand requires more work: you need to store a snapshot of the context when `.addEventListener` was called, which will be kept alive for as long as the event handler is registered and thus cannot be garbage-collected. ### Event dispatched due an outside trigger Example: user clicking on the document, localStorage changes from a different tab, messages from a different worker. For these events there is no JavaScript dispatch context, so we need to choose a fallback between the root empty context and the registration context. The coherent answer is to fallback to the root context ([Why "root context" is the coherent fallback for "dispatch context"](https://hackmd.io/@nicolo-ribaudo/BJXjpLbyyx)). Falling back to the empty context shuold be simple implementation-wise, and compared to using the registration context has the benefit of not keeping the registration context alive (as for sync events dispatched from JS). ### Events dispatched asynchronously from JS Example: `xhr.send()` -> `load`, `indexedDB.commit()` -> `complete`, `animation.play()` -> `finish` This where most of the complexity of propagating the dispatch context comes from. The rule of thumb for what the dispatch context should be is "if the async part was internally implemented using async/await that _synchronously_ dispatches events during its process, what would the context be?". A trivial approach to propagating the dispatch context inside specifications is to capture a snapshot when the function that starts the process is called (e.g. when calling `xhr.send()`), manually passing it around up to where the event is dispatched, and activate that snapshot before dispatching the event. However, this method has a significant problem: it adds noise to the specification, that makes it harder both to read and to write it. This problem would also happen if we default to the registration context and expose the dispatch context as `e.dispatchContext`. To solve this problem, we can instead _impilicitly_ pass the context around through specification. This implicit propagation would be for specification what AsyncContext is for JavaScript. You can read more details about this approach at ["Web integration for AsyncContext: in-spec context tracking"](https://hackmd.io/@nicolo-ribaudo/HyMrbNopR). While this implicit approach works well in many cases (especially for completion callbacks, where the callback is a direct consequence of the API that has been called), it doesn't work for all events. They will all need to be manually reviewed. ## An incremental approach Due to its need of extensive review, testing, and potential implementation complexity, properly propagating the dispatch context for asynchronous events triggered by JS will require significant time and effort. Propagation of the context for those async events **can be verified and exposed over time**. Those handlers can initially run in the root context, similarly to events caused by outside triggers, and over time start exposing a better context when feasible. This is observable, but being a change from "exposing less info" to "exposing more info" it's likely going to be web-compatible. The way this incremental approach can be implemented in specifications is by adding an optional "propagate asynchronous context" flag to the [fire an event](https://dom.spec.whatwg.org/#concept-event-fire) algorithm, that defaults to false. If there is no JavaScript code on the stack and the flag is not set to true, it will restore the root context before dispatching the event. There are some asynchronous events that will need to properly propagate the context from the beginning: - `postMessage` -> `onmessage` in the same agent, because it's often used as an alternative to `queueMicrotask` (same window would probably be enough, if same agent is too complex to implement?) - `postMessage` -> `onmessage` on a `MessageChannel` whose ports have not been transferred yet - `unhandledrejection` and `error` - events on on `XMLHttpRequest` ([tc39/proposal-async-context#22](https://github.com/tc39/proposal-async-context/issues/22)) - [others?] ## Prior art While we do not _have to_ follow precedent when designing language features, it can at least be a good indication of what the expectation might be. There are two types of precedent we can look at: how do features with similar properties to AsyncContext behave on the web, and the equivalent of AsyncContext behaves in other platforms. ### Similar features on the web There are no user-exposed API that behave similarly to AsyncContext in the standard/cross-browser web plaftorm. However, there are different WICG and Chrome-specific APIs that do: [Prioritized Task Scheduling](https://wicg.github.io/scheduling-apis/), [Task Attribution](https://wicg.github.io/soft-navigations/#sec-task-attribution-intro) and Chrome's [Async Stack Tagging API](https://docs.google.com/document/d/1Yv8qi-1gRuFB8EaQGb79n5GGPtm_ZRrpaigKNsf5g_0/edit?tab=t.0#heading=h.7nki9mck5t64). Rather than having 3-4 features that similarly propagate some data through asynchronous steps, we should try to unify them under a single model. #### Prioritized Task Scheduling The [Prioritized Task Scheduling](https://wicg.github.io/scheduling-apis/) proposal ([MDN](https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#examples)) allows defining some tasks that shuold run with a given priority, and it allows yielding back to the event loop while executing the task: ```javascript scheduler.postTask(async () => { await doSomething(); await scheduler.yield(); await doSomethingElse(); await scheduler.yield(); await doSomethingAgain(); }, { priority: "user-blocking" }) ``` In this example, the `scheduler.yield()` call will yield with the priority `"user-blocking"`, which is tracked across `await`s. When it comes to events, priority is preserved from the dispatch context for synchronous events, and it's lost for asynchronous events and for events with non-JS causes, falling back to the default global priority. #### Task Attribution The [Soft Navigations](https://wicg.github.io/soft-navigations/) proposal allows developers to attribute timing properties to "soft navigations", i.e. same-page navigations that happen through the Navigation API as a consequence of user gesture. The proposal provides, through Task Attribution, a way to track the logic relative to a navigation even accross asynchronous steps: through timers, through queued tasks and through promises. When it comes to event handlers: - synchronous event run in the same task as the code that dispatched them - events triggered by non-JS causes run with a new task root - asynchronous events run in with a new task root, except for `postMessage` which propagates the task to the `message` event handlers #### Async Stack Tagging API Chrome's [Async Stack Tagging API](https://docs.google.com/document/d/1Yv8qi-1gRuFB8EaQGb79n5GGPtm_ZRrpaigKNsf5g_0/edit?tab=t.0#heading=h.7nki9mck5t64) exposes Chrome's async stack traces tracking ability to user code, so that user-defined schedulers can integrate with it. For example, this code: ```javascript function schedule(cb) { const task = console.createTask("schedule"); return () => task.run(cb); } function main() { setTimeout(async function afterTime() { const run = schedule(function logger() { console.trace("Hi!") }); await something; run(); }, 10) } ``` will log a stack trace that contains: ``` logger schedule afterTime setTimeout main ``` even though the actual stack of the `console.trace` call does not contain neither `schedule` nor `main`. These traces are propagated through async/await, through timers and other schedulers. When it comes to events, it behaves exactly like the Task Attribution API above. However, this API special cases `load` and `error`, regardless of their target:, the handlers run with the trace that was active the first time the given callback was registered with `.addEventListener` on the given target. You can read more about it at ["AsyncContext: console.createTask API"](https://hackmd.io/@nicolo-ribaudo/ByJWkPWykx). ### Node.js: AsyncLocalStorage Node.js already implements an API that is very similar to `AsyncContext`, called `AsyncLocalStorage` (it's "async-local storage", and not "async LocalStorage"). You can read more about it in [their documentation](https://nodejs.org/api/async_context.html#class-asynclocalstorage). It is frequently used in Node.js-based web servers to associate data with a given request, and to collect telemetry data. When it comes to events, Node.js behaves as proposed in this document: it uses the dispatch context when available, and it falls back to the root context when not. ### Other languages C# and Dart both have concepts similar to AsyncContext: respectively, AsyncLocal and Zones. Both languages run event handlers in the context where the event was dispatched, falling back to the root context. You can read more about them, with examples ready to be run, at ["AsyncContext: other languages"](https://hackmd.io/@nicolo-ribaudo/BysMnI-1kx). ## Unsolved use case While this approach works perfectly for many of the AsyncContext use cases, it fails when trying to use it to detect which part of code is responsible for some action. Consider this scenario: your web app has two parts developed by two separate teams, and whenever there is an unhandled promise rejection you want to associate it to the corresponding team. You might try to do something like the following, which initially seems to work well: ```javascript function teamOne() { // do something setTimeout(() => { Promise.reject(); // :( }) } function teamTwo() { // ... } const currentTeam = new AsyncContext.Variable(); addEventListener("unhandledrejection", () => { console.log("Rejection from team " + currentTeam.get()); }); currentTeam.run("one", teamOne); currentTeam.run("two", teamTwo); ``` However, as soon as you introduce user interaction events it breaks apart. If Team One rewrites their code as follows, the `currentTeam` variable will have no value when running the `unhandledrejection` callback, because `click` used the root context: ```javascript function teamOne() { button.addEventListener("click", () => { Promise.reject(); // :( }); } ``` A solution to this problem is to allow re-defining a new "root context", which is captured at registration time and that is used in cases where there is no JS dispatch context: ```javascript const currentTeam = new AsyncContext.Variable(); addEventListener("unhandledrejection", () => { console.log("Rejection from team " + currentTeam.get()); }); currentTeam.run("one", () => EventTarget.captureFallbackContext(teamOne) ); currentTeam.run("two", () => EventTarget.captureFallbackContext(teamTwo) ); function teamOne() { button.addEventListener("click", () => { // this listener will never run in the root context: // if possible it will propagate the contex that // dispatched it (e.g. by a .click() call), but if // not it will fallback to the context that was active // when EventTarget.captureFallbackContext was called Promise.reject(); }); } function teamTwo() { // ... } ``` The idea is that `EventTarget.captureFallbackContext` would only be called a small number of times compared to how much `.addEventListener` is used, mostly to define "code regions" while the application is being bootstrapped. Thus, it captures significantly fewer async context snapshots than if we did it every time an event handler is registered, and it's always explicit rather than implicit. If browser internals were written in JavaScript, an implementation would look as follows: <details> <summary><code>EventTarget</code></summary> <style> details pre code { background-color: transparent !important } </style> ```javascript class EventTarget { static #fallbackContext = new AsyncContext.Variable({ defaultValue: new AsyncContext.Snapshot(), }); #callbacks = []; addEventListener(callback) { this.#callbacks.push({ callback, fallbackContext: EventTarget.#fallbackContext.get(), }); } dispatchEvent(event) { this.__browser_internal__dispatchEventInCurrentContext(event); } __browser_internal__dispatchEventInCurrentContext(event) { // Assert: there is some JS code code on the stack, // or if not there is some AsyncContext that was propagated // from the async call that caused this event for (const { callback } of this.#callbacks) { callback(event); } } __browser_internal__dispatchEventInEmptyContext(event) { // Assert: there is no JS code code on the stack, because // sync events always easily propagate their dispatch context for (const { callback, fallbackContext } of this.#callbacks) { fallbackContext.run(() => callback(event)); } } static captureFallbackContext(run) { EventTarget.#fallbackContext.run(new AsyncContext.Snapshot(), run); } } ``` </details> <!-- NOTE: This was a more complex proposal, that also triggered the fallback context for events dispatched from JS but with a context that is not a descendant of the This can be implemented with O(1) complexity for running event listener callbacks, and O(n) complexity for `EventTarget.captureFallbackContext` calls (where "n" is the number of nested `EventTarget.captureFallbackContext` calls). The idea is that `EventTarget.captureFallbackContext` would only be called a small number of times compared to how much `.addEventListener` is used, mostly to define "code regions" while the application is being bootstrapped. Thus, it captures significantly fewer async context snapshots than if we did it every time an event handler is registered, and it's always explicit rather than implicit. If browser internals were written in JavaScript, an implementation would look as follows: <details> <summary><code>EventTarget</code></summary> <style> details pre code { background-color: transparent !important } </style> ```javascript class EventTarget { static #rootContainer = new AsyncContext.Snapshot(); static #containmentStack = new AsyncContext.Variable({ defaultValue: { container: EventTarget.#rootContainer, stack: new ClonableWeakSet([this.#rootContainer]) }, }); #callbacks = []; addEventListener(callback) { this.#callbacks.push({ callback, container: EventTarget.#containmentStack.get().container, }); } dispatchEvent(event) { const containmentStack = EventTarget.#containmentStack.get(); for (const { callback, container } of this.#callbacks) { // O(1) if (EventTarget.#containmentStack.get().stack.has(container)) { callback(event); } else { container.run(() => callback(event)); } } } static containFallbackContext(run) { const container = new AsyncContext.Snapshot(); const oldStack = EventTarget.#containmentStack.get().stack; // O(n) const stack = oldStack.clone().add(container); EventTarget.#containmentStack.run({ container, stack }, run); } } ``` Where `ClonableWeakSet` can be efficiently implemented by browsers that have easy access to a `WeakMap`'s internals (they can just clone a real HashSet by iterating through its contents), but is more difficult to implement in JavaScript: ```javascript class ClonableWeakSet extends WeakSet { #contents = []; #indexes = new WeakMap(); #cleanup = new FinalizationRegistry(() => { if (Math.random() < 0.1) this.#compact(); }); #compact() { let oldIndex = 0, newIndex = 0; while (oldIndex < this.#contents.length) { const obj = this.#contents[oldIndex]?.deref(); if (obj !== undefined) { this.#contents[newIndex] = this.#contents[oldIndex]; this.#indexes.set(obj, newIndex); newIndex++; } oldIndex++; } this.#contents.length = newIndex; } add(value) { super.add(value); if (!this.#indexes.has(value)) { this.#indexes.set(value, this.#contents.length); this.#contents.push(new WeakRef(value)) this.#cleanup.register(value); } return this; } delete(value) { const res = super.delete(value); if (this.#indexes.has(value)) { this.#contents[this.#indexes.has(value)] = null; this.#indexes.delete(value); this.#cleanup.unregister(value); } return res; } clone() { const cloned = new ClonableWeakSet(); this.#contents.forEach(ref => { const obj = ref.deref(); if (obj !== undefined) cloned.add(obj); }); return cloned; } } ``` </details> -->

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully