1use std::sync::Arc;
62use std::time::Duration;
63
64use axum::Json;
65use axum::extract::rejection::JsonRejection;
66use axum::extract::{DefaultBodyLimit, Extension, Path, Query, Request, State};
67use axum::http::{StatusCode, header};
68use axum::middleware::{Next, from_fn_with_state};
69use axum::response::{IntoResponse, Response};
70use axum::routing::{get, post, put};
71use axum::{Router, routing::MethodRouter};
72use printobserver_core::recovery::recovery_detail;
73use printobserver_core::store::TimelineQuery;
74use printobserver_core::store::{
75 EventStore, HistoryQuery, ImageStore, PrintStore, SessionStore, StoreError,
76};
77use printobserver_core::{
78 ActionKind, Actor, ActorClass, ExecutionOutcome, PolicyDecision, RecoveryActionKind,
79 RecoveryDecision, SheetId, SpoolId,
80};
81use printobserver_core::{CoreError, MAX_LOOK_WAIT_S, Supervisor, effective_bounds};
82use printobserver_types::serde::Deserialize;
83use printobserver_types::serde_json::Value;
84use printobserver_types::{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}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
126pub enum Caller {
127 Operator,
129 Turn(TurnBinding),
131}
132
133impl Caller {
134 fn named(&self) -> String {
136 match self {
137 Self::Operator => "the operator".to_owned(),
138 Self::Turn(binding) => format!(
139 "the agent in session `{}` on print {}",
140 binding.session_name(),
141 binding.print_id()
142 ),
143 }
144 }
145}
146
147fn claimed(actor: &Actor) -> String {
149 match actor {
150 Actor::Operator => "the operator".to_owned(),
151 Actor::System => "the system".to_owned(),
152 Actor::Agent { session_name } => format!("the agent in session `{session_name}`"),
153 }
154}
155
156fn claim_refused(caller: &Caller, actor: &Actor) -> Option<Response> {
161 let held = match (caller, actor) {
162 (Caller::Operator, Actor::Operator) => true,
163 (Caller::Turn(binding), Actor::Agent { session_name }) => {
164 *session_name == binding.session_name()
165 }
166 _ => false,
167 };
168 if held {
169 return None;
170 }
171 let why = if matches!(actor, Actor::System) {
172 "no credential may claim the system, whose actions are the server's own"
173 } else {
174 "a request acts as the identity its credential authenticated, and no other"
175 };
176 Some(refusal(
177 StatusCode::FORBIDDEN,
178 format!(
179 "this request authenticated as {} and claims to be {}: {why}",
180 caller.named(),
181 claimed(actor)
182 ),
183 ))
184}
185
186pub(crate) fn scope_refused(caller: &Caller, print_id: PrintId) -> Option<Response> {
188 match caller {
189 Caller::Turn(binding) if binding.print_id() != print_id => Some(refusal(
190 StatusCode::FORBIDDEN,
191 format!(
192 "this request authenticated as {} and names print {print_id}: a supervision \
193 turn's credential reaches its own print alone",
194 caller.named()
195 ),
196 )),
197 _ => None,
198 }
199}
200
201fn printless_refused(caller: &Caller, what: &str) -> Option<Response> {
205 match caller {
206 Caller::Turn(_) => Some(refusal(
207 StatusCode::FORBIDDEN,
208 format!(
209 "this request authenticated as {} and asks for {what}: a supervision turn's \
210 credential reaches its own print alone",
211 caller.named()
212 ),
213 )),
214 Caller::Operator => None,
215 }
216}
217
218fn operator_refused(caller: &Caller, command: &str) -> Option<Response> {
221 match caller {
222 Caller::Turn(_) => Some(refusal(
223 StatusCode::FORBIDDEN,
224 format!(
225 "this request authenticated as {} and asks for `{command}`, which is the \
226 operator's alone: a supervision turn's credential does not reach it",
227 caller.named()
228 ),
229 )),
230 Caller::Operator => None,
231 }
232}
233
234fn unlooked_refused(
242 turns: &TurnCredentials,
243 caller: &Caller,
244 print_id: PrintId,
245) -> Option<Response> {
246 match caller {
247 Caller::Turn(binding) if !turns.has_looked(binding) => Some(refusal(
248 StatusCode::FORBIDDEN,
249 format!(
250 "this request authenticated as {} and acknowledges an event before the turn \
251 has taken a look: run `printobserver look --print-id {print_id}`, open the \
252 frames it names, and acknowledge what they show",
253 caller.named()
254 ),
255 )),
256 _ => None,
257 }
258}
259
260#[derive(Clone)]
262pub struct Admission {
263 operator: Arc<OperatorCredential>,
265 turns: TurnCredentials,
267}
268
269impl Admission {
270 fn caller(&self, presented: &[u8]) -> Option<Caller> {
272 if let Some(binding) = self.turns.admit(presented) {
273 return Some(Caller::Turn(binding));
274 }
275 self.operator.admits(presented).then_some(Caller::Operator)
276 }
277}
278
279impl core::fmt::Debug for ApiState {
280 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
281 formatter.debug_struct("ApiState").finish_non_exhaustive()
282 }
283}
284
285#[derive(Debug, Clone, Deserialize)]
287#[serde(crate = "printobserver_types::serde")]
288pub struct HistoryParams {
289 #[serde(default)]
291 pub limit: Option<u32>,
292}
293
294#[derive(Debug, Clone, Deserialize)]
297#[serde(crate = "printobserver_types::serde")]
298pub struct ContextParams {
299 #[serde(default)]
301 pub since: Option<printobserver_types::EventId>,
302}
303
304#[derive(Debug, Clone, Deserialize)]
306#[serde(crate = "printobserver_types::serde")]
307pub struct LookParams {
308 #[serde(default)]
310 pub wait_s: Option<u32>,
311}
312
313#[derive(Debug, Clone, Deserialize)]
315#[serde(crate = "printobserver_types::serde")]
316pub struct SpoolsParams {
317 #[serde(default)]
319 pub include_retired: Option<bool>,
320}
321
322#[derive(Debug, Clone, Deserialize)]
324#[serde(crate = "printobserver_types::serde")]
325pub struct PreflightParams {
326 #[serde(default)]
328 pub file_name: Option<String>,
329 #[serde(default)]
333 pub sheet: Option<String>,
334}
335
336pub const SPOOL_RECENT_EVENTS: u32 = 20;
338
339pub fn router(state: ApiState) -> Router {
347 let mut api = Router::new();
348 for operation in OPERATIONS {
349 api = api.route(operation.path, route_for(&operation));
350 }
351 let api = api
354 .fallback(nothing_here)
355 .layer(from_fn_with_state(
356 Admission {
357 operator: Arc::clone(&state.operator),
358 turns: state.turns.clone(),
359 },
360 authenticate,
361 ))
362 .layer(DefaultBodyLimit::max(BODY_BOUND))
363 .with_state(state);
364 Router::new().nest(VERSION_PREFIX, api)
365}
366
367const BEARER: &[u8] = b"Bearer ";
369
370pub const BODY_BOUND: usize = 2 * 1024 * 1024;
377
378pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
384
385pub async fn authenticate(
403 State(admission): State<Admission>,
404 mut request: Request,
405 next: Next,
406) -> Response {
407 let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
408 let admitted = match (presented.next(), presented.next()) {
409 (Some(only), None) => only
410 .as_bytes()
411 .strip_prefix(BEARER)
412 .and_then(|offered| admission.caller(offered)),
413 _ => None,
414 };
415 if let Some(caller) = admitted {
416 request.extensions_mut().insert(caller);
417 return next.run(request).await;
418 }
419 {
420 let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
421 format!(
422 "this server's API requires a credential, presented as `Authorization: Bearer \
423 <credential>`, and this server has no operator credential yet: run \
424 `{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
425 prints into the server's configuration, and restart the service"
426 )
427 } else {
428 format!(
429 "this server's API requires the credential it is configured with, presented as \
430 `Authorization: Bearer <credential>`. An operator without one runs \
431 `{CREDENTIAL_ISSUE}`"
432 )
433 };
434 let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
435 refused.headers_mut().insert(
436 header::WWW_AUTHENTICATE,
437 header::HeaderValue::from_static("Bearer"),
438 );
439 let _ = tokio::time::timeout(
443 DRAIN_BOUND,
444 axum::body::to_bytes(request.into_body(), BODY_BOUND),
445 )
446 .await;
447 refused
448 }
449}
450
451async fn nothing_here() -> Response {
453 refusal(
454 StatusCode::NOT_FOUND,
455 "no operation of this server is served at that path",
456 )
457}
458
459fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
461 if let Effect::Command(spool_command) = operation.effect {
462 let kind = spool_command.action_kind();
463 if operation.path.contains("{spool_id}") {
464 return post(
465 move |state: State<ApiState>,
466 caller: Extension<Caller>,
467 Path(spool_id): Path<SpoolId>,
468 body: Result<Json<Value>, JsonRejection>| async move {
469 command(kind, state, caller, Some(spool_id), body).await
470 },
471 );
472 }
473 return post(
474 move |state: State<ApiState>,
475 caller: Extension<Caller>,
476 body: Result<Json<Value>, JsonRejection>| async move {
477 command(kind, state, caller, None, body).await
478 },
479 );
480 }
481 if let Effect::Recovery(kind) = operation.effect {
482 return post(
483 move |state: State<ApiState>,
484 caller: Extension<Caller>,
485 body: Result<Json<Value>, JsonRejection>| async move {
486 recover(kind, state, caller, body).await
487 },
488 );
489 }
490 if let Effect::Mutating(kind) = operation.effect {
491 return post(
492 move |state: State<ApiState>,
493 caller: Extension<Caller>,
494 print_id: PrintPath,
495 body: Result<Json<ActionBody>, JsonRejection>| async move {
496 act(kind, state, caller, print_id, body).await
497 },
498 );
499 }
500 match (operation.name, operation.method) {
501 ("prints", Method::Get) => get(list_and_adopt_prints),
502 ("status", Method::Get) => get(status),
503 ("context", Method::Get) => get(context),
504 ("image", Method::Get) => get(image),
505 ("history", Method::Get) => get(history),
506 ("events", Method::Get) => get(crate::events::events),
507 ("look", Method::Get) => get(look),
508 (crate::operations::PRINTER_LOOK, Method::Get) => get(printer_look),
509 ("manifest_get", Method::Get) => get(manifest_get),
510 ("manifest_set", Method::Put) => put(manifest_set),
511 ("spools", Method::Get) => get(spools),
512 ("spool", Method::Get) => get(spool),
513 ("printer_history", Method::Get) => get(printer_history),
514 ("preflight", Method::Get) => get(preflight),
515 (crate::operations::RECOVERY_STATUS, Method::Get) => get(recover_status),
516 (crate::operations::BED_CLEAR, Method::Post) => post(bed_clear),
517 (crate::operations::RECHECK_CAMERA, Method::Post) => post(recheck_camera),
518 (name, method) => panic!(
519 "the operation `{name}` is declared as {method} and this router serves no such route"
520 ),
521 }
522}
523
524pub(crate) fn answer<T: printobserver_types::serde::Serialize>(
526 status: StatusCode,
527 body: &T,
528) -> Response {
529 let rendered = match printobserver_types::serde_json::to_vec(body) {
530 Ok(bytes) => bytes,
531 Err(error) => {
532 return (
533 StatusCode::INTERNAL_SERVER_ERROR,
534 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
535 format!("{{\"error\":\"{error}\"}}"),
536 )
537 .into_response();
538 }
539 };
540 (
541 status,
542 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
543 rendered,
544 )
545 .into_response()
546}
547
548pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
550 answer(status, &ErrorAnswer::saying(detail))
551}
552
553pub(crate) const PRINT_ID_REFUSED: &str = "a print is named by its id, a UUID, as `printobserver prints` \
556lists it; a start with no print open may name none, and is made under one minted for it";
557
558pub(crate) struct PrintPath(pub(crate) PrintId);
561
562impl<S: Send + Sync> axum::extract::FromRequestParts<S> for PrintPath {
563 type Rejection = Response;
564
565 async fn from_request_parts(
566 parts: &mut axum::http::request::Parts,
567 state: &S,
568 ) -> Result<Self, Self::Rejection> {
569 match Path::<PrintId>::from_request_parts(parts, state).await {
570 Ok(Path(print_id)) => Ok(Self(print_id)),
571 Err(rejected) => Err(refusal(
572 StatusCode::BAD_REQUEST,
573 format!("{}: {PRINT_ID_REFUSED}", rejected.body_text()),
574 )),
575 }
576 }
577}
578
579pub(crate) fn store_status(error: &StoreError) -> StatusCode {
581 match error {
582 StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
583 StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
584 StatusCode::BAD_REQUEST
585 }
586 StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
587 }
588}
589
590fn core_status(error: &CoreError) -> StatusCode {
592 match error {
593 CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
594 CoreError::Store(store) => store_status(store),
595 _ => StatusCode::INTERNAL_SERVER_ERROR,
596 }
597}
598
599async fn act(
607 kind: ActionKind,
608 State(state): State<ApiState>,
609 Extension(caller): Extension<Caller>,
610 PrintPath(print_id): PrintPath,
611 body: Result<Json<ActionBody>, JsonRejection>,
612) -> Response {
613 if kind == ActionKind::StartPrint
614 && let Some(refused) =
615 operator_refused(&caller, &crate::operations::command_for("start_print"))
616 {
617 return refused;
618 }
619 if let Some(refused) = scope_refused(&caller, print_id) {
620 return refused;
621 }
622 let body = match body {
623 Ok(Json(body)) => body,
624 Err(rejected) => return rejected.into_response(),
625 };
626 if let Some(refused) = claim_refused(&caller, &body.actor) {
627 return refused;
628 }
629 if kind == ActionKind::AcknowledgeFailure
630 && let Some(refused) = unlooked_refused(&state.turns, &caller, print_id)
631 {
632 return refused;
633 }
634 let action = match body.into_action(kind) {
635 Ok(action) => action,
636 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
637 };
638 let outcome = match state.supervisor.request_action(print_id, action).await {
639 Ok(outcome) => outcome,
640 Err(error) => return refusal(core_status(&error), error),
641 };
642 let printer_refusal = match &outcome.record.outcome {
643 Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
644 _ => None,
645 };
646 let status = match outcome.record.decision {
647 PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
648 PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
652 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
655 };
656 answer(
657 status,
658 &ActionAnswer {
659 record: outcome.record,
660 intervention: outcome.intervention,
661 printer_refusal,
662 },
663 )
664}
665
666async fn command(
675 kind: ActionKind,
676 State(state): State<ApiState>,
677 Extension(caller): Extension<Caller>,
678 spool_id: Option<SpoolId>,
679 body: Result<Json<Value>, JsonRejection>,
680) -> Response {
681 let body = match body {
682 Ok(Json(body)) => body,
683 Err(rejected) => return rejected.into_response(),
684 };
685 let Some(fields) = body.as_object() else {
686 return refusal(
687 StatusCode::BAD_REQUEST,
688 "a spool command's body is a document of its fields",
689 );
690 };
691 let actor = match claimed_actor(fields) {
692 Ok(actor) => actor,
693 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
694 };
695 if let Some(refused) = claim_refused(&caller, &actor) {
696 return refused;
697 }
698 let asked = match spool_command_of(kind, spool_id, body) {
699 Ok(asked) => asked,
700 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
701 };
702 let outcome = match state.supervisor.request_spool_command(asked).await {
703 Ok(outcome) => outcome,
704 Err(error) => return refusal(core_status(&error), error),
705 };
706 let status = match outcome.decision {
707 PolicyDecision::Accepted => StatusCode::OK,
708 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
710 };
711 answer(
712 status,
713 &SpoolCommandAnswer {
714 decision: outcome.decision,
715 spool: outcome.spool,
716 events: outcome.events,
717 },
718 )
719}
720
721async fn recover(
729 kind: RecoveryActionKind,
730 State(state): State<ApiState>,
731 Extension(caller): Extension<Caller>,
732 body: Result<Json<Value>, JsonRejection>,
733) -> Response {
734 let body = match body {
735 Ok(Json(body)) => body,
736 Err(rejected) => return rejected.into_response(),
737 };
738 if let Some(fields) = body.as_object() {
739 let actor = match claimed_actor(fields) {
740 Ok(actor) => actor,
741 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
742 };
743 if let Some(refused) = claim_refused(&caller, &actor) {
744 return refused;
745 }
746 }
747 let (action, actor, reason) = match recovery_of(kind, body) {
748 Ok(asked) => asked,
749 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
750 };
751 let issued = match state
752 .supervisor
753 .request_recovery(action.clone(), actor, reason)
754 .await
755 {
756 Ok(issued) => issued,
757 Err(error) => return refusal(core_status(&error), error),
758 };
759 let config = state.supervisor.config().recovery;
760 let status = match &issued.decision {
761 RecoveryDecision::Executed(ExecutionOutcome::Succeeded) => StatusCode::OK,
762 RecoveryDecision::Executed(ExecutionOutcome::Failed { .. }) => StatusCode::BAD_GATEWAY,
765 RecoveryDecision::Rejected(_) => StatusCode::CONFLICT,
767 };
768 answer(
769 status,
770 &RecoveryAnswer {
771 detail: recovery_detail(&action, &issued.decision, config.as_ref()),
772 action,
773 decision: issued.decision,
774 events: vec![issued.requested, issued.settled],
775 },
776 )
777}
778
779pub const BED_CLEAR_DETAIL: &str = "recorded: until the next print starts, a Z home is decided \
781 as though it asserted the bed clear, and a heat, a park and an XY home as though they \
782 asserted the nozzle clear of the part, wherever the operator's word counts";
783
784async fn bed_clear(
792 State(state): State<ApiState>,
793 Extension(caller): Extension<Caller>,
794 body: Result<Json<Value>, JsonRejection>,
795) -> Response {
796 let body = match body {
797 Ok(Json(body)) => body,
798 Err(rejected) => return rejected.into_response(),
799 };
800 let Some(fields) = body.as_object() else {
801 return refusal(
802 StatusCode::BAD_REQUEST,
803 "the body is not a document carrying an `actor` and a `reason`",
804 );
805 };
806 let actor = match claimed_actor(fields) {
807 Ok(actor) => actor,
808 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
809 };
810 if let Some(refused) = claim_refused(&caller, &actor) {
811 return refused;
812 }
813 if actor != Actor::Operator {
814 return refusal(
815 StatusCode::FORBIDDEN,
816 format!(
817 "{} may not say the bed is clear: an assertion is a person's word for what \
818 they can see, and only the operator's is recorded",
819 claimed(&actor)
820 ),
821 );
822 }
823 let body: BedClearBody = match printobserver_types::serde_json::from_value(body) {
824 Ok(body) => body,
825 Err(error) => {
826 return refusal(
827 StatusCode::BAD_REQUEST,
828 format!("the body is not an `actor` and a `reason`: {error}"),
829 );
830 }
831 };
832 let reason = match reason_of(body.reason.as_deref()) {
833 Ok(reason) => reason,
834 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
835 };
836 match state.supervisor.assert_bed_clear(reason).await {
837 Ok(event) => answer(
838 StatusCode::OK,
839 &BedClearAnswer {
840 event,
841 detail: BED_CLEAR_DETAIL.to_owned(),
842 },
843 ),
844 Err(error) => refusal(core_status(&error), error),
845 }
846}
847
848async fn recheck_camera(
866 State(state): State<ApiState>,
867 Extension(caller): Extension<Caller>,
868 PrintPath(print_id): PrintPath,
869 body: Result<Json<Value>, JsonRejection>,
870) -> Response {
871 if let Some(refused) = scope_refused(&caller, print_id) {
872 return refused;
873 }
874 let (actor, reason) = match actor_and_reason(&caller, body) {
875 Ok(asked) => asked,
876 Err(refused) => return *refused,
877 };
878 match state.prints.print(print_id).await {
882 Ok(Some(_)) => {}
883 Ok(None) => {
884 return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
885 }
886 Err(error) => return refusal(store_status(&error), error),
887 }
888 let Some(images) = state.check_images.clone() else {
889 return refusal(
890 StatusCode::SERVICE_UNAVAILABLE,
891 "nothing judges this server's camera frames",
892 );
893 };
894 if state.supervisor.config().camera_snapshot_url.is_none() {
895 return refusal(
896 StatusCode::SERVICE_UNAVAILABLE,
897 "no camera is configured to judge: set the server's `[camera] snapshot_url`",
898 );
899 }
900 let supervisor = Arc::clone(&state.supervisor);
901 let fresh = tokio::task::spawn_blocking(move || {
902 printobserver_core::block_on(supervisor.fresh_view(print_id))
903 })
904 .await;
905 let fresh = match fresh {
906 Ok(Ok(fresh)) => fresh,
907 Ok(Err(error)) => return refusal(core_status(&error), error),
908 Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
909 };
910 let Some((url, image)) = fresh.frame.clone() else {
911 return refusal(
912 StatusCode::SERVICE_UNAVAILABLE,
913 "the camera gave no good frame to judge",
914 );
915 };
916 let sha256 = hex_sha256(image.bytes.as_slice());
917 let captured_at = image
918 .captured_at
919 .unwrap_or_else(printobserver_types::Timestamp::now);
920 let alignment = if fresh.paused {
921 crate::alignment::AlignmentJudging::Never
922 } else {
923 crate::alignment::AlignmentJudging::Afresh
924 };
925 let judging = Arc::clone(&images);
926 let plan = fresh.plan.clone();
927 let bytes = image.bytes.as_slice().to_vec();
928 let digest = sha256.clone();
929 let judged = tokio::task::spawn_blocking(move || {
930 judging.judge_frame(print_id, &bytes, &digest, plan.as_ref(), alignment)
931 })
932 .await;
933 let judged = match judged {
934 Ok(Some(judged)) => judged,
935 Ok(None) => crate::alignment::Judged::nothing_to_judge(
939 images.alignment(print_id),
940 EventBody::of(&printobserver_core::CameraLookPayload {
941 waited_s: 0,
942 delivered: Vec::new(),
943 frame_captured_at: Some(captured_at),
944 })
945 .ok(),
946 ),
947 Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
948 };
949 if let Some(detail) = &judged.unreadable {
950 return refusal(StatusCode::SERVICE_UNAVAILABLE, detail);
951 }
952 eprintln!(
953 "printobserver: print {print_id}: the camera is judged again for {}: {reason}",
954 claimed(&actor)
955 );
956 let frame_path = match stored_with_frame(&state, print_id, &judged, (url, image)).await {
957 Ok(path) => path,
958 Err(refused) => return refused,
959 };
960 let shown =
961 match image_shown(&images, print_id, &frame_path, captured_at, &fresh, &judged).await {
962 Ok(shown) => shown,
963 Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
964 };
965 answer(
966 StatusCode::OK,
967 &crate::wire::RecheckCameraAnswer {
968 frame_path,
969 alignment: judged.alignment,
970 view_correction: judged.correction,
971 image_kind: shown.kind(),
972 image_fallback: shown.fallback,
973 },
974 )
975}
976
977fn actor_and_reason(
980 caller: &Caller,
981 body: Result<Json<Value>, JsonRejection>,
982) -> Result<(Actor, String), Box<Response>> {
983 let refused = |status: StatusCode, said: String| Box::new(refusal(status, said));
984 let body = match body {
985 Ok(Json(body)) => body,
986 Err(rejected) => return Err(Box::new(rejected.into_response())),
987 };
988 let Some(fields) = body.as_object() else {
989 return Err(refused(
990 StatusCode::BAD_REQUEST,
991 "the body is not a document carrying an `actor` and a `reason`".to_owned(),
992 ));
993 };
994 let actor = claimed_actor(fields)
995 .map_err(|rejected| refused(StatusCode::BAD_REQUEST, rejected.to_string()))?;
996 if let Some(claim) = claim_refused(caller, &actor) {
997 return Err(Box::new(claim));
998 }
999 let body: BedClearBody =
1000 printobserver_types::serde_json::from_value(body).map_err(|error| {
1001 refused(
1002 StatusCode::BAD_REQUEST,
1003 format!("the body is not an `actor` and a `reason`: {error}"),
1004 )
1005 })?;
1006 let reason = reason_of(body.reason.as_deref())
1007 .map_err(|rejected| refused(StatusCode::BAD_REQUEST, rejected.to_string()))?;
1008 Ok((actor, reason))
1009}
1010
1011async fn image_shown(
1014 images: &Arc<crate::check_images::PanelImages>,
1015 print_id: PrintId,
1016 frame_path: &std::path::Path,
1017 captured_at: printobserver_types::Timestamp,
1018 fresh: &printobserver_core::FreshView,
1019 judged: &crate::alignment::Judged,
1020) -> Result<printobserver_core::ShownImage, String> {
1021 let choosing = Arc::clone(images);
1022 let path = frame_path.to_path_buf();
1023 let plan = fresh.plan.clone();
1024 let paused = fresh.paused;
1025 let judged = judged.clone();
1026 tokio::task::spawn_blocking(move || {
1027 choosing.image_of(
1028 print_id,
1029 &crate::check_images::Shown {
1030 frame: &path,
1031 captured_at,
1032 made_for: printobserver_core::ImageUse::Look,
1033 plan: plan.as_ref(),
1034 paused,
1035 },
1036 Some(&judged),
1037 )
1038 })
1039 .await
1040 .map_err(|error| error.to_string())?
1041}
1042
1043async fn stored_with_frame(
1047 state: &ApiState,
1048 print_id: PrintId,
1049 judged: &crate::alignment::Judged,
1050 frame: (String, printobserver_vision_api::FetchedImage),
1051) -> Result<std::path::PathBuf, Response> {
1052 let mut frame = Some(frame);
1053 let mut stored = None;
1054 for record in judged.records.clone() {
1055 let event = state
1056 .supervisor
1057 .record_with_frame(print_id, record, frame.take())
1058 .await
1059 .map_err(|error| refusal(core_status(&error), error))?;
1060 if stored.is_none() {
1061 stored = event.image;
1062 }
1063 }
1064 let unkept = || {
1065 refusal(
1066 StatusCode::INTERNAL_SERVER_ERROR,
1067 "the fresh frame was not kept",
1068 )
1069 };
1070 let reference = stored.ok_or_else(unkept)?;
1071 match state.images.image(reference.id).await {
1072 Ok(printobserver_core::store::ImageLookup::Found { path, .. }) => Ok(path),
1073 _ => Err(unkept()),
1074 }
1075}
1076
1077fn hex_sha256(bytes: &[u8]) -> String {
1079 use sha2::Digest as _;
1080 sha2::Sha256::digest(bytes)
1081 .iter()
1082 .fold(String::with_capacity(64), |mut text, byte| {
1083 use core::fmt::Write as _;
1084 let _ = write!(text, "{byte:02x}");
1085 text
1086 })
1087}
1088
1089async fn recover_status(
1092 State(state): State<ApiState>,
1093 Extension(caller): Extension<Caller>,
1094) -> Response {
1095 let class = match caller {
1096 Caller::Operator => ActorClass::Operator,
1097 Caller::Turn(_) => ActorClass::Agent,
1098 };
1099 match state.supervisor.recovery_status(class).await {
1100 Ok(status) => answer(StatusCode::OK, &status),
1101 Err(error) => refusal(core_status(&error), error),
1102 }
1103}
1104
1105async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
1107 let listed = match state
1108 .supervisor
1109 .spools(params.include_retired.unwrap_or(false))
1110 .await
1111 {
1112 Ok(listed) => listed,
1113 Err(error) => return refusal(core_status(&error), error),
1114 };
1115 match state.supervisor.pending_charges(None).await {
1116 Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
1117 Err(error) => refusal(core_status(&error), error),
1118 }
1119}
1120
1121async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
1123 let found = match state.supervisor.spool(spool_id).await {
1124 Ok(Some(found)) => found,
1125 Ok(None) => {
1126 return refusal(
1127 StatusCode::NOT_FOUND,
1128 format!("there is no spool {spool_id}"),
1129 );
1130 }
1131 Err(error) => return refusal(core_status(&error), error),
1132 };
1133 let query = TimelineQuery {
1134 spool_id: Some(spool_id),
1135 limit: Some(SPOOL_RECENT_EVENTS),
1136 ..every_timeline_kind()
1137 };
1138 match state.supervisor.timeline(query).await {
1139 Ok(recent) => answer(
1140 StatusCode::OK,
1141 &SpoolAnswer {
1142 spool: found,
1143 recent,
1144 },
1145 ),
1146 Err(error) => refusal(core_status(&error), error),
1147 }
1148}
1149
1150const fn every_timeline_kind() -> TimelineQuery {
1152 TimelineQuery {
1153 kinds: Vec::new(),
1154 since: None,
1155 until: None,
1156 spool_id: None,
1157 before: None,
1158 limit: None,
1159 }
1160}
1161
1162fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
1164where
1165 T::Err: core::fmt::Display,
1166{
1167 text.parse()
1168 .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
1169}
1170
1171fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
1178 let mut query = every_timeline_kind();
1179 let mut seen: Vec<&str> = Vec::new();
1180 for (name, text) in asked {
1181 if name != "kinds" {
1182 if seen.contains(&name.as_str()) {
1183 return Err(format!(
1184 "`{name}` was given more than once, and this read takes one"
1185 ));
1186 }
1187 seen.push(name);
1188 }
1189 match name.as_str() {
1190 "kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
1191 "since" => query.since = Some(read_one::<Timestamp>(name, text)?),
1192 "until" => query.until = Some(read_one::<Timestamp>(name, text)?),
1193 "spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
1194 "before" => query.before = Some(read_one::<EventId>(name, text)?),
1195 "limit" => query.limit = Some(read_one::<u32>(name, text)?),
1196 other => return Err(format!("the printer history takes no `{other}`")),
1197 }
1198 }
1199 Ok(query)
1200}
1201
1202async fn printer_history(
1208 State(state): State<ApiState>,
1209 Query(asked): Query<Vec<(String, String)>>,
1210) -> Response {
1211 let query = match timeline_query(&asked) {
1212 Ok(query) => query,
1213 Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
1214 };
1215 let limit = match query.resolved_limit() {
1216 Ok(limit) => limit,
1217 Err(error) => return refusal(store_status(&error), error),
1218 };
1219 let events = match state.supervisor.timeline(query.clone()).await {
1220 Ok(events) => events,
1221 Err(error) => return refusal(core_status(&error), error),
1222 };
1223 let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
1224 let next = match events.last() {
1225 Some(last) if full => {
1226 let older = TimelineQuery {
1227 before: Some(last.id),
1228 limit: Some(1),
1229 ..query
1230 };
1231 match state.supervisor.timeline(older).await {
1232 Ok(older) if older.is_empty() => None,
1233 Ok(_) => Some(last.id),
1234 Err(error) => return refusal(core_status(&error), error),
1235 }
1236 }
1237 _ => None,
1238 };
1239 answer(StatusCode::OK, &TimelineAnswer { events, next })
1240}
1241
1242async fn preflight(
1246 State(state): State<ApiState>,
1247 Query(params): Query<PreflightParams>,
1248) -> Response {
1249 let Some(named) = params.file_name else {
1250 return refusal(
1251 StatusCode::BAD_REQUEST,
1252 "a filament check needs `file_name`, and this request carries none",
1253 );
1254 };
1255 let file_name = match FileName::new(&named) {
1256 Ok(file_name) => file_name,
1257 Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
1258 };
1259 let sheet = match params.sheet.map(SheetId::try_from).transpose() {
1260 Ok(sheet) => sheet,
1261 Err(why) => return refusal(StatusCode::BAD_REQUEST, why),
1262 };
1263 match state.supervisor.preflight(&file_name, sheet.as_ref()).await {
1264 Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
1265 Err(error) => refusal(core_status(&error), error),
1266 }
1267}
1268
1269async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
1276 match state.supervisor.list_and_adopt_prints().await {
1277 Ok(listing) => answer(
1278 StatusCode::OK,
1279 &PrintsAnswer {
1280 prints: listing.prints,
1281 active: listing.active,
1282 },
1283 ),
1284 Err(error) => refusal(core_status(&error), error),
1285 }
1286}
1287
1288async fn status(
1294 State(state): State<ApiState>,
1295 Extension(caller): Extension<Caller>,
1296 PrintPath(print_id): PrintPath,
1297) -> Response {
1298 if let Some(refused) = scope_refused(&caller, print_id) {
1299 return refused;
1300 }
1301 match state.prints.print(print_id).await {
1302 Ok(Some(_)) => {}
1303 Ok(None) => {
1304 return refusal(
1305 StatusCode::NOT_FOUND,
1306 format!("there is no print {print_id}"),
1307 );
1308 }
1309 Err(error) => return refusal(store_status(&error), error),
1310 }
1311 let context = match context_of(&state, print_id).await {
1312 Ok(context) => context,
1313 Err(refused) => return refused,
1314 };
1315 let session = match state.sessions.session(print_id).await {
1316 Ok(session) => session,
1317 Err(error) => return refusal(store_status(&error), error),
1318 };
1319 let planned_changes = if context.slicer.is_some() {
1322 match state
1323 .supervisor
1324 .planned_changes(&context.print, context.job.as_ref())
1325 .await
1326 {
1327 Ok(planned) => planned,
1328 Err(error) => return refusal(core_status(&error), error),
1329 }
1330 } else {
1331 None
1332 };
1333 answer(
1334 StatusCode::OK,
1335 &StatusAnswer {
1336 print: context.print,
1337 printer: context.printer,
1338 job: context.job,
1339 session,
1340 interventions: context.interventions,
1341 detector: context.detector,
1342 planned_changes,
1343 last_check_image: state
1344 .check_images
1345 .as_ref()
1346 .and_then(|images| images.last_check_image(print_id)),
1347 },
1348 )
1349}
1350
1351async fn context_of(
1359 state: &ApiState,
1360 print_id: PrintId,
1361) -> Result<printobserver_core::PrintContext, Response> {
1362 let supervisor = Arc::clone(&state.supervisor);
1363 let read = tokio::task::spawn_blocking(move || {
1364 printobserver_core::block_on(supervisor.context(print_id))
1365 })
1366 .await;
1367 match read {
1368 Ok(Ok(context)) => Ok(context),
1369 Ok(Err(error)) => Err(refusal(core_status(&error), error)),
1370 Err(error) => Err(refusal(StatusCode::INTERNAL_SERVER_ERROR, error)),
1371 }
1372}
1373
1374async fn context(
1382 State(state): State<ApiState>,
1383 Extension(caller): Extension<Caller>,
1384 PrintPath(print_id): PrintPath,
1385 Query(params): Query<ContextParams>,
1386) -> Response {
1387 if let Some(refused) = scope_refused(&caller, print_id) {
1388 return refused;
1389 }
1390 let supervisor = Arc::clone(&state.supervisor);
1392 let since = params.since;
1393 let read = tokio::task::spawn_blocking(move || {
1394 printobserver_core::block_on(supervisor.agent_context(print_id, since))
1395 })
1396 .await;
1397 let context = match read {
1398 Ok(Ok(read)) => read,
1399 Ok(Err(error)) => return refusal(core_status(&error), error),
1400 Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1401 };
1402 let mut image_path = None;
1403 if let Some(latest) = context.latest_image.as_ref() {
1404 match state.images.image(latest.id).await {
1405 Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
1406 Err(error) => return refusal(store_status(&error), error),
1407 }
1408 }
1409 answer(
1410 StatusCode::OK,
1411 &ContextAnswer {
1412 context,
1413 image_path,
1414 },
1415 )
1416}
1417
1418async fn look(
1426 State(state): State<ApiState>,
1427 Extension(caller): Extension<Caller>,
1428 PrintPath(print_id): PrintPath,
1429 Query(params): Query<LookParams>,
1430) -> Response {
1431 if let Some(refused) = scope_refused(&caller, print_id) {
1432 return refused;
1433 }
1434 let wait_s = params.wait_s.unwrap_or(0);
1435 if wait_s > MAX_LOOK_WAIT_S {
1436 return refusal(
1437 StatusCode::BAD_REQUEST,
1438 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1439 );
1440 }
1441 match state.prints.print(print_id).await {
1442 Ok(Some(_)) => {}
1443 Ok(None) => {
1444 return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
1445 }
1446 Err(error) => return refusal(store_status(&error), error),
1447 }
1448 if let Caller::Turn(binding) = &caller {
1451 state.turns.note_look(binding);
1452 }
1453 let supervisor = Arc::clone(&state.supervisor);
1454 let taken = tokio::task::spawn_blocking(move || {
1455 let (arrived, waited) =
1456 supervisor.await_look_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
1457 printobserver_core::block_on(supervisor.take_look(print_id, waited, arrived))
1458 })
1459 .await;
1460 match taken {
1461 Ok(Ok(look)) => answer(StatusCode::OK, &look),
1462 Ok(Err(error)) => refusal(core_status(&error), error),
1463 Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1464 }
1465}
1466
1467async fn printer_look(
1474 State(state): State<ApiState>,
1475 Extension(caller): Extension<Caller>,
1476 Query(params): Query<LookParams>,
1477) -> Response {
1478 if let Some(refused) = printless_refused(&caller, "a look at the printer with no print named") {
1479 return refused;
1480 }
1481 let wait_s = params.wait_s.unwrap_or(0);
1482 if wait_s > MAX_LOOK_WAIT_S {
1483 return refusal(
1484 StatusCode::BAD_REQUEST,
1485 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1486 );
1487 }
1488 let waited = Duration::from_secs(u64::from(wait_s));
1489 tokio::time::sleep(waited).await;
1490 match state.supervisor.take_printer_look(waited).await {
1491 Ok(look) => answer(StatusCode::OK, &look),
1492 Err(error) => refusal(core_status(&error), error),
1493 }
1494}
1495
1496async fn image(
1502 State(state): State<ApiState>,
1503 Extension(caller): Extension<Caller>,
1504 Path(image_id): Path<ImageId>,
1505) -> Response {
1506 match state.images.image(image_id).await {
1507 Ok(lookup) => {
1508 let belongs_to = match &lookup {
1509 printobserver_core::ImageLookup::Found { record, .. }
1510 | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
1511 };
1512 let refused = match belongs_to {
1513 Some(print_id) => scope_refused(&caller, print_id),
1514 None => {
1515 printless_refused(&caller, "a frame of the printer that belongs to no print")
1516 }
1517 };
1518 if let Some(refused) = refused {
1519 return refused;
1520 }
1521 answer(StatusCode::OK, &ImageAnswer::from(lookup))
1522 }
1523 Err(error) => refusal(store_status(&error), error),
1524 }
1525}
1526
1527async fn history(
1529 State(state): State<ApiState>,
1530 Extension(caller): Extension<Caller>,
1531 PrintPath(print_id): PrintPath,
1532 Query(params): Query<HistoryParams>,
1533) -> Response {
1534 if let Some(refused) = scope_refused(&caller, print_id) {
1535 return refused;
1536 }
1537 let query = HistoryQuery {
1538 print_id,
1539 kinds: Vec::new(),
1540 since: None,
1541 until: None,
1542 limit: params.limit,
1543 };
1544 match state.events.history(query).await {
1545 Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
1546 Err(error) => refusal(store_status(&error), error),
1547 }
1548}
1549
1550async fn manifest_get(
1552 State(state): State<ApiState>,
1553 Extension(caller): Extension<Caller>,
1554 PrintPath(print_id): PrintPath,
1555) -> Response {
1556 if let Some(refused) = scope_refused(&caller, print_id) {
1557 return refused;
1558 }
1559 let manifest = match state.prints.manifest(print_id).await {
1560 Ok(manifest) => manifest,
1561 Err(error) => return refusal(store_status(&error), error),
1562 };
1563 let narrowings = match state.prints.print(print_id).await {
1564 Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
1565 Err(error) => return refusal(store_status(&error), error),
1566 };
1567 answer(
1568 StatusCode::OK,
1569 &ManifestAnswer {
1570 manifest,
1571 narrowings,
1572 },
1573 )
1574}
1575
1576async fn manifest_set(
1585 State(state): State<ApiState>,
1586 Extension(caller): Extension<Caller>,
1587 PrintPath(print_id): PrintPath,
1588 body: Result<Json<ManifestBody>, JsonRejection>,
1589) -> Response {
1590 if let Some(refused) =
1591 operator_refused(&caller, &crate::operations::command_for("manifest_set"))
1592 {
1593 return refused;
1594 }
1595 let body = match body {
1596 Ok(Json(body)) => body,
1597 Err(rejected) => return rejected.into_response(),
1598 };
1599 if let Err(rejected) = body.reason() {
1600 return refusal(StatusCode::BAD_REQUEST, rejected);
1601 }
1602 let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
1603 if let Err(error) = state
1604 .prints
1605 .put_manifest(print_id, body.manifest.clone())
1606 .await
1607 {
1608 return refusal(store_status(&error), error);
1609 }
1610 for narrowing in narrowed.narrowings.clone() {
1611 if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
1612 return refusal(store_status(&error), error);
1613 }
1614 }
1615 answer(
1616 StatusCode::OK,
1617 &ManifestAnswer {
1618 manifest: Some(body.manifest),
1619 narrowings: narrowed.narrowings,
1620 },
1621 )
1622}
1623
1624#[cfg(test)]
1625mod tests {
1626 use axum::http::StatusCode;
1627 use printobserver_core::CoreError;
1628 use printobserver_core::store::StoreError;
1629
1630 use super::{core_status, store_status};
1631
1632 #[test]
1635 fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
1636 for (error, expected) in [
1637 (
1638 StoreError::NotFound {
1639 what: "print".to_owned(),
1640 },
1641 StatusCode::NOT_FOUND,
1642 ),
1643 (
1644 StoreError::LimitRefused {
1645 limit: 1_000,
1646 asked_for: 2_000,
1647 },
1648 StatusCode::BAD_REQUEST,
1649 ),
1650 (
1651 StoreError::ConstraintRefused {
1652 constraint: "actions.decision".to_owned(),
1653 },
1654 StatusCode::BAD_REQUEST,
1655 ),
1656 (
1657 StoreError::Database {
1658 detail: "the disk is full".to_owned(),
1659 },
1660 StatusCode::INTERNAL_SERVER_ERROR,
1661 ),
1662 (
1663 StoreError::Io {
1664 detail: "the disk is full".to_owned(),
1665 },
1666 StatusCode::INTERNAL_SERVER_ERROR,
1667 ),
1668 ] {
1669 assert_eq!(store_status(&error), expected, "{error}");
1670 }
1671 }
1672
1673 #[test]
1676 fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
1677 assert_eq!(
1678 core_status(&CoreError::NoSuchPrint {
1679 print_id: printobserver_types::PrintId::new(),
1680 }),
1681 StatusCode::NOT_FOUND
1682 );
1683 assert_eq!(
1684 core_status(&CoreError::Store(StoreError::NotFound {
1685 what: "print".to_owned(),
1686 })),
1687 StatusCode::NOT_FOUND
1688 );
1689 assert_eq!(
1690 core_status(&CoreError::Unrepresentable {
1691 detail: "an instant".to_owned(),
1692 }),
1693 StatusCode::INTERNAL_SERVER_ERROR
1694 );
1695 }
1696}