turbomcp-protocol 3.0.13

Complete MCP protocol implementation with types, traits, context management, and message handling
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
//! Optimized message types and serialization.
//!
//! This module provides the standard message handling abstraction for `TurboMCP`.
//! It supports multiple serialization formats (`JSON`, `MessagePack`, `CBOR`) and
//! includes SIMD acceleration when available.
//!
//! ## Message Types
//!
//! This is the **recommended message type** for most use cases. It provides:
//!
//! - Multiple serialization formats (`JSON`, `MessagePack`, `CBOR`)
//! - Automatic format detection
//! - SIMD-accelerated JSON parsing (when `simd` feature enabled)
//! - Cached parsed values for efficient reuse
//! - Ergonomic API for common operations
//!
//! For extreme performance scenarios, see [`ZeroCopyMessage`](crate::zero_copy::ZeroCopyMessage).
//!
//! ## Example
//!
//! ```rust
//! use turbomcp_protocol::{Message, MessageId};
//! use serde_json::json;
//!
//! // Create a JSON message
//! let msg = Message::json(
//!     MessageId::from("req-1"),
//!     json!({"method": "test", "params": {}})
//! )?;
//!
//! // Parse to specific type
//! #[derive(serde::Deserialize)]
//! struct Request {
//!     method: String,
//!     params: serde_json::Value,
//! }
//!
//! let request: Request = msg.parse_json()?;
//! assert_eq!(request.method, "test");
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use flate2::Compression;
use flate2::write::GzEncoder;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

use bytes::{Bytes, BytesMut};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[cfg(feature = "messagepack")]
use msgpacker::Packable;

use crate::types::{ContentType, ProtocolVersion, Timestamp};
use crate::{McpError as Error, Result};

/// A msgpacker-compatible representation of JSON values
#[cfg(feature = "messagepack")]
#[derive(Debug, Clone)]
pub enum JsonValue {
    /// Represents a null JSON value
    Null,
    /// Represents a boolean JSON value
    Bool(bool),
    /// Represents a numeric JSON value (stored as f64)
    Number(f64),
    /// Represents a string JSON value
    String(String),
    /// Represents an array JSON value
    Array(Vec<JsonValue>),
    /// Represents an object JSON value
    Object(std::collections::HashMap<String, JsonValue>),
}

#[cfg(feature = "messagepack")]
impl JsonValue {
    /// Converts a `serde_json::Value` into a `JsonValue` for msgpacker serialization
    pub fn from_serde_json(value: &serde_json::Value) -> Self {
        match value {
            serde_json::Value::Null => JsonValue::Null,
            serde_json::Value::Bool(b) => JsonValue::Bool(*b),
            serde_json::Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    JsonValue::Number(i as f64)
                } else if let Some(u) = n.as_u64() {
                    JsonValue::Number(u as f64)
                } else if let Some(f) = n.as_f64() {
                    JsonValue::Number(f)
                } else {
                    JsonValue::Null
                }
            }
            serde_json::Value::String(s) => JsonValue::String(s.clone()),
            serde_json::Value::Array(arr) => {
                JsonValue::Array(arr.iter().map(Self::from_serde_json).collect())
            }
            serde_json::Value::Object(obj) => {
                let mut map = std::collections::HashMap::new();
                for (k, v) in obj {
                    map.insert(k.clone(), Self::from_serde_json(v));
                }
                JsonValue::Object(map)
            }
        }
    }
}

