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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
// Copyright (c) 2018-2023, agnos.ai UK Ltd, all rights reserved.
//---------------------------------------------------------------

extern crate alloc;

use {
    crate::{
        database_call,
        rdfox_api::{
            CParameters,
            CParameters_destroy,
            CParameters_getString,
            CParameters_newEmptyParameters,
            CParameters_setString,
        },
    },
    alloc::ffi::CString,
    rdf_store_rs::RDFStoreError,
    std::{
        ffi::CStr,
        fmt::{Display, Formatter},
        os::raw::c_char,
        path::Path,
        ptr,
        sync::Arc,
    },
};

pub enum FactDomain {
    ASSERTED,
    INFERRED,
    ALL,
}

pub enum PersistenceMode {
    File,
    FileSequence,
    Off,
}

impl Display for PersistenceMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            PersistenceMode::File => write!(f, "file"),
            PersistenceMode::FileSequence => write!(f, "file-sequence"),
            PersistenceMode::Off => write!(f, "off"),
        }
    }
}

pub enum DataStoreType {
    ParallelNN,
    ParallelNW,
    ParallelWW,
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Parameters {
    pub(crate) inner: Arc<*mut CParameters>,
}

unsafe impl Sync for Parameters {}

unsafe impl Send for Parameters {}

impl Display for Parameters {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "Parameters[]") // TODO: show keys and values (currently not
        // possible)
    }
}

impl Drop for Parameters {
    fn drop(&mut self) {
        assert!(
            !self.inner.is_null(),
            "Parameters-object was already dropped"
        );
        unsafe {
            CParameters_destroy(self.inner.cast());
            // tracing::trace!(target: LOG_TARGET_DATABASE, "Dropped Params");
        }
    }
}

const SENSITIVE_PARAMETERS: [&str; 1] = ["license-content"];

impl Parameters {
    pub fn empty() -> Result<Self, RDFStoreError> {
        let mut parameters: *mut CParameters = ptr::null_mut();
        database_call!(
            "Allocating parameters",
            CParameters_newEmptyParameters(&mut parameters)
        )?;
        Ok(Parameters { inner: Arc::new(parameters) })
    }

    pub fn set_string(&self, key: &str, value: &str) -> Result<(), RDFStoreError> {
        let c_key = CString::new(key).unwrap();
        let c_value = CString::new(value).unwrap();
        let msg = if SENSITIVE_PARAMETERS.contains(&c_key.to_str().unwrap()) {
            format!(
                "Setting parameter {}=[***]",
                c_key.to_str().unwrap(),
            )
        } else {
            format!(
                "Setting parameter {}=[{}]",
                c_key.to_str().unwrap(),
                c_value.to_str().unwrap()
            )
        };
        database_call!(
            msg.as_str(),
            CParameters_setString(*self.inner, c_key.as_ptr(), c_value.as_ptr())
        )
    }

    pub fn get_string(&self, key: &str, default: &str) -> Result<String, RDFStoreError> {
        let c_key = CString::new(key).unwrap();
        let c_default = CString::new(default).unwrap();
        let mut c_value: *const c_char = ptr::null();
        let msg = format!(
            "Getting parameter {} with default value {}",
            c_key.to_str().unwrap(),
            c_default.to_str().unwrap()
        );
        database_call!(
            msg.as_str(),
            CParameters_getString(
                *self.inner,
                c_key.as_ptr(),
                c_default.as_ptr(),
                &mut c_value as *mut *const c_char
            )
        )?;
        let c_version = unsafe { CStr::from_ptr(c_value) };
        Ok(c_version.to_str().unwrap().to_owned())
    }

    pub fn fact_domain(self, fact_domain: FactDomain) -> Result<Self, RDFStoreError> {
        match fact_domain {
            FactDomain::ASSERTED => self.set_string("fact-domain", "explicit")?,
            FactDomain::INFERRED => self.set_string("fact-domain", "derived")?,
            FactDomain::ALL => self.set_string("fact-domain", "all")?,
        };
        Ok(self)
    }

