Skip to main content

libkeri/keri/app/
configing.rs

1//! libkeri configing module
2//!
3//! Configuration file management with multiple serialization formats
4
5use 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
16/// Returns contextmanager generated by openFiler with Configer instance as default
17/// and filed = true
18pub 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, // Fixed: pass temp parameter
42        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/// Habitat Config File
53///
54/// Supports four serializations: HJSON, JSON, MGPK (MsgPack), and CBOR
55/// The serialization is determined by the file extension .fext which may be
56/// either '.json', '.mgpk', or '.cbor'. The default is that .json extension
57/// uses HJSON because HJSON can get (load) a strict json file.
58/// To use strict json on put (dump) then set .human to false.
59#[derive(Debug)]
60pub struct Configer {
61    pub filer: Filer,
62    pub human: bool,
63}
64
65impl Configer {
66    // Class constants for KERI config paths
67    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    /// Setup config file at path
74    ///
75    /// Parameters:
76    ///     name: directory path name differentiator directory/file
77    ///         When system employs more than one keri installation, name allows
78    ///         differentiating each instance by name
79    ///     base: optional directory path segment inserted before name
80    ///         that allows further differentiation with a hierarchy. "" means optional.
81    ///     temp: assign to .temp
82    ///         true then open in temporary directory, clear on close
83    ///         Otherwise then open persistent directory, do not clear on close
84    ///     head_dir_path: optional head directory pathname for main database
85    ///     perm: optional numeric os dir permissions for database directory and database files
86    ///     reopen: true means (re)opened by this init, false means not (re)opened by this init but later
87    ///     clear: true means remove directory upon close if reopen, false means do not remove directory upon close if reopen
88    ///     reuse: true means reuse self.path if already exists, false means do not reuse but remake self.path
89    ///     clean: true means path uses clean tail variant, false means path uses normal tail variant
90    ///     filed: true means .path is file path not directory path, false means .path is directory path not file path
91    ///     mode: File open mode when filed default non-truncate r+w
92    ///     fext: File extension when filed
93    ///     human: true means use human friendly HJSON when fext is json
94    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        // Create a Filer with custom KERI paths
118        let mut filer = Filer::new(
119            Some(name),
120            Some(base),
121            temp,
122            head_dir_path.clone(),
123            perm,
124            Some(false), // Don't reopen yet, we need to set custom paths first
125            clear,
126            reuse,
127            clean,
128            Some(filed),
129            extensioned,
130            Some(mode.clone()),
131            Some(fext.clone()),
132        )?;
133
134        // Override the default paths with KERI-specific paths
135        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        // Now reopen with the custom paths
142        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    /// Serialize data dict and write to file given by path where serialization is
159    /// given by fext path's extension of either JSON, MsgPack, or CBOR for extension
160    /// .json, .mgpk, or .cbor respectively
161    ///
162    /// Parameters:
163    ///     data: to be serialized per file extension on path
164    ///     human: override for human-friendly JSON formatting
165    ///
166    /// Raises:
167    ///     HioError if unsupported file extension or file not opened
168    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)?; // Truncate
181
182        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                        // For human-friendly JSON, use pretty printing
190                        serde_json::to_string_pretty(data)
191                            .map_err(|e| HioError::SerializationError(e.to_string()))?
192                            .into_bytes()
193                    } else {
194                        // For compact JSON
195                        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)?; // fsync equivalent
215
216        Ok(true)
217    }
218
219    /// Returns data converted from contents of file path given extension
220    /// Returns empty/default value if empty file
221    ///
222    /// Raises:
223    ///     HioError if unsupported file extension or file not opened
224    ///
225    /// File may be either json, msgpack, or cbor given by extension .json, .mgpk, or
226    /// .cbor respectively
227    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                    // Try to parse as HJSON first, fall back to regular JSON
259                    // Note: We'll use regular JSON for now since hjson crate might not be available
260                    // In a real implementation, you'd want to add hjson support
261                    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    /// Close the configer
284    pub fn close(&mut self, clear: bool) -> Result<bool, HioError> {
285        self.filer.close(clear)
286    }
287
288    /// Reopen the configer
289    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    /// Check if config exists
305    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
320// Delegate common properties to the underlying Filer
321impl 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
334/// Context manager for Configer
335pub 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    // Force tests to run sequentially to avoid race conditions
378    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        // Handle poisoned mutex by ignoring the poison and continuing
385        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        // Clean up test directories
412        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        // Small delay to ensure filesystem operations complete
432        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            // Test Configer with defaults
441            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            )?; // defaults
449
450            // assert cfr.path == filepath
451            // github runner does not allow /usr/local/var
452            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            // Test empty file read
464            let empty_data: HashMap<String, String> = cfr.get(None)?;
465            assert!(empty_data.is_empty());
466
467            // Plain json manually (simulating direct file operations)
468            let data = HashMap::from([
469                ("name".to_string(), "habi".to_string()),
470                ("oobi".to_string(), "ABCDEFG".to_string()),
471            ]);
472
473            // Test put/get with HJSON (human=true)
474            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            // Verify human-readable format by reading raw file content
484            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                // Should be pretty-printed JSON (human-readable)
489                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            // Should error when trying to get from closed file
504            let result: Result<HashMap<String, String>, _> = cfr.get(None);
505            assert!(matches!(result, Err(HioError::FilerError(_))));
506
507            // Test reopen with reuse=true
508            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); // not empty
519
520            // Test reopen without reuse (remake but not clear)
521            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); // not empty
532
533            // Test reopen with reuse=true, clear=true (should remake even with reuse)
534            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()); // empty due to clear
545
546            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            // Test reopen with clear=true (should remake)
555            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()); // empty
566
567            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            // Test with plain json human==false
591            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), // human=false
606            )?;
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            // Test with human==false
623            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            // Verify compact JSON format by reading raw file content
632            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                // Should contain JSON structure - compact format without pretty printing
637                assert!(contents.contains("\"name\""));
638                assert!(contents.contains("\"hope\""));
639                assert!(contents.contains("\"oobi\""));
640                assert!(contents.contains("\"abc\""));
641                // For compact JSON, it should NOT contain newlines and indentation
642                assert!(!contents.contains("{\n"));
643                assert!(!contents.contains("  \""));
644                // But should still be valid JSON in one line
645                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            // Test with altPath by using not permitted headDirPath to force Alt
663            let restricted_head = PathBuf::from("/root/keri");
664
665            let mut cfr = Configer::new(
666                None,
667                None,
668                None,
669                Some(restricted_head), // This should force alt path
670                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            // Test put/get
701            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            // Test various reopen scenarios
722            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); // not empty
733
734            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); // not empty
745
746            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()); // empty
757
758            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()); // empty
777
778            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            // Test openCF hjson (default uses json and temp==true)
800            {
801                let mut cfr = open_cf(
802                    Some("test".to_string()),
803                    Some(true), // temp
804                    None,
805                    None,
806                    None,
807                    None,
808                    None,
809                    Some(true), // human
810                )?;
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            } // cfr goes out of scope, should clean temp files
838
839            Ok(())
840        })
841    }
842
843    #[test]
844    fn test_open_cf_context_json() -> Result<(), HioError> {
845        with_test_lock(|| {
846            // Test openCF json (human=false)
847            {
848                let mut cfr = open_cf(
849                    Some("test".to_string()),
850                    Some(true), // temp
851                    None,
852                    None,
853                    None,
854                    None,
855                    None,
856                    Some(false), // human=false
857                )?;
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            } // should clean temp files
884
885            Ok(())
886        })
887    }
888
889    #[test]
890    fn test_open_cf_context_msgpack() -> Result<(), HioError> {
891        with_test_lock(|| {
892            // Test openCF mgpk
893            {
894                let mut cfr = open_cf(
895                    Some("test".to_string()),
896                    Some(true), // temp
897                    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            } // should clean temp files
929
930            Ok(())
931        })
932    }
933
934    #[test]
935    fn test_open_cf_context_cbor() -> Result<(), HioError> {
936        with_test_lock(|| {
937            // Test openCF cbor
938            {
939                let mut cfr = open_cf(
940                    Some("test".to_string()),
941                    Some(true), // temp
942                    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            } // should clean temp files
974
975            Ok(())
976        })
977    }
978    #[test]
979    fn test_configer_error_cases() -> Result<(), HioError> {
980        with_test_lock(|| {
981            cleanup_test_dirs();
982
983            // Test that invalid extension causes an error during put/get operations
984            let mut cfr = Configer::new(
985                Some("test_invalid".to_string()),
986                Some("test".to_string()),
987                Some(true), // temp
988                None,
989                None,
990                None,
991                None,
992                None,
993                None,
994                None,
995                None,
996                None,
997                Some("invalid".to_string()), // Use invalid extension directly
998                None,
999            )?;
1000
1001            // Put some test data to the file first so it's not empty
1002            let test_data: HashMap<String, String> =
1003                HashMap::from([("key".to_string(), "value".to_string())]);
1004
1005            // Both put and get should fail with invalid extension
1006            let put_result = cfr.put(&test_data, None);
1007            assert!(matches!(put_result, Err(HioError::FilerError(_))));
1008
1009            // Since put failed, the file should still be empty, but let's test get anyway
1010            // We need to put some invalid content in the file first to avoid the empty file shortcut
1011            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            // Test data structure - add Default implementation
1031            #[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            // Test JSON
1050            {
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            // Test MessagePack
1073            {
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            // Test CBOR
1096            {
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}