Debian Codegraph @

third_party/rust/rkv/src/manager.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 collections::{btree_map::Entry, BTreeMap},
13 os::raw::c_uint,
14 path::{Path, PathBuf},
15 result,
16 sync::{Arc, RwLock},
17 };
18
19 use lazy_static::lazy_static;
20
21 #[cfg(feature = "lmdb")]
22 use crate::backend::LmdbEnvironment;
23 use crate::{
24 backend::{BackendEnvironment, BackendEnvironmentBuilder, SafeModeEnvironment},
25 error::{CloseError, StoreError},
26 helpers::canonicalize_path,
27 store::CloseOptions,
28 Rkv,
29 };
30
31 type Result<T> = result::Result<T, StoreError>;
32 type CloseResult<T> = result::Result<T, CloseError>;
33 type SharedRkv<E> = Arc<RwLock<Rkv<E>>>;
34
35 #[cfg(feature = "lmdb")]
36 lazy_static! {
37 static ref MANAGER_LMDB: RwLock<Manager<LmdbEnvironment>> = RwLock::new(Manager::new());
38 }
39
40 lazy_static! {
41 static ref MANAGER_SAFE_MODE: RwLock<Manager<SafeModeEnvironment>> =
42 RwLock::new(Manager::new());
43 }
44
45 /// A process is only permitted to have one open handle to each Rkv environment. This
46 /// manager exists to enforce that constraint: don't open environments directly.
47 ///
48 /// By default, path canonicalization is enabled for identifying RKV instances. This
49 /// is true by default, because it helps enforce the constraints guaranteed by
50 /// this manager. However, path canonicalization might crash in some fringe
51 /// circumstances, so the `no-canonicalize-path` feature offers the possibility of
52 /// disabling it. See: https://bugzilla.mozilla.org/show_bug.cgi?id=1531887
53 ///
54 /// When path canonicalization is disabled, you *must* ensure an RKV environment is
55 /// always created or retrieved with the same path.
56 pub struct Manager<E> {
57 environments: BTreeMap<PathBuf, SharedRkv<E>>,
58 }
59
60 impl<'e, E> Manager<E>
61 where
62 E: BackendEnvironment<'e>,
63 {
64 fn new() -> Manager<E> {
65 Manager {
66 environments: Default::default(),
67 }
68 }
69
70 /// Return the open env at `path`, returning `None` if it has not already been opened.
71 pub fn get<'p, P>(&self, path: P) -> Result<Option<SharedRkv<E>>>
72 where
73 P: Into<&'p Path>,
74 {
75 let canonical = if cfg!(feature = "no-canonicalize-path") {
76 path.into().to_path_buf()
77 } else {
78 canonicalize_path(path)?
79 };
80 Ok(self.environments.get(&canonical).cloned())
81 }
82
83 /// Return the open env at `path`, or create it by calling `f`.
84 pub fn get_or_create<'p, F, P>(&mut self, path: P, f: F) -> Result<SharedRkv<E>>
85 where
86 F: FnOnce(&Path) -> Result<Rkv<E>>,
87 P: Into<&'p Path>,
88 {
89 let canonical = if cfg!(feature = "no-canonicalize-path") {
90 path.into().to_path_buf()
91 } else {
92 canonicalize_path(path)?
93 };
94 Ok(match self.environments.entry(canonical) {
95 Entry::Occupied(e) => e.get().clone(),
96 Entry::Vacant(e) => {
97 let k = Arc::new(RwLock::new(f(e.key().as_path())?));
98 e.insert(k).clone()
99 }
100 })
101 }
102
103 /// Return the open env at `path` with `capacity`, or create it by calling `f`.
104 pub fn get_or_create_with_capacity<'p, F, P>(
105 &mut self,
106 path: P,
107 capacity: c_uint,
108 f: F,
109 ) -> Result<SharedRkv<E>>
110 where
111 F: FnOnce(&Path, c_uint) -> Result<Rkv<E>>,
112 P: Into<&'p Path>,
113 {
114 let canonical = if cfg!(feature = "no-canonicalize-path") {
115 path.into().to_path_buf()
116 } else {
117 canonicalize_path(path)?
118 };
119 Ok(match self.environments.entry(canonical) {
120 Entry::Occupied(e) => e.get().clone(),
121 Entry::Vacant(e) => {
122 let k = Arc::new(RwLock::new(f(e.key().as_path(), capacity)?));
123 e.insert(k).clone()
124 }
125 })
126 }
127
128 /// Return a new Rkv environment from the builder, or create it by calling `f`.
129 pub fn get_or_create_from_builder<'p, F, P, B>(
130 &mut self,
131 path: P,
132 builder: B,
133 f: F,
134 ) -> Result<SharedRkv<E>>
135 where
136 F: FnOnce(&Path, B) -> Result<Rkv<E>>,
137 P: Into<&'p Path>,
138 B: BackendEnvironmentBuilder<'e, Environment = E>,
139 {
140 let canonical = if cfg!(feature = "no-canonicalize-path") {
141 path.into().to_path_buf()
142 } else {
143 canonicalize_path(path)?
144 };
145 Ok(match self.environments.entry(canonical) {
146 Entry::Occupied(e) => e.get().clone(),
147 Entry::Vacant(e) => {
148 let k = Arc::new(RwLock::new(f(e.key().as_path(), builder)?));
149 e.insert(k).clone()
150 }
151 })
152 }
153
154 /// Tries to close the specified environment.
155 /// Returns an error when other users of this environment still exist.
156 pub fn try_close<'p, P>(&mut self, path: P, options: CloseOptions) -> CloseResult<()>
157 where
158 P: Into<&'p Path>,
159 {
160 let canonical = if cfg!(feature = "no-canonicalize-path") {
161 path.into().to_path_buf()
162 } else {
163 canonicalize_path(path)?
164 };
165 match self.environments.entry(canonical) {
166 Entry::Vacant(_) => Ok(()),
167 Entry::Occupied(e) if Arc::strong_count(e.get()) > 1 => {
168 Err(CloseError::EnvironmentStillOpen)
169 }
170 Entry::Occupied(e) => {
171 let env = Arc::try_unwrap(e.remove())
172 .map_err(|_| CloseError::UnknownEnvironmentStillOpen)?;
173 env.into_inner()?.close(options)?;
174 Ok(())
175 }
176 }
177 }
178 }
179
180 #[cfg(feature = "lmdb")]
181 impl Manager<LmdbEnvironment> {
182 pub fn singleton() -> &'static RwLock<Manager<LmdbEnvironment>> {
183 &MANAGER_LMDB
184 }
185 }
186
187 impl Manager<SafeModeEnvironment> {
188 pub fn singleton() -> &'static RwLock<Manager<SafeModeEnvironment>> {
189 &MANAGER_SAFE_MODE
190 }
191 }
192
193 #[cfg(test)]
194 mod tests {
195 use super::*;
196 use crate::*;
197
198 use std::fs;
199
200 use tempfile::Builder;
201
202 #[cfg(feature = "lmdb")]
203 use backend::Lmdb;
204
205 /// Test that one can mutate managed Rkv instances in surprising ways.
206 #[cfg(feature = "lmdb")]
207 #[test]
208 fn test_mutate_managed_rkv() {
209 let mut manager = Manager::<LmdbEnvironment>::new();
210
211 let root1 = Builder::new()
212 .prefix("test_mutate_managed_rkv_1")
213 .tempdir()
214 .expect("tempdir");
215 fs::create_dir_all(root1.path()).expect("dir created");
216 let path1 = root1.path();
217 let arc = manager
218 .get_or_create(path1, Rkv::new::<Lmdb>)
219 .expect("created");
220
221 // Arc<RwLock<>> has interior mutability, so we can replace arc's Rkv instance with a new
222 // instance that has a different path.
223 let root2 = Builder::new()
224 .prefix("test_mutate_managed_rkv_2")
225 .tempdir()
226 .expect("tempdir");
227 fs::create_dir_all(root2.path()).expect("dir created");
228 let path2 = root2.path();
229 {
230 let mut rkv = arc.write().expect("guard");
231 let rkv2 = Rkv::new::<Lmdb>(path2).expect("Rkv");
232 *rkv = rkv2;
233 }
234
235 // Arc now has a different internal Rkv with path2, but it's still mapped to path1 in
236 // manager, so its pointer is equal to a new Arc for path1.
237 let path1_arc = manager.get(path1).expect("success").expect("existed");
238 assert!(Arc::ptr_eq(&path1_arc, &arc));
239
240 // Meanwhile, a new Arc for path2 has a different pointer, even though its Rkv's path is
241 // the same as arc's current path.
242 let path2_arc = manager
243 .get_or_create(path2, Rkv::new::<Lmdb>)
244 .expect("success");
245 assert!(!Arc::ptr_eq(&path2_arc, &arc));
246 }
247 }