#[cfg(feature = "messagepack")]
impl msgpacker::Packable for JsonValue {
    fn pack<T>(&self, buf: &mut T) -> usize
    where
        T: Extend<u8>,
    {
        match self {
            JsonValue::Null => {
                // Pack nil
                buf.extend([0xc0]);
                1
            }
            JsonValue::Bool(b) => b.pack(buf),
            JsonValue::Number(n) => n.pack(buf),
            JsonValue::String(s) => s.pack(buf),
            JsonValue::Array(arr) => {
                // Pack array manually since Vec<JsonValue> doesn't implement Packable
                let len = arr.len();
                let mut bytes_written = 0;

                // Pack array length
                if len <= 15 {
                    buf.extend([0x90 + len as u8]);
                    bytes_written += 1;
                } else if len <= u16::MAX as usize {
                    buf.extend([0xdc]);
                    buf.extend((len as u16).to_be_bytes());
                    bytes_written += 3;
                } else {
                    buf.extend([0xdd]);
                    buf.extend((len as u32).to_be_bytes());
                    bytes_written += 5;
                }

                // Pack array elements
                for item in arr {
                    bytes_written += item.pack(buf);
                }

                bytes_written
            }
            JsonValue::Object(obj) => {
                // Pack map manually since HashMap<String, JsonValue> doesn't implement Packable
                let len = obj.len();
                let mut bytes_written = 0;

                // Pack map length
                if len <= 15 {
                    buf.extend([0x80 + len as u8]);
                    bytes_written += 1;
                } else if len <= u16::MAX as usize {
                    buf.extend([0xde]);
                    buf.extend((len as u16).to_be_bytes());
                    bytes_written += 3;
                } else {
                    buf.extend([0xdf]);
                    buf.extend((len as u32).to_be_bytes());
                    bytes_written += 5;
                }

                // Pack key-value pairs
                for (k, v) in obj {
                    bytes_written += k.pack(buf);
                    bytes_written += v.pack(buf);
                }

                bytes_written
            }
        }
    }
}

/// Unique identifier for messages
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MessageId {
    /// String identifier
    String(String),
    /// Numeric identifier
    Number(i64),
    /// UUID identifier
    Uuid(Uuid),
}

/// Message metadata for tracking and debugging
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageMetadata {
    /// Message creation timestamp
    pub created_at: Timestamp,

    /// Protocol version used
    pub protocol_version: ProtocolVersion,

    /// Content encoding (gzip, brotli, etc.)
    pub encoding: Option<String>,

    /// Content type of the payload
    pub content_type: ContentType,

    /// Message size in bytes
    pub size: usize,

    /// Correlation ID for request tracing
    pub correlation_id: Option<String>,

    /// Custom headers
    pub headers: HashMap<String, String>,
}

/// Optimized message container with zero-copy support
#[derive(Debug, Clone)]
pub struct Message {
    /// Message identifier
    pub id: MessageId,

    /// Message metadata
    pub metadata: MessageMetadata,

    /// Message payload with zero-copy optimization
    pub payload: MessagePayload,
}

/// Zero-copy message payload
#[derive(Debug, Clone)]
pub enum MessagePayload {
    /// JSON payload with potential zero-copy
    Json(JsonPayload),

    /// Binary payload (`MessagePack`, Protocol Buffers, etc.)
    Binary(BinaryPayload),

    /// Text payload
    Text(String),

    /// Empty payload
    Empty,
}

/// JSON payload with zero-copy support
#[derive(Debug, Clone)]
pub struct JsonPayload {
    /// Raw JSON bytes (zero-copy when possible)
    pub raw: Bytes,

    /// Parsed JSON value (lazily evaluated)
    pub parsed: Option<Arc<serde_json::Value>>,

    /// Whether the raw bytes are valid JSON
    pub is_valid: bool,
}

/// Binary payload for efficient serialization formats
#[derive(Debug, Clone)]
pub struct BinaryPayload {
    /// Raw binary data
    pub data: Bytes,

    /// Binary format identifier
    pub format: BinaryFormat,
}

/// Supported binary serialization formats
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BinaryFormat {
    /// `MessagePack` format
    MessagePack,

    /// Protocol Buffers
    ProtoBuf,

    /// CBOR (Concise Binary Object Representation)
    Cbor,

    /// Custom binary format
    Custom,
}

/// Message serializer with format detection
#[derive(Debug)]
pub struct MessageSerializer {
    /// Default serialization format
    default_format: SerializationFormat,

