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, 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
417impl Server {
418 pub async fn start(config_path: impl AsRef<Path>) -> Result<Running, StartError> {
427 let config = ServerConfig::load(config_path)?;
428 let store = SqliteStore::open(&config.state_dir).map_err(|error| StartError::Store {
429 detail: error.to_string(),
430 })?;
431 let migrated: Vec<String> = store.migrated().iter().map(ToString::to_string).collect();
434 let stores = Stores::of(Arc::new(store));
435 let printer = Arc::new(OctoPrintPrinter::new(config.octoprint.clone()));
436 probe(printer.as_ref()).await?;
437 let vision = Arc::new(
438 ObicoVision::new(ObicoVisionConfig {
439 blank_frame_max_stddev: config.blank_frame_max_stddev,
440 ..ObicoVisionConfig::default()
441 })
442 .map_err(|error| StartError::State {
443 detail: error.to_string(),
444 })?
445 .with_api(config.obico_api.clone()),
446 );
447 let agent = Arc::new(agent_for(&config)?);
448 let mut running = Self::start_with(
449 config,
450 Ports {
451 printer,
452 stores,
453 vision,
454 agent,
455 },
456 )
457 .await?;
458 running.warnings.extend(migrated);
459 Ok(running)
460 }
461
462 pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
469 let (operator, warnings) = operator_credential(&config)?;
474 let listener =
478 TcpListener::bind(config.listen)
479 .await
480 .map_err(|error| StartError::Listen {
481 address: config.listen,
482 detail: error.to_string(),
483 })?;
484 let address = listener.local_addr().map_err(|error| StartError::Listen {
485 address: config.listen,
486 detail: error.to_string(),
487 })?;
488 let clock = Arc::new(SystemClock);
489 let due = overdue(&ports.stores.actions, clock.now())
490 .await
491 .map_err(|error| StartError::Reconciliation {
492 detail: error.to_string(),
493 })?;
494 let supervisor = Supervisor::new(
495 core_config_of(&config),
496 Arc::clone(&ports.printer),
497 ports.stores.clone(),
498 Arc::clone(&ports.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
499 Arc::clone(&ports.agent),
500 clock,
501 );
502 let turns = TurnCredentials::new(Some(address));
505 supervisor.install_turn_authority(Arc::new(turns.clone()));
506 let reconciliation = reconcile(
507 &supervisor,
508 &ReconcileStores {
509 prints: Arc::clone(&ports.stores.prints),
510 sessions: Arc::clone(&ports.stores.sessions),
511 events: Arc::clone(&ports.stores.events),
512 },
513 due,
514 )
515 .await
516 .map_err(|error| StartError::Reconciliation {
517 detail: error.to_string(),
518 })?;
519
520 let ingress = IngressState::start(
521 Arc::clone(&supervisor),
522 Arc::clone(&ports.stores.events),
523 Arc::clone(&ports.vision),
524 config.ingress_shared_secret.clone(),
525 config.ingress_answer_bound,
526 );
527 let completions = ingress.completions();
528 let observing = crate::observation::start(&supervisor);
529 let watching = crate::watch::start(
530 &supervisor,
531 Arc::clone(&ports.printer),
532 detector_check(&config)?,
533 );
534 let (stored, signal) = Stored::channel();
538 ports.stores.events.on_stored(signal);
539 let application = router(ApiState {
540 supervisor: Arc::clone(&supervisor),
541 prints: Arc::clone(&ports.stores.prints),
542 events: Arc::clone(&ports.stores.events),
543 images: Arc::clone(&ports.stores.images),
544 sessions: Arc::clone(&ports.stores.sessions),
545 operator: Arc::new(operator),
546 turns,
547 stored,
548 })
549 .merge(
550 Router::new()
551 .route(INGRESS_PATH, post(receive))
552 .with_state(ingress),
553 );
554
555 let (stop, stopped) = oneshot::channel::<()>();
556 let serving = tokio::spawn(async move {
557 let _ = axum::serve(listener, application)
558 .with_graceful_shutdown(async move {
559 let _ = stopped.await;
560 })
561 .await;
562 });
563 Ok(Running {
564 address,
565 config,
566 warnings,
567 supervisor,
568 stores: ports.stores,
569 reconciliation,
570 completions,
571 stop: Some(stop),
572 serving,
573 observing,
574 watching,
575 })
576 }
577}
578
579fn core_config_of(config: &ServerConfig) -> CoreConfig {
581 let mut core_config = CoreConfig::new(config.safety.clone(), context_command());
582 core_config
583 .camera_snapshot_url
584 .clone_from(&config.camera_snapshot_url);
585 core_config.observation_interval = config.observation_interval;
586 core_config.printer_poll = config.printer_poll;
587 core_config.unattended_window = config.unattended_window;
588 core_config.spools = config.spools;
589 core_config.recovery = config.recovery;
590 core_config
591 .recovery_grants
592 .clone_from(&config.recovery_grants);
593 core_config
594}
595
596fn detector_check(
598 config: &ServerConfig,
599) -> Result<Option<Arc<dyn printobserver_core::DetectorProbe>>, StartError> {
600 config
601 .obico_ml_api_url
602 .as_ref()
603 .map(|url| {
604 DetectorHealthCheck::new(url)
605 .map(|check| Arc::new(check) as Arc<dyn printobserver_core::DetectorProbe>)
606 .map_err(|detail| StartError::State { detail })
607 })
608 .transpose()
609}
610
611async fn probe(printer: &dyn PrinterPort) -> Result<(), StartError> {
619 match printer.snapshot().await {
620 Err(PrinterError::Unreachable { detail }) => {
621 Err(StartError::Configuration(ConfigError::about(
622 ConfigField::OctoprintUrl,
623 format!("nothing answers there: {detail}"),
624 )))
625 }
626 Err(PrinterError::Unauthorized { detail }) => {
627 Err(StartError::Configuration(ConfigError::about(
628 ConfigField::OctoprintApiKey,
629 format!("the OctoPrint instance refused it: {detail}"),
630 )))
631 }
632 _ => Ok(()),
633 }
634}
635
636fn materialize(
644 directory: &Path,
645 name: &str,
646 contents: &str,
647) -> Result<std::path::PathBuf, StartError> {
648 let path = directory.join(name);
649 std::fs::write(&path, contents).map_err(|error| StartError::State {
650 detail: format!("{} could not be written: {error}", path.display()),
651 })?;
652 Ok(path)
653}
654
655fn beside_the_skill(skill_path: &Path) -> std::path::PathBuf {
662 match skill_path.parent() {
663 Some(directory) if !directory.as_os_str().is_empty() => directory.to_path_buf(),
664 _ => std::path::PathBuf::from("."),
665 }
666}
667
668fn agent_for(config: &ServerConfig) -> Result<OneharnessSupervisor, StartError> {
671 OneharnessSupervisor::open(agent_config(config)?).map_err(|error| StartError::Supervisor {
672 detail: error.to_string(),
673 })
674}
675
676pub fn agent_config(config: &ServerConfig) -> Result<SupervisorConfig, StartError> {
692 let assets = config.assets_dir();
693 std::fs::create_dir_all(&assets).map_err(|error| StartError::State {
694 detail: format!("{} could not be created: {error}", assets.display()),
695 })?;
696 let prompt_template_path = match &config.prompt_template_path {
697 Some(path) => path.clone(),
698 None => materialize(&assets, PROMPT_FILE, TURN_PROMPT)?,
699 };
700 let schema_path =
701 materialize(
702 &assets,
703 SCHEMA_FILE,
704 &printobserver_types::serde_json::to_string_pretty(&without_dialect(
705 printobserver_types::contract::schema_of::<
706 printobserver_supervisor_api::AgentAssessment,
707 >(),
708 ))
709 .map_err(|error| StartError::State {
710 detail: error.to_string(),
711 })?,
712 )?;
713 let assessment_schema =
714 AssessmentSchema::at(&schema_path).map_err(|error| StartError::Supervisor {
715 detail: error.to_string(),
716 })?;
717 let mut harness_env = match HarnessSignIn::of(&config.harness) {
722 Some(sign_in) => {
723 let directory =
724 sign_in
725 .prepare(&config.state_dir)
726 .map_err(|error| StartError::State {
727 detail: format!(
728 "{} could not be created: {error}",
729 sign_in.directory(&config.state_dir).display()
730 ),
731 })?;
732 vec![
733 sign_in
734 .assignment(&directory)
735 .map_err(|error| StartError::Supervisor {
736 detail: error.to_string(),
737 })?,
738 ]
739 }
740 None => Vec::new(),
741 };
742 let search_path = std::env::var_os("PATH").unwrap_or_default();
743 harness_env.extend(path_led_by_this_program(&search_path)?);
744 Ok(SupervisorConfig {
745 state_dir: config.state_dir.clone(),
746 skill_path: config.skill_path.clone(),
747 prompt_template_path,
748 assessment_schema,
749 harness: config.harness.clone(),
750 model: config.model.clone(),
751 working_dir: beside_the_skill(&config.skill_path),
755 turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
756 harness_bin: HarnessSignIn::of(&config.harness)
760 .and_then(|harness| harness.program_behind_launcher(&search_path)),
761 harness_env,
762 agent_commands: agent_commands()?,
763 })
764}
765
766const DIALECT_KEY: &str = "$schema";
768
769fn without_dialect(
779 mut schema: printobserver_types::serde_json::Value,
780) -> printobserver_types::serde_json::Value {
781 if let Some(object) = schema.as_object_mut() {
782 object.remove(DIALECT_KEY);
783 }
784 schema
785}
786
787fn agent_commands() -> Result<Vec<AgentCommand>, StartError> {
797 OPERATIONS
798 .iter()
799 .filter(|operation| crate::operations::printer_wide_of(operation.name).is_none())
800 .map(|operation| {
801 AgentCommand::new(&format!(
802 "{CONTEXT_PROGRAM} {}",
803 command_for(operation.name)
804 ))
805 })
806 .collect::<Result<_, _>>()
807 .map_err(|error| StartError::Supervisor {
808 detail: error.to_string(),
809 })
810}
811
812fn path_led_by_this_program(inherited: &OsStr) -> Result<Option<EnvAssignment>, StartError> {
825 let Some(directory) = std::env::current_exe()
826 .ok()
827 .and_then(|program| program.parent().map(Path::to_path_buf))
828 else {
829 return Ok(None);
830 };
831 let refused = |detail: String| StartError::Supervisor {
832 detail: format!(
833 "a turn's PATH cannot lead with {}: {detail}",
834 directory.display()
835 ),
836 };
837 let joined = std::env::join_paths(
838 std::iter::once(directory.clone()).chain(std::env::split_paths(inherited)),
839 )
840 .map_err(|error| refused(error.to_string()))?;
841 let joined = joined
842 .to_str()
843 .ok_or_else(|| refused("it is not valid Unicode".to_owned()))?;
844 EnvAssignment::new(&format!("PATH={joined}"))
845 .map(Some)
846 .map_err(|error| refused(error.to_string()))
847}
848
849pub struct Running {
854 address: SocketAddr,
856 config: ServerConfig,
858 warnings: Vec<String>,
861 supervisor: Arc<Supervisor>,
863 stores: Stores,
865 reconciliation: Reconciliation,
867 completions: watch::Receiver<u64>,
869 stop: Option<oneshot::Sender<()>>,
871 serving: JoinHandle<()>,
873 observing: JoinHandle<()>,
875 watching: crate::watch::Watching,
878}
879
880impl core::fmt::Debug for Running {
881 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
882 formatter
883 .debug_struct("Running")
884 .field("address", &self.address)
885 .field("reconciliation", &self.reconciliation)
886 .finish_non_exhaustive()
887 }
888}
889
890impl Running {
891 #[must_use]
893 pub const fn address(&self) -> SocketAddr {
894 self.address
895 }
896
897 #[must_use]
899 pub fn base_url(&self) -> String {
900 format!(
901 "http://{}{}",
902 self.address,
903 crate::operations::VERSION_PREFIX
904 )
905 }
906
907 #[must_use]
909 pub fn ingress_url(&self) -> String {
910 format!("http://{}{INGRESS_PATH}", self.address)
911 }
912
913 #[must_use]
915 pub const fn config(&self) -> &ServerConfig {
916 &self.config
917 }
918
919 #[must_use]
923 pub fn warnings(&self) -> &[String] {
924 &self.warnings
925 }
926
927 #[must_use]
929 pub const fn reconciliation(&self) -> &Reconciliation {
930 &self.reconciliation
931 }
932
933 #[must_use]
935 pub const fn supervisor(&self) -> &Arc<Supervisor> {
936 &self.supervisor
937 }
938
939 #[must_use]
941 pub const fn stores(&self) -> &Stores {
942 &self.stores
943 }
944
945 #[must_use]
948 pub fn completions(&self) -> watch::Receiver<u64> {
949 self.completions.clone()
950 }
951
952 pub async fn stop(mut self) {
954 if let Some(stop) = self.stop.take() {
955 let _ = stop.send(());
956 }
957 self.observing.abort();
958 self.watching.abort();
959 let _ = (&mut self.serving).await;
960 }
961
962 pub async fn serve_until_signalled(self) -> Result<(), StartError> {
973 stop_requested().await?;
974 self.stop().await;
975 Ok(())
976 }
977}
978
979fn unhandled(what: &str, error: &std::io::Error) -> StartError {
981 StartError::State {
982 detail: format!("{what} cannot be handled: {error}"),
983 }
984}
985
986#[cfg(unix)]
991async fn stop_requested() -> Result<(), StartError> {
992 use tokio::signal::unix::{SignalKind, signal};
993
994 let mut terminate = signal(SignalKind::terminate())
995 .map_err(|error| unhandled("the termination signal", &error))?;
996 let mut interrupt = signal(SignalKind::interrupt())
997 .map_err(|error| unhandled("the interrupt signal", &error))?;
998 tokio::select! {
999 _ = terminate.recv() => {}
1000 _ = interrupt.recv() => {}
1001 }
1002 Ok(())
1003}
1004
1005#[cfg(windows)]
1013async fn stop_requested() -> Result<(), StartError> {
1014 use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close, ctrl_shutdown};
1015
1016 let mut interrupt = ctrl_c().map_err(|error| unhandled("the CTRL_C event", &error))?;
1017 let mut breaking = ctrl_break().map_err(|error| unhandled("the CTRL_BREAK event", &error))?;
1018 let mut closing = ctrl_close().map_err(|error| unhandled("the CTRL_CLOSE event", &error))?;
1019 let mut shutting_down =
1020 ctrl_shutdown().map_err(|error| unhandled("the CTRL_SHUTDOWN event", &error))?;
1021 tokio::select! {
1022 _ = interrupt.recv() => {}
1023 _ = breaking.recv() => {}
1024 _ = closing.recv() => {}
1025 _ = shutting_down.recv() => {}
1026 }
1027 Ok(())
1028}
1029
1030impl Drop for Running {
1031 fn drop(&mut self) {
1032 if let Some(stop) = self.stop.take() {
1033 let _ = stop.send(());
1034 }
1035 self.serving.abort();
1036 }
1037}