From d65e36a4b6f2e28d25ed2996a94db17a7ae9abd9 Mon Sep 17 00:00:00 2001 From: "Carpenter, Adam (CORP)" Date: Mon, 29 Nov 2021 13:52:11 -0500 Subject: refactor: static global and once_cell depends --- angelsharkd/src/routes/extensions/mod.rs | 10 ++++- angelsharkd/src/routes/extensions/simple_search.rs | 43 +++++++++++----------- 2 files changed, 29 insertions(+), 24 deletions(-) (limited to 'angelsharkd/src/routes/extensions') diff --git a/angelsharkd/src/routes/extensions/mod.rs b/angelsharkd/src/routes/extensions/mod.rs index 5628588..b1c5aa3 100644 --- a/angelsharkd/src/routes/extensions/mod.rs +++ b/angelsharkd/src/routes/extensions/mod.rs @@ -1,3 +1,5 @@ +use std::sync::{Arc, Mutex}; + use crate::config::Config; use warp::{path, Filter, Rejection, Reply}; @@ -12,10 +14,14 @@ pub fn filter(config: &Config) -> impl Filter = Lazy::new(Haystack::new); - /// Collection of search terms type Needle = Vec; -pub fn search(config: &Config) -> impl Filter + Clone { - let runner = config.runner.clone(); - // TODO: anti-caching headers on resp? +pub fn search(haystack: Haystack) -> impl Filter + Clone { + // TODO: discourage caching response thru headers path("search") .and(post()) .and(content_length_limit(1024 * 16)) - .and(json::()) - .and(with_runner(runner)) - .and_then(handle_search) + .and(json()) + .and_then(move |terms: Needle| handle_search(haystack.clone(), terms)) } -pub fn refresh(config: &Config) -> impl Filter + Clone { - let runner = config.runner.clone(); +pub fn refresh( + runner: AcmRunner, + haystack: Haystack, +) -> impl Filter + Clone { path!("search" / "refresh") .and(get()) - .and(with_runner(runner)) - .and_then(handle_refresh) + .and_then(move || handle_refresh(haystack.clone(), runner.clone())) } -async fn handle_search(terms: Needle, runner: AcmRunner) -> Result { - HAYSTACK_CACHE.search(Vec::new()); - Ok("") +async fn handle_search(haystack: Haystack, needle: Needle) -> Result { + Ok(haystack.search(Vec::new())) } -async fn handle_refresh(runner: AcmRunner) -> Result { - HAYSTACK_CACHE.refresh(); +async fn handle_refresh(haystack: Haystack, runner: AcmRunner) -> Result { + haystack.refresh(); Ok("Refresh scheduled") } /// A lazy-loaded, asynchronously-refreshed exension-type haystack cache. -struct Haystack { +#[derive(Clone)] +pub struct Haystack { inner: Arc>, } impl Haystack { - fn new() -> Self { + pub fn new() -> Self { Self { inner: Arc::new(Mutex::new(String::with_capacity(0))), } } pub fn search(&self, needle: Needle) -> String { - (*self.inner.lock().unwrap()).clone() + if let Ok(matches) = self.inner.lock() { + matches.clone() + } else { + String::from("stale") + } } pub fn refresh(&self) { -- cgit v1.2.3