• Stars
    star
    587
  • Rank 76,145 (Top 2 %)
  • Language
    HTML
  • License
    Creative Commons ...
  • Created over 4 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Async Context for JavaScript

Async Context for JavaScript

Status: Stage 2

Champions:

Motivation

When writing synchronous JavaScript code, a reasonable expectation from developers is that values are consistently available over the life of the synchronous execution. These values may be passed explicitly (i.e., as parameters to the function or some nested function, or as a closed over variable), or implicitly (extracted from the call stack, e.g., outside the scope as a external object that the function or nested function has access to).

function program() {
  const value = { key: 123 };

  // Explicitly pass the value to function via parameters.
  // The value is available for the full execution of the function.
  explicit(value);

  // Explicitly captured by the closure.
  // The value is available for as long as the closure exists.
  const closure = () => {
    assert.equal(value.key, 123);
  };

  // Implicitly propagated via shared reference to an external variable.
  // The value is available as long as the shared reference is set.
  // In this case, for as long as the synchronous execution of the
  // try-finally code.
  try {
    shared = value;
    implicit();
  } finally {
    shared = undefined;
  }
}

function explicit(value) {
  assert.equal(value.key, 123);
}

let shared;
function implicit() {
  assert.equal(shared.key, 123);
}

program();

Async/await syntax improved in ergonomics of writing asynchronous JS. It allows developers to think of asynchronous code in terms of synchronous code. The behavior of the event loop executing the code remains the same as in a promise chain. However, passing code through the event loop loses implicit information from the call site because we end up replacing the call stack. In the case of async/await syntax, the loss of implicit call site information becomes invisible due to the visual similarity to synchronous code -- the only indicator of a barrier is the await keyword. As a result, code that "just works" in synchronous JS has unexpected behavior in asynchronous JS while appearing almost exactly the same.

function program() {
  const value = { key: 123 };

  // Implicitly propagated via shared reference to an external variable.
  // The value is only available only for the _synchronous execution_ of
  // the try-finally code.
  try {
    shared = value;
    implicit();
  } finally {
    shared = undefined;
  }
}

let shared;
async function implicit() {
  // The shared reference is still set to the correct value.
  assert.equal(shared.key, 123);

  await 1;

  // After awaiting, the shared reference has been reset to `undefined`.
  // We've lost access to our original value.
  assert.throws(() => {
    assert.equal(shared.key, 123);
  });
}

program();

The above problem existed already in promise callback-style code, but the introduction of async/await syntax has aggravated it by making the stack replacement almost undetectable. This problem is not generally solvable with user land code alone. For instance, if the call stack has already been replaced by the time the function is called, that function will never have a chance to capture the shared reference.

function program() {
  const value = { key: 123 };

  // Implicitly propagated via shared reference to an external variable.
  // The value is only available only for the _synchronous execution_ of
  // the try-finally code.
  try {
    shared = value;
    setTimeout(implicit, 0);
  } finally {
    shared = undefined;
  }
}

let shared;
function implicit() {
  // By the time this code is executed, the shared reference has already
  // been reset. There is no way for `indirect` to solve this because
  // because the bug is caused (accidentally) by the `program` function.
  assert.throws(() => {
    assert.equal(shared.key, 123);
  });
}

program();

This proposal introduces a general mechanism by which lost implicit call site information can be captured and used across transitions through the event loop, while allowing the developer to write async code largely as they do in cases without implicit information. The goal is to reduce the mental burden currently required for special handling async code in such cases.

Summary

This proposal introduces APIs to propagate a value through asynchronous code, such as a promise continuation or async callbacks.

Non-goals:

  1. Async tasks scheduling and interception.
  2. Error handling & bubbling through async stacks.

Proposed Solution

AsyncContext are designed as a value store for context propagation across logically-connected sync/async code execution.

namespace AsyncContext {
  class Variable<T> {
    constructor(options: AsyncVariableOptions<T>);

    get name(): string;

    run<R>(value: T, fn: (...args: any[])=> R, ...args: any[]): R;

    get(): T | undefined;
  }

  interface AsyncVariableOptions<T> {
    name?: string;
    defaultValue?: T;
  }

  class Snapshot {
    constructor();

    run<R>(fn: (...args: any[]) => R, ...args: any[]): R;
  }
}

