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::store::{EventDraft, EventStore};
38use printobserver_core::{PendingTurn, Supervisor};
39use printobserver_obico::{ObicoVision, obico_source};
40use printobserver_types::serde::Deserialize;
41use printobserver_types::{EventBody, RawBytes, Timestamp};
42use printobserver_vision_api::{MalformedExternalEventPayload, VisionPort};
43use tokio::sync::{mpsc, watch};
44
45use crate::config::SharedSecret;
46use crate::wire::{ErrorAnswer, IngressAnswer};
47
48/// The header a caller that can set headers carries the shared secret in.
49pub const TOKEN_HEADER: &str = "x-printobserver-token";
50
51/// The query parameter a caller that can only set a URL carries it in.
52pub const TOKEN_PARAM: &str = "token";
53
54/// How many bodies may be waiting on the worker at once.
55///
56/// Small on purpose. The queue is not a buffer for a backlog — it is the seam
57/// that lets the answer precede the handling — and a deep one would hide a
58/// worker that had stopped keeping up until far more alerts had been taken than
59/// could be acted on.
60pub const QUEUE_DEPTH: usize = 8;
61
62/// One body taken for handling, with what arrived beside it.
63#[derive(Debug, Clone)]
64struct Received {
65 /// The bytes exactly as posted.
66 body: RawBytes,
67 /// The content type they were posted under, when one was declared.
68 content_type: Option<String>,
69}
70
71/// The shared secret, as a post carried it.
72#[derive(Debug, Clone, Deserialize)]
73#[serde(crate = "printobserver_types::serde")]
74pub struct TokenParam {
75 /// The secret in the query, which is the form `Obico`'s own plugin carries.
76 #[serde(default)]
77 pub token: Option<String>,
78}
79
80/// What the ingress endpoint is given.
81#[derive(Clone)]
82pub struct IngressState {
83 /// The log an unauthenticated post is written down in.
84 events: Arc<dyn EventStore>,
85 /// The secret every post must carry, which is a value nothing can read out
86 /// of this state: what it offers is the comparison rather than the value.
87 secret: Arc<SharedSecret>,
88 /// How long taking a body may take before the post is refused.
89 bound: core::time::Duration,
90 /// The seam between the answer and the handling.
91 queue: mpsc::Sender<Received>,
92 /// How many bodies the worker has finished handling.
93 completed: watch::Sender<u64>,
94}
95
96impl core::fmt::Debug for IngressState {
97 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
98 formatter
99 .debug_struct("IngressState")
100 .field("bound", &self.bound)
101 .finish_non_exhaustive()
102 }
103}
104
105impl IngressState {
106 /// The endpoint's state, and the worker that handles what it takes.
107 ///
108 /// The worker runs until the sender is dropped, which is what stops it when
109 /// the server it belongs to is.
110 pub fn start(
111 supervisor: Arc<Supervisor>,
112 events: Arc<dyn EventStore>,
113 vision: Arc<ObicoVision>,
114 secret: SharedSecret,
115 bound: core::time::Duration,
116 ) -> Self {
117 let (queue, mut incoming) = mpsc::channel::<Received>(QUEUE_DEPTH);
118 let (completed, _) = watch::channel(0);
119 let worker_events = Arc::clone(&events);
120 let counter = completed.clone();
121 tokio::spawn(async move {
122 while let Some(received) = incoming.recv().await {
123 // Handled on a thread of its own rather than on an asynchronous
124 // worker. Two of the ports this server composes do blocking work
125 // — the printer adapter speaks HTTP with the standard library,
126 // and the supervising agent's harness drives a child process in
127 // process — so handling one alert holds whatever thread it is
128 // polled on for the whole of the handling. The API this server
129 // answers on that same runtime is what the agent calls *during*
130 // its own turn, and an alert that starved it would answer the
131 // agent minutes after it asked.
132 //
133 // Alerts are written down one at a time, in the order they
134 // arrived, and the turn one claims runs on a thread of its own
135 // so the next is written down while it runs: an alert for a
136 // print whose turn is running is handed to that turn, which is
137 // how it reaches the agent already watching the print, and an
138 // alert for another print is written down and supervised while
139 // the first turn — or a look inside it — is still waiting.
140 let writer = Arc::clone(&supervisor);
141 let events = Arc::clone(&worker_events);
142 let vision = Arc::clone(&vision);
143 let written = tokio::task::spawn_blocking(move || {
144 printobserver_core::block_on(handle(&writer, &events, &vision, received))
145 })
146 .await;
147 debug_assert!(written.is_ok(), "the writing down of one alert panicked");
148 let Ok(Some(turn)) = written else {
149 counter.send_modify(|count| *count += 1);
150 continue;
151 };
152 let runner = Arc::clone(&supervisor);
153 let finished = counter.clone();
154 tokio::spawn(async move {
155 let supervised = tokio::task::spawn_blocking(move || {
156 let _ = printobserver_core::block_on(runner.run_supervision(turn));
157 })
158 .await;
159 debug_assert!(supervised.is_ok(), "the supervision of one alert panicked");
160 finished.send_modify(|count| *count += 1);
161 });
162 }
163 });
164 Self {
165 events,
166 secret: Arc::new(secret),
167 bound,
168 queue,
169 completed,
170 }
171 }
172
173 /// How many bodies the worker has finished handling, watchable while it
174 /// works. This is the seam a caller sees the answer precede the handling
175 /// through.
176 #[must_use]
177 pub fn completions(&self) -> watch::Receiver<u64> {
178 self.completed.subscribe()
179 }
180}
181
182/// Handle one body the endpoint took: read it, give it to the loop to write
183/// down, and answer the turn it claimed, when it claimed one.
184async fn handle(
185 supervisor: &Arc<Supervisor>,
186 events: &Arc<dyn EventStore>,
187 vision: &Arc<ObicoVision>,
188 received: Received,
189) -> Option<PendingTurn> {
190 match vision
191 .normalize(received.body.clone(), received.content_type)
192 .await
193 {
194 // Core's own loop is the one place an alert becomes a supervised turn:
195 // it appends the event, fetches and stores the image the alert names,
196 // hands it to a running turn or claims one, and — through the turn this
197 // answers — runs it and closes the print out when the machine says it
198 // has ended. Nothing here repeats any of that.
199 Ok(alert) => supervisor
200 .receive_event(alert)
201 .await
202 .ok()
203 .and_then(|received| received.turn),
204 Err(refusal) => {
205 record_unread(events, received.body, refusal.to_string()).await;
206 None
207 }
208 }
209}
210
211/// Write down one body this system did not read, and the reason it did not.
212///
213/// The record is attempted rather than waited on, and a record that will not
214/// render is dropped exactly as one the store refuses is: the post has already
215/// been answered, and nothing here may take the ingress worker down.
216async fn record_unread(events: &Arc<dyn EventStore>, body: RawBytes, detail: String) {
217 let Ok(rendered) = EventBody::of(&MalformedExternalEventPayload { detail }) else {
218 return;
219 };
220 let _ = events
221 .append_event(EventDraft {
222 print_id: None,
223 source: obico_source(),
224 received_at: Timestamp::now(),
225 body: rendered,
226 raw: Some(body),
227 })
228 .await;
229}
230
231/// Take one body `Obico` posted.
232pub(crate) async fn receive(
233 State(state): State<IngressState>,
234 headers: HeaderMap,
235 Query(params): Query<TokenParam>,
236 body: axum::body::Bytes,
237) -> Response {
238 let offered = headers
239 .get(TOKEN_HEADER)
240 .and_then(|value| value.to_str().ok())
241 .map(str::to_owned)
242 .or(params.token);
243 let body = RawBytes::new(body.to_vec());
244 if !state.secret.matches(offered.as_deref()) {
245 // Written down inside the same bound the answer is given inside: an
246 // unauthenticated post is the one class of post an operator most needs
247 // to see, and it is also the one a caller can send as fast as it likes,
248 // so the record is attempted rather than waited on.
249 let _ = tokio::time::timeout(
250 state.bound,
251 record_unread(
252 &state.events,
253 body,
254 "the post carried no valid shared secret, so this system did not read it"
255 .to_owned(),
256 ),
257 )
258 .await;
259 return rendered(
260 StatusCode::UNAUTHORIZED,
261 &ErrorAnswer::saying("this ingress requires the shared secret it is configured with"),
262 );
263 }
264 let content_type = headers
265 .get(header::CONTENT_TYPE)
266 .and_then(|value| value.to_str().ok())
267 .map(str::to_owned);
268 let taken = tokio::time::timeout(
269 state.bound,
270 state.queue.send(Received { body, content_type }),
271 )
272 .await;
273 match taken {
274 Ok(Ok(())) => rendered(StatusCode::ACCEPTED, &IngressAnswer),
275 // Either the worker is too far behind to take this inside the bound, or
276 // it has stopped. Refusing inside the bound is the answer Obico can act
277 // on; holding past it is an alert Obico has already abandoned.
278 Ok(Err(_)) | Err(_) => rendered(
279 StatusCode::SERVICE_UNAVAILABLE,
280 &ErrorAnswer::saying(format!(
281 "this ingress could not take the body inside its {}ms answer bound",
282 state.bound.as_millis()
283 )),
284 ),
285 }
286}
287
288/// One answer, rendered as JSON.
289fn rendered<T: printobserver_types::serde::Serialize>(status: StatusCode, body: &T) -> Response {
290 (
291 status,
292 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
293 Json(printobserver_types::serde_json::to_value(body).unwrap_or_default()),
294 )
295 .into_response()
296}