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