use std::ffi::OsStr;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use axum::Router;
use axum::routing::post;
use printobserver_core::store::Stores;
use printobserver_core::{Clock as _, CoreConfig, Supervisor, SystemClock};
use printobserver_obico::{DetectorHealthCheck, ObicoVision, ObicoVisionConfig};
use printobserver_octoprint::OctoPrintPrinter;
use printobserver_oneharness::{
AgentCommand, AssessmentSchema, EnvAssignment, HarnessSignIn, OneharnessSupervisor,
SupervisorConfig,
};
use printobserver_printer_api::{PrinterError, PrinterPort};
use printobserver_store_sqlite::SqliteStore;
use printobserver_supervisor_api::SupervisorPort;
use tokio::net::TcpListener;
use tokio::sync::{oneshot, watch};
use tokio::task::JoinHandle;
use crate::api::{ApiState, router};
use crate::config::{ApiCredential, ConfigError, ConfigField, CredentialVerifier, ServerConfig};
use crate::events::Stored;
use crate::ingress::{IngressState, receive};
use crate::operations::{INGRESS_PATH, OPERATIONS, command_for};
use crate::reconcile::{ReconcileStores, Reconciliation, overdue, reconcile};
use crate::turns::TurnCredentials;
pub const CONTEXT_PROGRAM: &str = "printobserver";
pub const CLIENT_CONFIG_FILE: &str = "client.toml";
pub const API_CREDENTIAL_FILE: &str = "api-credential";
pub const API_CREDENTIAL_VERIFIER_FILE: &str = "api-credential.verifier";
pub const CREDENTIAL_ISSUE: &str = "printobserver credential issue";
pub const CREDENTIAL_VERIFIER: &str = "printobserver credential verifier";
#[cfg(unix)]
const PRIVATE: u32 = 0o600;
#[must_use]
pub fn context_command() -> String {
format!("{CONTEXT_PROGRAM} context --print-id {{print_id}}")
}
#[derive(Debug, Clone)]
pub enum OperatorCredential {
Verifier(CredentialVerifier),
Plaintext(ApiCredential),
Unconfigured,
}
impl OperatorCredential {
#[must_use]
pub fn admits(&self, presented: &[u8]) -> bool {
match self {
Self::Verifier(verifier) => verifier.admits(presented),
Self::Plaintext(credential) => credential.admits(presented),
Self::Unconfigured => false,
}
}
}
#[must_use]
pub fn plaintext_credential_warning() -> String {
format!(
"the server configuration carries `api.credential`, an operator credential in \
plaintext. A supervision turn runs as this service's user and can read that file, \
so it can read that credential until it is replaced. Replace it with \
`api.credential_verifier`: pipe the credential into `{CREDENTIAL_VERIFIER}` to print \
that line, put it in the configuration, delete `api.credential`, and restart the \
service"
)
}
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
let mut file = options.open(path)?;
let written = file.write_all(contents).and_then(|()| file.sync_all());
if written.is_err() {
let _ = std::fs::remove_file(path);
}
written
}
fn remove_if_there(path: &Path) -> std::io::Result<()> {
match std::fs::remove_file(path) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
_ => Ok(()),
}
}
fn take_plaintext_out(state_dir: &Path) -> Result<(), StartError> {
let client_config = state_dir.join(CLIENT_CONFIG_FILE);
remove_if_there(&client_config).map_err(|error| StartError::State {
detail: format!(
"{} could not be removed, and it may carry the operator's credential where a \
supervision turn can read it: {error}",
client_config.display()
),
})?;
let legacy = state_dir.join(API_CREDENTIAL_FILE);
let refusing = |detail: String| StartError::Credential {
path: legacy.clone(),
detail,
};
let held = match std::fs::read(&legacy) {
Ok(held) => held,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(refusing(format!("it cannot be read: {error}"))),
};
let verifier_file = state_dir.join(API_CREDENTIAL_VERIFIER_FILE);
if !verifier_file.exists() {
let text = core::str::from_utf8(&held).ok().map(without_terminator);
let credential = text
.ok_or("it is not text")
.and_then(ApiCredential::new)
.map_err(|why| {
refusing(format!(
"{why}. This server converts the credential an earlier version generated \
there into its verifier: correct the file, or remove it and run \
`{CREDENTIAL_ISSUE} --replace`"
))
})?;
write_private(
&verifier_file,
format!("{}\n", credential.verifier()).as_bytes(),
)
.map_err(|error| {
refusing(format!(
"its verifier could not be written to {}: {error}",
verifier_file.display()
))
})?;
}
std::fs::remove_file(&legacy)
.map_err(|error| refusing(format!("it could not be removed: {error}")))
}
pub fn operator_credential(
config: &ServerConfig,
) -> Result<(OperatorCredential, Vec<String>), StartError> {
take_plaintext_out(&config.state_dir)?;
let mut warnings = Vec::new();
if config.api_credential.is_some() {
warnings.push(plaintext_credential_warning());
}
if let Some(verifier) = &config.api_credential_verifier {
return Ok((OperatorCredential::Verifier(verifier.clone()), warnings));
}
if let Some(plaintext) = &config.api_credential {
return Ok((OperatorCredential::Plaintext(plaintext.clone()), warnings));
}
let path = config.state_dir.join(API_CREDENTIAL_VERIFIER_FILE);
let held = match std::fs::read_to_string(&path) {
Ok(held) => held,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok((OperatorCredential::Unconfigured, warnings));
}
Err(error) => {
return Err(StartError::Credential {
path,
detail: format!("it cannot be read: {error}"),
});
}
};
let verifier =
CredentialVerifier::parse(held.trim()).map_err(|why| StartError::Credential {
path: path.clone(),
detail: format!(
"{why}. Correct the file, or remove it and set `api.credential_verifier`"
),
})?;
Ok((OperatorCredential::Verifier(verifier), warnings))
}
fn without_terminator(text: &str) -> &str {
text.strip_suffix("\r\n")
.or_else(|| text.strip_suffix('\n'))
.unwrap_or(text)
}
pub const PROMPT_FILE: &str = "turn-prompt.md";
pub const SCHEMA_FILE: &str = "assessment-schema.json";
pub const TURN_PROMPT: &str = printobserver_oneharness::DEFAULT_TURN_PROMPT;
pub struct Ports {
pub printer: Arc<dyn PrinterPort>,
pub stores: Stores,
pub vision: Arc<ObicoVision>,
pub agent: Arc<dyn SupervisorPort>,
}
impl core::fmt::Debug for Ports {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.debug_struct("Ports").finish_non_exhaustive()
}
}
#[derive(Debug)]
pub enum StartError {
Configuration(ConfigError),
State {
detail: String,
},
Credential {
path: PathBuf,
detail: String,
},
Listen {
address: SocketAddr,
detail: String,
},
Store {
detail: String,
},
Supervisor {
detail: String,
},
Reconciliation {
detail: String,
},
}
impl StartError {
#[must_use]
pub const fn field(&self) -> Option<ConfigField> {
match self {
Self::Configuration(error) => error.field(),
_ => None,
}
}
}
impl core::fmt::Display for StartError {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Configuration(error) => write!(formatter, "{error}"),
Self::State { detail } => {
write!(
formatter,
"the state directory could not be prepared: {detail}"
)
}
Self::Credential { path, detail } => write!(
formatter,
"the credential file {} cannot be used: {detail}",
path.display()
),
Self::Listen { address, detail } => {
write!(formatter, "{address} could not be listened on: {detail}")
}
Self::Store { detail } => write!(formatter, "the store could not be opened: {detail}"),
Self::Supervisor { detail } => write!(
formatter,
"the supervising agent's harness could not be reached: {detail}"
),
Self::Reconciliation { detail } => write!(
formatter,
"what the store held could not be reconciled: {detail}"
),
}
}
}
impl core::error::Error for StartError {}
impl From<ConfigError> for StartError {
fn from(error: ConfigError) -> Self {
Self::Configuration(error)
}
}
#[derive(Debug)]
pub struct Server;
impl Server {
pub async fn start(config_path: impl AsRef<Path>) -> Result<Running, StartError> {
let config = ServerConfig::load(config_path)?;
let store = SqliteStore::open(&config.state_dir).map_err(|error| StartError::Store {
detail: error.to_string(),
})?;
let migrated: Vec<String> = store.migrated().iter().map(ToString::to_string).collect();
let stores = Stores::of(Arc::new(store));
let printer = Arc::new(OctoPrintPrinter::new(config.octoprint.clone()));
probe(printer.as_ref()).await?;
let vision = Arc::new(
ObicoVision::new(ObicoVisionConfig {
blank_frame_max_stddev: config.blank_frame_max_stddev,
..ObicoVisionConfig::default()
})
.map_err(|error| StartError::State {
detail: error.to_string(),
})?
.with_api(config.obico_api.clone()),
);
let agent = Arc::new(agent_for(&config)?);
let mut running = Self::start_with(
config,
Ports {
printer,
stores,
vision,
agent,
},
)
.await?;
running.warnings.extend(migrated);
Ok(running)
}
pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
let (operator, warnings) = operator_credential(&config)?;
let listener =
TcpListener::bind(config.listen)
.await
.map_err(|error| StartError::Listen {
address: config.listen,
detail: error.to_string(),
})?;
let address = listener.local_addr().map_err(|error| StartError::Listen {
address: config.listen,
detail: error.to_string(),
})?;
let clock = Arc::new(SystemClock);
let due = overdue(&ports.stores.actions, clock.now())
.await
.map_err(|error| StartError::Reconciliation {
detail: error.to_string(),
})?;
let supervisor = Supervisor::new(
core_config_of(&config),
Arc::clone(&ports.printer),
ports.stores.clone(),
Arc::clone(&ports.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
Arc::clone(&ports.agent),
clock,
);
let turns = TurnCredentials::new(Some(address));
supervisor.install_turn_authority(Arc::new(turns.clone()));
let reconciliation = reconcile(
&supervisor,
&ReconcileStores {
prints: Arc::clone(&ports.stores.prints),
sessions: Arc::clone(&ports.stores.sessions),
events: Arc::clone(&ports.stores.events),
},
due,
)
.await
.map_err(|error| StartError::Reconciliation {
detail: error.to_string(),
})?;
let ingress = IngressState::start(
Arc::clone(&supervisor),
Arc::clone(&ports.stores.events),
Arc::clone(&ports.vision),
config.ingress_shared_secret.clone(),
config.ingress_answer_bound,
);
let completions = ingress.completions();
let observing = crate::observation::start(&supervisor);
let watching = crate::watch::start(
&supervisor,
Arc::clone(&ports.printer),
detector_check(&config)?,
);
let (stored, signal) = Stored::channel();
ports.stores.events.on_stored(signal);
let application = router(ApiState {
supervisor: Arc::clone(&supervisor),
prints: Arc::clone(&ports.stores.prints),
events: Arc::clone(&ports.stores.events),
images: Arc::clone(&ports.stores.images),
sessions: Arc::clone(&ports.stores.sessions),
operator: Arc::new(operator),
turns,
stored,
})
.merge(
Router::new()
.route(INGRESS_PATH, post(receive))
.with_state(ingress),
);
let (stop, stopped) = oneshot::channel::<()>();
let serving = tokio::spawn(async move {
let _ = axum::serve(listener, application)
.with_graceful_shutdown(async move {
let _ = stopped.await;
})
.await;
});
Ok(Running {
address,
config,
warnings,
supervisor,
stores: ports.stores,
reconciliation,
completions,
stop: Some(stop),
serving,
observing,
watching,
})
}
}
fn core_config_of(config: &ServerConfig) -> CoreConfig {
let mut core_config = CoreConfig::new(config.safety.clone(), context_command());
core_config
.camera_snapshot_url
.clone_from(&config.camera_snapshot_url);
core_config.observation_interval = config.observation_interval;
core_config.printer_poll = config.printer_poll;
core_config.unattended_window = config.unattended_window;
core_config.spools = config.spools;
core_config.recovery = config.recovery;
core_config
.recovery_grants
.clone_from(&config.recovery_grants);
core_config
}
fn detector_check(
config: &ServerConfig,
) -> Result<Option<Arc<dyn printobserver_core::DetectorProbe>>, StartError> {
config
.obico_ml_api_url
.as_ref()
.map(|url| {
DetectorHealthCheck::new(url)
.map(|check| Arc::new(check) as Arc<dyn printobserver_core::DetectorProbe>)
.map_err(|detail| StartError::State { detail })
})
.transpose()
}
async fn probe(printer: &dyn PrinterPort) -> Result<(), StartError> {
match printer.snapshot().await {
Err(PrinterError::Unreachable { detail }) => {
Err(StartError::Configuration(ConfigError::about(
ConfigField::OctoprintUrl,
format!("nothing answers there: {detail}"),
)))
}
Err(PrinterError::Unauthorized { detail }) => {
Err(StartError::Configuration(ConfigError::about(
ConfigField::OctoprintApiKey,
format!("the OctoPrint instance refused it: {detail}"),
)))
}
_ => Ok(()),
}
}
fn materialize(
directory: &Path,
name: &str,
contents: &str,
) -> Result<std::path::PathBuf, StartError> {
let path = directory.join(name);
std::fs::write(&path, contents).map_err(|error| StartError::State {
detail: format!("{} could not be written: {error}", path.display()),
})?;
Ok(path)
}
fn beside_the_skill(skill_path: &Path) -> std::path::PathBuf {
match skill_path.parent() {
Some(directory) if !directory.as_os_str().is_empty() => directory.to_path_buf(),
_ => std::path::PathBuf::from("."),
}
}
fn agent_for(config: &ServerConfig) -> Result<OneharnessSupervisor, StartError> {
OneharnessSupervisor::open(agent_config(config)?).map_err(|error| StartError::Supervisor {
detail: error.to_string(),
})
}
pub fn agent_config(config: &ServerConfig) -> Result<SupervisorConfig, StartError> {
let assets = config.assets_dir();
std::fs::create_dir_all(&assets).map_err(|error| StartError::State {
detail: format!("{} could not be created: {error}", assets.display()),
})?;
let prompt_template_path = match &config.prompt_template_path {
Some(path) => path.clone(),
None => materialize(&assets, PROMPT_FILE, TURN_PROMPT)?,
};
let schema_path =
materialize(
&assets,
SCHEMA_FILE,
&printobserver_types::serde_json::to_string_pretty(&without_dialect(
printobserver_types::contract::schema_of::<
printobserver_supervisor_api::AgentAssessment,
>(),
))
.map_err(|error| StartError::State {
detail: error.to_string(),
})?,
)?;
let assessment_schema =
AssessmentSchema::at(&schema_path).map_err(|error| StartError::Supervisor {
detail: error.to_string(),
})?;
let mut harness_env = match HarnessSignIn::of(&config.harness) {
Some(sign_in) => {
let directory =
sign_in
.prepare(&config.state_dir)
.map_err(|error| StartError::State {
detail: format!(
"{} could not be created: {error}",
sign_in.directory(&config.state_dir).display()
),
})?;
vec![
sign_in
.assignment(&directory)
.map_err(|error| StartError::Supervisor {
detail: error.to_string(),
})?,
]
}
None => Vec::new(),
};
let search_path = std::env::var_os("PATH").unwrap_or_default();
harness_env.extend(path_led_by_this_program(&search_path)?);
Ok(SupervisorConfig {
state_dir: config.state_dir.clone(),
skill_path: config.skill_path.clone(),
prompt_template_path,
assessment_schema,
harness: config.harness.clone(),
model: config.model.clone(),
working_dir: beside_the_skill(&config.skill_path),
turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
harness_bin: HarnessSignIn::of(&config.harness)
.and_then(|harness| harness.program_behind_launcher(&search_path)),
harness_env,
agent_commands: agent_commands()?,
})
}
const DIALECT_KEY: &str = "$schema";
fn without_dialect(
mut schema: printobserver_types::serde_json::Value,
) -> printobserver_types::serde_json::Value {
if let Some(object) = schema.as_object_mut() {
object.remove(DIALECT_KEY);
}
schema
}
fn agent_commands() -> Result<Vec<AgentCommand>, StartError> {
OPERATIONS
.iter()
.filter(|operation| crate::operations::printer_wide_of(operation.name).is_none())
.map(|operation| {
AgentCommand::new(&format!(
"{CONTEXT_PROGRAM} {}",
command_for(operation.name)
))
})
.collect::<Result<_, _>>()
.map_err(|error| StartError::Supervisor {
detail: error.to_string(),
})
}
fn path_led_by_this_program(inherited: &OsStr) -> Result<Option<EnvAssignment>, StartError> {
let Some(directory) = std::env::current_exe()
.ok()
.and_then(|program| program.parent().map(Path::to_path_buf))
else {
return Ok(None);
};
let refused = |detail: String| StartError::Supervisor {
detail: format!(
"a turn's PATH cannot lead with {}: {detail}",
directory.display()
),
};
let joined = std::env::join_paths(
std::iter::once(directory.clone()).chain(std::env::split_paths(inherited)),
)
.map_err(|error| refused(error.to_string()))?;
let joined = joined
.to_str()
.ok_or_else(|| refused("it is not valid Unicode".to_owned()))?;
EnvAssignment::new(&format!("PATH={joined}"))
.map(Some)
.map_err(|error| refused(error.to_string()))
}
pub struct Running {
address: SocketAddr,
config: ServerConfig,
warnings: Vec<String>,
supervisor: Arc<Supervisor>,
stores: Stores,
reconciliation: Reconciliation,
completions: watch::Receiver<u64>,
stop: Option<oneshot::Sender<()>>,
serving: JoinHandle<()>,
observing: JoinHandle<()>,
watching: crate::watch::Watching,
}
impl core::fmt::Debug for Running {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter
.debug_struct("Running")
.field("address", &self.address)
.field("reconciliation", &self.reconciliation)
.finish_non_exhaustive()
}
}
impl Running {
#[must_use]
pub const fn address(&self) -> SocketAddr {
self.address
}
#[must_use]
pub fn base_url(&self) -> String {
format!(
"http://{}{}",
self.address,
crate::operations::VERSION_PREFIX
)
}
#[must_use]
pub fn ingress_url(&self) -> String {
format!("http://{}{INGRESS_PATH}", self.address)
}
#[must_use]
pub const fn config(&self) -> &ServerConfig {
&self.config
}
#[must_use]
pub fn warnings(&self) -> &[String] {
&self.warnings
}
#[must_use]
pub const fn reconciliation(&self) -> &Reconciliation {
&self.reconciliation
}
#[must_use]
pub const fn supervisor(&self) -> &Arc<Supervisor> {
&self.supervisor
}
#[must_use]
pub const fn stores(&self) -> &Stores {
&self.stores
}
#[must_use]
pub fn completions(&self) -> watch::Receiver<u64> {
self.completions.clone()
}
pub async fn stop(mut self) {
if let Some(stop) = self.stop.take() {
let _ = stop.send(());
}
self.observing.abort();
self.watching.abort();
let _ = (&mut self.serving).await;
}
pub async fn serve_until_signalled(self) -> Result<(), StartError> {
stop_requested().await?;
self.stop().await;
Ok(())
}
}
fn unhandled(what: &str, error: &std::io::Error) -> StartError {
StartError::State {
detail: format!("{what} cannot be handled: {error}"),
}
}
#[cfg(unix)]
async fn stop_requested() -> Result<(), StartError> {
use tokio::signal::unix::{SignalKind, signal};
let mut terminate = signal(SignalKind::terminate())
.map_err(|error| unhandled("the termination signal", &error))?;
let mut interrupt = signal(SignalKind::interrupt())
.map_err(|error| unhandled("the interrupt signal", &error))?;
tokio::select! {
_ = terminate.recv() => {}
_ = interrupt.recv() => {}
}
Ok(())
}
#[cfg(windows)]
async fn stop_requested() -> Result<(), StartError> {
use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close, ctrl_shutdown};
let mut interrupt = ctrl_c().map_err(|error| unhandled("the CTRL_C event", &error))?;
let mut breaking = ctrl_break().map_err(|error| unhandled("the CTRL_BREAK event", &error))?;
let mut closing = ctrl_close().map_err(|error| unhandled("the CTRL_CLOSE event", &error))?;
let mut shutting_down =
ctrl_shutdown().map_err(|error| unhandled("the CTRL_SHUTDOWN event", &error))?;
tokio::select! {
_ = interrupt.recv() => {}
_ = breaking.recv() => {}
_ = closing.recv() => {}
_ = shutting_down.recv() => {}
}
Ok(())
}
impl Drop for Running {
fn drop(&mut self) {
if let Some(stop) = self.stop.take() {
let _ = stop.send(());
}
self.serving.abort();
}
}