Transferable transport
TransferableTransport is a dnet transport for browser postMessage targets that need to transfer both data and transferable objects.
It wraps a target implementing PostMessage such as:
TransferableTransport works with messages that implement the IntoTransferable / FromTransferable conversion traits:
IntoTransferable<Context, Error>first converts outgoing messages into an (arbitrary) type implementingTransferabletrait.Transferabletrait implementation is then responsible for preparing message for transfer through the transport by converting it intoWithTransferabletype, which contains both the serialized message data (packed into JS object) and an JS array of transferable objects.- For incoming messages (on the receiving end),
Transferabletrait implementation is responsible for reconstructing the original message from the received JS object (handling of transferable objects is done automatically by the browser). FromTransferable<Context, Error>reconstructs incoming messages from the (arbitrary)Transferabletype.
Note
Transferabletrait uses arbitraryContext(passed by the user toTransferableTransportduring construction).
It may be used to store codec, works buffers, etc., required for message serialization and deserialization.
When to use
Use TransferableTransport when you need to send browser transferable objects, like:
If you only need serializable messages - without transferable objects - prefer dnet::js::Transport or its more specialized variants, such as MessagePortTransport or WebWorkerTransport.
Note
When directly using this or
dnet::js::Transportover aMessagePort, remember to callport.start()on both sides before sending messages.
Implementing IntoTransferable and FromTransferable
Implementing IntoTransferable, FromTransferable and Transferable manually is straightforward, but can be tedious.
Use #[derive(IntoTransferable)] to implement those traits automatically:
use js_sys::ArrayBuffer;
use dnet::js::{IntoTransferable, Transferable};
#[derive(IntoTransferable)]
struct Message {
some_field: String,
#[transferable]
buffer: ArrayBuffer,
}
Transferable fields must be marked with #[transferable].
Note
Generated
IntoTransferableimplementation expects you to usednet::js::wrapper::Contextwith your transport.
If you need to use a different context type, implementIntoTransferableandFromTransferablemanually.
Nested IntoTransferables
Messages deriving IntoTransferable can contain nested fields that also implement IntoTransferable.
Mark such fields with #[into_transferable]:
use js_sys::ArrayBuffer;
use dnet::js::IntoTransferable;
#[derive(IntoTransferable)]
struct Nested {
#[transferable]
buffer: ArrayBuffer,
}
#[derive(IntoTransferable)]
struct Message {
some_field: String,
#[into_transferable]
nested: Nested,
}
Note
For convenience
IntoTransferableis implemented for typed JS typed array types - seeIntoTransferable’s foreign impls.Example:
use js_sys::Uint16Array; use dnet::js::IntoTransferable; #[derive(Debug, IntoTransferable)] struct Message { #[into_transferable] array: Uint16Array, }
Warning
#[derive(IntoTransferable)]macro will generate extra structures named:
<YourTypeName>Wrapper,<YourTypeName>Stripped,<YourTypeName>IntoTransferables(only if nested#[into_transferable]fields are present),where
<YourTypeName>is the name of your message.If name collision(s) occurs, consider putting your message type into a separate module or - if not possible - implementing
IntoTransferableandFromTransferablemanually.
Example
The following example demonstrates how a host and a worker can exchange messages with transferable objects using TransferableTransport:
use futures::SinkExt;
use js_sys::{ArrayBuffer, Uint8Array};
use std::rc::Rc;
use web_sys::{MessageChannel, Worker, WorkerOptions, WorkerType};
use dnet::{
codecs::BincodeCodec,
js::{wrapper::Context, IntoTransferable, TransferableTransport},
Receive,
};
#[derive(IntoTransferable)]
struct Message {
#[transferable]
buffer: ArrayBuffer,
}
async fn host_example() -> Result<(), Box<dyn std::error::Error>> {
let options = WorkerOptions::new();
options.set_type(WorkerType::Module);
let worker = Worker::new_with_options("./worker.js", &options)?;
let context = Context::new(BincodeCodec::default());
let mut transport = TransferableTransport::<_, _, Message, Message, _>::new(
&worker,
None,
context,
true,
)
.await?;
let buffer = ArrayBuffer::new_with_length(8);
Uint8Array::new(&buffer).copy_from(&[1, 2, 3, 4, 5, 6, 7, 8]);
transport.send(Message { buffer }).await?;
Ok(())
}
async fn worker_example(
global: Rc<web_sys::DedicatedWorkerGlobalScope>,
) -> Result<(), Box<dyn std::error::Error>> {
let context = Context::new(BincodeCodec::default());
let mut transport = TransferableTransport::<_, _, Message, Message, _>::new(
&global,
None,
context,
false,
)
.await?;
let received = transport.receive().await?;
let Message { buffer } = received;
assert_eq!(Uint8Array::new(&buffer).to_vec(), vec![1, 2, 3, 4, 5, 6, 7, 8]);
Ok(())
}