Skip to main content

printobserver_server/
api.rs

1//! The HTTP surface, built by folding over the declared operations.
2//!
3//! # The router is the declaration
4//!
5//! Nothing here writes a route out. [`router`] walks
6//! [`OPERATIONS`](crate::operations::OPERATIONS) and registers one route per
7//! entry beneath the one versioned prefix, so the set served and the set
8//! declared cannot come apart — and the ten mutating operations share one
9//! handler which is given the [`ActionKind`] its own entry declares, so a
10//! request cannot reach an action the operation it was sent to does not name.
11//! The five spool commands share one handler of their own on the same terms.
12//!
13//! # Every action takes the same one path
14//!
15//! An action asked for here goes to
16//! [`Supervisor::request_action`](printobserver_core::Supervisor::request_action),
17//! which is the same call an operator's action makes and an agent's action
18//! makes. The policy is not re-implemented here and is not bypassed here: a
19//! rejected request answers the rejection the policy made, carrying its reason,
20//! the value asked for and the range allowed, and reaches no action method of
21//! the printer port at all.
22//!
23//! # Nothing is served to a caller that did not present a credential
24//!
25//! Every route beneath the versioned prefix — and the prefix's own fallback, so
26//! that a path nothing serves is refused the same way — sits behind
27//! [`authenticate`], which runs before any extractor reads a path, a query or a
28//! body. A request whose `Authorization` header is not exactly
29//! `Bearer <credential>`, for the operator's credential or a live supervision
30//! turn's, is answered `401` there, so it reaches no handler, no store, no
31//! printer port and no record. There is no route that skips it and no
32//! configuration that turns it off: [`ApiState`] cannot be built without what
33//! a credential is checked against.
34//!
35//! # Every request is the identity its credential authenticated
36//!
37//! What [`authenticate`] admitted is a [`Caller`]: the operator, or one turn —
38//! the agent, in one session, on one print. Every handler is given it, and the
39//! body's `actor` is a claim held to it **before** the policy is asked
40//! anything: a claim that is not the caller — an operator credential claiming
41//! to be the agent, a turn claiming to be the operator or another session, and
42//! anybody claiming to be the system, whose actions are the server's own — is
43//! refused `403` naming both, and nothing is decided or recorded. A turn's
44//! credential reaches its own print alone, the listing of prints beside it,
45//! and neither of the two writes that are not about a running print: starting
46//! one and replacing a manifest. So the class the policy rules on, and the
47//! agent's minimum interval with it, is the one the credential authenticated
48//! rather than the one the request claimed.
49//!
50//! The spool ledger is the printer's rather than one print's, so its four
51//! reads are open to every caller — a turn included, which is how the agent
52//! reads what is loaded and what a file needs — and its commands are held to
53//! the same claim and then to the envelope's own grants, which the domain rules
54//! on and records.
55//!
56//! The recovery operations are the printer's too: their read is open to every
57//! caller, answering what each action would meet for that caller, and each
58//! action is held to the same claim and then to the recovery grants and the
59//! machine's own state, which the domain rules on and records.
60
61use std::sync::Arc;
62use std::time::Duration;
63
64use axum::Json;
65use axum::extract::rejection::JsonRejection;
66use axum::extract::{DefaultBodyLimit, Extension, Path, Query, Request, State};
67use axum::http::{StatusCode, header};
68use axum::middleware::{Next, from_fn_with_state};
69use axum::response::{IntoResponse, Response};
70use axum::routing::{get, post, put};
71use axum::{Router, routing::MethodRouter};
72use printobserver_core::recovery::recovery_detail;
73use printobserver_core::store::TimelineQuery;
74use printobserver_core::store::{
75    EventStore, HistoryQuery, ImageStore, PrintStore, SessionStore, StoreError,
76};
77use printobserver_core::{
78    ActionKind, Actor, ActorClass, ExecutionOutcome, PolicyDecision, RecoveryActionKind,
79    RecoveryDecision, SheetId, SpoolId,
80};
81use printobserver_core::{CoreError, MAX_LOOK_WAIT_S, Supervisor, effective_bounds};
82use printobserver_types::serde::Deserialize;
83use printobserver_types::serde_json::Value;
84use printobserver_types::{EventId, EventKind, FileName, ImageId, PrintId, Timestamp};
85
86use crate::operations::{Effect, Method, OPERATIONS, Operation, VERSION_PREFIX};
87use crate::server::{CREDENTIAL_ISSUE, OperatorCredential};
88use crate::turns::{TurnBinding, TurnCredentials};
89use crate::wire::{
90    ActionAnswer, ActionBody, ContextAnswer, ErrorAnswer, HistoryAnswer, ImageAnswer,
91    ManifestAnswer, ManifestBody, PreflightAnswer, PrintsAnswer, RecoveryAnswer, SpoolAnswer,
92    SpoolCommandAnswer, SpoolsAnswer, StatusAnswer, TimelineAnswer, claimed_actor, recovery_of,
93    spool_command_of,
94};
95
96/// What every handler is given: the supervisor, and the stores the reads
97/// answer out of — the four aggregates a route reads, and not the actions,
98/// which reach the store through the supervisor alone.
99#[derive(Clone)]
100pub struct ApiState {
101    /// The supervision core, which every action passes through.
102    pub supervisor: Arc<Supervisor>,
103    /// The print records, their manifests and their narrowings.
104    pub prints: Arc<dyn PrintStore>,
105    /// The event log.
106    pub events: Arc<dyn EventStore>,
107    /// The images stored beside the events.
108    pub images: Arc<dyn ImageStore>,
109    /// The supervision sessions.
110    pub sessions: Arc<dyn SessionStore>,
111    /// What the operator's credential is checked against before anything
112    /// above is reached.
113    pub operator: Arc<OperatorCredential>,
114    /// The live supervision turns' credentials, checked the same way.
115    pub turns: TurnCredentials,
116    /// The broadcast an events read waits on, raised once an event is stored.
117    pub stored: crate::events::Stored,
118}
119
120/// Who one request authenticated as.
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum Caller {
123    /// The operator, by the credential the operator's verifier admits.
124    Operator,
125    /// One supervision turn's run: the agent, in one session, on one print.
126    Turn(TurnBinding),
127}
128
129impl Caller {
130    /// This caller, as a refusal names it.
131    fn named(&self) -> String {
132        match self {
133            Self::Operator => "the operator".to_owned(),
134            Self::Turn(binding) => format!(
135                "the agent in session `{}` on print {}",
136                binding.session_name(),
137                binding.print_id()
138            ),
139        }
140    }
141}
142
143/// One claimed actor, as a refusal names it.
144fn claimed(actor: &Actor) -> String {
145    match actor {
146        Actor::Operator => "the operator".to_owned(),
147        Actor::System => "the system".to_owned(),
148        Actor::Agent { session_name } => format!("the agent in session `{session_name}`"),
149    }
150}
151
152/// Refuse a claimed actor that is not the caller, before anything is decided.
153///
154/// The system is claimed by nobody: its actions are the server's own, and no
155/// credential this server admits is the server.
156fn claim_refused(caller: &Caller, actor: &Actor) -> Option<Response> {
157    let held = match (caller, actor) {
158        (Caller::Operator, Actor::Operator) => true,
159        (Caller::Turn(binding), Actor::Agent { session_name }) => {
160            *session_name == binding.session_name()
161        }
162        _ => false,
163    };
164    if held {
165        return None;
166    }
167    let why = if matches!(actor, Actor::System) {
168        "no credential may claim the system, whose actions are the server's own"
169    } else {
170        "a request acts as the identity its credential authenticated, and no other"
171    };
172    Some(refusal(
173        StatusCode::FORBIDDEN,
174        format!(
175            "this request authenticated as {} and claims to be {}: {why}",
176            caller.named(),
177            claimed(actor)
178        ),
179    ))
180}
181
182/// Refuse a turn's request about any print but its own.
183pub(crate) fn scope_refused(caller: &Caller, print_id: PrintId) -> Option<Response> {
184    match caller {
185        Caller::Turn(binding) if binding.print_id() != print_id => Some(refusal(
186            StatusCode::FORBIDDEN,
187            format!(
188                "this request authenticated as {} and names print {print_id}: a supervision \
189                 turn's credential reaches its own print alone",
190                caller.named()
191            ),
192        )),
193        _ => None,
194    }
195}
196
197/// Refuse a turn's request for something that belongs to no print: a turn's
198/// credential reaches its own print alone, and what belongs to none is the
199/// operator's.
200fn printless_refused(caller: &Caller, what: &str) -> Option<Response> {
201    match caller {
202        Caller::Turn(_) => Some(refusal(
203            StatusCode::FORBIDDEN,
204            format!(
205                "this request authenticated as {} and asks for {what}: a supervision turn's \
206                 credential reaches its own print alone",
207                caller.named()
208            ),
209        )),
210        Caller::Operator => None,
211    }
212}
213
214/// Refuse a turn's request for a write that is not about its running print:
215/// starting a print, and replacing a manifest, are the operator's alone.
216fn operator_refused(caller: &Caller, command: &str) -> Option<Response> {
217    match caller {
218        Caller::Turn(_) => Some(refusal(
219            StatusCode::FORBIDDEN,
220            format!(
221                "this request authenticated as {} and asks for `{command}`, which is the \
222                 operator's alone: a supervision turn's credential does not reach it",
223                caller.named()
224            ),
225        )),
226        Caller::Operator => None,
227    }
228}
229
230/// What [`authenticate`] checks a presented credential against.
231#[derive(Clone)]
232pub struct Admission {
233    /// The operator's.
234    operator: Arc<OperatorCredential>,
235    /// The live turns'.
236    turns: TurnCredentials,
237}
238
239impl Admission {
240    /// Who a presented credential authenticates as, when it is anybody.
241    fn caller(&self, presented: &[u8]) -> Option<Caller> {
242        if let Some(binding) = self.turns.admit(presented) {
243            return Some(Caller::Turn(binding));
244        }
245        self.operator.admits(presented).then_some(Caller::Operator)
246    }
247}
248
249impl core::fmt::Debug for ApiState {
250    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
251        formatter.debug_struct("ApiState").finish_non_exhaustive()
252    }
253}
254
255/// How many events a history read asks for, when it asks for a number.
256#[derive(Debug, Clone, Deserialize)]
257#[serde(crate = "printobserver_types::serde")]
258pub struct HistoryParams {
259    /// The limit asked for; absent takes the port's own default window.
260    #[serde(default)]
261    pub limit: Option<u32>,
262}
263
264/// The event a context read is asked `since`: only the events newer than it
265/// are answered, because the caller has read the rest.
266#[derive(Debug, Clone, Deserialize)]
267#[serde(crate = "printobserver_types::serde")]
268pub struct ContextParams {
269    /// The newest event the caller has read; absent answers the recent window.
270    #[serde(default)]
271    pub since: Option<printobserver_types::EventId>,
272}
273
274/// How long a look asks to wait for something to arrive, in whole seconds.
275#[derive(Debug, Clone, Deserialize)]
276#[serde(crate = "printobserver_types::serde")]
277pub struct LookParams {
278    /// The wait asked for; absent looks at once.
279    #[serde(default)]
280    pub wait_s: Option<u32>,
281}
282
283/// Whether a spools read asks for the retired ones too.
284#[derive(Debug, Clone, Deserialize)]
285#[serde(crate = "printobserver_types::serde")]
286pub struct SpoolsParams {
287    /// Asked for; absent, the retired spools are left out.
288    #[serde(default)]
289    pub include_retired: Option<bool>,
290}
291
292/// The file a filament check is about, and the sheet it would go down on.
293#[derive(Debug, Clone, Deserialize)]
294#[serde(crate = "printobserver_types::serde")]
295pub struct PreflightParams {
296    /// The file, as the printer names it.
297    #[serde(default)]
298    pub file_name: Option<String>,
299    /// The build sheet the sheet check is read against; absent, the check
300    /// reports no sheet result, and a blank one is refused.
301    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
302    #[serde(default)]
303    pub sheet: Option<String>,
304}
305
306/// How many of a spool's own events its read carries, newest first.
307pub const SPOOL_RECENT_EVENTS: u32 = 20;
308
309/// Every public operation, beneath the one versioned prefix.
310///
311/// # Panics
312///
313/// Panics when [`OPERATIONS`] declares an entry this function has no route for,
314/// which is a declaration and a router that have come apart — the one state
315/// this server must not come up in quietly.
316pub fn router(state: ApiState) -> Router {
317    let mut api = Router::new();
318    for operation in OPERATIONS {
319        api = api.route(operation.path, route_for(&operation));
320    }
321    // The layer is added after every route and the fallback, which is what
322    // puts all of them behind it.
323    let api = api
324        .fallback(nothing_here)
325        .layer(from_fn_with_state(
326            Admission {
327                operator: Arc::clone(&state.operator),
328                turns: state.turns.clone(),
329            },
330            authenticate,
331        ))
332        .layer(DefaultBodyLimit::max(BODY_BOUND))
333        .with_state(state);
334    Router::new().nest(VERSION_PREFIX, api)
335}
336
337/// The scheme the credential is presented under.
338const BEARER: &[u8] = b"Bearer ";
339
340/// How much of a request's body this server reads, admitted or refused.
341///
342/// One bound for both: the router's body limit is set from it, so it is what
343/// every extractor reads an admitted body to, and what [`authenticate`] drains
344/// a refused one to — a body the server would have taken is one it drains,
345/// and a larger one is left where it is either way.
346pub const BODY_BOUND: usize = 2 * 1024 * 1024;
347
348/// How long [`authenticate`] waits for a refused request's body to arrive.
349///
350/// A caller that sent a head and then nothing would otherwise hold its refusal
351/// open for as long as it liked; after this the refusal goes out over whatever
352/// arrived, and the connection ends as it did before there was a drain.
353pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
354
355/// Admit a request that presented the operator's credential or a live turn's,
356/// hand every handler who it authenticated as, and refuse every other request
357/// before anything reads it.
358///
359/// Exactly one `Authorization` header, spelled `Bearer ` and then the
360/// credential. Two headers, another scheme, another spelling of this one, and a
361/// credential that is nobody's are all the same refusal, which says what to
362/// present and nothing about what was presented — and, on a server that has no
363/// operator credential yet, names the command that issues one.
364///
365/// The refusal is decided on the head alone, and the body is then drained, up
366/// to [`BODY_BOUND`], before it is answered. Nothing reads what is
367/// drained: a connection closed with a body still unread on it is closed with
368/// a reset rather than an end, and a caller on Windows — where a reset discards
369/// everything received and not yet read — then reads the abort in place of the
370/// `401` that was already on its way. Linux hands over what was queued first,
371/// which is why the same race is only ever seen there.
372pub async fn authenticate(
373    State(admission): State<Admission>,
374    mut request: Request,
375    next: Next,
376) -> Response {
377    let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
378    let admitted = match (presented.next(), presented.next()) {
379        (Some(only), None) => only
380            .as_bytes()
381            .strip_prefix(BEARER)
382            .and_then(|offered| admission.caller(offered)),
383        _ => None,
384    };
385    if let Some(caller) = admitted {
386        request.extensions_mut().insert(caller);
387        return next.run(request).await;
388    }
389    {
390        let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
391            format!(
392                "this server's API requires a credential, presented as `Authorization: Bearer \
393                 <credential>`, and this server has no operator credential yet: run \
394                 `{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
395                 prints into the server's configuration, and restart the service"
396            )
397        } else {
398            format!(
399                "this server's API requires the credential it is configured with, presented as \
400                 `Authorization: Bearer <credential>`. An operator without one runs \
401                 `{CREDENTIAL_ISSUE}`"
402            )
403        };
404        let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
405        refused.headers_mut().insert(
406            header::WWW_AUTHENTICATE,
407            header::HeaderValue::from_static("Bearer"),
408        );
409        // A body past the bound, or one that has not arrived inside
410        // `DRAIN_BOUND`, is left where it is: the refusal is the answer either
411        // way, and what a caller then meets on the connection is its own doing.
412        let _ = tokio::time::timeout(
413            DRAIN_BOUND,
414            axum::body::to_bytes(request.into_body(), BODY_BOUND),
415        )
416        .await;
417        refused
418    }
419}
420
421/// A path beneath the versioned prefix that no operation serves.
422async fn nothing_here() -> Response {
423    refusal(
424        StatusCode::NOT_FOUND,
425        "no operation of this server is served at that path",
426    )
427}
428
429/// The route one declared operation is served by.
430fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
431    if let Effect::Command(spool_command) = operation.effect {
432        let kind = spool_command.action_kind();
433        if operation.path.contains("{spool_id}") {
434            return post(
435                move |state: State<ApiState>,
436                      caller: Extension<Caller>,
437                      Path(spool_id): Path<SpoolId>,
438                      body: Result<Json<Value>, JsonRejection>| async move {
439                    command(kind, state, caller, Some(spool_id), body).await
440                },
441            );
442        }
443        return post(
444            move |state: State<ApiState>,
445                  caller: Extension<Caller>,
446                  body: Result<Json<Value>, JsonRejection>| async move {
447                command(kind, state, caller, None, body).await
448            },
449        );
450    }
451    if let Effect::Recovery(kind) = operation.effect {
452        return post(
453            move |state: State<ApiState>,
454                  caller: Extension<Caller>,
455                  body: Result<Json<Value>, JsonRejection>| async move {
456                recover(kind, state, caller, body).await
457            },
458        );
459    }
460    if let Effect::Mutating(kind) = operation.effect {
461        return post(
462            move |state: State<ApiState>,
463                  caller: Extension<Caller>,
464                  print_id: Path<PrintId>,
465                  body: Result<Json<ActionBody>, JsonRejection>| async move {
466                act(kind, state, caller, print_id, body).await
467            },
468        );
469    }
470    match (operation.name, operation.method) {
471        ("prints", Method::Get) => get(list_and_adopt_prints),
472        ("status", Method::Get) => get(status),
473        ("context", Method::Get) => get(context),
474        ("image", Method::Get) => get(image),
475        ("history", Method::Get) => get(history),
476        ("events", Method::Get) => get(crate::events::events),
477        ("look", Method::Get) => get(look),
478        (crate::operations::PRINTER_LOOK, Method::Get) => get(printer_look),
479        ("manifest_get", Method::Get) => get(manifest_get),
480        ("manifest_set", Method::Put) => put(manifest_set),
481        ("spools", Method::Get) => get(spools),
482        ("spool", Method::Get) => get(spool),
483        ("printer_history", Method::Get) => get(printer_history),
484        ("preflight", Method::Get) => get(preflight),
485        (crate::operations::RECOVERY_STATUS, Method::Get) => get(recover_status),
486        (name, method) => panic!(
487            "the operation `{name}` is declared as {method} and this router serves no such route"
488        ),
489    }
490}
491
492/// One answer, rendered as JSON under the media type every operation answers in.
493pub(crate) fn answer<T: printobserver_types::serde::Serialize>(
494    status: StatusCode,
495    body: &T,
496) -> Response {
497    let rendered = match printobserver_types::serde_json::to_vec(body) {
498        Ok(bytes) => bytes,
499        Err(error) => {
500            return (
501                StatusCode::INTERNAL_SERVER_ERROR,
502                [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
503                format!("{{\"error\":\"{error}\"}}"),
504            )
505                .into_response();
506        }
507    };
508    (
509        status,
510        [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
511        rendered,
512    )
513        .into_response()
514}
515
516/// One refusal, rendered as JSON under the same media type.
517pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
518    answer(status, &ErrorAnswer::saying(detail))
519}
520
521/// The status a store refusal is answered under.
522pub(crate) fn store_status(error: &StoreError) -> StatusCode {
523    match error {
524        StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
525        StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
526            StatusCode::BAD_REQUEST
527        }
528        StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
529    }
530}
531
532/// The status a core refusal is answered under.
533fn core_status(error: &CoreError) -> StatusCode {
534    match error {
535        CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
536        CoreError::Store(store) => store_status(store),
537        _ => StatusCode::INTERNAL_SERVER_ERROR,
538    }
539}
540
541/// Ask for one action of the vocabulary against one print.
542///
543/// Who may ask is settled before the policy is: a turn's credential reaches
544/// no start and no print but its own — whatever the body says, so those two
545/// answer `403` ahead of any rejection of the body itself — and the claimed
546/// actor is held to the caller. A
547/// request refused here is decided on by nothing and recorded nowhere.
548async fn act(
549    kind: ActionKind,
550    State(state): State<ApiState>,
551    Extension(caller): Extension<Caller>,
552    Path(print_id): Path<PrintId>,
553    body: Result<Json<ActionBody>, JsonRejection>,
554) -> Response {
555    if kind == ActionKind::StartPrint
556        && let Some(refused) =
557            operator_refused(&caller, &crate::operations::command_for("start_print"))
558    {
559        return refused;
560    }
561    if let Some(refused) = scope_refused(&caller, print_id) {
562        return refused;
563    }
564    let body = match body {
565        Ok(Json(body)) => body,
566        Err(rejected) => return rejected.into_response(),
567    };
568    if let Some(refused) = claim_refused(&caller, &body.actor) {
569        return refused;
570    }
571    let action = match body.into_action(kind) {
572        Ok(action) => action,
573        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
574    };
575    let outcome = match state.supervisor.request_action(print_id, action).await {
576        Ok(outcome) => outcome,
577        Err(error) => return refusal(core_status(&error), error),
578    };
579    let printer_refusal = match &outcome.record.outcome {
580        Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
581        _ => None,
582    };
583    let status = match outcome.record.decision {
584        PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
585        // The policy accepted it and the machine did not. That is a request
586        // that was made and refused rather than one that never happened, so
587        // the record and the printer's own words are the answer.
588        PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
589        // The rejection itself is the answer: its reason, the value asked for
590        // and the range allowed are what let a caller ask again correctly.
591        PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
592    };
593    answer(
594        status,
595        &ActionAnswer {
596            record: outcome.record,
597            intervention: outcome.intervention,
598            printer_refusal,
599        },
600    )
601}
602
603/// Ask the spool ledger for one command.
604///
605/// The claimed actor is held to the caller before anything else of the body is
606/// read, and a body with no reason is refused before the domain is asked —
607/// so a request refused here is recorded nowhere. Whether the actor may ask at
608/// all is the envelope's grant, which the domain rules on and records like
609/// every refusal: a supervision turn's agent is refused there, under the
610/// default grants, rather than here.
611async fn command(
612    kind: ActionKind,
613    State(state): State<ApiState>,
614    Extension(caller): Extension<Caller>,
615    spool_id: Option<SpoolId>,
616    body: Result<Json<Value>, JsonRejection>,
617) -> Response {
618    let body = match body {
619        Ok(Json(body)) => body,
620        Err(rejected) => return rejected.into_response(),
621    };
622    let Some(fields) = body.as_object() else {
623        return refusal(
624            StatusCode::BAD_REQUEST,
625            "a spool command's body is a document of its fields",
626        );
627    };
628    let actor = match claimed_actor(fields) {
629        Ok(actor) => actor,
630        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
631    };
632    if let Some(refused) = claim_refused(&caller, &actor) {
633        return refused;
634    }
635    let asked = match spool_command_of(kind, spool_id, body) {
636        Ok(asked) => asked,
637        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
638    };
639    let outcome = match state.supervisor.request_spool_command(asked).await {
640        Ok(outcome) => outcome,
641        Err(error) => return refusal(core_status(&error), error),
642    };
643    let status = match outcome.decision {
644        PolicyDecision::Accepted => StatusCode::OK,
645        // The refusal is the answer, exactly as a print action's is.
646        PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
647    };
648    answer(
649        status,
650        &SpoolCommandAnswer {
651            decision: outcome.decision,
652            spool: outcome.spool,
653            events: outcome.events,
654        },
655    )
656}
657
658/// Ask the printer for one recovery action.
659///
660/// The body is held to the action's own fields, a reason and an actor before
661/// anything is decided, and the claimed actor to the caller — so a request
662/// refused here is recorded nowhere and reaches no printer. Whether the actor
663/// may ask, and whether the printer is in a state the action is safe from, is
664/// the supervision core's to rule on and record.
665async fn recover(
666    kind: RecoveryActionKind,
667    State(state): State<ApiState>,
668    Extension(caller): Extension<Caller>,
669    body: Result<Json<Value>, JsonRejection>,
670) -> Response {
671    let body = match body {
672        Ok(Json(body)) => body,
673        Err(rejected) => return rejected.into_response(),
674    };
675    if let Some(fields) = body.as_object() {
676        let actor = match claimed_actor(fields) {
677            Ok(actor) => actor,
678            Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
679        };
680        if let Some(refused) = claim_refused(&caller, &actor) {
681            return refused;
682        }
683    }
684    let (action, actor, reason) = match recovery_of(kind, body) {
685        Ok(asked) => asked,
686        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
687    };
688    let issued = match state
689        .supervisor
690        .request_recovery(action.clone(), actor, reason)
691        .await
692    {
693        Ok(issued) => issued,
694        Err(error) => return refusal(core_status(&error), error),
695    };
696    let config = state.supervisor.config().recovery;
697    let status = match &issued.decision {
698        RecoveryDecision::Executed(ExecutionOutcome::Succeeded) => StatusCode::OK,
699        // The printer was asked and refused: a request that was made rather
700        // than one that never happened, answered with the printer's words.
701        RecoveryDecision::Executed(ExecutionOutcome::Failed { .. }) => StatusCode::BAD_GATEWAY,
702        // The refusal is the answer, as a print action's is.
703        RecoveryDecision::Rejected(_) => StatusCode::CONFLICT,
704    };
705    answer(
706        status,
707        &RecoveryAnswer {
708            detail: recovery_detail(&action, &issued.decision, config.as_ref()),
709            action,
710            decision: issued.decision,
711            events: vec![issued.requested, issued.settled],
712        },
713    )
714}
715
716/// Everything a recovery is checked against now, and what each action would
717/// meet for the caller.
718async fn recover_status(
719    State(state): State<ApiState>,
720    Extension(caller): Extension<Caller>,
721) -> Response {
722    let class = match caller {
723        Caller::Operator => ActorClass::Operator,
724        Caller::Turn(_) => ActorClass::Agent,
725    };
726    match state.supervisor.recovery_status(class).await {
727        Ok(status) => answer(StatusCode::OK, &status),
728        Err(error) => refusal(core_status(&error), error),
729    }
730}
731
732/// Every spool, beside one line each and the charges a tool is holding.
733async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
734    let listed = match state
735        .supervisor
736        .spools(params.include_retired.unwrap_or(false))
737        .await
738    {
739        Ok(listed) => listed,
740        Err(error) => return refusal(core_status(&error), error),
741    };
742    match state.supervisor.pending_charges(None).await {
743        Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
744        Err(error) => refusal(core_status(&error), error),
745    }
746}
747
748/// One spool, and the newest of the printer's own events that name it.
749async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
750    let found = match state.supervisor.spool(spool_id).await {
751        Ok(Some(found)) => found,
752        Ok(None) => {
753            return refusal(
754                StatusCode::NOT_FOUND,
755                format!("there is no spool {spool_id}"),
756            );
757        }
758        Err(error) => return refusal(core_status(&error), error),
759    };
760    let query = TimelineQuery {
761        spool_id: Some(spool_id),
762        limit: Some(SPOOL_RECENT_EVENTS),
763        ..every_timeline_kind()
764    };
765    match state.supervisor.timeline(query).await {
766        Ok(recent) => answer(
767            StatusCode::OK,
768            &SpoolAnswer {
769                spool: found,
770                recent,
771            },
772        ),
773        Err(error) => refusal(core_status(&error), error),
774    }
775}
776
777/// The printer history unfiltered: every timeline kind, the default window.
778const fn every_timeline_kind() -> TimelineQuery {
779    TimelineQuery {
780        kinds: Vec::new(),
781        since: None,
782        until: None,
783        spool_id: None,
784        before: None,
785        limit: None,
786    }
787}
788
789/// One value of a printer history read, refused naming it when it is not one.
790fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
791where
792    T::Err: core::fmt::Display,
793{
794    text.parse()
795        .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
796}
797
798/// The printer history query a request's values make.
799///
800/// `kinds` may be given any number of times, each one kind; every other value
801/// at most once. A value this read does not take is refused naming it rather
802/// than ignored, because a filter that was quietly dropped answers more than
803/// was asked for.
804fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
805    let mut query = every_timeline_kind();
806    let mut seen: Vec<&str> = Vec::new();
807    for (name, text) in asked {
808        if name != "kinds" {
809            if seen.contains(&name.as_str()) {
810                return Err(format!(
811                    "`{name}` was given more than once, and this read takes one"
812                ));
813            }
814            seen.push(name);
815        }
816        match name.as_str() {
817            "kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
818            "since" => query.since = Some(read_one::<Timestamp>(name, text)?),
819            "until" => query.until = Some(read_one::<Timestamp>(name, text)?),
820            "spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
821            "before" => query.before = Some(read_one::<EventId>(name, text)?),
822            "limit" => query.limit = Some(read_one::<u32>(name, text)?),
823            other => return Err(format!("the printer history takes no `{other}`")),
824        }
825    }
826    Ok(query)
827}
828
829/// One page of the printer's own history, newest first, and the cursor for
830/// the page after it when there is one.
831///
832/// The cursor is answered only when an older event exists, so a caller paging
833/// by it stops at the last page rather than one empty page after it.
834async fn printer_history(
835    State(state): State<ApiState>,
836    Query(asked): Query<Vec<(String, String)>>,
837) -> Response {
838    let query = match timeline_query(&asked) {
839        Ok(query) => query,
840        Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
841    };
842    let limit = match query.resolved_limit() {
843        Ok(limit) => limit,
844        Err(error) => return refusal(store_status(&error), error),
845    };
846    let events = match state.supervisor.timeline(query.clone()).await {
847        Ok(events) => events,
848        Err(error) => return refusal(core_status(&error), error),
849    };
850    let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
851    let next = match events.last() {
852        Some(last) if full => {
853            let older = TimelineQuery {
854                before: Some(last.id),
855                limit: Some(1),
856                ..query
857            };
858            match state.supervisor.timeline(older).await {
859                Ok(older) if older.is_empty() => None,
860                Ok(_) => Some(last.id),
861                Err(error) => return refusal(core_status(&error), error),
862            }
863        }
864        _ => None,
865    };
866    answer(StatusCode::OK, &TimelineAnswer { events, next })
867}
868
869/// Whether the spools loaded hold enough for one file, the file was sliced
870/// for their material and, when a sheet is given, that sheet suits it — read
871/// now.
872async fn preflight(
873    State(state): State<ApiState>,
874    Query(params): Query<PreflightParams>,
875) -> Response {
876    let Some(named) = params.file_name else {
877        return refusal(
878            StatusCode::BAD_REQUEST,
879            "a filament check needs `file_name`, and this request carries none",
880        );
881    };
882    let file_name = match FileName::new(&named) {
883        Ok(file_name) => file_name,
884        Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
885    };
886    let sheet = match params.sheet.map(SheetId::try_from).transpose() {
887        Ok(sheet) => sheet,
888        Err(why) => return refusal(StatusCode::BAD_REQUEST, why),
889    };
890    match state.supervisor.preflight(&file_name, sheet.as_ref()).await {
891        Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
892        Err(error) => refusal(core_status(&error), error),
893    }
894}
895
896/// List every print, and name the one the printer's job belongs to.
897///
898/// Reading this adopts that job when no open print carries its file name, which
899/// is how a print started at the printer gets an identifier before anything has
900/// reported on it. A printer that cannot be read still answers the stored
901/// prints, with nothing active.
902async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
903    match state.supervisor.list_and_adopt_prints().await {
904        Ok(listing) => answer(
905            StatusCode::OK,
906            &PrintsAnswer {
907                prints: listing.prints,
908                active: listing.active,
909            },
910        ),
911        Err(error) => refusal(core_status(&error), error),
912    }
913}
914
915/// Read one print's status.
916///
917/// The print answered is the context's, read after the context read settled
918/// the open prints against the printer's job — so a status that finds the job
919/// over answers the print it closed rather than the one it found.
920async fn status(
921    State(state): State<ApiState>,
922    Extension(caller): Extension<Caller>,
923    Path(print_id): Path<PrintId>,
924) -> Response {
925    if let Some(refused) = scope_refused(&caller, print_id) {
926        return refused;
927    }
928    match state.prints.print(print_id).await {
929        Ok(Some(_)) => {}
930        Ok(None) => {
931            return refusal(
932                StatusCode::NOT_FOUND,
933                format!("there is no print {print_id}"),
934            );
935        }
936        Err(error) => return refusal(store_status(&error), error),
937    }
938    let context = match context_of(&state, print_id).await {
939        Ok(context) => context,
940        Err(refused) => return refused,
941    };
942    let session = match state.sessions.session(print_id).await {
943        Ok(session) => session,
944        Err(error) => return refusal(store_status(&error), error),
945    };
946    answer(
947        StatusCode::OK,
948        &StatusAnswer {
949            print: context.print,
950            printer: context.printer,
951            job: context.job,
952            session,
953            interventions: context.interventions,
954            detector: context.detector,
955        },
956    )
957}
958
959/// One print's context, read off the request's own thread.
960///
961/// The first read of a print's context after it starts reads the print's
962/// whole G-code to index it, through a printer port that blocks while it
963/// reads, so it is taken on a blocking thread, as a look is: a request that
964/// held an asynchronous worker for the length of a download would hold every
965/// task queued behind it there too.
966async fn context_of(
967    state: &ApiState,
968    print_id: PrintId,
969) -> Result<printobserver_core::PrintContext, Response> {
970    let supervisor = Arc::clone(&state.supervisor);
971    let read = tokio::task::spawn_blocking(move || {
972        printobserver_core::block_on(supervisor.context(print_id))
973    })
974    .await;
975    match read {
976        Ok(Ok(context)) => Ok(context),
977        Ok(Err(error)) => Err(refusal(core_status(&error), error)),
978        Err(error) => Err(refusal(StatusCode::INTERNAL_SERVER_ERROR, error)),
979    }
980}
981
982/// Read everything a supervision turn is given about one print, with the
983/// latest image materialized.
984///
985/// The path is looked up through the same store read the image operation
986/// answers from, so the two operations cannot disagree about where an image
987/// is. An image whose record is intact and whose file is gone answers no path,
988/// which is what the caller's own missing-file failure is about.
989async fn context(
990    State(state): State<ApiState>,
991    Extension(caller): Extension<Caller>,
992    Path(print_id): Path<PrintId>,
993    Query(params): Query<ContextParams>,
994) -> Response {
995    if let Some(refused) = scope_refused(&caller, print_id) {
996        return refused;
997    }
998    // Off the request's own thread, for the reason `context_of` gives.
999    let supervisor = Arc::clone(&state.supervisor);
1000    let since = params.since;
1001    let read = tokio::task::spawn_blocking(move || {
1002        printobserver_core::block_on(supervisor.agent_context(print_id, since))
1003    })
1004    .await;
1005    let context = match read {
1006        Ok(Ok(read)) => read,
1007        Ok(Err(error)) => return refusal(core_status(&error), error),
1008        Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1009    };
1010    let mut image_path = None;
1011    if let Some(latest) = context.latest_image.as_ref() {
1012        match state.images.image(latest.id).await {
1013            Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
1014            Err(error) => return refusal(store_status(&error), error),
1015        }
1016    }
1017    answer(
1018        StatusCode::OK,
1019        &ContextAnswer {
1020            context,
1021            image_path,
1022        },
1023    )
1024}
1025
1026/// Take a fresh look at one print.
1027///
1028/// A wait longer than the supervisor allows is refused rather than shortened,
1029/// and a print nothing is held under is refused before any wait. The wait
1030/// itself runs on a blocking thread, exactly as a turn does, so that a minute
1031/// and a half of waiting holds no asynchronous worker the agent's own requests
1032/// are answered on.
1033async fn look(
1034    State(state): State<ApiState>,
1035    Extension(caller): Extension<Caller>,
1036    Path(print_id): Path<PrintId>,
1037    Query(params): Query<LookParams>,
1038) -> Response {
1039    if let Some(refused) = scope_refused(&caller, print_id) {
1040        return refused;
1041    }
1042    let wait_s = params.wait_s.unwrap_or(0);
1043    if wait_s > MAX_LOOK_WAIT_S {
1044        return refusal(
1045            StatusCode::BAD_REQUEST,
1046            format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1047        );
1048    }
1049    match state.prints.print(print_id).await {
1050        Ok(Some(_)) => {}
1051        Ok(None) => {
1052            return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
1053        }
1054        Err(error) => return refusal(store_status(&error), error),
1055    }
1056    let supervisor = Arc::clone(&state.supervisor);
1057    let taken = tokio::task::spawn_blocking(move || {
1058        let (arrived, waited) =
1059            supervisor.await_look_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
1060        printobserver_core::block_on(supervisor.take_look(print_id, waited, arrived))
1061    })
1062    .await;
1063    match taken {
1064        Ok(Ok(look)) => answer(StatusCode::OK, &look),
1065        Ok(Err(error)) => refusal(core_status(&error), error),
1066        Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1067    }
1068}
1069
1070/// Take a fresh look at the printer, with no print named.
1071///
1072/// The look and its frame belong to no print, and the wait is a plain wait:
1073/// nothing any print's agent is owed can end it or be taken by it. A turn's
1074/// credential reaches its own print alone, so this is the operator's; a wait
1075/// longer than the supervisor allows is refused rather than shortened.
1076async fn printer_look(
1077    State(state): State<ApiState>,
1078    Extension(caller): Extension<Caller>,
1079    Query(params): Query<LookParams>,
1080) -> Response {
1081    if let Some(refused) = printless_refused(&caller, "a look at the printer with no print named") {
1082        return refused;
1083    }
1084    let wait_s = params.wait_s.unwrap_or(0);
1085    if wait_s > MAX_LOOK_WAIT_S {
1086        return refusal(
1087            StatusCode::BAD_REQUEST,
1088            format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1089        );
1090    }
1091    let waited = Duration::from_secs(u64::from(wait_s));
1092    tokio::time::sleep(waited).await;
1093    match state.supervisor.take_printer_look(waited).await {
1094        Ok(look) => answer(StatusCode::OK, &look),
1095        Err(error) => refusal(core_status(&error), error),
1096    }
1097}
1098
1099/// Materialize one image: its record, and the absolute path its bytes are at.
1100///
1101/// An image belongs to one print, or to none when it is a frame taken of the
1102/// printer with no print named. A turn's credential reaches the images of its
1103/// own print alone, so a frame of no print is the operator's.
1104async fn image(
1105    State(state): State<ApiState>,
1106    Extension(caller): Extension<Caller>,
1107    Path(image_id): Path<ImageId>,
1108) -> Response {
1109    match state.images.image(image_id).await {
1110        Ok(lookup) => {
1111            let belongs_to = match &lookup {
1112                printobserver_core::ImageLookup::Found { record, .. }
1113                | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
1114            };
1115            let refused = match belongs_to {
1116                Some(print_id) => scope_refused(&caller, print_id),
1117                None => {
1118                    printless_refused(&caller, "a frame of the printer that belongs to no print")
1119                }
1120            };
1121            if let Some(refused) = refused {
1122                return refused;
1123            }
1124            answer(StatusCode::OK, &ImageAnswer::from(lookup))
1125        }
1126        Err(error) => refusal(store_status(&error), error),
1127    }
1128}
1129
1130/// Read one print's events, newest first.
1131async fn history(
1132    State(state): State<ApiState>,
1133    Extension(caller): Extension<Caller>,
1134    Path(print_id): Path<PrintId>,
1135    Query(params): Query<HistoryParams>,
1136) -> Response {
1137    if let Some(refused) = scope_refused(&caller, print_id) {
1138        return refused;
1139    }
1140    let query = HistoryQuery {
1141        print_id,
1142        kinds: Vec::new(),
1143        since: None,
1144        until: None,
1145        limit: params.limit,
1146    };
1147    match state.events.history(query).await {
1148        Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
1149        Err(error) => refusal(store_status(&error), error),
1150    }
1151}
1152
1153/// Read one print's manifest.
1154async fn manifest_get(
1155    State(state): State<ApiState>,
1156    Extension(caller): Extension<Caller>,
1157    Path(print_id): Path<PrintId>,
1158) -> Response {
1159    if let Some(refused) = scope_refused(&caller, print_id) {
1160        return refused;
1161    }
1162    let manifest = match state.prints.manifest(print_id).await {
1163        Ok(manifest) => manifest,
1164        Err(error) => return refusal(store_status(&error), error),
1165    };
1166    let narrowings = match state.prints.print(print_id).await {
1167        Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
1168        Err(error) => return refusal(store_status(&error), error),
1169    };
1170    answer(
1171        StatusCode::OK,
1172        &ManifestAnswer {
1173            manifest,
1174            narrowings,
1175        },
1176    )
1177}
1178
1179/// Write one print's manifest.
1180///
1181/// A manifest narrows what any actor may ask for, so replacing one is a change
1182/// to the bounds a print runs under and carries a reason like every other
1183/// change. The reason is ruled on **before** anything is written, so a request
1184/// without one leaves the stored manifest and the print's narrowings as they
1185/// were — and every range it asked wider than the envelope allows is recorded
1186/// on the print, exactly as it is when a start attaches one.
1187async fn manifest_set(
1188    State(state): State<ApiState>,
1189    Extension(caller): Extension<Caller>,
1190    Path(print_id): Path<PrintId>,
1191    body: Result<Json<ManifestBody>, JsonRejection>,
1192) -> Response {
1193    if let Some(refused) =
1194        operator_refused(&caller, &crate::operations::command_for("manifest_set"))
1195    {
1196        return refused;
1197    }
1198    let body = match body {
1199        Ok(Json(body)) => body,
1200        Err(rejected) => return rejected.into_response(),
1201    };
1202    if let Err(rejected) = body.reason() {
1203        return refusal(StatusCode::BAD_REQUEST, rejected);
1204    }
1205    let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
1206    if let Err(error) = state
1207        .prints
1208        .put_manifest(print_id, body.manifest.clone())
1209        .await
1210    {
1211        return refusal(store_status(&error), error);
1212    }
1213    for narrowing in narrowed.narrowings.clone() {
1214        if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
1215            return refusal(store_status(&error), error);
1216        }
1217    }
1218    answer(
1219        StatusCode::OK,
1220        &ManifestAnswer {
1221            manifest: Some(body.manifest),
1222            narrowings: narrowed.narrowings,
1223        },
1224    )
1225}
1226
1227#[cfg(test)]
1228mod tests {
1229    use axum::http::StatusCode;
1230    use printobserver_core::CoreError;
1231    use printobserver_core::store::StoreError;
1232
1233    use super::{core_status, store_status};
1234
1235    /// Every refusal the store can make is answered under a status a caller can
1236    /// act on: what it asked for, what is not there, and what went wrong here.
1237    #[test]
1238    fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
1239        for (error, expected) in [
1240            (
1241                StoreError::NotFound {
1242                    what: "print".to_owned(),
1243                },
1244                StatusCode::NOT_FOUND,
1245            ),
1246            (
1247                StoreError::LimitRefused {
1248                    limit: 1_000,
1249                    asked_for: 2_000,
1250                },
1251                StatusCode::BAD_REQUEST,
1252            ),
1253            (
1254                StoreError::ConstraintRefused {
1255                    constraint: "actions.decision".to_owned(),
1256                },
1257                StatusCode::BAD_REQUEST,
1258            ),
1259            (
1260                StoreError::Database {
1261                    detail: "the disk is full".to_owned(),
1262                },
1263                StatusCode::INTERNAL_SERVER_ERROR,
1264            ),
1265            (
1266                StoreError::Io {
1267                    detail: "the disk is full".to_owned(),
1268                },
1269                StatusCode::INTERNAL_SERVER_ERROR,
1270            ),
1271        ] {
1272            assert_eq!(store_status(&error), expected, "{error}");
1273        }
1274    }
1275
1276    /// A print nothing holds is not found; a port that failed is this server's
1277    /// own failure rather than the caller's.
1278    #[test]
1279    fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
1280        assert_eq!(
1281            core_status(&CoreError::NoSuchPrint {
1282                print_id: printobserver_types::PrintId::new(),
1283            }),
1284            StatusCode::NOT_FOUND
1285        );
1286        assert_eq!(
1287            core_status(&CoreError::Store(StoreError::NotFound {
1288                what: "print".to_owned(),
1289            })),
1290            StatusCode::NOT_FOUND
1291        );
1292        assert_eq!(
1293            core_status(&CoreError::Unrepresentable {
1294                detail: "an instant".to_owned(),
1295            }),
1296            StatusCode::INTERNAL_SERVER_ERROR
1297        );
1298    }
1299}