1use std::fmt;
27use std::path::{Path, PathBuf};
28
29pub const INSTANCE_VARIABLE: &str = "QAR_INSTANCE";
33
34pub const DEFAULT_INSTANCE_NAME: &str = "default";
37
38pub const INSTANCE_NAME_MAX_LENGTH: usize = 64;
40
41pub const INSTANCES_REGISTRY_KEY: &str = r"SOFTWARE\Quaternar\QAROS\Instances";
44
45pub const INSTANCE_RUNTIME_FOLDER_VALUE: &str = "RuntimeFolder";
48
49pub const INSTALL_REGISTRY_KEY: &str = r"SOFTWARE\Quaternar\QAROS";
52
53pub const INSTALL_FOLDER_VALUE: &str = "InstallFolder";
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub enum LookupStep {
61 AlreadyLoaded,
63 BesideBinding,
65 Instance,
67 InstalledRuntime,
69 SearchPath,
71}
72
73impl LookupStep {
74 pub fn place(self) -> &'static str {
76 match self {
77 Self::AlreadyLoaded => "already loaded in this process",
78 Self::BesideBinding => "beside the binding",
79 Self::Instance => INSTANCE_VARIABLE,
80 Self::InstalledRuntime => "the installed QAROS",
81 Self::SearchPath if cfg!(windows) => "PATH",
82 Self::SearchPath => "the dynamic linker's search",
83 }
84 }
85}
86
87impl fmt::Display for LookupStep {
88 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89 formatter.write_str(self.place())
90 }
91}
92
93#[derive(Clone, Debug, PartialEq, Eq)]
95pub enum LookupOutcome {
96 NotApplicable,
100 Missing {
102 path: PathBuf,
104 },
105 FailedToLoad {
107 path: PathBuf,
109 message: String,
111 },
112 InvalidInstanceName {
115 name: String,
117 },
118 UnknownInstance {
122 name: String,
124 },
125 InstanceRuntimeNotLoadable {
128 name: String,
130 path: PathBuf,
132 message: Option<String>,
135 },
136}
137
138#[derive(Clone, Debug, PartialEq, Eq)]
140pub struct LookupAttempt {
141 pub step: LookupStep,
143 pub outcome: LookupOutcome,
145}
146
147impl fmt::Display for LookupAttempt {
148 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
149 let place = self.step.place();
150 match &self.outcome {
151 LookupOutcome::NotApplicable => {
152 let reason = match self.step {
153 LookupStep::AlreadyLoaded => "no".to_string(),
154 LookupStep::BesideBinding => "the binding's folder is unknown".to_string(),
155 LookupStep::Instance if cfg!(windows) => "not set".to_string(),
156 LookupStep::Instance => {
157 "read on Windows only (there are no instance records here)".to_string()
158 }
159 LookupStep::InstalledRuntime if cfg!(windows) => format!(
160 "not installed (no {INSTALL_FOLDER_VALUE} under HKLM\\{INSTALL_REGISTRY_KEY})"
161 ),
162 LookupStep::InstalledRuntime => "looked up on Windows only".to_string(),
163 LookupStep::SearchPath => "not found in any folder".to_string(),
164 };
165 write!(formatter, "{place}: {reason}")
166 }
167 LookupOutcome::Missing { path } if self.step == LookupStep::InstalledRuntime => write!(
168 formatter,
169 "{place}: the installed QAROS runtime in '{}' could not be loaded ({} does not \
170 exist). Repair or reinstall QAROS",
171 folder_of(path).display(),
172 path.display()
173 ),
174 LookupOutcome::Missing { path } => {
175 write!(formatter, "{place}: {} does not exist", path.display())
176 }
177 LookupOutcome::FailedToLoad { path, message }
178 if self.step == LookupStep::InstalledRuntime =>
179 {
180 write!(
181 formatter,
182 "{place}: the installed QAROS runtime in '{}' could not be loaded ({} failed \
183 to load: {message}). Repair or reinstall QAROS",
184 folder_of(path).display(),
185 path.display()
186 )
187 }
188 LookupOutcome::FailedToLoad { path, message } => {
189 write!(
190 formatter,
191 "{place}: {} failed to load: {message}",
192 path.display()
193 )
194 }
195 LookupOutcome::InvalidInstanceName { name } => write!(
196 formatter,
197 "{INSTANCE_VARIABLE}='{name}' is not a QAROS instance name (1-\
198 {INSTANCE_NAME_MAX_LENGTH} of A-Z a-z 0-9 . _ -); no runtime is loaded"
199 ),
200 LookupOutcome::UnknownInstance { name } if name == DEFAULT_INSTANCE_NAME => write!(
201 formatter,
202 "{INSTANCE_VARIABLE} is '{DEFAULT_INSTANCE_NAME}', but QAROS is not installed \
203 (no {INSTALL_FOLDER_VALUE} under HKLM\\{INSTALL_REGISTRY_KEY})"
204 ),
205 LookupOutcome::UnknownInstance { name } => write!(
206 formatter,
207 "{INSTANCE_VARIABLE} is '{name}', but no runtime folder is recorded for that \
208 instance (no full-path {INSTANCE_RUNTIME_FOLDER_VALUE} or \
209 {INSTALL_FOLDER_VALUE} under HKCU\\{INSTANCES_REGISTRY_KEY}\\{name}). Start its \
210 hub, or unset {INSTANCE_VARIABLE}"
211 ),
212 LookupOutcome::InstanceRuntimeNotLoadable {
213 name,
214 path,
215 message,
216 } => {
217 let file_name = path.file_name().map_or_else(
218 || path.display().to_string(),
219 |file_name| file_name.to_string_lossy().into_owned(),
220 );
221 write!(
222 formatter,
223 "{INSTANCE_VARIABLE} is '{name}', but no loadable {file_name} is in its \
224 runtime folder '{}'",
225 folder_of(path).display()
226 )?;
227 match message {
228 Some(message) => write!(formatter, " ({file_name} failed to load: {message})"),
229 None => write!(formatter, " ({file_name} does not exist there)"),
230 }
231 }
232 }
233 }
234}
235
236fn folder_of(path: &Path) -> &Path {
237 path.parent().unwrap_or(path)
238}
239
240pub fn is_valid_instance_name(name: &str) -> bool {
243 (1..=INSTANCE_NAME_MAX_LENGTH).contains(&name.len())
244 && name
245 .bytes()
246 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
247}
248
249pub(crate) fn is_fully_qualified_folder(folder: &str) -> bool {
253 let bytes = folder.as_bytes();
254 let drive = bytes.len() >= 3
255 && bytes[0].is_ascii_alphabetic()
256 && bytes[1] == b':'
257 && matches!(bytes[2], b'\\' | b'/');
258 let unc = bytes.starts_with(br"\\");
259 drive || unc
260}
261
262pub(crate) fn instance_runtime_folder<Locator: RuntimeLocator + ?Sized>(
271 locator: &Locator,
272 instance: &str,
273) -> Option<PathBuf> {
274 if !is_valid_instance_name(instance) {
275 return None;
276 }
277 if instance == DEFAULT_INSTANCE_NAME {
278 return locator.installed_bin_folder();
279 }
280 let recorded_folder = |value| {
281 locator
282 .instance_record_value(instance, value)
283 .filter(|folder| is_fully_qualified_folder(folder))
284 .map(PathBuf::from)
285 };
286 recorded_folder(INSTANCE_RUNTIME_FOLDER_VALUE)
287 .or_else(|| recorded_folder(INSTALL_FOLDER_VALUE).map(|folder| folder.join("bin")))
288}
289
290#[derive(Debug)]
292pub(crate) struct FoundRuntime<Library> {
293 pub(crate) library: Library,
294 pub(crate) step: LookupStep,
295 pub(crate) path: PathBuf,
298}
299
300#[derive(Clone, Debug, PartialEq, Eq)]
302pub(crate) enum SearchPath {
303 Folders(Vec<PathBuf>),
305 DynamicLinker,
307}
308
309pub(crate) trait RuntimeLocator {
311 type Library;
312
313 fn already_loaded(&self) -> Option<Self::Library>;
315 fn binding_folder(&self) -> Option<PathBuf>;
317 fn requested_instance(&self) -> Option<String>;
320 fn instance_record_value(&self, instance: &str, value: &str) -> Option<String>;
323 fn installed_bin_folder(&self) -> Option<PathBuf>;
325 fn search_path(&self) -> SearchPath;
327 fn is_file(&self, path: &Path) -> bool;
328 fn load(&self, path: &Path) -> Result<Self::Library, String>;
330 fn load_by_linker_search(&self, file_name: &str) -> Result<Self::Library, String>;
332}
333
334pub(crate) fn find_runtime<Locator: RuntimeLocator>(
337 locator: &Locator,
338 file_name: &str,
339) -> Result<FoundRuntime<Locator::Library>, Vec<LookupAttempt>> {
340 let mut attempts = Vec::new();
341 let found = |library, step, path| {
342 Ok(FoundRuntime {
343 library,
344 step,
345 path,
346 })
347 };
348
349 if let Some(library) = locator.already_loaded() {
350 return found(library, LookupStep::AlreadyLoaded, PathBuf::from(file_name));
351 }
352 attempts.push(not_applicable(LookupStep::AlreadyLoaded));
353
354 match locator.binding_folder() {
355 Some(folder) => match load_from_folder(locator, &folder, file_name) {
356 Ok(library) => {
357 return found(library, LookupStep::BesideBinding, folder.join(file_name));
358 }
359 Err(outcome) => attempts.push(LookupAttempt {
360 step: LookupStep::BesideBinding,
361 outcome,
362 }),
363 },
364 None => attempts.push(not_applicable(LookupStep::BesideBinding)),
365 }
366
367 if let Some(instance) = locator.requested_instance() {
370 return match load_requested_instance(locator, &instance, file_name) {
371 Ok((library, path)) => found(library, LookupStep::Instance, path),
372 Err(outcome) => {
373 attempts.push(LookupAttempt {
374 step: LookupStep::Instance,
375 outcome,
376 });
377 Err(attempts)
378 }
379 };
380 }
381 attempts.push(not_applicable(LookupStep::Instance));
382
383 if let Some(folder) = locator.installed_bin_folder() {
384 return match load_from_folder(locator, &folder, file_name) {
385 Ok(library) => found(
386 library,
387 LookupStep::InstalledRuntime,
388 folder.join(file_name),
389 ),
390 Err(outcome) => {
391 attempts.push(LookupAttempt {
392 step: LookupStep::InstalledRuntime,
393 outcome,
394 });
395 Err(attempts)
396 }
397 };
398 }
399 attempts.push(not_applicable(LookupStep::InstalledRuntime));
400
401 match locator.search_path() {
402 SearchPath::Folders(folders) => {
403 for folder in folders {
404 match load_from_folder(locator, &folder, file_name) {
405 Ok(library) => {
406 return found(library, LookupStep::SearchPath, folder.join(file_name));
407 }
408 Err(LookupOutcome::Missing { .. }) => {}
409 Err(outcome) => attempts.push(LookupAttempt {
410 step: LookupStep::SearchPath,
411 outcome,
412 }),
413 }
414 }
415 attempts.push(not_applicable(LookupStep::SearchPath));
416 }
417 SearchPath::DynamicLinker => match locator.load_by_linker_search(file_name) {
418 Ok(library) => {
419 return found(library, LookupStep::SearchPath, PathBuf::from(file_name));
420 }
421 Err(message) => attempts.push(LookupAttempt {
422 step: LookupStep::SearchPath,
423 outcome: LookupOutcome::FailedToLoad {
424 path: PathBuf::from(file_name),
425 message,
426 },
427 }),
428 },
429 }
430 Err(attempts)
431}
432
433fn load_requested_instance<Locator: RuntimeLocator>(
436 locator: &Locator,
437 instance: &str,
438 file_name: &str,
439) -> Result<(Locator::Library, PathBuf), LookupOutcome> {
440 let name = instance.to_string();
441 if !is_valid_instance_name(instance) {
442 return Err(LookupOutcome::InvalidInstanceName { name });
443 }
444 let Some(folder) = instance_runtime_folder(locator, instance) else {
445 return Err(LookupOutcome::UnknownInstance { name });
446 };
447 let path = folder.join(file_name);
448 match load_from_folder(locator, &folder, file_name) {
449 Ok(library) => Ok((library, path)),
450 Err(LookupOutcome::FailedToLoad { message, .. }) => {
451 Err(LookupOutcome::InstanceRuntimeNotLoadable {
452 name,
453 path,
454 message: Some(message),
455 })
456 }
457 Err(_) => Err(LookupOutcome::InstanceRuntimeNotLoadable {
458 name,
459 path,
460 message: None,
461 }),
462 }
463}
464
465fn not_applicable(step: LookupStep) -> LookupAttempt {
466 LookupAttempt {
467 step,
468 outcome: LookupOutcome::NotApplicable,
469 }
470}
471
472fn load_from_folder<Locator: RuntimeLocator>(
473 locator: &Locator,
474 folder: &Path,
475 file_name: &str,
476) -> Result<Locator::Library, LookupOutcome> {
477 let path = folder.join(file_name);
478 if !locator.is_file(&path) {
479 return Err(LookupOutcome::Missing { path });
480 }
481 locator
482 .load(&path)
483 .map_err(|message| LookupOutcome::FailedToLoad { path, message })
484}
485
486pub(crate) fn search_path_folders(path_value: &std::ffi::OsStr) -> Vec<PathBuf> {
489 path_value
490 .to_string_lossy()
491 .split(';')
492 .map(|entry| {
493 let entry = entry.trim();
494 entry
495 .strip_prefix('"')
496 .and_then(|unquoted| unquoted.strip_suffix('"'))
497 .unwrap_or(entry)
498 })
499 .filter(|entry| !entry.is_empty())
500 .map(PathBuf::from)
501 .filter(|folder| folder.is_absolute())
502 .collect()
503}
504
505#[cfg(test)]
506mod tests {
507 #![allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
508
509 use std::cell::RefCell;
510 use std::collections::HashMap;
511 use std::ffi::OsString;
512
513 use super::*;
514
515 const FILE_NAME: &str = "qar-streaming-c.dll";
516 const DEV_INSTANCE: &str = "dev-0123456789abcdef";
517
518 #[derive(Clone, Copy)]
520 enum FakeFile {
521 Loads,
522 FailsToLoad,
523 }
524
525 #[derive(Default)]
528 struct FakeSystem {
529 already_loaded: bool,
530 binding_folder: Option<PathBuf>,
531 requested_instance: Option<String>,
532 instance_records: HashMap<(String, String), String>,
534 installed_bin_folder: Option<PathBuf>,
535 search_path_folders: Option<Vec<PathBuf>>,
536 linker_finds_runtime: bool,
537 files: HashMap<PathBuf, FakeFile>,
538 loads: RefCell<Vec<PathBuf>>,
539 }
540
541 impl FakeSystem {
542 fn with_file(mut self, folder: &Path, file: FakeFile) -> Self {
543 self.files.insert(folder.join(FILE_NAME), file);
544 self
545 }
546
547 fn with_record(mut self, instance: &str, value: &str, folder: &str) -> Self {
548 self.instance_records.insert(
549 (instance.to_string(), value.to_string()),
550 folder.to_string(),
551 );
552 self
553 }
554
555 fn without_records(mut self) -> Self {
556 self.instance_records.clear();
557 self
558 }
559
560 fn requesting(mut self, instance: &str) -> Self {
561 self.requested_instance = Some(instance.to_string());
562 self
563 }
564 }
565
566 impl RuntimeLocator for FakeSystem {
567 type Library = PathBuf;
568
569 fn already_loaded(&self) -> Option<PathBuf> {
570 self.already_loaded.then(|| PathBuf::from("already loaded"))
571 }
572
573 fn binding_folder(&self) -> Option<PathBuf> {
574 self.binding_folder.clone()
575 }
576
577 fn requested_instance(&self) -> Option<String> {
578 self.requested_instance.clone()
579 }
580
581 fn instance_record_value(&self, instance: &str, value: &str) -> Option<String> {
582 self.instance_records
583 .get(&(instance.to_string(), value.to_string()))
584 .cloned()
585 }
586
587 fn installed_bin_folder(&self) -> Option<PathBuf> {
588 self.installed_bin_folder.clone()
589 }
590
591 fn search_path(&self) -> SearchPath {
592 self.search_path_folders
593 .clone()
594 .map_or(SearchPath::DynamicLinker, SearchPath::Folders)
595 }
596
597 fn is_file(&self, path: &Path) -> bool {
598 self.files.contains_key(path)
599 }
600
601 fn load(&self, path: &Path) -> Result<PathBuf, String> {
602 self.loads.borrow_mut().push(path.to_path_buf());
603 match self.files.get(path) {
604 Some(FakeFile::Loads) => Ok(path.to_path_buf()),
605 Some(FakeFile::FailsToLoad) => Err("a dependent DLL is missing".to_string()),
606 None => panic!("loaded {} without checking it exists", path.display()),
607 }
608 }
609
610 fn load_by_linker_search(&self, file_name: &str) -> Result<PathBuf, String> {
611 self.loads.borrow_mut().push(PathBuf::from(file_name));
612 if self.linker_finds_runtime {
613 Ok(PathBuf::from(format!("linker:{file_name}")))
614 } else {
615 Err(format!("{file_name}: cannot open shared object file"))
616 }
617 }
618 }
619
620 fn folder(name: &str) -> PathBuf {
621 std::env::temp_dir().join("qaros-lookup-test").join(name)
622 }
623
624 fn runtime_in(name: &str) -> PathBuf {
625 folder(name).join(FILE_NAME)
626 }
627
628 fn recorded(name: &str) -> String {
631 format!(r"C:\qaros-lookup-test\{name}")
632 }
633
634 fn recorded_runtime(name: &str) -> PathBuf {
635 PathBuf::from(recorded(name)).join(FILE_NAME)
636 }
637
638 fn system_with_a_runtime_everywhere() -> FakeSystem {
641 FakeSystem {
642 already_loaded: true,
643 binding_folder: Some(folder("binding")),
644 installed_bin_folder: Some(folder("installed")),
645 search_path_folders: Some(vec![folder("path-1")]),
646 ..FakeSystem::default()
647 }
648 .with_file(&folder("binding"), FakeFile::Loads)
649 .with_file(&folder("installed"), FakeFile::Loads)
650 .with_file(&folder("path-1"), FakeFile::Loads)
651 .with_record(
652 DEV_INSTANCE,
653 INSTANCE_RUNTIME_FOLDER_VALUE,
654 &recorded("dev-build"),
655 )
656 .with_file(Path::new(&recorded("dev-build")), FakeFile::Loads)
657 }
658
659 fn system_from_step_two() -> FakeSystem {
661 FakeSystem {
662 already_loaded: false,
663 binding_folder: None,
664 ..system_with_a_runtime_everywhere()
665 }
666 }
667
668 fn found_at(system: &FakeSystem) -> (LookupStep, PathBuf) {
669 let found = find_runtime(system, FILE_NAME).expect("a runtime");
670 let by_bare_name = found.step == LookupStep::AlreadyLoaded
671 || found.library.starts_with(format!("linker:{FILE_NAME}"));
672 let file_loaded = if by_bare_name {
673 PathBuf::from(FILE_NAME)
674 } else {
675 found.library.clone()
676 };
677 assert_eq!(
678 found.path, file_loaded,
679 "the path reported is the file loaded"
680 );
681 (found.step, found.library)
682 }
683
684 fn attempts_of(system: &FakeSystem) -> Vec<LookupAttempt> {
685 find_runtime(system, FILE_NAME).expect_err("no runtime")
686 }
687
688 fn instance_outcome(system: &FakeSystem) -> LookupOutcome {
690 let attempts = attempts_of(system);
691 let steps: Vec<LookupStep> = attempts.iter().map(|attempt| attempt.step).collect();
692 assert_eq!(
693 steps,
694 vec![
695 LookupStep::AlreadyLoaded,
696 LookupStep::BesideBinding,
697 LookupStep::Instance
698 ],
699 "a set QAR_INSTANCE ends the lookup at step 2"
700 );
701 attempts.last().expect("step 2").outcome.clone()
702 }
703
704 fn attempt(step: LookupStep, outcome: LookupOutcome) -> LookupAttempt {
705 LookupAttempt { step, outcome }
706 }
707
708 #[test]
709 fn a_runtime_already_in_the_process_wins_and_nothing_is_loaded() {
710 let system = system_with_a_runtime_everywhere().requesting(DEV_INSTANCE);
711 assert_eq!(
712 found_at(&system),
713 (LookupStep::AlreadyLoaded, PathBuf::from("already loaded"))
714 );
715 assert!(system.loads.borrow().is_empty());
716 }
717
718 #[test]
719 fn the_runtime_beside_the_binding_wins_over_the_instance_and_the_installation() {
720 let system = FakeSystem {
721 already_loaded: false,
722 ..system_with_a_runtime_everywhere().requesting(DEV_INSTANCE)
723 };
724 assert_eq!(
725 found_at(&system),
726 (LookupStep::BesideBinding, runtime_in("binding"))
727 );
728 }
729
730 #[test]
731 fn a_runtime_beside_the_binding_that_fails_to_load_is_reported_and_the_lookup_goes_on() {
732 let mut system = FakeSystem {
733 already_loaded: false,
734 ..system_with_a_runtime_everywhere().requesting(DEV_INSTANCE)
735 };
736 system
737 .files
738 .insert(runtime_in("binding"), FakeFile::FailsToLoad);
739 assert_eq!(
740 found_at(&system),
741 (LookupStep::Instance, recorded_runtime("dev-build"))
742 );
743 assert_eq!(
744 *system.loads.borrow(),
745 vec![runtime_in("binding"), recorded_runtime("dev-build")]
746 );
747 }
748
749 #[test]
750 fn the_runtime_folder_of_the_named_instance_wins_over_the_installation() {
751 let system = system_from_step_two().requesting(DEV_INSTANCE);
752 assert_eq!(
753 found_at(&system),
754 (LookupStep::Instance, recorded_runtime("dev-build"))
755 );
756 }
757
758 #[test]
759 fn the_default_instance_is_the_installed_qaros() {
760 let system = system_from_step_two().requesting(DEFAULT_INSTANCE_NAME);
761 assert_eq!(
762 found_at(&system),
763 (LookupStep::Instance, runtime_in("installed"))
764 );
765 }
766
767 #[test]
768 fn the_default_instance_without_an_installation_is_an_error_and_path_is_not_searched() {
769 let system = FakeSystem {
770 installed_bin_folder: None,
771 ..system_from_step_two().requesting(DEFAULT_INSTANCE_NAME)
772 };
773 let outcome = instance_outcome(&system);
774 assert_eq!(
775 outcome,
776 LookupOutcome::UnknownInstance {
777 name: DEFAULT_INSTANCE_NAME.to_string()
778 }
779 );
780 assert_eq!(
781 attempt(LookupStep::Instance, outcome).to_string(),
782 r"QAR_INSTANCE is 'default', but QAROS is not installed (no InstallFolder under HKLM\SOFTWARE\Quaternar\QAROS)"
783 );
784 assert!(system.loads.borrow().is_empty());
785 }
786
787 #[test]
788 fn a_named_instance_without_a_runtime_folder_falls_back_to_its_install_folders_bin() {
789 let bin = PathBuf::from(recorded("registered")).join("bin");
790 let system = system_from_step_two()
791 .without_records()
792 .requesting("registered")
793 .with_record("registered", INSTALL_FOLDER_VALUE, &recorded("registered"))
794 .with_file(&bin, FakeFile::Loads);
795 assert_eq!(
796 found_at(&system),
797 (LookupStep::Instance, bin.join(FILE_NAME))
798 );
799 }
800
801 #[test]
802 fn the_runtime_folder_wins_over_the_install_folder_of_the_same_record() {
803 let system = system_from_step_two().requesting(DEV_INSTANCE).with_record(
804 DEV_INSTANCE,
805 INSTALL_FOLDER_VALUE,
806 &recorded("registered"),
807 );
808 assert_eq!(
809 found_at(&system),
810 (LookupStep::Instance, recorded_runtime("dev-build"))
811 );
812 }
813
814 #[test]
815 fn an_unknown_instance_is_an_error_naming_it_never_the_installed_runtime() {
816 let system = system_from_step_two().requesting("nobody-recorded-this");
817 let outcome = instance_outcome(&system);
818 assert_eq!(
819 outcome,
820 LookupOutcome::UnknownInstance {
821 name: "nobody-recorded-this".to_string()
822 }
823 );
824 assert_eq!(
825 attempt(LookupStep::Instance, outcome).to_string(),
826 r"QAR_INSTANCE is 'nobody-recorded-this', but no runtime folder is recorded for that instance (no full-path RuntimeFolder or InstallFolder under HKCU\SOFTWARE\Quaternar\QAROS\Instances\nobody-recorded-this). Start its hub, or unset QAR_INSTANCE"
827 );
828 assert!(system.loads.borrow().is_empty());
829 }
830
831 #[test]
832 fn relative_or_drive_relative_recorded_folders_count_as_no_record() {
833 for folder in [
834 r"relative\bin",
835 r"C:bin",
836 r"\rooted-without-drive",
837 "",
838 "C:",
839 ] {
840 let system = system_from_step_two()
841 .without_records()
842 .requesting(DEV_INSTANCE)
843 .with_record(DEV_INSTANCE, INSTANCE_RUNTIME_FOLDER_VALUE, folder)
844 .with_record(DEV_INSTANCE, INSTALL_FOLDER_VALUE, folder);
845 assert_eq!(
846 instance_outcome(&system),
847 LookupOutcome::UnknownInstance {
848 name: DEV_INSTANCE.to_string()
849 },
850 "{folder:?}"
851 );
852 }
853 }
854
855 #[test]
856 fn drive_and_unc_folders_are_fully_qualified() {
857 for folder in [r"C:\QAROS\bin", "d:/qaros/bin", r"\\server\share\bin"] {
858 assert!(is_fully_qualified_folder(folder), "{folder:?}");
859 }
860 for folder in [
861 r"relative\bin",
862 r"C:bin",
863 r"\rooted",
864 "/usr/lib",
865 "",
866 r"1:\x",
867 ] {
868 assert!(!is_fully_qualified_folder(folder), "{folder:?}");
869 }
870 }
871
872 #[test]
873 fn an_invalid_instance_name_is_an_error_and_nothing_is_loaded() {
874 let too_long = "a".repeat(INSTANCE_NAME_MAX_LENGTH + 1);
875 for name in [
876 "with space",
877 r"..\escape",
878 "dev/x",
879 "d\u{e9}v",
880 too_long.as_str(),
881 ] {
882 let system = system_from_step_two().requesting(name);
883 let outcome = instance_outcome(&system);
884 assert_eq!(
885 outcome,
886 LookupOutcome::InvalidInstanceName {
887 name: name.to_string()
888 }
889 );
890 assert_eq!(
891 attempt(LookupStep::Instance, outcome).to_string(),
892 format!(
893 "QAR_INSTANCE='{name}' is not a QAROS instance name (1-64 of A-Z a-z 0-9 . _ -); no runtime is loaded"
894 )
895 );
896 assert!(system.loads.borrow().is_empty());
897 }
898 }
899
900 #[test]
901 fn instance_names_are_short_portable_tokens() {
902 let longest = "a".repeat(INSTANCE_NAME_MAX_LENGTH);
903 for name in ["default", DEV_INSTANCE, "A.b_c-9", longest.as_str()] {
904 assert!(is_valid_instance_name(name), "{name:?}");
905 }
906 let too_long = "a".repeat(INSTANCE_NAME_MAX_LENGTH + 1);
907 for name in [
908 "",
909 "with space",
910 r"..\escape",
911 "d\u{e9}v",
912 too_long.as_str(),
913 ] {
914 assert!(!is_valid_instance_name(name), "{name:?}");
915 }
916 }
917
918 #[test]
919 fn an_instance_folder_without_the_runtime_ends_the_lookup_before_the_installation() {
920 let system = system_from_step_two()
921 .without_records()
922 .requesting(DEV_INSTANCE)
923 .with_record(
924 DEV_INSTANCE,
925 INSTANCE_RUNTIME_FOLDER_VALUE,
926 &recorded("empty"),
927 );
928 let outcome = instance_outcome(&system);
929 assert_eq!(
930 outcome,
931 LookupOutcome::InstanceRuntimeNotLoadable {
932 name: DEV_INSTANCE.to_string(),
933 path: recorded_runtime("empty"),
934 message: None,
935 }
936 );
937 assert_eq!(
938 attempt(LookupStep::Instance, outcome).to_string(),
939 format!(
940 "QAR_INSTANCE is '{DEV_INSTANCE}', but no loadable {FILE_NAME} is in its runtime folder '{}' ({FILE_NAME} does not exist there)",
941 PathBuf::from(recorded("empty")).display()
942 )
943 );
944 assert!(system.loads.borrow().is_empty());
945 }
946
947 #[test]
948 fn an_instance_runtime_that_fails_to_load_ends_the_lookup() {
949 let mut system = system_from_step_two().requesting(DEV_INSTANCE);
950 system
951 .files
952 .insert(recorded_runtime("dev-build"), FakeFile::FailsToLoad);
953 let outcome = instance_outcome(&system);
954 assert_eq!(
955 outcome,
956 LookupOutcome::InstanceRuntimeNotLoadable {
957 name: DEV_INSTANCE.to_string(),
958 path: recorded_runtime("dev-build"),
959 message: Some("a dependent DLL is missing".to_string()),
960 }
961 );
962 let line = attempt(LookupStep::Instance, outcome).to_string();
963 assert!(
964 line.ends_with(&format!(
965 "({FILE_NAME} failed to load: a dependent DLL is missing)"
966 )),
967 "{line}"
968 );
969 assert_eq!(*system.loads.borrow(), vec![recorded_runtime("dev-build")]);
970 }
971
972 #[test]
973 fn without_the_variable_the_installation_wins_over_path() {
974 let system = system_from_step_two();
975 assert_eq!(
976 found_at(&system),
977 (LookupStep::InstalledRuntime, runtime_in("installed"))
978 );
979 }
980
981 #[test]
982 fn an_installation_without_its_runtime_is_reported_and_path_is_not_searched() {
983 let system = FakeSystem {
984 installed_bin_folder: Some(folder("broken-installation")),
985 ..system_from_step_two()
986 };
987 let attempts = attempts_of(&system);
988 assert_eq!(
989 attempts.last(),
990 Some(&attempt(
991 LookupStep::InstalledRuntime,
992 LookupOutcome::Missing {
993 path: runtime_in("broken-installation")
994 }
995 ))
996 );
997 let line = attempts.last().expect("step 3").to_string();
998 assert!(
999 line.starts_with(&format!(
1000 "the installed QAROS: the installed QAROS runtime in '{}' could not be loaded",
1001 folder("broken-installation").display()
1002 )),
1003 "{line}"
1004 );
1005 assert!(line.ends_with("Repair or reinstall QAROS"), "{line}");
1006 assert!(system.loads.borrow().is_empty());
1007 }
1008
1009 #[test]
1010 fn an_installed_runtime_that_fails_to_load_is_reported_and_path_is_not_searched() {
1011 let mut system = system_from_step_two();
1012 system
1013 .files
1014 .insert(runtime_in("installed"), FakeFile::FailsToLoad);
1015 assert_eq!(
1016 attempts_of(&system).last(),
1017 Some(&attempt(
1018 LookupStep::InstalledRuntime,
1019 LookupOutcome::FailedToLoad {
1020 path: runtime_in("installed"),
1021 message: "a dependent DLL is missing".to_string(),
1022 }
1023 ))
1024 );
1025 assert_eq!(*system.loads.borrow(), vec![runtime_in("installed")]);
1026 }
1027
1028 #[test]
1029 fn path_folders_are_tried_in_order_past_ones_without_the_runtime_or_failing_to_load() {
1030 let system = FakeSystem {
1031 search_path_folders: Some(vec![folder("path-a"), folder("path-b"), folder("path-c")]),
1032 ..FakeSystem::default()
1033 }
1034 .with_file(&folder("path-b"), FakeFile::FailsToLoad)
1035 .with_file(&folder("path-c"), FakeFile::Loads);
1036 assert_eq!(
1037 found_at(&system),
1038 (LookupStep::SearchPath, runtime_in("path-c"))
1039 );
1040 assert_eq!(
1041 *system.loads.borrow(),
1042 vec![runtime_in("path-b"), runtime_in("path-c")]
1043 );
1044 }
1045
1046 #[test]
1047 fn outside_windows_step_four_is_the_dynamic_linkers_search() {
1048 let system = FakeSystem {
1049 linker_finds_runtime: true,
1050 ..FakeSystem::default()
1051 };
1052 assert_eq!(
1053 found_at(&system),
1054 (
1055 LookupStep::SearchPath,
1056 PathBuf::from(format!("linker:{FILE_NAME}"))
1057 )
1058 );
1059 }
1060
1061 #[test]
1062 fn nothing_found_names_every_place_looked_at_in_order() {
1063 let system = FakeSystem {
1064 binding_folder: Some(folder("binding")),
1065 search_path_folders: Some(vec![folder("path-a"), folder("path-b")]),
1066 ..FakeSystem::default()
1067 }
1068 .with_file(&folder("path-b"), FakeFile::FailsToLoad);
1069 let attempts = attempts_of(&system);
1070 assert_eq!(
1071 attempts,
1072 vec![
1073 attempt(LookupStep::AlreadyLoaded, LookupOutcome::NotApplicable),
1074 attempt(
1075 LookupStep::BesideBinding,
1076 LookupOutcome::Missing {
1077 path: runtime_in("binding")
1078 }
1079 ),
1080 attempt(LookupStep::Instance, LookupOutcome::NotApplicable),
1081 attempt(LookupStep::InstalledRuntime, LookupOutcome::NotApplicable),
1082 attempt(
1083 LookupStep::SearchPath,
1084 LookupOutcome::FailedToLoad {
1085 path: runtime_in("path-b"),
1086 message: "a dependent DLL is missing".to_string(),
1087 }
1088 ),
1089 attempt(LookupStep::SearchPath, LookupOutcome::NotApplicable),
1090 ]
1091 );
1092 let lines: Vec<String> = attempts.iter().map(ToString::to_string).collect();
1093 assert_eq!(lines[0], "already loaded in this process: no");
1094 assert_eq!(
1095 lines[1],
1096 format!(
1097 "beside the binding: {} does not exist",
1098 runtime_in("binding").display()
1099 )
1100 );
1101 let expected_instance_line = if cfg!(windows) {
1102 "QAR_INSTANCE: not set"
1103 } else {
1104 "QAR_INSTANCE: read on Windows only (there are no instance records here)"
1105 };
1106 assert_eq!(lines[2], expected_instance_line);
1107 assert!(
1108 lines[3].starts_with("the installed QAROS: "),
1109 "{}",
1110 lines[3]
1111 );
1112 assert!(
1113 lines[4].ends_with("failed to load: a dependent DLL is missing"),
1114 "{}",
1115 lines[4]
1116 );
1117 assert!(
1118 lines[5].ends_with(": not found in any folder"),
1119 "{}",
1120 lines[5]
1121 );
1122 }
1123
1124 #[test]
1125 fn the_steps_print_their_place() {
1126 assert_eq!(LookupStep::Instance.to_string(), "QAR_INSTANCE");
1127 assert_eq!(LookupStep::BesideBinding.to_string(), "beside the binding");
1128 assert_eq!(
1129 LookupStep::InstalledRuntime.to_string(),
1130 "the installed QAROS"
1131 );
1132 }
1133
1134 #[test]
1135 fn path_entries_are_unquoted_and_empty_or_relative_ones_are_dropped() {
1136 let separator = OsString::from(";");
1137 let mut path_value = OsString::new();
1138 for entry in [
1139 folder("first").into_os_string(),
1140 OsString::new(),
1141 OsString::from("relative\\folder"),
1142 OsString::from("."),
1143 {
1144 let mut quoted = OsString::from("\"");
1145 quoted.push(folder("second with space"));
1146 quoted.push("\"");
1147 quoted
1148 },
1149 ] {
1150 path_value.push(&entry);
1151 path_value.push(&separator);
1152 }
1153 assert_eq!(
1154 search_path_folders(&path_value),
1155 vec![folder("first"), folder("second with space")]
1156 );
1157 }
1158}