Variable.prototype.run() and Variable.prototype.get() sets and gets the current value of an async execution flow. Snapshot allows you to opaquely capture the current value of all Variables and execute a function at a later time with as if those values were still the current values (a snapshot and restore). Note that even with Snapshot, you can only access the value associated with an Variable instance if you have access to that instance.

const asyncVar = new AsyncContext.Variable();

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

function main() {
  // AsyncContext.Variable is maintained through other platform queueing.
  setTimeout(() => {
    console.log(asyncVar.get()); // => 'top'

    asyncVar.run("A", () => {
      console.log(asyncVar.get()); // => 'A'

      setTimeout(() => {
        console.log(asyncVar.get()); // => 'A'
      }, randomTimeout());
    });
  }, randomTimeout());

  // AsyncContext.Variable runs can be nested.
  asyncVar.run("B", () => {
    console.log(asyncVar.get()); // => 'B'

    setTimeout(() => {
      console.log(asyncVar.get()); // => 'B'
    }, randomTimeout());
  });

  // AsyncContext.Variable was restored after the previous run.
  console.log(asyncVar.get()); // => 'top'

  // Captures the state of all AsyncContext.Variable's at this moment.
  const snapshotDuringTop = new AsyncContext.Snapshot();

  asyncVar.run("C", () => {
    console.log(asyncVar.get()); // => 'C'

    // The snapshotDuringTop will restore all AsyncContext.Variable to their snapshot
    // state and invoke the wrapped function. We pass a function which it will
    // invoke.
    snapshotDuringTop.run(() => {
      // Despite being lexically nested inside 'C', the snapshot restored us to
      // to the 'top' state.
      console.log(asyncVar.get()); // => 'top'
    });
  });
}

function randomTimeout() {
  return Math.random() * 1000;
}

Snapshot is useful for implementing APIs that logically "schedule" a callback, so the callback will be called with the context that it logically belongs to, regardless of the context under which it actually runs:

let queue = [];

export function enqueueCallback(cb: () => void) {
  // Each callback is stored with the context at which it was enqueued.
  const snapshot = new AsyncContext.Snapshot();
  queue.push(() => snapshot.run(cb));
}

runWhenIdle(() => {
  // All callbacks in the queue would be run with the current context if they
  // hadn't been wrapped.
  for (const cb of queue) {
    cb();
  }
  queue = [];
});

Note: There are controversial thought on the dynamic scoping and Variable, checkout SCOPING.md for more details.

Use cases

Use cases for async context include:

  • Annotating logs with information related to an asynchronous callstack.

  • Collecting performance information across logical asynchronous threads of control.

  • Web APIs such as Prioritized Task Scheduling.

  • There are a number of use cases for browsers to track the attribution of tasks in the event loop, even though an asynchronous callstack. They include:

    • Optimizing the loading of critical resources in web pages requires tracking whether a task is transitively depended on by a critical resource.

    • Tracking long tasks effectively with the Long Tasks API requires being able to tell where a task was spawned from.

    • Measuring the performance of SPA soft navigations requires being able to tell which task initiated a particular soft navigation.

Hosts are expected to use the infrastructure in this proposal to allow tracking not only asynchronous callstacks, but other ways to schedule jobs on the event loop (such as setTimeout) to maximize the value of these use cases.

A detailed example usecase can be found here

Examples

Determine the initiator of a task

Application monitoring tools like OpenTelemetry save their tracing spans in the AsyncContext.Variable and retrieve the span when they need to determine what started this chain of interaction.

These libraries can not intrude the developer APIs for seamless monitoring. The tracing span doesn't need to be manually passing around by usercodes.

// tracer.js

const asyncVar = new AsyncContext.Variable();
export function run(cb) {
  // (a)
  const span = {
    startTime: Date.now(),
    traceId: randomUUID(),
    spanId: randomUUID(),
  };
  asyncVar.run(span, cb);
}

export function end() {
  // (b)
  const span = asyncVar.get();
  span?.endTime = Date.now();
}
// my-app.js
import * as tracer from "./tracer.js";

button.onclick = (e) => {
  // (1)
  tracer.run(() => {
    fetch("https://example.com").then((res) => {
      // (2)

      return processBody(res.body).then((data) => {
        // (3)

        const dialog = html`<dialog>
          Here's some cool data: ${data} <button>OK, cool</button>
        </dialog>`;
        dialog.show();

        tracer.end();
      });
    });
  });
};

