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::{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}
119
120#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum Caller {
123 Operator,
125 Turn(TurnBinding),
127}
128
129impl Caller {
130 fn named(&self) -> String {
132 match self {
133 Self::Operator => "the operator".to_owned(),
134 Self::Turn(binding) => format!(
135 "the agent in session `{}` on print {}",
136 binding.session_name(),
137 binding.print_id()
138 ),
139 }
140 }
141}
142
143fn claimed(actor: &Actor) -> String {
145 match actor {
146 Actor::Operator => "the operator".to_owned(),
147 Actor::System => "the system".to_owned(),
148 Actor::Agent { session_name } => format!("the agent in session `{session_name}`"),
149 }
150}
151
152fn claim_refused(caller: &Caller, actor: &Actor) -> Option<Response> {
157 let held = match (caller, actor) {
158 (Caller::Operator, Actor::Operator) => true,
159 (Caller::Turn(binding), Actor::Agent { session_name }) => {
160 *session_name == binding.session_name()
161 }
162 _ => false,
163 };
164 if held {
165 return None;
166 }
167 let why = if matches!(actor, Actor::System) {
168 "no credential may claim the system, whose actions are the server's own"
169 } else {
170 "a request acts as the identity its credential authenticated, and no other"
171 };
172 Some(refusal(
173 StatusCode::FORBIDDEN,
174 format!(
175 "this request authenticated as {} and claims to be {}: {why}",
176 caller.named(),
177 claimed(actor)
178 ),
179 ))
180}
181
182pub(crate) fn scope_refused(caller: &Caller, print_id: PrintId) -> Option<Response> {
184 match caller {
185 Caller::Turn(binding) if binding.print_id() != print_id => Some(refusal(
186 StatusCode::FORBIDDEN,
187 format!(
188 "this request authenticated as {} and names print {print_id}: a supervision \
189 turn's credential reaches its own print alone",
190 caller.named()
191 ),
192 )),
193 _ => None,
194 }
195}
196
197fn printless_refused(caller: &Caller, what: &str) -> Option<Response> {
201 match caller {
202 Caller::Turn(_) => Some(refusal(
203 StatusCode::FORBIDDEN,
204 format!(
205 "this request authenticated as {} and asks for {what}: a supervision turn's \
206 credential reaches its own print alone",
207 caller.named()
208 ),
209 )),
210 Caller::Operator => None,
211 }
212}
213
214fn operator_refused(caller: &Caller, command: &str) -> Option<Response> {
217 match caller {
218 Caller::Turn(_) => Some(refusal(
219 StatusCode::FORBIDDEN,
220 format!(
221 "this request authenticated as {} and asks for `{command}`, which is the \
222 operator's alone: a supervision turn's credential does not reach it",
223 caller.named()
224 ),
225 )),
226 Caller::Operator => None,
227 }
228}
229
230fn unlooked_refused(
238 turns: &TurnCredentials,
239 caller: &Caller,
240 print_id: PrintId,
241) -> Option<Response> {
242 match caller {
243 Caller::Turn(binding) if !turns.has_looked(binding) => Some(refusal(
244 StatusCode::FORBIDDEN,
245 format!(
246 "this request authenticated as {} and acknowledges an event before the turn \
247 has taken a look: run `printobserver look --print-id {print_id}`, open the \
248 frames it names, and acknowledge what they show",
249 caller.named()
250 ),
251 )),
252 _ => None,
253 }
254}
255
256#[derive(Clone)]
258pub struct Admission {
259 operator: Arc<OperatorCredential>,
261 turns: TurnCredentials,
263}
264
265impl Admission {
266 fn caller(&self, presented: &[u8]) -> Option<Caller> {
268 if let Some(binding) = self.turns.admit(presented) {
269 return Some(Caller::Turn(binding));
270 }
271 self.operator.admits(presented).then_some(Caller::Operator)
272 }
273}
274
275impl core::fmt::Debug for ApiState {
276 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
277 formatter.debug_struct("ApiState").finish_non_exhaustive()
278 }
279}
280
281#[derive(Debug, Clone, Deserialize)]
283#[serde(crate = "printobserver_types::serde")]
284pub struct HistoryParams {
285 #[serde(default)]
287 pub limit: Option<u32>,
288}
289
290#[derive(Debug, Clone, Deserialize)]
293#[serde(crate = "printobserver_types::serde")]
294pub struct ContextParams {
295 #[serde(default)]
297 pub since: Option<printobserver_types::EventId>,
298}
299
300#[derive(Debug, Clone, Deserialize)]
302#[serde(crate = "printobserver_types::serde")]
303pub struct LookParams {
304 #[serde(default)]
306 pub wait_s: Option<u32>,
307}
308
309#[derive(Debug, Clone, Deserialize)]
311#[serde(crate = "printobserver_types::serde")]
312pub struct SpoolsParams {
313 #[serde(default)]
315 pub include_retired: Option<bool>,
316}
317
318#[derive(Debug, Clone, Deserialize)]
320#[serde(crate = "printobserver_types::serde")]
321pub struct PreflightParams {
322 #[serde(default)]
324 pub file_name: Option<String>,
325 #[serde(default)]
329 pub sheet: Option<String>,
330}
331
332pub const SPOOL_RECENT_EVENTS: u32 = 20;
334
335pub fn router(state: ApiState) -> Router {
343 let mut api = Router::new();
344 for operation in OPERATIONS {
345 api = api.route(operation.path, route_for(&operation));
346 }
347 let api = api
350 .fallback(nothing_here)
351 .layer(from_fn_with_state(
352 Admission {
353 operator: Arc::clone(&state.operator),
354 turns: state.turns.clone(),
355 },
356 authenticate,
357 ))
358 .layer(DefaultBodyLimit::max(BODY_BOUND))
359 .with_state(state);
360 Router::new().nest(VERSION_PREFIX, api)
361}
362
363const BEARER: &[u8] = b"Bearer ";
365
366pub const BODY_BOUND: usize = 2 * 1024 * 1024;
373
374pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
380
381pub async fn authenticate(
399 State(admission): State<Admission>,
400 mut request: Request,
401 next: Next,
402) -> Response {
403 let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
404 let admitted = match (presented.next(), presented.next()) {
405 (Some(only), None) => only
406 .as_bytes()
407 .strip_prefix(BEARER)
408 .and_then(|offered| admission.caller(offered)),
409 _ => None,
410 };
411 if let Some(caller) = admitted {
412 request.extensions_mut().insert(caller);
413 return next.run(request).await;
414 }
415 {
416 let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
417 format!(
418 "this server's API requires a credential, presented as `Authorization: Bearer \
419 <credential>`, and this server has no operator credential yet: run \
420 `{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
421 prints into the server's configuration, and restart the service"
422 )
423 } else {
424 format!(
425 "this server's API requires the credential it is configured with, presented as \
426 `Authorization: Bearer <credential>`. An operator without one runs \
427 `{CREDENTIAL_ISSUE}`"
428 )
429 };
430 let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
431 refused.headers_mut().insert(
432 header::WWW_AUTHENTICATE,
433 header::HeaderValue::from_static("Bearer"),
434 );
435 let _ = tokio::time::timeout(
439 DRAIN_BOUND,
440 axum::body::to_bytes(request.into_body(), BODY_BOUND),
441 )
442 .await;
443 refused
444 }
445}
446
447async fn nothing_here() -> Response {
449 refusal(
450 StatusCode::NOT_FOUND,
451 "no operation of this server is served at that path",
452 )
453}
454
455fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
457 if let Effect::Command(spool_command) = operation.effect {
458 let kind = spool_command.action_kind();
459 if operation.path.contains("{spool_id}") {
460 return post(
461 move |state: State<ApiState>,
462 caller: Extension<Caller>,
463 Path(spool_id): Path<SpoolId>,
464 body: Result<Json<Value>, JsonRejection>| async move {
465 command(kind, state, caller, Some(spool_id), body).await
466 },
467 );
468 }
469 return post(
470 move |state: State<ApiState>,
471 caller: Extension<Caller>,
472 body: Result<Json<Value>, JsonRejection>| async move {
473 command(kind, state, caller, None, body).await
474 },
475 );
476 }
477 if let Effect::Recovery(kind) = operation.effect {
478 return post(
479 move |state: State<ApiState>,
480 caller: Extension<Caller>,
481 body: Result<Json<Value>, JsonRejection>| async move {
482 recover(kind, state, caller, body).await
483 },
484 );
485 }
486 if let Effect::Mutating(kind) = operation.effect {
487 return post(
488 move |state: State<ApiState>,
489 caller: Extension<Caller>,
490 print_id: PrintPath,
491 body: Result<Json<ActionBody>, JsonRejection>| async move {
492 act(kind, state, caller, print_id, body).await
493 },
494 );
495 }
496 match (operation.name, operation.method) {
497 ("prints", Method::Get) => get(list_and_adopt_prints),
498 ("status", Method::Get) => get(status),
499 ("context", Method::Get) => get(context),
500 ("image", Method::Get) => get(image),
501 ("history", Method::Get) => get(history),
502 ("events", Method::Get) => get(crate::events::events),
503 ("look", Method::Get) => get(look),
504 (crate::operations::PRINTER_LOOK, Method::Get) => get(printer_look),
505 ("manifest_get", Method::Get) => get(manifest_get),
506 ("manifest_set", Method::Put) => put(manifest_set),
507 ("spools", Method::Get) => get(spools),
508 ("spool", Method::Get) => get(spool),
509 ("printer_history", Method::Get) => get(printer_history),
510 ("preflight", Method::Get) => get(preflight),
511 (crate::operations::RECOVERY_STATUS, Method::Get) => get(recover_status),
512 (crate::operations::BED_CLEAR, Method::Post) => post(bed_clear),
513 (name, method) => panic!(
514 "the operation `{name}` is declared as {method} and this router serves no such route"
515 ),
516 }
517}
518
519pub(crate) fn answer<T: printobserver_types::serde::Serialize>(
521 status: StatusCode,
522 body: &T,
523) -> Response {
524 let rendered = match printobserver_types::serde_json::to_vec(body) {
525 Ok(bytes) => bytes,
526 Err(error) => {
527 return (
528 StatusCode::INTERNAL_SERVER_ERROR,
529 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
530 format!("{{\"error\":\"{error}\"}}"),
531 )
532 .into_response();
533 }
534 };
535 (
536 status,
537 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
538 rendered,
539 )
540 .into_response()
541}
542
543pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
545 answer(status, &ErrorAnswer::saying(detail))
546}
547
548pub(crate) const PRINT_ID_REFUSED: &str = "a print is named by its id, a UUID, as `printobserver prints` \
551lists it; a start with no print open may name none, and is made under one minted for it";
552
553pub(crate) struct PrintPath(pub(crate) PrintId);
556
557impl<S: Send + Sync> axum::extract::FromRequestParts<S> for PrintPath {
558 type Rejection = Response;
559
560 async fn from_request_parts(
561 parts: &mut axum::http::request::Parts,
562 state: &S,
563 ) -> Result<Self, Self::Rejection> {
564 match Path::<PrintId>::from_request_parts(parts, state).await {
565 Ok(Path(print_id)) => Ok(Self(print_id)),
566 Err(rejected) => Err(refusal(
567 StatusCode::BAD_REQUEST,
568 format!("{}: {PRINT_ID_REFUSED}", rejected.body_text()),
569 )),
570 }
571 }
572}
573
574pub(crate) fn store_status(error: &StoreError) -> StatusCode {
576 match error {
577 StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
578 StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
579 StatusCode::BAD_REQUEST
580 }
581 StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
582 }
583}
584
585fn core_status(error: &CoreError) -> StatusCode {
587 match error {
588 CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
589 CoreError::Store(store) => store_status(store),
590 _ => StatusCode::INTERNAL_SERVER_ERROR,
591 }
592}
593
594async fn act(
602 kind: ActionKind,
603 State(state): State<ApiState>,
604 Extension(caller): Extension<Caller>,
605 PrintPath(print_id): PrintPath,
606 body: Result<Json<ActionBody>, JsonRejection>,
607) -> Response {
608 if kind == ActionKind::StartPrint
609 && let Some(refused) =
610 operator_refused(&caller, &crate::operations::command_for("start_print"))
611 {
612 return refused;
613 }
614 if let Some(refused) = scope_refused(&caller, print_id) {
615 return refused;
616 }
617 let body = match body {
618 Ok(Json(body)) => body,
619 Err(rejected) => return rejected.into_response(),
620 };
621 if let Some(refused) = claim_refused(&caller, &body.actor) {
622 return refused;
623 }
624 if kind == ActionKind::AcknowledgeFailure
625 && let Some(refused) = unlooked_refused(&state.turns, &caller, print_id)
626 {
627 return refused;
628 }
629 let action = match body.into_action(kind) {
630 Ok(action) => action,
631 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
632 };
633 let outcome = match state.supervisor.request_action(print_id, action).await {
634 Ok(outcome) => outcome,
635 Err(error) => return refusal(core_status(&error), error),
636 };
637 let printer_refusal = match &outcome.record.outcome {
638 Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
639 _ => None,
640 };
641 let status = match outcome.record.decision {
642 PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
643 PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
647 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
650 };
651 answer(
652 status,
653 &ActionAnswer {
654 record: outcome.record,
655 intervention: outcome.intervention,
656 printer_refusal,
657 },
658 )
659}
660
661async fn command(
670 kind: ActionKind,
671 State(state): State<ApiState>,
672 Extension(caller): Extension<Caller>,
673 spool_id: Option<SpoolId>,
674 body: Result<Json<Value>, JsonRejection>,
675) -> Response {
676 let body = match body {
677 Ok(Json(body)) => body,
678 Err(rejected) => return rejected.into_response(),
679 };
680 let Some(fields) = body.as_object() else {
681 return refusal(
682 StatusCode::BAD_REQUEST,
683 "a spool command's body is a document of its fields",
684 );
685 };
686 let actor = match claimed_actor(fields) {
687 Ok(actor) => actor,
688 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
689 };
690 if let Some(refused) = claim_refused(&caller, &actor) {
691 return refused;
692 }
693 let asked = match spool_command_of(kind, spool_id, body) {
694 Ok(asked) => asked,
695 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
696 };
697 let outcome = match state.supervisor.request_spool_command(asked).await {
698 Ok(outcome) => outcome,
699 Err(error) => return refusal(core_status(&error), error),
700 };
701 let status = match outcome.decision {
702 PolicyDecision::Accepted => StatusCode::OK,
703 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
705 };
706 answer(
707 status,
708 &SpoolCommandAnswer {
709 decision: outcome.decision,
710 spool: outcome.spool,
711 events: outcome.events,
712 },
713 )
714}
715
716async fn recover(
724 kind: RecoveryActionKind,
725 State(state): State<ApiState>,
726 Extension(caller): Extension<Caller>,
727 body: Result<Json<Value>, JsonRejection>,
728) -> Response {
729 let body = match body {
730 Ok(Json(body)) => body,
731 Err(rejected) => return rejected.into_response(),
732 };
733 if let Some(fields) = body.as_object() {
734 let actor = match claimed_actor(fields) {
735 Ok(actor) => actor,
736 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
737 };
738 if let Some(refused) = claim_refused(&caller, &actor) {
739 return refused;
740 }
741 }
742 let (action, actor, reason) = match recovery_of(kind, body) {
743 Ok(asked) => asked,
744 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
745 };
746 let issued = match state
747 .supervisor
748 .request_recovery(action.clone(), actor, reason)
749 .await
750 {
751 Ok(issued) => issued,
752 Err(error) => return refusal(core_status(&error), error),
753 };
754 let config = state.supervisor.config().recovery;
755 let status = match &issued.decision {
756 RecoveryDecision::Executed(ExecutionOutcome::Succeeded) => StatusCode::OK,
757 RecoveryDecision::Executed(ExecutionOutcome::Failed { .. }) => StatusCode::BAD_GATEWAY,
760 RecoveryDecision::Rejected(_) => StatusCode::CONFLICT,
762 };
763 answer(
764 status,
765 &RecoveryAnswer {
766 detail: recovery_detail(&action, &issued.decision, config.as_ref()),
767 action,
768 decision: issued.decision,
769 events: vec![issued.requested, issued.settled],
770 },
771 )
772}
773
774pub const BED_CLEAR_DETAIL: &str = "recorded: until the next print starts, a Z home is decided \
776 as though it asserted the bed clear, and a heat, a park and an XY home as though they \
777 asserted the nozzle clear of the part, wherever the operator's word counts";
778
779async fn bed_clear(
787 State(state): State<ApiState>,
788 Extension(caller): Extension<Caller>,
789 body: Result<Json<Value>, JsonRejection>,
790) -> Response {
791 let body = match body {
792 Ok(Json(body)) => body,
793 Err(rejected) => return rejected.into_response(),
794 };
795 let Some(fields) = body.as_object() else {
796 return refusal(
797 StatusCode::BAD_REQUEST,
798 "the body is not a document carrying an `actor` and a `reason`",
799 );
800 };
801 let actor = match claimed_actor(fields) {
802 Ok(actor) => actor,
803 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
804 };
805 if let Some(refused) = claim_refused(&caller, &actor) {
806 return refused;
807 }
808 if actor != Actor::Operator {
809 return refusal(
810 StatusCode::FORBIDDEN,
811 format!(
812 "{} may not say the bed is clear: an assertion is a person's word for what \
813 they can see, and only the operator's is recorded",
814 claimed(&actor)
815 ),
816 );
817 }
818 let body: BedClearBody = match printobserver_types::serde_json::from_value(body) {
819 Ok(body) => body,
820 Err(error) => {
821 return refusal(
822 StatusCode::BAD_REQUEST,
823 format!("the body is not an `actor` and a `reason`: {error}"),
824 );
825 }
826 };
827 let reason = match reason_of(body.reason.as_deref()) {
828 Ok(reason) => reason,
829 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
830 };
831 match state.supervisor.assert_bed_clear(reason).await {
832 Ok(event) => answer(
833 StatusCode::OK,
834 &BedClearAnswer {
835 event,
836 detail: BED_CLEAR_DETAIL.to_owned(),
837 },
838 ),
839 Err(error) => refusal(core_status(&error), error),
840 }
841}
842
843async fn recover_status(
846 State(state): State<ApiState>,
847 Extension(caller): Extension<Caller>,
848) -> Response {
849 let class = match caller {
850 Caller::Operator => ActorClass::Operator,
851 Caller::Turn(_) => ActorClass::Agent,
852 };
853 match state.supervisor.recovery_status(class).await {
854 Ok(status) => answer(StatusCode::OK, &status),
855 Err(error) => refusal(core_status(&error), error),
856 }
857}
858
859async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
861 let listed = match state
862 .supervisor
863 .spools(params.include_retired.unwrap_or(false))
864 .await
865 {
866 Ok(listed) => listed,
867 Err(error) => return refusal(core_status(&error), error),
868 };
869 match state.supervisor.pending_charges(None).await {
870 Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
871 Err(error) => refusal(core_status(&error), error),
872 }
873}
874
875async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
877 let found = match state.supervisor.spool(spool_id).await {
878 Ok(Some(found)) => found,
879 Ok(None) => {
880 return refusal(
881 StatusCode::NOT_FOUND,
882 format!("there is no spool {spool_id}"),
883 );
884 }
885 Err(error) => return refusal(core_status(&error), error),
886 };
887 let query = TimelineQuery {
888 spool_id: Some(spool_id),
889 limit: Some(SPOOL_RECENT_EVENTS),
890 ..every_timeline_kind()
891 };
892 match state.supervisor.timeline(query).await {
893 Ok(recent) => answer(
894 StatusCode::OK,
895 &SpoolAnswer {
896 spool: found,
897 recent,
898 },
899 ),
900 Err(error) => refusal(core_status(&error), error),
901 }
902}
903
904const fn every_timeline_kind() -> TimelineQuery {
906 TimelineQuery {
907 kinds: Vec::new(),
908 since: None,
909 until: None,
910 spool_id: None,
911 before: None,
912 limit: None,
913 }
914}
915
916fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
918where
919 T::Err: core::fmt::Display,
920{
921 text.parse()
922 .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
923}
924
925fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
932 let mut query = every_timeline_kind();
933 let mut seen: Vec<&str> = Vec::new();
934 for (name, text) in asked {
935 if name != "kinds" {
936 if seen.contains(&name.as_str()) {
937 return Err(format!(
938 "`{name}` was given more than once, and this read takes one"
939 ));
940 }
941 seen.push(name);
942 }
943 match name.as_str() {
944 "kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
945 "since" => query.since = Some(read_one::<Timestamp>(name, text)?),
946 "until" => query.until = Some(read_one::<Timestamp>(name, text)?),
947 "spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
948 "before" => query.before = Some(read_one::<EventId>(name, text)?),
949 "limit" => query.limit = Some(read_one::<u32>(name, text)?),
950 other => return Err(format!("the printer history takes no `{other}`")),
951 }
952 }
953 Ok(query)
954}
955
956async fn printer_history(
962 State(state): State<ApiState>,
963 Query(asked): Query<Vec<(String, String)>>,
964) -> Response {
965 let query = match timeline_query(&asked) {
966 Ok(query) => query,
967 Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
968 };
969 let limit = match query.resolved_limit() {
970 Ok(limit) => limit,
971 Err(error) => return refusal(store_status(&error), error),
972 };
973 let events = match state.supervisor.timeline(query.clone()).await {
974 Ok(events) => events,
975 Err(error) => return refusal(core_status(&error), error),
976 };
977 let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
978 let next = match events.last() {
979 Some(last) if full => {
980 let older = TimelineQuery {
981 before: Some(last.id),
982 limit: Some(1),
983 ..query
984 };
985 match state.supervisor.timeline(older).await {
986 Ok(older) if older.is_empty() => None,
987 Ok(_) => Some(last.id),
988 Err(error) => return refusal(core_status(&error), error),
989 }
990 }
991 _ => None,
992 };
993 answer(StatusCode::OK, &TimelineAnswer { events, next })
994}
995
996async fn preflight(
1000 State(state): State<ApiState>,
1001 Query(params): Query<PreflightParams>,
1002) -> Response {
1003 let Some(named) = params.file_name else {
1004 return refusal(
1005 StatusCode::BAD_REQUEST,
1006 "a filament check needs `file_name`, and this request carries none",
1007 );
1008 };
1009 let file_name = match FileName::new(&named) {
1010 Ok(file_name) => file_name,
1011 Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
1012 };
1013 let sheet = match params.sheet.map(SheetId::try_from).transpose() {
1014 Ok(sheet) => sheet,
1015 Err(why) => return refusal(StatusCode::BAD_REQUEST, why),
1016 };
1017 match state.supervisor.preflight(&file_name, sheet.as_ref()).await {
1018 Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
1019 Err(error) => refusal(core_status(&error), error),
1020 }
1021}
1022
1023async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
1030 match state.supervisor.list_and_adopt_prints().await {
1031 Ok(listing) => answer(
1032 StatusCode::OK,
1033 &PrintsAnswer {
1034 prints: listing.prints,
1035 active: listing.active,
1036 },
1037 ),
1038 Err(error) => refusal(core_status(&error), error),
1039 }
1040}
1041
1042async fn status(
1048 State(state): State<ApiState>,
1049 Extension(caller): Extension<Caller>,
1050 PrintPath(print_id): PrintPath,
1051) -> Response {
1052 if let Some(refused) = scope_refused(&caller, print_id) {
1053 return refused;
1054 }
1055 match state.prints.print(print_id).await {
1056 Ok(Some(_)) => {}
1057 Ok(None) => {
1058 return refusal(
1059 StatusCode::NOT_FOUND,
1060 format!("there is no print {print_id}"),
1061 );
1062 }
1063 Err(error) => return refusal(store_status(&error), error),
1064 }
1065 let context = match context_of(&state, print_id).await {
1066 Ok(context) => context,
1067 Err(refused) => return refused,
1068 };
1069 let session = match state.sessions.session(print_id).await {
1070 Ok(session) => session,
1071 Err(error) => return refusal(store_status(&error), error),
1072 };
1073 answer(
1074 StatusCode::OK,
1075 &StatusAnswer {
1076 print: context.print,
1077 printer: context.printer,
1078 job: context.job,
1079 session,
1080 interventions: context.interventions,
1081 detector: context.detector,
1082 },
1083 )
1084}
1085
1086async fn context_of(
1094 state: &ApiState,
1095 print_id: PrintId,
1096) -> Result<printobserver_core::PrintContext, Response> {
1097 let supervisor = Arc::clone(&state.supervisor);
1098 let read = tokio::task::spawn_blocking(move || {
1099 printobserver_core::block_on(supervisor.context(print_id))
1100 })
1101 .await;
1102 match read {
1103 Ok(Ok(context)) => Ok(context),
1104 Ok(Err(error)) => Err(refusal(core_status(&error), error)),
1105 Err(error) => Err(refusal(StatusCode::INTERNAL_SERVER_ERROR, error)),
1106 }
1107}
1108
1109async fn context(
1117 State(state): State<ApiState>,
1118 Extension(caller): Extension<Caller>,
1119 PrintPath(print_id): PrintPath,
1120 Query(params): Query<ContextParams>,
1121) -> Response {
1122 if let Some(refused) = scope_refused(&caller, print_id) {
1123 return refused;
1124 }
1125 let supervisor = Arc::clone(&state.supervisor);
1127 let since = params.since;
1128 let read = tokio::task::spawn_blocking(move || {
1129 printobserver_core::block_on(supervisor.agent_context(print_id, since))
1130 })
1131 .await;
1132 let context = match read {
1133 Ok(Ok(read)) => read,
1134 Ok(Err(error)) => return refusal(core_status(&error), error),
1135 Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1136 };
1137 let mut image_path = None;
1138 if let Some(latest) = context.latest_image.as_ref() {
1139 match state.images.image(latest.id).await {
1140 Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
1141 Err(error) => return refusal(store_status(&error), error),
1142 }
1143 }
1144 answer(
1145 StatusCode::OK,
1146 &ContextAnswer {
1147 context,
1148 image_path,
1149 },
1150 )
1151}
1152
1153async fn look(
1161 State(state): State<ApiState>,
1162 Extension(caller): Extension<Caller>,
1163 PrintPath(print_id): PrintPath,
1164 Query(params): Query<LookParams>,
1165) -> Response {
1166 if let Some(refused) = scope_refused(&caller, print_id) {
1167 return refused;
1168 }
1169 let wait_s = params.wait_s.unwrap_or(0);
1170 if wait_s > MAX_LOOK_WAIT_S {
1171 return refusal(
1172 StatusCode::BAD_REQUEST,
1173 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1174 );
1175 }
1176 match state.prints.print(print_id).await {
1177 Ok(Some(_)) => {}
1178 Ok(None) => {
1179 return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
1180 }
1181 Err(error) => return refusal(store_status(&error), error),
1182 }
1183 if let Caller::Turn(binding) = &caller {
1186 state.turns.note_look(binding);
1187 }
1188 let supervisor = Arc::clone(&state.supervisor);
1189 let taken = tokio::task::spawn_blocking(move || {
1190 let (arrived, waited) =
1191 supervisor.await_look_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
1192 printobserver_core::block_on(supervisor.take_look(print_id, waited, arrived))
1193 })
1194 .await;
1195 match taken {
1196 Ok(Ok(look)) => answer(StatusCode::OK, &look),
1197 Ok(Err(error)) => refusal(core_status(&error), error),
1198 Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1199 }
1200}
1201
1202async fn printer_look(
1209 State(state): State<ApiState>,
1210 Extension(caller): Extension<Caller>,
1211 Query(params): Query<LookParams>,
1212) -> Response {
1213 if let Some(refused) = printless_refused(&caller, "a look at the printer with no print named") {
1214 return refused;
1215 }
1216 let wait_s = params.wait_s.unwrap_or(0);
1217 if wait_s > MAX_LOOK_WAIT_S {
1218 return refusal(
1219 StatusCode::BAD_REQUEST,
1220 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1221 );
1222 }
1223 let waited = Duration::from_secs(u64::from(wait_s));
1224 tokio::time::sleep(waited).await;
1225 match state.supervisor.take_printer_look(waited).await {
1226 Ok(look) => answer(StatusCode::OK, &look),
1227 Err(error) => refusal(core_status(&error), error),
1228 }
1229}
1230
1231async fn image(
1237 State(state): State<ApiState>,
1238 Extension(caller): Extension<Caller>,
1239 Path(image_id): Path<ImageId>,
1240) -> Response {
1241 match state.images.image(image_id).await {
1242 Ok(lookup) => {
1243 let belongs_to = match &lookup {
1244 printobserver_core::ImageLookup::Found { record, .. }
1245 | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
1246 };
1247 let refused = match belongs_to {
1248 Some(print_id) => scope_refused(&caller, print_id),
1249 None => {
1250 printless_refused(&caller, "a frame of the printer that belongs to no print")
1251 }
1252 };
1253 if let Some(refused) = refused {
1254 return refused;
1255 }
1256 answer(StatusCode::OK, &ImageAnswer::from(lookup))
1257 }
1258 Err(error) => refusal(store_status(&error), error),
1259 }
1260}
1261
1262async fn history(
1264 State(state): State<ApiState>,
1265 Extension(caller): Extension<Caller>,
1266 PrintPath(print_id): PrintPath,
1267 Query(params): Query<HistoryParams>,
1268) -> Response {
1269 if let Some(refused) = scope_refused(&caller, print_id) {
1270 return refused;
1271 }
1272 let query = HistoryQuery {
1273 print_id,
1274 kinds: Vec::new(),
1275 since: None,
1276 until: None,
1277 limit: params.limit,
1278 };
1279 match state.events.history(query).await {
1280 Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
1281 Err(error) => refusal(store_status(&error), error),
1282 }
1283}
1284
1285async fn manifest_get(
1287 State(state): State<ApiState>,
1288 Extension(caller): Extension<Caller>,
1289 PrintPath(print_id): PrintPath,
1290) -> Response {
1291 if let Some(refused) = scope_refused(&caller, print_id) {
1292 return refused;
1293 }
1294 let manifest = match state.prints.manifest(print_id).await {
1295 Ok(manifest) => manifest,
1296 Err(error) => return refusal(store_status(&error), error),
1297 };
1298 let narrowings = match state.prints.print(print_id).await {
1299 Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
1300 Err(error) => return refusal(store_status(&error), error),
1301 };
1302 answer(
1303 StatusCode::OK,
1304 &ManifestAnswer {
1305 manifest,
1306 narrowings,
1307 },
1308 )
1309}
1310
1311async fn manifest_set(
1320 State(state): State<ApiState>,
1321 Extension(caller): Extension<Caller>,
1322 PrintPath(print_id): PrintPath,
1323 body: Result<Json<ManifestBody>, JsonRejection>,
1324) -> Response {
1325 if let Some(refused) =
1326 operator_refused(&caller, &crate::operations::command_for("manifest_set"))
1327 {
1328 return refused;
1329 }
1330 let body = match body {
1331 Ok(Json(body)) => body,
1332 Err(rejected) => return rejected.into_response(),
1333 };
1334 if let Err(rejected) = body.reason() {
1335 return refusal(StatusCode::BAD_REQUEST, rejected);
1336 }
1337 let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
1338 if let Err(error) = state
1339 .prints
1340 .put_manifest(print_id, body.manifest.clone())
1341 .await
1342 {
1343 return refusal(store_status(&error), error);
1344 }
1345 for narrowing in narrowed.narrowings.clone() {
1346 if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
1347 return refusal(store_status(&error), error);
1348 }
1349 }
1350 answer(
1351 StatusCode::OK,
1352 &ManifestAnswer {
1353 manifest: Some(body.manifest),
1354 narrowings: narrowed.narrowings,
1355 },
1356 )
1357}
1358
1359#[cfg(test)]
1360mod tests {
1361 use axum::http::StatusCode;
1362 use printobserver_core::CoreError;
1363 use printobserver_core::store::StoreError;
1364
1365 use super::{core_status, store_status};
1366
1367 #[test]
1370 fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
1371 for (error, expected) in [
1372 (
1373 StoreError::NotFound {
1374 what: "print".to_owned(),
1375 },
1376 StatusCode::NOT_FOUND,
1377 ),
1378 (
1379 StoreError::LimitRefused {
1380 limit: 1_000,
1381 asked_for: 2_000,
1382 },
1383 StatusCode::BAD_REQUEST,
1384 ),
1385 (
1386 StoreError::ConstraintRefused {
1387 constraint: "actions.decision".to_owned(),
1388 },
1389 StatusCode::BAD_REQUEST,
1390 ),
1391 (
1392 StoreError::Database {
1393 detail: "the disk is full".to_owned(),
1394 },
1395 StatusCode::INTERNAL_SERVER_ERROR,
1396 ),
1397 (
1398 StoreError::Io {
1399 detail: "the disk is full".to_owned(),
1400 },
1401 StatusCode::INTERNAL_SERVER_ERROR,
1402 ),
1403 ] {
1404 assert_eq!(store_status(&error), expected, "{error}");
1405 }
1406 }
1407
1408 #[test]
1411 fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
1412 assert_eq!(
1413 core_status(&CoreError::NoSuchPrint {
1414 print_id: printobserver_types::PrintId::new(),
1415 }),
1416 StatusCode::NOT_FOUND
1417 );
1418 assert_eq!(
1419 core_status(&CoreError::Store(StoreError::NotFound {
1420 what: "print".to_owned(),
1421 })),
1422 StatusCode::NOT_FOUND
1423 );
1424 assert_eq!(
1425 core_status(&CoreError::Unrepresentable {
1426 detail: "an instant".to_owned(),
1427 }),
1428 StatusCode::INTERNAL_SERVER_ERROR
1429 );
1430 }
1431}