fly_ruler_proto_core 0.2.2

Protobuf UDP runtime and time-series state kernel for aerospace simulation
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
//! Shared live/replay timeline state.

use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Instant;

use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::config::ReplayConfig;
use crate::store::{active_time_bounds, AircraftId, TimeSeriesStore, TimestampedState};

/// Current global timeline mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlaybackMode {
    /// Resolve every aircraft at its latest received state.
    Live,
    /// Resolve every aircraft at a fixed historical cursor.
    ReplayPaused,
    /// Advance the historical cursor using wall-clock time.
    ReplayPlaying,
}

/// Timeline entry type used by frame stepping.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlaybackStepUnit {
    /// Globally unique aircraft state timestamps.
    Sample,
    /// Globally unique lifecycle and custom-event timestamps.
    Event,
}

/// Direction used by frame stepping.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlaybackStepDirection {
    /// Move to an earlier timeline entry.
    Previous,
    /// Move to a later timeline entry.
    Next,
}

/// Serializable playback state exposed to bindings and management clients.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PlaybackSnapshot {
    /// Current playback mode.
    pub mode: PlaybackMode,
    /// Effective global cursor, or `None` for an empty store.
    pub cursor_secs: Option<f64>,
    /// Positive playback speed multiplier.
    pub speed: f64,
    /// Current global store time bounds.
    pub bounds: Option<(f64, f64)>,
    /// Monotonic revision incremented by explicit timeline mutations.
    pub revision: u64,
}

/// A state resolved against a playback cursor.
#[derive(Debug, Clone)]
pub struct ResolvedState {
    /// State sample selected using previous-value hold.
    pub sample: TimestampedState,
    /// Whether the aircraft lifecycle is spawned at this cursor.
    pub spawned: bool,
}

/// Playback control errors.
#[derive(Debug, Error, PartialEq)]
pub enum PlaybackError {
    /// A timeline operation requires at least one state or lifecycle event.
    #[error("the store contains no timeline data")]
    EmptyStore,
    /// A timestamp must be finite.
    #[error("timestamp must be finite")]
    InvalidTimestamp,
    /// A playback speed is outside the configured positive range.
    #[error("speed must be finite and within {min}..={max}")]
    InvalidSpeed {
        /// Minimum accepted speed.
        min: f64,
        /// Maximum accepted speed.
        max: f64,
    },
    /// A frame step count must be bounded to prevent expensive requests.
    #[error("step count must be within 1..=100")]
    InvalidStepCount,
}

#[derive(Debug)]
struct PlaybackInner {
    mode: PlaybackMode,
    cursor_secs: Option<f64>,
    speed: f64,
    anchor: Option<Instant>,
    revision: u64,
}

/// Thread-safe global playback state shared by HTTP, WebSocket, and renderers.
pub struct PlaybackController {
    store: Arc<TimeSeriesStore>,
    config: ReplayConfig,
    inner: Mutex<PlaybackInner>,
}

impl PlaybackController {
    /// Create a live playback controller over the given store.
    pub fn new(store: Arc<TimeSeriesStore>, config: ReplayConfig) -> Self {
        Self {
            store,
            inner: Mutex::new(PlaybackInner {
                mode: PlaybackMode::Live,
                cursor_secs: None,
                speed: config.default_speed,
                anchor: None,
                revision: 0,
            }),
            config,
        }
    }

    /// Return the effective current playback state.
    pub fn snapshot(&self) -> PlaybackSnapshot {
        let bounds = active_time_bounds(&self.store);
        let mut inner = lock_unpoisoned(&self.inner);
        update_effective_cursor(&mut inner, bounds);
        snapshot_from_inner(&inner, bounds)
    }

    /// Switch to live mode.
    pub fn live(&self) -> PlaybackSnapshot {
        let bounds = active_time_bounds(&self.store);
        let mut inner = lock_unpoisoned(&self.inner);
        inner.mode = PlaybackMode::Live;
        inner.cursor_secs = bounds.map(|bounds| bounds.1);
        inner.anchor = None;
        inner.revision = inner.revision.wrapping_add(1);
        snapshot_from_inner(&inner, bounds)
    }

    /// Pause at the effective current cursor.
    pub fn pause(&self) -> Result<PlaybackSnapshot, PlaybackError> {
        let bounds = active_time_bounds(&self.store).ok_or(PlaybackError::EmptyStore)?;
        let mut inner = lock_unpoisoned(&self.inner);
        update_effective_cursor(&mut inner, Some(bounds));
        inner.mode = PlaybackMode::ReplayPaused;
        inner.cursor_secs = Some(inner.cursor_secs.unwrap_or(bounds.1));
        inner.anchor = None;
        inner.revision = inner.revision.wrapping_add(1);
        Ok(snapshot_from_inner(&inner, Some(bounds)))
    }