    /// Whether to enable compression
    enable_compression: bool,

    /// Compression threshold in bytes
    compression_threshold: usize,
}

/// Supported serialization formats
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SerializationFormat {
    /// Standard JSON
    Json,

    /// Fast JSON with SIMD
    #[cfg(feature = "simd")]
    SimdJson,

    /// `MessagePack` binary format
    MessagePack,

    /// CBOR binary format
    Cbor,
}

impl Message {
    /// Create a new message with JSON payload
    ///
    /// # Errors
    ///
    /// Returns an error if the value cannot be serialized to JSON.
    pub fn json(id: MessageId, value: impl Serialize) -> Result<Self> {
        let json_bytes = Self::serialize_json(&value)?;
        let payload = MessagePayload::Json(JsonPayload {
            raw: json_bytes.freeze(),
            parsed: Some(Arc::new(serde_json::to_value(value)?)),
            is_valid: true,
        });

        Ok(Self {
            id,
            metadata: MessageMetadata::new(ContentType::Json, payload.size()),
            payload,
        })
    }

    /// Create a new message with binary payload
    pub fn binary(id: MessageId, data: Bytes, format: BinaryFormat) -> Self {
        let size = data.len();
        let payload = MessagePayload::Binary(BinaryPayload { data, format });

        Self {
            id,
            metadata: MessageMetadata::new(ContentType::Binary, size),
            payload,
        }
    }

    /// Create a new message with text payload
    #[must_use]
    pub fn text(id: MessageId, text: String) -> Self {
        let size = text.len();
        let payload = MessagePayload::Text(text);

        Self {
            id,
            metadata: MessageMetadata::new(ContentType::Text, size),
            payload,
        }
    }

    /// Create an empty message
    #[must_use]
    pub fn empty(id: MessageId) -> Self {
        Self {
            id,
            metadata: MessageMetadata::new(ContentType::Json, 0),
            payload: MessagePayload::Empty,
        }
    }

    /// Get the message size in bytes
    pub const fn size(&self) -> usize {
        self.metadata.size
    }

    /// Check if the message is empty
    pub const fn is_empty(&self) -> bool {
        matches!(self.payload, MessagePayload::Empty)
    }

    /// Serialize message to bytes using the specified format
    ///
    /// # Errors
    ///
    /// Returns an error if serialization fails for the specified format.
    pub fn serialize(&self, format: SerializationFormat) -> Result<Bytes> {
        match format {
            SerializationFormat::Json => self.serialize_json_format(),
            #[cfg(feature = "simd")]
            SerializationFormat::SimdJson => self.serialize_simd_json(),
            SerializationFormat::MessagePack => self.serialize_messagepack(),
            SerializationFormat::Cbor => self.serialize_cbor(),
        }
    }

    /// Deserialize message from bytes with format auto-detection
    ///
    /// # Errors
    ///
    /// Returns an error if format detection fails or deserialization fails.
    pub fn deserialize(bytes: Bytes) -> Result<Self> {
        // Try to detect format from content
        let format = Self::detect_format(&bytes);
        Self::deserialize_with_format(bytes, format)
    }

    /// Deserialize message from bytes using specified format
    pub fn deserialize_with_format(bytes: Bytes, format: SerializationFormat) -> Result<Self> {
        match format {
            SerializationFormat::Json => Ok(Self::deserialize_json(bytes)),
            #[cfg(feature = "simd")]
            SerializationFormat::SimdJson => Ok(Self::deserialize_simd_json(bytes)),
            SerializationFormat::MessagePack => Ok(Self::deserialize_messagepack(bytes)),
            SerializationFormat::Cbor => Self::deserialize_cbor(bytes),
        }
    }

