forked from rust-rocksdb/rust-rocksdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_options.rs
4521 lines (4198 loc) · 159 KB
/
db_options.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 Tyler Neely
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::ffi::CStr;
use std::path::Path;
use std::ptr::{null_mut, NonNull};
use std::slice;
use std::sync::Arc;
use libc::{self, c_char, c_double, c_int, c_uchar, c_uint, c_void, size_t};
use crate::statistics::{Histogram, HistogramData, StatsLevel};
use crate::{
compaction_filter::{self, CompactionFilterCallback, CompactionFilterFn},
compaction_filter_factory::{self, CompactionFilterFactory},
comparator::{
ComparatorCallback, ComparatorWithTsCallback, CompareFn, CompareTsFn, CompareWithoutTsFn,
},
db::DBAccess,
env::Env,
ffi,
ffi_util::{from_cstr, to_cpath, CStrLike},
merge_operator::{
self, full_merge_callback, partial_merge_callback, MergeFn, MergeOperatorCallback,
},
slice_transform::SliceTransform,
statistics::Ticker,
ColumnFamilyDescriptor, Error, SnapshotWithThreadMode,
};
pub(crate) struct WriteBufferManagerWrapper {
pub(crate) inner: NonNull<ffi::rocksdb_write_buffer_manager_t>,
}
impl Drop for WriteBufferManagerWrapper {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_write_buffer_manager_destroy(self.inner.as_ptr());
}
}
}
#[derive(Clone)]
pub struct WriteBufferManager(pub(crate) Arc<WriteBufferManagerWrapper>);
impl WriteBufferManager {
/// <https://github.com/facebook/rocksdb/wiki/Write-Buffer-Manager>
/// Write buffer manager helps users control the total memory used by memtables across multiple column families and/or DB instances.
/// Users can enable this control by 2 ways:
///
/// 1- Limit the total memtable usage across multiple column families and DBs under a threshold.
/// 2- Cost the memtable memory usage to block cache so that memory of RocksDB can be capped by the single limit.
/// The usage of a write buffer manager is similar to rate_limiter and sst_file_manager.
/// Users can create one write buffer manager object and pass it to all the options of column families or DBs whose memtable size they want to be controlled by this object.
///
/// A memory limit is given when creating the write buffer manager object. RocksDB will try to limit the total memory to under this limit.
///
/// a flush will be triggered on one column family of the DB you are inserting to,
///
/// If mutable memtable size exceeds about 90% of the limit,
/// If the total memory is over the limit, more aggressive flush may also be triggered only if the mutable memtable size also exceeds 50% of the limit.
/// Both checks are needed because if already more than half memory is being flushed, triggering more flush may not help.
///
/// The total memory is counted as total memory allocated in the arena, even if some of that may not yet be used by memtable.
///
/// buffer_size: the memory limit in bytes.
/// allow_stall: If set true, it will enable stalling of all writers when memory usage exceeds buffer_size (soft limit).
/// It will wait for flush to complete and memory usage to drop down
pub fn new_write_buffer_manager(buffer_size: size_t, allow_stall: bool) -> Self {
let inner = NonNull::new(unsafe {
ffi::rocksdb_write_buffer_manager_create(buffer_size, allow_stall)
})
.unwrap();
WriteBufferManager(Arc::new(WriteBufferManagerWrapper { inner }))
}
/// Users can set up RocksDB to cost memory used by memtables to block cache.
/// This can happen no matter whether you enable memtable memory limit or not.
/// This option is added to manage memory (memtables + block cache) under a single limit.
///
/// buffer_size: the memory limit in bytes.
/// allow_stall: If set true, it will enable stalling of all writers when memory usage exceeds buffer_size (soft limit).
/// It will wait for flush to complete and memory usage to drop down
/// cache: the block cache instance
pub fn new_write_buffer_manager_with_cache(
buffer_size: size_t,
allow_stall: bool,
cache: Cache,
) -> Self {
let inner = NonNull::new(unsafe {
ffi::rocksdb_write_buffer_manager_create_with_cache(
buffer_size,
cache.0.inner.as_ptr(),
allow_stall,
)
})
.unwrap();
WriteBufferManager(Arc::new(WriteBufferManagerWrapper { inner }))
}
/// Returns the WriteBufferManager memory usage in bytes.
pub fn get_usage(&self) -> usize {
unsafe { ffi::rocksdb_write_buffer_manager_memory_usage(self.0.inner.as_ptr()) }
}
/// Returns the current buffer size in bytes.
pub fn get_buffer_size(&self) -> usize {
unsafe { ffi::rocksdb_write_buffer_manager_buffer_size(self.0.inner.as_ptr()) }
}
/// Set the buffer size in bytes.
pub fn set_buffer_size(&self, new_size: usize) {
unsafe {
ffi::rocksdb_write_buffer_manager_set_buffer_size(self.0.inner.as_ptr(), new_size);
}
}
/// Returns if WriteBufferManager is enabled.
pub fn enabled(&self) -> bool {
unsafe { ffi::rocksdb_write_buffer_manager_enabled(self.0.inner.as_ptr()) }
}
/// set the allow_stall flag.
pub fn set_allow_stall(&self, allow_stall: bool) {
unsafe {
ffi::rocksdb_write_buffer_manager_set_allow_stall(self.0.inner.as_ptr(), allow_stall);
}
}
}
pub(crate) struct CacheWrapper {
pub(crate) inner: NonNull<ffi::rocksdb_cache_t>,
}
impl Drop for CacheWrapper {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_cache_destroy(self.inner.as_ptr());
}
}
}
#[derive(Clone)]
pub struct Cache(pub(crate) Arc<CacheWrapper>);
impl Cache {
/// Creates an LRU cache with capacity in bytes.
pub fn new_lru_cache(capacity: size_t) -> Cache {
let inner = NonNull::new(unsafe { ffi::rocksdb_cache_create_lru(capacity) }).unwrap();
Cache(Arc::new(CacheWrapper { inner }))
}
/// Creates a HyperClockCache with capacity in bytes.
///
/// `estimated_entry_charge` is an important tuning parameter. The optimal
/// choice at any given time is
/// `(cache.get_usage() - 64 * cache.get_table_address_count()) /
/// cache.get_occupancy_count()`, or approximately `cache.get_usage() /
/// cache.get_occupancy_count()`.
///
/// However, the value cannot be changed dynamically, so as the cache
/// composition changes at runtime, the following tradeoffs apply:
///
/// * If the estimate is substantially too high (e.g., 25% higher),
/// the cache may have to evict entries to prevent load factors that
/// would dramatically affect lookup times.
/// * If the estimate is substantially too low (e.g., less than half),
/// then meta data space overhead is substantially higher.
///
/// The latter is generally preferable, and picking the larger of
/// block size and meta data block size is a reasonable choice that
/// errs towards this side.
pub fn new_hyper_clock_cache(capacity: size_t, estimated_entry_charge: size_t) -> Cache {
Cache(Arc::new(CacheWrapper {
inner: NonNull::new(unsafe {
ffi::rocksdb_cache_create_hyper_clock(capacity, estimated_entry_charge)
})
.unwrap(),
}))
}
/// Returns the cache memory usage in bytes.
pub fn get_usage(&self) -> usize {
unsafe { ffi::rocksdb_cache_get_usage(self.0.inner.as_ptr()) }
}
/// Returns the pinned memory usage in bytes.
pub fn get_pinned_usage(&self) -> usize {
unsafe { ffi::rocksdb_cache_get_pinned_usage(self.0.inner.as_ptr()) }
}
/// Sets cache capacity in bytes.
pub fn set_capacity(&mut self, capacity: size_t) {
unsafe {
ffi::rocksdb_cache_set_capacity(self.0.inner.as_ptr(), capacity);
}
}
}
#[derive(Default)]
pub(crate) struct OptionsMustOutliveDB {
env: Option<Env>,
row_cache: Option<Cache>,
blob_cache: Option<Cache>,
block_based: Option<BlockBasedOptionsMustOutliveDB>,
write_buffer_manager: Option<WriteBufferManager>,
}
impl OptionsMustOutliveDB {
pub(crate) fn clone(&self) -> Self {
Self {
env: self.env.clone(),
row_cache: self.row_cache.clone(),
blob_cache: self.blob_cache.clone(),
block_based: self
.block_based
.as_ref()
.map(BlockBasedOptionsMustOutliveDB::clone),
write_buffer_manager: self.write_buffer_manager.clone(),
}
}
}
#[derive(Default)]
struct BlockBasedOptionsMustOutliveDB {
block_cache: Option<Cache>,
}
impl BlockBasedOptionsMustOutliveDB {
fn clone(&self) -> Self {
Self {
block_cache: self.block_cache.clone(),
}
}
}
/// Database-wide options around performance and behavior.
///
/// Please read the official tuning [guide](https://github.com/facebook/rocksdb/wiki/RocksDB-Tuning-Guide)
/// and most importantly, measure performance under realistic workloads with realistic hardware.
///
/// # Examples
///
/// ```
/// use rocksdb::{Options, DB};
/// use rocksdb::DBCompactionStyle;
///
/// fn badly_tuned_for_somebody_elses_disk() -> DB {
/// let path = "path/for/rocksdb/storageX";
/// let mut opts = Options::default();
/// opts.create_if_missing(true);
/// opts.set_max_open_files(10000);
/// opts.set_use_fsync(false);
/// opts.set_bytes_per_sync(8388608);
/// opts.optimize_for_point_lookup(1024);
/// opts.set_table_cache_num_shard_bits(6);
/// opts.set_max_write_buffer_number(32);
/// opts.set_write_buffer_size(536870912);
/// opts.set_target_file_size_base(1073741824);
/// opts.set_min_write_buffer_number_to_merge(4);
/// opts.set_level_zero_stop_writes_trigger(2000);
/// opts.set_level_zero_slowdown_writes_trigger(0);
/// opts.set_compaction_style(DBCompactionStyle::Universal);
/// opts.set_disable_auto_compactions(true);
///
/// DB::open(&opts, path).unwrap()
/// }
/// ```
pub struct Options {
pub(crate) inner: *mut ffi::rocksdb_options_t,
pub(crate) outlive: OptionsMustOutliveDB,
}
/// Optionally disable WAL or sync for this write.
///
/// # Examples
///
/// Making an unsafe write of a batch:
///
/// ```
/// use rocksdb::{DB, Options, WriteBatch, WriteOptions};
///
/// let path = "_path_for_rocksdb_storageY1";
/// {
/// let db = DB::open_default(path).unwrap();
/// let mut batch = WriteBatch::default();
/// batch.put(b"my key", b"my value");
/// batch.put(b"key2", b"value2");
/// batch.put(b"key3", b"value3");
///
/// let mut write_options = WriteOptions::default();
/// write_options.set_sync(false);
/// write_options.disable_wal(true);
///
/// db.write_opt(batch, &write_options);
/// }
/// let _ = DB::destroy(&Options::default(), path);
/// ```
pub struct WriteOptions {
pub(crate) inner: *mut ffi::rocksdb_writeoptions_t,
}
/// Optionally wait for the memtable flush to be performed.
///
/// # Examples
///
/// Manually flushing the memtable:
///
/// ```
/// use rocksdb::{DB, Options, FlushOptions};
///
/// let path = "_path_for_rocksdb_storageY2";
/// {
/// let db = DB::open_default(path).unwrap();
///
/// let mut flush_options = FlushOptions::default();
/// flush_options.set_wait(true);
///
/// db.flush_opt(&flush_options);
/// }
/// let _ = DB::destroy(&Options::default(), path);
/// ```
pub struct FlushOptions {
pub(crate) inner: *mut ffi::rocksdb_flushoptions_t,
}
/// For configuring block-based file storage.
pub struct BlockBasedOptions {
pub(crate) inner: *mut ffi::rocksdb_block_based_table_options_t,
outlive: BlockBasedOptionsMustOutliveDB,
}
pub struct ReadOptions {
pub(crate) inner: *mut ffi::rocksdb_readoptions_t,
// The `ReadOptions` owns a copy of the timestamp and iteration bounds.
// This is necessary to ensure the pointers we pass over the FFI live as
// long as the `ReadOptions`. This way, when performing the read operation,
// the pointers are guaranteed to be valid.
timestamp: Option<Vec<u8>>,
iter_start_ts: Option<Vec<u8>>,
iterate_upper_bound: Option<Vec<u8>>,
iterate_lower_bound: Option<Vec<u8>>,
}
/// Configuration of cuckoo-based storage.
pub struct CuckooTableOptions {
pub(crate) inner: *mut ffi::rocksdb_cuckoo_table_options_t,
}
/// For configuring external files ingestion.
///
/// # Examples
///
/// Move files instead of copying them:
///
/// ```
/// use rocksdb::{DB, IngestExternalFileOptions, SstFileWriter, Options};
///
/// let writer_opts = Options::default();
/// let mut writer = SstFileWriter::create(&writer_opts);
/// writer.open("_path_for_sst_file").unwrap();
/// writer.put(b"k1", b"v1").unwrap();
/// writer.finish().unwrap();
///
/// let path = "_path_for_rocksdb_storageY3";
/// {
/// let db = DB::open_default(&path).unwrap();
/// let mut ingest_opts = IngestExternalFileOptions::default();
/// ingest_opts.set_move_files(true);
/// db.ingest_external_file_opts(&ingest_opts, vec!["_path_for_sst_file"]).unwrap();
/// }
/// let _ = DB::destroy(&Options::default(), path);
/// ```
pub struct IngestExternalFileOptions {
pub(crate) inner: *mut ffi::rocksdb_ingestexternalfileoptions_t,
}
// Safety note: auto-implementing Send on most db-related types is prevented by the inner FFI
// pointer. In most cases, however, this pointer is Send-safe because it is never aliased and
// rocksdb internally does not rely on thread-local information for its user-exposed types.
unsafe impl Send for Options {}
unsafe impl Send for WriteOptions {}
unsafe impl Send for FlushOptions {}
unsafe impl Send for BlockBasedOptions {}
unsafe impl Send for CuckooTableOptions {}
unsafe impl Send for ReadOptions {}
unsafe impl Send for IngestExternalFileOptions {}
unsafe impl Send for CacheWrapper {}
unsafe impl Send for CompactOptions {}
unsafe impl Send for WriteBufferManagerWrapper {}
// Sync is similarly safe for many types because they do not expose interior mutability, and their
// use within the rocksdb library is generally behind a const reference
unsafe impl Sync for Options {}
unsafe impl Sync for WriteOptions {}
unsafe impl Sync for FlushOptions {}
unsafe impl Sync for BlockBasedOptions {}
unsafe impl Sync for CuckooTableOptions {}
unsafe impl Sync for ReadOptions {}
unsafe impl Sync for IngestExternalFileOptions {}
unsafe impl Sync for CacheWrapper {}
unsafe impl Sync for CompactOptions {}
unsafe impl Sync for WriteBufferManagerWrapper {}
impl Drop for Options {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_options_destroy(self.inner);
}
}
}
impl Clone for Options {
fn clone(&self) -> Self {
let inner = unsafe { ffi::rocksdb_options_create_copy(self.inner) };
assert!(!inner.is_null(), "Could not copy RocksDB options");
Self {
inner,
outlive: self.outlive.clone(),
}
}
}
impl Drop for BlockBasedOptions {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_block_based_options_destroy(self.inner);
}
}
}
impl Drop for CuckooTableOptions {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_cuckoo_options_destroy(self.inner);
}
}
}
impl Drop for FlushOptions {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_flushoptions_destroy(self.inner);
}
}
}
impl Drop for WriteOptions {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_writeoptions_destroy(self.inner);
}
}
}
impl Drop for ReadOptions {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_readoptions_destroy(self.inner);
}
}
}
impl Drop for IngestExternalFileOptions {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_ingestexternalfileoptions_destroy(self.inner);
}
}
}
impl BlockBasedOptions {
/// Approximate size of user data packed per block. Note that the
/// block size specified here corresponds to uncompressed data. The
/// actual size of the unit read from disk may be smaller if
/// compression is enabled. This parameter can be changed dynamically.
pub fn set_block_size(&mut self, size: usize) {
unsafe {
ffi::rocksdb_block_based_options_set_block_size(self.inner, size);
}
}
/// Block size for partitioned metadata. Currently applied to indexes when
/// kTwoLevelIndexSearch is used and to filters when partition_filters is used.
/// Note: Since in the current implementation the filters and index partitions
/// are aligned, an index/filter block is created when either index or filter
/// block size reaches the specified limit.
///
/// Note: this limit is currently applied to only index blocks; a filter
/// partition is cut right after an index block is cut.
pub fn set_metadata_block_size(&mut self, size: usize) {
unsafe {
ffi::rocksdb_block_based_options_set_metadata_block_size(self.inner, size as u64);
}
}
/// Note: currently this option requires kTwoLevelIndexSearch to be set as
/// well.
///
/// Use partitioned full filters for each SST file. This option is
/// incompatible with block-based filters.
pub fn set_partition_filters(&mut self, size: bool) {
unsafe {
ffi::rocksdb_block_based_options_set_partition_filters(self.inner, c_uchar::from(size));
}
}
/// Sets global cache for blocks (user data is stored in a set of blocks, and
/// a block is the unit of reading from disk).
///
/// If set, use the specified cache for blocks.
/// By default, rocksdb will automatically create and use an 8MB internal cache.
pub fn set_block_cache(&mut self, cache: &Cache) {
unsafe {
ffi::rocksdb_block_based_options_set_block_cache(self.inner, cache.0.inner.as_ptr());
}
self.outlive.block_cache = Some(cache.clone());
}
/// Disable block cache
pub fn disable_cache(&mut self) {
unsafe {
ffi::rocksdb_block_based_options_set_no_block_cache(self.inner, c_uchar::from(true));
}
}
/// Sets a [Bloom filter](https://github.com/facebook/rocksdb/wiki/RocksDB-Bloom-Filter)
/// policy to reduce disk reads.
///
/// # Examples
///
/// ```
/// use rocksdb::BlockBasedOptions;
///
/// let mut opts = BlockBasedOptions::default();
/// opts.set_bloom_filter(10.0, true);
/// ```
pub fn set_bloom_filter(&mut self, bits_per_key: c_double, block_based: bool) {
unsafe {
let bloom = if block_based {
ffi::rocksdb_filterpolicy_create_bloom(bits_per_key as _)
} else {
ffi::rocksdb_filterpolicy_create_bloom_full(bits_per_key as _)
};
ffi::rocksdb_block_based_options_set_filter_policy(self.inner, bloom);
}
}
/// Sets a [Ribbon filter](http://rocksdb.org/blog/2021/12/29/ribbon-filter.html)
/// policy to reduce disk reads.
///
/// Ribbon filters use less memory in exchange for slightly more CPU usage
/// compared to an equivalent bloom filter.
///
/// # Examples
///
/// ```
/// use rocksdb::BlockBasedOptions;
///
/// let mut opts = BlockBasedOptions::default();
/// opts.set_ribbon_filter(10.0);
/// ```
pub fn set_ribbon_filter(&mut self, bloom_equivalent_bits_per_key: c_double) {
unsafe {
let ribbon = ffi::rocksdb_filterpolicy_create_ribbon(bloom_equivalent_bits_per_key);
ffi::rocksdb_block_based_options_set_filter_policy(self.inner, ribbon);
}
}
/// Sets a hybrid [Ribbon filter](http://rocksdb.org/blog/2021/12/29/ribbon-filter.html)
/// policy to reduce disk reads.
///
/// Uses Bloom filters before the given level, and Ribbon filters for all
/// other levels. This combines the memory savings from Ribbon filters
/// with the lower CPU usage of Bloom filters.
///
/// # Examples
///
/// ```
/// use rocksdb::BlockBasedOptions;
///
/// let mut opts = BlockBasedOptions::default();
/// opts.set_hybrid_ribbon_filter(10.0, 2);
/// ```
pub fn set_hybrid_ribbon_filter(
&mut self,
bloom_equivalent_bits_per_key: c_double,
bloom_before_level: c_int,
) {
unsafe {
let ribbon = ffi::rocksdb_filterpolicy_create_ribbon_hybrid(
bloom_equivalent_bits_per_key,
bloom_before_level,
);
ffi::rocksdb_block_based_options_set_filter_policy(self.inner, ribbon);
}
}
/// If cache_index_and_filter_blocks is enabled, cache index and filter blocks with high priority.
/// If set to true, depending on implementation of block cache,
/// index and filter blocks may be less likely to be evicted than data blocks.
pub fn set_cache_index_and_filter_blocks(&mut self, v: bool) {
unsafe {
ffi::rocksdb_block_based_options_set_cache_index_and_filter_blocks(
self.inner,
c_uchar::from(v),
);
}
}
/// Defines the index type to be used for SS-table lookups.
///
/// # Examples
///
/// ```
/// use rocksdb::{BlockBasedOptions, BlockBasedIndexType, Options};
///
/// let mut opts = Options::default();
/// let mut block_opts = BlockBasedOptions::default();
/// block_opts.set_index_type(BlockBasedIndexType::HashSearch);
/// ```
pub fn set_index_type(&mut self, index_type: BlockBasedIndexType) {
let index = index_type as i32;
unsafe {
ffi::rocksdb_block_based_options_set_index_type(self.inner, index);
}
}
/// If cache_index_and_filter_blocks is true and the below is true, then
/// filter and index blocks are stored in the cache, but a reference is
/// held in the "table reader" object so the blocks are pinned and only
/// evicted from cache when the table reader is freed.
///
/// Default: false.
pub fn set_pin_l0_filter_and_index_blocks_in_cache(&mut self, v: bool) {
unsafe {
ffi::rocksdb_block_based_options_set_pin_l0_filter_and_index_blocks_in_cache(
self.inner,
c_uchar::from(v),
);
}
}
/// If cache_index_and_filter_blocks is true and the below is true, then
/// the top-level index of partitioned filter and index blocks are stored in
/// the cache, but a reference is held in the "table reader" object so the
/// blocks are pinned and only evicted from cache when the table reader is
/// freed. This is not limited to l0 in LSM tree.
///
/// Default: false.
pub fn set_pin_top_level_index_and_filter(&mut self, v: bool) {
unsafe {
ffi::rocksdb_block_based_options_set_pin_top_level_index_and_filter(
self.inner,
c_uchar::from(v),
);
}
}
/// Format version, reserved for backward compatibility.
///
/// See full [list](https://github.com/facebook/rocksdb/blob/v8.6.7/include/rocksdb/table.h#L493-L521)
/// of the supported versions.
///
/// Default: 5.
pub fn set_format_version(&mut self, version: i32) {
unsafe {
ffi::rocksdb_block_based_options_set_format_version(self.inner, version);
}
}
/// Number of keys between restart points for delta encoding of keys.
/// This parameter can be changed dynamically. Most clients should
/// leave this parameter alone. The minimum value allowed is 1. Any smaller
/// value will be silently overwritten with 1.
///
/// Default: 16.
pub fn set_block_restart_interval(&mut self, interval: i32) {
unsafe {
ffi::rocksdb_block_based_options_set_block_restart_interval(self.inner, interval);
}
}
/// Same as block_restart_interval but used for the index block.
/// If you don't plan to run RocksDB before version 5.16 and you are
/// using `index_block_restart_interval` > 1, you should
/// probably set the `format_version` to >= 4 as it would reduce the index size.
///
/// Default: 1.
pub fn set_index_block_restart_interval(&mut self, interval: i32) {
unsafe {
ffi::rocksdb_block_based_options_set_index_block_restart_interval(self.inner, interval);
}
}
/// Set the data block index type for point lookups:
/// `DataBlockIndexType::BinarySearch` to use binary search within the data block.
/// `DataBlockIndexType::BinaryAndHash` to use the data block hash index in combination with
/// the normal binary search.
///
/// The hash table utilization ratio is adjustable using [`set_data_block_hash_ratio`](#method.set_data_block_hash_ratio), which is
/// valid only when using `DataBlockIndexType::BinaryAndHash`.
///
/// Default: `BinarySearch`
/// # Examples
///
/// ```
/// use rocksdb::{BlockBasedOptions, DataBlockIndexType, Options};
///
/// let mut opts = Options::default();
/// let mut block_opts = BlockBasedOptions::default();
/// block_opts.set_data_block_index_type(DataBlockIndexType::BinaryAndHash);
/// block_opts.set_data_block_hash_ratio(0.85);
/// ```
pub fn set_data_block_index_type(&mut self, index_type: DataBlockIndexType) {
let index_t = index_type as i32;
unsafe {
ffi::rocksdb_block_based_options_set_data_block_index_type(self.inner, index_t);
}
}
/// Set the data block hash index utilization ratio.
///
/// The smaller the utilization ratio, the less hash collisions happen, and so reduce the risk for a
/// point lookup to fall back to binary search due to the collisions. A small ratio means faster
/// lookup at the price of more space overhead.
///
/// Default: 0.75
pub fn set_data_block_hash_ratio(&mut self, ratio: f64) {
unsafe {
ffi::rocksdb_block_based_options_set_data_block_hash_ratio(self.inner, ratio);
}
}
/// If false, place only prefixes in the filter, not whole keys.
///
/// Defaults to true.
pub fn set_whole_key_filtering(&mut self, v: bool) {
unsafe {
ffi::rocksdb_block_based_options_set_whole_key_filtering(self.inner, c_uchar::from(v));
}
}
/// Use the specified checksum type.
/// Newly created table files will be protected with this checksum type.
/// Old table files will still be readable, even though they have different checksum type.
pub fn set_checksum_type(&mut self, checksum_type: ChecksumType) {
unsafe {
ffi::rocksdb_block_based_options_set_checksum(self.inner, checksum_type as c_char);
}
}
/// If true, generate Bloom/Ribbon filters that minimize memory internal
/// fragmentation.
/// See official [wiki](
/// https://github.com/facebook/rocksdb/wiki/RocksDB-Bloom-Filter#reducing-internal-fragmentation)
/// for more information.
///
/// Defaults to false.
/// # Examples
///
/// ```
/// use rocksdb::BlockBasedOptions;
///
/// let mut opts = BlockBasedOptions::default();
/// opts.set_bloom_filter(10.0, true);
/// opts.set_optimize_filters_for_memory(true);
/// ```
pub fn set_optimize_filters_for_memory(&mut self, v: bool) {
unsafe {
ffi::rocksdb_block_based_options_set_optimize_filters_for_memory(
self.inner,
c_uchar::from(v),
);
}
}
}
impl Default for BlockBasedOptions {
fn default() -> Self {
let block_opts = unsafe { ffi::rocksdb_block_based_options_create() };
assert!(
!block_opts.is_null(),
"Could not create RocksDB block based options"
);
Self {
inner: block_opts,
outlive: BlockBasedOptionsMustOutliveDB::default(),
}
}
}
impl CuckooTableOptions {
/// Determines the utilization of hash tables. Smaller values
/// result in larger hash tables with fewer collisions.
/// Default: 0.9
pub fn set_hash_ratio(&mut self, ratio: f64) {
unsafe {
ffi::rocksdb_cuckoo_options_set_hash_ratio(self.inner, ratio);
}
}
/// A property used by builder to determine the depth to go to
/// to search for a path to displace elements in case of
/// collision. See Builder.MakeSpaceForKey method. Higher
/// values result in more efficient hash tables with fewer
/// lookups but take more time to build.
/// Default: 100
pub fn set_max_search_depth(&mut self, depth: u32) {
unsafe {
ffi::rocksdb_cuckoo_options_set_max_search_depth(self.inner, depth);
}
}
/// In case of collision while inserting, the builder
/// attempts to insert in the next cuckoo_block_size
/// locations before skipping over to the next Cuckoo hash
/// function. This makes lookups more cache friendly in case
/// of collisions.
/// Default: 5
pub fn set_cuckoo_block_size(&mut self, size: u32) {
unsafe {
ffi::rocksdb_cuckoo_options_set_cuckoo_block_size(self.inner, size);
}
}
/// If this option is enabled, user key is treated as uint64_t and its value
/// is used as hash value directly. This option changes builder's behavior.
/// Reader ignore this option and behave according to what specified in
/// table property.
/// Default: false
pub fn set_identity_as_first_hash(&mut self, flag: bool) {
unsafe {
ffi::rocksdb_cuckoo_options_set_identity_as_first_hash(self.inner, c_uchar::from(flag));
}
}
/// If this option is set to true, module is used during hash calculation.
/// This often yields better space efficiency at the cost of performance.
/// If this option is set to false, # of entries in table is constrained to
/// be power of two, and bit and is used to calculate hash, which is faster in general.
/// Default: true
pub fn set_use_module_hash(&mut self, flag: bool) {
unsafe {
ffi::rocksdb_cuckoo_options_set_use_module_hash(self.inner, c_uchar::from(flag));
}
}
}
impl Default for CuckooTableOptions {
fn default() -> Self {
let opts = unsafe { ffi::rocksdb_cuckoo_options_create() };
assert!(!opts.is_null(), "Could not create RocksDB cuckoo options");
Self { inner: opts }
}
}
// Verbosity of the LOG.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(i32)]
pub enum LogLevel {
Debug = 0,
Info,
Warn,
Error,
Fatal,
Header,
}
impl Options {
/// Constructs the DBOptions and ColumnFamilyDescriptors by loading the
/// latest RocksDB options file stored in the specified rocksdb database.
pub fn load_latest<P: AsRef<Path>>(
path: P,
env: Env,
ignore_unknown_options: bool,
cache: Cache,
) -> Result<(Options, Vec<ColumnFamilyDescriptor>), Error> {
let path = to_cpath(path)?;
let mut db_options: *mut ffi::rocksdb_options_t = null_mut();
let mut num_column_families: usize = 0;
let mut column_family_names: *mut *mut c_char = null_mut();
let mut column_family_options: *mut *mut ffi::rocksdb_options_t = null_mut();
unsafe {
ffi_try!(ffi::rocksdb_load_latest_options(
path.as_ptr(),
env.0.inner,
ignore_unknown_options,
cache.0.inner.as_ptr(),
&mut db_options,
&mut num_column_families,
&mut column_family_names,
&mut column_family_options,
));
}
let options = Options {
inner: db_options,
outlive: OptionsMustOutliveDB::default(),
};
let column_families = unsafe {
Options::read_column_descriptors(
num_column_families,
column_family_names,
column_family_options,
)
};
Ok((options, column_families))
}
/// read column descriptors from c pointers
#[inline]
unsafe fn read_column_descriptors(
num_column_families: usize,
column_family_names: *mut *mut c_char,
column_family_options: *mut *mut ffi::rocksdb_options_t,
) -> Vec<ColumnFamilyDescriptor> {
let column_family_names_iter =
slice::from_raw_parts(column_family_names, num_column_families)
.iter()
.map(|ptr| from_cstr(*ptr));
let column_family_options_iter =
slice::from_raw_parts(column_family_options, num_column_families)
.iter()
.map(|ptr| Options {
inner: *ptr,
outlive: OptionsMustOutliveDB::default(),
});
let column_descriptors = column_family_names_iter
.zip(column_family_options_iter)
.map(|(name, options)| ColumnFamilyDescriptor { name, options })
.collect::<Vec<_>>();
// free pointers
slice::from_raw_parts(column_family_names, num_column_families)
.iter()
.for_each(|ptr| ffi::rocksdb_free(*ptr as *mut c_void));
ffi::rocksdb_free(column_family_names as *mut c_void);
ffi::rocksdb_free(column_family_options as *mut c_void);
column_descriptors
}
/// By default, RocksDB uses only one background thread for flush and
/// compaction. Calling this function will set it up such that total of
/// `total_threads` is used. Good value for `total_threads` is the number of
/// cores. You almost definitely want to call this function if your system is
/// bottlenecked by RocksDB.
///
/// # Examples
///
/// ```
/// use rocksdb::Options;
///
/// let mut opts = Options::default();
/// opts.increase_parallelism(3);
/// ```
pub fn increase_parallelism(&mut self, parallelism: i32) {
unsafe {
ffi::rocksdb_options_increase_parallelism(self.inner, parallelism);
}
}
/// Optimize level style compaction.
///
/// Default values for some parameters in `Options` are not optimized for heavy
/// workloads and big datasets, which means you might observe write stalls under
/// some conditions.
///
/// This can be used as one of the starting points for tuning RocksDB options in
/// such cases.
///
/// Internally, it sets `write_buffer_size`, `min_write_buffer_number_to_merge`,
/// `max_write_buffer_number`, `level0_file_num_compaction_trigger`,
/// `target_file_size_base`, `max_bytes_for_level_base`, so it can override if those
/// parameters were set before.
///
/// It sets buffer sizes so that memory consumption would be constrained by
/// `memtable_memory_budget`.
pub fn optimize_level_style_compaction(&mut self, memtable_memory_budget: usize) {
unsafe {
ffi::rocksdb_options_optimize_level_style_compaction(
self.inner,
memtable_memory_budget as u64,
);
}
}