From 64d31d0c0226141db72b5907ee21792dd3e92dfa Mon Sep 17 00:00:00 2001 From: Fuwn Date: Thu, 24 Mar 2022 00:06:59 +0000 Subject: feat: cache github api This commit allows The Senpy Club API to cache GitHub's API response, refreshing the cache every fifty accesses. This commit also gets rid of a few dependencies which were replaced by their standard library counterparts. --- src/utils.rs | 58 +++++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 37 insertions(+), 21 deletions(-) (limited to 'src/utils.rs') diff --git a/src/utils.rs b/src/utils.rs index 8bb70da..333a1c0 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -16,39 +16,55 @@ // Copyright (C) 2022-2022 Fuwn // SPDX-License-Identifier: GPL-3.0-only +use std::{lazy::SyncLazy, sync::Mutex}; + use worker::Cors; use crate::{constants, structures::GitHubAPIResponse}; +static CACHE_UNSET: SyncLazy> = SyncLazy::new(|| Mutex::new(true)); +static CACHE_ACCESS_COUNT: SyncLazy> = + SyncLazy::new(|| Mutex::new(0)); +static GITHUB_API_CACHE: SyncLazy> = + SyncLazy::new(|| Mutex::new(GitHubAPIResponse::default())); + /// # Errors /// if GitHub API is unresponsive pub async fn github_api( ) -> Result> { - let mut client = reqwest::Client::new() - .get(constants::GITHUB_API_ENDPOINT) - .header( - "User-Agent", - format!("senpy-club/api-worker - {}", env!("VERGEN_GIT_SHA")), - ); - - if std::env::var("GITHUB_TOKEN").is_ok() { - client = client.header( - "Authorization", - format!( - "token {}", - std::env::var("GITHUB_TOKEN").unwrap_or_else(|_| "Null".to_string()) - ), - ); - } + if *CACHE_UNSET.lock().unwrap() + || *CACHE_ACCESS_COUNT.lock().unwrap() % 50 == 0 + { + *CACHE_UNSET.lock().unwrap() = false; - Ok( - client + let mut client = reqwest::Client::new() + .get(&*constants::GITHUB_API_ENDPOINT) + .header( + "User-Agent", + format!("senpy-club/api-worker - {}", env!("VERGEN_GIT_SHA")), + ); + + if std::env::var("GITHUB_TOKEN").is_ok() { + client = client.header( + "Authorization", + format!( + "token {}", + std::env::var("GITHUB_TOKEN").unwrap_or_else(|_| "Null".to_string()) + ), + ); + } + + *GITHUB_API_CACHE.lock().unwrap() = client .send() .await? .json::() .await - .unwrap_or_default(), - ) + .unwrap_or_default(); + } + + *CACHE_ACCESS_COUNT.lock().unwrap() += 1; + + Ok((*GITHUB_API_CACHE.lock().unwrap()).clone()) } /// # Panics @@ -79,7 +95,7 @@ pub async fn filter_images_by_language(language: &str) -> Vec { { images.push(format!( "{}{}", - constants::GITHUB_USER_CONTENT, + *constants::GITHUB_USER_CONTENT, // Pound symbols to URL (percent) encoding of pound symbol because we // are pushing a URL, not a string item.path.replace('#', "%23") -- cgit v1.2.3