From 461f838cc075ec8e700d5fb3ad766aa812cd46ac Mon Sep 17 00:00:00 2001 From: postscriptum Date: Mon, 23 Mar 2026 08:47:47 +0200 Subject: [PATCH] implement cache/clean api --- README.md | 5 +++-- src/list.rs | 5 +++++ src/list/cache.rs | 16 ++++++++++++++++ src/main.rs | 12 +++++++++++- 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 59c2583..79c3f96 100644 --- a/README.md +++ b/README.md @@ -26,8 +26,9 @@ RUST_LOG=trace cargo run -- --allow=http://localhost/allow.txt \ ``` * set `socks5://127.0.0.1:1080` proxy in your application * open http://127.0.0.1:8010 in browser for stats: - * `/api/allow/domain.com` - add rule to the current session (and `--cache` if defined) - * `/api/block/domain.com` - delete rule from the current session (and `--cache` if defined) + * `/api/allow/{domain.com}` - add rule to the current session (and `--cache` if defined) + * `/api/block/{domain.com}` - delete rule from the current session (and `--cache` if defined) + * `/api/cache/clean` - clean `--cache` file (returns deleted rules or `null` if not enabled) ### Allow list example diff --git a/src/list.rs b/src/list.rs index 0d52f1a..d614018 100644 --- a/src/list.rs +++ b/src/list.rs @@ -90,4 +90,9 @@ impl List { self.cache.block(rule).await?; Ok(self.index.write().await.remove(&Item::from_line(rule))) } + /// Privately clean `--cache` file collected, return deleted rules + /// * we can implement `self.index` update at this step @TODO + pub async fn cache_clean(&self) -> Result>> { + self.cache.clean().await + } } diff --git a/src/list/cache.rs b/src/list/cache.rs index 8a35c10..b0dc884 100644 --- a/src/list/cache.rs +++ b/src/list/cache.rs @@ -49,6 +49,22 @@ impl Cache { } Ok(()) } + /// Clean `--cache` file collected, return deleted rules + pub async fn clean(&self) -> Result>> { + match self.0 { + Some(ref p) => { + init_file(p).await?; + let mut rules = Vec::new(); + let lines = fs::read_to_string(p).await?; + for line in lines.lines() { + rules.push(line.into()); + } + fs::write(p, "").await?; + Ok(Some(rules)) + } + None => Ok(None), + } + } } /// Make sure that cache file is always exist (e.g. user may remove it when the daemon is running) diff --git a/src/main.rs b/src/main.rs index 82a5247..7428932 100644 --- a/src/main.rs +++ b/src/main.rs @@ -56,6 +56,16 @@ async fn api_block( })?)) } +#[rocket::get("/api/cache/clean")] +async fn api_cache_clean(list: &State>) -> Result>>, Status> { + let result = list.cache_clean().await; + info!("Clean cache file: {result:?}"); + Ok(Json(result.map_err(|e| { + error!("Could not handle cache clean request: `{e}`"); + Status::InternalServerError + })?)) +} + #[rocket::launch] async fn rocket() -> _ { env_logger::init(); @@ -91,7 +101,7 @@ async fn rocket() -> _ { .manage(Instant::now()) .mount( "/", - rocket::routes![index, api_totals, api_allow, api_block], + rocket::routes![index, api_totals, api_allow, api_block, api_cache_clean], ) }