Skip to main content

rust_rocksdb/
env.rs

1use std::path::Path;
2use std::sync::Arc;
3
4use libc::{self, c_int};
5
6use crate::{Error, ffi, ffi_util::to_cpath};
7
8/// An Env is an interface used by the rocksdb implementation to access
9/// operating system functionality like the filesystem etc. Callers
10/// may wish to provide a custom Env object when opening a database to
11/// get fine gain control; e.g., to rate limit file system operations.
12///
13/// All Env implementations are safe for concurrent access from
14/// multiple threads without any external synchronization.
15///
16/// Note: currently, C API behinds C++ API for various settings.
17/// See also: `rocksdb/include/env.h`
18#[derive(Clone)]
19pub struct Env(pub(crate) Arc<EnvWrapper>);
20
21pub(crate) struct EnvWrapper {
22    pub(crate) inner: *mut ffi::rocksdb_env_t,
23}
24
25impl Drop for EnvWrapper {
26    fn drop(&mut self) {
27        unsafe {
28            ffi::rocksdb_env_destroy(self.inner);
29        }
30    }
31}
32
33impl Env {
34    /// Returns default env
35    pub fn new() -> Result<Self, Error> {
36        let env = unsafe { ffi::rocksdb_create_default_env() };
37        if env.is_null() {
38            Err(Error::new("Could not create mem env".to_owned()))
39        } else {
40            Ok(Self(Arc::new(EnvWrapper { inner: env })))
41        }
42    }
43
44    /// Returns a new environment that stores its data in memory and delegates
45    /// all non-file-storage tasks to base_env.
46    pub fn mem_env() -> Result<Self, Error> {
47        let env = unsafe { ffi::rocksdb_create_mem_env() };
48        if env.is_null() {
49            Err(Error::new("Could not create mem env".to_owned()))
50        } else {
51            Ok(Self(Arc::new(EnvWrapper { inner: env })))
52        }
53    }
54
55    /// Returns a new environment which wraps and takes ownership of the provided
56    /// raw environment.
57    ///
58    /// # Safety
59    ///
60    /// Ownership of `env` is transferred to the returned Env, which becomes
61    /// responsible for freeing it. The caller should forget the raw pointer
62    /// after this call.
63    ///
64    /// # When would I use this?
65    ///
66    /// RocksDB's C++ [Env](https://github.com/facebook/rocksdb/blob/main/include/rocksdb/env.h)
67    /// class provides many extension points for low-level database subsystems, such as file IO.
68    /// These subsystems aren't covered within the scope of the C interface or this crate,
69    /// but from_raw() may be used to hand a pre-instrumented Env to this crate for further use.
70    ///
71    pub unsafe fn from_raw(env: *mut ffi::rocksdb_env_t) -> Self {
72        Self(Arc::new(EnvWrapper { inner: env }))
73    }
74
75    /// Sets the number of background worker threads of a specific thread pool for this environment.
76    /// `LOW` is the default pool.
77    ///
78    /// Default: 1
79    pub fn set_background_threads(&mut self, num_threads: c_int) {
80        unsafe {
81            ffi::rocksdb_env_set_background_threads(self.0.inner, num_threads);
82        }
83    }
84
85    /// Sets the size of the high priority thread pool that can be used to
86    /// prevent compactions from stalling memtable flushes.
87    pub fn set_high_priority_background_threads(&mut self, n: c_int) {
88        unsafe {
89            ffi::rocksdb_env_set_high_priority_background_threads(self.0.inner, n);
90        }
91    }
92
93    /// Sets the size of the low priority thread pool that can be used to
94    /// prevent compactions from stalling memtable flushes.
95    pub fn set_low_priority_background_threads(&mut self, n: c_int) {
96        unsafe {
97            ffi::rocksdb_env_set_low_priority_background_threads(self.0.inner, n);
98        }
99    }
100
101    /// Sets the size of the bottom priority thread pool that can be used to
102    /// prevent compactions from stalling memtable flushes.
103    pub fn set_bottom_priority_background_threads(&mut self, n: c_int) {
104        unsafe {
105            ffi::rocksdb_env_set_bottom_priority_background_threads(self.0.inner, n);
106        }
107    }
108
109    /// Wait for all threads started by StartThread to terminate.
110    pub fn join_all_threads(&mut self) {
111        unsafe {
112            ffi::rocksdb_env_join_all_threads(self.0.inner);
113        }
114    }
115
116    /// Lowering IO priority for threads from the specified pool.
117    pub fn lower_thread_pool_io_priority(&mut self) {
118        unsafe {
119            ffi::rocksdb_env_lower_thread_pool_io_priority(self.0.inner);
120        }
121    }
122
123    /// Lowering IO priority for high priority thread pool.
124    pub fn lower_high_priority_thread_pool_io_priority(&mut self) {
125        unsafe {
126            ffi::rocksdb_env_lower_high_priority_thread_pool_io_priority(self.0.inner);
127        }
128    }
129
130    /// Lowering CPU priority for threads from the specified pool.
131    pub fn lower_thread_pool_cpu_priority(&mut self) {
132        unsafe {
133            ffi::rocksdb_env_lower_thread_pool_cpu_priority(self.0.inner);
134        }
135    }
136
137    /// Lowering CPU priority for high priority thread pool.
138    pub fn lower_high_priority_thread_pool_cpu_priority(&mut self) {
139        unsafe {
140            ffi::rocksdb_env_lower_high_priority_thread_pool_cpu_priority(self.0.inner);
141        }
142    }
143
144    /// Returns the current `background_threads` setting.
145    ///
146    /// See [`Self::set_background_threads`] for what this controls.
147    pub fn get_background_threads(&self) -> c_int {
148        unsafe { ffi::rocksdb_env_get_background_threads(self.0.inner) }
149    }
150
151    /// Returns the current `bottom_priority_background_threads` setting.
152    ///
153    /// See [`Self::set_bottom_priority_background_threads`] for what this controls.
154    pub fn get_bottom_priority_background_threads(&self) -> c_int {
155        unsafe { ffi::rocksdb_env_get_bottom_priority_background_threads(self.0.inner) }
156    }
157
158    /// Returns the current `high_priority_background_threads` setting.
159    ///
160    /// See [`Self::set_high_priority_background_threads`] for what this controls.
161    pub fn get_high_priority_background_threads(&self) -> c_int {
162        unsafe { ffi::rocksdb_env_get_high_priority_background_threads(self.0.inner) }
163    }
164
165    /// Returns the current `low_priority_background_threads` setting.
166    ///
167    /// See [`Self::set_low_priority_background_threads`] for what this controls.
168    pub fn get_low_priority_background_threads(&self) -> c_int {
169        unsafe { ffi::rocksdb_env_get_low_priority_background_threads(self.0.inner) }
170    }
171
172    /// Creates `path` through this environment, and returns `Ok` if it is
173    /// already there.
174    ///
175    /// This is `Env::CreateDirIfMissing`, one level only. The POSIX
176    /// implementation is a plain `mkdir`, so every parent has to exist
177    /// already. It is not the recursive `std::fs::create_dir_all`.
178    ///
179    /// # Errors
180    ///
181    /// The POSIX environment fails when a parent directory is missing, when
182    /// the process cannot write there, or when `path` exists and is not a
183    /// directory. [`Env::mem_env`] always succeeds.
184    pub fn create_dir_if_missing<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
185        let cpath = to_cpath(path)?;
186        unsafe {
187            ffi_try!(ffi::rocksdb_create_dir_if_missing(
188                self.0.inner,
189                cpath.as_ptr(),
190            ));
191        }
192        Ok(())
193    }
194}
195
196unsafe impl Send for EnvWrapper {}
197unsafe impl Sync for EnvWrapper {}
198
199/// Priority at which an IO operation is charged to the rate limiter set with
200/// [`Options::set_ratelimiter`](crate::Options::set_ratelimiter).
201///
202/// Mirrors `Env::IOPriority` from `rocksdb/include/env.h`.
203#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
204#[repr(i32)]
205pub enum IoPriority {
206    Low = 0,
207    Mid = 1,
208    High = 2,
209    User = 3,
210    /// Do not charge the rate limiter at all.
211    Total = 4,
212}
213
214impl IoPriority {
215    pub(crate) fn try_from_raw(raw: c_int) -> Option<Self> {
216        match raw {
217            0 => Some(Self::Low),
218            1 => Some(Self::Mid),
219            2 => Some(Self::High),
220            3 => Some(Self::User),
221            4 => Some(Self::Total),
222            _ => None,
223        }
224    }
225}