Web Locks API

Editor’s Draft,

This version:
https://wicg.github.io/web-locks/
Test Suite:
https://github.com/web-platform-tests/wpt/tree/master/web-locks
Issue Tracking:
GitHub
Inline In Spec
Editor:
(Google Inc.)

Abstract

This document defines a web platform API that allows script to asynchronously acquire a lock over a resource, hold it while work is performed, then release it. While held, no other script in the origin can aquire a lock over the same resource. This allows contexts (windows, workers) within a web application to coordinate the usage of resources.

Status of this document

This specification was published by the Web Platform Incubator Community Group. It is not a W3C Standard nor is it on the W3C Standards Track. Please note that under the W3C Community Contributor License Agreement (CLA) there is a limited opt-out and other conditions apply. Learn more about W3C Community and Business Groups.

logo

1. Introduction

This section is non-normative.

A lock request is made by script for a particular resource name and mode. A scheduling algorithm looks at the state of current and previous requests, and eventually grants a lock request. A lock is a granted request; it has a resource name and mode. It is represented as an object returned to script. As long as the lock is held it may prevent other lock requests from being granted (depending on the name and mode). A lock can be released by script, at which point it may allow other lock requests to be granted.

The API provides optional functionality that may be used as needed, including:

Cooperative coordination takes place within the scope of same-origin agents; this may span multiple agent clusters.

1.1. Usage Overview

The API is used as follows:

  1. The lock is requested.

  2. Work is done while holding the lock in an asynchronous task.

  3. The lock is automatically released when the task completes.

1.2. Motivating Use Cases

A web-based document editor stores state in memory for fast access and persists changes (as a series of records) to a storage API such as the Indexed Database API for resiliency and offline use, and to a server for cross-device use. When the same document is opened for editing in two tabs the work must be coordinated across tabs, such as allowing only one tab to make changes to or synchronize the document at a time. This requires the tabs to coordinate on which will be actively making changes (and synchronizing the in-memory state with the storage API), knowing when the active tab goes away (navigated, closed, crashed) so that another tab can become active.

In a data synchronization service, a "master tab" is designated. This tab is the only one that should be performing some operations (e.g. network sync, cleaning up queued data, etc). It holds a lock and never releases it. Other tabs can attempt to acquire the lock, and such attempts will be queued. If the "master tab" crashes or is closed then one of the other tabs will get the lock and become the new master.

The Indexed Database API defines a transaction model allowing shared read and exclusive write access across multiple named storage partitions within an origin. Exposing this concept as a primitive allows any Web Platform activity to be scheduled based on resource availability, for example allowing transactions to be composed for other storage types (such as Caches [Service-Workers]), across storage types, even across non-storage APIs (e.g. network fetches).

2. Concepts

For the purposes of this specification:

A user agent has an associated lock task queue which is the result of starting a new parallel queue.

2.1. Resources Names

A resource name is a JavaScript string chosen by the web application to represent an abstract resource.

A resource name has no external meaning beyond the scheduling algorithm, but is global across browsing contexts within an origin. Web applications are free to use any resource naming scheme.

Resource names starting with U+002D HYPHEN-MINUS (-) are reserved; requesting these will cause an exception.

2.2. Lock Managers

A user agent has a lock manager for each origin, which encapsulates the state of all locks and lock requests for that origin.

Pages and workers (agents) on a single origin opened in the same user agent share a lock manager even if they are in unrelated browsing contexts.

2.3. Modes and Scheduling

A mode is either "exclusive" or "shared". Modes can be used to model the common readers-writer lock pattern. If an "exclusive" lock is held, then no other locks with that name can be granted. If a "shared" lock is held, other "shared" locks with that name can be granted — but not any "exclusive" locks. The default mode in the API is "exclusive".

Additional properties may influence scheduling, such as timeouts, fairness, and so on.

2.4. Locks

A lock represents exclusive access to a shared resource.

A lock has an associated agent which is an agent.

A lock has an associated clientId which is an opaque string.

A lock has an associated origin which is an origin.

A lock has an associated name which is a resource name.

A lock has an associated mode which is one of "exclusive" or "shared".

A lock has an associated waiting promise which is a Promise.

