remoc 0.19.1

🦑 Remote multiplexed objects, channels, observable collections and RPC making remote interactions seamless. Provides multiple remote channels and RPC over TCP, TLS or any other transport.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Codecs for transforming values into and from binary wire format.
//!
//! All codecs in this module are wrappers around the [serde] crates implementing the
//! data representations.
//! Thus you should refer to the corresponding crate documentation for information
//! about limitations and backward as well as forward compatibility.
//!
//! By default the **[Postbag codec](postbag::Postbag)** is used, which is highly efficient as well as
//! forward and backward compatible.
//! Unless you have specific requirements, it is *not recommended* to change the default
//! codec.
//!
//! # Crate features
//!
//! Each codec is gated by the corresponding crate feature `codec-*`, i.e.
//! the JSON codec is only available if the crate features `codec-json` is enabled.
//! The crate feature `full-codecs` enables all codecs.
//!
//! The default codec, named [Default](struct@Default), can be selected by enabling the
//! appropriate `default-codec-*` crate feature.
//! For example, if you want to use the JSON codec by default, enable the crate feature
//! `default-codec-json`.
//! Only one default codec feature must be enabled, otherwise a compile error will occur.
//! The default codec should only be selected by an application and not a library crate
//! that uses Remoc.
//! Otherwise a conflict between multiple libraries that depend upon different default
//! codecs will occur.
//!
//! The following features select the default codec.
//!
//!   * `default-codec-bincode` -- enables and selects Bincode 1 as the default codec
//!   * `default-codec-bincode2` -- enables and selects Bincode 2 as the default codec
//!   * `default-codec-ciborium` -- enables and selects CBOR as the default codec
//!   * `default-codec-json` -- enables and selects JSON as the default codec
//!   * `default-codec-message-pack` -- enables and selects MessagePack as the default codec
//!   * `default-codec-postbag` -- enables and selects Postbag with full configuration as the default codec
//!   * `default-codec-postbag-slim` -- enables and selects Postbag with slim configuration as the default codec
//!   * `default-codec-postcard` -- enables and selects Postcard as the default codec
//!
//! By default the Postbag codec is enabled and the default, i.e. the `default-codec-postbag`
//! crate feature is enabled.
//! Thus to change the default codec, you must specify `default-features = false` when
//! referencing Remoc in your `Cargo.toml`.
//!

use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned};
use std::{
    any::{Any, TypeId, type_name},
    error::Error,
    fmt,
    io::{Read, Write},
    sync::Arc,
};

/// Reference counted error that is send, sync, static and clone.
pub type ArcError = Arc<dyn Error + Send + Sync + 'static>;

/// An error consisting of a string message.
#[derive(Debug, Clone)]
pub(crate) struct ErrorMsg(pub String);

impl fmt::Display for ErrorMsg {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Error for ErrorMsg {}

/// Streaming serialization and deserialization is unavailable.
///
/// This is because the platform does not support threads or they
/// are not working.
///
/// When streaming is unavailable, only messages up to the size specified
/// in [`Cfg::max_data_size`](crate::chmux::Cfg::max_data_size) can be
/// sent and received. You can increase this limit to work around the issue.
#[derive(Debug, Clone)]
pub struct StreamingUnavailable;

impl fmt::Display for StreamingUnavailable {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "streaming serialization and deserialization is unavailable")
    }
}

impl Error for StreamingUnavailable {}

/// Serialization error.
#[derive(Debug, Clone)]
pub struct SerializationError(pub ArcError);

impl SerializationError {
    /// Creates a new serialization error.
    pub fn new<E>(err: E) -> Self
    where
        E: Error + Send + Sync + 'static,
    {
        Self(Arc::new(err))
    }
}

impl fmt::Display for SerializationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Error for SerializationError {}

impl Serialize for SerializationError {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let msg = self.0.to_string();
        msg.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for SerializationError {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let msg = String::deserialize(deserializer)?;
        Ok(Self::new(ErrorMsg(msg)))
    }
}

/// Deserialization error.
#[derive(Debug, Clone)]
pub struct DeserializationError(pub ArcError);

impl DeserializationError {
    /// Creates a new deserialization error.
    pub fn new<E>(err: E) -> Self
    where
        E: Error + Send + Sync + 'static,
    {
        Self(Arc::new(err))
    }
}

impl fmt::Display for DeserializationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Error for DeserializationError {}

