1use crate::{
2 database::Database,
3 error::{mdbx_result, Error, Result},
4 flags::EnvironmentFlags,
5 transaction::{RO, RW},
6 txn_manager::{TxnManager, TxnManagerMessage, TxnPtr},
7 txn_pool::ReadTxnPool,
8 Mode, SyncMode, Transaction, TransactionKind,
9};
10use byteorder::{ByteOrder, NativeEndian};
11use mem::size_of;
12use std::{
13 ffi::CString,
14 fmt::{self, Debug},
15 mem,
16 ops::{Bound, RangeBounds},
17 path::Path,
18 ptr,
19 sync::{mpsc::sync_channel, Arc},
20 thread::sleep,
21 time::Duration,
22};
23use tracing::warn;
24
25#[cfg(feature = "read-tx-timeouts")]
27const DEFAULT_MAX_READ_TRANSACTION_DURATION: Duration = Duration::from_secs(5 * 60);
28
29#[derive(Clone)]
34pub struct Environment {
35 inner: Arc<EnvironmentInner>,
36}
37
38impl Environment {
39 pub fn builder() -> EnvironmentBuilder {
41 EnvironmentBuilder {
42 flags: EnvironmentFlags::default(),
43 max_readers: None,
44 max_dbs: None,
45 sync_bytes: None,
46 sync_period: None,
47 rp_augment_limit: None,
48 loose_limit: None,
49 dp_reserve_limit: None,
50 txn_dp_limit: None,
51 spill_max_denominator: None,
52 spill_min_denominator: None,
53 geometry: None,
54 log_level: None,
55 kind: Default::default(),
56 handle_slow_readers: None,
57 #[cfg(feature = "read-tx-timeouts")]
58 max_read_transaction_duration: None,
59 }
60 }
61
62 #[inline]
64 pub fn is_write_map(&self) -> bool {
65 self.inner.env_kind.is_write_map()
66 }
67
68 #[inline]
70 pub fn env_kind(&self) -> EnvironmentKind {
71 self.inner.env_kind
72 }
73
74 #[inline]
76 pub fn is_read_write(&self) -> Result<bool> {
77 Ok(!self.is_read_only()?)
78 }
79
80 #[inline]
82 pub fn is_read_only(&self) -> Result<bool> {
83 Ok(matches!(self.info()?.mode(), Mode::ReadOnly))
84 }
85
86 #[inline]
88 pub(crate) fn txn_manager(&self) -> &TxnManager {
89 &self.inner.txn_manager
90 }
91
92 #[cfg(feature = "read-tx-timeouts")]
94 pub fn timed_out_not_aborted_transactions(&self) -> usize {
95 self.inner.txn_manager.timed_out_not_aborted_read_transactions().unwrap_or(0)
96 }
97
98 #[inline]
103 pub fn begin_ro_txn(&self) -> Result<Transaction<RO>> {
104 if let Some(txn_ptr) = self.inner.ro_txn_pool.pop() {
105 return Ok(Transaction::new_from_ptr(self.clone(), txn_ptr));
106 }
107 Transaction::new(self.clone())
108 }
109
110 #[inline]
112 pub(crate) fn ro_txn_pool(&self) -> &ReadTxnPool {
113 &self.inner.ro_txn_pool
114 }
115
116 pub fn begin_rw_txn(&self) -> Result<Transaction<RW>> {
119 let mut warned = false;
120 let txn = loop {
121 let (tx, rx) = sync_channel(0);
122 self.txn_manager().send_message(TxnManagerMessage::Begin {
123 parent: TxnPtr(ptr::null_mut()),
124 flags: RW::OPEN_FLAGS,
125 sender: tx,
126 });
127 let res = rx.recv().unwrap();
128 if matches!(&res, Err(Error::Busy)) {
129 if !warned {
130 warned = true;
131 warn!(target: "libmdbx", "Process stalled, awaiting read-write transaction lock.");
132 }
133 sleep(Duration::from_millis(250));
134 continue
135 }
136
137 break res
138 }?;
139 Ok(Transaction::new_from_ptr(self.clone(), txn.0))
140 }
141
142 #[inline]
147 pub(crate) fn env_ptr(&self) -> *mut ffi::MDBX_env {
148 self.inner.env
149 }
150
151 #[inline]
157 #[doc(hidden)]
158 pub fn with_raw_env_ptr<F, T>(&self, f: F) -> T
159 where
160 F: FnOnce(*mut ffi::MDBX_env) -> T,
161 {
162 f(self.env_ptr())
163 }
164
165 pub fn sync(&self, force: bool) -> Result<bool> {
167 mdbx_result(unsafe { ffi::mdbx_env_sync_ex(self.env_ptr(), force, false) })
168 }
169
170 pub fn stat(&self) -> Result<Stat> {
172 unsafe {
173 let mut stat = Stat::new();
174 mdbx_result(ffi::mdbx_env_stat_ex(
175 self.env_ptr(),
176 ptr::null(),
177 stat.mdbx_stat(),
178 size_of::<Stat>(),
179 ))?;
180 Ok(stat)
181 }
182 }
183
184 pub fn info(&self) -> Result<Info> {
186 unsafe {
187 let mut info = Info(mem::zeroed());
188 mdbx_result(ffi::mdbx_env_info_ex(
189 self.env_ptr(),
190 ptr::null(),
191 &mut info.0,
192 size_of::<Info>(),
193 ))?;
194 Ok(info)
195 }
196 }
197
198 pub fn freelist(&self) -> Result<usize> {
224 let mut freelist: usize = 0;
225 let txn = self.begin_ro_txn()?;
226 let db = Database::freelist_db();
227 let cursor = txn.cursor(db.dbi())?;
228
229 for result in cursor.iter_slices() {
230 let (_key, value) = result?;
231 if value.len() < size_of::<u32>() {
232 return Err(Error::Corrupted)
233 }
234 let s = &value[..size_of::<u32>()];
235 freelist += NativeEndian::read_u32(s) as usize;
236 }
237
238 Ok(freelist)
239 }
240
241 pub fn reader_check(&self) -> Result<bool> {
247 let mut dead = 0;
248 let recovered = mdbx_result(unsafe { ffi::mdbx_reader_check(self.env_ptr(), &mut dead) })?;
250 Ok(recovered || dead > 0)
251 }
252}
253
254struct EnvironmentInner {
259 env: *mut ffi::MDBX_env,
263 env_kind: EnvironmentKind,
265 txn_manager: TxnManager,
267 ro_txn_pool: ReadTxnPool,
269}
270
271impl Drop for EnvironmentInner {
272 fn drop(&mut self) {
273 #[cfg(feature = "read-tx-timeouts")]
274 self.txn_manager.stop_read_transaction_monitor();
275
276 self.ro_txn_pool.drain();
278
279 unsafe {
281 ffi::mdbx_env_close_ex(self.env, false);
282 }
283 }
284}
285
286unsafe impl Send for EnvironmentInner {}
289unsafe impl Sync for EnvironmentInner {}
290
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
295pub enum EnvironmentKind {
296 #[default]
298 Default,
299 WriteMap,
310}
311
312impl EnvironmentKind {
313 #[inline]
315 pub const fn is_write_map(&self) -> bool {
316 matches!(self, Self::WriteMap)
317 }
318
319 pub(crate) const fn extra_flags(&self) -> ffi::MDBX_env_flags_t {
321 match self {
322 Self::Default => ffi::MDBX_ENV_DEFAULTS,
323 Self::WriteMap => ffi::MDBX_WRITEMAP,
324 }
325 }
326}
327
328#[derive(Copy, Clone, Debug)]
329pub(crate) struct EnvPtr(pub(crate) *mut ffi::MDBX_env);
330unsafe impl Send for EnvPtr {}
331unsafe impl Sync for EnvPtr {}
332
333#[derive(Debug)]
337#[repr(transparent)]
338pub struct Stat(ffi::MDBX_stat);
339
340impl Stat {
341 pub(crate) const fn new() -> Self {
343 unsafe { Self(mem::zeroed()) }
344 }
345
346 pub(crate) const fn mdbx_stat(&mut self) -> *mut ffi::MDBX_stat {
348 &mut self.0
349 }
350}
351
352impl Stat {
353 #[inline]
355 pub const fn page_size(&self) -> u32 {
356 self.0.ms_psize
357 }
358
359 #[inline]
361 pub const fn depth(&self) -> u32 {
362 self.0.ms_depth
363 }
364
365 #[inline]
367 pub const fn branch_pages(&self) -> usize {
368 self.0.ms_branch_pages as usize
369 }
370
371 #[inline]
373 pub const fn leaf_pages(&self) -> usize {
374 self.0.ms_leaf_pages as usize
375 }
376
377 #[inline]
379 pub const fn overflow_pages(&self) -> usize {
380 self.0.ms_overflow_pages as usize
381 }
382
383 #[inline]
385 pub const fn entries(&self) -> usize {
386 self.0.ms_entries as usize
387 }
388}
389
390#[derive(Debug)]
391#[repr(transparent)]
392pub struct GeometryInfo(ffi::MDBX_envinfo__bindgen_ty_1);
393
394impl GeometryInfo {
395 pub const fn min(&self) -> u64 {
396 self.0.lower
397 }
398}
399
400#[derive(Debug)]
404#[repr(transparent)]
405pub struct Info(ffi::MDBX_envinfo);
406
407impl Info {
408 pub const fn geometry(&self) -> GeometryInfo {
409 GeometryInfo(self.0.mi_geo)
410 }
411
412 #[inline]
414 pub const fn map_size(&self) -> usize {
415 self.0.mi_mapsize as usize
416 }
417
418 #[inline]
420 pub const fn last_pgno(&self) -> usize {
421 self.0.mi_last_pgno as usize
422 }
423
424 #[inline]
426 pub const fn last_txnid(&self) -> usize {
427 self.0.mi_recent_txnid as usize
428 }
429
430 #[inline]
432 pub const fn max_readers(&self) -> usize {
433 self.0.mi_maxreaders as usize
434 }
435
436 #[inline]
438 pub const fn num_readers(&self) -> usize {
439 self.0.mi_numreaders as usize
440 }
441
442 #[inline]
444 pub const fn latter_reader_txnid(&self) -> u64 {
445 self.0.mi_latter_reader_txnid
446 }
447
448 #[inline]
450 pub const fn page_ops(&self) -> PageOps {
451 PageOps {
452 newly: self.0.mi_pgop_stat.newly,
453 cow: self.0.mi_pgop_stat.cow,
454 clone: self.0.mi_pgop_stat.clone,
455 split: self.0.mi_pgop_stat.split,
456 merge: self.0.mi_pgop_stat.merge,
457 spill: self.0.mi_pgop_stat.spill,
458 unspill: self.0.mi_pgop_stat.unspill,
459 wops: self.0.mi_pgop_stat.wops,
460 prefault: self.0.mi_pgop_stat.prefault,
461 mincore: self.0.mi_pgop_stat.mincore,
462 msync: self.0.mi_pgop_stat.msync,
463 fsync: self.0.mi_pgop_stat.fsync,
464 }
465 }
466
467 #[inline]
469 pub const fn mode(&self) -> Mode {
470 let mode = self.0.mi_mode as ffi::MDBX_env_flags_t;
471 if (mode & ffi::MDBX_RDONLY) != 0 {
472 Mode::ReadOnly
473 } else if (mode & ffi::MDBX_UTTERLY_NOSYNC) != 0 {
474 Mode::ReadWrite { sync_mode: SyncMode::UtterlyNoSync }
475 } else if (mode & ffi::MDBX_NOMETASYNC) != 0 {
476 Mode::ReadWrite { sync_mode: SyncMode::NoMetaSync }
477 } else if (mode & ffi::MDBX_SAFE_NOSYNC) != 0 {
478 Mode::ReadWrite { sync_mode: SyncMode::SafeNoSync }
479 } else {
480 Mode::ReadWrite { sync_mode: SyncMode::Durable }
481 }
482 }
483
484 pub fn last_steady_txnid(&self) -> Option<u64> {
488 const DATASIGN_WEAK: u64 = 1;
490 self.0
491 .mi_meta_sign
492 .iter()
493 .zip(self.0.mi_meta_txnid)
494 .filter(|(sign, _)| **sign > DATASIGN_WEAK)
495 .map(|(_, txnid)| txnid)
496 .max()
497 }
498}
499
500impl fmt::Debug for Environment {
501 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
502 f.debug_struct("Environment").field("kind", &self.inner.env_kind).finish_non_exhaustive()
503 }
504}
505
506#[derive(Clone, Debug, PartialEq, Eq)]
511pub enum PageSize {
512 MinimalAcceptable,
513 Set(usize),
514}
515
516#[derive(Clone, Debug, PartialEq, Eq)]
518pub struct PageOps {
519 pub newly: u64,
521 pub cow: u64,
523 pub clone: u64,
525 pub split: u64,
527 pub merge: u64,
529 pub spill: u64,
531 pub unspill: u64,
533 pub wops: u64,
535 pub msync: u64,
537 pub fsync: u64,
539 pub prefault: u64,
541 pub mincore: u64,
543}
544
545#[derive(Clone, Debug, PartialEq, Eq)]
547pub struct Geometry<R> {
548 pub size: Option<R>,
550 pub growth_step: Option<isize>,
551 pub shrink_threshold: Option<isize>,
552 pub page_size: Option<PageSize>,
553}
554
555impl<R> Default for Geometry<R> {
556 fn default() -> Self {
557 Self { size: None, growth_step: None, shrink_threshold: None, page_size: None }
558 }
559}
560
561pub type HandleSlowReadersCallback = extern "C" fn(
605 env: *const ffi::MDBX_env,
606 txn: *const ffi::MDBX_txn,
607 pid: ffi::mdbx_pid_t,
608 tid: ffi::mdbx_tid_t,
609 laggard: u64,
610 gap: std::ffi::c_uint,
611 space: usize,
612 retry: std::ffi::c_int,
613) -> HandleSlowReadersReturnCode;
614
615#[derive(Debug)]
616#[repr(i32)]
617pub enum HandleSlowReadersReturnCode {
618 Error = -2,
620 ProceedWithoutKillingReader = -1,
623 Success = 0,
628 ClearReaderSlot = 1,
632 ReaderProcessTerminated = 2,
635}
636
637#[derive(Debug, Clone)]
639pub struct EnvironmentBuilder {
640 flags: EnvironmentFlags,
641 max_readers: Option<u64>,
642 max_dbs: Option<u64>,
643 sync_bytes: Option<u64>,
644 sync_period: Option<u64>,
645 rp_augment_limit: Option<u64>,
646 loose_limit: Option<u64>,
647 dp_reserve_limit: Option<u64>,
648 txn_dp_limit: Option<u64>,
649 spill_max_denominator: Option<u64>,
650 spill_min_denominator: Option<u64>,
651 geometry: Option<Geometry<(Option<usize>, Option<usize>)>>,
652 log_level: Option<ffi::MDBX_log_level_t>,
653 kind: EnvironmentKind,
654 handle_slow_readers: Option<HandleSlowReadersCallback>,
655 #[cfg(feature = "read-tx-timeouts")]
656 max_read_transaction_duration: Option<read_transactions::MaxReadTransactionDuration>,
659}
660
661impl EnvironmentBuilder {
662 pub fn open(&self, path: &Path) -> Result<Environment> {
666 self.open_with_permissions(path, 0o644)
667 }
668
669 pub fn open_with_permissions(
673 &self,
674 path: &Path,
675 mode: ffi::mdbx_mode_t,
676 ) -> Result<Environment> {
677 let mut env: *mut ffi::MDBX_env = ptr::null_mut();
678 unsafe {
679 if let Some(log_level) = self.log_level {
680 ffi::mdbx_setup_debug(log_level, ffi::MDBX_DBG_DONTCHANGE, None);
683 }
684
685 mdbx_result(ffi::mdbx_env_create(&mut env))?;
686
687 if let Err(e) = (|| {
688 if let Some(geometry) = &self.geometry {
689 let mut min_size = -1;
690 let mut max_size = -1;
691
692 if let Some(size) = geometry.size {
693 if let Some(size) = size.0 {
694 min_size = size as isize;
695 }
696
697 if let Some(size) = size.1 {
698 max_size = size as isize;
699 }
700 }
701
702 mdbx_result(ffi::mdbx_env_set_geometry(
703 env,
704 min_size,
705 -1,
706 max_size,
707 geometry.growth_step.unwrap_or(-1),
708 geometry.shrink_threshold.unwrap_or(-1),
709 match geometry.page_size {
710 None => -1,
711 Some(PageSize::MinimalAcceptable) => 0,
712 Some(PageSize::Set(size)) => size as isize,
713 },
714 ))?;
715 }
716 for (opt, v) in [
717 (ffi::MDBX_opt_max_db, self.max_dbs),
718 (ffi::MDBX_opt_rp_augment_limit, self.rp_augment_limit),
719 (ffi::MDBX_opt_loose_limit, self.loose_limit),
720 (ffi::MDBX_opt_dp_reserve_limit, self.dp_reserve_limit),
721 (ffi::MDBX_opt_txn_dp_limit, self.txn_dp_limit),
722 (ffi::MDBX_opt_spill_max_denominator, self.spill_max_denominator),
723 (ffi::MDBX_opt_spill_min_denominator, self.spill_min_denominator),
724 ] {
725 if let Some(v) = v {
726 mdbx_result(ffi::mdbx_env_set_option(env, opt, v))?;
727 }
728 }
729
730 if let Some(max_readers) = self.max_readers {
732 mdbx_result(ffi::mdbx_env_set_option(
733 env,
734 ffi::MDBX_opt_max_readers,
735 max_readers,
736 ))?;
737 }
738
739 if let Some(handle_slow_readers) = self.handle_slow_readers {
740 mdbx_result(ffi::mdbx_env_set_hsr(
741 env,
742 convert_hsr_fn(Some(handle_slow_readers)),
743 ))?;
744 }
745
746 #[cfg(unix)]
747 fn path_to_bytes<P: AsRef<Path>>(path: P) -> Vec<u8> {
748 use std::os::unix::ffi::OsStrExt;
749 path.as_ref().as_os_str().as_bytes().to_vec()
750 }
751
752 #[cfg(windows)]
753 fn path_to_bytes<P: AsRef<Path>>(path: P) -> Vec<u8> {
754 path.as_ref().to_string_lossy().to_string().into_bytes()
758 }
759
760 let path = match CString::new(path_to_bytes(path)) {
761 Ok(path) => path,
762 Err(_) => return Err(Error::Invalid),
763 };
764 mdbx_result(ffi::mdbx_env_open(
765 env,
766 path.as_ptr(),
767 self.flags.make_flags() | self.kind.extra_flags(),
768 mode,
769 ))?;
770
771 for (opt, v) in [
772 (ffi::MDBX_opt_sync_bytes, self.sync_bytes),
773 (ffi::MDBX_opt_sync_period, self.sync_period),
774 ] {
775 if let Some(v) = v {
776 mdbx_result(ffi::mdbx_env_set_option(env, opt, v))?;
777 }
778 }
779
780 Ok(())
781 })() {
782 ffi::mdbx_env_close_ex(env, false);
783
784 return Err(e)
785 }
786 }
787
788 let env_ptr = EnvPtr(env);
789
790 #[cfg(not(feature = "read-tx-timeouts"))]
791 let txn_manager = TxnManager::new(env_ptr);
792
793 #[cfg(feature = "read-tx-timeouts")]
794 let txn_manager = {
795 if let crate::MaxReadTransactionDuration::Set(duration) = self
796 .max_read_transaction_duration
797 .unwrap_or(read_transactions::MaxReadTransactionDuration::Set(
798 DEFAULT_MAX_READ_TRANSACTION_DURATION,
799 ))
800 {
801 TxnManager::new_with_max_read_transaction_duration(env_ptr, duration)
802 } else {
803 TxnManager::new(env_ptr)
804 }
805 };
806
807 let env = EnvironmentInner {
808 env,
809 txn_manager,
810 env_kind: self.kind,
811 ro_txn_pool: ReadTxnPool::new(),
812 };
813
814 Ok(Environment { inner: Arc::new(env) })
815 }
816
817 pub const fn set_kind(&mut self, kind: EnvironmentKind) -> &mut Self {
819 self.kind = kind;
820 self
821 }
822
823 pub const fn write_map(&mut self) -> &mut Self {
827 self.set_kind(EnvironmentKind::WriteMap)
828 }
829
830 pub const fn set_flags(&mut self, flags: EnvironmentFlags) -> &mut Self {
832 self.flags = flags;
833 self
834 }
835
836 pub const fn set_max_readers(&mut self, max_readers: u64) -> &mut Self {
842 self.max_readers = Some(max_readers);
843 self
844 }
845
846 pub const fn set_max_dbs(&mut self, v: usize) -> &mut Self {
856 self.max_dbs = Some(v as u64);
857 self
858 }
859
860 pub const fn set_sync_bytes(&mut self, v: usize) -> &mut Self {
863 self.sync_bytes = Some(v as u64);
864 self
865 }
866
867 pub fn set_sync_period(&mut self, v: Duration) -> &mut Self {
870 let as_mdbx_units = (v.as_secs_f64() * 65536f64) as u64;
872 self.sync_period = Some(as_mdbx_units);
873 self
874 }
875
876 pub const fn set_rp_augment_limit(&mut self, v: u64) -> &mut Self {
877 self.rp_augment_limit = Some(v);
878 self
879 }
880
881 pub const fn set_loose_limit(&mut self, v: u64) -> &mut Self {
882 self.loose_limit = Some(v);
883 self
884 }
885
886 pub const fn set_dp_reserve_limit(&mut self, v: u64) -> &mut Self {
887 self.dp_reserve_limit = Some(v);
888 self
889 }
890
891 pub const fn set_txn_dp_limit(&mut self, v: u64) -> &mut Self {
892 self.txn_dp_limit = Some(v);
893 self
894 }
895
896 pub fn set_spill_max_denominator(&mut self, v: u8) -> &mut Self {
897 self.spill_max_denominator = Some(v.into());
898 self
899 }
900
901 pub fn set_spill_min_denominator(&mut self, v: u8) -> &mut Self {
902 self.spill_min_denominator = Some(v.into());
903 self
904 }
905
906 pub fn set_geometry<R: RangeBounds<usize>>(&mut self, geometry: Geometry<R>) -> &mut Self {
909 let convert_bound = |bound: Bound<&usize>| match bound {
910 Bound::Included(v) | Bound::Excluded(v) => Some(*v),
911 _ => None,
912 };
913 self.geometry = Some(Geometry {
914 size: geometry.size.map(|range| {
915 (convert_bound(range.start_bound()), convert_bound(range.end_bound()))
916 }),
917 growth_step: geometry.growth_step,
918 shrink_threshold: geometry.shrink_threshold,
919 page_size: geometry.page_size,
920 });
921 self
922 }
923
924 pub const fn set_log_level(&mut self, log_level: ffi::MDBX_log_level_t) -> &mut Self {
925 self.log_level = Some(log_level);
926 self
927 }
928
929 pub fn set_handle_slow_readers(&mut self, hsr: HandleSlowReadersCallback) -> &mut Self {
932 self.handle_slow_readers = Some(hsr);
933 self
934 }
935}
936
937#[cfg(feature = "read-tx-timeouts")]
938pub(crate) mod read_transactions {
939 use crate::EnvironmentBuilder;
940 use std::time::Duration;
941
942 #[derive(Debug, Clone, Copy)]
944 #[cfg(feature = "read-tx-timeouts")]
945 pub enum MaxReadTransactionDuration {
946 Unbounded,
948 Set(Duration),
950 }
951
952 #[cfg(feature = "read-tx-timeouts")]
953 impl MaxReadTransactionDuration {
954 pub const fn as_duration(&self) -> Option<Duration> {
955 match self {
956 Self::Unbounded => None,
957 Self::Set(duration) => Some(*duration),
958 }
959 }
960 }
961
962 impl EnvironmentBuilder {
963 pub const fn set_max_read_transaction_duration(
965 &mut self,
966 max_read_transaction_duration: MaxReadTransactionDuration,
967 ) -> &mut Self {
968 self.max_read_transaction_duration = Some(max_read_transaction_duration);
969 self
970 }
971 }
972}
973
974fn convert_hsr_fn(callback: Option<HandleSlowReadersCallback>) -> ffi::MDBX_hsr_func {
976 unsafe { std::mem::transmute(callback) }
977}
978
979#[cfg(test)]
980mod tests {
981 use crate::{Environment, Error, Geometry, HandleSlowReadersReturnCode, PageSize, WriteFlags};
982 use std::{
983 ops::RangeInclusive,
984 sync::atomic::{AtomicBool, Ordering},
985 };
986
987 #[test]
988 fn test_handle_slow_readers_callback() {
989 static CALLED: AtomicBool = AtomicBool::new(false);
990
991 extern "C" fn handle_slow_readers(
992 _env: *const ffi::MDBX_env,
993 _txn: *const ffi::MDBX_txn,
994 _pid: ffi::mdbx_pid_t,
995 _tid: ffi::mdbx_tid_t,
996 _laggard: u64,
997 _gap: std::ffi::c_uint,
998 _space: usize,
999 _retry: std::ffi::c_int,
1000 ) -> HandleSlowReadersReturnCode {
1001 CALLED.store(true, Ordering::Relaxed);
1002 HandleSlowReadersReturnCode::ProceedWithoutKillingReader
1003 }
1004
1005 let tempdir = tempfile::tempdir().unwrap();
1006 let env = Environment::builder()
1007 .set_geometry(Geometry::<RangeInclusive<usize>> {
1008 size: Some(0..=1024 * 1024), page_size: Some(PageSize::MinimalAcceptable), ..Default::default()
1011 })
1012 .set_handle_slow_readers(handle_slow_readers)
1013 .open(tempdir.path())
1014 .unwrap();
1015
1016 {
1018 let tx = env.begin_rw_txn().unwrap();
1019 let db = tx.open_db(None).unwrap();
1020 for i in 0usize..1_000 {
1021 tx.put(db.dbi(), i.to_le_bytes(), b"0", WriteFlags::empty()).unwrap()
1022 }
1023 tx.commit().unwrap();
1024 }
1025
1026 let _tx_ro = env.begin_ro_txn().unwrap();
1028
1029 {
1031 let tx = env.begin_rw_txn().unwrap();
1032 let db = tx.open_db(None).unwrap();
1033 for i in 0usize..1_000 {
1034 tx.put(db.dbi(), i.to_le_bytes(), b"1", WriteFlags::empty()).unwrap();
1035 }
1036 tx.commit().unwrap();
1037 }
1038
1039 {
1042 let tx = env.begin_rw_txn().unwrap();
1043 let db = tx.open_db(None).unwrap();
1044 for i in 1_000usize..1_000_000 {
1045 match tx.put(db.dbi(), i.to_le_bytes(), b"0", WriteFlags::empty()) {
1046 Ok(_) => {}
1047 Err(Error::MapFull) => break,
1048 result @ Err(_) => result.unwrap(),
1049 }
1050 }
1051 let _ = tx.commit();
1055 }
1056
1057 assert!(CALLED.load(Ordering::Relaxed));
1059 }
1060}