A lock has an associated released promise which is a Promise.

Each origin has an associated held lock set which is an ordered set of locks.

When lock lock’s waiting promise settles (fulfills or rejects), enqueue the following steps on the lock task queue:

  1. Release the lock lock.

  2. Resolve lock’s released promise with lock’s waiting promise.

2.5. Lock Requests

A lock request represents a pending request for a lock.

A lock request is a tuple of (agent, clientId, origin, name, mode, promise).

Each origin has an associated lock request queue, which is a queue of lock requests.

A lock request request is said to be grantable if the following steps return true:

  1. Let origin be request’s origin.

  2. Let queue be origin’s lock request queue

  3. Let held be origin’s held lock set

  4. Let mode be request’s associated mode

  5. Let name be request’s associated name

  6. If mode is "exclusive", then return true if all of the following conditions are true, and false otherwise:

    • No lock in held has a name that equals name

    • No lock request in queue earlier than request has a name that equals name.

  7. Otherwise, mode is "shared"; return true if all of the following conditions are true, and false otherwise:

2.6. Agent Integration

When an agent terminates, enqueue the following steps on the lock task queue:
  1. For each lock request request with agent equal to the terminating agent:

    1. Abort the request request.

  2. For each lock lock with agent equal to the terminating agent:

    1. Release the lock lock.

3. API

[SecureContext]
interface mixin NavigatorLocks {
  readonly attribute LockManager locks;
};
Navigator includes NavigatorLocks;
WorkerNavigator includes NavigatorLocks;

Each environment settings object has an associated LockManager object.

The locks attribute’s getter must return the context object's relevant settings object's LockManager object.

3.2. LockManager class

[SecureContext, Exposed=(Window,Worker)]
interface LockManager {
  Promise<any> request(DOMString name,
                       LockGrantedCallback callback);
  Promise<any> request(DOMString name,
                       LockOptions options,
                       LockGrantedCallback callback);

  Promise<LockManagerSnapshot> query();
};

callback LockGrantedCallback = Promise<any> (Lock? lock);

enum LockMode { "shared", "exclusive" };

dictionary LockOptions {
  LockMode mode = "exclusive";
  boolean ifAvailable = false;
  boolean steal = false;
  AbortSignal signal;
};

dictionary LockManagerSnapshot {
  sequence<LockInfo> held;
  sequence<LockInfo> pending;
};

dictionary LockInfo {
  DOMString name;
  LockMode mode;
  DOMString clientId;
};

A LockManager instance allows script to make lock requests and query the state of the origin’s lock manager.

3.2.1. The request() method

promise = navigator . locks . request(name, callback)
promise = navigator . locks . request(name, options, callback)

The request() method is called to request a lock.

The name (initial argument) is a resource name string.

The callback (final argument) is a callback function invoked with the Lock when granted. This is specified by script, and is usually an async function. The lock is held until the callback function completes. If a non-async callback function is passed in, then it is automatically wrapped in a promise that resolves immediately, so the lock is only held for the duration of the synchronous callback.

The returned promise resolves (or rejects) with the result of the callback after the lock is released, or rejects if the request is aborted.

Example:

try {
  const result = await navigator.locks.request('resource', async lock => {
    // The lock is held here.
    await do_something();
    await do_something_else();
    return "ok";
    // The lock will be released now.
  });
  // |result| has the return value of the callback.
} catch (ex) {
  // if the callback threw, it will be caught here.
}

The lock will be released when the callback exits for any reason — either when the code returns, or if it throws.

An options dictionary can be specified as a second argument; the callback argument is always last.

options . mode

The mode option can be "exclusive" (the default if not specified) or "shared". Multiple tabs/workers can hold a lock for the same resource in "shared" mode, but only one tab/worker can hold a lock for the resource in "exclusive" mode.

The most common use for this is to allow multiple readers to access a resource simultaneously but prevent changes. Once reader locks are released a single exclusive writer can acquire the lock to make changes, followed by another exclusive writer or more shared readers.

await navigator.locks.request('resource', {mode: 'shared'}, async lock => {
  // Lock is held here. Other contexts might also hold the lock in shared mode,
  // but no other contexts will hold the lock in exclusive mode.
});
options . ifAvailable

