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//!
12//! # Every action takes the same one path
13//!
14//! An action asked for here goes to
15//! [`Supervisor::request_action`](printobserver_core::Supervisor::request_action),
16//! which is the same call an operator's action makes and an agent's action
17//! makes. The policy is not re-implemented here and is not bypassed here: a
18//! rejected request answers the rejection the policy made, carrying its reason,
19//! the value asked for and the range allowed, and reaches no action method of
20//! the printer port at all.
21//!
22//! # Nothing is served to a caller that did not present the credential
23//!
24//! Every route beneath the versioned prefix — and the prefix's own fallback, so
25//! that a path nothing serves is refused the same way — sits behind
26//! [`authenticate`], which runs before any extractor reads a path, a query or a
27//! body. A request whose `Authorization` header is not exactly
28//! `Bearer <the credential in force>` is answered `401` there, so it reaches no
29//! handler, no store, no printer port and no record. There is no route that
30//! skips it and no configuration that turns it off: [`ApiState`] cannot be
31//! built without the credential it is checked against.
32
33use std::sync::Arc;
34use std::time::Duration;
35
36use axum::Json;
37use axum::extract::{DefaultBodyLimit, Path, Query, Request, State};
38use axum::http::{StatusCode, header};
39use axum::middleware::{Next, from_fn_with_state};
40use axum::response::{IntoResponse, Response};
41use axum::routing::{get, post, put};
42use axum::{Router, routing::MethodRouter};
43use printobserver_core::store::{
44    EventStore, HistoryQuery, ImageStore, PrintStore, SessionStore, StoreError,
45};
46use printobserver_core::{ActionKind, ExecutionOutcome, PolicyDecision};
47use printobserver_core::{CoreError, Supervisor, effective_bounds};
48use printobserver_types::serde::Deserialize;
49use printobserver_types::{ImageId, PrintId};
50
51use crate::config::ApiCredential;
52use crate::operations::{Effect, Method, OPERATIONS, Operation, VERSION_PREFIX};
53use crate::wire::{
54    ActionAnswer, ActionBody, ContextAnswer, ErrorAnswer, HistoryAnswer, ImageAnswer,
55    ManifestAnswer, ManifestBody, PrintsAnswer, StatusAnswer,
56};
57
58/// What every handler is given: the supervisor, and the stores the reads
59/// answer out of — the four aggregates a route reads, and not the actions,
60/// which reach the store through the supervisor alone.
61#[derive(Clone)]
62pub struct ApiState {
63    /// The supervision core, which every action passes through.
64    pub supervisor: Arc<Supervisor>,
65    /// The print records, their manifests and their narrowings.
66    pub prints: Arc<dyn PrintStore>,
67    /// The event log.
68    pub events: Arc<dyn EventStore>,
69    /// The images stored beside the events.
70    pub images: Arc<dyn ImageStore>,
71    /// The supervision sessions.
72    pub sessions: Arc<dyn SessionStore>,
73    /// The credential every request must present before anything above is
74    /// reached.
75    pub credential: Arc<ApiCredential>,
76}
77
78impl core::fmt::Debug for ApiState {
79    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
80        formatter.debug_struct("ApiState").finish_non_exhaustive()
81    }
82}
83
84/// How many events a history read asks for, when it asks for a number.
85#[derive(Debug, Clone, Deserialize)]
86#[serde(crate = "printobserver_types::serde")]
87pub struct HistoryParams {
88    /// The limit asked for; absent takes the port's own default window.
89    #[serde(default)]
90    pub limit: Option<u32>,
91}
92
93/// Every public operation, beneath the one versioned prefix.
94///
95/// # Panics
96///
97/// Panics when [`OPERATIONS`] declares an entry this function has no route for,
98/// which is a declaration and a router that have come apart — the one state
99/// this server must not come up in quietly.
100pub fn router(state: ApiState) -> Router {
101    let mut api = Router::new();
102    for operation in OPERATIONS {
103        api = api.route(operation.path, route_for(&operation));
104    }
105    // The layer is added after every route and the fallback, which is what
106    // puts all of them behind it.
107    let api = api
108        .fallback(nothing_here)
109        .layer(from_fn_with_state(
110            Arc::clone(&state.credential),
111            authenticate,
112        ))
113        .layer(DefaultBodyLimit::max(BODY_BOUND))
114        .with_state(state);
115    Router::new().nest(VERSION_PREFIX, api)
116}
117
118/// The scheme the credential is presented under.
119const BEARER: &[u8] = b"Bearer ";
120
121/// How much of a request's body this server reads, admitted or refused.
122///
123/// One bound for both: the router's body limit is set from it, so it is what
124/// every extractor reads an admitted body to, and what [`authenticate`] drains
125/// a refused one to — a body the server would have taken is one it drains,
126/// and a larger one is left where it is either way.
127pub const BODY_BOUND: usize = 2 * 1024 * 1024;
128
129/// How long [`authenticate`] waits for a refused request's body to arrive.
130///
131/// A caller that sent a head and then nothing would otherwise hold its refusal
132/// open for as long as it liked; after this the refusal goes out over whatever
133/// arrived, and the connection ends as it did before there was a drain.
134pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
135
136/// Admit a request that presented the credential in force, and refuse every
137/// other before anything reads it.
138///
139/// Exactly one `Authorization` header, spelled `Bearer ` and then the
140/// credential. Two headers, another scheme, another spelling of this one, and a
141/// credential that is not the one in force are all the same refusal, which says
142/// what to present and nothing about what was presented.
143///
144/// The refusal is decided on the head alone, and the body is then drained, up
145/// to [`BODY_BOUND`], before it is answered. Nothing reads what is
146/// drained: a connection closed with a body still unread on it is closed with
147/// a reset rather than an end, and a caller on Windows — where a reset discards
148/// everything received and not yet read — then reads the abort in place of the
149/// `401` that was already on its way. Linux hands over what was queued first,
150/// which is why the same race is only ever seen there.
151pub async fn authenticate(
152    State(credential): State<Arc<ApiCredential>>,
153    request: Request,
154    next: Next,
155) -> Response {
156    let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
157    let admitted = match (presented.next(), presented.next()) {
158        (Some(only), None) => only
159            .as_bytes()
160            .strip_prefix(BEARER)
161            .is_some_and(|offered| credential.admits(offered)),
162        _ => false,
163    };
164    if !admitted {
165        let mut refused = refusal(
166            StatusCode::UNAUTHORIZED,
167            "this server's API requires the credential it is configured with, presented as \
168             `Authorization: Bearer <credential>`",
169        );
170        refused.headers_mut().insert(
171            header::WWW_AUTHENTICATE,
172            header::HeaderValue::from_static("Bearer"),
173        );
174        // A body past the bound, or one that has not arrived inside
175        // `DRAIN_BOUND`, is left where it is: the refusal is the answer either
176        // way, and what a caller then meets on the connection is its own doing.
177        let _ = tokio::time::timeout(
178            DRAIN_BOUND,
179            axum::body::to_bytes(request.into_body(), BODY_BOUND),
180        )
181        .await;
182        return refused;
183    }
184    next.run(request).await
185}
186
187/// A path beneath the versioned prefix that no operation serves.
188async fn nothing_here() -> Response {
189    refusal(
190        StatusCode::NOT_FOUND,
191        "no operation of this server is served at that path",
192    )
193}
194
195/// The route one declared operation is served by.
196fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
197    if let Effect::Mutating(kind) = operation.effect {
198        return post(
199            move |state: State<ApiState>, print_id: Path<PrintId>, body: Json<ActionBody>| async move {
200                act(kind, state, print_id, body).await
201            },
202        );
203    }
204    match (operation.name, operation.method) {
205        ("prints", Method::Get) => get(list_and_adopt_prints),
206        ("status", Method::Get) => get(status),
207        ("context", Method::Get) => get(context),
208        ("image", Method::Get) => get(image),
209        ("history", Method::Get) => get(history),
210        ("manifest_get", Method::Get) => get(manifest_get),
211        ("manifest_set", Method::Put) => put(manifest_set),
212        (name, method) => panic!(
213            "the operation `{name}` is declared as {method} and this router serves no such route"
214        ),
215    }
216}
217
218/// One answer, rendered as JSON under the media type every operation answers in.
219fn answer<T: printobserver_types::serde::Serialize>(status: StatusCode, body: &T) -> Response {
220    let rendered = match printobserver_types::serde_json::to_vec(body) {
221        Ok(bytes) => bytes,
222        Err(error) => {
223            return (
224                StatusCode::INTERNAL_SERVER_ERROR,
225                [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
226                format!("{{\"error\":\"{error}\"}}"),
227            )
228                .into_response();
229        }
230    };
231    (
232        status,
233        [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
234        rendered,
235    )
236        .into_response()
237}
238
239/// One refusal, rendered as JSON under the same media type.
240fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
241    answer(status, &ErrorAnswer::saying(detail))
242}
243
244/// The status a store refusal is answered under.
245fn store_status(error: &StoreError) -> StatusCode {
246    match error {
247        StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
248        StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
249            StatusCode::BAD_REQUEST
250        }
251        StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
252    }
253}
254
255/// The status a core refusal is answered under.
256fn core_status(error: &CoreError) -> StatusCode {
257    match error {
258        CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
259        CoreError::Store(store) => store_status(store),
260        _ => StatusCode::INTERNAL_SERVER_ERROR,
261    }
262}
263
264/// Ask for one action of the vocabulary against one print.
265async fn act(
266    kind: ActionKind,
267    State(state): State<ApiState>,
268    Path(print_id): Path<PrintId>,
269    Json(body): Json<ActionBody>,
270) -> Response {
271    let action = match body.into_action(kind) {
272        Ok(action) => action,
273        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
274    };
275    let outcome = match state.supervisor.request_action(print_id, action).await {
276        Ok(outcome) => outcome,
277        Err(error) => return refusal(core_status(&error), error),
278    };
279    let printer_refusal = match &outcome.record.outcome {
280        Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
281        _ => None,
282    };
283    let status = match outcome.record.decision {
284        PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
285        // The policy accepted it and the machine did not. That is a request
286        // that was made and refused rather than one that never happened, so
287        // the record and the printer's own words are the answer.
288        PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
289        // The rejection itself is the answer: its reason, the value asked for
290        // and the range allowed are what let a caller ask again correctly.
291        PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
292    };
293    answer(
294        status,
295        &ActionAnswer {
296            record: outcome.record,
297            intervention: outcome.intervention,
298            printer_refusal,
299        },
300    )
301}
302
303/// List every print, and name the one the printer's job belongs to.
304///
305/// Reading this adopts that job when no open print carries its file name, which
306/// is how a print started at the printer gets an identifier before anything has
307/// reported on it. A printer that cannot be read still answers the stored
308/// prints, with nothing active.
309async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
310    match state.supervisor.list_and_adopt_prints().await {
311        Ok(listing) => answer(
312            StatusCode::OK,
313            &PrintsAnswer {
314                prints: listing.prints,
315                active: listing.active,
316            },
317        ),
318        Err(error) => refusal(core_status(&error), error),
319    }
320}
321
322/// Read one print's status.
323async fn status(State(state): State<ApiState>, Path(print_id): Path<PrintId>) -> Response {
324    let print = match state.prints.print(print_id).await {
325        Ok(Some(print)) => print,
326        Ok(None) => {
327            return refusal(
328                StatusCode::NOT_FOUND,
329                format!("there is no print {print_id}"),
330            );
331        }
332        Err(error) => return refusal(store_status(&error), error),
333    };
334    let context = match state.supervisor.context(print_id).await {
335        Ok(context) => context,
336        Err(error) => return refusal(core_status(&error), error),
337    };
338    let session = match state.sessions.session(print_id).await {
339        Ok(session) => session,
340        Err(error) => return refusal(store_status(&error), error),
341    };
342    answer(
343        StatusCode::OK,
344        &StatusAnswer {
345            print,
346            printer: context.printer,
347            job: context.job,
348            session,
349            interventions: context.interventions,
350        },
351    )
352}
353
354/// Read everything a supervision turn is given about one print, with the
355/// latest image materialized.
356///
357/// The path is looked up through the same store read the image operation
358/// answers from, so the two operations cannot disagree about where an image
359/// is. An image whose record is intact and whose file is gone answers no path,
360/// which is what the caller's own missing-file failure is about.
361async fn context(State(state): State<ApiState>, Path(print_id): Path<PrintId>) -> Response {
362    let context = match state.supervisor.context(print_id).await {
363        Ok(context) => context,
364        Err(error) => return refusal(core_status(&error), error),
365    };
366    let mut image_path = None;
367    if let Some(latest) = context.latest_image.as_ref() {
368        match state.images.image(latest.id).await {
369            Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
370            Err(error) => return refusal(store_status(&error), error),
371        }
372    }
373    answer(
374        StatusCode::OK,
375        &ContextAnswer {
376            context,
377            image_path,
378        },
379    )
380}
381
382/// Materialize one image: its record, and the absolute path its bytes are at.
383async fn image(State(state): State<ApiState>, Path(image_id): Path<ImageId>) -> Response {
384    match state.images.image(image_id).await {
385        Ok(lookup) => answer(StatusCode::OK, &ImageAnswer::from(lookup)),
386        Err(error) => refusal(store_status(&error), error),
387    }
388}
389
390/// Read one print's events, newest first.
391async fn history(
392    State(state): State<ApiState>,
393    Path(print_id): Path<PrintId>,
394    Query(params): Query<HistoryParams>,
395) -> Response {
396    let query = HistoryQuery {
397        print_id,
398        kinds: Vec::new(),
399        since: None,
400        until: None,
401        limit: params.limit,
402    };
403    match state.events.history(query).await {
404        Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
405        Err(error) => refusal(store_status(&error), error),
406    }
407}
408
409/// Read one print's manifest.
410async fn manifest_get(State(state): State<ApiState>, Path(print_id): Path<PrintId>) -> Response {
411    let manifest = match state.prints.manifest(print_id).await {
412        Ok(manifest) => manifest,
413        Err(error) => return refusal(store_status(&error), error),
414    };
415    let narrowings = match state.prints.print(print_id).await {
416        Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
417        Err(error) => return refusal(store_status(&error), error),
418    };
419    answer(
420        StatusCode::OK,
421        &ManifestAnswer {
422            manifest,
423            narrowings,
424        },
425    )
426}
427
428/// Write one print's manifest.
429///
430/// A manifest narrows what any actor may ask for, so replacing one is a change
431/// to the bounds a print runs under and carries a reason like every other
432/// change. The reason is ruled on **before** anything is written, so a request
433/// without one leaves the stored manifest and the print's narrowings as they
434/// were — and every range it asked wider than the envelope allows is recorded
435/// on the print, exactly as it is when a start attaches one.
436async fn manifest_set(
437    State(state): State<ApiState>,
438    Path(print_id): Path<PrintId>,
439    Json(body): Json<ManifestBody>,
440) -> Response {
441    if let Err(rejected) = body.reason() {
442        return refusal(StatusCode::BAD_REQUEST, rejected);
443    }
444    let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
445    if let Err(error) = state
446        .prints
447        .put_manifest(print_id, body.manifest.clone())
448        .await
449    {
450        return refusal(store_status(&error), error);
451    }
452    for narrowing in narrowed.narrowings.clone() {
453        if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
454            return refusal(store_status(&error), error);
455        }
456    }
457    answer(
458        StatusCode::OK,
459        &ManifestAnswer {
460            manifest: Some(body.manifest),
461            narrowings: narrowed.narrowings,
462        },
463    )
464}
465
466#[cfg(test)]
467mod tests {
468    use axum::http::StatusCode;
469    use printobserver_core::CoreError;
470    use printobserver_core::store::StoreError;
471
472    use super::{core_status, store_status};
473
474    /// Every refusal the store can make is answered under a status a caller can
475    /// act on: what it asked for, what is not there, and what went wrong here.
476    #[test]
477    fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
478        for (error, expected) in [
479            (
480                StoreError::NotFound {
481                    what: "print".to_owned(),
482                },
483                StatusCode::NOT_FOUND,
484            ),
485            (
486                StoreError::LimitRefused {
487                    limit: 1_000,
488                    asked_for: 2_000,
489                },
490                StatusCode::BAD_REQUEST,
491            ),
492            (
493                StoreError::ConstraintRefused {
494                    constraint: "actions.decision".to_owned(),
495                },
496                StatusCode::BAD_REQUEST,
497            ),
498            (
499                StoreError::Database {
500                    detail: "the disk is full".to_owned(),
501                },
502                StatusCode::INTERNAL_SERVER_ERROR,
503            ),
504            (
505                StoreError::Io {
506                    detail: "the disk is full".to_owned(),
507                },
508                StatusCode::INTERNAL_SERVER_ERROR,
509            ),
510        ] {
511            assert_eq!(store_status(&error), expected, "{error}");
512        }
513    }
514
515    /// A print nothing holds is not found; a port that failed is this server's
516    /// own failure rather than the caller's.
517    #[test]
518    fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
519        assert_eq!(
520            core_status(&CoreError::NoSuchPrint {
521                print_id: printobserver_types::PrintId::new(),
522            }),
523            StatusCode::NOT_FOUND
524        );
525        assert_eq!(
526            core_status(&CoreError::Store(StoreError::NotFound {
527                what: "print".to_owned(),
528            })),
529            StatusCode::NOT_FOUND
530        );
531        assert_eq!(
532            core_status(&CoreError::Unrepresentable {
533                detail: "an instant".to_owned(),
534            }),
535            StatusCode::INTERNAL_SERVER_ERROR
536        );
537    }
538}