impl Serialize for DeserializationError {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let msg = self.0.to_string();
        msg.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for DeserializationError {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let msg = String::deserialize(deserializer)?;
        Ok(Self::new(ErrorMsg(msg)))
    }
}

/// Serializes and deserializes items from and to byte data.
pub trait Codec: Send + Sync + Serialize + for<'de> Deserialize<'de> + Clone + Unpin + 'static {
    /// Serializes the specified item into the data format.
    fn serialize<Writer, Item>(writer: Writer, item: &Item) -> Result<(), SerializationError>
    where
        Writer: Write,
        Item: Serialize;

    /// Deserializes the specified data into an item.
    fn deserialize<Reader, Item>(reader: Reader) -> Result<Item, DeserializationError>
    where
        Reader: Read,
        Item: DeserializeOwned;
}

/// Dummy codec.
///
/// Does not support serialization or deserialization.
#[derive(Clone, Serialize, Deserialize)]
pub(crate) struct Dummy;

impl Codec for Dummy {
    fn serialize<Writer, Item>(_writer: Writer, _item: &Item) -> Result<(), SerializationError>
    where
        Writer: std::io::Write,
        Item: serde::Serialize,
    {
        Err(SerializationError::new(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "dummy codec does not support serialization",
        )))
    }

    fn deserialize<Reader, Item>(_reader: Reader) -> Result<Item, DeserializationError>
    where
        Reader: std::io::Read,
        Item: serde::de::DeserializeOwned,
    {
        Err(DeserializationError::new(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "dummy codec does not support deserialization",
        )))
    }
}

#[cfg(feature = "codec-json")]
pub mod map;

// ============================================================================
// Erased serializer and deserializer
// ============================================================================

/// Item that is Any and Send.
pub type AnySend = Box<dyn Any + Send>;

/// Type-erased serializer.
pub struct ErasedSerializer {
    type_id: TypeId,
    type_name: &'static str,
    codec_name: &'static str,
    inner: Box<dyn ErasedSerializerMethods>,
}

impl Clone for ErasedSerializer {
    fn clone(&self) -> Self {
        Self {
            type_id: self.type_id,
            type_name: self.type_name,
            codec_name: self.codec_name,
            inner: self.inner.clone(),
        }
    }
}

impl fmt::Debug for ErasedSerializer {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ErasedSerializer")
            .field("type", &self.type_name)
            .field("codec", &self.codec_name)
            .finish()
    }
}

impl ErasedSerializer {
    /// Creates a new type-erased serializer for the given type and codec.
    pub fn new<T, C>() -> Self
    where
        T: Serialize + Any,
        C: Codec,
    {
        Self {
            type_id: TypeId::of::<T>(),
            type_name: type_name::<T>(),
            codec_name: type_name::<C>(),
            inner: Box::new(ErasedSerializerInner::<T, C>(|_, _| ())),
        }
    }

    /// Checks that the passed type matches the underlying type.
    #[track_caller]
    pub fn check_type(&self, item: &dyn Any) {
        if item.type_id() != self.type_id {
            panic!("expected type {} for serialization", self.type_name);
        }
    }

    /// Serialize the type-erased item into the given writer.
    ///
    /// # Panics
    /// Panics if the type of the item does not match the type `T` used for calling [`ErasedSerializer::new`].
    pub fn serialize(&self, writer: &mut dyn Write, item: &dyn Any) -> Result<(), SerializationError> {
        self.inner.serialize(writer, item)
    }
}

trait ErasedSerializerMethods: Send + Sync {
    fn clone(&self) -> Box<dyn ErasedSerializerMethods>;
    fn serialize(&self, writer: &mut dyn Write, item: &dyn Any) -> Result<(), SerializationError>;
}

#[expect(dead_code)]
struct ErasedSerializerInner<T, C>(fn(T, C));

impl<T, C> ErasedSerializerMethods for ErasedSerializerInner<T, C>
where
    T: Serialize + Any,
    C: Codec,
{
    fn clone(&self) -> Box<dyn ErasedSerializerMethods> {
        Box::new(ErasedSerializerInner::<T, C>(|_, _| ()))
    }

    fn serialize(&self, writer: &mut dyn Write, item: &dyn Any) -> Result<(), SerializationError> {
        let Some(item) = item.downcast_ref::<T>() else { panic!("ErasedSerializer called with mismatched type") };
        <C as Codec>::serialize(writer, item)
    }
}