If the ifAvailable option is true, then the lock is only granted if it can be without additional waiting. Note that this is still not synchronous; in many user agents this will require cross-process communication to see if the lock can be granted. If the lock cannot be granted, the callback is invoked with null. (Since this is expected, the request is not rejected.)

await navigator.locks.request('resource', {ifAvailable: true}, async lock => {
  if (!lock) {
    // Didn’t get it. Maybe take appropriate action.
    return;
  }
  // Lock is held here.
});
options . signal

The signal option can be set to an AbortSignal. This allows aborting a lock request, for example if the request is not granted in a timely manner:

const controller = new AbortController();
setTimeout(() => controller.abort(), 200); // Wait at most 200ms.

try {
  await navigator.locks.request(
    'resource', {signal: controller.signal}, async lock => {
      // Lock is held here.
  });
  // Done with lock here.
} catch (ex) {
  // |ex| will be a DOMException with error name "AbortError" if timer fired.
}

If an abort is signalled before the lock is granted, then the request promise will reject with an AbortError. Once the lock has been granted, the signal is ignored.

options . steal
If the steal option is true, then any held locks for the resource will be released (and the released promise of such locks will resolve with AbortError), and the request will be granted, preempting any queued requests for it.

If a web application detects an unrecoverable state — for example, some coordination point like a Service Worker determines that a tab holding a lock is no longer responding — then it can "steal" a lock using this option.

