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