Debian Codegraph @

third_party/rust/rkv/src/backend/impl_safe/environment.rs

raw
1 // Copyright 2018-2019 Mozilla
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4 // this file except in compliance with the License. You may obtain a copy of the
5 // License at http://www.apache.org/licenses/LICENSE-2.0
6 // Unless required by applicable law or agreed to in writing, software distributed
7 // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8 // CONDITIONS OF ANY KIND, either express or implied. See the License for the
9 // specific language governing permissions and limitations under the License.
10
11 use std::{
12 borrow::Cow,
13 collections::HashMap,
14 fs,
15 ops::DerefMut,
16 path::{Path, PathBuf},
17 sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard},
18 };
19
20 use id_arena::Arena;
21 use log::warn;
22
23 use super::{
24 database::Database, DatabaseFlagsImpl, DatabaseImpl, EnvironmentFlagsImpl, ErrorImpl, InfoImpl,
25 RoTransactionImpl, RwTransactionImpl, StatImpl,
26 };
27 use crate::backend::common::RecoveryStrategy;
28 use crate::backend::traits::{BackendEnvironment, BackendEnvironmentBuilder};
29
30 const DEFAULT_DB_FILENAME: &str = "data.safe.bin";
31 const DEFAULT_CORRUPT_DB_EXTENSION: &str = "bin.corrupt";
32
33 type DatabaseArena = Arena<Database>;
34 type DatabaseNameMap = HashMap<Option<String>, DatabaseImpl>;
35
36 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
37 pub struct EnvironmentBuilderImpl {
38 flags: EnvironmentFlagsImpl,
39 max_readers: Option<usize>,
40 max_dbs: Option<usize>,
41 map_size: Option<usize>,
42 make_dir_if_needed: bool,
43 corruption_recovery_strategy: RecoveryStrategy,
44 }
45
46 impl<'b> BackendEnvironmentBuilder<'b> for EnvironmentBuilderImpl {
47 type Environment = EnvironmentImpl;
48 type Error = ErrorImpl;
49 type Flags = EnvironmentFlagsImpl;
50
51 fn new() -> EnvironmentBuilderImpl {
52 EnvironmentBuilderImpl {
53 flags: EnvironmentFlagsImpl::empty(),
54 max_readers: None,
55 max_dbs: None,
56 map_size: None,
57 make_dir_if_needed: false,
58 corruption_recovery_strategy: RecoveryStrategy::Error,
59 }
60 }
61
62 fn set_flags<T>(&mut self, flags: T) -> &mut Self
63 where
64 T: Into<Self::Flags>,
65 {
66 self.flags = flags.into();
67 self
68 }
69
70 fn set_max_readers(&mut self, max_readers: u32) -> &mut Self {
71 self.max_readers = Some(max_readers as usize);
72 self
73 }
74
75 fn set_max_dbs(&mut self, max_dbs: u32) -> &mut Self {
76 self.max_dbs = Some(max_dbs as usize);
77 self
78 }
79
80 fn set_map_size(&mut self, map_size: usize) -> &mut Self {
81 self.map_size = Some(map_size);
82 self
83 }
84
85 fn set_make_dir_if_needed(&mut self, make_dir_if_needed: bool) -> &mut Self {
86 self.make_dir_if_needed = make_dir_if_needed;
87 self
88 }
89
90 fn set_corruption_recovery_strategy(&mut self, strategy: RecoveryStrategy) -> &mut Self {
91 self.corruption_recovery_strategy = strategy;
92 self
93 }
94
95 fn open(&self, path: &Path) -> Result<Self::Environment, Self::Error> {
96 // Technically NO_SUB_DIR should change these checks here, but they're both currently
97 // unimplemented with this storage backend.
98 if !path.is_dir() {
99 if !self.make_dir_if_needed {
100 return Err(ErrorImpl::UnsuitableEnvironmentPath(path.into()));
101 }
102 fs::create_dir_all(path)?;
103 }
104 let mut env = EnvironmentImpl::new(
105 path,
106 self.flags,
107 self.max_readers,
108 self.max_dbs,
109 self.map_size,
110 )?;
111 env.read_from_disk(self.corruption_recovery_strategy)?;
112 Ok(env)
113 }
114 }
115
116 #[derive(Debug)]
117 pub(crate) struct EnvironmentDbs {
118 pub(crate) arena: DatabaseArena,
119 pub(crate) name_map: DatabaseNameMap,
120 }
121
122 #[derive(Debug)]
123 pub(crate) struct EnvironmentDbsRefMut<'a> {
124 pub(crate) arena: &'a mut DatabaseArena,
125 pub(crate) name_map: &'a mut DatabaseNameMap,
126 }
127
128 impl<'a> From<&'a mut EnvironmentDbs> for EnvironmentDbsRefMut<'a> {
129 fn from(dbs: &mut EnvironmentDbs) -> EnvironmentDbsRefMut {
130 EnvironmentDbsRefMut {
131 arena: &mut dbs.arena,
132 name_map: &mut dbs.name_map,
133 }
134 }
135 }
136
137 #[derive(Debug)]
138 pub struct EnvironmentImpl {
139 path: PathBuf,
140 max_dbs: usize,
141 dbs: RwLock<EnvironmentDbs>,
142 ro_txns: Arc<()>,
143 rw_txns: Arc<()>,
144 }
145
146 impl EnvironmentImpl {
147 fn serialize(&self) -> Result<Vec<u8>, ErrorImpl> {
148 let dbs = self.dbs.read().map_err(|_| ErrorImpl::EnvPoisonError)?;
149 let data: HashMap<_, _> = dbs
150 .name_map
151 .iter()
152 .map(|(name, id)| (name, &dbs.arena[id.0]))
153 .collect();
154 Ok(bincode::serialize(&data)?)
155 }
156
157 fn load(
158 path: &Path,
159 strategy: RecoveryStrategy,
160 ) -> Result<(DatabaseArena, DatabaseNameMap), ErrorImpl> {
161 let bytes = fs::read(path)?;
162
163 match Self::deserialize(&bytes) {
164 Ok((arena, name_map)) => Ok((arena, name_map)),
165 Err(err) => match strategy {
166 RecoveryStrategy::Error => Err(err),
167 RecoveryStrategy::Discard => Ok((DatabaseArena::new(), HashMap::new())),
168 RecoveryStrategy::Rename => {
169 let corrupted_path = path.with_extension(DEFAULT_CORRUPT_DB_EXTENSION);
170 fs::rename(path, corrupted_path)?;
171
172 Ok((DatabaseArena::new(), HashMap::new()))
173 }
174 },
175 }
176 }
177
178 fn deserialize(bytes: &[u8]) -> Result<(DatabaseArena, DatabaseNameMap), ErrorImpl> {
179 let mut arena = DatabaseArena::new();
180 let mut name_map = HashMap::new();
181 let data: HashMap<_, _> = bincode::deserialize(bytes)?;
182
183 for (name, db) in data {
184 name_map.insert(name, DatabaseImpl(arena.alloc(db)));
185 }
186 Ok((arena, name_map))
187 }
188 }
189
190 impl EnvironmentImpl {
191 pub(crate) fn new(
192 path: &Path,
193 flags: EnvironmentFlagsImpl,
194 max_readers: Option<usize>,
195 max_dbs: Option<usize>,
196 map_size: Option<usize>,
197 ) -> Result<EnvironmentImpl, ErrorImpl> {
198 if !flags.is_empty() {
199 warn!("Ignoring `flags={:?}`", flags);
200 }
201 if let Some(max_readers) = max_readers {
202 warn!("Ignoring `max_readers={}`", max_readers);
203 }
204 if let Some(map_size) = map_size {
205 warn!("Ignoring `map_size={}`", map_size);
206 }
207
208 Ok(EnvironmentImpl {
209 path: path.to_path_buf(),
210 max_dbs: max_dbs.unwrap_or(std::usize::MAX),
211 dbs: RwLock::new(EnvironmentDbs {
212 arena: DatabaseArena::new(),
213 name_map: HashMap::new(),
214 }),
215 ro_txns: Arc::new(()),
216 rw_txns: Arc::new(()),
217 })
218 }
219
220 pub(crate) fn read_from_disk(&mut self, strategy: RecoveryStrategy) -> Result<(), ErrorImpl> {
221 let mut path = Cow::from(&self.path);
222 if fs::metadata(&path)?.is_dir() {
223 path.to_mut().push(DEFAULT_DB_FILENAME);
224 };
225 if fs::metadata(&path).is_err() {
226 return Ok(());
227 };
228 let (arena, name_map) = Self::load(&path, strategy)?;
229 self.dbs = RwLock::new(EnvironmentDbs { arena, name_map });
230 Ok(())
231 }
232
233 pub(crate) fn write_to_disk(&self) -> Result<(), ErrorImpl> {
234 let mut path = Cow::from(&self.path);
235 if fs::metadata(&path)?.is_dir() {
236 path.to_mut().push(DEFAULT_DB_FILENAME);
237 };
238
239 // Write to a temp file first.
240 let tmp_path = path.with_extension("tmp");
241 fs::write(&tmp_path, self.serialize()?)?;
242
243 // Atomically move that file to the database file.
244 fs::rename(tmp_path, path)?;
245 Ok(())
246 }
247
248 pub(crate) fn dbs(&self) -> Result<RwLockReadGuard<EnvironmentDbs>, ErrorImpl> {
249 self.dbs.read().map_err(|_| ErrorImpl::EnvPoisonError)
250 }
251
252 pub(crate) fn dbs_mut(&self) -> Result<RwLockWriteGuard<EnvironmentDbs>, ErrorImpl> {
253 self.dbs.write().map_err(|_| ErrorImpl::EnvPoisonError)
254 }
255 }
256
257 impl<'e> BackendEnvironment<'e> for EnvironmentImpl {
258 type Database = DatabaseImpl;
259 type Error = ErrorImpl;
260 type Flags = DatabaseFlagsImpl;
261 type Info = InfoImpl;
262 type RoTransaction = RoTransactionImpl<'e>;
263 type RwTransaction = RwTransactionImpl<'e>;
264 type Stat = StatImpl;
265
266 fn get_dbs(&self) -> Result<Vec<Option<String>>, Self::Error> {
267 let dbs = self.dbs.read().map_err(|_| ErrorImpl::EnvPoisonError)?;
268 Ok(dbs.name_map.keys().map(|key| key.to_owned()).collect())
269 }
270
271 fn open_db(&self, name: Option<&str>) -> Result<Self::Database, Self::Error> {
272 if Arc::strong_count(&self.ro_txns) > 1 {
273 return Err(ErrorImpl::DbsIllegalOpen);
274 }
275 // TOOD: don't reallocate `name`.
276 let key = name.map(String::from);
277 let dbs = self.dbs.read().map_err(|_| ErrorImpl::EnvPoisonError)?;
278 let db = dbs.name_map.get(&key).ok_or(ErrorImpl::DbNotFoundError)?;
279 Ok(*db)
280 }
281
282 fn create_db(
283 &self,
284 name: Option<&str>,
285 flags: Self::Flags,
286 ) -> Result<Self::Database, Self::Error> {
287 if Arc::strong_count(&self.ro_txns) > 1 {
288 return Err(ErrorImpl::DbsIllegalOpen);
289 }
290 // TOOD: don't reallocate `name`.
291 let key = name.map(String::from);
292 let mut dbs = self.dbs.write().map_err(|_| ErrorImpl::EnvPoisonError)?;
293 if dbs.name_map.keys().filter_map(|k| k.as_ref()).count() >= self.max_dbs && name.is_some()
294 {
295 return Err(ErrorImpl::DbsFull);
296 }
297 let parts = EnvironmentDbsRefMut::from(dbs.deref_mut());
298 let arena = parts.arena;
299 let name_map = parts.name_map;
300 let id = name_map
301 .entry(key)
302 .or_insert_with(|| DatabaseImpl(arena.alloc(Database::new(Some(flags), None))));
303 Ok(*id)
304 }
305
306 fn begin_ro_txn(&'e self) -> Result<Self::RoTransaction, Self::Error> {
307 RoTransactionImpl::new(self, self.ro_txns.clone())
308 }
309
310 fn begin_rw_txn(&'e self) -> Result<Self::RwTransaction, Self::Error> {
311 RwTransactionImpl::new(self, self.rw_txns.clone())
312 }
313
314 fn sync(&self, force: bool) -> Result<(), Self::Error> {
315 warn!("Ignoring `force={}`", force);
316 self.write_to_disk()
317 }
318
319 fn stat(&self) -> Result<Self::Stat, Self::Error> {
320 Ok(StatImpl)
321 }
322
323 fn info(&self) -> Result<Self::Info, Self::Error> {
324 Ok(InfoImpl)
325 }
326
327 fn freelist(&self) -> Result<usize, Self::Error> {
328 unimplemented!()
329 }
330
331 fn load_ratio(&self) -> Result<Option<f32>, Self::Error> {
332 warn!("`load_ratio()` is irrelevant for this storage backend.");
333 Ok(None)
334 }
335
336 fn set_map_size(&self, size: usize) -> Result<(), Self::Error> {
337 warn!(
338 "`set_map_size({})` is ignored by this storage backend.",
339 size
340 );
341 Ok(())
342 }
343
344 fn get_files_on_disk(&self) -> Vec<PathBuf> {
345 // Technically NO_SUB_DIR and NO_LOCK should change this output, but
346 // they're both currently unimplemented with this storage backend.
347 let mut db_filename = self.path.clone();
348 db_filename.push(DEFAULT_DB_FILENAME);
349 vec![db_filename]
350 }
351 }