use super::*;
impl TenantRecord {
pub fn active<I, P>(id: I, plan: P) -> Self
where
I: Into<String>,
P: Into<String>,
{
Self {
id: id.into(),
status: TenantStatus::Active,
plan: plan.into(),
}
}
pub fn suspended<I>(id: I) -> Self
where
I: Into<String>,
{
Self {
id: id.into(),
status: TenantStatus::Suspended,
plan: String::new(),
}
}
}
impl TenantContext {
#[inline]
pub fn from_context(ctx: &Context) -> Option<Self> {
ctx.try_get_attribute::<Self, _>(ATTR_TENANT_CONTEXT)
}
}
impl Default for TenantConfig {
fn default() -> Self {
Self {
header_name: DEFAULT_TENANT_HEADER.to_owned(),
base_domain: None,
path_prefix: None,
default_tenant: None,
require_known: false,
tenants: Vec::new(),
exempt_prefixes: Vec::new(),
}
}
}
impl TenantConfig {
pub fn with_base_domain<D>(mut self, base_domain: D) -> Self
where
D: Into<String>,
{
self.set_base_domain(Some(base_domain.into()));
self
}
pub fn with_path_prefix<P>(mut self, prefix: P) -> Self
where
P: Into<String>,
{
self.set_path_prefix(Some(prefix.into()));
self
}
pub fn with_require_known(mut self, require: bool) -> Self {
self.set_require_known(require);
self
}
pub fn with_tenant(mut self, record: TenantRecord) -> Self {
self.get_mut_tenants().push(record);
self
}
pub fn with_exempt_prefixes<I, S>(mut self, prefixes: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.set_exempt_prefixes(prefixes.into_iter().map(Into::into).collect());
self
}
}
impl TenantPlugin {
pub fn new(config: TenantConfig, resolver: Option<Arc<dyn TenantResolver>>) -> Self {
let header_lower: String = config.get_header_name().trim().to_ascii_lowercase();
let dot_base_domain: Option<String> =
config
.try_get_base_domain()
.as_ref()
.and_then(|d: &String| {
let clean: &str = d.trim().trim_start_matches('.');
if clean.is_empty() {
None
} else {
Some(format!(".{}", clean.to_ascii_lowercase()))
}
});
let normalized_path_prefix: Option<String> = config
.try_get_path_prefix()
.as_ref()
.map(|p: &String| normalize_prefix(p));
let exempt_prefixes: Box<[String]> = config
.get_exempt_prefixes()
.iter()
.filter(|p: &&String| !p.trim().is_empty())
.map(|p: &String| normalize_prefix(p))
.collect::<Vec<String>>()
.into_boxed_slice();
let mut registry: HashMapXxHash3_64<String, TenantRecord> = hash_map_xx_hash3_64();
for rec in config.get_tenants() {
registry.insert(rec.get_id().clone(), rec.clone());
}
let missing_wire: Vec<u8> =
build_error_wire(HttpStatus::BadRequest, DEFAULT_MISSING_TENANT_BODY);
let unknown_wire: Vec<u8> =
build_error_wire(HttpStatus::NotFound, DEFAULT_UNKNOWN_TENANT_BODY);
let suspended_wire: Vec<u8> =
build_error_wire(HttpStatus::Forbidden, DEFAULT_SUSPENDED_TENANT_BODY);
Self {
config,
header_lower,
dot_base_domain,
normalized_path_prefix,
exempt_prefixes,
registry,
resolver,
missing_wire,
unknown_wire,
suspended_wire,
}
}
pub fn init(config: TenantConfig) -> &'static Self {
TENANT_PLUGIN.get_or_init(|| Self::new(config, None))
}
pub fn init_with_resolver(
config: TenantConfig,
resolver: Arc<dyn TenantResolver>,
) -> &'static Self {
TENANT_PLUGIN.get_or_init(|| Self::new(config, Some(resolver)))
}
#[inline(always)]
pub fn get() -> Option<&'static Self> {
TENANT_PLUGIN.get()
}
#[inline]
pub fn resolve(&self, request: &Request) -> TenantResolution {
let Self {
config,
header_lower,
dot_base_domain,
normalized_path_prefix,
exempt_prefixes,
registry,
resolver,
..
} = self;
let path: &str = request.get_path();
if exempt_prefixes
.iter()
.any(|p: &String| path_matches_prefix(path, p))
{
return TenantResolution::Exempt;
}
let extracted: Option<(&str, TenantSource)> = if !header_lower.is_empty()
&& let Some(val) = request
.get_headers()
.get(header_lower.as_str())
.and_then(|vals: &VecDeque<String>| vals.back())
&& is_valid_tenant_id(val.trim())
{
Some((val.trim(), TenantSource::Header))
} else if let Some(dot_base) = dot_base_domain
&& let Some(host_val) = request
.get_headers()
.get(HOST)
.and_then(|vals: &VecDeque<String>| vals.back())
&& let Some(sub) = extract_subdomain(host_val, dot_base)
{
Some((sub, TenantSource::Subdomain))
} else if let Some(prefix) = normalized_path_prefix
&& let Some(seg) = extract_path_tenant(path, prefix)
{
Some((seg, TenantSource::PathPrefix))
} else if let Some(default_id) = config.try_get_default_tenant() {
Some((default_id.as_str(), TenantSource::Default))
} else {
None
};
let Some((tenant_id, source)) = extracted else {
return TenantResolution::Missing;
};
if let Some(rec) = registry.get(tenant_id) {
return match rec.get_status() {
TenantStatus::Active => TenantResolution::Resolved(TenantContext {
tenant_id: rec.get_id().clone(),
plan: rec.get_plan().clone(),
source,
}),
TenantStatus::Suspended => TenantResolution::Suspended,
};
}
if let Some(custom) = resolver
&& let Some(rec) = custom.resolve(tenant_id)
{
return match rec.get_status() {
TenantStatus::Active => TenantResolution::Resolved(TenantContext {
tenant_id: rec.get_id().clone(),
plan: rec.get_plan().clone(),
source,
}),
TenantStatus::Suspended => TenantResolution::Suspended,
};
}
if config.get_require_known() {
TenantResolution::Unknown
} else {
TenantResolution::Resolved(TenantContext {
tenant_id: tenant_id.to_owned(),
plan: String::new(),
source,
})
}
}
}
impl ServerHook for TenantHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
#[inline(always)]
async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = TenantPlugin::get() else {
return Status::Continue;
};
match plugin.resolve(ctx.get_request()) {
TenantResolution::Exempt => Status::Continue,
TenantResolution::Resolved(tenant_ctx) => {
ctx.set_attribute(ATTR_TENANT_CONTEXT, tenant_ctx);
Status::Continue
}
TenantResolution::Missing => {
let TenantPlugin { missing_wire, .. } = plugin;
let _: Result<(), ResponseError> = stream.try_send(missing_wire).await;
Status::Reject
}
TenantResolution::Unknown => {
let TenantPlugin { unknown_wire, .. } = plugin;
let _: Result<(), ResponseError> = stream.try_send(unknown_wire).await;
Status::Reject
}
TenantResolution::Suspended => {
let TenantPlugin { suspended_wire, .. } = plugin;
let _: Result<(), ResponseError> = stream.try_send(suspended_wire).await;
Status::Reject
}
}
}
}