printobserver_server/ingress.rs
1//! The one endpoint `Obico`'s webhook notification plugin posts to.
2//!
3//! # It answers before it has handled anything
4//!
5//! `Obico` posts best-effort: its plugin calls `requests.post` with a five
6//! second timeout and raises on the answer, and nothing retries. So this
7//! endpoint does the two things that must precede an answer — check the shared
8//! secret, and take the body — and then answers, leaving the handling to a
9//! worker of its own. The bound the answer must arrive inside is
10//! [`ServerConfig::ingress_answer_bound`](crate::ServerConfig), and it is
11//! load-bearing rather than decorative: the queue between the endpoint and the
12//! worker is bounded, and a body the worker is too busy to take **inside that
13//! bound** is refused inside it rather than held past it.
14//!
15//! # The secret is carried in the request, not in the body
16//!
17//! Anything that can post here can pause a printer, so a post that carries no
18//! valid secret is refused. `Obico`'s plugin is configured with a URL and
19//! nothing else — `custom_webhook_URL` is the whole of its configuration — so
20//! the secret is accepted in the query as well as in a header, and the query
21//! form is the one a real `Obico` can carry.
22//!
23//! # An unauthenticated post is recorded
24//!
25//! Under the malformed-external-event kind, carrying the bytes that arrived.
26//! That is what that kind means — a body arrived and this system did not read
27//! it — and it is the only kind that carries bytes with no print behind them.
28//! Dropping it silently would leave the one class of post an operator most
29//! needs to see written down nowhere.
30
31use std::sync::Arc;
32
33use axum::Json;
34use axum::extract::{Query, State};
35use axum::http::{HeaderMap, StatusCode, header};
36use axum::response::{IntoResponse, Response};
37use printobserver_core::Supervisor;
38use printobserver_obico::ObicoVision;
39use printobserver_store_api::{EventDraft, StorePort};
40use printobserver_types::serde::Deserialize;
41use printobserver_types::{
42 EventPayload, EventSource, MalformedExternalEventPayload, RawBytes, Timestamp,
43};
44use printobserver_vision_api::VisionPort;
45use tokio::sync::{mpsc, watch};
46
47use crate::config::SharedSecret;
48use crate::wire::{ErrorAnswer, IngressAnswer};
49
50/// The header a caller that can set headers carries the shared secret in.
51pub const TOKEN_HEADER: &str = "x-printobserver-token";
52
53/// The query parameter a caller that can only set a URL carries it in.
54pub const TOKEN_PARAM: &str = "token";
55
56/// How many bodies may be waiting on the worker at once.
57///
58/// Small on purpose. The queue is not a buffer for a backlog — it is the seam
59/// that lets the answer precede the handling — and a deep one would hide a
60/// worker that had stopped keeping up until far more alerts had been taken than
61/// could be acted on.
62pub const QUEUE_DEPTH: usize = 8;
63
64/// One body taken for handling, with what arrived beside it.
65#[derive(Debug, Clone)]
66struct Received {
67 /// The bytes exactly as posted.
68 body: RawBytes,
69 /// The content type they were posted under, when one was declared.
70 content_type: Option<String>,
71}
72
73/// The shared secret, as a post carried it.
74#[derive(Debug, Clone, Deserialize)]
75#[serde(crate = "printobserver_types::serde")]
76pub struct TokenParam {
77 /// The secret in the query, which is the form `Obico`'s own plugin carries.
78 #[serde(default)]
79 pub token: Option<String>,
80}
81
82/// What the ingress endpoint is given.
83#[derive(Clone)]
84pub struct IngressState {
85 /// Where an unauthenticated post is written down.
86 store: Arc<dyn StorePort>,
87 /// The secret every post must carry, which is a value nothing can read out
88 /// of this state: what it offers is the comparison rather than the value.
89 secret: Arc<SharedSecret>,
90 /// How long taking a body may take before the post is refused.
91 bound: core::time::Duration,
92 /// The seam between the answer and the handling.
93 queue: mpsc::Sender<Received>,
94 /// How many bodies the worker has finished handling.
95 completed: watch::Sender<u64>,
96}
97
98impl core::fmt::Debug for IngressState {
99 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
100 formatter
101 .debug_struct("IngressState")
102 .field("bound", &self.bound)
103 .finish_non_exhaustive()
104 }
105}
106
107impl IngressState {
108 /// The endpoint's state, and the worker that handles what it takes.
109 ///
110 /// The worker runs until the sender is dropped, which is what stops it when
111 /// the server it belongs to is.
112 pub fn start(
113 supervisor: Arc<Supervisor>,
114 store: Arc<dyn StorePort>,
115 vision: Arc<ObicoVision>,
116 secret: SharedSecret,
117 bound: core::time::Duration,
118 ) -> Self {
119 let (queue, mut incoming) = mpsc::channel::<Received>(QUEUE_DEPTH);
120 let (completed, _) = watch::channel(0);
121 let worker_store = Arc::clone(&store);
122 let counter = completed.clone();
123 tokio::spawn(async move {
124 while let Some(received) = incoming.recv().await {
125 // Handled on a thread of its own rather than on an asynchronous
126 // worker. Two of the ports this server composes do blocking work
127 // — the printer adapter speaks HTTP with the standard library,
128 // and the supervising agent's harness drives a child process in
129 // process — so handling one alert holds whatever thread it is
130 // polled on for the whole of the handling. The API this server
131 // answers on that same runtime is what the agent calls *during*
132 // its own turn, and an alert that starved it would answer the
133 // agent minutes after it asked.
134 let supervisor = Arc::clone(&supervisor);
135 let store = Arc::clone(&worker_store);
136 let vision = Arc::clone(&vision);
137 let handled = tokio::task::spawn_blocking(move || {
138 printobserver_core::block_on(handle(&supervisor, &store, &vision, received));
139 })
140 .await;
141 debug_assert!(handled.is_ok(), "the handling of one alert panicked");
142 counter.send_modify(|count| *count += 1);
143 }
144 });
145 Self {
146 store,
147 secret: Arc::new(secret),
148 bound,
149 queue,
150 completed,
151 }
152 }
153
154 /// How many bodies the worker has finished handling, watchable while it
155 /// works. This is the seam a caller sees the answer precede the handling
156 /// through.
157 #[must_use]
158 pub fn completions(&self) -> watch::Receiver<u64> {
159 self.completed.subscribe()
160 }
161}
162
163/// Handle one body the endpoint took: read it, and give it to the loop.
164async fn handle(
165 supervisor: &Arc<Supervisor>,
166 store: &Arc<dyn StorePort>,
167 vision: &Arc<ObicoVision>,
168 received: Received,
169) {
170 match vision
171 .normalize(received.body.clone(), received.content_type)
172 .await
173 {
174 // Core's own loop is the one place an alert becomes a supervised turn:
175 // it appends the event, fetches and stores the image the alert names,
176 // runs the turn, and closes the print out when the machine says it has
177 // ended. Nothing here repeats any of that.
178 Ok(alert) => {
179 let _ = supervisor.handle_event(alert).await;
180 }
181 Err(refusal) => {
182 record_unread(store, received.body, refusal.to_string()).await;
183 }
184 }
185}
186
187/// Write down one body this system did not read, and the reason it did not.
188async fn record_unread(store: &Arc<dyn StorePort>, body: RawBytes, detail: String) {
189 let _ = store
190 .append_event(EventDraft {
191 print_id: None,
192 source: EventSource::Obico,
193 received_at: Timestamp::now(),
194 payload: EventPayload::MalformedExternalEvent(MalformedExternalEventPayload { detail }),
195 raw: Some(body),
196 })
197 .await;
198}
199
200/// Take one body `Obico` posted.
201pub(crate) async fn receive(
202 State(state): State<IngressState>,
203 headers: HeaderMap,
204 Query(params): Query<TokenParam>,
205 body: axum::body::Bytes,
206) -> Response {
207 let offered = headers
208 .get(TOKEN_HEADER)
209 .and_then(|value| value.to_str().ok())
210 .map(str::to_owned)
211 .or(params.token);
212 let body = RawBytes::new(body.to_vec());
213 if !state.secret.matches(offered.as_deref()) {
214 // Written down inside the same bound the answer is given inside: an
215 // unauthenticated post is the one class of post an operator most needs
216 // to see, and it is also the one a caller can send as fast as it likes,
217 // so the record is attempted rather than waited on.
218 let _ = tokio::time::timeout(
219 state.bound,
220 record_unread(
221 &state.store,
222 body,
223 "the post carried no valid shared secret, so this system did not read it"
224 .to_owned(),
225 ),
226 )
227 .await;
228 return rendered(
229 StatusCode::UNAUTHORIZED,
230 &ErrorAnswer::saying("this ingress requires the shared secret it is configured with"),
231 );
232 }
233 let content_type = headers
234 .get(header::CONTENT_TYPE)
235 .and_then(|value| value.to_str().ok())
236 .map(str::to_owned);
237 let taken = tokio::time::timeout(
238 state.bound,
239 state.queue.send(Received { body, content_type }),
240 )
241 .await;
242 match taken {
243 Ok(Ok(())) => rendered(StatusCode::ACCEPTED, &IngressAnswer),
244 // Either the worker is too far behind to take this inside the bound, or
245 // it has stopped. Refusing inside the bound is the answer Obico can act
246 // on; holding past it is an alert Obico has already abandoned.
247 Ok(Err(_)) | Err(_) => rendered(
248 StatusCode::SERVICE_UNAVAILABLE,
249 &ErrorAnswer::saying(format!(
250 "this ingress could not take the body inside its {}ms answer bound",
251 state.bound.as_millis()
252 )),
253 ),
254 }
255}
256
257/// One answer, rendered as JSON.
258fn rendered<T: printobserver_types::serde::Serialize>(status: StatusCode, body: &T) -> Response {
259 (
260 status,
261 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
262 Json(printobserver_types::serde_json::to_value(body).unwrap_or_default()),
263 )
264 .into_response()
265}