hapi-rs 21.0.2

Rust bindings to Houdini Engine API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use crate::session::Session;

pub use crate::ffi::raw::{HapiResult, StatusType, StatusVerbosity};
use thiserror::Error;

pub type Result<T> = std::result::Result<T, HapiError>;

/// Error type returned by all APIs
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum HapiError {
    /// HAPI function call failed
    Hapi {
        result_code: HapiResultCode,
        server_message: Option<String>,
        contexts: Vec<String>,
    },

    /// This is used by [`ErrorContext::context`] / [`ErrorContext::with_context`]
    Context {
        contexts: Vec<String>,
        #[source]
        source: Box<HapiError>,
    },

    /// `CString` conversion error - string contains null byte
    NullByte(#[from] std::ffi::NulError),

    /// UTF-8 conversion error
    Utf8(#[from] std::string::FromUtf8Error),

    /// IO error
    Io(#[from] std::io::Error),

    /// Internal library error
    Internal(String),
}

// Wrapper for HapiResult to provide Display for error messages
#[derive(Debug, Clone, Copy)]
pub struct HapiResultCode(pub HapiResult);

impl std::fmt::Display for HapiResultCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use HapiResult::{
            AlreadyInitialized, AssetDefAlreadyLoaded, AssetInvalid, CantGeneratePreset,
            CantLoadGeo, CantLoadPreset, CantLoadfile, DisallowedHengineindieW3partyPlugin,
            DisallowedLcAssetWithCLicense, DisallowedNcAssetWithCLicense,
            DisallowedNcAssetWithLcLicense, DisallowedNcLicenseFound, Failure, InvalidArgument,
            InvalidSession, InvalidSharedMemoryBuffer, NoLicenseFound, NodeInvalid, NotInitialized,
            ParmSetFailed, SharedMemoryBufferOverflow, Success, UserInterrupted,
        };
        let desc = match self.0 {
            Success => "SUCCESS",
            Failure => "FAILURE",
            AlreadyInitialized => "ALREADY_INITIALIZED",
            NotInitialized => "NOT_INITIALIZED",
            CantLoadfile => "CANT_LOADFILE",
            ParmSetFailed => "PARM_SET_FAILED",
            InvalidArgument => "INVALID_ARGUMENT",
            CantLoadGeo => "CANT_LOAD_GEO",
            CantGeneratePreset => "CANT_GENERATE_PRESET",
            CantLoadPreset => "CANT_LOAD_PRESET",
            AssetDefAlreadyLoaded => "ASSET_DEF_ALREADY_LOADED",
            NoLicenseFound => "NO_LICENSE_FOUND",
            DisallowedNcLicenseFound => "DISALLOWED_NC_LICENSE_FOUND",
            DisallowedNcAssetWithCLicense => "DISALLOWED_NC_ASSET_WITH_C_LICENSE",
            DisallowedNcAssetWithLcLicense => "DISALLOWED_NC_ASSET_WITH_LC_LICENSE",
            DisallowedLcAssetWithCLicense => "DISALLOWED_LC_ASSET_WITH_C_LICENSE",
            DisallowedHengineindieW3partyPlugin => "DISALLOWED_HENGINEINDIE_W_3PARTY_PLUGIN",
            AssetInvalid => "ASSET_INVALID",
            NodeInvalid => "NODE_INVALID",
            UserInterrupted => "USER_INTERRUPTED",
            InvalidSession => "INVALID_SESSION",
            SharedMemoryBufferOverflow => "SHARED_MEMORY_BUFFER_OVERFLOW",
            InvalidSharedMemoryBuffer => "INVALID_SHARED_MEMORY_BUFFER",
        };
        write!(f, "{desc}")
    }
}

// This special case for TryFrom<T, Error = HapiError> where conversion can't fail.
// for example when "impl TryInto<AttributeName>" receives AttributeName.
impl From<std::convert::Infallible> for HapiError {
    fn from(_: std::convert::Infallible) -> Self {
        unreachable!()
    }
}

impl From<HapiResult> for HapiError {
    fn from(r: HapiResult) -> Self {
        HapiError::Hapi {
            result_code: HapiResultCode(r),
            server_message: None,
            contexts: Vec::new(),
        }
    }
}

impl From<&str> for HapiError {
    fn from(value: &str) -> Self {
        HapiError::Internal(value.to_string())
    }
}

pub(crate) trait ErrorContext<T> {
    fn context<C>(self, context: C) -> Result<T>
    where
        C: Into<String>;

    #[allow(unused)]
    fn with_context<C, F>(self, func: F) -> Result<T>
    where
        C: Into<String>,
        F: FnOnce() -> C;
}

impl<T> ErrorContext<T> for Result<T> {
    fn context<C>(self, context: C) -> Result<T>
    where
        C: Into<String>,
    {
        match self {
            Ok(ok) => Ok(ok),
            Err(mut error) => {
                let context = context.into();
                match &mut error {
                    HapiError::Hapi { contexts, .. } | HapiError::Context { contexts, .. } => {
                        contexts.push(context);
                        Err(error)
                    }
                    _ => Err(HapiError::Context {
                        contexts: vec![context],
                        source: Box::new(error),
                    }),
                }
            }
        }
    }

    fn with_context<C, F>(self, func: F) -> Result<T>
    where
        C: Into<String>,
        F: FnOnce() -> C,
    {
        match self {
            Ok(ok) => Ok(ok),
            Err(mut error) => {
                let context = func().into();
                match &mut error {
                    HapiError::Hapi { contexts, .. } | HapiError::Context { contexts, .. } => {
                        contexts.push(context);
                        Err(error)
                    }
                    _ => Err(HapiError::Context {
                        contexts: vec![context],
                        source: Box::new(error),
                    }),
                }
            }
        }
    }
}

// Custom Display to show contexts properly for HAPI errors
impl std::fmt::Display for HapiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fn fmt_base(err: &HapiError, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match err {
                HapiError::Hapi {
                    result_code,
                    server_message,
                    ..
                } => {
                    write!(f, "[{result_code}]")?;
                    if let Some(msg) = server_message {
                        write!(f, ": [Engine Message]: {msg}")?;
                    }
                    Ok(())
                }
                HapiError::Context { source, .. } => fmt_base(source, f),
                HapiError::NullByte(e) => {
                    let vec = e.clone().into_vec();
                    let text = String::from_utf8_lossy(&vec);
                    write!(f, "String contains null byte in \"{text}\"")
                }
                HapiError::Utf8(e) => {
                    let text = String::from_utf8_lossy(e.as_bytes());
                    write!(f, "Invalid UTF-8 in string \"{text}\"")
                }
                HapiError::Io(e) => write!(f, "IO error: {e}"),
                HapiError::Internal(e) => write!(f, "Internal error: {e}"),
            }
        }

        fn collect_contexts<'a>(err: &'a HapiError, out: &mut Vec<&'a str>) {
            match err {
                HapiError::Hapi { contexts, .. } => {
                    out.extend(contexts.iter().map(std::string::String::as_str));
                }
                HapiError::Context { contexts, source } => {
                    collect_contexts(source, out);
                    out.extend(contexts.iter().map(std::string::String::as_str));
                }
                _ => {}
            }
        }

        fmt_base(self, f)?;

        let mut contexts = Vec::new();
        collect_contexts(self, &mut contexts);
        if !contexts.is_empty() {
            writeln!(f)?;
            for (n, msg) in contexts.iter().enumerate() {
                writeln!(f, "\t{n}. {msg}")?;
            }
        }
        Ok(())
    }
}