In the example above, run and end don't share same lexical scope with actual code functions, and they are capable of async reentrance thus capable of concurrent multi-tracking.

Transitive task attribution

User tasks can be scheduled with attributions. With AsyncContext.Variable, task attributions are propagated in the async task flow and sub-tasks can be scheduled with the same priority.

const scheduler = {
  asyncVar: new AsyncContext.Variable(),
  postTask(task, options) {
    // In practice, the task execution may be deferred.
    // Here we simply run the task immediately.
    return this.asyncVar.run({ priority: options.priority }, task);
  },
  currentTask() {
    return this.asyncVar.get() ?? { priority: "default" };
  },
};

const res = await scheduler.postTask(task, { priority: "background" });
console.log(res);

async function task() {
  // Fetch remains background priority by referring to scheduler.currentPriority().
  const resp = await fetch("/hello");
  const text = await resp.text();

  scheduler.currentTask(); // => { priority: 'background' }
  return doStuffs(text);
}

async function doStuffs(text) {
  // Some async calculation...
  return text;
}

Prior Arts

zones.js

Zones proposed a Zone object, which has the following API:

class Zone {
  constructor({ name, parent });

  name;
  get parent();

  fork({ name });
  run(callback);
  wrap(callback);

  static get current();
}

The concept of the current zone, reified as Zone.current, is crucial. Both run and wrap are designed to manage running the current zone:

  • z.run(callback) will set the current zone to z for the duration of callback, resetting it to its previous value afterward. This is how you "enter" a zone.
  • z.wrap(callback) produces a new function that essentially performs z.run(callback) (passing along arguments and this, of course).

The current zone is the async context that propagates with all our operations. In our above example, sites (1) through (6) would all have the same value of Zone.current. If a developer had done something like:

const loadZone = Zone.current.fork({ name: "loading zone" });
window.onload = loadZone.wrap(e => { ... });

then at all those sites, Zone.current would be equal to loadZone.

Node.js domain module

Domain's global central active domain can be consumed by multiple endpoints and be exchanged in any time with synchronous operation (domain.enter()). Since it is possible that some third party module changed active domain on the fly and application owner may unaware of such change, this can introduce unexpected implicit behavior and made domain diagnosis hard.

Check out Domain Module Postmortem for more details.

Node.js async_hooks

This is what the proposal evolved from. async_hooks in Node.js enabled async resources tracking for APM vendors. On which Node.js also implemented AsyncLocalStorage.

Chrome Async Stack Tagging API

Frameworks can schedule tasks with their own userland queues. In such case, the stack trace originated from the framework scheduling logic tells only part of the story.

Error: Call stack
  at someTask (example.js)
  at loop (framework.js)

The Chrome Async Stack Tagging API introduces a new console method named console.createTask(). The API signature is as follows:

interface Console {
  createTask(name: string): Task;
}

interface Task {
  run<T>(f: () => T): T;
}

console.createTask() snapshots the call stack into a Task record. And each Task.run() restores the saved call stack and append it to newly generated call stacks.

Error: Call stack
  at someTask (example.js)
  at loop (framework.js)          // <- Task.run
  at async someTask               // <- Async stack appended
  at schedule (framework.js)      // <- console.createTask
  at businessLogic (example.js)

More Repositories

1

proposals

Tracking ECMAScript Proposals
17,177
star
2

ecma262

Status, process, and documents for ECMA-262
HTML
14,437
star
3

proposal-pipeline-operator

A proposal for adding a useful pipe operator to JavaScript.
HTML
7,534
star
4

proposal-pattern-matching

Pattern matching syntax for ECMAScript
HTML
5,498
star
5

proposal-optional-chaining

HTML
4,942
star
6

proposal-type-annotations

ECMAScript proposal for type syntax that is erased - Stage 1
JavaScript
4,252
star
7

proposal-signals

A proposal to add signals to JavaScript.
3,387
star
8

proposal-temporal

Provides standard objects and functions for working with dates and times.
HTML
3,321
star
9

proposal-observable

Observables for ECMAScript
JavaScript
3,058
star
10

proposal-decorators

Decorators for ES6 classes
2,640
star
11

proposal-record-tuple

ECMAScript proposal for the Record and Tuple value types. | Stage 2: it will change!
HTML
2,496
star
12

test262

Official ECMAScript Conformance Test Suite
JavaScript
2,073
star
13

