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 let check_images = panel_images(&config, &alignments);
524 supervisor.install_check_images(
525 Arc::clone(&check_images) as Arc<dyn printobserver_core::CheckImages>
526 );
527 if let Some(scoring) = scoring_read(&config, &ports.vision)? {
528 supervisor.install_scoring_probe(scoring);
529 }
530 let reconciliation = reconcile(
531 &supervisor,
532 &ReconcileStores {
533 prints: Arc::clone(&ports.stores.prints),
534 sessions: Arc::clone(&ports.stores.sessions),
535 events: Arc::clone(&ports.stores.events),
536 },
537 due,
538 )
539 .await
540 .map_err(|error| StartError::Reconciliation {
541 detail: error.to_string(),
542 })?;
543 Box::pin(sweep_left_behind(&supervisor, &alignments)).await?;
544
545 let ingress = IngressState::start(
546 Arc::clone(&supervisor),
547 Arc::clone(&ports.stores.events),
548 Arc::clone(&ports.vision),
549 config.ingress_shared_secret.clone(),
550 config.ingress_answer_bound,
551 );
552 let completions = ingress.completions();
553 let observing = crate::observation::start(&supervisor);
554 let watching = crate::watch::start(
555 &supervisor,
556 Arc::clone(&ports.printer),
557 detector_check(&config)?,
558 Arc::clone(&alignments),
559 );
560 let (stored, signal) = Stored::channel();
564 ports.stores.events.on_stored(signal);
565 let application = router(ApiState {
566 supervisor: Arc::clone(&supervisor),
567 prints: Arc::clone(&ports.stores.prints),
568 events: Arc::clone(&ports.stores.events),
569 images: Arc::clone(&ports.stores.images),
570 sessions: Arc::clone(&ports.stores.sessions),
571 operator: Arc::new(operator),
572 turns,
573 stored,
574 check_images: Some(check_images),
575 })
576 .merge(
577 Router::new()
578 .route(INGRESS_PATH, post(receive))
579 .with_state(ingress),
580 );
581
582 let (stop, stopped) = oneshot::channel::<()>();
583 let serving = tokio::spawn(async move {
584 let _ = axum::serve(listener, application)
585 .with_graceful_shutdown(async move {
586 let _ = stopped.await;
587 })
588 .await;
589 });
590 Ok(Running {
591 address,
592 config,
593 warnings,
594 supervisor,
595 stores: ports.stores,
596 reconciliation,
597 completions,
598 stop: Some(stop),
599 serving,
600 observing,
601 watching,
602 alignments,
603 })
604 }
605}
606
607fn panel_images(
610 config: &ServerConfig,
611 alignments: &Arc<crate::alignment::Alignments>,
612) -> Arc<crate::check_images::PanelImages> {
613 Arc::new(crate::check_images::PanelImages::new(
614 &config.state_dir,
615 Arc::clone(alignments),
616 config
617 .camera_snapshot_url
618 .as_ref()
619 .map(|url| url.as_str().to_owned()),
620 ))
621}
622
623fn prepare_state(
626 config: &ServerConfig,
627 ports: &Ports,
628) -> Result<Arc<crate::alignment::Alignments>, StartError> {
629 let spool_dir = gcode_spool_dir(&config.state_dir);
630 std::fs::create_dir_all(&spool_dir).map_err(|error| StartError::State {
631 detail: format!("{}: {error}", spool_dir.display()),
632 })?;
633 crate::alignment::Alignments::new(
634 &config.state_dir,
635 config.camera_calibration.clone(),
636 Arc::clone(&ports.stores.prints),
637 )
638 .map(Arc::new)
639 .map_err(|error| StartError::State {
640 detail: format!(
641 "{}: {error}",
642 crate::alignment::verdict_dir(&config.state_dir).display()
643 ),
644 })
645}
646
647async fn sweep_left_behind(
651 supervisor: &Supervisor,
652 alignments: &crate::alignment::Alignments,
653) -> Result<(), StartError> {
654 let reconciling = |error: printobserver_core::CoreError| StartError::Reconciliation {
655 detail: error.to_string(),
656 };
657 supervisor.sweep_gcode_spools().await.map_err(reconciling)?;
658 alignments.sweep().await;
659 supervisor
660 .restore_planned_changes()
661 .await
662 .map_err(reconciling)
663}
664
665#[must_use]
667pub fn gcode_spool_dir(state_dir: &Path) -> std::path::PathBuf {
668 state_dir.join("gcode-spool")
669}
670
671fn core_config_of(config: &ServerConfig) -> CoreConfig {
673 let mut core_config = CoreConfig::new(config.safety.clone(), context_command());
674 core_config.gcode_spool_dir = Some(gcode_spool_dir(&config.state_dir));
675 core_config
676 .camera_snapshot_url
677 .clone_from(&config.camera_snapshot_url);
678 core_config.observation_interval = config.observation_interval;
679 core_config.printer_poll = config.printer_poll;
680 core_config.unattended_window = config.unattended_window;
681 core_config.spools = config.spools;
682 core_config.sheets.clone_from(&config.sheets);
683 core_config.recovery = config.recovery;
684 core_config
685 .recovery_grants
686 .clone_from(&config.recovery_grants);
687 core_config
688}
689
690fn scoring_read(
694 config: &ServerConfig,
695 vision: &ObicoVision,
696) -> Result<Option<Arc<dyn printobserver_core::ScoringProbe>>, StartError> {
697 config
698 .obico_api
699 .clone()
700 .map(|api| {
701 ObicoScoring::new(api, config.obico_printer_id, vision.known_printer())
702 .map(|scoring| Arc::new(scoring) as Arc<dyn printobserver_core::ScoringProbe>)
703 .map_err(|error| StartError::State {
704 detail: error.to_string(),
705 })
706 })
707 .transpose()
708}
709
710fn detector_check(
712 config: &ServerConfig,
713) -> Result<Option<Arc<dyn printobserver_core::DetectorProbe>>, StartError> {
714 config
715 .obico_ml_api_url
716 .as_ref()
717 .map(|url| {
718 DetectorHealthCheck::new(url)
719 .map(|check| Arc::new(check) as Arc<dyn printobserver_core::DetectorProbe>)
720 .map_err(|detail| StartError::State { detail })
721 })
722 .transpose()
723}
724
725async fn probe(printer: &dyn PrinterPort) -> Result<(), StartError> {
733 match printer.snapshot().await {
734 Err(PrinterError::Unreachable { detail }) => {
735 Err(StartError::Configuration(ConfigError::about(
736 ConfigField::OctoprintUrl,
737 format!("nothing answers there: {detail}"),
738 )))
739 }
740 Err(PrinterError::Unauthorized { detail }) => {
741 Err(StartError::Configuration(ConfigError::about(
742 ConfigField::OctoprintApiKey,
743 format!("the OctoPrint instance refused it: {detail}"),
744 )))
745 }
746 _ => Ok(()),
747 }
748}
749
750fn materialize(
758 directory: &Path,
759 name: &str,
760 contents: &str,
761) -> Result<std::path::PathBuf, StartError> {
762 let path = directory.join(name);
763 std::fs::write(&path, contents).map_err(|error| StartError::State {
764 detail: format!("{} could not be written: {error}", path.display()),
765 })?;
766 Ok(path)
767}
768
769fn beside_the_skill(skill_path: &Path) -> std::path::PathBuf {
776 match skill_path.parent() {
777 Some(directory) if !directory.as_os_str().is_empty() => directory.to_path_buf(),
778 _ => std::path::PathBuf::from("."),
779 }
780}
781
782fn agent_for(
785 config: &ServerConfig,
786 command_usage: &[String],
787) -> Result<OneharnessSupervisor, StartError> {
788 OneharnessSupervisor::open(agent_config_with(config, command_usage)?).map_err(|error| {
789 StartError::Supervisor {
790 detail: error.to_string(),
791 }
792 })
793}
794
795pub const TURN_READS: [&str; 2] = ["context", "look"];
798
799pub fn agent_config_with(
809 config: &ServerConfig,
810 command_usage: &[String],
811) -> Result<SupervisorConfig, StartError> {
812 let mut composed = agent_config(config)?;
813 let granted = config
814 .safety
815 .actions
816 .get(&printobserver_core::ActorClass::Agent)
817 .into_iter()
818 .flatten()
819 .filter_map(|kind| {
820 printobserver_types::serde_json::to_value(kind)
821 .ok()
822 .and_then(|named| named.as_str().map(command_for))
823 });
824 let handed: Vec<String> = TURN_READS
825 .iter()
826 .map(|read| command_for(read))
827 .chain(granted)
828 .map(|command| format!("printobserver {command}"))
829 .collect();
830 composed.command_usage = command_usage
831 .iter()
832 .filter(|line| {
833 handed
834 .iter()
835 .any(|command| line == &command || line.starts_with(&format!("{command} ")))
836 })
837 .cloned()
838 .collect();
839 Ok(composed)
840}
841
842pub fn agent_config(config: &ServerConfig) -> Result<SupervisorConfig, StartError> {
858 let assets = config.assets_dir();
859 std::fs::create_dir_all(&assets).map_err(|error| StartError::State {
860 detail: format!("{} could not be created: {error}", assets.display()),
861 })?;
862 let prompt_template_path = match &config.prompt_template_path {
863 Some(path) => path.clone(),
864 None => materialize(&assets, PROMPT_FILE, TURN_PROMPT)?,
865 };
866 let schema_path =
867 materialize(
868 &assets,
869 SCHEMA_FILE,
870 &printobserver_types::serde_json::to_string_pretty(&AssessmentSchema::as_handed(
871 printobserver_types::contract::schema_of::<
872 printobserver_supervisor_api::AgentAssessment,
873 >(),
874 ))
875 .map_err(|error| StartError::State {
876 detail: error.to_string(),
877 })?,
878 )?;
879 let assessment_schema =
880 AssessmentSchema::at(&schema_path).map_err(|error| StartError::Supervisor {
881 detail: error.to_string(),
882 })?;
883 let mut harness_env = match HarnessSignIn::of(&config.harness) {
888 Some(sign_in) => {
889 let directory =
890 sign_in
891 .prepare(&config.state_dir)
892 .map_err(|error| StartError::State {
893 detail: format!(
894 "{} could not be created: {error}",
895 sign_in.directory(&config.state_dir).display()
896 ),
897 })?;
898 let refused = |error: printobserver_oneharness::ConfigError| StartError::Supervisor {
899 detail: error.to_string(),
900 };
901 let mut assigned = vec![sign_in.assignment(&directory).map_err(refused)?];
902 assigned.extend(sign_in.session_assignments().map_err(refused)?);
904 assigned
905 }
906 None => Vec::new(),
907 };
908 let search_path = std::env::var_os("PATH").unwrap_or_default();
909 harness_env.extend(path_led_by_this_program(&search_path)?);
910 Ok(SupervisorConfig {
911 state_dir: config.state_dir.clone(),
912 skill_path: config.skill_path.clone(),
913 prompt_template_path,
914 assessment_schema,
915 harness: config.harness.clone(),
916 model: config.model.clone(),
917 working_dir: beside_the_skill(&config.skill_path),
921 turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
922 harness_bin: HarnessSignIn::of(&config.harness)
926 .and_then(|harness| harness.program_behind_launcher(&search_path)),
927 harness_env,
928 agent_commands: agent_commands()?,
929 withheld_beside_an_image: withheld_beside_an_image()?,
930 command_usage: Vec::new(),
931 auto_compact_tokens: config.auto_compact_tokens,
932 idle_compact_tokens: config.idle_compact_tokens,
933 })
934}
935
936fn agent_commands() -> Result<Vec<AgentCommand>, StartError> {
946 OPERATIONS
947 .iter()
948 .filter(|operation| crate::operations::printer_wide_of(operation.name).is_none())
949 .map(|operation| {
950 AgentCommand::new(&format!(
951 "{CONTEXT_PROGRAM} {}",
952 command_for(operation.name)
953 ))
954 })
955 .collect::<Result<_, _>>()
956 .map_err(|error| StartError::Supervisor {
957 detail: error.to_string(),
958 })
959}
960
961pub const WITHHELD_BESIDE_AN_IMAGE: [&str; 2] = ["look", "recheck_camera"];
969
970fn withheld_beside_an_image() -> Result<Vec<AgentCommand>, StartError> {
972 WITHHELD_BESIDE_AN_IMAGE
973 .iter()
974 .map(|read| AgentCommand::new(&format!("{CONTEXT_PROGRAM} {}", command_for(read))))
975 .collect::<Result<_, _>>()
976 .map_err(|error| StartError::Supervisor {
977 detail: error.to_string(),
978 })
979}
980
981fn path_led_by_this_program(inherited: &OsStr) -> Result<Option<EnvAssignment>, StartError> {
994 let Some(directory) = std::env::current_exe()
995 .ok()
996 .and_then(|program| program.parent().map(Path::to_path_buf))
997 else {
998 return Ok(None);
999 };
1000 let refused = |detail: String| StartError::Supervisor {
1001 detail: format!(
1002 "a turn's PATH cannot lead with {}: {detail}",
1003 directory.display()
1004 ),
1005 };
1006 let joined = std::env::join_paths(
1007 std::iter::once(directory.clone()).chain(std::env::split_paths(inherited)),
1008 )
1009 .map_err(|error| refused(error.to_string()))?;
1010 let joined = joined
1011 .to_str()
1012 .ok_or_else(|| refused("it is not valid Unicode".to_owned()))?;
1013 EnvAssignment::new(&format!("PATH={joined}"))
1014 .map(Some)
1015 .map_err(|error| refused(error.to_string()))
1016}
1017
1018pub struct Running {
1023 address: SocketAddr,
1025 config: ServerConfig,
1027 warnings: Vec<String>,
1030 supervisor: Arc<Supervisor>,
1032 stores: Stores,
1034 reconciliation: Reconciliation,
1036 completions: watch::Receiver<u64>,
1038 stop: Option<oneshot::Sender<()>>,
1040 serving: JoinHandle<()>,
1042 observing: JoinHandle<()>,
1044 watching: crate::watch::Watching,
1047 alignments: Arc<crate::alignment::Alignments>,
1049}
1050
1051impl core::fmt::Debug for Running {
1052 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1053 formatter
1054 .debug_struct("Running")
1055 .field("address", &self.address)
1056 .field("reconciliation", &self.reconciliation)
1057 .finish_non_exhaustive()
1058 }
1059}
1060
1061impl Running {
1062 #[must_use]
1065 pub fn print_alignment(
1066 &self,
1067 print_id: printobserver_types::PrintId,
1068 ) -> crate::alignment::PrintAlignment {
1069 self.alignments.print_alignment(print_id)
1070 }
1071
1072 #[must_use]
1074 pub const fn address(&self) -> SocketAddr {
1075 self.address
1076 }
1077
1078 #[must_use]
1080 pub fn base_url(&self) -> String {
1081 format!(
1082 "http://{}{}",
1083 self.address,
1084 crate::operations::VERSION_PREFIX
1085 )
1086 }
1087
1088 #[must_use]
1090 pub fn ingress_url(&self) -> String {
1091 format!("http://{}{INGRESS_PATH}", self.address)
1092 }
1093
1094 #[must_use]
1096 pub const fn config(&self) -> &ServerConfig {
1097 &self.config
1098 }
1099
1100 #[must_use]
1104 pub fn warnings(&self) -> &[String] {
1105 &self.warnings
1106 }
1107
1108 #[must_use]
1110 pub const fn reconciliation(&self) -> &Reconciliation {
1111 &self.reconciliation
1112 }
1113
1114 #[must_use]
1116 pub const fn supervisor(&self) -> &Arc<Supervisor> {
1117 &self.supervisor
1118 }
1119
1120 #[must_use]
1122 pub const fn stores(&self) -> &Stores {
1123 &self.stores
1124 }
1125
1126 #[must_use]
1129 pub fn completions(&self) -> watch::Receiver<u64> {
1130 self.completions.clone()
1131 }
1132
1133 pub async fn stop(mut self) {
1135 if let Some(stop) = self.stop.take() {
1136 let _ = stop.send(());
1137 }
1138 self.observing.abort();
1139 self.watching.abort();
1140 let _ = (&mut self.serving).await;
1141 }
1142
1143 pub async fn serve_until_signalled(self) -> Result<(), StartError> {
1154 stop_requested().await?;
1155 self.stop().await;
1156 Ok(())
1157 }
1158}
1159
1160fn unhandled(what: &str, error: &std::io::Error) -> StartError {
1162 StartError::State {
1163 detail: format!("{what} cannot be handled: {error}"),
1164 }
1165}
1166
1167#[cfg(unix)]
1172async fn stop_requested() -> Result<(), StartError> {
1173 use tokio::signal::unix::{SignalKind, signal};
1174
1175 let mut terminate = signal(SignalKind::terminate())
1176 .map_err(|error| unhandled("the termination signal", &error))?;
1177 let mut interrupt = signal(SignalKind::interrupt())
1178 .map_err(|error| unhandled("the interrupt signal", &error))?;
1179 tokio::select! {
1180 _ = terminate.recv() => {}
1181 _ = interrupt.recv() => {}
1182 }
1183 Ok(())
1184}
1185
1186#[cfg(windows)]
1194async fn stop_requested() -> Result<(), StartError> {
1195 use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close, ctrl_shutdown};
1196
1197 let mut interrupt = ctrl_c().map_err(|error| unhandled("the CTRL_C event", &error))?;
1198 let mut breaking = ctrl_break().map_err(|error| unhandled("the CTRL_BREAK event", &error))?;
1199 let mut closing = ctrl_close().map_err(|error| unhandled("the CTRL_CLOSE event", &error))?;
1200 let mut shutting_down =
1201 ctrl_shutdown().map_err(|error| unhandled("the CTRL_SHUTDOWN event", &error))?;
1202 tokio::select! {
1203 _ = interrupt.recv() => {}
1204 _ = breaking.recv() => {}
1205 _ = closing.recv() => {}
1206 _ = shutting_down.recv() => {}
1207 }
1208 Ok(())
1209}
1210
1211impl Drop for Running {
1212 fn drop(&mut self) {
1213 if let Some(stop) = self.stop.take() {
1214 let _ = stop.send(());
1215 }
1216 self.serving.abort();
1217 }
1218}