Skip to main content

hapi_rs/
server.rs

1use std::{
2    collections::HashMap,
3    ffi::{CString, OsStr, OsString},
4    net::SocketAddrV4,
5    num::NonZeroU64,
6    path::{Path, PathBuf},
7    process::{Child, Command, Stdio},
8    thread,
9    time::{Duration, Instant},
10};
11
12use log::{debug, error, warn};
13use temp_env;
14
15use crate::{
16    errors::{ErrorContext, HapiError, Result},
17    ffi::{self, ThriftServerOptions, enums::StatusVerbosity},
18    session::UninitializedSession,
19    utils,
20};
21
22pub use crate::ffi::raw::ThriftSharedMemoryBufferType;
23
24/// Controls which Houdini product licenses HARS may check out.
25///
26/// The preference is passed to the server through `HOUDINI_PLUGIN_LIC_OPT`
27/// before HARS starts. It has no effect when merely attaching to an already
28/// running server.
29#[derive(Copy, Clone, Debug, PartialEq, Eq)]
30pub enum LicensePreference {
31    /// Allow Houdini Engine, Houdini Core, or Houdini FX licenses.
32    AnyAvailable,
33    /// Restrict checkout to Houdini Engine licenses.
34    HoudiniEngineOnly,
35    /// Allow Houdini Engine or Houdini Core, but not Houdini FX.
36    HoudiniEngineAndCore,
37}
38
39impl std::fmt::Display for LicensePreference {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        write!(
42            f,
43            "{}",
44            match self {
45                LicensePreference::AnyAvailable => {
46                    "--check-licenses=Houdini-Engine,Houdini-Escape,Houdini-Fx"
47                }
48                LicensePreference::HoudiniEngineOnly => {
49                    "--check-licenses=Houdini-Engine --skip-licenses=Houdini-Escape,Houdini-Fx"
50                }
51                LicensePreference::HoudiniEngineAndCore => {
52                    "--check-licenses=Houdini-Engine,Houdini-Escape --skip-licenses=Houdini-Fx"
53                }
54            }
55        )
56    }
57}
58
59/// Configuration for a local Thrift shared-memory transport.
60///
61/// The buffer type and size are supplied to both HARS and the client session;
62/// HAPI requires the two sides to match.
63#[derive(Clone, Debug)]
64pub struct ThriftSharedMemoryTransport {
65    /// Name of the platform shared-memory object used by HARS and HARC.
66    pub memory_name: String,
67    /// Fixed-length or ring-buffer transport mode.
68    pub buffer_type: ThriftSharedMemoryBufferType,
69    /// Shared-memory buffer size in megabytes.
70    pub buffer_size: i64,
71}
72
73/// Configuration for a TCP Thrift transport.
74#[derive(Clone, Debug)]
75pub struct ThriftSocketTransport {
76    /// IPv4 address and port on which HARS listens or to which HARC connects.
77    pub address: SocketAddrV4,
78}
79
80/// Configuration for a named-pipe Thrift transport.
81///
82/// On Unix-like systems HAPI implements this transport as a Unix domain
83/// socket; on Windows it is a native named pipe.
84#[derive(Clone, Debug)]
85pub struct ThriftPipeTransport {
86    /// Pipe name or Unix domain socket path shared by HARS and HARC.
87    pub pipe_path: PathBuf,
88}
89
90/// Transport used to communicate with a Thrift HARS server.
91#[derive(Clone, Debug)]
92pub enum ThriftTransport {
93    /// Local shared-memory transport.
94    SharedMemory(ThriftSharedMemoryTransport),
95    /// Named pipe or Unix domain socket transport.
96    Pipe(ThriftPipeTransport),
97    /// TCP socket transport.
98    Socket(ThriftSocketTransport),
99}
100
101/// Builder for [`ThriftSharedMemoryTransport`].
102///
103/// Defaults to a random memory name, HAPI's fixed-length buffer mode, and the
104/// official HAPI default size of 100 MB.
105pub struct ThriftSharedMemoryTransportBuilder {
106    memory_name: String,
107    buffer_type: ThriftSharedMemoryBufferType,
108    buffer_size: i64,
109}
110
111impl Default for ThriftSharedMemoryTransportBuilder {
112    fn default() -> Self {
113        Self {
114            memory_name: format!("shared-memory-{}", utils::random_string(16)),
115            buffer_type: ThriftSharedMemoryBufferType::Buffer,
116            // Match HAPI_ThriftServerOptions_Create and HAPI_SessionInfo_Create.
117            buffer_size: 100, // MB
118        }
119    }
120}
121
122impl ThriftSharedMemoryTransportBuilder {
123    #[must_use]
124    pub fn with_memory_name(mut self, name: impl Into<String>) -> Self {
125        self.memory_name = name.into();
126        self
127    }
128    #[must_use]
129    pub fn with_buffer_type(mut self, buffer_type: ThriftSharedMemoryBufferType) -> Self {
130        self.buffer_type = buffer_type;
131        self
132    }
133    #[must_use]
134    pub fn with_buffer_size(mut self, buffer_size: NonZeroU64) -> Self {
135        self.buffer_size = if let Ok(size) = buffer_size.get().try_into() {
136            size
137        } else {
138            // When u64 can't fit into i64, use the HAPI default of 100 MB.
139            warn!("ThriftSharedMemoryTransport buffer size is too large, using default of 100");
140            100
141        };
142        self
143    }
144    #[must_use]
145    pub fn build(self) -> ThriftSharedMemoryTransport {
146        ThriftSharedMemoryTransport {
147            memory_name: self.memory_name,
148            buffer_type: self.buffer_type,
149            buffer_size: self.buffer_size,
150        }
151    }
152}
153
154/// Configuration used to start or connect to a Thrift HARS server.
155///
156/// Server-start settings such as [`Self::auto_close`], [`Self::verbosity`],
157/// [`Self::log_file`], and [`Self::server_ready_timeout`] only affect a server
158/// started with [`start_engine_server`] or [`crate::session::new_thrift_session`].
159/// They cannot reconfigure an existing server used by the `connect_to_*`
160/// helpers.
161///
162/// The default selects shared memory with a random name, enables HARS
163/// auto-close, and retries client connection attempts for ten seconds.
164#[derive(Clone, Debug)]
165pub struct ServerOptions {
166    /// Thrift transport and endpoint configuration.
167    pub thrift_transport: ThriftTransport,
168    /// Ask a newly started HARS process to exit after its last client closes.
169    pub auto_close: bool,
170    /// Maximum HARS log verbosity.
171    pub verbosity: StatusVerbosity,
172    /// Optional file to which a newly started HARS writes its log.
173    pub log_file: Option<CString>,
174    /// Process environment entries temporarily applied while starting HARS.
175    pub env_variables: Option<HashMap<OsString, OsString>>,
176    /// Optional Houdini license checkout preference.
177    pub license_preference: Option<LicensePreference>,
178    /// Number of HARC subconnections requested for the session.
179    pub connection_count: i32,
180    /// Optional HARS readiness timeout, in milliseconds.
181    ///
182    /// When absent, the default supplied by HAPI is retained.
183    pub server_ready_timeout: Option<u32>,
184    pub(crate) connection_retry_interval: Option<Duration>,
185}
186
187impl Default for ServerOptions {
188    fn default() -> Self {
189        Self {
190            thrift_transport: ThriftTransport::SharedMemory(
191                ThriftSharedMemoryTransportBuilder::default().build(),
192            ),
193            auto_close: true,
194            verbosity: StatusVerbosity::Statusverbosity0,
195            log_file: None,
196            env_variables: None,
197            license_preference: None,
198            connection_count: 0,
199            server_ready_timeout: None,
200            connection_retry_interval: Some(Duration::from_secs(10)),
201        }
202    }
203}
204
205impl ServerOptions {
206    /// Create options for a shared-memory transport with a random name.
207    #[must_use]
208    pub fn shared_memory_with_defaults() -> Self {
209        Self::default().with_thrift_transport(ThriftTransport::SharedMemory(
210            ThriftSharedMemoryTransportBuilder::default().build(),
211        ))
212    }
213
214    /// Create options for a named pipe transport.
215    #[must_use]
216    pub fn pipe_with_defaults() -> Self {
217        Self::default().with_thrift_transport(ThriftTransport::Pipe(ThriftPipeTransport {
218            pipe_path: PathBuf::from(format!("hapi-pipe-{}", utils::random_string(16))),
219        }))
220    }
221
222    /// Create options for a socket transport.
223    #[must_use]
224    pub fn socket_with_defaults(address: SocketAddrV4) -> Self {
225        Self::default()
226            .with_thrift_transport(ThriftTransport::Socket(ThriftSocketTransport { address }))
227    }
228
229    #[must_use]
230    /// Replace the configured Thrift transport.
231    pub fn with_thrift_transport(mut self, transport: ThriftTransport) -> Self {
232        self.thrift_transport = transport;
233        self
234    }
235
236    /// Set the total retry timeout used while establishing a Thrift session.
237    ///
238    /// `None` retries indefinitely. This is separate from
239    /// [`Self::with_server_ready_timeout`], which controls server startup.
240    #[must_use]
241    pub fn with_connection_timeout(mut self, timeout: Option<Duration>) -> Self {
242        self.connection_retry_interval = timeout;
243        self
244    }
245
246    /// Set the license preference for the server.
247    /// For more information, see <https://www.sidefx.com/docs/houdini//licensing/system.html>
248    /// Default is No preference, the server decides which license to check out.
249    #[must_use]
250    pub fn with_license_preference(mut self, license_preference: LicensePreference) -> Self {
251        self.license_preference.replace(license_preference);
252
253        self.env_variables.get_or_insert_default().insert(
254            OsString::from("HOUDINI_PLUGIN_LIC_OPT"),
255            OsString::from(license_preference.to_string()),
256        );
257
258        self
259    }
260
261    /// Set the log file for the server.
262    /// BUG: HARS 21.0.685 has a bug where the log file is always created in the working directory
263    ///
264    /// # Panics
265    /// Panics if `file` contains an interior null byte and cannot be converted to a C string.
266    #[must_use]
267    pub fn with_log_file(mut self, file: impl AsRef<Path>) -> Self {
268        self.log_file = Some(utils::path_to_cstring(file).expect("Path to CString failed"));
269        self
270    }
271
272    /// Set **real** environment variables before the server starts.
273    /// Unlike [`crate::session::Session::set_server_var`], where the variables are set in the session after the
274    /// server starts.
275    #[must_use]
276    pub fn with_env_variables<'a, I, K, V>(mut self, variables: I) -> Self
277    where
278        I: Iterator<Item = &'a (K, V)>,
279        K: Into<OsString> + Clone + 'a,
280        V: Into<OsString> + Clone + 'a,
281    {
282        self.env_variables
283            .get_or_insert_default()
284            .extend(variables.map(|(k, v)| (k.clone().into(), v.clone().into())));
285        self
286    }
287
288    /// Automatically close the server when the last connection drops.
289    #[must_use]
290    pub fn with_auto_close(mut self, auto_close: bool) -> Self {
291        self.auto_close = auto_close;
292        self
293    }
294
295    /// Set the verbosity level for the server.
296    #[must_use]
297    pub fn with_verbosity(mut self, verbosity: StatusVerbosity) -> Self {
298        self.verbosity = verbosity;
299        self
300    }
301
302    #[must_use]
303    #[cfg(feature = "async-cooking")]
304    /// Set the number of HARC subconnections used by asynchronous HAPI calls.
305    pub fn with_connection_count(mut self, connection_count: i32) -> Self {
306        // BUG: HARS 21.0.* has a bug where the connection count is not respected.
307        // If connection_count is > 0, there is a bug in HARS which prevents session creation.
308        // However, async attribute access requires a connection count > 0 according to SESI support, otherwise HARS crashes too.
309        self.connection_count = connection_count;
310        self
311    }
312
313    /// Set the timeout for the server to be ready in ms
314    /// This is the timeout for the server to initialize and be ready to accept connections.
315    #[must_use]
316    pub fn with_server_ready_timeout(mut self, timeout: u32) -> Self {
317        self.server_ready_timeout.replace(timeout);
318        self
319    }
320
321    pub(crate) fn session_info(&self) -> crate::ffi::SessionInfo {
322        let mut session_info =
323            crate::ffi::SessionInfo::default().with_connection_count(self.connection_count);
324
325        if let ThriftTransport::SharedMemory(transport) = &self.thrift_transport {
326            session_info.set_shared_memory_buffer_type(transport.buffer_type);
327            session_info.set_shared_memory_buffer_size(transport.buffer_size);
328        }
329
330        session_info
331    }
332
333    pub(crate) fn thrift_options(&self) -> crate::ffi::ThriftServerOptions {
334        let mut options = ThriftServerOptions::default()
335            .with_auto_close(self.auto_close)
336            .with_verbosity(self.verbosity);
337
338        if let ThriftTransport::SharedMemory(transport) = &self.thrift_transport {
339            options.set_shared_memory_buffer_type(transport.buffer_type);
340            options.set_shared_memory_buffer_size(transport.buffer_size);
341        }
342        if let Some(timeout) = self.server_ready_timeout {
343            #[allow(clippy::cast_precision_loss)]
344            options.set_timeout_ms(timeout as f32);
345        }
346
347        options
348    }
349}
350
351fn call_with_temp_environment<R, T, F>(variables: Option<&[(T, T)]>, f: F) -> Result<R>
352where
353    T: AsRef<OsStr>,
354    F: FnOnce() -> Result<R>,
355{
356    if let Some(env_variables) = variables {
357        let env_variables: Vec<(&OsStr, Option<&OsStr>)> = env_variables
358            .iter()
359            .map(|(k, v)| (k.as_ref(), Some(v.as_ref())))
360            .collect::<Vec<_>>();
361        temp_env::with_vars(env_variables.as_slice(), f)
362    } else {
363        f()
364    }
365}
366
367/// Connect to the Thrift pipe server and return an uninitialized session.
368pub fn connect_to_pipe_server(
369    server_options: ServerOptions,
370    pid: Option<u32>,
371) -> Result<UninitializedSession> {
372    validate_server_options(&server_options)?;
373    let ThriftTransport::Pipe(ThriftPipeTransport { pipe_path }) = &server_options.thrift_transport
374    else {
375        return Err(HapiError::Internal(
376            "ServerOptions is not configured for pipe transport".to_owned(),
377        ));
378    };
379    let pipe_name = utils::path_to_cstring(pipe_path)?;
380    debug!("Connecting to pipe server: {:?}", pipe_path.display());
381    let handle = try_connect_with_timeout(
382        server_options.connection_retry_interval,
383        Duration::from_millis(100),
384        || ffi::new_thrift_piped_session(&pipe_name, &server_options.session_info().0),
385    )?;
386    Ok(UninitializedSession {
387        session_handle: Some(handle),
388        server_options: Some(server_options),
389        server: crate::session::ServerConnection::Borrowed { reported_pid: pid },
390    })
391}
392
393/// Connect to the Thrift shared memory server and return an uninitialized session.
394pub fn connect_to_memory_server(
395    server_options: ServerOptions,
396    pid: Option<u32>,
397) -> Result<UninitializedSession> {
398    validate_server_options(&server_options)?;
399    let ThriftTransport::SharedMemory(ThriftSharedMemoryTransport { memory_name, .. }) =
400        &server_options.thrift_transport
401    else {
402        return Err(HapiError::Internal(
403            "ServerOptions is not configured for shared memory transport".to_owned(),
404        ));
405    };
406    let mem_name_cstr = CString::new(memory_name.clone())?;
407    debug!("Connecting to shared memory server: {memory_name:?}");
408    let handle = try_connect_with_timeout(
409        server_options.connection_retry_interval,
410        Duration::from_millis(100),
411        || ffi::new_thrift_shared_memory_session(&mem_name_cstr, &server_options.session_info().0),
412    )?;
413    Ok(UninitializedSession {
414        session_handle: Some(handle),
415        server_options: Some(server_options),
416        server: crate::session::ServerConnection::Borrowed { reported_pid: pid },
417    })
418}
419
420fn try_connect_with_timeout<F: Fn() -> Result<crate::ffi::raw::HAPI_Session>>(
421    timeout: Option<Duration>,
422    wait_ms: Duration,
423    f: F,
424) -> Result<crate::ffi::raw::HAPI_Session> {
425    debug!("Trying to connect to server with timeout: {timeout:?}");
426    let started = Instant::now();
427    let mut last_error = None;
428    let handle = loop {
429        match f() {
430            Ok(handle) => break handle,
431            Err(e) => {
432                error!("Error while trying to connect to server: {e:?}");
433                last_error.replace(e);
434            }
435        }
436        if let Some(timeout) = timeout
437            && started.elapsed() >= timeout
438        {
439            // last_error is guaranteed to be Some() because we break out of the loop if we get a result.
440            return Err(last_error.unwrap()).context(format!(
441                "Could not connect to server within timeout: {:?}",
442                timeout
443            ));
444        }
445        let sleep_for = timeout
446            .map(|timeout| wait_ms.min(timeout.saturating_sub(started.elapsed())))
447            .unwrap_or(wait_ms);
448        if !sleep_for.is_zero() {
449            thread::sleep(sleep_for);
450        }
451    };
452    Ok(handle)
453}
454
455/// Connect to the Thrift socket server and return an uninitialized session.
456pub fn connect_to_socket_server(
457    server_options: ServerOptions,
458    pid: Option<u32>,
459) -> Result<UninitializedSession> {
460    validate_server_options(&server_options)?;
461    let ThriftTransport::Socket(ThriftSocketTransport { address }) =
462        &server_options.thrift_transport
463    else {
464        return Err(HapiError::Internal(
465            "ServerOptions is not configured for socket transport".to_owned(),
466        ));
467    };
468    debug!("Connecting to socket server: {address:?}");
469    let host = CString::new(address.ip().to_string())
470        .map_err(HapiError::from)
471        .context("Converting SocketAddr to CString")?;
472    let handle = try_connect_with_timeout(
473        server_options.connection_retry_interval,
474        Duration::from_millis(100),
475        || {
476            ffi::new_thrift_socket_session(
477                i32::from(address.port()),
478                &host,
479                &server_options.session_info().0,
480            )
481        },
482    )?;
483    Ok(UninitializedSession {
484        session_handle: Some(handle),
485        server_options: Some(server_options),
486        server: crate::session::ServerConnection::Borrowed { reported_pid: pid },
487    })
488}
489
490/// Start HARS and return its process ID.
491///
492/// This is a low-level unmanaged API. The caller is responsible for closing
493/// all client sessions and, on Unix, reaping the returned child process.
494/// [`crate::session::new_thrift_session`] manages those responsibilities.
495pub fn start_engine_server(server_options: &ServerOptions) -> Result<u32> {
496    validate_server_options(server_options)?;
497    let env_variables = server_options.env_variables.as_ref().map(|env_variables| {
498        env_variables
499            .iter()
500            .map(|(k, v)| (k.as_os_str(), v.as_os_str()))
501            .collect::<Vec<_>>()
502    });
503    match &server_options.thrift_transport {
504        ThriftTransport::SharedMemory(transport) => {
505            debug!(
506                "Starting shared memory server name: {}",
507                transport.memory_name
508            );
509            let memory_name = CString::new(transport.memory_name.clone())?;
510            ffi::clear_connection_error()?;
511            call_with_temp_environment(env_variables.as_deref(), || {
512                ffi::start_thrift_shared_memory_server(
513                    &memory_name,
514                    &server_options.thrift_options().0,
515                    server_options.log_file.as_deref(),
516                )
517                .with_context(|| {
518                    format!(
519                        "Failed to start shared memory server: {}",
520                        transport.memory_name
521                    )
522                })
523            })
524        }
525        ThriftTransport::Pipe(transport) => {
526            debug!(
527                "Starting named pipe server: {}",
528                transport.pipe_path.display()
529            );
530            let pipe_name = utils::path_to_cstring(&transport.pipe_path)?;
531            ffi::clear_connection_error()?;
532            call_with_temp_environment(env_variables.as_deref(), || {
533                ffi::start_thrift_pipe_server(
534                    &pipe_name,
535                    &server_options.thrift_options().0,
536                    server_options.log_file.as_deref(),
537                )
538                .with_context(|| {
539                    format!(
540                        "Failed to start pipe server: {}",
541                        transport.pipe_path.display()
542                    )
543                })
544            })
545        }
546        ThriftTransport::Socket(transport) => {
547            debug!(
548                "Starting socket server on port: {}",
549                transport.address.port()
550            );
551            ffi::clear_connection_error()?;
552            call_with_temp_environment(env_variables.as_deref(), || {
553                ffi::start_thrift_socket_server(
554                    i32::from(transport.address.port()),
555                    &server_options.thrift_options().0,
556                    server_options.log_file.as_deref(),
557                )
558            })
559        }
560    }
561}
562
563fn validate_server_options(server_options: &ServerOptions) -> Result<()> {
564    if server_options.connection_count < 0 {
565        return Err(HapiError::Internal(
566            "ServerOptions.connection_count cannot be negative".to_owned(),
567        ));
568    }
569    match &server_options.thrift_transport {
570        ThriftTransport::SharedMemory(transport) => {
571            if transport.memory_name.is_empty() {
572                return Err(HapiError::Internal(
573                    "Shared-memory transport name cannot be empty".to_owned(),
574                ));
575            }
576            if transport.buffer_size <= 0 {
577                return Err(HapiError::Internal(
578                    "Shared-memory buffer size must be positive".to_owned(),
579                ));
580            }
581        }
582        ThriftTransport::Pipe(transport) if transport.pipe_path.as_os_str().is_empty() => {
583            return Err(HapiError::Internal(
584                "Pipe transport path cannot be empty".to_owned(),
585            ));
586        }
587        ThriftTransport::Socket(transport) if transport.address.port() == 0 => {
588            return Err(HapiError::Internal(
589                "Socket transport port cannot be zero".to_owned(),
590            ));
591        }
592        ThriftTransport::Pipe(_) | ThriftTransport::Socket(_) => {}
593    }
594    Ok(())
595}
596
597/// Finish an owned HARS process. During construction failure the process is
598/// terminated immediately. During normal auto-close shutdown it first gets a
599/// chance to exit after the final client disconnects.
600pub(crate) fn finish_owned_server(
601    pid: u32,
602    auto_close: bool,
603    construction_failed: bool,
604    pipe_path: Option<&Path>,
605) -> Result<()> {
606    if !construction_failed && !auto_close {
607        return Ok(());
608    }
609
610    #[cfg(unix)]
611    reap_unix_child(pid, !construction_failed)?;
612
613    #[cfg(windows)]
614    finish_windows_child(pid, !construction_failed)?;
615
616    #[cfg(not(any(unix, windows)))]
617    let _ = (pid, auto_close, construction_failed);
618
619    if let Some(pipe_path) = pipe_path {
620        let _ = std::fs::remove_file(pipe_path);
621    }
622    Ok(())
623}
624
625#[cfg(windows)]
626fn finish_windows_child(pid: u32, allow_graceful_exit: bool) -> Result<()> {
627    use windows_sys::Win32::{
628        Foundation::{CloseHandle, ERROR_INVALID_PARAMETER, WAIT_OBJECT_0, WAIT_TIMEOUT},
629        System::Threading::{
630            OpenProcess, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, TerminateProcess,
631            WaitForSingleObject,
632        },
633    };
634
635    let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_TERMINATE, 0, pid) };
636    if handle.is_null() {
637        let error = std::io::Error::last_os_error();
638        return if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {
639            // The process has already exited.
640            Ok(())
641        } else {
642            Err(HapiError::Io(error))
643        };
644    }
645    let wait_ms = if allow_graceful_exit { 2_000 } else { 0 };
646    let wait_result = unsafe { WaitForSingleObject(handle, wait_ms) };
647    let result = match wait_result {
648        WAIT_OBJECT_0 => Ok(()),
649        WAIT_TIMEOUT => {
650            if unsafe { TerminateProcess(handle, 1) } == 0 {
651                Err(HapiError::Io(std::io::Error::last_os_error()))
652            } else {
653                let terminated = unsafe { WaitForSingleObject(handle, 1_000) };
654                if terminated == WAIT_OBJECT_0 {
655                    Ok(())
656                } else {
657                    Err(HapiError::Internal(format!(
658                        "Timed out waiting for HARS process {pid} to terminate"
659                    )))
660                }
661            }
662        }
663        _ => Err(HapiError::Io(std::io::Error::last_os_error())),
664    };
665    unsafe {
666        CloseHandle(handle);
667    }
668    result
669}
670
671#[cfg(unix)]
672fn reap_unix_child(pid: u32, allow_graceful_exit: bool) -> Result<()> {
673    let pid = i32::try_from(pid)
674        .map_err(|_| HapiError::Internal("HARS PID does not fit pid_t".to_owned()))?;
675    let graceful_deadline = Instant::now()
676        + if allow_graceful_exit {
677            Duration::from_secs(2)
678        } else {
679            Duration::ZERO
680        };
681
682    loop {
683        let mut status = 0;
684        let result = unsafe { libc::waitpid(pid, &raw mut status, libc::WNOHANG) };
685        if result == pid
686            || (result == -1
687                && std::io::Error::last_os_error().raw_os_error() == Some(libc::ECHILD))
688        {
689            return Ok(());
690        }
691        if result == -1 {
692            return Err(HapiError::Io(std::io::Error::last_os_error()));
693        }
694        if Instant::now() >= graceful_deadline {
695            break;
696        }
697        thread::sleep(Duration::from_millis(20));
698    }
699
700    // waitpid returned zero, so this is still our live child and not a reused PID.
701    if unsafe { libc::kill(pid, libc::SIGTERM) } == -1 {
702        let error = std::io::Error::last_os_error();
703        if error.raw_os_error() != Some(libc::ESRCH) {
704            return Err(HapiError::Io(error));
705        }
706    }
707    let term_deadline = Instant::now() + Duration::from_secs(1);
708    loop {
709        let mut status = 0;
710        let result = unsafe { libc::waitpid(pid, &raw mut status, libc::WNOHANG) };
711        if result == pid
712            || (result == -1
713                && std::io::Error::last_os_error().raw_os_error() == Some(libc::ECHILD))
714        {
715            return Ok(());
716        }
717        if result == -1 {
718            return Err(HapiError::Io(std::io::Error::last_os_error()));
719        }
720        if Instant::now() >= term_deadline {
721            break;
722        }
723        thread::sleep(Duration::from_millis(20));
724    }
725    if unsafe { libc::kill(pid, libc::SIGKILL) } == -1 {
726        let error = std::io::Error::last_os_error();
727        if error.raw_os_error() != Some(libc::ESRCH) {
728            return Err(HapiError::Io(error));
729        }
730    }
731    let mut status = 0;
732    let result = unsafe { libc::waitpid(pid, &raw mut status, 0) };
733    if result == pid
734        || (result == -1 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ECHILD))
735    {
736        Ok(())
737    } else {
738        Err(HapiError::Io(std::io::Error::last_os_error()))
739    }
740}
741
742/// Start an interactive Houdini session with engine server embedded.
743pub fn start_houdini_server(
744    pipe_name: impl AsRef<str>,
745    houdini_executable: impl AsRef<Path>,
746    fx_license: bool,
747    env_variables: Option<&[(String, String)]>,
748) -> Result<Child> {
749    let mut command = Command::new(houdini_executable.as_ref());
750    call_with_temp_environment(env_variables, move || {
751        command
752            .arg(format!("-hess=pipe:{}", pipe_name.as_ref()))
753            .arg(if fx_license {
754                "-force-fx-license"
755            } else {
756                "-core"
757            })
758            .stdin(Stdio::null())
759            .stdout(Stdio::null())
760            .stderr(Stdio::null())
761            .spawn()
762            .map_err(HapiError::from)
763    })
764}
765
766#[cfg(test)]
767mod tests {
768    use super::*;
769    use std::cell::Cell;
770    use std::{ffi::OsString, net::Ipv4Addr, num::NonZeroU64};
771
772    use crate::ffi::enums::StatusVerbosity;
773
774    #[test]
775    fn license_preference_display_strings() {
776        assert_eq!(
777            LicensePreference::AnyAvailable.to_string(),
778            "--check-licenses=Houdini-Engine,Houdini-Escape,Houdini-Fx"
779        );
780        assert_eq!(
781            LicensePreference::HoudiniEngineOnly.to_string(),
782            "--check-licenses=Houdini-Engine --skip-licenses=Houdini-Escape,Houdini-Fx"
783        );
784        assert_eq!(
785            LicensePreference::HoudiniEngineAndCore.to_string(),
786            "--check-licenses=Houdini-Engine,Houdini-Escape --skip-licenses=Houdini-Fx"
787        );
788    }
789
790    #[test]
791    fn shared_memory_transport_builder_applies_options() {
792        let transport = ThriftSharedMemoryTransportBuilder::default()
793            .with_memory_name("test-memory")
794            .with_buffer_type(ThriftSharedMemoryBufferType::RingBuffer)
795            .with_buffer_size(NonZeroU64::new(512).unwrap())
796            .build();
797
798        assert_eq!(transport.memory_name, "test-memory");
799        assert_eq!(
800            transport.buffer_type,
801            ThriftSharedMemoryBufferType::RingBuffer
802        );
803        assert_eq!(transport.buffer_size, 512);
804    }
805
806    #[test]
807    fn shared_memory_transport_builder_clamps_oversized_buffer() {
808        let transport = ThriftSharedMemoryTransportBuilder::default()
809            .with_buffer_size(NonZeroU64::new(i64::MAX as u64 + 1).unwrap())
810            .build();
811
812        assert_eq!(transport.buffer_size, 100);
813    }
814
815    #[test]
816    fn server_options_shared_memory_maps_to_session_and_thrift_options() {
817        let transport = ThriftSharedMemoryTransportBuilder::default()
818            .with_buffer_type(ThriftSharedMemoryBufferType::RingBuffer)
819            .with_buffer_size(NonZeroU64::new(256).unwrap())
820            .build();
821        let options = ServerOptions::default()
822            .with_auto_close(false)
823            .with_verbosity(StatusVerbosity::Statusverbosity2)
824            .with_server_ready_timeout(5_000)
825            .with_thrift_transport(ThriftTransport::SharedMemory(transport.clone()));
826
827        let session_info = options.session_info();
828        assert_eq!(
829            session_info.shared_memory_buffer_type(),
830            ThriftSharedMemoryBufferType::RingBuffer
831        );
832        assert_eq!(session_info.shared_memory_buffer_size(), 256);
833
834        let thrift_options = options.thrift_options();
835        assert!(!thrift_options.auto_close());
836        assert_eq!(
837            thrift_options.verbosity(),
838            StatusVerbosity::Statusverbosity2
839        );
840        assert_eq!(
841            thrift_options.shared_memory_buffer_type(),
842            ThriftSharedMemoryBufferType::RingBuffer
843        );
844        assert_eq!(thrift_options.shared_memory_buffer_size(), 256);
845        assert_eq!(thrift_options.timeout_ms(), 5_000.0);
846    }
847
848    #[test]
849    fn server_options_license_preference_sets_plugin_env() {
850        let options =
851            ServerOptions::default().with_license_preference(LicensePreference::HoudiniEngineOnly);
852        let env = options.env_variables.expect("env map");
853        assert_eq!(
854            env.get(&OsString::from("HOUDINI_PLUGIN_LIC_OPT")),
855            Some(&OsString::from(
856                "--check-licenses=Houdini-Engine --skip-licenses=Houdini-Escape,Houdini-Fx"
857            ))
858        );
859    }
860
861    #[test]
862    fn environment_variables_merge_with_license_preference() {
863        let options = ServerOptions::default()
864            .with_license_preference(LicensePreference::HoudiniEngineOnly)
865            .with_env_variables([("HAPI_RS_TEST", "present")].iter());
866        let env = options.env_variables.expect("env map");
867        assert_eq!(
868            env.get(&OsString::from("HAPI_RS_TEST")),
869            Some(&OsString::from("present"))
870        );
871        assert!(env.contains_key(&OsString::from("HOUDINI_PLUGIN_LIC_OPT")));
872    }
873
874    #[test]
875    fn invalid_public_server_options_are_rejected() {
876        let mut options = ServerOptions::shared_memory_with_defaults();
877        options.connection_count = -1;
878        assert!(validate_server_options(&options).is_err());
879
880        let mut options = ServerOptions::shared_memory_with_defaults();
881        let ThriftTransport::SharedMemory(transport) = &mut options.thrift_transport else {
882            unreachable!()
883        };
884        transport.buffer_size = 0;
885        assert!(validate_server_options(&options).is_err());
886
887        let mut options = ServerOptions::shared_memory_with_defaults();
888        let ThriftTransport::SharedMemory(transport) = &mut options.thrift_transport else {
889            unreachable!()
890        };
891        transport.memory_name.clear();
892        assert!(validate_server_options(&options).is_err());
893
894        let options = ServerOptions::default().with_thrift_transport(ThriftTransport::Pipe(
895            ThriftPipeTransport {
896                pipe_path: PathBuf::new(),
897            },
898        ));
899        assert!(validate_server_options(&options).is_err());
900
901        let options =
902            ServerOptions::socket_with_defaults(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0));
903        assert!(validate_server_options(&options).is_err());
904    }
905
906    #[test]
907    fn socket_with_defaults_preserves_address() {
908        let address = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 12_345);
909        let options = ServerOptions::socket_with_defaults(address);
910        let ThriftTransport::Socket(ThriftSocketTransport { address: actual }) =
911            options.thrift_transport
912        else {
913            panic!("expected socket transport");
914        };
915        assert_eq!(actual, address);
916    }
917
918    #[test]
919    fn connect_rejects_mismatched_transport_without_calling_hapi() {
920        let memory_options = ServerOptions::shared_memory_with_defaults();
921        let pipe_options = ServerOptions::pipe_with_defaults();
922        let socket_options =
923            ServerOptions::socket_with_defaults(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 9_999));
924
925        assert!(connect_to_memory_server(pipe_options.clone(), None).is_err());
926        assert!(connect_to_pipe_server(memory_options.clone(), None).is_err());
927        assert!(connect_to_socket_server(memory_options, None).is_err());
928        assert!(connect_to_memory_server(socket_options.clone(), None).is_err());
929        assert!(connect_to_pipe_server(socket_options, None).is_err());
930    }
931
932    #[test]
933    fn zero_connection_timeout_attempts_once_without_sleeping() {
934        let attempts = Cell::new(0);
935        let started = Instant::now();
936        let error = try_connect_with_timeout(Some(Duration::ZERO), Duration::from_secs(1), || {
937            attempts.set(attempts.get() + 1);
938            Err(HapiError::Internal("not ready".to_owned()))
939        })
940        .unwrap_err();
941
942        assert_eq!(attempts.get(), 1);
943        assert!(started.elapsed() < Duration::from_millis(100));
944        assert!(error.to_string().contains("within timeout"));
945    }
946
947    #[test]
948    fn connection_retry_returns_first_success() {
949        let attempts = Cell::new(0);
950        let handle = try_connect_with_timeout(None, Duration::ZERO, || {
951            attempts.set(attempts.get() + 1);
952            if attempts.get() < 3 {
953                Err(HapiError::Internal("not ready".to_owned()))
954            } else {
955                Ok(crate::ffi::raw::HAPI_Session {
956                    type_: crate::ffi::raw::SessionType::Thrift,
957                    id: 42,
958                })
959            }
960        })
961        .unwrap();
962
963        assert_eq!(attempts.get(), 3);
964        assert_eq!(handle.id, 42);
965    }
966
967    #[cfg(unix)]
968    #[test]
969    fn owned_child_is_reaped_after_graceful_exit() {
970        let child = Command::new("sh")
971            .args(["-c", "exit 0"])
972            .spawn()
973            .expect("spawn child");
974        let pid = child.id();
975        drop(child);
976
977        reap_unix_child(pid, true).expect("reap child");
978        assert_child_already_reaped(pid);
979    }
980
981    #[cfg(unix)]
982    #[test]
983    fn owned_child_uses_kill_fallback_when_term_is_ignored() {
984        let child = Command::new("sh")
985            .args(["-c", "trap '' TERM; exec sleep 30"])
986            .spawn()
987            .expect("spawn child");
988        let pid = child.id();
989        drop(child);
990        thread::sleep(Duration::from_millis(100));
991
992        reap_unix_child(pid, false).expect("terminate and reap child");
993        assert_child_already_reaped(pid);
994    }
995
996    #[cfg(unix)]
997    #[test]
998    fn auto_close_false_leaves_owned_server_running() {
999        let mut child = Command::new("sleep")
1000            .arg("30")
1001            .spawn()
1002            .expect("spawn child");
1003        let pid = child.id();
1004
1005        finish_owned_server(pid, false, false, None).expect("leave child running");
1006        assert!(child.try_wait().expect("query child").is_none());
1007
1008        child.kill().expect("kill test child");
1009        child.wait().expect("reap test child");
1010    }
1011
1012    #[cfg(unix)]
1013    #[test]
1014    fn construction_failure_terminates_child_and_removes_owned_pipe() {
1015        let child = Command::new("sleep")
1016            .arg("30")
1017            .spawn()
1018            .expect("spawn child");
1019        let pid = child.id();
1020        drop(child);
1021        let pipe = tempfile::NamedTempFile::new().expect("temporary pipe placeholder");
1022        let pipe_path = pipe.path().to_owned();
1023        drop(pipe);
1024
1025        finish_owned_server(pid, true, true, Some(&pipe_path)).expect("rollback server");
1026        assert!(!pipe_path.exists());
1027        assert_child_already_reaped(pid);
1028    }
1029
1030    #[cfg(unix)]
1031    #[test]
1032    fn already_reaped_child_is_a_successful_noop() {
1033        let mut child = Command::new("sh")
1034            .args(["-c", "exit 0"])
1035            .spawn()
1036            .expect("spawn child");
1037        let pid = child.id();
1038        child.wait().expect("reap child");
1039
1040        reap_unix_child(pid, true).expect("already-reaped child is okay");
1041    }
1042
1043    #[cfg(unix)]
1044    fn assert_child_already_reaped(pid: u32) {
1045        let mut status = 0;
1046        let result = unsafe { libc::waitpid(pid as i32, &raw mut status, libc::WNOHANG) };
1047        assert_eq!(result, -1);
1048        assert_eq!(
1049            std::io::Error::last_os_error().raw_os_error(),
1050            Some(libc::ECHILD)
1051        );
1052    }
1053}