Skip to main content

grafton_ndi/error/
loading.rs

1//! Structured causes for native library selection failures.
2
3use thiserror::Error;
4
5use std::{
6    ffi::CStr,
7    fmt,
8    path::{Path, PathBuf},
9};
10
11/// Why an irreversible runtime or File selection cannot meet a request.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
13#[non_exhaustive]
14pub enum SelectionConflict {
15    /// The request names a different library from the one selected.
16    #[error("a different library is already selected")]
17    DifferentLibrary,
18    /// The selected runtime does not meet the requested SDK edition.
19    #[error("the selected runtime does not meet the requested SDK edition")]
20    EditionNotMet,
21    /// A library path cannot replace the implementation linked into the program.
22    #[error("a linked implementation cannot be replaced")]
23    LinkedImplementation,
24    /// Native loading re-entered selection on its own loading thread.
25    #[error("native loading re-entered selection")]
26    ReentrantSelection,
27    /// The selected runtime is Standard, but the File library needs Advanced.
28    #[error("the File library needs the Advanced SDK runtime")]
29    FileNeedsAdvancedRuntime,
30    /// The process's global symbol scope contains another NDI runtime.
31    ///
32    /// On dynamically loaded, non-Apple ELF targets, an explicit runtime path
33    /// must identify that same module. The File library also refuses a global
34    /// runtime other than the selected core. Both checks run before opening
35    /// the candidate. Select the runtime named in the diagnostic, or stop
36    /// linking or preloading the other runtime.
37    #[error("another NDI runtime is in the global symbol scope")]
38    ForeignRuntimeInScope,
39}
40
41/// Which native library a failed selection sought.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
43#[non_exhaustive]
44pub enum LibraryKind {
45    /// The NDI runtime.
46    #[error("NDI runtime")]
47    Runtime,
48    /// The separately loaded NDI File library.
49    #[error("NDI File library")]
50    File,
51}
52
53/// A selection conflict, with the library identities needed to act on it.
54///
55/// The payload is boxed so adding diagnostic context does not enlarge
56/// [`crate::Error`] on capture and send paths. Use the accessors for decisions
57/// and [`Display`](fmt::Display) for diagnostic text.
58#[derive(Debug, Clone, PartialEq, Eq, Hash)]
59pub struct SelectionFailure(Box<SelectionData>);
60
61#[derive(Debug, Clone, PartialEq, Eq, Hash)]
62enum SelectionData {
63    #[cfg_attr(ndi_link_static, allow(dead_code))]
64    DifferentLibrary {
65        library: LibraryKind,
66        selected: PathBuf,
67        requested: PathBuf,
68    },
69    EditionNotMet {
70        selected: Option<PathBuf>,
71        requested: Option<PathBuf>,
72    },
73    #[cfg_attr(not(any(ndi_link_static, test)), allow(dead_code))]
74    LinkedImplementation {
75        library: LibraryKind,
76        requested: PathBuf,
77    },
78    ReentrantSelection {
79        library: LibraryKind,
80    },
81    #[cfg_attr(any(not(feature = "file-io"), ndi_link_static), allow(dead_code))]
82    FileNeedsAdvancedRuntime {
83        selected: Option<PathBuf>,
84        requested: Option<PathBuf>,
85    },
86    #[cfg_attr(ndi_link_static, allow(dead_code))]
87    ForeignRuntimeInScope {
88        library: LibraryKind,
89        selected: Option<PathBuf>,
90        requested: Option<PathBuf>,
91        foreign_module: PathBuf,
92        candidate: PathBuf,
93        origin: LoadOrigin,
94    },
95}
96
97impl SelectionFailure {
98    /// The typed cause of this conflict.
99    pub fn kind(&self) -> SelectionConflict {
100        match &*self.0 {
101            SelectionData::DifferentLibrary { .. } => SelectionConflict::DifferentLibrary,
102            SelectionData::EditionNotMet { .. } => SelectionConflict::EditionNotMet,
103            SelectionData::LinkedImplementation { .. } => SelectionConflict::LinkedImplementation,
104            SelectionData::ReentrantSelection { .. } => SelectionConflict::ReentrantSelection,
105            SelectionData::FileNeedsAdvancedRuntime { .. } => {
106                SelectionConflict::FileNeedsAdvancedRuntime
107            }
108            SelectionData::ForeignRuntimeInScope { .. } => SelectionConflict::ForeignRuntimeInScope,
109        }
110    }
111
112    /// The native library the failed selection sought.
113    pub fn library(&self) -> LibraryKind {
114        match &*self.0 {
115            SelectionData::DifferentLibrary { library, .. }
116            | SelectionData::LinkedImplementation { library, .. }
117            | SelectionData::ReentrantSelection { library }
118            | SelectionData::ForeignRuntimeInScope { library, .. } => *library,
119            SelectionData::EditionNotMet { .. } => LibraryKind::Runtime,
120            SelectionData::FileNeedsAdvancedRuntime { .. } => LibraryKind::File,
121        }
122    }
123
124    /// The already selected library, when its path is known.
125    ///
126    /// For a File conflict caused by the selected core runtime, this is that
127    /// core runtime's path, rather than a File library not yet selected.
128    pub fn selected(&self) -> Option<&Path> {
129        match &*self.0 {
130            SelectionData::DifferentLibrary { selected, .. } => Some(selected),
131            SelectionData::EditionNotMet { selected, .. }
132            | SelectionData::FileNeedsAdvancedRuntime { selected, .. }
133            | SelectionData::ForeignRuntimeInScope { selected, .. } => selected.as_deref(),
134            SelectionData::LinkedImplementation { .. }
135            | SelectionData::ReentrantSelection { .. } => None,
136        }
137    }
138
139    /// The explicit library path that conflicted, when the caller supplied one.
140    pub fn requested(&self) -> Option<&Path> {
141        match &*self.0 {
142            SelectionData::DifferentLibrary { requested, .. }
143            | SelectionData::LinkedImplementation { requested, .. } => Some(requested),
144            SelectionData::FileNeedsAdvancedRuntime { requested, .. }
145            | SelectionData::ForeignRuntimeInScope { requested, .. }
146            | SelectionData::EditionNotMet { requested, .. } => requested.as_deref(),
147            SelectionData::ReentrantSelection { .. } => None,
148        }
149    }
150
151    /// The foreign runtime already in the process's global symbol scope.
152    pub fn foreign_module(&self) -> Option<&Path> {
153        match &*self.0 {
154            SelectionData::ForeignRuntimeInScope { foreign_module, .. } => Some(foreign_module),
155            _ => None,
156        }
157    }
158
159    #[cfg(any(not(ndi_link_static), test))]
160    pub(crate) fn different_library(
161        library: LibraryKind,
162        selected: &Path,
163        requested: &Path,
164    ) -> Self {
165        Self(Box::new(SelectionData::DifferentLibrary {
166            library,
167            selected: selected.into(),
168            requested: requested.into(),
169        }))
170    }
171
172    pub(crate) fn edition_not_met(selected: Option<&Path>, requested: Option<&Path>) -> Self {
173        Self(Box::new(SelectionData::EditionNotMet {
174            selected: selected.map(Path::to_owned),
175            requested: requested.map(Path::to_owned),
176        }))
177    }
178
179    #[cfg(any(ndi_link_static, test))]
180    pub(crate) fn linked(library: LibraryKind, requested: &Path) -> Self {
181        Self(Box::new(SelectionData::LinkedImplementation {
182            library,
183            requested: requested.into(),
184        }))
185    }
186
187    pub(crate) fn reentrant(library: LibraryKind) -> Self {
188        Self(Box::new(SelectionData::ReentrantSelection { library }))
189    }
190
191    #[cfg(all(feature = "file-io", any(not(ndi_link_static), test)))]
192    pub(crate) fn file_needs_advanced(selected: Option<&Path>, requested: Option<&Path>) -> Self {
193        Self(Box::new(SelectionData::FileNeedsAdvancedRuntime {
194            selected: selected.map(Path::to_owned),
195            requested: requested.map(Path::to_owned),
196        }))
197    }
198
199    #[cfg(any(not(ndi_link_static), test))]
200    pub(crate) fn foreign(
201        library: LibraryKind,
202        selected: Option<&Path>,
203        requested: Option<&Path>,
204        foreign_module: &Path,
205        candidate: &Path,
206        origin: LoadOrigin,
207    ) -> Self {
208        Self(Box::new(SelectionData::ForeignRuntimeInScope {
209            library,
210            selected: selected.map(Path::to_owned),
211            requested: requested.map(Path::to_owned),
212            foreign_module: foreign_module.into(),
213            candidate: candidate.into(),
214            origin,
215        }))
216    }
217}
218
219impl std::error::Error for SelectionFailure {}
220
221impl fmt::Display for SelectionFailure {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        write!(f, "{} selection: {}", self.library(), self.kind())?;
224        for (label, path) in [
225            ("selected", self.selected()),
226            ("requested", self.requested()),
227        ] {
228            if let Some(path) = path {
229                write!(f, ", {label} {}", path.display())?;
230            }
231        }
232        if let SelectionData::ForeignRuntimeInScope {
233            candidate,
234            origin,
235            foreign_module,
236            ..
237        } = &*self.0
238        {
239            write!(
240                f,
241                ", candidate {} ({origin}), foreign runtime {}. Select that runtime or stop linking or preloading it",
242                candidate.display(),
243                foreign_module.display(),
244            )?;
245        }
246        Ok(())
247    }
248}
249
250/// Why a native library location was considered.
251#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
252#[non_exhaustive]
253pub enum LoadOrigin {
254    /// An exact path the caller supplied.
255    Explicit,
256    /// Beside the selected NDI runtime.
257    Companion,
258    /// Beside the running executable.
259    Executable,
260    /// The directory supplied through `NDI_RUNTIME_DIR_V6`.
261    RuntimeDirectory,
262    /// An absolute `PATH` directory on Windows (or a refused relative entry).
263    PathDirectory,
264    /// An absolute `DYLD_LIBRARY_PATH` directory on Apple targets (or a refused relative entry).
265    DyldLibraryDirectory,
266    /// A refused relative or empty `DYLD_FALLBACK_LIBRARY_PATH` entry on Apple targets.
267    DyldFallbackLibraryDirectory,
268    /// Unix's native search, Apple `@rpath`, or Windows' System32-only search.
269    LoaderSearch,
270    /// The SDK archive linked into the program at build time.
271    LinkedArchive,
272}
273
274impl fmt::Display for LoadOrigin {
275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276        f.write_str(match self {
277            Self::Explicit => "explicit library path",
278            Self::Companion => "next to the NDI runtime",
279            Self::Executable => "next to the executable",
280            Self::RuntimeDirectory => "NDI_RUNTIME_DIR_V6",
281            Self::PathDirectory => "PATH",
282            Self::DyldLibraryDirectory => "DYLD_LIBRARY_PATH",
283            Self::DyldFallbackLibraryDirectory => "DYLD_FALLBACK_LIBRARY_PATH",
284            Self::LoaderSearch => "system library search",
285            Self::LinkedArchive => "linked SDK archive",
286        })
287    }
288}
289
290/// Why a runtime's version text could not be read.
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
292#[non_exhaustive]
293pub enum VersionTextDefect {
294    /// The runtime returned a null version pointer.
295    #[error("NDIlib_version returned no version text")]
296    Missing,
297    /// No terminator occurred within the SDK string bound.
298    #[error("its version text has no terminator within the 4 MiB one SDK string may take")]
299    Unterminated,
300    /// The bounded version text is not valid UTF-8.
301    #[error("its version text is not UTF-8 at byte {valid_up_to}")]
302    NotUtf8 {
303        /// The byte offset at which valid UTF-8 ends.
304        valid_up_to: usize,
305    },
306}
307
308/// Why a candidate could not provide a usable implementation.
309///
310/// This is a structured diagnostic, not a promise that the platform loader
311/// can distinguish an absent bare name from every other loading failure.
312#[derive(Debug, Clone, PartialEq, Eq, Hash, Error)]
313#[error("{}", LoadRefusalDiagnostic(self))]
314#[non_exhaustive]
315pub enum LoadRefusal {
316    /// No file exists at an exact directory candidate.
317    Absent,
318    /// The platform loader could not open a location; its diagnostic is retained.
319    PlatformLoader {
320        /// The operating system's diagnostic, including its cause chain.
321        detail: String,
322    },
323    /// A loaded module or resolved address could not be identified.
324    NotIdentifiable {
325        /// The platform's diagnostic.
326        detail: String,
327    },
328    /// The platform opened another file instead of the requested absolute path.
329    ResolvedToAnotherFile {
330        /// The path the loader actually opened.
331        resolved: PathBuf,
332    },
333    /// The identification anchor is absent: this file is not the requested library.
334    MissingAnchor {
335        /// The statically declared identification symbol's name.
336        symbol: &'static CStr,
337        /// The platform's symbol lookup diagnostic.
338        detail: String,
339    },
340    /// An identified library lacks an entry point required by the API.
341    MissingEntryPoint {
342        /// The statically declared native symbol's name.
343        symbol: &'static CStr,
344    },
345    /// A lookup found the entry point in a dependency instead of the selected module.
346    EntryPointOutsideModule {
347        /// The statically declared native symbol's name.
348        symbol: &'static CStr,
349        /// The selected module that did not define it.
350        module: PathBuf,
351    },
352    /// The library lacks the entry points identifying the requested Advanced edition.
353    EditionNotMet,
354    /// The runtime did not return bounded, valid UTF-8 version text.
355    UnreadableVersion(VersionTextDefect),
356    /// A loader search returned a module already loaded and refused earlier.
357    AlreadyRefused {
358        /// The file first associated with that module.
359        path: PathBuf,
360        /// Why this attempt could not use it.
361        refusal: Box<LoadRefusal>,
362    },
363    /// The File library has no complete family of entry points.
364    NoCompleteFileFamily {
365        /// The first missing, statically declared entry point in declaration order.
366        first_missing: &'static CStr,
367    },
368    /// The File library's imports bind to a runtime other than the selected one.
369    BoundToAnotherRuntime,
370    /// Another NDI runtime in the global symbol scope would capture this
371    /// candidate's native calls. The candidate was not opened.
372    ///
373    /// Applies to dynamically loaded, non-Apple ELF targets. Select the module
374    /// named here, or stop linking or preloading it. An explicit runtime path
375    /// instead reports [`SelectionConflict::ForeignRuntimeInScope`].
376    ForeignRuntimeInScope {
377        /// The module defining `NDIlib_version` in the global symbol scope.
378        module: PathBuf,
379    },
380    /// An `NDI_RUNTIME_DIR_V6`, `PATH`, `DYLD_LIBRARY_PATH` or
381    /// `DYLD_FALLBACK_LIBRARY_PATH` directory is relative or empty and was not
382    /// opened. [`LoadAttempt::origin`] identifies the environment variable.
383    RelativeSearchDirectory,
384}
385
386struct LoadRefusalDiagnostic<'a>(&'a LoadRefusal);
387
388impl fmt::Display for LoadRefusalDiagnostic<'_> {
389    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390        match self.0 {
391            LoadRefusal::Absent => f.write_str("not found"),
392            LoadRefusal::PlatformLoader { detail } | LoadRefusal::NotIdentifiable { detail } => f.write_str(detail),
393            LoadRefusal::UnreadableVersion(defect) => fmt::Display::fmt(defect, f),
394            LoadRefusal::ResolvedToAnotherFile { resolved } => write!(f, "the loader resolved it to {}", resolved.display()),
395            LoadRefusal::MissingAnchor { symbol, detail } => write!(f, "it does not export {}: {detail}", symbol.to_string_lossy()),
396            LoadRefusal::MissingEntryPoint { symbol } => write!(f, "it does not export the required entry point {}", symbol.to_string_lossy()),
397            LoadRefusal::EntryPointOutsideModule { symbol, module } => write!(f, "{} resolves outside {}", symbol.to_string_lossy(), module.display()),
398            LoadRefusal::EditionNotMet => f.write_str("it does not export the Advanced SDK entry points"),
399            LoadRefusal::AlreadyRefused { path, refusal } => write!(f,
400                "the platform loader returned {}, which is already loaded and was rejected ({refusal}); no other library of that name can be found by name in this process, so remove or fix that file or pass an explicit library path", path.display()),
401            LoadRefusal::NoCompleteFileFamily { first_missing } => write!(f, "it provides no family of NDI File entry points (it does not export {})", first_missing.to_string_lossy()),
402            LoadRefusal::BoundToAnotherRuntime => f.write_str("it is bound to an NDI runtime other than the selected one"),
403            LoadRefusal::ForeignRuntimeInScope { module } => write!(f,
404                "the process's global symbol scope already holds another NDI runtime ({}); select that runtime or stop linking or preloading it", module.display()),
405            LoadRefusal::RelativeSearchDirectory => f.write_str("the library search directory must be absolute and nonempty"),
406        }
407    }
408}
409
410/// One refused native library location, in the order it was tried.
411#[derive(Debug, Clone, PartialEq, Eq, Hash)]
412pub struct LoadAttempt {
413    location: PathBuf,
414    origin: LoadOrigin,
415    refusal: LoadRefusal,
416    loaded: bool,
417    resolved: Option<PathBuf>,
418}
419
420impl LoadAttempt {
421    pub(crate) fn new(
422        location: PathBuf,
423        origin: LoadOrigin,
424        refusal: LoadRefusal,
425        loaded: bool,
426        resolved: Option<PathBuf>,
427    ) -> Self {
428        Self {
429            location,
430            origin,
431            refusal,
432            loaded,
433            resolved,
434        }
435    }
436
437    /// The requested path or name; for a linked archive, its diagnostic label.
438    pub fn location(&self) -> &Path {
439        &self.location
440    }
441
442    /// Why this location was included in the search.
443    pub fn origin(&self) -> LoadOrigin {
444        self.origin
445    }
446
447    /// Why this location was refused.
448    pub fn refusal(&self) -> &LoadRefusal {
449        &self.refusal
450    }
451
452    /// Whether this attempt loaded native code before refusing it.
453    pub fn loaded(&self) -> bool {
454        self.loaded
455    }
456
457    /// The identified module path, when the platform could report it.
458    pub fn resolved_path(&self) -> Option<&Path> {
459        self.resolved.as_deref()
460    }
461}
462
463impl fmt::Display for LoadAttempt {
464    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465        if self.origin == LoadOrigin::LinkedArchive {
466            return write!(f, "{}: {}", self.location.display(), self.refusal);
467        }
468        write!(f, "{} ({})", self.location.display(), self.origin)?;
469        if self.origin == LoadOrigin::LoaderSearch
470            && !matches!(self.refusal, LoadRefusal::AlreadyRefused { .. })
471        {
472            if let Some(path) = &self.resolved {
473                write!(f, " resolved to {}", path.display())?;
474            }
475        }
476        write!(f, ": {}", self.refusal)
477    }
478}
479
480/// A failed search, with a typed cause for every attempted location.
481///
482/// The aggregate is boxed so enriching selection diagnostics does not enlarge
483/// [`crate::Error`] on capture and send paths. Match [`LoadRefusal`] rather
484/// than parsing the text produced by `Display`.
485#[derive(Debug, Clone, PartialEq, Eq, Hash, Error)]
486#[error("{0}")]
487pub struct LoadFailure(Box<FailureData>);
488
489#[derive(Debug, Clone, PartialEq, Eq, Hash)]
490struct FailureData {
491    library: LibraryKind,
492    description: Option<String>,
493    attempts: Vec<LoadAttempt>,
494}
495
496impl LoadFailure {
497    #[cfg(any(not(ndi_link_static), test))]
498    pub(crate) fn searched(
499        library: LibraryKind,
500        description: &str,
501        attempts: Vec<LoadAttempt>,
502    ) -> Self {
503        Self(Box::new(FailureData {
504            library,
505            description: Some(description.to_owned()),
506            attempts,
507        }))
508    }
509
510    #[cfg(any(ndi_link_static, test))]
511    pub(crate) fn linked(library: LibraryKind, refusal: LoadRefusal) -> Self {
512        Self(Box::new(FailureData {
513            library,
514            description: None,
515            attempts: vec![LoadAttempt::new(
516                PathBuf::from(format!("{library} (linked SDK archive)")),
517                LoadOrigin::LinkedArchive,
518                refusal,
519                true,
520                None,
521            )],
522        }))
523    }
524
525    /// Which native library the selection sought.
526    pub fn library(&self) -> LibraryKind {
527        self.0.library
528    }
529
530    /// Every refused location, in search order.
531    pub fn attempts(&self) -> &[LoadAttempt] {
532        &self.0.attempts
533    }
534
535    /// Whether any candidate loaded native code before it was refused.
536    ///
537    /// `false` means none could be opened. It does not establish that every
538    /// bare name was absent: platform loader failures retain the OS diagnostic.
539    pub fn loaded_any(&self) -> bool {
540        self.0.attempts.iter().any(LoadAttempt::loaded)
541    }
542}
543
544impl fmt::Display for FailureData {
545    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
546        if let Some(description) = &self.description {
547            write!(f, "no usable {description}; tried ")?;
548        }
549        for (index, attempt) in self.attempts.iter().enumerate() {
550            if index != 0 {
551                f.write_str("; ")?;
552            }
553            fmt::Display::fmt(attempt, f)?;
554        }
555        Ok(())
556    }
557}
558
559#[cfg(test)]
560mod tests {
561    use super::*;
562    use crate::Error;
563
564    #[test]
565    fn refusal_display_keeps_each_existing_diagnostic() {
566        let cases = [
567            (LoadRefusal::Absent, "not found"),
568            (LoadRefusal::PlatformLoader { detail: "dlopen failed: absent".into() }, "dlopen failed: absent"),
569            (LoadRefusal::NotIdentifiable { detail: "the module cannot be identified".into() }, "the module cannot be identified"),
570            (LoadRefusal::ResolvedToAnotherFile { resolved: "another.so".into() }, "the loader resolved it to another.so"),
571            (LoadRefusal::MissingAnchor { symbol: c"NDIlib_version", detail: "undefined symbol".into() }, "it does not export NDIlib_version: undefined symbol"),
572            (LoadRefusal::MissingEntryPoint { symbol: c"NDIlib_initialize" }, "it does not export the required entry point NDIlib_initialize"),
573            (LoadRefusal::EntryPointOutsideModule { symbol: c"NDIlib_initialize", module: "selected.so".into() }, "NDIlib_initialize resolves outside selected.so"),
574            (LoadRefusal::EditionNotMet, "it does not export the Advanced SDK entry points"),
575            (LoadRefusal::UnreadableVersion(VersionTextDefect::Missing), "NDIlib_version returned no version text"),
576            (LoadRefusal::UnreadableVersion(VersionTextDefect::Unterminated), "its version text has no terminator within the 4 MiB one SDK string may take"),
577            (LoadRefusal::UnreadableVersion(VersionTextDefect::NotUtf8 { valid_up_to: 7 }), "its version text is not UTF-8 at byte 7"),
578            (LoadRefusal::AlreadyRefused { path: "rejected.so".into(), refusal: Box::new(LoadRefusal::EditionNotMet) }, "the platform loader returned rejected.so, which is already loaded and was rejected (it does not export the Advanced SDK entry points); no other library of that name can be found by name in this process, so remove or fix that file or pass an explicit library path"),
579            (LoadRefusal::NoCompleteFileFamily { first_missing: c"NDIlib_file_player_create" }, "it provides no family of NDI File entry points (it does not export NDIlib_file_player_create)"),
580            (LoadRefusal::BoundToAnotherRuntime, "it is bound to an NDI runtime other than the selected one"),
581            (LoadRefusal::ForeignRuntimeInScope { module: "preloaded.so".into() }, "the process's global symbol scope already holds another NDI runtime (preloaded.so); select that runtime or stop linking or preloading it"),
582            (LoadRefusal::RelativeSearchDirectory, "the library search directory must be absolute and nonempty"),
583        ];
584        for (refusal, expected) in cases {
585            assert_eq!(refusal.to_string(), expected, "{refusal:?}");
586        }
587    }
588
589    #[test]
590    fn structured_search_keeps_order_origins_and_loaded_status() {
591        let absent = LoadAttempt::new(
592            "bundle/ndi.so".into(),
593            LoadOrigin::Executable,
594            LoadRefusal::Absent,
595            false,
596            None,
597        );
598        let relative = LoadAttempt::new(
599            "relative".into(),
600            LoadOrigin::RuntimeDirectory,
601            LoadRefusal::RelativeSearchDirectory,
602            false,
603            None,
604        );
605        let loader = LoadAttempt::new(
606            "ndi.so".into(),
607            LoadOrigin::LoaderSearch,
608            LoadRefusal::EditionNotMet,
609            true,
610            Some("resolved.so".into()),
611        );
612        let nothing_loaded = LoadFailure::searched(
613            LibraryKind::Runtime,
614            "NDI runtime",
615            vec![absent.clone(), relative.clone()],
616        );
617        assert!(!nothing_loaded.loaded_any());
618        let failure = LoadFailure::searched(
619            LibraryKind::Runtime,
620            "NDI runtime",
621            vec![absent, relative, loader],
622        );
623        assert_eq!(failure.library(), LibraryKind::Runtime);
624        assert_eq!(failure.attempts().len(), 3);
625        assert!(failure.loaded_any());
626        assert_eq!(
627            failure.attempts()[2].resolved_path(),
628            Some(Path::new("resolved.so"))
629        );
630        assert_eq!(failure.to_string(), "no usable NDI runtime; tried bundle/ndi.so (next to the executable): not found; relative (NDI_RUNTIME_DIR_V6): the library search directory must be absolute and nonempty; ndi.so (system library search) resolved to resolved.so: it does not export the Advanced SDK entry points");
631        assert_eq!(Error::RuntimeLoadFailed(failure).to_string(), "Failed to load an NDI library: no usable NDI runtime; tried bundle/ndi.so (next to the executable): not found; relative (NDI_RUNTIME_DIR_V6): the library search directory must be absolute and nonempty; ndi.so (system library search) resolved to resolved.so: it does not export the Advanced SDK entry points");
632    }
633
634    #[test]
635    fn every_conflict_kind_preserves_its_typed_paths_and_diagnostic() {
636        fn check(
637            failure: SelectionFailure,
638            kind: SelectionConflict,
639            library: LibraryKind,
640            selected: Option<&Path>,
641            requested: Option<&Path>,
642            foreign: Option<&Path>,
643            candidate: Option<(&Path, LoadOrigin)>,
644        ) {
645            assert_eq!(failure.kind(), kind);
646            assert_eq!(failure.library(), library);
647            assert_eq!(failure.selected(), selected);
648            assert_eq!(failure.requested(), requested);
649            assert_eq!(failure.foreign_module(), foreign);
650            let diagnostic = failure.to_string();
651            assert!(diagnostic.starts_with(&format!("{library} selection: {kind}")));
652            for (label, path) in [
653                ("selected", selected),
654                ("requested", requested),
655                ("foreign runtime", foreign),
656            ] {
657                if let Some(path) = path {
658                    assert!(
659                        diagnostic.contains(&format!(", {label} {}", path.display())),
660                        "{diagnostic}"
661                    );
662                } else {
663                    assert!(!diagnostic.contains(&format!(", {label} ")), "{diagnostic}");
664                }
665            }
666            if let Some((path, origin)) = candidate {
667                assert!(
668                    diagnostic.contains(&format!(", candidate {} ({origin})", path.display())),
669                    "{diagnostic}"
670                );
671            }
672            assert_eq!(
673                Error::RuntimeConflict(failure).to_string(),
674                format!("Conflicting {diagnostic}")
675            );
676        }
677
678        let selected = Path::new("selected/ndi.so");
679        let requested = Path::new("requested/ndi.so");
680        let foreign = Path::new("foreign/ndi.so");
681        let candidate = Path::new("candidate/ndi.so");
682
683        for library in [LibraryKind::Runtime, LibraryKind::File] {
684            check(
685                SelectionFailure::different_library(library, selected, requested),
686                SelectionConflict::DifferentLibrary,
687                library,
688                Some(selected),
689                Some(requested),
690                None,
691                None,
692            );
693            check(
694                SelectionFailure::linked(library, requested),
695                SelectionConflict::LinkedImplementation,
696                library,
697                None,
698                Some(requested),
699                None,
700                None,
701            );
702            check(
703                SelectionFailure::reentrant(library),
704                SelectionConflict::ReentrantSelection,
705                library,
706                None,
707                None,
708                None,
709                None,
710            );
711            for (explicit, origin) in [
712                (Some(requested), LoadOrigin::Explicit),
713                (None, LoadOrigin::Companion),
714            ] {
715                check(
716                    SelectionFailure::foreign(
717                        library,
718                        Some(selected),
719                        explicit,
720                        foreign,
721                        candidate,
722                        origin,
723                    ),
724                    SelectionConflict::ForeignRuntimeInScope,
725                    library,
726                    Some(selected),
727                    explicit,
728                    Some(foreign),
729                    Some((candidate, origin)),
730                );
731            }
732        }
733        for selected in [None, Some(selected)] {
734            for requested in [None, Some(requested)] {
735                check(
736                    SelectionFailure::edition_not_met(selected, requested),
737                    SelectionConflict::EditionNotMet,
738                    LibraryKind::Runtime,
739                    selected,
740                    requested,
741                    None,
742                    None,
743                );
744                #[cfg(feature = "file-io")]
745                check(
746                    SelectionFailure::file_needs_advanced(selected, requested),
747                    SelectionConflict::FileNeedsAdvancedRuntime,
748                    LibraryKind::File,
749                    selected,
750                    requested,
751                    None,
752                    None,
753                );
754            }
755        }
756    }
757
758    #[test]
759    fn linked_failures_report_one_linked_attempt_with_a_library_label() {
760        for library in [LibraryKind::Runtime, LibraryKind::File] {
761            let label = format!("{library} (linked SDK archive)");
762            let failure = LoadFailure::linked(library, LoadRefusal::EditionNotMet);
763            assert_eq!(failure.library(), library);
764            assert!(failure.loaded_any());
765            assert_eq!(failure.attempts().len(), 1);
766            assert_eq!(failure.attempts()[0].origin(), LoadOrigin::LinkedArchive);
767            assert_eq!(failure.attempts()[0].location(), Path::new(&label));
768            assert_eq!(
769                failure.to_string(),
770                format!("{label}: it does not export the Advanced SDK entry points")
771            );
772        }
773    }
774}