use std::time::{Duration, Instant};
use serde_json::Value;
use tokio::sync::mpsc;
use crate::proto::JsonRpcNotification;
use crate::proto::writer::Outgoing;
const MIN_INTERVAL: Duration = Duration::from_millis(250);
const MIN_FRACTION: f64 = 0.01;
#[derive(Debug)]
pub struct Emitter {
token: Value,
out: mpsc::Sender<Outgoing>,
total: Option<u64>,
last_at: Instant,
last_value: u64,
started: bool,
}
impl Emitter {
#[must_use]
pub fn new(token: Option<Value>, out: mpsc::Sender<Outgoing>) -> Option<Self> {
token.map(|token| Self {
token,
out,
total: None,
last_at: Instant::now() - MIN_INTERVAL,
last_value: 0,
started: false,
})
}
pub fn set_total(&mut self, total: Option<u64>) {
self.total = total;
}
pub fn report(&mut self, current: u64, message: &str) {
if self.started && current <= self.last_value {
return;
}
let now = Instant::now();
if self.started && now.duration_since(self.last_at) < MIN_INTERVAL {
return;
}
if self.started
&& let Some(total) = self.total
&& total > 0
{
let moved = (current - self.last_value) as f64 / total as f64;
if moved < MIN_FRACTION && current < total {
return;
}
}
self.last_at = now;
self.last_value = current;
self.started = true;
let mut params = serde_json::Map::new();
params.insert("progressToken".to_string(), self.token.clone());
params.insert("progress".to_string(), Value::Number(current.into()));
if let Some(total) = self.total {
params.insert("total".to_string(), Value::Number(total.into()));
}
params.insert("message".to_string(), Value::String(message.to_string()));
let _ = self
.out
.try_send(Outgoing::notification(JsonRpcNotification::new(
"notifications/progress",
Value::Object(params),
)));
}
pub fn finish(&mut self, current: u64, message: &str) {
self.last_at = Instant::now() - MIN_INTERVAL;
if current > self.last_value || !self.started {
self.last_value = current.saturating_sub(1);
self.report(current, message);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn drain(rx: &mut mpsc::Receiver<Outgoing>) -> Vec<Value> {
let mut out = Vec::new();
while let Ok(message) = rx.try_recv() {
if let Outgoing::Notification(notification) = message {
out.push(notification.params.clone().unwrap());
}
}
out
}
#[tokio::test]
async fn no_token_means_no_emitter() {
let (tx, _rx) = mpsc::channel(8);
assert!(Emitter::new(None, tx).is_none());
}
#[tokio::test]
async fn first_report_is_always_emitted() {
let (tx, mut rx) = mpsc::channel(8);
let mut emitter = Emitter::new(Some(serde_json::json!("t")), tx).unwrap();
emitter.report(10, "starting");
let sent = drain(&mut rx);
assert_eq!(sent.len(), 1);
assert_eq!(sent[0]["progressToken"], "t");
assert_eq!(sent[0]["progress"], 10);
assert!(sent[0].get("total").is_none());
}
#[tokio::test]
async fn rate_limit_suppresses_a_rapid_second_report() {
let (tx, mut rx) = mpsc::channel(8);
let mut emitter = Emitter::new(Some(serde_json::json!(1)), tx).unwrap();
emitter.report(10, "a");
emitter.report(20, "b");
assert_eq!(drain(&mut rx).len(), 1);
}
#[tokio::test]
async fn non_increasing_progress_is_dropped() {
let (tx, mut rx) = mpsc::channel(8);
let mut emitter = Emitter::new(Some(serde_json::json!(1)), tx).unwrap();
emitter.report(100, "a");
drain(&mut rx);
emitter.last_at = Instant::now() - Duration::from_secs(1);
emitter.report(100, "same");
emitter.report(50, "backwards");
assert!(drain(&mut rx).is_empty());
}
#[tokio::test]
async fn progress_is_monotonic_across_a_transfer() {
let (tx, mut rx) = mpsc::channel(64);
let mut emitter = Emitter::new(Some(serde_json::json!(1)), tx).unwrap();
emitter.set_total(Some(1000));
for step in 1..=10u64 {
emitter.last_at = Instant::now() - Duration::from_secs(1);
emitter.report(step * 100, "chunk");
}
emitter.finish(1000, "done");
let values: Vec<u64> = drain(&mut rx)
.iter()
.map(|params| params["progress"].as_u64().unwrap())
.collect();
assert!(values.len() >= 2);
assert!(
values.windows(2).all(|pair| pair[1] > pair[0]),
"progress must strictly increase: {values:?}"
);
assert_eq!(*values.last().unwrap(), 1000);
}
#[tokio::test]
async fn total_is_included_when_known() {
let (tx, mut rx) = mpsc::channel(8);
let mut emitter = Emitter::new(Some(serde_json::json!(1)), tx).unwrap();
emitter.set_total(Some(2048));
emitter.report(1024, "half");
let sent = drain(&mut rx);
assert_eq!(sent[0]["total"], 2048);
}
}