more multi-tenancy
This commit is contained in:
+2
-34
@@ -1,8 +1,3 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, RwLock},
|
||||
};
|
||||
|
||||
use axum::{async_trait, extract::FromRequestParts, http::request::Parts};
|
||||
use diesel::{pg::PgConnection, prelude::*, sql_types::Text};
|
||||
use uuid::Uuid;
|
||||
@@ -33,42 +28,26 @@ impl TenantRepository {
|
||||
#[derive(Clone)]
|
||||
pub struct TenantService {
|
||||
pool: PgPool,
|
||||
cache_by_id: Arc<RwLock<HashMap<Uuid, Tenant>>>,
|
||||
cache_by_slug: Arc<RwLock<HashMap<String, Tenant>>>,
|
||||
}
|
||||
|
||||
impl TenantService {
|
||||
pub fn new(pool: PgPool) -> Self {
|
||||
Self {
|
||||
pool,
|
||||
cache_by_id: Arc::new(RwLock::new(HashMap::new())),
|
||||
cache_by_slug: Arc::new(RwLock::new(HashMap::new())),
|
||||
}
|
||||
Self { pool }
|
||||
}
|
||||
|
||||
pub fn get_by_id(&self, tenant_id: Uuid) -> AppResult<Tenant> {
|
||||
if let Some(tenant) = self.cache_by_id.read().unwrap().get(&tenant_id) {
|
||||
return Ok(tenant.clone());
|
||||
}
|
||||
|
||||
let tenant = self.load(|conn| TenantRepository::get_by_id(conn, tenant_id))?;
|
||||
self.store(&tenant);
|
||||
Ok(tenant)
|
||||
}
|
||||
|
||||
pub fn get_by_slug(&self, slug: &str) -> AppResult<Tenant> {
|
||||
if let Some(tenant) = self.cache_by_slug.read().unwrap().get(slug) {
|
||||
return Ok(tenant.clone());
|
||||
}
|
||||
|
||||
let slug_owned = slug.to_owned();
|
||||
let tenant = self.load(|conn| TenantRepository::get_by_slug(conn, &slug_owned))?;
|
||||
self.store(&tenant);
|
||||
Ok(tenant)
|
||||
}
|
||||
|
||||
pub fn tenant_id_for_slug(&self, slug: &str) -> AppResult<Uuid> {
|
||||
Ok(self.get_by_slug(slug)?.tenant_id)
|
||||
Ok(self.get_by_slug(slug)?.id)
|
||||
}
|
||||
|
||||
fn load<F>(&self, loader: F) -> AppResult<Tenant>
|
||||
@@ -82,17 +61,6 @@ impl TenantService {
|
||||
let tenant = loader(&mut conn)?;
|
||||
Ok(tenant)
|
||||
}
|
||||
|
||||
fn store(&self, tenant: &Tenant) {
|
||||
{
|
||||
let mut by_id = self.cache_by_id.write().unwrap();
|
||||
by_id.insert(tenant.tenant_id, tenant.clone());
|
||||
}
|
||||
{
|
||||
let mut by_slug = self.cache_by_slug.write().unwrap();
|
||||
by_slug.insert(tenant.slug.clone(), tenant.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_tenant_guc(conn: &mut PgConnection, tenant_id: Uuid) -> AppResult<()> {
|
||||
|
||||
Reference in New Issue
Block a user