/// Type-erased deserializer.
pub struct ErasedDeserializer {
    type_name: &'static str,
    codec_name: &'static str,
    inner: Box<dyn ErasedDeserializerMethods>,
}

impl Clone for ErasedDeserializer {
    fn clone(&self) -> Self {
        Self { type_name: self.type_name, codec_name: self.codec_name, inner: self.inner.clone() }
    }
}

impl fmt::Debug for ErasedDeserializer {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ErasedDeserializer")
            .field("type", &self.type_name)
            .field("codec", &self.codec_name)
            .finish()
    }
}

impl ErasedDeserializer {
    /// Creates a new type-erased deserializer for the given type and codec.
    pub fn new<T, C>() -> Self
    where
        T: DeserializeOwned + Any + Send,
        C: Codec,
    {
        Self {
            type_name: type_name::<T>(),
            codec_name: type_name::<C>(),
            inner: Box::new(ErasedDeserializerInner::<T, C>(|_, _| ())),
        }
    }

    /// Deserialize the item of type `T` used for calling [`ErasedDeserializer::new`] from the given reader.
    ///  
    /// The deserialized item is returned type erased.
    pub fn deserialize(&self, reader: &mut dyn Read) -> Result<AnySend, DeserializationError> {
        self.inner.deserialize(reader)
    }
}

trait ErasedDeserializerMethods: Send + Sync {
    fn clone(&self) -> Box<dyn ErasedDeserializerMethods>;
    fn deserialize(&self, reader: &mut dyn Read) -> Result<AnySend, DeserializationError>;
}

#[expect(dead_code)]
struct ErasedDeserializerInner<T, C>(fn(T, C));

impl<T, C> ErasedDeserializerMethods for ErasedDeserializerInner<T, C>
where
    T: DeserializeOwned + Any + Send,
    C: Codec,
{
    fn clone(&self) -> Box<dyn ErasedDeserializerMethods> {
        Box::new(ErasedDeserializerInner::<T, C>(|_, _| ()))
    }

    fn deserialize(&self, reader: &mut dyn Read) -> Result<AnySend, DeserializationError> {
        let item: T = <C as Codec>::deserialize(reader)?;
        Ok(Box::new(item))
    }
}

// ============================================================================
// Codecs
// ============================================================================

#[cfg(feature = "codec-postbag")]
mod postbag;
#[cfg(feature = "default-codec-postbag")]
#[doc(no_inline)]
pub use postbag::Postbag as Default;
#[cfg(feature = "default-codec-postbag-slim")]
#[doc(no_inline)]
pub use postbag::PostbagSlim as Default;
#[cfg(feature = "codec-postbag")]
pub use postbag::{Postbag, PostbagSlim};

#[cfg(feature = "codec-bincode")]
mod bincode;
#[cfg(feature = "default-codec-bincode")]
#[doc(no_inline)]
pub use self::bincode::Bincode as Default;
#[cfg(feature = "default-codec-bincode2")]
#[doc(no_inline)]
pub use self::bincode::Bincode2 as Default;
#[cfg(feature = "codec-bincode")]
pub use self::bincode::{Bincode, Bincode2};

#[cfg(feature = "codec-ciborium")]
mod ciborium;
#[cfg(feature = "codec-ciborium")]
pub use self::ciborium::Ciborium;
#[cfg(feature = "default-codec-ciborium")]
#[doc(no_inline)]
pub use self::ciborium::Ciborium as Default;

#[cfg(feature = "codec-json")]
mod json;
#[cfg(feature = "codec-json")]
pub use json::Json;
#[cfg(feature = "default-codec-json")]
#[doc(no_inline)]
pub use json::Json as Default;

#[cfg(feature = "codec-message-pack")]
mod message_pack;
#[cfg(feature = "codec-message-pack")]
pub use message_pack::MessagePack;
#[cfg(feature = "default-codec-message-pack")]
#[doc(no_inline)]
pub use message_pack::MessagePack as Default;

#[cfg(feature = "codec-postcard")]
mod postcard;
#[cfg(feature = "codec-postcard")]
pub use postcard::Postcard;
#[cfg(feature = "default-codec-postcard")]
#[doc(no_inline)]
pub use postcard::Postcard as Default;

/// Default codec is not set and cannot be used.
///
/// Set one of the crate features `default-codec-*` to define the default codec.
///
/// This will cause a compile error when you attempt to use it.
#[cfg(not(feature = "default-codec-set"))]
pub struct Default;