proposal-dynamic-import

import() proposal for JavaScript
HTML
1,863
star
14

proposal-bind-operator

This-Binding Syntax for ECMAScript
1,742
star
15

proposal-class-fields

Orthogonally-informed combination of public and private fields proposals
HTML
1,722
star
16

proposal-async-await

Async/await for ECMAScript
HTML
1,578
star
17

proposal-object-rest-spread

Rest/Spread Properties for ECMAScript
HTML
1,493
star
18

proposal-shadowrealm

ECMAScript Proposal, specs, and reference implementation for Realms
HTML
1,429
star
19

proposal-iterator-helpers

Methods for working with iterators in ECMAScript
HTML
1,307
star
20

proposal-nullish-coalescing

Nullish coalescing proposal x ?? y
HTML
1,232
star
21

proposal-top-level-await

top-level `await` proposal for ECMAScript (stage 4)
HTML
1,083
star
22

proposal-partial-application

Proposal to add partial application to ECMAScript
HTML
1,002
star
23

proposal-do-expressions

Proposal for `do` expressions
HTML
990
star
24

proposal-binary-ast

Binary AST proposal for ECMAScript
961
star
25

agendas

TC39 meeting agendas
JavaScript
952
star
26

proposal-built-in-modules

HTML
891
star
27

proposal-async-iteration

Asynchronous iteration for JavaScript
HTML
857
star
28

proposal-explicit-resource-management

ECMAScript Explicit Resource Management
JavaScript
746
star
29

proposal-set-methods

Proposal for new Set methods in JS
HTML
655
star
30

proposal-string-dedent

TC39 Proposal to remove common leading indentation from multiline template strings
HTML
614
star
31

proposal-operator-overloading

JavaScript
610
star
32

proposal-import-attributes

Proposal for syntax to import ES modules with assertions
HTML
591
star
33

proposal-bigint

Arbitrary precision integers in JavaScript
HTML
561
star
34

ecmascript_simd

SIMD numeric type for EcmaScript
JavaScript
540
star
35

ecma402

Status, process, and documents for ECMA 402
HTML
529
star
36

proposal-slice-notation

HTML
523
star
37

proposal-change-array-by-copy

Provides additional methods on Array.prototype and TypedArray.prototype to enable changes on the array by returning a new copy of it with the change.
HTML
511
star
38

notes

TC39 meeting notes
JavaScript
496
star
39

proposal-class-public-fields

Stage 2 proposal for public class fields in ECMAScript
HTML
489
star
40

proposal-iterator.range

A proposal for ECMAScript to add a built-in Iterator.range()
HTML
483
star
41

proposal-decimal

Built-in exact decimal numbers for JavaScript
HTML
477
star
42

proposal-uuid

UUID proposal for ECMAScript (Stage 1)
JavaScript
463
star
43

proposal-module-expressions

HTML
433
star
44

proposal-throw-expressions

Proposal for ECMAScript 'throw' expressions
JavaScript
425
star
45

proposal-UnambiguousJavaScriptGrammar

413
star
46

proposal-weakrefs

WeakRefs
HTML
409
star
47

proposal-array-grouping

A proposal to make grouping of array items easier
HTML
407
star
48

proposal-error-cause

TC39 proposal for accumulating errors
HTML
380
star
49

proposal-cancelable-promises

Former home of the now-withdrawn cancelable promises proposal for JavaScript
Shell
376
star
50

proposal-ecmascript-sharedmem

Shared memory and atomics for ECMAscript
HTML
374
star
51

proposal-module-declarations

JavaScript Module Declarations
HTML
369
star
52

proposal-first-class-protocols

a proposal to bring protocol-based interfaces to ECMAScript users
352
star
53

proposal-relative-indexing-method

A TC39 proposal to add an .at() method to all the basic indexable classes (Array, String, TypedArray)
HTML
351
star
54

proposal-global

ECMAScript Proposal, specs, and reference implementation for `global`
HTML
346
star
55

proposal-private-methods

Private methods and getter/setters for ES6 classes
HTML
345
star
56

proposal-numeric-separator

A proposal to add numeric literal separators in JavaScript.
HTML
330
star
57

proposal-private-fields

A Private Fields Proposal for ECMAScript
HTML
319
star
58

tc39.github.io

Get involved in specifying JavaScript
HTML
318
star
59

proposal-object-from-entries

