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::{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::ingress::{IngressState, receive};
43use crate::operations::{INGRESS_PATH, OPERATIONS, command_for};
44use crate::reconcile::{ReconcileStores, Reconciliation, overdue, reconcile};
45use crate::turns::TurnCredentials;
46
47pub const CONTEXT_PROGRAM: &str = "printobserver";
49
50pub const CLIENT_CONFIG_FILE: &str = "client.toml";
55
56pub const API_CREDENTIAL_FILE: &str = "api-credential";
61
62pub const API_CREDENTIAL_VERIFIER_FILE: &str = "api-credential.verifier";
65
66pub const CREDENTIAL_ISSUE: &str = "printobserver credential issue";
69
70pub const CREDENTIAL_VERIFIER: &str = "printobserver credential verifier";
73
74#[cfg(unix)]
80const PRIVATE: u32 = 0o600;
81
82#[must_use]
91pub fn context_command() -> String {
92 format!("{CONTEXT_PROGRAM} context --print-id {{print_id}}")
93}
94
95#[derive(Debug, Clone)]
97pub enum OperatorCredential {
98 Verifier(CredentialVerifier),
100 Plaintext(ApiCredential),
103 Unconfigured,
106}
107
108impl OperatorCredential {
109 #[must_use]
111 pub fn admits(&self, presented: &[u8]) -> bool {
112 match self {
113 Self::Verifier(verifier) => verifier.admits(presented),
114 Self::Plaintext(credential) => credential.admits(presented),
115 Self::Unconfigured => false,
116 }
117 }
118}
119
120#[must_use]
124pub fn plaintext_credential_warning() -> String {
125 format!(
126 "the server configuration carries `api.credential`, an operator credential in \
127 plaintext. A supervision turn runs as this service's user and can read that file, \
128 so it can read that credential until it is replaced. Replace it with \
129 `api.credential_verifier`: pipe the credential into `{CREDENTIAL_VERIFIER}` to print \
130 that line, put it in the configuration, delete `api.credential`, and restart the \
131 service"
132 )
133}
134
135fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
137 use std::io::Write as _;
138
139 let mut options = std::fs::OpenOptions::new();
140 options.write(true).create_new(true);
141 #[cfg(unix)]
142 std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
143 let mut file = options.open(path)?;
144 let written = file.write_all(contents).and_then(|()| file.sync_all());
146 if written.is_err() {
147 let _ = std::fs::remove_file(path);
150 }
151 written
152}
153
154fn remove_if_there(path: &Path) -> std::io::Result<()> {
156 match std::fs::remove_file(path) {
157 Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
158 _ => Ok(()),
159 }
160}
161
162fn take_plaintext_out(state_dir: &Path) -> Result<(), StartError> {
178 let client_config = state_dir.join(CLIENT_CONFIG_FILE);
179 remove_if_there(&client_config).map_err(|error| StartError::State {
180 detail: format!(
181 "{} could not be removed, and it may carry the operator's credential where a \
182 supervision turn can read it: {error}",
183 client_config.display()
184 ),
185 })?;
186 let legacy = state_dir.join(API_CREDENTIAL_FILE);
187 let refusing = |detail: String| StartError::Credential {
188 path: legacy.clone(),
189 detail,
190 };
191 let held = match std::fs::read(&legacy) {
192 Ok(held) => held,
193 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
194 Err(error) => return Err(refusing(format!("it cannot be read: {error}"))),
195 };
196 let verifier_file = state_dir.join(API_CREDENTIAL_VERIFIER_FILE);
197 if !verifier_file.exists() {
198 let text = core::str::from_utf8(&held).ok().map(without_terminator);
199 let credential = text
200 .ok_or("it is not text")
201 .and_then(ApiCredential::new)
202 .map_err(|why| {
203 refusing(format!(
204 "{why}. This server converts the credential an earlier version generated \
205 there into its verifier: correct the file, or remove it and run \
206 `{CREDENTIAL_ISSUE} --replace`"
207 ))
208 })?;
209 write_private(
210 &verifier_file,
211 format!("{}\n", credential.verifier()).as_bytes(),
212 )
213 .map_err(|error| {
214 refusing(format!(
215 "its verifier could not be written to {}: {error}",
216 verifier_file.display()
217 ))
218 })?;
219 }
220 std::fs::remove_file(&legacy)
221 .map_err(|error| refusing(format!("it could not be removed: {error}")))
222}
223
224pub fn operator_credential(
239 config: &ServerConfig,
240) -> Result<(OperatorCredential, Vec<String>), StartError> {
241 take_plaintext_out(&config.state_dir)?;
242 let mut warnings = Vec::new();
243 if config.api_credential.is_some() {
244 warnings.push(plaintext_credential_warning());
245 }
246 if let Some(verifier) = &config.api_credential_verifier {
247 return Ok((OperatorCredential::Verifier(verifier.clone()), warnings));
248 }
249 if let Some(plaintext) = &config.api_credential {
250 return Ok((OperatorCredential::Plaintext(plaintext.clone()), warnings));
251 }
252 let path = config.state_dir.join(API_CREDENTIAL_VERIFIER_FILE);
253 let held = match std::fs::read_to_string(&path) {
254 Ok(held) => held,
255 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
256 return Ok((OperatorCredential::Unconfigured, warnings));
257 }
258 Err(error) => {
259 return Err(StartError::Credential {
260 path,
261 detail: format!("it cannot be read: {error}"),
262 });
263 }
264 };
265 let verifier =
266 CredentialVerifier::parse(held.trim()).map_err(|why| StartError::Credential {
267 path: path.clone(),
268 detail: format!(
269 "{why}. Correct the file, or remove it and set `api.credential_verifier`"
270 ),
271 })?;
272 Ok((OperatorCredential::Verifier(verifier), warnings))
273}
274
275fn without_terminator(text: &str) -> &str {
282 text.strip_suffix("\r\n")
283 .or_else(|| text.strip_suffix('\n'))
284 .unwrap_or(text)
285}
286
287pub const PROMPT_FILE: &str = "turn-prompt.md";
289
290pub const SCHEMA_FILE: &str = "assessment-schema.json";
292
293pub const TURN_PROMPT: &str = printobserver_oneharness::DEFAULT_TURN_PROMPT;
299
300pub struct Ports {
305 pub printer: Arc<dyn PrinterPort>,
307 pub stores: Stores,
309 pub vision: Arc<ObicoVision>,
311 pub agent: Arc<dyn SupervisorPort>,
313}
314
315impl core::fmt::Debug for Ports {
316 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
317 formatter.debug_struct("Ports").finish_non_exhaustive()
318 }
319}
320
321#[derive(Debug)]
323pub enum StartError {
324 Configuration(ConfigError),
326 State {
328 detail: String,
330 },
331 Credential {
333 path: PathBuf,
335 detail: String,
337 },
338 Listen {
340 address: SocketAddr,
342 detail: String,
344 },
345 Store {
347 detail: String,
349 },
350 Supervisor {
352 detail: String,
354 },
355 Reconciliation {
357 detail: String,
359 },
360}
361
362impl StartError {
363 #[must_use]
365 pub const fn field(&self) -> Option<ConfigField> {
366 match self {
367 Self::Configuration(error) => error.field(),
368 _ => None,
369 }
370 }
371}
372
373impl core::fmt::Display for StartError {
374 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
375 match self {
376 Self::Configuration(error) => write!(formatter, "{error}"),
377 Self::State { detail } => {
378 write!(
379 formatter,
380 "the state directory could not be prepared: {detail}"
381 )
382 }
383 Self::Credential { path, detail } => write!(
384 formatter,
385 "the credential file {} cannot be used: {detail}",
386 path.display()
387 ),
388 Self::Listen { address, detail } => {
389 write!(formatter, "{address} could not be listened on: {detail}")
390 }
391 Self::Store { detail } => write!(formatter, "the store could not be opened: {detail}"),
392 Self::Supervisor { detail } => write!(
393 formatter,
394 "the supervising agent's harness could not be reached: {detail}"
395 ),
396 Self::Reconciliation { detail } => write!(
397 formatter,
398 "what the store held could not be reconciled: {detail}"
399 ),
400 }
401 }
402}
403
404impl core::error::Error for StartError {}
405
406impl From<ConfigError> for StartError {
407 fn from(error: ConfigError) -> Self {
408 Self::Configuration(error)
409 }
410}
411
412#[derive(Debug)]
414pub struct Server;
415
416impl Server {
417 pub async fn start(config_path: impl AsRef<Path>) -> Result<Running, StartError> {
426 let config = ServerConfig::load(config_path)?;
427 let stores = Stores::of(Arc::new(SqliteStore::open(&config.state_dir).map_err(
428 |error| StartError::Store {
429 detail: error.to_string(),
430 },
431 )?));
432 let printer = Arc::new(OctoPrintPrinter::new(config.octoprint.clone()));
433 probe(printer.as_ref()).await?;
434 let vision = Arc::new(
435 ObicoVision::new(ObicoVisionConfig::default())
436 .map_err(|error| StartError::State {
437 detail: error.to_string(),
438 })?
439 .with_api(config.obico_api.clone()),
440 );
441 let agent = Arc::new(agent_for(&config)?);
442 Self::start_with(
443 config,
444 Ports {
445 printer,
446 stores,
447 vision,
448 agent,
449 },
450 )
451 .await
452 }
453
454 pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
461 let (operator, warnings) = operator_credential(&config)?;
466 let listener =
470 TcpListener::bind(config.listen)
471 .await
472 .map_err(|error| StartError::Listen {
473 address: config.listen,
474 detail: error.to_string(),
475 })?;
476 let address = listener.local_addr().map_err(|error| StartError::Listen {
477 address: config.listen,
478 detail: error.to_string(),
479 })?;
480 let clock = Arc::new(SystemClock);
481 let due = overdue(&ports.stores.actions, clock.now())
482 .await
483 .map_err(|error| StartError::Reconciliation {
484 detail: error.to_string(),
485 })?;
486 let mut core_config = CoreConfig::new(config.safety.clone(), context_command());
487 core_config
488 .camera_snapshot_url
489 .clone_from(&config.camera_snapshot_url);
490 core_config.observation_interval = config.observation_interval;
491 core_config.spools = config.spools;
492 let supervisor = Supervisor::new(
493 core_config,
494 Arc::clone(&ports.printer),
495 ports.stores.clone(),
496 Arc::clone(&ports.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
497 Arc::clone(&ports.agent),
498 clock,
499 );
500 let turns = TurnCredentials::new(Some(address));
503 supervisor.install_turn_authority(Arc::new(turns.clone()));
504 let reconciliation = reconcile(
505 &supervisor,
506 &ReconcileStores {
507 prints: Arc::clone(&ports.stores.prints),
508 sessions: Arc::clone(&ports.stores.sessions),
509 events: Arc::clone(&ports.stores.events),
510 },
511 due,
512 )
513 .await
514 .map_err(|error| StartError::Reconciliation {
515 detail: error.to_string(),
516 })?;
517
518 let ingress = IngressState::start(
519 Arc::clone(&supervisor),
520 Arc::clone(&ports.stores.events),
521 Arc::clone(&ports.vision),
522 config.ingress_shared_secret.clone(),
523 config.ingress_answer_bound,
524 );
525 let completions = ingress.completions();
526 let observing = crate::observation::start(&supervisor);
527 let application = router(ApiState {
528 supervisor: Arc::clone(&supervisor),
529 prints: Arc::clone(&ports.stores.prints),
530 events: Arc::clone(&ports.stores.events),
531 images: Arc::clone(&ports.stores.images),
532 sessions: Arc::clone(&ports.stores.sessions),
533 operator: Arc::new(operator),
534 turns,
535 })
536 .merge(
537 Router::new()
538 .route(INGRESS_PATH, post(receive))
539 .with_state(ingress),
540 );
541
542 let (stop, stopped) = oneshot::channel::<()>();
543 let serving = tokio::spawn(async move {
544 let _ = axum::serve(listener, application)
545 .with_graceful_shutdown(async move {
546 let _ = stopped.await;
547 })
548 .await;
549 });
550 Ok(Running {
551 address,
552 config,
553 warnings,
554 supervisor,
555 stores: ports.stores,
556 reconciliation,
557 completions,
558 stop: Some(stop),
559 serving,
560 observing,
561 })
562 }
563}
564
565async fn probe(printer: &dyn PrinterPort) -> Result<(), StartError> {
573 match printer.snapshot().await {
574 Err(PrinterError::Unreachable { detail }) => {
575 Err(StartError::Configuration(ConfigError::about(
576 ConfigField::OctoprintUrl,
577 format!("nothing answers there: {detail}"),
578 )))
579 }
580 Err(PrinterError::Unauthorized { detail }) => {
581 Err(StartError::Configuration(ConfigError::about(
582 ConfigField::OctoprintApiKey,
583 format!("the OctoPrint instance refused it: {detail}"),
584 )))
585 }
586 _ => Ok(()),
587 }
588}
589
590fn materialize(
598 directory: &Path,
599 name: &str,
600 contents: &str,
601) -> Result<std::path::PathBuf, StartError> {
602 let path = directory.join(name);
603 std::fs::write(&path, contents).map_err(|error| StartError::State {
604 detail: format!("{} could not be written: {error}", path.display()),
605 })?;
606 Ok(path)
607}
608
609fn beside_the_skill(skill_path: &Path) -> std::path::PathBuf {
616 match skill_path.parent() {
617 Some(directory) if !directory.as_os_str().is_empty() => directory.to_path_buf(),
618 _ => std::path::PathBuf::from("."),
619 }
620}
621
622fn agent_for(config: &ServerConfig) -> Result<OneharnessSupervisor, StartError> {
625 OneharnessSupervisor::open(agent_config(config)?).map_err(|error| StartError::Supervisor {
626 detail: error.to_string(),
627 })
628}
629
630pub fn agent_config(config: &ServerConfig) -> Result<SupervisorConfig, StartError> {
646 let assets = config.assets_dir();
647 std::fs::create_dir_all(&assets).map_err(|error| StartError::State {
648 detail: format!("{} could not be created: {error}", assets.display()),
649 })?;
650 let prompt_template_path = match &config.prompt_template_path {
651 Some(path) => path.clone(),
652 None => materialize(&assets, PROMPT_FILE, TURN_PROMPT)?,
653 };
654 let schema_path =
655 materialize(
656 &assets,
657 SCHEMA_FILE,
658 &printobserver_types::serde_json::to_string_pretty(&without_dialect(
659 printobserver_types::contract::schema_of::<
660 printobserver_supervisor_api::AgentAssessment,
661 >(),
662 ))
663 .map_err(|error| StartError::State {
664 detail: error.to_string(),
665 })?,
666 )?;
667 let assessment_schema =
668 AssessmentSchema::at(&schema_path).map_err(|error| StartError::Supervisor {
669 detail: error.to_string(),
670 })?;
671 let mut harness_env = match HarnessSignIn::of(&config.harness) {
676 Some(sign_in) => {
677 let directory =
678 sign_in
679 .prepare(&config.state_dir)
680 .map_err(|error| StartError::State {
681 detail: format!(
682 "{} could not be created: {error}",
683 sign_in.directory(&config.state_dir).display()
684 ),
685 })?;
686 vec![
687 sign_in
688 .assignment(&directory)
689 .map_err(|error| StartError::Supervisor {
690 detail: error.to_string(),
691 })?,
692 ]
693 }
694 None => Vec::new(),
695 };
696 let search_path = std::env::var_os("PATH").unwrap_or_default();
697 harness_env.extend(path_led_by_this_program(&search_path)?);
698 Ok(SupervisorConfig {
699 state_dir: config.state_dir.clone(),
700 skill_path: config.skill_path.clone(),
701 prompt_template_path,
702 assessment_schema,
703 harness: config.harness.clone(),
704 model: config.model.clone(),
705 working_dir: beside_the_skill(&config.skill_path),
709 turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
710 harness_bin: HarnessSignIn::of(&config.harness)
714 .and_then(|harness| harness.program_behind_launcher(&search_path)),
715 harness_env,
716 agent_commands: agent_commands()?,
717 })
718}
719
720const DIALECT_KEY: &str = "$schema";
722
723fn without_dialect(
733 mut schema: printobserver_types::serde_json::Value,
734) -> printobserver_types::serde_json::Value {
735 if let Some(object) = schema.as_object_mut() {
736 object.remove(DIALECT_KEY);
737 }
738 schema
739}
740
741fn agent_commands() -> Result<Vec<AgentCommand>, StartError> {
750 OPERATIONS
751 .iter()
752 .map(|operation| {
753 AgentCommand::new(&format!(
754 "{CONTEXT_PROGRAM} {}",
755 command_for(operation.name)
756 ))
757 })
758 .collect::<Result<_, _>>()
759 .map_err(|error| StartError::Supervisor {
760 detail: error.to_string(),
761 })
762}
763
764fn path_led_by_this_program(inherited: &OsStr) -> Result<Option<EnvAssignment>, StartError> {
777 let Some(directory) = std::env::current_exe()
778 .ok()
779 .and_then(|program| program.parent().map(Path::to_path_buf))
780 else {
781 return Ok(None);
782 };
783 let refused = |detail: String| StartError::Supervisor {
784 detail: format!(
785 "a turn's PATH cannot lead with {}: {detail}",
786 directory.display()
787 ),
788 };
789 let joined = std::env::join_paths(
790 std::iter::once(directory.clone()).chain(std::env::split_paths(inherited)),
791 )
792 .map_err(|error| refused(error.to_string()))?;
793 let joined = joined
794 .to_str()
795 .ok_or_else(|| refused("it is not valid Unicode".to_owned()))?;
796 EnvAssignment::new(&format!("PATH={joined}"))
797 .map(Some)
798 .map_err(|error| refused(error.to_string()))
799}
800
801pub struct Running {
806 address: SocketAddr,
808 config: ServerConfig,
810 warnings: Vec<String>,
813 supervisor: Arc<Supervisor>,
815 stores: Stores,
817 reconciliation: Reconciliation,
819 completions: watch::Receiver<u64>,
821 stop: Option<oneshot::Sender<()>>,
823 serving: JoinHandle<()>,
825 observing: JoinHandle<()>,
827}
828
829impl core::fmt::Debug for Running {
830 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
831 formatter
832 .debug_struct("Running")
833 .field("address", &self.address)
834 .field("reconciliation", &self.reconciliation)
835 .finish_non_exhaustive()
836 }
837}
838
839impl Running {
840 #[must_use]
842 pub const fn address(&self) -> SocketAddr {
843 self.address
844 }
845
846 #[must_use]
848 pub fn base_url(&self) -> String {
849 format!(
850 "http://{}{}",
851 self.address,
852 crate::operations::VERSION_PREFIX
853 )
854 }
855
856 #[must_use]
858 pub fn ingress_url(&self) -> String {
859 format!("http://{}{INGRESS_PATH}", self.address)
860 }
861
862 #[must_use]
864 pub const fn config(&self) -> &ServerConfig {
865 &self.config
866 }
867
868 #[must_use]
872 pub fn warnings(&self) -> &[String] {
873 &self.warnings
874 }
875
876 #[must_use]
878 pub const fn reconciliation(&self) -> &Reconciliation {
879 &self.reconciliation
880 }
881
882 #[must_use]
884 pub const fn supervisor(&self) -> &Arc<Supervisor> {
885 &self.supervisor
886 }
887
888 #[must_use]
890 pub const fn stores(&self) -> &Stores {
891 &self.stores
892 }
893
894 #[must_use]
897 pub fn completions(&self) -> watch::Receiver<u64> {
898 self.completions.clone()
899 }
900
901 pub async fn stop(mut self) {
903 if let Some(stop) = self.stop.take() {
904 let _ = stop.send(());
905 }
906 self.observing.abort();
907 let _ = (&mut self.serving).await;
908 }
909
910 pub async fn serve_until_signalled(self) -> Result<(), StartError> {
921 stop_requested().await?;
922 self.stop().await;
923 Ok(())
924 }
925}
926
927fn unhandled(what: &str, error: &std::io::Error) -> StartError {
929 StartError::State {
930 detail: format!("{what} cannot be handled: {error}"),
931 }
932}
933
934#[cfg(unix)]
939async fn stop_requested() -> Result<(), StartError> {
940 use tokio::signal::unix::{SignalKind, signal};
941
942 let mut terminate = signal(SignalKind::terminate())
943 .map_err(|error| unhandled("the termination signal", &error))?;
944 let mut interrupt = signal(SignalKind::interrupt())
945 .map_err(|error| unhandled("the interrupt signal", &error))?;
946 tokio::select! {
947 _ = terminate.recv() => {}
948 _ = interrupt.recv() => {}
949 }
950 Ok(())
951}
952
953#[cfg(windows)]
961async fn stop_requested() -> Result<(), StartError> {
962 use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close, ctrl_shutdown};
963
964 let mut interrupt = ctrl_c().map_err(|error| unhandled("the CTRL_C event", &error))?;
965 let mut breaking = ctrl_break().map_err(|error| unhandled("the CTRL_BREAK event", &error))?;
966 let mut closing = ctrl_close().map_err(|error| unhandled("the CTRL_CLOSE event", &error))?;
967 let mut shutting_down =
968 ctrl_shutdown().map_err(|error| unhandled("the CTRL_SHUTDOWN event", &error))?;
969 tokio::select! {
970 _ = interrupt.recv() => {}
971 _ = breaking.recv() => {}
972 _ = closing.recv() => {}
973 _ = shutting_down.recv() => {}
974 }
975 Ok(())
976}
977
978impl Drop for Running {
979 fn drop(&mut self) {
980 if let Some(stop) = self.stop.take() {
981 let _ = stop.send(());
982 }
983 self.serving.abort();
984 }
985}