The request(name, callback) and request(name, options, callback) methods, when invoked, must run these steps:

  1. Let promise be a new promise.

  2. If options was not passed, then let options be a new LockOptions dictionary with default members.

  3. Let environment be context object's relevant settings object.

  4. Let origin be environment’s origin.

  5. If origin is an opaque origin, then reject promise with a "SecurityError" DOMException.

  6. Otherwise, if name starts with U+002D HYPHEN-MINUS (-), then reject promise with a "NotSupportedError" DOMException.

  7. Otherwise, if both optionssteal dictionary member and option’s ifAvailable dictionary member are true, then reject promise with a "NotSupportedError" DOMException.

  8. Otherwise, if optionssteal dictionary member is true and option’s mode dictionary member is not "exclusive", then reject promise with a "NotSupportedError" DOMException.

  9. Otherwise, if option’s signal dictionary member is present, and either of optionssteal dictionary member or optionsifAvailable dictionary member is true, then reject promise with a "NotSupportedError" DOMException.

  10. Otherwise, if optionssignal dictionary member is present and its aborted flag is set, then reject promise with an "AbortError" {{DOMException}.

  11. Otherwise, run these steps:

    1. Let request be the result of running the steps to request a lock with promise, the current agent, environment’s id, origin, callback, name, optionsmode dictionary member, optionsifAvailable dictionary member, and optionssteal dictionary member.

    2. If optionssignal dictionary member is present, then add the following abort steps to optionssignal dictionary member:

      1. Enqueue the steps to abort the request request to the lock task queue.

      2. Reject promise with an "AbortError" DOMException.

  12. Return promise.

3.2.2. The query() method

state = await navigator . locks . query()

The query() method can be used to produce a snapshot of the lock manager state for an origin, which allows a web application to introspect its usage of locks, for logging or debugging purposes.

The returned promise resolves to state, a plain-old-data structure (i.e. JSON-like data) with this form:

{
  held: [
    { name: "resource1", mode: "exclusive",
      clientId: "8b1e730c-7405-47db-9265-6ee7c73ac153" },
    { name: "resource2", mode: "shared",
      clientId: "8b1e730c-7405-47db-9265-6ee7c73ac153" },
    { name: "resource2", mode: "shared",
      clientId: "fad203a5-1f31-472b-a7f7-a3236a1f6d3b" },
  ],
  pending: [
    { name: "resource1", mode: "exclusive",
      clientId: "fad203a5-1f31-472b-a7f7-a3236a1f6d3b" },
    { name: "resource1", mode: "exclusive",
      clientId: "d341a5d0-1d8d-4224-be10-704d1ef92a15" },
  ]
}

The clientId field corresponds to a unique context (frame or worker), and is the same value returned by Client's id attribute.

The query() method, when invoked, must run these steps:

  1. Let promise be a new promise.

  2. Let origin be context object's relevant settings object's origin.

  3. If origin is an opaque origin, then reject promise with a "SecurityError" DOMException and abort these steps.

  4. Otherwise, enqueue the steps to snapshot the lock state for origin with promise to the lock task queue.

  5. Return promise.

3.3. Lock class

[SecureContext, Exposed=(Window,Worker)]
interface Lock {
  readonly attribute DOMString name;
  readonly attribute LockMode mode;
};

A Lock object has an associated lock.

The name attribute getter returns the associated name of the lock.

The mode attribute getter returns the associated mode of the lock.

4. Algorithms

4.1. Request a lock

To request a lock with promise, agent, clientId, origin, callback, name, mode, ifAvailable, steal, and optional signal:
  1. Let request be a new lock request (agent, clientId, origin, name, mode, promise).

  2. Enqueue the following steps to the lock task queue:

  3. Let queue be origin’s lock request queue.

  4. Let held be origin’s held lock set.

  5. If steal is true, then run these steps:

    1. For each lock of held:

      1. If lock’s name is name, then run these steps:

        1. Remove lock from held.

        2. Reject lock’s released promise with an "AbortError" DOMException.

    2. Prepend request in origin’s lock request queue.

  6. Otherwise, run these steps:

    1. If ifAvailable is true and request is not grantable, then enqueue the following steps on callback’s relevant settings object's responsible event loop:

      1. Let r be the result of invoking callback with null as the only argument.

      2. Resolve promise with r and abort these steps.

    2. Enqueue request in origin’s lock request queue.

  7. Process the lock request queue for origin.

  8. Return request.

4.2. Release a lock

To release the lock lock:
  1. Assert: these steps are running on the lock task queue.

  2. Let origin be lock’s origin.

  3. Remove lock from the origin’s held lock set.

  4. Process the lock request queue for origin.

4.3. Abort a request

To abort the request request:
  1. Assert: these steps are running on the lock task queue.

  2. Let origin be request’s origin.

  3. Remove request from origin’s lock request queue.

  4. Process the lock request queue for origin.

4.4. Process a lock request queue

To process the lock request queue for origin:
  1. Assert: these steps are running on the lock task queue.

  2. Let queue be origin’s lock request queue.

  3. For each request of queue:

    1. If request is grantable, then run these steps:

      1. Remove request from queue.

      2. Let agent be request’s agent

      3. Let clientId be request’s clientId.

      4. Let name be request’s name.

      5. Let mode be request’s mode.

      6. Let p be request’s promise.

      7. Let waiting be a new Promise.

      8. Let lock be a new lock with agent agent, clientId clientId, origin origin, mode mode, name name, released promise p, and waiting promise waiting.

      9. Append lock to origin’s held lock set.

      10. Enqueue the following steps on callback’s relevant settings object's responsible event loop:

        1. Let r be the result of invoking callback with a new Lock object associated with lock as the only argument.

        2. Resolve waiting with r.

4.5. Snapshot the lock state

To snapshot the lock state for origin with promise:
  1. Assert: these steps are running on the lock task queue.

  2. Let pending be a new list.

  3. For each request of origin’s lock request queue:

    1. Let info be a new LockInfo dictionary.

    2. Set info’s name dictionary member to request’s name.

    3. Set info’s mode dictionary member to request’s mode.

    4. Set info’s clientId dictionary member to request’s clientId.

    5. Append info to pending.

  4. Let held be a new list.

  5. For each lock of origin’s held lock set:

    1. Let info be a new LockInfo dictionary.

    2. Set info’s name dictionary member to lock’s name.

    3. Set info’s mode dictionary member to lock’s mode.

    4. Set info’s clientId dictionary member to lock’s clientId.

    5. Append info to held.

  6. Let snapshot be a new LockManagerSnapshot dictionary.

  7. Set snapshot’s held dictionary member to held.

  8. Set snapshot’s pending dictionary member to pending.

  9. Resolve promise with snapshot.

5. Usage Considerations

This section is non-normative.

5.1. Deadlocks

Deadlocks are a concept in concurrent computing, and deadlocks scoped to a particular lock manager can be introduced by this API.

Preventing deadlocks requires care. One approach is to always acquire multiple locks in a strict order.

6. Security and Privacy Considerations

6.1. Lock Scope

The definition of a lock manager's scope is important as it defines a privacy boundary. Locks can be used as an ephemeral state retention mechanism and, like storage APIs, can be used as a communication mechanism, and must be no more privileged than storage facilities. User agents that impose finer granularity on one of these services must impose it on others; for example, a user agent that exposes different storage partitions to a top-level page (first-party) and a cross-origin iframe (third-party) in the same origin for privacy reasons must similarly partition locking.

This also provides reasonable expectations for web application authors; if a lock is acquired over a storage resource, all same-origin browsing contexts must observe the same state.

6.2. Private Browsing

Every private mode browsing session is considered a separate user agent for the purposes of this API. That is, locks requested/held outside such a session have no affect on requested/held inside such a session, and vice versa. This prevents a website from determining that a session is "incognito" while also not allowing a communication mechanism between such sessions.

6.3. Implementation Risks

Implementations must ensure that locks do not span origins. Failure to do so would provide a side-channel for communication between script running in two origins, or allow one script in one origin to disrupt the behavior of another (e.g. denying service).

6.4. Checklist

The W3C TAG has developed a Self-Review Questionnaire: Security and Privacy for editors of specifications to informatively answer. Revisiting the questions here:

7. Acknowledgements

Many thanks to Alex Russell, Anne van Kesteren, Boris Zbarsky, Darin Fisher, Domenic Denicola, Gus Caplan, Harald Alvestrand, Jake Archibald, L. David Baron, Luciano Pacheco, Marcos Caceres, Ralph Chelala, Raymond Toy, Ryan Fioravanti, and Victor Costan for helping craft this proposal.

Special thanks to Tab Atkins, Jr. for creating and maintaining Bikeshed, the specification authoring tool used to create this document, and for his general authoring advice.

Conformance

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[DOM]
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/
[HTML]
Anne van Kesteren; et al. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[INFRA]
Anne van Kesteren; Domenic Denicola. Infra Standard. Living Standard. URL: https://infra.spec.whatwg.org/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[WebIDL]
Cameron McCormack; Boris Zbarsky; Tobie Langel. Web IDL. 15 December 2016. ED. URL: https://heycam.github.io/webidl/

Informative References

[IndexedDB-2]
Ali Alabbas; Joshua Bell. Indexed Database API 2.0. 30 January 2018. REC. URL: https://www.w3.org/TR/IndexedDB-2/
[Service-Workers]
Alex Russell; et al. Service Workers 1. 2 November 2017. WD. URL: https://www.w3.org/TR/service-workers-1/
[Storage]
Anne van Kesteren. Storage Standard. Living Standard. URL: https://storage.spec.whatwg.org/

IDL Index

[SecureContext]
interface mixin NavigatorLocks {
  readonly attribute LockManager locks;
};
Navigator includes NavigatorLocks;
WorkerNavigator includes NavigatorLocks;

[SecureContext, Exposed=(Window,Worker)]
interface LockManager {
  Promise<any> request(DOMString name,
                       LockGrantedCallback callback);
  Promise<any> request(DOMString name,
                       LockOptions options,
                       LockGrantedCallback callback);

  Promise<LockManagerSnapshot> query();
};

callback LockGrantedCallback = Promise<any> (Lock? lock);

enum LockMode { "shared", "exclusive" };

dictionary LockOptions {
  LockMode mode = "exclusive";
  boolean ifAvailable = false;
  boolean steal = false;
  AbortSignal signal;
};

dictionary LockManagerSnapshot {
  sequence<LockInfo> held;
  sequence<LockInfo> pending;
};

dictionary LockInfo {
  DOMString name;
  LockMode mode;
  DOMString clientId;
};

[SecureContext, Exposed=(Window,Worker)]
interface Lock {
  readonly attribute DOMString name;
  readonly attribute LockMode mode;
};

Issues Index

Migrate this definition to [HTML] or [Storage] so it can be referenced by other standards.
Normative reference for terminates.