    /// Seek to a clamped historical timestamp and pause.
    pub fn seek(&self, timestamp_secs: f64) -> Result<PlaybackSnapshot, PlaybackError> {
        if !timestamp_secs.is_finite() {
            return Err(PlaybackError::InvalidTimestamp);
        }
        let bounds = active_time_bounds(&self.store).ok_or(PlaybackError::EmptyStore)?;
        let mut inner = lock_unpoisoned(&self.inner);
        inner.mode = PlaybackMode::ReplayPaused;
        inner.cursor_secs = Some(timestamp_secs.clamp(bounds.0, bounds.1));
        inner.anchor = None;
        inner.revision = inner.revision.wrapping_add(1);
        Ok(snapshot_from_inner(&inner, Some(bounds)))
    }

    /// Start forward playback at the current cursor.
    pub fn play(&self, speed: Option<f64>) -> Result<PlaybackSnapshot, PlaybackError> {
        if let Some(speed) = speed {
            validate_speed(&self.config, speed)?;
        }
        let bounds = active_time_bounds(&self.store).ok_or(PlaybackError::EmptyStore)?;
        let mut inner = lock_unpoisoned(&self.inner);
        update_effective_cursor(&mut inner, Some(bounds));
        if let Some(speed) = speed {
            inner.speed = speed;
        }
        inner.cursor_secs = Some(
            inner
                .cursor_secs
                .unwrap_or(bounds.0)
                .clamp(bounds.0, bounds.1),
        );
        inner.mode = PlaybackMode::ReplayPlaying;
        inner.anchor = Some(Instant::now());
        inner.revision = inner.revision.wrapping_add(1);
        update_effective_cursor(&mut inner, Some(bounds));
        Ok(snapshot_from_inner(&inner, Some(bounds)))
    }

    /// Set the speed while preserving the effective cursor.
    pub fn set_speed(&self, speed: f64) -> Result<PlaybackSnapshot, PlaybackError> {
        validate_speed(&self.config, speed)?;
        let bounds = active_time_bounds(&self.store);
        let mut inner = lock_unpoisoned(&self.inner);
        update_effective_cursor(&mut inner, bounds);
        inner.speed = speed;
        if inner.mode == PlaybackMode::ReplayPlaying {
            inner.anchor = Some(Instant::now());
        }
        inner.revision = inner.revision.wrapping_add(1);
        Ok(snapshot_from_inner(&inner, bounds))
    }

    /// Pause and move to an adjacent globally unique sample or event timestamp.
    pub fn step(
        &self,
        unit: PlaybackStepUnit,
        direction: PlaybackStepDirection,
        count: usize,
    ) -> Result<PlaybackSnapshot, PlaybackError> {
        if !(1..=100).contains(&count) {
            return Err(PlaybackError::InvalidStepCount);
        }
        let bounds = active_time_bounds(&self.store).ok_or(PlaybackError::EmptyStore)?;
        let mut inner = lock_unpoisoned(&self.inner);
        update_effective_cursor(&mut inner, Some(bounds));
        let cursor = inner.cursor_secs.unwrap_or(bounds.1);
        let target = match (unit, direction) {
            (PlaybackStepUnit::Sample, PlaybackStepDirection::Previous) => {
                self.store.previous_global_state_timestamp(cursor, count)
            }
            (PlaybackStepUnit::Sample, PlaybackStepDirection::Next) => {
                self.store.next_global_state_timestamp(cursor, count)
            }
            (PlaybackStepUnit::Event, PlaybackStepDirection::Previous) => {
                self.store.previous_global_event_timestamp(cursor, count)
            }
            (PlaybackStepUnit::Event, PlaybackStepDirection::Next) => {
                self.store.next_global_event_timestamp(cursor, count)
            }
        };
        inner.mode = PlaybackMode::ReplayPaused;
        inner.cursor_secs = Some(target.unwrap_or(cursor).clamp(bounds.0, bounds.1));
        inner.anchor = None;
        inner.revision = inner.revision.wrapping_add(1);
        Ok(snapshot_from_inner(&inner, Some(bounds)))
    }

    /// Reset after clearing all data.
    pub fn reset_empty(&self) -> PlaybackSnapshot {
        let mut inner = lock_unpoisoned(&self.inner);
        inner.mode = PlaybackMode::ReplayPaused;
        inner.cursor_secs = None;
        inner.anchor = None;
        inner.revision = inner.revision.wrapping_add(1);
        snapshot_from_inner(&inner, None)
    }

