Skip to main content

printobserver_server/
server.rs

1//! The composition root: the one place an implementation crate is named.
2//!
3//! Everything below this file is written against the four ports. This is where
4//! one implementation is chosen for each — `OctoPrint` behind the printer port,
5//! `Obico` behind the vision port, `OneHarness` behind the supervisor port, and
6//! `SQLite` behind the store port — and `just check-repo` refuses any other
7//! crate that names one.
8//!
9//! [`Server::start`] is that root. [`Server::start_with`] takes ports a caller
10//! composed, which is how the tiers that stand in for a machine drive the real
11//! surface without one; the two share every line after the ports exist, so what
12//! a tier drives is the server this file starts.
13
14use 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
38/// The program a supervision turn runs to read its print's context.
39pub const CONTEXT_PROGRAM: &str = "printobserver";
40
41/// The file this server writes the address it took into, under the state
42/// directory, for the clients that run beside it.
43pub const CLIENT_CONFIG_FILE: &str = "client.toml";
44
45/// The command a supervision turn runs to read its print's context.
46///
47/// This program's own context read, against the print the turn is about and
48/// the configuration file naming the address this server took — which is the
49/// bound address rather than the configured one, because a configuration may
50/// ask for any free port and a turn has to reach the one that was taken.
51/// `printobserver-oneharness` substitutes the print for the placeholder.
52///
53/// The address travels in a file rather than on the command line because no
54/// client command of that program takes one: where a server is and what
55/// authenticates to it are configuration, and a command line that could carry
56/// them is a command line that could be pointed anywhere.
57#[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
65/// Write the configuration the clients beside this server read it by.
66///
67/// One file naming the address that was actually bound, so a supervision turn
68/// — and an operator on this host — reaches this server without being told
69/// where it is. It carries no credential: this server requires none of its API
70/// callers, and a file this program wrote carrying one would be a secret
71/// nobody chose to store.
72fn 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
82/// The file name the agent's skill is materialized under.
83pub const SKILL_FILE: &str = "printobserver-skill.md";
84
85/// The file name the agent's prompt template is materialized under.
86pub const PROMPT_FILE: &str = "turn-prompt.md";
87
88/// The file name the assessment schema is materialized under.
89pub const SCHEMA_FILE: &str = "assessment-schema.json";
90
91/// The prompt template this program carries and materializes.
92///
93/// The adapter's own committed asset rather than a copy of it, so what an
94/// installed program fills a turn with and what `just check-repo` reads are one
95/// file.
96pub const TURN_PROMPT: &str = printobserver_oneharness::DEFAULT_TURN_PROMPT;
97
98/// The four implementations one running server was composed from.
99///
100/// A tier that stands in for a machine hands these in; [`Server::start`] builds
101/// them from the configuration.
102pub struct Ports {
103    /// The printer.
104    pub printer: Arc<dyn PrinterPort>,
105    /// Durable state.
106    pub store: Arc<dyn StorePort>,
107    /// External observations, and the snapshot fetch.
108    pub vision: Arc<ObicoVision>,
109    /// The supervising agent's harness.
110    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/// Why this server did not start.
120#[derive(Debug)]
121pub enum StartError {
122    /// The configuration will not do, naming the field that will not.
123    Configuration(ConfigError),
124    /// The state directory could not be prepared.
125    State {
126        /// What went wrong.
127        detail: String,
128    },
129    /// The address could not be listened on.
130    Listen {
131        /// The address that was asked for.
132        address: SocketAddr,
133        /// What went wrong.
134        detail: String,
135    },
136    /// The store could not be opened.
137    Store {
138        /// What the store said.
139        detail: String,
140    },
141    /// The supervising agent's harness could not be reached at all.
142    Supervisor {
143        /// What the harness said.
144        detail: String,
145    },
146    /// Reconciling what the store held failed.
147    Reconciliation {
148        /// What went wrong.
149        detail: String,
150    },
151}
152
153impl StartError {
154    /// The configuration field this refusal is about, when it is about one.
155    #[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/// The composition root.
199#[derive(Debug)]
200pub struct Server;
201
202impl Server {
203    /// Read one configuration file, compose the four implementations, and serve.
204    ///
205    /// # Errors
206    ///
207    /// Returns [`StartError::Configuration`] naming the field that will not do
208    /// — including the two only the machine can rule on, an `OctoPrint` address
209    /// nothing answers at and a key that instance refuses — and the other
210    /// variants for a host that will not let this server come up.
211    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    /// Serve over ports a caller composed.
240    ///
241    /// # Errors
242    ///
243    /// The same as [`Server::start`], less the refusals that belong to building
244    /// the implementations.
245    pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
246        // The listener is taken first, because the command a supervision turn
247        // runs to read its context names the address this server is answering
248        // on — and a configuration may ask for any free port.
249        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
320/// Ask the machine whether the address and the key are the ones it answers to.
321///
322/// Only the two answers that are *about the configuration* refuse a start. A
323/// printer that is off, in an error state, or answering something this adapter
324/// cannot read is a machine having a bad day rather than a file with the wrong
325/// value in it, and a supervisor that would not come up for one of those could
326/// not be used to find out why.
327async 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
345/// Write one of the agent's committed assets into the state directory.
346///
347/// The port reads its skill, its template and its schema from paths, so that
348/// editing one on a running host is a restart rather than a rebuild. An
349/// installed program has no checkout to read them out of, so the bytes it
350/// carries are written here — and an operator who configured a path of their
351/// own is pointed at theirs instead.
352fn 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
364/// Write the reference documents the skill links to into the assets directory.
365///
366/// The skill is deliberately short and links out for everything else, so an
367/// install that carried the skill and none of what it points at would hand the
368/// agent a set of dead links — which is worse than no links, because it reads as
369/// documentation right up to the moment it is opened. Each document goes to the
370/// path the skill links to it by, relative to the assets directory, and the
371/// harness runs with that directory as its working directory: so the one
372/// relative link in the skill resolves both from the skill's own location and
373/// from where the agent is standing, and it resolves to the same file.
374fn 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
389/// The supervising agent's harness, over the assets this program carries.
390fn 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        // The assets directory rather than the state directory, so that the
426        // skill's own relative links to the reference documents beside it
427        // resolve from where the agent is standing as well as from the skill.
428        // llmlint: ignore[changed_behavior_has_e2e] A wrong cwd makes relative reference-file opens fail visibly on the first documentation read; the narrowed rule requires a silent failure. The installed-assets journey already proves the bundled links resolve without a checkout.
429        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
439/// One server, serving.
440///
441/// Dropping this stops it, and so does [`Running::stop`]; nothing here outlives
442/// the handle a caller holds.
443pub struct Running {
444    /// Where it is answering.
445    address: SocketAddr,
446    /// What it was configured with.
447    config: ServerConfig,
448    /// The supervision core.
449    supervisor: Arc<Supervisor>,
450    /// Durable state.
451    store: Arc<dyn StorePort>,
452    /// What this start adopted.
453    reconciliation: Reconciliation,
454    /// How many posts the ingress worker has finished handling.
455    completions: watch::Receiver<u64>,
456    /// The graceful-shutdown signal, taken when it is sent.
457    stop: Option<oneshot::Sender<()>>,
458    /// The task serving requests.
459    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    /// Where this server is answering.
474    #[must_use]
475    pub const fn address(&self) -> SocketAddr {
476        self.address
477    }
478
479    /// The base URL of its versioned surface.
480    #[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    /// The URL its ingress endpoint answers on.
490    #[must_use]
491    pub fn ingress_url(&self) -> String {
492        format!("http://{}{INGRESS_PATH}", self.address)
493    }
494
495    /// What it was configured with.
496    #[must_use]
497    pub const fn config(&self) -> &ServerConfig {
498        &self.config
499    }
500
501    /// What this start adopted from the store.
502    #[must_use]
503    pub const fn reconciliation(&self) -> &Reconciliation {
504        &self.reconciliation
505    }
506
507    /// The supervision core it is serving over.
508    #[must_use]
509    pub const fn supervisor(&self) -> &Arc<Supervisor> {
510        &self.supervisor
511    }
512
513    /// Durable state, as it is serving over it.
514    #[must_use]
515    pub const fn store(&self) -> &Arc<dyn StorePort> {
516        &self.store
517    }
518
519    /// How many posts the ingress worker has finished handling, watchable while
520    /// it works.
521    #[must_use]
522    pub fn completions(&self) -> watch::Receiver<u64> {
523        self.completions.clone()
524    }
525
526    /// Stop serving, and wait for the last request to finish.
527    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    /// Serve until the operating system asks this process to stop.
535    ///
536    /// This is what the `server` subcommand runs. It answers when the service
537    /// manager sends the signal it stops units with, or when the terminal that
538    /// started it interrupts.
539    ///
540    /// # Errors
541    ///
542    /// Returns [`StartError::State`] when the signal handlers cannot be
543    /// installed, which is a process that could not be stopped cleanly.
544    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}