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