TC39 proposal for Object.fromEntries
HTML
318
star
60

proposal-promise-allSettled

ECMAScript Proposal, specs, and reference implementation for Promise.allSettled
HTML
314
star
61

proposal-await.ops

Introduce await.all / await.race / await.allSettled / await.any to simplify the usage of Promises
HTML
310
star
62

proposal-regex-escaping

Proposal for investigating RegExp escaping for the ECMAScript standard
JavaScript
309
star
63

proposal-export-default-from

Proposal to add `export v from "mod";` to ECMAScript.
HTML
306
star
64

proposal-logical-assignment

A proposal to combine Logical Operators and Assignment Expressions
HTML
302
star
65

proposal-promise-finally

ECMAScript Proposal, specs, and reference implementation for Promise.prototype.finally
HTML
279
star
66

proposal-json-modules

Proposal to import JSON files as modules
HTML
272
star
67

proposal-asset-references

Proposal to ECMAScript to add first-class location references relative to a module
270
star
68

proposal-cancellation

Proposal for a Cancellation API for ECMAScript
HTML
267
star
69

proposal-promise-with-resolvers

HTML
255
star
70

proposal-string-replaceall

ECMAScript proposal: String.prototype.replaceAll
HTML
253
star
71

proposal-export-ns-from

Proposal to add `export * as ns from "mod";` to ECMAScript.
HTML
242
star
72

proposal-structs

JavaScript Structs: Fixed Layout Objects
230
star
73

proposal-ses

Draft proposal for SES (Secure EcmaScript)
HTML
223
star
74

proposal-intl-relative-time

`Intl.RelativeTimeFormat` specification [draft]
HTML
215
star
75

proposal-json-parse-with-source

Proposal for extending JSON.parse to expose input source text.
HTML
214
star
76

proposal-flatMap

proposal for flatten and flatMap on arrays
HTML
214
star
77

proposal-defer-import-eval

A proposal for introducing a way to defer evaluate of a module
HTML
208
star
78

ecmarkup

An HTML superset/Markdown subset source format for ECMAScript and related specifications
TypeScript
201
star
79

proposal-promise-any

ECMAScript proposal: Promise.any
HTML
200
star
80

proposal-optional-chaining-assignment

`a?.b = c` proposal
186
star
81

proposal-decorators-previous

Decorators for ECMAScript
HTML
184
star
82

proposal-smart-pipelines

Old archived draft proposal for smart pipelines. Go to the new Hack-pipes proposal at js-choi/proposal-hack-pipes.
HTML
181
star
83

proposal-array-from-async

Draft specification for a proposed Array.fromAsync method in JavaScript.
HTML
178
star
84

proposal-upsert

ECMAScript Proposal, specs, and reference implementation for Map.prototype.upsert
HTML
176
star
85

proposal-collection-methods

HTML
171
star
86

proposal-array-filtering

A proposal to make filtering arrays easier
HTML
171
star
87

proposal-ptc-syntax

Discussion and specification for an explicit syntactic opt-in for Tail Calls.
HTML
169
star
88

proposal-extractors

Extractors for ECMAScript
JavaScript
166
star
89

proposal-error-stacks

ECMAScript Proposal, specs, and reference implementation for Error.prototype.stack / System.getStack
HTML
166
star
90

proposal-intl-duration-format

164
star
91

how-we-work

Documentation of how TC39 operates and how to participate
161
star
92

proposal-Array.prototype.includes

Spec, tests, reference implementation, and docs for ESnext-track Array.prototype.includes
HTML
157
star
93

proposal-promise-try

ECMAScript Proposal, specs, and reference implementation for Promise.try
HTML
154
star
94

proposal-extensions

Extensions proposal for ECMAScript
HTML
150
star
95

proposal-hashbang

#! for JS
HTML
148
star
96

proposal-import-meta

import.meta proposal for JavaScript
HTML
146
star
97

proposal-intl-segmenter

Unicode text segmentation for ECMAScript
HTML
146
star
98

proposal-resizablearraybuffer

Proposal for resizable array buffers
HTML
145
star
99

proposal-seeded-random

Proposal for an options argument to be added to JS's Math.random() function, and some options to start it with.
HTML
143
star
100

eshost

A uniform wrapper around a multitude of ECMAScript hosts. CLI: https://github.com/bterlson/eshost-cli
JavaScript
142
star