1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
use std::path::{Path, PathBuf};
use std::fs::create_dir_all;

use tantivy::directory::MmapDirectory;
use tantivy::{Index, ReloadPolicy, IndexWriter, IndexReader};

use crate::prelude::*;
use tantivy::schema::Schema;


/// Resolve home
pub(crate) fn resolve_home<T: AsRef<str>>(home: Option<T>) -> Result<PathBuf, IndexError> {
    let home = match &home {
        Some(h) => h.as_ref(),
        None => "indexes"
    };
    let home = Path::new(home);
    let _ = create_dir_all(home)?;
    Ok(home.to_owned())
}

/// Resolve Index
pub(crate) fn resolve_index_directory_path<T: AsRef<str>>(name: T, home: Option<T>) -> Result<PathBuf, IndexError> {
    let home = resolve_home(home)?;
    let path = home.join(name.as_ref());
    Ok(path)
}


/// Create a MMap dir
pub(crate) fn open_mmap_directory(path: PathBuf) -> Result<MmapDirectory, IndexError> {
    if !path.exists() {
        let _ = create_dir_all(&path)?;
    }
    let dir = MmapDirectory::open(path)?;
    Ok(dir)
}


/// Open a store or create & open using a schema
pub(crate) fn open_index(dir: MmapDirectory, schema: Option<&Schema>) -> Result<Index, IndexError> {
    let index = if Index::exists(&dir) {
        Index::open(dir)
    } else {
        if let None = schema {
            let error = IndexError::new(
                "Unable to create index",
                "Schema is required for new index",
            );
            return Err(error);
        }
        let schema = schema.unwrap();
        Index::create(dir, schema.clone())
    }?;

    Ok(index)
}

/// Convenience method to open writer
pub(crate) fn open_index_writer(index: &Index) -> Result<IndexWriter, IndexError> {
    let index_writer = index.writer(50_000_000)
        .map_err(|e| {
            let reason = e.to_string();
            let error = IndexError::new(
                "Unable to create index writer",
                reason.as_str(),
            );
            error
        })?;
    Ok(index_writer)
}


/// Convenience method to open reader
pub(crate) fn open_index_reader(index: &Index) -> Result<IndexReader, IndexError> {
    let index_reader = index
        .reader_builder()
        .reload_policy(ReloadPolicy::OnCommit)
        .try_into().map_err(|e| {
        let reason = e.to_string();
        let error = IndexError::new(
            "Unable to create index reader",
            reason.as_str(),
        );
        error
    })?;
    Ok(index_reader)
}


#[cfg(test)]
mod tests {
    use super::*;
    use std::str::FromStr;
    use std::fs::remove_dir_all;
    use super::super::utils;
    use serde::Serialize;

    #[derive(Serialize)]
    struct Dummy {
        x: String,
        y: String,
        z: u64,
    }

    impl Default for Dummy {
        fn default() -> Self {
            let x: String = "".to_string();
            let y: String = "".to_string();
            let z: u64 = 1u64;
            Self {
                x,
                y,
                z,
            }
        }
    }


    #[test]
    fn validate_open_mmap_on_missing_dir() {
        let path = random_string(Some(10));
        let p = Path::new(&path);
        assert!(!p.exists());
        let path = PathBuf::from_str(&path);
        assert!(path.is_ok());
        let path = path.ok().unwrap();
        let path = open_mmap_directory(path);
        assert!(path.is_ok());
        assert!(p.exists());
        let _ = remove_dir_all(&p);
    }

    #[test]
    fn validate_open_index_on_missing_dir() {
        let data = Dummy {
            x: "A".to_owned(),
            y: "B".to_owned(),
            z: 100,
        };
        let data = utils::as_value(&data).unwrap();
        let schema = utils::to_schema(&data, None).unwrap();
        let path = random_string(Some(10));
        let p = Path::new(&path);
        assert!(!p.exists());
        let path = PathBuf::from_str(&path).unwrap();
        let path = open_mmap_directory(path).unwrap();
        let result = open_index(path, Some(&schema));
        assert!(result.is_ok());
        assert!(p.exists());
        let _ = remove_dir_all(&p);
    }

    #[test]
    fn error_while_opening_new_index_without_schema() {
        let tmp_error_while_opening_new_index_without_schema = "error_while_opening_new_index_without_schema";

        let path = Path::new(tmp_error_while_opening_new_index_without_schema);
        assert!(!path.exists());
        let _ = std::fs::create_dir_all(path);
        assert!(path.exists());


        let dir = MmapDirectory::open(path).unwrap();
        let index = open_index(dir, None);
        assert!(index.is_err());
        let _ = std::fs::remove_dir_all(path);
    }

    #[test]
    fn error_while_opening_open_index_writer() {
        let tmp_error_while_opening_new_index_without_schema = "error_while_opening_open_index_writer";

        let path = Path::new(tmp_error_while_opening_new_index_without_schema);
        assert!(!path.exists());
        let _ = std::fs::create_dir_all(path);
        assert!(path.exists());


        let dir = MmapDirectory::open(path).unwrap();


        let dummy = Dummy::default();
        let data = as_value(&dummy).unwrap();
        let schema = to_schema(&data, None).unwrap();
        let index = open_index(dir, Some(&schema)).unwrap();

        let _ = std::fs::remove_dir_all(path);

        let writer = open_index_writer(&index);
        assert!(writer.is_err());
    }

    #[test]
    fn error_while_opening_open_index_reader() {
        let tmp_error_while_opening_new_index_without_schema = "error_while_opening_open_index_reader";

        let path = Path::new(tmp_error_while_opening_new_index_without_schema);
        assert!(!path.exists());
        let _ = std::fs::create_dir_all(path);
        assert!(path.exists());


        let dir = MmapDirectory::open(path).unwrap();


        let dummy = Dummy::default();
        let data = as_value(&dummy).unwrap();
        let schema = to_schema(&data, None).unwrap();
        let index = open_index(dir, Some(&schema)).unwrap();

        let _ = std::fs::remove_dir_all(path);

        let reader = open_index_reader(&index);
        assert!(reader.is_err());
    }
}