chore (backend-rs): set cache ttl

This commit is contained in:
naskya 2024-08-01 16:49:06 +09:00
parent b4b993a661
commit 47018b4cff
No known key found for this signature in database
GPG key ID: 712D413B3A9FED5C
8 changed files with 26 additions and 40 deletions

View file

@ -1455,8 +1455,6 @@ export declare function updateAntennasOnNewNote(note: Note, noteAuthor: Acct, no
export declare function updateMetaCache(): Promise<void>
export declare function updateNodeinfoCache(): Promise<void>
/** Usage statistics for this server. */
export interface Usage {
users: Users

View file

@ -457,7 +457,6 @@ module.exports.unwatchNote = nativeBinding.unwatchNote
module.exports.updateAntennaCache = nativeBinding.updateAntennaCache
module.exports.updateAntennasOnNewNote = nativeBinding.updateAntennasOnNewNote
module.exports.updateMetaCache = nativeBinding.updateMetaCache
module.exports.updateNodeinfoCache = nativeBinding.updateNodeinfoCache
module.exports.UserEmojiModPerm = nativeBinding.UserEmojiModPerm
module.exports.UserEvent = nativeBinding.UserEvent
module.exports.UserProfileFfvisibility = nativeBinding.UserProfileFfvisibility

View file

@ -14,13 +14,23 @@ struct TimedData<T: Clone> {
}
impl<T: Clone> Cache<T> {
pub const fn new(ttl: Option<Duration>) -> Self {
pub const fn new() -> Self {
Self {
cache: Mutex::new(TimedData {
value: None,
last_updated: DateTime::UNIX_EPOCH,
}),
ttl,
ttl: None,
}
}
pub const fn new_with_ttl(ttl: Duration) -> Self {
Self {
cache: Mutex::new(TimedData {
value: None,
last_updated: DateTime::UNIX_EPOCH,
}),
ttl: Some(ttl),
}
}

View file

@ -1,26 +1,27 @@
//! Server information
use crate::{cache::Cache, database::db_conn, model::entity::meta};
use chrono::Duration;
use sea_orm::{prelude::*, ActiveValue};
type Meta = meta::Model;
static INSTANCE_META_CACHE: Cache<Meta> = Cache::new(None);
static INSTANCE_META_CACHE: Cache<Meta> = Cache::new_with_ttl(Duration::minutes(5));
#[macros::export(js_name = "fetchMeta")]
pub async fn local_server_info() -> Result<Meta, DbErr> {
local_server_info_impl(true).await
local_server_info_impl(false).await
}
#[macros::export(js_name = "updateMetaCache")]
pub async fn update() -> Result<(), DbErr> {
local_server_info_impl(false).await?;
local_server_info_impl(true).await?;
Ok(())
}
async fn local_server_info_impl(use_cache: bool) -> Result<Meta, DbErr> {
async fn local_server_info_impl(force_update_cache: bool) -> Result<Meta, DbErr> {
// try using cache
if use_cache {
if !force_update_cache {
if let Some(cache) = INSTANCE_META_CACHE.get() {
return Ok(cache);
}

View file

@ -8,11 +8,12 @@ use crate::{
misc,
model::entity::{note, user},
};
use chrono::Duration;
use sea_orm::prelude::*;
use serde_json::json;
use std::collections::HashMap;
static NODEINFO_CACHE: Cache<Nodeinfo21> = Cache::new(None);
static NODEINFO_CACHE: Cache<Nodeinfo21> = Cache::new_with_ttl(Duration::hours(1));
/// Fetches the number of total/active local users and local posts.
///
@ -122,11 +123,10 @@ async fn generate_nodeinfo_2_1() -> Result<Nodeinfo21, DbErr> {
})
}
async fn nodeinfo_2_1_impl(use_cache: bool) -> Result<Nodeinfo21, DbErr> {
if use_cache {
if let Some(nodeinfo) = NODEINFO_CACHE.get() {
return Ok(nodeinfo);
}
/// Returns NodeInfo (version 2.1) of the local server.
pub async fn nodeinfo_2_1() -> Result<Nodeinfo21, DbErr> {
if let Some(nodeinfo) = NODEINFO_CACHE.get() {
return Ok(nodeinfo);
}
let nodeinfo = generate_nodeinfo_2_1().await?;
@ -137,11 +137,6 @@ async fn nodeinfo_2_1_impl(use_cache: bool) -> Result<Nodeinfo21, DbErr> {
Ok(nodeinfo)
}
/// Returns NodeInfo (version 2.1) of the local server.
pub async fn nodeinfo_2_1() -> Result<Nodeinfo21, DbErr> {
nodeinfo_2_1_impl(true).await
}
/// Returns NodeInfo (version 2.0) of the local server.
pub async fn nodeinfo_2_0() -> Result<Nodeinfo20, DbErr> {
Ok(nodeinfo_2_1().await?.into())
@ -166,9 +161,3 @@ pub async fn nodeinfo_2_1_as_json() -> Result<serde_json::Value, Error> {
pub async fn nodeinfo_2_0_as_json() -> Result<serde_json::Value, Error> {
Ok(serde_json::to_value(nodeinfo_2_0().await?)?)
}
#[macros::ts_export(js_name = "updateNodeinfoCache")]
pub async fn update_cache() -> Result<(), DbErr> {
nodeinfo_2_1_impl(false).await?;
Ok(())
}

View file

@ -1,10 +1,6 @@
//! Determine whether to enable the cat language conversion
use crate::{
cache,
database::db_conn,
model::entity::user,
};
use crate::{cache, database::db_conn, model::entity::user};
use sea_orm::{DbErr, EntityTrait, QuerySelect, SelectColumns};
#[macros::errors]

View file

@ -6,7 +6,7 @@ use crate::{cache::Cache, database::db_conn, model::entity::antenna};
use sea_orm::prelude::*;
use std::sync::Arc;
static ANTENNAS_CACHE: Cache<Arc<[antenna::Model]>> = Cache::new(None);
static ANTENNAS_CACHE: Cache<Arc<[antenna::Model]>> = Cache::new();
async fn update() -> Result<Arc<[antenna::Model]>, DbErr> {
tracing::debug!("updating cache");

View file

@ -7,8 +7,6 @@ import {
greet,
removeOldAttestationChallenges,
showServerInfo,
updateMetaCache,
updateNodeinfoCache,
type Config,
} from "backend-rs";
import { config } from "@/config.js";
@ -29,7 +27,6 @@ export async function masterMain() {
showEnvironment();
showNodejsVersion();
await connectDb();
await updateMetaCache();
} catch (e) {
bootLogger.error(
`Fatal error occurred during initialization:\n${inspect(e)}`,
@ -51,10 +48,6 @@ export async function masterMain() {
import("../daemons/server-stats.js").then((x) => x.default());
import("../daemons/queue-stats.js").then((x) => x.default());
// Update meta cache every 5 minitues
setInterval(() => updateMetaCache(), 1000 * 60 * 5);
// Update nodeinfo cache every hour
setInterval(() => updateNodeinfoCache(), 1000 * 60 * 60);
// Remove old attestation challenges
setInterval(() => removeOldAttestationChallenges(), 1000 * 60 * 30);
}