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 three ports and the
4//! supervision domain's store traits. This is where one implementation is
5//! chosen for each — `OctoPrint` behind the printer port, `Obico` behind the
6//! vision port, `OneHarness` behind the supervisor port, and `SQLite` behind
7//! the store traits — and `just check-repo` refuses any other crate that names
8//! one. The store is one implementation held once per aggregate: [`Stores::of`]
9//! coerces the one `SQLite` store to each of the seven trait objects, and every
10//! consumer below is handed the handle for the aggregate it names and no
11//! other.
12//!
13//! [`Server::start`] is that root. [`Server::start_with`] takes ports a caller
14//! composed, which is how the tiers that stand in for a machine drive the real
15//! surface without one; the two share every line after the ports exist, so what
16//! a tier drives is the server this file starts.
17
18use std::ffi::OsStr;
19use std::net::SocketAddr;
20use std::path::{Path, PathBuf};
21use std::sync::Arc;
22
23use axum::Router;
24use axum::routing::post;
25use printobserver_core::store::Stores;
26use printobserver_core::{Clock as _, CoreConfig, Supervisor, SystemClock};
27use printobserver_obico::{DetectorHealthCheck, ObicoScoring, ObicoVision, ObicoVisionConfig};
28use printobserver_octoprint::OctoPrintPrinter;
29use printobserver_oneharness::{
30    AgentCommand, AssessmentSchema, EnvAssignment, HarnessSignIn, OneharnessSupervisor,
31    SupervisorConfig,
32};
33use printobserver_printer_api::{PrinterError, PrinterPort};
34use printobserver_store_sqlite::SqliteStore;
35use printobserver_supervisor_api::SupervisorPort;
36use tokio::net::TcpListener;
37use tokio::sync::{oneshot, watch};
38use tokio::task::JoinHandle;
39
40use crate::api::{ApiState, router};
41use crate::config::{ApiCredential, ConfigError, ConfigField, CredentialVerifier, ServerConfig};
42use crate::events::Stored;
43use crate::ingress::{IngressState, receive};
44use crate::operations::{INGRESS_PATH, OPERATIONS, command_for};
45use crate::reconcile::{ReconcileStores, Reconciliation, overdue, reconcile};
46use crate::turns::TurnCredentials;
47
48/// The program a supervision turn runs to read its print's context.
49pub const CONTEXT_PROGRAM: &str = "printobserver";
50
51/// The file, under the state directory, a server before this one wrote the
52/// address it took and the credential in force into. A start deletes it: a
53/// supervision turn runs as the service's user and could read the operator's
54/// credential out of it.
55pub const CLIENT_CONFIG_FILE: &str = "client.toml";
56
57/// The file, under the state directory, a server before this one generated its
58/// API credential into, as plaintext. A start converts it into
59/// [`API_CREDENTIAL_VERIFIER_FILE`] and deletes it, so the credential it held
60/// keeps authenticating while nothing the service's user can read holds it.
61pub const API_CREDENTIAL_FILE: &str = "api-credential";
62
63/// The file, under the state directory, holding the verifier of the operator's
64/// credential — read when `api.credential_verifier` is not configured.
65pub const API_CREDENTIAL_VERIFIER_FILE: &str = "api-credential.verifier";
66
67/// The command that gives an operator a credential, as every refusal and
68/// warning about one names it.
69pub const CREDENTIAL_ISSUE: &str = "printobserver credential issue";
70
71/// The command that prints the verifier of a credential an operator already
72/// holds.
73pub const CREDENTIAL_VERIFIER: &str = "printobserver credential verifier";
74
75/// The mode the verifier file is created with.
76///
77/// Unix alone has one. A file Windows creates carries the access its directory
78/// grants rather than a mode, so there the state directory is what keeps it to
79/// the service's own account.
80#[cfg(unix)]
81const PRIVATE: u32 = 0o600;
82
83/// The command a supervision turn runs to read its print's context.
84///
85/// This program's own context read, against the print the turn is about, and
86/// nothing else: where the server is and the credential the turn answers to
87/// reach the turn through its environment alone — the address the server
88/// bound and a credential minted for that turn — so the command names no
89/// configuration file and the program reads none.
90/// `printobserver-oneharness` substitutes the print for the placeholder.
91#[must_use]
92pub fn context_command() -> String {
93    format!("{CONTEXT_PROGRAM} context --print-id {{print_id}}")
94}
95
96/// Who an operator's credential is checked against, as one start settled it.
97#[derive(Debug, Clone)]
98pub enum OperatorCredential {
99    /// Its verifier, from `api.credential_verifier` or the state directory.
100    Verifier(CredentialVerifier),
101    /// A plaintext `api.credential` the configuration still carries, admitted
102    /// until it is replaced.
103    Plaintext(ApiCredential),
104    /// Nothing at all: a fresh install whose operator has not run
105    /// `printobserver credential issue` yet. No operator request is admitted.
106    Unconfigured,
107}
108
109impl OperatorCredential {
110    /// Whether a presented credential is the operator's.
111    #[must_use]
112    pub fn admits(&self, presented: &[u8]) -> bool {
113        match self {
114            Self::Verifier(verifier) => verifier.admits(presented),
115            Self::Plaintext(credential) => credential.admits(presented),
116            Self::Unconfigured => false,
117        }
118    }
119}
120
121/// The warning every start under a plaintext `api.credential` gives, which
122/// names the key, its replacement and the command that computes one, and never
123/// what the key holds.
124#[must_use]
125pub fn plaintext_credential_warning() -> String {
126    format!(
127        "the server configuration carries `api.credential`, an operator credential in \
128         plaintext. A supervision turn runs as this service's user and can read that file, \
129         so it can read that credential until it is replaced. Replace it with \
130         `api.credential_verifier`: pipe the credential into `{CREDENTIAL_VERIFIER}` to print \
131         that line, put it in the configuration, delete `api.credential`, and restart the \
132         service"
133    )
134}
135
136/// Write one file this start creates, exclusively and private to the service.
137fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
138    use std::io::Write as _;
139
140    let mut options = std::fs::OpenOptions::new();
141    options.write(true).create_new(true);
142    #[cfg(unix)]
143    std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
144    let mut file = options.open(path)?;
145    // llmlint: ignore[changed_behavior_has_e2e] A write or sync failing into a file this start just created exclusively is a full or failing disk, which no journey can arrange on a runner without root; the conversion it serves, and the next start after it, are driven by `a_legacy_installation_keeps_its_operators_credential_through_every_route`.
146    let written = file.write_all(contents).and_then(|()| file.sync_all());
147    if written.is_err() {
148        // The file is this start's own and holds nothing usable, so it is
149        // taken back rather than left for the next start to refuse.
150        let _ = std::fs::remove_file(path);
151    }
152    written
153}
154
155/// Remove one file a server before this one left, when it is there.
156fn remove_if_there(path: &Path) -> std::io::Result<()> {
157    match std::fs::remove_file(path) {
158        Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
159        _ => Ok(()),
160    }
161}
162
163/// Take the plaintext a server before this one left in the state directory out
164/// of it.
165///
166/// `client.toml` is deleted. `api-credential` is converted into the verifier
167/// file — written first, exclusively, so a start that stops between the two
168/// leaves the credential still convertible — and then deleted; one left beside
169/// a verifier file that is already there is deleted outright, because that
170/// verifier is what is in force.
171///
172/// # Errors
173///
174/// Returns [`StartError::Credential`] naming the file, and never what it holds,
175/// when the legacy credential cannot be read, holds nothing a header could
176/// present, or cannot be converted or removed; and [`StartError::State`] when
177/// `client.toml` cannot be removed.
178fn take_plaintext_out(state_dir: &Path) -> Result<(), StartError> {
179    let client_config = state_dir.join(CLIENT_CONFIG_FILE);
180    remove_if_there(&client_config).map_err(|error| StartError::State {
181        detail: format!(
182            "{} could not be removed, and it may carry the operator's credential where a \
183             supervision turn can read it: {error}",
184            client_config.display()
185        ),
186    })?;
187    let legacy = state_dir.join(API_CREDENTIAL_FILE);
188    let refusing = |detail: String| StartError::Credential {
189        path: legacy.clone(),
190        detail,
191    };
192    let held = match std::fs::read(&legacy) {
193        Ok(held) => held,
194        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
195        Err(error) => return Err(refusing(format!("it cannot be read: {error}"))),
196    };
197    let verifier_file = state_dir.join(API_CREDENTIAL_VERIFIER_FILE);
198    if !verifier_file.exists() {
199        let text = core::str::from_utf8(&held).ok().map(without_terminator);
200        let credential = text
201            .ok_or("it is not text")
202            .and_then(ApiCredential::new)
203            .map_err(|why| {
204                refusing(format!(
205                    "{why}. This server converts the credential an earlier version generated \
206                     there into its verifier: correct the file, or remove it and run \
207                     `{CREDENTIAL_ISSUE} --replace`"
208                ))
209            })?;
210        write_private(
211            &verifier_file,
212            format!("{}\n", credential.verifier()).as_bytes(),
213        )
214        .map_err(|error| {
215            refusing(format!(
216                "its verifier could not be written to {}: {error}",
217                verifier_file.display()
218            ))
219        })?;
220    }
221    std::fs::remove_file(&legacy)
222        .map_err(|error| refusing(format!("it could not be removed: {error}")))
223}
224
225/// The operator credential this start serves under, and the warnings it owes.
226///
227/// The legacy plaintext is taken out of the state directory first. Then
228/// `api.credential_verifier` when it is configured, a plaintext
229/// `api.credential` when that is all the configuration carries, the verifier
230/// file in the state directory, and otherwise nothing — a fresh install, which
231/// supervises and admits no operator until one is issued. A plaintext
232/// `api.credential` warns whether or not a verifier wins over it.
233///
234/// # Errors
235///
236/// Returns [`StartError::Credential`] naming the file, and never what it
237/// holds, when the legacy plaintext cannot be taken out or the verifier file
238/// cannot be read as one.
239pub fn operator_credential(
240    config: &ServerConfig,
241) -> Result<(OperatorCredential, Vec<String>), StartError> {
242    take_plaintext_out(&config.state_dir)?;
243    let mut warnings = Vec::new();
244    if config.api_credential.is_some() {
245        warnings.push(plaintext_credential_warning());
246    }
247    if let Some(verifier) = &config.api_credential_verifier {
248        return Ok((OperatorCredential::Verifier(verifier.clone()), warnings));
249    }
250    if let Some(plaintext) = &config.api_credential {
251        return Ok((OperatorCredential::Plaintext(plaintext.clone()), warnings));
252    }
253    let path = config.state_dir.join(API_CREDENTIAL_VERIFIER_FILE);
254    let held = match std::fs::read_to_string(&path) {
255        Ok(held) => held,
256        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
257            return Ok((OperatorCredential::Unconfigured, warnings));
258        }
259        Err(error) => {
260            return Err(StartError::Credential {
261                path,
262                detail: format!("it cannot be read: {error}"),
263            });
264        }
265    };
266    let verifier =
267        CredentialVerifier::parse(held.trim()).map_err(|why| StartError::Credential {
268            path: path.clone(),
269            detail: format!(
270                "{why}. Correct the file, or remove it and set `api.credential_verifier`"
271            ),
272        })?;
273    Ok((OperatorCredential::Verifier(verifier), warnings))
274}
275
276/// A credential file's text with the one line terminator a person's editor or
277/// shell ends it with set aside.
278///
279/// Exactly one, `\n` or `\r\n`: that terminator is not part of the credential,
280/// and anything else in the text — a second one included — is left for the
281/// character rule to refuse.
282fn without_terminator(text: &str) -> &str {
283    text.strip_suffix("\r\n")
284        .or_else(|| text.strip_suffix('\n'))
285        .unwrap_or(text)
286}
287
288/// The file name the agent's prompt template is materialized under.
289pub const PROMPT_FILE: &str = "turn-prompt.md";
290
291/// The file name the assessment schema is materialized under.
292pub const SCHEMA_FILE: &str = "assessment-schema.json";
293
294/// The prompt template this program carries and materializes.
295///
296/// The adapter's own committed asset rather than a copy of it, so what an
297/// installed program fills a turn with and what `just check-repo` reads are one
298/// file.
299pub const TURN_PROMPT: &str = printobserver_oneharness::DEFAULT_TURN_PROMPT;
300
301/// The four implementations one running server was composed from.
302///
303/// A tier that stands in for a machine hands these in; [`Server::start`] builds
304/// them from the configuration.
305pub struct Ports {
306    /// The printer.
307    pub printer: Arc<dyn PrinterPort>,
308    /// Durable state, one handle per aggregate onto one store.
309    pub stores: Stores,
310    /// External observations, and the snapshot fetch.
311    pub vision: Arc<ObicoVision>,
312    /// The supervising agent's harness.
313    pub agent: Arc<dyn SupervisorPort>,
314}
315
316impl core::fmt::Debug for Ports {
317    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
318        formatter.debug_struct("Ports").finish_non_exhaustive()
319    }
320}
321
322/// Why this server did not start.
323#[derive(Debug)]
324pub enum StartError {
325    /// The configuration will not do, naming the field that will not.
326    Configuration(ConfigError),
327    /// The state directory could not be prepared.
328    State {
329        /// What went wrong.
330        detail: String,
331    },
332    /// A credential file in the state directory cannot be used.
333    Credential {
334        /// The file.
335        path: PathBuf,
336        /// Why it cannot be used, in words that never quote what it holds.
337        detail: String,
338    },
339    /// The address could not be listened on.
340    Listen {
341        /// The address that was asked for.
342        address: SocketAddr,
343        /// What went wrong.
344        detail: String,
345    },
346    /// The store could not be opened.
347    Store {
348        /// What the store said.
349        detail: String,
350    },
351    /// The supervising agent's harness could not be reached at all.
352    Supervisor {
353        /// What the harness said.
354        detail: String,
355    },
356    /// Reconciling what the store held failed.
357    Reconciliation {
358        /// What went wrong.
359        detail: String,
360    },
361}
362
363impl StartError {
364    /// The configuration field this refusal is about, when it is about one.
365    #[must_use]
366    pub const fn field(&self) -> Option<ConfigField> {
367        match self {
368            Self::Configuration(error) => error.field(),
369            _ => None,
370        }
371    }
372}
373
374impl core::fmt::Display for StartError {
375    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
376        match self {
377            Self::Configuration(error) => write!(formatter, "{error}"),
378            Self::State { detail } => {
379                write!(
380                    formatter,
381                    "the state directory could not be prepared: {detail}"
382                )
383            }
384            Self::Credential { path, detail } => write!(
385                formatter,
386                "the credential file {} cannot be used: {detail}",
387                path.display()
388            ),
389            Self::Listen { address, detail } => {
390                write!(formatter, "{address} could not be listened on: {detail}")
391            }
392            Self::Store { detail } => write!(formatter, "the store could not be opened: {detail}"),
393            Self::Supervisor { detail } => write!(
394                formatter,
395                "the supervising agent's harness could not be reached: {detail}"
396            ),
397            Self::Reconciliation { detail } => write!(
398                formatter,
399                "what the store held could not be reconciled: {detail}"
400            ),
401        }
402    }
403}
404
405impl core::error::Error for StartError {}
406
407impl From<ConfigError> for StartError {
408    fn from(error: ConfigError) -> Self {
409        Self::Configuration(error)
410    }
411}
412
413/// The composition root.
414#[derive(Debug)]
415pub struct Server;
416
417/// Take the listener a configuration asks for, and the address it bound, which
418/// a configuration asking for any free port learns only here.
419async fn bind(listen: SocketAddr) -> Result<(TcpListener, SocketAddr), StartError> {
420    let failed = |error: std::io::Error| StartError::Listen {
421        address: listen,
422        detail: error.to_string(),
423    };
424    let listener = TcpListener::bind(listen).await.map_err(failed)?;
425    let address = listener.local_addr().map_err(failed)?;
426    Ok((listener, address))
427}
428
429impl Server {
430    /// Read one configuration file, compose the four implementations, and serve.
431    ///
432    /// # Errors
433    ///
434    /// Returns [`StartError::Configuration`] naming the field that will not do
435    /// — including the two only the machine can rule on, an `OctoPrint` address
436    /// nothing answers at and a key that instance refuses — and the other
437    /// variants for a host that will not let this server come up.
438    pub async fn start(config_path: impl AsRef<Path>) -> Result<Running, StartError> {
439        Self::start_with_usage(config_path, &[]).await
440    }
441
442    /// Serve as [`Server::start`] does, handing each supervision turn the
443    /// usage line of every command it may run, out of `command_usage`: every
444    /// command the program serving the turns has, as it prints them.
445    ///
446    /// # Errors
447    ///
448    /// The same as [`Server::start`].
449    pub async fn start_with_usage(
450        config_path: impl AsRef<Path>,
451        command_usage: &[String],
452    ) -> Result<Running, StartError> {
453        let config = ServerConfig::load(config_path)?;
454        let store = SqliteStore::open(&config.state_dir).map_err(|error| StartError::Store {
455            detail: error.to_string(),
456        })?;
457        // A row a migration could not carry forward as it was is said once, as
458        // the start that migrated it comes up, beside the store's own record.
459        let migrated: Vec<String> = store.migrated().iter().map(ToString::to_string).collect();
460        let stores = Stores::of(Arc::new(store));
461        let printer = Arc::new(OctoPrintPrinter::new(config.octoprint.clone()));
462        probe(printer.as_ref()).await?;
463        let vision = Arc::new(
464            ObicoVision::new(ObicoVisionConfig {
465                blank_frame_max_stddev: config.blank_frame_max_stddev,
466                ..ObicoVisionConfig::default()
467            })
468            .map_err(|error| StartError::State {
469                detail: error.to_string(),
470            })?
471            .with_api(config.obico_api.clone()),
472        );
473        let agent = Arc::new(agent_for(&config, command_usage)?);
474        let mut running = Self::start_with(
475            config,
476            Ports {
477                printer,
478                stores,
479                vision,
480                agent,
481            },
482        )
483        .await?;
484        running.warnings.extend(migrated);
485        Ok(running)
486    }
487
488    /// Serve over ports a caller composed.
489    ///
490    /// # Errors
491    ///
492    /// The same as [`Server::start`], less the refusals that belong to building
493    /// the implementations.
494    pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
495        // The operator's credential is settled before anything listens, so
496        // there is no moment at which this server answers a request it has
497        // nothing to check against — and the plaintext an earlier version left
498        // is out of the state directory before the first turn could read it.
499        let (operator, warnings) = operator_credential(&config)?;
500        // The listener is taken next, because the command a supervision turn
501        // runs to read its context names the address this server is answering
502        // on — and a configuration may ask for any free port.
503        let (listener, address) = bind(config.listen).await?;
504        let clock = Arc::new(SystemClock);
505        let alignments = prepare_state(&config, &ports)?;
506        let due = overdue(&ports.stores.actions, clock.now())
507            .await
508            .map_err(|error| StartError::Reconciliation {
509                detail: error.to_string(),
510            })?;
511        let supervisor = Supervisor::new(
512            core_config_of(&config),
513            Arc::clone(&ports.printer),
514            ports.stores.clone(),
515            Arc::clone(&ports.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
516            Arc::clone(&ports.agent),
517            clock,
518        );
519        // Every turn's runs are told the address this server bound, beside the
520        // credential minted for them.
521        let turns = TurnCredentials::new(Some(address));
522        supervisor.install_turn_authority(Arc::new(turns.clone()));
523        supervisor.install_check_images(Arc::new(crate::check_images::PanelImages::new(
524            &config.state_dir,
525            Arc::clone(&alignments),
526            config
527                .camera_snapshot_url
528                .as_ref()
529                .map(|url| url.as_str().to_owned()),
530        )));
531        if let Some(scoring) = scoring_read(&config, &ports.vision)? {
532            supervisor.install_scoring_probe(scoring);
533        }
534        let reconciliation = reconcile(
535            &supervisor,
536            &ReconcileStores {
537                prints: Arc::clone(&ports.stores.prints),
538                sessions: Arc::clone(&ports.stores.sessions),
539                events: Arc::clone(&ports.stores.events),
540            },
541            due,
542        )
543        .await
544        .map_err(|error| StartError::Reconciliation {
545            detail: error.to_string(),
546        })?;
547        Box::pin(sweep_left_behind(&supervisor, &alignments)).await?;
548
549        let ingress = IngressState::start(
550            Arc::clone(&supervisor),
551            Arc::clone(&ports.stores.events),
552            Arc::clone(&ports.vision),
553            config.ingress_shared_secret.clone(),
554            config.ingress_answer_bound,
555        );
556        let completions = ingress.completions();
557        let observing = crate::observation::start(&supervisor);
558        let watching = crate::watch::start(
559            &supervisor,
560            Arc::clone(&ports.printer),
561            detector_check(&config)?,
562            Arc::clone(&alignments),
563        );
564        // Every events read waits on this, and every write that stores an
565        // event raises it once committed — whichever of this server's parts
566        // made the write.
567        let (stored, signal) = Stored::channel();
568        ports.stores.events.on_stored(signal);
569        let application = router(ApiState {
570            supervisor: Arc::clone(&supervisor),
571            prints: Arc::clone(&ports.stores.prints),
572            events: Arc::clone(&ports.stores.events),
573            images: Arc::clone(&ports.stores.images),
574            sessions: Arc::clone(&ports.stores.sessions),
575            operator: Arc::new(operator),
576            turns,
577            stored,
578        })
579        .merge(
580            Router::new()
581                .route(INGRESS_PATH, post(receive))
582                .with_state(ingress),
583        );
584
585        let (stop, stopped) = oneshot::channel::<()>();
586        let serving = tokio::spawn(async move {
587            let _ = axum::serve(listener, application)
588                .with_graceful_shutdown(async move {
589                    let _ = stopped.await;
590                })
591                .await;
592        });
593        Ok(Running {
594            address,
595            config,
596            warnings,
597            supervisor,
598            stores: ports.stores,
599            reconciliation,
600            completions,
601            stop: Some(stop),
602            serving,
603            observing,
604            watching,
605            alignments,
606        })
607    }
608}
609
610/// The directories this start keeps per-print state in — each open print's
611/// G-code spool, and every print's alignment verdict — made when absent.
612fn prepare_state(
613    config: &ServerConfig,
614    ports: &Ports,
615) -> Result<Arc<crate::alignment::Alignments>, StartError> {
616    let spool_dir = gcode_spool_dir(&config.state_dir);
617    std::fs::create_dir_all(&spool_dir).map_err(|error| StartError::State {
618        detail: format!("{}: {error}", spool_dir.display()),
619    })?;
620    crate::alignment::Alignments::new(
621        &config.state_dir,
622        config.camera_calibration.clone(),
623        Arc::clone(&ports.stores.prints),
624    )
625    .map(Arc::new)
626    .map_err(|error| StartError::State {
627        detail: format!(
628            "{}: {error}",
629            crate::alignment::verdict_dir(&config.state_dir).display()
630        ),
631    })
632}
633
634/// Delete what a print closed while no server ran left behind: its G-code
635/// spool and its alignment verdict.
636async fn sweep_left_behind(
637    supervisor: &Supervisor,
638    alignments: &crate::alignment::Alignments,
639) -> Result<(), StartError> {
640    supervisor
641        .sweep_gcode_spools()
642        .await
643        .map_err(|error| StartError::Reconciliation {
644            detail: error.to_string(),
645        })?;
646    alignments.sweep().await;
647    Ok(())
648}
649
650/// Where each open print's G-code is spooled, under a state directory.
651#[must_use]
652pub fn gcode_spool_dir(state_dir: &Path) -> std::path::PathBuf {
653    state_dir.join("gcode-spool")
654}
655
656/// What supervision is configured with, from the server's own configuration.
657fn core_config_of(config: &ServerConfig) -> CoreConfig {
658    let mut core_config = CoreConfig::new(config.safety.clone(), context_command());
659    core_config.gcode_spool_dir = Some(gcode_spool_dir(&config.state_dir));
660    core_config
661        .camera_snapshot_url
662        .clone_from(&config.camera_snapshot_url);
663    core_config.observation_interval = config.observation_interval;
664    core_config.printer_poll = config.printer_poll;
665    core_config.unattended_window = config.unattended_window;
666    core_config.spools = config.spools;
667    core_config.sheets.clone_from(&config.sheets);
668    core_config.recovery = config.recovery;
669    core_config
670        .recovery_grants
671        .clone_from(&config.recovery_grants);
672    core_config
673}
674
675/// The reader of `Obico`'s own record of the print, when its API is
676/// configured: of the printer `obico.printer_id` names, or the one the last
677/// body `Obico` posted named.
678fn scoring_read(
679    config: &ServerConfig,
680    vision: &ObicoVision,
681) -> Result<Option<Arc<dyn printobserver_core::ScoringProbe>>, StartError> {
682    config
683        .obico_api
684        .clone()
685        .map(|api| {
686            ObicoScoring::new(api, config.obico_printer_id, vision.known_printer())
687                .map(|scoring| Arc::new(scoring) as Arc<dyn printobserver_core::ScoringProbe>)
688                .map_err(|error| StartError::State {
689                    detail: error.to_string(),
690                })
691        })
692        .transpose()
693}
694
695/// The failure detector's health check, when its address is configured.
696fn detector_check(
697    config: &ServerConfig,
698) -> Result<Option<Arc<dyn printobserver_core::DetectorProbe>>, StartError> {
699    config
700        .obico_ml_api_url
701        .as_ref()
702        .map(|url| {
703            DetectorHealthCheck::new(url)
704                .map(|check| Arc::new(check) as Arc<dyn printobserver_core::DetectorProbe>)
705                .map_err(|detail| StartError::State { detail })
706        })
707        .transpose()
708}
709
710/// Ask the machine whether the address and the key are the ones it answers to.
711///
712/// Only the two answers that are *about the configuration* refuse a start. A
713/// printer that is off, in an error state, or answering something this adapter
714/// cannot read is a machine having a bad day rather than a file with the wrong
715/// value in it, and a supervisor that would not come up for one of those could
716/// not be used to find out why.
717async fn probe(printer: &dyn PrinterPort) -> Result<(), StartError> {
718    match printer.snapshot().await {
719        Err(PrinterError::Unreachable { detail }) => {
720            Err(StartError::Configuration(ConfigError::about(
721                ConfigField::OctoprintUrl,
722                format!("nothing answers there: {detail}"),
723            )))
724        }
725        Err(PrinterError::Unauthorized { detail }) => {
726            Err(StartError::Configuration(ConfigError::about(
727                ConfigField::OctoprintApiKey,
728                format!("the OctoPrint instance refused it: {detail}"),
729            )))
730        }
731        _ => Ok(()),
732    }
733}
734
735/// Write one of the agent's committed assets into the state directory.
736///
737/// The port reads its template and its schema from paths, so that editing one
738/// on a running host is a restart rather than a rebuild. An installed program
739/// has no checkout to read them out of, so the bytes it carries are written
740/// here — and an operator who configured a template of their own is pointed at
741/// theirs instead.
742fn materialize(
743    directory: &Path,
744    name: &str,
745    contents: &str,
746) -> Result<std::path::PathBuf, StartError> {
747    let path = directory.join(name);
748    std::fs::write(&path, contents).map_err(|error| StartError::State {
749        detail: format!("{} could not be written: {error}", path.display()),
750    })?;
751    Ok(path)
752}
753
754/// The directory the harness runs in: the one holding the configured skill.
755///
756/// An installed skill is a directory — its `SKILL.md` and the `reference/`
757/// documents that file links to by relative paths — so the agent stands where
758/// those links resolve. A skill named by a bare file name sits in this
759/// process's own working directory.
760fn beside_the_skill(skill_path: &Path) -> std::path::PathBuf {
761    match skill_path.parent() {
762        Some(directory) if !directory.as_os_str().is_empty() => directory.to_path_buf(),
763        _ => std::path::PathBuf::from("."),
764    }
765}
766
767/// The supervising agent's harness, over the configured skill and the assets
768/// this program carries.
769fn agent_for(
770    config: &ServerConfig,
771    command_usage: &[String],
772) -> Result<OneharnessSupervisor, StartError> {
773    OneharnessSupervisor::open(agent_config_with(config, command_usage)?).map_err(|error| {
774        StartError::Supervisor {
775            detail: error.to_string(),
776        }
777    })
778}
779
780/// The reads a supervision turn is handed the usage of, beside every action
781/// the safety envelope grants its role: the whole context, and a fresh look.
782pub const TURN_READS: [&str; 2] = ["context", "look"];
783
784/// The supervising agent's configuration, as [`Server::start_with_usage`]
785/// composes it: [`agent_config`]'s, handing each turn the usage, out of
786/// `command_usage`, of [`TURN_READS`] and of each action the configured
787/// envelope grants the agent — what a check acts with, and no command it
788/// cannot ask for.
789///
790/// # Errors
791///
792/// The same as [`agent_config`].
793pub fn agent_config_with(
794    config: &ServerConfig,
795    command_usage: &[String],
796) -> Result<SupervisorConfig, StartError> {
797    let mut composed = agent_config(config)?;
798    let granted = config
799        .safety
800        .actions
801        .get(&printobserver_core::ActorClass::Agent)
802        .into_iter()
803        .flatten()
804        .filter_map(|kind| {
805            printobserver_types::serde_json::to_value(kind)
806                .ok()
807                .and_then(|named| named.as_str().map(command_for))
808        });
809    let handed: Vec<String> = TURN_READS
810        .iter()
811        .map(|read| command_for(read))
812        .chain(granted)
813        .map(|command| format!("printobserver {command}"))
814        .collect();
815    composed.command_usage = command_usage
816        .iter()
817        .filter(|line| {
818            handed
819                .iter()
820                .any(|command| line == &command || line.starts_with(&format!("{command} ")))
821        })
822        .cloned()
823        .collect();
824    Ok(composed)
825}
826
827/// The supervising agent's configuration, as [`Server::start`] composes it.
828///
829/// The template and the assessment schema are written into the assets
830/// directory; the skill is the installed one `supervisor.skill_path` names, and
831/// every turn runs in the directory holding it — where an installed skill's
832/// `reference/` documents sit, so the links the skill carries resolve from
833/// where the agent stands. The harness is the one `supervisor.harness` names,
834/// found by name, and a harness this program can sign in is pointed at the
835/// sign-in kept under the state directory.
836///
837/// # Errors
838///
839/// Returns [`StartError::State`] when the assets or the sign-in directory
840/// cannot be written, and [`StartError::Supervisor`] when the schema it wrote
841/// constrains nothing.
842pub fn agent_config(config: &ServerConfig) -> Result<SupervisorConfig, StartError> {
843    let assets = config.assets_dir();
844    std::fs::create_dir_all(&assets).map_err(|error| StartError::State {
845        detail: format!("{} could not be created: {error}", assets.display()),
846    })?;
847    let prompt_template_path = match &config.prompt_template_path {
848        Some(path) => path.clone(),
849        None => materialize(&assets, PROMPT_FILE, TURN_PROMPT)?,
850    };
851    let schema_path =
852        materialize(
853            &assets,
854            SCHEMA_FILE,
855            &printobserver_types::serde_json::to_string_pretty(&AssessmentSchema::as_handed(
856                printobserver_types::contract::schema_of::<
857                    printobserver_supervisor_api::AgentAssessment,
858                >(),
859            ))
860            .map_err(|error| StartError::State {
861                detail: error.to_string(),
862            })?,
863        )?;
864    let assessment_schema =
865        AssessmentSchema::at(&schema_path).map_err(|error| StartError::Supervisor {
866            detail: error.to_string(),
867        })?;
868    // A harness this program can sign in keeps that sign-in under the state
869    // directory — the one place the service's unit lets it write — and every
870    // turn is pointed at the directory `printobserver sign-in` wrote it to. A
871    // harness outside the table is handed nothing extra.
872    let mut harness_env = match HarnessSignIn::of(&config.harness) {
873        Some(sign_in) => {
874            let directory =
875                sign_in
876                    .prepare(&config.state_dir)
877                    .map_err(|error| StartError::State {
878                        detail: format!(
879                            "{} could not be created: {error}",
880                            sign_in.directory(&config.state_dir).display()
881                        ),
882                    })?;
883            let refused = |error: printobserver_oneharness::ConfigError| StartError::Supervisor {
884                detail: error.to_string(),
885            };
886            let mut assigned = vec![sign_in.assignment(&directory).map_err(refused)?];
887            // llmlint: ignore[changed_behavior_has_e2e] See suppressions.toml.
888            assigned.extend(sign_in.session_assignments().map_err(refused)?);
889            assigned
890        }
891        None => Vec::new(),
892    };
893    let search_path = std::env::var_os("PATH").unwrap_or_default();
894    harness_env.extend(path_led_by_this_program(&search_path)?);
895    Ok(SupervisorConfig {
896        state_dir: config.state_dir.clone(),
897        skill_path: config.skill_path.clone(),
898        prompt_template_path,
899        assessment_schema,
900        harness: config.harness.clone(),
901        model: config.model.clone(),
902        // The skill's own directory rather than the state or assets directory,
903        // so that the skill's relative links to the reference documents beside
904        // it resolve from where the agent is standing as well as from the skill.
905        working_dir: beside_the_skill(&config.skill_path),
906        turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
907        // Found by name, unless npm's launcher is all a search finds: then the
908        // native program behind it, which `OneHarness` can start where the
909        // launcher cannot be.
910        harness_bin: HarnessSignIn::of(&config.harness)
911            .and_then(|harness| harness.program_behind_launcher(&search_path)),
912        harness_env,
913        agent_commands: agent_commands()?,
914        withheld_beside_an_image: withheld_beside_an_image()?,
915        command_usage: Vec::new(),
916        auto_compact_tokens: config.auto_compact_tokens,
917        idle_compact_tokens: config.idle_compact_tokens,
918    })
919}
920
921/// The commands the supervising agent may run: this program's own, one per
922/// operation the server serves that has a command, and no other.
923///
924/// Every one of them is a request to this server, so what the agent can change
925/// is still exactly what the policy grants its actor. Derived from
926/// [`OPERATIONS`] through the command-line program's own spelling, so an
927/// operation the server gains is a command the agent may run from the same
928/// change. An operation reached through another's command
929/// ([`printer_wide_of`](crate::operations::printer_wide_of)) adds none.
930fn agent_commands() -> Result<Vec<AgentCommand>, StartError> {
931    OPERATIONS
932        .iter()
933        .filter(|operation| crate::operations::printer_wide_of(operation.name).is_none())
934        .map(|operation| {
935            AgentCommand::new(&format!(
936                "{CONTEXT_PROGRAM} {}",
937                command_for(operation.name)
938            ))
939        })
940        .collect::<Result<_, _>>()
941        .map_err(|error| StartError::Supervisor {
942            detail: error.to_string(),
943        })
944}
945
946/// The reads a turn handed an image runs none of: a fresh look.
947///
948/// A turn carrying a check's image decides on that image. A look there only
949/// stalls the decision, and a later frame can show a part that moved dragged
950/// back under its walls, which the agent then reads as fine. It can also run on
951/// into the moment the print's next turn was due to begin.
952pub const WITHHELD_BESIDE_AN_IMAGE: [&str; 1] = ["look"];
953
954/// [`WITHHELD_BESIDE_AN_IMAGE`] as the agent commands it names.
955fn withheld_beside_an_image() -> Result<Vec<AgentCommand>, StartError> {
956    WITHHELD_BESIDE_AN_IMAGE
957        .iter()
958        .map(|read| AgentCommand::new(&format!("{CONTEXT_PROGRAM} {}", command_for(read))))
959        .collect::<Result<_, _>>()
960        .map_err(|error| StartError::Supervisor {
961            detail: error.to_string(),
962        })
963}
964
965/// A turn's `PATH`: the directory this program is running from, then the
966/// search path this process was given.
967///
968/// The context command, and every command the agent may run, names this
969/// program by name rather than by path, and nothing makes that name resolve in
970/// a service's environment: neither installer puts the program's directory on
971/// a `PATH`, and Windows' service control manager hands a service the
972/// environment it had at boot. Leading the turn's `PATH` with this program's
973/// own directory makes the name the program that is serving.
974///
975/// Nothing is added when the running program's path cannot be read, which
976/// leaves the turn the `PATH` it inherits.
977fn path_led_by_this_program(inherited: &OsStr) -> Result<Option<EnvAssignment>, StartError> {
978    let Some(directory) = std::env::current_exe()
979        .ok()
980        .and_then(|program| program.parent().map(Path::to_path_buf))
981    else {
982        return Ok(None);
983    };
984    let refused = |detail: String| StartError::Supervisor {
985        detail: format!(
986            "a turn's PATH cannot lead with {}: {detail}",
987            directory.display()
988        ),
989    };
990    let joined = std::env::join_paths(
991        std::iter::once(directory.clone()).chain(std::env::split_paths(inherited)),
992    )
993    .map_err(|error| refused(error.to_string()))?;
994    let joined = joined
995        .to_str()
996        .ok_or_else(|| refused("it is not valid Unicode".to_owned()))?;
997    EnvAssignment::new(&format!("PATH={joined}"))
998        .map(Some)
999        .map_err(|error| refused(error.to_string()))
1000}
1001
1002/// One server, serving.
1003///
1004/// Dropping this stops it, and so does [`Running::stop`]; nothing here outlives
1005/// the handle a caller holds.
1006pub struct Running {
1007    /// Where it is answering.
1008    address: SocketAddr,
1009    /// What it was configured with.
1010    config: ServerConfig,
1011    /// What this start found that its operator should change, in words that
1012    /// quote no credential.
1013    warnings: Vec<String>,
1014    /// The supervision core.
1015    supervisor: Arc<Supervisor>,
1016    /// Durable state, one handle per aggregate.
1017    stores: Stores,
1018    /// What this start adopted.
1019    reconciliation: Reconciliation,
1020    /// How many posts the ingress worker has finished handling.
1021    completions: watch::Receiver<u64>,
1022    /// The graceful-shutdown signal, taken when it is sent.
1023    stop: Option<oneshot::Sender<()>>,
1024    /// The task serving requests.
1025    serving: JoinHandle<()>,
1026    /// The task giving every active print its periodic observation.
1027    observing: JoinHandle<()>,
1028    /// The printer watch's tasks: its reads, its push reader and its detector
1029    /// check.
1030    watching: crate::watch::Watching,
1031    /// Every print's first-layer alignment verdict.
1032    alignments: Arc<crate::alignment::Alignments>,
1033}
1034
1035impl core::fmt::Debug for Running {
1036    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1037        formatter
1038            .debug_struct("Running")
1039            .field("address", &self.address)
1040            .field("reconciliation", &self.reconciliation)
1041            .finish_non_exhaustive()
1042    }
1043}
1044
1045impl Running {
1046    /// One print's first-layer alignment verdict, which a check reads before
1047    /// drawing the planned toolpath on its image.
1048    #[must_use]
1049    pub fn print_alignment(
1050        &self,
1051        print_id: printobserver_types::PrintId,
1052    ) -> crate::alignment::PrintAlignment {
1053        self.alignments.print_alignment(print_id)
1054    }
1055
1056    /// Where this server is answering.
1057    #[must_use]
1058    pub const fn address(&self) -> SocketAddr {
1059        self.address
1060    }
1061
1062    /// The base URL of its versioned surface.
1063    #[must_use]
1064    pub fn base_url(&self) -> String {
1065        format!(
1066            "http://{}{}",
1067            self.address,
1068            crate::operations::VERSION_PREFIX
1069        )
1070    }
1071
1072    /// The URL its ingress endpoint answers on.
1073    #[must_use]
1074    pub fn ingress_url(&self) -> String {
1075        format!("http://{}{INGRESS_PATH}", self.address)
1076    }
1077
1078    /// What it was configured with.
1079    #[must_use]
1080    pub const fn config(&self) -> &ServerConfig {
1081        &self.config
1082    }
1083
1084    /// What this start found that its operator should change — a plaintext
1085    /// `api.credential` among them — in words that quote no credential. The
1086    /// program running the server writes each to its log on every start.
1087    #[must_use]
1088    pub fn warnings(&self) -> &[String] {
1089        &self.warnings
1090    }
1091
1092    /// What this start adopted from the store.
1093    #[must_use]
1094    pub const fn reconciliation(&self) -> &Reconciliation {
1095        &self.reconciliation
1096    }
1097
1098    /// The supervision core it is serving over.
1099    #[must_use]
1100    pub const fn supervisor(&self) -> &Arc<Supervisor> {
1101        &self.supervisor
1102    }
1103
1104    /// Durable state, as it is serving over it.
1105    #[must_use]
1106    pub const fn stores(&self) -> &Stores {
1107        &self.stores
1108    }
1109
1110    /// How many posts the ingress worker has finished handling, watchable while
1111    /// it works.
1112    #[must_use]
1113    pub fn completions(&self) -> watch::Receiver<u64> {
1114        self.completions.clone()
1115    }
1116
1117    /// Stop serving, and wait for the last request to finish.
1118    pub async fn stop(mut self) {
1119        if let Some(stop) = self.stop.take() {
1120            let _ = stop.send(());
1121        }
1122        self.observing.abort();
1123        self.watching.abort();
1124        let _ = (&mut self.serving).await;
1125    }
1126
1127    /// Serve until the operating system asks this process to stop.
1128    ///
1129    /// This is what the `server` subcommand runs. It answers however this
1130    /// platform asks a process to stop — see [`stop_requested`] — and every one
1131    /// of those ways enters the same shutdown: [`Running::stop`].
1132    ///
1133    /// # Errors
1134    ///
1135    /// Returns [`StartError::State`] when the stop handlers cannot be
1136    /// installed, which is a process that could not be stopped cleanly.
1137    pub async fn serve_until_signalled(self) -> Result<(), StartError> {
1138        stop_requested().await?;
1139        self.stop().await;
1140        Ok(())
1141    }
1142}
1143
1144/// A stop handler that could not be installed, naming which.
1145fn unhandled(what: &str, error: &std::io::Error) -> StartError {
1146    StartError::State {
1147        detail: format!("{what} cannot be handled: {error}"),
1148    }
1149}
1150
1151/// Wait until the operating system asks this process to stop.
1152///
1153/// On Unix that is the signal a service manager stops a unit with, or the
1154/// interrupt from the terminal that started it.
1155#[cfg(unix)]
1156async fn stop_requested() -> Result<(), StartError> {
1157    use tokio::signal::unix::{SignalKind, signal};
1158
1159    let mut terminate = signal(SignalKind::terminate())
1160        .map_err(|error| unhandled("the termination signal", &error))?;
1161    let mut interrupt = signal(SignalKind::interrupt())
1162        .map_err(|error| unhandled("the interrupt signal", &error))?;
1163    tokio::select! {
1164        _ = terminate.recv() => {}
1165        _ = interrupt.recv() => {}
1166    }
1167    Ok(())
1168}
1169
1170/// Wait until the operating system asks this process to stop.
1171///
1172/// Windows has no signals: a console process is stopped by a console control
1173/// event. `CTRL_C` and `CTRL_BREAK` are the terminal's interrupt — the second is
1174/// the one another process can send a process group started apart from its own
1175/// — and `CTRL_CLOSE` and `CTRL_SHUTDOWN` are the console closing and the
1176/// machine shutting down.
1177#[cfg(windows)]
1178async fn stop_requested() -> Result<(), StartError> {
1179    use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close, ctrl_shutdown};
1180
1181    let mut interrupt = ctrl_c().map_err(|error| unhandled("the CTRL_C event", &error))?;
1182    let mut breaking = ctrl_break().map_err(|error| unhandled("the CTRL_BREAK event", &error))?;
1183    let mut closing = ctrl_close().map_err(|error| unhandled("the CTRL_CLOSE event", &error))?;
1184    let mut shutting_down =
1185        ctrl_shutdown().map_err(|error| unhandled("the CTRL_SHUTDOWN event", &error))?;
1186    tokio::select! {
1187        _ = interrupt.recv() => {}
1188        _ = breaking.recv() => {}
1189        _ = closing.recv() => {}
1190        _ = shutting_down.recv() => {}
1191    }
1192    Ok(())
1193}
1194
1195impl Drop for Running {
1196    fn drop(&mut self) {
1197        if let Some(stop) = self.stop.take() {
1198            let _ = stop.send(());
1199        }
1200        self.serving.abort();
1201    }
1202}