1use crate::{
8 be::{
9 dbentry::{DbBackup, DbEntry},
10 dbrepl::DbReplMeta,
11 },
12 entry::Entry,
13 filter::{Filter, FilterPlan, FilterResolved, FilterValidResolved},
14 prelude::*,
15 repl::{
16 cid::Cid,
17 proto::ReplCidRange,
18 ruv::{
19 ReplicationUpdateVector, ReplicationUpdateVectorReadTransaction,
20 ReplicationUpdateVectorTransaction, ReplicationUpdateVectorWriteTransaction,
21 },
22 },
23 utils::trigraph_iter,
24 value::{IndexType, Value},
25};
26use concread::cowcell::*;
27use hashbrown::{HashMap, HashSet};
28use idlset::{v2::IDLBitRange, AndNot};
29use kanidm_proto::{
30 backup::BackupCompression,
31 internal::{ConsistencyError, OperationError},
32};
33use std::{
34 collections::BTreeMap,
35 io::prelude::*,
36 ops::DerefMut,
37 path::{Path, PathBuf},
38 sync::Arc,
39 time::Duration,
40};
41use tracing::{trace, trace_span};
42use uuid::Uuid;
43
44use flate2::{write::GzEncoder, Compression};
45
46pub(crate) mod dbentry;
47pub(crate) mod dbrepl;
48pub(crate) mod dbvalue;
49
50mod idl_arc_sqlite;
51mod idl_sqlite;
52pub(crate) mod idxkey;
53pub(crate) mod keystorage;
54
55pub(crate) use self::idxkey::{IdxKey, IdxKeyRef, IdxKeyToRef, IdxSlope};
56use crate::be::idl_arc_sqlite::{
57 IdlArcSqlite, IdlArcSqliteReadTransaction, IdlArcSqliteTransaction,
58 IdlArcSqliteWriteTransaction,
59};
60use kanidm_proto::internal::FsType;
61
62const FILTER_SEARCH_TEST_THRESHOLD: usize = 0;
64const FILTER_EXISTS_TEST_THRESHOLD: usize = 0;
65const FILTER_SUBSTR_TEST_THRESHOLD: usize = 4;
66
67#[derive(Debug, Clone)]
68pub struct Limits {
71 pub unindexed_allow: bool,
72 pub search_max_results: usize,
73 pub search_max_filter_test: usize,
74 pub filter_max_elements: usize,
75}
76
77impl Default for Limits {
78 fn default() -> Self {
79 Limits {
80 unindexed_allow: false,
81 search_max_results: DEFAULT_LIMIT_SEARCH_MAX_RESULTS as usize,
82 search_max_filter_test: DEFAULT_LIMIT_SEARCH_MAX_FILTER_TEST as usize,
83 filter_max_elements: DEFAULT_LIMIT_FILTER_MAX_ELEMENTS as usize,
84 }
85 }
86}
87
88impl Limits {
89 pub fn unlimited() -> Self {
90 Limits {
91 unindexed_allow: true,
92 search_max_results: usize::MAX >> 1,
93 search_max_filter_test: usize::MAX >> 1,
94 filter_max_elements: usize::MAX,
95 }
96 }
97
98 pub fn api_token() -> Self {
99 Limits {
100 unindexed_allow: false,
101 search_max_results: DEFAULT_LIMIT_API_SEARCH_MAX_RESULTS as usize,
102 search_max_filter_test: DEFAULT_LIMIT_API_SEARCH_MAX_FILTER_TEST as usize,
103 filter_max_elements: DEFAULT_LIMIT_FILTER_MAX_ELEMENTS as usize,
104 }
105 }
106}
107
108#[derive(Debug, Clone)]
111pub enum IdList {
112 AllIds,
114 Partial(IDLBitRange),
119 PartialThreshold(IDLBitRange),
123 Indexed(IDLBitRange),
125}
126
127#[derive(Debug)]
128pub struct IdRawEntry {
129 id: u64,
130 data: Vec<u8>,
131}
132
133#[derive(Debug, Clone)]
134pub struct IdxMeta {
135 pub idxkeys: HashMap<IdxKey, IdxSlope>,
136}
137
138impl IdxMeta {
139 pub fn new(idxkeys: HashMap<IdxKey, IdxSlope>) -> Self {
140 IdxMeta { idxkeys }
141 }
142}
143
144#[derive(Clone)]
145pub struct BackendConfig {
146 path: PathBuf,
147 pool_size: u32,
148 db_name: &'static str,
149 fstype: FsType,
150 arcsize: Option<usize>,
152}
153
154impl BackendConfig {
155 pub fn new(
156 path: Option<&Path>,
157 pool_size: u32,
158 fstype: FsType,
159 arcsize: Option<usize>,
160 ) -> Self {
161 BackendConfig {
162 pool_size,
163 path: path.unwrap_or_else(|| Path::new("")).to_path_buf(),
165 db_name: "main",
166 fstype,
167 arcsize,
168 }
169 }
170
171 pub(crate) fn new_test(db_name: &'static str) -> Self {
172 BackendConfig {
173 pool_size: 1,
174 path: PathBuf::from(""),
175 db_name,
176 fstype: FsType::Generic,
177 arcsize: Some(2048),
178 }
179 }
180}
181
182#[derive(Clone)]
183pub struct Backend {
184 idlayer: Arc<IdlArcSqlite>,
186 idxmeta: Arc<CowCell<IdxMeta>>,
191 ruv: Arc<ReplicationUpdateVector>,
195 cfg: BackendConfig,
196}
197
198pub struct BackendReadTransaction<'a> {
199 idlayer: IdlArcSqliteReadTransaction<'a>,
200 idxmeta: CowCellReadTxn<IdxMeta>,
201 ruv: ReplicationUpdateVectorReadTransaction<'a>,
202}
203
204unsafe impl Sync for BackendReadTransaction<'_> {}
205
206unsafe impl Send for BackendReadTransaction<'_> {}
207
208pub struct BackendWriteTransaction<'a> {
209 idlayer: IdlArcSqliteWriteTransaction<'a>,
210 idxmeta_wr: CowCellWriteTxn<'a, IdxMeta>,
211 ruv: ReplicationUpdateVectorWriteTransaction<'a>,
212}
213
214impl IdRawEntry {
215 fn into_dbentry(self) -> Result<(u64, DbEntry), OperationError> {
216 serde_json::from_slice(self.data.as_slice())
217 .map_err(|e| {
218 admin_error!(?e, "Serde JSON Error");
219 OperationError::SerdeJsonError
220 })
221 .map(|dbe| (self.id, dbe))
222 }
223
224 fn into_entry(self) -> Result<EntrySealedCommitted, OperationError> {
225 let db_e = serde_json::from_slice(self.data.as_slice()).map_err(|e| {
226 admin_error!(?e, id = %self.id, "Serde JSON Error");
227 let raw_str = String::from_utf8_lossy(self.data.as_slice());
228 debug!(raw = %raw_str);
229 OperationError::SerdeJsonError
230 })?;
231 Entry::from_dbentry(db_e, self.id).ok_or(OperationError::CorruptedEntry(self.id))
233 }
234}
235
236pub trait BackendTransaction {
237 type IdlLayerType: IdlArcSqliteTransaction;
238 fn get_idlayer(&mut self) -> &mut Self::IdlLayerType;
239
240 type RuvType: ReplicationUpdateVectorTransaction;
241 fn get_ruv(&mut self) -> &mut Self::RuvType;
242
243 fn get_idxmeta_ref(&self) -> &IdxMeta;
244
245 #[allow(clippy::cognitive_complexity)]
248 fn filter2idl(
249 &mut self,
250 filt: &FilterResolved,
251 thres: usize,
252 ) -> Result<(IdList, FilterPlan), OperationError> {
253 Ok(match filt {
254 FilterResolved::Eq(attr, value, idx) => {
255 if idx.is_some() {
256 let idx_key = value.get_idx_eq_key();
258 match self
260 .get_idlayer()
261 .get_idl(attr, IndexType::Equality, &idx_key)?
262 {
263 Some(idl) => (
264 IdList::Indexed(idl),
265 FilterPlan::EqIndexed(attr.clone(), idx_key),
266 ),
267 None => (IdList::AllIds, FilterPlan::EqCorrupt(attr.clone())),
268 }
269 } else {
270 (IdList::AllIds, FilterPlan::EqUnindexed(attr.clone()))
272 }
273 }
274 FilterResolved::Stw(attr, subvalue, idx)
275 | FilterResolved::Enw(attr, subvalue, idx)
276 | FilterResolved::Cnt(attr, subvalue, idx) => {
277 trace!(?idx, ?subvalue, ?attr);
279 if let (true, Some(idx_key)) = (idx.is_some(), subvalue.get_idx_sub_key()) {
280 self.filter2idl_sub(attr, idx_key)?
281 } else {
282 (IdList::AllIds, FilterPlan::SubUnindexed(attr.clone()))
284 }
285 }
286 FilterResolved::Pres(attr, idx) => {
287 if idx.is_some() {
288 match self.get_idlayer().get_idl(attr, IndexType::Presence, "_")? {
290 Some(idl) => (IdList::Indexed(idl), FilterPlan::PresIndexed(attr.clone())),
291 None => (IdList::AllIds, FilterPlan::PresCorrupt(attr.clone())),
292 }
293 } else {
294 (IdList::AllIds, FilterPlan::PresUnindexed(attr.clone()))
296 }
297 }
298 FilterResolved::LessThan(attr, _subvalue, idx) => {
299 if idx.is_some() {
300 match self.get_idlayer().get_idl(attr, IndexType::Presence, "_")? {
305 Some(idl) => (
306 IdList::Partial(idl),
307 FilterPlan::LessThanIndexed(attr.clone()),
308 ),
309 None => (IdList::AllIds, FilterPlan::LessThanCorrupt(attr.clone())),
310 }
311 } else {
312 (IdList::AllIds, FilterPlan::LessThanUnindexed(attr.clone()))
313 }
314 }
315 FilterResolved::Or(l, _) => {
316 let mut plan = Vec::with_capacity(0);
319 let mut result = IDLBitRange::new();
320 let mut partial = false;
321 let mut threshold = false;
322 for f in l.iter() {
324 match self.filter2idl(f, thres)? {
326 (IdList::Indexed(idl), fp) => {
327 plan.push(fp);
328 result = result | idl;
330 }
331 (IdList::Partial(idl), fp) => {
332 plan.push(fp);
333 result = result | idl;
335 partial = true;
336 }
337 (IdList::PartialThreshold(idl), fp) => {
338 plan.push(fp);
339 result = result | idl;
341 partial = true;
342 threshold = true;
343 }
344 (IdList::AllIds, fp) => {
345 plan.push(fp);
346 filter_trace!("Term {:?} is AllIds, shortcut return", f);
348 let setplan = FilterPlan::OrUnindexed(plan);
349 return Ok((IdList::AllIds, setplan));
350 }
351 }
352 } if partial {
355 if threshold {
356 let setplan = FilterPlan::OrPartialThreshold(plan);
357 (IdList::PartialThreshold(result), setplan)
358 } else {
359 let setplan = FilterPlan::OrPartial(plan);
360 (IdList::Partial(result), setplan)
361 }
362 } else {
363 let setplan = FilterPlan::OrIndexed(plan);
364 (IdList::Indexed(result), setplan)
365 }
366 }
367 FilterResolved::And(l, _) => {
368 let (f_andnot, f_rem): (Vec<_>, Vec<_>) = l.iter().partition(|f| f.is_andnot());
374
375 let mut f_rem_iter = f_rem.iter();
378
379 let (mut cand_idl, fp) = match f_rem_iter.next() {
381 Some(f) => self.filter2idl(f, thres)?,
382 None => {
383 filter_warn!(
384 "And filter was empty, or contains only AndNot, can not evaluate."
385 );
386 return Ok((IdList::Indexed(IDLBitRange::new()), FilterPlan::Invalid));
387 }
388 };
389
390 let mut f_rem_count = f_rem.len() + f_andnot.len() - 1;
394
395 let mut plan = vec![fp];
397
398 match &cand_idl {
399 IdList::Indexed(idl) | IdList::Partial(idl) | IdList::PartialThreshold(idl) => {
400 if idl.below_threshold(thres) && f_rem_count > 0 {
404 let setplan = FilterPlan::AndPartialThreshold(plan);
405 return Ok((IdList::PartialThreshold(idl.clone()), setplan));
406 } else if idl.is_empty() {
407 let setplan = FilterPlan::AndEmptyCand(plan);
410 return Ok((IdList::Indexed(IDLBitRange::new()), setplan));
411 }
412 }
413 IdList::AllIds => {}
414 }
415
416 for f in f_rem_iter {
418 f_rem_count -= 1;
419 let (inter, fp) = self.filter2idl(f, thres)?;
420 plan.push(fp);
421 cand_idl = match (cand_idl, inter) {
422 (IdList::Indexed(ia), IdList::Indexed(ib)) => {
423 let r = ia & ib;
424 if r.below_threshold(thres) && f_rem_count > 0 {
425 let setplan = FilterPlan::AndPartialThreshold(plan);
427 return Ok((IdList::PartialThreshold(r), setplan));
428 } else if r.is_empty() {
429 let setplan = FilterPlan::AndEmptyCand(plan);
432 return Ok((IdList::Indexed(IDLBitRange::new()), setplan));
433 } else {
434 IdList::Indexed(r)
435 }
436 }
437 (IdList::Indexed(ia), IdList::Partial(ib))
438 | (IdList::Partial(ia), IdList::Indexed(ib))
439 | (IdList::Partial(ia), IdList::Partial(ib)) => {
440 let r = ia & ib;
441 if r.below_threshold(thres) && f_rem_count > 0 {
442 let setplan = FilterPlan::AndPartialThreshold(plan);
444 return Ok((IdList::PartialThreshold(r), setplan));
445 } else {
446 IdList::Partial(r)
447 }
448 }
449 (IdList::Indexed(ia), IdList::PartialThreshold(ib))
450 | (IdList::PartialThreshold(ia), IdList::Indexed(ib))
451 | (IdList::PartialThreshold(ia), IdList::PartialThreshold(ib))
452 | (IdList::PartialThreshold(ia), IdList::Partial(ib))
453 | (IdList::Partial(ia), IdList::PartialThreshold(ib)) => {
454 let r = ia & ib;
455 if r.below_threshold(thres) && f_rem_count > 0 {
456 let setplan = FilterPlan::AndPartialThreshold(plan);
458 return Ok((IdList::PartialThreshold(r), setplan));
459 } else {
460 IdList::PartialThreshold(r)
461 }
462 }
463 (IdList::Indexed(i), IdList::AllIds)
464 | (IdList::AllIds, IdList::Indexed(i))
465 | (IdList::Partial(i), IdList::AllIds)
466 | (IdList::AllIds, IdList::Partial(i)) => IdList::Partial(i),
467 (IdList::PartialThreshold(i), IdList::AllIds)
468 | (IdList::AllIds, IdList::PartialThreshold(i)) => {
469 IdList::PartialThreshold(i)
470 }
471 (IdList::AllIds, IdList::AllIds) => IdList::AllIds,
472 };
473 }
474
475 for f in f_andnot.iter() {
478 f_rem_count -= 1;
479 let FilterResolved::AndNot(f_in, _) = f else {
480 filter_error!("Invalid server state, a cand filter leaked to andnot set!");
481 return Err(OperationError::InvalidState);
482 };
483 let (inter, fp) = self.filter2idl(f_in, thres)?;
484 plan.push(FilterPlan::AndNot(Box::new(fp)));
486 cand_idl = match (cand_idl, inter) {
487 (IdList::Indexed(ia), IdList::Indexed(ib)) => {
488 let r = ia.andnot(ib);
489 IdList::Indexed(r)
499 }
500 (IdList::Indexed(ia), IdList::Partial(ib))
501 | (IdList::Partial(ia), IdList::Indexed(ib))
502 | (IdList::Partial(ia), IdList::Partial(ib)) => {
503 let r = ia.andnot(ib);
504 if r.below_threshold(thres) && f_rem_count > 0 {
507 let setplan = FilterPlan::AndPartialThreshold(plan);
508 return Ok((IdList::PartialThreshold(r), setplan));
509 } else {
510 IdList::Partial(r)
511 }
512 }
513 (IdList::Indexed(ia), IdList::PartialThreshold(ib))
514 | (IdList::PartialThreshold(ia), IdList::Indexed(ib))
515 | (IdList::PartialThreshold(ia), IdList::PartialThreshold(ib))
516 | (IdList::PartialThreshold(ia), IdList::Partial(ib))
517 | (IdList::Partial(ia), IdList::PartialThreshold(ib)) => {
518 let r = ia.andnot(ib);
519 if r.below_threshold(thres) && f_rem_count > 0 {
522 let setplan = FilterPlan::AndPartialThreshold(plan);
523 return Ok((IdList::PartialThreshold(r), setplan));
524 } else {
525 IdList::PartialThreshold(r)
526 }
527 }
528
529 (IdList::Indexed(_), IdList::AllIds)
530 | (IdList::AllIds, IdList::Indexed(_))
531 | (IdList::Partial(_), IdList::AllIds)
532 | (IdList::AllIds, IdList::Partial(_))
533 | (IdList::PartialThreshold(_), IdList::AllIds)
534 | (IdList::AllIds, IdList::PartialThreshold(_)) => {
535 IdList::AllIds
539 }
540 (IdList::AllIds, IdList::AllIds) => IdList::AllIds,
541 };
542 }
543
544 let setplan = match cand_idl {
546 IdList::Indexed(_) => FilterPlan::AndIndexed(plan),
547 IdList::Partial(_) | IdList::PartialThreshold(_) => {
548 FilterPlan::AndPartial(plan)
549 }
550 IdList::AllIds => FilterPlan::AndUnindexed(plan),
551 };
552
553 (cand_idl, setplan)
556 } FilterResolved::Inclusion(l, _) => {
558 let mut plan = Vec::with_capacity(0);
564 let mut result = IDLBitRange::new();
565 for f in l.iter() {
567 match self.filter2idl(f, thres)? {
569 (IdList::Indexed(idl), fp) => {
570 plan.push(fp);
571 if idl.is_empty() {
572 filter_trace!("Inclusion is unable to proceed - an empty (missing) item was found!");
574 let setplan = FilterPlan::InclusionIndexed(plan);
575 return Ok((IdList::Indexed(IDLBitRange::new()), setplan));
576 } else {
577 result = result | idl;
578 }
579 }
580 (_, fp) => {
581 plan.push(fp);
582 let setplan = FilterPlan::InclusionInvalid(plan);
583 error!(
584 ?setplan,
585 "Inclusion is unable to proceed - all terms must be fully indexed!"
586 );
587 return Ok((IdList::Partial(IDLBitRange::new()), setplan));
588 }
589 }
590 } let setplan = FilterPlan::InclusionIndexed(plan);
593 (IdList::Indexed(result), setplan)
594 }
595 FilterResolved::AndNot(_f, _) => {
600 filter_error!("Requested a top level or isolated AndNot, returning empty");
603 (IdList::Indexed(IDLBitRange::new()), FilterPlan::Invalid)
604 }
605 FilterResolved::Invalid(_) => {
606 (IdList::Indexed(IDLBitRange::new()), FilterPlan::Invalid)
608 }
609 })
610 }
611
612 fn filter2idl_sub(
613 &mut self,
614 attr: &Attribute,
615 sub_idx_key: String,
616 ) -> Result<(IdList, FilterPlan), OperationError> {
617 let mut grapheme_iter = trigraph_iter(&sub_idx_key);
619
620 let mut idl = match grapheme_iter.next() {
627 Some(idx_key) => {
628 match self
629 .get_idlayer()
630 .get_idl(attr, IndexType::SubString, idx_key)?
631 {
632 Some(idl) => idl,
633 None => return Ok((IdList::AllIds, FilterPlan::SubCorrupt(attr.clone()))),
634 }
635 }
636 None => {
637 return Ok((IdList::Indexed(IDLBitRange::new()), FilterPlan::Invalid));
640 }
641 };
642
643 if idl.len() > FILTER_SUBSTR_TEST_THRESHOLD {
644 for idx_key in grapheme_iter {
645 match self
647 .get_idlayer()
648 .get_idl(attr, IndexType::SubString, idx_key)?
649 {
650 Some(r_idl) => {
651 idl = r_idl & idl;
653 }
654 None => {
655 idl = IDLBitRange::new();
657 }
658 };
659
660 if idl.len() < FILTER_SUBSTR_TEST_THRESHOLD {
661 break;
662 }
663 }
664 } else {
665 drop(grapheme_iter);
666 }
667
668 Ok((
670 IdList::Partial(idl),
671 FilterPlan::SubIndexed(attr.clone(), sub_idx_key),
672 ))
673 }
674
675 #[instrument(level = "debug", name = "be::search", skip_all)]
676 fn search(
677 &mut self,
678 erl: &Limits,
679 filt: &Filter<FilterValidResolved>,
680 ) -> Result<Vec<Arc<EntrySealedCommitted>>, OperationError> {
681 trace!(filter_optimised = ?filt);
685
686 let (idl, fplan) = trace_span!("be::search -> filter2idl")
687 .in_scope(|| self.filter2idl(filt.to_inner(), FILTER_SEARCH_TEST_THRESHOLD))?;
688
689 debug!(search_filter_executed_plan = %fplan);
690
691 match &idl {
692 IdList::AllIds => {
693 if !erl.unindexed_allow {
694 admin_error!(
695 "filter (search) is fully unindexed, and not allowed by resource limits"
696 );
697 return Err(OperationError::ResourceLimit);
698 }
699 }
700 IdList::Partial(idl_br) => {
701 if !idl_br.below_threshold(erl.search_max_filter_test) {
703 admin_error!("filter (search) is partial indexed and greater than search_max_filter_test allowed by resource limits");
704 return Err(OperationError::ResourceLimit);
705 }
706 }
707 IdList::PartialThreshold(_) => {
708 }
711 IdList::Indexed(idl_br) => {
712 if !idl_br.below_threshold(erl.search_max_results) {
717 admin_error!("filter (search) is indexed and greater than search_max_results allowed by resource limits");
718 return Err(OperationError::ResourceLimit);
719 }
720 }
721 };
722
723 let entries = self.get_idlayer().get_identry(&idl).map_err(|e| {
724 admin_error!(?e, "get_identry failed");
725 e
726 })?;
727
728 let mut entries_filtered = match idl {
729 IdList::AllIds => trace_span!("be::search<entry::ftest::allids>").in_scope(|| {
730 entries
731 .into_iter()
732 .filter(|e| e.entry_match_no_index(filt))
733 .collect()
734 }),
735 IdList::Partial(_) => trace_span!("be::search<entry::ftest::partial>").in_scope(|| {
736 entries
737 .into_iter()
738 .filter(|e| e.entry_match_no_index(filt))
739 .collect()
740 }),
741 IdList::PartialThreshold(_) => trace_span!("be::search<entry::ftest::thresh>")
742 .in_scope(|| {
743 entries
744 .into_iter()
745 .filter(|e| e.entry_match_no_index(filt))
746 .collect()
747 }),
748 IdList::Indexed(_) => {
750 filter_trace!("filter (search) was fully indexed 👏");
751 entries
752 }
753 };
754
755 if entries_filtered.len() > erl.search_max_results {
758 admin_error!("filter (search) is resolved and greater than search_max_results allowed by resource limits");
759 return Err(OperationError::ResourceLimit);
760 }
761
762 entries_filtered.shrink_to_fit();
764
765 Ok(entries_filtered)
766 }
767
768 #[instrument(level = "debug", name = "be::exists", skip_all)]
773 fn exists(
774 &mut self,
775 erl: &Limits,
776 filt: &Filter<FilterValidResolved>,
777 ) -> Result<bool, OperationError> {
778 trace!(filter_optimised = ?filt);
779
780 let (idl, fplan) = trace_span!("be::exists -> filter2idl")
783 .in_scope(|| self.filter2idl(filt.to_inner(), FILTER_EXISTS_TEST_THRESHOLD))?;
784
785 debug!(exist_filter_executed_plan = %fplan);
786
787 match &idl {
789 IdList::AllIds => {
790 if !erl.unindexed_allow {
791 admin_error!(
792 "filter (exists) is fully unindexed, and not allowed by resource limits"
793 );
794 return Err(OperationError::ResourceLimit);
795 }
796 }
797 IdList::Partial(idl_br) => {
798 if !idl_br.below_threshold(erl.search_max_filter_test) {
799 admin_error!("filter (exists) is partial indexed and greater than search_max_filter_test allowed by resource limits");
800 return Err(OperationError::ResourceLimit);
801 }
802 }
803 IdList::PartialThreshold(_) => {
804 }
807 IdList::Indexed(_) => {}
808 }
809
810 match &idl {
813 IdList::Indexed(idl) => Ok(!idl.is_empty()),
814 _ => {
815 let entries = self.get_idlayer().get_identry(&idl).map_err(|e| {
816 admin_error!(?e, "get_identry failed");
817 e
818 })?;
819
820 let entries_filtered: Vec<_> =
822 trace_span!("be::exists<entry::ftest>").in_scope(|| {
823 entries
824 .into_iter()
825 .filter(|e| e.entry_match_no_index(filt))
826 .collect()
827 });
828
829 Ok(!entries_filtered.is_empty())
830 }
831 } }
833
834 fn retrieve_range(
835 &mut self,
836 ranges: &BTreeMap<Uuid, ReplCidRange>,
837 ) -> Result<Vec<Arc<EntrySealedCommitted>>, OperationError> {
838 let idl = self.get_ruv().range_to_idl(ranges);
842 if idl.is_empty() {
849 return Ok(Vec::with_capacity(0));
851 }
852
853 let id_list = IdList::Indexed(idl);
855
856 self.get_idlayer().get_identry(&id_list).map_err(|e| {
857 admin_error!(?e, "get_identry failed");
858 e
859 })
860 }
861
862 fn verify(&mut self) -> Vec<Result<(), ConsistencyError>> {
863 self.get_idlayer().verify()
864 }
865
866 fn verify_entry_index(&mut self, e: &EntrySealedCommitted) -> Result<(), ConsistencyError> {
867 if e.mask_recycled_ts().is_some() {
869 let e_uuid = e.get_uuid();
870 let (n2u_add, n2u_rem) = Entry::idx_name2uuid_diff(None, Some(e));
872
873 let (Some(n2u_set), None) = (n2u_add, n2u_rem) else {
874 admin_error!("Invalid idx_name2uuid_diff state");
875 return Err(ConsistencyError::BackendIndexSync);
876 };
877
878 n2u_set
880 .iter()
881 .try_for_each(|name| match self.get_idlayer().name2uuid(name) {
882 Ok(Some(idx_uuid)) => {
883 if idx_uuid == e_uuid {
884 Ok(())
885 } else {
886 admin_error!("Invalid name2uuid state -> incorrect uuid association");
887 Err(ConsistencyError::BackendIndexSync)
888 }
889 }
890 r => {
891 admin_error!(state = ?r, "Invalid name2uuid state");
892 Err(ConsistencyError::BackendIndexSync)
893 }
894 })?;
895
896 let spn = e.get_uuid2spn();
897 match self.get_idlayer().uuid2spn(e_uuid) {
898 Ok(Some(idx_spn)) => {
899 if spn != idx_spn {
900 admin_error!("Invalid uuid2spn state -> incorrect idx spn value");
901 return Err(ConsistencyError::BackendIndexSync);
902 }
903 }
904 r => {
905 admin_error!(state = ?r, ?e_uuid, "Invalid uuid2spn state");
906 trace!(entry = ?e);
907 return Err(ConsistencyError::BackendIndexSync);
908 }
909 };
910
911 let rdn = e.get_uuid2rdn();
912 match self.get_idlayer().uuid2rdn(e_uuid) {
913 Ok(Some(idx_rdn)) => {
914 if rdn != idx_rdn {
915 admin_error!("Invalid uuid2rdn state -> incorrect idx rdn value");
916 return Err(ConsistencyError::BackendIndexSync);
917 }
918 }
919 r => {
920 admin_error!(state = ?r, "Invalid uuid2rdn state");
921 return Err(ConsistencyError::BackendIndexSync);
922 }
923 };
924 }
925
926 Ok(())
933 }
934
935 fn verify_indexes(&mut self) -> Vec<Result<(), ConsistencyError>> {
936 let idl = IdList::AllIds;
937 let entries = match self.get_idlayer().get_identry(&idl) {
938 Ok(s) => s,
939 Err(e) => {
940 admin_error!(?e, "get_identry failure");
941 return vec![Err(ConsistencyError::Unknown)];
942 }
943 };
944
945 let r = entries.iter().try_for_each(|e| self.verify_entry_index(e));
946
947 if r.is_err() {
948 vec![r]
949 } else {
950 Vec::with_capacity(0)
951 }
952 }
953
954 fn verify_ruv(&mut self, results: &mut Vec<Result<(), ConsistencyError>>) {
955 let idl = IdList::AllIds;
957 let entries = match self.get_idlayer().get_identry(&idl) {
958 Ok(ent) => ent,
959 Err(e) => {
960 results.push(Err(ConsistencyError::Unknown));
961 admin_error!(?e, "get_identry failed");
962 return;
963 }
964 };
965
966 self.get_ruv().verify(&entries, results);
967 }
968
969 fn backup<OUT>(
970 &mut self,
971 mut output: OUT,
972 compression: BackupCompression,
973 ) -> Result<(), OperationError>
974 where
975 OUT: std::io::Write,
976 {
977 let repl_meta = self.get_ruv().to_db_backup_ruv();
978
979 let idl = IdList::AllIds;
982 let idlayer = self.get_idlayer();
983 let raw_entries: Vec<IdRawEntry> = idlayer.get_identry_raw(&idl)?;
984
985 let entries: Result<Vec<DbEntry>, _> = raw_entries
986 .iter()
987 .map(|id_ent| {
988 serde_json::from_slice(id_ent.data.as_slice())
989 .map_err(|_| OperationError::SerdeJsonError) })
991 .collect();
992
993 let entries = entries?;
994
995 let db_s_uuid = idlayer
996 .get_db_s_uuid()
997 .and_then(|u| u.ok_or(OperationError::InvalidDbState))?;
998 let db_d_uuid = idlayer
999 .get_db_d_uuid()
1000 .and_then(|u| u.ok_or(OperationError::InvalidDbState))?;
1001 let db_ts_max = idlayer
1002 .get_db_ts_max()
1003 .and_then(|u| u.ok_or(OperationError::InvalidDbState))?;
1004
1005 let keyhandles = idlayer.get_key_handles()?;
1006
1007 let bak = DbBackup::V5 {
1008 version: env!("KANIDM_PKG_SERIES").to_string(),
1010 db_s_uuid,
1011 db_d_uuid,
1012 db_ts_max,
1013 keyhandles,
1014 repl_meta,
1015 entries,
1016 };
1017
1018 let serialized_entries_str = serde_json::to_string(&bak).map_err(|e| {
1019 admin_error!(?e, "serde error");
1020 OperationError::SerdeJsonError
1021 })?;
1022
1023 match compression {
1024 BackupCompression::NoCompression => {
1025 output
1026 .write(serialized_entries_str.as_bytes())
1027 .map_err(|e| {
1028 error!(?e, "fs::write error");
1029 OperationError::FsError
1030 })?;
1031 }
1032 BackupCompression::Gzip => {
1033 let mut encoder = GzEncoder::new(&mut output, Compression::best());
1034 encoder
1035 .write_all(serialized_entries_str.as_bytes())
1036 .map_err(|e| {
1037 error!(?e, "Gzip compression error writing backup");
1038 OperationError::FsError
1039 })?;
1040 }
1041 }
1042
1043 output.flush().map_err(|err| {
1044 error!(?err, "Unable to flush backup output stream");
1045 OperationError::FsError
1046 })?;
1047
1048 Ok(())
1049 }
1050
1051 fn name2uuid(&mut self, name: &str) -> Result<Option<Uuid>, OperationError> {
1052 self.get_idlayer().name2uuid(name)
1053 }
1054
1055 fn externalid2uuid(&mut self, name: &str) -> Result<Option<Uuid>, OperationError> {
1056 self.get_idlayer().externalid2uuid(name)
1057 }
1058
1059 fn uuid2spn(&mut self, uuid: Uuid) -> Result<Option<Value>, OperationError> {
1060 self.get_idlayer().uuid2spn(uuid)
1061 }
1062
1063 fn uuid2rdn(&mut self, uuid: Uuid) -> Result<Option<String>, OperationError> {
1064 self.get_idlayer().uuid2rdn(uuid)
1065 }
1066}
1067
1068impl<'a> BackendTransaction for BackendReadTransaction<'a> {
1069 type IdlLayerType = IdlArcSqliteReadTransaction<'a>;
1070 type RuvType = ReplicationUpdateVectorReadTransaction<'a>;
1071
1072 fn get_idlayer(&mut self) -> &mut IdlArcSqliteReadTransaction<'a> {
1073 &mut self.idlayer
1074 }
1075
1076 fn get_ruv(&mut self) -> &mut ReplicationUpdateVectorReadTransaction<'a> {
1077 &mut self.ruv
1078 }
1079
1080 fn get_idxmeta_ref(&self) -> &IdxMeta {
1081 &self.idxmeta
1082 }
1083}
1084
1085impl BackendReadTransaction<'_> {
1086 pub fn list_indexes(&mut self) -> Result<Vec<String>, OperationError> {
1087 self.get_idlayer().list_idxs()
1088 }
1089
1090 pub fn list_id2entry(&mut self) -> Result<Vec<(u64, String)>, OperationError> {
1091 self.get_idlayer().list_id2entry()
1092 }
1093
1094 pub fn list_index_content(
1095 &mut self,
1096 index_name: &str,
1097 ) -> Result<Vec<(String, IDLBitRange)>, OperationError> {
1098 self.get_idlayer().list_index_content(index_name)
1099 }
1100
1101 pub fn get_id2entry(&mut self, id: u64) -> Result<(u64, String), OperationError> {
1102 self.get_idlayer().get_id2entry(id)
1103 }
1104
1105 pub fn list_quarantined(&mut self) -> Result<Vec<(u64, String)>, OperationError> {
1106 self.get_idlayer().list_quarantined()
1107 }
1108}
1109
1110impl<'a> BackendTransaction for BackendWriteTransaction<'a> {
1111 type IdlLayerType = IdlArcSqliteWriteTransaction<'a>;
1112 type RuvType = ReplicationUpdateVectorWriteTransaction<'a>;
1113
1114 fn get_idlayer(&mut self) -> &mut IdlArcSqliteWriteTransaction<'a> {
1115 &mut self.idlayer
1116 }
1117
1118 fn get_ruv(&mut self) -> &mut ReplicationUpdateVectorWriteTransaction<'a> {
1119 &mut self.ruv
1120 }
1121
1122 fn get_idxmeta_ref(&self) -> &IdxMeta {
1123 &self.idxmeta_wr
1124 }
1125}
1126
1127impl<'a> BackendWriteTransaction<'a> {
1128 pub(crate) fn get_ruv_write(&mut self) -> &mut ReplicationUpdateVectorWriteTransaction<'a> {
1129 &mut self.ruv
1130 }
1131
1132 #[instrument(level = "debug", name = "be::create", skip_all)]
1133 pub fn create(
1134 &mut self,
1135 cid: &Cid,
1136 entries: Vec<EntrySealedNew>,
1137 ) -> Result<Vec<EntrySealedCommitted>, OperationError> {
1138 if entries.is_empty() {
1139 admin_error!("No entries provided to BE to create, invalid server call!");
1140 return Err(OperationError::EmptyRequest);
1141 }
1142
1143 entries.iter().try_for_each(|e| {
1146 if e.get_changestate().contains_tail_cid(cid) {
1147 Ok(())
1148 } else {
1149 admin_error!(
1150 "Entry changelog does not contain a change related to this transaction"
1151 );
1152 Err(OperationError::ReplEntryNotChanged)
1153 }
1154 })?;
1155
1156 let mut id_max = self.idlayer.get_id2entry_max_id()?;
1159 let c_entries: Vec<_> = entries
1160 .into_iter()
1161 .map(|e| {
1162 id_max += 1;
1163 e.into_sealed_committed_id(id_max)
1164 })
1165 .collect();
1166
1167 let ruv_idl = IDLBitRange::from_iter(c_entries.iter().map(|e| e.get_id()));
1170
1171 self.get_ruv().insert_change(cid, ruv_idl)?;
1173
1174 self.idlayer.write_identries(c_entries.iter())?;
1175
1176 self.idlayer.set_id2entry_max_id(id_max);
1177
1178 for e in c_entries.iter() {
1180 self.entry_index(None, Some(e))?
1181 }
1182
1183 Ok(c_entries)
1184 }
1185
1186 #[instrument(level = "debug", name = "be::create", skip_all)]
1187 pub fn refresh(
1192 &mut self,
1193 entries: Vec<EntrySealedNew>,
1194 ) -> Result<Vec<EntrySealedCommitted>, OperationError> {
1195 if entries.is_empty() {
1196 admin_error!("No entries provided to BE to create, invalid server call!");
1197 return Err(OperationError::EmptyRequest);
1198 }
1199
1200 let mut id_max = self.idlayer.get_id2entry_max_id()?;
1202 let c_entries: Vec<_> = entries
1203 .into_iter()
1204 .map(|e| {
1205 id_max += 1;
1206 e.into_sealed_committed_id(id_max)
1207 })
1208 .collect();
1209
1210 self.idlayer.write_identries(c_entries.iter())?;
1211
1212 self.idlayer.set_id2entry_max_id(id_max);
1213
1214 for e in c_entries.iter() {
1216 self.get_ruv().update_entry_changestate(e)?;
1217 }
1218
1219 for e in c_entries.iter() {
1221 self.entry_index(None, Some(e))?
1222 }
1223
1224 Ok(c_entries)
1225 }
1226
1227 #[instrument(level = "debug", name = "be::modify", skip_all)]
1228 pub fn modify(
1229 &mut self,
1230 cid: &Cid,
1231 pre_entries: &[Arc<EntrySealedCommitted>],
1232 post_entries: &[EntrySealedCommitted],
1233 ) -> Result<(), OperationError> {
1234 if post_entries.is_empty() || pre_entries.is_empty() {
1235 admin_error!("No entries provided to BE to modify, invalid server call!");
1236 return Err(OperationError::EmptyRequest);
1237 }
1238
1239 assert_eq!(post_entries.len(), pre_entries.len());
1240
1241 let post_entries_iter = post_entries.iter().filter(|e| {
1242 trace!(?cid);
1243 trace!(changestate = ?e.get_changestate());
1244 e.get_changestate().contains_tail_cid(cid)
1250 });
1251
1252 let ruv_idl = IDLBitRange::from_iter(post_entries_iter.map(|e| e.get_id()));
1255
1256 if !ruv_idl.is_empty() {
1257 self.get_ruv().insert_change(cid, ruv_idl)?;
1258 }
1259
1260 self.get_idlayer().write_identries(post_entries.iter())?;
1262
1263 pre_entries
1266 .iter()
1267 .zip(post_entries.iter())
1268 .try_for_each(|(pre, post)| self.entry_index(Some(pre.as_ref()), Some(post)))
1269 }
1270
1271 #[instrument(level = "debug", name = "be::incremental_prepare", skip_all)]
1272 pub fn incremental_prepare(
1273 &mut self,
1274 entry_meta: &[EntryIncrementalNew],
1275 ) -> Result<Vec<Arc<EntrySealedCommitted>>, OperationError> {
1276 let mut ret_entries = Vec::with_capacity(entry_meta.len());
1277 let id_max_pre = self.idlayer.get_id2entry_max_id()?;
1278 let mut id_max = id_max_pre;
1279
1280 for ctx_ent in entry_meta.iter() {
1281 let ctx_ent_uuid = ctx_ent.get_uuid();
1282 let idx_key = ctx_ent_uuid.as_hyphenated().to_string();
1283
1284 let idl =
1285 self.get_idlayer()
1286 .get_idl(&Attribute::Uuid, IndexType::Equality, &idx_key)?;
1287
1288 let entry = match idl {
1289 Some(idl) if idl.is_empty() => {
1290 id_max += 1;
1293
1294 let stub_entry = Arc::new(EntrySealedCommitted::stub_sealed_committed_id(
1295 id_max, ctx_ent,
1296 ));
1297 self.entry_index(None, Some(stub_entry.as_ref()))?;
1300
1301 stub_entry
1303 }
1304 Some(idl) if idl.len() == 1 => {
1305 let mut entries = self
1307 .get_idlayer()
1308 .get_identry(&IdList::Indexed(idl))
1309 .map_err(|e| {
1310 admin_error!(?e, "get_identry failed");
1311 e
1312 })?;
1313
1314 if let Some(entry) = entries.pop() {
1315 entry
1317 } else {
1318 error!("Invalid entry state, index was unable to locate entry");
1319 return Err(OperationError::InvalidDbState);
1320 }
1321 }
1323 Some(idl) => {
1324 error!(uuid = ?ctx_ent_uuid, "Invalid IDL state, uuid index must have only a single or no values. Contains {:?}", idl);
1326 return Err(OperationError::InvalidDbState);
1327 }
1328 None => {
1329 error!(uuid = ?ctx_ent_uuid, "Invalid IDL state, uuid index must be present");
1331 return Err(OperationError::InvalidDbState);
1332 }
1333 };
1334
1335 ret_entries.push(entry);
1336 }
1337
1338 if id_max != id_max_pre {
1339 self.idlayer.set_id2entry_max_id(id_max);
1340 }
1341
1342 Ok(ret_entries)
1343 }
1344
1345 #[instrument(level = "debug", name = "be::incremental_apply", skip_all)]
1346 pub fn incremental_apply(
1347 &mut self,
1348 update_entries: &[(EntrySealedCommitted, Arc<EntrySealedCommitted>)],
1349 create_entries: Vec<EntrySealedNew>,
1350 ) -> Result<(), OperationError> {
1351 if !create_entries.is_empty() {
1354 let mut id_max = self.idlayer.get_id2entry_max_id()?;
1356 let c_entries: Vec<_> = create_entries
1357 .into_iter()
1358 .map(|e| {
1359 id_max += 1;
1360 e.into_sealed_committed_id(id_max)
1361 })
1362 .collect();
1363
1364 self.idlayer.write_identries(c_entries.iter())?;
1365
1366 self.idlayer.set_id2entry_max_id(id_max);
1367
1368 for e in c_entries.iter() {
1370 self.get_ruv().update_entry_changestate(e)?;
1371 }
1372
1373 for e in c_entries.iter() {
1375 self.entry_index(None, Some(e))?
1376 }
1377 }
1378
1379 if !update_entries.is_empty() {
1381 self.get_idlayer()
1382 .write_identries(update_entries.iter().map(|(up, _)| up))?;
1383
1384 for (e, _) in update_entries.iter() {
1385 self.get_ruv().update_entry_changestate(e)?;
1386 }
1387
1388 for (post, pre) in update_entries.iter() {
1389 self.entry_index(Some(pre.as_ref()), Some(post))?
1390 }
1391 }
1392
1393 Ok(())
1394 }
1395
1396 #[instrument(level = "debug", name = "be::reap_tombstones", skip_all)]
1397 pub fn reap_tombstones(&mut self, cid: &Cid, trim_cid: &Cid) -> Result<usize, OperationError> {
1398 debug_assert!(cid > trim_cid);
1399 self.get_ruv().insert_change(cid, IDLBitRange::default())?;
1402
1403 let idl = self.get_ruv().trim_up_to(trim_cid).map_err(|e| {
1406 admin_error!(
1407 ?e,
1408 "During tombstone cleanup, failed to trim RUV to {:?}",
1409 trim_cid
1410 );
1411 e
1412 })?;
1413
1414 let entries = self
1415 .get_idlayer()
1416 .get_identry(&IdList::Indexed(idl))
1417 .map_err(|e| {
1418 admin_error!(?e, "get_identry failed");
1419 e
1420 })?;
1421
1422 if entries.is_empty() {
1423 admin_debug!("No entries affected - reap_tombstones operation success");
1424 return Ok(0);
1425 }
1426
1427 let (tombstones, leftover): (Vec<_>, Vec<_>) = entries
1441 .into_iter()
1442 .partition(|e| e.get_changestate().can_delete(trim_cid));
1443
1444 let ruv_idls = self.get_ruv().ruv_idls();
1445
1446 if !leftover
1450 .iter()
1451 .all(|e| e.get_changestate().is_live() || ruv_idls.contains(e.get_id()))
1452 {
1453 admin_error!("Left over entries may be orphaned due to missing RUV entries");
1454 return Err(OperationError::ReplInvalidRUVState);
1455 }
1456
1457 let id_list: IDLBitRange = tombstones.iter().map(|e| e.get_id()).collect();
1462
1463 if !((&ruv_idls & &id_list).is_empty()) {
1466 admin_error!("RUV still contains entries that are going to be removed.");
1467 return Err(OperationError::ReplInvalidRUVState);
1468 }
1469
1470 let sz = id_list.len();
1472 self.get_idlayer().delete_identry(id_list.into_iter())?;
1473
1474 tombstones
1477 .iter()
1478 .try_for_each(|e| self.entry_index(Some(e), None))?;
1479
1480 Ok(sz)
1481 }
1482
1483 #[instrument(level = "debug", name = "be::update_idxmeta", skip_all)]
1484 pub fn update_idxmeta(&mut self, idxkeys: Vec<IdxKey>) -> Result<(), OperationError> {
1485 if self.is_idx_slopeyness_generated()? {
1486 trace!("Indexing slopes available");
1487 } else {
1488 warn!("No indexing slopes available. You should consider reindexing to generate these");
1489 };
1490
1491 let mut idxkeys = idxkeys
1500 .into_iter()
1501 .map(|k| self.get_idx_slope(&k).map(|slope| (k, slope)))
1502 .collect::<Result<HashMap<_, _>, _>>()?;
1503
1504 std::mem::swap(&mut self.idxmeta_wr.deref_mut().idxkeys, &mut idxkeys);
1505 Ok(())
1506 }
1507
1508 #[allow(clippy::cognitive_complexity)]
1518 fn entry_index(
1519 &mut self,
1520 pre: Option<&EntrySealedCommitted>,
1521 post: Option<&EntrySealedCommitted>,
1522 ) -> Result<(), OperationError> {
1523 let (e_uuid, e_id, uuid_same) = match (pre, post) {
1524 (None, None) => {
1525 admin_error!("Invalid call to entry_index - no entries provided");
1526 return Err(OperationError::InvalidState);
1527 }
1528 (Some(pre), None) => {
1529 trace!("Attempting to remove entry indexes");
1530 (pre.get_uuid(), pre.get_id(), true)
1531 }
1532 (None, Some(post)) => {
1533 trace!("Attempting to create entry indexes");
1534 (post.get_uuid(), post.get_id(), true)
1535 }
1536 (Some(pre), Some(post)) => {
1537 trace!("Attempting to modify entry indexes");
1538 assert_eq!(pre.get_id(), post.get_id());
1539 (
1540 post.get_uuid(),
1541 post.get_id(),
1542 pre.get_uuid() == post.get_uuid(),
1543 )
1544 }
1545 };
1546
1547 let mask_pre = pre.and_then(|e| e.mask_recycled_ts());
1552 let mask_pre = if !uuid_same {
1553 let uuid = mask_pre.map(|e| e.get_uuid()).ok_or_else(|| {
1559 admin_error!("Invalid entry state - possible memory corruption");
1560 OperationError::InvalidState
1561 })?;
1562
1563 let (n2u_add, n2u_rem) = Entry::idx_name2uuid_diff(mask_pre, None);
1564 assert!(n2u_add.is_none());
1566
1567 let (eid2u_add, eid2u_rem) = Entry::idx_externalid2uuid_diff(mask_pre, None);
1568 assert!(eid2u_add.is_none());
1570
1571 let u2s_act = Entry::idx_uuid2spn_diff(mask_pre, None);
1572 let u2r_act = Entry::idx_uuid2rdn_diff(mask_pre, None);
1573
1574 trace!(?n2u_rem, ?eid2u_rem, ?u2s_act, ?u2r_act,);
1575
1576 if let Some(rem) = n2u_rem {
1578 self.idlayer.write_name2uuid_rem(rem)?
1579 }
1580
1581 if let Some(rem) = eid2u_rem {
1582 self.idlayer.write_externalid2uuid_rem(rem)?
1583 }
1584
1585 match u2s_act {
1586 None => {}
1587 Some(Ok(k)) => self.idlayer.write_uuid2spn(uuid, Some(k))?,
1588 Some(Err(_)) => self.idlayer.write_uuid2spn(uuid, None)?,
1589 }
1590
1591 match u2r_act {
1592 None => {}
1593 Some(Ok(k)) => self.idlayer.write_uuid2rdn(uuid, Some(k))?,
1594 Some(Err(_)) => self.idlayer.write_uuid2rdn(uuid, None)?,
1595 }
1596 None
1598 } else {
1599 mask_pre
1601 };
1602
1603 let mask_post = post.and_then(|e| e.mask_recycled_ts());
1604 let (n2u_add, n2u_rem) = Entry::idx_name2uuid_diff(mask_pre, mask_post);
1605 let (eid2u_add, eid2u_rem) = Entry::idx_externalid2uuid_diff(mask_pre, mask_post);
1606
1607 let u2s_act = Entry::idx_uuid2spn_diff(mask_pre, mask_post);
1608 let u2r_act = Entry::idx_uuid2rdn_diff(mask_pre, mask_post);
1609
1610 trace!(
1611 ?n2u_add,
1612 ?n2u_rem,
1613 ?eid2u_add,
1614 ?eid2u_rem,
1615 ?u2s_act,
1616 ?u2r_act
1617 );
1618
1619 if let Some(add) = n2u_add {
1621 self.idlayer.write_name2uuid_add(e_uuid, add)?
1622 }
1623 if let Some(rem) = n2u_rem {
1624 self.idlayer.write_name2uuid_rem(rem)?
1625 }
1626
1627 if let Some(add) = eid2u_add {
1628 self.idlayer.write_externalid2uuid_add(e_uuid, add)?
1629 }
1630 if let Some(rem) = eid2u_rem {
1631 self.idlayer.write_externalid2uuid_rem(rem)?
1632 }
1633
1634 match u2s_act {
1635 None => {}
1636 Some(Ok(k)) => self.idlayer.write_uuid2spn(e_uuid, Some(k))?,
1637 Some(Err(_)) => self.idlayer.write_uuid2spn(e_uuid, None)?,
1638 }
1639
1640 match u2r_act {
1641 None => {}
1642 Some(Ok(k)) => self.idlayer.write_uuid2rdn(e_uuid, Some(k))?,
1643 Some(Err(_)) => self.idlayer.write_uuid2rdn(e_uuid, None)?,
1644 }
1645
1646 let idxmeta = unsafe { &(*(&self.idxmeta_wr.idxkeys as *const _)) };
1653
1654 let idx_diff = Entry::idx_diff(idxmeta, pre, post);
1655
1656 idx_diff.into_iter()
1657 .try_for_each(|act| {
1658 match act {
1659 Ok((attr, itype, idx_key)) => {
1660 trace!("Adding {:?} idx -> {:?}: {:?}", itype, attr, idx_key);
1661 match self.idlayer.get_idl(attr, itype, &idx_key)? {
1662 Some(mut idl) => {
1663 idl.insert_id(e_id);
1664 if cfg!(debug_assertions)
1665 && *attr == Attribute::Uuid && itype == IndexType::Equality {
1666 if idl.len() > 1 {
1668 trace!(duplicate_idl = ?idl, ?idx_key);
1669 }
1670 debug_assert!(idl.len() <= 1);
1671 }
1672 self.idlayer.write_idl(attr, itype, &idx_key, &idl)
1673 }
1674 None => {
1675 warn!(
1676 "WARNING: index {:?} {:?} was not found. YOU MUST REINDEX YOUR DATABASE",
1677 attr, itype
1678 );
1679 Ok(())
1680 }
1681 }
1682 }
1683 Err((attr, itype, idx_key)) => {
1684 trace!("Removing {:?} idx -> {:?}: {:?}", itype, attr, idx_key);
1685 match self.idlayer.get_idl(attr, itype, &idx_key)? {
1686 Some(mut idl) => {
1687 idl.remove_id(e_id);
1688 if cfg!(debug_assertions) && *attr == Attribute::Uuid && itype == IndexType::Equality {
1689 if idl.len() > 1 {
1691 trace!(duplicate_idl = ?idl, ?idx_key);
1692 }
1693 debug_assert!(idl.len() <= 1);
1694 }
1695 self.idlayer.write_idl(attr, itype, &idx_key, &idl)
1696 }
1697 None => {
1698 warn!(
1699 "WARNING: index {:?} {:?} was not found. YOU MUST REINDEX YOUR DATABASE",
1700 attr, itype
1701 );
1702 Ok(())
1703 }
1704 }
1705 }
1706 }
1707 })
1708 }
1710
1711 #[allow(dead_code)]
1712 fn missing_idxs(&mut self) -> Result<Vec<(Attribute, IndexType)>, OperationError> {
1713 let idx_table_list = self.get_idlayer().list_idxs()?;
1714
1715 let idx_table_set: HashSet<_> = idx_table_list.into_iter().collect();
1717
1718 let missing: Vec<_> = self
1719 .idxmeta_wr
1720 .idxkeys
1721 .keys()
1722 .filter_map(|ikey| {
1723 let tname = format!("idx_{}_{}", ikey.itype.as_idx_str(), ikey.attr.as_str());
1725 trace!("Checking for {}", tname);
1726
1727 if idx_table_set.contains(&tname) {
1728 None
1729 } else {
1730 Some((ikey.attr.clone(), ikey.itype))
1731 }
1732 })
1733 .collect();
1734 Ok(missing)
1735 }
1736
1737 fn create_idxs(&mut self) -> Result<(), OperationError> {
1738 trace!("Creating index -> name2uuid");
1740 self.idlayer.create_name2uuid()?;
1741
1742 trace!("Creating index -> externalid2uuid");
1743 self.idlayer.create_externalid2uuid()?;
1744
1745 trace!("Creating index -> uuid2spn");
1746 self.idlayer.create_uuid2spn()?;
1747
1748 trace!("Creating index -> uuid2rdn");
1749 self.idlayer.create_uuid2rdn()?;
1750
1751 self.idxmeta_wr
1752 .idxkeys
1753 .keys()
1754 .try_for_each(|ikey| self.idlayer.create_idx(&ikey.attr, ikey.itype))
1755 }
1756
1757 pub fn upgrade_reindex(&mut self, v: i64) -> Result<(), OperationError> {
1758 let dbv = self.get_db_index_version()?;
1759 admin_debug!(?dbv, ?v, "upgrade_reindex");
1760 if dbv < v {
1761 self.reindex(false)?;
1762 self.set_db_index_version(v)
1763 } else {
1764 Ok(())
1765 }
1766 }
1767
1768 #[instrument(level = "info", skip_all)]
1769 pub fn reindex(&mut self, immediate: bool) -> Result<(), OperationError> {
1770 let notice_immediate = immediate || (cfg!(not(test)) && cfg!(not(debug_assertions)));
1771
1772 info!(
1773 immediate = notice_immediate,
1774 "System reindex: started - this may take a long time!"
1775 );
1776
1777 self.idlayer.danger_purge_idxs()?;
1780
1781 self.create_idxs()?;
1784
1785 let idl = IdList::AllIds;
1789 let entries = self.idlayer.get_identry(&idl).inspect_err(|err| {
1790 error!(?err, "get_identry failure");
1791 })?;
1792
1793 let mut count = 0;
1794
1795 entries
1797 .iter()
1798 .try_for_each(|e| {
1799 if immediate {
1800 count += 1;
1801 if count % 2500 == 0 {
1802 eprint!("{count}");
1803 } else if count % 250 == 0 {
1804 eprint!(".");
1805 }
1806 }
1807
1808 self.entry_index(None, Some(e))
1809 })
1810 .inspect_err(|err| {
1811 error!(?err, "reindex failed");
1812 })?;
1813
1814 if immediate {
1815 eprintln!(" done ✅");
1816 }
1817
1818 info!(immediate, "Reindexed {count} entries");
1819
1820 info!("Optimising Indexes: started");
1821 self.idlayer.optimise_dirty_idls();
1822 info!("Optimising Indexes: complete ✅");
1823 info!("Calculating Index Optimisation Slopes: started");
1824 self.idlayer.analyse_idx_slopes().inspect_err(|err| {
1825 error!(?err, "index optimisation failed");
1826 })?;
1827 info!("Calculating Index Optimisation Slopes: complete ✅");
1828 info!("System reindex: complete 🎉");
1829 Ok(())
1830 }
1831
1832 fn danger_purge_idxs(&mut self) -> Result<(), OperationError> {
1837 self.get_idlayer().danger_purge_idxs()
1838 }
1839
1840 pub(crate) fn danger_delete_all_db_content(&mut self) -> Result<(), OperationError> {
1845 self.get_ruv().clear();
1846 self.get_idlayer()
1847 .danger_purge_id2entry()
1848 .and_then(|_| self.danger_purge_idxs())
1849 }
1850
1851 #[cfg(test)]
1852 pub fn load_test_idl(
1853 &mut self,
1854 attr: &Attribute,
1855 itype: IndexType,
1856 idx_key: &str,
1857 ) -> Result<Option<IDLBitRange>, OperationError> {
1858 self.get_idlayer().get_idl(attr, itype, idx_key)
1859 }
1860
1861 fn is_idx_slopeyness_generated(&mut self) -> Result<bool, OperationError> {
1862 self.get_idlayer().is_idx_slopeyness_generated()
1863 }
1864
1865 fn get_idx_slope(&mut self, ikey: &IdxKey) -> Result<IdxSlope, OperationError> {
1866 let slope = self
1868 .get_idlayer()
1869 .get_idx_slope(ikey)?
1870 .unwrap_or_else(|| get_idx_slope_default(ikey));
1871 trace!("index slope - {:?} -> {:?}", ikey, slope);
1872 Ok(slope)
1873 }
1874
1875 pub fn restore<IN>(
1876 &mut self,
1877 input: IN,
1878 compression: BackupCompression,
1879 ) -> Result<(), OperationError>
1880 where
1881 IN: std::io::Read,
1882 {
1883 let dbbak_option: Result<DbBackup, serde_json::Error> = match compression {
1887 BackupCompression::NoCompression => serde_json::from_reader(input),
1888 BackupCompression::Gzip => {
1889 let decoder = flate2::read::GzDecoder::new(input);
1890 serde_json::from_reader(decoder)
1891 }
1892 };
1893
1894 let dbbak = dbbak_option.map_err(|err| {
1895 error!(?err, "serde_json error");
1896 OperationError::SerdeJsonError
1897 })?;
1898
1899 self.danger_delete_all_db_content().inspect_err(|err| {
1900 error!(?err, "delete_all_db_content failed");
1901 })?;
1902
1903 let idlayer = self.get_idlayer();
1904
1905 let (dbentries, repl_meta, maybe_version) = match dbbak {
1906 DbBackup::V1(dbentries) => (dbentries, None, None),
1907 DbBackup::V2 {
1908 db_s_uuid,
1909 db_d_uuid,
1910 db_ts_max,
1911 entries,
1912 } => {
1913 idlayer.write_db_s_uuid(db_s_uuid)?;
1915 idlayer.write_db_d_uuid(db_d_uuid)?;
1916 idlayer.set_db_ts_max(db_ts_max)?;
1917 (entries, None, None)
1918 }
1919 DbBackup::V3 {
1920 db_s_uuid,
1921 db_d_uuid,
1922 db_ts_max,
1923 keyhandles,
1924 entries,
1925 } => {
1926 idlayer.write_db_s_uuid(db_s_uuid)?;
1928 idlayer.write_db_d_uuid(db_d_uuid)?;
1929 idlayer.set_db_ts_max(db_ts_max)?;
1930 idlayer.set_key_handles(keyhandles)?;
1931 (entries, None, None)
1932 }
1933 DbBackup::V4 {
1934 db_s_uuid,
1935 db_d_uuid,
1936 db_ts_max,
1937 keyhandles,
1938 repl_meta,
1939 entries,
1940 } => {
1941 idlayer.write_db_s_uuid(db_s_uuid)?;
1943 idlayer.write_db_d_uuid(db_d_uuid)?;
1944 idlayer.set_db_ts_max(db_ts_max)?;
1945 idlayer.set_key_handles(keyhandles)?;
1946 (entries, Some(repl_meta), None)
1947 }
1948 DbBackup::V5 {
1949 version,
1950 db_s_uuid,
1951 db_d_uuid,
1952 db_ts_max,
1953 keyhandles,
1954 repl_meta,
1955 entries,
1956 } => {
1957 idlayer.write_db_s_uuid(db_s_uuid)?;
1959 idlayer.write_db_d_uuid(db_d_uuid)?;
1960 idlayer.set_db_ts_max(db_ts_max)?;
1961 idlayer.set_key_handles(keyhandles)?;
1962 (entries, Some(repl_meta), Some(version))
1963 }
1964 };
1965
1966 if let Some(version) = maybe_version {
1967 if version != env!("KANIDM_PKG_SERIES") {
1968 error!("The provided backup data is from server version {} and is unable to be restored on this instance ({})", version, env!("KANIDM_PKG_SERIES"));
1969 return Err(OperationError::DB0001MismatchedRestoreVersion);
1970 }
1971 } else {
1972 error!("The provided backup data is from an older server version and is unable to be restored.");
1973 return Err(OperationError::DB0002MismatchedRestoreVersion);
1974 };
1975
1976 match repl_meta {
1978 Some(DbReplMeta::V1 { ruv: db_ruv }) => {
1979 self.get_ruv()
1980 .restore(db_ruv.into_iter().map(|db_cid| db_cid.into()))?;
1981 }
1982 None => {
1983 warn!("Unable to restore replication metadata, this server may need a refresh.");
1984 }
1985 }
1986
1987 info!("Restoring {} entries ...", dbentries.len());
1988
1989 let mut id_max = 0;
1991 let identries: Result<Vec<IdRawEntry>, _> = dbentries
1992 .iter()
1993 .map(|e| {
1994 id_max += 1;
1995 let data = serde_json::to_vec(&e).map_err(|_| OperationError::SerdeCborError)?;
1996 Ok(IdRawEntry { id: id_max, data })
1997 })
1998 .collect();
1999
2000 let idlayer = self.get_idlayer();
2001
2002 idlayer.write_identries_raw(identries?.into_iter())?;
2003
2004 info!("Restored {} entries", dbentries.len());
2005
2006 let vr = self.verify();
2007 if vr.is_empty() {
2008 Ok(())
2009 } else {
2010 Err(OperationError::ConsistencyError(
2011 vr.into_iter().filter_map(|v| v.err()).collect(),
2012 ))
2013 }
2014 }
2015
2016 #[instrument(level = "debug", name = "be::ruv_rebuild", skip_all)]
2027 fn ruv_reload(&mut self) -> Result<(), OperationError> {
2028 let idlayer = self.get_idlayer();
2029
2030 let db_ruv = idlayer.get_db_ruv()?;
2031
2032 self.get_ruv().restore(db_ruv)?;
2036
2037 self.ruv_rebuild()
2039 }
2040
2041 #[instrument(level = "debug", name = "be::ruv_rebuild", skip_all)]
2042 fn ruv_rebuild(&mut self) -> Result<(), OperationError> {
2043 let idl = IdList::AllIds;
2051 let entries = self.get_idlayer().get_identry(&idl).map_err(|e| {
2052 admin_error!(?e, "get_identry failed");
2053 e
2054 })?;
2055
2056 self.get_ruv().rebuild(&entries)?;
2057
2058 Ok(())
2059 }
2060
2061 pub fn quarantine_entry(&mut self, id: u64) -> Result<(), OperationError> {
2062 self.get_idlayer().quarantine_entry(id)?;
2063 self.set_db_index_version(0)
2066 }
2067
2068 pub fn restore_quarantined(&mut self, id: u64) -> Result<(), OperationError> {
2069 self.get_idlayer().restore_quarantined(id)?;
2070 self.set_db_index_version(0)
2073 }
2074
2075 #[cfg(any(test, debug_assertions))]
2076 pub fn clear_cache(&mut self) -> Result<(), OperationError> {
2077 self.get_idlayer().clear_cache()
2078 }
2079
2080 pub fn commit(self) -> Result<(), OperationError> {
2081 let BackendWriteTransaction {
2082 mut idlayer,
2083 idxmeta_wr,
2084 ruv,
2085 } = self;
2086
2087 idlayer.write_db_ruv(ruv.added(), ruv.removed())?;
2089
2090 idlayer.commit().map(|()| {
2091 ruv.commit();
2092 idxmeta_wr.commit();
2093 })
2094 }
2095
2096 pub(crate) fn reset_db_s_uuid(&mut self) -> Result<Uuid, OperationError> {
2097 let nsid = Uuid::new_v4();
2099 self.get_idlayer().write_db_s_uuid(nsid).map_err(|err| {
2100 error!(?err, "Unable to persist server uuid");
2101 err
2102 })?;
2103 Ok(nsid)
2104 }
2105 pub fn get_db_s_uuid(&mut self) -> Result<Uuid, OperationError> {
2106 let res = self.get_idlayer().get_db_s_uuid().map_err(|err| {
2107 error!(?err, "Failed to read server uuid");
2108 err
2109 })?;
2110 match res {
2111 Some(s_uuid) => Ok(s_uuid),
2112 None => self.reset_db_s_uuid(),
2113 }
2114 }
2115
2116 fn reset_db_d_uuid(&mut self) -> Result<Uuid, OperationError> {
2119 let nsid = Uuid::new_v4();
2120 self.get_idlayer().write_db_d_uuid(nsid).map_err(|err| {
2121 error!(?err, "Unable to persist domain uuid");
2122 err
2123 })?;
2124 Ok(nsid)
2125 }
2126
2127 pub fn set_db_d_uuid(&mut self, nsid: Uuid) -> Result<(), OperationError> {
2130 self.get_idlayer().write_db_d_uuid(nsid)
2131 }
2132
2133 pub fn get_db_d_uuid(&mut self) -> Result<Uuid, OperationError> {
2135 let res = self.get_idlayer().get_db_d_uuid().map_err(|err| {
2136 error!(?err, "Failed to read domain uuid");
2137 err
2138 })?;
2139 match res {
2140 Some(d_uuid) => Ok(d_uuid),
2141 None => self.reset_db_d_uuid(),
2142 }
2143 }
2144
2145 pub fn set_db_ts_max(&mut self, ts: Duration) -> Result<(), OperationError> {
2146 self.get_idlayer().set_db_ts_max(ts)
2147 }
2148
2149 pub fn get_db_ts_max(&mut self, ts: Duration) -> Result<Duration, OperationError> {
2150 match self.get_idlayer().get_db_ts_max()? {
2152 Some(dts) => Ok(dts),
2153 None => Ok(ts),
2154 }
2155 }
2156
2157 fn get_db_index_version(&mut self) -> Result<i64, OperationError> {
2158 self.get_idlayer().get_db_index_version()
2159 }
2160
2161 fn set_db_index_version(&mut self, v: i64) -> Result<(), OperationError> {
2162 self.get_idlayer().set_db_index_version(v)
2163 }
2164}
2165
2166fn get_idx_slope_default(ikey: &IdxKey) -> IdxSlope {
2170 match (ikey.attr.as_str(), &ikey.itype) {
2171 (ATTR_NAME, IndexType::Equality)
2172 | (ATTR_SPN, IndexType::Equality)
2173 | (ATTR_UUID, IndexType::Equality) => 1,
2174 (ATTR_CLASS, IndexType::Equality) => 180,
2175 (_, IndexType::Equality) => 45,
2176 (_, IndexType::SubString) => 90,
2177 (_, IndexType::Presence) => 90,
2178 (_, IndexType::Ordering) => 120,
2179 }
2180}
2181
2182impl Backend {
2184 #[instrument(level = "debug", name = "be::new", skip_all)]
2185 pub fn new(
2186 mut cfg: BackendConfig,
2187 idxkeys: Vec<IdxKey>,
2191 vacuum: bool,
2192 ) -> Result<Self, OperationError> {
2193 debug!(db_tickets = ?cfg.pool_size, profile = %env!("KANIDM_PROFILE_NAME"), cpu_flags = %env!("KANIDM_CPU_FLAGS"));
2194
2195 if cfg.path.as_os_str().is_empty() {
2197 cfg.pool_size = 1;
2198 }
2199
2200 let idxkeys: HashMap<_, _> = idxkeys
2206 .into_iter()
2207 .map(|ikey| {
2208 let slope = get_idx_slope_default(&ikey);
2209 (ikey, slope)
2210 })
2211 .collect();
2212
2213 let ruv = Arc::new(ReplicationUpdateVector::default());
2216
2217 let idlayer = Arc::new(IdlArcSqlite::new(&cfg, vacuum)?);
2219 let be = Backend {
2220 cfg,
2221 idlayer,
2222 ruv,
2223 idxmeta: Arc::new(CowCell::new(IdxMeta::new(idxkeys))),
2224 };
2225
2226 let mut idl_write = be.idlayer.write()?;
2231 idl_write
2232 .setup()
2233 .and_then(|_| idl_write.commit())
2234 .map_err(|e| {
2235 admin_error!(?e, "Failed to setup idlayer");
2236 e
2237 })?;
2238
2239 let mut be_write = be.write()?;
2245 be_write
2246 .ruv_reload()
2247 .and_then(|_| be_write.commit())
2248 .map_err(|e| {
2249 admin_error!(?e, "Failed to reload ruv");
2250 e
2251 })?;
2252
2253 Ok(be)
2254 }
2255
2256 pub fn get_pool_size(&self) -> u32 {
2257 debug_assert!(self.cfg.pool_size > 0);
2258 self.cfg.pool_size
2259 }
2260
2261 pub fn try_quiesce(&self) {
2262 self.idlayer.try_quiesce();
2263 }
2264
2265 pub fn read(&self) -> Result<BackendReadTransaction<'_>, OperationError> {
2266 Ok(BackendReadTransaction {
2267 idlayer: self.idlayer.read()?,
2268 idxmeta: self.idxmeta.read(),
2269 ruv: self.ruv.read(),
2270 })
2271 }
2272
2273 pub fn write(&self) -> Result<BackendWriteTransaction<'_>, OperationError> {
2274 Ok(BackendWriteTransaction {
2275 idlayer: self.idlayer.write()?,
2276 idxmeta_wr: self.idxmeta.write(),
2277 ruv: self.ruv.write(),
2278 })
2279 }
2280}
2281
2282#[cfg(test)]
2285mod tests {
2286 use super::{
2287 super::entry::{Entry, EntryInit, EntryNew},
2288 Backend, BackendConfig, BackendTransaction, BackendWriteTransaction, DbBackup, IdList,
2289 IdxKey, Limits, OperationError,
2290 };
2291 use crate::{
2292 prelude::*,
2293 repl::cid::Cid,
2294 value::{IndexType, PartialValue, Value},
2295 };
2296 use idlset::v2::IDLBitRange;
2297 use kanidm_proto::backup::BackupCompression;
2298 use std::{
2299 iter::FromIterator,
2300 sync::{Arc, LazyLock},
2301 time::Duration,
2302 };
2303
2304 static CID_ZERO: LazyLock<Cid> = LazyLock::new(Cid::new_zero);
2305 static CID_ONE: LazyLock<Cid> = LazyLock::new(|| Cid::new_count(1));
2306 static CID_TWO: LazyLock<Cid> = LazyLock::new(|| Cid::new_count(2));
2307 static CID_THREE: LazyLock<Cid> = LazyLock::new(|| Cid::new_count(3));
2308 static CID_ADV: LazyLock<Cid> = LazyLock::new(|| Cid::new_count(10));
2309
2310 macro_rules! run_test {
2311 ($test_fn:expr) => {{
2312 sketching::test_init();
2313
2314 let idxmeta = vec![
2316 IdxKey {
2317 attr: Attribute::Name.into(),
2318 itype: IndexType::Equality,
2319 },
2320 IdxKey {
2321 attr: Attribute::Name.into(),
2322 itype: IndexType::Presence,
2323 },
2324 IdxKey {
2325 attr: Attribute::Name.into(),
2326 itype: IndexType::SubString,
2327 },
2328 IdxKey {
2329 attr: Attribute::Uuid.into(),
2330 itype: IndexType::Equality,
2331 },
2332 IdxKey {
2333 attr: Attribute::Uuid.into(),
2334 itype: IndexType::Presence,
2335 },
2336 IdxKey {
2337 attr: Attribute::TestAttr.into(),
2338 itype: IndexType::Equality,
2339 },
2340 IdxKey {
2341 attr: Attribute::TestNumber.into(),
2342 itype: IndexType::Equality,
2343 },
2344 ];
2345
2346 let be = Backend::new(BackendConfig::new_test("main"), idxmeta, false)
2347 .expect("Failed to setup backend");
2348
2349 let mut be_txn = be.write().unwrap();
2350
2351 let r = $test_fn(&mut be_txn);
2352 assert!(be_txn.commit().is_ok());
2354 r
2355 }};
2356 }
2357
2358 macro_rules! entry_exists {
2359 ($be:expr, $ent:expr) => {{
2360 let ei = $ent.clone().into_sealed_committed();
2361 let filt = ei
2362 .filter_from_attrs(&[Attribute::Uuid.into()])
2363 .expect("failed to generate filter")
2364 .into_valid_resolved();
2365 let lims = Limits::unlimited();
2366 let entries = $be.search(&lims, &filt).expect("failed to search");
2367 entries.first().is_some()
2368 }};
2369 }
2370
2371 macro_rules! entry_attr_pres {
2372 ($be:expr, $ent:expr, $attr:expr) => {{
2373 let ei = $ent.clone().into_sealed_committed();
2374 let filt = ei
2375 .filter_from_attrs(&[Attribute::UserId.into()])
2376 .expect("failed to generate filter")
2377 .into_valid_resolved();
2378 let lims = Limits::unlimited();
2379 let entries = $be.search(&lims, &filt).expect("failed to search");
2380 match entries.first() {
2381 Some(ent) => ent.attribute_pres($attr),
2382 None => false,
2383 }
2384 }};
2385 }
2386
2387 macro_rules! idl_state {
2388 ($be:expr, $attr:expr, $itype:expr, $idx_key:expr, $expect:expr) => {{
2389 let t_idl = $be
2390 .load_test_idl(&$attr, $itype, &$idx_key.to_string())
2391 .expect("IdList Load failed");
2392 let t = $expect.map(|v: Vec<u64>| IDLBitRange::from_iter(v));
2393 assert_eq!(t_idl, t);
2394 }};
2395 }
2396
2397 #[test]
2398 fn test_be_simple_create() {
2399 run_test!(|be: &mut BackendWriteTransaction| {
2400 trace!("Simple Create");
2401
2402 let empty_result = be.create(&CID_ZERO, Vec::with_capacity(0));
2403 trace!("{:?}", empty_result);
2404 assert_eq!(empty_result, Err(OperationError::EmptyRequest));
2405
2406 let mut e: Entry<EntryInit, EntryNew> = Entry::new();
2407 e.add_ava(Attribute::UserId, Value::from("william"));
2408 e.add_ava(
2409 Attribute::Uuid,
2410 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
2411 );
2412 let e = e.into_sealed_new();
2413
2414 let single_result = be.create(&CID_ZERO, vec![e.clone()]);
2415
2416 assert!(single_result.is_ok());
2417
2418 assert!(entry_exists!(be, e));
2420 });
2421 }
2422
2423 #[test]
2424 fn test_be_simple_search() {
2425 run_test!(|be: &mut BackendWriteTransaction| {
2426 trace!("Simple Search");
2427
2428 let mut e: Entry<EntryInit, EntryNew> = Entry::new();
2429 e.add_ava(Attribute::UserId, Value::from("claire"));
2430 e.add_ava(
2431 Attribute::Uuid,
2432 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
2433 );
2434 let e = e.into_sealed_new();
2435
2436 let single_result = be.create(&CID_ZERO, vec![e]);
2437 assert!(single_result.is_ok());
2438 let filt = filter_resolved!(f_eq(Attribute::UserId, PartialValue::new_utf8s("claire")));
2441
2442 let lims = Limits::unlimited();
2443
2444 let r = be.search(&lims, &filt);
2445 assert!(r.expect("Search failed!").len() == 1);
2446
2447 });
2453 }
2454
2455 #[test]
2456 fn test_be_search_with_invalid() {
2457 run_test!(|be: &mut BackendWriteTransaction| {
2458 trace!("Simple Search");
2459
2460 let mut e: Entry<EntryInit, EntryNew> = Entry::new();
2461 e.add_ava(Attribute::UserId, Value::from("bagel"));
2462 e.add_ava(
2463 Attribute::Uuid,
2464 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
2465 );
2466 let e = e.into_sealed_new();
2467
2468 let single_result = be.create(&CID_ZERO, vec![e]);
2469 assert!(single_result.is_ok());
2470
2471 let filt = filter_resolved!(f_or(vec![
2473 f_eq(Attribute::UserId, PartialValue::new_utf8s("bagel")),
2474 f_invalid(Attribute::UserId)
2475 ]));
2476
2477 let lims = Limits::unlimited();
2478
2479 let r = be.search(&lims, &filt);
2480 assert!(r.expect("Search failed!").len() == 1);
2481
2482 let filt = filter_resolved!(f_and(vec![
2484 f_eq(Attribute::UserId, PartialValue::new_utf8s("bagel")),
2485 f_invalid(Attribute::UserId)
2486 ]));
2487
2488 let lims = Limits::unlimited();
2489
2490 let r = be.search(&lims, &filt);
2491 assert!(r.expect("Search failed!").is_empty());
2492 });
2493 }
2494
2495 #[test]
2496 fn test_be_simple_modify() {
2497 run_test!(|be: &mut BackendWriteTransaction| {
2498 trace!("Simple Modify");
2499 let lims = Limits::unlimited();
2500 let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
2502 e1.add_ava(Attribute::UserId, Value::from("william"));
2503 e1.add_ava(
2504 Attribute::Uuid,
2505 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
2506 );
2507
2508 let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
2509 e2.add_ava(Attribute::UserId, Value::from("alice"));
2510 e2.add_ava(
2511 Attribute::Uuid,
2512 Value::from("4b6228ab-1dbe-42a4-a9f5-f6368222438e"),
2513 );
2514
2515 let ve1 = e1.clone().into_sealed_new();
2516 let ve2 = e2.clone().into_sealed_new();
2517
2518 assert!(be.create(&CID_ZERO, vec![ve1, ve2]).is_ok());
2519 assert!(entry_exists!(be, e1));
2520 assert!(entry_exists!(be, e2));
2521
2522 let mut results = be
2524 .search(&lims, &filter_resolved!(f_pres(Attribute::UserId)))
2525 .expect("Failed to search");
2526
2527 let r1 = results.remove(0);
2529 let r2 = results.remove(0);
2530
2531 let mut r1 = r1.as_ref().clone().into_invalid();
2532 let mut r2 = r2.as_ref().clone().into_invalid();
2533
2534 let ue1 = e1.clone().into_sealed_committed();
2538 assert!(be
2539 .modify(&CID_ZERO, &[Arc::new(ue1.clone())], &[ue1])
2540 .is_err());
2541 assert!(be.modify(&CID_ZERO, &[], &[]).is_err());
2543
2544 let pre1 = Arc::new(r1.clone().into_sealed_committed());
2546 let pre2 = Arc::new(r2.clone().into_sealed_committed());
2547 r1.add_ava(Attribute::TestAttr, Value::from("modified"));
2548 r2.add_ava(Attribute::TestAttr, Value::from("modified"));
2549
2550 let vr1 = r1.into_sealed_committed();
2553 let vr2 = r2.into_sealed_committed();
2554
2555 assert!(be
2557 .modify(&CID_ZERO, &[pre1], std::slice::from_ref(&vr1))
2558 .is_ok());
2559 assert!(entry_attr_pres!(be, vr1, Attribute::TestAttr));
2561 assert!(!entry_attr_pres!(be, vr2, Attribute::TestAttr));
2562
2563 assert!(be
2565 .modify(
2566 &CID_ZERO,
2567 &[Arc::new(vr1.clone()), pre2],
2568 &[vr1.clone(), vr2.clone()]
2569 )
2570 .is_ok());
2571
2572 assert!(entry_attr_pres!(be, vr1, Attribute::TestAttr));
2573 assert!(entry_attr_pres!(be, vr2, Attribute::TestAttr));
2574 });
2575 }
2576
2577 #[test]
2578 fn test_be_simple_delete() {
2579 run_test!(|be: &mut BackendWriteTransaction| {
2580 trace!("Simple Delete");
2581 let lims = Limits::unlimited();
2582
2583 let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
2585 e1.add_ava(Attribute::UserId, Value::from("william"));
2586 e1.add_ava(
2587 Attribute::Uuid,
2588 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
2589 );
2590
2591 let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
2592 e2.add_ava(Attribute::UserId, Value::from("alice"));
2593 e2.add_ava(
2594 Attribute::Uuid,
2595 Value::from("4b6228ab-1dbe-42a4-a9f5-f6368222438e"),
2596 );
2597
2598 let mut e3: Entry<EntryInit, EntryNew> = Entry::new();
2599 e3.add_ava(Attribute::UserId, Value::from("lucy"));
2600 e3.add_ava(
2601 Attribute::Uuid,
2602 Value::from("7b23c99d-c06b-4a9a-a958-3afa56383e1d"),
2603 );
2604
2605 let ve1 = e1.clone().into_sealed_new();
2606 let ve2 = e2.clone().into_sealed_new();
2607 let ve3 = e3.clone().into_sealed_new();
2608
2609 assert!(be.create(&CID_ZERO, vec![ve1, ve2, ve3]).is_ok());
2610 assert!(entry_exists!(be, e1));
2611 assert!(entry_exists!(be, e2));
2612 assert!(entry_exists!(be, e3));
2613
2614 let mut results = be
2616 .search(&lims, &filter_resolved!(f_pres(Attribute::UserId)))
2617 .expect("Failed to search");
2618
2619 let r1 = results.remove(0);
2621 let r2 = results.remove(0);
2622 let r3 = results.remove(0);
2623
2624 assert!(matches!(be.reap_tombstones(&CID_ADV, &CID_ZERO), Ok(0)));
2626
2627 let r1_ts = r1.to_tombstone(CID_ONE.clone()).into_sealed_committed();
2630
2631 assert!(be
2632 .modify(&CID_ONE, &[r1], std::slice::from_ref(&r1_ts))
2633 .is_ok());
2634
2635 let r2_ts = r2.to_tombstone(CID_TWO.clone()).into_sealed_committed();
2636 let r3_ts = r3.to_tombstone(CID_TWO.clone()).into_sealed_committed();
2637
2638 assert!(be
2639 .modify(&CID_TWO, &[r2, r3], &[r2_ts.clone(), r3_ts.clone()])
2640 .is_ok());
2641
2642 assert!(matches!(be.reap_tombstones(&CID_ADV, &CID_ZERO), Ok(0)));
2645
2646 assert!(entry_exists!(be, r1_ts));
2647 assert!(entry_exists!(be, r2_ts));
2648 assert!(entry_exists!(be, r3_ts));
2649
2650 assert!(matches!(be.reap_tombstones(&CID_ADV, &CID_ONE), Ok(0)));
2651
2652 assert!(entry_exists!(be, r1_ts));
2653 assert!(entry_exists!(be, r2_ts));
2654 assert!(entry_exists!(be, r3_ts));
2655
2656 assert!(matches!(be.reap_tombstones(&CID_ADV, &CID_TWO), Ok(1)));
2657
2658 assert!(!entry_exists!(be, r1_ts));
2659 assert!(entry_exists!(be, r2_ts));
2660 assert!(entry_exists!(be, r3_ts));
2661
2662 assert!(matches!(be.reap_tombstones(&CID_ADV, &CID_THREE), Ok(2)));
2663
2664 assert!(!entry_exists!(be, r1_ts));
2665 assert!(!entry_exists!(be, r2_ts));
2666 assert!(!entry_exists!(be, r3_ts));
2667
2668 assert!(matches!(be.reap_tombstones(&CID_ADV, &CID_THREE), Ok(0)));
2670
2671 assert!(!entry_exists!(be, r1_ts));
2672 assert!(!entry_exists!(be, r2_ts));
2673 assert!(!entry_exists!(be, r3_ts));
2674 });
2675 }
2676
2677 #[test]
2678 fn test_be_backup_restore() {
2679 run_test!(|be: &mut BackendWriteTransaction| {
2680 be.reset_db_s_uuid().unwrap();
2682 be.reset_db_d_uuid().unwrap();
2683 be.set_db_ts_max(Duration::from_secs(1)).unwrap();
2684
2685 let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
2687 e1.add_ava(Attribute::UserId, Value::from("william"));
2688 e1.add_ava(
2689 Attribute::Uuid,
2690 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
2691 );
2692
2693 let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
2694 e2.add_ava(Attribute::UserId, Value::from("alice"));
2695 e2.add_ava(
2696 Attribute::Uuid,
2697 Value::from("4b6228ab-1dbe-42a4-a9f5-f6368222438e"),
2698 );
2699
2700 let mut e3: Entry<EntryInit, EntryNew> = Entry::new();
2701 e3.add_ava(Attribute::UserId, Value::from("lucy"));
2702 e3.add_ava(
2703 Attribute::Uuid,
2704 Value::from("7b23c99d-c06b-4a9a-a958-3afa56383e1d"),
2705 );
2706
2707 let ve1 = e1.clone().into_sealed_new();
2708 let ve2 = e2.clone().into_sealed_new();
2709 let ve3 = e3.clone().into_sealed_new();
2710
2711 assert!(be.create(&CID_ZERO, vec![ve1, ve2, ve3]).is_ok());
2712 assert!(entry_exists!(be, e1));
2713 assert!(entry_exists!(be, e2));
2714 assert!(entry_exists!(be, e3));
2715
2716 let mut buf = std::io::Cursor::new(Vec::new());
2717
2718 be.backup(&mut buf, BackupCompression::Gzip)
2719 .expect("Backup failed!");
2720
2721 buf.set_position(0);
2722
2723 be.restore(&mut buf, BackupCompression::Gzip)
2724 .expect("Restore failed!");
2725
2726 assert!(be.verify().is_empty());
2727 });
2728 }
2729
2730 #[test]
2731 fn test_be_backup_restore_tampered() {
2732 run_test!(|be: &mut BackendWriteTransaction| {
2733 be.reset_db_s_uuid().unwrap();
2735 be.reset_db_d_uuid().unwrap();
2736 be.set_db_ts_max(Duration::from_secs(1)).unwrap();
2737 let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
2739 e1.add_ava(Attribute::UserId, Value::from("william"));
2740 e1.add_ava(
2741 Attribute::Uuid,
2742 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
2743 );
2744
2745 let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
2746 e2.add_ava(Attribute::UserId, Value::from("alice"));
2747 e2.add_ava(
2748 Attribute::Uuid,
2749 Value::from("4b6228ab-1dbe-42a4-a9f5-f6368222438e"),
2750 );
2751
2752 let mut e3: Entry<EntryInit, EntryNew> = Entry::new();
2753 e3.add_ava(Attribute::UserId, Value::from("lucy"));
2754 e3.add_ava(
2755 Attribute::Uuid,
2756 Value::from("7b23c99d-c06b-4a9a-a958-3afa56383e1d"),
2757 );
2758
2759 let ve1 = e1.clone().into_sealed_new();
2760 let ve2 = e2.clone().into_sealed_new();
2761 let ve3 = e3.clone().into_sealed_new();
2762
2763 assert!(be.create(&CID_ZERO, vec![ve1, ve2, ve3]).is_ok());
2764 assert!(entry_exists!(be, e1));
2765 assert!(entry_exists!(be, e2));
2766 assert!(entry_exists!(be, e3));
2767
2768 let mut buf = std::io::Cursor::new(Vec::new());
2769
2770 be.backup(&mut buf, BackupCompression::NoCompression)
2771 .expect("Backup failed!");
2772
2773 buf.set_position(0);
2775
2776 let mut dbbak: DbBackup = serde_json::from_reader(&mut buf).unwrap();
2778
2779 match &mut dbbak {
2780 DbBackup::V5 {
2781 version: _,
2782 db_s_uuid: _,
2783 db_d_uuid: _,
2784 db_ts_max: _,
2785 keyhandles: _,
2786 repl_meta: _,
2787 entries,
2788 } => {
2789 let _ = entries.pop();
2790 }
2791 _ => {
2792 unreachable!()
2794 }
2795 };
2796
2797 buf.get_mut().clear();
2798 buf.set_position(0);
2799
2800 serde_json::to_writer(&mut buf, &dbbak).unwrap();
2801
2802 buf.set_position(0);
2804
2805 be.restore(&mut buf, BackupCompression::NoCompression)
2806 .expect("Restore failed!");
2807
2808 assert!(be.verify().is_empty());
2809 });
2810 }
2811
2812 #[test]
2813 fn test_be_sid_generation_and_reset() {
2814 run_test!(|be: &mut BackendWriteTransaction| {
2815 let sid1 = be.get_db_s_uuid().unwrap();
2816 let sid2 = be.get_db_s_uuid().unwrap();
2817 assert_eq!(sid1, sid2);
2818 let sid3 = be.reset_db_s_uuid().unwrap();
2819 assert!(sid1 != sid3);
2820 let sid4 = be.get_db_s_uuid().unwrap();
2821 assert_eq!(sid3, sid4);
2822 });
2823 }
2824
2825 #[test]
2826 fn test_be_reindex_empty() {
2827 run_test!(|be: &mut BackendWriteTransaction| {
2828 let missing = be.missing_idxs().unwrap();
2830 assert_eq!(missing.len(), 7);
2831 assert!(be.reindex(false).is_ok());
2832 let missing = be.missing_idxs().unwrap();
2833 debug!("{:?}", missing);
2834 assert!(missing.is_empty());
2835 });
2836 }
2837
2838 #[test]
2839 fn test_be_reindex_data() {
2840 run_test!(|be: &mut BackendWriteTransaction| {
2841 let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
2843 e1.add_ava(Attribute::Name, Value::new_iname("william"));
2844 e1.add_ava(
2845 Attribute::Uuid,
2846 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
2847 );
2848 let e1 = e1.into_sealed_new();
2849
2850 let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
2851 e2.add_ava(Attribute::Name, Value::new_iname("claire"));
2852 e2.add_ava(
2853 Attribute::Uuid,
2854 Value::from("bd651620-00dd-426b-aaa0-4494f7b7906f"),
2855 );
2856 let e2 = e2.into_sealed_new();
2857
2858 be.create(&CID_ZERO, vec![e1, e2]).unwrap();
2859
2860 be.danger_purge_idxs().unwrap();
2862 let missing = be.missing_idxs().unwrap();
2864 assert_eq!(missing.len(), 7);
2865 assert!(be.reindex(false).is_ok());
2866 let missing = be.missing_idxs().unwrap();
2867 debug!("{:?}", missing);
2868 assert!(missing.is_empty());
2869 idl_state!(
2872 be,
2873 Attribute::Name,
2874 IndexType::Equality,
2875 "william",
2876 Some(vec![1])
2877 );
2878
2879 idl_state!(
2880 be,
2881 Attribute::Name,
2882 IndexType::Equality,
2883 "claire",
2884 Some(vec![2])
2885 );
2886
2887 for sub in [
2888 "w", "m", "wi", "il", "ll", "li", "ia", "am", "wil", "ill", "lli", "lia", "iam",
2889 ] {
2890 idl_state!(
2891 be,
2892 Attribute::Name,
2893 IndexType::SubString,
2894 sub,
2895 Some(vec![1])
2896 );
2897 }
2898
2899 for sub in [
2900 "c", "r", "e", "cl", "la", "ai", "ir", "re", "cla", "lai", "air", "ire",
2901 ] {
2902 idl_state!(
2903 be,
2904 Attribute::Name,
2905 IndexType::SubString,
2906 sub,
2907 Some(vec![2])
2908 );
2909 }
2910
2911 for sub in ["i", "a", "l"] {
2912 idl_state!(
2913 be,
2914 Attribute::Name,
2915 IndexType::SubString,
2916 sub,
2917 Some(vec![1, 2])
2918 );
2919 }
2920
2921 idl_state!(
2922 be,
2923 Attribute::Name,
2924 IndexType::Presence,
2925 "_",
2926 Some(vec![1, 2])
2927 );
2928
2929 idl_state!(
2930 be,
2931 Attribute::Uuid,
2932 IndexType::Equality,
2933 "db237e8a-0079-4b8c-8a56-593b22aa44d1",
2934 Some(vec![1])
2935 );
2936
2937 idl_state!(
2938 be,
2939 Attribute::Uuid,
2940 IndexType::Equality,
2941 "bd651620-00dd-426b-aaa0-4494f7b7906f",
2942 Some(vec![2])
2943 );
2944
2945 idl_state!(
2946 be,
2947 Attribute::Uuid,
2948 IndexType::Presence,
2949 "_",
2950 Some(vec![1, 2])
2951 );
2952
2953 idl_state!(
2956 be,
2957 Attribute::Name,
2958 IndexType::Equality,
2959 "not-exist",
2960 Some(Vec::with_capacity(0))
2961 );
2962
2963 idl_state!(
2964 be,
2965 Attribute::Uuid,
2966 IndexType::Equality,
2967 "fake-0079-4b8c-8a56-593b22aa44d1",
2968 Some(Vec::with_capacity(0))
2969 );
2970
2971 let uuid_p_idl = be
2972 .load_test_idl(&Attribute::from("not_indexed"), IndexType::Presence, "_")
2973 .unwrap(); assert_eq!(uuid_p_idl, None);
2975
2976 let claire_uuid = uuid!("bd651620-00dd-426b-aaa0-4494f7b7906f");
2978 let william_uuid = uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1");
2979
2980 assert_eq!(be.name2uuid("claire"), Ok(Some(claire_uuid)));
2981 assert_eq!(be.name2uuid("william"), Ok(Some(william_uuid)));
2982 assert_eq!(
2983 be.name2uuid("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
2984 Ok(None)
2985 );
2986 assert_eq!(
2988 be.uuid2spn(claire_uuid),
2989 Ok(Some(Value::new_iname("claire")))
2990 );
2991 assert_eq!(
2992 be.uuid2spn(william_uuid),
2993 Ok(Some(Value::new_iname("william")))
2994 );
2995 assert_eq!(
2997 be.uuid2rdn(claire_uuid),
2998 Ok(Some("name=claire".to_string()))
2999 );
3000 assert_eq!(
3001 be.uuid2rdn(william_uuid),
3002 Ok(Some("name=william".to_string()))
3003 );
3004 });
3005 }
3006
3007 #[test]
3008 fn test_be_index_create_delete_simple() {
3009 run_test!(|be: &mut BackendWriteTransaction| {
3010 assert!(be.reindex(false).is_ok());
3012 let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
3015 e1.add_ava(Attribute::Name, Value::from("william"));
3016 e1.add_ava(
3017 Attribute::Uuid,
3018 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
3019 );
3020 let e1 = e1.into_sealed_new();
3021
3022 let rset = be.create(&CID_ZERO, vec![e1]).unwrap();
3023 let mut rset: Vec<_> = rset.into_iter().map(Arc::new).collect();
3024 let e1 = rset.pop().unwrap();
3025
3026 idl_state!(
3027 be,
3028 Attribute::Name.as_ref(),
3029 IndexType::Equality,
3030 "william",
3031 Some(vec![1])
3032 );
3033
3034 idl_state!(
3035 be,
3036 Attribute::Name.as_ref(),
3037 IndexType::Presence,
3038 "_",
3039 Some(vec![1])
3040 );
3041
3042 idl_state!(
3043 be,
3044 Attribute::Uuid.as_ref(),
3045 IndexType::Equality,
3046 "db237e8a-0079-4b8c-8a56-593b22aa44d1",
3047 Some(vec![1])
3048 );
3049
3050 idl_state!(
3051 be,
3052 Attribute::Uuid.as_ref(),
3053 IndexType::Presence,
3054 "_",
3055 Some(vec![1])
3056 );
3057
3058 let william_uuid = uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1");
3059 assert_eq!(be.name2uuid("william"), Ok(Some(william_uuid)));
3060 assert_eq!(be.uuid2spn(william_uuid), Ok(Some(Value::from("william"))));
3061 assert_eq!(
3062 be.uuid2rdn(william_uuid),
3063 Ok(Some("name=william".to_string()))
3064 );
3065
3066 let e1_ts = e1.to_tombstone(CID_ONE.clone()).into_sealed_committed();
3068 assert!(be.modify(&CID_ONE, &[e1], &[e1_ts]).is_ok());
3069 be.reap_tombstones(&CID_ADV, &CID_TWO).unwrap();
3070
3071 idl_state!(
3072 be,
3073 Attribute::Name.as_ref(),
3074 IndexType::Equality,
3075 "william",
3076 Some(Vec::with_capacity(0))
3077 );
3078
3079 idl_state!(
3080 be,
3081 Attribute::Name.as_ref(),
3082 IndexType::Presence,
3083 "_",
3084 Some(Vec::with_capacity(0))
3085 );
3086
3087 idl_state!(
3088 be,
3089 Attribute::Uuid.as_ref(),
3090 IndexType::Equality,
3091 "db237e8a-0079-4b8c-8a56-593b22aa44d1",
3092 Some(Vec::with_capacity(0))
3093 );
3094
3095 idl_state!(
3096 be,
3097 Attribute::Uuid.as_ref(),
3098 IndexType::Presence,
3099 "_",
3100 Some(Vec::with_capacity(0))
3101 );
3102
3103 assert_eq!(be.name2uuid("william"), Ok(None));
3104 assert_eq!(be.uuid2spn(william_uuid), Ok(None));
3105 assert_eq!(be.uuid2rdn(william_uuid), Ok(None));
3106 })
3107 }
3108
3109 #[test]
3110 fn test_be_index_create_delete_multi() {
3111 run_test!(|be: &mut BackendWriteTransaction| {
3112 assert!(be.reindex(false).is_ok());
3115 let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
3118 e1.add_ava(Attribute::Name, Value::new_iname("william"));
3119 e1.add_ava(
3120 Attribute::Uuid,
3121 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
3122 );
3123 let e1 = e1.into_sealed_new();
3124
3125 let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
3126 e2.add_ava(Attribute::Name, Value::new_iname("claire"));
3127 e2.add_ava(
3128 Attribute::Uuid,
3129 Value::from("bd651620-00dd-426b-aaa0-4494f7b7906f"),
3130 );
3131 let e2 = e2.into_sealed_new();
3132
3133 let mut e3: Entry<EntryInit, EntryNew> = Entry::new();
3134 e3.add_ava(Attribute::UserId, Value::new_iname("lucy"));
3135 e3.add_ava(
3136 Attribute::Uuid,
3137 Value::from("7b23c99d-c06b-4a9a-a958-3afa56383e1d"),
3138 );
3139 let e3 = e3.into_sealed_new();
3140
3141 let mut rset = be.create(&CID_ZERO, vec![e1, e2, e3]).unwrap();
3142 rset.remove(1);
3143 let mut rset: Vec<_> = rset.into_iter().map(Arc::new).collect();
3144 let e1 = rset.pop().unwrap();
3145 let e3 = rset.pop().unwrap();
3146
3147 let e1_ts = e1.to_tombstone(CID_ONE.clone()).into_sealed_committed();
3149 let e3_ts = e3.to_tombstone(CID_ONE.clone()).into_sealed_committed();
3150 assert!(be.modify(&CID_ONE, &[e1, e3], &[e1_ts, e3_ts]).is_ok());
3151 be.reap_tombstones(&CID_ADV, &CID_TWO).unwrap();
3152
3153 idl_state!(
3154 be,
3155 Attribute::Name.as_ref(),
3156 IndexType::Equality,
3157 "claire",
3158 Some(vec![2])
3159 );
3160
3161 idl_state!(
3162 be,
3163 Attribute::Name.as_ref(),
3164 IndexType::Presence,
3165 "_",
3166 Some(vec![2])
3167 );
3168
3169 idl_state!(
3170 be,
3171 Attribute::Uuid.as_ref(),
3172 IndexType::Equality,
3173 "bd651620-00dd-426b-aaa0-4494f7b7906f",
3174 Some(vec![2])
3175 );
3176
3177 idl_state!(
3178 be,
3179 Attribute::Uuid.as_ref(),
3180 IndexType::Presence,
3181 "_",
3182 Some(vec![2])
3183 );
3184
3185 let claire_uuid = uuid!("bd651620-00dd-426b-aaa0-4494f7b7906f");
3186 let william_uuid = uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1");
3187 let lucy_uuid = uuid!("7b23c99d-c06b-4a9a-a958-3afa56383e1d");
3188
3189 assert_eq!(be.name2uuid("claire"), Ok(Some(claire_uuid)));
3190 let x = be.uuid2spn(claire_uuid);
3191 trace!(?x);
3192 assert_eq!(
3193 be.uuid2spn(claire_uuid),
3194 Ok(Some(Value::new_iname("claire")))
3195 );
3196 assert_eq!(
3197 be.uuid2rdn(claire_uuid),
3198 Ok(Some("name=claire".to_string()))
3199 );
3200
3201 assert_eq!(be.name2uuid("william"), Ok(None));
3202 assert_eq!(be.uuid2spn(william_uuid), Ok(None));
3203 assert_eq!(be.uuid2rdn(william_uuid), Ok(None));
3204
3205 assert_eq!(be.name2uuid("lucy"), Ok(None));
3206 assert_eq!(be.uuid2spn(lucy_uuid), Ok(None));
3207 assert_eq!(be.uuid2rdn(lucy_uuid), Ok(None));
3208 })
3209 }
3210
3211 #[test]
3212 fn test_be_index_modify_simple() {
3213 run_test!(|be: &mut BackendWriteTransaction| {
3214 assert!(be.reindex(false).is_ok());
3215 let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
3219 e1.add_ava(Attribute::Name, Value::new_iname("william"));
3220 e1.add_ava(
3221 Attribute::Uuid,
3222 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
3223 );
3224 e1.add_ava(Attribute::TestAttr, Value::from("test"));
3225 let e1 = e1.into_sealed_new();
3226
3227 let rset = be.create(&CID_ZERO, vec![e1]).unwrap();
3228 let rset: Vec<_> = rset.into_iter().map(Arc::new).collect();
3229 let mut ce1 = rset[0].as_ref().clone().into_invalid();
3231 ce1.add_ava(Attribute::TestNumber, Value::from("test"));
3233 ce1.purge_ava(Attribute::TestAttr);
3235 ce1.purge_ava(Attribute::Name);
3237 ce1.add_ava(Attribute::Name, Value::new_iname("claire"));
3238
3239 let ce1 = ce1.into_sealed_committed();
3240
3241 be.modify(&CID_ZERO, &rset, &[ce1]).unwrap();
3242
3243 idl_state!(
3245 be,
3246 Attribute::Name.as_ref(),
3247 IndexType::Equality,
3248 "claire",
3249 Some(vec![1])
3250 );
3251
3252 idl_state!(
3253 be,
3254 Attribute::Name.as_ref(),
3255 IndexType::Presence,
3256 "_",
3257 Some(vec![1])
3258 );
3259
3260 idl_state!(
3261 be,
3262 Attribute::TestNumber.as_ref(),
3263 IndexType::Equality,
3264 "test",
3265 Some(vec![1])
3266 );
3267
3268 idl_state!(
3269 be,
3270 Attribute::TestAttr,
3271 IndexType::Equality,
3272 "test",
3273 Some(vec![])
3274 );
3275
3276 let william_uuid = uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1");
3277 assert_eq!(be.name2uuid("william"), Ok(None));
3278 assert_eq!(be.name2uuid("claire"), Ok(Some(william_uuid)));
3279 assert_eq!(
3280 be.uuid2spn(william_uuid),
3281 Ok(Some(Value::new_iname("claire")))
3282 );
3283 assert_eq!(
3284 be.uuid2rdn(william_uuid),
3285 Ok(Some("name=claire".to_string()))
3286 );
3287 })
3288 }
3289
3290 #[test]
3291 fn test_be_index_modify_rename() {
3292 run_test!(|be: &mut BackendWriteTransaction| {
3293 assert!(be.reindex(false).is_ok());
3294 let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
3298 e1.add_ava(Attribute::Name, Value::new_iname("william"));
3299 e1.add_ava(
3300 Attribute::Uuid,
3301 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
3302 );
3303 let e1 = e1.into_sealed_new();
3304
3305 let rset = be.create(&CID_ZERO, vec![e1]).unwrap();
3306 let rset: Vec<_> = rset.into_iter().map(Arc::new).collect();
3307 let mut ce1 = rset[0].as_ref().clone().into_invalid();
3309 ce1.purge_ava(Attribute::Name);
3310 ce1.purge_ava(Attribute::Uuid);
3311 ce1.add_ava(Attribute::Name, Value::new_iname("claire"));
3312 ce1.add_ava(
3313 Attribute::Uuid,
3314 Value::from("04091a7a-6ce4-42d2-abf5-c2ce244ac9e8"),
3315 );
3316 let ce1 = ce1.into_sealed_committed();
3317
3318 be.modify(&CID_ZERO, &rset, &[ce1]).unwrap();
3319
3320 idl_state!(
3321 be,
3322 Attribute::Name.as_ref(),
3323 IndexType::Equality,
3324 "claire",
3325 Some(vec![1])
3326 );
3327
3328 idl_state!(
3329 be,
3330 Attribute::Uuid.as_ref(),
3331 IndexType::Equality,
3332 "04091a7a-6ce4-42d2-abf5-c2ce244ac9e8",
3333 Some(vec![1])
3334 );
3335
3336 idl_state!(
3337 be,
3338 Attribute::Name.as_ref(),
3339 IndexType::Presence,
3340 "_",
3341 Some(vec![1])
3342 );
3343 idl_state!(
3344 be,
3345 Attribute::Uuid.as_ref(),
3346 IndexType::Presence,
3347 "_",
3348 Some(vec![1])
3349 );
3350
3351 idl_state!(
3352 be,
3353 Attribute::Uuid.as_ref(),
3354 IndexType::Equality,
3355 "db237e8a-0079-4b8c-8a56-593b22aa44d1",
3356 Some(Vec::with_capacity(0))
3357 );
3358 idl_state!(
3359 be,
3360 Attribute::Name.as_ref(),
3361 IndexType::Equality,
3362 "william",
3363 Some(Vec::with_capacity(0))
3364 );
3365
3366 let claire_uuid = uuid!("04091a7a-6ce4-42d2-abf5-c2ce244ac9e8");
3367 let william_uuid = uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1");
3368 assert_eq!(be.name2uuid("william"), Ok(None));
3369 assert_eq!(be.name2uuid("claire"), Ok(Some(claire_uuid)));
3370 assert_eq!(be.uuid2spn(william_uuid), Ok(None));
3371 assert_eq!(be.uuid2rdn(william_uuid), Ok(None));
3372 assert_eq!(
3373 be.uuid2spn(claire_uuid),
3374 Ok(Some(Value::new_iname("claire")))
3375 );
3376 assert_eq!(
3377 be.uuid2rdn(claire_uuid),
3378 Ok(Some("name=claire".to_string()))
3379 );
3380 })
3381 }
3382
3383 #[test]
3384 fn test_be_index_search_simple() {
3385 run_test!(|be: &mut BackendWriteTransaction| {
3386 assert!(be.reindex(false).is_ok());
3387
3388 let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
3390 e1.add_ava(Attribute::Name, Value::new_iname("william"));
3391 e1.add_ava(
3392 Attribute::Uuid,
3393 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
3394 );
3395 e1.add_ava(Attribute::NoIndex, Value::from("william"));
3396 e1.add_ava(Attribute::OtherNoIndex, Value::from("william"));
3397 let e1 = e1.into_sealed_new();
3398
3399 let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
3400 e2.add_ava(Attribute::Name, Value::new_iname("claire"));
3401 e2.add_ava(
3402 Attribute::Uuid,
3403 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d2"),
3404 );
3405 let e2 = e2.into_sealed_new();
3406
3407 let _rset = be.create(&CID_ZERO, vec![e1, e2]).unwrap();
3408 let f_un =
3410 filter_resolved!(f_eq(Attribute::NoIndex, PartialValue::new_utf8s("william")));
3411
3412 let (r, _plan) = be.filter2idl(f_un.to_inner(), 0).unwrap();
3413 match r {
3414 IdList::AllIds => {}
3415 _ => {
3416 panic!("");
3417 }
3418 }
3419
3420 let feq = filter_resolved!(f_eq(Attribute::Name, PartialValue::new_utf8s("william")));
3422
3423 let (r, _plan) = be.filter2idl(feq.to_inner(), 0).unwrap();
3424 match r {
3425 IdList::Indexed(idl) => {
3426 assert_eq!(idl, IDLBitRange::from_iter(vec![1]));
3427 }
3428 _ => {
3429 panic!("");
3430 }
3431 }
3432
3433 let f_in_and = filter_resolved!(f_and!([
3436 f_eq(Attribute::Name, PartialValue::new_utf8s("william")),
3437 f_eq(
3438 Attribute::Uuid,
3439 PartialValue::new_utf8s("db237e8a-0079-4b8c-8a56-593b22aa44d1")
3440 )
3441 ]));
3442
3443 let (r, _plan) = be.filter2idl(f_in_and.to_inner(), 0).unwrap();
3444 match r {
3445 IdList::Indexed(idl) => {
3446 assert_eq!(idl, IDLBitRange::from_iter(vec![1]));
3447 }
3448 _ => {
3449 panic!("");
3450 }
3451 }
3452
3453 let f_p1 = filter_resolved!(f_and!([
3455 f_eq(Attribute::Name, PartialValue::new_utf8s("william")),
3456 f_eq(Attribute::NoIndex, PartialValue::new_utf8s("william"))
3457 ]));
3458
3459 let f_p2 = filter_resolved!(f_and!([
3460 f_eq(Attribute::Name, PartialValue::new_utf8s("william")),
3461 f_eq(Attribute::NoIndex, PartialValue::new_utf8s("william"))
3462 ]));
3463
3464 let (r, _plan) = be.filter2idl(f_p1.to_inner(), 0).unwrap();
3465 match r {
3466 IdList::Partial(idl) => {
3467 assert_eq!(idl, IDLBitRange::from_iter(vec![1]));
3468 }
3469 _ => unreachable!(),
3470 }
3471
3472 let (r, _plan) = be.filter2idl(f_p2.to_inner(), 0).unwrap();
3473 match r {
3474 IdList::Partial(idl) => {
3475 assert_eq!(idl, IDLBitRange::from_iter(vec![1]));
3476 }
3477 _ => unreachable!(),
3478 }
3479
3480 let f_p3 = filter_resolved!(f_sub(Attribute::Name, PartialValue::new_utf8s("wil")));
3482
3483 let (r, plan) = be.filter2idl(f_p3.to_inner(), 0).unwrap();
3484 trace!(?r, ?plan);
3485 match r {
3486 IdList::Partial(idl) => {
3487 assert_eq!(idl, IDLBitRange::from_iter(vec![1]));
3488 }
3489 _ => unreachable!(),
3490 }
3491
3492 let f_no_and = filter_resolved!(f_and!([
3494 f_eq(Attribute::NoIndex, PartialValue::new_utf8s("william")),
3495 f_eq(Attribute::OtherNoIndex, PartialValue::new_utf8s("william"))
3496 ]));
3497
3498 let (r, _plan) = be.filter2idl(f_no_and.to_inner(), 0).unwrap();
3499 match r {
3500 IdList::AllIds => {}
3501 _ => {
3502 panic!("");
3503 }
3504 }
3505
3506 let f_in_or = filter_resolved!(f_or!([f_eq(
3508 Attribute::Name,
3509 PartialValue::new_utf8s("william")
3510 )]));
3511
3512 let (r, _plan) = be.filter2idl(f_in_or.to_inner(), 0).unwrap();
3513 match r {
3514 IdList::Indexed(idl) => {
3515 assert_eq!(idl, IDLBitRange::from_iter(vec![1]));
3516 }
3517 _ => {
3518 panic!("");
3519 }
3520 }
3521 let f_un_or = filter_resolved!(f_or!([f_eq(
3523 Attribute::NoIndex,
3524 PartialValue::new_utf8s("william")
3525 )]));
3526
3527 let (r, _plan) = be.filter2idl(f_un_or.to_inner(), 0).unwrap();
3528 match r {
3529 IdList::AllIds => {}
3530 _ => {
3531 panic!("");
3532 }
3533 }
3534
3535 let f_r_andnot = filter_resolved!(f_andnot(f_eq(
3537 Attribute::Name,
3538 PartialValue::new_utf8s("william")
3539 )));
3540
3541 let (r, _plan) = be.filter2idl(f_r_andnot.to_inner(), 0).unwrap();
3542 match r {
3543 IdList::Indexed(idl) => {
3544 assert_eq!(idl, IDLBitRange::from_iter(Vec::with_capacity(0)));
3545 }
3546 _ => {
3547 panic!("");
3548 }
3549 }
3550
3551 let f_and_andnot = filter_resolved!(f_and!([f_andnot(f_eq(
3553 Attribute::Name,
3554 PartialValue::new_utf8s("william")
3555 ))]));
3556
3557 let (r, _plan) = be.filter2idl(f_and_andnot.to_inner(), 0).unwrap();
3558 match r {
3559 IdList::Indexed(idl) => {
3560 assert_eq!(idl, IDLBitRange::from_iter(Vec::with_capacity(0)));
3561 }
3562 _ => {
3563 panic!("");
3564 }
3565 }
3566 let f_or_andnot = filter_resolved!(f_or!([f_andnot(f_eq(
3568 Attribute::Name,
3569 PartialValue::new_utf8s("william")
3570 ))]));
3571
3572 let (r, _plan) = be.filter2idl(f_or_andnot.to_inner(), 0).unwrap();
3573 match r {
3574 IdList::Indexed(idl) => {
3575 assert_eq!(idl, IDLBitRange::from_iter(Vec::with_capacity(0)));
3576 }
3577 _ => {
3578 panic!("");
3579 }
3580 }
3581
3582 let f_and_andnot = filter_resolved!(f_and!([
3584 f_andnot(f_eq(Attribute::Name, PartialValue::new_utf8s("claire"))),
3585 f_pres(Attribute::Name)
3586 ]));
3587
3588 let (r, _plan) = be.filter2idl(f_and_andnot.to_inner(), 0).unwrap();
3589 match r {
3590 IdList::Indexed(idl) => {
3591 debug!("{:?}", idl);
3592 assert_eq!(idl, IDLBitRange::from_iter(vec![1]));
3593 }
3594 _ => {
3595 panic!("");
3596 }
3597 }
3598 let f_and_andnot = filter_resolved!(f_and!([
3600 f_pres(Attribute::Name),
3601 f_andnot(f_eq(Attribute::Name, PartialValue::new_utf8s("claire")))
3602 ]));
3603
3604 let (r, _plan) = be.filter2idl(f_and_andnot.to_inner(), 0).unwrap();
3605 match r {
3606 IdList::Indexed(idl) => {
3607 assert_eq!(idl, IDLBitRange::from_iter(vec![1]));
3608 }
3609 _ => {
3610 panic!("");
3611 }
3612 }
3613 let f_and_andnot = filter_resolved!(f_and!([
3615 f_andnot(f_eq(Attribute::Name, PartialValue::new_utf8s("claire"))),
3616 f_pres(Attribute::NoIndex)
3617 ]));
3618
3619 let (r, _plan) = be.filter2idl(f_and_andnot.to_inner(), 0).unwrap();
3620 match r {
3621 IdList::AllIds => {}
3622 _ => {
3623 panic!("");
3624 }
3625 }
3626 let f_and_andnot = filter_resolved!(f_and!([
3628 f_pres(Attribute::NoIndex),
3629 f_andnot(f_eq(Attribute::Name, PartialValue::new_utf8s("claire")))
3630 ]));
3631
3632 let (r, _plan) = be.filter2idl(f_and_andnot.to_inner(), 0).unwrap();
3633 match r {
3634 IdList::AllIds => {}
3635 _ => {
3636 panic!("");
3637 }
3638 }
3639
3640 let f_e_or = filter_resolved!(f_or!([]));
3642
3643 let (r, _plan) = be.filter2idl(f_e_or.to_inner(), 0).unwrap();
3644 match r {
3645 IdList::Indexed(idl) => {
3646 assert_eq!(idl, IDLBitRange::from_iter(vec![]));
3647 }
3648 _ => {
3649 panic!("");
3650 }
3651 }
3652
3653 let f_e_and = filter_resolved!(f_and!([]));
3654
3655 let (r, _plan) = be.filter2idl(f_e_and.to_inner(), 0).unwrap();
3656 match r {
3657 IdList::Indexed(idl) => {
3658 assert_eq!(idl, IDLBitRange::from_iter(vec![]));
3659 }
3660 _ => {
3661 panic!("");
3662 }
3663 }
3664 })
3665 }
3666
3667 #[test]
3668 fn test_be_index_search_missing() {
3669 run_test!(|be: &mut BackendWriteTransaction| {
3670 be.danger_purge_idxs().unwrap();
3673 debug!("{:?}", be.missing_idxs().unwrap());
3674 let f_eq = filter_resolved!(f_eq(Attribute::Name, PartialValue::new_utf8s("william")));
3675
3676 let (r, _plan) = be.filter2idl(f_eq.to_inner(), 0).unwrap();
3677 match r {
3678 IdList::AllIds => {}
3679 _ => {
3680 panic!("");
3681 }
3682 }
3683 })
3684 }
3685
3686 #[test]
3687 fn test_be_index_slope_generation() {
3688 run_test!(|be: &mut BackendWriteTransaction| {
3689 let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
3691 e1.add_ava(Attribute::Name, Value::new_iname("william"));
3692 e1.add_ava(
3693 Attribute::Uuid,
3694 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
3695 );
3696 e1.add_ava(Attribute::TestAttr, Value::from("dupe"));
3697 e1.add_ava(Attribute::TestNumber, Value::from("1"));
3698 let e1 = e1.into_sealed_new();
3699
3700 let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
3701 e2.add_ava(Attribute::Name, Value::new_iname("claire"));
3702 e2.add_ava(
3703 Attribute::Uuid,
3704 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d2"),
3705 );
3706 e2.add_ava(Attribute::TestAttr, Value::from("dupe"));
3707 e2.add_ava(Attribute::TestNumber, Value::from("1"));
3708 let e2 = e2.into_sealed_new();
3709
3710 let mut e3: Entry<EntryInit, EntryNew> = Entry::new();
3711 e3.add_ava(Attribute::Name, Value::new_iname("benny"));
3712 e3.add_ava(
3713 Attribute::Uuid,
3714 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d3"),
3715 );
3716 e3.add_ava(Attribute::TestAttr, Value::from("dupe"));
3717 e3.add_ava(Attribute::TestNumber, Value::from("2"));
3718 let e3 = e3.into_sealed_new();
3719
3720 let _rset = be.create(&CID_ZERO, vec![e1, e2, e3]).unwrap();
3721
3722 assert!(!be.is_idx_slopeyness_generated().unwrap());
3725
3726 let ta_eq_slope = be
3727 .get_idx_slope(&IdxKey::new(Attribute::TestAttr, IndexType::Equality))
3728 .unwrap();
3729 assert_eq!(ta_eq_slope, 45);
3730
3731 let tb_eq_slope = be
3732 .get_idx_slope(&IdxKey::new(Attribute::TestNumber, IndexType::Equality))
3733 .unwrap();
3734 assert_eq!(tb_eq_slope, 45);
3735
3736 let name_eq_slope = be
3737 .get_idx_slope(&IdxKey::new(Attribute::Name, IndexType::Equality))
3738 .unwrap();
3739 assert_eq!(name_eq_slope, 1);
3740 let uuid_eq_slope = be
3741 .get_idx_slope(&IdxKey::new(Attribute::Uuid, IndexType::Equality))
3742 .unwrap();
3743 assert_eq!(uuid_eq_slope, 1);
3744
3745 let name_pres_slope = be
3746 .get_idx_slope(&IdxKey::new(Attribute::Name, IndexType::Presence))
3747 .unwrap();
3748 assert_eq!(name_pres_slope, 90);
3749 let uuid_pres_slope = be
3750 .get_idx_slope(&IdxKey::new(Attribute::Uuid, IndexType::Presence))
3751 .unwrap();
3752 assert_eq!(uuid_pres_slope, 90);
3753 assert!(be.reindex(false).is_ok());
3758 assert!(be.is_idx_slopeyness_generated().unwrap());
3759
3760 let ta_eq_slope = be
3761 .get_idx_slope(&IdxKey::new(Attribute::TestAttr, IndexType::Equality))
3762 .unwrap();
3763 assert_eq!(ta_eq_slope, 200);
3764
3765 let tb_eq_slope = be
3766 .get_idx_slope(&IdxKey::new(Attribute::TestNumber, IndexType::Equality))
3767 .unwrap();
3768 assert_eq!(tb_eq_slope, 133);
3769
3770 let name_eq_slope = be
3771 .get_idx_slope(&IdxKey::new(Attribute::Name, IndexType::Equality))
3772 .unwrap();
3773 assert_eq!(name_eq_slope, 51);
3774 let uuid_eq_slope = be
3775 .get_idx_slope(&IdxKey::new(Attribute::Uuid, IndexType::Equality))
3776 .unwrap();
3777 assert_eq!(uuid_eq_slope, 51);
3778
3779 let name_pres_slope = be
3780 .get_idx_slope(&IdxKey::new(Attribute::Name, IndexType::Presence))
3781 .unwrap();
3782 assert_eq!(name_pres_slope, 200);
3783 let uuid_pres_slope = be
3784 .get_idx_slope(&IdxKey::new(Attribute::Uuid, IndexType::Presence))
3785 .unwrap();
3786 assert_eq!(uuid_pres_slope, 200);
3787 })
3788 }
3789
3790 #[test]
3791 fn test_be_limits_allids() {
3792 run_test!(|be: &mut BackendWriteTransaction| {
3793 let mut lim_allow_allids = Limits::unlimited();
3794 lim_allow_allids.unindexed_allow = true;
3795
3796 let mut lim_deny_allids = Limits::unlimited();
3797 lim_deny_allids.unindexed_allow = false;
3798
3799 let mut e: Entry<EntryInit, EntryNew> = Entry::new();
3800 e.add_ava(Attribute::UserId, Value::from("william"));
3801 e.add_ava(
3802 Attribute::Uuid,
3803 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
3804 );
3805 e.add_ava(Attribute::NonExist, Value::from("x"));
3806 let e = e.into_sealed_new();
3807 let single_result = be.create(&CID_ZERO, vec![e.clone()]);
3808
3809 assert!(single_result.is_ok());
3810 let filt = e
3811 .filter_from_attrs(&[Attribute::NonExist])
3812 .expect("failed to generate filter")
3813 .into_valid_resolved();
3814 let res = be.search(&lim_allow_allids, &filt);
3816 assert!(res.is_ok());
3817 let res = be.exists(&lim_allow_allids, &filt);
3818 assert!(res.is_ok());
3819
3820 let res = be.search(&lim_deny_allids, &filt);
3822 assert_eq!(res, Err(OperationError::ResourceLimit));
3823 let res = be.exists(&lim_deny_allids, &filt);
3824 assert_eq!(res, Err(OperationError::ResourceLimit));
3825 })
3826 }
3827
3828 #[test]
3829 fn test_be_limits_results_max() {
3830 run_test!(|be: &mut BackendWriteTransaction| {
3831 let mut lim_allow = Limits::unlimited();
3832 lim_allow.search_max_results = usize::MAX;
3833
3834 let mut lim_deny = Limits::unlimited();
3835 lim_deny.search_max_results = 0;
3836
3837 let mut e: Entry<EntryInit, EntryNew> = Entry::new();
3838 e.add_ava(Attribute::UserId, Value::from("william"));
3839 e.add_ava(
3840 Attribute::Uuid,
3841 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
3842 );
3843 e.add_ava(Attribute::NonExist, Value::from("x"));
3844 let e = e.into_sealed_new();
3845 let single_result = be.create(&CID_ZERO, vec![e.clone()]);
3846 assert!(single_result.is_ok());
3847
3848 let filt = e
3849 .filter_from_attrs(&[Attribute::NonExist])
3850 .expect("failed to generate filter")
3851 .into_valid_resolved();
3852
3853 let res = be.search(&lim_allow, &filt);
3856 assert!(res.is_ok());
3857 let res = be.exists(&lim_allow, &filt);
3858 assert!(res.is_ok());
3859
3860 let res = be.search(&lim_deny, &filt);
3862 assert_eq!(res, Err(OperationError::ResourceLimit));
3863 let res = be.exists(&lim_deny, &filt);
3865 assert!(res.is_ok());
3866
3867 assert!(be.reindex(false).is_ok());
3869 let res = be.search(&lim_deny, &filt);
3870 assert_eq!(res, Err(OperationError::ResourceLimit));
3871 let res = be.exists(&lim_deny, &filt);
3873 assert!(res.is_ok());
3874 })
3875 }
3876
3877 #[test]
3878 fn test_be_limits_partial_filter() {
3879 run_test!(|be: &mut BackendWriteTransaction| {
3880 let mut lim_allow = Limits::unlimited();
3891 lim_allow.search_max_filter_test = usize::MAX;
3892
3893 let mut lim_deny = Limits::unlimited();
3894 lim_deny.search_max_filter_test = 0;
3895
3896 let mut e: Entry<EntryInit, EntryNew> = Entry::new();
3897 e.add_ava(Attribute::Name, Value::new_iname("william"));
3898 e.add_ava(
3899 Attribute::Uuid,
3900 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
3901 );
3902 e.add_ava(Attribute::NonExist, Value::from("x"));
3903 e.add_ava(Attribute::NonExist, Value::from("y"));
3904 let e = e.into_sealed_new();
3905 let single_result = be.create(&CID_ZERO, vec![e]);
3906 assert!(single_result.is_ok());
3907
3908 assert!(be.reindex(false).is_ok());
3910
3911 let filt = filter_resolved!(f_and!([
3922 f_or!([
3923 f_eq(Attribute::NonExist, PartialValue::new_utf8s("x")),
3924 f_eq(Attribute::NonExist, PartialValue::new_utf8s("y"))
3925 ]),
3926 f_or!([
3927 f_eq(Attribute::Name, PartialValue::new_utf8s("claire")),
3928 f_eq(Attribute::Name, PartialValue::new_utf8s("william"))
3929 ]),
3930 ]));
3931
3932 let res = be.search(&lim_allow, &filt);
3933 assert!(res.is_ok());
3934 let res = be.exists(&lim_allow, &filt);
3935 assert!(res.is_ok());
3936
3937 let res = be.search(&lim_deny, &filt);
3939 assert_eq!(res, Err(OperationError::ResourceLimit));
3940 let res = be.exists(&lim_deny, &filt);
3942 assert_eq!(res, Err(OperationError::ResourceLimit));
3943 })
3944 }
3945
3946 #[test]
3947 fn test_be_multiple_create() {
3948 sketching::test_init();
3949
3950 let idxmeta = vec![IdxKey {
3952 attr: Attribute::Uuid,
3953 itype: IndexType::Equality,
3954 }];
3955
3956 let be_a = Backend::new(BackendConfig::new_test("main"), idxmeta.clone(), false)
3957 .expect("Failed to setup backend");
3958
3959 let be_b = Backend::new(BackendConfig::new_test("db_2"), idxmeta, false)
3960 .expect("Failed to setup backend");
3961
3962 let mut be_a_txn = be_a.write().unwrap();
3963 let mut be_b_txn = be_b.write().unwrap();
3964
3965 assert!(be_a_txn.get_db_s_uuid() != be_b_txn.get_db_s_uuid());
3966
3967 let mut e: Entry<EntryInit, EntryNew> = Entry::new();
3969 e.add_ava(Attribute::UserId, Value::from("william"));
3970 e.add_ava(
3971 Attribute::Uuid,
3972 Value::from("db237e8a-0079-4b8c-8a56-593b22aa44d1"),
3973 );
3974 let e = e.into_sealed_new();
3975
3976 let single_result = be_a_txn.create(&CID_ZERO, vec![e]);
3977
3978 assert!(single_result.is_ok());
3979
3980 let filt = filter_resolved!(f_eq(Attribute::UserId, PartialValue::new_utf8s("william")));
3982
3983 let lims = Limits::unlimited();
3984
3985 let r = be_a_txn.search(&lims, &filt);
3986 assert!(r.expect("Search failed!").len() == 1);
3987
3988 let r = be_b_txn.search(&lims, &filt);
3989 assert!(r.expect("Search failed!").is_empty());
3990
3991 let mut e: Entry<EntryInit, EntryNew> = Entry::new();
3993 e.add_ava(Attribute::UserId, Value::from("claire"));
3994 e.add_ava(
3995 Attribute::Uuid,
3996 Value::from("0c680959-0944-47d6-9dea-53304d124266"),
3997 );
3998 let e = e.into_sealed_new();
3999
4000 let single_result = be_b_txn.create(&CID_ZERO, vec![e]);
4001
4002 assert!(single_result.is_ok());
4003
4004 let filt = filter_resolved!(f_eq(Attribute::UserId, PartialValue::new_utf8s("claire")));
4006
4007 let lims = Limits::unlimited();
4008
4009 let r = be_a_txn.search(&lims, &filt);
4010 assert!(r.expect("Search failed!").is_empty());
4011
4012 let r = be_b_txn.search(&lims, &filt);
4013 assert!(r.expect("Search failed!").len() == 1);
4014 }
4015}