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::{ObicoVision, ObicoVisionConfig};
use printobserver_octoprint::OctoPrintPrinter;
use printobserver_oneharness::{
AssessmentSchema, 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, ServerConfig};
use crate::ingress::{IngressState, receive};
use crate::operations::INGRESS_PATH;
use crate::reconcile::{ReconcileStores, Reconciliation, overdue, reconcile};
pub const CONTEXT_PROGRAM: &str = "printobserver";
pub const CLIENT_CONFIG_FILE: &str = "client.toml";
pub const API_CREDENTIAL_FILE: &str = "api-credential";
#[cfg(unix)]
const PRIVATE: u32 = 0o600;
#[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,
credential: &ApiCredential,
) -> Result<PathBuf, StartError> {
use std::io::Write as _;
let path = directory.join(CLIENT_CONFIG_FILE);
let failing = |error: std::io::Error| StartError::State {
detail: format!("{} could not be written: {error}", path.display()),
};
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
let mut file = options.open(&path).map_err(failing)?;
#[cfg(unix)]
file.set_permissions(std::os::unix::fs::PermissionsExt::from_mode(PRIVATE))
.map_err(failing)?;
file.write_all(
format!(
"[client]\nserver = \"http://{address}\"\ncredential = \"{}\"\n",
toml_basic_string(credential.written())
)
.as_bytes(),
)
.map_err(failing)?;
Ok(path)
}
fn toml_basic_string(text: &str) -> String {
text.replace('\\', "\\\\").replace('"', "\\\"")
}
fn credential_in_force(config: &ServerConfig) -> Result<ApiCredential, StartError> {
use std::io::Write as _;
if let Some(configured) = &config.api_credential {
return Ok(configured.clone());
}
let path = config.state_dir.join(API_CREDENTIAL_FILE);
let refusing = |detail: String| StartError::Credential {
path: path.clone(),
detail,
};
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
match options.open(&path) {
Ok(mut file) => {
let generated = ApiCredential::generate().map_err(|error| {
refusing(format!(
"no credential could be generated for it, because the operating system's \
random source refused: {error}"
))
});
let written = generated.and_then(|credential| {
file.write_all(credential.written().as_bytes())
.and_then(|()| file.sync_all())
.map(|()| credential)
.map_err(|error| refusing(format!("it could not be written: {error}")))
});
if written.is_err() {
let _ = std::fs::remove_file(&path);
}
written
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
let held = std::fs::read(&path)
.map_err(|error| refusing(format!("it cannot be read: {error}")))?;
let text = core::str::from_utf8(&held).ok().map(without_terminator);
text.ok_or("it is not text")
.and_then(ApiCredential::new)
.map_err(|why| {
refusing(format!(
"{why}. This server does not replace a credential it did not write \
just now: correct the file, or remove it to have a new one generated"
))
})
}
Err(error) => Err(refusing(format!("it cannot be created: {error}"))),
}
}
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 API 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 stores = Stores::of(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,
stores,
vision,
agent,
},
)
.await
}
pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
let credential = credential_in_force(&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 client_config = write_client_config(&config.state_dir, address, &credential)?;
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(
CoreConfig::new(config.safety.clone(), context_command(&client_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 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 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),
credential: Arc::new(credential),
})
.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,
stores: ports.stores,
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 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(
&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 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(),
};
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: None,
harness_env,
})
}
pub struct Running {
address: SocketAddr,
config: ServerConfig,
supervisor: Arc<Supervisor>,
stores: Stores,
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 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(());
}
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();
}
}