1. 11 ワークレット
    1. 11.1 導入
      1. 11.1.1 動機
      2. 11.1.2 コードの冪等性
      3. 11.1.3 投機的評価
    2. 11.2 例
      1. 11.2.1 スクリプトの読み込み
      2. 11.2.2 クラスの登録およびそのメソッドの呼び出し
    3. 11.3 インフラ
      1. 11.3.1 グローバルスコープ
        1. 11.3.1.1 エージェントおよびイベントループ
        2. 11.3.1.2 作成および終了
        3. 11.3.1.3 ワークレットのスクリプト設定
      2. 11.3.2 Workletクラス
      3. 11.3.3 ワークレットの存続期間

11 ワークレット

11.1 導入

この節は非規範的である。

ワークレットは、特定の実装モデルを必要とせずに、メインのJavaScript実行環境から独立してスクリプトを実行するために使用できる仕様のインフラの一部である。

ここで指定したワークレットインフラは、ウェブ開発者が直接使用することはできない。その代わりに、他の仕様はそのワークレットインフラに基づいて構築され、ブラウザー実装パイプラインの特定の部分で実行するために特化された、直接使用可能なワークレットタイプを作成する。

11.1.1 動機

この節は非規範的である。

レンダリング、または音声出力などの実装パイプラインのその他の機微な部分に拡張ポイントを許可することは困難である。拡張ポイントがWindow上で利用可能なAPIへの完全なアクセスを伴う形で設けられるなら、エンジンは、それらのフェーズの途中で何が起こり得るかについて従来保持していた前提を放棄する必要がある。例えば、レイアウトフェーズ中、レンダリングエンジンはDOMが変更されないと想定する。

さらに、Window環境で拡張ポイントを定義すると、ユーザーエージェントはWindowオブジェクトと同じスレッドで作業を実行するよう制限される。(ただし、実装がスレッドセーフなAPIを可能にする複雑でオーバーヘッドの大きいインフラと、スレッドのjoinに関する保証を追加する場合は除く。)

ワークレットは、ユーザーエージェントが現在依存している保証を維持しながら、拡張ポイントを可能にするよう設計されている。これは、WorkletGlobalScopeのサブクラスに基づく新しいグローバル環境を通じて実現される。

ワークレットはウェブワーカーに類似している。ただし、次の点が異なる:

ワークレットは比較的オーバーヘッドが大きいため、控えめに使用するのが最善である。このため、与えられたWorkletGlobalScopeは複数の個別のスクリプト間で共有されることが想定されている。(これは、単一のWindowが複数の個別のスクリプト間で共有される方法に類似している。)

ワークレットは、さまざまなユースケースに対応する汎用技術である。CSS Painting APIで定義されているものなど、一部のワークレットは、ステートレスで、冪等で、短時間で実行される計算を対象とする拡張ポイントを提供しており、これらには次のいくつかの節で説明する特別な考慮事項がある。一方、Web Audio APIで定義されているものなど、その他のものは、ステートフルで長時間実行される操作に使用される。[CSSPAINT] [WEBAUDIO]

11.1.2 コードの冪等性

ワークレットを使用する一部の仕様は、ユーザーエージェントが複数のスレッドにわたって作業を並列化すること、または必要に応じてスレッド間で作業を移動したりできるようにすることを意図している。これらの仕様では、ユーザーエージェントは、ウェブ開発者が提供したクラス上のメソッドを実装定義の順序で呼び出す場合がある。

その結果、相互運用性の問題を防ぐために、そのようなWorkletGlobalScopeにクラスを登録する著者は、コードを冪等にすべきである。つまり、そのクラス上のメソッドまたはメソッド群は、特定の入力が与えられた場合に同じ出力を生成すべきである。

この仕様は、著者が冪等な方法でコードを記述するよう促すために、次のテクニックを使用する:

これらの制限は共に、2つの異なるスクリプトがグローバルオブジェクトのプロパティを使用して状態を共有することを防ぐ助けとなる。

さらに、ワークレットを使用し、実装定義の動作を許可することを意図する仕様は、次の要件に従わなければならない:

11.1.3 投機的評価

ワークレットを使用する一部の仕様は、ユーザーエージェントの状態に基づいて、ウェブ開発者が提供したクラス上のメソッドを呼び出すことができる。スレッド間の並行性を高めるため、ユーザーエージェントは、将来起こり得る状態に基づいて、メソッドを投機的に呼び出してもよい。

