hyperi-rustlib 2.5.5

Opinionated Rust framework for high-throughput data pipelines at PB scale. Auto-wiring config, logging, metrics, tracing, health, and graceful shutdown — built from many years of production infrastructure experience.
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
// Project:   hyperi-rustlib
// File:      src/transport/detect.rs
// Purpose:   Stateful payload format detection with auto-locking
// Language:  Rust
//
// License:   FSL-1.1-ALv2
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! # Format Detection
//!
//! Stateful payload format detection that auto-locks to the first detected format.
//! Mismatched formats can be sent to DLQ, or the detector can auto-reset after
//! sustained mismatches.
//!
//! ## Modes
//!
//! - **Auto** (default): Detect format from first message, lock it
//! - **ForceJson**: Only accept JSON, reject MessagePack
//! - **ForceMessagePack**: Only accept MessagePack, reject JSON
//!
//! ## Example
//!
//! ```rust
//! use hyperi_rustlib::transport::{FormatDetector, FormatMode, DetectedFormat};
//!
//! let detector = FormatDetector::new();
//!
//! // First message sets the format
//! let result = detector.check_and_detect(br#"{"event": "login"}"#);
//! assert!(result.is_ok());
//! assert_eq!(detector.format(), DetectedFormat::Json);
//!
//! // Subsequent messages must match
//! let result = detector.check_and_detect(br#"{"event": "logout"}"#);
//! assert!(result.is_ok());
//!
//! // Mismatched format returns Err (send to DLQ)
//! let msgpack = [0x81, 0xa3, b'f', b'o', b'o'];
//! let result = detector.check_and_detect(&msgpack);
//! assert!(result.is_err());
//! ```

use std::sync::atomic::{AtomicU8, Ordering};

/// Detected payload format (for stateful detection).
///
/// Separate from `PayloadFormat` which includes `Auto` for config purposes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum DetectedFormat {
    /// Format not yet detected
    Unknown = 0,
    /// JSON format
    Json = 1,
    /// MessagePack format
    MessagePack = 2,
}

impl From<u8> for DetectedFormat {
    fn from(v: u8) -> Self {
        match v {
            1 => DetectedFormat::Json,
            2 => DetectedFormat::MessagePack,
            _ => DetectedFormat::Unknown,
        }
    }
}

/// Format detection mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FormatMode {
    /// Auto-detect format from first message (default)
    #[default]
    Auto,
    /// Force JSON only - reject MessagePack
    ForceJson,
    /// Force MessagePack only - reject JSON
    ForceMessagePack,
}

impl FormatMode {
    /// Parse from string (for config).
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "auto" => Some(FormatMode::Auto),
            "json" => Some(FormatMode::ForceJson),
            "messagepack" | "msgpack" => Some(FormatMode::ForceMessagePack),
            _ => None,
        }
    }
}

/// Stateful format detector with auto-detection and locking.
///
/// Once a format is detected, the detector locks to that format.
/// Mismatches return `Err` (for DLQ routing). After sustained mismatches
/// (configurable threshold), the detector auto-resets in Auto mode.
pub struct FormatDetector {
    detected_format: AtomicU8,
    mismatch_count: AtomicU8,
    mode: FormatMode,
}

impl FormatDetector {
    /// Threshold of consecutive mismatches before considering format reset (Auto mode only)
    const MISMATCH_THRESHOLD: u8 = 10;

