rqbit/crates/librqbit/src/http_api.rs

66 lines
2.1 KiB
Rust
Raw Normal View History

2021-06-30 10:14:33 +01:00
use std::sync::Arc;
2021-06-30 10:31:30 +01:00
use std::io::Write;
use std::sync::atomic::Ordering;
2021-06-30 18:42:16 +01:00
use std::time::Instant;
2021-06-30 10:14:33 +01:00
use warp::Filter;
2021-06-30 23:26:22 +01:00
use crate::speed_estimator::SpeedEstimator;
2021-06-30 10:14:33 +01:00
use crate::torrent_state::TorrentState;
// This is just a stub for debugging, nothing useful here.
2021-06-30 23:26:22 +01:00
pub async fn make_and_run_http_api(
state: Arc<TorrentState>,
estimator: Arc<SpeedEstimator>,
) -> anyhow::Result<()> {
2021-06-30 10:31:30 +01:00
let dump_haves = warp::path("haves").map({
let state = state.clone();
move || format!("{:?}", state.locked.read().chunks.get_have_pieces())
});
let dump_stats = warp::path("stats").map({
let state = state.clone();
let start_time = Instant::now();
let initial_downloaded_and_checked =
state.stats.downloaded_and_checked.load(Ordering::Relaxed);
move || {
let mut buf = Vec::new();
2021-06-30 23:26:22 +01:00
writeln!(buf, "{:#?}", state.stats_snapshot()).unwrap();
2021-06-30 10:31:30 +01:00
writeln!(
buf,
"Average download time: {:?}",
2021-06-30 23:26:22 +01:00
state.stats.average_piece_download_time()
2021-06-30 10:31:30 +01:00
)
.unwrap();
// Poor mans download speed computation
let elapsed = start_time.elapsed();
let downloaded_bytes = state.stats.downloaded_and_checked.load(Ordering::Relaxed)
- initial_downloaded_and_checked;
let downloaded_mb = downloaded_bytes as f64 / 1024f64 / 1024f64;
writeln!(
buf,
2021-06-30 23:26:22 +01:00
"Total download speed over all time: {:.2}Mbps",
2021-06-30 10:31:30 +01:00
downloaded_mb / elapsed.as_secs_f64()
)
.unwrap();
2021-06-30 23:26:22 +01:00
writeln!(buf, "Download speed: {:.2}Mbps", estimator.download_mbps()).unwrap();
match estimator.time_remaining() {
Some(time) => {
writeln!(buf, "Time remaining: {:?}", time).unwrap();
}
None => {
writeln!(buf, "Time remaining: unknown").unwrap();
}
}
2021-06-30 10:31:30 +01:00
buf
}
});
let router = dump_haves.or(dump_stats);
warp::serve(router).run(([127, 0, 0, 1], 3030)).await;
2021-06-30 10:14:33 +01:00
Ok(())
}