1use std::sync::Arc;
57use std::time::Duration;
58
59use axum::Json;
60use axum::extract::rejection::JsonRejection;
61use axum::extract::{DefaultBodyLimit, Extension, Path, Query, Request, State};
62use axum::http::{StatusCode, header};
63use axum::middleware::{Next, from_fn_with_state};
64use axum::response::{IntoResponse, Response};
65use axum::routing::{get, post, put};
66use axum::{Router, routing::MethodRouter};
67use printobserver_core::store::TimelineQuery;
68use printobserver_core::store::{
69 EventStore, HistoryQuery, ImageStore, PrintStore, SessionStore, StoreError,
70};
71use printobserver_core::{ActionKind, Actor, ExecutionOutcome, PolicyDecision, SpoolId};
72use printobserver_core::{CoreError, MAX_LOOK_WAIT_S, Supervisor, effective_bounds};
73use printobserver_types::serde::Deserialize;
74use printobserver_types::serde_json::Value;
75use printobserver_types::{EventId, EventKind, FileName, ImageId, PrintId, Timestamp};
76
77use crate::operations::{Effect, Method, OPERATIONS, Operation, VERSION_PREFIX};
78use crate::server::{CREDENTIAL_ISSUE, OperatorCredential};
79use crate::turns::{TurnBinding, TurnCredentials};
80use crate::wire::{
81 ActionAnswer, ActionBody, ContextAnswer, ErrorAnswer, HistoryAnswer, ImageAnswer,
82 ManifestAnswer, ManifestBody, PreflightAnswer, PrintsAnswer, SpoolAnswer, SpoolCommandAnswer,
83 SpoolsAnswer, StatusAnswer, TimelineAnswer, claimed_actor, spool_command_of,
84};
85
86#[derive(Clone)]
90pub struct ApiState {
91 pub supervisor: Arc<Supervisor>,
93 pub prints: Arc<dyn PrintStore>,
95 pub events: Arc<dyn EventStore>,
97 pub images: Arc<dyn ImageStore>,
99 pub sessions: Arc<dyn SessionStore>,
101 pub operator: Arc<OperatorCredential>,
104 pub turns: TurnCredentials,
106}
107
108#[derive(Debug, Clone, PartialEq, Eq)]
110pub enum Caller {
111 Operator,
113 Turn(TurnBinding),
115}
116
117impl Caller {
118 fn named(&self) -> String {
120 match self {
121 Self::Operator => "the operator".to_owned(),
122 Self::Turn(binding) => format!(
123 "the agent in session `{}` on print {}",
124 binding.session_name(),
125 binding.print_id()
126 ),
127 }
128 }
129}
130
131fn claimed(actor: &Actor) -> String {
133 match actor {
134 Actor::Operator => "the operator".to_owned(),
135 Actor::System => "the system".to_owned(),
136 Actor::Agent { session_name } => format!("the agent in session `{session_name}`"),
137 }
138}
139
140fn claim_refused(caller: &Caller, actor: &Actor) -> Option<Response> {
145 let held = match (caller, actor) {
146 (Caller::Operator, Actor::Operator) => true,
147 (Caller::Turn(binding), Actor::Agent { session_name }) => {
148 *session_name == binding.session_name()
149 }
150 _ => false,
151 };
152 if held {
153 return None;
154 }
155 let why = if matches!(actor, Actor::System) {
156 "no credential may claim the system, whose actions are the server's own"
157 } else {
158 "a request acts as the identity its credential authenticated, and no other"
159 };
160 Some(refusal(
161 StatusCode::FORBIDDEN,
162 format!(
163 "this request authenticated as {} and claims to be {}: {why}",
164 caller.named(),
165 claimed(actor)
166 ),
167 ))
168}
169
170fn scope_refused(caller: &Caller, print_id: PrintId) -> Option<Response> {
172 match caller {
173 Caller::Turn(binding) if binding.print_id() != print_id => Some(refusal(
174 StatusCode::FORBIDDEN,
175 format!(
176 "this request authenticated as {} and names print {print_id}: a supervision \
177 turn's credential reaches its own print alone",
178 caller.named()
179 ),
180 )),
181 _ => None,
182 }
183}
184
185fn operator_refused(caller: &Caller, command: &str) -> Option<Response> {
188 match caller {
189 Caller::Turn(_) => Some(refusal(
190 StatusCode::FORBIDDEN,
191 format!(
192 "this request authenticated as {} and asks for `{command}`, which is the \
193 operator's alone: a supervision turn's credential does not reach it",
194 caller.named()
195 ),
196 )),
197 Caller::Operator => None,
198 }
199}
200
201#[derive(Clone)]
203pub struct Admission {
204 operator: Arc<OperatorCredential>,
206 turns: TurnCredentials,
208}
209
210impl Admission {
211 fn caller(&self, presented: &[u8]) -> Option<Caller> {
213 if let Some(binding) = self.turns.admit(presented) {
214 return Some(Caller::Turn(binding));
215 }
216 self.operator.admits(presented).then_some(Caller::Operator)
217 }
218}
219
220impl core::fmt::Debug for ApiState {
221 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
222 formatter.debug_struct("ApiState").finish_non_exhaustive()
223 }
224}
225
226#[derive(Debug, Clone, Deserialize)]
228#[serde(crate = "printobserver_types::serde")]
229pub struct HistoryParams {
230 #[serde(default)]
232 pub limit: Option<u32>,
233}
234
235#[derive(Debug, Clone, Deserialize)]
237#[serde(crate = "printobserver_types::serde")]
238pub struct LookParams {
239 #[serde(default)]
241 pub wait_s: Option<u32>,
242}
243
244#[derive(Debug, Clone, Deserialize)]
246#[serde(crate = "printobserver_types::serde")]
247pub struct SpoolsParams {
248 #[serde(default)]
250 pub include_retired: Option<bool>,
251}
252
253#[derive(Debug, Clone, Deserialize)]
255#[serde(crate = "printobserver_types::serde")]
256pub struct PreflightParams {
257 #[serde(default)]
259 pub file_name: Option<String>,
260}
261
262pub const SPOOL_RECENT_EVENTS: u32 = 20;
264
265pub fn router(state: ApiState) -> Router {
273 let mut api = Router::new();
274 for operation in OPERATIONS {
275 api = api.route(operation.path, route_for(&operation));
276 }
277 let api = api
280 .fallback(nothing_here)
281 .layer(from_fn_with_state(
282 Admission {
283 operator: Arc::clone(&state.operator),
284 turns: state.turns.clone(),
285 },
286 authenticate,
287 ))
288 .layer(DefaultBodyLimit::max(BODY_BOUND))
289 .with_state(state);
290 Router::new().nest(VERSION_PREFIX, api)
291}
292
293const BEARER: &[u8] = b"Bearer ";
295
296pub const BODY_BOUND: usize = 2 * 1024 * 1024;
303
304pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
310
311pub async fn authenticate(
329 State(admission): State<Admission>,
330 mut request: Request,
331 next: Next,
332) -> Response {
333 let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
334 let admitted = match (presented.next(), presented.next()) {
335 (Some(only), None) => only
336 .as_bytes()
337 .strip_prefix(BEARER)
338 .and_then(|offered| admission.caller(offered)),
339 _ => None,
340 };
341 if let Some(caller) = admitted {
342 request.extensions_mut().insert(caller);
343 return next.run(request).await;
344 }
345 {
346 let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
347 format!(
348 "this server's API requires a credential, presented as `Authorization: Bearer \
349 <credential>`, and this server has no operator credential yet: run \
350 `{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
351 prints into the server's configuration, and restart the service"
352 )
353 } else {
354 format!(
355 "this server's API requires the credential it is configured with, presented as \
356 `Authorization: Bearer <credential>`. An operator without one runs \
357 `{CREDENTIAL_ISSUE}`"
358 )
359 };
360 let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
361 refused.headers_mut().insert(
362 header::WWW_AUTHENTICATE,
363 header::HeaderValue::from_static("Bearer"),
364 );
365 let _ = tokio::time::timeout(
369 DRAIN_BOUND,
370 axum::body::to_bytes(request.into_body(), BODY_BOUND),
371 )
372 .await;
373 refused
374 }
375}
376
377async fn nothing_here() -> Response {
379 refusal(
380 StatusCode::NOT_FOUND,
381 "no operation of this server is served at that path",
382 )
383}
384
385fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
387 if let Effect::Command(spool_command) = operation.effect {
388 let kind = spool_command.action_kind();
389 if operation.path.contains("{spool_id}") {
390 return post(
391 move |state: State<ApiState>,
392 caller: Extension<Caller>,
393 Path(spool_id): Path<SpoolId>,
394 body: Result<Json<Value>, JsonRejection>| async move {
395 command(kind, state, caller, Some(spool_id), body).await
396 },
397 );
398 }
399 return post(
400 move |state: State<ApiState>,
401 caller: Extension<Caller>,
402 body: Result<Json<Value>, JsonRejection>| async move {
403 command(kind, state, caller, None, body).await
404 },
405 );
406 }
407 if let Effect::Mutating(kind) = operation.effect {
408 return post(
409 move |state: State<ApiState>,
410 caller: Extension<Caller>,
411 print_id: Path<PrintId>,
412 body: Result<Json<ActionBody>, JsonRejection>| async move {
413 act(kind, state, caller, print_id, body).await
414 },
415 );
416 }
417 match (operation.name, operation.method) {
418 ("prints", Method::Get) => get(list_and_adopt_prints),
419 ("status", Method::Get) => get(status),
420 ("context", Method::Get) => get(context),
421 ("image", Method::Get) => get(image),
422 ("history", Method::Get) => get(history),
423 ("look", Method::Get) => get(look),
424 ("manifest_get", Method::Get) => get(manifest_get),
425 ("manifest_set", Method::Put) => put(manifest_set),
426 ("spools", Method::Get) => get(spools),
427 ("spool", Method::Get) => get(spool),
428 ("printer_history", Method::Get) => get(printer_history),
429 ("preflight", Method::Get) => get(preflight),
430 (name, method) => panic!(
431 "the operation `{name}` is declared as {method} and this router serves no such route"
432 ),
433 }
434}
435
436fn answer<T: printobserver_types::serde::Serialize>(status: StatusCode, body: &T) -> Response {
438 let rendered = match printobserver_types::serde_json::to_vec(body) {
439 Ok(bytes) => bytes,
440 Err(error) => {
441 return (
442 StatusCode::INTERNAL_SERVER_ERROR,
443 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
444 format!("{{\"error\":\"{error}\"}}"),
445 )
446 .into_response();
447 }
448 };
449 (
450 status,
451 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
452 rendered,
453 )
454 .into_response()
455}
456
457fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
459 answer(status, &ErrorAnswer::saying(detail))
460}
461
462fn store_status(error: &StoreError) -> StatusCode {
464 match error {
465 StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
466 StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
467 StatusCode::BAD_REQUEST
468 }
469 StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
470 }
471}
472
473fn core_status(error: &CoreError) -> StatusCode {
475 match error {
476 CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
477 CoreError::Store(store) => store_status(store),
478 _ => StatusCode::INTERNAL_SERVER_ERROR,
479 }
480}
481
482async fn act(
490 kind: ActionKind,
491 State(state): State<ApiState>,
492 Extension(caller): Extension<Caller>,
493 Path(print_id): Path<PrintId>,
494 body: Result<Json<ActionBody>, JsonRejection>,
495) -> Response {
496 if kind == ActionKind::StartPrint
497 && let Some(refused) =
498 operator_refused(&caller, &crate::operations::command_for("start_print"))
499 {
500 return refused;
501 }
502 if let Some(refused) = scope_refused(&caller, print_id) {
503 return refused;
504 }
505 let body = match body {
506 Ok(Json(body)) => body,
507 Err(rejected) => return rejected.into_response(),
508 };
509 if let Some(refused) = claim_refused(&caller, &body.actor) {
510 return refused;
511 }
512 let action = match body.into_action(kind) {
513 Ok(action) => action,
514 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
515 };
516 let outcome = match state.supervisor.request_action(print_id, action).await {
517 Ok(outcome) => outcome,
518 Err(error) => return refusal(core_status(&error), error),
519 };
520 let printer_refusal = match &outcome.record.outcome {
521 Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
522 _ => None,
523 };
524 let status = match outcome.record.decision {
525 PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
526 PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
530 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
533 };
534 answer(
535 status,
536 &ActionAnswer {
537 record: outcome.record,
538 intervention: outcome.intervention,
539 printer_refusal,
540 },
541 )
542}
543
544async fn command(
553 kind: ActionKind,
554 State(state): State<ApiState>,
555 Extension(caller): Extension<Caller>,
556 spool_id: Option<SpoolId>,
557 body: Result<Json<Value>, JsonRejection>,
558) -> Response {
559 let body = match body {
560 Ok(Json(body)) => body,
561 Err(rejected) => return rejected.into_response(),
562 };
563 let Some(fields) = body.as_object() else {
564 return refusal(
565 StatusCode::BAD_REQUEST,
566 "a spool command's body is a document of its fields",
567 );
568 };
569 let actor = match claimed_actor(fields) {
570 Ok(actor) => actor,
571 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
572 };
573 if let Some(refused) = claim_refused(&caller, &actor) {
574 return refused;
575 }
576 let asked = match spool_command_of(kind, spool_id, body) {
577 Ok(asked) => asked,
578 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
579 };
580 let outcome = match state.supervisor.request_spool_command(asked).await {
581 Ok(outcome) => outcome,
582 Err(error) => return refusal(core_status(&error), error),
583 };
584 let status = match outcome.decision {
585 PolicyDecision::Accepted => StatusCode::OK,
586 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
588 };
589 answer(
590 status,
591 &SpoolCommandAnswer {
592 decision: outcome.decision,
593 spool: outcome.spool,
594 events: outcome.events,
595 },
596 )
597}
598
599async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
601 let listed = match state
602 .supervisor
603 .spools(params.include_retired.unwrap_or(false))
604 .await
605 {
606 Ok(listed) => listed,
607 Err(error) => return refusal(core_status(&error), error),
608 };
609 match state.supervisor.pending_charges(None).await {
610 Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
611 Err(error) => refusal(core_status(&error), error),
612 }
613}
614
615async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
617 let found = match state.supervisor.spool(spool_id).await {
618 Ok(Some(found)) => found,
619 Ok(None) => {
620 return refusal(
621 StatusCode::NOT_FOUND,
622 format!("there is no spool {spool_id}"),
623 );
624 }
625 Err(error) => return refusal(core_status(&error), error),
626 };
627 let query = TimelineQuery {
628 spool_id: Some(spool_id),
629 limit: Some(SPOOL_RECENT_EVENTS),
630 ..every_timeline_kind()
631 };
632 match state.supervisor.timeline(query).await {
633 Ok(recent) => answer(
634 StatusCode::OK,
635 &SpoolAnswer {
636 spool: found,
637 recent,
638 },
639 ),
640 Err(error) => refusal(core_status(&error), error),
641 }
642}
643
644const fn every_timeline_kind() -> TimelineQuery {
646 TimelineQuery {
647 kinds: Vec::new(),
648 since: None,
649 until: None,
650 spool_id: None,
651 before: None,
652 limit: None,
653 }
654}
655
656fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
658where
659 T::Err: core::fmt::Display,
660{
661 text.parse()
662 .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
663}
664
665fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
672 let mut query = every_timeline_kind();
673 let mut seen: Vec<&str> = Vec::new();
674 for (name, text) in asked {
675 if name != "kinds" {
676 if seen.contains(&name.as_str()) {
677 return Err(format!(
678 "`{name}` was given more than once, and this read takes one"
679 ));
680 }
681 seen.push(name);
682 }
683 match name.as_str() {
684 "kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
685 "since" => query.since = Some(read_one::<Timestamp>(name, text)?),
686 "until" => query.until = Some(read_one::<Timestamp>(name, text)?),
687 "spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
688 "before" => query.before = Some(read_one::<EventId>(name, text)?),
689 "limit" => query.limit = Some(read_one::<u32>(name, text)?),
690 other => return Err(format!("the printer history takes no `{other}`")),
691 }
692 }
693 Ok(query)
694}
695
696async fn printer_history(
702 State(state): State<ApiState>,
703 Query(asked): Query<Vec<(String, String)>>,
704) -> Response {
705 let query = match timeline_query(&asked) {
706 Ok(query) => query,
707 Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
708 };
709 let limit = match query.resolved_limit() {
710 Ok(limit) => limit,
711 Err(error) => return refusal(store_status(&error), error),
712 };
713 let events = match state.supervisor.timeline(query.clone()).await {
714 Ok(events) => events,
715 Err(error) => return refusal(core_status(&error), error),
716 };
717 let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
718 let next = match events.last() {
719 Some(last) if full => {
720 let older = TimelineQuery {
721 before: Some(last.id),
722 limit: Some(1),
723 ..query
724 };
725 match state.supervisor.timeline(older).await {
726 Ok(older) if older.is_empty() => None,
727 Ok(_) => Some(last.id),
728 Err(error) => return refusal(core_status(&error), error),
729 }
730 }
731 _ => None,
732 };
733 answer(StatusCode::OK, &TimelineAnswer { events, next })
734}
735
736async fn preflight(
738 State(state): State<ApiState>,
739 Query(params): Query<PreflightParams>,
740) -> Response {
741 let Some(named) = params.file_name else {
742 return refusal(
743 StatusCode::BAD_REQUEST,
744 "a filament check needs `file_name`, and this request carries none",
745 );
746 };
747 let file_name = match FileName::new(&named) {
748 Ok(file_name) => file_name,
749 Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
750 };
751 match state.supervisor.preflight(&file_name).await {
752 Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
753 Err(error) => refusal(core_status(&error), error),
754 }
755}
756
757async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
764 match state.supervisor.list_and_adopt_prints().await {
765 Ok(listing) => answer(
766 StatusCode::OK,
767 &PrintsAnswer {
768 prints: listing.prints,
769 active: listing.active,
770 },
771 ),
772 Err(error) => refusal(core_status(&error), error),
773 }
774}
775
776async fn status(
782 State(state): State<ApiState>,
783 Extension(caller): Extension<Caller>,
784 Path(print_id): Path<PrintId>,
785) -> Response {
786 if let Some(refused) = scope_refused(&caller, print_id) {
787 return refused;
788 }
789 match state.prints.print(print_id).await {
790 Ok(Some(_)) => {}
791 Ok(None) => {
792 return refusal(
793 StatusCode::NOT_FOUND,
794 format!("there is no print {print_id}"),
795 );
796 }
797 Err(error) => return refusal(store_status(&error), error),
798 }
799 let context = match state.supervisor.context(print_id).await {
800 Ok(context) => context,
801 Err(error) => return refusal(core_status(&error), error),
802 };
803 let session = match state.sessions.session(print_id).await {
804 Ok(session) => session,
805 Err(error) => return refusal(store_status(&error), error),
806 };
807 answer(
808 StatusCode::OK,
809 &StatusAnswer {
810 print: context.print,
811 printer: context.printer,
812 job: context.job,
813 session,
814 interventions: context.interventions,
815 },
816 )
817}
818
819async fn context(
827 State(state): State<ApiState>,
828 Extension(caller): Extension<Caller>,
829 Path(print_id): Path<PrintId>,
830) -> Response {
831 if let Some(refused) = scope_refused(&caller, print_id) {
832 return refused;
833 }
834 let context = match state.supervisor.context(print_id).await {
835 Ok(context) => context,
836 Err(error) => return refusal(core_status(&error), error),
837 };
838 let mut image_path = None;
839 if let Some(latest) = context.latest_image.as_ref() {
840 match state.images.image(latest.id).await {
841 Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
842 Err(error) => return refusal(store_status(&error), error),
843 }
844 }
845 answer(
846 StatusCode::OK,
847 &ContextAnswer {
848 context,
849 image_path,
850 },
851 )
852}
853
854async fn look(
862 State(state): State<ApiState>,
863 Extension(caller): Extension<Caller>,
864 Path(print_id): Path<PrintId>,
865 Query(params): Query<LookParams>,
866) -> Response {
867 if let Some(refused) = scope_refused(&caller, print_id) {
868 return refused;
869 }
870 let wait_s = params.wait_s.unwrap_or(0);
871 if wait_s > MAX_LOOK_WAIT_S {
872 return refusal(
873 StatusCode::BAD_REQUEST,
874 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
875 );
876 }
877 match state.prints.print(print_id).await {
878 Ok(Some(_)) => {}
879 Ok(None) => {
880 return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
881 }
882 Err(error) => return refusal(store_status(&error), error),
883 }
884 let supervisor = Arc::clone(&state.supervisor);
885 let taken = tokio::task::spawn_blocking(move || {
886 let started = std::time::Instant::now();
887 let arrived = supervisor.await_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
888 printobserver_core::block_on(supervisor.take_look(print_id, started.elapsed(), arrived))
889 })
890 .await;
891 match taken {
892 Ok(Ok(look)) => answer(StatusCode::OK, &look),
893 Ok(Err(error)) => refusal(core_status(&error), error),
894 Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
895 }
896}
897
898async fn image(
903 State(state): State<ApiState>,
904 Extension(caller): Extension<Caller>,
905 Path(image_id): Path<ImageId>,
906) -> Response {
907 match state.images.image(image_id).await {
908 Ok(lookup) => {
909 let belongs_to = match &lookup {
910 printobserver_core::ImageLookup::Found { record, .. }
911 | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
912 };
913 if let Some(refused) = scope_refused(&caller, belongs_to) {
914 return refused;
915 }
916 answer(StatusCode::OK, &ImageAnswer::from(lookup))
917 }
918 Err(error) => refusal(store_status(&error), error),
919 }
920}
921
922async fn history(
924 State(state): State<ApiState>,
925 Extension(caller): Extension<Caller>,
926 Path(print_id): Path<PrintId>,
927 Query(params): Query<HistoryParams>,
928) -> Response {
929 if let Some(refused) = scope_refused(&caller, print_id) {
930 return refused;
931 }
932 let query = HistoryQuery {
933 print_id,
934 kinds: Vec::new(),
935 since: None,
936 until: None,
937 limit: params.limit,
938 };
939 match state.events.history(query).await {
940 Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
941 Err(error) => refusal(store_status(&error), error),
942 }
943}
944
945async fn manifest_get(
947 State(state): State<ApiState>,
948 Extension(caller): Extension<Caller>,
949 Path(print_id): Path<PrintId>,
950) -> Response {
951 if let Some(refused) = scope_refused(&caller, print_id) {
952 return refused;
953 }
954 let manifest = match state.prints.manifest(print_id).await {
955 Ok(manifest) => manifest,
956 Err(error) => return refusal(store_status(&error), error),
957 };
958 let narrowings = match state.prints.print(print_id).await {
959 Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
960 Err(error) => return refusal(store_status(&error), error),
961 };
962 answer(
963 StatusCode::OK,
964 &ManifestAnswer {
965 manifest,
966 narrowings,
967 },
968 )
969}
970
971async fn manifest_set(
980 State(state): State<ApiState>,
981 Extension(caller): Extension<Caller>,
982 Path(print_id): Path<PrintId>,
983 body: Result<Json<ManifestBody>, JsonRejection>,
984) -> Response {
985 if let Some(refused) =
986 operator_refused(&caller, &crate::operations::command_for("manifest_set"))
987 {
988 return refused;
989 }
990 let body = match body {
991 Ok(Json(body)) => body,
992 Err(rejected) => return rejected.into_response(),
993 };
994 if let Err(rejected) = body.reason() {
995 return refusal(StatusCode::BAD_REQUEST, rejected);
996 }
997 let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
998 if let Err(error) = state
999 .prints
1000 .put_manifest(print_id, body.manifest.clone())
1001 .await
1002 {
1003 return refusal(store_status(&error), error);
1004 }
1005 for narrowing in narrowed.narrowings.clone() {
1006 if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
1007 return refusal(store_status(&error), error);
1008 }
1009 }
1010 answer(
1011 StatusCode::OK,
1012 &ManifestAnswer {
1013 manifest: Some(body.manifest),
1014 narrowings: narrowed.narrowings,
1015 },
1016 )
1017}
1018
1019#[cfg(test)]
1020mod tests {
1021 use axum::http::StatusCode;
1022 use printobserver_core::CoreError;
1023 use printobserver_core::store::StoreError;
1024
1025 use super::{core_status, store_status};
1026
1027 #[test]
1030 fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
1031 for (error, expected) in [
1032 (
1033 StoreError::NotFound {
1034 what: "print".to_owned(),
1035 },
1036 StatusCode::NOT_FOUND,
1037 ),
1038 (
1039 StoreError::LimitRefused {
1040 limit: 1_000,
1041 asked_for: 2_000,
1042 },
1043 StatusCode::BAD_REQUEST,
1044 ),
1045 (
1046 StoreError::ConstraintRefused {
1047 constraint: "actions.decision".to_owned(),
1048 },
1049 StatusCode::BAD_REQUEST,
1050 ),
1051 (
1052 StoreError::Database {
1053 detail: "the disk is full".to_owned(),
1054 },
1055 StatusCode::INTERNAL_SERVER_ERROR,
1056 ),
1057 (
1058 StoreError::Io {
1059 detail: "the disk is full".to_owned(),
1060 },
1061 StatusCode::INTERNAL_SERVER_ERROR,
1062 ),
1063 ] {
1064 assert_eq!(store_status(&error), expected, "{error}");
1065 }
1066 }
1067
1068 #[test]
1071 fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
1072 assert_eq!(
1073 core_status(&CoreError::NoSuchPrint {
1074 print_id: printobserver_types::PrintId::new(),
1075 }),
1076 StatusCode::NOT_FOUND
1077 );
1078 assert_eq!(
1079 core_status(&CoreError::Store(StoreError::NotFound {
1080 what: "print".to_owned(),
1081 })),
1082 StatusCode::NOT_FOUND
1083 );
1084 assert_eq!(
1085 core_status(&CoreError::Unrepresentable {
1086 detail: "an instant".to_owned(),
1087 }),
1088 StatusCode::INTERNAL_SERVER_ERROR
1089 );
1090 }
1091}