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