impl HapiResult {
    /// Check `HAPI_Result` status and convert to `HapiError` if the status is not success.
    pub(crate) fn check_err<F, M>(self, session: &Session, context: F) -> Result<()>
    where
        M: Into<String>,
        F: FnOnce() -> M,
    {
        match self {
            HapiResult::Success => Ok(()),
            _err => {
                let server_message = if session.is_valid() {
                    session
                        .get_status_string(StatusType::CallResult, StatusVerbosity::All)
                        .ok()
                } else {
                    Some("Session is corrupted: error message not available".to_string())
                };

                Err(HapiError::Hapi {
                    result_code: HapiResultCode(self),
                    server_message: server_message
                        .or_else(|| Some("Could not retrieve error message".to_string())),
                    contexts: vec![context().into()],
                })
            }
        }
    }

    /// Convert `HAPI_Result` to `HapiError` if the status is not success and add a message to the error.
    pub(crate) fn add_context<I: Into<String>>(self, message: I) -> Result<()> {
        match self {
            HapiResult::Success => Ok(()),
            _err => Err(HapiError::Hapi {
                result_code: HapiResultCode(self),
                server_message: None,
                contexts: vec![message.into()],
            }),
        }
    }

    pub(crate) fn with_context<F, M>(self, func: F) -> Result<()>
    where
        F: FnOnce() -> M,
        M: Into<String>,
    {
        self.add_context(func())
    }

