1use 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
48pub const CONTEXT_PROGRAM: &str = "printobserver";
50
51pub const CLIENT_CONFIG_FILE: &str = "client.toml";
56
57pub const API_CREDENTIAL_FILE: &str = "api-credential";
62
63pub const API_CREDENTIAL_VERIFIER_FILE: &str = "api-credential.verifier";
66
67pub const CREDENTIAL_ISSUE: &str = "printobserver credential issue";
70
71pub const CREDENTIAL_VERIFIER: &str = "printobserver credential verifier";
74
75#[cfg(unix)]
81const PRIVATE: u32 = 0o600;
82
83#[must_use]
92pub fn context_command() -> String {
93 format!("{CONTEXT_PROGRAM} context --print-id {{print_id}}")
94}
95
96#[derive(Debug, Clone)]
98pub enum OperatorCredential {
99 Verifier(CredentialVerifier),
101 Plaintext(ApiCredential),
104 Unconfigured,
107}
108
109impl OperatorCredential {
110 #[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#[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
136fn 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 let written = file.write_all(contents).and_then(|()| file.sync_all());
147 if written.is_err() {
148 let _ = std::fs::remove_file(path);
151 }
152 written
153}
154
155fn 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
163fn 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
225pub 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
276fn without_terminator(text: &str) -> &str {
283 text.strip_suffix("\r\n")
284 .or_else(|| text.strip_suffix('\n'))
285 .unwrap_or(text)
286}
287
288pub const PROMPT_FILE: &str = "turn-prompt.md";
290
291pub const SCHEMA_FILE: &str = "assessment-schema.json";
293
294pub const TURN_PROMPT: &str = printobserver_oneharness::DEFAULT_TURN_PROMPT;
300
301pub struct Ports {
306 pub printer: Arc<dyn PrinterPort>,
308 pub stores: Stores,
310 pub vision: Arc<ObicoVision>,
312 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#[derive(Debug)]
324pub enum StartError {
325 Configuration(ConfigError),
327 State {
329 detail: String,
331 },
332 Credential {
334 path: PathBuf,
336 detail: String,
338 },
339 Listen {
341 address: SocketAddr,
343 detail: String,
345 },
346 Store {
348 detail: String,
350 },
351 Supervisor {
353 detail: String,
355 },
356 Reconciliation {
358 detail: String,
360 },
361}
362
363impl StartError {
364 #[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#[derive(Debug)]
415pub struct Server;
416
417async 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 pub async fn start(config_path: impl AsRef<Path>) -> Result<Running, StartError> {
439 Self::start_with_usage(config_path, &[]).await
440 }
441
442 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 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 pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
495 let (operator, warnings) = operator_credential(&config)?;
500 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 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 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
610fn 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
634async fn sweep_left_behind(
638 supervisor: &Supervisor,
639 alignments: &crate::alignment::Alignments,
640) -> Result<(), StartError> {
641 let reconciling = |error: printobserver_core::CoreError| StartError::Reconciliation {
642 detail: error.to_string(),
643 };
644 supervisor.sweep_gcode_spools().await.map_err(reconciling)?;
645 alignments.sweep().await;
646 supervisor
647 .restore_planned_changes()
648 .await
649 .map_err(reconciling)
650}
651
652#[must_use]
654pub fn gcode_spool_dir(state_dir: &Path) -> std::path::PathBuf {
655 state_dir.join("gcode-spool")
656}
657
658fn core_config_of(config: &ServerConfig) -> CoreConfig {
660 let mut core_config = CoreConfig::new(config.safety.clone(), context_command());
661 core_config.gcode_spool_dir = Some(gcode_spool_dir(&config.state_dir));
662 core_config
663 .camera_snapshot_url
664 .clone_from(&config.camera_snapshot_url);
665 core_config.observation_interval = config.observation_interval;
666 core_config.printer_poll = config.printer_poll;
667 core_config.unattended_window = config.unattended_window;
668 core_config.spools = config.spools;
669 core_config.sheets.clone_from(&config.sheets);
670 core_config.recovery = config.recovery;
671 core_config
672 .recovery_grants
673 .clone_from(&config.recovery_grants);
674 core_config
675}
676
677fn scoring_read(
681 config: &ServerConfig,
682 vision: &ObicoVision,
683) -> Result<Option<Arc<dyn printobserver_core::ScoringProbe>>, StartError> {
684 config
685 .obico_api
686 .clone()
687 .map(|api| {
688 ObicoScoring::new(api, config.obico_printer_id, vision.known_printer())
689 .map(|scoring| Arc::new(scoring) as Arc<dyn printobserver_core::ScoringProbe>)
690 .map_err(|error| StartError::State {
691 detail: error.to_string(),
692 })
693 })
694 .transpose()
695}
696
697fn detector_check(
699 config: &ServerConfig,
700) -> Result<Option<Arc<dyn printobserver_core::DetectorProbe>>, StartError> {
701 config
702 .obico_ml_api_url
703 .as_ref()
704 .map(|url| {
705 DetectorHealthCheck::new(url)
706 .map(|check| Arc::new(check) as Arc<dyn printobserver_core::DetectorProbe>)
707 .map_err(|detail| StartError::State { detail })
708 })
709 .transpose()
710}
711
712async fn probe(printer: &dyn PrinterPort) -> Result<(), StartError> {
720 match printer.snapshot().await {
721 Err(PrinterError::Unreachable { detail }) => {
722 Err(StartError::Configuration(ConfigError::about(
723 ConfigField::OctoprintUrl,
724 format!("nothing answers there: {detail}"),
725 )))
726 }
727 Err(PrinterError::Unauthorized { detail }) => {
728 Err(StartError::Configuration(ConfigError::about(
729 ConfigField::OctoprintApiKey,
730 format!("the OctoPrint instance refused it: {detail}"),
731 )))
732 }
733 _ => Ok(()),
734 }
735}
736
737fn materialize(
745 directory: &Path,
746 name: &str,
747 contents: &str,
748) -> Result<std::path::PathBuf, StartError> {
749 let path = directory.join(name);
750 std::fs::write(&path, contents).map_err(|error| StartError::State {
751 detail: format!("{} could not be written: {error}", path.display()),
752 })?;
753 Ok(path)
754}
755
756fn beside_the_skill(skill_path: &Path) -> std::path::PathBuf {
763 match skill_path.parent() {
764 Some(directory) if !directory.as_os_str().is_empty() => directory.to_path_buf(),
765 _ => std::path::PathBuf::from("."),
766 }
767}
768
769fn agent_for(
772 config: &ServerConfig,
773 command_usage: &[String],
774) -> Result<OneharnessSupervisor, StartError> {
775 OneharnessSupervisor::open(agent_config_with(config, command_usage)?).map_err(|error| {
776 StartError::Supervisor {
777 detail: error.to_string(),
778 }
779 })
780}
781
782pub const TURN_READS: [&str; 2] = ["context", "look"];
785
786pub fn agent_config_with(
796 config: &ServerConfig,
797 command_usage: &[String],
798) -> Result<SupervisorConfig, StartError> {
799 let mut composed = agent_config(config)?;
800 let granted = config
801 .safety
802 .actions
803 .get(&printobserver_core::ActorClass::Agent)
804 .into_iter()
805 .flatten()
806 .filter_map(|kind| {
807 printobserver_types::serde_json::to_value(kind)
808 .ok()
809 .and_then(|named| named.as_str().map(command_for))
810 });
811 let handed: Vec<String> = TURN_READS
812 .iter()
813 .map(|read| command_for(read))
814 .chain(granted)
815 .map(|command| format!("printobserver {command}"))
816 .collect();
817 composed.command_usage = command_usage
818 .iter()
819 .filter(|line| {
820 handed
821 .iter()
822 .any(|command| line == &command || line.starts_with(&format!("{command} ")))
823 })
824 .cloned()
825 .collect();
826 Ok(composed)
827}
828
829pub fn agent_config(config: &ServerConfig) -> Result<SupervisorConfig, StartError> {
845 let assets = config.assets_dir();
846 std::fs::create_dir_all(&assets).map_err(|error| StartError::State {
847 detail: format!("{} could not be created: {error}", assets.display()),
848 })?;
849 let prompt_template_path = match &config.prompt_template_path {
850 Some(path) => path.clone(),
851 None => materialize(&assets, PROMPT_FILE, TURN_PROMPT)?,
852 };
853 let schema_path =
854 materialize(
855 &assets,
856 SCHEMA_FILE,
857 &printobserver_types::serde_json::to_string_pretty(&AssessmentSchema::as_handed(
858 printobserver_types::contract::schema_of::<
859 printobserver_supervisor_api::AgentAssessment,
860 >(),
861 ))
862 .map_err(|error| StartError::State {
863 detail: error.to_string(),
864 })?,
865 )?;
866 let assessment_schema =
867 AssessmentSchema::at(&schema_path).map_err(|error| StartError::Supervisor {
868 detail: error.to_string(),
869 })?;
870 let mut harness_env = match HarnessSignIn::of(&config.harness) {
875 Some(sign_in) => {
876 let directory =
877 sign_in
878 .prepare(&config.state_dir)
879 .map_err(|error| StartError::State {
880 detail: format!(
881 "{} could not be created: {error}",
882 sign_in.directory(&config.state_dir).display()
883 ),
884 })?;
885 let refused = |error: printobserver_oneharness::ConfigError| StartError::Supervisor {
886 detail: error.to_string(),
887 };
888 let mut assigned = vec![sign_in.assignment(&directory).map_err(refused)?];
889 assigned.extend(sign_in.session_assignments().map_err(refused)?);
891 assigned
892 }
893 None => Vec::new(),
894 };
895 let search_path = std::env::var_os("PATH").unwrap_or_default();
896 harness_env.extend(path_led_by_this_program(&search_path)?);
897 Ok(SupervisorConfig {
898 state_dir: config.state_dir.clone(),
899 skill_path: config.skill_path.clone(),
900 prompt_template_path,
901 assessment_schema,
902 harness: config.harness.clone(),
903 model: config.model.clone(),
904 working_dir: beside_the_skill(&config.skill_path),
908 turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
909 harness_bin: HarnessSignIn::of(&config.harness)
913 .and_then(|harness| harness.program_behind_launcher(&search_path)),
914 harness_env,
915 agent_commands: agent_commands()?,
916 withheld_beside_an_image: withheld_beside_an_image()?,
917 command_usage: Vec::new(),
918 auto_compact_tokens: config.auto_compact_tokens,
919 idle_compact_tokens: config.idle_compact_tokens,
920 })
921}
922
923fn agent_commands() -> Result<Vec<AgentCommand>, StartError> {
933 OPERATIONS
934 .iter()
935 .filter(|operation| crate::operations::printer_wide_of(operation.name).is_none())
936 .map(|operation| {
937 AgentCommand::new(&format!(
938 "{CONTEXT_PROGRAM} {}",
939 command_for(operation.name)
940 ))
941 })
942 .collect::<Result<_, _>>()
943 .map_err(|error| StartError::Supervisor {
944 detail: error.to_string(),
945 })
946}
947
948pub const WITHHELD_BESIDE_AN_IMAGE: [&str; 1] = ["look"];
955
956fn withheld_beside_an_image() -> Result<Vec<AgentCommand>, StartError> {
958 WITHHELD_BESIDE_AN_IMAGE
959 .iter()
960 .map(|read| AgentCommand::new(&format!("{CONTEXT_PROGRAM} {}", command_for(read))))
961 .collect::<Result<_, _>>()
962 .map_err(|error| StartError::Supervisor {
963 detail: error.to_string(),
964 })
965}
966
967fn path_led_by_this_program(inherited: &OsStr) -> Result<Option<EnvAssignment>, StartError> {
980 let Some(directory) = std::env::current_exe()
981 .ok()
982 .and_then(|program| program.parent().map(Path::to_path_buf))
983 else {
984 return Ok(None);
985 };
986 let refused = |detail: String| StartError::Supervisor {
987 detail: format!(
988 "a turn's PATH cannot lead with {}: {detail}",
989 directory.display()
990 ),
991 };
992 let joined = std::env::join_paths(
993 std::iter::once(directory.clone()).chain(std::env::split_paths(inherited)),
994 )
995 .map_err(|error| refused(error.to_string()))?;
996 let joined = joined
997 .to_str()
998 .ok_or_else(|| refused("it is not valid Unicode".to_owned()))?;
999 EnvAssignment::new(&format!("PATH={joined}"))
1000 .map(Some)
1001 .map_err(|error| refused(error.to_string()))
1002}
1003
1004pub struct Running {
1009 address: SocketAddr,
1011 config: ServerConfig,
1013 warnings: Vec<String>,
1016 supervisor: Arc<Supervisor>,
1018 stores: Stores,
1020 reconciliation: Reconciliation,
1022 completions: watch::Receiver<u64>,
1024 stop: Option<oneshot::Sender<()>>,
1026 serving: JoinHandle<()>,
1028 observing: JoinHandle<()>,
1030 watching: crate::watch::Watching,
1033 alignments: Arc<crate::alignment::Alignments>,
1035}
1036
1037impl core::fmt::Debug for Running {
1038 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1039 formatter
1040 .debug_struct("Running")
1041 .field("address", &self.address)
1042 .field("reconciliation", &self.reconciliation)
1043 .finish_non_exhaustive()
1044 }
1045}
1046
1047impl Running {
1048 #[must_use]
1051 pub fn print_alignment(
1052 &self,
1053 print_id: printobserver_types::PrintId,
1054 ) -> crate::alignment::PrintAlignment {
1055 self.alignments.print_alignment(print_id)
1056 }
1057
1058 #[must_use]
1060 pub const fn address(&self) -> SocketAddr {
1061 self.address
1062 }
1063
1064 #[must_use]
1066 pub fn base_url(&self) -> String {
1067 format!(
1068 "http://{}{}",
1069 self.address,
1070 crate::operations::VERSION_PREFIX
1071 )
1072 }
1073
1074 #[must_use]
1076 pub fn ingress_url(&self) -> String {
1077 format!("http://{}{INGRESS_PATH}", self.address)
1078 }
1079
1080 #[must_use]
1082 pub const fn config(&self) -> &ServerConfig {
1083 &self.config
1084 }
1085
1086 #[must_use]
1090 pub fn warnings(&self) -> &[String] {
1091 &self.warnings
1092 }
1093
1094 #[must_use]
1096 pub const fn reconciliation(&self) -> &Reconciliation {
1097 &self.reconciliation
1098 }
1099
1100 #[must_use]
1102 pub const fn supervisor(&self) -> &Arc<Supervisor> {
1103 &self.supervisor
1104 }
1105
1106 #[must_use]
1108 pub const fn stores(&self) -> &Stores {
1109 &self.stores
1110 }
1111
1112 #[must_use]
1115 pub fn completions(&self) -> watch::Receiver<u64> {
1116 self.completions.clone()
1117 }
1118
1119 pub async fn stop(mut self) {
1121 if let Some(stop) = self.stop.take() {
1122 let _ = stop.send(());
1123 }
1124 self.observing.abort();
1125 self.watching.abort();
1126 let _ = (&mut self.serving).await;
1127 }
1128
1129 pub async fn serve_until_signalled(self) -> Result<(), StartError> {
1140 stop_requested().await?;
1141 self.stop().await;
1142 Ok(())
1143 }
1144}
1145
1146fn unhandled(what: &str, error: &std::io::Error) -> StartError {
1148 StartError::State {
1149 detail: format!("{what} cannot be handled: {error}"),
1150 }
1151}
1152
1153#[cfg(unix)]
1158async fn stop_requested() -> Result<(), StartError> {
1159 use tokio::signal::unix::{SignalKind, signal};
1160
1161 let mut terminate = signal(SignalKind::terminate())
1162 .map_err(|error| unhandled("the termination signal", &error))?;
1163 let mut interrupt = signal(SignalKind::interrupt())
1164 .map_err(|error| unhandled("the interrupt signal", &error))?;
1165 tokio::select! {
1166 _ = terminate.recv() => {}
1167 _ = interrupt.recv() => {}
1168 }
1169 Ok(())
1170}
1171
1172#[cfg(windows)]
1180async fn stop_requested() -> Result<(), StartError> {
1181 use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close, ctrl_shutdown};
1182
1183 let mut interrupt = ctrl_c().map_err(|error| unhandled("the CTRL_C event", &error))?;
1184 let mut breaking = ctrl_break().map_err(|error| unhandled("the CTRL_BREAK event", &error))?;
1185 let mut closing = ctrl_close().map_err(|error| unhandled("the CTRL_CLOSE event", &error))?;
1186 let mut shutting_down =
1187 ctrl_shutdown().map_err(|error| unhandled("the CTRL_SHUTDOWN event", &error))?;
1188 tokio::select! {
1189 _ = interrupt.recv() => {}
1190 _ = breaking.recv() => {}
1191 _ = closing.recv() => {}
1192 _ = shutting_down.recv() => {}
1193 }
1194 Ok(())
1195}
1196
1197impl Drop for Running {
1198 fn drop(&mut self) {
1199 if let Some(stop) = self.stop.take() {
1200 let _ = stop.send(());
1201 }
1202 self.serving.abort();
1203 }
1204}