1use super::*;
2
3impl TenantRecord {
5 pub fn active<I, P>(id: I, plan: P) -> Self
16 where
17 I: Into<String>,
18 P: Into<String>,
19 {
20 Self {
21 id: id.into(),
22 status: TenantStatus::Active,
23 plan: plan.into(),
24 }
25 }
26
27 pub fn suspended<I>(id: I) -> Self
37 where
38 I: Into<String>,
39 {
40 Self {
41 id: id.into(),
42 status: TenantStatus::Suspended,
43 plan: String::new(),
44 }
45 }
46}
47
48impl TenantContext {
50 #[inline]
60 pub fn from_context(ctx: &Context) -> Option<Self> {
61 ctx.try_get_attribute::<Self, _>(ATTR_TENANT_CONTEXT)
62 }
63}
64
65impl Default for TenantConfig {
67 fn default() -> Self {
73 Self {
74 header_name: DEFAULT_TENANT_HEADER.to_owned(),
75 base_domain: None,
76 path_prefix: None,
77 default_tenant: None,
78 require_known: false,
79 tenants: Vec::new(),
80 exempt_prefixes: Vec::new(),
81 }
82 }
83}
84
85impl TenantConfig {
87 pub fn with_base_domain<D>(mut self, base_domain: D) -> Self
97 where
98 D: Into<String>,
99 {
100 self.set_base_domain(Some(base_domain.into()));
101 self
102 }
103
104 pub fn with_path_prefix<P>(mut self, prefix: P) -> Self
114 where
115 P: Into<String>,
116 {
117 self.set_path_prefix(Some(prefix.into()));
118 self
119 }
120
121 pub fn with_require_known(mut self, require: bool) -> Self {
131 self.set_require_known(require);
132 self
133 }
134
135 pub fn with_tenant(mut self, record: TenantRecord) -> Self {
145 self.get_mut_tenants().push(record);
146 self
147 }
148
149 pub fn with_exempt_prefixes<I, S>(mut self, prefixes: I) -> Self
159 where
160 I: IntoIterator<Item = S>,
161 S: Into<String>,
162 {
163 self.set_exempt_prefixes(prefixes.into_iter().map(Into::into).collect());
164 self
165 }
166}
167
168impl TenantPlugin {
170 pub fn new(config: TenantConfig, resolver: Option<Arc<dyn TenantResolver>>) -> Self {
181 let header_lower: String = config.get_header_name().trim().to_ascii_lowercase();
182 let dot_base_domain: Option<String> =
183 config
184 .try_get_base_domain()
185 .as_ref()
186 .and_then(|d: &String| {
187 let clean: &str = d.trim().trim_start_matches('.');
188 if clean.is_empty() {
189 None
190 } else {
191 Some(format!(".{}", clean.to_ascii_lowercase()))
192 }
193 });
194 let normalized_path_prefix: Option<String> = config
195 .try_get_path_prefix()
196 .as_ref()
197 .map(|p: &String| normalize_prefix(p));
198 let exempt_prefixes: Box<[String]> = config
199 .get_exempt_prefixes()
200 .iter()
201 .filter(|p: &&String| !p.trim().is_empty())
202 .map(|p: &String| normalize_prefix(p))
203 .collect::<Vec<String>>()
204 .into_boxed_slice();
205 let mut registry: HashMapXxHash3_64<String, TenantRecord> = hash_map_xx_hash3_64();
206 for rec in config.get_tenants() {
207 registry.insert(rec.get_id().clone(), rec.clone());
208 }
209 let missing_wire: Vec<u8> =
210 build_error_wire(HttpStatus::BadRequest, DEFAULT_MISSING_TENANT_BODY);
211 let unknown_wire: Vec<u8> =
212 build_error_wire(HttpStatus::NotFound, DEFAULT_UNKNOWN_TENANT_BODY);
213 let suspended_wire: Vec<u8> =
214 build_error_wire(HttpStatus::Forbidden, DEFAULT_SUSPENDED_TENANT_BODY);
215 Self {
216 config,
217 header_lower,
218 dot_base_domain,
219 normalized_path_prefix,
220 exempt_prefixes,
221 registry,
222 resolver,
223 missing_wire,
224 unknown_wire,
225 suspended_wire,
226 }
227 }
228
229 pub fn init(config: TenantConfig) -> &'static Self {
239 TENANT_PLUGIN.get_or_init(|| Self::new(config, None))
240 }
241
242 pub fn init_with_resolver(
253 config: TenantConfig,
254 resolver: Arc<dyn TenantResolver>,
255 ) -> &'static Self {
256 TENANT_PLUGIN.get_or_init(|| Self::new(config, Some(resolver)))
257 }
258
259 #[inline(always)]
265 pub fn get() -> Option<&'static Self> {
266 TENANT_PLUGIN.get()
267 }
268
269 #[inline]
279 pub fn resolve(&self, request: &Request) -> TenantResolution {
280 let Self {
281 config,
282 header_lower,
283 dot_base_domain,
284 normalized_path_prefix,
285 exempt_prefixes,
286 registry,
287 resolver,
288 ..
289 } = self;
290 let path: &str = request.get_path();
291 if exempt_prefixes
292 .iter()
293 .any(|p: &String| path_matches_prefix(path, p))
294 {
295 return TenantResolution::Exempt;
296 }
297 let extracted: Option<(&str, TenantSource)> = if !header_lower.is_empty()
298 && let Some(val) = request
299 .get_headers()
300 .get(header_lower.as_str())
301 .and_then(|vals: &VecDeque<String>| vals.back())
302 && is_valid_tenant_id(val.trim())
303 {
304 Some((val.trim(), TenantSource::Header))
305 } else if let Some(dot_base) = dot_base_domain
306 && let Some(host_val) = request
307 .get_headers()
308 .get(HOST)
309 .and_then(|vals: &VecDeque<String>| vals.back())
310 && let Some(sub) = extract_subdomain(host_val, dot_base)
311 {
312 Some((sub, TenantSource::Subdomain))
313 } else if let Some(prefix) = normalized_path_prefix
314 && let Some(seg) = extract_path_tenant(path, prefix)
315 {
316 Some((seg, TenantSource::PathPrefix))
317 } else if let Some(default_id) = config.try_get_default_tenant() {
318 Some((default_id.as_str(), TenantSource::Default))
319 } else {
320 None
321 };
322 let Some((tenant_id, source)) = extracted else {
323 return TenantResolution::Missing;
324 };
325 if let Some(rec) = registry.get(tenant_id) {
326 return match rec.get_status() {
327 TenantStatus::Active => TenantResolution::Resolved(TenantContext {
328 tenant_id: rec.get_id().clone(),
329 plan: rec.get_plan().clone(),
330 source,
331 }),
332 TenantStatus::Suspended => TenantResolution::Suspended,
333 };
334 }
335 if let Some(custom) = resolver
336 && let Some(rec) = custom.resolve(tenant_id)
337 {
338 return match rec.get_status() {
339 TenantStatus::Active => TenantResolution::Resolved(TenantContext {
340 tenant_id: rec.get_id().clone(),
341 plan: rec.get_plan().clone(),
342 source,
343 }),
344 TenantStatus::Suspended => TenantResolution::Suspended,
345 };
346 }
347 if config.get_require_known() {
348 TenantResolution::Unknown
349 } else {
350 TenantResolution::Resolved(TenantContext {
351 tenant_id: tenant_id.to_owned(),
352 plan: String::new(),
353 source,
354 })
355 }
356 }
357}
358
359impl ServerHook for TenantHook {
361 #[inline(always)]
372 async fn new(_: &mut Stream, _: &mut Context) -> Self {
373 Self
374 }
375
376 #[inline(always)]
388 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
389 let Some(plugin) = TenantPlugin::get() else {
390 return Status::Continue;
391 };
392 match plugin.resolve(ctx.get_request()) {
393 TenantResolution::Exempt => Status::Continue,
394 TenantResolution::Resolved(tenant_ctx) => {
395 ctx.set_attribute(ATTR_TENANT_CONTEXT, tenant_ctx);
396 Status::Continue
397 }
398 TenantResolution::Missing => {
399 let TenantPlugin { missing_wire, .. } = plugin;
400 let _: Result<(), ResponseError> = stream.try_send(missing_wire).await;
401 Status::Reject
402 }
403 TenantResolution::Unknown => {
404 let TenantPlugin { unknown_wire, .. } = plugin;
405 let _: Result<(), ResponseError> = stream.try_send(unknown_wire).await;
406 Status::Reject
407 }
408 TenantResolution::Suspended => {
409 let TenantPlugin { suspended_wire, .. } = plugin;
410 let _: Result<(), ResponseError> = stream.try_send(suspended_wire).await;
411 Status::Reject
412 }
413 }
414 }
415}