1use anyhow::{Context, Result};
2use axum::{
3 extract::{Path, State},
4 http::StatusCode,
5 http::HeaderMap,
6 response::{IntoResponse, Response},
7 routing::{get, post},
8 Router,
9};
10use std::net::SocketAddr;
11use std::sync::Arc;
12use tokio::net::TcpListener;
13use tracing::{error, info, warn};
14
15use crate::actor::{ActorError, ReceiptOutcome};
16use libkeri_http::{CESR_ATTACHMENT_HEADER, CESR_STREAM_CONTENT_TYPE};
17use crate::witness::Witness;
18
19#[derive(Clone)]
20pub struct WitnessState {
21 witness: Arc<Witness>,
22}
23
24pub struct WitnessServer {
25 witness: Arc<Witness>,
26}
27
28impl WitnessServer {
29 pub fn new(witness: Witness) -> Self {
30 Self {
31 witness: Arc::new(witness),
32 }
33 }
34
35 pub async fn run(self) -> Result<()> {
36 let mut tasks = vec![];
37
38 for curl in &self.witness.config.curls {
39 if !curl.starts_with("http://") {
40 warn!("Skipping {}: only HTTP transport is implemented", curl);
41 continue;
42 }
43 let witness_clone = Arc::clone(&self.witness);
44 let curl = curl.clone();
45
46 let task = tokio::spawn(async move {
47 if let Err(e) = Self::start_listener(&curl, witness_clone).await {
48 error!("Failed to start listener on {}: {}", curl, e);
49 }
50 });
51
52 tasks.push(task);
53 }
54
55 for task in tasks {
56 task.await?;
57 }
58
59 Ok(())
60 }
61
62 async fn start_listener(curl: &str, witness: Arc<Witness>) -> Result<()> {
63 let state = WitnessState { witness };
64
65 let app = Router::new()
67 .route("/", get(health_check).post(http_ingest).put(http_ingest))
68 .route("/receipts", post(post_receipt))
69 .route("/oobi/:aid", get(get_oobi))
70 .route("/oobi/:aid/:role", get(get_oobi_role))
71 .route("/oobi/:aid/:role/:eid", get(get_oobi_role_eid))
72 .with_state(state);
73
74 let addr = Self::parse_curl(curl)?;
75 info!("Listening on {}", addr);
76
77 let listener = TcpListener::bind(addr)
78 .await
79 .with_context(|| format!("Failed to bind to {}", addr))?;
80
81 axum::serve(listener, app).await?;
82
83 Ok(())
84 }
85
86 fn parse_curl(curl: &str) -> Result<SocketAddr> {
87 let addr_str = curl
88 .strip_prefix("tcp://")
89 .or_else(|| curl.strip_prefix("http://"))
90 .ok_or_else(|| anyhow::anyhow!("Unsupported protocol in curl: {}", curl))?;
91
92 addr_str
93 .trim_end_matches('/')
94 .parse()
95 .with_context(|| format!("Failed to parse address: {}", addr_str))
96 }
97}
98
99async fn health_check(State(state): State<WitnessState>) -> impl IntoResponse {
100 (
101 StatusCode::OK,
102 format!("Witness {} running (AID: {})", state.witness.alias, state.witness.identifier),
103 )
104}
105
106fn error_response(e: ActorError) -> Response {
107 let status = match e {
108 ActorError::BadRequest(_) => StatusCode::BAD_REQUEST,
109 ActorError::NotFound(_) => StatusCode::NOT_FOUND,
110 ActorError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
111 ActorError::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
112 };
113 if status.is_server_error() {
114 error!("{}", e);
115 } else {
116 info!("{}", e);
117 }
118 (status, e.to_string()).into_response()
119}
120
121fn cesr_response(status: StatusCode, body: Vec<u8>) -> Response {
122 (status, [("Content-Type", CESR_STREAM_CONTENT_TYPE)], body).into_response()
123}
124
125fn attachments(headers: &HeaderMap) -> Option<String> {
127 headers
128 .get(CESR_ATTACHMENT_HEADER)
129 .and_then(|v| v.to_str().ok())
130 .map(str::to_string)
131}
132
133async fn oobi(state: WitnessState, aid: String, role: Option<String>) -> Response {
134 info!("OOBI request for {} role={:?}", aid, role);
135 match state.witness.actor.oobi(aid, role).await {
136 Ok(msg) => cesr_response(StatusCode::OK, msg),
137 Err(e) => error_response(e),
138 }
139}
140
141async fn get_oobi(State(state): State<WitnessState>, Path(aid): Path<String>) -> Response {
142 oobi(state, aid, None).await
143}
144
145async fn get_oobi_role(
146 State(state): State<WitnessState>,
147 Path((aid, role)): Path<(String, String)>,
148) -> Response {
149 oobi(state, aid, Some(role)).await
150}
151
152async fn get_oobi_role_eid(
153 State(state): State<WitnessState>,
154 Path((aid, role, _eid)): Path<(String, String, String)>,
155) -> Response {
156 oobi(state, aid, Some(role)).await
157}
158
159async fn post_receipt(
161 State(state): State<WitnessState>,
162 headers: HeaderMap,
163 body: axum::body::Bytes,
164) -> Response {
165 let Some(att) = attachments(&headers) else {
166 return error_response(ActorError::BadRequest(format!(
167 "missing {} header",
168 CESR_ATTACHMENT_HEADER
169 )));
170 };
171 match state.witness.actor.receipt(body.to_vec(), att).await {
172 Ok(ReceiptOutcome::Receipted(rct)) => cesr_response(StatusCode::OK, rct),
173 Ok(ReceiptOutcome::Pending) => StatusCode::ACCEPTED.into_response(),
174 Err(e) => error_response(e),
175 }
176}
177
178async fn http_ingest(
181 State(state): State<WitnessState>,
182 headers: HeaderMap,
183 body: axum::body::Bytes,
184) -> Response {
185 let msg = match attachments(&headers) {
186 Some(att) => libkeri_http::join(&body, &att),
187 None => body.to_vec(),
188 };
189 match state.witness.actor.ingest(msg).await {
190 Ok(()) => StatusCode::NO_CONTENT.into_response(),
191 Err(e) => error_response(e),
192 }
193}