use crate::resource::tenant::{IsolationLevel, TenantContext};
use uuid::Uuid;
#[derive(Debug, Clone)]
pub struct RequestContext {
pub request_id: String,
pub tenant_context: Option<TenantContext>,
}
impl RequestContext {
pub fn new(request_id: String) -> Self {
Self {
request_id,
tenant_context: None,
}
}
pub fn with_generated_id() -> Self {
Self {
request_id: Uuid::new_v4().to_string(),
tenant_context: None,
}
}
pub fn with_tenant(request_id: String, tenant_context: TenantContext) -> Self {
Self {
request_id,
tenant_context: Some(tenant_context),
}
}
pub fn with_tenant_generated_id(tenant_context: TenantContext) -> Self {
Self {
request_id: Uuid::new_v4().to_string(),
tenant_context: Some(tenant_context),
}
}
pub fn tenant_id(&self) -> Option<&str> {
self.tenant_context.as_ref().map(|t| t.tenant_id.as_str())
}
pub fn client_id(&self) -> Option<&str> {
self.tenant_context.as_ref().map(|t| t.client_id.as_str())
}
pub fn is_multi_tenant(&self) -> bool {
self.tenant_context.is_some()
}
pub fn isolation_level(&self) -> Option<&IsolationLevel> {
self.tenant_context.as_ref().map(|t| &t.isolation_level)
}
pub fn can_perform_operation(&self, operation: &str) -> bool {
match &self.tenant_context {
Some(tenant) => tenant.can_perform_operation(operation),
None => true, }
}
pub fn validate_operation(&self, operation: &str) -> Result<(), String> {
if self.can_perform_operation(operation) {
Ok(())
} else {
Err(format!(
"Operation '{}' not permitted for tenant",
operation
))
}
}
}
impl Default for RequestContext {
fn default() -> Self {
Self::with_generated_id()
}
}
#[derive(Debug, Clone, Default)]
pub struct ListQuery {
pub count: Option<usize>,
pub start_index: Option<usize>,
pub filter: Option<String>,
pub attributes: Vec<String>,
pub excluded_attributes: Vec<String>,
}
impl ListQuery {
pub fn new() -> Self {
Self::default()
}
pub fn with_count(mut self, count: usize) -> Self {
self.count = Some(count);
self
}
pub fn with_start_index(mut self, start_index: usize) -> Self {
self.start_index = Some(start_index);
self
}
pub fn with_filter(mut self, filter: String) -> Self {
self.filter = Some(filter);
self
}
pub fn with_attribute(mut self, attribute: String) -> Self {
self.attributes.push(attribute);
self
}
pub fn with_attributes(mut self, attributes: Vec<String>) -> Self {
self.attributes.extend(attributes);
self
}
pub fn with_excluded_attribute(mut self, attribute: String) -> Self {
self.excluded_attributes.push(attribute);
self
}
pub fn with_excluded_attributes(mut self, attributes: Vec<String>) -> Self {
self.excluded_attributes.extend(attributes);
self
}
}