| 1 |
# `sync-message-port` |
| 2 |
|
| 3 |
This package exposes a utility class that encapsulates the ability to send and |
| 4 |
receive messages with arbitrary structure across Node.js worker boundaries. It |
| 5 |
can be used as the building block for synchronous versions of APIs that are |
| 6 |
traditionally only available asynchronously in the Node.js ecosystem by running |
| 7 |
the asynchronous APIs in a worker and accessing their results synchronously from |
| 8 |
the main thread. |
| 9 |
|
| 10 |
See [the `sync-child-process` package] for an example of `sync-message-port` in |
| 11 |
action. |
| 12 |
|
| 13 |
[the `sync-child-process` package]: https://github.com/sass/sync-child-process |
| 14 |
|
| 15 |
[**API Docs**] |
| 16 |
|
| 17 |
[**API Docs**]: https://sass.github.io/sync-message-port/classes/SyncMessagePort.html |
| 18 |
|
| 19 |
## Usage |
| 20 |
|
| 21 |
1. Use [`SyncMessagePort.createChannel()`] to create a message channel that's |
| 22 |
set up to be compatible with `SyncMessagePort`s. A normal `MessageChannel` |
| 23 |
won't work! |
| 24 |
|
| 25 |
2. You can send this `MessageChannel`'s ports across worker boundaries just like |
| 26 |
any other `MessagePort`. Send one to the worker you want to communicate with |
| 27 |
synchronously. |
| 28 |
|
| 29 |
3. Once you're ready to start sending and receiving messages, wrap *both* ports |
| 30 |
in [`new SyncMessagePort()`], even if one is only ever going to be sending |
| 31 |
messages and not receiving them. |
| 32 |
|
| 33 |
4. Use [`SyncMessagePort.postMessage()`] to send messages and |
| 34 |
`SyncMessagePort.receiveMessage()` to receive them synchronously. |
| 35 |
|
| 36 |
[`SyncMessagePort.createChannel()`]: https://sass.github.io/sync-message-port/classes/SyncMessagePort.html#createChannel |
| 37 |
[`new SyncMessagePort()`]: https://sass.github.io/sync-message-port/classes/SyncMessagePort.html#constructor |
| 38 |
[`SyncMessagePort.postMessage()`]: https://sass.github.io/sync-message-port/classes/SyncMessagePort.html#postMessage |
| 39 |
[`SyncMessagePort.receiveMessage()`]: https://sass.github.io/sync-message-port/classes/SyncMessagePort.html#receiveMessage |
| 40 |
|
| 41 |
```js |
| 42 |
import {Worker} from 'node:worker_threads'; |
| 43 |
import {SyncMessagePort} from 'sync-message-port'; |
| 44 |
// or |
| 45 |
// const {SyncMessagePort} = require('sync-message-port'); |
| 46 |
|
| 47 |
// Channels must be created using this function. A MessageChannel created by |
| 48 |
// hand won't work. |
| 49 |
const channel = SyncMessagePort.createChannel(); |
| 50 |
const localPort = new SyncMessagePort(channel.port1); |
| 51 |
|
| 52 |
const worker = new Worker(` |
| 53 |
import {workerData} from 'node:worker_threads'; |
| 54 |
import {SyncMessagePort} from 'sync-message-port'; |
| 55 |
|
| 56 |
const remotePort = new SyncMessagePort(workerData.port); |
| 57 |
|
| 58 |
setTimeout(() => { |
| 59 |
remotePort.postMessage("hello from worker!"); |
| 60 |
}, 2000); |
| 61 |
`, { |
| 62 |
workerData: {port: channel.port2}, |
| 63 |
transferList: [channel.port2], |
| 64 |
eval: true, |
| 65 |
}); |
| 66 |
|
| 67 |
// Note that because workers report errors asynchronously, this won't report an |
| 68 |
// error if the worker fails to load because the main thread will be |
| 69 |
// synchronously waiting for its first message. |
| 70 |
worker.on('error', console.error); |
| 71 |
|
| 72 |
console.log(localPort.receiveMessage()); |
| 73 |
``` |
| 74 |
|
| 75 |
## Why synchrony? |
| 76 |
|
| 77 |
Although JavaScript in general and Node.js in particular are typically designed |
| 78 |
to embrace asynchrony, there are a number of reasons why a synchronous API may |
| 79 |
be preferable or even necessary. |
| 80 |
|
| 81 |
### No a/synchronous polymorphism |
| 82 |
|
| 83 |
Although `async`/`await` and the `Promise` API has substantially improved the |
| 84 |
usability of writing asynchronous code in JavaScript, it doesn't address one |
| 85 |
core issue: there's no way to write code that's *polymorphic* over asynchrony. |
| 86 |
Put in simpler terms, there's no language-level way to write a complex function |
| 87 |
that takes a callback and to run that functions synchronously if the callback is |
| 88 |
synchronous and asynchronously otherwise. The only option is to write the |
| 89 |
function twice. |
| 90 |
|
| 91 |
This poses a real, practical problem when interacting with libraries. Suppose |
| 92 |
you have a library that takes a callback option—for example, an HTML |
| 93 |
sanitization library that takes a callback to determine how to handle a given |
| 94 |
`<a href="...">`. The library doesn't need to do any IO itself, so it's written |
| 95 |
synchronously. But what if your callback wants to make an HTTP request to |
| 96 |
determine how to handle a tag? You're stuck unless you can make that request |
| 97 |
synchronous. This library makes that possible. |
| 98 |
|
| 99 |
### Performance considerations |
| 100 |
|
| 101 |
Asynchrony is generally more performant in situations where there's a large |
| 102 |
amount of concurrent IO happening. But when performance is CPU-bound, it's often |
| 103 |
substantially worse due to the overhead of bouncing back and forth between the |
| 104 |
event loop and user code. |
| 105 |
|
| 106 |
As a real-world example, the Sass compiler API supports both synchronous and |
| 107 |
asynchronous code paths to work around the polymorphism problem described above. |
| 108 |
The logic of these paths is exactly the same—the only difference is that the |
| 109 |
asynchronous path's functions all return `Promise`s instead of synchronous |
| 110 |
values. Compiling with the asynchronous path often takes 2-3x longer than with |
| 111 |
the synchronous path. This means that being able to run plugins synchronously |
| 112 |
can provide a substantial overall performance gain, even if the plugins |
| 113 |
themselves lose the benefit of concurrency. |
| 114 |
|
| 115 |
## How does it work? |
| 116 |
|
| 117 |
This uses [`Atomics`] and [`SharedArrayBuffer`] under the covers to signal |
| 118 |
across threads when messages are available, and |
| 119 |
[`worker_threads.receiveMessageOnPort()`] to actually retrieve messages. |
| 120 |
|
| 121 |
[`Atomics`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics |
| 122 |
[`SharedArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer |
| 123 |
[`worker_threads.receiveMessageOnPort()`]: https://nodejs.org/api/worker_threads.html#workerreceivemessageonportport |
| 124 |
|
| 125 |
### Can I use this in a browser? |
| 126 |
|
| 127 |
Unfortunately, no. Browsers don't support any equivalent of |
| 128 |
`worker_threads.receiveMessageOnPort()`, even within worker threads. You could |
| 129 |
make a similar package that can transmit only binary data (or data that can be |
| 130 |
encoded as binary) using only `SharedArrayBuffer`, but that's outside the scope |
| 131 |
of this package. |
| 132 |
|
| 133 |
Disclaimer: this is not an official Google product. |