use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use axum::Router;
use axum::routing::post;
use printobserver_core::{Clock as _, CoreConfig, Supervisor, SystemClock};
use printobserver_obico::{ObicoVision, ObicoVisionConfig};
use printobserver_octoprint::OctoPrintPrinter;
use printobserver_oneharness::{AssessmentSchema, OneharnessSupervisor, SupervisorConfig};
use printobserver_printer_api::{PrinterError, PrinterPort};
use printobserver_store_api::StorePort;
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::{ConfigError, ConfigField, ServerConfig};
use crate::ingress::{IngressState, receive};
use crate::operations::INGRESS_PATH;
use crate::reconcile::{Reconciliation, overdue, reconcile};
pub const CONTEXT_PROGRAM: &str = "printobserver";
pub const CLIENT_CONFIG_FILE: &str = "client.toml";
#[must_use]
pub fn context_command(client_config: &Path) -> String {
format!(
"{CONTEXT_PROGRAM} context --config {} --print-id {{print_id}}",
client_config.display()
)
}
fn write_client_config(directory: &Path, address: SocketAddr) -> Result<PathBuf, StartError> {
let path = directory.join(CLIENT_CONFIG_FILE);
std::fs::write(&path, format!("[client]\nserver = \"http://{address}\"\n")).map_err(
|error| StartError::State {
detail: format!("{} could not be written: {error}", path.display()),
},
)?;
Ok(path)
}
pub const SKILL_FILE: &str = "printobserver-skill.md";
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 store: Arc<dyn StorePort>,
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,
},
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::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 =
Arc::new(
SqliteStore::open(&config.state_dir).map_err(|error| StartError::Store {
detail: error.to_string(),
})?,
);
let printer = Arc::new(OctoPrintPrinter::new(config.octoprint.clone()));
probe(printer.as_ref()).await?;
let vision = Arc::new(
ObicoVision::new(ObicoVisionConfig::default()).map_err(|error| StartError::State {
detail: error.to_string(),
})?,
);
let agent = Arc::new(agent_for(&config)?);
Self::start_with(
config,
Ports {
printer,
store,
vision,
agent,
},
)
.await
}
pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
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 client_config = write_client_config(&config.state_dir, address)?;
let clock = Arc::new(SystemClock);
let due = overdue(&ports.store, clock.now()).await.map_err(|error| {
StartError::Reconciliation {
detail: error.to_string(),
}
})?;
let supervisor = Supervisor::new(
CoreConfig::new(config.safety.clone(), context_command(&client_config)),
Arc::clone(&ports.printer),
Arc::clone(&ports.store),
Arc::clone(&ports.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
Arc::clone(&ports.agent),
clock,
);
let reconciliation = reconcile(&supervisor, &ports.store, due)
.await
.map_err(|error| StartError::Reconciliation {
detail: error.to_string(),
})?;
let ingress = IngressState::start(
Arc::clone(&supervisor),
Arc::clone(&ports.store),
Arc::clone(&ports.vision),
config.ingress_shared_secret.clone(),
config.ingress_answer_bound,
);
let completions = ingress.completions();
let application = router(ApiState {
supervisor: Arc::clone(&supervisor),
store: Arc::clone(&ports.store),
})
.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,
supervisor,
store: ports.store,
reconciliation,
completions,
stop: Some(stop),
serving,
})
}
}
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 materialize_references(assets: &Path) -> Result<(), StartError> {
for (relative, contents) in printobserver_oneharness::DEFAULT_REFERENCES {
let path = assets.join(relative);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|error| StartError::State {
detail: format!("{} could not be created: {error}", parent.display()),
})?;
}
std::fs::write(&path, contents).map_err(|error| StartError::State {
detail: format!("{} could not be written: {error}", path.display()),
})?;
}
Ok(())
}
fn agent_for(config: &ServerConfig) -> Result<OneharnessSupervisor, 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()),
})?;
materialize_references(&assets)?;
let skill_path = match &config.skill_path {
Some(path) => path.clone(),
None => materialize(&assets, SKILL_FILE, printobserver_oneharness::DEFAULT_SKILL)?,
};
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(
&printobserver_types::contract::schema_of::<printobserver_types::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(),
})?;
OneharnessSupervisor::open(SupervisorConfig {
state_dir: config.state_dir.clone(),
skill_path,
prompt_template_path,
assessment_schema,
harness: config.harness.clone(),
model: config.model.clone(),
working_dir: assets.clone(),
turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
harness_bin: None,
harness_env: Vec::new(),
})
.map_err(|error| StartError::Supervisor {
detail: error.to_string(),
})
}
pub struct Running {
address: SocketAddr,
config: ServerConfig,
supervisor: Arc<Supervisor>,
store: Arc<dyn StorePort>,
reconciliation: Reconciliation,
completions: watch::Receiver<u64>,
stop: Option<oneshot::Sender<()>>,
serving: JoinHandle<()>,
}
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 const fn reconciliation(&self) -> &Reconciliation {
&self.reconciliation
}
#[must_use]
pub const fn supervisor(&self) -> &Arc<Supervisor> {
&self.supervisor
}
#[must_use]
pub const fn store(&self) -> &Arc<dyn StorePort> {
&self.store
}
#[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(());
}
let _ = (&mut self.serving).await;
}
pub async fn serve_until_signalled(self) -> Result<(), StartError> {
use tokio::signal::unix::{SignalKind, signal};
let mut terminate = signal(SignalKind::terminate()).map_err(|error| StartError::State {
detail: format!("the termination signal cannot be handled: {error}"),
})?;
let mut interrupt = signal(SignalKind::interrupt()).map_err(|error| StartError::State {
detail: format!("the interrupt signal cannot be handled: {error}"),
})?;
tokio::select! {
_ = terminate.recv() => {}
_ = interrupt.recv() => {}
}
self.stop().await;
Ok(())
}
}
impl Drop for Running {
fn drop(&mut self) {
if let Some(stop) = self.stop.take() {
let _ = stop.send(());
}
self.serving.abort();
}
}