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_core::store::{EventDraft, EventStore};
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 let supervisor = Arc::clone(&supervisor);
133 let events = Arc::clone(&worker_events);
134 let vision = Arc::clone(&vision);
135 let handled = tokio::task::spawn_blocking(move || {
136 printobserver_core::block_on(handle(&supervisor, &events, &vision, received));
137 })
138 .await;
139 debug_assert!(handled.is_ok(), "the handling of one alert panicked");
140 counter.send_modify(|count| *count += 1);
141 }
142 });
143 Self {
144 events,
145 secret: Arc::new(secret),
146 bound,
147 queue,
148 completed,
149 }
150 }
151
152 /// How many bodies the worker has finished handling, watchable while it
153 /// works. This is the seam a caller sees the answer precede the handling
154 /// through.
155 #[must_use]
156 pub fn completions(&self) -> watch::Receiver<u64> {
157 self.completed.subscribe()
158 }
159}
160
161/// Handle one body the endpoint took: read it, and give it to the loop.
162async fn handle(
163 supervisor: &Arc<Supervisor>,
164 events: &Arc<dyn EventStore>,
165 vision: &Arc<ObicoVision>,
166 received: Received,
167) {
168 match vision
169 .normalize(received.body.clone(), received.content_type)
170 .await
171 {
172 // Core's own loop is the one place an alert becomes a supervised turn:
173 // it appends the event, fetches and stores the image the alert names,
174 // runs the turn, and closes the print out when the machine says it has
175 // ended. Nothing here repeats any of that.
176 Ok(alert) => {
177 let _ = supervisor.handle_event(alert).await;
178 }
179 Err(refusal) => {
180 record_unread(events, received.body, refusal.to_string()).await;
181 }
182 }
183}
184
185/// Write down one body this system did not read, and the reason it did not.
186///
187/// The record is attempted rather than waited on, and a record that will not
188/// render is dropped exactly as one the store refuses is: the post has already
189/// been answered, and nothing here may take the ingress worker down.
190async fn record_unread(events: &Arc<dyn EventStore>, body: RawBytes, detail: String) {
191 let Ok(rendered) = EventBody::of(&MalformedExternalEventPayload { detail }) else {
192 return;
193 };
194 let _ = events
195 .append_event(EventDraft {
196 print_id: None,
197 source: obico_source(),
198 received_at: Timestamp::now(),
199 body: rendered,
200 raw: Some(body),
201 })
202 .await;
203}
204
205/// Take one body `Obico` posted.
206pub(crate) async fn receive(
207 State(state): State<IngressState>,
208 headers: HeaderMap,
209 Query(params): Query<TokenParam>,
210 body: axum::body::Bytes,
211) -> Response {
212 let offered = headers
213 .get(TOKEN_HEADER)
214 .and_then(|value| value.to_str().ok())
215 .map(str::to_owned)
216 .or(params.token);
217 let body = RawBytes::new(body.to_vec());
218 if !state.secret.matches(offered.as_deref()) {
219 // Written down inside the same bound the answer is given inside: an
220 // unauthenticated post is the one class of post an operator most needs
221 // to see, and it is also the one a caller can send as fast as it likes,
222 // so the record is attempted rather than waited on.
223 let _ = tokio::time::timeout(
224 state.bound,
225 record_unread(
226 &state.events,
227 body,
228 "the post carried no valid shared secret, so this system did not read it"
229 .to_owned(),
230 ),
231 )
232 .await;
233 return rendered(
234 StatusCode::UNAUTHORIZED,
235 &ErrorAnswer::saying("this ingress requires the shared secret it is configured with"),
236 );
237 }
238 let content_type = headers
239 .get(header::CONTENT_TYPE)
240 .and_then(|value| value.to_str().ok())
241 .map(str::to_owned);
242 let taken = tokio::time::timeout(
243 state.bound,
244 state.queue.send(Received { body, content_type }),
245 )
246 .await;
247 match taken {
248 Ok(Ok(())) => rendered(StatusCode::ACCEPTED, &IngressAnswer),
249 // Either the worker is too far behind to take this inside the bound, or
250 // it has stopped. Refusing inside the bound is the answer Obico can act
251 // on; holding past it is an alert Obico has already abandoned.
252 Ok(Err(_)) | Err(_) => rendered(
253 StatusCode::SERVICE_UNAVAILABLE,
254 &ErrorAnswer::saying(format!(
255 "this ingress could not take the body inside its {}ms answer bound",
256 state.bound.as_millis()
257 )),
258 ),
259 }
260}
261
262/// One answer, rendered as JSON.
263fn rendered<T: printobserver_types::serde::Serialize>(status: StatusCode, body: &T) -> Response {
264 (
265 status,
266 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
267 Json(printobserver_types::serde_json::to_value(body).unwrap_or_default()),
268 )
269 .into_response()
270}