1use std::sync::Arc;
34use std::time::Duration;
35
36use axum::Json;
37use axum::extract::{DefaultBodyLimit, Path, Query, Request, State};
38use axum::http::{StatusCode, header};
39use axum::middleware::{Next, from_fn_with_state};
40use axum::response::{IntoResponse, Response};
41use axum::routing::{get, post, put};
42use axum::{Router, routing::MethodRouter};
43use printobserver_core::store::{
44 EventStore, HistoryQuery, ImageStore, PrintStore, SessionStore, StoreError,
45};
46use printobserver_core::{ActionKind, ExecutionOutcome, PolicyDecision};
47use printobserver_core::{CoreError, Supervisor, effective_bounds};
48use printobserver_types::serde::Deserialize;
49use printobserver_types::{ImageId, PrintId};
50
51use crate::config::ApiCredential;
52use crate::operations::{Effect, Method, OPERATIONS, Operation, VERSION_PREFIX};
53use crate::wire::{
54 ActionAnswer, ActionBody, ContextAnswer, ErrorAnswer, HistoryAnswer, ImageAnswer,
55 ManifestAnswer, ManifestBody, PrintsAnswer, StatusAnswer,
56};
57
58#[derive(Clone)]
62pub struct ApiState {
63 pub supervisor: Arc<Supervisor>,
65 pub prints: Arc<dyn PrintStore>,
67 pub events: Arc<dyn EventStore>,
69 pub images: Arc<dyn ImageStore>,
71 pub sessions: Arc<dyn SessionStore>,
73 pub credential: Arc<ApiCredential>,
76}
77
78impl core::fmt::Debug for ApiState {
79 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
80 formatter.debug_struct("ApiState").finish_non_exhaustive()
81 }
82}
83
84#[derive(Debug, Clone, Deserialize)]
86#[serde(crate = "printobserver_types::serde")]
87pub struct HistoryParams {
88 #[serde(default)]
90 pub limit: Option<u32>,
91}
92
93pub fn router(state: ApiState) -> Router {
101 let mut api = Router::new();
102 for operation in OPERATIONS {
103 api = api.route(operation.path, route_for(&operation));
104 }
105 let api = api
108 .fallback(nothing_here)
109 .layer(from_fn_with_state(
110 Arc::clone(&state.credential),
111 authenticate,
112 ))
113 .layer(DefaultBodyLimit::max(BODY_BOUND))
114 .with_state(state);
115 Router::new().nest(VERSION_PREFIX, api)
116}
117
118const BEARER: &[u8] = b"Bearer ";
120
121pub const BODY_BOUND: usize = 2 * 1024 * 1024;
128
129pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
135
136pub async fn authenticate(
152 State(credential): State<Arc<ApiCredential>>,
153 request: Request,
154 next: Next,
155) -> Response {
156 let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
157 let admitted = match (presented.next(), presented.next()) {
158 (Some(only), None) => only
159 .as_bytes()
160 .strip_prefix(BEARER)
161 .is_some_and(|offered| credential.admits(offered)),
162 _ => false,
163 };
164 if !admitted {
165 let mut refused = refusal(
166 StatusCode::UNAUTHORIZED,
167 "this server's API requires the credential it is configured with, presented as \
168 `Authorization: Bearer <credential>`",
169 );
170 refused.headers_mut().insert(
171 header::WWW_AUTHENTICATE,
172 header::HeaderValue::from_static("Bearer"),
173 );
174 let _ = tokio::time::timeout(
178 DRAIN_BOUND,
179 axum::body::to_bytes(request.into_body(), BODY_BOUND),
180 )
181 .await;
182 return refused;
183 }
184 next.run(request).await
185}
186
187async fn nothing_here() -> Response {
189 refusal(
190 StatusCode::NOT_FOUND,
191 "no operation of this server is served at that path",
192 )
193}
194
195fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
197 if let Effect::Mutating(kind) = operation.effect {
198 return post(
199 move |state: State<ApiState>, print_id: Path<PrintId>, body: Json<ActionBody>| async move {
200 act(kind, state, print_id, body).await
201 },
202 );
203 }
204 match (operation.name, operation.method) {
205 ("prints", Method::Get) => get(list_and_adopt_prints),
206 ("status", Method::Get) => get(status),
207 ("context", Method::Get) => get(context),
208 ("image", Method::Get) => get(image),
209 ("history", Method::Get) => get(history),
210 ("manifest_get", Method::Get) => get(manifest_get),
211 ("manifest_set", Method::Put) => put(manifest_set),
212 (name, method) => panic!(
213 "the operation `{name}` is declared as {method} and this router serves no such route"
214 ),
215 }
216}
217
218fn answer<T: printobserver_types::serde::Serialize>(status: StatusCode, body: &T) -> Response {
220 let rendered = match printobserver_types::serde_json::to_vec(body) {
221 Ok(bytes) => bytes,
222 Err(error) => {
223 return (
224 StatusCode::INTERNAL_SERVER_ERROR,
225 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
226 format!("{{\"error\":\"{error}\"}}"),
227 )
228 .into_response();
229 }
230 };
231 (
232 status,
233 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
234 rendered,
235 )
236 .into_response()
237}
238
239fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
241 answer(status, &ErrorAnswer::saying(detail))
242}
243
244fn store_status(error: &StoreError) -> StatusCode {
246 match error {
247 StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
248 StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
249 StatusCode::BAD_REQUEST
250 }
251 StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
252 }
253}
254
255fn core_status(error: &CoreError) -> StatusCode {
257 match error {
258 CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
259 CoreError::Store(store) => store_status(store),
260 _ => StatusCode::INTERNAL_SERVER_ERROR,
261 }
262}
263
264async fn act(
266 kind: ActionKind,
267 State(state): State<ApiState>,
268 Path(print_id): Path<PrintId>,
269 Json(body): Json<ActionBody>,
270) -> Response {
271 let action = match body.into_action(kind) {
272 Ok(action) => action,
273 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
274 };
275 let outcome = match state.supervisor.request_action(print_id, action).await {
276 Ok(outcome) => outcome,
277 Err(error) => return refusal(core_status(&error), error),
278 };
279 let printer_refusal = match &outcome.record.outcome {
280 Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
281 _ => None,
282 };
283 let status = match outcome.record.decision {
284 PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
285 PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
289 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
292 };
293 answer(
294 status,
295 &ActionAnswer {
296 record: outcome.record,
297 intervention: outcome.intervention,
298 printer_refusal,
299 },
300 )
301}
302
303async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
310 match state.supervisor.list_and_adopt_prints().await {
311 Ok(listing) => answer(
312 StatusCode::OK,
313 &PrintsAnswer {
314 prints: listing.prints,
315 active: listing.active,
316 },
317 ),
318 Err(error) => refusal(core_status(&error), error),
319 }
320}
321
322async fn status(State(state): State<ApiState>, Path(print_id): Path<PrintId>) -> Response {
324 let print = match state.prints.print(print_id).await {
325 Ok(Some(print)) => print,
326 Ok(None) => {
327 return refusal(
328 StatusCode::NOT_FOUND,
329 format!("there is no print {print_id}"),
330 );
331 }
332 Err(error) => return refusal(store_status(&error), error),
333 };
334 let context = match state.supervisor.context(print_id).await {
335 Ok(context) => context,
336 Err(error) => return refusal(core_status(&error), error),
337 };
338 let session = match state.sessions.session(print_id).await {
339 Ok(session) => session,
340 Err(error) => return refusal(store_status(&error), error),
341 };
342 answer(
343 StatusCode::OK,
344 &StatusAnswer {
345 print,
346 printer: context.printer,
347 job: context.job,
348 session,
349 interventions: context.interventions,
350 },
351 )
352}
353
354async fn context(State(state): State<ApiState>, Path(print_id): Path<PrintId>) -> Response {
362 let context = match state.supervisor.context(print_id).await {
363 Ok(context) => context,
364 Err(error) => return refusal(core_status(&error), error),
365 };
366 let mut image_path = None;
367 if let Some(latest) = context.latest_image.as_ref() {
368 match state.images.image(latest.id).await {
369 Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
370 Err(error) => return refusal(store_status(&error), error),
371 }
372 }
373 answer(
374 StatusCode::OK,
375 &ContextAnswer {
376 context,
377 image_path,
378 },
379 )
380}
381
382async fn image(State(state): State<ApiState>, Path(image_id): Path<ImageId>) -> Response {
384 match state.images.image(image_id).await {
385 Ok(lookup) => answer(StatusCode::OK, &ImageAnswer::from(lookup)),
386 Err(error) => refusal(store_status(&error), error),
387 }
388}
389
390async fn history(
392 State(state): State<ApiState>,
393 Path(print_id): Path<PrintId>,
394 Query(params): Query<HistoryParams>,
395) -> Response {
396 let query = HistoryQuery {
397 print_id,
398 kinds: Vec::new(),
399 since: None,
400 until: None,
401 limit: params.limit,
402 };
403 match state.events.history(query).await {
404 Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
405 Err(error) => refusal(store_status(&error), error),
406 }
407}
408
409async fn manifest_get(State(state): State<ApiState>, Path(print_id): Path<PrintId>) -> Response {
411 let manifest = match state.prints.manifest(print_id).await {
412 Ok(manifest) => manifest,
413 Err(error) => return refusal(store_status(&error), error),
414 };
415 let narrowings = match state.prints.print(print_id).await {
416 Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
417 Err(error) => return refusal(store_status(&error), error),
418 };
419 answer(
420 StatusCode::OK,
421 &ManifestAnswer {
422 manifest,
423 narrowings,
424 },
425 )
426}
427
428async fn manifest_set(
437 State(state): State<ApiState>,
438 Path(print_id): Path<PrintId>,
439 Json(body): Json<ManifestBody>,
440) -> Response {
441 if let Err(rejected) = body.reason() {
442 return refusal(StatusCode::BAD_REQUEST, rejected);
443 }
444 let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
445 if let Err(error) = state
446 .prints
447 .put_manifest(print_id, body.manifest.clone())
448 .await
449 {
450 return refusal(store_status(&error), error);
451 }
452 for narrowing in narrowed.narrowings.clone() {
453 if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
454 return refusal(store_status(&error), error);
455 }
456 }
457 answer(
458 StatusCode::OK,
459 &ManifestAnswer {
460 manifest: Some(body.manifest),
461 narrowings: narrowed.narrowings,
462 },
463 )
464}
465
466#[cfg(test)]
467mod tests {
468 use axum::http::StatusCode;
469 use printobserver_core::CoreError;
470 use printobserver_core::store::StoreError;
471
472 use super::{core_status, store_status};
473
474 #[test]
477 fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
478 for (error, expected) in [
479 (
480 StoreError::NotFound {
481 what: "print".to_owned(),
482 },
483 StatusCode::NOT_FOUND,
484 ),
485 (
486 StoreError::LimitRefused {
487 limit: 1_000,
488 asked_for: 2_000,
489 },
490 StatusCode::BAD_REQUEST,
491 ),
492 (
493 StoreError::ConstraintRefused {
494 constraint: "actions.decision".to_owned(),
495 },
496 StatusCode::BAD_REQUEST,
497 ),
498 (
499 StoreError::Database {
500 detail: "the disk is full".to_owned(),
501 },
502 StatusCode::INTERNAL_SERVER_ERROR,
503 ),
504 (
505 StoreError::Io {
506 detail: "the disk is full".to_owned(),
507 },
508 StatusCode::INTERNAL_SERVER_ERROR,
509 ),
510 ] {
511 assert_eq!(store_status(&error), expected, "{error}");
512 }
513 }
514
515 #[test]
518 fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
519 assert_eq!(
520 core_status(&CoreError::NoSuchPrint {
521 print_id: printobserver_types::PrintId::new(),
522 }),
523 StatusCode::NOT_FOUND
524 );
525 assert_eq!(
526 core_status(&CoreError::Store(StoreError::NotFound {
527 what: "print".to_owned(),
528 })),
529 StatusCode::NOT_FOUND
530 );
531 assert_eq!(
532 core_status(&CoreError::Unrepresentable {
533 detail: "an instant".to_owned(),
534 }),
535 StatusCode::INTERNAL_SERVER_ERROR
536 );
537 }
538}