multi tenancy part 1

This commit is contained in:
2025-10-22 22:52:59 +02:00
parent 8e3f09774a
commit e175d28c2c
35 changed files with 1288 additions and 314 deletions
+16 -3
View File
@@ -4,6 +4,7 @@ use diesel::{
pg::PgConnection,
r2d2::{ConnectionManager, PooledConnection},
};
use uuid::Uuid;
use crate::{
auth::jwt::JwtService,
@@ -11,9 +12,10 @@ use crate::{
db::PgPool,
error::{AppError, AppResult},
storage::ObjectStorage,
tenants::{apply_tenant_guc, TenantService},
};
type PgPooledConnection = PooledConnection<ConnectionManager<PgConnection>>;
pub type PgPooledConnection = PooledConnection<ConnectionManager<PgConnection>>;
#[derive(Clone)]
pub struct AppState {
@@ -21,6 +23,7 @@ pub struct AppState {
pub config: Arc<AppConfig>,
pub storage: Arc<dyn ObjectStorage>,
pub jwt: JwtService,
pub tenants: TenantService,
}
impl AppState {
@@ -30,15 +33,25 @@ impl AppState {
storage: Arc<dyn ObjectStorage>,
jwt: JwtService,
) -> Self {
let config = Arc::new(config);
let tenants = TenantService::new(pool.clone());
Self {
pool,
config: Arc::new(config),
config,
storage,
jwt,
tenants,
}
}
pub fn db(&self) -> AppResult<PgPooledConnection> {
pub fn db_for_tenant(&self, tenant_id: Uuid) -> AppResult<PgPooledConnection> {
let mut conn = self.db_unscoped()?;
apply_tenant_guc(&mut conn, tenant_id)?;
Ok(conn)
}
pub fn db_unscoped(&self) -> AppResult<PgPooledConnection> {
self.pool
.get()
.map_err(|err| AppError::internal(format!("database pool error: {err}")))