1use rmp_serde as msgpack;
6use serde::{Deserialize, Serialize};
7use serde_cbor;
8use serde_json;
9use std::fs::File;
10use std::io::{Read, Seek, SeekFrom, Write};
11use std::path::{Path, PathBuf};
12
13use crate::hio::errors::HioError;
14use crate::hio::filing::{Filer, FilerContext};
15
16pub fn open_cf(
19 name: Option<String>,
20 temp: Option<bool>,
21 reopen: Option<bool>,
22 clear: Option<bool>,
23 filed: Option<bool>,
24 base: Option<String>,
25 fext: Option<String>,
26 human: Option<bool>,
27) -> Result<ConfigerContext, HioError> {
28 let filed = filed.unwrap_or(true);
29 let fext = fext.unwrap_or_else(|| "json".to_string());
30 let human = human.unwrap_or(true);
31
32 let configer = Configer::new(
33 name,
34 base,
35 temp,
36 None,
37 None,
38 reopen,
39 clear,
40 None,
41 None, Some(filed),
43 None,
44 None,
45 Some(fext),
46 Some(human),
47 )?;
48
49 Ok(ConfigerContext::new(configer, clear.unwrap_or(false)))
50}
51
52#[derive(Debug)]
60pub struct Configer {
61 pub filer: Filer,
62 pub human: bool,
63}
64
65impl Configer {
66 const TAIL_DIR_PATH: &'static str = "keri/cf";
68 const CLEAN_TAIL_DIR_PATH: &'static str = "keri/clean/cf";
69 const ALT_TAIL_DIR_PATH: &'static str = ".keri/cf";
70 const ALT_CLEAN_TAIL_DIR_PATH: &'static str = ".keri/clean/cf";
71 const TEMP_PREFIX: &'static str = "keri_cf_";
72
73 pub fn new(
95 name: Option<String>,
96 base: Option<String>,
97 temp: Option<bool>,
98 head_dir_path: Option<PathBuf>,
99 perm: Option<u32>,
100 reopen: Option<bool>,
101 clear: Option<bool>,
102 reuse: Option<bool>,
103 clean: Option<bool>,
104 filed: Option<bool>,
105 extensioned: Option<bool>,
106 mode: Option<String>,
107 fext: Option<String>,
108 human: Option<bool>,
109 ) -> Result<Self, HioError> {
110 let name = name.unwrap_or_else(|| "conf".to_string());
111 let base = base.unwrap_or_else(|| "main".to_string());
112 let filed = filed.unwrap_or(true);
113 let mode = mode.unwrap_or_else(|| "r+b".to_string());
114 let fext = fext.unwrap_or_else(|| "json".to_string());
115 let human = human.unwrap_or(true);
116
117 let mut filer = Filer::new(
119 Some(name),
120 Some(base),
121 temp,
122 head_dir_path.clone(),
123 perm,
124 Some(false), clear,
126 reuse,
127 clean,
128 Some(filed),
129 extensioned,
130 Some(mode.clone()),
131 Some(fext.clone()),
132 )?;
133
134 filer.tail_dir_path = PathBuf::from(Self::TAIL_DIR_PATH);
136 filer.clean_tail_dir_path = PathBuf::from(Self::CLEAN_TAIL_DIR_PATH);
137 filer.alt_tail_dir_path = PathBuf::from(Self::ALT_TAIL_DIR_PATH);
138 filer.alt_clean_tail_dir_path = PathBuf::from(Self::ALT_CLEAN_TAIL_DIR_PATH);
139 filer.temp_prefix = Self::TEMP_PREFIX.to_string();
140
141 if reopen.unwrap_or(true) {
143 filer.reopen(
144 temp,
145 head_dir_path,
146 perm,
147 clear.unwrap_or(false),
148 reuse.unwrap_or(false),
149 clean.unwrap_or(false),
150 Some(mode),
151 Some(fext),
152 )?;
153 }
154
155 Ok(Configer { filer, human })
156 }
157
158 pub fn put<T: Serialize>(&mut self, data: &T, human: Option<bool>) -> Result<bool, HioError> {
169 if self.filer.file.is_none() {
170 return Err(HioError::FilerError(format!(
171 "File '{:?}' not opened.",
172 self.filer.path
173 )));
174 }
175
176 let human = human.unwrap_or(self.human);
177 let file = self.filer.file.as_mut().unwrap();
178
179 file.seek(SeekFrom::Start(0)).map_err(HioError::IoError)?;
180 file.set_len(0).map_err(HioError::IoError)?; let path = self.filer.path.as_ref().unwrap();
183 let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("");
184
185 let serialized =
186 match ext {
187 "json" => {
188 if human {
189 serde_json::to_string_pretty(data)
191 .map_err(|e| HioError::SerializationError(e.to_string()))?
192 .into_bytes()
193 } else {
194 serde_json::to_string(data)
196 .map_err(|e| HioError::SerializationError(e.to_string()))?
197 .into_bytes()
198 }
199 }
200 "mgpk" => msgpack::to_vec(data)
201 .map_err(|e| HioError::SerializationError(e.to_string()))?,
202 "cbor" => serde_cbor::to_vec(data)
203 .map_err(|e| HioError::SerializationError(e.to_string()))?,
204 _ => {
205 return Err(HioError::FilerError(format!(
206 "Invalid file path ext '{}' not '.json', '.mgpk', or '.cbor'.",
207 ext
208 )));
209 }
210 };
211
212 file.write_all(&serialized).map_err(HioError::IoError)?;
213 file.flush().map_err(HioError::IoError)?;
214 file.sync_all().map_err(HioError::IoError)?; Ok(true)
217 }
218
219 pub fn get<T>(&mut self, human: Option<bool>) -> Result<T, HioError>
228 where
229 T: for<'de> Deserialize<'de> + Default,
230 {
231 if self.filer.file.is_none() {
232 return Err(HioError::FilerError(format!(
233 "File '{:?}' not opened.",
234 self.filer.path
235 )));
236 }
237
238 let human = human.unwrap_or(self.human);
239 let file = self.filer.file.as_mut().unwrap();
240
241 file.seek(SeekFrom::Start(0)).map_err(HioError::IoError)?;
242 let mut contents = Vec::new();
243 file.read_to_end(&mut contents).map_err(HioError::IoError)?;
244
245 if contents.is_empty() {
246 return Ok(T::default());
247 }
248
249 let path = self.filer.path.as_ref().unwrap();
250 let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("");
251
252 let data = match ext {
253 "json" => {
254 let text = String::from_utf8(contents)
255 .map_err(|e| HioError::SerializationError(e.to_string()))?;
256
257 if human {
258 serde_json::from_str(&text)
262 .map_err(|e| HioError::SerializationError(e.to_string()))?
263 } else {
264 serde_json::from_str(&text)
265 .map_err(|e| HioError::SerializationError(e.to_string()))?
266 }
267 }
268 "mgpk" => msgpack::from_slice(&contents)
269 .map_err(|e| HioError::SerializationError(e.to_string()))?,
270 "cbor" => serde_cbor::from_slice(&contents)
271 .map_err(|e| HioError::SerializationError(e.to_string()))?,
272 _ => {
273 return Err(HioError::FilerError(format!(
274 "Invalid file path ext '{}' not '.json', '.mgpk', or '.cbor'.",
275 ext
276 )));
277 }
278 };
279
280 Ok(data)
281 }
282
283 pub fn close(&mut self, clear: bool) -> Result<bool, HioError> {
285 self.filer.close(clear)
286 }
287
288 pub fn reopen(
290 &mut self,
291 temp: Option<bool>,
292 head_dir_path: Option<PathBuf>,
293 perm: Option<u32>,
294 clear: bool,
295 reuse: bool,
296 clean: bool,
297 mode: Option<String>,
298 fext: Option<String>,
299 ) -> Result<bool, HioError> {
300 self.filer
301 .reopen(temp, head_dir_path, perm, clear, reuse, clean, mode, fext)
302 }
303
304 pub fn exists(
306 &self,
307 name: &str,
308 base: &str,
309 head_dir_path: Option<&Path>,
310 clean: bool,
311 filed: bool,
312 extensioned: bool,
313 fext: Option<&str>,
314 ) -> Result<bool, HioError> {
315 self.filer
316 .exists(name, base, head_dir_path, clean, filed, extensioned, fext)
317 }
318}
319
320impl std::ops::Deref for Configer {
322 type Target = Filer;
323 fn deref(&self) -> &Self::Target {
324 &self.filer
325 }
326}
327
328impl std::ops::DerefMut for Configer {
329 fn deref_mut(&mut self) -> &mut Self::Target {
330 &mut self.filer
331 }
332}
333
334pub struct ConfigerContext {
336 pub configer: Configer,
337 clear_on_drop: bool,
338}
339
340impl ConfigerContext {
341 pub fn new(configer: Configer, clear: bool) -> Self {
342 let clear_on_drop = configer.filer.temp || clear;
343 Self {
344 configer,
345 clear_on_drop,
346 }
347 }
348}
349
350impl Drop for ConfigerContext {
351 fn drop(&mut self) {
352 let _ = self.configer.close(self.clear_on_drop);
353 }
354}
355
356impl std::ops::Deref for ConfigerContext {
357 type Target = Configer;
358 fn deref(&self) -> &Self::Target {
359 &self.configer
360 }
361}
362
363impl std::ops::DerefMut for ConfigerContext {
364 fn deref_mut(&mut self) -> &mut Self::Target {
365 &mut self.configer
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372 use serde::{Deserialize, Serialize};
373 use std::collections::HashMap;
374 use std::io::{Read, Seek, SeekFrom, Write};
375 use std::sync::Mutex;
376
377 static TEST_MUTEX: Mutex<()> = Mutex::new(());
379
380 fn with_test_lock<F, R>(f: F) -> R
381 where
382 F: FnOnce() -> R,
383 {
384 let _guard = match TEST_MUTEX.lock() {
386 Ok(guard) => guard,
387 Err(poisoned) => {
388 eprintln!("Test mutex was poisoned, recovering...");
389 poisoned.into_inner()
390 }
391 };
392 f()
393 }
394
395 #[derive(Debug, Serialize, Deserialize, PartialEq, Default)]
396 struct TestConfig {
397 dt: String,
398 nel: TestNel,
399 iurls: Vec<String>,
400 durls: Vec<String>,
401 wurls: Vec<String>,
402 }
403
404 #[derive(Debug, Serialize, Deserialize, PartialEq, Default)]
405 struct TestNel {
406 dt: String,
407 curls: Vec<String>,
408 }
409
410 fn cleanup_test_dirs() {
411 let dirs_to_clean = vec!["/usr/local/var/keri"];
413
414 for dir in dirs_to_clean {
415 let path = PathBuf::from(dir);
416 if path.exists() {
417 let _ = std::fs::remove_dir_all(&path);
418 }
419 }
420
421 if let Some(home) = dirs::home_dir() {
422 let alt_dirs = vec![home.join(".keri")];
423
424 for dir in alt_dirs {
425 if dir.exists() {
426 let _ = std::fs::remove_dir_all(&dir);
427 }
428 }
429 }
430
431 std::thread::sleep(std::time::Duration::from_millis(10));
433 }
434
435 #[test]
436 fn test_configer() -> Result<(), HioError> {
437 with_test_lock(|| {
438 cleanup_test_dirs();
439
440 let filepath = "/usr/local/var/keri/cf/main/conf.json";
442 if PathBuf::from(filepath).exists() {
443 std::fs::remove_file(filepath).ok();
444 }
445
446 let mut cfr = Configer::new(
447 None, None, None, None, None, None, None, None, None, None, None, None, None, None,
448 )?; assert!(cfr
453 .path
454 .as_ref()
455 .unwrap()
456 .to_string_lossy()
457 .ends_with("keri/cf/main/conf.json"));
458 assert!(cfr.opened);
459 assert!(cfr.path.as_ref().unwrap().exists());
460 assert!(cfr.file.is_some());
461 assert!(cfr.human);
462
463 let empty_data: HashMap<String, String> = cfr.get(None)?;
465 assert!(empty_data.is_empty());
466
467 let data = HashMap::from([
469 ("name".to_string(), "habi".to_string()),
470 ("oobi".to_string(), "ABCDEFG".to_string()),
471 ]);
472
473 let wdata = HashMap::from([
475 ("name".to_string(), "hope".to_string()),
476 ("oobi".to_string(), "abc".to_string()),
477 ]);
478
479 assert!(cfr.put(&wdata, None)?);
480 let rdata: HashMap<String, String> = cfr.get(None)?;
481 assert_eq!(rdata, wdata);
482
483 if let Some(ref mut file) = cfr.file {
485 file.seek(SeekFrom::Start(0)).unwrap();
486 let mut contents = String::new();
487 file.read_to_string(&mut contents).unwrap();
488 assert!(contents.contains("{\n"));
490 assert!(contents.contains(" \""));
491 }
492
493 cfr.close(false)?;
494 assert!(!cfr.opened);
495 assert!(cfr
496 .path
497 .as_ref()
498 .unwrap()
499 .to_string_lossy()
500 .ends_with("keri/cf/main/conf.json"));
501 assert!(cfr.path.as_ref().unwrap().exists());
502
503 let result: Result<HashMap<String, String>, _> = cfr.get(None);
505 assert!(matches!(result, Err(HioError::FilerError(_))));
506
507 cfr.reopen(None, None, None, false, true, false, None, None)?;
509 assert!(cfr.opened);
510 assert!(cfr
511 .path
512 .as_ref()
513 .unwrap()
514 .to_string_lossy()
515 .ends_with("keri/cf/main/conf.json"));
516 assert!(cfr.path.as_ref().unwrap().exists());
517 let rdata: HashMap<String, String> = cfr.get(None)?;
518 assert_eq!(rdata, wdata); cfr.reopen(None, None, None, false, false, false, None, None)?;
522 assert!(cfr.opened);
523 assert!(cfr
524 .path
525 .as_ref()
526 .unwrap()
527 .to_string_lossy()
528 .ends_with("keri/cf/main/conf.json"));
529 assert!(cfr.path.as_ref().unwrap().exists());
530 let rdata: HashMap<String, String> = cfr.get(None)?;
531 assert_eq!(rdata, wdata); cfr.reopen(None, None, None, true, true, false, None, None)?;
535 assert!(cfr.opened);
536 assert!(cfr
537 .path
538 .as_ref()
539 .unwrap()
540 .to_string_lossy()
541 .ends_with("keri/cf/main/conf.json"));
542 assert!(cfr.path.as_ref().unwrap().exists());
543 let rdata: HashMap<String, String> = cfr.get(None)?;
544 assert!(rdata.is_empty()); let wdata = HashMap::from([
547 ("name".to_string(), "hope".to_string()),
548 ("oobi".to_string(), "abc".to_string()),
549 ]);
550 assert!(cfr.put(&wdata, None)?);
551 let rdata: HashMap<String, String> = cfr.get(None)?;
552 assert_eq!(rdata, wdata);
553
554 cfr.reopen(None, None, None, true, false, false, None, None)?;
556 assert!(cfr.opened);
557 assert!(cfr
558 .path
559 .as_ref()
560 .unwrap()
561 .to_string_lossy()
562 .ends_with("keri/cf/main/conf.json"));
563 assert!(cfr.path.as_ref().unwrap().exists());
564 let rdata: HashMap<String, String> = cfr.get(None)?;
565 assert!(rdata.is_empty()); let wdata = HashMap::from([
568 ("name".to_string(), "hope".to_string()),
569 ("oobi".to_string(), "abc".to_string()),
570 ]);
571 assert!(cfr.put(&wdata, None)?);
572 let rdata: HashMap<String, String> = cfr.get(None)?;
573 assert_eq!(rdata, wdata);
574
575 cfr.close(true)?;
576 assert!(!cfr.path.as_ref().unwrap().exists());
577 let result: Result<HashMap<String, String>, _> = cfr.get(None);
578 assert!(matches!(result, Err(HioError::FilerError(_))));
579
580 cleanup_test_dirs();
581 Ok(())
582 })
583 }
584
585 #[test]
586 fn test_configer_human_false() -> Result<(), HioError> {
587 with_test_lock(|| {
588 cleanup_test_dirs();
589
590 let mut cfr = Configer::new(
592 None,
593 None,
594 None,
595 None,
596 None,
597 None,
598 None,
599 None,
600 None,
601 None,
602 None,
603 None,
604 None,
605 Some(false), )?;
607
608 assert!(cfr
609 .path
610 .as_ref()
611 .unwrap()
612 .to_string_lossy()
613 .ends_with("keri/cf/main/conf.json"));
614 assert!(cfr.opened);
615 assert!(cfr.path.as_ref().unwrap().exists());
616 assert!(cfr.file.is_some());
617 assert!(!cfr.human);
618
619 let empty_data: HashMap<String, String> = cfr.get(None)?;
620 assert!(empty_data.is_empty());
621
622 let wdata = HashMap::from([
624 ("name".to_string(), "hope".to_string()),
625 ("oobi".to_string(), "abc".to_string()),
626 ]);
627 assert!(cfr.put(&wdata, None)?);
628 let rdata: HashMap<String, String> = cfr.get(None)?;
629 assert_eq!(rdata, wdata);
630
631 if let Some(ref mut file) = cfr.file {
633 file.seek(SeekFrom::Start(0)).unwrap();
634 let mut contents = String::new();
635 file.read_to_string(&mut contents).unwrap();
636 assert!(contents.contains("\"name\""));
638 assert!(contents.contains("\"hope\""));
639 assert!(contents.contains("\"oobi\""));
640 assert!(contents.contains("\"abc\""));
641 assert!(!contents.contains("{\n"));
643 assert!(!contents.contains(" \""));
644 assert!(contents.starts_with('{'));
646 assert!(contents.ends_with('}'));
647 }
648
649 cfr.close(true)?;
650 assert!(!cfr.path.as_ref().unwrap().exists());
651
652 cleanup_test_dirs();
653 Ok(())
654 })
655 }
656
657 #[test]
658 fn test_configer_alt_path() -> Result<(), HioError> {
659 with_test_lock(|| {
660 cleanup_test_dirs();
661
662 let restricted_head = PathBuf::from("/root/keri");
664
665 let mut cfr = Configer::new(
666 None,
667 None,
668 None,
669 Some(restricted_head), None,
671 None,
672 None,
673 None,
674 None,
675 None,
676 None,
677 None,
678 None,
679 None,
680 )?;
681
682 assert!(cfr
683 .path
684 .as_ref()
685 .unwrap()
686 .to_string_lossy()
687 .contains(".keri/cf/main/conf.json"));
688 assert!(cfr.opened);
689 assert!(cfr.path.as_ref().unwrap().exists());
690 assert!(cfr.file.is_some());
691
692 let empty_data: HashMap<String, String> = cfr.get(None)?;
693 assert!(empty_data.is_empty());
694
695 let data = HashMap::from([
696 ("name".to_string(), "habi".to_string()),
697 ("oobi".to_string(), "ABCDEFG".to_string()),
698 ]);
699
700 let wdata = HashMap::from([
702 ("name".to_string(), "hope".to_string()),
703 ("oobi".to_string(), "abc".to_string()),
704 ]);
705 assert!(cfr.put(&wdata, None)?);
706 let rdata: HashMap<String, String> = cfr.get(None)?;
707 assert_eq!(rdata, wdata);
708
709 cfr.close(false)?;
710 assert!(!cfr.opened);
711 assert!(cfr
712 .path
713 .as_ref()
714 .unwrap()
715 .to_string_lossy()
716 .contains(".keri/cf/main/conf.json"));
717 assert!(cfr.path.as_ref().unwrap().exists());
718 let result: Result<HashMap<String, String>, _> = cfr.get(None);
719 assert!(matches!(result, Err(HioError::FilerError(_))));
720
721 cfr.reopen(None, None, None, false, true, false, None, None)?;
723 assert!(cfr.opened);
724 assert!(cfr
725 .path
726 .as_ref()
727 .unwrap()
728 .to_string_lossy()
729 .contains(".keri/cf/main/conf.json"));
730 assert!(cfr.path.as_ref().unwrap().exists());
731 let rdata: HashMap<String, String> = cfr.get(None)?;
732 assert_eq!(rdata, wdata); cfr.reopen(None, None, None, false, false, false, None, None)?;
735 assert!(cfr.opened);
736 assert!(cfr
737 .path
738 .as_ref()
739 .unwrap()
740 .to_string_lossy()
741 .contains(".keri/cf/main/conf.json"));
742 assert!(cfr.path.as_ref().unwrap().exists());
743 let rdata: HashMap<String, String> = cfr.get(None)?;
744 assert_eq!(rdata, wdata); cfr.reopen(None, None, None, true, true, false, None, None)?;
747 assert!(cfr.opened);
748 assert!(cfr
749 .path
750 .as_ref()
751 .unwrap()
752 .to_string_lossy()
753 .contains(".keri/cf/main/conf.json"));
754 assert!(cfr.path.as_ref().unwrap().exists());
755 let rdata: HashMap<String, String> = cfr.get(None)?;
756 assert!(rdata.is_empty()); let wdata = HashMap::from([
759 ("name".to_string(), "hope".to_string()),
760 ("oobi".to_string(), "abc".to_string()),
761 ]);
762 assert!(cfr.put(&wdata, None)?);
763 let rdata: HashMap<String, String> = cfr.get(None)?;
764 assert_eq!(rdata, wdata);
765
766 cfr.reopen(None, None, None, true, false, false, None, None)?;
767 assert!(cfr.opened);
768 assert!(cfr
769 .path
770 .as_ref()
771 .unwrap()
772 .to_string_lossy()
773 .contains(".keri/cf/main/conf.json"));
774 assert!(cfr.path.as_ref().unwrap().exists());
775 let rdata: HashMap<String, String> = cfr.get(None)?;
776 assert!(rdata.is_empty()); let wdata = HashMap::from([
779 ("name".to_string(), "hope".to_string()),
780 ("oobi".to_string(), "abc".to_string()),
781 ]);
782 assert!(cfr.put(&wdata, None)?);
783 let rdata: HashMap<String, String> = cfr.get(None)?;
784 assert_eq!(rdata, wdata);
785
786 cfr.close(true)?;
787 assert!(!cfr.path.as_ref().unwrap().exists());
788 let result: Result<HashMap<String, String>, _> = cfr.get(None);
789 assert!(matches!(result, Err(HioError::FilerError(_))));
790
791 cleanup_test_dirs();
792 Ok(())
793 })
794 }
795
796 #[test]
797 fn test_open_cf_context_hjson() -> Result<(), HioError> {
798 with_test_lock(|| {
799 {
801 let mut cfr = open_cf(
802 Some("test".to_string()),
803 Some(true), None,
805 None,
806 None,
807 None,
808 None,
809 Some(true), )?;
811
812 let temp_dir = std::env::temp_dir();
813 assert!(cfr
814 .path
815 .as_ref()
816 .unwrap()
817 .to_string_lossy()
818 .contains("keri_"));
819 assert!(cfr
820 .path
821 .as_ref()
822 .unwrap()
823 .to_string_lossy()
824 .contains("_test/keri/cf/main/test.json"));
825 assert!(cfr.opened);
826 assert!(cfr.human);
827 assert!(cfr.path.as_ref().unwrap().exists());
828 assert!(cfr.file.is_some());
829
830 let wdata = HashMap::from([
831 ("name".to_string(), "hope".to_string()),
832 ("oobi".to_string(), "abc".to_string()),
833 ]);
834 assert!(cfr.put(&wdata, None)?);
835 let rdata: HashMap<String, String> = cfr.get(None)?;
836 assert_eq!(rdata, wdata);
837 } Ok(())
840 })
841 }
842
843 #[test]
844 fn test_open_cf_context_json() -> Result<(), HioError> {
845 with_test_lock(|| {
846 {
848 let mut cfr = open_cf(
849 Some("test".to_string()),
850 Some(true), None,
852 None,
853 None,
854 None,
855 None,
856 Some(false), )?;
858
859 assert!(cfr
860 .path
861 .as_ref()
862 .unwrap()
863 .to_string_lossy()
864 .contains("keri_"));
865 assert!(cfr
866 .path
867 .as_ref()
868 .unwrap()
869 .to_string_lossy()
870 .contains("_test/keri/cf/main/test.json"));
871 assert!(cfr.opened);
872 assert!(!cfr.human);
873 assert!(cfr.path.as_ref().unwrap().exists());
874 assert!(cfr.file.is_some());
875
876 let wdata = HashMap::from([
877 ("name".to_string(), "hope".to_string()),
878 ("oobi".to_string(), "abc".to_string()),
879 ]);
880 assert!(cfr.put(&wdata, None)?);
881 let rdata: HashMap<String, String> = cfr.get(None)?;
882 assert_eq!(rdata, wdata);
883 } Ok(())
886 })
887 }
888
889 #[test]
890 fn test_open_cf_context_msgpack() -> Result<(), HioError> {
891 with_test_lock(|| {
892 {
894 let mut cfr = open_cf(
895 Some("test".to_string()),
896 Some(true), None,
898 None,
899 None,
900 None,
901 Some("mgpk".to_string()),
902 None,
903 )?;
904
905 assert!(cfr
906 .path
907 .as_ref()
908 .unwrap()
909 .to_string_lossy()
910 .contains("keri_"));
911 assert!(cfr
912 .path
913 .as_ref()
914 .unwrap()
915 .to_string_lossy()
916 .contains("_test/keri/cf/main/test.mgpk"));
917 assert!(cfr.opened);
918 assert!(cfr.path.as_ref().unwrap().exists());
919 assert!(cfr.file.is_some());
920
921 let wdata = HashMap::from([
922 ("name".to_string(), "hope".to_string()),
923 ("oobi".to_string(), "abc".to_string()),
924 ]);
925 assert!(cfr.put(&wdata, None)?);
926 let rdata: HashMap<String, String> = cfr.get(None)?;
927 assert_eq!(rdata, wdata);
928 } Ok(())
931 })
932 }
933
934 #[test]
935 fn test_open_cf_context_cbor() -> Result<(), HioError> {
936 with_test_lock(|| {
937 {
939 let mut cfr = open_cf(
940 Some("test".to_string()),
941 Some(true), None,
943 None,
944 None,
945 None,
946 Some("cbor".to_string()),
947 None,
948 )?;
949
950 assert!(cfr
951 .path
952 .as_ref()
953 .unwrap()
954 .to_string_lossy()
955 .contains("keri_"));
956 assert!(cfr
957 .path
958 .as_ref()
959 .unwrap()
960 .to_string_lossy()
961 .contains("_test/keri/cf/main/test.cbor"));
962 assert!(cfr.opened);
963 assert!(cfr.path.as_ref().unwrap().exists());
964 assert!(cfr.file.is_some());
965
966 let wdata = HashMap::from([
967 ("name".to_string(), "hope".to_string()),
968 ("oobi".to_string(), "abc".to_string()),
969 ]);
970 assert!(cfr.put(&wdata, None)?);
971 let rdata: HashMap<String, String> = cfr.get(None)?;
972 assert_eq!(rdata, wdata);
973 } Ok(())
976 })
977 }
978 #[test]
979 fn test_configer_error_cases() -> Result<(), HioError> {
980 with_test_lock(|| {
981 cleanup_test_dirs();
982
983 let mut cfr = Configer::new(
985 Some("test_invalid".to_string()),
986 Some("test".to_string()),
987 Some(true), None,
989 None,
990 None,
991 None,
992 None,
993 None,
994 None,
995 None,
996 None,
997 Some("invalid".to_string()), None,
999 )?;
1000
1001 let test_data: HashMap<String, String> =
1003 HashMap::from([("key".to_string(), "value".to_string())]);
1004
1005 let put_result = cfr.put(&test_data, None);
1007 assert!(matches!(put_result, Err(HioError::FilerError(_))));
1008
1009 if let Some(ref mut file) = cfr.file {
1012 use std::io::Write;
1013 file.seek(SeekFrom::Start(0)).unwrap();
1014 file.write_all(b"invalid content").unwrap();
1015 file.flush().unwrap();
1016 }
1017
1018 let get_result: Result<HashMap<String, String>, _> = cfr.get(None);
1019 assert!(matches!(get_result, Err(HioError::FilerError(_))));
1020
1021 cfr.close(true)?;
1022 cleanup_test_dirs();
1023 Ok(())
1024 })
1025 }
1026
1027 #[test]
1028 fn test_configer_different_formats() -> Result<(), HioError> {
1029 with_test_lock(|| {
1030 #[derive(Debug, Serialize, Deserialize, PartialEq, Default)]
1032 struct ComplexData {
1033 name: String,
1034 oobi: String,
1035 numbers: Vec<i32>,
1036 nested: HashMap<String, String>,
1037 }
1038
1039 let test_data = ComplexData {
1040 name: "test".to_string(),
1041 oobi: "ABCDEFG".to_string(),
1042 numbers: vec![1, 2, 3, 4, 5],
1043 nested: HashMap::from([
1044 ("key1".to_string(), "value1".to_string()),
1045 ("key2".to_string(), "value2".to_string()),
1046 ]),
1047 };
1048
1049 {
1051 let mut cfr = Configer::new(
1052 Some("test_complex_json".to_string()),
1053 None,
1054 Some(true),
1055 None,
1056 None,
1057 None,
1058 None,
1059 None,
1060 None,
1061 None,
1062 None,
1063 None,
1064 Some("json".to_string()),
1065 Some(true),
1066 )?;
1067 cfr.put(&test_data, None)?;
1068 let retrieved: ComplexData = cfr.get(None)?;
1069 assert_eq!(test_data, retrieved);
1070 }
1071
1072 {
1074 let mut cfr = Configer::new(
1075 Some("test_complex_mgpk".to_string()),
1076 None,
1077 Some(true),
1078 None,
1079 None,
1080 None,
1081 None,
1082 None,
1083 None,
1084 None,
1085 None,
1086 None,
1087 Some("mgpk".to_string()),
1088 None,
1089 )?;
1090 cfr.put(&test_data, None)?;
1091 let retrieved: ComplexData = cfr.get(None)?;
1092 assert_eq!(test_data, retrieved);
1093 }
1094
1095 {
1097 let mut cfr = Configer::new(
1098 Some("test_complex_cbor".to_string()),
1099 None,
1100 Some(true),
1101 None,
1102 None,
1103 None,
1104 None,
1105 None,
1106 None,
1107 None,
1108 None,
1109 None,
1110 Some("cbor".to_string()),
1111 None,
1112 )?;
1113 cfr.put(&test_data, None)?;
1114 let retrieved: ComplexData = cfr.get(None)?;
1115 assert_eq!(test_data, retrieved);
1116 }
1117
1118 Ok(())
1119 })
1120 }
1121}