/
kv.rs
1166 lines (963 loc) 路 37.4 KB
/
kv.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
// Sonic
//
// Fast, lightweight and schema-less search backend
// Copyright: 2019, Valerian Saliou <valerian@valeriansaliou.name>
// License: Mozilla Public License v2.0 (MPL v2.0)
use byteorder::{ByteOrder, LittleEndian, ReadBytesExt};
use hashbrown::HashMap;
use radix::RadixNum;
use rocksdb::backup::{
BackupEngine as DBBackupEngine, BackupEngineOptions as DBBackupEngineOptions,
RestoreOptions as DBRestoreOptions,
};
use rocksdb::{
DBCompactionStyle, DBCompressionType, DBVector, Error as DBError, Options as DBOptions,
WriteBatch, DB,
};
use std::fmt;
use std::fs;
use std::io::{self, Cursor};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock};
use std::time::SystemTime;
use std::vec::Drain;
use super::generic::{
StoreGeneric, StoreGenericActionBuilder, StoreGenericBuilder, StoreGenericPool,
};
use super::identifiers::*;
use super::item::StoreItemPart;
use super::keyer::{StoreKeyerBuilder, StoreKeyerHasher, StoreKeyerKey, StoreKeyerPrefix};
use crate::APP_CONF;
pub struct StoreKVPool;
pub struct StoreKVBuilder;
pub struct StoreKV {
database: DB,
last_used: Arc<RwLock<SystemTime>>,
pub lock: RwLock<bool>,
}
pub struct StoreKVActionBuilder;
pub struct StoreKVAction<'a> {
store: Option<StoreKVBox>,
bucket: StoreItemPart<'a>,
}
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub struct StoreKVKey {
collection_hash: StoreKVAtom,
}
#[derive(PartialEq)]
pub enum StoreKVAcquireMode {
Any,
OpenOnly,
}
type StoreKVAtom = u32;
type StoreKVBox = Arc<StoreKV>;
const ATOM_HASH_RADIX: usize = 16;
lazy_static! {
pub static ref STORE_ACCESS_LOCK: Arc<RwLock<bool>> = Arc::new(RwLock::new(false));
static ref STORE_ACQUIRE_LOCK: Arc<Mutex<bool>> = Arc::new(Mutex::new(false));
static ref STORE_POOL: Arc<RwLock<HashMap<StoreKVKey, StoreKVBox>>> =
Arc::new(RwLock::new(HashMap::new()));
}
impl StoreKVPool {
pub fn count() -> usize {
STORE_POOL.read().unwrap().len()
}
pub fn acquire<'a, T: Into<&'a str>>(
mode: StoreKVAcquireMode,
collection: T,
) -> Result<Option<StoreKVBox>, ()> {
let collection_str = collection.into();
let pool_key = StoreKVKey::from_str(collection_str);
// Freeze acquire lock, and reference it in context
// Notice: this prevents two databases on the same collection to be opened at the same time.
let _acquire = STORE_ACQUIRE_LOCK.lock().unwrap();
// Acquire a thread-safe store pool reference in read mode
let store_pool_read = STORE_POOL.read().unwrap();
if let Some(store_kv) = store_pool_read.get(&pool_key) {
Self::proceed_acquire_cache("kv", collection_str, pool_key, store_kv)
.map(|result| Some(result))
} else {
info!(
"kv store not in pool for collection: {} {}, opening it",
collection_str, pool_key
);
// Important: we need to drop the read reference first, to avoid \
// dead-locking when acquiring the RWLock in write mode in this block.
drop(store_pool_read);
// Check if can open database?
let can_open_db = if mode == StoreKVAcquireMode::OpenOnly {
StoreKVBuilder::path(pool_key.collection_hash).exists()
} else {
true
};
// Open KV database? (ie. we do not need to create a new KV database file tree if \
// the database does not exist yet on disk and we are just looking to read data from \
// it)
if can_open_db {
Self::proceed_acquire_open("kv", collection_str, pool_key, &*STORE_POOL)
.map(|result| Some(result))
} else {
Ok(None)
}
}
}
pub fn janitor() {
Self::proceed_janitor(
"kv",
&*STORE_POOL,
APP_CONF.store.kv.pool.inactive_after,
&*STORE_ACCESS_LOCK,
)
}
pub fn backup(path: &Path) -> Result<(), io::Error> {
debug!("backing up all kv stores to path: {:?}", path);
// Create backup directory (full path)
fs::create_dir_all(path)?;
// Proceed dump action (backup)
Self::dump_action("backup", &*APP_CONF.store.kv.path, path, &Self::backup_item)
}
pub fn restore(path: &Path) -> Result<(), io::Error> {
debug!("restoring all kv stores from path: {:?}", path);
// Proceed dump action (restore)
Self::dump_action(
"restore",
path,
&*APP_CONF.store.kv.path,
&Self::restore_item,
)
}
fn dump_action(
action: &str,
read_path: &Path,
write_path: &Path,
fn_item: &Fn(&Path, &Path, &str) -> Result<(), io::Error>,
) -> Result<(), io::Error> {
// Iterate on KV collections
for collection in fs::read_dir(read_path)? {
let collection = collection?;
// Actual collection found?
match (collection.file_type(), collection.file_name().to_str()) {
(Ok(collection_file_type), Some(collection_name)) => {
if collection_file_type.is_dir() {
debug!("kv collection ongoing {}: {}", action, collection_name);
fn_item(write_path, &collection.path(), collection_name)?;
}
}
_ => {}
}
}
Ok(())
}
fn backup_item(
backup_path: &Path,
_origin_path: &Path,
collection_name: &str,
) -> Result<(), io::Error> {
// Acquire access lock (in blocking write mode), and reference it in context
// Notice: this prevents store to be acquired from any context
let _access = STORE_ACCESS_LOCK.write().unwrap();
// Generate path to KV backup
let kv_backup_path = backup_path.join(collection_name);
debug!(
"kv collection: {} backing up to path: {:?}",
collection_name, kv_backup_path
);
// Erase any previously-existing KV backup
if kv_backup_path.exists() {
fs::remove_dir_all(&kv_backup_path)?;
}
// Create backup folder for collection
fs::create_dir_all(backup_path.join(collection_name))?;
// Convert names to hashes (as names are hashes encoded as base-16 strings, but we need \
// them as proper integers)
if let Ok(collection_radix) = RadixNum::from_str(collection_name, ATOM_HASH_RADIX) {
if let Ok(collection_hash) = collection_radix.as_decimal() {
let origin_kv = StoreKVBuilder::open(collection_hash as StoreKVAtom)
.or(io_error!("database open failure"))?;
// Initialize KV database backup engine
let mut kv_backup_engine =
DBBackupEngine::open(&DBBackupEngineOptions::default(), &kv_backup_path)
.or(io_error!("backup engine failure"))?;
// Proceed actual KV database backup
kv_backup_engine
.create_new_backup(&origin_kv)
.or(io_error!("database backup failure"))?;
info!(
"kv collection: {} backed up to path: {:?}",
collection_name, kv_backup_path
);
}
}
Ok(())
}
fn restore_item(
_backup_path: &Path,
origin_path: &Path,
collection_name: &str,
) -> Result<(), io::Error> {
// Acquire access lock (in blocking write mode), and reference it in context
// Notice: this prevents store to be acquired from any context
let _access = STORE_ACCESS_LOCK.write().unwrap();
debug!(
"kv collection: {} restoring from path: {:?}",
collection_name, origin_path
);
// Convert names to hashes (as names are hashes encoded as base-16 strings, but we need \
// them as proper integers)
if let Ok(collection_radix) = RadixNum::from_str(collection_name, ATOM_HASH_RADIX) {
if let Ok(collection_hash) = collection_radix.as_decimal() {
// Force a KV store close
StoreKVBuilder::close(collection_hash as StoreKVAtom);
// Generate path to KV
let kv_path = StoreKVBuilder::path(collection_hash as StoreKVAtom);
// Remove existing KV database data?
if kv_path.exists() {
fs::remove_dir_all(&kv_path)?;
}
// Create KV folder for collection
fs::create_dir_all(&kv_path)?;
// Initialize KV database backup engine
let mut kv_backup_engine =
DBBackupEngine::open(&DBBackupEngineOptions::default(), &origin_path)
.or(io_error!("backup engine failure"))?;
kv_backup_engine
.restore_from_latest_backup(&kv_path, &kv_path, &DBRestoreOptions::default())
.or(io_error!("database restore failure"))?;
info!(
"kv collection: {} restored to path: {:?} from backup: {:?}",
collection_name, kv_path, origin_path
);
}
}
Ok(())
}
}
impl StoreGenericPool<StoreKVKey, StoreKV, StoreKVBuilder> for StoreKVPool {}
impl StoreKVBuilder {
fn open(collection_hash: StoreKVAtom) -> Result<DB, DBError> {
debug!(
"opening key-value database for collection: <{:x?}>",
collection_hash
);
// Configure database options
let db_options = Self::configure();
// Open database at path for collection
DB::open(&db_options, Self::path(collection_hash))
}
fn close(collection_hash: StoreKVAtom) {
debug!(
"closing key-value database for collection: <{:x?}>",
collection_hash
);
let mut store_pool_write = STORE_POOL.write().unwrap();
let collection_target = StoreKVKey::from_atom(collection_hash);
store_pool_write.remove(&collection_target);
}
fn path(collection_hash: StoreKVAtom) -> PathBuf {
APP_CONF
.store
.kv
.path
.join(format!("{:x?}", collection_hash))
}
fn configure() -> DBOptions {
debug!("configuring key-value database");
// Make database options
let mut db_options = DBOptions::default();
// Set static options
db_options.create_if_missing(true);
db_options.set_use_fsync(false);
db_options.set_compaction_style(DBCompactionStyle::Level);
db_options.set_min_write_buffer_number(1);
db_options.set_max_write_buffer_number(2);
// Set dynamic options
db_options.set_compression_type(if APP_CONF.store.kv.database.compress {
DBCompressionType::Lz4
} else {
DBCompressionType::None
});
db_options.set_max_open_files(if let Some(value) = APP_CONF.store.kv.database.max_files {
value as i32
} else {
-1
});
db_options.increase_parallelism(APP_CONF.store.kv.database.parallelism as i32);
db_options
.set_max_background_compactions(APP_CONF.store.kv.database.max_compactions as i32);
db_options.set_max_background_flushes(APP_CONF.store.kv.database.max_flushes as i32);
db_options.set_write_buffer_size(APP_CONF.store.kv.database.write_buffer * 1024);
db_options
}
}
impl StoreGenericBuilder<StoreKVKey, StoreKV> for StoreKVBuilder {
fn new(pool_key: StoreKVKey) -> Result<StoreKV, ()> {
Self::open(pool_key.collection_hash)
.map(|db| StoreKV {
database: db,
last_used: Arc::new(RwLock::new(SystemTime::now())),
lock: RwLock::new(false),
})
.or_else(|err| {
error!("failed opening kv: {}", err);
Err(())
})
}
}
impl StoreKV {
pub fn get(&self, key: &[u8]) -> Result<Option<DBVector>, DBError> {
self.database.get(key)
}
pub fn put(&self, key: &[u8], data: &[u8]) -> Result<(), DBError> {
self.database.put(key, data)
}
pub fn delete(&self, key: &[u8]) -> Result<(), DBError> {
self.database.delete(key)
}
}
impl StoreGeneric for StoreKV {
fn ref_last_used<'a>(&'a self) -> &'a RwLock<SystemTime> {
&self.last_used
}
}
impl StoreKVActionBuilder {
pub fn access(bucket: StoreItemPart, store: Option<StoreKVBox>) -> StoreKVAction {
Self::build(bucket, store)
}
pub fn erase<'a, T: Into<&'a str>>(collection: T, bucket: Option<T>) -> Result<u32, ()> {
Self::dispatch_erase("kv", collection, bucket)
}
fn build(bucket: StoreItemPart, store: Option<StoreKVBox>) -> StoreKVAction {
StoreKVAction { store, bucket }
}
}
impl StoreGenericActionBuilder for StoreKVActionBuilder {
fn proceed_erase_collection(collection_str: &str) -> Result<u32, ()> {
let collection_atom = StoreKeyerHasher::to_compact(collection_str);
let collection_path = StoreKVBuilder::path(collection_atom);
// Force a KV store close
StoreKVBuilder::close(collection_atom);
if collection_path.exists() {
debug!(
"kv collection store exists, erasing: {}/* at path: {:?}",
collection_str, &collection_path
);
// Remove KV store storage from filesystem
let erase_result = fs::remove_dir_all(&collection_path);
if erase_result.is_ok() {
debug!("done with kv collection erasure");
Ok(1)
} else {
Err(())
}
} else {
debug!(
"kv collection store does not exist, consider already erased: {}/* at path: {:?}",
collection_str, &collection_path
);
Ok(0)
}
}
fn proceed_erase_bucket(_collection: &str, _bucket: &str) -> Result<u32, ()> {
// This one is not implemented, as we need to acquire the collection; which would cause \
// a party-killer dead-lock.
Err(())
}
}
impl<'a> StoreKVAction<'a> {
/// Meta-to-Value mapper
///
/// [IDX=0] ((meta)) ~> ((value))
pub fn get_meta_to_value(&self, meta: StoreMetaKey) -> Result<Option<StoreMetaValue>, ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::meta_to_value(self.bucket.as_str(), &meta);
debug!("store get meta-to-value: {}", store_key);
match store.get(&store_key.as_bytes()) {
Ok(Some(value)) => {
debug!("got meta-to-value: {}", store_key);
Ok(if let Some(value) = value.to_utf8() {
match meta {
StoreMetaKey::IIDIncr => value
.parse::<StoreObjectIID>()
.ok()
.map(|value| StoreMetaValue::IIDIncr(value))
.or(None),
}
} else {
None
})
}
Ok(None) => {
debug!("no meta-to-value found: {}", store_key);
Ok(None)
}
Err(err) => {
error!(
"error getting meta-to-value: {} with trace: {}",
store_key, err
);
Err(())
}
}
} else {
Ok(None)
}
}
pub fn set_meta_to_value(&self, meta: StoreMetaKey, value: StoreMetaValue) -> Result<(), ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::meta_to_value(self.bucket.as_str(), &meta);
debug!("store set meta-to-value: {}", store_key);
let value_string = match value {
StoreMetaValue::IIDIncr(iid_incr) => iid_incr.to_string(),
};
store
.put(&store_key.as_bytes(), value_string.as_bytes())
.or(Err(()))
} else {
Err(())
}
}
/// Term-to-IIDs mapper
///
/// [IDX=1] ((term)) ~> [((iid))]
pub fn get_term_to_iids(
&self,
term_hashed: StoreTermHashed,
) -> Result<Option<Vec<StoreObjectIID>>, ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::term_to_iids(self.bucket.as_str(), term_hashed);
debug!("store get term-to-iids: {}", store_key);
match store.get(&store_key.as_bytes()) {
Ok(Some(value)) => {
debug!(
"got term-to-iids: {} with encoded value: {:?}",
store_key, &*value
);
Self::decode_u32_list(&*value)
.or(Err(()))
.map(|value_decoded| {
debug!(
"got term-to-iids: {} with decoded value: {:?}",
store_key, &value_decoded
);
Some(value_decoded)
})
}
Ok(None) => {
debug!("no term-to-iids found: {}", store_key);
Ok(None)
}
Err(err) => {
error!(
"error getting term-to-iids: {} with trace: {}",
store_key, err
);
Err(())
}
}
} else {
Ok(None)
}
}
pub fn set_term_to_iids(
&self,
term_hashed: StoreTermHashed,
iids: &[StoreObjectIID],
) -> Result<(), ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::term_to_iids(self.bucket.as_str(), term_hashed);
debug!("store set term-to-iids: {}", store_key);
// Encode IID list into storage serialized format
let iids_encoded = Self::encode_u32_list(iids);
debug!(
"store set term-to-iids: {} with encoded value: {:?}",
store_key, iids_encoded
);
store.put(&store_key.as_bytes(), &iids_encoded).or(Err(()))
} else {
Err(())
}
}
pub fn delete_term_to_iids(&self, term_hashed: StoreTermHashed) -> Result<(), ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::term_to_iids(self.bucket.as_str(), term_hashed);
debug!("store delete term-to-iids: {}", store_key);
store.delete(&store_key.as_bytes()).or(Err(()))
} else {
Err(())
}
}
/// OID-to-IID mapper
///
/// [IDX=2] ((oid)) ~> ((iid))
pub fn get_oid_to_iid(&self, oid: StoreObjectOID<'a>) -> Result<Option<StoreObjectIID>, ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::oid_to_iid(self.bucket.as_str(), oid);
debug!("store get oid-to-iid: {}", store_key);
match store.get(&store_key.as_bytes()) {
Ok(Some(value)) => {
debug!(
"got oid-to-iid: {} with encoded value: {:?}",
store_key, &*value
);
Self::decode_u32(&*value).or(Err(())).map(|value_decoded| {
debug!(
"got oid-to-iid: {} with decoded value: {:?}",
store_key, &value_decoded
);
Some(value_decoded)
})
}
Ok(None) => {
debug!("no oid-to-iid found: {}", store_key);
Ok(None)
}
Err(err) => {
error!(
"error getting oid-to-iid: {} with trace: {}",
store_key, err
);
Err(())
}
}
} else {
Ok(None)
}
}
pub fn set_oid_to_iid(&self, oid: StoreObjectOID<'a>, iid: StoreObjectIID) -> Result<(), ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::oid_to_iid(self.bucket.as_str(), oid);
debug!("store set oid-to-iid: {}", store_key);
// Encode IID
let iid_encoded = Self::encode_u32(iid);
debug!(
"store set oid-to-iid: {} with encoded value: {:?}",
store_key, iid_encoded
);
store.put(&store_key.as_bytes(), &iid_encoded).or(Err(()))
} else {
Err(())
}
}
pub fn delete_oid_to_iid(&self, oid: StoreObjectOID<'a>) -> Result<(), ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::oid_to_iid(self.bucket.as_str(), oid);
debug!("store delete oid-to-iid: {}", store_key);
store.delete(&store_key.as_bytes()).or(Err(()))
} else {
Err(())
}
}
/// IID-to-OID mapper
///
/// [IDX=3] ((iid)) ~> ((oid))
pub fn get_iid_to_oid(&self, iid: StoreObjectIID) -> Result<Option<String>, ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::iid_to_oid(self.bucket.as_str(), iid);
debug!("store get iid-to-oid: {}", store_key);
match store.get(&store_key.as_bytes()) {
Ok(Some(value)) => Ok(value.to_utf8().map(|value| value.to_string())),
Ok(None) => Ok(None),
Err(_) => Err(()),
}
} else {
Ok(None)
}
}
pub fn set_iid_to_oid(&self, iid: StoreObjectIID, oid: StoreObjectOID<'a>) -> Result<(), ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::iid_to_oid(self.bucket.as_str(), iid);
debug!("store set iid-to-oid: {}", store_key);
store.put(&store_key.as_bytes(), oid.as_bytes()).or(Err(()))
} else {
Err(())
}
}
pub fn delete_iid_to_oid(&self, iid: StoreObjectIID) -> Result<(), ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::iid_to_oid(self.bucket.as_str(), iid);
debug!("store delete iid-to-oid: {}", store_key);
store.delete(&store_key.as_bytes()).or(Err(()))
} else {
Err(())
}
}
/// IID-to-Terms mapper
///
/// [IDX=4] ((iid)) ~> [((term))]
pub fn get_iid_to_terms(
&self,
iid: StoreObjectIID,
) -> Result<Option<Vec<StoreTermHashed>>, ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::iid_to_terms(self.bucket.as_str(), iid);
debug!("store get iid-to-terms: {}", store_key);
match store.get(&store_key.as_bytes()) {
Ok(Some(value)) => {
debug!(
"got iid-to-terms: {} with encoded value: {:?}",
store_key, &*value
);
Self::decode_u32_list(&*value)
.or(Err(()))
.map(|value_decoded| {
debug!(
"got iid-to-terms: {} with decoded value: {:?}",
store_key, &value_decoded
);
if !value_decoded.is_empty() {
Some(value_decoded)
} else {
None
}
})
}
Ok(None) => Ok(None),
Err(_) => Err(()),
}
} else {
Ok(None)
}
}
pub fn set_iid_to_terms(
&self,
iid: StoreObjectIID,
terms_hashed: &[StoreTermHashed],
) -> Result<(), ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::iid_to_terms(self.bucket.as_str(), iid);
debug!("store set iid-to-terms: {}", store_key);
// Encode term list into storage serialized format
let terms_hashed_encoded = Self::encode_u32_list(terms_hashed);
debug!(
"store set iid-to-terms: {} with encoded value: {:?}",
store_key, terms_hashed_encoded
);
store
.put(&store_key.as_bytes(), &terms_hashed_encoded)
.or(Err(()))
} else {
Err(())
}
}
pub fn delete_iid_to_terms(&self, iid: StoreObjectIID) -> Result<(), ()> {
if let Some(ref store) = self.store {
let store_key = StoreKeyerBuilder::iid_to_terms(self.bucket.as_str(), iid);
debug!("store delete iid-to-terms: {}", store_key);
store.delete(&store_key.as_bytes()).or(Err(()))
} else {
Err(())
}
}
pub fn batch_flush_bucket(
&self,
iid: StoreObjectIID,
oid: StoreObjectOID<'a>,
iid_terms_hashed: &[StoreTermHashed],
) -> Result<u32, ()> {
let mut count = 0;
debug!(
"store batch flush bucket: {} with hashed terms: {:?}",
iid, iid_terms_hashed
);
// Delete OID <> IID association
match (
self.delete_oid_to_iid(&oid),
self.delete_iid_to_oid(iid),
self.delete_iid_to_terms(iid),
) {
(Ok(_), Ok(_), Ok(_)) => {
// Delete IID from each associated term
for iid_term in iid_terms_hashed {
if let Ok(Some(mut iid_term_iids)) = self.get_term_to_iids(*iid_term) {
if iid_term_iids.contains(&iid) {
count += 1;
// Remove IID from list of IIDs
iid_term_iids.retain(|cur_iid| cur_iid != &iid);
}
let is_ok = if iid_term_iids.is_empty() {
self.delete_term_to_iids(*iid_term).is_ok()
} else {
self.set_term_to_iids(*iid_term, &iid_term_iids).is_ok()
};
if !is_ok {
return Err(());
}
}
}
Ok(count)
}
_ => Err(()),
}
}
pub fn batch_truncate_object(
&self,
term_hashed: StoreTermHashed,
term_iids_drain: Drain<StoreObjectIID>,
) -> Result<u32, ()> {
let mut count = 0;
for term_iid_drain in term_iids_drain {
debug!("store batch truncate object iid: {}", term_iid_drain);
// Nuke term in IID to Terms list
if let Ok(Some(mut term_iid_drain_terms)) = self.get_iid_to_terms(term_iid_drain) {
count += 1;
term_iid_drain_terms.retain(|cur_term| cur_term != &term_hashed);
// IID to Terms list is empty? Flush whole object.
if term_iid_drain_terms.is_empty() {
// Acquire OID for this drained IID
if let Ok(Some(term_iid_drain_oid)) = self.get_iid_to_oid(term_iid_drain) {
if self
.batch_flush_bucket(term_iid_drain, &term_iid_drain_oid, &Vec::new())
.is_err()
{
error!(
"failed executing store batch truncate object batch-flush-bucket"
);
}
} else {
error!("failed getting store batch truncate object iid-to-oid");
}
} else {
// Update IID to Terms list
if self
.set_iid_to_terms(term_iid_drain, &term_iid_drain_terms)
.is_err()
{
error!("failed setting store batch truncate object iid-to-terms");
}
}
}
}
Ok(count)
}
pub fn batch_erase_bucket(&self) -> Result<u32, ()> {
if let Some(ref store) = self.store {
// Generate all key prefix values (with dummy post-prefix values; we dont care)
let (k_meta_to_value, k_term_to_iids, k_oid_to_iid, k_iid_to_oid, k_iid_to_terms) = (
StoreKeyerBuilder::meta_to_value(self.bucket.as_str(), &StoreMetaKey::IIDIncr),
StoreKeyerBuilder::term_to_iids(self.bucket.as_str(), 0),
StoreKeyerBuilder::oid_to_iid(self.bucket.as_str(), &String::new()),
StoreKeyerBuilder::iid_to_oid(self.bucket.as_str(), 0),
StoreKeyerBuilder::iid_to_terms(self.bucket.as_str(), 0),
);
let key_prefixes: [StoreKeyerPrefix; 5] = [
k_meta_to_value.as_prefix(),
k_term_to_iids.as_prefix(),
k_oid_to_iid.as_prefix(),
k_iid_to_oid.as_prefix(),
k_iid_to_terms.as_prefix(),
];
// Scan all keys per-prefix and nuke them right away
for key_prefix in &key_prefixes {
debug!(
"store batch erase bucket: {} for prefix: {:?}",
self.bucket.as_str(),
key_prefix
);
// Generate start and end prefix for batch delete (in other words, the minimum \
// key value possible, and the highest key value possible)
let key_prefix_start: StoreKeyerKey = [
key_prefix[0],
key_prefix[1],
key_prefix[2],
key_prefix[3],
key_prefix[4],
0,
0,
0,
0,
];
let key_prefix_end: StoreKeyerKey = [
key_prefix[0],
key_prefix[1],
key_prefix[2],
key_prefix[3],
key_prefix[4],
255,
255,
255,
255,
];
// Batch-delete keys matching range
let mut batch = WriteBatch::default();
if batch
.delete_range(&key_prefix_start, &key_prefix_end)
.is_ok()
{
// Commit operation to database
if let Err(err) = store.database.write(batch) {
error!(
"failed in store batch erase bucket: {} with error: {}",
self.bucket.as_str(),
err
);
} else {
// Ensure last key is deleted (as RocksDB end key is exclusive; while \
// start key is inclusive, we need to ensure the end-of-range key is \
// deleted)
store.database.delete(&key_prefix_end).ok();
debug!(
"succeeded in store batch erase bucket: {}",
self.bucket.as_str()
);
}
} else {
error!(
"error stacking range delete in store batch erase bucket: {}",
self.bucket.as_str()
);
}
}
info!(
"done processing store batch erase bucket: {}",
self.bucket.as_str()
);
Ok(1)
} else {
Err(())
}
}
fn encode_u32(decoded: u32) -> [u8; 4] {
let mut encoded = [0; 4];
LittleEndian::write_u32(&mut encoded, decoded);
encoded
}
fn decode_u32(encoded: &[u8]) -> Result<u32, ()> {
Cursor::new(encoded).read_u32::<LittleEndian>().or(Err(()))
}
fn encode_u32_list(decoded: &[u32]) -> Vec<u8> {
// Pre-reserve required capacity as to avoid heap resizes (50% performance gain relative \
// to initializing this with a zero-capacity)