From 1506802c20dfaf433538ff7bd22c938c8c41b3a5 Mon Sep 17 00:00:00 2001 From: Kitaiti Makoto Date: Wed, 24 Nov 2021 22:04:35 +0900 Subject: [PATCH] Implement LOCAL_INSTANCE_USER and related methods --- plume-models/src/instance.rs | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/plume-models/src/instance.rs b/plume-models/src/instance.rs index f3f05481..5f4905d7 100644 --- a/plume-models/src/instance.rs +++ b/plume-models/src/instance.rs @@ -8,6 +8,7 @@ use crate::{ }; use chrono::NaiveDateTime; use diesel::{self, result::Error::NotFound, ExpressionMethods, QueryDsl, RunQueryDsl}; +use once_cell::sync::OnceCell; use plume_common::utils::md_to_html; use std::sync::RwLock; @@ -46,6 +47,7 @@ lazy_static! { } const LOCAL_INSTANCE_USERNAME: &str = "__instance__"; +static LOCAL_INSTANCE_USER: OnceCell = OnceCell::new(); impl Instance { pub fn set_local(self) { @@ -78,16 +80,11 @@ impl Instance { .map_err(Error::from) } - pub fn page(conn: &Connection, (min, max): (i32, i32)) -> Result> { - instances::table - .order(instances::public_domain.asc()) - .offset(min.into()) - .limit((max - min).into()) - .load::(conn) - .map_err(Error::from) + pub fn get_local_instance_user() -> Option<&'static User> { + LOCAL_INSTANCE_USER.get() } - pub fn get_local_instance_user(conn: &Connection) -> Result { + pub fn get_local_instance_user_uncached(conn: &Connection) -> Result { users::table .filter(users::role.eq(3)) .first(conn) @@ -109,6 +106,23 @@ impl Instance { }) } + pub fn cache_local_instance_user(conn: &Connection) { + let user = Self::get_local_instance_user_uncached(conn) + .expect("Failed to get local instance user"); + LOCAL_INSTANCE_USER + .set(user) + .expect("Failed to set local instance user"); + } + + pub fn page(conn: &Connection, (min, max): (i32, i32)) -> Result> { + instances::table + .order(instances::public_domain.asc()) + .offset(min.into()) + .limit((max - min).into()) + .load::(conn) + .map_err(Error::from) + } + insert!(instances, NewInstance); get!(instances); find_by!(instances, find_by_domain, public_domain as &str);