    /// Reset after loading data, paused at the first global sample.
    pub fn reset_after_load(&self) -> PlaybackSnapshot {
        let bounds = active_time_bounds(&self.store);
        let mut inner = lock_unpoisoned(&self.inner);
        inner.mode = PlaybackMode::ReplayPaused;
        inner.cursor_secs = bounds.map(|bounds| bounds.0);
        inner.anchor = None;
        inner.revision = inner.revision.wrapping_add(1);
        snapshot_from_inner(&inner, bounds)
    }

    /// Resolve one aircraft according to the effective global mode.
    pub fn resolve_aircraft(&self, id: &AircraftId) -> Option<ResolvedState> {
        let playback = self.snapshot();
        self.resolve_aircraft_with(&playback, id)
    }

    /// Resolve one aircraft against an already captured playback snapshot.
    ///
    /// This keeps multi-aircraft WebSocket frames and renderer updates on one
    /// exact global cursor.
    pub fn resolve_aircraft_with(
        &self,
        playback: &PlaybackSnapshot,
        id: &AircraftId,
    ) -> Option<ResolvedState> {
        let sample = match playback.mode {
            PlaybackMode::Live => self.store.get_latest(id),
            PlaybackMode::ReplayPaused | PlaybackMode::ReplayPlaying => playback
                .cursor_secs
                .and_then(|cursor| self.store.get_state_at_or_before(id, cursor)),
        }?;
        let spawned = match playback.mode {
            PlaybackMode::Live => self.store.is_spawned_at(id, f64::INFINITY),
            PlaybackMode::ReplayPaused | PlaybackMode::ReplayPlaying => playback
                .cursor_secs
                .is_some_and(|cursor| self.store.is_spawned_at(id, cursor)),
        };
        Some(ResolvedState { sample, spawned })
    }

    /// Return the underlying store.
    pub fn store(&self) -> Arc<TimeSeriesStore> {
        Arc::clone(&self.store)
    }
}

fn validate_speed(config: &ReplayConfig, speed: f64) -> Result<(), PlaybackError> {
    if speed.is_finite() && (config.min_speed..=config.max_speed).contains(&speed) {
        Ok(())
    } else {
        Err(PlaybackError::InvalidSpeed {
            min: config.min_speed,
            max: config.max_speed,
        })
    }
}

fn update_effective_cursor(inner: &mut PlaybackInner, bounds: Option<(f64, f64)>) {
    let Some((start, end)) = bounds else {
        inner.cursor_secs = None;
        inner.anchor = None;
        if inner.mode == PlaybackMode::Live {
            return;
        }
        inner.mode = PlaybackMode::ReplayPaused;
        return;
    };

    match inner.mode {
        PlaybackMode::Live => {
            inner.cursor_secs = Some(end);
            inner.anchor = None;
        }
        PlaybackMode::ReplayPaused => {
            inner.cursor_secs = Some(inner.cursor_secs.unwrap_or(start).clamp(start, end));
            inner.anchor = None;
        }
        PlaybackMode::ReplayPlaying => {
            let base = inner.cursor_secs.unwrap_or(start);
            let elapsed = inner
                .anchor
                .map_or(0.0, |anchor| anchor.elapsed().as_secs_f64());
            let next = base + elapsed * inner.speed;
            if next >= end {
                inner.cursor_secs = Some(end);
                inner.mode = PlaybackMode::ReplayPaused;
                inner.anchor = None;
                inner.revision = inner.revision.wrapping_add(1);
            } else {
                inner.cursor_secs = Some(next.max(start));
                inner.anchor = Some(Instant::now());
            }
        }
    }
}

fn snapshot_from_inner(inner: &PlaybackInner, bounds: Option<(f64, f64)>) -> PlaybackSnapshot {
    PlaybackSnapshot {
        mode: inner.mode,
        cursor_secs: inner.cursor_secs,
        speed: inner.speed,
        bounds,
        revision: inner.revision,
    }
}

