1use std::{
2 fmt::Write as _,
3 fs::{self, File, OpenOptions},
4 future::Future as _,
5 io::{self, Read as _},
6 path::{Path, PathBuf},
7 process::{Command, ExitStatus, Stdio},
8 sync::mpsc::{self, RecvTimeoutError},
9 thread,
10 time::{Duration, Instant},
11};
12
13#[cfg(unix)]
14use std::os::unix::fs::OpenOptionsExt as _;
15
16use ic_host_fs::{directory::create_unique_directory, owned_directory::OwnedDirectory};
17use ic_host_process::child::{CleanupError, CleanupPolicy, OwnedChild};
18use ic_platform::pocket_ic::{PocketIc, PocketIcBuilder};
19
20use super::transport;
21
22const STARTUP_POLL_INTERVAL: Duration = Duration::from_millis(20);
23const SERVER_OUTPUT_LIMIT: usize = 16 * 1024;
24const SERVER_PORT_FILE_LIMIT: usize = 64;
27
28#[derive(Clone, Debug, Eq, PartialEq)]
33pub enum PocketIcStartupConfig {
34 Spawn {
36 server_binary: PathBuf,
38 timeout: Duration,
40 server_hard_ttl: Option<Duration>,
42 server_idle_ttl: Option<Duration>,
44 server_output_files: Option<(PathBuf, PathBuf)>,
47 },
48 Connect {
50 server_url: String,
52 timeout: Duration,
54 },
55}
56
57pub struct PocketIcManagedServer {
68 server: ManagedServer,
69 url: String,
70}
71
72#[must_use]
99pub struct PocketIcInstance<T> {
100 instance: T,
101 server: Option<PocketIcManagedServer>,
102}
103
104impl<T> PocketIcInstance<T> {
105 pub const fn from_borrowed_server(instance: T) -> Self {
111 Self {
112 instance,
113 server: None,
114 }
115 }
116
117 #[must_use]
119 pub const fn instance(&self) -> &T {
120 &self.instance
121 }
122
123 pub const fn instance_mut(&mut self) -> &mut T {
135 &mut self.instance
136 }
137
138 #[must_use]
140 pub const fn server(&self) -> Option<&PocketIcManagedServer> {
141 self.server.as_ref()
142 }
143
144 #[must_use]
150 pub fn into_parts(self) -> (T, Option<PocketIcManagedServer>) {
151 (self.instance, self.server)
152 }
153}
154
155#[derive(Clone, Debug, Default, Eq, PartialEq)]
161pub struct PocketIcManagedServerOutput {
162 stdout: String,
163 stderr: String,
164}
165
166#[derive(Debug)]
172pub struct PocketIcStartupError {
173 failure: Box<PocketIcStartupFailure>,
174 output: PocketIcManagedServerOutput,
175 command_cleanup: Option<Box<CleanupError>>,
176 server_cleanup: Option<Box<CleanupError>>,
177}
178
179impl PocketIcStartupError {
180 fn new(failure: PocketIcStartupFailure) -> Self {
181 Self {
182 failure: Box::new(failure),
183 output: PocketIcManagedServerOutput::default(),
184 command_cleanup: None,
185 server_cleanup: None,
186 }
187 }
188
189 #[must_use]
191 pub fn failure(&self) -> &PocketIcStartupFailure {
192 &self.failure
193 }
194
195 #[must_use]
197 pub const fn output(&self) -> &PocketIcManagedServerOutput {
198 &self.output
199 }
200
201 #[must_use]
203 pub fn command_cleanup(&self) -> Option<&CleanupError> {
204 self.command_cleanup.as_deref()
205 }
206
207 #[must_use]
209 pub fn server_cleanup(&self) -> Option<&CleanupError> {
210 self.server_cleanup.as_deref()
211 }
212
213 fn with_cleanup(
214 mut self,
215 command: Option<CleanupError>,
216 server: Option<(PocketIcManagedServerOutput, Option<CleanupError>)>,
217 ) -> Self {
218 self.command_cleanup = command.map(Box::new);
219 if let Some((output, cleanup)) = server {
220 self.output = output;
221 self.server_cleanup = cleanup.map(Box::new);
222 }
223 self
224 }
225}
226
227#[non_exhaustive]
229#[derive(Debug, thiserror::Error)]
230pub enum PocketIcStartupFailure {
231 #[error(
233 "configure IC_TESTKIT_POCKET_IC_URL or POCKET_IC_BIN; prepare a verified binary with make install-server"
234 )]
235 NotConfigured,
236 #[error("invalid selected environment value: {variable}")]
238 InvalidEnvironment {
239 variable: &'static str,
241 },
242 #[error("PocketIC version probe failed: {source}")]
244 ServerVersionProbe {
245 source: ic_host_process::tool::ToolError,
247 },
248 #[error("PocketIC version mismatch: expected {expected:?}, observed {:?}", String::from_utf8_lossy(.observed))]
250 ServerVersionMismatch {
251 expected: String,
253 observed: Vec<u8>,
255 },
256 #[error("command {} failed: {source}", .program.display())]
258 CommandRun {
259 program: PathBuf,
261 source: io::Error,
263 },
264 #[error("{message}")]
266 InvalidConfiguration {
267 message: String,
269 },
270 #[error("invalid PocketIC server URL {server_url:?}: {message}")]
272 InvalidServerUrl {
273 server_url: String,
275 message: String,
277 },
278 #[error("failed to {operation} at {}: {source}", .path.display())]
280 Io {
281 operation: &'static str,
283 path: PathBuf,
285 source: io::Error,
287 },
288 #[error("failed to spawn PocketIC server {}: {source}", .server_binary.display())]
290 ServerSpawn {
291 server_binary: PathBuf,
293 source: io::Error,
295 },
296 #[error("PocketIC server {} exited with {status} after {elapsed:?}", .server_binary.display())]
298 ServerExited {
299 server_binary: PathBuf,
301 status: ExitStatus,
303 elapsed: Duration,
305 },
306 #[error("PocketIC server {} was not ready within {timeout:?}", .server_binary.display())]
308 ReadinessTimeout {
309 server_binary: PathBuf,
311 timeout: Duration,
313 },
314 #[error("PocketIC server {} published invalid port {value:?}", .server_binary.display())]
316 InvalidServerPort {
317 server_binary: PathBuf,
319 value: String,
321 },
322 #[error("PocketIC instance creation exceeded {timeout:?}")]
324 InstanceCreationTimeout {
325 timeout: Duration,
327 },
328 #[error("failed to spawn PocketIC builder worker: {source}")]
330 BuilderThreadSpawn {
331 source: io::Error,
333 },
334 #[error("PocketIC startup panicked: {source}")]
336 BuilderPanicked {
337 source: super::PocketIcOperationError,
339 },
340 #[error("PocketIC builder worker disconnected without a result")]
342 BuilderDisconnected,
343 #[error("PocketIC server cleanup failed after command exited with {command_status}")]
345 ServerCleanup {
346 command_status: ExitStatus,
348 },
349}
350
351impl PocketIcStartupConfig {
352 pub fn from_env(timeout: Duration) -> Result<Self, PocketIcStartupError> {
366 Self::from_environment(timeout, |name| std::env::var_os(name))
367 }
368
369 fn from_environment(
370 timeout: Duration,
371 mut variable: impl FnMut(&str) -> Option<std::ffi::OsString>,
372 ) -> Result<Self, PocketIcStartupError> {
373 if let Some(value) = variable("IC_TESTKIT_POCKET_IC_URL") {
374 let server_url = value
375 .into_string()
376 .ok()
377 .filter(|value| !value.is_empty())
378 .ok_or_else(|| {
379 PocketIcStartupError::new(PocketIcStartupFailure::InvalidEnvironment {
380 variable: "IC_TESTKIT_POCKET_IC_URL",
381 })
382 })?;
383 let config = Self::Connect {
384 server_url: (&server_url).into(),
385 timeout,
386 };
387 config.validate()?;
388 let _ = configured_builder(PocketIcBuilder::new(), &server_url)?;
389 return Ok(config);
390 }
391 let value = variable("POCKET_IC_BIN")
392 .ok_or_else(|| PocketIcStartupError::new(PocketIcStartupFailure::NotConfigured))?;
393 if value.is_empty() {
394 return Err(PocketIcStartupError::new(
395 PocketIcStartupFailure::InvalidEnvironment {
396 variable: "POCKET_IC_BIN",
397 },
398 ));
399 }
400 let path = PathBuf::from(value);
401 let binary = fs::canonicalize(&path).map_err(|source| {
402 PocketIcStartupError::new(PocketIcStartupFailure::Io {
403 operation: "resolve configured PocketIC executable",
404 path,
405 source,
406 })
407 })?;
408 let config = Self::Spawn {
409 server_binary: (&binary).into(),
410 timeout,
411 server_hard_ttl: None,
412 server_idle_ttl: None,
413 server_output_files: None,
414 };
415 config.validate()?;
416 let evidence = ic_host_process::tool::capture_group_command(
417 Command::new(&binary).arg("--version"),
418 ic_host_process::tool::OutputLimits {
419 stdout: ic_host_process::tool::OutputLimit::Terminate(SERVER_OUTPUT_LIMIT),
420 stderr: ic_host_process::tool::OutputLimit::Terminate(SERVER_OUTPUT_LIMIT),
421 timeout: Some(timeout),
422 },
423 )
424 .and_then(ic_host_process::tool::CompletedExecution::require_success)
425 .map_err(|source| {
426 PocketIcStartupError::new(PocketIcStartupFailure::ServerVersionProbe { source })
427 })?;
428 let expected = super::server::expected_server_version();
429 if !super::supports_pocket_ic_server(&evidence.stdout) {
430 return Err(PocketIcStartupError::new(
431 PocketIcStartupFailure::ServerVersionMismatch {
432 expected,
433 observed: evidence.stdout,
434 },
435 ));
436 }
437 Ok(config)
438 }
439
440 #[must_use]
442 pub const fn timeout(&self) -> Duration {
443 match self {
444 Self::Spawn { timeout, .. } | Self::Connect { timeout, .. } => *timeout,
445 }
446 }
447
448 pub fn build_instance(
472 self,
473 builder: PocketIcBuilder,
474 ) -> Result<PocketIcInstance<PocketIc>, PocketIcStartupError> {
475 let startup = StartupDeadline::new(&self)?;
476 let (server, url) = match self {
477 Self::Connect { server_url, .. } => (None, server_url),
478 spawn @ Self::Spawn { .. } => {
479 let (server, url) = spawn.spawn_server(startup.started)?.wait_ready(&startup)?;
480 (Some(server), url)
481 }
482 };
483 build_bounded(builder, &url, &startup, server)
484 }
485
486 pub async fn build_instance_async(
522 self,
523 builder: PocketIcBuilder,
524 ) -> Result<PocketIcInstance<ic_platform::pocket_ic::nonblocking::PocketIc>, PocketIcStartupError>
525 {
526 let startup = StartupDeadline::new(&self)?;
527 let (server, server_url) = match self {
528 Self::Connect { server_url, .. } => (None, server_url),
529 spawn @ Self::Spawn { .. } => {
530 let mut server = spawn.spawn_server(startup.started)?;
531 let server_url = loop {
532 match server.poll_ready(&startup) {
533 Ok(Some(url)) => break url,
534 Ok(None) => {
535 tokio::time::sleep(
536 startup
537 .deadline
538 .saturating_duration_since(Instant::now())
539 .min(STARTUP_POLL_INTERVAL),
540 )
541 .await;
542 }
543 Err(error) => return Err(finalize_failure(error, None, Some(server))),
544 }
545 };
546 (Some(server), server_url)
547 }
548 };
549 build_async_bounded(builder, &server_url, &startup, server).await
550 }
551
552 pub fn start_managed_server(self) -> Result<PocketIcManagedServer, PocketIcStartupError> {
569 if matches!(self, Self::Connect { .. }) {
570 self.validate()?;
571 return Err(PocketIcStartupError::new(
572 PocketIcStartupFailure::InvalidConfiguration {
573 message: "starting a managed PocketIC server requires a spawn configuration"
574 .to_owned(),
575 },
576 ));
577 }
578 let startup = StartupDeadline::new(&self)?;
579 let (server, url) = self.spawn_server(startup.started)?.wait_ready(&startup)?;
580 Ok(PocketIcManagedServer { server, url })
581 }
582
583 fn spawn_server(self, started: Instant) -> Result<ManagedServer, PocketIcStartupError> {
586 let Self::Spawn {
587 server_binary,
588 server_hard_ttl,
589 server_idle_ttl,
590 server_output_files,
591 ..
592 } = self
593 else {
594 unreachable!("connect configurations do not spawn a server")
595 };
596 ManagedServer::spawn(
597 server_binary,
598 server_hard_ttl,
599 server_idle_ttl,
600 server_output_files,
601 started,
602 )
603 }
604
605 pub fn run_command(
625 self,
626 command: &mut Command,
627 mut cancelled: impl FnMut() -> bool,
628 ) -> Result<ExitStatus, PocketIcStartupError> {
629 self.validate()?;
630 let program = PathBuf::from(command.get_program());
631 let command_error = |source| {
632 PocketIcStartupError::new(PocketIcStartupFailure::CommandRun {
633 program: program.clone(),
634 source,
635 })
636 };
637 if cancelled() {
638 return Err(command_error(io::Error::from(io::ErrorKind::Interrupted)));
639 }
640 let (server, url) = match self {
641 Self::Connect { server_url, .. } => (None, server_url),
642 spawn @ Self::Spawn { .. } => {
643 let server = spawn.start_managed_server()?;
644 let url = server.url().to_owned();
645 (Some(server.server), url)
646 }
647 };
648 let mut server = server;
649 if cancelled() {
650 return Err(finalize_failure(
651 command_error(io::Error::from(io::ErrorKind::Interrupted)),
652 None,
653 server,
654 ));
655 }
656 command.env("IC_TESTKIT_POCKET_IC_URL", url);
657 let mut owned_child = match OwnedChild::spawn(command, CleanupPolicy::KillAndWait) {
658 Ok(child) => child,
659 Err(source) => {
660 return Err(finalize_failure(
661 PocketIcStartupError::new(PocketIcStartupFailure::Io {
662 operation: "spawn command with PocketIC server",
663 path: PathBuf::from(command.get_program()),
664 source,
665 }),
666 None,
667 server,
668 ));
669 }
670 };
671 let result = loop {
672 if cancelled() {
673 break Err(command_error(io::Error::from(io::ErrorKind::Interrupted)));
674 }
675 match owned_child.try_wait() {
676 Ok(Some(status)) => break Ok(status),
677 Ok(None) => {
678 if let Some(managed) = server.as_mut() {
679 match managed.try_wait() {
680 Ok(Some(status)) => break Err(managed.exit_failure(status)),
681 Ok(None) => {}
682 Err(error) => break Err(error),
683 }
684 }
685 thread::sleep(STARTUP_POLL_INTERVAL);
686 }
687 Err(source) => break Err(command_error(source)),
688 }
689 };
690 match result {
691 Err(error) => Err(finalize_failure(error, Some(&mut owned_child), server)),
692 Ok(status) => {
693 if let Some(server) = server {
694 let (output, cleanup) = server.terminate_and_capture();
695 if let Some(cleanup) = cleanup {
696 return Err(PocketIcStartupError::new(
697 PocketIcStartupFailure::ServerCleanup {
698 command_status: status,
699 },
700 )
701 .with_cleanup(None, Some((output, Some(cleanup)))));
702 }
703 }
704 Ok(status)
705 }
706 }
707 }
708
709 fn validate(&self) -> Result<(), PocketIcStartupError> {
710 if self.timeout().is_zero() {
711 return Err(PocketIcStartupError::new(
712 PocketIcStartupFailure::InvalidConfiguration {
713 message: "PocketIC startup timeout must be greater than zero".to_owned(),
714 },
715 ));
716 }
717 if let Self::Spawn {
718 server_hard_ttl,
719 server_idle_ttl,
720 ..
721 } = self
722 {
723 for (ttl, message) in [
724 (
725 server_hard_ttl,
726 "PocketIC server hard TTL must be at least one second",
727 ),
728 (
729 server_idle_ttl,
730 "PocketIC server idle TTL must be at least one second",
731 ),
732 ] {
733 if ttl.is_some_and(|ttl| ttl.as_secs() == 0) {
734 return Err(PocketIcStartupError::new(
735 PocketIcStartupFailure::InvalidConfiguration {
736 message: message.to_owned(),
737 },
738 ));
739 }
740 }
741 }
742 Ok(())
743 }
744}
745
746impl PocketIcManagedServer {
747 #[must_use]
754 pub fn process_id(&self) -> u32 {
755 self.server.child.id()
756 }
757
758 #[must_use]
760 pub fn url(&self) -> &str {
761 &self.url
762 }
763
764 #[must_use]
770 pub fn output(&self) -> PocketIcManagedServerOutput {
771 self.server.files.capture()
772 }
773}
774
775impl PocketIcManagedServerOutput {
776 #[must_use]
778 pub fn stdout(&self) -> &str {
779 &self.stdout
780 }
781
782 #[must_use]
784 pub fn stderr(&self) -> &str {
785 &self.stderr
786 }
787}
788
789struct StartupDeadline {
790 started: Instant,
791 timeout: Duration,
792 deadline: Instant,
793}
794
795impl StartupDeadline {
796 fn new(config: &PocketIcStartupConfig) -> Result<Self, PocketIcStartupError> {
797 config.validate()?;
798 let started = Instant::now();
799 let timeout = config.timeout();
800 Ok(Self {
801 started,
802 timeout,
803 deadline: startup_deadline(started, timeout)?,
804 })
805 }
806
807 fn check_instance_deadline(
808 &self,
809 server: &mut Option<ManagedServer>,
810 ) -> Result<Instant, PocketIcStartupError> {
811 let now = Instant::now();
812 if now >= self.deadline {
813 return Err(finalize_failure(
814 PocketIcStartupError::new(PocketIcStartupFailure::InstanceCreationTimeout {
815 timeout: self.timeout,
816 }),
817 None,
818 server.take(),
819 ));
820 }
821 Ok(now)
822 }
823
824 fn admit_instance<T>(
825 &self,
826 instance: T,
827 server_url: &str,
828 server: &mut Option<ManagedServer>,
829 ) -> Result<PocketIcInstance<T>, PocketIcStartupError> {
830 self.check_instance_deadline(server)?;
831 check_server(server)?;
832 Ok(PocketIcInstance {
833 instance,
834 server: server.take().map(|server| PocketIcManagedServer {
835 server,
836 url: server_url.to_owned(),
837 }),
838 })
839 }
840}
841
842fn startup_deadline(started: Instant, timeout: Duration) -> Result<Instant, PocketIcStartupError> {
843 started.checked_add(timeout).ok_or_else(|| {
844 PocketIcStartupError::new(PocketIcStartupFailure::InvalidConfiguration {
845 message: "PocketIC startup timeout exceeds the platform clock range".to_owned(),
846 })
847 })
848}
849
850fn build_bounded(
851 builder: PocketIcBuilder,
852 server_url: &str,
853 startup: &StartupDeadline,
854 mut server: Option<ManagedServer>,
855) -> Result<PocketIcInstance<PocketIc>, PocketIcStartupError> {
856 let builder = configured_builder(builder, server_url)
857 .map_err(|error| finalize_failure(error, None, server.take()))?;
858 let (sender, receiver) = mpsc::sync_channel(1);
859 if let Err(source) = thread::Builder::new()
860 .name("ic-testkit-pocket-ic-startup".to_owned())
861 .spawn(move || {
862 let result = transport::capture_operation(|| builder.build());
863 let _ = sender.send(result);
864 })
865 {
866 return Err(finalize_failure(
867 PocketIcStartupError::new(PocketIcStartupFailure::BuilderThreadSpawn { source }),
868 None,
869 server,
870 ));
871 }
872 await_builder(receiver, server_url, startup, &mut server)
873}
874
875#[expect(
876 clippy::needless_pass_by_value,
877 reason = "consume the receiver so failed startup disconnects late builders"
878)]
879fn await_builder(
880 receiver: mpsc::Receiver<Result<PocketIc, super::PocketIcOperationError>>,
881 server_url: &str,
882 startup: &StartupDeadline,
883 server: &mut Option<ManagedServer>,
884) -> Result<PocketIcInstance<PocketIc>, PocketIcStartupError> {
885 loop {
886 let now = startup.check_instance_deadline(server)?;
887 let remaining = startup.deadline.saturating_duration_since(now);
888 let wait = if server.is_some() {
889 remaining.min(STARTUP_POLL_INTERVAL)
890 } else {
891 remaining
892 };
893 match receiver.recv_timeout(wait) {
894 Ok(Ok(pocket_ic)) => {
895 return startup.admit_instance(pocket_ic, server_url, server);
896 }
897 Ok(Err(source)) => {
898 return Err(finalize_failure(
899 PocketIcStartupError::new(PocketIcStartupFailure::BuilderPanicked { source }),
900 None,
901 server.take(),
902 ));
903 }
904 Err(RecvTimeoutError::Disconnected) => {
905 return Err(finalize_failure(
906 PocketIcStartupError::new(PocketIcStartupFailure::BuilderDisconnected),
907 None,
908 server.take(),
909 ));
910 }
911 Err(RecvTimeoutError::Timeout) => {
912 check_server(server)?;
913 }
914 }
915 }
916}
917
918fn configured_builder(
919 builder: PocketIcBuilder,
920 server_url: &str,
921) -> Result<PocketIcBuilder, PocketIcStartupError> {
922 server_url
923 .parse()
924 .map(|url| builder.with_server_url(url))
925 .map_err(|error| {
926 PocketIcStartupError::new(PocketIcStartupFailure::InvalidServerUrl {
927 server_url: server_url.to_owned(),
928 message: error.to_string(),
929 })
930 })
931}
932
933fn check_server(server: &mut Option<ManagedServer>) -> Result<(), PocketIcStartupError> {
934 if let Some(managed) = server.as_mut() {
935 let error = match managed.try_wait() {
936 Ok(Some(status)) => Some(managed.exit_failure(status)),
937 Ok(None) => None,
938 Err(error) => Some(error),
939 };
940 if let Some(error) = error {
941 return Err(finalize_failure(error, None, server.take()));
942 }
943 }
944 Ok(())
945}
946
947async fn build_async_bounded(
948 builder: PocketIcBuilder,
949 server_url: &str,
950 startup: &StartupDeadline,
951 mut server: Option<ManagedServer>,
952) -> Result<PocketIcInstance<ic_platform::pocket_ic::nonblocking::PocketIc>, PocketIcStartupError> {
953 let builder = configured_builder(builder, server_url)
954 .map_err(|error| finalize_failure(error, None, server.take()))?;
955 let mut construction = std::pin::pin!(builder.build_async());
956 let mut construction = std::pin::pin!(std::future::poll_fn(|context| {
957 match transport::capture_operation(|| construction.as_mut().poll(context)) {
958 Ok(poll) => poll.map(Ok),
959 Err(source) => std::task::Poll::Ready(Err(PocketIcStartupError::new(
960 PocketIcStartupFailure::BuilderPanicked { source },
961 ))),
962 }
963 }));
964 let mut server = server;
966 loop {
967 let now = startup.check_instance_deadline(&mut server)?;
968 check_server(&mut server)?;
969 let next_check = if server.is_some() {
970 now + startup
971 .deadline
972 .saturating_duration_since(now)
973 .min(STARTUP_POLL_INTERVAL)
974 } else {
975 startup.deadline
976 };
977 match tokio::time::timeout_at(next_check.into(), construction.as_mut()).await {
978 Ok(Ok(instance)) => {
979 return startup.admit_instance(instance, server_url, &mut server);
980 }
981 Ok(Err(error)) => return Err(finalize_failure(error, None, server)),
982 Err(_) => {}
983 }
984 }
985}
986
987fn finalize_failure(
989 error: PocketIcStartupError,
990 command: Option<&mut OwnedChild>,
991 server: Option<ManagedServer>,
992) -> PocketIcStartupError {
993 error.with_cleanup(
994 command.and_then(|child| child.terminate().err()),
995 server.map(ManagedServer::terminate_and_capture),
996 )
997}
998
999struct ManagedServer {
1000 child: OwnedChild,
1001 binary: PathBuf,
1002 files: StartupFiles,
1003 started: Instant,
1004}
1005
1006enum PortFileState {
1007 Pending,
1008 Ready(u16),
1009 Invalid(String),
1010}
1011
1012impl ManagedServer {
1013 fn wait_ready(
1014 mut self,
1015 startup: &StartupDeadline,
1016 ) -> Result<(Self, String), PocketIcStartupError> {
1017 loop {
1018 match self.poll_ready(startup) {
1019 Ok(Some(url)) => return Ok((self, url)),
1020 Ok(None) => thread::sleep(
1021 startup
1022 .deadline
1023 .saturating_duration_since(Instant::now())
1024 .min(STARTUP_POLL_INTERVAL),
1025 ),
1026 Err(error) => return Err(finalize_failure(error, None, Some(self))),
1027 }
1028 }
1029 }
1030
1031 fn spawn(
1032 binary: PathBuf,
1033 hard_ttl: Option<Duration>,
1034 idle_ttl: Option<Duration>,
1035 output_files: Option<(PathBuf, PathBuf)>,
1036 started: Instant,
1037 ) -> Result<Self, PocketIcStartupError> {
1038 let (files, stdout, stderr) = StartupFiles::create(output_files)?;
1039 let mut command = Command::new(&binary);
1040 if let Some(hard_ttl) = hard_ttl {
1041 command
1042 .arg("--hard-ttl")
1043 .arg(hard_ttl.as_secs().to_string());
1044 }
1045 if let Some(idle_ttl) = idle_ttl {
1046 command.arg("--ttl").arg(idle_ttl.as_secs().to_string());
1047 }
1048 command
1049 .arg("--port-file")
1050 .arg(&files.port)
1051 .stdout(Stdio::from(stdout))
1052 .stderr(Stdio::from(stderr));
1053 let child =
1054 OwnedChild::spawn(&mut command, CleanupPolicy::KillAndWait).map_err(|source| {
1055 PocketIcStartupError::new(PocketIcStartupFailure::ServerSpawn {
1056 server_binary: binary.clone(),
1057 source,
1058 })
1059 })?;
1060 Ok(Self {
1061 child,
1062 binary,
1063 files,
1064 started,
1065 })
1066 }
1067
1068 fn poll_ready(
1069 &mut self,
1070 startup: &StartupDeadline,
1071 ) -> Result<Option<String>, PocketIcStartupError> {
1072 if let Some(status) = self.try_wait()? {
1073 return Err(self.exit_failure(status));
1074 }
1075 if Instant::now() >= startup.deadline {
1076 return Err(PocketIcStartupError::new(
1077 PocketIcStartupFailure::ReadinessTimeout {
1078 server_binary: self.binary.clone(),
1079 timeout: startup.timeout,
1080 },
1081 ));
1082 }
1083 match self.files.read_port()? {
1084 PortFileState::Pending => Ok(None),
1085 PortFileState::Ready(port) => Ok(Some(format!("http://127.0.0.1:{port}/"))),
1086 PortFileState::Invalid(value) => Err(PocketIcStartupError::new(
1087 PocketIcStartupFailure::InvalidServerPort {
1088 server_binary: self.binary.clone(),
1089 value,
1090 },
1091 )),
1092 }
1093 }
1094
1095 fn try_wait(&mut self) -> Result<Option<ExitStatus>, PocketIcStartupError> {
1096 self.child.try_wait().map_err(|source| {
1097 PocketIcStartupError::new(PocketIcStartupFailure::Io {
1098 operation: "inspect PocketIC server child",
1099 path: self.binary.clone(),
1100 source,
1101 })
1102 })
1103 }
1104
1105 fn exit_failure(&self, status: ExitStatus) -> PocketIcStartupError {
1106 PocketIcStartupError::new(PocketIcStartupFailure::ServerExited {
1107 server_binary: self.binary.clone(),
1108 status,
1109 elapsed: self.started.elapsed(),
1110 })
1111 }
1112
1113 fn terminate_and_capture(self) -> (PocketIcManagedServerOutput, Option<CleanupError>) {
1114 let Self {
1115 mut child, files, ..
1116 } = self;
1117 let cleanup = child.terminate().err();
1118 drop(child);
1120 (files.capture(), cleanup)
1121 }
1122}
1123
1124struct StartupFiles {
1125 #[cfg_attr(
1126 not(test),
1127 expect(
1128 dead_code,
1129 reason = "retains directory ownership until cleanup or drop"
1130 )
1131 )]
1132 directory: OwnedDirectory,
1133 port: PathBuf,
1134 stdout: PathBuf,
1135 stderr: PathBuf,
1136}
1137
1138impl StartupFiles {
1139 fn read_port(&self) -> Result<PortFileState, PocketIcStartupError> {
1140 let port_path = &self.port;
1141 let mut contents = String::new();
1142 match ic_host_fs::read::open_regular_file(port_path)
1143 .map_err(|error| match error {
1144 ic_host_artifacts::artifact::ArtifactError::Io(source) => source,
1145 error => io::Error::new(io::ErrorKind::InvalidData, error),
1146 })
1147 .and_then(|file| {
1148 file.take((SERVER_PORT_FILE_LIMIT + 1) as u64)
1149 .read_to_string(&mut contents)
1150 }) {
1151 Ok(_) => {}
1152 Err(error) if error.kind() == io::ErrorKind::NotFound => {
1153 return Ok(PortFileState::Pending);
1154 }
1155 Err(source) => {
1156 return Err(PocketIcStartupError::new(PocketIcStartupFailure::Io {
1157 operation: "read PocketIC server port file",
1158 path: port_path.clone(),
1159 source,
1160 }));
1161 }
1162 }
1163 if contents.len() > SERVER_PORT_FILE_LIMIT {
1164 return Ok(PortFileState::Invalid(format!(
1165 "{} (port file exceeds {SERVER_PORT_FILE_LIMIT} bytes)",
1166 contents.trim()
1167 )));
1168 }
1169 if !contents.contains('\n') {
1170 return Ok(PortFileState::Pending);
1171 }
1172 let value = contents.trim().to_owned();
1173 match value.parse::<u16>() {
1174 Ok(port) if port != 0 => Ok(PortFileState::Ready(port)),
1175 _ => Ok(PortFileState::Invalid(value)),
1176 }
1177 }
1178
1179 fn capture(&self) -> PocketIcManagedServerOutput {
1180 PocketIcManagedServerOutput {
1181 stdout: read_bounded_lossy(&self.stdout),
1182 stderr: read_bounded_lossy(&self.stderr),
1183 }
1184 }
1185
1186 fn create(
1187 output_files: Option<(PathBuf, PathBuf)>,
1188 ) -> Result<(Self, File, File), PocketIcStartupError> {
1189 let output_files = output_files
1190 .map(|(stdout, stderr)| {
1191 Ok::<_, PocketIcStartupError>((
1192 std::path::absolute(&stdout)
1193 .map_err(|source| startup_file_error("resolve", &stdout, source))?,
1194 std::path::absolute(&stderr)
1195 .map_err(|source| startup_file_error("resolve", &stderr, source))?,
1196 ))
1197 })
1198 .transpose()?;
1199 let directory = OwnedDirectory::new(
1200 create_unique_directory(
1201 &std::env::temp_dir(),
1202 "ic-testkit-pocket-ic-startup",
1203 0o700,
1204 None,
1205 )
1206 .map_err(|source| startup_file_error("create", &std::env::temp_dir(), source))?,
1207 );
1208 let base = directory.path();
1209 let (stdout_path, stderr_path) =
1210 output_files.unwrap_or_else(|| (base.join("stdout"), base.join("stderr")));
1211 let files = Self {
1212 port: base.join("port"),
1213 stdout: stdout_path,
1214 stderr: stderr_path,
1215 directory,
1216 };
1217 let stdout = create_new_file(&files.stdout)
1218 .map_err(|source| startup_file_error("create", &files.stdout, source))?;
1219 let stderr = create_new_file(&files.stderr)
1220 .map_err(|source| startup_file_error("create", &files.stderr, source))?;
1221 Ok((files, stdout, stderr))
1222 }
1223}
1224
1225fn create_new_file(path: &Path) -> io::Result<File> {
1226 let mut options = OpenOptions::new();
1227 options.write(true).create_new(true);
1228 #[cfg(unix)]
1229 options.mode(0o600);
1230 options.open(path)
1231}
1232
1233fn startup_file_error(
1234 operation: &'static str,
1235 path: &Path,
1236 source: io::Error,
1237) -> PocketIcStartupError {
1238 PocketIcStartupError::new(PocketIcStartupFailure::Io {
1239 operation,
1240 path: path.to_owned(),
1241 source,
1242 })
1243}
1244
1245fn read_bounded_lossy(path: &Path) -> String {
1246 let Ok((bytes, length)) = ic_host_fs::read::read_file_prefix(path, SERVER_OUTPUT_LIMIT) else {
1247 return String::new();
1248 };
1249 let mut output = String::from_utf8_lossy(&bytes).into_owned();
1250 let omitted = length.saturating_sub(bytes.len() as u64);
1251 if omitted > 0 {
1252 let _ = write!(output, "\n<truncated {omitted} bytes>");
1253 }
1254 output
1255}
1256
1257impl std::fmt::Display for PocketIcStartupError {
1258 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1259 std::fmt::Display::fmt(self.failure.as_ref(), formatter)?;
1260 if !self.output.stdout.is_empty() {
1261 write!(formatter, "; server stdout: {}", self.output.stdout)?;
1262 }
1263 if !self.output.stderr.is_empty() {
1264 write!(formatter, "; server stderr: {}", self.output.stderr)?;
1265 }
1266 for (owner, cleanup) in [
1267 ("command", self.command_cleanup()),
1268 ("server", self.server_cleanup()),
1269 ] {
1270 if let Some(error) = cleanup {
1271 write!(formatter, "; {owner} cleanup also failed: {error}")?;
1272 }
1273 }
1274 Ok(())
1275 }
1276}
1277
1278impl std::error::Error for PocketIcStartupError {
1279 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1280 std::error::Error::source(self.failure.as_ref())
1281 }
1282}
1283
1284#[cfg(test)]
1285mod tests {
1286 mod instances;
1287
1288 use std::{
1289 fs,
1290 path::PathBuf,
1291 time::{Duration, Instant},
1292 };
1293
1294 use super::{
1295 OwnedDirectory, PocketIcStartupConfig, PocketIcStartupError, PocketIcStartupFailure,
1296 StartupFiles, create_unique_directory,
1297 };
1298 use ic_platform::pocket_ic::PocketIcBuilder;
1299
1300 #[cfg(unix)]
1301 use ic_host_process::testing::write_executable_script;
1302 #[cfg(unix)]
1303 use std::{
1304 io::Write as _,
1305 os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _},
1306 process::Command,
1307 sync::mpsc,
1308 };
1309
1310 #[test]
1311 fn completed_instances_must_still_meet_the_startup_deadline() {
1312 let started = Instant::now();
1313 let startup = super::StartupDeadline {
1314 started,
1315 timeout: Duration::from_secs(60),
1316 deadline: started + Duration::from_secs(60),
1317 };
1318 let mut server = None;
1319 let instance = startup
1320 .admit_instance(7_u8, "http://localhost/", &mut server)
1321 .unwrap();
1322 assert_eq!(*instance.instance(), 7);
1323 assert!(server.is_none());
1324 let expired = super::StartupDeadline {
1325 deadline: started,
1326 ..startup
1327 };
1328 let error = expired
1329 .admit_instance(7_u8, "http://localhost/", &mut server)
1330 .err()
1331 .expect("completed instance after the deadline must refuse admission");
1332 assert!(
1333 matches!(error.failure(), PocketIcStartupFailure::InstanceCreationTimeout { timeout } if *timeout == Duration::from_secs(60))
1334 );
1335 assert!(server.is_none());
1336 }
1337
1338 #[test]
1339 fn original_failure_output_and_both_typed_cleanup_reports_survive_projection() {
1340 use std::error::Error as _;
1341 for failure in [
1342 PocketIcStartupFailure::ReadinessTimeout {
1343 server_binary: "server".into(),
1344 timeout: Duration::from_secs(1),
1345 },
1346 PocketIcStartupFailure::InstanceCreationTimeout {
1347 timeout: Duration::from_secs(1),
1348 },
1349 PocketIcStartupFailure::InvalidServerPort {
1350 server_binary: "server".into(),
1351 value: "invalid".into(),
1352 },
1353 PocketIcStartupFailure::BuilderPanicked {
1354 source: super::super::PocketIcOperationError::new("original-panic"),
1355 },
1356 PocketIcStartupFailure::BuilderDisconnected,
1357 PocketIcStartupFailure::BuilderThreadSpawn {
1358 source: std::io::Error::from_raw_os_error(9),
1359 },
1360 PocketIcStartupFailure::Io {
1361 operation: "original-io",
1362 path: "port".into(),
1363 source: std::io::Error::from_raw_os_error(9),
1364 },
1365 ] {
1366 let primary_text = failure.to_string();
1367 let output = super::PocketIcManagedServerOutput {
1368 stdout: "original-stdout".into(),
1369 stderr: "original-stderr".into(),
1370 };
1371 let command = super::CleanupError {
1372 status: None,
1373 group_error: None,
1374 term_error: Some(std::io::Error::from_raw_os_error(4)),
1375 kill_error: Some(std::io::Error::from_raw_os_error(5)),
1376 wait_error: None,
1377 };
1378 let server = super::CleanupError {
1379 status: None,
1380 group_error: Some(std::io::Error::from_raw_os_error(1)),
1381 term_error: None,
1382 kill_error: None,
1383 wait_error: Some(std::io::Error::from_raw_os_error(10)),
1384 };
1385 let error = PocketIcStartupError::new(failure)
1386 .with_cleanup(Some(command), Some((output, Some(server))));
1387 assert_eq!(error.failure().to_string(), primary_text);
1388 assert_eq!(error.output().stdout(), "original-stdout");
1389 assert_eq!(error.output().stderr(), "original-stderr");
1390 let command = error.command_cleanup().unwrap();
1391 let server = error.server_cleanup().unwrap();
1392 assert_eq!(command.kill_error.as_ref().unwrap().raw_os_error(), Some(5));
1393 assert_eq!(command.term_error.as_ref().unwrap().raw_os_error(), Some(4));
1394 assert_eq!(server.group_error.as_ref().unwrap().raw_os_error(), Some(1));
1395 assert_eq!(server.wait_error.as_ref().unwrap().raw_os_error(), Some(10));
1396 if matches!(
1397 error.failure(),
1398 PocketIcStartupFailure::Io { .. }
1399 | PocketIcStartupFailure::BuilderThreadSpawn { .. }
1400 ) {
1401 assert_eq!(
1402 error
1403 .source()
1404 .unwrap()
1405 .downcast_ref::<std::io::Error>()
1406 .unwrap()
1407 .raw_os_error(),
1408 Some(9)
1409 );
1410 }
1411 if let PocketIcStartupFailure::BuilderPanicked { source } = error.failure() {
1412 assert_eq!(
1413 error
1414 .source()
1415 .unwrap()
1416 .downcast_ref::<super::super::PocketIcOperationError>(),
1417 Some(source)
1418 );
1419 }
1420 let displayed = error.to_string();
1421 assert!(displayed.starts_with(&primary_text));
1422 for marker in [
1423 "original-stdout",
1424 "original-stderr",
1425 "command cleanup also failed",
1426 "server cleanup also failed",
1427 ] {
1428 assert!(displayed.contains(marker));
1429 }
1430 }
1431 let error = PocketIcStartupError::new(PocketIcStartupFailure::NotConfigured);
1432 assert_eq!(error.to_string(), error.failure().to_string());
1433 assert!(error.command_cleanup().is_none());
1434 assert!(error.server_cleanup().is_none());
1435 }
1436
1437 #[cfg(unix)]
1438 #[test]
1439 fn builder_failures_finalize_the_owned_server_and_keep_output() {
1440 for disconnected in [false, true] {
1441 let script = TestServerScript::new(
1442 "builder-failure",
1443 "#!/bin/sh\nprintf '%s\n%s\n' \"$$\" \"$2\"\nprintf 'builder-diagnostic' >&2\nprintf '34567\n' > \"$2\"\nexec sleep 30\n",
1444 );
1445 let managed = PocketIcStartupConfig::Spawn {
1446 server_binary: script.path(),
1447 timeout: Duration::from_secs(2),
1448 server_hard_ttl: None,
1449 server_idle_ttl: None,
1450 server_output_files: None,
1451 }
1452 .start_managed_server()
1453 .unwrap();
1454 let pid = managed.process_id();
1455 let directory = managed.server.files.directory.path().to_path_buf();
1456 let (sender, receiver) = mpsc::channel();
1457 if !disconnected {
1458 sender
1459 .send(Err(super::super::PocketIcOperationError::new(
1460 "original-builder-panic",
1461 )))
1462 .unwrap();
1463 }
1464 drop(sender);
1465 let error = super::await_builder(
1466 receiver,
1467 "http://127.0.0.1:34567/",
1468 &super::StartupDeadline {
1469 started: Instant::now(),
1470 deadline: Instant::now() + Duration::from_secs(2),
1471 timeout: Duration::from_secs(2),
1472 },
1473 &mut Some(managed.server),
1474 )
1475 .err()
1476 .unwrap();
1477 assert!(matches!(
1478 (disconnected, error.failure()),
1479 (true, PocketIcStartupFailure::BuilderDisconnected)
1480 | (false, PocketIcStartupFailure::BuilderPanicked { .. })
1481 ));
1482 assert_eq!(error.output().stderr(), "builder-diagnostic");
1483 assert!(error.server_cleanup().is_none());
1484 assert!(!directory.exists());
1485 assert_eq!(process_state(pid), None);
1486 }
1487 }
1488
1489 #[cfg(unix)]
1490 #[test]
1491 fn port_io_and_command_spawn_failures_finalize_the_owned_server() {
1492 for port_io in [true, false] {
1493 let port = if port_io {
1494 "mkfifo \"$2\""
1495 } else {
1496 "printf '34567\n' > \"$2\""
1497 };
1498 let script = TestServerScript::new(
1499 "owned-io-failure",
1500 &format!(
1501 "#!/bin/sh\nprintf '%s\n%s\n' \"$$\" \"$2\"\nprintf 'original-server-diagnostic' >&2\n{port}\nexec sleep 30\n"
1502 ),
1503 );
1504 let config = PocketIcStartupConfig::Spawn {
1505 server_binary: script.path(),
1506 timeout: Duration::from_secs(2),
1507 server_hard_ttl: None,
1508 server_idle_ttl: None,
1509 server_output_files: None,
1510 };
1511 let error = if port_io {
1512 config.start_managed_server().err().unwrap()
1513 } else {
1514 config
1515 .run_command(&mut Command::new("/missing/ic-testkit-command"), || false)
1516 .unwrap_err()
1517 };
1518 let PocketIcStartupFailure::Io { source, .. } = error.failure() else {
1519 panic!("expected original IO failure: {error:?}");
1520 };
1521 assert_eq!(
1522 source.kind(),
1523 if port_io {
1524 std::io::ErrorKind::InvalidData
1525 } else {
1526 std::io::ErrorKind::NotFound
1527 }
1528 );
1529 assert_eq!(error.output().stderr(), "original-server-diagnostic");
1530 let mut lines = error.output().stdout().lines();
1531 let pid = lines.next().unwrap().parse().unwrap();
1532 let port = PathBuf::from(lines.next().unwrap());
1533 assert_eq!(process_state(pid), None);
1534 assert!(!port.parent().unwrap().exists());
1535 assert!(error.server_cleanup().is_none());
1536 }
1537 }
1538
1539 #[cfg(unix)]
1540 #[test]
1541 fn command_cancellation_before_startup_has_no_spawn_effects() {
1542 let error = PocketIcStartupConfig::Spawn {
1543 server_binary: ("/missing/server").into(),
1544 timeout: Duration::from_secs(1),
1545 server_hard_ttl: None,
1546 server_idle_ttl: None,
1547 server_output_files: None,
1548 }
1549 .run_command(&mut Command::new("/missing/command"), || true)
1550 .unwrap_err();
1551 assert!(
1552 matches!(error.failure(), PocketIcStartupFailure::CommandRun { source, .. } if source.kind() == std::io::ErrorKind::Interrupted)
1553 );
1554 assert_eq!(error.output().stdout(), "");
1555 assert_eq!(error.output().stderr(), "");
1556 assert!(error.command_cleanup().is_none());
1557 assert!(error.server_cleanup().is_none());
1558 }
1559
1560 #[cfg(unix)]
1561 #[test]
1562 fn cancellation_callback_panic_still_reaps_the_owned_command() {
1563 let script = TestServerScript::new(
1564 "cancel-panic",
1565 "#!/bin/sh\nprintf '%s' \"$$\" > \"$1\"\nexec sleep 30\n",
1566 );
1567 let pid_file = script.path().with_extension("pid");
1568 let result = std::panic::catch_unwind(|| {
1569 PocketIcStartupConfig::Connect {
1570 server_url: ("http://127.0.0.1:12345/").into(),
1571 timeout: Duration::from_secs(1),
1572 }
1573 .run_command(Command::new(script.path()).arg(&pid_file), || {
1574 assert!(
1575 !fs::read_to_string(&pid_file).is_ok_and(|value| !value.is_empty()),
1576 "caller cancellation failed"
1577 );
1578 false
1579 })
1580 });
1581 assert!(result.is_err());
1582 let pid = fs::read_to_string(&pid_file).unwrap().parse().unwrap();
1583 assert!(process_state(pid).is_none_or(|state| state == 'Z'));
1584 fs::remove_file(pid_file).unwrap();
1585 }
1586
1587 #[cfg(unix)]
1588 #[test]
1589 fn environment_selection_prefers_urls_and_fails_closed() {
1590 use std::os::unix::ffi::OsStringExt as _;
1591
1592 let timeout = Duration::from_secs(1);
1593 let config = PocketIcStartupConfig::from_environment(timeout, |name| {
1594 Some(
1595 if name == "IC_TESTKIT_POCKET_IC_URL" {
1596 "http://127.0.0.1:12345/"
1597 } else {
1598 "/missing/server"
1599 }
1600 .into(),
1601 )
1602 })
1603 .unwrap();
1604 assert!(
1605 matches!(config, PocketIcStartupConfig::Connect { ref server_url, .. } if server_url == "http://127.0.0.1:12345/")
1606 );
1607 assert!(matches!(
1608 PocketIcStartupConfig::from_environment(timeout, |_| None)
1609 .as_ref()
1610 .map_err(PocketIcStartupError::failure),
1611 Err(PocketIcStartupFailure::NotConfigured)
1612 ));
1613 assert!(matches!(
1614 PocketIcStartupConfig::from_environment(timeout, |_| Some("".into()))
1615 .as_ref()
1616 .map_err(PocketIcStartupError::failure),
1617 Err(PocketIcStartupFailure::InvalidEnvironment {
1618 variable: "IC_TESTKIT_POCKET_IC_URL"
1619 })
1620 ));
1621 assert!(matches!(
1622 PocketIcStartupConfig::from_environment(timeout, |_| Some("bad URL".into()))
1623 .as_ref()
1624 .map_err(PocketIcStartupError::failure),
1625 Err(PocketIcStartupFailure::InvalidServerUrl { .. })
1626 ));
1627 assert!(matches!(
1628 PocketIcStartupConfig::from_environment(timeout, |_| Some(
1629 std::ffi::OsString::from_vec(vec![0xff])
1630 ))
1631 .as_ref()
1632 .map_err(PocketIcStartupError::failure),
1633 Err(PocketIcStartupFailure::InvalidEnvironment { .. })
1634 ));
1635 }
1636
1637 #[cfg(unix)]
1638 #[test]
1639 fn version_capture_cleans_wrapper_descendants_on_exit_and_timeout() {
1640 for timeout in [false, true] {
1641 let qualified = format!(
1642 "printf 'pocket-ic-server {}\\n'",
1643 crate::pic::POCKET_IC_SERVER_VERSION
1644 );
1645 let ending = if timeout { "wait" } else { &qualified };
1646 let script = TestServerScript::new(
1647 "version-group",
1648 &format!(
1649 "#!/bin/sh\nsleep 30 >/dev/null 2>&1 &\nprintf '%s' \"$!\" > \"$0.pid\"\n{ending}\n"
1650 ),
1651 );
1652 let result = PocketIcStartupConfig::from_environment(Duration::from_secs(1), |name| {
1653 (name == "POCKET_IC_BIN").then(|| script.path().into_os_string())
1654 });
1655 if timeout {
1656 assert!(matches!(
1657 result.as_ref().map_err(PocketIcStartupError::failure),
1658 Err(PocketIcStartupFailure::ServerVersionProbe { .. })
1659 ));
1660 } else {
1661 assert!(result.is_ok());
1662 }
1663 let pid_file = script.path().with_extension("pid");
1664 let pid = fs::read_to_string(&pid_file).unwrap().parse().unwrap();
1665 let deadline = Instant::now() + Duration::from_secs(3);
1666 while process_state(pid).is_some_and(|state| state != 'Z') {
1667 assert!(
1668 Instant::now() < deadline,
1669 "version wrapper descendant remained alive"
1670 );
1671 std::thread::sleep(Duration::from_millis(20));
1672 }
1673 fs::remove_file(pid_file).unwrap();
1674 }
1675 }
1676
1677 #[cfg(unix)]
1678 #[test]
1679 fn owned_builder_panic_retains_server_output_and_reaps_child() {
1680 let script = TestServerScript::new(
1681 "builder-panic",
1682 "#!/bin/sh\nprintf '%s' \"$$\" > \"$0.pid\"\nprintf 'builder stdout'\nprintf 'builder stderr' >&2\nprintf '34567\\n' > \"$2\"\nexec sleep 30\n",
1683 );
1684 let error = PocketIcStartupConfig::Spawn {
1685 server_binary: script.path(),
1686 timeout: Duration::from_secs(2),
1687 server_hard_ttl: None,
1688 server_idle_ttl: None,
1689 server_output_files: None,
1690 }
1691 .build_instance(PocketIcBuilder::new())
1692 .err()
1693 .unwrap();
1694 let PocketIcStartupFailure::BuilderPanicked { source } = error.failure() else {
1695 panic!("expected builder failure, got {error:?}");
1696 };
1697 assert_ne!(source.message(), "");
1698 assert_eq!(
1699 std::error::Error::source(&error)
1700 .unwrap()
1701 .downcast_ref::<super::super::PocketIcOperationError>(),
1702 Some(source)
1703 );
1704 assert_eq!(error.output().stdout(), "builder stdout");
1705 assert_eq!(error.output().stderr(), "builder stderr");
1706 assert!(error.server_cleanup().is_none());
1707 let pid_file = script.path().with_extension("pid");
1708 let pid = fs::read_to_string(&pid_file).unwrap().parse().unwrap();
1709 assert_eq!(process_state(pid), None);
1710 fs::remove_file(pid_file).unwrap();
1711 }
1712
1713 #[cfg(unix)]
1714 #[test]
1715 fn environment_binary_selection_uses_bounded_shared_version_capture() {
1716 let qualified = format!(
1717 "printf 'pocket-ic-server {}\\n'",
1718 crate::pic::POCKET_IC_SERVER_VERSION
1719 );
1720 let failed = format!("{qualified}; exit 23");
1721 for (label, body, expected) in [
1722 ("qualified", qualified.as_str(), 0),
1723 ("compatible-16.0", "printf 'pocket-ic-server 16.0.0\\n'", 0),
1724 ("compatible-patch", "printf 'pocket-ic-server 16.0.1\\n'", 0),
1725 ("wrong-version", "printf 'pocket-ic-server 15.0.0\\n'", 1),
1726 ("future-major", "printf 'pocket-ic-server 17.0.0\\n'", 1),
1727 ("malformed-version", "printf 'pocket-ic-server 16.1\\n'", 1),
1728 ("failed-version", failed.as_str(), 2),
1729 ("invalid-utf8", "printf '\\377'", 1),
1730 ("version-timeout", "exec sleep 30", 2),
1731 ] {
1732 let script = TestServerScript::new(
1733 label,
1734 &format!("#!/bin/sh\n[ \"$1\" = --version ] || exit 99\n{body}\n"),
1735 );
1736 let timeout = if label == "version-timeout" {
1739 Duration::from_millis(200)
1740 } else {
1741 Duration::from_secs(5)
1742 };
1743 let result = PocketIcStartupConfig::from_environment(timeout, |name| {
1744 (name == "POCKET_IC_BIN").then(|| script.path().into_os_string())
1745 });
1746 match (
1747 expected,
1748 result.as_ref().map_err(PocketIcStartupError::failure),
1749 ) {
1750 (0, Ok(config)) => {
1751 let binary = script.path().canonicalize().unwrap();
1752 assert!(
1753 matches!(config, PocketIcStartupConfig::Spawn { server_binary, .. } if server_binary == &binary)
1754 );
1755 }
1756 (1, Err(PocketIcStartupFailure::ServerVersionMismatch { .. }))
1757 | (2, Err(PocketIcStartupFailure::ServerVersionProbe { .. })) => {}
1758 (_, result) => panic!("unexpected {label} result: {result:?}"),
1759 }
1760 }
1761 }
1762
1763 #[cfg(unix)]
1764 fn process_state(pid: u32) -> Option<char> {
1765 ic_host_process::testing::process_state(pid).expect("inspect managed test process state")
1766 }
1767
1768 #[cfg(unix)]
1769 #[test]
1770 fn reading_large_sparse_server_output_is_bounded() {
1771 let (files, _, _) = StartupFiles::create(None).expect("allocate startup files");
1772 let mut file = fs::File::create(&files.stdout).expect("create sparse log");
1773 file.write_all(b"server started\n").expect("write prefix");
1774 let size = 8_u64 * 1024 * 1024 * 1024;
1775 file.set_len(size).expect("extend sparse log");
1776 let output = super::read_bounded_lossy(&files.stdout);
1777 assert!(output.starts_with("server started\n"));
1778 assert!(output.ends_with(&format!(
1779 "<truncated {} bytes>",
1780 size - super::SERVER_OUTPUT_LIMIT as u64
1781 )));
1782 assert!(output.len() < super::SERVER_OUTPUT_LIMIT + 100);
1783 }
1784
1785 #[cfg(unix)]
1786 #[test]
1787 fn startup_readers_reject_fifos_without_waiting_for_a_writer() {
1788 let (files, stdout, stderr) = StartupFiles::create(None).expect("allocate startup files");
1789 drop((stdout, stderr));
1790 fs::remove_file(&files.stdout).unwrap();
1791 fs::remove_file(&files.stderr).unwrap();
1792 assert!(
1793 Command::new("mkfifo")
1794 .args([&files.port, &files.stdout, &files.stderr])
1795 .status()
1796 .expect("create FIFO startup files")
1797 .success()
1798 );
1799 for path in [&files.port, &files.stdout, &files.stderr] {
1800 let fifo = path.clone();
1804 let (stop_writer, stopped) = mpsc::channel();
1805 let writer = std::thread::spawn(move || {
1806 loop {
1807 match stopped.recv_timeout(Duration::from_millis(200)) {
1808 Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => return false,
1809 Err(mpsc::RecvTimeoutError::Timeout) => {}
1810 }
1811 if fs::OpenOptions::new()
1812 .write(true)
1813 .custom_flags(libc::O_NONBLOCK)
1814 .open(&fifo)
1815 .is_ok()
1816 {
1817 return true;
1818 }
1819 }
1820 });
1821 let result = if path == &files.port {
1822 Some(files.read_port())
1823 } else {
1824 assert_eq!(super::read_bounded_lossy(path), "");
1825 None
1826 };
1827 let _ = stop_writer.send(());
1828 assert!(
1829 !writer.join().expect("join delayed FIFO writer"),
1830 "startup reader waited for a writer: {}",
1831 path.display(),
1832 );
1833 if let Some(result) = result {
1834 assert!(matches!(
1835 result.as_ref().map_err(PocketIcStartupError::failure),
1836 Err(PocketIcStartupFailure::Io { source, .. })
1837 if source.kind() == std::io::ErrorKind::InvalidData
1838 ));
1839 }
1840 }
1841 }
1842
1843 #[test]
1844 fn port_file_readiness_preserves_partial_writes_and_rejects_oversized_contents() {
1845 let (files, _, _) = StartupFiles::create(None).expect("allocate startup files");
1846 assert!(matches!(
1847 files.read_port().unwrap(),
1848 super::PortFileState::Pending
1849 ));
1850 for contents in ["", "34567"] {
1851 fs::write(&files.port, contents).unwrap();
1852 assert!(matches!(
1853 files.read_port().unwrap(),
1854 super::PortFileState::Pending
1855 ));
1856 }
1857 for (contents, expected) in [("1\n", 1), ("65535\n", 65535), (" 34567\r\n", 34567)] {
1858 fs::write(&files.port, contents).unwrap();
1859 assert!(matches!(
1860 files.read_port().unwrap(),
1861 super::PortFileState::Ready(port) if port == expected
1862 ));
1863 }
1864 for contents in ["0\n", "65536\n", "invalid\n", "1\n2\n"] {
1865 fs::write(&files.port, contents).unwrap();
1866 assert!(matches!(
1867 files.read_port().unwrap(),
1868 super::PortFileState::Invalid(_)
1869 ));
1870 }
1871 fs::write(&files.port, [0xff, b'\n']).unwrap();
1872 assert!(matches!(
1873 files.read_port().as_ref().map_err(PocketIcStartupError::failure),
1874 Err(PocketIcStartupFailure::Io { source, .. })
1875 if source.kind() == std::io::ErrorKind::InvalidData
1876 ));
1877 for contents in ["1\n".to_owned() + &" ".repeat(128), "0".repeat(128)] {
1878 fs::write(&files.port, contents).unwrap();
1879 assert!(
1880 matches!(files.read_port().unwrap(), super::PortFileState::Invalid(_)),
1881 "oversized port contents must fail even without a newline",
1882 );
1883 }
1884 fs::File::options()
1886 .write(true)
1887 .open(&files.port)
1888 .unwrap()
1889 .set_len(1024 * 1024)
1890 .unwrap();
1891 assert!(matches!(
1892 files.read_port().unwrap(),
1893 super::PortFileState::Invalid(value) if value.len() < 256
1894 ));
1895 }
1896
1897 #[test]
1898 fn startup_config_requires_positive_bounds() {
1899 let config = PocketIcStartupConfig::Spawn {
1900 server_binary: "pocket-ic".into(),
1901 timeout: Duration::from_secs(1),
1902 server_hard_ttl: None,
1903 server_idle_ttl: Some(Duration::from_millis(1)),
1904 server_output_files: None,
1905 };
1906 assert!(matches!(
1907 config.validate().unwrap_err().failure(),
1908 PocketIcStartupFailure::InvalidConfiguration { .. }
1909 ));
1910 let error = PocketIcStartupConfig::Connect {
1911 server_url: ("http://127.0.0.1:1/").into(),
1912 timeout: Duration::ZERO,
1913 }
1914 .validate()
1915 .expect_err("zero startup timeout must fail");
1916 assert!(matches!(
1917 error.failure(),
1918 PocketIcStartupFailure::InvalidConfiguration { .. }
1919 ));
1920
1921 let error = PocketIcStartupConfig::Spawn {
1922 server_binary: ("pocket-ic").into(),
1923 timeout: Duration::from_secs(1),
1924 server_hard_ttl: Some(Duration::from_millis(1)),
1925 server_idle_ttl: None,
1926 server_output_files: None,
1927 }
1928 .validate()
1929 .expect_err("subsecond server hard TTL must fail");
1930 assert!(matches!(
1931 error.failure(),
1932 PocketIcStartupFailure::InvalidConfiguration { .. }
1933 ));
1934 }
1935
1936 #[test]
1937 fn startup_files_leave_the_server_owned_port_path_absent() {
1938 let (files, stdout, stderr) = StartupFiles::create(None).expect("allocate startup files");
1939 let directory = files.directory.path().to_path_buf();
1940
1941 assert!(directory.is_dir());
1942 assert!(!files.port.exists());
1943 assert!(files.stdout.is_file());
1944 assert!(files.stderr.is_file());
1945 #[cfg(unix)]
1946 {
1947 let mode = fs::metadata(&directory)
1948 .expect("inspect private startup directory")
1949 .permissions()
1950 .mode();
1951 assert_eq!(mode & 0o077, 0);
1952 }
1953
1954 drop(stdout);
1955 drop(stderr);
1956 drop(files);
1957 assert!(!directory.exists());
1958 }
1959
1960 #[cfg(unix)]
1961 #[test]
1962 fn caller_output_files_survive_startup_command_and_cancellation_cleanup() {
1963 for outcome in [
1964 "timeout",
1965 "startup-exit",
1966 "server-exit",
1967 "command-exit",
1968 "cancel",
1969 "success",
1970 ] {
1971 let (owner, _, _) = StartupFiles::create(None).unwrap();
1972 let stdout = owner.directory.path().join("retained-stdout");
1973 let stderr = owner.directory.path().join("retained-stderr");
1974 let ending = match outcome {
1975 "timeout" => "exec sleep 30",
1976 "startup-exit" => "exit 41",
1977 "server-exit" => {
1978 "printf '34567\\n' > \"$2\"; while [ ! -s \"$0.command\" ]; do sleep 0.02; done; exit 42"
1979 }
1980 _ => "printf '34567\\n' > \"$2\"; exec sleep 30",
1981 };
1982 let script = TestServerScript::new(
1983 outcome,
1984 &format!(
1985 "#!/bin/sh\nprintf '%s\\n%s\\n' \"$$\" \"$2\" > \"$0.pid\"\ndd if=/dev/zero bs=1024 count=20 2>/dev/null\nprintf raw-stdout-end\ndd if=/dev/zero bs=1024 count=20 >&2 2>/dev/null\nprintf raw-stderr-end >&2\n{ending}\n"
1986 ),
1987 );
1988 let pid_file = script.path().with_extension("pid");
1989 let command_file = script.path().with_extension("command");
1990 let config = PocketIcStartupConfig::Spawn {
1991 server_binary: script.path(),
1992 timeout: Duration::from_millis(if outcome == "timeout" { 1000 } else { 2000 }),
1993 server_hard_ttl: None,
1994 server_idle_ttl: None,
1995 server_output_files: Some(((&stdout).into(), (&stderr).into())),
1996 };
1997 if outcome == "timeout" || outcome == "startup-exit" {
1998 let error = config.start_managed_server().err().unwrap();
1999 match (outcome, error.failure()) {
2000 ("timeout", PocketIcStartupFailure::ReadinessTimeout { .. }) => {
2001 assert!(error.output().stdout().contains("truncated"));
2002 assert!(!error.output().stderr().contains("raw-stderr-end"));
2003 }
2004 ("startup-exit", PocketIcStartupFailure::ServerExited { status, .. }) => {
2005 assert_eq!(status.code(), Some(41));
2006 }
2007 (_, error) => panic!("unexpected startup result: {error:?}"),
2008 }
2009 } else {
2010 let command_end = match outcome {
2011 "command-exit" => "exit 37",
2012 "success" => "exit 0",
2013 _ => "exec sleep 30",
2014 };
2015 let result = config.run_command(
2016 Command::new("/bin/sh")
2017 .args([
2018 "-c",
2019 &format!("printf '%s' \"$$\" > \"$1\"; {command_end}"),
2020 "fixture",
2021 ])
2022 .arg(&command_file),
2023 || {
2024 outcome == "cancel"
2025 && fs::metadata(&command_file).is_ok_and(|m| m.len() > 0)
2026 },
2027 );
2028 let result = result.as_ref().map_err(PocketIcStartupError::failure);
2029 match (outcome, result) {
2030 ("command-exit", Ok(status)) => assert_eq!(status.code(), Some(37)),
2031 ("success", Ok(status)) => assert!(status.success()),
2032 ("server-exit", Err(PocketIcStartupFailure::ServerExited { status, .. })) => {
2033 assert_eq!(status.code(), Some(42));
2034 }
2035 ("cancel", Err(PocketIcStartupFailure::CommandRun { source, .. })) => {
2036 assert_eq!(source.kind(), std::io::ErrorKind::Interrupted);
2037 }
2038 (_, result) => panic!("unexpected command result: {result:?}"),
2039 }
2040 let pid = fs::read_to_string(&command_file).unwrap().parse().unwrap();
2041 assert!(process_state(pid).is_none_or(|state| state == 'Z'));
2042 }
2043 for (path, suffix) in [(&stdout, b"raw-stdout-end"), (&stderr, b"raw-stderr-end")] {
2044 let bytes = fs::read(path).unwrap();
2045 assert_eq!(bytes.len(), 20 * 1024 + suffix.len());
2046 assert!(bytes.ends_with(suffix));
2047 assert_eq!(
2048 fs::metadata(path).unwrap().permissions().mode() & 0o777,
2049 0o600
2050 );
2051 }
2052 let report = fs::read_to_string(&pid_file).unwrap();
2053 let mut lines = report.lines();
2054 assert_eq!(process_state(lines.next().unwrap().parse().unwrap()), None);
2055 assert!(
2056 !PathBuf::from(lines.next().unwrap())
2057 .parent()
2058 .unwrap()
2059 .exists()
2060 );
2061 fs::remove_file(pid_file).unwrap();
2062 }
2063 }
2064
2065 #[cfg(unix)]
2066 #[test]
2067 fn caller_output_files_refuse_existing_entries_and_keep_partial_preparation() {
2068 use std::os::unix::fs::symlink;
2069
2070 let (owner, _, _) = StartupFiles::create(None).unwrap();
2071 let stdout = owner.directory.path().join("retained-stdout");
2072 let stderr = owner.directory.path().join("retained-stderr");
2073 let unrelated = owner.directory.path().join("unrelated");
2074 fs::write(&unrelated, b"original").unwrap();
2075 symlink(&unrelated, &stderr).unwrap();
2076 let error = StartupFiles::create(Some((stdout.clone(), stderr.clone())))
2077 .err()
2078 .unwrap();
2079 assert!(
2080 matches!(error.failure(), PocketIcStartupFailure::Io { source, .. } if source.kind() == std::io::ErrorKind::AlreadyExists)
2081 );
2082 assert!(stdout.is_file());
2083 assert_eq!(fs::read(&unrelated).unwrap(), b"original");
2084 fs::write(&stdout, b"retained attempt").unwrap();
2085 assert!(StartupFiles::create(Some((stdout.clone(), stderr.clone()))).is_err());
2086 assert_eq!(fs::read(&stdout).unwrap(), b"retained attempt");
2087 fs::remove_file(stderr.clone()).unwrap();
2088 assert!(
2089 Command::new("mkfifo")
2090 .arg(&stderr)
2091 .status()
2092 .unwrap()
2093 .success()
2094 );
2095 fs::remove_file(stdout.clone()).unwrap();
2096 assert!(StartupFiles::create(Some((stdout.clone(), stderr))).is_err());
2097 assert!(stdout.is_file());
2098 }
2099
2100 #[cfg(unix)]
2101 #[test]
2102 fn managed_startup_reports_an_exited_server_with_bounded_output() {
2103 let script = TestServerScript::new(
2104 "exit",
2105 "#!/bin/sh\nif [ \"$1\" != \"--port-file\" ] || [ -e \"$2\" ]; then exit 97; fi\nprintf 'synthetic server stdout'\nprintf 'synthetic bind failure' >&2\nexit 23\n",
2106 );
2107
2108 let result = PocketIcStartupConfig::Spawn {
2109 server_binary: script.path(),
2110 timeout: Duration::from_secs(2),
2111 server_hard_ttl: None,
2112 server_idle_ttl: None,
2113 server_output_files: None,
2114 }
2115 .build_instance(PocketIcBuilder::new().with_application_subnet());
2116
2117 let error = result.err().unwrap();
2118 let PocketIcStartupFailure::ServerExited {
2119 server_binary,
2120 status,
2121 ..
2122 } = error.failure()
2123 else {
2124 panic!("expected a structured server exit, got {error:?}");
2125 };
2126 assert_eq!(server_binary, &script.path());
2127 assert_eq!(status.code(), Some(23));
2128 assert_eq!(error.output().stdout(), "synthetic server stdout");
2129 assert_eq!(error.output().stderr(), "synthetic bind failure");
2130 }
2131
2132 #[cfg(unix)]
2133 #[test]
2134 fn managed_startup_rejects_oversized_port_files_and_cleans_up() {
2135 let script = TestServerScript::new(
2136 "oversized-port",
2137 "#!/bin/sh\nprintf '%s\\n%s\\n' \"$$\" \"$2\"\nprintf '34567\\n%064s' '' > \"$2.pending\"\nmv \"$2.pending\" \"$2\"\nexec sleep 30\n",
2138 );
2139 let result = PocketIcStartupConfig::Spawn {
2140 server_binary: script.path(),
2141 timeout: Duration::from_secs(2),
2142 server_hard_ttl: None,
2143 server_idle_ttl: None,
2144 server_output_files: None,
2145 }
2146 .start_managed_server();
2147 let error = result.err().unwrap();
2148 let PocketIcStartupFailure::InvalidServerPort { value, .. } = error.failure() else {
2149 panic!("oversized port publication must fail readiness");
2150 };
2151 assert!(value.contains("port file exceeds"));
2152 assert!(value.len() < 256);
2153 let mut lines = error.output().stdout().lines();
2154 let pid = lines.next().unwrap().parse::<u32>().unwrap();
2155 let port_path = PathBuf::from(lines.next().unwrap());
2156 assert!(!port_path.parent().unwrap().exists());
2157 assert_eq!(process_state(pid), None, "failed server must be reaped");
2158 }
2159
2160 #[cfg(unix)]
2161 #[test]
2162 fn managed_startup_terminates_a_server_that_never_becomes_ready() {
2163 let script = TestServerScript::new(
2164 "timeout",
2165 "#!/bin/sh\nif [ \"$1\" != \"--port-file\" ] || [ -e \"$2\" ]; then exit 97; fi\nexec sleep 30\n",
2166 );
2167 let timeout = Duration::from_millis(100);
2168 let started = Instant::now();
2169
2170 let result = PocketIcStartupConfig::Spawn {
2171 server_binary: script.path(),
2172 timeout,
2173 server_hard_ttl: None,
2174 server_idle_ttl: None,
2175 server_output_files: None,
2176 }
2177 .build_instance(PocketIcBuilder::new().with_application_subnet());
2178
2179 assert!(
2180 started.elapsed() < Duration::from_secs(2),
2181 "bounded startup should not wait for the sleeping child"
2182 );
2183 let error = result.err().unwrap();
2184 assert!(
2185 matches!(error.failure(), PocketIcStartupFailure::ReadinessTimeout {
2186 server_binary, timeout: actual_timeout,
2187 } if server_binary == &script.path() && *actual_timeout == timeout)
2188 );
2189 assert!(error.server_cleanup().is_none());
2190 }
2191
2192 #[cfg(unix)]
2193 #[test]
2194 fn managed_server_handle_exposes_process_id_url_output_and_raii_ownership() {
2195 let script = TestServerScript::new(
2196 "handle",
2197 "#!/bin/sh\nif [ \"$1\" != \"--port-file\" ] || [ -e \"$2\" ]; then echo 'unexpected managed server arguments' >&2; exit 97; fi\nprintf 'managed server ready: %s' \"$$\"\nprintf '34567\\n' > \"$2\"\nexec sleep 30\n",
2198 );
2199
2200 let server = PocketIcStartupConfig::Spawn {
2201 server_binary: script.path(),
2202 timeout: Duration::from_secs(2),
2203 server_hard_ttl: None,
2204 server_idle_ttl: None,
2205 server_output_files: None,
2206 }
2207 .start_managed_server()
2208 .expect("start caller-owned managed server");
2209
2210 assert_eq!(server.url(), "http://127.0.0.1:34567/");
2211 assert_eq!(
2212 server.output().stdout(),
2213 format!("managed server ready: {}", server.process_id())
2214 );
2215 assert_eq!(server.output().stderr(), "");
2216 let pid = server.process_id();
2217 assert!(process_state(pid).is_some_and(|state| state != 'Z'));
2218 drop(server);
2219 assert_eq!(process_state(pid), None, "owned server must be reaped");
2220 }
2221
2222 #[cfg(unix)]
2223 #[test]
2224 fn managed_server_cleans_descendants_on_drop_timeout_and_exit() {
2225 for mode in ["drop", "timeout", "exit"] {
2226 let publish = if mode == "drop" {
2227 "printf '34567\\n' > \"$2\"\n"
2228 } else {
2229 ""
2230 };
2231 let finish = if mode == "exit" {
2232 "sleep 0.03\nexit 23\n"
2233 } else {
2234 "exec sleep 30\n"
2235 };
2236 let script = TestServerScript::new(
2237 mode,
2238 &format!("#!/bin/sh\nsleep 30 &\nprintf '%s' \"$!\"\n{publish}{finish}"),
2239 );
2240 let result = PocketIcStartupConfig::Spawn {
2241 server_binary: script.path(),
2242 timeout: Duration::from_millis(300),
2243 server_hard_ttl: None,
2244 server_idle_ttl: None,
2245 server_output_files: None,
2246 }
2247 .start_managed_server();
2248 let output = match result {
2249 Ok(server) => {
2250 let output = server.output().stdout().to_owned();
2251 drop(server);
2252 output
2253 }
2254 Err(error) => {
2255 match error.failure() {
2256 PocketIcStartupFailure::ReadinessTimeout { .. } => {
2257 assert_eq!(mode, "timeout");
2258 assert!(error.server_cleanup().is_none());
2259 }
2260 PocketIcStartupFailure::ServerExited { status, .. } => {
2261 assert_eq!(mode, "exit");
2262 assert_eq!(status.code(), Some(23));
2263 }
2264 _ => panic!("unexpected {mode} startup result: {error}"),
2265 }
2266 error.output().stdout().to_owned()
2267 }
2268 };
2269 let pid = output
2270 .parse::<u32>()
2271 .expect("server published its descendant PID");
2272 let deadline = Instant::now() + Duration::from_secs(2);
2273 while process_state(pid).is_some_and(|state| state != 'Z') {
2274 assert!(
2275 Instant::now() < deadline,
2276 "{mode} left its descendant running"
2277 );
2278 std::thread::sleep(Duration::from_millis(10));
2279 }
2280 }
2281 }
2282
2283 #[cfg(unix)]
2284 #[test]
2285 fn managed_server_passes_an_explicit_hard_ttl() {
2286 let script = TestServerScript::new(
2287 "hard-ttl",
2288 "#!/bin/sh\nif [ \"$1\" != \"--hard-ttl\" ] || [ \"$2\" != \"17\" ] || [ \"$3\" != \"--port-file\" ] || [ -e \"$4\" ]; then exit 97; fi\nprintf '34567\\n' > \"$4\"\nexec sleep 30\n",
2289 );
2290
2291 let server = PocketIcStartupConfig::Spawn {
2292 server_binary: script.path(),
2293 timeout: Duration::from_secs(2),
2294 server_hard_ttl: Some(Duration::from_secs(17)),
2295 server_idle_ttl: None,
2296 server_output_files: None,
2297 }
2298 .start_managed_server()
2299 .expect("start managed server with an explicit hard TTL");
2300
2301 assert_eq!(server.url(), "http://127.0.0.1:34567/");
2302 }
2303
2304 #[cfg(unix)]
2305 #[test]
2306 #[ignore = "requires POCKET_IC_BIN=<caller-provided PocketIC server binary>"]
2307 fn caller_provided_server_publishes_port_constructs_instance_and_cleans_up() {
2308 let binary = std::env::var_os("POCKET_IC_BIN")
2309 .map(PathBuf::from)
2310 .expect("set POCKET_IC_BIN to the exact server binary");
2311 let wrapper = TestServerScript::new(
2314 "real-owned-instance",
2315 "#!/bin/sh\nprintf '%s\n%s\n' \"$$\" \"$4\" > \"$0.record\"\nexec \"$POCKET_IC_BIN\" \"$@\"\n",
2316 );
2317 let owned = PocketIcStartupConfig::Spawn {
2318 server_binary: wrapper.path(),
2319 timeout: Duration::from_secs(30),
2320 server_hard_ttl: Some(Duration::from_secs(60)),
2321 server_idle_ttl: None,
2322 server_output_files: None,
2323 }
2324 .build_instance(PocketIcBuilder::new().with_application_subnet())
2325 .expect("owned managed spawn must construct an instance");
2326 let record_file = wrapper.path().with_extension("record");
2327 let record = fs::read_to_string(&record_file).unwrap();
2328 let mut fields = record.lines();
2329 let pid = fields.next().unwrap().parse().unwrap();
2330 let port_path = PathBuf::from(fields.next().unwrap());
2331 let startup_directory = port_path.parent().unwrap();
2332 drop(owned);
2333 assert!(!startup_directory.exists());
2334 assert_eq!(process_state(pid), None);
2335 fs::remove_file(record_file).unwrap();
2336
2337 let server = PocketIcStartupConfig::Spawn {
2338 server_binary: (&binary).into(),
2339 timeout: Duration::from_secs(30),
2340 server_hard_ttl: Some(Duration::from_secs(60)),
2341 server_idle_ttl: None,
2342 server_output_files: None,
2343 }
2344 .start_managed_server()
2345 .expect("caller-provided PocketIC server must publish its port");
2346 let files = &server.server.files;
2347 let startup_directory = files.directory.path().to_path_buf();
2348
2349 assert!(files.port.is_file());
2350 let pocket_ic = PocketIcStartupConfig::Connect {
2351 server_url: (server.url()).into(),
2352 timeout: Duration::from_secs(30),
2353 }
2354 .build_instance(PocketIcBuilder::new().with_application_subnet())
2355 .expect("construct instance through caller-provided server");
2356
2357 drop(pocket_ic);
2358 drop(server);
2359 assert!(!startup_directory.exists());
2360 }
2361
2362 #[cfg(unix)]
2363 struct TestServerScript {
2364 path: PathBuf,
2365 #[expect(
2366 dead_code,
2367 reason = "retains directory ownership until cleanup or drop"
2368 )]
2369 directory: OwnedDirectory,
2370 }
2371
2372 #[cfg(unix)]
2373 impl TestServerScript {
2374 fn new(label: &str, contents: &str) -> Self {
2375 let directory = OwnedDirectory::new(
2376 create_unique_directory(
2377 &std::env::temp_dir(),
2378 &format!("ic-testkit-pocket-ic-{label}"),
2379 0o700,
2380 None,
2381 )
2382 .expect("create test server directory"),
2383 );
2384 let path = directory.path().join("server");
2385 write_executable_script(&path, contents).expect("write executable test script");
2386 Self { path, directory }
2387 }
2388
2389 fn path(&self) -> PathBuf {
2390 self.path.clone()
2391 }
2392 }
2393}