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