use std::sync::Arc;
use super::catalog::{CatalogError, Database, PgCatalog};
use crate::backend::s3::S3;
use crate::backend::{TenantSpace, Under};
use crate::clock::Clock;
use crate::envelope::{self, Key};
use crate::fs::Fs;
use crate::ids::TenantId;
use crate::store::{OpenError, Store, StoreError};
use crate::tenants::TenantError;
const REMOVE_BATCH: i64 = 10_000;
const RESEAL_BATCH: i64 = 1_000;
pub(crate) struct PgTenantSpace {
database: Arc<Database>,
s3: Arc<S3>,
fs: Arc<dyn Fs>,
}
impl PgTenantSpace {
pub(crate) fn new(database: Arc<Database>, s3: Arc<S3>, fs: Arc<dyn Fs>) -> PgTenantSpace {
PgTenantSpace { database, s3, fs }
}
}
fn open_error(e: CatalogError) -> OpenError {
match e {
CatalogError::WrongKey => OpenError::WrongKey,
_ => OpenError::Store(StoreError::Io),
}
}
fn tenant_io<E>(_: E) -> TenantError {
TenantError::Io
}
impl TenantSpace for PgTenantSpace {
fn make(&self, id: TenantId, key: Key, clock: Arc<dyn Clock>) -> Result<(), OpenError> {
let catalog_key = envelope::catalog_key(&key).map_err(|_| StoreError::Io)?;
match PgCatalog::create(self.database.clone(), id, &catalog_key) {
Ok(_) | Err(CatalogError::Exists) => {}
Err(e) => return Err(open_error(e)),
}
drop(self.open(id, key, true, clock)?);
Ok(())
}
fn open(
&self,
id: TenantId,
key: Key,
recover: bool,
clock: Arc<dyn Clock>,
) -> Result<Store, OpenError> {
let catalog_key = envelope::catalog_key(&key).map_err(|_| StoreError::Io)?;
let catalog =
PgCatalog::open(self.database.clone(), id, &catalog_key).map_err(open_error)?;
Store::open_on(
id,
key,
Box::new(catalog),
Arc::new(self.s3.tenant(id)),
Some(Arc::new(self.s3.packs(id))),
self.fs.clone(),
clock,
recover,
)
}
fn present(&self) -> Result<Vec<TenantId>, TenantError> {
let mut ids = PgCatalog::present(&self.database).map_err(tenant_io)?;
ids.extend(self.s3.tenants().map_err(tenant_io)?);
ids.sort_by_key(|id| id.0);
ids.dedup();
Ok(ids)
}
fn remove(&self, id: TenantId) -> Result<(), TenantError> {
PgCatalog::remove(&self.database, id, REMOVE_BATCH, || {
self.s3.remove_tenant(id).map_err(|_| CatalogError::Io)
})
.map_err(tenant_io)
}
fn catalog_under(&self, id: TenantId, old: &Key, new: &Key) -> Result<Under, TenantError> {
PgCatalog::under(&self.database, id, old, new).map_err(tenant_io)
}
fn reseal(&self, id: TenantId, old: &Key, new: &Key) -> Result<(), TenantError> {
PgCatalog::reseal(&self.database, id, old, new, RESEAL_BATCH).map_err(tenant_io)
}
}