    pub fn switch_off_file_access_sandboxing(self) -> Result<Self, RDFStoreError> {
        self.set_string("sandbox-directory", "")?;
        Ok(self)
    }

    pub fn persist_datastore(self, mode: PersistenceMode) -> Result<Self, RDFStoreError> {
        match mode {
            PersistenceMode::File => self.set_string("persist-ds", "file")?,
            PersistenceMode::FileSequence => self.set_string("persist-ds", "file-sequence")?,
            PersistenceMode::Off => self.set_string("persist-ds", "off")?,
        };
        Ok(self)
    }

    pub fn persist_roles(self, mode: PersistenceMode) -> Result<Self, RDFStoreError> {
        self.set_string("persist-roles", &mode.to_string())?;
        Ok(self)
    }

    pub fn server_directory(self, dir: &Path) -> Result<Self, RDFStoreError> {
        if dir.is_dir() {
            self.set_string("server-directory", dir.to_str().unwrap())?;
            Ok(self)
        } else {
            panic!("{dir:?} is not a directory")
        }
    }

    pub fn license_file(self, file: &Path) -> Result<Self, RDFStoreError> {
        if file.is_file() {
            self.set_string("license-file", file.to_str().unwrap())?;
            Ok(self)
        } else {
            panic!("{file:?} does not exist")
        }
    }

    pub fn license_content(self, content: &str) -> Result<Self, RDFStoreError> {
        // Content that comes in via an environment variable can have literal `\\n`
        // strings in them that should be replaced by actual line-feeds
        let content = content.replace("\r\n", "\n").replace("\\n", "\n");
        // Add a line feed at the end of the content just to make sure, if it's
        // missing the last field in the license key will not be recognized
        self.set_string("license-content", format!("{content}\n").as_str())?;
        Ok(self)
    }

    pub fn set_license(self, database_dir: Option<&Path>) -> Result<Self, RDFStoreError> {
        match super::license::find_license(database_dir)? {
            (Some(license_file_name), None) => {
                return self.license_file(license_file_name.as_path())
            },
            (None, Some(license_content)) => return self.license_content(license_content.as_str()),
            _ => {},
        };
        Ok(self)
    }

    pub fn import_rename_user_blank_nodes(self, setting: bool) -> Result<Self, RDFStoreError> {
        self.set_string(
            "import.rename-user-blank-nodes",
            format!("{setting:?}").as_str(),
        )?;
        Ok(self)
    }

    /// If true, all API calls are recorded in a script that
    /// the shell can replay later. later.
    /// The default value is false.
    pub fn api_log(self, on: bool) -> Result<Self, RDFStoreError> {
        if on {
            self.set_string("api-log", "on")?;
        } else {
            self.set_string("api-log", "off")?;
        }
        Ok(self)
    }

    /// Specifies the directory into which API logs will be written.
    /// Default is directory api-log within the configured server directory.
    pub fn api_log_directory(self, dir: &Path) -> Result<Self, RDFStoreError> {
        if dir.exists() {
            let x = self.api_log(true)?;
            x.set_string("api-log.directory", dir.to_str().unwrap())?;
            Ok(x)
        } else {
            tracing::error!(
                "Could not enable logging since directory does not exist: {}",
                dir.to_str().unwrap()
            );
            Ok(self)
        }
    }

    pub fn data_store_type(self, data_store_type: DataStoreType) -> Result<Self, RDFStoreError> {
        match data_store_type {
            DataStoreType::ParallelNN => self.set_string("type", "parallel-nn")?,
            DataStoreType::ParallelNW => self.set_string("type", "parallel-nw")?,
            DataStoreType::ParallelWW => self.set_string("type", "parallel-ww")?,
        }
        Ok(self)
    }
}

#[cfg(test)]
mod tests {
    #[test_log::test]
    fn test_set_param() {
        let params = crate::Parameters::empty().unwrap();
        params.set_string("key1", "value1").unwrap();
        let value = params.get_string("key1", "whatever").unwrap();
        assert_eq!(value, "value1");
    }
}