adk_website/deploy/
agency.rs1use std::collections::BTreeMap;
9use std::sync::Arc;
10
11use adk_core::audit_log::{AuditActor, AuditTrail};
12use adk_core::{AdkError, Result};
13use adk_harness::website::{SitePartitions, SiteRef};
14use adk_kernel::{CrossingAccess, CrossingResource, CrossingRoute, PartitionPolicy, Partitions};
15use axum::body::Body;
16use axum::http::{Request, StatusCode, header};
17use axum::response::{IntoResponse, Response};
18use serde_json::json;
19use tower::ServiceExt;
20
21use crate::audit;
22
23pub const CROSS_SITE_TOOL: &str = "cross_site_request";
26
27pub const REQUEST_REFUSED: &str = "awp.request.refused";
29
30pub struct Agency {
48 table: Partitions,
49 sites: BTreeMap<String, (SiteRef, SitePartitions)>,
50}
51
52impl Agency {
53 pub fn new(table: Partitions) -> Self {
55 Self { table, sites: BTreeMap::new() }
56 }
57
58 pub async fn add(&mut self, site: SiteRef) -> Result<SitePartitions> {
64 if self.sites.contains_key(&site.name) || self.sites.values().any(|(s, _)| s.id == site.id)
65 {
66 return Err(AdkError::config(format!(
67 "the agency already runs a site named {} or with its id; every site needs its own (A-I22)",
68 site.name
69 )));
70 }
71 let partitions = SitePartitions::new(&site);
72 partitions
73 .install(&self.table, AuditActor::default())
74 .await
75 .map_err(|e| AdkError::config(e.to_string()))?;
76 self.sites.insert(site.name.clone(), (site, partitions.clone()));
77 Ok(partitions)
78 }
79
80 pub fn sites(&self) -> impl Iterator<Item = &SiteRef> {
82 self.sites.values().map(|(site, _)| site)
83 }
84
85 pub fn partitions(&self, name: &str) -> Option<&SitePartitions> {
87 self.sites.get(name).map(|(_, partitions)| partitions)
88 }
89
90 pub fn back_office_policy(&self, name: &str, coordinator: &str) -> Result<PartitionPolicy> {
99 let partitions = self
100 .partitions(name)
101 .ok_or_else(|| AdkError::config(format!("the agency runs no site named {name}")))?;
102 Ok(self
103 .table
104 .policy(partitions.back_office().id.clone())
105 .with_coordinator(coordinator)
106 .with_crossing_tool(
107 CROSS_SITE_TOOL,
108 CrossingRoute::argument(
109 CrossingResource::Memory,
110 CrossingAccess::Read,
111 "another site's memory",
112 ),
113 ))
114 }
115
116 pub fn table(&self) -> &Partitions {
118 &self.table
119 }
120}
121
122#[derive(Clone)]
125pub struct AgencyRouter {
126 edges: Arc<BTreeMap<String, axum::Router>>,
127 audit: Option<AuditTrail>,
128}
129
130impl AgencyRouter {
131 pub fn new(edges: BTreeMap<String, axum::Router>) -> Self {
133 Self { edges: Arc::new(edges), audit: None }
134 }
135
136 #[must_use]
138 pub fn with_audit(mut self, trail: AuditTrail) -> Self {
139 self.audit = Some(trail);
140 self
141 }
142
143 pub fn router(self) -> axum::Router {
145 axum::Router::new().fallback(move |request: Request<Body>| {
146 let agency = self.clone();
147 async move { agency.dispatch(request).await }
148 })
149 }
150
151 async fn dispatch(&self, request: Request<Body>) -> Response {
152 let host = request
154 .headers()
155 .get(header::HOST)
156 .and_then(|value| value.to_str().ok())
157 .or_else(|| request.uri().host())
158 .map(|host| host.split(':').next().unwrap_or(host).to_ascii_lowercase())
159 .unwrap_or_default();
160 if let Some(edge) = self.edges.get(&host) {
161 return match edge.clone().oneshot(request).await {
162 Ok(response) => response,
163 Err(never) => match never {},
164 };
165 }
166 audit::record(
167 self.audit.as_ref(),
168 REQUEST_REFUSED,
169 AuditActor::default(),
170 json!({ "host": host, "path": request.uri().path(), "reason": "not_a_site_of_this_agency" }),
171 )
172 .await;
173 tracing::info!(host, path = request.uri().path(), "awp.request.refused");
174 (StatusCode::NOT_FOUND, axum::Json(json!({ "awp": "2.0", "error": { "code": "resource_not_found", "message": "no site is served at this host", "retryable": false } })))
175 .into_response()
176 }
177}