use std::sync::Arc;
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use printobserver_core::Supervisor;
use printobserver_core::store::{EventDraft, EventStore};
use printobserver_obico::{ObicoVision, obico_source};
use printobserver_types::serde::Deserialize;
use printobserver_types::{EventBody, RawBytes, Timestamp};
use printobserver_vision_api::{MalformedExternalEventPayload, VisionPort};
use tokio::sync::{mpsc, watch};
use crate::config::SharedSecret;
use crate::wire::{ErrorAnswer, IngressAnswer};
pub const TOKEN_HEADER: &str = "x-printobserver-token";
pub const TOKEN_PARAM: &str = "token";
pub const QUEUE_DEPTH: usize = 8;
#[derive(Debug, Clone)]
struct Received {
body: RawBytes,
content_type: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
pub struct TokenParam {
#[serde(default)]
pub token: Option<String>,
}
#[derive(Clone)]
pub struct IngressState {
events: Arc<dyn EventStore>,
secret: Arc<SharedSecret>,
bound: core::time::Duration,
queue: mpsc::Sender<Received>,
completed: watch::Sender<u64>,
}
impl core::fmt::Debug for IngressState {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter
.debug_struct("IngressState")
.field("bound", &self.bound)
.finish_non_exhaustive()
}
}
impl IngressState {
pub fn start(
supervisor: Arc<Supervisor>,
events: Arc<dyn EventStore>,
vision: Arc<ObicoVision>,
secret: SharedSecret,
bound: core::time::Duration,
) -> Self {
let (queue, mut incoming) = mpsc::channel::<Received>(QUEUE_DEPTH);
let (completed, _) = watch::channel(0);
let worker_events = Arc::clone(&events);
let counter = completed.clone();
tokio::spawn(async move {
while let Some(received) = incoming.recv().await {
let supervisor = Arc::clone(&supervisor);
let events = Arc::clone(&worker_events);
let vision = Arc::clone(&vision);
let handled = tokio::task::spawn_blocking(move || {
printobserver_core::block_on(handle(&supervisor, &events, &vision, received));
})
.await;
debug_assert!(handled.is_ok(), "the handling of one alert panicked");
counter.send_modify(|count| *count += 1);
}
});
Self {
events,
secret: Arc::new(secret),
bound,
queue,
completed,
}
}
#[must_use]
pub fn completions(&self) -> watch::Receiver<u64> {
self.completed.subscribe()
}
}
async fn handle(
supervisor: &Arc<Supervisor>,
events: &Arc<dyn EventStore>,
vision: &Arc<ObicoVision>,
received: Received,
) {
match vision
.normalize(received.body.clone(), received.content_type)
.await
{
Ok(alert) => {
let _ = supervisor.handle_event(alert).await;
}
Err(refusal) => {
record_unread(events, received.body, refusal.to_string()).await;
}
}
}
async fn record_unread(events: &Arc<dyn EventStore>, body: RawBytes, detail: String) {
let Ok(rendered) = EventBody::of(&MalformedExternalEventPayload { detail }) else {
return;
};
let _ = events
.append_event(EventDraft {
print_id: None,
source: obico_source(),
received_at: Timestamp::now(),
body: rendered,
raw: Some(body),
})
.await;
}
pub(crate) async fn receive(
State(state): State<IngressState>,
headers: HeaderMap,
Query(params): Query<TokenParam>,
body: axum::body::Bytes,
) -> Response {
let offered = headers
.get(TOKEN_HEADER)
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
.or(params.token);
let body = RawBytes::new(body.to_vec());
if !state.secret.matches(offered.as_deref()) {
let _ = tokio::time::timeout(
state.bound,
record_unread(
&state.events,
body,
"the post carried no valid shared secret, so this system did not read it"
.to_owned(),
),
)
.await;
return rendered(
StatusCode::UNAUTHORIZED,
&ErrorAnswer::saying("this ingress requires the shared secret it is configured with"),
);
}
let content_type = headers
.get(header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let taken = tokio::time::timeout(
state.bound,
state.queue.send(Received { body, content_type }),
)
.await;
match taken {
Ok(Ok(())) => rendered(StatusCode::ACCEPTED, &IngressAnswer),
Ok(Err(_)) | Err(_) => rendered(
StatusCode::SERVICE_UNAVAILABLE,
&ErrorAnswer::saying(format!(
"this ingress could not take the body inside its {}ms answer bound",
state.bound.as_millis()
)),
),
}
}
fn rendered<T: printobserver_types::serde::Serialize>(status: StatusCode, body: &T) -> Response {
(
status,
[(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
Json(printobserver_types::serde_json::to_value(body).unwrap_or_default()),
)
.into_response()
}