Implementing the AudioWorklet API is a challenging task. It's best to start with some context about Worklets themselves.

Quoting MDN,

The Worklet interface is a lightweight version of Web Workers and gives developers access to low-level parts of the rendering pipeline.

Web Workers and Worklets have similar implementations in Servo. For example, both of them run on a separate thread than the script thread.

As the first step for any worker or worklet, we need to give the browser engine the JavaScript code we want to execute on the separate thread. The current Worklet implementation in Servo only allows developers to run classic scripts.

According to the Worklet specs, supporting JavaScript modules is necessary for a complete implementation.

For the past few weeks, I have been trying to implement module imports for Worklets in Servo. At first, it might seem like Servo already has an implementation for importing JavaScript modules in the Workers and all I need to do is copy that implementation.

This is where the difference between Workers and Worklets become significant. We will start by looking at the Worker and Worklet specifications.

If you open up the Web Worker specification, you can see that the specification provides a reference for the “infrastructure”.

A part of the Worker's infrastructure is the event loop.

A worker event loop's task queues only have events, callbacks, and networking activity as tasks. These worker event loops are created by the run a worker algorithm.

Similarly, the worklet infrastructure also have “Agents and event loops”. If we look at what the spec says about the Worklet event loops,

Worklet event loops are also somewhat special. They are only used for tasks associated with addModule(), tasks wherein the user agent invokes author-defined methods, and microtasks. Thus, even though the event loop processing model specifies that all event loops run continuously, implementations can achieve observably-equivalent results using a simpler strategy, which just invokes author-provided methods and then relies on that process to perform a microtask checkpoint.

We learn that Worklet event loops are in fact (somewhat) special. Worklet event loops require a different implementation, and this is where Worklets being “a lightweight version of Web Workers” becomes important. We do not want a full fledged heavy event loop for a worklet, we can get away with a “simpler strategy”.

And that's exactly what I have been working on. I started by fixing the addModule implementation of addModule method.

The fetch implementation requires a MicrotaskQueue as described by the specification. I am currently adding a MicrotaskQueue and microtask checkpoints to the current Worklet implementation as well as writing tests to ensure that JavaScript modules work fine. A challenge in implementation is to be able to fetch JavaScript modules in a multi-threaded Worklet architecture.

LinkedIn: https://www.linkedin.com/in/niyabits/