    /// Parse JSON payload to structured data
    pub fn parse_json<T>(&self) -> Result<T>
    where
        T: for<'de> Deserialize<'de>,
    {
        match &self.payload {
            MessagePayload::Json(json_payload) => json_payload.parsed.as_ref().map_or_else(
                || {
                    #[cfg(feature = "simd")]
                    {
                        let mut json_bytes = json_payload.raw.to_vec();
                        simd_json::from_slice(&mut json_bytes).map_err(|e| {
                            Error::serialization(format!("SIMD JSON parsing failed: {e}"))
                        })
                    }
                    #[cfg(not(feature = "simd"))]
                    {
                        serde_json::from_slice(&json_payload.raw).map_err(|e| {
                            Error::serialization(format!("JSON parsing failed: {}", e))
                        })
                    }
                },
                |parsed| {
                    serde_json::from_value((**parsed).clone())
                        .map_err(|e| Error::serialization(format!("JSON parsing failed: {e}")))
                },
            ),
            _ => Err(Error::invalid_params("Message payload is not JSON")),
        }
    }

    // Private helper methods

    fn serialize_json(value: &impl Serialize) -> Result<BytesMut> {
        #[cfg(feature = "simd")]
        {
            sonic_rs::to_vec(value)
                .map(|v| BytesMut::from(v.as_slice()))
                .map_err(|e| Error::serialization(format!("SIMD JSON serialization failed: {e}")))
        }
        #[cfg(not(feature = "simd"))]
        {
            serde_json::to_vec(value)
                .map(|v| BytesMut::from(v.as_slice()))
                .map_err(|e| Error::serialization(format!("JSON serialization failed: {}", e)))
        }
    }

    fn serialize_json_format(&self) -> Result<Bytes> {
        match &self.payload {
            MessagePayload::Json(json_payload) => Ok(json_payload.raw.clone()),
            MessagePayload::Text(text) => Ok(Bytes::from(text.clone())),
            MessagePayload::Empty => Ok(Bytes::from_static(b"{}")),
            MessagePayload::Binary(_) => Err(Error::invalid_params(
                "Cannot serialize non-JSON payload as JSON",
            )),
        }
    }

    #[cfg(feature = "simd")]
    fn serialize_simd_json(&self) -> Result<Bytes> {
        match &self.payload {
            MessagePayload::Json(json_payload) => {
                if json_payload.is_valid {
                    Ok(json_payload.raw.clone())
                } else {
                    Err(Error::serialization("Invalid JSON payload"))
                }
            }
            _ => Err(Error::invalid_params(
                "Cannot serialize non-JSON payload with SIMD JSON",
            )),
        }
    }

    fn serialize_messagepack(&self) -> Result<Bytes> {
        #[cfg(feature = "messagepack")]
        {
            match &self.payload {
                MessagePayload::Binary(binary) if binary.format == BinaryFormat::MessagePack => {
                    Ok(binary.data.clone())
                }
                MessagePayload::Json(json_payload) => json_payload.parsed.as_ref().map_or_else(
                    || {
                        Err(Error::serialization(
                            "Cannot serialize unparsed JSON to MessagePack",
                        ))
                    },
                    |parsed| {
                        // Convert serde_json::Value to msgpacker-compatible format
                        let packable_value = JsonValue::from_serde_json(parsed.as_ref());
                        let mut buffer = Vec::new();
                        packable_value.pack(&mut buffer);
                        Ok(Bytes::from(buffer))
                    },
                ),
                _ => Err(Error::invalid_params(
                    "Cannot serialize payload as MessagePack",
                )),
            }
        }
        #[cfg(not(feature = "messagepack"))]
        {
            let _ = self; // Silence unused warning
            Err(Error::invalid_params(
                "MessagePack serialization not available",
            ))
        }
    }