fn lock_unpoisoned<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pb;
    use std::time::Duration;

    fn state(x: f64) -> pb::AircraftState {
        pb::AircraftState {
            position: Some(pb::Vector3 { x, y: 0.0, z: 0.0 }),
            ..Default::default()
        }
    }

    fn controller() -> PlaybackController {
        let store = Arc::new(TimeSeriesStore::new());
        store.append_state("a".to_string(), 10.0, state(1.0));
        store.append_state("a".to_string(), 20.0, state(2.0));
        PlaybackController::new(store, ReplayConfig::default())
    }

    #[test]
    fn live_pause_seek_and_live_transitions() {
        let playback = controller();
        assert_eq!(playback.snapshot().cursor_secs, Some(20.0));
        assert_eq!(playback.pause().unwrap().mode, PlaybackMode::ReplayPaused);
        assert_eq!(playback.seek(15.0).unwrap().cursor_secs, Some(15.0));
        assert_eq!(
            playback
                .resolve_aircraft(&"a".to_string())
                .unwrap()
                .sample
                .timestamp_secs,
            10.0
        );
        assert_eq!(playback.live().mode, PlaybackMode::Live);
    }

    #[test]
    fn invalid_speed_and_empty_store_are_rejected() {
        let empty =
            PlaybackController::new(Arc::new(TimeSeriesStore::new()), ReplayConfig::default());
        assert_eq!(empty.pause().unwrap_err(), PlaybackError::EmptyStore);
        assert!(matches!(
            controller().set_speed(0.0),
            Err(PlaybackError::InvalidSpeed { .. })
        ));
    }

    #[test]
    fn resets_increment_revision() {
        let playback = controller();
        let initial = playback.snapshot().revision;
        assert!(playback.reset_empty().revision > initial);
        assert!(playback.reset_after_load().revision > initial);
    }

    #[test]
    fn playing_advances_and_pauses_at_the_end() {
        let playback = controller();
        playback.seek(19.99).unwrap();
        let started = playback.play(Some(16.0)).unwrap();
        assert_eq!(started.mode, PlaybackMode::ReplayPlaying);
        std::thread::sleep(Duration::from_millis(2));
        let ended = playback.snapshot();
        assert_eq!(ended.mode, PlaybackMode::ReplayPaused);
        assert_eq!(ended.cursor_secs, Some(20.0));
        assert!(ended.revision > started.revision);
    }

    #[test]
    fn replay_does_not_block_live_ingestion_and_live_jumps_to_latest() {
        let playback = controller();
        playback.seek(10.0).unwrap();
        let store = playback.store();
        store.append_state("a".to_string(), 30.0, state(3.0));
        assert_eq!(playback.snapshot().cursor_secs, Some(10.0));
        assert_eq!(
            playback
                .resolve_aircraft(&"a".to_string())
                .unwrap()
                .sample
                .timestamp_secs,
            10.0
        );
        assert_eq!(playback.live().cursor_secs, Some(30.0));
        assert_eq!(
            playback
                .resolve_aircraft(&"a".to_string())
                .unwrap()
                .sample
                .timestamp_secs,
            30.0
        );
    }

    #[test]
    fn stepping_uses_global_unique_samples_and_events() {
        let store = Arc::new(TimeSeriesStore::new());
        store.append_state("a".to_string(), 10.0, state(1.0));
        store.append_state("a".to_string(), 20.0, state(2.0));
        store.append_state("b".to_string(), 20.0, state(3.0));
        store.append_state("b".to_string(), 30.0, state(4.0));
        store.append_event(
            "a".to_string(),
            12.0,
            crate::store::Event::Custom("one".to_string()),
        );
        store.append_event(
            "b".to_string(),
            24.0,
            crate::store::Event::Custom("two".to_string()),
        );
        let playback = PlaybackController::new(store, ReplayConfig::default());

        let previous = playback
            .step(PlaybackStepUnit::Sample, PlaybackStepDirection::Previous, 1)
            .unwrap();
        assert_eq!(previous.cursor_secs, Some(20.0));
        let earliest = playback
            .step(
                PlaybackStepUnit::Sample,
                PlaybackStepDirection::Previous,
                10,
            )
            .unwrap();
        assert_eq!(earliest.cursor_secs, Some(10.0));
        let event = playback
            .step(PlaybackStepUnit::Event, PlaybackStepDirection::Next, 1)
            .unwrap();
        assert_eq!(event.cursor_secs, Some(12.0));
    }

    #[test]
    fn step_validates_count_and_increments_revision_at_boundaries() {
        let playback = controller();
        assert_eq!(
            playback
                .step(PlaybackStepUnit::Sample, PlaybackStepDirection::Next, 0,)
                .unwrap_err(),
            PlaybackError::InvalidStepCount
        );
        let initial = playback.snapshot();
        let boundary = playback
            .step(PlaybackStepUnit::Sample, PlaybackStepDirection::Next, 1)
            .unwrap();
        assert_eq!(boundary.cursor_secs, initial.cursor_secs);
        assert_eq!(boundary.mode, PlaybackMode::ReplayPaused);
        assert!(boundary.revision > initial.revision);
    }
}