    /// Create a new detector in Auto mode.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            detected_format: AtomicU8::new(DetectedFormat::Unknown as u8),
            mismatch_count: AtomicU8::new(0),
            mode: FormatMode::Auto,
        }
    }

    /// Create a detector with a specific mode.
    #[must_use]
    pub fn with_mode(mode: FormatMode) -> Self {
        let initial_format = match mode {
            FormatMode::Auto => DetectedFormat::Unknown,
            FormatMode::ForceJson => DetectedFormat::Json,
            FormatMode::ForceMessagePack => DetectedFormat::MessagePack,
        };
        Self {
            detected_format: AtomicU8::new(initial_format as u8),
            mismatch_count: AtomicU8::new(0),
            mode,
        }
    }

    /// Get the current mode.
    #[must_use]
    pub fn mode(&self) -> FormatMode {
        self.mode
    }

    /// Get the currently detected format.
    #[must_use]
    pub fn format(&self) -> DetectedFormat {
        DetectedFormat::from(self.detected_format.load(Ordering::Relaxed))
    }

    /// Check if format matches expected, tracking mismatches.
    ///
    /// Returns `Ok(format)` if message should be processed, `Err(expected)` if it
    /// should go to DLQ (expected format returned for error context).
    #[inline]
    pub fn check_and_detect(&self, payload: &[u8]) -> Result<DetectedFormat, DetectedFormat> {
        let detected = detect_format_bytes(payload);

        // Handle forced modes - no auto-detection, no reset
        match self.mode {
            FormatMode::ForceJson => {
                return match detected {
                    Some(DetectedFormat::Json) => Ok(DetectedFormat::Json),
                    _ => Err(DetectedFormat::Json), // Expected JSON, got something else -> DLQ
                };
            }
            FormatMode::ForceMessagePack => {
                return match detected {
                    Some(DetectedFormat::MessagePack) => Ok(DetectedFormat::MessagePack),
                    _ => Err(DetectedFormat::MessagePack), // Expected MsgPack, got something else -> DLQ
                };
            }
            FormatMode::Auto => {} // Continue with auto-detection logic
        }

        // Auto mode logic
        let current = self.format();

        match (current, detected) {
            // First message - set the format
            (DetectedFormat::Unknown, Some(fmt)) => {
                self.detected_format.store(fmt as u8, Ordering::Relaxed);
                self.mismatch_count.store(0, Ordering::Relaxed);
                Ok(fmt)
            }

            // Unknown format in payload - DLQ
            (_, None) => Err(DetectedFormat::Unknown),

            // Format matches - process
            (expected, Some(actual)) if expected == actual => {
                self.mismatch_count.store(0, Ordering::Relaxed);
                Ok(actual)
            }

            // Format mismatch - check if we should reset
            (expected, Some(actual)) => {
                let count = self.mismatch_count.fetch_add(1, Ordering::Relaxed);
                if count >= Self::MISMATCH_THRESHOLD {
                    // Too many mismatches - assume format changed, reset
                    self.detected_format.store(actual as u8, Ordering::Relaxed);
                    self.mismatch_count.store(0, Ordering::Relaxed);
                    #[cfg(feature = "logger")]
                    tracing::warn!(
                        old = ?expected,
                        new = ?actual,
                        "Format changed after {} mismatches, resetting",
                        count
                    );
                    Ok(actual)
                } else {
                    // Mismatch - send to DLQ
                    Err(expected)
                }
            }
        }
    }

    /// Force reset to unknown (for testing or manual override, Auto mode only).
    pub fn reset(&self) {
        if self.mode == FormatMode::Auto {
            self.detected_format
                .store(DetectedFormat::Unknown as u8, Ordering::Relaxed);
            self.mismatch_count.store(0, Ordering::Relaxed);
        }
    }
}

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

/// Detect payload format from raw bytes (internal).
///
/// Optimized for the common case where JSON starts with '{' at position 0.
#[inline]
fn detect_format_bytes(payload: &[u8]) -> Option<DetectedFormat> {
    // Fast path: check first byte directly (common case - no leading whitespace)
    let first_byte = *payload.first()?;

    // Most common case: JSON object starting with '{'
    if first_byte == b'{' || first_byte == b'[' {
        return Some(DetectedFormat::Json);
    }

    // Check for MessagePack before considering whitespace
    // (MessagePack never starts with whitespace-like bytes)
    // MessagePack: fixmap (0x80-0x8F), map16/32 (0xDE/0xDF), fixarray (0x90-0x9F), array16/32 (0xDC/0xDD)
    if matches!(first_byte, 0x80..=0x8F | 0xDE | 0xDF | 0x90..=0x9F | 0xDC | 0xDD) {
        return Some(DetectedFormat::MessagePack);
    }

    // Slow path: skip leading whitespace for JSON (rare case)
    if first_byte.is_ascii_whitespace() {
        for &b in payload.iter().skip(1) {
            if !b.is_ascii_whitespace() {
                return match b {
                    b'{' | b'[' => Some(DetectedFormat::Json),
                    _ => None,
                };
            }
        }
        return None; // All whitespace
    }

    None
}