    fn serialize_cbor(&self) -> Result<Bytes> {
        match &self.payload {
            MessagePayload::Binary(binary) if binary.format == BinaryFormat::Cbor => {
                Ok(binary.data.clone())
            }
            MessagePayload::Json(json_payload) => {
                if let Some(parsed) = &json_payload.parsed {
                    {
                        let mut buffer = Vec::new();
                        ciborium::into_writer(parsed.as_ref(), &mut buffer)
                            .map(|_| Bytes::from(buffer))
                            .map_err(|e| {
                                Error::serialization(format!("CBOR serialization failed: {e}"))
                            })
                    }
                } else {
                    // Fallback: attempt to parse then encode
                    #[cfg(feature = "simd")]
                    {
                        let mut json_bytes = json_payload.raw.to_vec();
                        let value: serde_json::Value = simd_json::from_slice(&mut json_bytes)
                            .map_err(|e| {
                                Error::serialization(format!(
                                    "SIMD JSON parsing failed before CBOR: {e}"
                                ))
                            })?;
                        {
                            let mut buffer = Vec::new();
                            ciborium::into_writer(&value, &mut buffer)
                                .map(|_| Bytes::from(buffer))
                                .map_err(|e| {
                                    Error::serialization(format!("CBOR serialization failed: {e}"))
                                })
                        }
                    }
                    #[cfg(not(feature = "simd"))]
                    {
                        let value: serde_json::Value = serde_json::from_slice(&json_payload.raw)
                            .map_err(|e| {
                                Error::serialization(format!(
                                    "JSON parsing failed before CBOR: {}",
                                    e
                                ))
                            })?;
                        let mut buf = Vec::new();
                        ciborium::ser::into_writer(&value, &mut buf).map_err(|e| {
                            Error::serialization(format!("CBOR serialization failed: {}", e))
                        })?;
                        Ok(Bytes::from(buf))
                    }
                }
            }
            _ => Err(Error::invalid_params("Cannot serialize payload as CBOR")),
        }
    }

    fn deserialize_json(bytes: Bytes) -> Self {
        // Validate JSON format
        let is_valid = serde_json::from_slice::<serde_json::Value>(&bytes).is_ok();

        let payload = MessagePayload::Json(JsonPayload {
            raw: bytes,
            parsed: None, // Lazy evaluation
            is_valid,
        });

        Self {
            id: MessageId::Uuid(Uuid::new_v4()),
            metadata: MessageMetadata::new(ContentType::Json, payload.size()),
            payload,
        }
    }

    #[cfg(feature = "simd")]
    fn deserialize_simd_json(bytes: Bytes) -> Self {
        let mut json_bytes = bytes.to_vec();
        let is_valid = simd_json::from_slice::<serde_json::Value>(&mut json_bytes).is_ok();

        let payload = MessagePayload::Json(JsonPayload {
            raw: bytes,
            parsed: None,
            is_valid,
        });

        Self {
            id: MessageId::Uuid(Uuid::new_v4()),
            metadata: MessageMetadata::new(ContentType::Json, payload.size()),
            payload,
        }
    }

    fn deserialize_messagepack(bytes: Bytes) -> Self {
        let payload = MessagePayload::Binary(BinaryPayload {
            data: bytes,
            format: BinaryFormat::MessagePack,
        });

        Self {
            id: MessageId::Uuid(Uuid::new_v4()),
            metadata: MessageMetadata::new(ContentType::Binary, payload.size()),
            payload,
        }
    }

    fn deserialize_cbor(bytes: Bytes) -> Result<Self> {
        // Accept raw CBOR as binary or attempt to decode into JSON Value
        if let Ok(value) = ciborium::from_reader::<serde_json::Value, _>(&bytes[..]) {
            let raw = serde_json::to_vec(&value)
                .map(Bytes::from)
                .map_err(|e| Error::serialization(format!("JSON re-encode failed: {e}")))?;
            let payload = MessagePayload::Json(JsonPayload {
                raw,
                parsed: Some(Arc::new(value)),
                is_valid: true,
            });
            return Ok(Self {
                id: MessageId::Uuid(Uuid::new_v4()),
                metadata: MessageMetadata::new(ContentType::Json, payload.size()),
                payload,
            });
        }

        // If decoding to JSON fails, keep as CBOR binary
        let payload = MessagePayload::Binary(BinaryPayload {
            data: bytes,
            format: BinaryFormat::Cbor,
        });
        Ok(Self {
            id: MessageId::Uuid(Uuid::new_v4()),
            metadata: MessageMetadata::new(ContentType::Binary, payload.size()),
            payload,
        })
    }

