diff options
author | Vincent Ambo <mail@tazj.in> | 2022-04-16T21·29+0200 |
---|---|---|
committer | clbot <clbot@tvl.fyi> | 2022-04-16T21·31+0000 |
commit | 91198685b41265a08af814a461645a8f62693c0a (patch) | |
tree | 7cd78f059d97caada355f39b3c04a515614f4008 | |
parent | 78c966dc78e12bd00cac3987f4f221a760850010 (diff) |
feat(tazjin/tgsa): cache generated bbcode in-memory per message r/3967
Change-Id: Id36266ef20585bfbdffb197ab08aba2978cb86cb Reviewed-on: https://cl.tvl.fyi/c/depot/+/5471 Reviewed-by: tazjin <tazjin@tvl.su> Autosubmit: tazjin <tazjin@tvl.su> Tested-by: BuildkiteCI
-rw-r--r-- | users/tazjin/tgsa/src/main.rs | 35 |
1 files changed, 27 insertions, 8 deletions
diff --git a/users/tazjin/tgsa/src/main.rs b/users/tazjin/tgsa/src/main.rs index d23430d7ee2e..93c76c3cfd4f 100644 --- a/users/tazjin/tgsa/src/main.rs +++ b/users/tazjin/tgsa/src/main.rs @@ -1,6 +1,8 @@ use anyhow::{anyhow, Context, Result}; +use std::collections::HashMap; +use std::sync::RwLock; -#[derive(Debug)] +#[derive(Clone, Debug, Eq, Hash, PartialEq)] struct TgLink { username: String, message_id: usize, @@ -34,6 +36,7 @@ impl TgLink { } fn fetch_embed(link: &TgLink) -> Result<String> { + println!("fetching {}#{}", link.username, link.message_id); let response = crimp::Request::get(&link.to_url()) .send() .context("failed to fetch embed data")? @@ -159,15 +162,28 @@ fn to_bbcode(link: &TgLink, msg: &TgMessage) -> Result<String> { Ok(out) } -fn handle_tg_link(link: &TgLink) -> Result<String> { +type Cache = RwLock<HashMap<TgLink, String>>; + +fn handle_tg_link(cache: &Cache, link: &TgLink) -> Result<String> { + if let Some(bbcode) = cache.read().unwrap().get(&link) { + println!("serving {}#{} from cache", link.username, link.message_id); + return Ok(bbcode.to_string()); + } + let embed = fetch_embed(&link)?; let msg = parse_tgmessage(&embed)?; - to_bbcode(&link, &msg).context("failed to make bbcode") + let bbcode = to_bbcode(&link, &msg).context("failed to make bbcode")?; + + cache.write().unwrap().insert(link.clone(), bbcode.clone()); + + Ok(bbcode) } fn main() { crimp::init(); + let cache: Cache = RwLock::new(HashMap::new()); + rouille::start_server("0.0.0.0:8472", move |request| { match TgLink::parse(request.raw_url()) { None => rouille::Response::text( @@ -194,16 +210,19 @@ pm me on the forums if this makes you mad or something. "#, ), Some(link) => { - let result = handle_tg_link(&link); + let result = handle_tg_link(&cache, &link); match result { Ok(bbcode) => rouille::Response::text(bbcode), - Err(err) => rouille::Response::text(format!( - r#"something broke: {} + Err(err) => { + println!("something failed: {}", err); + rouille::Response::text(format!( + r#"something broke: {} nobody has been alerted about this and it has probably not been logged. pm me on the forums if you think it's important enough."#, - err - )), + err + )) + } } } } |