これらの仕様では、ユーザーエージェントは、現在のユーザーエージェントの状態に対応する引数だけでなく、任意の引数を使用して、任意の時点でそのようなメソッドを呼び出す場合がある。このような投機的評価の結果は、直ちには表示されないが、ユーザーエージェントの状態が予測された状態と一致した場合に使用できるよう、キャッシュされることがある。これにより、ユーザーエージェントとワークレットのスレッド間の並行性を高めることができる。

その結果、ユーザーエージェント間の相互運用性のリスクを防ぐために、そのようなWorkletGlobalScopeにクラスを登録する著者は、コードをステートレスにすべきである。つまり、メソッドを呼び出すことの唯一の効果はその結果であるべきであり、可変状態の更新などの副作用であってはならない。

コードの冪等性を促進する同じテクニックは、著者がステートレスなコードを記述することも促進する。

11.2 例

この節は非規範的である。

これらの例では、偽ワークレットを使用する。Windowオブジェクトは2つのWorkletインスタンスを提供し、それぞれが独自のFakeWorkletGlobalScopeの集合内でコードを実行する:

partial interface Window {
  [SameObject, SecureContext] readonly attribute Worklet fakeWorklet1;
  [SameObject, SecureContext] readonly attribute Worklet fakeWorklet2;
};

それぞれのWindowには2つのWorkletインスタンス、偽ワークレット1と偽ワークレット2がある。これらはいずれも、ワークレットのグローバルスコープ型がFakeWorkletGlobalScopeに設定され、ワークレットの宛先型が"fakeworklet"に設定されている。ユーザーエージェントは、各ワークレットにつき少なくとも2つのFakeWorkletGlobalScopeインスタンスを作成すべきである。

"fakeworklet"は、実際にはFetchにおける有効な宛先ではない。しかし、これは、実際のワークレットが一般に、それぞれのワークレット型に固有の宛先を持つことを示している。[FETCH]

The fakeWorklet1 getter steps are to return this's fake worklet 1.

The fakeWorklet2 getter steps are to return this's fake worklet 2.


[Global=(Worklet,FakeWorklet),
 Exposed=FakeWorklet,
 SecureContext]
interface FakeWorkletGlobalScope : WorkletGlobalScope {
  undefined registerFake(DOMString type, Function classConstructor);
};

Each FakeWorkletGlobalScope has a registered class constructors map, which is an ordered map, initially empty.

The registerFake(type, classConstructor) method steps are to set this's registered class constructors map[type] to classConstructor.

11.2.1 スクリプトの読み込み

この節は非規範的である。

偽ワークレット1にスクリプトを読み込むため、ウェブ開発者は次のように記述する:

window.fakeWorklet1.addModule('script1.mjs');
window.fakeWorklet1.addModule('script2.mjs');

どちらのスクリプトのフェッチが先に完了し、最初に実行されるかはネットワークのタイミングに依存することに注意する。それはscript1.mjsまたはscript2.mjsのいずれかであり得る。これは一般に、投機的評価への準備に関する提案に従っている場合、ワークレットへの読み込みを意図して適切に記述されたスクリプトでは問題にならない。

ウェブ開発者が、スクリプトが正常に実行され、いくつかのワークレットに読み込まれた後にのみタスクを実行したい場合、次のように記述できる:

Promise.all([
    window.fakeWorklet1.addModule('script1.mjs'),
    window.fakeWorklet2.addModule('script2.mjs')
]).then(() => {
    // Do something which relies on those scripts being loaded.
});

スクリプトの読み込みに関するもう1つの重要な点は、コードの冪等性に関する節で説明したとおり、読み込まれたスクリプトは1つのWorkletにつき複数のWorkletGlobalScopeで実行され得ることである。特に、偽ワークレット1および偽ワークレット2に関する上記の仕様は、これを要求する。そこで、次のようなシナリオを考える:

// script.mjs
console.log("Hello from a FakeWorkletGlobalScope!");
// app.mjs
window.fakeWorklet1.addModule("script.mjs");

これにより、ユーザーエージェントのコンソールに次のような出力が生じることがある:

[fakeWorklet1#1] Hello from a FakeWorkletGlobalScope!
[fakeWorklet1#4] Hello from a FakeWorkletGlobalScope!
[fakeWorklet1#2] Hello from a FakeWorkletGlobalScope!
[fakeWorklet1#3] Hello from a FakeWorkletGlobalScope!

ユーザーエージェントがある時点で、FakeWorkletGlobalScopeの3番目のインスタンスを強制終了して再起動することを決定した場合、その際、コンソールには再び[fakeWorklet1#3] Hello from a FakeWorkletGlobalScope!が出力される。

11.2.2 クラスの登録およびそのメソッドの呼び出し

この節は非規範的である。

ウェブ開発者による偽ワークレットの意図された使用法の1つが、ブール否定という非常に複雑なプロセスをカスタマイズできるようにすることであるとする。ウェブ開発者は、そのカスタマイズを次のように登録する場合がある:

// script.mjs
registerFake('negation-processor', class {
  process(arg) {
    return !arg;
  }
});
// app.mjs
window.fakeWorklet1.addModule("script.mjs");

To make use of such registered classes, the specification for fake worklets could define a find the opposite of true algorithm, given a Worklet worklet:

  1. Optionally, create a worklet global scope for worklet.

  2. Let workletGlobalScope be one of worklet's global scopes, chosen in an implementation-defined manner.

  3. Let classConstructor be workletGlobalScope's registered class constructors map["negation-processor"].

  4. Let classInstance be the result of constructing classConstructor, with no arguments.

  5. Let function be Get(classInstance, "process"). 例外を再度投げる。

  6. Let callback be the result of converting function to a Web IDL Function instance.

  7. Return the result of invoking callback with « true » and "rethrow", and with callback this value set to classInstance.

Another, perhaps better, specification architecture would be to extract the "process" property and convert it into a Function at registration time, as part of the registerFake() method steps.

11.3 インフラ

11.3.1 グローバルスコープ

WorkletGlobalScopeのサブクラスは、特定のWorkletに読み込まれたコードを実行できるグローバルオブジェクトを作成するために使用される。

[Exposed=Worklet, SecureContext]
interface WorkletGlobalScope {};

他の仕様は、WorkletGlobalScopeをサブクラス化し、クラスを登録するためのAPIおよび、それぞれのワークレット型に固有のその他のAPIを追加することを意図している。

Each WorkletGlobalScope has an associated module map. It is a module map, initially empty.

11.3.1.1 エージェントおよびイベントループ

この節は非規範的である。

各WorkletGlobalScopeは、それぞれ独自のワークレットエージェントに含まれており、そのエージェントには対応するイベントループがある。しかし、実際には、これらのエージェントおよびイベントループの実装は、他の大半のものとは異なると想定されている。

理論上、実装はWorkletGlobalScopeの各インスタンスに個別のスレッドを使用でき、このレベルの並列性を可能にするにはエージェントを使用するのが最適であるため、各WorkletGlobalScopeに対してワークレットエージェントが存在する。ただし、それらの[[CanBlock]]の値はfalseであるため、エージェントとスレッドが1対1で対応する必要はない。これにより、実装は、ワークレットに読み込まれたスクリプトを任意のスレッドで実行でき、これには、[[CanBlock]]がfalseである他のエージェントからのコードを実行しているスレッド、例えば類似オリジンのウィンドウエージェント("メインスレッド")のスレッドも含まれる。これとは対照的に、専用ワーカーエージェントは、[[CanBlock]]の値がtrueであるため、事実上、専用のオペレーティングシステムスレッドを必要とする。

ワークレットのイベントループも、いくぶん特殊である。それらは、addModule()に関連付けられたタスク、ユーザーエージェントが著者定義のメソッドを呼び出すタスク、およびマイクロタスクにのみ使用される。したがって、イベントループ処理モデルはすべてのイベントループが継続的に実行されることを規定しているが、実装は、著者が提供したメソッドを呼び出し、そのプロセスにマイクロタスクチェックポイントを実行させるだけの、より単純な戦略を用いて、観測可能な結果が等価になるようにできる。

11.3.1.2 Creation and termination

To create a worklet global scope for a Worklet worklet:

  1. Let outsideSettings be worklet's relevant settings object.

  2. Let agent be the result of obtaining a worklet agent given outsideSettings. Run the rest of these steps in that agent.

  3. Let realmExecutionContext be the result of creating a new realm given agent and the following customizations:

  4. Let workletGlobalScope be the global object of realmExecutionContext's Realm component.

  5. Let insideSettings be the result of setting up a worklet environment settings object given realmExecutionContext and outsideSettings.

  6. Let pendingAddedModules be a clone of worklet's added modules list.

  7. Let runNextAddedModule be the following steps:

    1. If pendingAddedModules is not empty:

      1. Let moduleURL be the result of dequeuing from pendingAddedModules.

      2. Fetch a worklet script graph given moduleURL, insideSettings, worklet's worklet destination type, what credentials mode?, insideSettings, worklet's module responses map, and with the following steps given script:

        This will not actually perform a network request, as it will just reuse responses from worklet's module responses map. The main purpose of this step is to create a new workletGlobalScope-specific module script from the response.

        1. Assert: script is not null, since the fetch succeeded and the source text was successfully parsed when worklet's module responses map was initially populated with moduleURL.

        2. Run a module script given script.

        3. Run runNextAddedModule.

      3. Abort these steps.
    2. Append workletGlobalScope to outsideSettings's global object's associated Document's worklet global scopes.

    3. Append workletGlobalScope to worklet's global scopes.

    4. Run the responsible event loop specified by insideSettings.

  8. Run runNextAddedModule.

To terminate a worklet global scope given a WorkletGlobalScope workletGlobalScope:

  1. Let eventLoop be workletGlobalScope's relevant agent's event loop.

  2. If there are any tasks queued in eventLoop's task queues, discard them without processing them.

  3. Wait for eventLoop to complete the currently running task.

  4. If the previous step doesn't complete within an implementation-defined period of time, then abort the script currently running in the worklet.

  5. Destroy eventLoop.

  6. Remove workletGlobalScope from the global scopes of the Worklet whose global scopes contains workletGlobalScope.

  7. Remove workletGlobalScope from the worklet global scopes of the Document whose worklet global scopes contains workletGlobalScope.

11.3.1.3 Script settings for worklets

To set up a worklet environment settings object, given a JavaScript execution context executionContext and an environment settings object outsideSettings:

  1. Let origin be a unique opaque origin.

  2. Let inheritedAPIBaseURL be outsideSettings's API base URL.

  3. Let inheritedPolicyContainer be a clone of outsideSettings's policy container.

  4. Let realm be the value of executionContext's Realm component.

  5. Let workletGlobalScope be realm's global object.

  6. Let settingsObject be a new environment settings object whose algorithms are defined as follows:

    The realm execution context

    Return executionContext.

    The module map

    Return workletGlobalScope's module map.

    The API base URL

    Return inheritedAPIBaseURL.

    Unlike workers or other globals derived from a single resource, worklets have no primary resource; instead, multiple scripts, each with their own URL, are loaded into the global scope via worklet.addModule(). So this API base URL is rather unlike that of other globals. However, so far this doesn't matter, as no APIs available to worklet code make use of the API base URL.

    The origin

    Return origin.

    The has cross-site ancestor

    Return true.

    The policy container

    Return inheritedPolicyContainer.

    The cross-origin isolated capability

    Return outsideSettings's cross-origin isolated capability.

    The time origin

    Return outsideSettings's time origin.

  7. Set settingsObject's id to a new unique opaque string, creation URL to inheritedAPIBaseURL, top-level creation URL to null, top-level origin to outsideSettings's top-level origin, target browsing context to null, and active service worker to null.

  8. Set realm's [[HostDefined]] field to settingsObject.

  9. Return settingsObject.

11.3.2 Workletクラス

Worklet

Support in all current engines.

Firefox76+Safari14.1+Chrome65+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Workletクラスは、関連付けられたWorkletGlobalScopeにモジュールスクリプトを追加する機能を提供する。その後、ユーザーエージェントはWorkletGlobalScopeに登録されたクラスを作成し、それらのメソッドを呼び出すことができる。

[Exposed=Window, SecureContext]
interface Worklet {
  [NewObject] Promise<undefined> addModule(USVString moduleURL, optional WorkletOptions options = {});
};

dictionary WorkletOptions {
  RequestCredentials credentials = "same-origin";
};

Workletインスタンスを作成する仕様は、各インスタンスについて次の事項を指定しなければならない:

await worklet.addModule(moduleURL[, { credentials }])

Worklet/addModule

Support in all current engines.

Firefox76+Safari14.1+Chrome65+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

moduleURLで指定されたモジュールスクリプトを読み込み、workletのすべてのグローバルスコープで実行する。また、この処理の一環として、ワークレット型に応じて追加のグローバルスコープを作成することもできる。スクリプトがすべてのグローバルスコープで正常に読み込まれ、実行されると、返されるプロミスは実行される。

credentialsオプションは、スクリプトのフェッチ処理を変更するために資格情報モードに設定できる。デフォルトは"same-origin"である。

スクリプトまたはその依存関係のフェッチに失敗すると、返されるプロミスは"AbortError" DOMExceptionで拒否される。スクリプトまたはその依存関係の解析でエラーが発生すると、返されるプロミスは解析中に生成された例外で拒否される。

A Worklet has a list of global scopes, which contains instances of the Worklet's worklet global scope type. It is initially empty.

A Worklet has an added modules list, which is a list of URLs, initially empty. Access to this list should be thread-safe.

A Worklet has a module responses map, which is an ordered map from URLs to either "fetching" or tuples consisting of a response and either null, failure, or a byte sequence representing the response body. This map is initially empty, and access to it should be thread-safe.

The added modules list and module responses map exist to ensure that WorkletGlobalScopes created at different times get equivalent module scripts run in them, based on the same source text. This allows the creation of additional WorkletGlobalScopes to be transparent to the author.

In practice, user agents are not expected to implement these data structures, and the algorithms that consult them, using thread-safe programming techniques. Instead, when addModule() is called, user agents can fetch the module graph on the main thread, and send the fetched source text (i.e., the important data contained in the module responses map) to each thread which has a WorkletGlobalScope.

Then, when a user agent creates a new WorkletGlobalScope for a given Worklet, it can simply send the map of fetched source text and the list of entry points from the main thread to the thread containing the new WorkletGlobalScope.

The addModule(moduleURL, options) method steps are:

  1. Let outsideSettings be the relevant settings object of this.

  2. Let moduleURLRecord be the result of encoding-parsing a URL given moduleURL, relative to outsideSettings.

  3. If moduleURLRecord is failure, then return a promise rejected with a "SyntaxError" DOMException.

  4. Let promise be a new promise.

  5. Let workletInstance be this.

  6. Run the following steps in parallel:

    1. If workletInstance's global scopes is empty:

      1. Create a worklet global scope given workletInstance.

      2. Optionally, create additional global scope instances given workletInstance, depending on the specific worklet in question and its specification.

      3. Wait for all steps of the creation process(es) — including those taking place within the worklet agents — to complete, before moving on.

    2. Let pendingTasks be workletInstance's global scopes's size.

    3. Let addedSuccessfully be false.

    4. For each workletGlobalScope of workletInstance's global scopes, queue a global task on the networking task source given workletGlobalScope to fetch a worklet script graph given moduleURLRecord, outsideSettings, workletInstance's worklet destination type, options["credentials"], workletGlobalScope's relevant settings object, workletInstance's module responses map, and the following steps given script:

      Only the first of these fetches will actually perform a network request; the ones for other WorkletGlobalScopes will reuse responses from workletInstance's module responses map.

      1. If script is null:

        1. Queue a global task on the networking task source given workletInstance's relevant global object to perform the following steps:

          1. If pendingTasks is not −1:

            1. Set pendingTasks to −1.

            2. Reject promise with an "AbortError" DOMException.

        2. Abort these steps.

      2. If script's error to rethrow is not null:

        1. Queue a global task on the networking task source given workletInstance's relevant global object to perform the following steps:

          1. If pendingTasks is not −1:

            1. Set pendingTasks to −1.

            2. Reject promise with script's error to rethrow.

        2. Abort these steps.

      3. If addedSuccessfully is false:

        1. Append moduleURLRecord to workletInstance's added modules list.

        2. Set addedSuccessfully to true.

      4. Run a module script given script.

      5. Queue a global task on the networking task source given workletInstance's relevant global object to perform the following steps:

        1. If pendingTasks is not −1:

          1. Set pendingTasks to pendingTasks − 1.

          2. If pendingTasks is 0, then resolve promise.

  7. Return promise.

11.3.3 ワークレットの存続期間

Workletの存続期間には特別な考慮事項はなく、Windowなど、それが属するオブジェクトに結び付けられている。

Each Document has a worklet global scopes, which is a set of WorkletGlobalScopes, initially empty.

WorkletGlobalScopeの存続期間は、少なくとも、それを含むワークレットグローバルスコープを有するDocumentに結び付けられている。特に、Documentを破棄すると、対応するWorkletGlobalScopeは終了し、ガベージコレクションが可能になる。

さらに、対応するワークレット型を定義する仕様で別段の定めがない限り、ユーザーエージェントは任意の時点で、特定のWorkletGlobalScopeを終了させてもよい。例えば、ワークレットエージェントのイベントループにキューに入っているタスクがない場合、ユーザーエージェントがそのワークレットを使用する予定の保留中の操作を持たない場合、またはユーザーエージェントが無限ループもしくは課された時間制限を超えるコールバックなどの異常な操作を検出した場合に、終了させることがある。

最後に、特定のワークレット型に関する仕様は、特定のワークレット型についてWorkletGlobalScopeをいつ作成するかに関する、より詳細な情報を示すことができる。たとえば、例に示すように、ワークレットコードを呼び出す特定の処理中に、それらを作成することがある。