use std::sync::Arc;
use std::time::Duration;
use axum::Json;
use axum::extract::rejection::{JsonRejection, QueryRejection};
use axum::extract::{DefaultBodyLimit, Extension, Path, Query, Request, State};
use axum::http::{StatusCode, header};
use axum::middleware::{Next, from_fn_with_state};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post, put};
use axum::{Router, routing::MethodRouter};
use printobserver_core::recovery::recovery_detail;
use printobserver_core::store::TimelineQuery;
use printobserver_core::store::{
EventStore, HistoryQuery, ImageStore, PrintStore, SessionStore, StoreError,
};
use printobserver_core::{
ActionKind, Actor, ActorClass, ExecutionOutcome, PolicyDecision, RecoveryActionKind,
RecoveryDecision, SheetId, SpoolId,
};
use printobserver_core::{CoreError, MAX_LOOK_WAIT_S, Supervisor, effective_bounds};
use printobserver_types::serde::Deserialize;
use printobserver_types::serde_json::Value;
use printobserver_types::{EventBody, EventId, EventKind, FileName, ImageId, PrintId, Timestamp};
use crate::operations::{Effect, Method, OPERATIONS, Operation, VERSION_PREFIX};
use crate::server::{CREDENTIAL_ISSUE, OperatorCredential};
use crate::turns::{TurnBinding, TurnCredentials};
use crate::wire::{
ActionAnswer, ActionBody, BedClearAnswer, BedClearBody, ContextAnswer, ErrorAnswer,
HistoryAnswer, ImageAnswer, ManifestAnswer, ManifestBody, PreflightAnswer, PrintsAnswer,
RecoveryAnswer, SpoolAnswer, SpoolCommandAnswer, SpoolsAnswer, StatusAnswer, TimelineAnswer,
claimed_actor, reason_of, recovery_of, spool_command_of,
};
#[derive(Clone)]
pub struct ApiState {
pub supervisor: Arc<Supervisor>,
pub prints: Arc<dyn PrintStore>,
pub events: Arc<dyn EventStore>,
pub images: Arc<dyn ImageStore>,
pub sessions: Arc<dyn SessionStore>,
pub operator: Arc<OperatorCredential>,
pub turns: TurnCredentials,
pub stored: crate::events::Stored,
pub check_images: Option<Arc<crate::check_images::PanelImages>>,
pub harness: Arc<crate::readiness::HarnessCheck>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Caller {
Operator,
Turn(TurnBinding),
}
impl Caller {
fn named(&self) -> String {
match self {
Self::Operator => "the operator".to_owned(),
Self::Turn(binding) => format!(
"the agent in session `{}` on print {}",
binding.session_name(),
binding.print_id()
),
}
}
}
fn claimed(actor: &Actor) -> String {
match actor {
Actor::Operator => "the operator".to_owned(),
Actor::System => "the system".to_owned(),
Actor::Agent { session_name } => format!("the agent in session `{session_name}`"),
}
}
fn claim_refused(caller: &Caller, actor: &Actor) -> Option<Response> {
let held = match (caller, actor) {
(Caller::Operator, Actor::Operator) => true,
(Caller::Turn(binding), Actor::Agent { session_name }) => {
*session_name == binding.session_name()
}
_ => false,
};
if held {
return None;
}
let why = if matches!(actor, Actor::System) {
"no credential may claim the system, whose actions are the server's own"
} else {
"a request acts as the identity its credential authenticated, and no other"
};
Some(refusal(
StatusCode::FORBIDDEN,
format!(
"this request authenticated as {} and claims to be {}: {why}",
caller.named(),
claimed(actor)
),
))
}
pub(crate) fn scope_refused(caller: &Caller, print_id: PrintId) -> Option<Response> {
match caller {
Caller::Turn(binding) if binding.print_id() != print_id => Some(refusal(
StatusCode::FORBIDDEN,
format!(
"this request authenticated as {} and names print {print_id}: a supervision \
turn's credential reaches its own print alone",
caller.named()
),
)),
_ => None,
}
}
fn printless_refused(caller: &Caller, what: &str) -> Option<Response> {
match caller {
Caller::Turn(_) => Some(refusal(
StatusCode::FORBIDDEN,
format!(
"this request authenticated as {} and asks for {what}: a supervision turn's \
credential reaches its own print alone",
caller.named()
),
)),
Caller::Operator => None,
}
}
fn operator_refused(caller: &Caller, command: &str) -> Option<Response> {
match caller {
Caller::Turn(_) => Some(refusal(
StatusCode::FORBIDDEN,
format!(
"this request authenticated as {} and asks for `{command}`, which is the \
operator's alone: a supervision turn's credential does not reach it",
caller.named()
),
)),
Caller::Operator => None,
}
}
fn unlooked_refused(
turns: &TurnCredentials,
caller: &Caller,
print_id: PrintId,
) -> Option<Response> {
match caller {
Caller::Turn(binding) if !turns.has_looked(binding) => Some(refusal(
StatusCode::FORBIDDEN,
format!(
"this request authenticated as {} and acknowledges an event before the turn \
has taken a look: run `printobserver look --print-id {print_id}`, open the \
frames it names, and acknowledge what they show",
caller.named()
),
)),
_ => None,
}
}
#[derive(Clone)]
pub struct Admission {
operator: Arc<OperatorCredential>,
turns: TurnCredentials,
}
impl Admission {
fn caller(&self, presented: &[u8]) -> Option<Caller> {
if let Some(binding) = self.turns.admit(presented) {
return Some(Caller::Turn(binding));
}
self.operator.admits(presented).then_some(Caller::Operator)
}
}
impl core::fmt::Debug for ApiState {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.debug_struct("ApiState").finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
pub struct HistoryParams {
#[serde(default)]
pub limit: Option<u32>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
pub struct ContextParams {
#[serde(default)]
pub since: Option<printobserver_types::EventId>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
pub struct LookParams {
#[serde(default)]
pub wait_s: Option<u32>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
pub struct SpoolsParams {
#[serde(default)]
pub include_retired: Option<bool>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
pub struct PreflightParams {
#[serde(default)]
pub file_name: Option<String>,
#[serde(default)]
pub sheet: Option<String>,
}
pub const SPOOL_RECENT_EVENTS: u32 = 20;
pub fn router(state: ApiState) -> Router {
let mut api = Router::new();
for operation in OPERATIONS {
api = api.route(operation.path, route_for(&operation));
}
let api = api
.fallback(nothing_here)
.layer(from_fn_with_state(
Admission {
operator: Arc::clone(&state.operator),
turns: state.turns.clone(),
},
authenticate,
))
.layer(DefaultBodyLimit::max(BODY_BOUND))
.with_state(state);
Router::new().nest(VERSION_PREFIX, api)
}
const BEARER: &[u8] = b"Bearer ";
pub const BODY_BOUND: usize = 2 * 1024 * 1024;
pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
pub async fn authenticate(
State(admission): State<Admission>,
mut request: Request,
next: Next,
) -> Response {
let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
let admitted = match (presented.next(), presented.next()) {
(Some(only), None) => only
.as_bytes()
.strip_prefix(BEARER)
.and_then(|offered| admission.caller(offered)),
_ => None,
};
if let Some(caller) = admitted {
request.extensions_mut().insert(caller);
return next.run(request).await;
}
{
let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
format!(
"this server's API requires a credential, presented as `Authorization: Bearer \
<credential>`, and this server has no operator credential yet: run \
`{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
prints into the server's configuration, and restart the service"
)
} else {
format!(
"this server's API requires the credential it is configured with, presented as \
`Authorization: Bearer <credential>`. An operator without one runs \
`{CREDENTIAL_ISSUE}`"
)
};
let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
refused.headers_mut().insert(
header::WWW_AUTHENTICATE,
header::HeaderValue::from_static("Bearer"),
);
let _ = tokio::time::timeout(
DRAIN_BOUND,
axum::body::to_bytes(request.into_body(), BODY_BOUND),
)
.await;
refused
}
}
async fn nothing_here() -> Response {
refusal(
StatusCode::NOT_FOUND,
"no operation of this server is served at that path",
)
}
fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
if let Effect::Command(spool_command) = operation.effect {
let kind = spool_command.action_kind();
if operation.path.contains("{spool_id}") {
return post(
move |state: State<ApiState>,
caller: Extension<Caller>,
Path(spool_id): Path<SpoolId>,
body: Result<Json<Value>, JsonRejection>| async move {
command(kind, state, caller, Some(spool_id), body).await
},
);
}
return post(
move |state: State<ApiState>,
caller: Extension<Caller>,
body: Result<Json<Value>, JsonRejection>| async move {
command(kind, state, caller, None, body).await
},
);
}
if let Effect::Recovery(kind) = operation.effect {
return post(
move |state: State<ApiState>,
caller: Extension<Caller>,
body: Result<Json<Value>, JsonRejection>| async move {
recover(kind, state, caller, body).await
},
);
}
if let Effect::Mutating(kind) = operation.effect {
return post(
move |state: State<ApiState>,
caller: Extension<Caller>,
print_id: PrintPath,
body: Result<Json<ActionBody>, JsonRejection>| async move {
act(kind, state, caller, print_id, body).await
},
);
}
match (operation.name, operation.method) {
("prints", Method::Get) => get(list_and_adopt_prints),
("status", Method::Get) => get(status),
("context", Method::Get) => get(context),
("image", Method::Get) => get(image),
("history", Method::Get) => get(history),
("events", Method::Get) => get(crate::events::events),
("look", Method::Get) => get(look),
(crate::operations::PRINTER_LOOK, Method::Get) => get(printer_look),
("manifest_get", Method::Get) => get(manifest_get),
("manifest_set", Method::Put) => put(manifest_set),
("spools", Method::Get) => get(spools),
("spool", Method::Get) => get(spool),
("printer_history", Method::Get) => get(printer_history),
("preflight", Method::Get) => get(preflight),
(crate::operations::RECOVERY_STATUS, Method::Get) => get(recover_status),
(crate::operations::BED_CLEAR, Method::Post) => post(bed_clear),
(crate::operations::RECHECK_CAMERA, Method::Post) => post(recheck_camera),
(crate::operations::CHECK_CAMERA, Method::Get) => get(check_camera),
(crate::operations::CHECK_HARNESS, Method::Get) => get(check_harness),
(name, method) => panic!(
"the operation `{name}` is declared as {method} and this router serves no such route"
),
}
}
async fn check_harness(State(state): State<ApiState>, caller: Extension<Caller>) -> Response {
if let Some(refused) = printless_refused(&caller, "a check of the supervising harness") {
return refused;
}
let check = Arc::clone(&state.harness);
match tokio::task::spawn_blocking(move || check.run()).await {
Ok(readiness) => answer(StatusCode::OK, &readiness),
Err(error) => refusal(
StatusCode::INTERNAL_SERVER_ERROR,
format!("the harness check did not finish: {error}"),
),
}
}
pub(crate) fn answer<T: printobserver_types::serde::Serialize>(
status: StatusCode,
body: &T,
) -> Response {
let rendered = match printobserver_types::serde_json::to_vec(body) {
Ok(bytes) => bytes,
Err(error) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
[(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
format!("{{\"error\":\"{error}\"}}"),
)
.into_response();
}
};
(
status,
[(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
rendered,
)
.into_response()
}
pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
answer(status, &ErrorAnswer::saying(detail))
}
pub(crate) const PRINT_ID_REFUSED: &str = "a print is named by its id, a UUID, as `printobserver prints` \
lists it; a start with no print open may name none, and is made under one minted for it";
pub(crate) struct PrintPath(pub(crate) PrintId);
impl<S: Send + Sync> axum::extract::FromRequestParts<S> for PrintPath {
type Rejection = Response;
async fn from_request_parts(
parts: &mut axum::http::request::Parts,
state: &S,
) -> Result<Self, Self::Rejection> {
match Path::<PrintId>::from_request_parts(parts, state).await {
Ok(Path(print_id)) => Ok(Self(print_id)),
Err(rejected) => Err(refusal(
StatusCode::BAD_REQUEST,
format!("{}: {PRINT_ID_REFUSED}", rejected.body_text()),
)),
}
}
}
pub(crate) fn store_status(error: &StoreError) -> StatusCode {
match error {
StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
StatusCode::BAD_REQUEST
}
StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn core_status(error: &CoreError) -> StatusCode {
match error {
CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
CoreError::Store(store) => store_status(store),
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
}
async fn act(
kind: ActionKind,
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
PrintPath(print_id): PrintPath,
body: Result<Json<ActionBody>, JsonRejection>,
) -> Response {
if kind == ActionKind::StartPrint
&& let Some(refused) =
operator_refused(&caller, &crate::operations::command_for("start_print"))
{
return refused;
}
if let Some(refused) = scope_refused(&caller, print_id) {
return refused;
}
let body = match body {
Ok(Json(body)) => body,
Err(rejected) => return rejected.into_response(),
};
if let Some(refused) = claim_refused(&caller, &body.actor) {
return refused;
}
if kind == ActionKind::AcknowledgeFailure
&& let Some(refused) = unlooked_refused(&state.turns, &caller, print_id)
{
return refused;
}
let action = match body.into_action(kind) {
Ok(action) => action,
Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
};
let outcome = match state.supervisor.request_action(print_id, action).await {
Ok(outcome) => outcome,
Err(error) => return refusal(core_status(&error), error),
};
let printer_refusal = match &outcome.record.outcome {
Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
_ => None,
};
let status = match outcome.record.decision {
PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
};
answer(
status,
&ActionAnswer {
record: outcome.record,
intervention: outcome.intervention,
printer_refusal,
},
)
}
async fn command(
kind: ActionKind,
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
spool_id: Option<SpoolId>,
body: Result<Json<Value>, JsonRejection>,
) -> Response {
let body = match body {
Ok(Json(body)) => body,
Err(rejected) => return rejected.into_response(),
};
let Some(fields) = body.as_object() else {
return refusal(
StatusCode::BAD_REQUEST,
"a spool command's body is a document of its fields",
);
};
let actor = match claimed_actor(fields) {
Ok(actor) => actor,
Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
};
if let Some(refused) = claim_refused(&caller, &actor) {
return refused;
}
let asked = match spool_command_of(kind, spool_id, body) {
Ok(asked) => asked,
Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
};
let outcome = match state.supervisor.request_spool_command(asked).await {
Ok(outcome) => outcome,
Err(error) => return refusal(core_status(&error), error),
};
let status = match outcome.decision {
PolicyDecision::Accepted => StatusCode::OK,
PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
};
answer(
status,
&SpoolCommandAnswer {
decision: outcome.decision,
spool: outcome.spool,
events: outcome.events,
},
)
}
async fn recover(
kind: RecoveryActionKind,
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
body: Result<Json<Value>, JsonRejection>,
) -> Response {
let body = match body {
Ok(Json(body)) => body,
Err(rejected) => return rejected.into_response(),
};
if let Some(fields) = body.as_object() {
let actor = match claimed_actor(fields) {
Ok(actor) => actor,
Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
};
if let Some(refused) = claim_refused(&caller, &actor) {
return refused;
}
}
let (action, actor, reason) = match recovery_of(kind, body) {
Ok(asked) => asked,
Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
};
let issued = match state
.supervisor
.request_recovery(action.clone(), actor, reason)
.await
{
Ok(issued) => issued,
Err(error) => return refusal(core_status(&error), error),
};
let config = state.supervisor.config().recovery;
let status = match &issued.decision {
RecoveryDecision::Executed(ExecutionOutcome::Succeeded) => StatusCode::OK,
RecoveryDecision::Executed(ExecutionOutcome::Failed { .. }) => StatusCode::BAD_GATEWAY,
RecoveryDecision::Rejected(_) => StatusCode::CONFLICT,
};
answer(
status,
&RecoveryAnswer {
detail: recovery_detail(&action, &issued.decision, config.as_ref()),
action,
decision: issued.decision,
events: vec![issued.requested, issued.settled],
},
)
}
pub const BED_CLEAR_DETAIL: &str = "recorded: until the next print starts, a Z home is decided \
as though it asserted the bed clear, and a heat, a park and an XY home as though they \
asserted the nozzle clear of the part, wherever the operator's word counts";
async fn bed_clear(
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
body: Result<Json<Value>, JsonRejection>,
) -> Response {
let body = match body {
Ok(Json(body)) => body,
Err(rejected) => return rejected.into_response(),
};
let Some(fields) = body.as_object() else {
return refusal(
StatusCode::BAD_REQUEST,
"the body is not a document carrying an `actor` and a `reason`",
);
};
let actor = match claimed_actor(fields) {
Ok(actor) => actor,
Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
};
if let Some(refused) = claim_refused(&caller, &actor) {
return refused;
}
if actor != Actor::Operator {
return refusal(
StatusCode::FORBIDDEN,
format!(
"{} may not say the bed is clear: an assertion is a person's word for what \
they can see, and only the operator's is recorded",
claimed(&actor)
),
);
}
let body: BedClearBody = match printobserver_types::serde_json::from_value(body) {
Ok(body) => body,
Err(error) => {
return refusal(
StatusCode::BAD_REQUEST,
format!("the body is not an `actor` and a `reason`: {error}"),
);
}
};
let reason = match reason_of(body.reason.as_deref()) {
Ok(reason) => reason,
Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
};
match state.supervisor.assert_bed_clear(reason).await {
Ok(event) => answer(
StatusCode::OK,
&BedClearAnswer {
event,
detail: BED_CLEAR_DETAIL.to_owned(),
},
),
Err(error) => refusal(core_status(&error), error),
}
}
async fn recheck_camera(
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
PrintPath(print_id): PrintPath,
body: Result<Json<Value>, JsonRejection>,
) -> Response {
if let Some(refused) = scope_refused(&caller, print_id) {
return refused;
}
let (actor, reason) = match actor_and_reason(&caller, body) {
Ok(asked) => asked,
Err(refused) => return *refused,
};
match state.prints.print(print_id).await {
Ok(Some(_)) => {}
Ok(None) => {
return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
}
Err(error) => return refusal(store_status(&error), error),
}
let Some(images) = state.check_images.clone() else {
return refusal(
StatusCode::SERVICE_UNAVAILABLE,
"nothing judges this server's camera frames",
);
};
if state.supervisor.config().camera_snapshot_url.is_none() {
return refusal(
StatusCode::SERVICE_UNAVAILABLE,
"no camera is configured to judge: set the server's `[camera] snapshot_url`",
);
}
let supervisor = Arc::clone(&state.supervisor);
let fresh = tokio::task::spawn_blocking(move || {
printobserver_core::block_on(supervisor.fresh_view(print_id))
})
.await;
let fresh = match fresh {
Ok(Ok(fresh)) => fresh,
Ok(Err(error)) => return refusal(core_status(&error), error),
Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
};
let Some((url, image)) = fresh.frame.clone() else {
return refusal(
StatusCode::SERVICE_UNAVAILABLE,
"the camera gave no good frame to judge",
);
};
let sha256 = hex_sha256(image.bytes.as_slice());
let captured_at = image
.captured_at
.unwrap_or_else(printobserver_types::Timestamp::now);
let alignment = crate::alignment::AlignmentJudging::of_recheck(fresh.paused);
images.adopt_camera_check(print_id, fresh.camera_check.as_ref());
let judging = Arc::clone(&images);
let plan = fresh.plan.clone();
let bytes = image.bytes.as_slice().to_vec();
let digest = sha256.clone();
let judged = tokio::task::spawn_blocking(move || {
judging.judge_frame(print_id, &bytes, &digest, plan.as_ref(), alignment)
})
.await;
let judged = match judged {
Ok(Some(judged)) => judged,
Ok(None) => crate::alignment::Judged::nothing_to_judge(
images.alignment(print_id),
EventBody::of(&printobserver_core::CameraLookPayload {
waited_s: 0,
delivered: Vec::new(),
frame_captured_at: Some(captured_at),
})
.ok(),
),
Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
};
if let Some(detail) = &judged.unreadable {
return refusal(StatusCode::SERVICE_UNAVAILABLE, detail);
}
eprintln!(
"printobserver: print {print_id}: the camera is judged again for {}: {reason}",
claimed(&actor)
);
let frame_path = match stored_with_frame(&state, print_id, &judged, (url, image)).await {
Ok(path) => path,
Err(refused) => return refused,
};
let shown =
match image_shown(&images, print_id, &frame_path, captured_at, &fresh, &judged).await {
Ok(shown) => shown,
Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
};
answer(
StatusCode::OK,
&crate::wire::RecheckCameraAnswer {
frame_path,
alignment: judged.alignment,
view_correction: judged.correction,
image_kind: shown.kind(),
image_fallback: shown.fallback,
},
)
}
async fn check_camera(
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
query: Result<Query<crate::camera_check::CheckCameraQuery>, QueryRejection>,
) -> Response {
if let Some(refused) = printless_refused(&caller, "a check of the printer's camera") {
return refused;
}
let body = match query {
Ok(Query(query)) => query,
Err(error) => {
return refusal(
StatusCode::BAD_REQUEST,
format!("a camera check names a `sheet` and a `bed_z_mm`: {error}"),
);
}
};
let known = printobserver_panels::SheetOutline::committed_sheets();
let sheet = match printobserver_core::SheetId::try_from(body.sheet.clone()) {
Ok(sheet) if known.contains(&sheet.as_str()) => sheet,
_ => {
return refusal(
StatusCode::BAD_REQUEST,
format!(
"`sheet` is `{}`, and the sheets a camera check knows the outline of are {}",
body.sheet,
known.join(", ")
),
);
}
};
if !(body.bed_z_mm.is_finite() && body.bed_z_mm >= 0.0) {
return refusal(
StatusCode::BAD_REQUEST,
"`bed_z_mm` must be the bed's height in millimetres, read back with M114 while idle: \
a finite number at or above zero",
);
}
if let Err(error) = state.events.newest_stored().await {
return refusal(store_status(&error), error);
}
let Some(images) = state.check_images.clone() else {
return refusal(
StatusCode::SERVICE_UNAVAILABLE,
"nothing judges this server's camera frames",
);
};
let calibration = images.calibration().cloned();
let asked = crate::camera_check::Asked {
id: printobserver_core::CameraCheckId::new(),
checked_at: printobserver_types::Timestamp::now(),
sheet,
bed_z_mm: body.bed_z_mm,
};
let look = match state.supervisor.take_check_look().await {
Ok(look) => look,
Err(error) => return refusal(core_status(&error), error),
};
let check = match checked(&images, asked, look, calibration).await {
Ok(check) => check,
Err(refused) => return *refused,
};
let body = match EventBody::of(&crate::camera_check::CameraCheckedPayload {
camera_check: check.clone(),
}) {
Ok(body) => body,
Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
};
if let Err(error) = state
.events
.append_event(printobserver_core::store::EventDraft {
print_id: None,
source: printobserver_core::operator_source(),
received_at: check.checked_at,
body,
raw: None,
})
.await
{
return refusal(store_status(&error), error);
}
eprintln!(
"printobserver: camera check {} on {} at bed Z {:.2}: {}",
check.id,
check.sheet.as_str(),
check.bed_z_mm,
check.verdict.as_str()
);
answer(StatusCode::OK, &check)
}
async fn checked(
images: &crate::check_images::PanelImages,
asked: crate::camera_check::Asked,
look: printobserver_core::CheckLook,
calibration: Option<printobserver_panels::CameraCalibration>,
) -> Result<crate::camera_check::CameraCheck, Box<Response>> {
use crate::camera_check::UnavailableReason;
Ok(match (look, calibration) {
(printobserver_core::CheckLook::NoCamera, _) => {
return Err(Box::new(refusal(
StatusCode::SERVICE_UNAVAILABLE,
"no camera is configured to check: set the server's `[camera] snapshot_url`",
)));
}
(printobserver_core::CheckLook::NoFrame { detail, .. }, _) => {
asked.camera_unavailable(UnavailableReason::NoFrame, &detail, None)
}
(printobserver_core::CheckLook::Failed { detail, .. }, _) => {
asked.camera_unavailable(UnavailableReason::LookFailed, &detail, None)
}
(printobserver_core::CheckLook::Framed { frame, path, .. }, None) => {
asked.camera_unavailable(UnavailableReason::NoCalibration, "", Some((frame, path)))
}
(
printobserver_core::CheckLook::Framed {
frame,
path,
bytes,
url,
..
},
Some(calibration),
) => {
let sheet = asked.sheet.clone();
let bed_z_mm = asked.bed_z_mm;
let tolerance = calibration.drift_tolerance_px;
let fitted = tokio::task::spawn_blocking(move || {
printobserver_panels::SheetOutline::committed(sheet.as_str()).map(|outline| {
printobserver_panels::fit_sheet(&printobserver_panels::SheetInputs {
frame_jpeg: &bytes,
camera_snapshot_url: &url,
calibration: &calibration,
sheet: outline,
bed_z_mm,
})
})
})
.await;
let Ok(Some(fitted)) = fitted else {
return Err(Box::new(refusal(
StatusCode::INTERNAL_SERVER_ERROR,
"the camera check's fit did not finish",
)));
};
match fitted {
Ok(fit) => {
let drawn = match images.write_camera_check_image(asked.id, &fit.drawn_jpeg) {
Ok(drawn) => drawn,
Err(error) => {
return Err(Box::new(refusal(
StatusCode::INTERNAL_SERVER_ERROR,
error,
)));
}
};
asked.judged(&fit, tolerance, frame, drawn)
}
Err(error @ printobserver_panels::ComposeError::FrameMismatch { .. }) => asked
.camera_unavailable(
UnavailableReason::FrameMismatch,
&error.to_string(),
Some((frame, path)),
),
Err(error) => asked.camera_unavailable(
UnavailableReason::NoFrame,
&error.to_string(),
Some((frame, path)),
),
}
}
})
}
fn actor_and_reason(
caller: &Caller,
body: Result<Json<Value>, JsonRejection>,
) -> Result<(Actor, String), Box<Response>> {
let refused = |status: StatusCode, said: String| Box::new(refusal(status, said));
let body = match body {
Ok(Json(body)) => body,
Err(rejected) => return Err(Box::new(rejected.into_response())),
};
let Some(fields) = body.as_object() else {
return Err(refused(
StatusCode::BAD_REQUEST,
"the body is not a document carrying an `actor` and a `reason`".to_owned(),
));
};
let actor = claimed_actor(fields)
.map_err(|rejected| refused(StatusCode::BAD_REQUEST, rejected.to_string()))?;
if let Some(claim) = claim_refused(caller, &actor) {
return Err(Box::new(claim));
}
let body: BedClearBody =
printobserver_types::serde_json::from_value(body).map_err(|error| {
refused(
StatusCode::BAD_REQUEST,
format!("the body is not an `actor` and a `reason`: {error}"),
)
})?;
let reason = reason_of(body.reason.as_deref())
.map_err(|rejected| refused(StatusCode::BAD_REQUEST, rejected.to_string()))?;
Ok((actor, reason))
}
async fn image_shown(
images: &Arc<crate::check_images::PanelImages>,
print_id: PrintId,
frame_path: &std::path::Path,
captured_at: printobserver_types::Timestamp,
fresh: &printobserver_core::FreshView,
judged: &crate::alignment::Judged,
) -> Result<printobserver_core::ShownImage, String> {
let choosing = Arc::clone(images);
let path = frame_path.to_path_buf();
let plan = fresh.plan.clone();
let paused = fresh.paused;
let judged = judged.clone();
tokio::task::spawn_blocking(move || {
choosing.image_of(
print_id,
&crate::check_images::Shown {
frame: &path,
captured_at,
made_for: printobserver_core::ImageUse::Look,
plan: plan.as_ref(),
paused,
},
Some(&judged),
)
})
.await
.map_err(|error| error.to_string())?
}
async fn stored_with_frame(
state: &ApiState,
print_id: PrintId,
judged: &crate::alignment::Judged,
frame: (String, printobserver_vision_api::FetchedImage),
) -> Result<std::path::PathBuf, Response> {
let mut frame = Some(frame);
let mut stored = None;
for record in judged.records.clone() {
let event = state
.supervisor
.record_with_frame(print_id, record, frame.take())
.await
.map_err(|error| refusal(core_status(&error), error))?;
if stored.is_none() {
stored = event.image;
}
}
let unkept = || {
refusal(
StatusCode::INTERNAL_SERVER_ERROR,
"the fresh frame was not kept",
)
};
let reference = stored.ok_or_else(unkept)?;
match state.images.image(reference.id).await {
Ok(printobserver_core::store::ImageLookup::Found { path, .. }) => Ok(path),
_ => Err(unkept()),
}
}
fn hex_sha256(bytes: &[u8]) -> String {
use sha2::Digest as _;
sha2::Sha256::digest(bytes)
.iter()
.fold(String::with_capacity(64), |mut text, byte| {
use core::fmt::Write as _;
let _ = write!(text, "{byte:02x}");
text
})
}
async fn recover_status(
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
) -> Response {
let class = match caller {
Caller::Operator => ActorClass::Operator,
Caller::Turn(_) => ActorClass::Agent,
};
match state.supervisor.recovery_status(class).await {
Ok(status) => answer(StatusCode::OK, &status),
Err(error) => refusal(core_status(&error), error),
}
}
async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
let listed = match state
.supervisor
.spools(params.include_retired.unwrap_or(false))
.await
{
Ok(listed) => listed,
Err(error) => return refusal(core_status(&error), error),
};
match state.supervisor.pending_charges(None).await {
Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
Err(error) => refusal(core_status(&error), error),
}
}
async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
let found = match state.supervisor.spool(spool_id).await {
Ok(Some(found)) => found,
Ok(None) => {
return refusal(
StatusCode::NOT_FOUND,
format!("there is no spool {spool_id}"),
);
}
Err(error) => return refusal(core_status(&error), error),
};
let query = TimelineQuery {
spool_id: Some(spool_id),
limit: Some(SPOOL_RECENT_EVENTS),
..every_timeline_kind()
};
match state.supervisor.timeline(query).await {
Ok(recent) => answer(
StatusCode::OK,
&SpoolAnswer {
spool: found,
recent,
},
),
Err(error) => refusal(core_status(&error), error),
}
}
const fn every_timeline_kind() -> TimelineQuery {
TimelineQuery {
kinds: Vec::new(),
since: None,
until: None,
spool_id: None,
before: None,
limit: None,
}
}
fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
where
T::Err: core::fmt::Display,
{
text.parse()
.map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
}
fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
let mut query = every_timeline_kind();
let mut seen: Vec<&str> = Vec::new();
for (name, text) in asked {
if name != "kinds" {
if seen.contains(&name.as_str()) {
return Err(format!(
"`{name}` was given more than once, and this read takes one"
));
}
seen.push(name);
}
match name.as_str() {
"kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
"since" => query.since = Some(read_one::<Timestamp>(name, text)?),
"until" => query.until = Some(read_one::<Timestamp>(name, text)?),
"spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
"before" => query.before = Some(read_one::<EventId>(name, text)?),
"limit" => query.limit = Some(read_one::<u32>(name, text)?),
other => return Err(format!("the printer history takes no `{other}`")),
}
}
Ok(query)
}
async fn printer_history(
State(state): State<ApiState>,
Query(asked): Query<Vec<(String, String)>>,
) -> Response {
let query = match timeline_query(&asked) {
Ok(query) => query,
Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
};
let limit = match query.resolved_limit() {
Ok(limit) => limit,
Err(error) => return refusal(store_status(&error), error),
};
let events = match state.supervisor.timeline(query.clone()).await {
Ok(events) => events,
Err(error) => return refusal(core_status(&error), error),
};
let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
let next = match events.last() {
Some(last) if full => {
let older = TimelineQuery {
before: Some(last.id),
limit: Some(1),
..query
};
match state.supervisor.timeline(older).await {
Ok(older) if older.is_empty() => None,
Ok(_) => Some(last.id),
Err(error) => return refusal(core_status(&error), error),
}
}
_ => None,
};
answer(StatusCode::OK, &TimelineAnswer { events, next })
}
async fn preflight(
State(state): State<ApiState>,
Query(params): Query<PreflightParams>,
) -> Response {
let Some(named) = params.file_name else {
return refusal(
StatusCode::BAD_REQUEST,
"a filament check needs `file_name`, and this request carries none",
);
};
let file_name = match FileName::new(&named) {
Ok(file_name) => file_name,
Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
};
let sheet = match params.sheet.map(SheetId::try_from).transpose() {
Ok(sheet) => sheet,
Err(why) => return refusal(StatusCode::BAD_REQUEST, why),
};
match state.supervisor.preflight(&file_name, sheet.as_ref()).await {
Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
Err(error) => refusal(core_status(&error), error),
}
}
async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
match state.supervisor.list_and_adopt_prints().await {
Ok(listing) => answer(
StatusCode::OK,
&PrintsAnswer {
prints: listing.prints,
active: listing.active,
},
),
Err(error) => refusal(core_status(&error), error),
}
}
async fn status(
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
PrintPath(print_id): PrintPath,
) -> Response {
if let Some(refused) = scope_refused(&caller, print_id) {
return refused;
}
match state.prints.print(print_id).await {
Ok(Some(_)) => {}
Ok(None) => {
return refusal(
StatusCode::NOT_FOUND,
format!("there is no print {print_id}"),
);
}
Err(error) => return refusal(store_status(&error), error),
}
let context = match context_of(&state, print_id).await {
Ok(context) => context,
Err(refused) => return refused,
};
let session = match state.sessions.session(print_id).await {
Ok(session) => session,
Err(error) => return refusal(store_status(&error), error),
};
let planned_changes = if context.slicer.is_some() {
match state
.supervisor
.planned_changes(&context.print, context.job.as_ref())
.await
{
Ok(planned) => planned,
Err(error) => return refusal(core_status(&error), error),
}
} else {
None
};
answer(
StatusCode::OK,
&StatusAnswer {
print: context.print,
printer: context.printer,
job: context.job,
session,
interventions: context.interventions,
detector: context.detector,
planned_changes,
last_check_image: state
.check_images
.as_ref()
.and_then(|images| images.last_check_image(print_id)),
},
)
}
async fn context_of(
state: &ApiState,
print_id: PrintId,
) -> Result<printobserver_core::PrintContext, Response> {
let supervisor = Arc::clone(&state.supervisor);
let read = tokio::task::spawn_blocking(move || {
printobserver_core::block_on(supervisor.context(print_id))
})
.await;
match read {
Ok(Ok(context)) => Ok(context),
Ok(Err(error)) => Err(refusal(core_status(&error), error)),
Err(error) => Err(refusal(StatusCode::INTERNAL_SERVER_ERROR, error)),
}
}
async fn context(
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
PrintPath(print_id): PrintPath,
Query(params): Query<ContextParams>,
) -> Response {
if let Some(refused) = scope_refused(&caller, print_id) {
return refused;
}
let supervisor = Arc::clone(&state.supervisor);
let since = params.since;
let read = tokio::task::spawn_blocking(move || {
printobserver_core::block_on(supervisor.agent_context(print_id, since))
})
.await;
let context = match read {
Ok(Ok(read)) => read,
Ok(Err(error)) => return refusal(core_status(&error), error),
Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
};
let mut image_path = None;
if let Some(latest) = context.latest_image.as_ref() {
match state.images.image(latest.id).await {
Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
Err(error) => return refusal(store_status(&error), error),
}
}
answer(
StatusCode::OK,
&ContextAnswer {
context,
image_path,
},
)
}
async fn look(
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
PrintPath(print_id): PrintPath,
Query(params): Query<LookParams>,
) -> Response {
if let Some(refused) = scope_refused(&caller, print_id) {
return refused;
}
let wait_s = params.wait_s.unwrap_or(0);
if wait_s > MAX_LOOK_WAIT_S {
return refusal(
StatusCode::BAD_REQUEST,
format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
);
}
match state.prints.print(print_id).await {
Ok(Some(_)) => {}
Ok(None) => {
return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
}
Err(error) => return refusal(store_status(&error), error),
}
if let Caller::Turn(binding) = &caller {
state.turns.note_look(binding);
}
let supervisor = Arc::clone(&state.supervisor);
let taken = tokio::task::spawn_blocking(move || {
let (arrived, waited) =
supervisor.await_look_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
printobserver_core::block_on(supervisor.take_look(print_id, waited, arrived))
})
.await;
match taken {
Ok(Ok(look)) => answer(StatusCode::OK, &look),
Ok(Err(error)) => refusal(core_status(&error), error),
Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
}
}
async fn printer_look(
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
Query(params): Query<LookParams>,
) -> Response {
if let Some(refused) = printless_refused(&caller, "a look at the printer with no print named") {
return refused;
}
let wait_s = params.wait_s.unwrap_or(0);
if wait_s > MAX_LOOK_WAIT_S {
return refusal(
StatusCode::BAD_REQUEST,
format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
);
}
let waited = Duration::from_secs(u64::from(wait_s));
tokio::time::sleep(waited).await;
match state.supervisor.take_printer_look(waited).await {
Ok(look) => answer(StatusCode::OK, &look),
Err(error) => refusal(core_status(&error), error),
}
}
async fn image(
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
Path(image_id): Path<ImageId>,
) -> Response {
match state.images.image(image_id).await {
Ok(lookup) => {
let belongs_to = match &lookup {
printobserver_core::ImageLookup::Found { record, .. }
| printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
};
let refused = match belongs_to {
Some(print_id) => scope_refused(&caller, print_id),
None => {
printless_refused(&caller, "a frame of the printer that belongs to no print")
}
};
if let Some(refused) = refused {
return refused;
}
answer(StatusCode::OK, &ImageAnswer::from(lookup))
}
Err(error) => refusal(store_status(&error), error),
}
}
async fn history(
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
PrintPath(print_id): PrintPath,
Query(params): Query<HistoryParams>,
) -> Response {
if let Some(refused) = scope_refused(&caller, print_id) {
return refused;
}
let query = HistoryQuery {
print_id,
kinds: Vec::new(),
since: None,
until: None,
limit: params.limit,
};
match state.events.history(query).await {
Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
Err(error) => refusal(store_status(&error), error),
}
}
async fn manifest_get(
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
PrintPath(print_id): PrintPath,
) -> Response {
if let Some(refused) = scope_refused(&caller, print_id) {
return refused;
}
let manifest = match state.prints.manifest(print_id).await {
Ok(manifest) => manifest,
Err(error) => return refusal(store_status(&error), error),
};
let narrowings = match state.prints.print(print_id).await {
Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
Err(error) => return refusal(store_status(&error), error),
};
answer(
StatusCode::OK,
&ManifestAnswer {
manifest,
narrowings,
},
)
}
async fn manifest_set(
State(state): State<ApiState>,
Extension(caller): Extension<Caller>,
PrintPath(print_id): PrintPath,
body: Result<Json<ManifestBody>, JsonRejection>,
) -> Response {
if let Some(refused) =
operator_refused(&caller, &crate::operations::command_for("manifest_set"))
{
return refused;
}
let body = match body {
Ok(Json(body)) => body,
Err(rejected) => return rejected.into_response(),
};
if let Err(rejected) = body.reason() {
return refusal(StatusCode::BAD_REQUEST, rejected);
}
let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
if let Err(error) = state
.prints
.put_manifest(print_id, body.manifest.clone())
.await
{
return refusal(store_status(&error), error);
}
for narrowing in narrowed.narrowings.clone() {
if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
return refusal(store_status(&error), error);
}
}
answer(
StatusCode::OK,
&ManifestAnswer {
manifest: Some(body.manifest),
narrowings: narrowed.narrowings,
},
)
}
#[cfg(test)]
mod tests {
use axum::http::StatusCode;
use printobserver_core::CoreError;
use printobserver_core::store::StoreError;
use super::{core_status, store_status};
#[test]
fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
for (error, expected) in [
(
StoreError::NotFound {
what: "print".to_owned(),
},
StatusCode::NOT_FOUND,
),
(
StoreError::LimitRefused {
limit: 1_000,
asked_for: 2_000,
},
StatusCode::BAD_REQUEST,
),
(
StoreError::ConstraintRefused {
constraint: "actions.decision".to_owned(),
},
StatusCode::BAD_REQUEST,
),
(
StoreError::Database {
detail: "the disk is full".to_owned(),
},
StatusCode::INTERNAL_SERVER_ERROR,
),
(
StoreError::Io {
detail: "the disk is full".to_owned(),
},
StatusCode::INTERNAL_SERVER_ERROR,
),
] {
assert_eq!(store_status(&error), expected, "{error}");
}
}
#[test]
fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
assert_eq!(
core_status(&CoreError::NoSuchPrint {
print_id: printobserver_types::PrintId::new(),
}),
StatusCode::NOT_FOUND
);
assert_eq!(
core_status(&CoreError::Store(StoreError::NotFound {
what: "print".to_owned(),
})),
StatusCode::NOT_FOUND
);
assert_eq!(
core_status(&CoreError::Unrepresentable {
detail: "an instant".to_owned(),
}),
StatusCode::INTERNAL_SERVER_ERROR
);
}
}