1use std::net::SocketAddr;
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17
18use axum::Router;
19use axum::routing::post;
20use printobserver_core::{Clock as _, CoreConfig, Supervisor, SystemClock};
21use printobserver_obico::{ObicoVision, ObicoVisionConfig};
22use printobserver_octoprint::OctoPrintPrinter;
23use printobserver_oneharness::{AssessmentSchema, OneharnessSupervisor, SupervisorConfig};
24use printobserver_printer_api::{PrinterError, PrinterPort};
25use printobserver_store_api::StorePort;
26use printobserver_store_sqlite::SqliteStore;
27use printobserver_supervisor_api::SupervisorPort;
28use tokio::net::TcpListener;
29use tokio::sync::{oneshot, watch};
30use tokio::task::JoinHandle;
31
32use crate::api::{ApiState, router};
33use crate::config::{ConfigError, ConfigField, ServerConfig};
34use crate::ingress::{IngressState, receive};
35use crate::operations::INGRESS_PATH;
36use crate::reconcile::{Reconciliation, overdue, reconcile};
37
38pub const CONTEXT_PROGRAM: &str = "printobserver";
40
41pub const CLIENT_CONFIG_FILE: &str = "client.toml";
44
45#[must_use]
58pub fn context_command(client_config: &Path) -> String {
59 format!(
60 "{CONTEXT_PROGRAM} context --config {} --print-id {{print_id}}",
61 client_config.display()
62 )
63}
64
65fn write_client_config(directory: &Path, address: SocketAddr) -> Result<PathBuf, StartError> {
73 let path = directory.join(CLIENT_CONFIG_FILE);
74 std::fs::write(&path, format!("[client]\nserver = \"http://{address}\"\n")).map_err(
75 |error| StartError::State {
76 detail: format!("{} could not be written: {error}", path.display()),
77 },
78 )?;
79 Ok(path)
80}
81
82pub const SKILL_FILE: &str = "printobserver-skill.md";
84
85pub const PROMPT_FILE: &str = "turn-prompt.md";
87
88pub const SCHEMA_FILE: &str = "assessment-schema.json";
90
91pub const TURN_PROMPT: &str = printobserver_oneharness::DEFAULT_TURN_PROMPT;
97
98pub struct Ports {
103 pub printer: Arc<dyn PrinterPort>,
105 pub store: Arc<dyn StorePort>,
107 pub vision: Arc<ObicoVision>,
109 pub agent: Arc<dyn SupervisorPort>,
111}
112
113impl core::fmt::Debug for Ports {
114 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
115 formatter.debug_struct("Ports").finish_non_exhaustive()
116 }
117}
118
119#[derive(Debug)]
121pub enum StartError {
122 Configuration(ConfigError),
124 State {
126 detail: String,
128 },
129 Listen {
131 address: SocketAddr,
133 detail: String,
135 },
136 Store {
138 detail: String,
140 },
141 Supervisor {
143 detail: String,
145 },
146 Reconciliation {
148 detail: String,
150 },
151}
152
153impl StartError {
154 #[must_use]
156 pub const fn field(&self) -> Option<ConfigField> {
157 match self {
158 Self::Configuration(error) => error.field(),
159 _ => None,
160 }
161 }
162}
163
164impl core::fmt::Display for StartError {
165 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
166 match self {
167 Self::Configuration(error) => write!(formatter, "{error}"),
168 Self::State { detail } => {
169 write!(
170 formatter,
171 "the state directory could not be prepared: {detail}"
172 )
173 }
174 Self::Listen { address, detail } => {
175 write!(formatter, "{address} could not be listened on: {detail}")
176 }
177 Self::Store { detail } => write!(formatter, "the store could not be opened: {detail}"),
178 Self::Supervisor { detail } => write!(
179 formatter,
180 "the supervising agent's harness could not be reached: {detail}"
181 ),
182 Self::Reconciliation { detail } => write!(
183 formatter,
184 "what the store held could not be reconciled: {detail}"
185 ),
186 }
187 }
188}
189
190impl core::error::Error for StartError {}
191
192impl From<ConfigError> for StartError {
193 fn from(error: ConfigError) -> Self {
194 Self::Configuration(error)
195 }
196}
197
198#[derive(Debug)]
200pub struct Server;
201
202impl Server {
203 pub async fn start(config_path: impl AsRef<Path>) -> Result<Running, StartError> {
212 let config = ServerConfig::load(config_path)?;
213 let store =
214 Arc::new(
215 SqliteStore::open(&config.state_dir).map_err(|error| StartError::Store {
216 detail: error.to_string(),
217 })?,
218 );
219 let printer = Arc::new(OctoPrintPrinter::new(config.octoprint.clone()));
220 probe(printer.as_ref()).await?;
221 let vision = Arc::new(
222 ObicoVision::new(ObicoVisionConfig::default()).map_err(|error| StartError::State {
223 detail: error.to_string(),
224 })?,
225 );
226 let agent = Arc::new(agent_for(&config)?);
227 Self::start_with(
228 config,
229 Ports {
230 printer,
231 store,
232 vision,
233 agent,
234 },
235 )
236 .await
237 }
238
239 pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
246 let listener =
250 TcpListener::bind(config.listen)
251 .await
252 .map_err(|error| StartError::Listen {
253 address: config.listen,
254 detail: error.to_string(),
255 })?;
256 let address = listener.local_addr().map_err(|error| StartError::Listen {
257 address: config.listen,
258 detail: error.to_string(),
259 })?;
260 let client_config = write_client_config(&config.state_dir, address)?;
261 let clock = Arc::new(SystemClock);
262 let due = overdue(&ports.store, clock.now()).await.map_err(|error| {
263 StartError::Reconciliation {
264 detail: error.to_string(),
265 }
266 })?;
267 let supervisor = Supervisor::new(
268 CoreConfig::new(config.safety.clone(), context_command(&client_config)),
269 Arc::clone(&ports.printer),
270 Arc::clone(&ports.store),
271 Arc::clone(&ports.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
272 Arc::clone(&ports.agent),
273 clock,
274 );
275 let reconciliation = reconcile(&supervisor, &ports.store, due)
276 .await
277 .map_err(|error| StartError::Reconciliation {
278 detail: error.to_string(),
279 })?;
280
281 let ingress = IngressState::start(
282 Arc::clone(&supervisor),
283 Arc::clone(&ports.store),
284 Arc::clone(&ports.vision),
285 config.ingress_shared_secret.clone(),
286 config.ingress_answer_bound,
287 );
288 let completions = ingress.completions();
289 let application = router(ApiState {
290 supervisor: Arc::clone(&supervisor),
291 store: Arc::clone(&ports.store),
292 })
293 .merge(
294 Router::new()
295 .route(INGRESS_PATH, post(receive))
296 .with_state(ingress),
297 );
298
299 let (stop, stopped) = oneshot::channel::<()>();
300 let serving = tokio::spawn(async move {
301 let _ = axum::serve(listener, application)
302 .with_graceful_shutdown(async move {
303 let _ = stopped.await;
304 })
305 .await;
306 });
307 Ok(Running {
308 address,
309 config,
310 supervisor,
311 store: ports.store,
312 reconciliation,
313 completions,
314 stop: Some(stop),
315 serving,
316 })
317 }
318}
319
320async fn probe(printer: &dyn PrinterPort) -> Result<(), StartError> {
328 match printer.snapshot().await {
329 Err(PrinterError::Unreachable { detail }) => {
330 Err(StartError::Configuration(ConfigError::about(
331 ConfigField::OctoprintUrl,
332 format!("nothing answers there: {detail}"),
333 )))
334 }
335 Err(PrinterError::Unauthorized { detail }) => {
336 Err(StartError::Configuration(ConfigError::about(
337 ConfigField::OctoprintApiKey,
338 format!("the OctoPrint instance refused it: {detail}"),
339 )))
340 }
341 _ => Ok(()),
342 }
343}
344
345fn materialize(
353 directory: &Path,
354 name: &str,
355 contents: &str,
356) -> Result<std::path::PathBuf, StartError> {
357 let path = directory.join(name);
358 std::fs::write(&path, contents).map_err(|error| StartError::State {
359 detail: format!("{} could not be written: {error}", path.display()),
360 })?;
361 Ok(path)
362}
363
364fn materialize_references(assets: &Path) -> Result<(), StartError> {
375 for (relative, contents) in printobserver_oneharness::DEFAULT_REFERENCES {
376 let path = assets.join(relative);
377 if let Some(parent) = path.parent() {
378 std::fs::create_dir_all(parent).map_err(|error| StartError::State {
379 detail: format!("{} could not be created: {error}", parent.display()),
380 })?;
381 }
382 std::fs::write(&path, contents).map_err(|error| StartError::State {
383 detail: format!("{} could not be written: {error}", path.display()),
384 })?;
385 }
386 Ok(())
387}
388
389fn agent_for(config: &ServerConfig) -> Result<OneharnessSupervisor, StartError> {
391 let assets = config.assets_dir();
392 std::fs::create_dir_all(&assets).map_err(|error| StartError::State {
393 detail: format!("{} could not be created: {error}", assets.display()),
394 })?;
395 materialize_references(&assets)?;
396 let skill_path = match &config.skill_path {
397 Some(path) => path.clone(),
398 None => materialize(&assets, SKILL_FILE, printobserver_oneharness::DEFAULT_SKILL)?,
399 };
400 let prompt_template_path = match &config.prompt_template_path {
401 Some(path) => path.clone(),
402 None => materialize(&assets, PROMPT_FILE, TURN_PROMPT)?,
403 };
404 let schema_path = materialize(
405 &assets,
406 SCHEMA_FILE,
407 &printobserver_types::serde_json::to_string_pretty(
408 &printobserver_types::contract::schema_of::<printobserver_types::AgentAssessment>(),
409 )
410 .map_err(|error| StartError::State {
411 detail: error.to_string(),
412 })?,
413 )?;
414 let assessment_schema =
415 AssessmentSchema::at(&schema_path).map_err(|error| StartError::Supervisor {
416 detail: error.to_string(),
417 })?;
418 OneharnessSupervisor::open(SupervisorConfig {
419 state_dir: config.state_dir.clone(),
420 skill_path,
421 prompt_template_path,
422 assessment_schema,
423 harness: config.harness.clone(),
424 model: config.model.clone(),
425 working_dir: assets.clone(),
430 turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
431 harness_bin: None,
432 harness_env: Vec::new(),
433 })
434 .map_err(|error| StartError::Supervisor {
435 detail: error.to_string(),
436 })
437}
438
439pub struct Running {
444 address: SocketAddr,
446 config: ServerConfig,
448 supervisor: Arc<Supervisor>,
450 store: Arc<dyn StorePort>,
452 reconciliation: Reconciliation,
454 completions: watch::Receiver<u64>,
456 stop: Option<oneshot::Sender<()>>,
458 serving: JoinHandle<()>,
460}
461
462impl core::fmt::Debug for Running {
463 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
464 formatter
465 .debug_struct("Running")
466 .field("address", &self.address)
467 .field("reconciliation", &self.reconciliation)
468 .finish_non_exhaustive()
469 }
470}
471
472impl Running {
473 #[must_use]
475 pub const fn address(&self) -> SocketAddr {
476 self.address
477 }
478
479 #[must_use]
481 pub fn base_url(&self) -> String {
482 format!(
483 "http://{}{}",
484 self.address,
485 crate::operations::VERSION_PREFIX
486 )
487 }
488
489 #[must_use]
491 pub fn ingress_url(&self) -> String {
492 format!("http://{}{INGRESS_PATH}", self.address)
493 }
494
495 #[must_use]
497 pub const fn config(&self) -> &ServerConfig {
498 &self.config
499 }
500
501 #[must_use]
503 pub const fn reconciliation(&self) -> &Reconciliation {
504 &self.reconciliation
505 }
506
507 #[must_use]
509 pub const fn supervisor(&self) -> &Arc<Supervisor> {
510 &self.supervisor
511 }
512
513 #[must_use]
515 pub const fn store(&self) -> &Arc<dyn StorePort> {
516 &self.store
517 }
518
519 #[must_use]
522 pub fn completions(&self) -> watch::Receiver<u64> {
523 self.completions.clone()
524 }
525
526 pub async fn stop(mut self) {
528 if let Some(stop) = self.stop.take() {
529 let _ = stop.send(());
530 }
531 let _ = (&mut self.serving).await;
532 }
533
534 pub async fn serve_until_signalled(self) -> Result<(), StartError> {
545 use tokio::signal::unix::{SignalKind, signal};
546
547 let mut terminate = signal(SignalKind::terminate()).map_err(|error| StartError::State {
548 detail: format!("the termination signal cannot be handled: {error}"),
549 })?;
550 let mut interrupt = signal(SignalKind::interrupt()).map_err(|error| StartError::State {
551 detail: format!("the interrupt signal cannot be handled: {error}"),
552 })?;
553 tokio::select! {
554 _ = terminate.recv() => {}
555 _ = interrupt.recv() => {}
556 }
557 self.stop().await;
558 Ok(())
559 }
560}
561
562impl Drop for Running {
563 fn drop(&mut self) {
564 if let Some(stop) = self.stop.take() {
565 let _ = stop.send(());
566 }
567 self.serving.abort();
568 }
569}