Skip to main content

printobserver_server/
api.rs

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