chore: 新增项目规则文档、构建别名及忽略规则

添加 AGENTS.md 项目规则文件,涵盖语言与工具链、模块设计、
Git 提交规范及验证流程等内容。

变更要点:
- .cargo/config.toml 新增 xtask 命令别名
- .gitignore 忽略运行时地图缓存、接收器配置文件、
  构建锁文件及本地 docs/ 目录
- 新增 AGENTS.md 定义项目编码、提交与审查规则
```
This commit is contained in:
2026-10-21 16:23:47 +08:00
parent 19d4b6de29
commit 7d2e37a0ef
75 changed files with 13196 additions and 2939 deletions
+42
View File
@@ -0,0 +1,42 @@
use realtime_core::Store;
use rid_shared::Observation;
use std::time::{Instant, SystemTime, UNIX_EPOCH};
fn main() {
let count: usize = std::env::args()
.nth(1)
.unwrap_or("10000".into())
.parse()
.expect("target count");
assert!((1..=100000).contains(&count));
let mut store = Store::new(count, count * 2, 30000, 1);
let start = Instant::now();
for sequence in 0..100 {
for id in 0..count {
store.apply(
Observation {
target_id: format!("SIM-{id}"),
receiver_id: "SIM".into(),
source_epoch: 1,
sequence,
longitude: 120.0 + id as f64 * 0.00001,
latitude: 30.0,
altitude_m: 100.0,
heading_deg: 90.0,
},
sequence,
);
}
}
let elapsed = start.elapsed();
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis();
println!(
"{{\"kind\":\"state-core-only-not-end-to-end\",\"targets\":{count},\"updates\":{},\"seconds\":{},\"updates_per_second\":{},\"measured_at_unix_ms\":{now}}}",
count * 100,
elapsed.as_secs_f64(),
count as f64 * 100.0 / elapsed.as_secs_f64()
);
}
@@ -0,0 +1,111 @@
//! Explicit synthetic input generator for an isolated --simulation-api server.
use rid_shared::Observation;
use std::{
io::{BufRead, BufReader, Read, Write},
net::TcpStream,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut count = 1000usize;
let mut interval_ms = 20u64;
let mut seconds = 30u64;
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
let value = args.next().ok_or("missing argument value")?;
match arg.as_str() {
"--targets" => count = value.parse()?,
"--interval-ms" => interval_ms = value.parse()?,
"--seconds" => seconds = value.parse()?,
_ => {
return Err(
"usage: rid-simulator [--targets 1000] [--interval-ms 20] [--seconds 30]"
.into(),
);
}
}
}
if !(1..=10000).contains(&count)
|| !(1..=1000).contains(&interval_ms)
|| !(1..=7200).contains(&seconds)
{
return Err("invalid load; targets 1..10000, interval 1..1000 ms, seconds 1..7200".into());
}
eprintln!(
"SYNTHETIC DATA ONLY: localhost:8787 must use --simulation-api. Requested interval is not a throughput guarantee."
);
let epoch = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64;
let socket = TcpStream::connect_timeout(&"127.0.0.1:8787".parse()?, Duration::from_secs(2))?;
socket.set_nodelay(true)?;
socket.set_read_timeout(Some(Duration::from_secs(5)))?;
socket.set_write_timeout(Some(Duration::from_secs(5)))?;
let mut connection = BufReader::new(socket);
let start = Instant::now();
let mut sequence = 0;
let mut overruns = 0;
while start.elapsed() < Duration::from_secs(seconds) {
sequence += 1;
let tick = Instant::now();
for offset in (0..count).step_by(1000) {
let batch: Vec<_> = (offset..(offset + 1000).min(count))
.map(|id| Observation {
target_id: format!("SIM-{id:05}"),
receiver_id: "SIMULATOR".into(),
source_epoch: epoch,
sequence,
longitude: 120.0
+ (id as f64).cos() * 0.1
+ ((sequence as f64) * 0.01).sin() * 0.005,
latitude: 30.0 + (id as f64).sin() * 0.1,
altitude_m: 100.0,
heading_deg: (id % 360) as f32,
})
.collect();
let body = postcard::to_allocvec(&batch)?;
write!(
connection.get_mut(),
"POST /api/realtime/ingest HTTP/1.1\r\nHost: 127.0.0.1:8787\r\nContent-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: keep-alive\r\n\r\n",
body.len()
)?;
connection.get_mut().write_all(&body)?;
let mut line = String::new();
connection.read_line(&mut line)?;
if !line.starts_with("HTTP/1.1 200") {
return Err(format!("input rejected: {}", line.trim()).into());
}
let mut length = None;
loop {
line.clear();
if connection.read_line(&mut line)? == 0 {
return Err("server closed response headers".into());
}
if line.len() > 8192 {
return Err("response header exceeds limit".into());
}
if line == "\r\n" {
break;
}
if let Some((name, value)) = line.split_once(':')
&& name.eq_ignore_ascii_case("content-length")
{
length = Some(value.trim().parse::<usize>()?);
}
}
let length = length
.filter(|n| *n <= 4096)
.ok_or("invalid response length")?;
let mut response = vec![0; length];
connection.read_exact(&mut response)?;
}
if let Some(remaining) = Duration::from_millis(interval_ms).checked_sub(tick.elapsed()) {
std::thread::sleep(remaining)
} else {
overruns += 1;
}
}
println!(
"{{\"mode\":\"synthetic-http-postcard\",\"targets\":{count},\"requested_interval_ms\":{interval_ms},\"ticks\":{sequence},\"overruns\":{overruns},\"actual_seconds\":{}}}",
start.elapsed().as_secs_f64()
);
Ok(())
}
+211
View File
@@ -0,0 +1,211 @@
//! Bounded latest-state store, independent of SQLite and archive generation.
use rid_shared::{Frame, Metrics, Observation, PROTOCOL_VERSION, Target};
use std::collections::{HashMap, HashSet, VecDeque};
struct Track {
target: Target,
sources: HashMap<String, (u64, u64)>,
}
pub struct Store {
tracks: HashMap<String, Track>,
changes: VecDeque<(u64, String)>,
journal_capacity: usize,
epoch: u64,
ttl_ms: u64,
metrics: Metrics,
}
impl Store {
pub fn new(capacity: usize, journal_capacity: usize, ttl_ms: u64, epoch: u64) -> Self {
assert!(capacity > 0 && journal_capacity > 0 && ttl_ms > 0);
Self {
tracks: HashMap::new(),
changes: VecDeque::new(),
journal_capacity,
epoch,
ttl_ms,
metrics: Metrics {
capacity,
..Metrics::default()
},
}
}
fn changed(&mut self, id: String) {
self.metrics.sequence += 1;
if self.changes.len() == self.journal_capacity {
self.changes.pop_front();
}
self.changes.push_back((self.metrics.sequence, id));
}
/// Multiple receivers use arrival order; no unverified sensor-time fusion is implied.
pub fn apply(&mut self, observation: Observation, now_ms: u64) -> bool {
if !observation.validate() {
self.metrics.rejected += 1;
return false;
}
let id = observation.target_id.clone();
if let Some(track) = self.tracks.get_mut(&id) {
if let Some(&(epoch, sequence)) = track.sources.get(&observation.receiver_id) {
if observation.source_epoch < epoch
|| (observation.source_epoch == epoch && observation.sequence <= sequence)
{
self.metrics.stale += 1;
return false;
}
} else if track.sources.len() >= 8 {
self.metrics.rejected += 1;
return false;
}
track.sources.insert(
observation.receiver_id.clone(),
(observation.source_epoch, observation.sequence),
);
track.target = Target {
observation,
received_at_ms: now_ms,
};
} else {
if self.tracks.len() >= self.metrics.capacity {
self.metrics.rejected += 1;
return false;
}
let sources = HashMap::from([(
observation.receiver_id.clone(),
(observation.source_epoch, observation.sequence),
)]);
self.tracks.insert(
id.clone(),
Track {
target: Target {
observation,
received_at_ms: now_ms,
},
sources,
},
);
}
self.metrics.accepted += 1;
self.changed(id);
true
}
pub fn expire(&mut self, now_ms: u64) {
let expired: Vec<String> = self
.tracks
.iter()
.filter(|(_, t)| now_ms.saturating_sub(t.target.received_at_ms) >= self.ttl_ms)
.map(|(id, _)| id.clone())
.collect();
for id in expired {
self.tracks.remove(&id);
self.metrics.expired += 1;
self.changed(id);
}
}
pub fn frame(&self, since: Option<u64>, now_ms: u64) -> Frame {
let snapshot = since.is_none_or(|s| {
s > self.metrics.sequence
|| self
.changes
.front()
.is_some_and(|(oldest, _)| s.saturating_add(1) < *oldest)
});
let mut targets = Vec::new();
let mut removed = Vec::new();
if snapshot {
targets.extend(self.tracks.values().map(|t| t.target.clone()));
} else {
let mut ids = HashSet::new();
for (_, id) in self
.changes
.iter()
.rev()
.take_while(|(seq, _)| *seq > since.unwrap())
{
if ids.insert(id) {
if let Some(track) = self.tracks.get(id) {
targets.push(track.target.clone());
} else {
removed.push(id.clone());
}
}
}
}
Frame {
version: PROTOCOL_VERSION,
epoch: self.epoch,
sequence: self.metrics.sequence,
snapshot,
server_time_ms: now_ms,
targets,
removed,
}
}
pub fn metrics(&self) -> Metrics {
Metrics {
active_targets: self.tracks.len(),
..self.metrics.clone()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample(id: &str, sequence: u64) -> Observation {
Observation {
target_id: id.into(),
receiver_id: "station-1".into(),
source_epoch: 1,
sequence,
longitude: 120.0,
latitude: 30.0,
altitude_m: 100.0,
heading_deg: 90.0,
}
}
#[test]
fn stale_and_capacity_are_bounded() {
let mut s = Store::new(1, 4, 100, 1);
assert!(s.apply(sample("a", 2), 0));
assert!(!s.apply(sample("a", 1), 1));
assert!(!s.apply(sample("b", 1), 1));
assert_eq!(s.metrics().active_targets, 1);
assert_eq!(s.metrics().stale, 1);
s.expire(100);
assert!(s.apply(sample("b", 1), 100));
}
#[test]
fn coalesces_and_resynchronizes_after_journal_overflow() {
let mut s = Store::new(4, 2, 100, 42);
for seq in 1..=4 {
s.apply(sample("a", seq), seq);
}
let frame = s.frame(Some(2), 4);
assert!(!frame.snapshot);
assert_eq!(frame.targets.len(), 1);
assert_eq!(frame.targets[0].observation.sequence, 4);
assert!(s.frame(Some(0), 4).snapshot);
s.expire(104);
let frame = s.frame(Some(4), 104);
assert_eq!(frame.removed, ["a"]);
assert_eq!(frame.epoch, 42);
}
#[test]
fn rejects_invalid_values_and_previous_source_session() {
let mut s = Store::new(2, 4, 100, 1);
let mut a = sample("a", 1);
a.longitude = f64::NAN;
assert!(!s.apply(a, 0));
let mut a = sample("a", 1);
a.source_epoch = 2;
assert!(s.apply(a, 1));
assert!(!s.apply(sample("a", 100), 2));
assert_eq!(s.frame(None, 2).targets[0].observation.source_epoch, 2);
}
}