    pub(crate) fn with_server_message<F, M>(self, func: F) -> Result<()>
    where
        F: FnOnce() -> M,
        M: Into<String>,
    {
        match self {
            HapiResult::Success => Ok(()),
            _err => Err(HapiError::Hapi {
                result_code: HapiResultCode(self),
                server_message: Some(func().into()),
                contexts: vec![],
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::error::Error as _;

    #[test]
    fn context_chain_is_rendered_for_internal_errors() {
        let err = (Err::<(), HapiError>(HapiError::Internal("root".to_string())))
            .context("first context")
            .context("second context")
            .unwrap_err();

        let s = err.to_string();
        assert!(s.starts_with("Internal error: root"));
        assert!(s.contains("\n\t0. first context\n\t1. second context\n"));

        // Verify the source chain is preserved via #[source]
        let source = err.source().expect("source");
        assert_eq!(source.to_string(), "Internal error: root");
    }

    #[test]
    fn hapi_errors_server_message_and_contexts() {
        let err = (Err::<(), HapiError>(HapiError::Hapi {
            result_code: HapiResultCode(HapiResult::Failure),
            server_message: Some("could not cook".to_string()),
            contexts: vec!["low-level".to_string()],
        }))
        .context("high-level")
        .unwrap_err();

        let s = err.to_string();
        assert_eq!(
            s,
            "[FAILURE]: [Engine Message]: could not cook\n\t0. low-level\n\t1. high-level\n"
        );
    }

    #[test]
    fn context_added_outside_hapi_error_is_rendered_after_inner_contexts() {
        // Create a HAPI error with one context, then add an outer wrapper context.
        let base = HapiError::Hapi {
            result_code: HapiResultCode(HapiResult::InvalidArgument),
            server_message: None,
            contexts: vec!["inner".to_string()],
        };
        let wrapped = (Err::<(), HapiError>(base)).context("outer").unwrap_err();

        let s = wrapped.to_string();
        // Base header comes from the underlying Hapi error
        assert!(s.starts_with("[INVALID_ARGUMENT]"));
        // Context order: inner first, then outer
        assert!(s.contains("\n\t0. inner\n\t1. outer\n"));
    }

    #[test]
    fn result_with_context_adds_context_on_error() {
        let err = Err::<(), HapiError>(HapiError::Internal("root".to_string()))
            .with_context(|| "deferred context")
            .unwrap_err();

        assert_eq!(
            err.to_string(),
            "Internal error: root\n\t0. deferred context\n"
        );
        assert_eq!(
            err.source().expect("source").to_string(),
            "Internal error: root"
        );
    }

    #[test]
    fn hapi_result_add_context_returns_hapi_error_on_failure() {
        let err = HapiResult::InvalidArgument
            .add_context("invalid parm")
            .unwrap_err();

        match err {
            HapiError::Hapi {
                result_code,
                server_message,
                contexts,
            } => {
                assert_eq!(result_code.to_string(), "INVALID_ARGUMENT");
                assert_eq!(server_message, None);
                assert_eq!(contexts, vec!["invalid parm"]);
            }
            other => panic!("expected Hapi error, got {other:?}"),
        }
    }

    #[test]
    fn hapi_result_with_context_returns_hapi_error_on_failure() {
        let err = HapiResult::Failure
            .with_context(|| "deferred hapi context")
            .unwrap_err();

        assert_eq!(err.to_string(), "[FAILURE]\n\t0. deferred hapi context\n");
    }

    #[test]
    fn hapi_result_with_server_message_returns_hapi_error_on_failure() {
        let err = HapiResult::CantLoadfile
            .with_server_message(|| "could not load asset")
            .unwrap_err();

        match err {
            HapiError::Hapi {
                result_code,
                server_message,
                contexts,
            } => {
                assert_eq!(result_code.to_string(), "CANT_LOADFILE");
                assert_eq!(server_message, Some("could not load asset".to_string()));
                assert!(contexts.is_empty());
            }
            other => panic!("expected Hapi error, got {other:?}"),
        }
    }

    #[test]
    fn null_byte_errors_are_rendered() {
        let err = std::ffi::CString::new(b"ab\0cd".to_vec()).unwrap_err();
        let err = HapiError::from(err);

        assert_eq!(err.to_string(), "String contains null byte in \"ab\0cd\"");
    }

    #[test]
    fn utf8_errors_are_rendered() {
        let err = String::from_utf8(vec![b'a', 0xff, b'b']).unwrap_err();
        let err = HapiError::from(err);

        assert_eq!(err.to_string(), "Invalid UTF-8 in string \"a\u{FFFD}b\"");
    }

    #[test]
    fn io_errors_are_rendered() {
        let err = HapiError::from(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "missing file",
        ));

        assert_eq!(err.to_string(), "IO error: missing file");
    }

    #[test]
    fn str_converts_to_internal_error() {
        let err = HapiError::from("bad state");

        assert_eq!(err.to_string(), "Internal error: bad state");
    }

    #[test]
    fn hapi_result_converts_to_hapi_error() {
        let err = HapiError::from(HapiResult::ParmSetFailed);

        match err {
            HapiError::Hapi {
                result_code,
                server_message,
                contexts,
            } => {
                assert_eq!(result_code.to_string(), "PARM_SET_FAILED");
                assert_eq!(server_message, None);
                assert!(contexts.is_empty());
            }
            other => panic!("expected Hapi error, got {other:?}"),
        }
    }
}