use std::collections::BTreeMap;
use std::sync::Arc;
use adk_core::audit_log::{AuditActor, AuditTrail};
use adk_core::{AdkError, Result};
use adk_harness::website::{SitePartitions, SiteRef};
use adk_kernel::{CrossingAccess, CrossingResource, CrossingRoute, PartitionPolicy, Partitions};
use axum::body::Body;
use axum::http::{Request, StatusCode, header};
use axum::response::{IntoResponse, Response};
use serde_json::json;
use tower::ServiceExt;
use crate::audit;
pub const CROSS_SITE_TOOL: &str = "cross_site_request";
pub const REQUEST_REFUSED: &str = "awp.request.refused";
pub struct Agency {
table: Partitions,
sites: BTreeMap<String, (SiteRef, SitePartitions)>,
}
impl Agency {
pub fn new(table: Partitions) -> Self {
Self { table, sites: BTreeMap::new() }
}
pub async fn add(&mut self, site: SiteRef) -> Result<SitePartitions> {
if self.sites.contains_key(&site.name) || self.sites.values().any(|(s, _)| s.id == site.id)
{
return Err(AdkError::config(format!(
"the agency already runs a site named {} or with its id; every site needs its own (A-I22)",
site.name
)));
}
let partitions = SitePartitions::new(&site);
partitions
.install(&self.table, AuditActor::default())
.await
.map_err(|e| AdkError::config(e.to_string()))?;
self.sites.insert(site.name.clone(), (site, partitions.clone()));
Ok(partitions)
}
pub fn sites(&self) -> impl Iterator<Item = &SiteRef> {
self.sites.values().map(|(site, _)| site)
}
pub fn partitions(&self, name: &str) -> Option<&SitePartitions> {
self.sites.get(name).map(|(_, partitions)| partitions)
}
pub fn back_office_policy(&self, name: &str, coordinator: &str) -> Result<PartitionPolicy> {
let partitions = self
.partitions(name)
.ok_or_else(|| AdkError::config(format!("the agency runs no site named {name}")))?;
Ok(self
.table
.policy(partitions.back_office().id.clone())
.with_coordinator(coordinator)
.with_crossing_tool(
CROSS_SITE_TOOL,
CrossingRoute::argument(
CrossingResource::Memory,
CrossingAccess::Read,
"another site's memory",
),
))
}
pub fn table(&self) -> &Partitions {
&self.table
}
}
#[derive(Clone)]
pub struct AgencyRouter {
edges: Arc<BTreeMap<String, axum::Router>>,
audit: Option<AuditTrail>,
}
impl AgencyRouter {
pub fn new(edges: BTreeMap<String, axum::Router>) -> Self {
Self { edges: Arc::new(edges), audit: None }
}
#[must_use]
pub fn with_audit(mut self, trail: AuditTrail) -> Self {
self.audit = Some(trail);
self
}
pub fn router(self) -> axum::Router {
axum::Router::new().fallback(move |request: Request<Body>| {
let agency = self.clone();
async move { agency.dispatch(request).await }
})
}
async fn dispatch(&self, request: Request<Body>) -> Response {
let host = request
.headers()
.get(header::HOST)
.and_then(|value| value.to_str().ok())
.or_else(|| request.uri().host())
.map(|host| host.split(':').next().unwrap_or(host).to_ascii_lowercase())
.unwrap_or_default();
if let Some(edge) = self.edges.get(&host) {
return match edge.clone().oneshot(request).await {
Ok(response) => response,
Err(never) => match never {},
};
}
audit::record(
self.audit.as_ref(),
REQUEST_REFUSED,
AuditActor::default(),
json!({ "host": host, "path": request.uri().path(), "reason": "not_a_site_of_this_agency" }),
)
.await;
tracing::info!(host, path = request.uri().path(), "awp.request.refused");
(StatusCode::NOT_FOUND, axum::Json(json!({ "awp": "2.0", "error": { "code": "resource_not_found", "message": "no site is served at this host", "retryable": false } })))
.into_response()
}
}