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, 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, ContextAnswer, ErrorAnswer, HistoryAnswer, ImageAnswer,
91 ManifestAnswer, ManifestBody, PreflightAnswer, PrintsAnswer, RecoveryAnswer, SpoolAnswer,
92 SpoolCommandAnswer, SpoolsAnswer, StatusAnswer, TimelineAnswer, claimed_actor, recovery_of,
93 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
230#[derive(Clone)]
232pub struct Admission {
233 operator: Arc<OperatorCredential>,
235 turns: TurnCredentials,
237}
238
239impl Admission {
240 fn caller(&self, presented: &[u8]) -> Option<Caller> {
242 if let Some(binding) = self.turns.admit(presented) {
243 return Some(Caller::Turn(binding));
244 }
245 self.operator.admits(presented).then_some(Caller::Operator)
246 }
247}
248
249impl core::fmt::Debug for ApiState {
250 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
251 formatter.debug_struct("ApiState").finish_non_exhaustive()
252 }
253}
254
255#[derive(Debug, Clone, Deserialize)]
257#[serde(crate = "printobserver_types::serde")]
258pub struct HistoryParams {
259 #[serde(default)]
261 pub limit: Option<u32>,
262}
263
264#[derive(Debug, Clone, Deserialize)]
266#[serde(crate = "printobserver_types::serde")]
267pub struct LookParams {
268 #[serde(default)]
270 pub wait_s: Option<u32>,
271}
272
273#[derive(Debug, Clone, Deserialize)]
275#[serde(crate = "printobserver_types::serde")]
276pub struct SpoolsParams {
277 #[serde(default)]
279 pub include_retired: Option<bool>,
280}
281
282#[derive(Debug, Clone, Deserialize)]
284#[serde(crate = "printobserver_types::serde")]
285pub struct PreflightParams {
286 #[serde(default)]
288 pub file_name: Option<String>,
289}
290
291pub const SPOOL_RECENT_EVENTS: u32 = 20;
293
294pub fn router(state: ApiState) -> Router {
302 let mut api = Router::new();
303 for operation in OPERATIONS {
304 api = api.route(operation.path, route_for(&operation));
305 }
306 let api = api
309 .fallback(nothing_here)
310 .layer(from_fn_with_state(
311 Admission {
312 operator: Arc::clone(&state.operator),
313 turns: state.turns.clone(),
314 },
315 authenticate,
316 ))
317 .layer(DefaultBodyLimit::max(BODY_BOUND))
318 .with_state(state);
319 Router::new().nest(VERSION_PREFIX, api)
320}
321
322const BEARER: &[u8] = b"Bearer ";
324
325pub const BODY_BOUND: usize = 2 * 1024 * 1024;
332
333pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
339
340pub async fn authenticate(
358 State(admission): State<Admission>,
359 mut request: Request,
360 next: Next,
361) -> Response {
362 let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
363 let admitted = match (presented.next(), presented.next()) {
364 (Some(only), None) => only
365 .as_bytes()
366 .strip_prefix(BEARER)
367 .and_then(|offered| admission.caller(offered)),
368 _ => None,
369 };
370 if let Some(caller) = admitted {
371 request.extensions_mut().insert(caller);
372 return next.run(request).await;
373 }
374 {
375 let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
376 format!(
377 "this server's API requires a credential, presented as `Authorization: Bearer \
378 <credential>`, and this server has no operator credential yet: run \
379 `{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
380 prints into the server's configuration, and restart the service"
381 )
382 } else {
383 format!(
384 "this server's API requires the credential it is configured with, presented as \
385 `Authorization: Bearer <credential>`. An operator without one runs \
386 `{CREDENTIAL_ISSUE}`"
387 )
388 };
389 let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
390 refused.headers_mut().insert(
391 header::WWW_AUTHENTICATE,
392 header::HeaderValue::from_static("Bearer"),
393 );
394 let _ = tokio::time::timeout(
398 DRAIN_BOUND,
399 axum::body::to_bytes(request.into_body(), BODY_BOUND),
400 )
401 .await;
402 refused
403 }
404}
405
406async fn nothing_here() -> Response {
408 refusal(
409 StatusCode::NOT_FOUND,
410 "no operation of this server is served at that path",
411 )
412}
413
414fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
416 if let Effect::Command(spool_command) = operation.effect {
417 let kind = spool_command.action_kind();
418 if operation.path.contains("{spool_id}") {
419 return post(
420 move |state: State<ApiState>,
421 caller: Extension<Caller>,
422 Path(spool_id): Path<SpoolId>,
423 body: Result<Json<Value>, JsonRejection>| async move {
424 command(kind, state, caller, Some(spool_id), body).await
425 },
426 );
427 }
428 return post(
429 move |state: State<ApiState>,
430 caller: Extension<Caller>,
431 body: Result<Json<Value>, JsonRejection>| async move {
432 command(kind, state, caller, None, body).await
433 },
434 );
435 }
436 if let Effect::Recovery(kind) = operation.effect {
437 return post(
438 move |state: State<ApiState>,
439 caller: Extension<Caller>,
440 body: Result<Json<Value>, JsonRejection>| async move {
441 recover(kind, state, caller, body).await
442 },
443 );
444 }
445 if let Effect::Mutating(kind) = operation.effect {
446 return post(
447 move |state: State<ApiState>,
448 caller: Extension<Caller>,
449 print_id: Path<PrintId>,
450 body: Result<Json<ActionBody>, JsonRejection>| async move {
451 act(kind, state, caller, print_id, body).await
452 },
453 );
454 }
455 match (operation.name, operation.method) {
456 ("prints", Method::Get) => get(list_and_adopt_prints),
457 ("status", Method::Get) => get(status),
458 ("context", Method::Get) => get(context),
459 ("image", Method::Get) => get(image),
460 ("history", Method::Get) => get(history),
461 ("events", Method::Get) => get(crate::events::events),
462 ("look", Method::Get) => get(look),
463 (crate::operations::PRINTER_LOOK, Method::Get) => get(printer_look),
464 ("manifest_get", Method::Get) => get(manifest_get),
465 ("manifest_set", Method::Put) => put(manifest_set),
466 ("spools", Method::Get) => get(spools),
467 ("spool", Method::Get) => get(spool),
468 ("printer_history", Method::Get) => get(printer_history),
469 ("preflight", Method::Get) => get(preflight),
470 (crate::operations::RECOVERY_STATUS, Method::Get) => get(recover_status),
471 (name, method) => panic!(
472 "the operation `{name}` is declared as {method} and this router serves no such route"
473 ),
474 }
475}
476
477pub(crate) fn answer<T: printobserver_types::serde::Serialize>(
479 status: StatusCode,
480 body: &T,
481) -> Response {
482 let rendered = match printobserver_types::serde_json::to_vec(body) {
483 Ok(bytes) => bytes,
484 Err(error) => {
485 return (
486 StatusCode::INTERNAL_SERVER_ERROR,
487 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
488 format!("{{\"error\":\"{error}\"}}"),
489 )
490 .into_response();
491 }
492 };
493 (
494 status,
495 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
496 rendered,
497 )
498 .into_response()
499}
500
501pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
503 answer(status, &ErrorAnswer::saying(detail))
504}
505
506pub(crate) fn store_status(error: &StoreError) -> StatusCode {
508 match error {
509 StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
510 StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
511 StatusCode::BAD_REQUEST
512 }
513 StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
514 }
515}
516
517fn core_status(error: &CoreError) -> StatusCode {
519 match error {
520 CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
521 CoreError::Store(store) => store_status(store),
522 _ => StatusCode::INTERNAL_SERVER_ERROR,
523 }
524}
525
526async fn act(
534 kind: ActionKind,
535 State(state): State<ApiState>,
536 Extension(caller): Extension<Caller>,
537 Path(print_id): Path<PrintId>,
538 body: Result<Json<ActionBody>, JsonRejection>,
539) -> Response {
540 if kind == ActionKind::StartPrint
541 && let Some(refused) =
542 operator_refused(&caller, &crate::operations::command_for("start_print"))
543 {
544 return refused;
545 }
546 if let Some(refused) = scope_refused(&caller, print_id) {
547 return refused;
548 }
549 let body = match body {
550 Ok(Json(body)) => body,
551 Err(rejected) => return rejected.into_response(),
552 };
553 if let Some(refused) = claim_refused(&caller, &body.actor) {
554 return refused;
555 }
556 let action = match body.into_action(kind) {
557 Ok(action) => action,
558 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
559 };
560 let outcome = match state.supervisor.request_action(print_id, action).await {
561 Ok(outcome) => outcome,
562 Err(error) => return refusal(core_status(&error), error),
563 };
564 let printer_refusal = match &outcome.record.outcome {
565 Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
566 _ => None,
567 };
568 let status = match outcome.record.decision {
569 PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
570 PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
574 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
577 };
578 answer(
579 status,
580 &ActionAnswer {
581 record: outcome.record,
582 intervention: outcome.intervention,
583 printer_refusal,
584 },
585 )
586}
587
588async fn command(
597 kind: ActionKind,
598 State(state): State<ApiState>,
599 Extension(caller): Extension<Caller>,
600 spool_id: Option<SpoolId>,
601 body: Result<Json<Value>, JsonRejection>,
602) -> Response {
603 let body = match body {
604 Ok(Json(body)) => body,
605 Err(rejected) => return rejected.into_response(),
606 };
607 let Some(fields) = body.as_object() else {
608 return refusal(
609 StatusCode::BAD_REQUEST,
610 "a spool command's body is a document of its fields",
611 );
612 };
613 let actor = match claimed_actor(fields) {
614 Ok(actor) => actor,
615 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
616 };
617 if let Some(refused) = claim_refused(&caller, &actor) {
618 return refused;
619 }
620 let asked = match spool_command_of(kind, spool_id, body) {
621 Ok(asked) => asked,
622 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
623 };
624 let outcome = match state.supervisor.request_spool_command(asked).await {
625 Ok(outcome) => outcome,
626 Err(error) => return refusal(core_status(&error), error),
627 };
628 let status = match outcome.decision {
629 PolicyDecision::Accepted => StatusCode::OK,
630 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
632 };
633 answer(
634 status,
635 &SpoolCommandAnswer {
636 decision: outcome.decision,
637 spool: outcome.spool,
638 events: outcome.events,
639 },
640 )
641}
642
643async fn recover(
651 kind: RecoveryActionKind,
652 State(state): State<ApiState>,
653 Extension(caller): Extension<Caller>,
654 body: Result<Json<Value>, JsonRejection>,
655) -> Response {
656 let body = match body {
657 Ok(Json(body)) => body,
658 Err(rejected) => return rejected.into_response(),
659 };
660 if let Some(fields) = body.as_object() {
661 let actor = match claimed_actor(fields) {
662 Ok(actor) => actor,
663 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
664 };
665 if let Some(refused) = claim_refused(&caller, &actor) {
666 return refused;
667 }
668 }
669 let (action, actor, reason) = match recovery_of(kind, body) {
670 Ok(asked) => asked,
671 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
672 };
673 let issued = match state
674 .supervisor
675 .request_recovery(action.clone(), actor, reason)
676 .await
677 {
678 Ok(issued) => issued,
679 Err(error) => return refusal(core_status(&error), error),
680 };
681 let config = state.supervisor.config().recovery;
682 let status = match &issued.decision {
683 RecoveryDecision::Executed(ExecutionOutcome::Succeeded) => StatusCode::OK,
684 RecoveryDecision::Executed(ExecutionOutcome::Failed { .. }) => StatusCode::BAD_GATEWAY,
687 RecoveryDecision::Rejected(_) => StatusCode::CONFLICT,
689 };
690 answer(
691 status,
692 &RecoveryAnswer {
693 detail: recovery_detail(&action, &issued.decision, config.as_ref()),
694 action,
695 decision: issued.decision,
696 events: vec![issued.requested, issued.settled],
697 },
698 )
699}
700
701async fn recover_status(
704 State(state): State<ApiState>,
705 Extension(caller): Extension<Caller>,
706) -> Response {
707 let class = match caller {
708 Caller::Operator => ActorClass::Operator,
709 Caller::Turn(_) => ActorClass::Agent,
710 };
711 match state.supervisor.recovery_status(class).await {
712 Ok(status) => answer(StatusCode::OK, &status),
713 Err(error) => refusal(core_status(&error), error),
714 }
715}
716
717async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
719 let listed = match state
720 .supervisor
721 .spools(params.include_retired.unwrap_or(false))
722 .await
723 {
724 Ok(listed) => listed,
725 Err(error) => return refusal(core_status(&error), error),
726 };
727 match state.supervisor.pending_charges(None).await {
728 Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
729 Err(error) => refusal(core_status(&error), error),
730 }
731}
732
733async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
735 let found = match state.supervisor.spool(spool_id).await {
736 Ok(Some(found)) => found,
737 Ok(None) => {
738 return refusal(
739 StatusCode::NOT_FOUND,
740 format!("there is no spool {spool_id}"),
741 );
742 }
743 Err(error) => return refusal(core_status(&error), error),
744 };
745 let query = TimelineQuery {
746 spool_id: Some(spool_id),
747 limit: Some(SPOOL_RECENT_EVENTS),
748 ..every_timeline_kind()
749 };
750 match state.supervisor.timeline(query).await {
751 Ok(recent) => answer(
752 StatusCode::OK,
753 &SpoolAnswer {
754 spool: found,
755 recent,
756 },
757 ),
758 Err(error) => refusal(core_status(&error), error),
759 }
760}
761
762const fn every_timeline_kind() -> TimelineQuery {
764 TimelineQuery {
765 kinds: Vec::new(),
766 since: None,
767 until: None,
768 spool_id: None,
769 before: None,
770 limit: None,
771 }
772}
773
774fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
776where
777 T::Err: core::fmt::Display,
778{
779 text.parse()
780 .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
781}
782
783fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
790 let mut query = every_timeline_kind();
791 let mut seen: Vec<&str> = Vec::new();
792 for (name, text) in asked {
793 if name != "kinds" {
794 if seen.contains(&name.as_str()) {
795 return Err(format!(
796 "`{name}` was given more than once, and this read takes one"
797 ));
798 }
799 seen.push(name);
800 }
801 match name.as_str() {
802 "kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
803 "since" => query.since = Some(read_one::<Timestamp>(name, text)?),
804 "until" => query.until = Some(read_one::<Timestamp>(name, text)?),
805 "spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
806 "before" => query.before = Some(read_one::<EventId>(name, text)?),
807 "limit" => query.limit = Some(read_one::<u32>(name, text)?),
808 other => return Err(format!("the printer history takes no `{other}`")),
809 }
810 }
811 Ok(query)
812}
813
814async fn printer_history(
820 State(state): State<ApiState>,
821 Query(asked): Query<Vec<(String, String)>>,
822) -> Response {
823 let query = match timeline_query(&asked) {
824 Ok(query) => query,
825 Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
826 };
827 let limit = match query.resolved_limit() {
828 Ok(limit) => limit,
829 Err(error) => return refusal(store_status(&error), error),
830 };
831 let events = match state.supervisor.timeline(query.clone()).await {
832 Ok(events) => events,
833 Err(error) => return refusal(core_status(&error), error),
834 };
835 let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
836 let next = match events.last() {
837 Some(last) if full => {
838 let older = TimelineQuery {
839 before: Some(last.id),
840 limit: Some(1),
841 ..query
842 };
843 match state.supervisor.timeline(older).await {
844 Ok(older) if older.is_empty() => None,
845 Ok(_) => Some(last.id),
846 Err(error) => return refusal(core_status(&error), error),
847 }
848 }
849 _ => None,
850 };
851 answer(StatusCode::OK, &TimelineAnswer { events, next })
852}
853
854async fn preflight(
856 State(state): State<ApiState>,
857 Query(params): Query<PreflightParams>,
858) -> Response {
859 let Some(named) = params.file_name else {
860 return refusal(
861 StatusCode::BAD_REQUEST,
862 "a filament check needs `file_name`, and this request carries none",
863 );
864 };
865 let file_name = match FileName::new(&named) {
866 Ok(file_name) => file_name,
867 Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
868 };
869 match state.supervisor.preflight(&file_name).await {
870 Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
871 Err(error) => refusal(core_status(&error), error),
872 }
873}
874
875async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
882 match state.supervisor.list_and_adopt_prints().await {
883 Ok(listing) => answer(
884 StatusCode::OK,
885 &PrintsAnswer {
886 prints: listing.prints,
887 active: listing.active,
888 },
889 ),
890 Err(error) => refusal(core_status(&error), error),
891 }
892}
893
894async fn status(
900 State(state): State<ApiState>,
901 Extension(caller): Extension<Caller>,
902 Path(print_id): Path<PrintId>,
903) -> Response {
904 if let Some(refused) = scope_refused(&caller, print_id) {
905 return refused;
906 }
907 match state.prints.print(print_id).await {
908 Ok(Some(_)) => {}
909 Ok(None) => {
910 return refusal(
911 StatusCode::NOT_FOUND,
912 format!("there is no print {print_id}"),
913 );
914 }
915 Err(error) => return refusal(store_status(&error), error),
916 }
917 let context = match state.supervisor.context(print_id).await {
918 Ok(context) => context,
919 Err(error) => return refusal(core_status(&error), error),
920 };
921 let session = match state.sessions.session(print_id).await {
922 Ok(session) => session,
923 Err(error) => return refusal(store_status(&error), error),
924 };
925 answer(
926 StatusCode::OK,
927 &StatusAnswer {
928 print: context.print,
929 printer: context.printer,
930 job: context.job,
931 session,
932 interventions: context.interventions,
933 detector: context.detector,
934 },
935 )
936}
937
938async fn context(
946 State(state): State<ApiState>,
947 Extension(caller): Extension<Caller>,
948 Path(print_id): Path<PrintId>,
949) -> Response {
950 if let Some(refused) = scope_refused(&caller, print_id) {
951 return refused;
952 }
953 let context = match state.supervisor.context(print_id).await {
954 Ok(context) => context,
955 Err(error) => return refusal(core_status(&error), error),
956 };
957 let mut image_path = None;
958 if let Some(latest) = context.latest_image.as_ref() {
959 match state.images.image(latest.id).await {
960 Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
961 Err(error) => return refusal(store_status(&error), error),
962 }
963 }
964 answer(
965 StatusCode::OK,
966 &ContextAnswer {
967 context,
968 image_path,
969 },
970 )
971}
972
973async fn look(
981 State(state): State<ApiState>,
982 Extension(caller): Extension<Caller>,
983 Path(print_id): Path<PrintId>,
984 Query(params): Query<LookParams>,
985) -> Response {
986 if let Some(refused) = scope_refused(&caller, print_id) {
987 return refused;
988 }
989 let wait_s = params.wait_s.unwrap_or(0);
990 if wait_s > MAX_LOOK_WAIT_S {
991 return refusal(
992 StatusCode::BAD_REQUEST,
993 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
994 );
995 }
996 match state.prints.print(print_id).await {
997 Ok(Some(_)) => {}
998 Ok(None) => {
999 return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
1000 }
1001 Err(error) => return refusal(store_status(&error), error),
1002 }
1003 let supervisor = Arc::clone(&state.supervisor);
1004 let taken = tokio::task::spawn_blocking(move || {
1005 let started = std::time::Instant::now();
1006 let arrived = supervisor.await_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
1007 printobserver_core::block_on(supervisor.take_look(print_id, started.elapsed(), arrived))
1008 })
1009 .await;
1010 match taken {
1011 Ok(Ok(look)) => answer(StatusCode::OK, &look),
1012 Ok(Err(error)) => refusal(core_status(&error), error),
1013 Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1014 }
1015}
1016
1017async fn printer_look(
1024 State(state): State<ApiState>,
1025 Extension(caller): Extension<Caller>,
1026 Query(params): Query<LookParams>,
1027) -> Response {
1028 if let Some(refused) = printless_refused(&caller, "a look at the printer with no print named") {
1029 return refused;
1030 }
1031 let wait_s = params.wait_s.unwrap_or(0);
1032 if wait_s > MAX_LOOK_WAIT_S {
1033 return refusal(
1034 StatusCode::BAD_REQUEST,
1035 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1036 );
1037 }
1038 let waited = Duration::from_secs(u64::from(wait_s));
1039 tokio::time::sleep(waited).await;
1040 match state.supervisor.take_printer_look(waited).await {
1041 Ok(look) => answer(StatusCode::OK, &look),
1042 Err(error) => refusal(core_status(&error), error),
1043 }
1044}
1045
1046async fn image(
1052 State(state): State<ApiState>,
1053 Extension(caller): Extension<Caller>,
1054 Path(image_id): Path<ImageId>,
1055) -> Response {
1056 match state.images.image(image_id).await {
1057 Ok(lookup) => {
1058 let belongs_to = match &lookup {
1059 printobserver_core::ImageLookup::Found { record, .. }
1060 | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
1061 };
1062 let refused = match belongs_to {
1063 Some(print_id) => scope_refused(&caller, print_id),
1064 None => {
1065 printless_refused(&caller, "a frame of the printer that belongs to no print")
1066 }
1067 };
1068 if let Some(refused) = refused {
1069 return refused;
1070 }
1071 answer(StatusCode::OK, &ImageAnswer::from(lookup))
1072 }
1073 Err(error) => refusal(store_status(&error), error),
1074 }
1075}
1076
1077async fn history(
1079 State(state): State<ApiState>,
1080 Extension(caller): Extension<Caller>,
1081 Path(print_id): Path<PrintId>,
1082 Query(params): Query<HistoryParams>,
1083) -> Response {
1084 if let Some(refused) = scope_refused(&caller, print_id) {
1085 return refused;
1086 }
1087 let query = HistoryQuery {
1088 print_id,
1089 kinds: Vec::new(),
1090 since: None,
1091 until: None,
1092 limit: params.limit,
1093 };
1094 match state.events.history(query).await {
1095 Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
1096 Err(error) => refusal(store_status(&error), error),
1097 }
1098}
1099
1100async fn manifest_get(
1102 State(state): State<ApiState>,
1103 Extension(caller): Extension<Caller>,
1104 Path(print_id): Path<PrintId>,
1105) -> Response {
1106 if let Some(refused) = scope_refused(&caller, print_id) {
1107 return refused;
1108 }
1109 let manifest = match state.prints.manifest(print_id).await {
1110 Ok(manifest) => manifest,
1111 Err(error) => return refusal(store_status(&error), error),
1112 };
1113 let narrowings = match state.prints.print(print_id).await {
1114 Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
1115 Err(error) => return refusal(store_status(&error), error),
1116 };
1117 answer(
1118 StatusCode::OK,
1119 &ManifestAnswer {
1120 manifest,
1121 narrowings,
1122 },
1123 )
1124}
1125
1126async fn manifest_set(
1135 State(state): State<ApiState>,
1136 Extension(caller): Extension<Caller>,
1137 Path(print_id): Path<PrintId>,
1138 body: Result<Json<ManifestBody>, JsonRejection>,
1139) -> Response {
1140 if let Some(refused) =
1141 operator_refused(&caller, &crate::operations::command_for("manifest_set"))
1142 {
1143 return refused;
1144 }
1145 let body = match body {
1146 Ok(Json(body)) => body,
1147 Err(rejected) => return rejected.into_response(),
1148 };
1149 if let Err(rejected) = body.reason() {
1150 return refusal(StatusCode::BAD_REQUEST, rejected);
1151 }
1152 let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
1153 if let Err(error) = state
1154 .prints
1155 .put_manifest(print_id, body.manifest.clone())
1156 .await
1157 {
1158 return refusal(store_status(&error), error);
1159 }
1160 for narrowing in narrowed.narrowings.clone() {
1161 if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
1162 return refusal(store_status(&error), error);
1163 }
1164 }
1165 answer(
1166 StatusCode::OK,
1167 &ManifestAnswer {
1168 manifest: Some(body.manifest),
1169 narrowings: narrowed.narrowings,
1170 },
1171 )
1172}
1173
1174#[cfg(test)]
1175mod tests {
1176 use axum::http::StatusCode;
1177 use printobserver_core::CoreError;
1178 use printobserver_core::store::StoreError;
1179
1180 use super::{core_status, store_status};
1181
1182 #[test]
1185 fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
1186 for (error, expected) in [
1187 (
1188 StoreError::NotFound {
1189 what: "print".to_owned(),
1190 },
1191 StatusCode::NOT_FOUND,
1192 ),
1193 (
1194 StoreError::LimitRefused {
1195 limit: 1_000,
1196 asked_for: 2_000,
1197 },
1198 StatusCode::BAD_REQUEST,
1199 ),
1200 (
1201 StoreError::ConstraintRefused {
1202 constraint: "actions.decision".to_owned(),
1203 },
1204 StatusCode::BAD_REQUEST,
1205 ),
1206 (
1207 StoreError::Database {
1208 detail: "the disk is full".to_owned(),
1209 },
1210 StatusCode::INTERNAL_SERVER_ERROR,
1211 ),
1212 (
1213 StoreError::Io {
1214 detail: "the disk is full".to_owned(),
1215 },
1216 StatusCode::INTERNAL_SERVER_ERROR,
1217 ),
1218 ] {
1219 assert_eq!(store_status(&error), expected, "{error}");
1220 }
1221 }
1222
1223 #[test]
1226 fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
1227 assert_eq!(
1228 core_status(&CoreError::NoSuchPrint {
1229 print_id: printobserver_types::PrintId::new(),
1230 }),
1231 StatusCode::NOT_FOUND
1232 );
1233 assert_eq!(
1234 core_status(&CoreError::Store(StoreError::NotFound {
1235 what: "print".to_owned(),
1236 })),
1237 StatusCode::NOT_FOUND
1238 );
1239 assert_eq!(
1240 core_status(&CoreError::Unrepresentable {
1241 detail: "an instant".to_owned(),
1242 }),
1243 StatusCode::INTERNAL_SERVER_ERROR
1244 );
1245 }
1246}