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 five 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::net::SocketAddr;
19use std::path::{Path, PathBuf};
20use std::sync::Arc;
21
22use axum::Router;
23use axum::routing::post;
24use printobserver_core::store::Stores;
25use printobserver_core::{Clock as _, CoreConfig, Supervisor, SystemClock};
26use printobserver_obico::{ObicoVision, ObicoVisionConfig};
27use printobserver_octoprint::OctoPrintPrinter;
28use printobserver_oneharness::{
29    AssessmentSchema, HarnessSignIn, OneharnessSupervisor, SupervisorConfig,
30};
31use printobserver_printer_api::{PrinterError, PrinterPort};
32use printobserver_store_sqlite::SqliteStore;
33use printobserver_supervisor_api::SupervisorPort;
34use tokio::net::TcpListener;
35use tokio::sync::{oneshot, watch};
36use tokio::task::JoinHandle;
37
38use crate::api::{ApiState, router};
39use crate::config::{ApiCredential, ConfigError, ConfigField, ServerConfig};
40use crate::ingress::{IngressState, receive};
41use crate::operations::INGRESS_PATH;
42use crate::reconcile::{ReconcileStores, Reconciliation, overdue, reconcile};
43
44/// The program a supervision turn runs to read its print's context.
45pub const CONTEXT_PROGRAM: &str = "printobserver";
46
47/// The file this server writes the address it took and the credential in force
48/// into, under the state directory, for the clients that run beside it.
49pub const CLIENT_CONFIG_FILE: &str = "client.toml";
50
51/// The file, under the state directory, holding the API credential this server
52/// generated for itself — read when `api.credential` is not configured, and
53/// written only when it is not there.
54pub const API_CREDENTIAL_FILE: &str = "api-credential";
55
56/// The mode both files carrying the credential are created with.
57///
58/// Unix alone has one. A file Windows creates carries the access its directory
59/// grants rather than a mode, so there the state directory is what keeps both
60/// files to the service's own account.
61#[cfg(unix)]
62const PRIVATE: u32 = 0o600;
63
64/// The command a supervision turn runs to read its print's context.
65///
66/// This program's own context read, against the print the turn is about and
67/// the configuration file naming the address this server took — which is the
68/// bound address rather than the configured one, because a configuration may
69/// ask for any free port and a turn has to reach the one that was taken — and
70/// the credential in force.
71/// `printobserver-oneharness` substitutes the print for the placeholder.
72///
73/// Both travel in a file rather than on the command line because no client
74/// command of that program takes either: where a server is and what
75/// authenticates to it are configuration, and a command line that could carry
76/// them is a command line that could be pointed anywhere — and one that lands a
77/// credential in a process table.
78#[must_use]
79pub fn context_command(client_config: &Path) -> String {
80    format!(
81        "{CONTEXT_PROGRAM} context --config {} --print-id {{print_id}}",
82        client_config.display()
83    )
84}
85
86/// Write the configuration the clients beside this server read it by.
87///
88/// One `[client]` table naming the address that was actually bound and the
89/// credential in force, so a supervision turn — and an operator on this host
90/// who can read the state directory — reaches and authenticates to this server
91/// without being told either or copying a secret by hand. It is the one file
92/// this program writes the credential into beside the one it generated, so it
93/// is private to the service's own user from the moment it exists: created, or
94/// narrowed when an earlier start left it, before a byte is written.
95fn write_client_config(
96    directory: &Path,
97    address: SocketAddr,
98    credential: &ApiCredential,
99) -> Result<PathBuf, StartError> {
100    use std::io::Write as _;
101
102    let path = directory.join(CLIENT_CONFIG_FILE);
103    let failing = |error: std::io::Error| StartError::State {
104        detail: format!("{} could not be written: {error}", path.display()),
105    };
106    let mut options = std::fs::OpenOptions::new();
107    options.write(true).create(true).truncate(true);
108    #[cfg(unix)]
109    std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
110    let mut file = options.open(&path).map_err(failing)?;
111    #[cfg(unix)]
112    file.set_permissions(std::os::unix::fs::PermissionsExt::from_mode(PRIVATE))
113        .map_err(failing)?;
114    file.write_all(
115        format!(
116            "[client]\nserver = \"http://{address}\"\ncredential = \"{}\"\n",
117            toml_basic_string(credential.written())
118        )
119        .as_bytes(),
120    )
121    .map_err(failing)?;
122    Ok(path)
123}
124
125/// Text as the body of a TOML basic string.
126///
127/// A credential is printable ASCII by construction, so the quote and the
128/// backslash are the only two characters that need an escape.
129fn toml_basic_string(text: &str) -> String {
130    text.replace('\\', "\\\\").replace('"', "\\\"")
131}
132
133/// The API credential this start serves under.
134///
135/// The configured one when `api.credential` names one, in which case the state
136/// directory's file is neither read nor written. Otherwise the file: created
137/// with a fresh credential when it is not there — exclusively, so that nothing
138/// already at that path is ever replaced — and read as it is when it is.
139///
140/// # Errors
141///
142/// Returns [`StartError::Credential`] naming the file, and never what it holds,
143/// when it cannot be created or read or holds nothing a header could present.
144fn credential_in_force(config: &ServerConfig) -> Result<ApiCredential, StartError> {
145    use std::io::Write as _;
146
147    if let Some(configured) = &config.api_credential {
148        return Ok(configured.clone());
149    }
150    let path = config.state_dir.join(API_CREDENTIAL_FILE);
151    let refusing = |detail: String| StartError::Credential {
152        path: path.clone(),
153        detail,
154    };
155    let mut options = std::fs::OpenOptions::new();
156    options.write(true).create_new(true);
157    #[cfg(unix)]
158    std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
159    match options.open(&path) {
160        Ok(mut file) => {
161            let generated = ApiCredential::generate().map_err(|error| {
162                refusing(format!(
163                    "no credential could be generated for it, because the operating system's \
164                     random source refused: {error}"
165                ))
166            });
167            let written = generated.and_then(|credential| {
168                file.write_all(credential.written().as_bytes())
169                    .and_then(|()| file.sync_all())
170                    .map(|()| credential)
171                    .map_err(|error| refusing(format!("it could not be written: {error}")))
172            });
173            if written.is_err() {
174                // The file is this start's own and holds nothing usable, so it
175                // is taken back rather than left for the next start to refuse.
176                let _ = std::fs::remove_file(&path);
177            }
178            written
179        }
180        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
181            // llmlint: ignore[least_privilege_grants] The contract reuses an existing credential file's contents unchanged and never rewrites a file this start did not write, so the server does not change a hand-provisioned file's mode. The installed path keeps the file private by its directory: the installer creates the state directory at mode 0700, owned by the service user, and a file this server generates is created 0600. A mode check on hand-provisioned files is recorded as a follow-up.
182            let held = std::fs::read(&path)
183                .map_err(|error| refusing(format!("it cannot be read: {error}")))?;
184            let text = core::str::from_utf8(&held).ok().map(without_terminator);
185            text.ok_or("it is not text")
186                .and_then(ApiCredential::new)
187                .map_err(|why| {
188                    refusing(format!(
189                        "{why}. This server does not replace a credential it did not write \
190                         just now: correct the file, or remove it to have a new one generated"
191                    ))
192                })
193        }
194        Err(error) => Err(refusing(format!("it cannot be created: {error}"))),
195    }
196}
197
198/// A credential file's text with the one line terminator a person's editor or
199/// shell ends it with set aside.
200///
201/// Exactly one, `\n` or `\r\n`: that terminator is not part of the credential,
202/// and anything else in the text — a second one included — is left for the
203/// character rule to refuse.
204fn without_terminator(text: &str) -> &str {
205    text.strip_suffix("\r\n")
206        .or_else(|| text.strip_suffix('\n'))
207        .unwrap_or(text)
208}
209
210/// The file name the agent's prompt template is materialized under.
211pub const PROMPT_FILE: &str = "turn-prompt.md";
212
213/// The file name the assessment schema is materialized under.
214pub const SCHEMA_FILE: &str = "assessment-schema.json";
215
216/// The prompt template this program carries and materializes.
217///
218/// The adapter's own committed asset rather than a copy of it, so what an
219/// installed program fills a turn with and what `just check-repo` reads are one
220/// file.
221pub const TURN_PROMPT: &str = printobserver_oneharness::DEFAULT_TURN_PROMPT;
222
223/// The four implementations one running server was composed from.
224///
225/// A tier that stands in for a machine hands these in; [`Server::start`] builds
226/// them from the configuration.
227pub struct Ports {
228    /// The printer.
229    pub printer: Arc<dyn PrinterPort>,
230    /// Durable state, one handle per aggregate onto one store.
231    pub stores: Stores,
232    /// External observations, and the snapshot fetch.
233    pub vision: Arc<ObicoVision>,
234    /// The supervising agent's harness.
235    pub agent: Arc<dyn SupervisorPort>,
236}
237
238impl core::fmt::Debug for Ports {
239    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
240        formatter.debug_struct("Ports").finish_non_exhaustive()
241    }
242}
243
244/// Why this server did not start.
245#[derive(Debug)]
246pub enum StartError {
247    /// The configuration will not do, naming the field that will not.
248    Configuration(ConfigError),
249    /// The state directory could not be prepared.
250    State {
251        /// What went wrong.
252        detail: String,
253    },
254    /// The API credential file in the state directory cannot be used.
255    Credential {
256        /// The file.
257        path: PathBuf,
258        /// Why it cannot be used, in words that never quote what it holds.
259        detail: String,
260    },
261    /// The address could not be listened on.
262    Listen {
263        /// The address that was asked for.
264        address: SocketAddr,
265        /// What went wrong.
266        detail: String,
267    },
268    /// The store could not be opened.
269    Store {
270        /// What the store said.
271        detail: String,
272    },
273    /// The supervising agent's harness could not be reached at all.
274    Supervisor {
275        /// What the harness said.
276        detail: String,
277    },
278    /// Reconciling what the store held failed.
279    Reconciliation {
280        /// What went wrong.
281        detail: String,
282    },
283}
284
285impl StartError {
286    /// The configuration field this refusal is about, when it is about one.
287    #[must_use]
288    pub const fn field(&self) -> Option<ConfigField> {
289        match self {
290            Self::Configuration(error) => error.field(),
291            _ => None,
292        }
293    }
294}
295
296impl core::fmt::Display for StartError {
297    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
298        match self {
299            Self::Configuration(error) => write!(formatter, "{error}"),
300            Self::State { detail } => {
301                write!(
302                    formatter,
303                    "the state directory could not be prepared: {detail}"
304                )
305            }
306            Self::Credential { path, detail } => write!(
307                formatter,
308                "the API credential file {} cannot be used: {detail}",
309                path.display()
310            ),
311            Self::Listen { address, detail } => {
312                write!(formatter, "{address} could not be listened on: {detail}")
313            }
314            Self::Store { detail } => write!(formatter, "the store could not be opened: {detail}"),
315            Self::Supervisor { detail } => write!(
316                formatter,
317                "the supervising agent's harness could not be reached: {detail}"
318            ),
319            Self::Reconciliation { detail } => write!(
320                formatter,
321                "what the store held could not be reconciled: {detail}"
322            ),
323        }
324    }
325}
326
327impl core::error::Error for StartError {}
328
329impl From<ConfigError> for StartError {
330    fn from(error: ConfigError) -> Self {
331        Self::Configuration(error)
332    }
333}
334
335/// The composition root.
336#[derive(Debug)]
337pub struct Server;
338
339impl Server {
340    /// Read one configuration file, compose the four implementations, and serve.
341    ///
342    /// # Errors
343    ///
344    /// Returns [`StartError::Configuration`] naming the field that will not do
345    /// — including the two only the machine can rule on, an `OctoPrint` address
346    /// nothing answers at and a key that instance refuses — and the other
347    /// variants for a host that will not let this server come up.
348    pub async fn start(config_path: impl AsRef<Path>) -> Result<Running, StartError> {
349        let config = ServerConfig::load(config_path)?;
350        let stores = Stores::of(Arc::new(SqliteStore::open(&config.state_dir).map_err(
351            |error| StartError::Store {
352                detail: error.to_string(),
353            },
354        )?));
355        let printer = Arc::new(OctoPrintPrinter::new(config.octoprint.clone()));
356        probe(printer.as_ref()).await?;
357        let vision = Arc::new(
358            ObicoVision::new(ObicoVisionConfig::default()).map_err(|error| StartError::State {
359                detail: error.to_string(),
360            })?,
361        );
362        let agent = Arc::new(agent_for(&config)?);
363        Self::start_with(
364            config,
365            Ports {
366                printer,
367                stores,
368                vision,
369                agent,
370            },
371        )
372        .await
373    }
374
375    /// Serve over ports a caller composed.
376    ///
377    /// # Errors
378    ///
379    /// The same as [`Server::start`], less the refusals that belong to building
380    /// the implementations.
381    pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
382        // The credential is settled before anything listens, so there is no
383        // moment at which this server answers a request it has nothing to
384        // check against.
385        let credential = credential_in_force(&config)?;
386        // The listener is taken next, because the command a supervision turn
387        // runs to read its context names the address this server is answering
388        // on — and a configuration may ask for any free port.
389        let listener =
390            TcpListener::bind(config.listen)
391                .await
392                .map_err(|error| StartError::Listen {
393                    address: config.listen,
394                    detail: error.to_string(),
395                })?;
396        let address = listener.local_addr().map_err(|error| StartError::Listen {
397            address: config.listen,
398            detail: error.to_string(),
399        })?;
400        let client_config = write_client_config(&config.state_dir, address, &credential)?;
401        let clock = Arc::new(SystemClock);
402        let due = overdue(&ports.stores.actions, clock.now())
403            .await
404            .map_err(|error| StartError::Reconciliation {
405                detail: error.to_string(),
406            })?;
407        let supervisor = Supervisor::new(
408            CoreConfig::new(config.safety.clone(), context_command(&client_config)),
409            Arc::clone(&ports.printer),
410            ports.stores.clone(),
411            Arc::clone(&ports.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
412            Arc::clone(&ports.agent),
413            clock,
414        );
415        let reconciliation = reconcile(
416            &supervisor,
417            &ReconcileStores {
418                prints: Arc::clone(&ports.stores.prints),
419                sessions: Arc::clone(&ports.stores.sessions),
420                events: Arc::clone(&ports.stores.events),
421            },
422            due,
423        )
424        .await
425        .map_err(|error| StartError::Reconciliation {
426            detail: error.to_string(),
427        })?;
428
429        let ingress = IngressState::start(
430            Arc::clone(&supervisor),
431            Arc::clone(&ports.stores.events),
432            Arc::clone(&ports.vision),
433            config.ingress_shared_secret.clone(),
434            config.ingress_answer_bound,
435        );
436        let completions = ingress.completions();
437        let application = router(ApiState {
438            supervisor: Arc::clone(&supervisor),
439            prints: Arc::clone(&ports.stores.prints),
440            events: Arc::clone(&ports.stores.events),
441            images: Arc::clone(&ports.stores.images),
442            sessions: Arc::clone(&ports.stores.sessions),
443            credential: Arc::new(credential),
444        })
445        .merge(
446            Router::new()
447                .route(INGRESS_PATH, post(receive))
448                .with_state(ingress),
449        );
450
451        let (stop, stopped) = oneshot::channel::<()>();
452        let serving = tokio::spawn(async move {
453            let _ = axum::serve(listener, application)
454                .with_graceful_shutdown(async move {
455                    let _ = stopped.await;
456                })
457                .await;
458        });
459        Ok(Running {
460            address,
461            config,
462            supervisor,
463            stores: ports.stores,
464            reconciliation,
465            completions,
466            stop: Some(stop),
467            serving,
468        })
469    }
470}
471
472/// Ask the machine whether the address and the key are the ones it answers to.
473///
474/// Only the two answers that are *about the configuration* refuse a start. A
475/// printer that is off, in an error state, or answering something this adapter
476/// cannot read is a machine having a bad day rather than a file with the wrong
477/// value in it, and a supervisor that would not come up for one of those could
478/// not be used to find out why.
479async fn probe(printer: &dyn PrinterPort) -> Result<(), StartError> {
480    match printer.snapshot().await {
481        Err(PrinterError::Unreachable { detail }) => {
482            Err(StartError::Configuration(ConfigError::about(
483                ConfigField::OctoprintUrl,
484                format!("nothing answers there: {detail}"),
485            )))
486        }
487        Err(PrinterError::Unauthorized { detail }) => {
488            Err(StartError::Configuration(ConfigError::about(
489                ConfigField::OctoprintApiKey,
490                format!("the OctoPrint instance refused it: {detail}"),
491            )))
492        }
493        _ => Ok(()),
494    }
495}
496
497/// Write one of the agent's committed assets into the state directory.
498///
499/// The port reads its template and its schema from paths, so that editing one
500/// on a running host is a restart rather than a rebuild. An installed program
501/// has no checkout to read them out of, so the bytes it carries are written
502/// here — and an operator who configured a template of their own is pointed at
503/// theirs instead.
504fn materialize(
505    directory: &Path,
506    name: &str,
507    contents: &str,
508) -> Result<std::path::PathBuf, StartError> {
509    let path = directory.join(name);
510    std::fs::write(&path, contents).map_err(|error| StartError::State {
511        detail: format!("{} could not be written: {error}", path.display()),
512    })?;
513    Ok(path)
514}
515
516/// The directory the harness runs in: the one holding the configured skill.
517///
518/// An installed skill is a directory — its `SKILL.md` and the `reference/`
519/// documents that file links to by relative paths — so the agent stands where
520/// those links resolve. A skill named by a bare file name sits in this
521/// process's own working directory.
522fn beside_the_skill(skill_path: &Path) -> std::path::PathBuf {
523    match skill_path.parent() {
524        Some(directory) if !directory.as_os_str().is_empty() => directory.to_path_buf(),
525        _ => std::path::PathBuf::from("."),
526    }
527}
528
529/// The supervising agent's harness, over the configured skill and the assets
530/// this program carries.
531fn agent_for(config: &ServerConfig) -> Result<OneharnessSupervisor, StartError> {
532    OneharnessSupervisor::open(agent_config(config)?).map_err(|error| StartError::Supervisor {
533        detail: error.to_string(),
534    })
535}
536
537/// The supervising agent's configuration, as [`Server::start`] composes it.
538///
539/// The template and the assessment schema are written into the assets
540/// directory; the skill is the installed one `supervisor.skill_path` names, and
541/// every turn runs in the directory holding it — where an installed skill's
542/// `reference/` documents sit, so the links the skill carries resolve from
543/// where the agent stands. The harness is the one `supervisor.harness` names,
544/// found by name, and a harness this program can sign in is pointed at the
545/// sign-in kept under the state directory.
546///
547/// # Errors
548///
549/// Returns [`StartError::State`] when the assets or the sign-in directory
550/// cannot be written, and [`StartError::Supervisor`] when the schema it wrote
551/// constrains nothing.
552pub fn agent_config(config: &ServerConfig) -> Result<SupervisorConfig, StartError> {
553    let assets = config.assets_dir();
554    std::fs::create_dir_all(&assets).map_err(|error| StartError::State {
555        detail: format!("{} could not be created: {error}", assets.display()),
556    })?;
557    let prompt_template_path = match &config.prompt_template_path {
558        Some(path) => path.clone(),
559        None => materialize(&assets, PROMPT_FILE, TURN_PROMPT)?,
560    };
561    let schema_path = materialize(
562        &assets,
563        SCHEMA_FILE,
564        &printobserver_types::serde_json::to_string_pretty(
565            &printobserver_types::contract::schema_of::<
566                printobserver_supervisor_api::AgentAssessment,
567            >(),
568        )
569        .map_err(|error| StartError::State {
570            detail: error.to_string(),
571        })?,
572    )?;
573    let assessment_schema =
574        AssessmentSchema::at(&schema_path).map_err(|error| StartError::Supervisor {
575            detail: error.to_string(),
576        })?;
577    // A harness this program can sign in keeps that sign-in under the state
578    // directory — the one place the service's unit lets it write — and every
579    // turn is pointed at the directory `printobserver sign-in` wrote it to. A
580    // harness outside the table is handed nothing extra.
581    let harness_env = match HarnessSignIn::of(&config.harness) {
582        Some(sign_in) => {
583            let directory =
584                sign_in
585                    .prepare(&config.state_dir)
586                    .map_err(|error| StartError::State {
587                        detail: format!(
588                            "{} could not be created: {error}",
589                            sign_in.directory(&config.state_dir).display()
590                        ),
591                    })?;
592            vec![
593                sign_in
594                    .assignment(&directory)
595                    .map_err(|error| StartError::Supervisor {
596                        detail: error.to_string(),
597                    })?,
598            ]
599        }
600        None => Vec::new(),
601    };
602    Ok(SupervisorConfig {
603        state_dir: config.state_dir.clone(),
604        skill_path: config.skill_path.clone(),
605        prompt_template_path,
606        assessment_schema,
607        harness: config.harness.clone(),
608        model: config.model.clone(),
609        // The skill's own directory rather than the state or assets directory,
610        // so that the skill's relative links to the reference documents beside
611        // it resolve from where the agent is standing as well as from the skill.
612        working_dir: beside_the_skill(&config.skill_path),
613        turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
614        harness_bin: None,
615        harness_env,
616    })
617}
618
619/// One server, serving.
620///
621/// Dropping this stops it, and so does [`Running::stop`]; nothing here outlives
622/// the handle a caller holds.
623pub struct Running {
624    /// Where it is answering.
625    address: SocketAddr,
626    /// What it was configured with.
627    config: ServerConfig,
628    /// The supervision core.
629    supervisor: Arc<Supervisor>,
630    /// Durable state, one handle per aggregate.
631    stores: Stores,
632    /// What this start adopted.
633    reconciliation: Reconciliation,
634    /// How many posts the ingress worker has finished handling.
635    completions: watch::Receiver<u64>,
636    /// The graceful-shutdown signal, taken when it is sent.
637    stop: Option<oneshot::Sender<()>>,
638    /// The task serving requests.
639    serving: JoinHandle<()>,
640}
641
642impl core::fmt::Debug for Running {
643    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
644        formatter
645            .debug_struct("Running")
646            .field("address", &self.address)
647            .field("reconciliation", &self.reconciliation)
648            .finish_non_exhaustive()
649    }
650}
651
652impl Running {
653    /// Where this server is answering.
654    #[must_use]
655    pub const fn address(&self) -> SocketAddr {
656        self.address
657    }
658
659    /// The base URL of its versioned surface.
660    #[must_use]
661    pub fn base_url(&self) -> String {
662        format!(
663            "http://{}{}",
664            self.address,
665            crate::operations::VERSION_PREFIX
666        )
667    }
668
669    /// The URL its ingress endpoint answers on.
670    #[must_use]
671    pub fn ingress_url(&self) -> String {
672        format!("http://{}{INGRESS_PATH}", self.address)
673    }
674
675    /// What it was configured with.
676    #[must_use]
677    pub const fn config(&self) -> &ServerConfig {
678        &self.config
679    }
680
681    /// What this start adopted from the store.
682    #[must_use]
683    pub const fn reconciliation(&self) -> &Reconciliation {
684        &self.reconciliation
685    }
686
687    /// The supervision core it is serving over.
688    #[must_use]
689    pub const fn supervisor(&self) -> &Arc<Supervisor> {
690        &self.supervisor
691    }
692
693    /// Durable state, as it is serving over it.
694    #[must_use]
695    pub const fn stores(&self) -> &Stores {
696        &self.stores
697    }
698
699    /// How many posts the ingress worker has finished handling, watchable while
700    /// it works.
701    #[must_use]
702    pub fn completions(&self) -> watch::Receiver<u64> {
703        self.completions.clone()
704    }
705
706    /// Stop serving, and wait for the last request to finish.
707    pub async fn stop(mut self) {
708        if let Some(stop) = self.stop.take() {
709            let _ = stop.send(());
710        }
711        let _ = (&mut self.serving).await;
712    }
713
714    /// Serve until the operating system asks this process to stop.
715    ///
716    /// This is what the `server` subcommand runs. It answers however this
717    /// platform asks a process to stop — see [`stop_requested`] — and every one
718    /// of those ways enters the same shutdown: [`Running::stop`].
719    ///
720    /// # Errors
721    ///
722    /// Returns [`StartError::State`] when the stop handlers cannot be
723    /// installed, which is a process that could not be stopped cleanly.
724    pub async fn serve_until_signalled(self) -> Result<(), StartError> {
725        stop_requested().await?;
726        self.stop().await;
727        Ok(())
728    }
729}
730
731/// A stop handler that could not be installed, naming which.
732fn unhandled(what: &str, error: &std::io::Error) -> StartError {
733    StartError::State {
734        detail: format!("{what} cannot be handled: {error}"),
735    }
736}
737
738/// Wait until the operating system asks this process to stop.
739///
740/// On Unix that is the signal a service manager stops a unit with, or the
741/// interrupt from the terminal that started it.
742#[cfg(unix)]
743async fn stop_requested() -> Result<(), StartError> {
744    use tokio::signal::unix::{SignalKind, signal};
745
746    let mut terminate = signal(SignalKind::terminate())
747        .map_err(|error| unhandled("the termination signal", &error))?;
748    let mut interrupt = signal(SignalKind::interrupt())
749        .map_err(|error| unhandled("the interrupt signal", &error))?;
750    tokio::select! {
751        _ = terminate.recv() => {}
752        _ = interrupt.recv() => {}
753    }
754    Ok(())
755}
756
757/// Wait until the operating system asks this process to stop.
758///
759/// Windows has no signals: a console process is stopped by a console control
760/// event. `CTRL_C` and `CTRL_BREAK` are the terminal's interrupt — the second is
761/// the one another process can send a process group started apart from its own
762/// — and `CTRL_CLOSE` and `CTRL_SHUTDOWN` are the console closing and the
763/// machine shutting down.
764#[cfg(windows)]
765async fn stop_requested() -> Result<(), StartError> {
766    use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close, ctrl_shutdown};
767
768    let mut interrupt = ctrl_c().map_err(|error| unhandled("the CTRL_C event", &error))?;
769    let mut breaking = ctrl_break().map_err(|error| unhandled("the CTRL_BREAK event", &error))?;
770    let mut closing = ctrl_close().map_err(|error| unhandled("the CTRL_CLOSE event", &error))?;
771    let mut shutting_down =
772        ctrl_shutdown().map_err(|error| unhandled("the CTRL_SHUTDOWN event", &error))?;
773    tokio::select! {
774        _ = interrupt.recv() => {}
775        _ = breaking.recv() => {}
776        _ = closing.recv() => {}
777        _ = shutting_down.recv() => {}
778    }
779    Ok(())
780}
781
782impl Drop for Running {
783    fn drop(&mut self) {
784        if let Some(stop) = self.stop.take() {
785            let _ = stop.send(());
786        }
787        self.serving.abort();
788    }
789}