    fn detect_format(bytes: &[u8]) -> SerializationFormat {
        if bytes.is_empty() {
            return SerializationFormat::Json;
        }

        // Check for JSON (starts with '{' or '[')
        if matches!(bytes[0], b'{' | b'[') {
            #[cfg(feature = "simd")]
            {
                return SerializationFormat::SimdJson;
            }
            #[cfg(not(feature = "simd"))]
            {
                return SerializationFormat::Json;
            }
        }

        // Check for MessagePack (starts with specific bytes)
        if bytes.len() >= 2 && (bytes[0] == 0x82 || bytes[0] == 0x83) {
            return SerializationFormat::MessagePack;
        }

        // Default to JSON
        #[cfg(feature = "simd")]
        {
            SerializationFormat::SimdJson
        }
        #[cfg(not(feature = "simd"))]
        {
            SerializationFormat::Json
        }
    }
}

impl MessagePayload {
    /// Get the size of the payload in bytes
    pub const fn size(&self) -> usize {
        match self {
            Self::Json(json) => json.raw.len(),
            Self::Binary(binary) => binary.data.len(),
            Self::Text(text) => text.len(),
            Self::Empty => 0,
        }
    }
}

impl MessageMetadata {
    /// Create new message metadata
    #[must_use]
    pub fn new(content_type: ContentType, size: usize) -> Self {
        Self {
            created_at: Timestamp::now(),
            protocol_version: ProtocolVersion::LATEST.clone(),
            encoding: None,
            content_type,
            size,
            correlation_id: None,
            headers: HashMap::new(),
        }
    }

    /// Add a custom header
    #[must_use]
    pub fn with_header(mut self, key: String, value: String) -> Self {
        self.headers.insert(key, value);
        self
    }

    /// Set correlation ID for tracing
    #[must_use]
    pub fn with_correlation_id(mut self, correlation_id: String) -> Self {
        self.correlation_id = Some(correlation_id);
        self
    }

    /// Set content encoding
    #[must_use]
    pub fn with_encoding(mut self, encoding: String) -> Self {
        self.encoding = Some(encoding);
        self
    }
}

impl MessageSerializer {
    /// Create a new message serializer with default settings
    #[must_use]
    pub const fn new() -> Self {
        Self {
            default_format: SerializationFormat::Json,
            enable_compression: false,
            compression_threshold: 1024, // 1KB
        }
    }

    /// Set the default serialization format
    #[must_use]
    pub const fn with_format(mut self, format: SerializationFormat) -> Self {
        self.default_format = format;
        self
    }

    /// Enable compression for messages above threshold
    #[must_use]
    pub const fn with_compression(mut self, enable: bool, threshold: usize) -> Self {
        self.enable_compression = enable;
        self.compression_threshold = threshold;
        self
    }

    /// Serialize a message using the default format
    pub fn serialize(&self, message: &mut Message) -> Result<Bytes> {
        let serialized = message.serialize(self.default_format)?;

        // Apply compression if enabled and message is large enough
        if self.enable_compression && serialized.len() > self.compression_threshold {
            message.metadata.encoding = Some("gzip".to_string()); // Set encoding to gzip
            Ok(self.compress(serialized))
        } else {
            Ok(serialized)
        }
    }

    /// Compresses the given data using gzip.
    /// Returns the compressed data, or the original data if compression fails.
    fn compress(&self, data: Bytes) -> Bytes {
        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        if let Err(e) = std::io::Write::write_all(&mut encoder, &data) {
            eprintln!("Failed to compress data: {}", e);
            return data; // Return original data on error
        }
        match encoder.finish() {
            Ok(compressed_data) => Bytes::from(compressed_data),
            Err(e) => {
                eprintln!("Failed to finish compression: {}", e);
                data // Return original data on error
            }
        }
    }
}

