1use std::sync::Arc;
62use std::time::Duration;
63
64use axum::Json;
65use axum::extract::rejection::{JsonRejection, QueryRejection};
66use axum::extract::{DefaultBodyLimit, Extension, Path, Query, Request, State};
67use axum::http::{StatusCode, header};
68use axum::middleware::{Next, from_fn_with_state};
69use axum::response::{IntoResponse, Response};
70use axum::routing::{get, post, put};
71use axum::{Router, routing::MethodRouter};
72use printobserver_core::recovery::recovery_detail;
73use printobserver_core::store::TimelineQuery;
74use printobserver_core::store::{
75 EventStore, HistoryQuery, ImageStore, PrintStore, SessionStore, StoreError,
76};
77use printobserver_core::{
78 ActionKind, Actor, ActorClass, ExecutionOutcome, PolicyDecision, RecoveryActionKind,
79 RecoveryDecision, SheetId, SpoolId,
80};
81use printobserver_core::{CoreError, MAX_LOOK_WAIT_S, Supervisor, effective_bounds};
82use printobserver_types::serde::Deserialize;
83use printobserver_types::serde_json::Value;
84use printobserver_types::{EventBody, EventId, EventKind, FileName, ImageId, PrintId, Timestamp};
85
86use crate::operations::{Effect, Method, OPERATIONS, Operation, VERSION_PREFIX};
87use crate::server::{CREDENTIAL_ISSUE, OperatorCredential};
88use crate::turns::{TurnBinding, TurnCredentials};
89use crate::wire::{
90 ActionAnswer, ActionBody, BedClearAnswer, BedClearBody, ContextAnswer, ErrorAnswer,
91 HistoryAnswer, ImageAnswer, ManifestAnswer, ManifestBody, PreflightAnswer, PrintsAnswer,
92 RecoveryAnswer, SpoolAnswer, SpoolCommandAnswer, SpoolsAnswer, StatusAnswer, TimelineAnswer,
93 claimed_actor, reason_of, recovery_of, spool_command_of,
94};
95
96#[derive(Clone)]
100pub struct ApiState {
101 pub supervisor: Arc<Supervisor>,
103 pub prints: Arc<dyn PrintStore>,
105 pub events: Arc<dyn EventStore>,
107 pub images: Arc<dyn ImageStore>,
109 pub sessions: Arc<dyn SessionStore>,
111 pub operator: Arc<OperatorCredential>,
114 pub turns: TurnCredentials,
116 pub stored: crate::events::Stored,
118 pub check_images: Option<Arc<crate::check_images::PanelImages>>,
122 pub harness: Arc<crate::readiness::HarnessCheck>,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq)]
128pub enum Caller {
129 Operator,
131 Turn(TurnBinding),
133}
134
135impl Caller {
136 fn named(&self) -> String {
138 match self {
139 Self::Operator => "the operator".to_owned(),
140 Self::Turn(binding) => format!(
141 "the agent in session `{}` on print {}",
142 binding.session_name(),
143 binding.print_id()
144 ),
145 }
146 }
147}
148
149fn claimed(actor: &Actor) -> String {
151 match actor {
152 Actor::Operator => "the operator".to_owned(),
153 Actor::System => "the system".to_owned(),
154 Actor::Agent { session_name } => format!("the agent in session `{session_name}`"),
155 }
156}
157
158fn claim_refused(caller: &Caller, actor: &Actor) -> Option<Response> {
163 let held = match (caller, actor) {
164 (Caller::Operator, Actor::Operator) => true,
165 (Caller::Turn(binding), Actor::Agent { session_name }) => {
166 *session_name == binding.session_name()
167 }
168 _ => false,
169 };
170 if held {
171 return None;
172 }
173 let why = if matches!(actor, Actor::System) {
174 "no credential may claim the system, whose actions are the server's own"
175 } else {
176 "a request acts as the identity its credential authenticated, and no other"
177 };
178 Some(refusal(
179 StatusCode::FORBIDDEN,
180 format!(
181 "this request authenticated as {} and claims to be {}: {why}",
182 caller.named(),
183 claimed(actor)
184 ),
185 ))
186}
187
188pub(crate) fn scope_refused(caller: &Caller, print_id: PrintId) -> Option<Response> {
190 match caller {
191 Caller::Turn(binding) if binding.print_id() != print_id => Some(refusal(
192 StatusCode::FORBIDDEN,
193 format!(
194 "this request authenticated as {} and names print {print_id}: a supervision \
195 turn's credential reaches its own print alone",
196 caller.named()
197 ),
198 )),
199 _ => None,
200 }
201}
202
203fn printless_refused(caller: &Caller, what: &str) -> Option<Response> {
207 match caller {
208 Caller::Turn(_) => Some(refusal(
209 StatusCode::FORBIDDEN,
210 format!(
211 "this request authenticated as {} and asks for {what}: a supervision turn's \
212 credential reaches its own print alone",
213 caller.named()
214 ),
215 )),
216 Caller::Operator => None,
217 }
218}
219
220fn operator_refused(caller: &Caller, command: &str) -> Option<Response> {
223 match caller {
224 Caller::Turn(_) => Some(refusal(
225 StatusCode::FORBIDDEN,
226 format!(
227 "this request authenticated as {} and asks for `{command}`, which is the \
228 operator's alone: a supervision turn's credential does not reach it",
229 caller.named()
230 ),
231 )),
232 Caller::Operator => None,
233 }
234}
235
236fn unlooked_refused(
244 turns: &TurnCredentials,
245 caller: &Caller,
246 print_id: PrintId,
247) -> Option<Response> {
248 match caller {
249 Caller::Turn(binding) if !turns.has_looked(binding) => Some(refusal(
250 StatusCode::FORBIDDEN,
251 format!(
252 "this request authenticated as {} and acknowledges an event before the turn \
253 has taken a look: run `printobserver look --print-id {print_id}`, open the \
254 frames it names, and acknowledge what they show",
255 caller.named()
256 ),
257 )),
258 _ => None,
259 }
260}
261
262#[derive(Clone)]
264pub struct Admission {
265 operator: Arc<OperatorCredential>,
267 turns: TurnCredentials,
269}
270
271impl Admission {
272 fn caller(&self, presented: &[u8]) -> Option<Caller> {
274 if let Some(binding) = self.turns.admit(presented) {
275 return Some(Caller::Turn(binding));
276 }
277 self.operator.admits(presented).then_some(Caller::Operator)
278 }
279}
280
281impl core::fmt::Debug for ApiState {
282 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
283 formatter.debug_struct("ApiState").finish_non_exhaustive()
284 }
285}
286
287#[derive(Debug, Clone, Deserialize)]
289#[serde(crate = "printobserver_types::serde")]
290pub struct HistoryParams {
291 #[serde(default)]
293 pub limit: Option<u32>,
294}
295
296#[derive(Debug, Clone, Deserialize)]
299#[serde(crate = "printobserver_types::serde")]
300pub struct ContextParams {
301 #[serde(default)]
303 pub since: Option<printobserver_types::EventId>,
304}
305
306#[derive(Debug, Clone, Deserialize)]
308#[serde(crate = "printobserver_types::serde")]
309pub struct LookParams {
310 #[serde(default)]
312 pub wait_s: Option<u32>,
313}
314
315#[derive(Debug, Clone, Deserialize)]
317#[serde(crate = "printobserver_types::serde")]
318pub struct SpoolsParams {
319 #[serde(default)]
321 pub include_retired: Option<bool>,
322}
323
324#[derive(Debug, Clone, Deserialize)]
326#[serde(crate = "printobserver_types::serde")]
327pub struct PreflightParams {
328 #[serde(default)]
330 pub file_name: Option<String>,
331 #[serde(default)]
335 pub sheet: Option<String>,
336}
337
338pub const SPOOL_RECENT_EVENTS: u32 = 20;
340
341pub fn router(state: ApiState) -> Router {
349 let mut api = Router::new();
350 for operation in OPERATIONS {
351 api = api.route(operation.path, route_for(&operation));
352 }
353 let api = api
356 .fallback(nothing_here)
357 .layer(from_fn_with_state(
358 Admission {
359 operator: Arc::clone(&state.operator),
360 turns: state.turns.clone(),
361 },
362 authenticate,
363 ))
364 .layer(DefaultBodyLimit::max(BODY_BOUND))
365 .with_state(state);
366 Router::new().nest(VERSION_PREFIX, api)
367}
368
369const BEARER: &[u8] = b"Bearer ";
371
372pub const BODY_BOUND: usize = 2 * 1024 * 1024;
379
380pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
386
387pub async fn authenticate(
405 State(admission): State<Admission>,
406 mut request: Request,
407 next: Next,
408) -> Response {
409 let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
410 let admitted = match (presented.next(), presented.next()) {
411 (Some(only), None) => only
412 .as_bytes()
413 .strip_prefix(BEARER)
414 .and_then(|offered| admission.caller(offered)),
415 _ => None,
416 };
417 if let Some(caller) = admitted {
418 request.extensions_mut().insert(caller);
419 return next.run(request).await;
420 }
421 {
422 let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
423 format!(
424 "this server's API requires a credential, presented as `Authorization: Bearer \
425 <credential>`, and this server has no operator credential yet: run \
426 `{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
427 prints into the server's configuration, and restart the service"
428 )
429 } else {
430 format!(
431 "this server's API requires the credential it is configured with, presented as \
432 `Authorization: Bearer <credential>`. An operator without one runs \
433 `{CREDENTIAL_ISSUE}`"
434 )
435 };
436 let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
437 refused.headers_mut().insert(
438 header::WWW_AUTHENTICATE,
439 header::HeaderValue::from_static("Bearer"),
440 );
441 let _ = tokio::time::timeout(
445 DRAIN_BOUND,
446 axum::body::to_bytes(request.into_body(), BODY_BOUND),
447 )
448 .await;
449 refused
450 }
451}
452
453async fn nothing_here() -> Response {
455 refusal(
456 StatusCode::NOT_FOUND,
457 "no operation of this server is served at that path",
458 )
459}
460
461fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
463 if let Effect::Command(spool_command) = operation.effect {
464 let kind = spool_command.action_kind();
465 if operation.path.contains("{spool_id}") {
466 return post(
467 move |state: State<ApiState>,
468 caller: Extension<Caller>,
469 Path(spool_id): Path<SpoolId>,
470 body: Result<Json<Value>, JsonRejection>| async move {
471 command(kind, state, caller, Some(spool_id), body).await
472 },
473 );
474 }
475 return post(
476 move |state: State<ApiState>,
477 caller: Extension<Caller>,
478 body: Result<Json<Value>, JsonRejection>| async move {
479 command(kind, state, caller, None, body).await
480 },
481 );
482 }
483 if let Effect::Recovery(kind) = operation.effect {
484 return post(
485 move |state: State<ApiState>,
486 caller: Extension<Caller>,
487 body: Result<Json<Value>, JsonRejection>| async move {
488 recover(kind, state, caller, body).await
489 },
490 );
491 }
492 if let Effect::Mutating(kind) = operation.effect {
493 return post(
494 move |state: State<ApiState>,
495 caller: Extension<Caller>,
496 print_id: PrintPath,
497 body: Result<Json<ActionBody>, JsonRejection>| async move {
498 act(kind, state, caller, print_id, body).await
499 },
500 );
501 }
502 match (operation.name, operation.method) {
503 ("prints", Method::Get) => get(list_and_adopt_prints),
504 ("status", Method::Get) => get(status),
505 ("context", Method::Get) => get(context),
506 ("image", Method::Get) => get(image),
507 ("history", Method::Get) => get(history),
508 ("events", Method::Get) => get(crate::events::events),
509 ("look", Method::Get) => get(look),
510 (crate::operations::PRINTER_LOOK, Method::Get) => get(printer_look),
511 ("manifest_get", Method::Get) => get(manifest_get),
512 ("manifest_set", Method::Put) => put(manifest_set),
513 ("spools", Method::Get) => get(spools),
514 ("spool", Method::Get) => get(spool),
515 ("printer_history", Method::Get) => get(printer_history),
516 ("preflight", Method::Get) => get(preflight),
517 (crate::operations::RECOVERY_STATUS, Method::Get) => get(recover_status),
518 (crate::operations::BED_CLEAR, Method::Post) => post(bed_clear),
519 (crate::operations::RECHECK_CAMERA, Method::Post) => post(recheck_camera),
520 (crate::operations::CHECK_CAMERA, Method::Get) => get(check_camera),
521 (crate::operations::CHECK_HARNESS, Method::Get) => get(check_harness),
522 (name, method) => panic!(
523 "the operation `{name}` is declared as {method} and this router serves no such route"
524 ),
525 }
526}
527
528async fn check_harness(State(state): State<ApiState>, caller: Extension<Caller>) -> Response {
537 if let Some(refused) = printless_refused(&caller, "a check of the supervising harness") {
538 return refused;
539 }
540 let check = Arc::clone(&state.harness);
541 match tokio::task::spawn_blocking(move || check.run()).await {
542 Ok(readiness) => answer(StatusCode::OK, &readiness),
543 Err(error) => refusal(
544 StatusCode::INTERNAL_SERVER_ERROR,
545 format!("the harness check did not finish: {error}"),
546 ),
547 }
548}
549
550pub(crate) fn answer<T: printobserver_types::serde::Serialize>(
552 status: StatusCode,
553 body: &T,
554) -> Response {
555 let rendered = match printobserver_types::serde_json::to_vec(body) {
556 Ok(bytes) => bytes,
557 Err(error) => {
558 return (
559 StatusCode::INTERNAL_SERVER_ERROR,
560 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
561 format!("{{\"error\":\"{error}\"}}"),
562 )
563 .into_response();
564 }
565 };
566 (
567 status,
568 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
569 rendered,
570 )
571 .into_response()
572}
573
574pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
576 answer(status, &ErrorAnswer::saying(detail))
577}
578
579pub(crate) const PRINT_ID_REFUSED: &str = "a print is named by its id, a UUID, as `printobserver prints` \
582lists it; a start with no print open may name none, and is made under one minted for it";
583
584pub(crate) struct PrintPath(pub(crate) PrintId);
587
588impl<S: Send + Sync> axum::extract::FromRequestParts<S> for PrintPath {
589 type Rejection = Response;
590
591 async fn from_request_parts(
592 parts: &mut axum::http::request::Parts,
593 state: &S,
594 ) -> Result<Self, Self::Rejection> {
595 match Path::<PrintId>::from_request_parts(parts, state).await {
596 Ok(Path(print_id)) => Ok(Self(print_id)),
597 Err(rejected) => Err(refusal(
598 StatusCode::BAD_REQUEST,
599 format!("{}: {PRINT_ID_REFUSED}", rejected.body_text()),
600 )),
601 }
602 }
603}
604
605pub(crate) fn store_status(error: &StoreError) -> StatusCode {
607 match error {
608 StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
609 StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
610 StatusCode::BAD_REQUEST
611 }
612 StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
613 }
614}
615
616fn core_status(error: &CoreError) -> StatusCode {
618 match error {
619 CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
620 CoreError::Store(store) => store_status(store),
621 _ => StatusCode::INTERNAL_SERVER_ERROR,
622 }
623}
624
625async fn act(
633 kind: ActionKind,
634 State(state): State<ApiState>,
635 Extension(caller): Extension<Caller>,
636 PrintPath(print_id): PrintPath,
637 body: Result<Json<ActionBody>, JsonRejection>,
638) -> Response {
639 if kind == ActionKind::StartPrint
640 && let Some(refused) =
641 operator_refused(&caller, &crate::operations::command_for("start_print"))
642 {
643 return refused;
644 }
645 if let Some(refused) = scope_refused(&caller, print_id) {
646 return refused;
647 }
648 let body = match body {
649 Ok(Json(body)) => body,
650 Err(rejected) => return rejected.into_response(),
651 };
652 if let Some(refused) = claim_refused(&caller, &body.actor) {
653 return refused;
654 }
655 if kind == ActionKind::AcknowledgeFailure
656 && let Some(refused) = unlooked_refused(&state.turns, &caller, print_id)
657 {
658 return refused;
659 }
660 let action = match body.into_action(kind) {
661 Ok(action) => action,
662 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
663 };
664 let outcome = match state.supervisor.request_action(print_id, action).await {
665 Ok(outcome) => outcome,
666 Err(error) => return refusal(core_status(&error), error),
667 };
668 let printer_refusal = match &outcome.record.outcome {
669 Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
670 _ => None,
671 };
672 let status = match outcome.record.decision {
673 PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
674 PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
678 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
681 };
682 answer(
683 status,
684 &ActionAnswer {
685 record: outcome.record,
686 intervention: outcome.intervention,
687 printer_refusal,
688 },
689 )
690}
691
692async fn command(
701 kind: ActionKind,
702 State(state): State<ApiState>,
703 Extension(caller): Extension<Caller>,
704 spool_id: Option<SpoolId>,
705 body: Result<Json<Value>, JsonRejection>,
706) -> Response {
707 let body = match body {
708 Ok(Json(body)) => body,
709 Err(rejected) => return rejected.into_response(),
710 };
711 let Some(fields) = body.as_object() else {
712 return refusal(
713 StatusCode::BAD_REQUEST,
714 "a spool command's body is a document of its fields",
715 );
716 };
717 let actor = match claimed_actor(fields) {
718 Ok(actor) => actor,
719 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
720 };
721 if let Some(refused) = claim_refused(&caller, &actor) {
722 return refused;
723 }
724 let asked = match spool_command_of(kind, spool_id, body) {
725 Ok(asked) => asked,
726 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
727 };
728 let outcome = match state.supervisor.request_spool_command(asked).await {
729 Ok(outcome) => outcome,
730 Err(error) => return refusal(core_status(&error), error),
731 };
732 let status = match outcome.decision {
733 PolicyDecision::Accepted => StatusCode::OK,
734 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
736 };
737 answer(
738 status,
739 &SpoolCommandAnswer {
740 decision: outcome.decision,
741 spool: outcome.spool,
742 events: outcome.events,
743 },
744 )
745}
746
747async fn recover(
755 kind: RecoveryActionKind,
756 State(state): State<ApiState>,
757 Extension(caller): Extension<Caller>,
758 body: Result<Json<Value>, JsonRejection>,
759) -> Response {
760 let body = match body {
761 Ok(Json(body)) => body,
762 Err(rejected) => return rejected.into_response(),
763 };
764 if let Some(fields) = body.as_object() {
765 let actor = match claimed_actor(fields) {
766 Ok(actor) => actor,
767 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
768 };
769 if let Some(refused) = claim_refused(&caller, &actor) {
770 return refused;
771 }
772 }
773 let (action, actor, reason) = match recovery_of(kind, body) {
774 Ok(asked) => asked,
775 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
776 };
777 let issued = match state
778 .supervisor
779 .request_recovery(action.clone(), actor, reason)
780 .await
781 {
782 Ok(issued) => issued,
783 Err(error) => return refusal(core_status(&error), error),
784 };
785 let config = state.supervisor.config().recovery;
786 let status = match &issued.decision {
787 RecoveryDecision::Executed(ExecutionOutcome::Succeeded) => StatusCode::OK,
788 RecoveryDecision::Executed(ExecutionOutcome::Failed { .. }) => StatusCode::BAD_GATEWAY,
791 RecoveryDecision::Rejected(_) => StatusCode::CONFLICT,
793 };
794 answer(
795 status,
796 &RecoveryAnswer {
797 detail: recovery_detail(&action, &issued.decision, config.as_ref()),
798 action,
799 decision: issued.decision,
800 events: vec![issued.requested, issued.settled],
801 },
802 )
803}
804
805pub const BED_CLEAR_DETAIL: &str = "recorded: until the next print starts, a Z home is decided \
807 as though it asserted the bed clear, and a heat, a park and an XY home as though they \
808 asserted the nozzle clear of the part, wherever the operator's word counts";
809
810async fn bed_clear(
818 State(state): State<ApiState>,
819 Extension(caller): Extension<Caller>,
820 body: Result<Json<Value>, JsonRejection>,
821) -> Response {
822 let body = match body {
823 Ok(Json(body)) => body,
824 Err(rejected) => return rejected.into_response(),
825 };
826 let Some(fields) = body.as_object() else {
827 return refusal(
828 StatusCode::BAD_REQUEST,
829 "the body is not a document carrying an `actor` and a `reason`",
830 );
831 };
832 let actor = match claimed_actor(fields) {
833 Ok(actor) => actor,
834 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
835 };
836 if let Some(refused) = claim_refused(&caller, &actor) {
837 return refused;
838 }
839 if actor != Actor::Operator {
840 return refusal(
841 StatusCode::FORBIDDEN,
842 format!(
843 "{} may not say the bed is clear: an assertion is a person's word for what \
844 they can see, and only the operator's is recorded",
845 claimed(&actor)
846 ),
847 );
848 }
849 let body: BedClearBody = match printobserver_types::serde_json::from_value(body) {
850 Ok(body) => body,
851 Err(error) => {
852 return refusal(
853 StatusCode::BAD_REQUEST,
854 format!("the body is not an `actor` and a `reason`: {error}"),
855 );
856 }
857 };
858 let reason = match reason_of(body.reason.as_deref()) {
859 Ok(reason) => reason,
860 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
861 };
862 match state.supervisor.assert_bed_clear(reason).await {
863 Ok(event) => answer(
864 StatusCode::OK,
865 &BedClearAnswer {
866 event,
867 detail: BED_CLEAR_DETAIL.to_owned(),
868 },
869 ),
870 Err(error) => refusal(core_status(&error), error),
871 }
872}
873
874async fn recheck_camera(
892 State(state): State<ApiState>,
893 Extension(caller): Extension<Caller>,
894 PrintPath(print_id): PrintPath,
895 body: Result<Json<Value>, JsonRejection>,
896) -> Response {
897 if let Some(refused) = scope_refused(&caller, print_id) {
898 return refused;
899 }
900 let (actor, reason) = match actor_and_reason(&caller, body) {
901 Ok(asked) => asked,
902 Err(refused) => return *refused,
903 };
904 match state.prints.print(print_id).await {
908 Ok(Some(_)) => {}
909 Ok(None) => {
910 return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
911 }
912 Err(error) => return refusal(store_status(&error), error),
913 }
914 let Some(images) = state.check_images.clone() else {
915 return refusal(
916 StatusCode::SERVICE_UNAVAILABLE,
917 "nothing judges this server's camera frames",
918 );
919 };
920 if state.supervisor.config().camera_snapshot_url.is_none() {
921 return refusal(
922 StatusCode::SERVICE_UNAVAILABLE,
923 "no camera is configured to judge: set the server's `[camera] snapshot_url`",
924 );
925 }
926 let supervisor = Arc::clone(&state.supervisor);
927 let fresh = tokio::task::spawn_blocking(move || {
928 printobserver_core::block_on(supervisor.fresh_view(print_id))
929 })
930 .await;
931 let fresh = match fresh {
932 Ok(Ok(fresh)) => fresh,
933 Ok(Err(error)) => return refusal(core_status(&error), error),
934 Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
935 };
936 let Some((url, image)) = fresh.frame.clone() else {
937 return refusal(
938 StatusCode::SERVICE_UNAVAILABLE,
939 "the camera gave no good frame to judge",
940 );
941 };
942 let sha256 = hex_sha256(image.bytes.as_slice());
943 let captured_at = image
944 .captured_at
945 .unwrap_or_else(printobserver_types::Timestamp::now);
946 let alignment = crate::alignment::AlignmentJudging::of_recheck(fresh.paused);
947 images.adopt_camera_check(print_id, fresh.camera_check.as_ref());
948 let judging = Arc::clone(&images);
949 let plan = fresh.plan.clone();
950 let bytes = image.bytes.as_slice().to_vec();
951 let digest = sha256.clone();
952 let judged = tokio::task::spawn_blocking(move || {
953 judging.judge_frame(print_id, &bytes, &digest, plan.as_ref(), alignment)
954 })
955 .await;
956 let judged = match judged {
957 Ok(Some(judged)) => judged,
958 Ok(None) => crate::alignment::Judged::nothing_to_judge(
962 images.alignment(print_id),
963 EventBody::of(&printobserver_core::CameraLookPayload {
964 waited_s: 0,
965 delivered: Vec::new(),
966 frame_captured_at: Some(captured_at),
967 })
968 .ok(),
969 ),
970 Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
971 };
972 if let Some(detail) = &judged.unreadable {
973 return refusal(StatusCode::SERVICE_UNAVAILABLE, detail);
974 }
975 eprintln!(
976 "printobserver: print {print_id}: the camera is judged again for {}: {reason}",
977 claimed(&actor)
978 );
979 let frame_path = match stored_with_frame(&state, print_id, &judged, (url, image)).await {
980 Ok(path) => path,
981 Err(refused) => return refused,
982 };
983 let shown =
984 match image_shown(&images, print_id, &frame_path, captured_at, &fresh, &judged).await {
985 Ok(shown) => shown,
986 Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
987 };
988 answer(
989 StatusCode::OK,
990 &crate::wire::RecheckCameraAnswer {
991 frame_path,
992 alignment: judged.alignment,
993 view_correction: judged.correction,
994 image_kind: shown.kind(),
995 image_fallback: shown.fallback,
996 },
997 )
998}
999
1000async fn check_camera(
1013 State(state): State<ApiState>,
1014 Extension(caller): Extension<Caller>,
1015 query: Result<Query<crate::camera_check::CheckCameraQuery>, QueryRejection>,
1016) -> Response {
1017 if let Some(refused) = printless_refused(&caller, "a check of the printer's camera") {
1018 return refused;
1019 }
1020 let body = match query {
1021 Ok(Query(query)) => query,
1022 Err(error) => {
1023 return refusal(
1024 StatusCode::BAD_REQUEST,
1025 format!("a camera check names a `sheet` and a `bed_z_mm`: {error}"),
1026 );
1027 }
1028 };
1029 let known = printobserver_panels::SheetOutline::committed_sheets();
1030 let sheet = match printobserver_core::SheetId::try_from(body.sheet.clone()) {
1031 Ok(sheet) if known.contains(&sheet.as_str()) => sheet,
1032 _ => {
1033 return refusal(
1034 StatusCode::BAD_REQUEST,
1035 format!(
1036 "`sheet` is `{}`, and the sheets a camera check knows the outline of are {}",
1037 body.sheet,
1038 known.join(", ")
1039 ),
1040 );
1041 }
1042 };
1043 if !(body.bed_z_mm.is_finite() && body.bed_z_mm >= 0.0) {
1044 return refusal(
1045 StatusCode::BAD_REQUEST,
1046 "`bed_z_mm` must be the bed's height in millimetres, read back with M114 while idle: \
1047 a finite number at or above zero",
1048 );
1049 }
1050 if let Err(error) = state.events.newest_stored().await {
1053 return refusal(store_status(&error), error);
1054 }
1055 let Some(images) = state.check_images.clone() else {
1056 return refusal(
1057 StatusCode::SERVICE_UNAVAILABLE,
1058 "nothing judges this server's camera frames",
1059 );
1060 };
1061 let calibration = images.calibration().cloned();
1062 let asked = crate::camera_check::Asked {
1063 id: printobserver_core::CameraCheckId::new(),
1064 checked_at: printobserver_types::Timestamp::now(),
1065 sheet,
1066 bed_z_mm: body.bed_z_mm,
1067 };
1068 let look = match state.supervisor.take_check_look().await {
1069 Ok(look) => look,
1070 Err(error) => return refusal(core_status(&error), error),
1071 };
1072 let check = match checked(&images, asked, look, calibration).await {
1073 Ok(check) => check,
1074 Err(refused) => return *refused,
1075 };
1076 let body = match EventBody::of(&crate::camera_check::CameraCheckedPayload {
1077 camera_check: check.clone(),
1078 }) {
1079 Ok(body) => body,
1080 Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1081 };
1082 if let Err(error) = state
1083 .events
1084 .append_event(printobserver_core::store::EventDraft {
1085 print_id: None,
1086 source: printobserver_core::operator_source(),
1087 received_at: check.checked_at,
1088 body,
1089 raw: None,
1090 })
1091 .await
1092 {
1093 return refusal(store_status(&error), error);
1094 }
1095 eprintln!(
1096 "printobserver: camera check {} on {} at bed Z {:.2}: {}",
1097 check.id,
1098 check.sheet.as_str(),
1099 check.bed_z_mm,
1100 check.verdict.as_str()
1101 );
1102 answer(StatusCode::OK, &check)
1103}
1104
1105async fn checked(
1109 images: &crate::check_images::PanelImages,
1110 asked: crate::camera_check::Asked,
1111 look: printobserver_core::CheckLook,
1112 calibration: Option<printobserver_panels::CameraCalibration>,
1113) -> Result<crate::camera_check::CameraCheck, Box<Response>> {
1114 use crate::camera_check::UnavailableReason;
1115 Ok(match (look, calibration) {
1116 (printobserver_core::CheckLook::NoCamera, _) => {
1117 return Err(Box::new(refusal(
1118 StatusCode::SERVICE_UNAVAILABLE,
1119 "no camera is configured to check: set the server's `[camera] snapshot_url`",
1120 )));
1121 }
1122 (printobserver_core::CheckLook::NoFrame { detail, .. }, _) => {
1123 asked.camera_unavailable(UnavailableReason::NoFrame, &detail, None)
1124 }
1125 (printobserver_core::CheckLook::Failed { detail, .. }, _) => {
1126 asked.camera_unavailable(UnavailableReason::LookFailed, &detail, None)
1127 }
1128 (printobserver_core::CheckLook::Framed { frame, path, .. }, None) => {
1129 asked.camera_unavailable(UnavailableReason::NoCalibration, "", Some((frame, path)))
1130 }
1131 (
1132 printobserver_core::CheckLook::Framed {
1133 frame,
1134 path,
1135 bytes,
1136 url,
1137 ..
1138 },
1139 Some(calibration),
1140 ) => {
1141 let sheet = asked.sheet.clone();
1142 let bed_z_mm = asked.bed_z_mm;
1143 let tolerance = calibration.drift_tolerance_px;
1144 let fitted = tokio::task::spawn_blocking(move || {
1145 printobserver_panels::SheetOutline::committed(sheet.as_str()).map(|outline| {
1147 printobserver_panels::fit_sheet(&printobserver_panels::SheetInputs {
1148 frame_jpeg: &bytes,
1149 camera_snapshot_url: &url,
1150 calibration: &calibration,
1151 sheet: outline,
1152 bed_z_mm,
1153 })
1154 })
1155 })
1156 .await;
1157 let Ok(Some(fitted)) = fitted else {
1158 return Err(Box::new(refusal(
1159 StatusCode::INTERNAL_SERVER_ERROR,
1160 "the camera check's fit did not finish",
1161 )));
1162 };
1163 match fitted {
1164 Ok(fit) => {
1165 let drawn = match images.write_camera_check_image(asked.id, &fit.drawn_jpeg) {
1166 Ok(drawn) => drawn,
1167 Err(error) => {
1168 return Err(Box::new(refusal(
1169 StatusCode::INTERNAL_SERVER_ERROR,
1170 error,
1171 )));
1172 }
1173 };
1174 asked.judged(&fit, tolerance, frame, drawn)
1175 }
1176 Err(error @ printobserver_panels::ComposeError::FrameMismatch { .. }) => asked
1177 .camera_unavailable(
1178 UnavailableReason::FrameMismatch,
1179 &error.to_string(),
1180 Some((frame, path)),
1181 ),
1182 Err(error) => asked.camera_unavailable(
1183 UnavailableReason::NoFrame,
1184 &error.to_string(),
1185 Some((frame, path)),
1186 ),
1187 }
1188 }
1189 })
1190}
1191
1192fn actor_and_reason(
1195 caller: &Caller,
1196 body: Result<Json<Value>, JsonRejection>,
1197) -> Result<(Actor, String), Box<Response>> {
1198 let refused = |status: StatusCode, said: String| Box::new(refusal(status, said));
1199 let body = match body {
1200 Ok(Json(body)) => body,
1201 Err(rejected) => return Err(Box::new(rejected.into_response())),
1202 };
1203 let Some(fields) = body.as_object() else {
1204 return Err(refused(
1205 StatusCode::BAD_REQUEST,
1206 "the body is not a document carrying an `actor` and a `reason`".to_owned(),
1207 ));
1208 };
1209 let actor = claimed_actor(fields)
1210 .map_err(|rejected| refused(StatusCode::BAD_REQUEST, rejected.to_string()))?;
1211 if let Some(claim) = claim_refused(caller, &actor) {
1212 return Err(Box::new(claim));
1213 }
1214 let body: BedClearBody =
1215 printobserver_types::serde_json::from_value(body).map_err(|error| {
1216 refused(
1217 StatusCode::BAD_REQUEST,
1218 format!("the body is not an `actor` and a `reason`: {error}"),
1219 )
1220 })?;
1221 let reason = reason_of(body.reason.as_deref())
1222 .map_err(|rejected| refused(StatusCode::BAD_REQUEST, rejected.to_string()))?;
1223 Ok((actor, reason))
1224}
1225
1226async fn image_shown(
1229 images: &Arc<crate::check_images::PanelImages>,
1230 print_id: PrintId,
1231 frame_path: &std::path::Path,
1232 captured_at: printobserver_types::Timestamp,
1233 fresh: &printobserver_core::FreshView,
1234 judged: &crate::alignment::Judged,
1235) -> Result<printobserver_core::ShownImage, String> {
1236 let choosing = Arc::clone(images);
1237 let path = frame_path.to_path_buf();
1238 let plan = fresh.plan.clone();
1239 let paused = fresh.paused;
1240 let judged = judged.clone();
1241 tokio::task::spawn_blocking(move || {
1242 choosing.image_of(
1243 print_id,
1244 &crate::check_images::Shown {
1245 frame: &path,
1246 captured_at,
1247 made_for: printobserver_core::ImageUse::Look,
1248 plan: plan.as_ref(),
1249 paused,
1250 },
1251 Some(&judged),
1252 )
1253 })
1254 .await
1255 .map_err(|error| error.to_string())?
1256}
1257
1258async fn stored_with_frame(
1262 state: &ApiState,
1263 print_id: PrintId,
1264 judged: &crate::alignment::Judged,
1265 frame: (String, printobserver_vision_api::FetchedImage),
1266) -> Result<std::path::PathBuf, Response> {
1267 let mut frame = Some(frame);
1268 let mut stored = None;
1269 for record in judged.records.clone() {
1270 let event = state
1271 .supervisor
1272 .record_with_frame(print_id, record, frame.take())
1273 .await
1274 .map_err(|error| refusal(core_status(&error), error))?;
1275 if stored.is_none() {
1276 stored = event.image;
1277 }
1278 }
1279 let unkept = || {
1280 refusal(
1281 StatusCode::INTERNAL_SERVER_ERROR,
1282 "the fresh frame was not kept",
1283 )
1284 };
1285 let reference = stored.ok_or_else(unkept)?;
1286 match state.images.image(reference.id).await {
1287 Ok(printobserver_core::store::ImageLookup::Found { path, .. }) => Ok(path),
1288 _ => Err(unkept()),
1289 }
1290}
1291
1292fn hex_sha256(bytes: &[u8]) -> String {
1294 use sha2::Digest as _;
1295 sha2::Sha256::digest(bytes)
1296 .iter()
1297 .fold(String::with_capacity(64), |mut text, byte| {
1298 use core::fmt::Write as _;
1299 let _ = write!(text, "{byte:02x}");
1300 text
1301 })
1302}
1303
1304async fn recover_status(
1307 State(state): State<ApiState>,
1308 Extension(caller): Extension<Caller>,
1309) -> Response {
1310 let class = match caller {
1311 Caller::Operator => ActorClass::Operator,
1312 Caller::Turn(_) => ActorClass::Agent,
1313 };
1314 match state.supervisor.recovery_status(class).await {
1315 Ok(status) => answer(StatusCode::OK, &status),
1316 Err(error) => refusal(core_status(&error), error),
1317 }
1318}
1319
1320async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
1322 let listed = match state
1323 .supervisor
1324 .spools(params.include_retired.unwrap_or(false))
1325 .await
1326 {
1327 Ok(listed) => listed,
1328 Err(error) => return refusal(core_status(&error), error),
1329 };
1330 match state.supervisor.pending_charges(None).await {
1331 Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
1332 Err(error) => refusal(core_status(&error), error),
1333 }
1334}
1335
1336async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
1338 let found = match state.supervisor.spool(spool_id).await {
1339 Ok(Some(found)) => found,
1340 Ok(None) => {
1341 return refusal(
1342 StatusCode::NOT_FOUND,
1343 format!("there is no spool {spool_id}"),
1344 );
1345 }
1346 Err(error) => return refusal(core_status(&error), error),
1347 };
1348 let query = TimelineQuery {
1349 spool_id: Some(spool_id),
1350 limit: Some(SPOOL_RECENT_EVENTS),
1351 ..every_timeline_kind()
1352 };
1353 match state.supervisor.timeline(query).await {
1354 Ok(recent) => answer(
1355 StatusCode::OK,
1356 &SpoolAnswer {
1357 spool: found,
1358 recent,
1359 },
1360 ),
1361 Err(error) => refusal(core_status(&error), error),
1362 }
1363}
1364
1365const fn every_timeline_kind() -> TimelineQuery {
1367 TimelineQuery {
1368 kinds: Vec::new(),
1369 since: None,
1370 until: None,
1371 spool_id: None,
1372 before: None,
1373 limit: None,
1374 }
1375}
1376
1377fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
1379where
1380 T::Err: core::fmt::Display,
1381{
1382 text.parse()
1383 .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
1384}
1385
1386fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
1393 let mut query = every_timeline_kind();
1394 let mut seen: Vec<&str> = Vec::new();
1395 for (name, text) in asked {
1396 if name != "kinds" {
1397 if seen.contains(&name.as_str()) {
1398 return Err(format!(
1399 "`{name}` was given more than once, and this read takes one"
1400 ));
1401 }
1402 seen.push(name);
1403 }
1404 match name.as_str() {
1405 "kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
1406 "since" => query.since = Some(read_one::<Timestamp>(name, text)?),
1407 "until" => query.until = Some(read_one::<Timestamp>(name, text)?),
1408 "spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
1409 "before" => query.before = Some(read_one::<EventId>(name, text)?),
1410 "limit" => query.limit = Some(read_one::<u32>(name, text)?),
1411 other => return Err(format!("the printer history takes no `{other}`")),
1412 }
1413 }
1414 Ok(query)
1415}
1416
1417async fn printer_history(
1423 State(state): State<ApiState>,
1424 Query(asked): Query<Vec<(String, String)>>,
1425) -> Response {
1426 let query = match timeline_query(&asked) {
1427 Ok(query) => query,
1428 Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
1429 };
1430 let limit = match query.resolved_limit() {
1431 Ok(limit) => limit,
1432 Err(error) => return refusal(store_status(&error), error),
1433 };
1434 let events = match state.supervisor.timeline(query.clone()).await {
1435 Ok(events) => events,
1436 Err(error) => return refusal(core_status(&error), error),
1437 };
1438 let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
1439 let next = match events.last() {
1440 Some(last) if full => {
1441 let older = TimelineQuery {
1442 before: Some(last.id),
1443 limit: Some(1),
1444 ..query
1445 };
1446 match state.supervisor.timeline(older).await {
1447 Ok(older) if older.is_empty() => None,
1448 Ok(_) => Some(last.id),
1449 Err(error) => return refusal(core_status(&error), error),
1450 }
1451 }
1452 _ => None,
1453 };
1454 answer(StatusCode::OK, &TimelineAnswer { events, next })
1455}
1456
1457async fn preflight(
1461 State(state): State<ApiState>,
1462 Query(params): Query<PreflightParams>,
1463) -> Response {
1464 let Some(named) = params.file_name else {
1465 return refusal(
1466 StatusCode::BAD_REQUEST,
1467 "a filament check needs `file_name`, and this request carries none",
1468 );
1469 };
1470 let file_name = match FileName::new(&named) {
1471 Ok(file_name) => file_name,
1472 Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
1473 };
1474 let sheet = match params.sheet.map(SheetId::try_from).transpose() {
1475 Ok(sheet) => sheet,
1476 Err(why) => return refusal(StatusCode::BAD_REQUEST, why),
1477 };
1478 match state.supervisor.preflight(&file_name, sheet.as_ref()).await {
1479 Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
1480 Err(error) => refusal(core_status(&error), error),
1481 }
1482}
1483
1484async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
1491 match state.supervisor.list_and_adopt_prints().await {
1492 Ok(listing) => answer(
1493 StatusCode::OK,
1494 &PrintsAnswer {
1495 prints: listing.prints,
1496 active: listing.active,
1497 },
1498 ),
1499 Err(error) => refusal(core_status(&error), error),
1500 }
1501}
1502
1503async fn status(
1509 State(state): State<ApiState>,
1510 Extension(caller): Extension<Caller>,
1511 PrintPath(print_id): PrintPath,
1512) -> Response {
1513 if let Some(refused) = scope_refused(&caller, print_id) {
1514 return refused;
1515 }
1516 match state.prints.print(print_id).await {
1517 Ok(Some(_)) => {}
1518 Ok(None) => {
1519 return refusal(
1520 StatusCode::NOT_FOUND,
1521 format!("there is no print {print_id}"),
1522 );
1523 }
1524 Err(error) => return refusal(store_status(&error), error),
1525 }
1526 let context = match context_of(&state, print_id).await {
1527 Ok(context) => context,
1528 Err(refused) => return refused,
1529 };
1530 let session = match state.sessions.session(print_id).await {
1531 Ok(session) => session,
1532 Err(error) => return refusal(store_status(&error), error),
1533 };
1534 let planned_changes = if context.slicer.is_some() {
1537 match state
1538 .supervisor
1539 .planned_changes(&context.print, context.job.as_ref())
1540 .await
1541 {
1542 Ok(planned) => planned,
1543 Err(error) => return refusal(core_status(&error), error),
1544 }
1545 } else {
1546 None
1547 };
1548 answer(
1549 StatusCode::OK,
1550 &StatusAnswer {
1551 print: context.print,
1552 printer: context.printer,
1553 job: context.job,
1554 session,
1555 interventions: context.interventions,
1556 detector: context.detector,
1557 planned_changes,
1558 last_check_image: state
1559 .check_images
1560 .as_ref()
1561 .and_then(|images| images.last_check_image(print_id)),
1562 },
1563 )
1564}
1565
1566async fn context_of(
1574 state: &ApiState,
1575 print_id: PrintId,
1576) -> Result<printobserver_core::PrintContext, Response> {
1577 let supervisor = Arc::clone(&state.supervisor);
1578 let read = tokio::task::spawn_blocking(move || {
1579 printobserver_core::block_on(supervisor.context(print_id))
1580 })
1581 .await;
1582 match read {
1583 Ok(Ok(context)) => Ok(context),
1584 Ok(Err(error)) => Err(refusal(core_status(&error), error)),
1585 Err(error) => Err(refusal(StatusCode::INTERNAL_SERVER_ERROR, error)),
1586 }
1587}
1588
1589async fn context(
1597 State(state): State<ApiState>,
1598 Extension(caller): Extension<Caller>,
1599 PrintPath(print_id): PrintPath,
1600 Query(params): Query<ContextParams>,
1601) -> Response {
1602 if let Some(refused) = scope_refused(&caller, print_id) {
1603 return refused;
1604 }
1605 let supervisor = Arc::clone(&state.supervisor);
1607 let since = params.since;
1608 let read = tokio::task::spawn_blocking(move || {
1609 printobserver_core::block_on(supervisor.agent_context(print_id, since))
1610 })
1611 .await;
1612 let context = match read {
1613 Ok(Ok(read)) => read,
1614 Ok(Err(error)) => return refusal(core_status(&error), error),
1615 Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1616 };
1617 let mut image_path = None;
1618 if let Some(latest) = context.latest_image.as_ref() {
1619 match state.images.image(latest.id).await {
1620 Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
1621 Err(error) => return refusal(store_status(&error), error),
1622 }
1623 }
1624 answer(
1625 StatusCode::OK,
1626 &ContextAnswer {
1627 context,
1628 image_path,
1629 },
1630 )
1631}
1632
1633async fn look(
1641 State(state): State<ApiState>,
1642 Extension(caller): Extension<Caller>,
1643 PrintPath(print_id): PrintPath,
1644 Query(params): Query<LookParams>,
1645) -> Response {
1646 if let Some(refused) = scope_refused(&caller, print_id) {
1647 return refused;
1648 }
1649 let wait_s = params.wait_s.unwrap_or(0);
1650 if wait_s > MAX_LOOK_WAIT_S {
1651 return refusal(
1652 StatusCode::BAD_REQUEST,
1653 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1654 );
1655 }
1656 match state.prints.print(print_id).await {
1657 Ok(Some(_)) => {}
1658 Ok(None) => {
1659 return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
1660 }
1661 Err(error) => return refusal(store_status(&error), error),
1662 }
1663 if let Caller::Turn(binding) = &caller {
1666 state.turns.note_look(binding);
1667 }
1668 let supervisor = Arc::clone(&state.supervisor);
1669 let taken = tokio::task::spawn_blocking(move || {
1670 let (arrived, waited) =
1671 supervisor.await_look_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
1672 printobserver_core::block_on(supervisor.take_look(print_id, waited, arrived))
1673 })
1674 .await;
1675 match taken {
1676 Ok(Ok(look)) => answer(StatusCode::OK, &look),
1677 Ok(Err(error)) => refusal(core_status(&error), error),
1678 Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1679 }
1680}
1681
1682async fn printer_look(
1689 State(state): State<ApiState>,
1690 Extension(caller): Extension<Caller>,
1691 Query(params): Query<LookParams>,
1692) -> Response {
1693 if let Some(refused) = printless_refused(&caller, "a look at the printer with no print named") {
1694 return refused;
1695 }
1696 let wait_s = params.wait_s.unwrap_or(0);
1697 if wait_s > MAX_LOOK_WAIT_S {
1698 return refusal(
1699 StatusCode::BAD_REQUEST,
1700 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1701 );
1702 }
1703 let waited = Duration::from_secs(u64::from(wait_s));
1704 tokio::time::sleep(waited).await;
1705 match state.supervisor.take_printer_look(waited).await {
1706 Ok(look) => answer(StatusCode::OK, &look),
1707 Err(error) => refusal(core_status(&error), error),
1708 }
1709}
1710
1711async fn image(
1717 State(state): State<ApiState>,
1718 Extension(caller): Extension<Caller>,
1719 Path(image_id): Path<ImageId>,
1720) -> Response {
1721 match state.images.image(image_id).await {
1722 Ok(lookup) => {
1723 let belongs_to = match &lookup {
1724 printobserver_core::ImageLookup::Found { record, .. }
1725 | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
1726 };
1727 let refused = match belongs_to {
1728 Some(print_id) => scope_refused(&caller, print_id),
1729 None => {
1730 printless_refused(&caller, "a frame of the printer that belongs to no print")
1731 }
1732 };
1733 if let Some(refused) = refused {
1734 return refused;
1735 }
1736 answer(StatusCode::OK, &ImageAnswer::from(lookup))
1737 }
1738 Err(error) => refusal(store_status(&error), error),
1739 }
1740}
1741
1742async fn history(
1744 State(state): State<ApiState>,
1745 Extension(caller): Extension<Caller>,
1746 PrintPath(print_id): PrintPath,
1747 Query(params): Query<HistoryParams>,
1748) -> Response {
1749 if let Some(refused) = scope_refused(&caller, print_id) {
1750 return refused;
1751 }
1752 let query = HistoryQuery {
1753 print_id,
1754 kinds: Vec::new(),
1755 since: None,
1756 until: None,
1757 limit: params.limit,
1758 };
1759 match state.events.history(query).await {
1760 Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
1761 Err(error) => refusal(store_status(&error), error),
1762 }
1763}
1764
1765async fn manifest_get(
1767 State(state): State<ApiState>,
1768 Extension(caller): Extension<Caller>,
1769 PrintPath(print_id): PrintPath,
1770) -> Response {
1771 if let Some(refused) = scope_refused(&caller, print_id) {
1772 return refused;
1773 }
1774 let manifest = match state.prints.manifest(print_id).await {
1775 Ok(manifest) => manifest,
1776 Err(error) => return refusal(store_status(&error), error),
1777 };
1778 let narrowings = match state.prints.print(print_id).await {
1779 Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
1780 Err(error) => return refusal(store_status(&error), error),
1781 };
1782 answer(
1783 StatusCode::OK,
1784 &ManifestAnswer {
1785 manifest,
1786 narrowings,
1787 },
1788 )
1789}
1790
1791async fn manifest_set(
1800 State(state): State<ApiState>,
1801 Extension(caller): Extension<Caller>,
1802 PrintPath(print_id): PrintPath,
1803 body: Result<Json<ManifestBody>, JsonRejection>,
1804) -> Response {
1805 if let Some(refused) =
1806 operator_refused(&caller, &crate::operations::command_for("manifest_set"))
1807 {
1808 return refused;
1809 }
1810 let body = match body {
1811 Ok(Json(body)) => body,
1812 Err(rejected) => return rejected.into_response(),
1813 };
1814 if let Err(rejected) = body.reason() {
1815 return refusal(StatusCode::BAD_REQUEST, rejected);
1816 }
1817 let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
1818 if let Err(error) = state
1819 .prints
1820 .put_manifest(print_id, body.manifest.clone())
1821 .await
1822 {
1823 return refusal(store_status(&error), error);
1824 }
1825 for narrowing in narrowed.narrowings.clone() {
1826 if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
1827 return refusal(store_status(&error), error);
1828 }
1829 }
1830 answer(
1831 StatusCode::OK,
1832 &ManifestAnswer {
1833 manifest: Some(body.manifest),
1834 narrowings: narrowed.narrowings,
1835 },
1836 )
1837}
1838
1839#[cfg(test)]
1840mod tests {
1841 use axum::http::StatusCode;
1842 use printobserver_core::CoreError;
1843 use printobserver_core::store::StoreError;
1844
1845 use super::{core_status, store_status};
1846
1847 #[test]
1850 fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
1851 for (error, expected) in [
1852 (
1853 StoreError::NotFound {
1854 what: "print".to_owned(),
1855 },
1856 StatusCode::NOT_FOUND,
1857 ),
1858 (
1859 StoreError::LimitRefused {
1860 limit: 1_000,
1861 asked_for: 2_000,
1862 },
1863 StatusCode::BAD_REQUEST,
1864 ),
1865 (
1866 StoreError::ConstraintRefused {
1867 constraint: "actions.decision".to_owned(),
1868 },
1869 StatusCode::BAD_REQUEST,
1870 ),
1871 (
1872 StoreError::Database {
1873 detail: "the disk is full".to_owned(),
1874 },
1875 StatusCode::INTERNAL_SERVER_ERROR,
1876 ),
1877 (
1878 StoreError::Io {
1879 detail: "the disk is full".to_owned(),
1880 },
1881 StatusCode::INTERNAL_SERVER_ERROR,
1882 ),
1883 ] {
1884 assert_eq!(store_status(&error), expected, "{error}");
1885 }
1886 }
1887
1888 #[test]
1891 fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
1892 assert_eq!(
1893 core_status(&CoreError::NoSuchPrint {
1894 print_id: printobserver_types::PrintId::new(),
1895 }),
1896 StatusCode::NOT_FOUND
1897 );
1898 assert_eq!(
1899 core_status(&CoreError::Store(StoreError::NotFound {
1900 what: "print".to_owned(),
1901 })),
1902 StatusCode::NOT_FOUND
1903 );
1904 assert_eq!(
1905 core_status(&CoreError::Unrepresentable {
1906 detail: "an instant".to_owned(),
1907 }),
1908 StatusCode::INTERNAL_SERVER_ERROR
1909 );
1910 }
1911}