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::{EventBody, 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, BedClearAnswer, BedClearBody, ContextAnswer, ErrorAnswer,
91    HistoryAnswer, ImageAnswer, ManifestAnswer, ManifestBody, PreflightAnswer, PrintsAnswer,
92    RecoveryAnswer, SpoolAnswer, SpoolCommandAnswer, SpoolsAnswer, StatusAnswer, TimelineAnswer,
93    claimed_actor, reason_of, recovery_of, 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    /// What makes every check's image and judges every frame of a print,
119    /// which a recheck of a print's camera asks directly; none where nothing
120    /// was installed.
121    pub check_images: Option<Arc<crate::check_images::PanelImages>>,
122}
123
124/// Who one request authenticated as.
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub enum Caller {
127    /// The operator, by the credential the operator's verifier admits.
128    Operator,
129    /// One supervision turn's run: the agent, in one session, on one print.
130    Turn(TurnBinding),
131}
132
133impl Caller {
134    /// This caller, as a refusal names it.
135    fn named(&self) -> String {
136        match self {
137            Self::Operator => "the operator".to_owned(),
138            Self::Turn(binding) => format!(
139                "the agent in session `{}` on print {}",
140                binding.session_name(),
141                binding.print_id()
142            ),
143        }
144    }
145}
146
147/// One claimed actor, as a refusal names it.
148fn claimed(actor: &Actor) -> String {
149    match actor {
150        Actor::Operator => "the operator".to_owned(),
151        Actor::System => "the system".to_owned(),
152        Actor::Agent { session_name } => format!("the agent in session `{session_name}`"),
153    }
154}
155
156/// Refuse a claimed actor that is not the caller, before anything is decided.
157///
158/// The system is claimed by nobody: its actions are the server's own, and no
159/// credential this server admits is the server.
160fn claim_refused(caller: &Caller, actor: &Actor) -> Option<Response> {
161    let held = match (caller, actor) {
162        (Caller::Operator, Actor::Operator) => true,
163        (Caller::Turn(binding), Actor::Agent { session_name }) => {
164            *session_name == binding.session_name()
165        }
166        _ => false,
167    };
168    if held {
169        return None;
170    }
171    let why = if matches!(actor, Actor::System) {
172        "no credential may claim the system, whose actions are the server's own"
173    } else {
174        "a request acts as the identity its credential authenticated, and no other"
175    };
176    Some(refusal(
177        StatusCode::FORBIDDEN,
178        format!(
179            "this request authenticated as {} and claims to be {}: {why}",
180            caller.named(),
181            claimed(actor)
182        ),
183    ))
184}
185
186/// Refuse a turn's request about any print but its own.
187pub(crate) fn scope_refused(caller: &Caller, print_id: PrintId) -> Option<Response> {
188    match caller {
189        Caller::Turn(binding) if binding.print_id() != print_id => Some(refusal(
190            StatusCode::FORBIDDEN,
191            format!(
192                "this request authenticated as {} and names print {print_id}: a supervision \
193                 turn's credential reaches its own print alone",
194                caller.named()
195            ),
196        )),
197        _ => None,
198    }
199}
200
201/// Refuse a turn's request for something that belongs to no print: a turn's
202/// credential reaches its own print alone, and what belongs to none is the
203/// operator's.
204fn printless_refused(caller: &Caller, what: &str) -> Option<Response> {
205    match caller {
206        Caller::Turn(_) => Some(refusal(
207            StatusCode::FORBIDDEN,
208            format!(
209                "this request authenticated as {} and asks for {what}: a supervision turn's \
210                 credential reaches its own print alone",
211                caller.named()
212            ),
213        )),
214        Caller::Operator => None,
215    }
216}
217
218/// Refuse a turn's request for a write that is not about its running print:
219/// starting a print, and replacing a manifest, are the operator's alone.
220fn operator_refused(caller: &Caller, command: &str) -> Option<Response> {
221    match caller {
222        Caller::Turn(_) => Some(refusal(
223            StatusCode::FORBIDDEN,
224            format!(
225                "this request authenticated as {} and asks for `{command}`, which is the \
226                 operator's alone: a supervision turn's credential does not reach it",
227                caller.named()
228            ),
229        )),
230        Caller::Operator => None,
231    }
232}
233
234/// Refuse a turn's acknowledgement before the turn has taken a look.
235///
236/// The frames a turn's context names are already old when it reads them, so
237/// what a turn writes down of its event is judged from a look it took — or
238/// from the image it was handed, which counts as its look, because a turn
239/// handed one is allowed no other; the operator, who is not a turn, is held to
240/// nothing here.
241fn unlooked_refused(
242    turns: &TurnCredentials,
243    caller: &Caller,
244    print_id: PrintId,
245) -> Option<Response> {
246    match caller {
247        Caller::Turn(binding) if !turns.has_looked(binding) => Some(refusal(
248            StatusCode::FORBIDDEN,
249            format!(
250                "this request authenticated as {} and acknowledges an event before the turn \
251                 has taken a look: run `printobserver look --print-id {print_id}`, open the \
252                 frames it names, and acknowledge what they show",
253                caller.named()
254            ),
255        )),
256        _ => None,
257    }
258}
259
260/// What [`authenticate`] checks a presented credential against.
261#[derive(Clone)]
262pub struct Admission {
263    /// The operator's.
264    operator: Arc<OperatorCredential>,
265    /// The live turns'.
266    turns: TurnCredentials,
267}
268
269impl Admission {
270    /// Who a presented credential authenticates as, when it is anybody.
271    fn caller(&self, presented: &[u8]) -> Option<Caller> {
272        if let Some(binding) = self.turns.admit(presented) {
273            return Some(Caller::Turn(binding));
274        }
275        self.operator.admits(presented).then_some(Caller::Operator)
276    }
277}
278
279impl core::fmt::Debug for ApiState {
280    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
281        formatter.debug_struct("ApiState").finish_non_exhaustive()
282    }
283}
284
285/// How many events a history read asks for, when it asks for a number.
286#[derive(Debug, Clone, Deserialize)]
287#[serde(crate = "printobserver_types::serde")]
288pub struct HistoryParams {
289    /// The limit asked for; absent takes the port's own default window.
290    #[serde(default)]
291    pub limit: Option<u32>,
292}
293
294/// The event a context read is asked `since`: only the events newer than it
295/// are answered, because the caller has read the rest.
296#[derive(Debug, Clone, Deserialize)]
297#[serde(crate = "printobserver_types::serde")]
298pub struct ContextParams {
299    /// The newest event the caller has read; absent answers the recent window.
300    #[serde(default)]
301    pub since: Option<printobserver_types::EventId>,
302}
303
304/// How long a look asks to wait for something to arrive, in whole seconds.
305#[derive(Debug, Clone, Deserialize)]
306#[serde(crate = "printobserver_types::serde")]
307pub struct LookParams {
308    /// The wait asked for; absent looks at once.
309    #[serde(default)]
310    pub wait_s: Option<u32>,
311}
312
313/// Whether a spools read asks for the retired ones too.
314#[derive(Debug, Clone, Deserialize)]
315#[serde(crate = "printobserver_types::serde")]
316pub struct SpoolsParams {
317    /// Asked for; absent, the retired spools are left out.
318    #[serde(default)]
319    pub include_retired: Option<bool>,
320}
321
322/// The file a filament check is about, and the sheet it would go down on.
323#[derive(Debug, Clone, Deserialize)]
324#[serde(crate = "printobserver_types::serde")]
325pub struct PreflightParams {
326    /// The file, as the printer names it.
327    #[serde(default)]
328    pub file_name: Option<String>,
329    /// The build sheet the sheet check is read against; absent, the check
330    /// reports no sheet result, and a blank one is refused.
331    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
332    #[serde(default)]
333    pub sheet: Option<String>,
334}
335
336/// How many of a spool's own events its read carries, newest first.
337pub const SPOOL_RECENT_EVENTS: u32 = 20;
338
339/// Every public operation, beneath the one versioned prefix.
340///
341/// # Panics
342///
343/// Panics when [`OPERATIONS`] declares an entry this function has no route for,
344/// which is a declaration and a router that have come apart — the one state
345/// this server must not come up in quietly.
346pub fn router(state: ApiState) -> Router {
347    let mut api = Router::new();
348    for operation in OPERATIONS {
349        api = api.route(operation.path, route_for(&operation));
350    }
351    // The layer is added after every route and the fallback, which is what
352    // puts all of them behind it.
353    let api = api
354        .fallback(nothing_here)
355        .layer(from_fn_with_state(
356            Admission {
357                operator: Arc::clone(&state.operator),
358                turns: state.turns.clone(),
359            },
360            authenticate,
361        ))
362        .layer(DefaultBodyLimit::max(BODY_BOUND))
363        .with_state(state);
364    Router::new().nest(VERSION_PREFIX, api)
365}
366
367/// The scheme the credential is presented under.
368const BEARER: &[u8] = b"Bearer ";
369
370/// How much of a request's body this server reads, admitted or refused.
371///
372/// One bound for both: the router's body limit is set from it, so it is what
373/// every extractor reads an admitted body to, and what [`authenticate`] drains
374/// a refused one to — a body the server would have taken is one it drains,
375/// and a larger one is left where it is either way.
376pub const BODY_BOUND: usize = 2 * 1024 * 1024;
377
378/// How long [`authenticate`] waits for a refused request's body to arrive.
379///
380/// A caller that sent a head and then nothing would otherwise hold its refusal
381/// open for as long as it liked; after this the refusal goes out over whatever
382/// arrived, and the connection ends as it did before there was a drain.
383pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
384
385/// Admit a request that presented the operator's credential or a live turn's,
386/// hand every handler who it authenticated as, and refuse every other request
387/// before anything reads it.
388///
389/// Exactly one `Authorization` header, spelled `Bearer ` and then the
390/// credential. Two headers, another scheme, another spelling of this one, and a
391/// credential that is nobody's are all the same refusal, which says what to
392/// present and nothing about what was presented — and, on a server that has no
393/// operator credential yet, names the command that issues one.
394///
395/// The refusal is decided on the head alone, and the body is then drained, up
396/// to [`BODY_BOUND`], before it is answered. Nothing reads what is
397/// drained: a connection closed with a body still unread on it is closed with
398/// a reset rather than an end, and a caller on Windows — where a reset discards
399/// everything received and not yet read — then reads the abort in place of the
400/// `401` that was already on its way. Linux hands over what was queued first,
401/// which is why the same race is only ever seen there.
402pub async fn authenticate(
403    State(admission): State<Admission>,
404    mut request: Request,
405    next: Next,
406) -> Response {
407    let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
408    let admitted = match (presented.next(), presented.next()) {
409        (Some(only), None) => only
410            .as_bytes()
411            .strip_prefix(BEARER)
412            .and_then(|offered| admission.caller(offered)),
413        _ => None,
414    };
415    if let Some(caller) = admitted {
416        request.extensions_mut().insert(caller);
417        return next.run(request).await;
418    }
419    {
420        let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
421            format!(
422                "this server's API requires a credential, presented as `Authorization: Bearer \
423                 <credential>`, and this server has no operator credential yet: run \
424                 `{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
425                 prints into the server's configuration, and restart the service"
426            )
427        } else {
428            format!(
429                "this server's API requires the credential it is configured with, presented as \
430                 `Authorization: Bearer <credential>`. An operator without one runs \
431                 `{CREDENTIAL_ISSUE}`"
432            )
433        };
434        let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
435        refused.headers_mut().insert(
436            header::WWW_AUTHENTICATE,
437            header::HeaderValue::from_static("Bearer"),
438        );
439        // A body past the bound, or one that has not arrived inside
440        // `DRAIN_BOUND`, is left where it is: the refusal is the answer either
441        // way, and what a caller then meets on the connection is its own doing.
442        let _ = tokio::time::timeout(
443            DRAIN_BOUND,
444            axum::body::to_bytes(request.into_body(), BODY_BOUND),
445        )
446        .await;
447        refused
448    }
449}
450
451/// A path beneath the versioned prefix that no operation serves.
452async fn nothing_here() -> Response {
453    refusal(
454        StatusCode::NOT_FOUND,
455        "no operation of this server is served at that path",
456    )
457}
458
459/// The route one declared operation is served by.
460fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
461    if let Effect::Command(spool_command) = operation.effect {
462        let kind = spool_command.action_kind();
463        if operation.path.contains("{spool_id}") {
464            return post(
465                move |state: State<ApiState>,
466                      caller: Extension<Caller>,
467                      Path(spool_id): Path<SpoolId>,
468                      body: Result<Json<Value>, JsonRejection>| async move {
469                    command(kind, state, caller, Some(spool_id), body).await
470                },
471            );
472        }
473        return post(
474            move |state: State<ApiState>,
475                  caller: Extension<Caller>,
476                  body: Result<Json<Value>, JsonRejection>| async move {
477                command(kind, state, caller, None, body).await
478            },
479        );
480    }
481    if let Effect::Recovery(kind) = operation.effect {
482        return post(
483            move |state: State<ApiState>,
484                  caller: Extension<Caller>,
485                  body: Result<Json<Value>, JsonRejection>| async move {
486                recover(kind, state, caller, body).await
487            },
488        );
489    }
490    if let Effect::Mutating(kind) = operation.effect {
491        return post(
492            move |state: State<ApiState>,
493                  caller: Extension<Caller>,
494                  print_id: PrintPath,
495                  body: Result<Json<ActionBody>, JsonRejection>| async move {
496                act(kind, state, caller, print_id, body).await
497            },
498        );
499    }
500    match (operation.name, operation.method) {
501        ("prints", Method::Get) => get(list_and_adopt_prints),
502        ("status", Method::Get) => get(status),
503        ("context", Method::Get) => get(context),
504        ("image", Method::Get) => get(image),
505        ("history", Method::Get) => get(history),
506        ("events", Method::Get) => get(crate::events::events),
507        ("look", Method::Get) => get(look),
508        (crate::operations::PRINTER_LOOK, Method::Get) => get(printer_look),
509        ("manifest_get", Method::Get) => get(manifest_get),
510        ("manifest_set", Method::Put) => put(manifest_set),
511        ("spools", Method::Get) => get(spools),
512        ("spool", Method::Get) => get(spool),
513        ("printer_history", Method::Get) => get(printer_history),
514        ("preflight", Method::Get) => get(preflight),
515        (crate::operations::RECOVERY_STATUS, Method::Get) => get(recover_status),
516        (crate::operations::BED_CLEAR, Method::Post) => post(bed_clear),
517        (crate::operations::RECHECK_CAMERA, Method::Post) => post(recheck_camera),
518        (name, method) => panic!(
519            "the operation `{name}` is declared as {method} and this router serves no such route"
520        ),
521    }
522}
523
524/// One answer, rendered as JSON under the media type every operation answers in.
525pub(crate) fn answer<T: printobserver_types::serde::Serialize>(
526    status: StatusCode,
527    body: &T,
528) -> Response {
529    let rendered = match printobserver_types::serde_json::to_vec(body) {
530        Ok(bytes) => bytes,
531        Err(error) => {
532            return (
533                StatusCode::INTERNAL_SERVER_ERROR,
534                [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
535                format!("{{\"error\":\"{error}\"}}"),
536            )
537                .into_response();
538        }
539    };
540    (
541        status,
542        [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
543        rendered,
544    )
545        .into_response()
546}
547
548/// One refusal, rendered as JSON under the same media type.
549pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
550    answer(status, &ErrorAnswer::saying(detail))
551}
552
553/// What a print id that names no print is refused with, after what was wrong
554/// with it: what to pass instead.
555pub(crate) const PRINT_ID_REFUSED: &str = "a print is named by its id, a UUID, as `printobserver prints` \
556lists it; a start with no print open may name none, and is made under one minted for it";
557
558/// The print a route's path names, refused in this server's own error shape,
559/// saying what to pass, when the path names no print at all.
560pub(crate) struct PrintPath(pub(crate) PrintId);
561
562impl<S: Send + Sync> axum::extract::FromRequestParts<S> for PrintPath {
563    type Rejection = Response;
564
565    async fn from_request_parts(
566        parts: &mut axum::http::request::Parts,
567        state: &S,
568    ) -> Result<Self, Self::Rejection> {
569        match Path::<PrintId>::from_request_parts(parts, state).await {
570            Ok(Path(print_id)) => Ok(Self(print_id)),
571            Err(rejected) => Err(refusal(
572                StatusCode::BAD_REQUEST,
573                format!("{}: {PRINT_ID_REFUSED}", rejected.body_text()),
574            )),
575        }
576    }
577}
578
579/// The status a store refusal is answered under.
580pub(crate) fn store_status(error: &StoreError) -> StatusCode {
581    match error {
582        StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
583        StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
584            StatusCode::BAD_REQUEST
585        }
586        StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
587    }
588}
589
590/// The status a core refusal is answered under.
591fn core_status(error: &CoreError) -> StatusCode {
592    match error {
593        CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
594        CoreError::Store(store) => store_status(store),
595        _ => StatusCode::INTERNAL_SERVER_ERROR,
596    }
597}
598
599/// Ask for one action of the vocabulary against one print.
600///
601/// Who may ask is settled before the policy is: a turn's credential reaches
602/// no start and no print but its own — whatever the body says, so those two
603/// answer `403` ahead of any rejection of the body itself — and the claimed
604/// actor is held to the caller. A
605/// request refused here is decided on by nothing and recorded nowhere.
606async fn act(
607    kind: ActionKind,
608    State(state): State<ApiState>,
609    Extension(caller): Extension<Caller>,
610    PrintPath(print_id): PrintPath,
611    body: Result<Json<ActionBody>, JsonRejection>,
612) -> Response {
613    if kind == ActionKind::StartPrint
614        && let Some(refused) =
615            operator_refused(&caller, &crate::operations::command_for("start_print"))
616    {
617        return refused;
618    }
619    if let Some(refused) = scope_refused(&caller, print_id) {
620        return refused;
621    }
622    let body = match body {
623        Ok(Json(body)) => body,
624        Err(rejected) => return rejected.into_response(),
625    };
626    if let Some(refused) = claim_refused(&caller, &body.actor) {
627        return refused;
628    }
629    if kind == ActionKind::AcknowledgeFailure
630        && let Some(refused) = unlooked_refused(&state.turns, &caller, print_id)
631    {
632        return refused;
633    }
634    let action = match body.into_action(kind) {
635        Ok(action) => action,
636        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
637    };
638    let outcome = match state.supervisor.request_action(print_id, action).await {
639        Ok(outcome) => outcome,
640        Err(error) => return refusal(core_status(&error), error),
641    };
642    let printer_refusal = match &outcome.record.outcome {
643        Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
644        _ => None,
645    };
646    let status = match outcome.record.decision {
647        PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
648        // The policy accepted it and the machine did not. That is a request
649        // that was made and refused rather than one that never happened, so
650        // the record and the printer's own words are the answer.
651        PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
652        // The rejection itself is the answer: its reason, the value asked for
653        // and the range allowed are what let a caller ask again correctly.
654        PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
655    };
656    answer(
657        status,
658        &ActionAnswer {
659            record: outcome.record,
660            intervention: outcome.intervention,
661            printer_refusal,
662        },
663    )
664}
665
666/// Ask the spool ledger for one command.
667///
668/// The claimed actor is held to the caller before anything else of the body is
669/// read, and a body with no reason is refused before the domain is asked —
670/// so a request refused here is recorded nowhere. Whether the actor may ask at
671/// all is the envelope's grant, which the domain rules on and records like
672/// every refusal: a supervision turn's agent is refused there, under the
673/// default grants, rather than here.
674async fn command(
675    kind: ActionKind,
676    State(state): State<ApiState>,
677    Extension(caller): Extension<Caller>,
678    spool_id: Option<SpoolId>,
679    body: Result<Json<Value>, JsonRejection>,
680) -> Response {
681    let body = match body {
682        Ok(Json(body)) => body,
683        Err(rejected) => return rejected.into_response(),
684    };
685    let Some(fields) = body.as_object() else {
686        return refusal(
687            StatusCode::BAD_REQUEST,
688            "a spool command's body is a document of its fields",
689        );
690    };
691    let actor = match claimed_actor(fields) {
692        Ok(actor) => actor,
693        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
694    };
695    if let Some(refused) = claim_refused(&caller, &actor) {
696        return refused;
697    }
698    let asked = match spool_command_of(kind, spool_id, body) {
699        Ok(asked) => asked,
700        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
701    };
702    let outcome = match state.supervisor.request_spool_command(asked).await {
703        Ok(outcome) => outcome,
704        Err(error) => return refusal(core_status(&error), error),
705    };
706    let status = match outcome.decision {
707        PolicyDecision::Accepted => StatusCode::OK,
708        // The refusal is the answer, exactly as a print action's is.
709        PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
710    };
711    answer(
712        status,
713        &SpoolCommandAnswer {
714            decision: outcome.decision,
715            spool: outcome.spool,
716            events: outcome.events,
717        },
718    )
719}
720
721/// Ask the printer for one recovery action.
722///
723/// The body is held to the action's own fields, a reason and an actor before
724/// anything is decided, and the claimed actor to the caller — so a request
725/// refused here is recorded nowhere and reaches no printer. Whether the actor
726/// may ask, and whether the printer is in a state the action is safe from, is
727/// the supervision core's to rule on and record.
728async fn recover(
729    kind: RecoveryActionKind,
730    State(state): State<ApiState>,
731    Extension(caller): Extension<Caller>,
732    body: Result<Json<Value>, JsonRejection>,
733) -> Response {
734    let body = match body {
735        Ok(Json(body)) => body,
736        Err(rejected) => return rejected.into_response(),
737    };
738    if let Some(fields) = body.as_object() {
739        let actor = match claimed_actor(fields) {
740            Ok(actor) => actor,
741            Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
742        };
743        if let Some(refused) = claim_refused(&caller, &actor) {
744            return refused;
745        }
746    }
747    let (action, actor, reason) = match recovery_of(kind, body) {
748        Ok(asked) => asked,
749        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
750    };
751    let issued = match state
752        .supervisor
753        .request_recovery(action.clone(), actor, reason)
754        .await
755    {
756        Ok(issued) => issued,
757        Err(error) => return refusal(core_status(&error), error),
758    };
759    let config = state.supervisor.config().recovery;
760    let status = match &issued.decision {
761        RecoveryDecision::Executed(ExecutionOutcome::Succeeded) => StatusCode::OK,
762        // The printer was asked and refused: a request that was made rather
763        // than one that never happened, answered with the printer's words.
764        RecoveryDecision::Executed(ExecutionOutcome::Failed { .. }) => StatusCode::BAD_GATEWAY,
765        // The refusal is the answer, as a print action's is.
766        RecoveryDecision::Rejected(_) => StatusCode::CONFLICT,
767    };
768    answer(
769        status,
770        &RecoveryAnswer {
771            detail: recovery_detail(&action, &issued.decision, config.as_ref()),
772            action,
773            decision: issued.decision,
774            events: vec![issued.requested, issued.settled],
775        },
776    )
777}
778
779/// What a recorded bed-clear means from now on, in a sentence for a person.
780pub const BED_CLEAR_DETAIL: &str = "recorded: until the next print starts, a Z home is decided \
781    as though it asserted the bed clear, and a heat, a park and an XY home as though they \
782    asserted the nozzle clear of the part, wherever the operator's word counts";
783
784/// Record the operator's word that the bed is clear.
785///
786/// The claimed actor is held to the caller before anything is written, and
787/// the one actor admitted is the operator: a turn claiming the operator, any
788/// claim to the system, and the agent's own word are each refused `403` and
789/// recorded nowhere. A reason that is absent or blank is refused before
790/// anything is written.
791async fn bed_clear(
792    State(state): State<ApiState>,
793    Extension(caller): Extension<Caller>,
794    body: Result<Json<Value>, JsonRejection>,
795) -> Response {
796    let body = match body {
797        Ok(Json(body)) => body,
798        Err(rejected) => return rejected.into_response(),
799    };
800    let Some(fields) = body.as_object() else {
801        return refusal(
802            StatusCode::BAD_REQUEST,
803            "the body is not a document carrying an `actor` and a `reason`",
804        );
805    };
806    let actor = match claimed_actor(fields) {
807        Ok(actor) => actor,
808        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
809    };
810    if let Some(refused) = claim_refused(&caller, &actor) {
811        return refused;
812    }
813    if actor != Actor::Operator {
814        return refusal(
815            StatusCode::FORBIDDEN,
816            format!(
817                "{} may not say the bed is clear: an assertion is a person's word for what \
818                 they can see, and only the operator's is recorded",
819                claimed(&actor)
820            ),
821        );
822    }
823    let body: BedClearBody = match printobserver_types::serde_json::from_value(body) {
824        Ok(body) => body,
825        Err(error) => {
826            return refusal(
827                StatusCode::BAD_REQUEST,
828                format!("the body is not an `actor` and a `reason`: {error}"),
829            );
830        }
831    };
832    let reason = match reason_of(body.reason.as_deref()) {
833        Ok(reason) => reason,
834        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
835    };
836    match state.supervisor.assert_bed_clear(reason).await {
837        Ok(event) => answer(
838            StatusCode::OK,
839            &BedClearAnswer {
840                event,
841                detail: BED_CLEAR_DETAIL.to_owned(),
842            },
843        ),
844        Err(error) => refusal(core_status(&error), error),
845    }
846}
847
848/// Judge a print's camera again on a fresh frame: its view and its first-layer
849/// alignment at once, a latched verdict included, taking the correction afresh
850/// when the layer is clearly found, and recording each judgement as a check's
851/// are. Nothing is sent to the printer.
852///
853/// The claimed actor is held to the caller before anything is fetched, and a
854/// reason that is absent or blank is refused. While the printer reports the
855/// print paused its bed stands off the plan's height, so only the view is
856/// judged. A store that cannot read the print answers this server's own
857/// failure, and a print it does not hold `404`, before anything of the camera
858/// is asked. With no calibration or no camera stream configured there is
859/// nothing to judge a frame against: the fresh frame is kept as a look's is,
860/// and answered as the whole frame for that reason. A server that judges no
861/// frames, one with no camera configured, and a camera that gives no good
862/// frame are each refused `503`, in this server's own error shape: `409` and
863/// `502` are the policy's and the machine's answers to a decision, each
864/// carrying its record, and nothing was decided here.
865async fn recheck_camera(
866    State(state): State<ApiState>,
867    Extension(caller): Extension<Caller>,
868    PrintPath(print_id): PrintPath,
869    body: Result<Json<Value>, JsonRejection>,
870) -> Response {
871    if let Some(refused) = scope_refused(&caller, print_id) {
872        return refused;
873    }
874    let (actor, reason) = match actor_and_reason(&caller, body) {
875        Ok(asked) => asked,
876        Err(refused) => return *refused,
877    };
878    // The store answers first, as it does for every operation: a print it
879    // cannot read is this server's own failure, and one it does not hold is
880    // missing, whatever the camera would have said.
881    match state.prints.print(print_id).await {
882        Ok(Some(_)) => {}
883        Ok(None) => {
884            return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
885        }
886        Err(error) => return refusal(store_status(&error), error),
887    }
888    let Some(images) = state.check_images.clone() else {
889        return refusal(
890            StatusCode::SERVICE_UNAVAILABLE,
891            "nothing judges this server's camera frames",
892        );
893    };
894    if state.supervisor.config().camera_snapshot_url.is_none() {
895        return refusal(
896            StatusCode::SERVICE_UNAVAILABLE,
897            "no camera is configured to judge: set the server's `[camera] snapshot_url`",
898        );
899    }
900    let supervisor = Arc::clone(&state.supervisor);
901    let fresh = tokio::task::spawn_blocking(move || {
902        printobserver_core::block_on(supervisor.fresh_view(print_id))
903    })
904    .await;
905    let fresh = match fresh {
906        Ok(Ok(fresh)) => fresh,
907        Ok(Err(error)) => return refusal(core_status(&error), error),
908        Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
909    };
910    let Some((url, image)) = fresh.frame.clone() else {
911        return refusal(
912            StatusCode::SERVICE_UNAVAILABLE,
913            "the camera gave no good frame to judge",
914        );
915    };
916    let sha256 = hex_sha256(image.bytes.as_slice());
917    let captured_at = image
918        .captured_at
919        .unwrap_or_else(printobserver_types::Timestamp::now);
920    let alignment = if fresh.paused {
921        crate::alignment::AlignmentJudging::Never
922    } else {
923        crate::alignment::AlignmentJudging::Afresh
924    };
925    let judging = Arc::clone(&images);
926    let plan = fresh.plan.clone();
927    let bytes = image.bytes.as_slice().to_vec();
928    let digest = sha256.clone();
929    let judged = tokio::task::spawn_blocking(move || {
930        judging.judge_frame(print_id, &bytes, &digest, plan.as_ref(), alignment)
931    })
932    .await;
933    let judged = match judged {
934        Ok(Some(judged)) => judged,
935        // With no calibration, or no stream it was fitted on, nothing can be
936        // judged of the frame: it is kept as a look's is, and answered as the
937        // whole frame for that reason.
938        Ok(None) => crate::alignment::Judged::nothing_to_judge(
939            images.alignment(print_id),
940            EventBody::of(&printobserver_core::CameraLookPayload {
941                waited_s: 0,
942                delivered: Vec::new(),
943                frame_captured_at: Some(captured_at),
944            })
945            .ok(),
946        ),
947        Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
948    };
949    if let Some(detail) = &judged.unreadable {
950        return refusal(StatusCode::SERVICE_UNAVAILABLE, detail);
951    }
952    eprintln!(
953        "printobserver: print {print_id}: the camera is judged again for {}: {reason}",
954        claimed(&actor)
955    );
956    let frame_path = match stored_with_frame(&state, print_id, &judged, (url, image)).await {
957        Ok(path) => path,
958        Err(refused) => return refused,
959    };
960    let shown =
961        match image_shown(&images, print_id, &frame_path, captured_at, &fresh, &judged).await {
962            Ok(shown) => shown,
963            Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
964        };
965    answer(
966        StatusCode::OK,
967        &crate::wire::RecheckCameraAnswer {
968            frame_path,
969            alignment: judged.alignment,
970            view_correction: judged.correction,
971            image_kind: shown.kind(),
972            image_fallback: shown.fallback,
973        },
974    )
975}
976
977/// The actor and the reason one request's body carries, the actor held to the
978/// caller, or the refusal of the request.
979fn actor_and_reason(
980    caller: &Caller,
981    body: Result<Json<Value>, JsonRejection>,
982) -> Result<(Actor, String), Box<Response>> {
983    let refused = |status: StatusCode, said: String| Box::new(refusal(status, said));
984    let body = match body {
985        Ok(Json(body)) => body,
986        Err(rejected) => return Err(Box::new(rejected.into_response())),
987    };
988    let Some(fields) = body.as_object() else {
989        return Err(refused(
990            StatusCode::BAD_REQUEST,
991            "the body is not a document carrying an `actor` and a `reason`".to_owned(),
992        ));
993    };
994    let actor = claimed_actor(fields)
995        .map_err(|rejected| refused(StatusCode::BAD_REQUEST, rejected.to_string()))?;
996    if let Some(claim) = claim_refused(caller, &actor) {
997        return Err(Box::new(claim));
998    }
999    let body: BedClearBody =
1000        printobserver_types::serde_json::from_value(body).map_err(|error| {
1001            refused(
1002                StatusCode::BAD_REQUEST,
1003                format!("the body is not an `actor` and a `reason`: {error}"),
1004            )
1005        })?;
1006    let reason = reason_of(body.reason.as_deref())
1007        .map_err(|rejected| refused(StatusCode::BAD_REQUEST, rejected.to_string()))?;
1008    Ok((actor, reason))
1009}
1010
1011/// The image a check of a print would be shown of a judged fresh frame, made
1012/// off the request's own thread.
1013async fn image_shown(
1014    images: &Arc<crate::check_images::PanelImages>,
1015    print_id: PrintId,
1016    frame_path: &std::path::Path,
1017    captured_at: printobserver_types::Timestamp,
1018    fresh: &printobserver_core::FreshView,
1019    judged: &crate::alignment::Judged,
1020) -> Result<printobserver_core::ShownImage, String> {
1021    let choosing = Arc::clone(images);
1022    let path = frame_path.to_path_buf();
1023    let plan = fresh.plan.clone();
1024    let paused = fresh.paused;
1025    let judged = judged.clone();
1026    tokio::task::spawn_blocking(move || {
1027        choosing.image_of(
1028            print_id,
1029            &crate::check_images::Shown {
1030                frame: &path,
1031                captured_at,
1032                made_for: printobserver_core::ImageUse::Look,
1033                plan: plan.as_ref(),
1034                paused,
1035            },
1036            Some(&judged),
1037        )
1038    })
1039    .await
1040    .map_err(|error| error.to_string())?
1041}
1042
1043/// Append a judgement's records to a print's history, the fresh frame stored
1044/// with the first and named by every later one, and answer where it was
1045/// stored.
1046async fn stored_with_frame(
1047    state: &ApiState,
1048    print_id: PrintId,
1049    judged: &crate::alignment::Judged,
1050    frame: (String, printobserver_vision_api::FetchedImage),
1051) -> Result<std::path::PathBuf, Response> {
1052    let mut frame = Some(frame);
1053    let mut stored = None;
1054    for record in judged.records.clone() {
1055        let event = state
1056            .supervisor
1057            .record_with_frame(print_id, record, frame.take())
1058            .await
1059            .map_err(|error| refusal(core_status(&error), error))?;
1060        if stored.is_none() {
1061            stored = event.image;
1062        }
1063    }
1064    let unkept = || {
1065        refusal(
1066            StatusCode::INTERNAL_SERVER_ERROR,
1067            "the fresh frame was not kept",
1068        )
1069    };
1070    let reference = stored.ok_or_else(unkept)?;
1071    match state.images.image(reference.id).await {
1072        Ok(printobserver_core::store::ImageLookup::Found { path, .. }) => Ok(path),
1073        _ => Err(unkept()),
1074    }
1075}
1076
1077/// A digest as the image store names a frame: lowercase hexadecimal SHA-256.
1078fn hex_sha256(bytes: &[u8]) -> String {
1079    use sha2::Digest as _;
1080    sha2::Sha256::digest(bytes)
1081        .iter()
1082        .fold(String::with_capacity(64), |mut text, byte| {
1083            use core::fmt::Write as _;
1084            let _ = write!(text, "{byte:02x}");
1085            text
1086        })
1087}
1088
1089/// Everything a recovery is checked against now, and what each action would
1090/// meet for the caller.
1091async fn recover_status(
1092    State(state): State<ApiState>,
1093    Extension(caller): Extension<Caller>,
1094) -> Response {
1095    let class = match caller {
1096        Caller::Operator => ActorClass::Operator,
1097        Caller::Turn(_) => ActorClass::Agent,
1098    };
1099    match state.supervisor.recovery_status(class).await {
1100        Ok(status) => answer(StatusCode::OK, &status),
1101        Err(error) => refusal(core_status(&error), error),
1102    }
1103}
1104
1105/// Every spool, beside one line each and the charges a tool is holding.
1106async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
1107    let listed = match state
1108        .supervisor
1109        .spools(params.include_retired.unwrap_or(false))
1110        .await
1111    {
1112        Ok(listed) => listed,
1113        Err(error) => return refusal(core_status(&error), error),
1114    };
1115    match state.supervisor.pending_charges(None).await {
1116        Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
1117        Err(error) => refusal(core_status(&error), error),
1118    }
1119}
1120
1121/// One spool, and the newest of the printer's own events that name it.
1122async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
1123    let found = match state.supervisor.spool(spool_id).await {
1124        Ok(Some(found)) => found,
1125        Ok(None) => {
1126            return refusal(
1127                StatusCode::NOT_FOUND,
1128                format!("there is no spool {spool_id}"),
1129            );
1130        }
1131        Err(error) => return refusal(core_status(&error), error),
1132    };
1133    let query = TimelineQuery {
1134        spool_id: Some(spool_id),
1135        limit: Some(SPOOL_RECENT_EVENTS),
1136        ..every_timeline_kind()
1137    };
1138    match state.supervisor.timeline(query).await {
1139        Ok(recent) => answer(
1140            StatusCode::OK,
1141            &SpoolAnswer {
1142                spool: found,
1143                recent,
1144            },
1145        ),
1146        Err(error) => refusal(core_status(&error), error),
1147    }
1148}
1149
1150/// The printer history unfiltered: every timeline kind, the default window.
1151const fn every_timeline_kind() -> TimelineQuery {
1152    TimelineQuery {
1153        kinds: Vec::new(),
1154        since: None,
1155        until: None,
1156        spool_id: None,
1157        before: None,
1158        limit: None,
1159    }
1160}
1161
1162/// One value of a printer history read, refused naming it when it is not one.
1163fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
1164where
1165    T::Err: core::fmt::Display,
1166{
1167    text.parse()
1168        .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
1169}
1170
1171/// The printer history query a request's values make.
1172///
1173/// `kinds` may be given any number of times, each one kind; every other value
1174/// at most once. A value this read does not take is refused naming it rather
1175/// than ignored, because a filter that was quietly dropped answers more than
1176/// was asked for.
1177fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
1178    let mut query = every_timeline_kind();
1179    let mut seen: Vec<&str> = Vec::new();
1180    for (name, text) in asked {
1181        if name != "kinds" {
1182            if seen.contains(&name.as_str()) {
1183                return Err(format!(
1184                    "`{name}` was given more than once, and this read takes one"
1185                ));
1186            }
1187            seen.push(name);
1188        }
1189        match name.as_str() {
1190            "kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
1191            "since" => query.since = Some(read_one::<Timestamp>(name, text)?),
1192            "until" => query.until = Some(read_one::<Timestamp>(name, text)?),
1193            "spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
1194            "before" => query.before = Some(read_one::<EventId>(name, text)?),
1195            "limit" => query.limit = Some(read_one::<u32>(name, text)?),
1196            other => return Err(format!("the printer history takes no `{other}`")),
1197        }
1198    }
1199    Ok(query)
1200}
1201
1202/// One page of the printer's own history, newest first, and the cursor for
1203/// the page after it when there is one.
1204///
1205/// The cursor is answered only when an older event exists, so a caller paging
1206/// by it stops at the last page rather than one empty page after it.
1207async fn printer_history(
1208    State(state): State<ApiState>,
1209    Query(asked): Query<Vec<(String, String)>>,
1210) -> Response {
1211    let query = match timeline_query(&asked) {
1212        Ok(query) => query,
1213        Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
1214    };
1215    let limit = match query.resolved_limit() {
1216        Ok(limit) => limit,
1217        Err(error) => return refusal(store_status(&error), error),
1218    };
1219    let events = match state.supervisor.timeline(query.clone()).await {
1220        Ok(events) => events,
1221        Err(error) => return refusal(core_status(&error), error),
1222    };
1223    let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
1224    let next = match events.last() {
1225        Some(last) if full => {
1226            let older = TimelineQuery {
1227                before: Some(last.id),
1228                limit: Some(1),
1229                ..query
1230            };
1231            match state.supervisor.timeline(older).await {
1232                Ok(older) if older.is_empty() => None,
1233                Ok(_) => Some(last.id),
1234                Err(error) => return refusal(core_status(&error), error),
1235            }
1236        }
1237        _ => None,
1238    };
1239    answer(StatusCode::OK, &TimelineAnswer { events, next })
1240}
1241
1242/// Whether the spools loaded hold enough for one file, the file was sliced
1243/// for their material and, when a sheet is given, that sheet suits it — read
1244/// now.
1245async fn preflight(
1246    State(state): State<ApiState>,
1247    Query(params): Query<PreflightParams>,
1248) -> Response {
1249    let Some(named) = params.file_name else {
1250        return refusal(
1251            StatusCode::BAD_REQUEST,
1252            "a filament check needs `file_name`, and this request carries none",
1253        );
1254    };
1255    let file_name = match FileName::new(&named) {
1256        Ok(file_name) => file_name,
1257        Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
1258    };
1259    let sheet = match params.sheet.map(SheetId::try_from).transpose() {
1260        Ok(sheet) => sheet,
1261        Err(why) => return refusal(StatusCode::BAD_REQUEST, why),
1262    };
1263    match state.supervisor.preflight(&file_name, sheet.as_ref()).await {
1264        Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
1265        Err(error) => refusal(core_status(&error), error),
1266    }
1267}
1268
1269/// List every print, and name the one the printer's job belongs to.
1270///
1271/// Reading this adopts that job when no open print carries its file name, which
1272/// is how a print started at the printer gets an identifier before anything has
1273/// reported on it. A printer that cannot be read still answers the stored
1274/// prints, with nothing active.
1275async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
1276    match state.supervisor.list_and_adopt_prints().await {
1277        Ok(listing) => answer(
1278            StatusCode::OK,
1279            &PrintsAnswer {
1280                prints: listing.prints,
1281                active: listing.active,
1282            },
1283        ),
1284        Err(error) => refusal(core_status(&error), error),
1285    }
1286}
1287
1288/// Read one print's status.
1289///
1290/// The print answered is the context's, read after the context read settled
1291/// the open prints against the printer's job — so a status that finds the job
1292/// over answers the print it closed rather than the one it found.
1293async fn status(
1294    State(state): State<ApiState>,
1295    Extension(caller): Extension<Caller>,
1296    PrintPath(print_id): PrintPath,
1297) -> Response {
1298    if let Some(refused) = scope_refused(&caller, print_id) {
1299        return refused;
1300    }
1301    match state.prints.print(print_id).await {
1302        Ok(Some(_)) => {}
1303        Ok(None) => {
1304            return refusal(
1305                StatusCode::NOT_FOUND,
1306                format!("there is no print {print_id}"),
1307            );
1308        }
1309        Err(error) => return refusal(store_status(&error), error),
1310    }
1311    let context = match context_of(&state, print_id).await {
1312        Ok(context) => context,
1313        Err(refused) => return refused,
1314    };
1315    let session = match state.sessions.session(print_id).await {
1316        Ok(session) => session,
1317        Err(error) => return refusal(store_status(&error), error),
1318    };
1319    // The context read built the print's index when it answered a plan, so
1320    // this reads no file; a print it answered none for has none to answer.
1321    let planned_changes = if context.slicer.is_some() {
1322        match state
1323            .supervisor
1324            .planned_changes(&context.print, context.job.as_ref())
1325            .await
1326        {
1327            Ok(planned) => planned,
1328            Err(error) => return refusal(core_status(&error), error),
1329        }
1330    } else {
1331        None
1332    };
1333    answer(
1334        StatusCode::OK,
1335        &StatusAnswer {
1336            print: context.print,
1337            printer: context.printer,
1338            job: context.job,
1339            session,
1340            interventions: context.interventions,
1341            detector: context.detector,
1342            planned_changes,
1343            last_check_image: state
1344                .check_images
1345                .as_ref()
1346                .and_then(|images| images.last_check_image(print_id)),
1347        },
1348    )
1349}
1350
1351/// One print's context, read off the request's own thread.
1352///
1353/// The first read of a print's context after it starts reads the print's
1354/// whole G-code to index it, through a printer port that blocks while it
1355/// reads, so it is taken on a blocking thread, as a look is: a request that
1356/// held an asynchronous worker for the length of a download would hold every
1357/// task queued behind it there too.
1358async fn context_of(
1359    state: &ApiState,
1360    print_id: PrintId,
1361) -> Result<printobserver_core::PrintContext, Response> {
1362    let supervisor = Arc::clone(&state.supervisor);
1363    let read = tokio::task::spawn_blocking(move || {
1364        printobserver_core::block_on(supervisor.context(print_id))
1365    })
1366    .await;
1367    match read {
1368        Ok(Ok(context)) => Ok(context),
1369        Ok(Err(error)) => Err(refusal(core_status(&error), error)),
1370        Err(error) => Err(refusal(StatusCode::INTERNAL_SERVER_ERROR, error)),
1371    }
1372}
1373
1374/// Read everything a supervision turn is given about one print, with the
1375/// latest image materialized.
1376///
1377/// The path is looked up through the same store read the image operation
1378/// answers from, so the two operations cannot disagree about where an image
1379/// is. An image whose record is intact and whose file is gone answers no path,
1380/// which is what the caller's own missing-file failure is about.
1381async fn context(
1382    State(state): State<ApiState>,
1383    Extension(caller): Extension<Caller>,
1384    PrintPath(print_id): PrintPath,
1385    Query(params): Query<ContextParams>,
1386) -> Response {
1387    if let Some(refused) = scope_refused(&caller, print_id) {
1388        return refused;
1389    }
1390    // Off the request's own thread, for the reason `context_of` gives.
1391    let supervisor = Arc::clone(&state.supervisor);
1392    let since = params.since;
1393    let read = tokio::task::spawn_blocking(move || {
1394        printobserver_core::block_on(supervisor.agent_context(print_id, since))
1395    })
1396    .await;
1397    let context = match read {
1398        Ok(Ok(read)) => read,
1399        Ok(Err(error)) => return refusal(core_status(&error), error),
1400        Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1401    };
1402    let mut image_path = None;
1403    if let Some(latest) = context.latest_image.as_ref() {
1404        match state.images.image(latest.id).await {
1405            Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
1406            Err(error) => return refusal(store_status(&error), error),
1407        }
1408    }
1409    answer(
1410        StatusCode::OK,
1411        &ContextAnswer {
1412            context,
1413            image_path,
1414        },
1415    )
1416}
1417
1418/// Take a fresh look at one print.
1419///
1420/// A wait longer than the supervisor allows is refused rather than shortened,
1421/// and a print nothing is held under is refused before any wait. The wait
1422/// itself runs on a blocking thread, exactly as a turn does, so that a minute
1423/// and a half of waiting holds no asynchronous worker the agent's own requests
1424/// are answered on.
1425async fn look(
1426    State(state): State<ApiState>,
1427    Extension(caller): Extension<Caller>,
1428    PrintPath(print_id): PrintPath,
1429    Query(params): Query<LookParams>,
1430) -> Response {
1431    if let Some(refused) = scope_refused(&caller, print_id) {
1432        return refused;
1433    }
1434    let wait_s = params.wait_s.unwrap_or(0);
1435    if wait_s > MAX_LOOK_WAIT_S {
1436        return refusal(
1437            StatusCode::BAD_REQUEST,
1438            format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1439        );
1440    }
1441    match state.prints.print(print_id).await {
1442        Ok(Some(_)) => {}
1443        Ok(None) => {
1444            return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
1445        }
1446        Err(error) => return refusal(store_status(&error), error),
1447    }
1448    // A look that was asked for counts whatever the camera then gives it: a
1449    // turn whose camera is down has still looked, and can say so.
1450    if let Caller::Turn(binding) = &caller {
1451        state.turns.note_look(binding);
1452    }
1453    let supervisor = Arc::clone(&state.supervisor);
1454    let taken = tokio::task::spawn_blocking(move || {
1455        let (arrived, waited) =
1456            supervisor.await_look_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
1457        printobserver_core::block_on(supervisor.take_look(print_id, waited, arrived))
1458    })
1459    .await;
1460    match taken {
1461        Ok(Ok(look)) => answer(StatusCode::OK, &look),
1462        Ok(Err(error)) => refusal(core_status(&error), error),
1463        Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1464    }
1465}
1466
1467/// Take a fresh look at the printer, with no print named.
1468///
1469/// The look and its frame belong to no print, and the wait is a plain wait:
1470/// nothing any print's agent is owed can end it or be taken by it. A turn's
1471/// credential reaches its own print alone, so this is the operator's; a wait
1472/// longer than the supervisor allows is refused rather than shortened.
1473async fn printer_look(
1474    State(state): State<ApiState>,
1475    Extension(caller): Extension<Caller>,
1476    Query(params): Query<LookParams>,
1477) -> Response {
1478    if let Some(refused) = printless_refused(&caller, "a look at the printer with no print named") {
1479        return refused;
1480    }
1481    let wait_s = params.wait_s.unwrap_or(0);
1482    if wait_s > MAX_LOOK_WAIT_S {
1483        return refusal(
1484            StatusCode::BAD_REQUEST,
1485            format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1486        );
1487    }
1488    let waited = Duration::from_secs(u64::from(wait_s));
1489    tokio::time::sleep(waited).await;
1490    match state.supervisor.take_printer_look(waited).await {
1491        Ok(look) => answer(StatusCode::OK, &look),
1492        Err(error) => refusal(core_status(&error), error),
1493    }
1494}
1495
1496/// Materialize one image: its record, and the absolute path its bytes are at.
1497///
1498/// An image belongs to one print, or to none when it is a frame taken of the
1499/// printer with no print named. A turn's credential reaches the images of its
1500/// own print alone, so a frame of no print is the operator's.
1501async fn image(
1502    State(state): State<ApiState>,
1503    Extension(caller): Extension<Caller>,
1504    Path(image_id): Path<ImageId>,
1505) -> Response {
1506    match state.images.image(image_id).await {
1507        Ok(lookup) => {
1508            let belongs_to = match &lookup {
1509                printobserver_core::ImageLookup::Found { record, .. }
1510                | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
1511            };
1512            let refused = match belongs_to {
1513                Some(print_id) => scope_refused(&caller, print_id),
1514                None => {
1515                    printless_refused(&caller, "a frame of the printer that belongs to no print")
1516                }
1517            };
1518            if let Some(refused) = refused {
1519                return refused;
1520            }
1521            answer(StatusCode::OK, &ImageAnswer::from(lookup))
1522        }
1523        Err(error) => refusal(store_status(&error), error),
1524    }
1525}
1526
1527/// Read one print's events, newest first.
1528async fn history(
1529    State(state): State<ApiState>,
1530    Extension(caller): Extension<Caller>,
1531    PrintPath(print_id): PrintPath,
1532    Query(params): Query<HistoryParams>,
1533) -> Response {
1534    if let Some(refused) = scope_refused(&caller, print_id) {
1535        return refused;
1536    }
1537    let query = HistoryQuery {
1538        print_id,
1539        kinds: Vec::new(),
1540        since: None,
1541        until: None,
1542        limit: params.limit,
1543    };
1544    match state.events.history(query).await {
1545        Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
1546        Err(error) => refusal(store_status(&error), error),
1547    }
1548}
1549
1550/// Read one print's manifest.
1551async fn manifest_get(
1552    State(state): State<ApiState>,
1553    Extension(caller): Extension<Caller>,
1554    PrintPath(print_id): PrintPath,
1555) -> Response {
1556    if let Some(refused) = scope_refused(&caller, print_id) {
1557        return refused;
1558    }
1559    let manifest = match state.prints.manifest(print_id).await {
1560        Ok(manifest) => manifest,
1561        Err(error) => return refusal(store_status(&error), error),
1562    };
1563    let narrowings = match state.prints.print(print_id).await {
1564        Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
1565        Err(error) => return refusal(store_status(&error), error),
1566    };
1567    answer(
1568        StatusCode::OK,
1569        &ManifestAnswer {
1570            manifest,
1571            narrowings,
1572        },
1573    )
1574}
1575
1576/// Write one print's manifest.
1577///
1578/// A manifest narrows what any actor may ask for, so replacing one is a change
1579/// to the bounds a print runs under and carries a reason like every other
1580/// change. The reason is ruled on **before** anything is written, so a request
1581/// without one leaves the stored manifest and the print's narrowings as they
1582/// were — and every range it asked wider than the envelope allows is recorded
1583/// on the print, exactly as it is when a start attaches one.
1584async fn manifest_set(
1585    State(state): State<ApiState>,
1586    Extension(caller): Extension<Caller>,
1587    PrintPath(print_id): PrintPath,
1588    body: Result<Json<ManifestBody>, JsonRejection>,
1589) -> Response {
1590    if let Some(refused) =
1591        operator_refused(&caller, &crate::operations::command_for("manifest_set"))
1592    {
1593        return refused;
1594    }
1595    let body = match body {
1596        Ok(Json(body)) => body,
1597        Err(rejected) => return rejected.into_response(),
1598    };
1599    if let Err(rejected) = body.reason() {
1600        return refusal(StatusCode::BAD_REQUEST, rejected);
1601    }
1602    let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
1603    if let Err(error) = state
1604        .prints
1605        .put_manifest(print_id, body.manifest.clone())
1606        .await
1607    {
1608        return refusal(store_status(&error), error);
1609    }
1610    for narrowing in narrowed.narrowings.clone() {
1611        if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
1612            return refusal(store_status(&error), error);
1613        }
1614    }
1615    answer(
1616        StatusCode::OK,
1617        &ManifestAnswer {
1618            manifest: Some(body.manifest),
1619            narrowings: narrowed.narrowings,
1620        },
1621    )
1622}
1623
1624#[cfg(test)]
1625mod tests {
1626    use axum::http::StatusCode;
1627    use printobserver_core::CoreError;
1628    use printobserver_core::store::StoreError;
1629
1630    use super::{core_status, store_status};
1631
1632    /// Every refusal the store can make is answered under a status a caller can
1633    /// act on: what it asked for, what is not there, and what went wrong here.
1634    #[test]
1635    fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
1636        for (error, expected) in [
1637            (
1638                StoreError::NotFound {
1639                    what: "print".to_owned(),
1640                },
1641                StatusCode::NOT_FOUND,
1642            ),
1643            (
1644                StoreError::LimitRefused {
1645                    limit: 1_000,
1646                    asked_for: 2_000,
1647                },
1648                StatusCode::BAD_REQUEST,
1649            ),
1650            (
1651                StoreError::ConstraintRefused {
1652                    constraint: "actions.decision".to_owned(),
1653                },
1654                StatusCode::BAD_REQUEST,
1655            ),
1656            (
1657                StoreError::Database {
1658                    detail: "the disk is full".to_owned(),
1659                },
1660                StatusCode::INTERNAL_SERVER_ERROR,
1661            ),
1662            (
1663                StoreError::Io {
1664                    detail: "the disk is full".to_owned(),
1665                },
1666                StatusCode::INTERNAL_SERVER_ERROR,
1667            ),
1668        ] {
1669            assert_eq!(store_status(&error), expected, "{error}");
1670        }
1671    }
1672
1673    /// A print nothing holds is not found; a port that failed is this server's
1674    /// own failure rather than the caller's.
1675    #[test]
1676    fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
1677        assert_eq!(
1678            core_status(&CoreError::NoSuchPrint {
1679                print_id: printobserver_types::PrintId::new(),
1680            }),
1681            StatusCode::NOT_FOUND
1682        );
1683        assert_eq!(
1684            core_status(&CoreError::Store(StoreError::NotFound {
1685                what: "print".to_owned(),
1686            })),
1687            StatusCode::NOT_FOUND
1688        );
1689        assert_eq!(
1690            core_status(&CoreError::Unrepresentable {
1691                detail: "an instant".to_owned(),
1692            }),
1693            StatusCode::INTERNAL_SERVER_ERROR
1694        );
1695    }
1696}