| 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 |
fs, |
| 13 |
os::raw::c_uint, |
| 14 |
path::{Path, PathBuf}, |
| 15 |
}; |
| 16 |
|
| 17 |
#[cfg(any(feature = "db-dup-sort", feature = "db-int-key"))] |
| 18 |
use crate::backend::{BackendDatabaseFlags, DatabaseFlags}; |
| 19 |
use crate::{ |
| 20 |
backend::{ |
| 21 |
BackendEnvironment, BackendEnvironmentBuilder, BackendRoCursorTransaction, |
| 22 |
BackendRwCursorTransaction, SafeModeError, |
| 23 |
}, |
| 24 |
error::{CloseError, StoreError}, |
| 25 |
readwrite::{Reader, Writer}, |
| 26 |
store::{single::SingleStore, CloseOptions, Options as StoreOptions}, |
| 27 |
}; |
| 28 |
|
| 29 |
#[cfg(feature = "db-dup-sort")] |
| 30 |
use crate::store::multi::MultiStore; |
| 31 |
|
| 32 |
#[cfg(feature = "db-int-key")] |
| 33 |
use crate::store::integer::IntegerStore; |
| 34 |
#[cfg(feature = "db-int-key")] |
| 35 |
use crate::store::keys::PrimitiveInt; |
| 36 |
|
| 37 |
#[cfg(all(feature = "db-dup-sort", feature = "db-int-key"))] |
| 38 |
use crate::store::integermulti::MultiIntegerStore; |
| 39 |
|
| 40 |
pub static DEFAULT_MAX_DBS: c_uint = 5; |
| 41 |
|
| 42 |
/// Wrapper around an `Environment` (e.g. such as an `LMDB` or `SafeMode` environment). |
| 43 |
#[derive(Debug)] |
| 44 |
pub struct Rkv<E> { |
| 45 |
_path: PathBuf, |
| 46 |
env: E, |
| 47 |
} |
| 48 |
|
| 49 |
/// Static methods. |
| 50 |
impl<'e, E> Rkv<E> |
| 51 |
where |
| 52 |
E: BackendEnvironment<'e>, |
| 53 |
{ |
| 54 |
pub fn environment_builder<B>() -> B |
| 55 |
where |
| 56 |
B: BackendEnvironmentBuilder<'e, Environment = E>, |
| 57 |
{ |
| 58 |
B::new() |
| 59 |
} |
| 60 |
|
| 61 |
/// Return a new Rkv environment that supports up to `DEFAULT_MAX_DBS` open databases. |
| 62 |
#[allow(clippy::new_ret_no_self)] |
| 63 |
pub fn new<B>(path: &Path) -> Result<Rkv<E>, StoreError> |
| 64 |
where |
| 65 |
B: BackendEnvironmentBuilder<'e, Environment = E>, |
| 66 |
{ |
| 67 |
Rkv::with_capacity::<B>(path, DEFAULT_MAX_DBS) |
| 68 |
} |
| 69 |
|
| 70 |
/// Return a new Rkv environment that supports the specified number of open databases. |
| 71 |
pub fn with_capacity<B>(path: &Path, max_dbs: c_uint) -> Result<Rkv<E>, StoreError> |
| 72 |
where |
| 73 |
B: BackendEnvironmentBuilder<'e, Environment = E>, |
| 74 |
{ |
| 75 |
let mut builder = B::new(); |
| 76 |
builder.set_max_dbs(max_dbs); |
| 77 |
|
| 78 |
// Future: set flags, maximum size, etc. here if necessary. |
| 79 |
Rkv::from_builder(path, builder) |
| 80 |
} |
| 81 |
|
| 82 |
/// Return a new Rkv environment from the provided builder. |
| 83 |
pub fn from_builder<B>(path: &Path, builder: B) -> Result<Rkv<E>, StoreError> |
| 84 |
where |
| 85 |
B: BackendEnvironmentBuilder<'e, Environment = E>, |
| 86 |
{ |
| 87 |
Ok(Rkv { |
| 88 |
_path: path.into(), |
| 89 |
env: builder.open(path).map_err(|e| e.into())?, |
| 90 |
}) |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
/// Store creation methods. |
| 95 |
impl<'e, E> Rkv<E> |
| 96 |
where |
| 97 |
E: BackendEnvironment<'e>, |
| 98 |
{ |
| 99 |
/// Return all created databases. |
| 100 |
pub fn get_dbs(&self) -> Result<Vec<Option<String>>, StoreError> { |
| 101 |
self.env.get_dbs().map_err(|e| e.into()) |
| 102 |
} |
| 103 |
|
| 104 |
/// Create or Open an existing database in (&[u8] -> Single Value) mode. |
| 105 |
/// Note: that create=true cannot be called concurrently with other operations so if |
| 106 |
/// you are sure that the database exists, call this with create=false. |
| 107 |
pub fn open_single<'s, T>( |
| 108 |
&self, |
| 109 |
name: T, |
| 110 |
opts: StoreOptions<E::Flags>, |
| 111 |
) -> Result<SingleStore<E::Database>, StoreError> |
| 112 |
where |
| 113 |
T: Into<Option<&'s str>>, |
| 114 |
{ |
| 115 |
self.open(name, opts).map(SingleStore::new) |
| 116 |
} |
| 117 |
|
| 118 |
/// Create or Open an existing database in (Integer -> Single Value) mode. |
| 119 |
/// Note: that create=true cannot be called concurrently with other operations so if |
| 120 |
/// you are sure that the database exists, call this with create=false. |
| 121 |
#[cfg(feature = "db-int-key")] |
| 122 |
pub fn open_integer<'s, T, K>( |
| 123 |
&self, |
| 124 |
name: T, |
| 125 |
mut opts: StoreOptions<E::Flags>, |
| 126 |
) -> Result<IntegerStore<E::Database, K>, StoreError> |
| 127 |
where |
| 128 |
K: PrimitiveInt, |
| 129 |
T: Into<Option<&'s str>>, |
| 130 |
{ |
| 131 |
opts.flags.set(DatabaseFlags::INTEGER_KEY, true); |
| 132 |
self.open(name, opts).map(IntegerStore::new) |
| 133 |
} |
| 134 |
|
| 135 |
/// Create or Open an existing database in (&[u8] -> Multiple Values) mode. |
| 136 |
/// Note: that create=true cannot be called concurrently with other operations so if |
| 137 |
/// you are sure that the database exists, call this with create=false. |
| 138 |
#[cfg(feature = "db-dup-sort")] |
| 139 |
pub fn open_multi<'s, T>( |
| 140 |
&self, |
| 141 |
name: T, |
| 142 |
mut opts: StoreOptions<E::Flags>, |
| 143 |
) -> Result<MultiStore<E::Database>, StoreError> |
| 144 |
where |
| 145 |
T: Into<Option<&'s str>>, |
| 146 |
{ |
| 147 |
opts.flags.set(DatabaseFlags::DUP_SORT, true); |
| 148 |
self.open(name, opts).map(MultiStore::new) |
| 149 |
} |
| 150 |
|
| 151 |
/// Create or Open an existing database in (Integer -> Multiple Values) mode. |
| 152 |
/// Note: that create=true cannot be called concurrently with other operations so if |
| 153 |
/// you are sure that the database exists, call this with create=false. |
| 154 |
#[cfg(all(feature = "db-dup-sort", feature = "db-int-key"))] |
| 155 |
pub fn open_multi_integer<'s, T, K>( |
| 156 |
&self, |
| 157 |
name: T, |
| 158 |
mut opts: StoreOptions<E::Flags>, |
| 159 |
) -> Result<MultiIntegerStore<E::Database, K>, StoreError> |
| 160 |
where |
| 161 |
K: PrimitiveInt, |
| 162 |
T: Into<Option<&'s str>>, |
| 163 |
{ |
| 164 |
opts.flags.set(DatabaseFlags::INTEGER_KEY, true); |
| 165 |
opts.flags.set(DatabaseFlags::DUP_SORT, true); |
| 166 |
self.open(name, opts).map(MultiIntegerStore::new) |
| 167 |
} |
| 168 |
|
| 169 |
fn open<'s, T>(&self, name: T, opts: StoreOptions<E::Flags>) -> Result<E::Database, StoreError> |
| 170 |
where |
| 171 |
T: Into<Option<&'s str>>, |
| 172 |
{ |
| 173 |
if opts.create { |
| 174 |
self.env |
| 175 |
.create_db(name.into(), opts.flags) |
| 176 |
.map_err(|e| match e.into() { |
| 177 |
#[cfg(feature = "lmdb")] |
| 178 |
StoreError::LmdbError(lmdb::Error::BadRslot) => { |
| 179 |
StoreError::open_during_transaction() |
| 180 |
} |
| 181 |
StoreError::SafeModeError(SafeModeError::DbsIllegalOpen) => { |
| 182 |
StoreError::open_during_transaction() |
| 183 |
} |
| 184 |
e => e, |
| 185 |
}) |
| 186 |
} else { |
| 187 |
self.env.open_db(name.into()).map_err(|e| match e.into() { |
| 188 |
#[cfg(feature = "lmdb")] |
| 189 |
StoreError::LmdbError(lmdb::Error::BadRslot) => { |
| 190 |
StoreError::open_during_transaction() |
| 191 |
} |
| 192 |
StoreError::SafeModeError(SafeModeError::DbsIllegalOpen) => { |
| 193 |
StoreError::open_during_transaction() |
| 194 |
} |
| 195 |
e => e, |
| 196 |
}) |
| 197 |
} |
| 198 |
} |
| 199 |
} |
| 200 |
|
| 201 |
/// Read and write accessors. |
| 202 |
impl<'e, E> Rkv<E> |
| 203 |
where |
| 204 |
E: BackendEnvironment<'e>, |
| 205 |
{ |
| 206 |
/// Create a read transaction. There can be multiple concurrent readers for an |
| 207 |
/// environment, up to the maximum specified by LMDB (default 126), and you can open |
| 208 |
/// readers while a write transaction is active. |
| 209 |
pub fn read<T>(&'e self) -> Result<Reader<T>, StoreError> |
| 210 |
where |
| 211 |
E: BackendEnvironment<'e, RoTransaction = T>, |
| 212 |
T: BackendRoCursorTransaction<'e, Database = E::Database>, |
| 213 |
{ |
| 214 |
Ok(Reader::new(self.env.begin_ro_txn().map_err(|e| e.into())?)) |
| 215 |
} |
| 216 |
|
| 217 |
/// Create a write transaction. There can be only one write transaction active at any |
| 218 |
/// given time, so trying to create a second one will block until the first is |
| 219 |
/// committed or aborted. |
| 220 |
pub fn write<T>(&'e self) -> Result<Writer<T>, StoreError> |
| 221 |
where |
| 222 |
E: BackendEnvironment<'e, RwTransaction = T>, |
| 223 |
T: BackendRwCursorTransaction<'e, Database = E::Database>, |
| 224 |
{ |
| 225 |
Ok(Writer::new(self.env.begin_rw_txn().map_err(|e| e.into())?)) |
| 226 |
} |
| 227 |
} |
| 228 |
|
| 229 |
/// Other environment methods. |
| 230 |
impl<'e, E> Rkv<E> |
| 231 |
where |
| 232 |
E: BackendEnvironment<'e>, |
| 233 |
{ |
| 234 |
/// Flush the data buffers to disk. This call is only useful, when the environment was |
| 235 |
/// open with either `NO_SYNC`, `NO_META_SYNC` or `MAP_ASYNC` (see below). The call is |
| 236 |
/// not valid if the environment was opened with `READ_ONLY`. |
| 237 |
/// |
| 238 |
/// Data is always written to disk when `transaction.commit()` is called, but the |
| 239 |
/// operating system may keep it buffered. LMDB always flushes the OS buffers upon |
| 240 |
/// commit as well, unless the environment was opened with `NO_SYNC` or in part |
| 241 |
/// `NO_META_SYNC`. |
| 242 |
/// |
| 243 |
/// `force`: if true, force a synchronous flush. Otherwise if the environment has the |
| 244 |
/// `NO_SYNC` flag set the flushes will be omitted, and with `MAP_ASYNC` they will |
| 245 |
/// be asynchronous. |
| 246 |
pub fn sync(&self, force: bool) -> Result<(), StoreError> { |
| 247 |
self.env.sync(force).map_err(|e| e.into()) |
| 248 |
} |
| 249 |
|
| 250 |
/// Retrieve statistics about this environment. |
| 251 |
/// |
| 252 |
/// It includes: |
| 253 |
/// * Page size in bytes |
| 254 |
/// * B-tree depth |
| 255 |
/// * Number of internal (non-leaf) pages |
| 256 |
/// * Number of leaf pages |
| 257 |
/// * Number of overflow pages |
| 258 |
/// * Number of data entries |
| 259 |
pub fn stat(&self) -> Result<E::Stat, StoreError> { |
| 260 |
self.env.stat().map_err(|e| e.into()) |
| 261 |
} |
| 262 |
|
| 263 |
/// Retrieve information about this environment. |
| 264 |
/// |
| 265 |
/// It includes: |
| 266 |
/// * Map size in bytes |
| 267 |
/// * The last used page number |
| 268 |
/// * The last transaction ID |
| 269 |
/// * Max number of readers allowed |
| 270 |
/// * Number of readers in use |
| 271 |
pub fn info(&self) -> Result<E::Info, StoreError> { |
| 272 |
self.env.info().map_err(|e| e.into()) |
| 273 |
} |
| 274 |
|
| 275 |
/// Retrieve the load ratio (# of used pages / total pages) about this environment. |
| 276 |
/// |
| 277 |
/// With the formular: (last_page_no - freelist_pages) / total_pages. |
| 278 |
/// A value of `None` means that the backend doesn't ever need to be resized. |
| 279 |
pub fn load_ratio(&self) -> Result<Option<f32>, StoreError> { |
| 280 |
self.env.load_ratio().map_err(|e| e.into()) |
| 281 |
} |
| 282 |
|
| 283 |
/// Sets the size of the memory map to use for the environment. |
| 284 |
/// |
| 285 |
/// This can be used to resize the map when the environment is already open. You can |
| 286 |
/// also use `Rkv::environment_builder()` to set the map size during the `Rkv` |
| 287 |
/// initialization. |
| 288 |
/// |
| 289 |
/// Note: |
| 290 |
/// |
| 291 |
/// * No active transactions allowed when performing resizing in this process. It's up |
| 292 |
/// to the consumer to enforce that. |
| 293 |
/// |
| 294 |
/// * The size should be a multiple of the OS page size. Any attempt to set a size |
| 295 |
/// smaller than the space already consumed by the environment will be silently |
| 296 |
/// changed to the current size of the used space. |
| 297 |
/// |
| 298 |
/// * In the multi-process case, once a process resizes the map, other processes need |
| 299 |
/// to either re-open the environment, or call set_map_size with size 0 to update |
| 300 |
/// the environment. Otherwise, new transaction creation will fail with |
| 301 |
/// `LmdbError::MapResized`. |
| 302 |
pub fn set_map_size(&self, size: usize) -> Result<(), StoreError> { |
| 303 |
self.env.set_map_size(size).map_err(Into::into) |
| 304 |
} |
| 305 |
|
| 306 |
/// Closes this environment and optionally deletes all its files from disk. Doesn't |
| 307 |
/// delete the folder used when opening the environment. |
| 308 |
pub fn close(self, options: CloseOptions) -> Result<(), CloseError> { |
| 309 |
let files = self.env.get_files_on_disk(); |
| 310 |
drop(self); |
| 311 |
|
| 312 |
if options.delete { |
| 313 |
for file in files { |
| 314 |
fs::remove_file(file)?; |
| 315 |
} |
| 316 |
} |
| 317 |
|
| 318 |
Ok(()) |
| 319 |
} |
| 320 |
} |