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