impl Default for MessageSerializer {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for MessageId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::String(s) => write!(f, "{s}"),
            Self::Number(n) => write!(f, "{n}"),
            Self::Uuid(u) => write!(f, "{u}"),
        }
    }
}

impl From<String> for MessageId {
    fn from(s: String) -> Self {
        Self::String(s)
    }
}

impl From<&str> for MessageId {
    fn from(s: &str) -> Self {
        Self::String(s.to_string())
    }
}

impl From<i64> for MessageId {
    fn from(n: i64) -> Self {
        Self::Number(n)
    }
}

impl From<Uuid> for MessageId {
    fn from(u: Uuid) -> Self {
        Self::Uuid(u)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_message_creation() {
        let message = Message::json(MessageId::from("test"), json!({"key": "value"})).unwrap();
        assert_eq!(message.id.to_string(), "test");
        assert!(!message.is_empty());
    }

    #[test]
    fn test_message_serialization() {
        let message = Message::json(MessageId::from(1), json!({"test": true})).unwrap();
        let serialized = message.serialize(SerializationFormat::Json).unwrap();
        assert!(!serialized.is_empty());
    }

    #[derive(Deserialize, PartialEq, Debug)]
    struct TestData {
        number: i32,
    }

    #[test]
    fn test_message_parsing() {
        let message = Message::json(MessageId::from("test"), json!({"number": 42})).unwrap();

        let parsed: TestData = message.parse_json().unwrap();
        assert_eq!(parsed.number, 42);
    }

    #[test]
    fn test_format_detection() {
        let json_bytes = Bytes::from(r#"{"test": true}"#);
        let format = Message::detect_format(&json_bytes);

        #[cfg(feature = "simd")]
        assert_eq!(format, SerializationFormat::SimdJson);
        #[cfg(not(feature = "simd"))]
        assert_eq!(format, SerializationFormat::Json);
    }

    #[test]
    fn test_message_metadata() {
        let metadata = MessageMetadata::new(ContentType::Json, 100)
            .with_header("custom".to_string(), "value".to_string())
            .with_correlation_id("corr-123".to_string());

        assert_eq!(metadata.size, 100);
        assert_eq!(metadata.headers.get("custom"), Some(&"value".to_string()));
        assert_eq!(metadata.correlation_id, Some("corr-123".to_string()));
    }

    #[test]
    fn test_message_serializer_compression() {
        use flate2::read::GzDecoder;
        use std::io::Read;

        let serializer = MessageSerializer::new().with_compression(true, 10); // Enable compression with a low threshold

        let large_json = json!({
            "data": "a".repeat(100), // A string larger than 10 bytes
        });
        let mut message =
            Message::json(MessageId::from("compressed_test"), large_json.clone()).unwrap();

        let original_size = message.size();
        assert!(
            original_size > 10,
            "Original message size should be greater than compression threshold"
        );

        let compressed_bytes = serializer.serialize(&mut message).unwrap();

        // Assert encoding metadata is set
        assert_eq!(message.metadata.encoding, Some("gzip".to_string()));

        // Assert compressed size is smaller (unless data is incompressible)
        assert!(
            compressed_bytes.len() < original_size,
            "Compressed size should be smaller than original"
        );

        // Decompress and verify content
        let mut decoder = GzDecoder::new(&compressed_bytes[..]);
        let mut decompressed_data = Vec::new();
        decoder.read_to_end(&mut decompressed_data).unwrap();

        let decompressed_message = Message::deserialize(Bytes::from(decompressed_data)).unwrap();
        let parsed_json: serde_json::Value = decompressed_message.parse_json().unwrap();

        assert_eq!(parsed_json, large_json);
    }
}