mecha10-core 0.8.1

Mecha10 core runtime and foundational types
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
//! Bag File Recording and Replay (ROS bag-like)
//!
//! Records messages from arbitrary topics to bag files and replays them later.
//! Similar to ROS bags but designed for the Mecha10 framework.
//!
//! # Features
//!
//! - Record messages from any topic with timestamps
//! - Replay messages with original or custom timing
//! - Multiple recording formats (CBOR, MessagePack, JSON)
//! - Compression support (zstd, gzip)
//! - Topic filtering on record and replay
//! - Time manipulation (speed up, slow down, step through)
//! - Metadata tracking (topics, message counts, duration)
//!
//! # File Format
//!
//! Bag files use a simple chunked format:
//!
//! ```text
//! [Header]
//! - Magic bytes: "METABAG1"
//! - Version: u32
//! - Compression: u8 (0=none, 1=zstd, 2=gzip)
//! - Metadata length: u64
//! - Metadata: CBOR-encoded BagMetadata
//!
//! [Chunk 0]
//! - Timestamp: u64 (microseconds since epoch)
//! - Topic length: u32
//! - Topic: String
//! - Message length: u32
//! - Message data: Vec<u8> (serialized message)
//!
//! [Chunk 1]
//! ...
//! ```
//!
//! # Example: Recording
//!
//! ```rust,no_run
//! use mecha10_core::prelude::*;
//! use mecha10_core::recorder::{BagRecorder, Compression, RecorderConfig};
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//!     let ctx = Context::new("recorder").await?;
//!
//!     let config = RecorderConfig {
//!         output_path: "/tmp/recording.bag".into(),
//!         topics: vec![
//!             "/sensor/camera/rgb".to_string(),
//!             "/sensor/lidar/scan".to_string(),
//!         ],
//!         compression: Compression::Zstd,
//!         buffer_size: 1000,
//!         ..Default::default()
//!     };
//!
//!     let mut recorder = BagRecorder::new(ctx, config).await?;
//!     recorder.start().await?;
//!
//!     // Record for 60 seconds
//!     tokio::time::sleep(Duration::from_secs(60)).await;
//!
//!     recorder.stop().await?;
//!     println!("Recording saved: {:?}", recorder.metadata().await);
//!
//!     Ok(())
//! }
//! ```
//!
//! # Example: Replay
//!
//! ```rust,no_run
//! use mecha10_core::prelude::*;
//! use mecha10_core::recorder::{BagPlayer, PlayerConfig};
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//!     let ctx = Context::new("player").await?;
//!
//!     let config = PlayerConfig {
//!         bag_path: "/tmp/recording.bag".into(),
//!         topics: None, // Replay all topics
//!         rate: 1.0, // Real-time speed
//!         loop_playback: false,
//!         start_paused: false,
//!         ..Default::default()
//!     };
//!
//!     let mut player = BagPlayer::new(ctx, config).await?;
//!     player.play().await?;
//!
//!     Ok(())
//! }
//! ```

use crate::{Context, Mecha10Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Read, Write};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;
use tracing::{debug, info, warn};

const MAGIC_BYTES: &[u8; 8] = b"METABAG1";
const VERSION: u32 = 1;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum Compression {
    #[default]
    None = 0,
    Zstd = 1,
    Gzip = 2,
}

