Skip to main content

hapi_rs/
session.rs

1//! Session is responsible for communicating with HAPI
2//!
3//! The Engine [promises](https://www.sidefx.com/docs/hengine/_h_a_p_i__sessions.html#HAPI_Sessions_Multithreading)
4//! to be thread-safe when accessing a single `Session` from multiple threads.
5//! `hapi-rs` relies on this promise and the [Session] struct holds only an `Arc` pointer to the session,
6//! and *does not* protect the session with Mutex, although there is a [`ReentrantMutex`]
7//! private member which is used internally in a few cases where API calls must be sequential.
8//!
9//! When the last instance of the `Session` is about to get dropped, it'll be cleaned up
10//! (if [`SessionOptions::cleanup`] was set) and automatically closed.
11//!
12//! The Engine process (pipe, socket, or shared memory) can be auto-terminated as well if told so when starting
13//! the server. See [`crate::server::start_engine_server`] together with the transport helpers
14//! [`crate::server::connect_to_pipe_server`], [`crate::server::connect_to_socket_server`], and
15//! [`crate::server::connect_to_memory_server`].
16//!
17//! Helper constructors terminate the server by default. This is useful for quick one-off jobs.
18//!
19use log::{debug, error};
20use parking_lot::{Mutex, ReentrantMutex};
21use std::fmt::Debug;
22use std::path::PathBuf;
23use std::{
24    ffi::CString,
25    path::Path,
26    sync::{
27        Arc,
28        atomic::{AtomicBool, Ordering},
29    },
30};
31
32pub use crate::{
33    asset::AssetLibrary,
34    errors::*,
35    ffi::{
36        CompositorOptions, CookOptions, ImageFileFormat, ImageInfo, SessionInfo, SessionSyncInfo,
37        ThriftServerOptions, TimelineOptions, Viewport, enums::*,
38    },
39    node::{HoudiniNode, ManagerNode, ManagerType, NodeHandle, NodeType, Transform},
40    parameter::Parameter,
41    server::ServerOptions,
42    stringhandle::StringArray,
43};
44
45/// State returned by `HAPI_GetStatus` for `HAPI_STATUS_COOK_STATE`.
46pub type SessionState = State;
47/// Houdini license type currently checked out by the session.
48pub type LicenseType = raw::License;
49
50use crate::cop::CopImageDescription;
51use crate::ffi::CameraInfo;
52use crate::stringhandle::StringHandle;
53use crate::{ffi::raw, utils};
54
55static IN_PROCESS_RUNTIME_SHUT_DOWN: AtomicBool = AtomicBool::new(false);
56
57#[derive(Debug)]
58pub(crate) enum ServerConnection {
59    Borrowed {
60        reported_pid: Option<u32>,
61    },
62    OwnedHars {
63        pid: u32,
64        auto_close: bool,
65        pipe_path: Option<PathBuf>,
66    },
67    InProcess,
68}
69
70impl ServerConnection {
71    fn pid(&self) -> Option<u32> {
72        match self {
73            Self::Borrowed { reported_pid } => *reported_pid,
74            Self::OwnedHars { pid, .. } => Some(*pid),
75            Self::InProcess => None,
76        }
77    }
78
79    fn finish(&self, construction_failed: bool) -> Result<()> {
80        match self {
81            Self::OwnedHars {
82                pid,
83                auto_close,
84                pipe_path,
85            } => crate::server::finish_owned_server(
86                *pid,
87                *auto_close,
88                construction_failed,
89                pipe_path.as_deref(),
90            ),
91            Self::Borrowed { .. } | Self::InProcess => Ok(()),
92        }
93    }
94}
95
96#[derive(Debug)]
97struct LifecycleState {
98    closed: bool,
99    server: ServerConnection,
100}
101
102trait LifecycleBackend {
103    fn is_valid(&mut self, handle: &raw::HAPI_Session) -> bool;
104    fn is_initialized(&mut self, handle: &raw::HAPI_Session) -> bool;
105    fn cleanup(&mut self, handle: &raw::HAPI_Session) -> Result<()>;
106    fn shutdown(&mut self, handle: &raw::HAPI_Session) -> Result<()>;
107    fn close(&mut self, handle: &raw::HAPI_Session) -> Result<()>;
108    fn finish_server(&mut self, server: &ServerConnection, construction_failed: bool)
109    -> Result<()>;
110    fn mark_in_process_shutdown(&mut self);
111}
112
113struct HapiLifecycleBackend;
114
115impl LifecycleBackend for HapiLifecycleBackend {
116    fn is_valid(&mut self, handle: &raw::HAPI_Session) -> bool {
117        crate::ffi::is_raw_session_valid(handle)
118    }
119
120    fn is_initialized(&mut self, handle: &raw::HAPI_Session) -> bool {
121        crate::ffi::is_raw_session_initialized(handle)
122    }
123
124    fn cleanup(&mut self, handle: &raw::HAPI_Session) -> Result<()> {
125        crate::ffi::cleanup_raw_session(handle)
126    }
127
128    fn shutdown(&mut self, handle: &raw::HAPI_Session) -> Result<()> {
129        crate::ffi::shutdown_raw_session(handle)
130    }
131
132    fn close(&mut self, handle: &raw::HAPI_Session) -> Result<()> {
133        crate::ffi::close_raw_session(handle)
134    }
135
136    fn finish_server(
137        &mut self,
138        server: &ServerConnection,
139        construction_failed: bool,
140    ) -> Result<()> {
141        server.finish(construction_failed)
142    }
143
144    fn mark_in_process_shutdown(&mut self) {
145        IN_PROCESS_RUNTIME_SHUT_DOWN.store(true, Ordering::Release);
146    }
147}
148
149fn lifecycle_errors(errors: Vec<String>, operation: &str) -> Result<()> {
150    if errors.is_empty() {
151        Ok(())
152    } else {
153        Err(HapiError::Internal(format!(
154            "{operation} encountered errors: {}",
155            errors.join("; ")
156        )))
157    }
158}
159
160/// Builder struct for [`Session::node_builder`] API
161pub struct NodeBuilder<'s> {
162    session: &'s Session,
163    name: String,
164    label: Option<String>,
165    parent: Option<NodeHandle>,
166    cook: bool,
167}
168
169impl NodeBuilder<'_> {
170    /// Give new node a label
171    #[must_use]
172    pub fn with_label(mut self, label: impl Into<String>) -> Self {
173        self.label = Some(label.into());
174        self
175    }
176
177    /// Create new node as child of a parent node.
178    #[must_use]
179    pub fn with_parent<H: AsRef<NodeHandle>>(mut self, parent: H) -> Self {
180        self.parent.replace(*parent.as_ref());
181        self
182    }
183
184    /// Cook node after creation.
185    #[must_use]
186    pub fn cook(mut self, cook: bool) -> Self {
187        self.cook = cook;
188        self
189    }
190
191    /// Consume the builder and create the node
192    pub fn create(self) -> Result<HoudiniNode> {
193        let NodeBuilder {
194            session,
195            name,
196            label,
197            parent,
198            cook,
199        } = self;
200        session.create_node_with(&name, parent, label.as_deref(), cook)
201    }
202}
203
204impl PartialEq for raw::HAPI_Session {
205    fn eq(&self, other: &Self) -> bool {
206        self.type_ == other.type_ && self.id == other.id
207    }
208}
209
210/// Trait bound for [`Session::get_server_var()`] and [`Session::set_server_var()`]
211pub trait EnvVariable {
212    type Type: ?Sized + ToOwned + Debug;
213    fn get_value(session: &Session, key: impl AsRef<str>)
214    -> Result<<Self::Type as ToOwned>::Owned>;
215    fn set_value(session: &Session, key: impl AsRef<str>, val: &Self::Type) -> Result<()>;
216}
217
218impl EnvVariable for str {
219    type Type = str;
220
221    fn get_value(session: &Session, key: impl AsRef<str>) -> Result<String> {
222        let key = CString::new(key.as_ref())?;
223        let handle = crate::ffi::get_server_env_str(session, &key)?;
224        crate::stringhandle::get_string(handle, session)
225    }
226
227    fn set_value(session: &Session, key: impl AsRef<str>, val: &Self::Type) -> Result<()> {
228        let key = CString::new(key.as_ref())?;
229        let val = CString::new(val)?;
230        crate::ffi::set_server_env_str(session, &key, &val)
231    }
232}
233
234impl EnvVariable for Path {
235    type Type = Self;
236
237    fn get_value(session: &Session, key: impl AsRef<str>) -> Result<PathBuf> {
238        let key = CString::new(key.as_ref())?;
239        crate::stringhandle::get_string(crate::ffi::get_server_env_str(session, &key)?, session)
240            .map(PathBuf::from)
241    }
242
243    fn set_value(session: &Session, key: impl AsRef<str>, val: &Self::Type) -> Result<()> {
244        let key = CString::new(key.as_ref())?;
245        let val = utils::path_to_cstring(val)?;
246        crate::ffi::set_server_env_str(session, &key, &val)
247    }
248}
249
250impl EnvVariable for i32 {
251    type Type = Self;
252
253    fn get_value(session: &Session, key: impl AsRef<str>) -> Result<Self::Type> {
254        let key = CString::new(key.as_ref())?;
255        crate::ffi::get_server_env_int(session, &key)
256    }
257
258    fn set_value(session: &Session, key: impl AsRef<str>, val: &Self::Type) -> Result<()> {
259        let key = CString::new(key.as_ref())?;
260        crate::ffi::set_server_env_int(session, &key, *val)
261    }
262}
263
264/// Result of async cook operation [`Session::cook`]
265#[derive(Debug, Clone, Eq, PartialEq)]
266pub enum CookResult {
267    /// Cooking completed without cook or fatal errors.
268    Succeeded,
269    /// Some nodes cooked with errors
270    CookErrors(String),
271    /// One or more nodes could not cook - should abort cooking
272    FatalErrors(String),
273}
274
275impl CookResult {
276    /// Convenient method for cook result message if any
277    #[must_use]
278    pub fn message(&self) -> Option<&str> {
279        match self {
280            Self::Succeeded => None,
281            Self::CookErrors(msg) | Self::FatalErrors(msg) => Some(msg.as_str()),
282        }
283    }
284}
285
286/// By which means the session communicates with the server.
287#[derive(Debug)]
288pub(crate) struct SessionInner {
289    pub(crate) handle: raw::HAPI_Session,
290    pub(crate) options: SessionOptions,
291    pub(crate) lock: ReentrantMutex<()>,
292    lifecycle: Mutex<LifecycleState>,
293}
294
295/// An initialized connection to a Houdini Engine runtime.
296///
297/// Clones share one underlying HAPI session. The connection remains open until
298/// [`Self::close`] is called or the last clone and all objects retaining a clone
299/// are dropped. Final teardown is performed exactly once.
300///
301/// `Session` is [`Send`] and [`Sync`]. HARC serializes individual calls made to
302/// one Thrift session; callers must still coordinate multi-call operations for
303/// which ordering matters.
304///
305/// Dropping or closing a session always calls `HAPI_CloseSession`. The optional,
306/// potentially expensive `HAPI_Cleanup` step is controlled by
307/// [`SessionOptions::cleanup`] and is disabled by default.
308#[derive(Debug, Clone)]
309pub struct Session {
310    pub(crate) inner: Arc<SessionInner>,
311}
312
313impl PartialEq for Session {
314    fn eq(&self, other: &Self) -> bool {
315        self.inner.handle.id == other.inner.handle.id
316            && self.inner.handle.type_ == other.inner.handle.type_
317    }
318}
319
320/// A live HAPI connection that has not yet been initialized.
321///
322/// Values are returned by the `connect_to_*` helpers in [`crate::server`]. Call
323/// [`Self::initialize`] to run `HAPI_Initialize` and obtain a [`Session`]. If
324/// this value is dropped or initialization fails, its native connection is
325/// closed automatically.
326#[derive(Debug)]
327pub struct UninitializedSession {
328    pub(crate) session_handle: Option<raw::HAPI_Session>,
329    pub(crate) server_options: Option<ServerOptions>,
330    pub(crate) server: ServerConnection,
331}
332
333impl UninitializedSession {
334    /// Initialize the Houdini Engine runtime for this connection.
335    ///
336    /// On success, ownership of the native handle transfers to the returned
337    /// [`Session`]. On failure, the connection is closed during rollback.
338    pub fn initialize(mut self, session_options: SessionOptions) -> Result<Session> {
339        debug!("Initializing session");
340        let handle = self
341            .session_handle
342            .expect("uninitialized session handle was already consumed");
343        crate::ffi::initialize_session(handle, &session_options)
344            .with_context(|| "Calling initialize_session")?;
345
346        self.session_handle.take();
347        let server = std::mem::replace(
348            &mut self.server,
349            ServerConnection::Borrowed { reported_pid: None },
350        );
351        Ok(Session {
352            inner: Arc::new(SessionInner {
353                handle,
354                options: session_options,
355                lock: ReentrantMutex::new(()),
356                lifecycle: Mutex::new(LifecycleState {
357                    closed: false,
358                    server,
359                }),
360            }),
361        })
362    }
363
364    pub(crate) fn mark_owned_server(&mut self, pid: u32) {
365        let (auto_close, pipe_path) =
366            self.server_options
367                .as_ref()
368                .map_or((true, None), |options| {
369                    let pipe_path = match &options.thrift_transport {
370                        crate::server::ThriftTransport::Pipe(transport) => {
371                            Some(transport.pipe_path.clone())
372                        }
373                        crate::server::ThriftTransport::SharedMemory(_)
374                        | crate::server::ThriftTransport::Socket(_) => None,
375                    };
376                    (options.auto_close, pipe_path)
377                });
378        self.server = ServerConnection::OwnedHars {
379            pid,
380            auto_close,
381            pipe_path,
382        };
383    }
384}
385
386impl Drop for UninitializedSession {
387    fn drop(&mut self) {
388        let handle = self.session_handle.take();
389        if let Err(error) =
390            rollback_uninitialized_with(handle.as_ref(), &self.server, &mut HapiLifecycleBackend)
391        {
392            error!("Uninitialized session rollback failed: {error}");
393        }
394    }
395}
396
397fn rollback_uninitialized_with<B: LifecycleBackend>(
398    handle: Option<&raw::HAPI_Session>,
399    server: &ServerConnection,
400    backend: &mut B,
401) -> Result<()> {
402    let mut errors = Vec::new();
403    if let Some(handle) = handle
404        && backend.is_valid(handle)
405    {
406        if backend.is_initialized(handle)
407            && let Err(error) = backend.cleanup(handle)
408        {
409            errors.push(error.to_string());
410        }
411        if matches!(server, ServerConnection::InProcess)
412            && let Err(error) = backend.shutdown(handle)
413        {
414            errors.push(error.to_string());
415        }
416        if let Err(error) = backend.close(handle) {
417            errors.push(error.to_string());
418        }
419    }
420    if matches!(server, ServerConnection::InProcess) {
421        backend.mark_in_process_shutdown();
422    }
423    if let Err(error) = backend.finish_server(server, true) {
424        errors.push(error.to_string());
425    }
426    lifecycle_errors(errors, "Uninitialized session rollback")
427}
428
429impl Session {
430    /// Return [`SessionType`] current session is initialized with.
431    #[must_use]
432    pub fn session_type(&self) -> SessionType {
433        self.inner.handle.type_
434    }
435
436    /// Return the server PID when it was supplied by the caller or the server
437    /// was started by this crate. In-process sessions return `None`.
438    #[must_use]
439    pub fn server_pid(&self) -> Option<u32> {
440        self.inner.lifecycle.lock().server.pid()
441    }
442
443    #[inline]
444    pub(crate) fn ptr(&self) -> *const raw::HAPI_Session {
445        &raw const self.inner.handle
446    }
447
448    /// Set environment variable on the server. This is set AFTER the server has started.
449    /// For variables set before the server starts, use [`ServerOptions::with_env_variables`].
450    pub fn set_server_var<T: EnvVariable + ?Sized>(
451        &self,
452        key: &str,
453        value: &T::Type,
454    ) -> Result<()> {
455        debug_assert!(self.is_valid());
456        debug!("Setting server variable {key}={value:?}");
457        T::set_value(self, key, value)
458    }
459
460    /// Get environment variable from the server
461    pub fn get_server_var<T: EnvVariable + ?Sized>(
462        &self,
463        key: &str,
464    ) -> Result<<T::Type as ToOwned>::Owned> {
465        debug_assert!(self.is_valid());
466        debug!("Querying server variable {key}");
467        T::get_value(self, key)
468    }
469
470    /// Retrieve all server variables as contiguous string array.
471    /// Iterating over the array will yield strings like "TEST=177".
472    pub fn get_server_variables(&self) -> Result<StringArray> {
473        debug_assert!(self.is_valid());
474        debug!("Querying all server variables");
475        let count = crate::ffi::get_server_env_var_count(self)?;
476        let handles = crate::ffi::get_server_env_var_list(self, count)?;
477        crate::stringhandle::get_string_array(&handles, self).context("Calling get_string_array")
478    }
479
480    /// Retrieve string data given a handle.
481    pub fn get_string(&self, handle: StringHandle) -> Result<String> {
482        crate::stringhandle::get_string(handle, self)
483    }
484
485    /// Retrieve multiple strings in batch mode.
486    pub fn get_string_batch(&self, handles: &[StringHandle]) -> Result<StringArray> {
487        crate::stringhandle::get_string_array(handles, self)
488    }
489
490    /// Push a custom string to the server and return a handle to it.
491    pub fn set_custom_string(&self, string: impl AsRef<str>) -> Result<StringHandle> {
492        debug_assert!(self.is_valid());
493        debug!("Setting custom string: {}", string.as_ref());
494        let string = CString::new(string.as_ref())?;
495        crate::ffi::set_custom_string(self, &string)
496    }
497
498    /// Remove a custom string from the server.
499    pub fn remove_custom_string(&self, handle: StringHandle) -> Result<()> {
500        debug_assert!(self.is_valid());
501        debug!("Removing custom string: {handle:?}");
502        crate::ffi::remove_custom_string(self, handle)
503    }
504
505    /// Close the shared underlying session.
506    ///
507    /// This operation is idempotent. All clones become closed after this call.
508    pub fn close(&self) -> Result<()> {
509        self.inner.finalize()
510    }
511
512    /// Close the shared underlying session.
513    #[deprecated(note = "use Session::close; HAPI cleanup alone does not close a session")]
514    pub fn cleanup(self) -> Result<()> {
515        self.close()
516    }
517
518    /// Create an input geometry node which can accept modifications
519    pub fn create_input_node(
520        &self,
521        name: &str,
522        parent: Option<NodeHandle>,
523    ) -> Result<crate::geometry::Geometry> {
524        debug!("Creating input node: {name}");
525        debug_assert!(self.is_valid());
526        let name = CString::new(name)?;
527        let id = crate::ffi::create_input_node(self, &name, parent)?;
528        let node = HoudiniNode::new(self.clone(), NodeHandle(id), None)?;
529        crate::ffi::cook_node(&node, None).with_context(|| "Cooking input node")?;
530        let info =
531            crate::geometry::GeoInfo::from_node(&node).with_context(|| "Getting geometry info")?;
532        Ok(crate::geometry::Geometry { node, info })
533    }
534
535    /// Create an input geometry node with [`PartType`] set to `Curve`
536    pub fn create_input_curve_node(
537        &self,
538        name: &str,
539        parent: Option<NodeHandle>,
540    ) -> Result<crate::geometry::Geometry> {
541        debug!("Creating input curve node: {name}");
542        debug_assert!(self.is_valid());
543        let name = CString::new(name)?;
544        let id = crate::ffi::create_input_curve_node(self, &name, parent)?;
545        let node = HoudiniNode::new(self.clone(), NodeHandle(id), None)?;
546        let info = crate::geometry::GeoInfo::from_node(&node)?;
547        Ok(crate::geometry::Geometry { node, info })
548    }
549
550    /// Create a node. `name` must start with a network category, e.g, "Object/geo", "Sop/box",
551    /// in operator namespace was used, the full name may look like this: `namespace::Object/mynode`
552    /// If you need more creating options, see the [`Session::node_builder`] API.
553    /// New node will *not* be cooked.
554    pub fn create_node(&self, name: impl AsRef<str>) -> Result<HoudiniNode> {
555        self.create_node_with(name.as_ref(), None, None, false)
556    }
557
558    /// A builder pattern for creating a node with more options.
559    pub fn node_builder(&self, node_name: impl Into<String>) -> NodeBuilder<'_> {
560        NodeBuilder {
561            session: self,
562            name: node_name.into(),
563            label: None,
564            parent: None,
565            cook: false,
566        }
567    }
568
569    // Internal function for creating nodes
570    pub(crate) fn create_node_with<P>(
571        &self,
572        name: &str,
573        parent: P,
574        label: Option<&str>,
575        cook: bool,
576    ) -> Result<HoudiniNode>
577    where
578        P: Into<Option<NodeHandle>>,
579    {
580        let parent = parent.into();
581        debug!("Creating node instance for op: {name}, with parent: {parent:?}");
582        debug_assert!(self.is_valid());
583        debug_assert!(
584            parent.is_some() || name.contains('/'),
585            "Node name must be fully qualified if parent node is not specified"
586        );
587        debug_assert!(
588            !(parent.is_some() && name.contains('/')),
589            "Cannot use fully qualified node name with parent node"
590        );
591        let name = CString::new(name)?;
592        let label = label.map(CString::new).transpose()?;
593        let node_id = crate::ffi::create_node(&name, label.as_deref(), self, parent, cook)?;
594        if self.inner.options.threaded {
595            // In async cooking mode, cook() always returns a CookResult::Success, we need to check CookResult for errors
596            if let CookResult::FatalErrors(message) = self.cook()? {
597                return Err(HapiError::Hapi {
598                    result_code: HapiResultCode(HapiResult::Failure),
599                    server_message: Some(message),
600                    contexts: Vec::new(),
601                });
602            }
603        }
604        HoudiniNode::new(self.clone(), NodeHandle(node_id), None)
605    }
606
607    /// Delete the node from the session. See also [`HoudiniNode::delete`]
608    pub fn delete_node<H: Into<NodeHandle>>(&self, node: H) -> Result<()> {
609        let node = node.into();
610        debug!(
611            "Deleting node {}",
612            node.path(self)
613                .unwrap_or_else(|_| "Could not get path".to_owned())
614        );
615        crate::ffi::delete_node(node, self)
616    }
617
618    /// Find a node given an absolute path. To find a child node, pass the `parent` node
619    /// or use [`HoudiniNode::find_child_node`]
620    pub fn get_node_from_path(
621        &self,
622        path: impl AsRef<str>,
623        parent: impl Into<Option<NodeHandle>>,
624    ) -> Result<Option<HoudiniNode>> {
625        debug_assert!(self.is_valid());
626        debug!("Searching node at path: {}", path.as_ref());
627        let path = CString::new(path.as_ref())?;
628        match crate::ffi::get_node_from_path(self, parent.into(), &path) {
629            Ok(handle) => Ok(NodeHandle(handle).to_node(self).ok()),
630            Err(HapiError::Hapi { result_code, .. })
631                if matches!(result_code.0, HapiResult::InvalidArgument) =>
632            {
633                Ok(None)
634            }
635            Err(e) => Err(e),
636        }
637    }
638
639    /// Find a parameter by path, absolute or relative to a start node.
640    pub fn find_parameter_from_path(
641        &self,
642        path: impl AsRef<str>,
643        start: impl Into<Option<NodeHandle>>,
644    ) -> Result<Option<Parameter>> {
645        debug_assert!(self.is_valid());
646        debug!("Searching parameter at path: {}", path.as_ref());
647        let Some((path, parm)) = path.as_ref().rsplit_once('/') else {
648            return Ok(None);
649        };
650        let Some(node) = self.get_node_from_path(path, start)? else {
651            debug!("Node {path} not found");
652            return Ok(None);
653        };
654        Ok(node.parameter(parm).ok())
655    }
656
657    /// Returns a manager (root) node such as OBJ, TOP, CHOP, etc
658    pub fn get_manager_node(&self, manager: ManagerType) -> Result<ManagerNode> {
659        debug_assert!(self.is_valid());
660        debug!("Getting Manager node of type: {manager:?}");
661        let node_type = NodeType::from(manager);
662        let handle = crate::ffi::get_manager_node(self, node_type)?;
663        Ok(ManagerNode {
664            session: self.clone(),
665            handle: NodeHandle(handle),
666            node_type: manager,
667        })
668    }
669
670    /// Return a list of transforms for all object nodes under a given parent node.
671    pub fn get_composed_object_transform(
672        &self,
673        parent: impl AsRef<NodeHandle>,
674        rst_order: RSTOrder,
675    ) -> Result<Vec<Transform>> {
676        debug_assert!(self.is_valid());
677        crate::ffi::get_composed_object_transforms(self, *parent.as_ref(), rst_order)
678            .map(|transforms| transforms.into_iter().map(Transform).collect())
679    }
680
681    /// Save current session to hip file
682    pub fn save_hip(&self, path: impl AsRef<Path>, lock_nodes: bool) -> Result<()> {
683        debug!("Saving hip file: {}", path.as_ref().display());
684        debug_assert!(self.is_valid());
685        let path = utils::path_to_cstring(path)?;
686        crate::ffi::save_hip(self, &path, lock_nodes)
687    }
688
689    /// Load a hip file into current session
690    pub fn load_hip(&self, path: impl AsRef<Path>, cook: bool) -> Result<()> {
691        debug!("Loading hip file: {}", path.as_ref().display());
692        debug_assert!(self.is_valid());
693        let path = utils::path_to_cstring(path)?;
694        crate::ffi::load_hip(self, &path, cook)
695    }
696
697    /// Merge a hip file into current session
698    pub fn merge_hip(&self, name: &str, cook: bool) -> Result<i32> {
699        debug!("Merging hip file: {name}");
700        debug_assert!(self.is_valid());
701        let name = CString::new(name)?;
702        crate::ffi::merge_hip(self, &name, cook)
703    }
704
705    /// Get node ids created by merging [`Session::merge_hip`] a hip file.
706    pub fn get_hip_file_nodes(&self, hip_id: i32) -> Result<Vec<NodeHandle>> {
707        crate::ffi::get_hipfile_node_ids(self, hip_id)
708            .map(|handles| handles.into_iter().map(NodeHandle).collect())
709    }
710
711    /// Load an HDA file into current session
712    pub fn load_asset_file(&self, file: impl AsRef<Path>) -> Result<AssetLibrary> {
713        debug_assert!(self.is_valid());
714        AssetLibrary::from_file(self.clone(), file)
715    }
716
717    /// Returns a list of loaded asset libraries including Houdini's default.
718    pub fn get_loaded_asset_libraries(&self) -> Result<Vec<AssetLibrary>> {
719        debug_assert!(self.is_valid());
720
721        crate::ffi::get_asset_library_ids(self)?
722            .into_iter()
723            .map(|library_id| {
724                crate::ffi::get_asset_library_file_path(self, library_id).map(|path| AssetLibrary {
725                    lib_id: library_id,
726                    session: self.clone(),
727                    file: Some(PathBuf::from(path)),
728                })
729            })
730            .collect()
731    }
732
733    /// Interrupt session cooking
734    pub fn interrupt(&self) -> Result<()> {
735        debug_assert!(self.is_valid());
736        debug!("Interrupting session cooking");
737        crate::ffi::interrupt(self)
738    }
739
740    // Uncertain if this API makes sense.
741    #[doc(hidden)]
742    #[allow(unused)]
743    pub(crate) fn get_call_result_status(&self) -> Result<HapiResult> {
744        debug_assert!(self.is_valid());
745        let status = crate::ffi::get_status_code(self, StatusType::CallResult)?;
746        Ok(unsafe { std::mem::transmute::<i32, HapiResult>(status) })
747    }
748
749    /// Get session state when the server is in threaded mode.
750    pub fn get_cook_state_status(&self) -> Result<SessionState> {
751        debug_assert!(self.is_valid());
752        crate::ffi::get_cook_state_status(self)
753    }
754
755    /// Is session currently cooking. In non-threaded mode always returns false
756    pub fn is_cooking(&self) -> Result<bool> {
757        debug_assert!(self.is_valid());
758        Ok(matches!(
759            self.get_cook_state_status()?,
760            SessionState::Cooking
761        ))
762    }
763
764    /// Explicit check if the session is valid. Many APIs do this check in the debug build.
765    #[inline]
766    #[must_use]
767    pub fn is_valid(&self) -> bool {
768        !self.inner.lifecycle.lock().closed && crate::ffi::is_session_valid(self)
769    }
770
771    /// Get the status message given a type and verbosity
772    pub fn get_status_string(
773        &self,
774        status: StatusType,
775        verbosity: StatusVerbosity,
776    ) -> Result<String> {
777        debug_assert!(self.is_valid());
778        crate::ffi::get_status_string(self, status, verbosity)
779    }
780
781    /// Get session cook result status as string
782    pub fn get_cook_result_string(&self, verbosity: StatusVerbosity) -> Result<String> {
783        debug_assert!(self.is_valid());
784        self.get_status_string(StatusType::CookResult, verbosity)
785    }
786
787    /// How many nodes need to cook
788    pub fn cooking_total_count(&self) -> Result<i32> {
789        debug_assert!(self.is_valid());
790        crate::ffi::get_cooking_total_count(self)
791    }
792
793    /// How many nodes have already cooked
794    pub fn cooking_current_count(&self) -> Result<i32> {
795        debug_assert!(self.is_valid());
796        crate::ffi::get_cooking_current_count(self)
797    }
798
799    /// In threaded mode wait for Session finishes cooking. In single-thread mode, immediately return
800    /// See [Documentation](https://www.sidefx.com/docs/hengine/_h_a_p_i__sessions.html)
801    pub fn cook(&self) -> Result<CookResult> {
802        debug_assert!(self.is_valid());
803        debug!("Cooking session..");
804        if self.inner.options.threaded {
805            loop {
806                match self.get_cook_state_status()? {
807                    SessionState::Ready => break Ok(CookResult::Succeeded),
808                    SessionState::ReadyWithFatalErrors => {
809                        self.interrupt()?;
810                        let err = self.get_cook_result_string(StatusVerbosity::Errors)?;
811                        break Ok(CookResult::FatalErrors(err));
812                    }
813                    SessionState::ReadyWithCookErrors => {
814                        let err = self.get_cook_result_string(StatusVerbosity::Errors)?;
815                        break Ok(CookResult::CookErrors(err));
816                    }
817                    // Continue polling
818                    _ => {}
819                }
820            }
821        } else {
822            // In single threaded mode, the cook happens inside of HAPI_CookNode(),
823            // and HAPI_GetStatus() will immediately return HAPI_STATE_READY.
824            Ok(CookResult::Succeeded)
825        }
826    }
827
828    /// Retrieve connection error if could not connect to engine instance
829    pub fn get_connection_error(&self, clear: bool) -> Result<String> {
830        debug_assert!(self.is_valid());
831        crate::ffi::get_connection_error(clear)
832    }
833
834    /// Get Houdini time
835    pub fn get_time(&self) -> Result<f64> {
836        debug_assert!(self.is_valid());
837        crate::ffi::get_time(self)
838    }
839
840    /// Set Houdini time
841    pub fn set_time(&self, time: f64) -> Result<()> {
842        debug_assert!(self.is_valid());
843        crate::ffi::set_time(self, time)
844    }
845
846    /// Lock the internal reentrant mutex. Should not be used in general, but may be useful
847    /// in certain situations when a series of API calls must be done in sequence
848    pub fn lock(&self) -> parking_lot::ReentrantMutexGuard<'_, ()> {
849        self.inner.lock.lock()
850    }
851
852    /// Set Houdini timeline options
853    pub fn set_timeline_options(&self, options: &TimelineOptions) -> Result<()> {
854        debug_assert!(self.is_valid());
855        crate::ffi::set_timeline_options(self, &options.0)
856    }
857
858    /// Get Houdini timeline options
859    pub fn get_timeline_options(&self) -> Result<TimelineOptions> {
860        debug_assert!(self.is_valid());
861        crate::ffi::get_timeline_options(self).map(TimelineOptions)
862    }
863
864    /// Set session to use Houdini time
865    pub fn set_use_houdini_time(&self, do_use: bool) -> Result<()> {
866        debug_assert!(self.is_valid());
867        crate::ffi::set_use_houdini_time(self, do_use)
868    }
869
870    /// Check if session uses Houdini time
871    pub fn get_use_houdini_time(&self) -> Result<bool> {
872        debug_assert!(self.is_valid());
873        crate::ffi::get_use_houdini_time(self)
874    }
875
876    /// Get the viewport(camera) position
877    pub fn get_viewport(&self) -> Result<Viewport> {
878        debug_assert!(self.is_valid());
879        crate::ffi::get_viewport(self).map(Viewport)
880    }
881
882    /// Set the viewport(camera) position
883    pub fn set_viewport(&self, viewport: &Viewport) -> Result<()> {
884        debug_assert!(self.is_valid());
885        crate::ffi::set_viewport(self, viewport)
886    }
887
888    /// Set session sync mode on/off
889    pub fn set_sync(&self, enable: bool) -> Result<()> {
890        debug_assert!(self.is_valid());
891        crate::ffi::set_session_sync(self, enable)
892    }
893    /// Get session sync info
894    pub fn get_sync_info(&self) -> Result<SessionSyncInfo> {
895        debug_assert!(self.is_valid());
896        crate::ffi::get_session_sync_info(self).map(SessionSyncInfo)
897    }
898
899    /// Set session sync info
900    pub fn set_sync_info(&self, info: &SessionSyncInfo) -> Result<()> {
901        debug_assert!(self.is_valid());
902        crate::ffi::set_session_sync_info(self, &info.0)
903    }
904
905    /// Get license type used by this session
906    pub fn get_license_type(&self) -> Result<LicenseType> {
907        debug_assert!(self.is_valid());
908        crate::ffi::session_get_license_type(self)
909    }
910
911    /// Render a COP node to an image file
912    pub fn render_cop_to_image(
913        &self,
914        cop_node: impl Into<NodeHandle>,
915        output_name: Option<&str>,
916        image_planes: impl AsRef<str>,
917        out_image: impl AsRef<Path>,
918    ) -> Result<String> {
919        let cop_node = cop_node.into();
920        let out_image = out_image.as_ref();
921        debug!("Start rendering COP to image file {}", out_image.display());
922        debug_assert!(cop_node.is_valid(self)?);
923        if let Some(output_name) = output_name {
924            let output_name = CString::new(output_name)?;
925            crate::ffi::render_cop_output_to_image(self, cop_node, &output_name)?;
926        } else {
927            crate::ffi::render_cop_to_image(self, cop_node)?;
928        }
929        crate::material::extract_image_to_file(self, cop_node, image_planes, out_image)
930    }
931
932    /// Create a new input camera node with the given name/label.
933    pub fn create_input_camera_node(
934        &self,
935        name: &str,
936        label: &str,
937        parent_node: Option<NodeHandle>,
938    ) -> Result<NodeHandle> {
939        let name = CString::new(name)?;
940        let label = CString::new(label)?;
941        crate::ffi::create_input_camera_node(self, parent_node, &name, &label)
942    }
943
944    /// Set the camera parameters on an input camera node.
945    pub fn set_input_camera_info(&self, node: NodeHandle, info: &CameraInfo) -> Result<()> {
946        crate::ffi::set_input_camera_info(node, self, &info.0)
947    }
948
949    /// Set the transform on an input camera node.
950    pub fn set_input_camera_transform(
951        &self,
952        node: NodeHandle,
953        rst_order: RSTOrder,
954        rot_order: XYZOrder,
955        transform: &Transform,
956    ) -> Result<()> {
957        crate::ffi::set_input_camera_transform(node, self, rst_order, rot_order, &transform.0)
958    }
959
960    /// Loads some raw image data into a COP node, returning the handle of the created node.
961    pub fn create_cop_image(
962        &self,
963        description: CopImageDescription,
964        parent_node: Option<NodeHandle>,
965    ) -> Result<NodeHandle> {
966        crate::ffi::create_cop_image(
967            self,
968            parent_node,
969            description.width,
970            description.height,
971            description.packing,
972            description.flip_x,
973            description.flip_y,
974            description.image_data,
975        )
976    }
977
978    // TODO: consider removing this in favour of ['Material'] helper struct which has this API
979    pub fn render_texture_to_image(
980        &self,
981        node: impl Into<NodeHandle>,
982        parm_name: &str,
983    ) -> Result<()> {
984        debug_assert!(self.is_valid());
985        let name = CString::new(parm_name)?;
986        let node = node.into();
987        let id = crate::ffi::get_parm_id_from_name(&name, node, self)?;
988        crate::ffi::render_texture_to_image(self, node, crate::parameter::ParmHandle(id))
989    }
990
991    // TODO: consider removing this in favour of ['Material'] helper struct which has this API
992    pub fn extract_image_to_file(
993        &self,
994        node: impl Into<NodeHandle>,
995        image_planes: &str,
996        path: impl AsRef<Path>,
997    ) -> Result<String> {
998        crate::material::extract_image_to_file(self, node.into(), image_planes, path)
999    }
1000
1001    // TODO: consider removing this in favour of ['Material'] helper struct which has this API
1002    pub fn extract_image_to_memory(
1003        &self,
1004        node: impl Into<NodeHandle>,
1005        buffer: &mut Vec<u8>,
1006        image_planes: impl AsRef<str>,
1007        format: impl AsRef<str>,
1008    ) -> Result<()> {
1009        debug_assert!(self.is_valid());
1010        crate::material::extract_image_to_memory(self, node.into(), buffer, image_planes, format)
1011    }
1012
1013    // TODO: consider removing this in favour of ['Material'] helper struct which has this API
1014    pub fn get_image_info(&self, node: impl Into<NodeHandle>) -> Result<ImageInfo> {
1015        debug_assert!(self.is_valid());
1016        crate::ffi::get_image_info(self, node.into()).map(ImageInfo)
1017    }
1018
1019    /// Render a COP node to a memory buffer
1020    // TODO: consider removing this in favour of ['Material'] helper struct which has this API
1021    pub fn render_cop_to_memory(
1022        &self,
1023        cop_node: impl Into<NodeHandle>,
1024        buffer: &mut Vec<u8>,
1025        image_planes: impl AsRef<str>,
1026        format: impl AsRef<str>,
1027    ) -> Result<()> {
1028        debug!("Start rendering COP to memory.");
1029        let cop_node = cop_node.into();
1030        debug_assert!(cop_node.is_valid(self)?);
1031        crate::ffi::render_cop_to_image(self, cop_node)?;
1032        crate::material::extract_image_to_memory(self, cop_node, buffer, image_planes, format)
1033    }
1034
1035    pub fn get_supported_image_formats(&self) -> Result<Vec<ImageFileFormat<'_>>> {
1036        debug_assert!(self.is_valid());
1037        crate::ffi::get_supported_image_file_formats(self).map(|v| {
1038            v.into_iter()
1039                .map(|inner| ImageFileFormat(inner, self.into()))
1040                .collect()
1041        })
1042    }
1043
1044    pub fn get_active_cache_names(&self) -> Result<StringArray> {
1045        debug_assert!(self.is_valid());
1046        crate::ffi::get_active_cache_names(self)
1047    }
1048
1049    pub fn get_cache_property_value(
1050        &self,
1051        cache_name: &str,
1052        property: CacheProperty,
1053    ) -> Result<i32> {
1054        let cache_name = CString::new(cache_name)?;
1055        crate::ffi::get_cache_property(self, &cache_name, property)
1056    }
1057
1058    pub fn set_cache_property_value(
1059        &self,
1060        cache_name: &str,
1061        property: CacheProperty,
1062        value: i32,
1063    ) -> Result<()> {
1064        let cache_name = CString::new(cache_name)?;
1065        crate::ffi::set_cache_property(self, &cache_name, property, value)
1066    }
1067
1068    pub fn python_thread_interpreter_lock(&self, lock: bool) -> Result<()> {
1069        debug_assert!(self.is_valid());
1070        crate::ffi::python_thread_interpreter_lock(self, lock)
1071    }
1072    pub fn get_compositor_options(&self) -> Result<CompositorOptions> {
1073        crate::ffi::get_compositor_options(self).map(CompositorOptions)
1074    }
1075
1076    pub fn set_compositor_options(&self, options: &CompositorOptions) -> Result<()> {
1077        crate::ffi::set_compositor_options(self, &options.0)
1078    }
1079
1080    pub fn get_preset_names(&self, bytes: &[u8]) -> Result<Vec<String>> {
1081        debug_assert!(self.is_valid());
1082        let mut handles = vec![];
1083        for handle in crate::ffi::get_preset_names(self, bytes)? {
1084            let v = crate::stringhandle::get_string(handle, self)?;
1085            handles.push(v);
1086        }
1087        Ok(handles)
1088    }
1089
1090    pub fn start_performance_monitor_profile(&self, title: &str) -> Result<i32> {
1091        let title = CString::new(title)?;
1092        crate::ffi::start_performance_monitor_profile(self, &title)
1093    }
1094
1095    pub fn stop_performance_monitor_profile(
1096        &self,
1097        profile_id: i32,
1098        output_file: &str,
1099    ) -> Result<()> {
1100        let output_file = CString::new(output_file)?;
1101        crate::ffi::stop_performance_monitor_profile(self, profile_id, &output_file)
1102    }
1103
1104    #[cfg(feature = "async-cooking")]
1105    pub fn get_job_status(&self, job_id: i32) -> Result<JobStatus> {
1106        crate::ffi::get_job_status(self, job_id)
1107    }
1108}
1109
1110impl SessionInner {
1111    fn finalize(&self) -> Result<()> {
1112        let mut lifecycle = self.lifecycle.lock();
1113        Self::finalize_locked_with(
1114            &self.handle,
1115            &self.options,
1116            &mut lifecycle,
1117            &mut HapiLifecycleBackend,
1118        )
1119    }
1120
1121    fn finalize_locked_with<B: LifecycleBackend>(
1122        handle: &raw::HAPI_Session,
1123        options: &SessionOptions,
1124        lifecycle: &mut LifecycleState,
1125        backend: &mut B,
1126    ) -> Result<()> {
1127        if lifecycle.closed {
1128            return Ok(());
1129        }
1130        // Mark closed before entering HAPI so recursive error handling cannot start teardown again.
1131        lifecycle.closed = true;
1132        debug!("Closing session pid: {:?}", lifecycle.server.pid());
1133
1134        let mut errors = Vec::new();
1135        if backend.is_valid(handle) {
1136            if options.cleanup
1137                && backend.is_initialized(handle)
1138                && let Err(error) = backend.cleanup(handle)
1139            {
1140                errors.push(error.to_string());
1141            }
1142            if matches!(lifecycle.server, ServerConnection::InProcess)
1143                && let Err(error) = backend.shutdown(handle)
1144            {
1145                errors.push(error.to_string());
1146            }
1147            if let Err(error) = backend.close(handle) {
1148                errors.push(error.to_string());
1149            }
1150        }
1151        if matches!(lifecycle.server, ServerConnection::InProcess) {
1152            backend.mark_in_process_shutdown();
1153        }
1154        if let Err(error) = backend.finish_server(&lifecycle.server, false) {
1155            errors.push(error.to_string());
1156        }
1157        lifecycle_errors(errors, "Session close")
1158    }
1159}
1160
1161impl Drop for SessionInner {
1162    fn drop(&mut self) {
1163        let lifecycle = self.lifecycle.get_mut();
1164        if let Err(error) = Self::finalize_locked_with(
1165            &self.handle,
1166            &self.options,
1167            lifecycle,
1168            &mut HapiLifecycleBackend,
1169        ) {
1170            error!("Session close failed in Drop: {error}");
1171        }
1172    }
1173}
1174
1175/// Options passed to `HAPI_Initialize` when creating an initialized [`Session`].
1176///
1177/// These settings configure the Houdini runtime after a transport connection
1178/// exists. Server process and transport settings belong in
1179/// [`crate::server::ServerOptions`].
1180#[derive(Default, Clone, Debug)]
1181pub struct SessionOptions {
1182    /// Default cook options used by the session.
1183    pub cook_opt: CookOptions,
1184    /// Whether Houdini cooks on a separate cooking thread.
1185    pub threaded: bool,
1186    /// Run `HAPI_Cleanup` before closing the session.
1187    ///
1188    /// This is disabled by default because cleanup can be expensive and normal
1189    /// server termination releases its Houdini-side state. Enable it only when
1190    /// that state requires an orderly teardown before the connection closes.
1191    pub cleanup: bool,
1192    /// Platform-separated list of Houdini environment files loaded at initialization.
1193    pub env_files: Option<CString>,
1194    /// Platform-separated HDA/OTL search paths.
1195    pub otl_path: Option<CString>,
1196    /// Platform-separated generic DSO plugin search paths.
1197    pub dso_path: Option<CString>,
1198    /// Platform-separated image DSO plugin search paths.
1199    pub img_dso_path: Option<CString>,
1200    /// Platform-separated audio DSO plugin search paths.
1201    pub aud_dso_path: Option<CString>,
1202}
1203
1204impl SessionOptions {
1205    /// A list of Houdini environment files the Engine will load from.
1206    ///
1207    /// # Panics
1208    /// Panics if the joined path list contains an interior null byte.
1209    #[must_use]
1210    pub fn houdini_env_files<I>(mut self, files: I) -> Self
1211    where
1212        I: IntoIterator,
1213        I::Item: AsRef<str>,
1214    {
1215        let paths = utils::join_paths(files);
1216        self.env_files
1217            .replace(CString::new(paths).expect("Zero byte"));
1218        self
1219    }
1220
1221    /// Add search paths for the Engine to find HDAs.
1222    ///
1223    /// # Panics
1224    /// Panics if the joined path list contains an interior null byte.
1225    #[must_use]
1226    pub fn otl_search_paths<I>(mut self, paths: I) -> Self
1227    where
1228        I: IntoIterator,
1229        I::Item: AsRef<str>,
1230    {
1231        let paths = utils::join_paths(paths);
1232        self.otl_path
1233            .replace(CString::new(paths).expect("Zero byte"));
1234        self
1235    }
1236
1237    /// Add search paths for the Engine to find DSO plugins.
1238    ///
1239    /// # Panics
1240    /// Panics if the joined path list contains an interior null byte.
1241    #[must_use]
1242    pub fn dso_search_paths<P>(mut self, paths: P) -> Self
1243    where
1244        P: IntoIterator,
1245        P::Item: AsRef<str>,
1246    {
1247        let paths = utils::join_paths(paths);
1248        self.dso_path
1249            .replace(CString::new(paths).expect("Zero byte"));
1250        self
1251    }
1252
1253    /// Add search paths for the Engine to find image plugins.
1254    ///
1255    /// # Panics
1256    /// Panics if the joined path list contains an interior null byte.
1257    #[must_use]
1258    pub fn image_search_paths<P>(mut self, paths: P) -> Self
1259    where
1260        P: IntoIterator,
1261        P::Item: AsRef<str>,
1262    {
1263        let paths = utils::join_paths(paths);
1264        self.img_dso_path
1265            .replace(CString::new(paths).expect("Zero byte"));
1266        self
1267    }
1268
1269    /// Add search paths for the Engine to find audio files.
1270    ///
1271    /// # Panics
1272    /// Panics if the joined path list contains an interior null byte.
1273    #[must_use]
1274    pub fn audio_search_paths<P>(mut self, paths: P) -> Self
1275    where
1276        P: IntoIterator,
1277        P::Item: AsRef<str>,
1278    {
1279        let paths = utils::join_paths(paths);
1280        self.aud_dso_path
1281            .replace(CString::new(paths).expect("Zero byte"));
1282        self
1283    }
1284
1285    /// Pass session [`CookOptions`]
1286    #[must_use]
1287    pub fn cook_options(mut self, options: CookOptions) -> Self {
1288        self.cook_opt = options;
1289        self
1290    }
1291
1292    /// Makes the server operate in threaded mode. See the official docs for more info.
1293    #[must_use]
1294    pub fn threaded(mut self, threaded: bool) -> Self {
1295        self.threaded = threaded;
1296        self
1297    }
1298
1299    /// Set whether to run the potentially expensive `HAPI_Cleanup` before close.
1300    #[must_use]
1301    pub fn cleanup(mut self, cleanup: bool) -> Self {
1302        self.cleanup = cleanup;
1303        self
1304    }
1305}
1306
1307/// Create an in-process session.
1308/// Usefull for quick testing and debugging. Session crash will crash the main process.
1309/// For production use, use [`new_thrift_session`] instead.
1310pub fn new_in_process_session(options: Option<SessionOptions>) -> Result<Session> {
1311    debug!("Creating new in-process session");
1312    if IN_PROCESS_RUNTIME_SHUT_DOWN.load(Ordering::Acquire) {
1313        return Err(HapiError::Internal(
1314            "The in-process HAPI runtime has already been shut down and cannot be restarted"
1315                .to_owned(),
1316        ));
1317    }
1318    let session_options = options.unwrap_or_default();
1319    let session_info = SessionInfo::default();
1320    let handle = crate::ffi::create_inprocess_session(&session_info.0)?;
1321    let session = UninitializedSession {
1322        session_handle: Some(handle),
1323        server_options: None,
1324        server: ServerConnection::InProcess,
1325    }
1326    .initialize(session_options)?;
1327    Ok(session)
1328}
1329
1330/// Start a Thrift server and initialize a session with it.
1331pub fn new_thrift_session(
1332    session_options: SessionOptions,
1333    server_options: ServerOptions,
1334) -> Result<Session> {
1335    let uninitialized = match &server_options.thrift_transport {
1336        crate::server::ThriftTransport::SharedMemory(_) => {
1337            let pid = crate::server::start_engine_server(&server_options)?;
1338            let connection = crate::server::connect_to_memory_server(server_options, Some(pid))
1339                .context("Could not connect to shared memory server");
1340            match connection {
1341                Ok(mut session) => {
1342                    session.mark_owned_server(pid);
1343                    session
1344                }
1345                Err(error) => {
1346                    let pipe_path = None;
1347                    if let Err(cleanup_error) =
1348                        crate::server::finish_owned_server(pid, true, true, pipe_path)
1349                    {
1350                        error!("Could not roll back HARS after connect failure: {cleanup_error}");
1351                    }
1352                    return Err(error);
1353                }
1354            }
1355        }
1356        crate::server::ThriftTransport::Pipe(_) => {
1357            let pid = crate::server::start_engine_server(&server_options)?;
1358            let pipe_path = match &server_options.thrift_transport {
1359                crate::server::ThriftTransport::Pipe(transport) => {
1360                    Some(transport.pipe_path.clone())
1361                }
1362                _ => unreachable!(),
1363            };
1364            let connection = crate::server::connect_to_pipe_server(server_options, Some(pid))
1365                .context("Could not connect to pipe server");
1366            match connection {
1367                Ok(mut session) => {
1368                    session.mark_owned_server(pid);
1369                    session
1370                }
1371                Err(error) => {
1372                    if let Err(cleanup_error) =
1373                        crate::server::finish_owned_server(pid, true, true, pipe_path.as_deref())
1374                    {
1375                        error!("Could not roll back HARS after connect failure: {cleanup_error}");
1376                    }
1377                    return Err(error);
1378                }
1379            }
1380        }
1381        crate::server::ThriftTransport::Socket(_) => {
1382            let pid = crate::server::start_engine_server(&server_options)?;
1383            let connection = crate::server::connect_to_socket_server(server_options, Some(pid))
1384                .context("Could not connect to socket server");
1385            match connection {
1386                Ok(mut session) => {
1387                    session.mark_owned_server(pid);
1388                    session
1389                }
1390                Err(error) => {
1391                    if let Err(cleanup_error) =
1392                        crate::server::finish_owned_server(pid, true, true, None)
1393                    {
1394                        error!("Could not roll back HARS after connect failure: {cleanup_error}");
1395                    }
1396                    return Err(error);
1397                }
1398            }
1399        }
1400    };
1401    uninitialized.initialize(session_options)
1402}
1403
1404/// Shortcut for creating a simple Thrift session with good defaults.
1405pub fn simple_session() -> Result<Session> {
1406    new_thrift_session(
1407        SessionOptions::default(),
1408        ServerOptions::shared_memory_with_defaults(),
1409    )
1410}
1411
1412#[cfg(test)]
1413mod lifecycle_tests {
1414    use super::*;
1415    use std::collections::HashSet;
1416
1417    struct FakeBackend {
1418        valid: bool,
1419        initialized: bool,
1420        failures: HashSet<&'static str>,
1421        events: Vec<&'static str>,
1422    }
1423
1424    impl FakeBackend {
1425        fn new(valid: bool, initialized: bool, failures: &[&'static str]) -> Self {
1426            Self {
1427                valid,
1428                initialized,
1429                failures: failures.iter().copied().collect(),
1430                events: Vec::new(),
1431            }
1432        }
1433
1434        fn record(&mut self, event: &'static str) -> Result<()> {
1435            self.events.push(event);
1436            if self.failures.contains(event) {
1437                Err(HapiError::Internal(format!("{event} failed")))
1438            } else {
1439                Ok(())
1440            }
1441        }
1442    }
1443
1444    impl LifecycleBackend for FakeBackend {
1445        fn is_valid(&mut self, _handle: &raw::HAPI_Session) -> bool {
1446            self.events.push("valid");
1447            self.valid
1448        }
1449
1450        fn is_initialized(&mut self, _handle: &raw::HAPI_Session) -> bool {
1451            self.events.push("initialized");
1452            self.initialized
1453        }
1454
1455        fn cleanup(&mut self, _handle: &raw::HAPI_Session) -> Result<()> {
1456            self.record("cleanup")
1457        }
1458
1459        fn shutdown(&mut self, _handle: &raw::HAPI_Session) -> Result<()> {
1460            self.record("shutdown")
1461        }
1462
1463        fn close(&mut self, _handle: &raw::HAPI_Session) -> Result<()> {
1464            self.record("close")
1465        }
1466
1467        fn finish_server(
1468            &mut self,
1469            _server: &ServerConnection,
1470            construction_failed: bool,
1471        ) -> Result<()> {
1472            self.record(if construction_failed {
1473                "finish_rollback"
1474            } else {
1475                "finish"
1476            })
1477        }
1478
1479        fn mark_in_process_shutdown(&mut self) {
1480            self.events.push("mark_shutdown");
1481        }
1482    }
1483
1484    fn handle() -> raw::HAPI_Session {
1485        raw::HAPI_Session {
1486            type_: SessionType::Thrift,
1487            id: 7,
1488        }
1489    }
1490
1491    fn borrowed_state() -> LifecycleState {
1492        LifecycleState {
1493            closed: false,
1494            server: ServerConnection::Borrowed { reported_pid: None },
1495        }
1496    }
1497
1498    #[test]
1499    fn normal_close_skips_opt_in_cleanup_and_is_idempotent() {
1500        let mut backend = FakeBackend::new(true, true, &[]);
1501        let mut state = borrowed_state();
1502
1503        SessionInner::finalize_locked_with(
1504            &handle(),
1505            &SessionOptions::default(),
1506            &mut state,
1507            &mut backend,
1508        )
1509        .unwrap();
1510        assert!(state.closed);
1511        assert_eq!(backend.events, ["valid", "close", "finish"]);
1512
1513        SessionInner::finalize_locked_with(
1514            &handle(),
1515            &SessionOptions::default(),
1516            &mut state,
1517            &mut backend,
1518        )
1519        .unwrap();
1520        assert_eq!(backend.events, ["valid", "close", "finish"]);
1521    }
1522
1523    #[test]
1524    fn cleanup_close_and_process_errors_are_aggregated_without_short_circuiting() {
1525        let mut backend = FakeBackend::new(true, true, &["cleanup", "close", "finish"]);
1526        let mut state = borrowed_state();
1527        let options = SessionOptions::default().cleanup(true);
1528
1529        let error =
1530            SessionInner::finalize_locked_with(&handle(), &options, &mut state, &mut backend)
1531                .unwrap_err()
1532                .to_string();
1533
1534        assert_eq!(
1535            backend.events,
1536            ["valid", "initialized", "cleanup", "close", "finish"]
1537        );
1538        assert!(error.contains("cleanup failed"));
1539        assert!(error.contains("close failed"));
1540        assert!(error.contains("finish failed"));
1541        assert!(state.closed);
1542    }
1543
1544    #[test]
1545    fn invalid_session_skips_hapi_teardown_but_still_finishes_owned_server() {
1546        let mut backend = FakeBackend::new(false, false, &[]);
1547        let mut state = borrowed_state();
1548
1549        SessionInner::finalize_locked_with(
1550            &handle(),
1551            &SessionOptions::default().cleanup(true),
1552            &mut state,
1553            &mut backend,
1554        )
1555        .unwrap();
1556
1557        assert_eq!(backend.events, ["valid", "finish"]);
1558    }
1559
1560    #[test]
1561    fn in_process_close_shuts_down_and_marks_global_runtime() {
1562        let mut backend = FakeBackend::new(true, true, &[]);
1563        let mut state = LifecycleState {
1564            closed: false,
1565            server: ServerConnection::InProcess,
1566        };
1567
1568        SessionInner::finalize_locked_with(
1569            &handle(),
1570            &SessionOptions::default(),
1571            &mut state,
1572            &mut backend,
1573        )
1574        .unwrap();
1575
1576        assert_eq!(
1577            backend.events,
1578            ["valid", "shutdown", "close", "mark_shutdown", "finish"]
1579        );
1580    }
1581
1582    #[test]
1583    fn in_process_shutdown_failure_does_not_skip_close_or_runtime_reset() {
1584        let mut backend = FakeBackend::new(true, true, &["shutdown"]);
1585        let mut state = LifecycleState {
1586            closed: false,
1587            server: ServerConnection::InProcess,
1588        };
1589
1590        let error = SessionInner::finalize_locked_with(
1591            &handle(),
1592            &SessionOptions::default(),
1593            &mut state,
1594            &mut backend,
1595        )
1596        .unwrap_err()
1597        .to_string();
1598
1599        assert_eq!(
1600            backend.events,
1601            ["valid", "shutdown", "close", "mark_shutdown", "finish"]
1602        );
1603        assert!(error.contains("shutdown failed"));
1604        assert!(state.closed);
1605    }
1606
1607    #[test]
1608    fn initialized_connection_rollback_cleans_closes_and_finishes_server() {
1609        let mut backend = FakeBackend::new(true, true, &[]);
1610
1611        rollback_uninitialized_with(
1612            Some(&handle()),
1613            &ServerConnection::Borrowed { reported_pid: None },
1614            &mut backend,
1615        )
1616        .unwrap();
1617
1618        assert_eq!(
1619            backend.events,
1620            [
1621                "valid",
1622                "initialized",
1623                "cleanup",
1624                "close",
1625                "finish_rollback"
1626            ]
1627        );
1628    }
1629
1630    #[test]
1631    fn rollback_without_a_handle_only_finishes_the_server() {
1632        let mut backend = FakeBackend::new(true, true, &[]);
1633
1634        rollback_uninitialized_with(
1635            None,
1636            &ServerConnection::Borrowed { reported_pid: None },
1637            &mut backend,
1638        )
1639        .unwrap();
1640
1641        assert_eq!(backend.events, ["finish_rollback"]);
1642    }
1643
1644    #[test]
1645    fn valid_but_uninitialized_rollback_skips_cleanup() {
1646        let mut backend = FakeBackend::new(true, false, &[]);
1647
1648        rollback_uninitialized_with(
1649            Some(&handle()),
1650            &ServerConnection::Borrowed { reported_pid: None },
1651            &mut backend,
1652        )
1653        .unwrap();
1654
1655        assert_eq!(
1656            backend.events,
1657            ["valid", "initialized", "close", "finish_rollback"]
1658        );
1659    }
1660
1661    #[test]
1662    fn invalid_in_process_rollback_still_resets_global_runtime() {
1663        let mut backend = FakeBackend::new(false, false, &[]);
1664
1665        rollback_uninitialized_with(Some(&handle()), &ServerConnection::InProcess, &mut backend)
1666            .unwrap();
1667
1668        assert_eq!(
1669            backend.events,
1670            ["valid", "mark_shutdown", "finish_rollback"]
1671        );
1672    }
1673
1674    #[test]
1675    fn cleanup_is_skipped_when_session_was_not_initialized() {
1676        let mut backend = FakeBackend::new(true, false, &[]);
1677        let mut state = borrowed_state();
1678
1679        SessionInner::finalize_locked_with(
1680            &handle(),
1681            &SessionOptions::default().cleanup(true),
1682            &mut state,
1683            &mut backend,
1684        )
1685        .unwrap();
1686
1687        assert_eq!(backend.events, ["valid", "initialized", "close", "finish"]);
1688    }
1689
1690    #[test]
1691    fn rollback_attempts_every_stage_and_aggregates_failures() {
1692        let mut backend = FakeBackend::new(
1693            true,
1694            true,
1695            &["cleanup", "shutdown", "close", "finish_rollback"],
1696        );
1697
1698        let error = rollback_uninitialized_with(
1699            Some(&handle()),
1700            &ServerConnection::InProcess,
1701            &mut backend,
1702        )
1703        .unwrap_err()
1704        .to_string();
1705
1706        assert_eq!(
1707            backend.events,
1708            [
1709                "valid",
1710                "initialized",
1711                "cleanup",
1712                "shutdown",
1713                "close",
1714                "mark_shutdown",
1715                "finish_rollback"
1716            ]
1717        );
1718        for failure in ["cleanup", "shutdown", "close", "finish_rollback"] {
1719            assert!(error.contains(&format!("{failure} failed")));
1720        }
1721    }
1722}