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::readiness::HarnessCheck;
46use crate::reconcile::{ReconcileStores, Reconciliation, overdue, reconcile};
47use crate::turns::TurnCredentials;
48
49pub const CONTEXT_PROGRAM: &str = "printobserver";
51
52pub const CLIENT_CONFIG_FILE: &str = "client.toml";
57
58pub const API_CREDENTIAL_FILE: &str = "api-credential";
63
64pub const API_CREDENTIAL_VERIFIER_FILE: &str = "api-credential.verifier";
67
68pub const CREDENTIAL_ISSUE: &str = "printobserver credential issue";
71
72pub const CREDENTIAL_VERIFIER: &str = "printobserver credential verifier";
75
76#[cfg(unix)]
82const PRIVATE: u32 = 0o600;
83
84#[must_use]
93pub fn context_command() -> String {
94 format!("{CONTEXT_PROGRAM} context --print-id {{print_id}}")
95}
96
97#[derive(Debug, Clone)]
99pub enum OperatorCredential {
100 Verifier(CredentialVerifier),
102 Plaintext(ApiCredential),
105 Unconfigured,
108}
109
110impl OperatorCredential {
111 #[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#[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
137fn 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 let written = file.write_all(contents).and_then(|()| file.sync_all());
148 if written.is_err() {
149 let _ = std::fs::remove_file(path);
152 }
153 written
154}
155
156fn 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
164fn 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
226pub 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
277fn without_terminator(text: &str) -> &str {
284 text.strip_suffix("\r\n")
285 .or_else(|| text.strip_suffix('\n'))
286 .unwrap_or(text)
287}
288
289pub const PROMPT_FILE: &str = "turn-prompt.md";
291
292pub const SCHEMA_FILE: &str = "assessment-schema.json";
294
295pub const TURN_PROMPT: &str = printobserver_oneharness::DEFAULT_TURN_PROMPT;
301
302pub struct Ports {
307 pub printer: Arc<dyn PrinterPort>,
309 pub stores: Stores,
311 pub vision: Arc<ObicoVision>,
313 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#[derive(Debug)]
325pub enum StartError {
326 Configuration(ConfigError),
328 State {
330 detail: String,
332 },
333 Credential {
335 path: PathBuf,
337 detail: String,
339 },
340 Listen {
342 address: SocketAddr,
344 detail: String,
346 },
347 Store {
349 detail: String,
351 },
352 Supervisor {
354 detail: String,
356 },
357 Reconciliation {
359 detail: String,
361 },
362}
363
364impl StartError {
365 #[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#[derive(Debug)]
416pub struct Server;
417
418async 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 pub async fn start(config_path: impl AsRef<Path>) -> Result<Running, StartError> {
440 Self::start_with_usage(config_path, &[]).await
441 }
442
443 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 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 pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
496 let (operator, warnings) = operator_credential(&config)?;
501 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 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 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
609fn 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
625fn 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
649async 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#[must_use]
669pub fn gcode_spool_dir(state_dir: &Path) -> std::path::PathBuf {
670 state_dir.join("gcode-spool")
671}
672
673fn 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
692fn 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
712fn 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
727async 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
752fn 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
771fn 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
784fn 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
797pub const TURN_READS: [&str; 2] = ["context", "look"];
800
801pub 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
844pub 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 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 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 working_dir: beside_the_skill(&config.skill_path),
923 turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
924 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
938fn 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
963pub const WITHHELD_BESIDE_AN_IMAGE: [&str; 2] = ["look", "recheck_camera"];
971
972fn 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
983fn 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
1020pub struct Running {
1025 address: SocketAddr,
1027 config: ServerConfig,
1029 warnings: Vec<String>,
1032 supervisor: Arc<Supervisor>,
1034 stores: Stores,
1036 reconciliation: Reconciliation,
1038 completions: watch::Receiver<u64>,
1040 stop: Option<oneshot::Sender<()>>,
1042 serving: JoinHandle<()>,
1044 observing: JoinHandle<()>,
1046 watching: crate::watch::Watching,
1049 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 #[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 #[must_use]
1076 pub const fn address(&self) -> SocketAddr {
1077 self.address
1078 }
1079
1080 #[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 #[must_use]
1092 pub fn ingress_url(&self) -> String {
1093 format!("http://{}{INGRESS_PATH}", self.address)
1094 }
1095
1096 #[must_use]
1098 pub const fn config(&self) -> &ServerConfig {
1099 &self.config
1100 }
1101
1102 #[must_use]
1106 pub fn warnings(&self) -> &[String] {
1107 &self.warnings
1108 }
1109
1110 #[must_use]
1112 pub const fn reconciliation(&self) -> &Reconciliation {
1113 &self.reconciliation
1114 }
1115
1116 #[must_use]
1118 pub const fn supervisor(&self) -> &Arc<Supervisor> {
1119 &self.supervisor
1120 }
1121
1122 #[must_use]
1124 pub const fn stores(&self) -> &Stores {
1125 &self.stores
1126 }
1127
1128 #[must_use]
1131 pub fn completions(&self) -> watch::Receiver<u64> {
1132 self.completions.clone()
1133 }
1134
1135 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 pub async fn serve_until_signalled(self) -> Result<(), StartError> {
1156 stop_requested().await?;
1157 self.stop().await;
1158 Ok(())
1159 }
1160}
1161
1162fn unhandled(what: &str, error: &std::io::Error) -> StartError {
1164 StartError::State {
1165 detail: format!("{what} cannot be handled: {error}"),
1166 }
1167}
1168
1169#[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#[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}