use std::fs;
use std::fs::File;
use std::path::Path;
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
use arrow::array::{Array, BinaryArray, Float64Array, StringArray};
use arrow::datatypes::{DataType, Field, Schema};
use arrow::record_batch::RecordBatch;
use dashmap::DashMap;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::arrow::ArrowWriter;
use prost::Message as ProstMessage;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::{debug, info, warn};
use crate::config::StoreConfig;
use crate::pb;
use crate::utils::uuid_to_hex;
use crate::PROTOCOL_VERSION;
pub type AircraftId = String;
#[derive(Debug, Clone)]
pub struct AircraftConfig {
pub name: String,
pub toml_config: String,
}
#[derive(Debug, Clone)]
pub enum Event {
Spawn(Box<pb::AircraftSpawnInfo>),
Despawn(pb::DespawnInfo),
Custom(String),
}
#[derive(Debug, Clone)]
pub struct TimestampedState {
pub timestamp_secs: f64,
pub state: pb::AircraftState,
}
#[derive(Debug, Clone)]
pub struct TimestampedEvent {
pub timestamp_secs: f64,
pub event: Event,
}
#[derive(Debug, Clone)]
pub struct GlobalTimestampedEvent {
pub aircraft_id: AircraftId,
pub timestamp_secs: f64,
pub event: Event,
}
#[derive(Debug, Clone, Default)]
pub struct AircraftTimeSeries {
pub states: Vec<TimestampedState>,
pub events: Vec<TimestampedEvent>,
pub config: Option<AircraftConfig>,
}
#[derive(Debug, Clone)]
pub struct AircraftSummary {
pub id: AircraftId,
pub config: Option<AircraftConfig>,
pub time_range: Option<(f64, f64)>,
pub state_count: usize,
pub event_count: usize,
}
#[derive(Debug, Clone)]
pub struct StorePage<T> {
pub items: Vec<T>,
pub total: usize,
pub offset: usize,
pub limit: usize,
}
#[derive(Debug, Default)]
pub struct TimeSeriesStore {
data: RwLock<DashMap<AircraftId, AircraftTimeSeries>>,
}
#[derive(Debug, Error)]
pub enum StoreError {
#[error("io error: {0}")]
Io(#[from] std::io::Error),
#[error("json error: {0}")]
Json(#[from] serde_json::Error),
#[error("parquet error: {0}")]
Parquet(#[from] parquet::errors::ParquetError),
#[error("arrow error: {0}")]
Arrow(#[from] arrow::error::ArrowError),
#[error("decode error: {0}")]
Decode(#[from] prost::DecodeError),
#[error("invalid data: {0}")]
InvalidData(String),
}
#[derive(Debug, Serialize, Deserialize)]
struct MetaFile {
version: String,
aircrafts: Vec<MetaAircraft>,
}
#[derive(Debug, Serialize, Deserialize)]
struct MetaAircraft {
id: String,
name: Option<String>,
toml_config: Option<String>,
time_range: Option<(f64, f64)>,
state_count: usize,
event_count: usize,
}
impl TimeSeriesStore {
pub fn new() -> Self {
Self {
data: RwLock::new(DashMap::new()),
}
}
pub fn append_state(&self, id: AircraftId, timestamp: f64, state: pb::AircraftState) {
let data = read_unpoisoned(&self.data);
let mut series = data.entry(id).or_default();
if series
.states
.last()
.is_none_or(|last| last.timestamp_secs <= timestamp)
{
series.states.push(TimestampedState {
timestamp_secs: timestamp,
state,
});
return;
}
let insert_at = series
.states
.partition_point(|state| state.timestamp_secs <= timestamp);
series.states.insert(
insert_at,
TimestampedState {
timestamp_secs: timestamp,
state,
},
);
}
pub fn append_event(&self, id: AircraftId, timestamp: f64, event: Event) {
let data = read_unpoisoned(&self.data);
let mut series = data.entry(id).or_default();
if let Event::Spawn(spawn) = &event {
series.config = Some(AircraftConfig {
name: spawn.name.clone(),
toml_config: spawn.toml_config.clone(),
});
}
if series
.events
.last()
.is_none_or(|last| last.timestamp_secs <= timestamp)
{
series.events.push(TimestampedEvent {
timestamp_secs: timestamp,
event,
});
return;
}
let insert_at = series
.events
.partition_point(|event| event.timestamp_secs <= timestamp);
series.events.insert(
insert_at,
TimestampedEvent {
timestamp_secs: timestamp,
event,
},
);
}
pub fn append_message(&self, msg: pb::Message) {
self.append_message_with_config(msg, &StoreConfig);
}
pub fn append_message_with_config(
&self,
msg: pb::Message,
#[allow(unused_variables)] config: &StoreConfig,
) {
let Some(pb::message::Envelope::Request(req)) = msg.envelope else {
debug!(target: "fly_ruler_proto_core.store", "ignored non-request envelope");
return;
};
let timestamp = req.timestamp;
let Some(command) = req.command.and_then(|c| c.kind) else {
warn!(target: "fly_ruler_proto_core.store", "ignored request without command");
return;
};
let pb::request_command::Kind::AircraftEvent(event) = command else {
debug!(target: "fly_ruler_proto_core.store", "ignored non-aircraft command");
return;
};
let aircraft_id = event
.aircraft_id
.as_ref()
.map(uuid_to_hex)
.unwrap_or_else(|| "unknown".to_string());
let Some(info) = event.info.and_then(|i| i.kind) else {
warn!(target: "fly_ruler_proto_core.store", aircraft_id = aircraft_id, "ignored aircraft event without command info");
return;
};
match info {
pb::aircraft_command_info::Kind::StateUpdate(state) => {
self.append_state(aircraft_id, timestamp, state);
}
pb::aircraft_command_info::Kind::Spawn(spawn) => {
if let Some(state) = spawn.initial_state.clone() {
self.append_state(aircraft_id.clone(), timestamp, state);
}
self.append_event(aircraft_id, timestamp, Event::Spawn(Box::new(spawn)));
}
pb::aircraft_command_info::Kind::Despawn(despawn) => {
self.append_event(aircraft_id, timestamp, Event::Despawn(despawn));
}
pb::aircraft_command_info::Kind::CustomEvent(custom) => {
self.append_event(aircraft_id, timestamp, Event::Custom(custom));
}
}
}
pub fn get_latest(&self, id: &AircraftId) -> Option<TimestampedState> {
let data = read_unpoisoned(&self.data);
data.get(id)
.and_then(|series| series.states.last().cloned())
}
pub fn get_state_at_or_before(
&self,
id: &AircraftId,
timestamp: f64,
) -> Option<TimestampedState> {
if !timestamp.is_finite() {
return None;
}
let data = read_unpoisoned(&self.data);
data.get(id).and_then(|series| {
let end = series
.states
.partition_point(|state| state.timestamp_secs <= timestamp);
end.checked_sub(1)
.and_then(|index| series.states.get(index).cloned())
})
}
pub fn is_spawned_at(&self, id: &AircraftId, timestamp: f64) -> bool {
let data = read_unpoisoned(&self.data);
data.get(id)
.and_then(|series| {
let end = if timestamp.is_infinite() && timestamp.is_sign_positive() {
series.events.len()
} else if timestamp.is_finite() {
series
.events
.partition_point(|event| event.timestamp_secs <= timestamp)
} else {
0
};
series.events[..end]
.iter()
.rev()
.find_map(|entry| match entry.event {
Event::Spawn(_) => Some(true),
Event::Despawn(_) => Some(false),
Event::Custom(_) => None,
})
})
.unwrap_or(false)
}
pub fn get_states_range(
&self,
id: &AircraftId,
start: f64,
end: f64,
) -> Option<Vec<TimestampedState>> {
let data = read_unpoisoned(&self.data);
data.get(id).map(|series| {
series
.states
.iter()
.filter(|s| s.timestamp_secs >= start && s.timestamp_secs <= end)
.cloned()
.collect()
})
}
pub fn get_states_page(
&self,
id: &AircraftId,
start: f64,
end: f64,
offset: usize,
limit: usize,
) -> Option<StorePage<TimestampedState>> {
let data = read_unpoisoned(&self.data);
data.get(id).map(|series| {
let first = series
.states
.partition_point(|state| state.timestamp_secs < start);
let last = series
.states
.partition_point(|state| state.timestamp_secs <= end);
page_slice(&series.states[first..last], offset, limit)
})
}
pub(crate) fn visit_states_range<R>(
&self,
id: &AircraftId,
start: f64,
end: f64,
visitor: impl FnOnce(&[TimestampedState]) -> R,
) -> Option<R> {
let data = read_unpoisoned(&self.data);
data.get(id).map(|series| {
let first = series
.states
.partition_point(|state| state.timestamp_secs < start);
let last = series
.states
.partition_point(|state| state.timestamp_secs <= end);
visitor(&series.states[first..last])
})
}
pub fn get_events_range(
&self,
id: &AircraftId,
start: f64,
end: f64,
) -> Option<Vec<TimestampedEvent>> {
let data = read_unpoisoned(&self.data);
data.get(id).map(|series| {
series
.events
.iter()
.filter(|e| e.timestamp_secs >= start && e.timestamp_secs <= end)
.cloned()
.collect()
})
}
pub fn get_events_page(
&self,
id: &AircraftId,
start: f64,
end: f64,
offset: usize,
limit: usize,
) -> Option<StorePage<TimestampedEvent>> {
let data = read_unpoisoned(&self.data);
data.get(id).map(|series| {
let first = series
.events
.partition_point(|event| event.timestamp_secs < start);
let last = series
.events
.partition_point(|event| event.timestamp_secs <= end);
page_slice(&series.events[first..last], offset, limit)
})
}
pub fn get_global_events_page(
&self,
start: f64,
end: f64,
offset: usize,
limit: usize,
) -> StorePage<GlobalTimestampedEvent> {
let data = read_unpoisoned(&self.data);
let mut aircraft_ids = data
.iter()
.map(|entry| entry.key().clone())
.collect::<Vec<_>>();
aircraft_ids.sort();
let mut events = Vec::new();
for aircraft_id in aircraft_ids {
let Some(series) = data.get(&aircraft_id) else {
continue;
};
let first = series
.events
.partition_point(|event| event.timestamp_secs < start);
let last = series
.events
.partition_point(|event| event.timestamp_secs <= end);
events.extend(
series.events[first..last]
.iter()
.map(|entry| GlobalTimestampedEvent {
aircraft_id: aircraft_id.clone(),
timestamp_secs: entry.timestamp_secs,
event: entry.event.clone(),
}),
);
}
events.sort_by(|left, right| {
left.timestamp_secs
.total_cmp(&right.timestamp_secs)
.then_with(|| left.aircraft_id.cmp(&right.aircraft_id))
});
page_slice(&events, offset, limit)
}
pub fn previous_global_state_timestamp(&self, cursor: f64, count: usize) -> Option<f64> {
self.adjacent_global_timestamp(cursor, count, TimelineEntryKind::State, false)
}
pub fn next_global_state_timestamp(&self, cursor: f64, count: usize) -> Option<f64> {
self.adjacent_global_timestamp(cursor, count, TimelineEntryKind::State, true)
}
pub fn previous_global_event_timestamp(&self, cursor: f64, count: usize) -> Option<f64> {
self.adjacent_global_timestamp(cursor, count, TimelineEntryKind::Event, false)
}
pub fn next_global_event_timestamp(&self, cursor: f64, count: usize) -> Option<f64> {
self.adjacent_global_timestamp(cursor, count, TimelineEntryKind::Event, true)
}
fn adjacent_global_timestamp(
&self,
cursor: f64,
count: usize,
kind: TimelineEntryKind,
forward: bool,
) -> Option<f64> {
if !cursor.is_finite() || count == 0 {
return None;
}
let data = read_unpoisoned(&self.data);
let mut probe = cursor;
let mut result = None;
for _ in 0..count {
let candidate = data
.iter()
.filter_map(|entry| match kind {
TimelineEntryKind::State => {
if forward {
let index = entry
.states
.partition_point(|state| state.timestamp_secs <= probe);
entry.states.get(index).map(|state| state.timestamp_secs)
} else {
let index = entry
.states
.partition_point(|state| state.timestamp_secs < probe);
index
.checked_sub(1)
.and_then(|index| entry.states.get(index))
.map(|state| state.timestamp_secs)
}
}
TimelineEntryKind::Event => {
if forward {
let index = entry
.events
.partition_point(|event| event.timestamp_secs <= probe);
entry.events.get(index).map(|event| event.timestamp_secs)
} else {
let index = entry
.events
.partition_point(|event| event.timestamp_secs < probe);
index
.checked_sub(1)
.and_then(|index| entry.events.get(index))
.map(|event| event.timestamp_secs)
}
}
})
.reduce(|best, candidate| {
if (forward && candidate.total_cmp(&best).is_lt())
|| (!forward && candidate.total_cmp(&best).is_gt())
{
candidate
} else {
best
}
});
let Some(candidate) = candidate else {
break;
};
result = Some(candidate);
probe = candidate;
}
result
}
pub fn get_aircraft_ids(&self) -> Vec<AircraftId> {
let data = read_unpoisoned(&self.data);
let mut ids: Vec<_> = data.iter().map(|item| item.key().clone()).collect();
ids.sort();
ids
}
pub fn aircraft_summaries(&self) -> Vec<AircraftSummary> {
let data = read_unpoisoned(&self.data);
let mut summaries: Vec<_> = data
.iter()
.map(|entry| {
let series = entry.value();
AircraftSummary {
id: entry.key().clone(),
config: series.config.clone(),
time_range: series
.states
.first()
.zip(series.states.last())
.map(|(first, last)| (first.timestamp_secs, last.timestamp_secs)),
state_count: series.states.len(),
event_count: series.events.len(),
}
})
.collect();
summaries.sort_by(|left, right| left.id.cmp(&right.id));
summaries
}
pub fn snapshot_clone(&self) -> Self {
let snapshot = Self::new();
let data = read_unpoisoned(&self.data);
let snapshot_data = write_unpoisoned(&snapshot.data);
for entry in &*data {
snapshot_data.insert(entry.key().clone(), entry.value().clone());
}
drop(snapshot_data);
snapshot
}
pub fn replace_from(&self, other: &Self) {
if std::ptr::eq(self, other) {
return;
}
let replacement = DashMap::new();
let other_data = read_unpoisoned(&other.data);
for entry in &*other_data {
replacement.insert(entry.key().clone(), entry.value().clone());
}
drop(other_data);
*write_unpoisoned(&self.data) = replacement;
}
pub fn clear(&self) {
*write_unpoisoned(&self.data) = DashMap::new();
}
pub fn save_to_disk(&self, path: &Path) -> Result<(), StoreError> {
info!(target: "fly_ruler_proto_core.store", path = %path.display(), "saving store to disk");
fs::create_dir_all(path)?;
self.write_meta(path)?;
self.write_states_parquet(path)?;
self.write_events_parquet(path)?;
info!(target: "fly_ruler_proto_core.store", path = %path.display(), aircraft_count = self.get_aircraft_ids().len(), "store save completed");
Ok(())
}
pub fn load_from_disk(&self, path: &Path) -> Result<(), StoreError> {
info!(target: "fly_ruler_proto_core.store", path = %path.display(), "loading store from disk");
let loaded = Self::new();
loaded.read_states_parquet(path)?;
loaded.read_events_parquet(path)?;
loaded.read_meta(path)?;
self.replace_from(&loaded);
info!(target: "fly_ruler_proto_core.store", path = %path.display(), aircraft_count = self.get_aircraft_ids().len(), "store load completed");
Ok(())
}
fn write_meta(&self, path: &Path) -> Result<(), StoreError> {
let mut aircrafts = Vec::new();
let data = read_unpoisoned(&self.data);
for item in &*data {
let id = item.key().clone();
let series = item.value();
let time_range = series
.states
.first()
.zip(series.states.last())
.map(|(a, b)| (a.timestamp_secs, b.timestamp_secs));
aircrafts.push(MetaAircraft {
id,
name: series.config.as_ref().map(|c| c.name.clone()),
toml_config: series.config.as_ref().map(|c| c.toml_config.clone()),
time_range,
state_count: series.states.len(),
event_count: series.events.len(),
});
}
aircrafts.sort_by(|a, b| a.id.cmp(&b.id));
let meta = MetaFile {
version: PROTOCOL_VERSION.to_string(),
aircrafts,
};
let bytes = serde_json::to_vec_pretty(&meta)?;
fs::write(path.join("meta.json"), bytes)?;
Ok(())
}
fn read_meta(&self, path: &Path) -> Result<(), StoreError> {
let meta_path = path.join("meta.json");
if !meta_path.exists() {
return Ok(());
}
let data = fs::read(meta_path)?;
let meta: MetaFile = serde_json::from_slice(&data)?;
for entry in meta.aircrafts {
let data = read_unpoisoned(&self.data);
if let Some(mut series) = data.get_mut(&entry.id) {
if let (Some(name), Some(toml_config)) = (entry.name, entry.toml_config) {
series.config = Some(AircraftConfig { name, toml_config });
}
};
}
Ok(())
}
fn write_states_parquet(&self, path: &Path) -> Result<(), StoreError> {
let schema = Arc::new(Schema::new(vec![
Field::new("aircraft_id", DataType::Utf8, false),
Field::new("timestamp", DataType::Float64, false),
Field::new("state_payload", DataType::Binary, false),
]));
let mut ids = Vec::<String>::new();
let mut ts = Vec::<f64>::new();
let mut payloads = Vec::<Vec<u8>>::new();
let data = read_unpoisoned(&self.data);
for item in &*data {
let id = item.key().clone();
for state in &item.value().states {
ids.push(id.clone());
ts.push(state.timestamp_secs);
payloads.push(state.state.encode_to_vec());
}
}
let batch = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(StringArray::from(ids)) as Arc<dyn Array>,
Arc::new(Float64Array::from(ts)) as Arc<dyn Array>,
Arc::new(BinaryArray::from_iter_values(payloads)) as Arc<dyn Array>,
],
)?;
let file = File::create(path.join("states.parquet"))?;
let mut writer = ArrowWriter::try_new(file, schema, None)?;
writer.write(&batch)?;
writer.close()?;
Ok(())
}
fn write_events_parquet(&self, path: &Path) -> Result<(), StoreError> {
let schema = Arc::new(Schema::new(vec![
Field::new("aircraft_id", DataType::Utf8, false),
Field::new("timestamp", DataType::Float64, false),
Field::new("event_type", DataType::Utf8, false),
Field::new("event_payload", DataType::Binary, false),
]));
let mut ids = Vec::<String>::new();
let mut ts = Vec::<f64>::new();
let mut kinds = Vec::<String>::new();
let mut payloads = Vec::<Vec<u8>>::new();
let data = read_unpoisoned(&self.data);
for item in &*data {
let id = item.key().clone();
for event in &item.value().events {
ids.push(id.clone());
ts.push(event.timestamp_secs);
let (kind, payload) = encode_event(&event.event);
kinds.push(kind);
payloads.push(payload);
}
}
let batch = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(StringArray::from(ids)) as Arc<dyn Array>,
Arc::new(Float64Array::from(ts)) as Arc<dyn Array>,
Arc::new(StringArray::from(kinds)) as Arc<dyn Array>,
Arc::new(BinaryArray::from_iter_values(payloads)) as Arc<dyn Array>,
],
)?;
let file = File::create(path.join("events.parquet"))?;
let mut writer = ArrowWriter::try_new(file, schema, None)?;
writer.write(&batch)?;
writer.close()?;
Ok(())
}
fn read_states_parquet(&self, path: &Path) -> Result<(), StoreError> {
let file_path = path.join("states.parquet");
if !file_path.exists() {
return Ok(());
}
let file = File::open(file_path)?;
let mut reader = ParquetRecordBatchReaderBuilder::try_new(file)?
.with_batch_size(1024)
.build()?;
for maybe_batch in &mut reader {
let batch = maybe_batch?;
let ids = as_string_array(batch.column(0), "aircraft_id")?;
let timestamps = as_f64_array(batch.column(1), "timestamp")?;
let payloads = as_binary_array(batch.column(2), "state_payload")?;
for i in 0..batch.num_rows() {
let id = ids.value(i).to_string();
let ts = timestamps.value(i);
let state = pb::AircraftState::decode(payloads.value(i))?;
self.append_state(id, ts, state);
}
}
Ok(())
}
fn read_events_parquet(&self, path: &Path) -> Result<(), StoreError> {
let file_path = path.join("events.parquet");
if !file_path.exists() {
return Ok(());
}
let file = File::open(file_path)?;
let mut reader = ParquetRecordBatchReaderBuilder::try_new(file)?
.with_batch_size(1024)
.build()?;
for maybe_batch in &mut reader {
let batch = maybe_batch?;
let ids = as_string_array(batch.column(0), "aircraft_id")?;
let timestamps = as_f64_array(batch.column(1), "timestamp")?;
let kinds = as_string_array(batch.column(2), "event_type")?;
let payloads = as_binary_array(batch.column(3), "event_payload")?;
for i in 0..batch.num_rows() {
let id = ids.value(i).to_string();
let ts = timestamps.value(i);
let event = decode_event(kinds.value(i), payloads.value(i))?;
self.append_event(id, ts, event);
}
}
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
enum TimelineEntryKind {
State,
Event,
}
fn page_slice<T: Clone>(items: &[T], offset: usize, limit: usize) -> StorePage<T> {
let total = items.len();
let start = offset.min(total);
let end = start.saturating_add(limit).min(total);
StorePage {
items: items[start..end].to_vec(),
total,
offset,
limit,
}
}
fn read_unpoisoned<T>(lock: &RwLock<T>) -> RwLockReadGuard<'_, T> {
lock.read().unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn write_unpoisoned<T>(lock: &RwLock<T>) -> RwLockWriteGuard<'_, T> {
lock.write()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn as_string_array<'a>(
array: &'a Arc<dyn Array>,
name: &str,
) -> Result<&'a StringArray, StoreError> {
array
.as_any()
.downcast_ref::<StringArray>()
.ok_or_else(|| StoreError::InvalidData(format!("{name} column type mismatch")))
}
fn as_f64_array<'a>(array: &'a Arc<dyn Array>, name: &str) -> Result<&'a Float64Array, StoreError> {
array
.as_any()
.downcast_ref::<Float64Array>()
.ok_or_else(|| StoreError::InvalidData(format!("{name} column type mismatch")))
}
fn as_binary_array<'a>(
array: &'a Arc<dyn Array>,
name: &str,
) -> Result<&'a BinaryArray, StoreError> {
array
.as_any()
.downcast_ref::<BinaryArray>()
.ok_or_else(|| StoreError::InvalidData(format!("{name} column type mismatch")))
}
fn encode_event(event: &Event) -> (String, Vec<u8>) {
match event {
Event::Spawn(spawn) => ("spawn".to_string(), spawn.encode_to_vec()),
Event::Despawn(despawn) => ("despawn".to_string(), despawn.encode_to_vec()),
Event::Custom(custom) => ("custom".to_string(), custom.as_bytes().to_vec()),
}
}
fn decode_event(kind: &str, payload: &[u8]) -> Result<Event, StoreError> {
match kind {
"spawn" => Ok(Event::Spawn(Box::new(pb::AircraftSpawnInfo::decode(
payload,
)?))),
"despawn" => Ok(Event::Despawn(pb::DespawnInfo::decode(payload)?)),
"custom" => Ok(Event::Custom(String::from_utf8(payload.to_vec()).map_err(
|e| StoreError::InvalidData(format!("invalid utf8 custom event: {e}")),
)?)),
_ => Err(StoreError::InvalidData(format!(
"unknown event type: {kind}"
))),
}
}
pub fn event_count_for(store: &TimeSeriesStore) -> usize {
let data = read_unpoisoned(&store.data);
data.iter().map(|entry| entry.value().events.len()).sum()
}
pub fn state_count_for(store: &TimeSeriesStore) -> usize {
let data = read_unpoisoned(&store.data);
data.iter().map(|entry| entry.value().states.len()).sum()
}
pub fn aircraft_count_for(store: &TimeSeriesStore) -> usize {
read_unpoisoned(&store.data).iter().count()
}
pub fn active_time_bounds(store: &TimeSeriesStore) -> Option<(f64, f64)> {
let mut min_start: Option<f64> = None;
let mut max_end: Option<f64> = None;
let data = read_unpoisoned(&store.data);
for entry in &*data {
let series = entry.value();
let first = series
.states
.first()
.map(|state| state.timestamp_secs)
.into_iter()
.chain(series.events.first().map(|event| event.timestamp_secs))
.min_by(f64::total_cmp);
let last = series
.states
.last()
.map(|state| state.timestamp_secs)
.into_iter()
.chain(series.events.last().map(|event| event.timestamp_secs))
.max_by(f64::total_cmp);
if let (Some(first), Some(last)) = (first, last) {
min_start = Some(match min_start {
Some(current) => current.min(first),
None => first,
});
max_end = Some(match max_end {
Some(current) => current.max(last),
None => last,
});
}
}
Some((min_start?, max_end?))
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{SystemTime, UNIX_EPOCH};
fn mk_state(x: f64) -> pb::AircraftState {
pb::AircraftState {
position: Some(pb::Vector3 { x, y: 0.0, z: 0.0 }),
velocity: Some(pb::Vector3 {
x: 0.0,
y: 0.0,
z: 0.0,
}),
attitude: Some(pb::Quaternion {
w: 1.0,
x: 0.0,
y: 0.0,
z: 0.0,
}),
angular_velocity: Some(pb::Vector3 {
x: 0.0,
y: 0.0,
z: 0.0,
}),
derived: None,
control_surfaces: None,
engines: vec![],
custom_fields: vec![],
}
}
#[test]
fn append_and_query_range_works() {
let store = TimeSeriesStore::new();
store.append_state("a1".to_string(), 1.0, mk_state(1.0));
store.append_state("a1".to_string(), 2.0, mk_state(2.0));
store.append_state("a1".to_string(), 3.0, mk_state(3.0));
let latest = store.get_latest(&"a1".to_string()).unwrap();
assert_eq!(latest.timestamp_secs, 3.0);
let range = store.get_states_range(&"a1".to_string(), 1.5, 3.0).unwrap();
assert_eq!(range.len(), 2);
assert_eq!(range[0].timestamp_secs, 2.0);
}
#[test]
fn save_and_load_roundtrip_works() {
let store = TimeSeriesStore::new();
store.append_state("a1".to_string(), 1.0, mk_state(10.0));
store.append_event("a1".to_string(), 1.5, Event::Custom("evt".to_string()));
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let dir = std::env::temp_dir().join(format!("fly_ruler_store_test_{nanos}"));
store.save_to_disk(&dir).unwrap();
let restored = TimeSeriesStore::new();
restored.load_from_disk(&dir).unwrap();
assert_eq!(state_count_for(&restored), 1);
assert_eq!(event_count_for(&restored), 1);
assert_eq!(aircraft_count_for(&restored), 1);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn out_of_order_state_insert_keeps_sorted_order() {
let store = TimeSeriesStore::new();
store.append_state("a1".to_string(), 3.0, mk_state(3.0));
store.append_state("a1".to_string(), 1.0, mk_state(1.0));
store.append_state("a1".to_string(), 2.0, mk_state(2.0));
let states = store
.get_states_range(&"a1".to_string(), 0.0, 10.0)
.unwrap();
assert_eq!(states.len(), 3);
assert_eq!(states[0].timestamp_secs, 1.0);
assert_eq!(states[1].timestamp_secs, 2.0);
assert_eq!(states[2].timestamp_secs, 3.0);
}
#[test]
fn adjacent_global_timestamps_deduplicate_and_clamp_to_available_entries() {
let store = TimeSeriesStore::new();
for timestamp in [1.0, 2.0, 4.0] {
store.append_state("a".to_string(), timestamp, mk_state(timestamp));
}
for timestamp in [2.0, 3.0, 5.0] {
store.append_state("b".to_string(), timestamp, mk_state(timestamp));
}
store.append_event("a".to_string(), 1.5, Event::Custom("a".to_string()));
store.append_event("b".to_string(), 3.5, Event::Custom("b".to_string()));
assert_eq!(store.next_global_state_timestamp(1.0, 1), Some(2.0));
assert_eq!(store.next_global_state_timestamp(1.0, 2), Some(3.0));
assert_eq!(store.next_global_state_timestamp(1.0, 99), Some(5.0));
assert_eq!(store.previous_global_state_timestamp(5.0, 2), Some(3.0));
assert_eq!(store.previous_global_event_timestamp(4.0, 1), Some(3.5));
assert_eq!(store.next_global_event_timestamp(0.0, 99), Some(3.5));
}
#[test]
fn spawn_event_populates_aircraft_config() {
let store = TimeSeriesStore::new();
let spawn = pb::AircraftSpawnInfo {
name: "F-16".to_string(),
toml_config: "[aircraft]\nname='F-16'".to_string(),
initial_state: Some(mk_state(0.0)),
};
store.append_event("a1".to_string(), 1.0, Event::Spawn(Box::new(spawn)));
let data = read_unpoisoned(&store.data);
let entry = data.get("a1").unwrap();
let config = entry.config.as_ref().unwrap();
assert_eq!(config.name, "F-16");
assert!(config.toml_config.contains("aircraft"));
}
#[test]
fn clear_removes_all_in_memory_data() {
let store = TimeSeriesStore::new();
store.append_state("a1".to_string(), 1.0, mk_state(1.0));
store.append_event("a1".to_string(), 1.2, Event::Custom("x".to_string()));
assert_eq!(aircraft_count_for(&store), 1);
store.clear();
assert_eq!(aircraft_count_for(&store), 0);
assert_eq!(state_count_for(&store), 0);
assert_eq!(event_count_for(&store), 0);
}
#[test]
fn active_time_bounds_returns_global_min_max() {
let store = TimeSeriesStore::new();
store.append_state("a1".to_string(), 10.0, mk_state(1.0));
store.append_state("a1".to_string(), 20.0, mk_state(2.0));
store.append_state("a2".to_string(), 5.0, mk_state(3.0));
store.append_state("a2".to_string(), 25.0, mk_state(4.0));
store.append_event("a1".to_string(), 30.0, Event::Custom("end".to_string()));
store.append_event("a2".to_string(), 1.0, Event::Custom("begin".to_string()));
let bounds = active_time_bounds(&store).unwrap();
assert_eq!(bounds.0, 1.0);
assert_eq!(bounds.1, 30.0);
}
#[test]
fn state_at_or_before_uses_last_duplicate() {
let store = TimeSeriesStore::new();
store.append_state("a1".to_string(), 1.0, mk_state(1.0));
store.append_state("a1".to_string(), 1.0, mk_state(2.0));
store.append_state("a1".to_string(), 2.0, mk_state(3.0));
let state = store
.get_state_at_or_before(&"a1".to_string(), 1.0)
.unwrap();
assert_eq!(state.state.position.unwrap().x, 2.0);
assert!(store
.get_state_at_or_before(&"a1".to_string(), 0.5)
.is_none());
}
#[test]
fn paginated_ranges_report_total() {
let store = TimeSeriesStore::new();
for timestamp in 0..5 {
store.append_state(
"a1".to_string(),
timestamp as f64,
mk_state(timestamp as f64),
);
}
let page = store
.get_states_page(&"a1".to_string(), 1.0, 4.0, 1, 2)
.unwrap();
assert_eq!(page.total, 4);
assert_eq!(page.items.len(), 2);
assert_eq!(page.items[0].timestamp_secs, 2.0);
}
#[test]
fn global_event_page_is_sorted_and_paginated() {
let store = TimeSeriesStore::new();
store.append_event("b".to_string(), 2.0, Event::Custom("b2".to_string()));
store.append_event("a".to_string(), 1.0, Event::Custom("a1".to_string()));
store.append_event("b".to_string(), 1.0, Event::Custom("b1".to_string()));
store.append_event("a".to_string(), 3.0, Event::Custom("a3".to_string()));
let page = store.get_global_events_page(1.0, 3.0, 1, 2);
assert_eq!(page.total, 4);
assert_eq!(page.items.len(), 2);
assert_eq!(page.items[0].aircraft_id, "b");
assert_eq!(page.items[0].timestamp_secs, 1.0);
assert_eq!(page.items[1].aircraft_id, "b");
assert_eq!(page.items[1].timestamp_secs, 2.0);
}
#[test]
fn snapshot_replace_and_lifecycle_queries_work() {
let store = TimeSeriesStore::new();
store.append_event("a1".to_string(), 1.0, Event::Spawn(Box::default()));
store.append_event(
"a1".to_string(),
3.0,
Event::Despawn(pb::DespawnInfo::default()),
);
assert!(store.is_spawned_at(&"a1".to_string(), 2.0));
assert!(!store.is_spawned_at(&"a1".to_string(), 4.0));
let snapshot = store.snapshot_clone();
store.clear();
store.replace_from(&snapshot);
assert_eq!(store.aircraft_summaries().len(), 1);
}
}