From 91198685b41265a08af814a461645a8f62693c0a Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Sat, 16 Apr 2022 23:29:25 +0200 Subject: feat(tazjin/tgsa): cache generated bbcode in-memory per message Change-Id: Id36266ef20585bfbdffb197ab08aba2978cb86cb Reviewed-on: https://cl.tvl.fyi/c/depot/+/5471 Reviewed-by: tazjin Autosubmit: tazjin Tested-by: BuildkiteCI --- users/tazjin/tgsa/src/main.rs | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/users/tazjin/tgsa/src/main.rs b/users/tazjin/tgsa/src/main.rs index d23430d7ee..93c76c3cfd 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 { + 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 { Ok(out) } -fn handle_tg_link(link: &TgLink) -> Result { +type Cache = RwLock>; + +fn handle_tg_link(cache: &Cache, link: &TgLink) -> Result { + 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 + )) + } } } } -- cgit 1.4.1