chore (backend-rs): use Arc for antenna cache

This commit is contained in:
naskya 2024-06-09 01:08:40 +09:00
parent 4a1ca48538
commit 9f16c00f0c
No known key found for this signature in database
GPG key ID: 712D413B3A9FED5C
3 changed files with 19 additions and 23 deletions

View file

@ -2,24 +2,23 @@
use crate::{database::db_conn, model::entity::antenna};
use sea_orm::prelude::*;
use std::sync::Mutex;
use std::sync::{Arc, Mutex};
static CACHE: Mutex<Option<Vec<antenna::Model>>> = Mutex::new(None);
static CACHE: Mutex<Option<Arc<[antenna::Model]>>> = Mutex::new(None);
fn set(antennas: &[antenna::Model]) {
let _ = CACHE
.lock()
.map(|mut cache| *cache = Some(antennas.to_owned()));
fn set(antennas: Arc<[antenna::Model]>) {
let _ = CACHE.lock().map(|mut cache| *cache = Some(antennas));
}
pub(super) async fn update() -> Result<Vec<antenna::Model>, DbErr> {
pub(super) async fn update() -> Result<Arc<[antenna::Model]>, DbErr> {
tracing::debug!("updating cache");
let antennas = antenna::Entity::find().all(db_conn().await?).await?;
set(&antennas);
let antennas: Arc<[antenna::Model]> =
antenna::Entity::find().all(db_conn().await?).await?.into();
set(antennas.clone());
Ok(antennas)
}
pub(super) async fn get() -> Result<Vec<antenna::Model>, DbErr> {
pub(super) async fn get() -> Result<Arc<[antenna::Model]>, DbErr> {
if let Some(cache) = CACHE.lock().ok().and_then(|cache| cache.clone()) {
return Ok(cache);
}

View file

@ -12,8 +12,6 @@ pub enum AntennaCheckError {
Db(#[from] DbErr),
#[error("Cache error: {0}")]
Cache(#[from] cache::Error),
#[error("User profile not found: {0}")]
UserProfileNotFound(String),
}
fn match_all(space_separated_words: &str, text: &str, case_sensitive: bool) -> bool {
@ -29,7 +27,7 @@ fn match_all(space_separated_words: &str, text: &str, case_sensitive: bool) -> b
}
}
pub async fn check_hit_antenna(
pub(super) async fn check_hit_antenna(
antenna: &antenna::Model,
note: &note::Model,
note_all_texts: &[String],

View file

@ -37,19 +37,18 @@ type Note = note::Model;
#[crate::export]
pub async fn update_antennas_on_new_note(
note: Note,
note: &Note,
note_author: &Acct,
note_muted_users: &[String],
) -> Result<(), Error> {
let note_cloned = note.clone();
let note_all_texts = all_texts(
PartialNoteToElaborate {
file_ids: note.file_ids,
user_id: note.user_id,
text: note.text,
cw: note.cw,
renote_id: note.renote_id,
reply_id: note.reply_id,
file_ids: note.file_ids.to_owned(),
user_id: note.user_id.to_owned(),
text: note.text.to_owned(),
cw: note.cw.to_owned(),
renote_id: note.renote_id.to_owned(),
reply_id: note.reply_id.to_owned(),
},
false,
)
@ -60,8 +59,8 @@ pub async fn update_antennas_on_new_note(
if note_muted_users.contains(&antenna.user_id) {
continue;
}
if check_hit_antenna(antenna, &note_cloned, &note_all_texts, note_author).await? {
add_note_to_antenna(&antenna.id, &note_cloned).await?;
if check_hit_antenna(antenna, note, &note_all_texts, note_author).await? {
add_note_to_antenna(&antenna.id, note).await?;
}
}