Skip to main content

orcher_sdk/
payload.rs

1//! Converting values to and from [`Payload`]s.
2//!
3//! A payload carries every input and result that crosses the wire: workflow and task
4//! arguments, task results, and handler inputs and outputs. It holds the encoded bytes plus
5//! string metadata such as `encoding` and `content-type`.
6//!
7//! JSON is the default encoding, and [`PayloadCodec`] applies it to every serde type. The
8//! module also offers bincode and, with the `compression` feature, gzip-compressed JSON.
9//! Decoders read only the payload bytes and ignore its metadata, so decode a payload with
10//! the function that matches how it was encoded.
11//!
12//! ## Quick Start
13//!
14//! ```rust
15//! use orcher_sdk::prelude::*;
16//! use serde::{Serialize, Deserialize};
17//!
18//! #[derive(Serialize, Deserialize)]
19//! struct OrderInput {
20//!     order_id: String,
21//!     amount: f64,
22//! }
23//!
24//! // Serialize to payload
25//! let input = OrderInput {
26//!     order_id: "order-123".to_string(),
27//!     amount: 99.99,
28//! };
29//!
30//! let payload = to_payload(&input).unwrap();
31//!
32//! // Deserialize from payload
33//! let decoded: OrderInput = from_payload(&payload).unwrap();
34//! ```
35//!
36//! ## Custom Serialization
37//!
38//! Types that do not implement serde's traits can implement [`PayloadCodec`] themselves:
39//!
40//! ```rust
41//! use orcher_sdk::payload::PayloadCodec;
42//! use orcher_sdk::Result;
43//!
44//! struct CustomType {
45//!     data: Vec<u8>,
46//! }
47//!
48//! impl PayloadCodec for CustomType {
49//!     fn encode(&self) -> Result<Vec<u8>> {
50//!         Ok(self.data.clone())
51//!     }
52//!
53//!     fn decode(bytes: &[u8]) -> Result<Self> {
54//!         Ok(Self { data: bytes.to_vec() })
55//!     }
56//! }
57//!
58//! let payload = CustomType { data: vec![1, 2, 3] }.to_payload()?;
59//! assert_eq!(CustomType::from_payload(&payload)?.data, vec![1, 2, 3]);
60//! # Ok::<(), orcher_sdk::Error>(())
61//! ```
62
63use crate::error::{Error, Result};
64use serde::{Deserialize, Serialize};
65use std::collections::HashMap;
66
67pub use orcher_sdk_core::payload::Payload;
68
69/// A type that can be encoded to and decoded from a [`Payload`].
70///
71/// Every type that implements serde's `Serialize` and `Deserialize` gets this trait
72/// through a blanket implementation that uses JSON and sets the JSON payload metadata.
73/// Implement it by hand only for types without serde support; such an implementation
74/// supplies `encode` and `decode`, and the provided methods wrap the bytes in a payload
75/// without metadata.
76///
77/// ## Example
78///
79/// ```rust
80/// use orcher_sdk::prelude::*;
81/// use serde::{Serialize, Deserialize};
82///
83/// #[derive(Serialize, Deserialize)]
84/// struct MyData {
85///     value: i32,
86/// }
87///
88/// // `MyData` implements `PayloadCodec` through the blanket implementation.
89/// ```
90pub trait PayloadCodec: Sized {
91    /// Encodes this value to bytes.
92    ///
93    /// # Errors
94    ///
95    /// Returns an error if the value cannot be encoded.
96    fn encode(&self) -> Result<Vec<u8>>;
97
98    /// Decodes a value from bytes.
99    ///
100    /// # Errors
101    ///
102    /// Returns an error if the bytes are not a valid encoding of `Self`.
103    fn decode(bytes: &[u8]) -> Result<Self>;
104
105    /// Encodes this value into a payload.
106    ///
107    /// # Errors
108    ///
109    /// Returns an error if the value cannot be encoded.
110    fn to_payload(&self) -> Result<Payload> {
111        let bytes = self.encode()?;
112        Ok(Payload::new_data(bytes))
113    }
114
115    /// Decodes a value from a payload's bytes.
116    ///
117    /// # Errors
118    ///
119    /// Returns an error if the bytes are not a valid encoding of `Self`.
120    fn from_payload(payload: &Payload) -> Result<Self> {
121        Self::decode(&payload.data)
122    }
123}
124
125/// Method-call syntax for decoding a [`Payload`].
126///
127/// ## Example
128///
129/// ```rust
130/// use orcher_sdk::prelude::*;
131/// use serde::{Serialize, Deserialize};
132///
133/// #[derive(Serialize, Deserialize)]
134/// struct MyData { value: i32 }
135///
136/// let payload = to_payload(&MyData { value: 7 })?;
137///
138/// // Method syntax:
139/// let data: MyData = payload.from_payload()?;
140///
141/// // Equivalent associated-function syntax:
142/// let data = MyData::from_payload(&payload)?;
143/// assert_eq!(data.value, 7);
144/// # Ok::<(), orcher_sdk::Error>(())
145/// ```
146pub trait PayloadExt {
147    /// Decodes this payload as a `T`; the same as `T::from_payload(self)`.
148    ///
149    /// # Errors
150    ///
151    /// Returns an error if the payload bytes are not a valid encoding of `T`.
152    // Named after `PayloadCodec::from_payload`, which it forwards to; renaming it to
153    // satisfy the `from_*` convention would break every caller.
154    #[allow(clippy::wrong_self_convention)]
155    fn from_payload<T: PayloadCodec>(&self) -> Result<T>;
156}
157
158impl PayloadExt for Payload {
159    fn from_payload<T: PayloadCodec>(&self) -> Result<T> {
160        T::from_payload(self)
161    }
162}
163
164// JSON for every serde type. The payload methods are overridden so payloads carry the
165// JSON `encoding` and `content-type` metadata.
166impl<T> PayloadCodec for T
167where
168    T: Serialize + for<'de> Deserialize<'de>,
169{
170    fn encode(&self) -> Result<Vec<u8>> {
171        serde_json::to_vec(self).map_err(|e| Error::Serialization(e.to_string()))
172    }
173
174    fn decode(bytes: &[u8]) -> Result<Self> {
175        serde_json::from_slice(bytes).map_err(|e| Error::Serialization(e.to_string()))
176    }
177
178    fn to_payload(&self) -> Result<Payload> {
179        Payload::from_json(self).map_err(|e| Error::Serialization(e.to_string()))
180    }
181
182    fn from_payload(payload: &Payload) -> Result<Self> {
183        payload
184            .to_json()
185            .map_err(|e| Error::Serialization(e.to_string()))
186    }
187}
188
189/// Encodes a value as a JSON [`Payload`].
190///
191/// This is the usual way to build workflow and task inputs.
192///
193/// # Errors
194///
195/// Returns [`Error::Serialization`] if the value cannot be serialized.
196///
197/// # Example
198///
199/// ```rust
200/// use orcher_sdk::prelude::*;
201/// use serde::{Serialize, Deserialize};
202///
203/// #[derive(Serialize, Deserialize)]
204/// struct Input {
205///     name: String,
206/// }
207///
208/// let input = Input { name: "Alice".to_string() };
209/// let payload = to_payload(&input).unwrap();
210/// ```
211pub fn to_payload<T: Serialize>(value: &T) -> Result<Payload> {
212    Payload::from_json(value).map_err(|e| Error::Serialization(e.to_string()))
213}
214
215/// Decodes a value from a [`Payload`] using the type's [`PayloadCodec`].
216///
217/// For serde types this reads the payload as JSON.
218///
219/// # Errors
220///
221/// Returns an error if the payload bytes are not a valid encoding of `T`.
222///
223/// # Example
224///
225/// ```rust
226/// use orcher_sdk::prelude::*;
227/// use serde::{Serialize, Deserialize};
228///
229/// #[derive(Serialize, Deserialize)]
230/// struct Output {
231///     result: i32,
232/// }
233///
234/// # let payload = to_payload(&Output { result: 42 }).unwrap();
235/// let output: Output = from_payload(&payload).unwrap();
236/// assert_eq!(output.result, 42);
237/// ```
238pub fn from_payload<T: PayloadCodec>(payload: &Payload) -> Result<T> {
239    T::from_payload(payload)
240}
241
242/// Serializes a value to JSON bytes.
243///
244/// # Errors
245///
246/// Returns [`Error::Serialization`] if the value cannot be serialized.
247///
248/// # Example
249///
250/// ```rust
251/// use orcher_sdk::payload::to_json_bytes;
252/// use serde::{Serialize, Deserialize};
253///
254/// #[derive(Serialize, Deserialize)]
255/// struct Data {
256///     value: i32,
257/// }
258///
259/// let data = Data { value: 42 };
260/// let bytes = to_json_bytes(&data).unwrap();
261/// ```
262pub fn to_json_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>> {
263    serde_json::to_vec(value).map_err(|e| Error::Serialization(e.to_string()))
264}
265
266/// Deserializes a value from JSON bytes.
267///
268/// # Errors
269///
270/// Returns [`Error::Serialization`] if the bytes are not valid JSON for `T`.
271///
272/// # Example
273///
274/// ```rust
275/// use orcher_sdk::payload::{from_json_bytes, to_json_bytes};
276/// use serde::{Serialize, Deserialize};
277///
278/// #[derive(Serialize, Deserialize)]
279/// struct Data {
280///     value: i32,
281/// }
282///
283/// # let bytes = to_json_bytes(&Data { value: 42 }).unwrap();
284/// let data: Data = from_json_bytes(&bytes).unwrap();
285/// assert_eq!(data.value, 42);
286/// ```
287pub fn from_json_bytes<T: for<'de> Deserialize<'de>>(bytes: &[u8]) -> Result<T> {
288    serde_json::from_slice(bytes).map_err(|e| Error::Serialization(e.to_string()))
289}
290
291/// Serializes a value to a pretty-printed JSON string, for logging and debugging.
292///
293/// # Errors
294///
295/// Returns [`Error::Serialization`] if the value cannot be serialized.
296///
297/// # Example
298///
299/// ```rust
300/// use orcher_sdk::payload::to_json_string;
301/// use serde::{Serialize, Deserialize};
302///
303/// #[derive(Serialize, Deserialize)]
304/// struct Data {
305///     value: i32,
306/// }
307///
308/// let data = Data { value: 42 };
309/// let json = to_json_string(&data).unwrap();
310/// println!("{}", json);
311/// ```
312pub fn to_json_string<T: Serialize>(value: &T) -> Result<String> {
313    serde_json::to_string_pretty(value).map_err(|e| Error::Serialization(e.to_string()))
314}
315
316/// Deserializes a value from a JSON string.
317///
318/// # Errors
319///
320/// Returns [`Error::Serialization`] if the string is not valid JSON for `T`.
321///
322/// # Example
323///
324/// ```rust
325/// use orcher_sdk::payload::from_json_string;
326/// use serde::{Serialize, Deserialize};
327///
328/// #[derive(Serialize, Deserialize)]
329/// struct Data {
330///     value: i32,
331/// }
332///
333/// let json = r#"{"value": 42}"#;
334/// let data: Data = from_json_string(json).unwrap();
335/// assert_eq!(data.value, 42);
336/// ```
337pub fn from_json_string<T: for<'de> Deserialize<'de>>(json: &str) -> Result<T> {
338    serde_json::from_str(json).map_err(|e| Error::Serialization(e.to_string()))
339}
340
341/// Serializes a value to bincode bytes.
342///
343/// Bincode is more compact and faster than JSON, but not human-readable, and the bytes do
344/// not describe their own layout: the reader must decode into the same type definition.
345///
346/// # Errors
347///
348/// Returns [`Error::Serialization`] if the value cannot be serialized.
349///
350/// # Example
351///
352/// ```rust
353/// use orcher_sdk::payload::to_binary_bytes;
354/// use serde::{Serialize, Deserialize};
355///
356/// #[derive(Serialize, Deserialize)]
357/// struct Data {
358///     value: i32,
359/// }
360///
361/// let data = Data { value: 42 };
362/// let bytes = to_binary_bytes(&data).unwrap();
363/// ```
364pub fn to_binary_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>> {
365    bincode::serialize(value).map_err(|e| Error::Serialization(e.to_string()))
366}
367
368/// Deserializes a value from bincode bytes.
369///
370/// # Errors
371///
372/// Returns [`Error::Serialization`] if the bytes are not a valid bincode encoding of `T`.
373///
374/// # Example
375///
376/// ```rust
377/// use orcher_sdk::payload::{from_binary_bytes, to_binary_bytes};
378/// use serde::{Serialize, Deserialize};
379///
380/// #[derive(Serialize, Deserialize)]
381/// struct Data {
382///     value: i32,
383/// }
384///
385/// # let bytes = to_binary_bytes(&Data { value: 42 }).unwrap();
386/// let data: Data = from_binary_bytes(&bytes).unwrap();
387/// assert_eq!(data.value, 42);
388/// ```
389pub fn from_binary_bytes<T: for<'de> Deserialize<'de>>(bytes: &[u8]) -> Result<T> {
390    bincode::deserialize(bytes).map_err(|e| Error::Serialization(e.to_string()))
391}
392
393/// Encodes a value as a bincode [`Payload`].
394///
395/// Sets the `encoding` metadata to `bincode` and `content-type` to
396/// `application/octet-stream`. Decode it with [`from_binary_payload`].
397///
398/// # Errors
399///
400/// Returns [`Error::Serialization`] if the value cannot be serialized.
401///
402/// # Example
403///
404/// ```rust
405/// use orcher_sdk::payload::to_binary_payload;
406/// use serde::{Serialize, Deserialize};
407///
408/// #[derive(Serialize, Deserialize)]
409/// struct Data {
410///     value: i32,
411/// }
412///
413/// let data = Data { value: 42 };
414/// let payload = to_binary_payload(&data).unwrap();
415/// ```
416pub fn to_binary_payload<T: Serialize>(value: &T) -> Result<Payload> {
417    let bytes = to_binary_bytes(value)?;
418    let payload = Payload::new_data(bytes)
419        .with_metadata("encoding", "bincode")
420        .with_metadata("content-type", "application/octet-stream");
421    Ok(payload)
422}
423
424/// Decodes a value from a payload made by [`to_binary_payload`].
425///
426/// # Errors
427///
428/// Returns [`Error::Serialization`] if the payload bytes are not a valid bincode encoding
429/// of `T`.
430///
431/// # Example
432///
433/// ```rust
434/// use orcher_sdk::payload::{from_binary_payload, to_binary_payload};
435/// use serde::{Serialize, Deserialize};
436///
437/// #[derive(Serialize, Deserialize)]
438/// struct Data {
439///     value: i32,
440/// }
441///
442/// # let payload = to_binary_payload(&Data { value: 42 }).unwrap();
443/// let data: Data = from_binary_payload(&payload).unwrap();
444/// assert_eq!(data.value, 42);
445/// ```
446pub fn from_binary_payload<T: for<'de> Deserialize<'de>>(payload: &Payload) -> Result<T> {
447    from_binary_bytes(&payload.data)
448}
449
450#[cfg(feature = "compression")]
451use flate2::{read::GzDecoder, write::GzEncoder, Compression};
452
453#[cfg(feature = "compression")]
454use std::io::{Read, Write};
455
456/// Compresses bytes with gzip.
457///
458/// Requires the `compression` feature.
459///
460/// # Errors
461///
462/// Returns [`Error::Serialization`] if compression fails.
463///
464/// # Example
465///
466/// ```rust
467/// use orcher_sdk::payload::compress_bytes;
468///
469/// let data = b"Hello, World!".repeat(1000);
470/// let compressed = compress_bytes(&data).unwrap();
471/// assert!(compressed.len() < data.len());
472/// ```
473#[cfg(feature = "compression")]
474pub fn compress_bytes(bytes: &[u8]) -> Result<Vec<u8>> {
475    let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
476    encoder
477        .write_all(bytes)
478        .map_err(|e| Error::Serialization(format!("Compression failed: {}", e)))?;
479    encoder
480        .finish()
481        .map_err(|e| Error::Serialization(format!("Compression failed: {}", e)))
482}
483
484/// Decompresses gzip bytes.
485///
486/// Requires the `compression` feature.
487///
488/// # Errors
489///
490/// Returns [`Error::Serialization`] if the input is not valid gzip data.
491///
492/// # Example
493///
494/// ```rust
495/// use orcher_sdk::payload::{compress_bytes, decompress_bytes};
496///
497/// let data = b"Hello, World!".repeat(1000);
498/// let compressed = compress_bytes(&data).unwrap();
499/// let decompressed = decompress_bytes(&compressed).unwrap();
500/// assert_eq!(data, decompressed.as_slice());
501/// ```
502#[cfg(feature = "compression")]
503pub fn decompress_bytes(bytes: &[u8]) -> Result<Vec<u8>> {
504    let mut decoder = GzDecoder::new(bytes);
505    let mut decompressed = Vec::new();
506    decoder
507        .read_to_end(&mut decompressed)
508        .map_err(|e| Error::Serialization(format!("Decompression failed: {}", e)))?;
509    Ok(decompressed)
510}
511
512/// Encodes a value as gzip-compressed JSON in a [`Payload`].
513///
514/// Sets the `encoding` metadata to `json+gzip`, `content-type` to `application/json`, and
515/// `compressed` to `true`. Decode it with [`from_compressed_payload`]. Requires the
516/// `compression` feature.
517///
518/// # Errors
519///
520/// Returns [`Error::Serialization`] if serialization or compression fails.
521///
522/// # Example
523///
524/// ```rust
525/// use orcher_sdk::payload::to_compressed_payload;
526/// use serde::{Serialize, Deserialize};
527///
528/// #[derive(Serialize, Deserialize)]
529/// struct LargeData {
530///     items: Vec<String>,
531/// }
532///
533/// let data = LargeData { items: vec!["item".to_string(); 10000] };
534/// let payload = to_compressed_payload(&data).unwrap();
535/// ```
536#[cfg(feature = "compression")]
537pub fn to_compressed_payload<T: Serialize>(value: &T) -> Result<Payload> {
538    let json_bytes = to_json_bytes(value)?;
539    let compressed = compress_bytes(&json_bytes)?;
540    let payload = Payload::new_data(compressed)
541        .with_metadata("encoding", "json+gzip")
542        .with_metadata("content-type", "application/json")
543        .with_metadata("compressed", "true");
544    Ok(payload)
545}
546
547/// Decodes a value from a payload made by [`to_compressed_payload`].
548///
549/// Requires the `compression` feature.
550///
551/// # Errors
552///
553/// Returns [`Error::Serialization`] if the payload bytes are not valid gzip data or do not
554/// hold valid JSON for `T`.
555///
556/// # Example
557///
558/// ```rust
559/// use orcher_sdk::payload::{to_compressed_payload, from_compressed_payload};
560/// use serde::{Serialize, Deserialize};
561///
562/// #[derive(Serialize, Deserialize)]
563/// struct LargeData {
564///     items: Vec<String>,
565/// }
566///
567/// # let data = LargeData { items: vec!["item".to_string(); 10000] };
568/// # let payload = to_compressed_payload(&data).unwrap();
569/// let decoded: LargeData = from_compressed_payload(&payload).unwrap();
570/// ```
571#[cfg(feature = "compression")]
572pub fn from_compressed_payload<T: for<'de> Deserialize<'de>>(payload: &Payload) -> Result<T> {
573    let decompressed = decompress_bytes(&payload.data)?;
574    from_json_bytes(&decompressed)
575}
576
577/// Builds a [`Payload`] with custom metadata.
578///
579/// The `json`, `binary`, and `string` setters also set the matching `encoding` and
580/// `content-type` metadata; `bytes` sets only the data. A later setter replaces the data
581/// and overwrites those two keys.
582///
583/// # Example
584///
585/// ```rust
586/// use orcher_sdk::payload::PayloadBuilder;
587/// use serde::{Serialize, Deserialize};
588///
589/// #[derive(Serialize, Deserialize)]
590/// struct Data {
591///     value: i32,
592/// }
593///
594/// let data = Data { value: 42 };
595/// let payload = PayloadBuilder::new()
596///     .json(&data).unwrap()
597///     .metadata("version", "1.0")
598///     .metadata("source", "rust-sdk")
599///     .build();
600/// ```
601pub struct PayloadBuilder {
602    data: Vec<u8>,
603    metadata: HashMap<String, Vec<u8>>,
604}
605
606impl PayloadBuilder {
607    /// Creates a builder with empty data and no metadata.
608    pub fn new() -> Self {
609        Self {
610            data: Vec::new(),
611            metadata: HashMap::new(),
612        }
613    }
614
615    /// Sets the data to the JSON encoding of `value`.
616    ///
617    /// # Errors
618    ///
619    /// Returns [`Error::Serialization`] if the value cannot be serialized.
620    pub fn json<T: Serialize>(mut self, value: &T) -> Result<Self> {
621        self.data = to_json_bytes(value)?;
622        self.metadata
623            .insert("encoding".to_string(), b"json".to_vec());
624        self.metadata
625            .insert("content-type".to_string(), b"application/json".to_vec());
626        Ok(self)
627    }
628
629    /// Sets the data to the bincode encoding of `value`.
630    ///
631    /// # Errors
632    ///
633    /// Returns [`Error::Serialization`] if the value cannot be serialized.
634    pub fn binary<T: Serialize>(mut self, value: &T) -> Result<Self> {
635        self.data = to_binary_bytes(value)?;
636        self.metadata
637            .insert("encoding".to_string(), b"bincode".to_vec());
638        self.metadata.insert(
639            "content-type".to_string(),
640            b"application/octet-stream".to_vec(),
641        );
642        Ok(self)
643    }
644
645    /// Sets the data to raw bytes, leaving the metadata unchanged.
646    pub fn bytes(mut self, bytes: Vec<u8>) -> Self {
647        self.data = bytes;
648        self
649    }
650
651    /// Sets the data to a UTF-8 string.
652    pub fn string(mut self, value: impl Into<String>) -> Self {
653        self.data = value.into().into_bytes();
654        self.metadata
655            .insert("encoding".to_string(), b"utf-8".to_vec());
656        self.metadata
657            .insert("content-type".to_string(), b"text/plain".to_vec());
658        self
659    }
660
661    /// Adds a metadata entry, replacing any existing value for `key`.
662    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<Vec<u8>>) -> Self {
663        self.metadata.insert(key.into(), value.into());
664        self
665    }
666
667    /// Returns the finished payload.
668    pub fn build(self) -> Payload {
669        Payload {
670            data: self.data,
671            metadata: self.metadata,
672        }
673    }
674}
675
676impl Default for PayloadBuilder {
677    fn default() -> Self {
678        Self::new()
679    }
680}
681
682#[cfg(test)]
683mod tests {
684    use super::*;
685    use serde::{Deserialize, Serialize};
686
687    #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
688    struct TestData {
689        name: String,
690        value: i32,
691    }
692
693    #[test]
694    fn test_to_from_payload() {
695        let data = TestData {
696            name: "test".to_string(),
697            value: 42,
698        };
699
700        let payload = to_payload(&data).unwrap();
701        let decoded: TestData = from_payload(&payload).unwrap();
702
703        assert_eq!(data, decoded);
704    }
705
706    #[test]
707    fn test_payload_codec_trait() {
708        let data = TestData {
709            name: "test".to_string(),
710            value: 42,
711        };
712
713        let payload = data.to_payload().unwrap();
714        let decoded = TestData::from_payload(&payload).unwrap();
715
716        assert_eq!(data, decoded);
717    }
718
719    #[test]
720    fn test_json_bytes() {
721        let data = TestData {
722            name: "test".to_string(),
723            value: 42,
724        };
725
726        let bytes = to_json_bytes(&data).unwrap();
727        let decoded: TestData = from_json_bytes(&bytes).unwrap();
728
729        assert_eq!(data, decoded);
730    }
731
732    #[test]
733    fn test_json_string() {
734        let data = TestData {
735            name: "test".to_string(),
736            value: 42,
737        };
738
739        let json = to_json_string(&data).unwrap();
740        assert!(json.contains("test"));
741        assert!(json.contains("42"));
742
743        let decoded: TestData = from_json_string(&json).unwrap();
744        assert_eq!(data, decoded);
745    }
746
747    #[test]
748    fn test_binary_serialization() {
749        let data = TestData {
750            name: "test".to_string(),
751            value: 42,
752        };
753
754        let bytes = to_binary_bytes(&data).unwrap();
755        let decoded: TestData = from_binary_bytes(&bytes).unwrap();
756
757        assert_eq!(data, decoded);
758    }
759
760    #[test]
761    fn test_binary_payload() {
762        let data = TestData {
763            name: "test".to_string(),
764            value: 42,
765        };
766
767        let payload = to_binary_payload(&data).unwrap();
768        assert_eq!(
769            payload.get_metadata_string("encoding"),
770            Some("bincode".to_string())
771        );
772
773        let decoded: TestData = from_binary_payload(&payload).unwrap();
774        assert_eq!(data, decoded);
775    }
776
777    #[test]
778    fn test_payload_builder() {
779        let data = TestData {
780            name: "builder".to_string(),
781            value: 100,
782        };
783
784        let payload = PayloadBuilder::new()
785            .json(&data)
786            .unwrap()
787            .metadata("version", "1.0")
788            .metadata("custom", "value")
789            .build();
790
791        assert_eq!(
792            payload.get_metadata_string("version"),
793            Some("1.0".to_string())
794        );
795        assert_eq!(
796            payload.get_metadata_string("custom"),
797            Some("value".to_string())
798        );
799
800        let decoded: TestData = from_payload(&payload).unwrap();
801        assert_eq!(data, decoded);
802    }
803
804    #[test]
805    fn test_payload_builder_string() {
806        let payload = PayloadBuilder::new()
807            .string("Hello, World!")
808            .metadata("author", "test")
809            .build();
810
811        let text = String::from_utf8(payload.data.clone()).unwrap();
812        assert_eq!(text, "Hello, World!");
813        assert_eq!(
814            payload.get_metadata_string("author"),
815            Some("test".to_string())
816        );
817    }
818
819    #[test]
820    fn test_payload_builder_bytes() {
821        let bytes = vec![1, 2, 3, 4, 5];
822        let payload = PayloadBuilder::new()
823            .bytes(bytes.clone())
824            .metadata("type", "binary")
825            .build();
826
827        assert_eq!(payload.data, bytes);
828        assert_eq!(
829            payload.get_metadata_string("type"),
830            Some("binary".to_string())
831        );
832    }
833
834    #[test]
835    fn test_empty_payload() {
836        let payload = Payload::default();
837        assert!(payload.is_empty());
838        assert_eq!(payload.len(), 0);
839    }
840
841    #[test]
842    fn test_payload_metadata() {
843        let payload = Payload::new_data(vec![1, 2, 3])
844            .with_metadata("key1", "value1")
845            .with_metadata("key2", b"value2".to_vec());
846
847        assert_eq!(
848            payload.get_metadata_string("key1"),
849            Some("value1".to_string())
850        );
851        assert_eq!(payload.get_metadata("key2"), Some(b"value2".as_slice()));
852    }
853
854    #[cfg(feature = "compression")]
855    #[test]
856    fn test_compression() {
857        let data = b"Hello, World!".repeat(100);
858        let compressed = compress_bytes(&data).unwrap();
859
860        // Repetitive input must shrink.
861        assert!(compressed.len() < data.len());
862
863        let decompressed = decompress_bytes(&compressed).unwrap();
864        assert_eq!(data.to_vec(), decompressed);
865    }
866
867    #[cfg(feature = "compression")]
868    #[test]
869    fn test_compressed_payload() {
870        let data = TestData {
871            name: "compressed".to_string(),
872            value: 999,
873        };
874
875        let payload = to_compressed_payload(&data).unwrap();
876        assert_eq!(
877            payload.get_metadata_string("compressed"),
878            Some("true".to_string())
879        );
880
881        let decoded: TestData = from_compressed_payload(&payload).unwrap();
882        assert_eq!(data, decoded);
883    }
884}