/// Stateless format detection (convenience function).
///
/// For stateful detection with locking, use `FormatDetector`.
#[inline]
#[must_use]
pub fn detect_format(payload: &[u8]) -> Option<DetectedFormat> {
    detect_format_bytes(payload)
}

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

    #[test]
    fn test_detect_json_object() {
        assert_eq!(
            detect_format(b"{\"key\": \"value\"}"),
            Some(DetectedFormat::Json)
        );
    }

    #[test]
    fn test_detect_json_array() {
        assert_eq!(detect_format(b"[1, 2, 3]"), Some(DetectedFormat::Json));
    }

    #[test]
    fn test_detect_json_with_whitespace() {
        assert_eq!(
            detect_format(b"  \n\t{\"key\": 1}"),
            Some(DetectedFormat::Json)
        );
    }

    #[test]
    fn test_detect_msgpack_fixmap() {
        assert_eq!(
            detect_format(&[0x81, 0xA3, b'k', b'e', b'y']),
            Some(DetectedFormat::MessagePack)
        );
    }

    #[test]
    fn test_detect_msgpack_map16() {
        assert_eq!(
            detect_format(&[0xDE, 0x00, 0x01]),
            Some(DetectedFormat::MessagePack)
        );
    }

    #[test]
    fn test_detect_empty() {
        assert_eq!(detect_format(b""), None);
    }

    #[test]
    fn test_detect_whitespace_only() {
        assert_eq!(detect_format(b"   \n\t  "), None);
    }

    #[test]
    fn test_detect_unknown() {
        assert_eq!(detect_format(b"hello"), None);
    }

    #[test]
    fn test_format_detector_auto_detect() {
        let detector = FormatDetector::new();
        assert_eq!(detector.format(), DetectedFormat::Unknown);

        // First JSON message sets format
        let result = detector.check_and_detect(b"{\"key\": 1}");
        assert_eq!(result, Ok(DetectedFormat::Json));
        assert_eq!(detector.format(), DetectedFormat::Json);

        // Subsequent JSON messages pass
        assert_eq!(
            detector.check_and_detect(b"{\"key\": 2}"),
            Ok(DetectedFormat::Json)
        );

        // MessagePack mismatch goes to DLQ
        assert_eq!(
            detector.check_and_detect(&[0x81, 0xA1, b'k']),
            Err(DetectedFormat::Json)
        );
    }

    #[test]
    fn test_format_detector_mismatch_reset() {
        let detector = FormatDetector::new();

        // Set to JSON
        detector.check_and_detect(b"{\"key\": 1}").unwrap();

        // Send 11 MessagePack messages (> threshold of 10)
        for _ in 0..11 {
            let _ = detector.check_and_detect(&[0x81, 0xA1, b'k']);
        }

        // Format should have switched to MessagePack
        assert_eq!(detector.format(), DetectedFormat::MessagePack);
    }

    #[test]
    fn test_force_json_mode() {
        let detector = FormatDetector::with_mode(FormatMode::ForceJson);
        assert_eq!(detector.mode(), FormatMode::ForceJson);
        assert_eq!(detector.format(), DetectedFormat::Json);

        // JSON passes
        assert_eq!(
            detector.check_and_detect(b"{\"key\": 1}"),
            Ok(DetectedFormat::Json)
        );

        // MessagePack fails immediately (no mismatch counting)
        assert_eq!(
            detector.check_and_detect(&[0x81, 0xA1, b'k']),
            Err(DetectedFormat::Json)
        );

        // Unknown format also fails
        assert_eq!(
            detector.check_and_detect(b"hello"),
            Err(DetectedFormat::Json)
        );

        // Format stays locked
        assert_eq!(detector.format(), DetectedFormat::Json);
    }

    #[test]
    fn test_force_msgpack_mode() {
        let detector = FormatDetector::with_mode(FormatMode::ForceMessagePack);
        assert_eq!(detector.mode(), FormatMode::ForceMessagePack);
        assert_eq!(detector.format(), DetectedFormat::MessagePack);

        // MessagePack passes
        assert_eq!(
            detector.check_and_detect(&[0x81, 0xA1, b'k']),
            Ok(DetectedFormat::MessagePack)
        );

        // JSON fails immediately
        assert_eq!(
            detector.check_and_detect(b"{\"key\": 1}"),
            Err(DetectedFormat::MessagePack)
        );

        // Format stays locked
        assert_eq!(detector.format(), DetectedFormat::MessagePack);
    }

    #[test]
    fn test_force_mode_no_reset() {
        let detector = FormatDetector::with_mode(FormatMode::ForceJson);

        // Send many MessagePack messages - should NOT reset
        for _ in 0..20 {
            let _ = detector.check_and_detect(&[0x81, 0xA1, b'k']);
        }

        // Format should still be JSON (no auto-reset in force mode)
        assert_eq!(detector.format(), DetectedFormat::Json);
    }

    #[test]
    fn test_format_mode_from_str() {
        assert_eq!(FormatMode::parse("auto"), Some(FormatMode::Auto));
        assert_eq!(FormatMode::parse("AUTO"), Some(FormatMode::Auto));
        assert_eq!(FormatMode::parse("json"), Some(FormatMode::ForceJson));
        assert_eq!(FormatMode::parse("JSON"), Some(FormatMode::ForceJson));
        assert_eq!(
            FormatMode::parse("messagepack"),
            Some(FormatMode::ForceMessagePack)
        );
        assert_eq!(
            FormatMode::parse("msgpack"),
            Some(FormatMode::ForceMessagePack)
        );
        assert_eq!(FormatMode::parse("invalid"), None);
    }
}