impl From<u8> for Compression {
    fn from(v: u8) -> Self {
        match v {
            1 => Compression::Zstd,
            2 => Compression::Gzip,
            _ => Compression::None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BagMetadata {
    pub topics: Vec<String>,

    pub message_counts: HashMap<String, u64>,

    pub start_time_us: u64,

    pub end_time_us: u64,

    pub duration_sec: f64,

    pub total_messages: u64,

    pub compression: Compression,

    #[serde(default)]
    pub custom: HashMap<String, String>,
}

#[derive(Debug, Clone)]
struct MessageChunk {
    timestamp_us: u64,

    topic: String,

    data: Vec<u8>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecorderConfig {
    pub output_path: PathBuf,

    #[serde(default)]
    pub topics: Vec<String>,

    #[serde(default)]
    pub compression: Compression,

    #[serde(default = "default_buffer_size")]
    pub buffer_size: usize,

    #[serde(default)]
    pub max_file_size: u64,

    #[serde(default)]
    pub split_on_max_size: bool,
}

fn default_buffer_size() -> usize {
    1000
}

impl Default for RecorderConfig {
    fn default() -> Self {
        Self {
            output_path: PathBuf::from("recording.bag"),
            topics: Vec::new(),
            compression: Compression::None,
            buffer_size: default_buffer_size(),
            max_file_size: 0,
            split_on_max_size: false,
        }
    }
}

pub struct BagRecorder {
    config: RecorderConfig,
    ctx: Arc<Context>,
    buffer: Arc<RwLock<Vec<MessageChunk>>>,
    metadata: Arc<RwLock<BagMetadata>>,
    running: Arc<RwLock<bool>>,
    write_task: Option<tokio::task::JoinHandle<()>>,
}

impl BagRecorder {
    /// Create a new bag recorder
    pub async fn new(ctx: Context, config: RecorderConfig) -> Result<Self> {
        let metadata = BagMetadata {
            topics: config.topics.clone(),
            message_counts: HashMap::new(),
            start_time_us: crate::prelude::now_micros(),
            end_time_us: 0,
            duration_sec: 0.0,
            total_messages: 0,
            compression: config.compression,
            custom: HashMap::new(),
        };

        Ok(Self {
            config,
            ctx: Arc::new(ctx),
            buffer: Arc::new(RwLock::new(Vec::new())),
            metadata: Arc::new(RwLock::new(metadata)),
            running: Arc::new(RwLock::new(false)),
            write_task: None,
        })
    }

    /// Start recording
    pub async fn start(&mut self) -> Result<()> {
        *self.running.write().await = true;

        info!("Starting bag recorder: {:?}", self.config.output_path);

        self.write_header().await?;

        let buffer = Arc::clone(&self.buffer);
        let _metadata = Arc::clone(&self.metadata);
        let running = Arc::clone(&self.running);
        let output_path = self.config.output_path.clone();
        let compression = self.config.compression;
        let buffer_size = self.config.buffer_size;

        let write_task = tokio::spawn(async move {
            while *running.read().await {
                tokio::time::sleep(Duration::from_millis(100)).await;

                let mut buf = buffer.write().await;
                if buf.len() >= buffer_size {
                    if let Err(e) = Self::write_chunks(&output_path, &buf, compression).await {
                        warn!("Failed to write chunks: {}", e);
                    }
                    buf.clear();
                }
            }

            let buf = buffer.read().await;
            if !buf.is_empty() {
                if let Err(e) = Self::write_chunks(&output_path, &buf, compression).await {
                    warn!("Failed to write final chunks: {}", e);
                }
            }
        });

        self.write_task = Some(write_task);

        for topic in &self.config.topics {
            let topic_clone = topic.clone();
            let buffer = Arc::clone(&self.buffer);
            let metadata = Arc::clone(&self.metadata);
            let running = Arc::clone(&self.running);
            let ctx = Arc::clone(&self.ctx);

            tokio::spawn(async move {
                match ctx.subscribe_raw::<serde_json::Value>(&topic_clone).await {
                    Ok(mut rx) => {
                        while *running.read().await {
                            if let Some(msg) = rx.recv().await {
                                let mut data = Vec::new();
                                if ciborium::ser::into_writer(&msg, &mut data).is_ok() {
                                    let chunk = MessageChunk {
                                        timestamp_us: crate::prelude::now_micros(),
                                        topic: topic_clone.clone(),
                                        data,
                                    };

                                    buffer.write().await.push(chunk);

                                    let mut meta = metadata.write().await;
                                    *meta.message_counts.entry(topic_clone.clone()).or_insert(0) += 1;
                                    meta.total_messages += 1;
                                }
                            }
                        }
                    }
                    Err(e) => {
                        warn!("Failed to subscribe to {}: {}", topic_clone, e);
                    }
                }
            });
        }

        Ok(())
    }

    /// Stop recording
    pub async fn stop(&mut self) -> Result<()> {
        *self.running.write().await = false;

        info!("Stopping bag recorder");

        if let Some(task) = self.write_task.take() {
            task.await
                .map_err(|e| Mecha10Error::Other(format!("Write task error: {}", e)))?;
        }

        let mut meta = self.metadata.write().await;
        meta.end_time_us = crate::prelude::now_micros();
        meta.duration_sec = (meta.end_time_us - meta.start_time_us) as f64 / 1_000_000.0;

        self.write_header().await?;

        info!(
            "Recording complete: {} messages, {:.1}s",
            meta.total_messages, meta.duration_sec
        );

        Ok(())
    }

    /// Get current metadata
    pub async fn metadata(&self) -> BagMetadata {
        self.metadata.read().await.clone()
    }

    /// Write bag file header with metadata
    async fn write_header(&self) -> Result<()> {
        let meta = self.metadata.read().await;

        let mut file = std::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&self.config.output_path)
            .map_err(Mecha10Error::Io)?;

        file.write_all(MAGIC_BYTES).map_err(Mecha10Error::Io)?;

        file.write_all(&VERSION.to_le_bytes()).map_err(Mecha10Error::Io)?;

        file.write_all(&[self.config.compression as u8])
            .map_err(Mecha10Error::Io)?;

        let mut meta_bytes = Vec::new();
        ciborium::ser::into_writer(&*meta, &mut meta_bytes)
            .map_err(|e| Mecha10Error::Other(format!("Serialization error: {}", e)))?;

        file.write_all(&(meta_bytes.len() as u64).to_le_bytes())
            .map_err(Mecha10Error::Io)?;

        file.write_all(&meta_bytes).map_err(Mecha10Error::Io)?;

        Ok(())
    }

    /// Write message chunks to file
    async fn write_chunks(path: &PathBuf, chunks: &[MessageChunk], _compression: Compression) -> Result<()> {
        let mut file = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(path)
            .map_err(Mecha10Error::Io)?;

        for chunk in chunks {
            file.write_all(&chunk.timestamp_us.to_le_bytes())
                .map_err(Mecha10Error::Io)?;

            let topic_bytes = chunk.topic.as_bytes();
            file.write_all(&(topic_bytes.len() as u32).to_le_bytes())
                .map_err(Mecha10Error::Io)?;
            file.write_all(topic_bytes).map_err(Mecha10Error::Io)?;

            file.write_all(&(chunk.data.len() as u32).to_le_bytes())
                .map_err(Mecha10Error::Io)?;
            file.write_all(&chunk.data).map_err(Mecha10Error::Io)?;
        }

        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlayerConfig {
    pub bag_path: PathBuf,

    #[serde(default)]
    pub topics: Option<Vec<String>>,

    #[serde(default = "default_rate")]
    pub rate: f64,

    #[serde(default)]
    pub loop_playback: bool,

    #[serde(default)]
    pub start_paused: bool,

    #[serde(default)]
    pub skip_to_us: u64,
}

fn default_rate() -> f64 {
    1.0
}

impl Default for PlayerConfig {
    fn default() -> Self {
        Self {
            bag_path: PathBuf::from("recording.bag"),
            topics: None,
            rate: 1.0,
            loop_playback: false,
            start_paused: false,
            skip_to_us: 0,
        }
    }
}

pub struct BagPlayer {
    config: PlayerConfig,
    ctx: Arc<Context>,
    metadata: BagMetadata,
    chunks: Vec<MessageChunk>,
    paused: Arc<RwLock<bool>>,
    playing: Arc<RwLock<bool>>,
}

impl BagPlayer {
    /// Create a new bag player
    pub async fn new(ctx: Context, config: PlayerConfig) -> Result<Self> {
        info!("Loading bag file: {:?}", config.bag_path);

        let (metadata, chunks) = Self::read_bag_file(&config.bag_path).await?;

        info!(
            "Loaded bag: {} messages, {:.1}s duration, {} topics",
            metadata.total_messages,
            metadata.duration_sec,
            metadata.topics.len()
        );

        Ok(Self {
            config,
            ctx: Arc::new(ctx),
            metadata,
            chunks,
            paused: Arc::new(RwLock::new(false)),
            playing: Arc::new(RwLock::new(false)),
        })
    }

    /// Start playback
    pub async fn play(&mut self) -> Result<()> {
        if self.config.start_paused {
            *self.paused.write().await = true;
        }

        *self.playing.write().await = true;

        info!("Starting playback at {}x speed", self.config.rate);

        loop {
            let start_time = self.chunks.first().map(|c| c.timestamp_us).unwrap_or(0);
            let playback_start = std::time::Instant::now();

            for chunk in &self.chunks {
                while *self.paused.read().await {
                    tokio::time::sleep(Duration::from_millis(100)).await;
                }

                if !*self.playing.read().await {
                    break;
                }

                if let Some(topics) = &self.config.topics {
                    if !topics.contains(&chunk.topic) {
                        continue;
                    }
                }

                let msg_time_offset = chunk.timestamp_us - start_time;
                let real_time_offset = (msg_time_offset as f64 / self.config.rate) as u64;
                let target_time = playback_start + Duration::from_micros(real_time_offset);

                if let Some(sleep_duration) = target_time.checked_duration_since(std::time::Instant::now()) {
                    tokio::time::sleep(sleep_duration).await;
                }

                match ciborium::de::from_reader::<serde_json::Value, _>(chunk.data.as_slice()) {
                    Ok(msg) => {
                        if let Err(e) = self.ctx.publish_raw(&chunk.topic, &msg).await {
                            warn!("Failed to publish to {}: {}", chunk.topic, e);
                        } else {
                            debug!("Replayed message on {}", chunk.topic);
                        }
                    }
                    Err(e) => {
                        warn!("Failed to deserialize message: {}", e);
                    }
                }
            }

            if !self.config.loop_playback {
                break;
            }

            info!("Looping playback");
        }

        *self.playing.write().await = false;
        info!("Playback complete");

        Ok(())
    }

    /// Shared body behind `pause`/`resume`/`stop`: flip a `RwLock<bool>` flag and log the
    /// resulting transition.
    async fn set_flag(flag: &RwLock<bool>, value: bool, message: &str) {
        *flag.write().await = value;
        info!("{}", message);
    }

    /// Pause playback
    pub async fn pause(&self) {
        Self::set_flag(&self.paused, true, "Playback paused").await;
    }

    /// Resume playback
    pub async fn resume(&self) {
        Self::set_flag(&self.paused, false, "Playback resumed").await;
    }

    /// Stop playback
    pub async fn stop(&self) {
        Self::set_flag(&self.playing, false, "Playback stopped").await;
    }

    /// Get bag metadata
    pub fn metadata(&self) -> &BagMetadata {
        &self.metadata
    }

    /// Read and parse bag file
    async fn read_bag_file(path: &PathBuf) -> Result<(BagMetadata, Vec<MessageChunk>)> {
        let mut file = std::fs::File::open(path).map_err(Mecha10Error::Io)?;

        let mut magic = [0u8; 8];
        file.read_exact(&mut magic).map_err(Mecha10Error::Io)?;

        if &magic != MAGIC_BYTES {
            return Err(Mecha10Error::Other("Invalid bag file format".to_string()));
        }

        let mut version_bytes = [0u8; 4];
        file.read_exact(&mut version_bytes).map_err(Mecha10Error::Io)?;
        let version = u32::from_le_bytes(version_bytes);

        if version != VERSION {
            return Err(Mecha10Error::Other(format!("Unsupported bag version: {}", version)));
        }

        let mut compression_byte = [0u8; 1];
        file.read_exact(&mut compression_byte).map_err(Mecha10Error::Io)?;
        let _compression = Compression::from(compression_byte[0]);

        let mut meta_len_bytes = [0u8; 8];
        file.read_exact(&mut meta_len_bytes).map_err(Mecha10Error::Io)?;
        let meta_len = u64::from_le_bytes(meta_len_bytes) as usize;

        let mut meta_bytes = vec![0u8; meta_len];
        file.read_exact(&mut meta_bytes).map_err(Mecha10Error::Io)?;

        let metadata: BagMetadata = ciborium::de::from_reader(meta_bytes.as_slice())
            .map_err(|e| Mecha10Error::Other(format!("Failed to parse metadata: {}", e)))?;

        let mut chunks = Vec::new();

        loop {
            let mut timestamp_bytes = [0u8; 8];
            if file.read_exact(&mut timestamp_bytes).is_err() {
                break;
            }
            let timestamp_us = u64::from_le_bytes(timestamp_bytes);

            let mut topic_len_bytes = [0u8; 4];
            file.read_exact(&mut topic_len_bytes).map_err(Mecha10Error::Io)?;
            let topic_len = u32::from_le_bytes(topic_len_bytes) as usize;

            let mut topic_bytes = vec![0u8; topic_len];
            file.read_exact(&mut topic_bytes).map_err(Mecha10Error::Io)?;
            let topic = String::from_utf8(topic_bytes)
                .map_err(|e| Mecha10Error::Other(format!("Invalid topic string: {}", e)))?;

            let mut data_len_bytes = [0u8; 4];
            file.read_exact(&mut data_len_bytes).map_err(Mecha10Error::Io)?;
            let data_len = u32::from_le_bytes(data_len_bytes) as usize;

            let mut data = vec![0u8; data_len];
            file.read_exact(&mut data).map_err(Mecha10Error::Io)?;

            chunks.push(MessageChunk {
                timestamp_us,
                topic,
                data,
            });
        }

        Ok((metadata, chunks))
    }
}