1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
use crate::PersyId;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use config::Config;
use index::keeper::AddTo;
use index::keeper::IndexSegmentKeeper;
use index::serialization::IndexSerialization;
use persy::{PRes, PersyError, PersyImpl, RecRef};
use snapshot::SnapshotId;
use std::cmp::Ordering;
use std::collections::hash_map::Entry;
use std::collections::hash_map::HashMap;
use std::fmt::Display;
use std::io::{Cursor, Read, Write};
use std::str;
use std::sync::{Arc, Condvar, Mutex};
use transaction::Transaction;

/// Enum of all the possible Key or Value types for indexes
#[derive(Clone)]
pub enum IndexTypeId {
    U8,
    U16,
    U32,
    U64,
    U128,
    I8,
    I16,
    I32,
    I64,
    I128,
    F32W,
    F64W,
    STRING,
    PERSYID,
}

impl From<u8> for IndexTypeId {
    fn from(val: u8) -> IndexTypeId {
        match val {
            1 => IndexTypeId::U8,
            2 => IndexTypeId::U16,
            3 => IndexTypeId::U32,
            4 => IndexTypeId::U64,
            14 => IndexTypeId::U128,
            5 => IndexTypeId::I8,
            6 => IndexTypeId::I16,
            7 => IndexTypeId::I32,
            8 => IndexTypeId::I64,
            15 => IndexTypeId::I128,
            9 => IndexTypeId::F32W,
            10 => IndexTypeId::F64W,
            12 => IndexTypeId::STRING,
            13 => IndexTypeId::PERSYID,
            _ => panic!("type node defined for {}", val),
        }
    }
}

/// Trait implemented by all supported types in the index
pub trait IndexType: Display + Sized + IndexOrd + Clone + AddTo + IndexSerialization {
    fn get_id() -> u8;
    fn get_type_id() -> IndexTypeId;
}
pub trait IndexOrd {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering;
}

macro_rules! impl_index_ord {
    ($t:ident) => {
        impl IndexOrd for $t {
            fn cmp(&self, other: &Self) -> std::cmp::Ordering {
                std::cmp::Ord::cmp(self, other)
            }
        }
    };
}
impl_index_ord!(u8);
impl_index_ord!(u16);
impl_index_ord!(u32);
impl_index_ord!(u64);
impl_index_ord!(u128);
impl_index_ord!(i8);
impl_index_ord!(i16);
impl_index_ord!(i32);
impl_index_ord!(i64);
impl_index_ord!(i128);
impl_index_ord!(String);
impl_index_ord!(PersyId);

impl IndexOrd for f32 {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        if self.is_nan() {
            if other.is_nan() {
                std::cmp::Ordering::Equal
            } else {
                std::cmp::Ordering::Less
            }
        } else if other.is_nan() {
            std::cmp::Ordering::Greater
        } else {
            std::cmp::PartialOrd::partial_cmp(self, other).unwrap()
        }
    }
}

impl IndexOrd for f64 {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        if self.is_nan() {
            if other.is_nan() {
                std::cmp::Ordering::Equal
            } else {
                std::cmp::Ordering::Less
            }
        } else if other.is_nan() {
            std::cmp::Ordering::Greater
        } else {
            std::cmp::PartialOrd::partial_cmp(self, other).unwrap()
        }
    }
}

/// Define the behavior of the index in case a key value pair already exists
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ValueMode {
    /// An error will return if a key value pair already exists
    EXCLUSIVE,
    /// The value will be add to a list of values for the key, duplicate value will be collapsed to
    /// only one entry
    CLUSTER,
    /// The existing value will be replaced with the new value if a key value pair already exists
    REPLACE,
}

pub const INDEX_META_PREFIX: &str = "+_M";
pub const INDEX_DATA_PREFIX: &str = "+_D";

fn format_segment_name_meta(index_name: &str) -> String {
    format!("{}{}", INDEX_META_PREFIX, index_name)
}

fn format_segment_name_data(index_name: &str) -> String {
    format!("{}{}", INDEX_DATA_PREFIX, index_name)
}

#[derive(Debug, PartialOrd, PartialEq, Clone)]
pub struct F32W(pub f32);
#[derive(Debug, PartialOrd, PartialEq, Clone)]
pub struct F64W(pub f64);

impl Ord for F32W {
    fn cmp(&self, other: &Self) -> Ordering {
        if let Some(r) = self.partial_cmp(&other) {
            r
        } else if self.0.is_nan() {
            Ordering::Greater
        } else {
            Ordering::Less
        }
    }
}
impl Eq for F32W {}
impl Display for F32W {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.0.fmt(f)
    }
}
impl From<f32> for F32W {
    fn from(f: f32) -> F32W {
        F32W(f)
    }
}
impl From<&f32> for F32W {
    fn from(f: &f32) -> F32W {
        F32W(*f)
    }
}

impl From<F32W> for f32 {
    fn from(f: F32W) -> f32 {
        f.0
    }
}

impl Ord for F64W {
    fn cmp(&self, other: &Self) -> Ordering {
        if let Some(r) = self.partial_cmp(&other) {
            r
        } else if self.0.is_nan() {
            Ordering::Greater
        } else {
            Ordering::Less
        }
    }
}
impl Eq for F64W {}
impl Display for F64W {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.0.fmt(f)
    }
}
impl From<f64> for F64W {
    fn from(f: f64) -> F64W {
        F64W(f)
    }
}

impl From<&f64> for F64W {
    fn from(f: &f64) -> F64W {
        F64W(*f)
    }
}
impl From<F64W> for f64 {
    fn from(f: F64W) -> f64 {
        f.0
    }
}

impl From<u8> for ValueMode {
    fn from(value: u8) -> Self {
        match value {
            1 => ValueMode::EXCLUSIVE,
            2 => ValueMode::CLUSTER,
            3 => ValueMode::REPLACE,
            _ => unreachable!("is impossible to get a value mode from values not 1,2,3"),
        }
    }
}

impl ValueMode {
    fn to_u8(&self) -> u8 {
        match self {
            ValueMode::EXCLUSIVE => 1,
            ValueMode::CLUSTER => 2,
            ValueMode::REPLACE => 3,
        }
    }
}

struct IndexLock {
    write: bool,
    read_count: u32,
    cond: Arc<Condvar>,
}

impl IndexLock {
    fn new_write() -> IndexLock {
        IndexLock {
            write: true,
            read_count: 0,
            cond: Arc::new(Condvar::new()),
        }
    }

    fn new_read() -> IndexLock {
        IndexLock {
            write: false,
            read_count: 1,
            cond: Arc::new(Condvar::new()),
        }
    }

    fn inc_read(&mut self) {
        self.read_count += 1;
    }

    fn dec_read(&mut self) -> bool {
        self.read_count -= 1;
        self.read_count == 0
    }
}

pub struct Indexes {
    index_locks: Mutex<HashMap<String, IndexLock>>,
    config: Arc<Config>,
}

#[derive(Clone)]
pub struct IndexConfig {
    name: String,
    root: Option<RecRef>,
    pub key_type: u8,
    pub value_type: u8,
    page_min: usize,
    page_max: usize,
    pub value_mode: ValueMode,
}

impl IndexConfig {
    fn serialize(&self, w: &mut dyn Write) -> PRes<()> {
        if let Some(ref root) = self.root {
            w.write_u64::<BigEndian>(root.page)?;
            w.write_u32::<BigEndian>(root.pos)?;
        } else {
            w.write_u64::<BigEndian>(0)?;
            w.write_u32::<BigEndian>(0)?;
        }
        w.write_u8(self.key_type)?;
        w.write_u8(self.value_type)?;
        w.write_u32::<BigEndian>(self.page_min as u32)?;
        w.write_u32::<BigEndian>(self.page_max as u32)?;
        w.write_u8(self.value_mode.to_u8())?;
        w.write_u16::<BigEndian>(self.name.len() as u16)?;
        w.write_all(self.name.as_bytes())?;
        Ok(())
    }
    fn deserialize(r: &mut dyn Read) -> PRes<IndexConfig> {
        let index_root_page = r.read_u64::<BigEndian>()?;
        let index_root_pos = r.read_u32::<BigEndian>()?;
        let key_type = r.read_u8()?;
        let value_type = r.read_u8()?;
        let page_min = r.read_u32::<BigEndian>()? as usize;
        let page_max = r.read_u32::<BigEndian>()? as usize;
        let value_mode = ValueMode::from(r.read_u8()?);

        let name_size = r.read_u16::<BigEndian>()? as usize;
        let mut slice: Vec<u8> = vec![0; name_size];
        r.read_exact(&mut slice)?;
        let name: String = str::from_utf8(&slice[0..name_size])?.into();
        let root = if index_root_page != 0 && index_root_pos != 0 {
            Some(RecRef::new(index_root_page, index_root_pos))
        } else {
            None
        };
        Ok(IndexConfig {
            name,
            root,
            key_type,
            value_type,
            page_min,
            page_max,
            value_mode,
        })
    }
}

fn error_map(err: PersyError) -> PersyError {
    if let PersyError::SegmentNotFound = err {
        PersyError::IndexNotFound
    } else {
        err
    }
}

impl Indexes {
    pub fn new(config: &Arc<Config>) -> Indexes {
        Indexes {
            index_locks: Mutex::new(HashMap::new()),
            config: config.clone(),
        }
    }

    pub fn create_index<K, V>(
        p: &PersyImpl,
        tx: &mut Transaction,
        name: &str,
        min: usize,
        max: usize,
        value_mode: ValueMode,
    ) -> PRes<()>
    where
        K: IndexType,
        V: IndexType,
    {
        if min > max / 2 {
            return Err(PersyError::IndexMinElementsShouldBeAtLeastDoubleOfMax);
        }
        let segment_name_meta = format_segment_name_meta(name);
        p.create_segment(tx, &segment_name_meta)?;
        let segment_name_data = format_segment_name_data(name);
        p.create_segment(tx, &segment_name_data)?;
        let cfg = IndexConfig {
            name: name.to_string(),
            root: None,
            key_type: K::get_id(),
            value_type: V::get_id(),
            page_min: min,
            page_max: max,
            value_mode,
        };
        let mut scfg = Vec::new();
        cfg.serialize(&mut scfg)?;
        p.insert_record(tx, &segment_name_meta, &scfg)?;
        Ok(())
    }

    pub fn drop_index(p: &PersyImpl, tx: &mut Transaction, name: &str) -> PRes<()> {
        let segment_name_meta = format_segment_name_meta(name);
        p.drop_segment(tx, &segment_name_meta)?;
        let segment_name_data = format_segment_name_data(name);
        p.drop_segment(tx, &segment_name_data)?;
        Ok(())
    }

    pub fn update_index_root(p: &PersyImpl, tx: &mut Transaction, name: &str, root: Option<RecRef>) -> PRes<()> {
        let segment_name = format_segment_name_meta(name);
        let (id, mut config) =
            if let Some((rid, content)) = p.scan_tx(tx, &segment_name).map_err(error_map)?.next(p, tx) {
                (rid, IndexConfig::deserialize(&mut Cursor::new(content))?)
            } else {
                return Err(PersyError::IndexNotFound);
            };

        if config.root != root {
            config.root = root;
            let mut scfg = Vec::new();
            config.serialize(&mut scfg)?;
            p.update_record(tx, &segment_name, &id.0, &scfg)?;
        }
        Ok(())
    }

    pub fn get_index(p: &PersyImpl, op_tx: Option<&mut Transaction>, name: &str) -> PRes<IndexConfig> {
        let segment_name_meta = format_segment_name_meta(name);
        let meta = if let Some(tx) = op_tx {
            p.scan_tx(tx, &segment_name_meta).map_err(error_map)?.next(p, tx)
        } else {
            p.scan(&segment_name_meta).map_err(error_map)?.next(p)
        };

        if let Some((_, content)) = meta {
            Ok(IndexConfig::deserialize(&mut Cursor::new(content))?)
        } else {
            Err(PersyError::IndexNotFound)
        }
    }

    pub fn check_and_get_index<K: IndexType, V: IndexType>(
        p: &PersyImpl,
        op_tx: Option<&mut Transaction>,
        name: &str,
    ) -> PRes<IndexConfig> {
        let index = Indexes::get_index(p, op_tx, name)?;
        if index.key_type != K::get_id() {
            return Err(PersyError::IndexTypeMismatch(
                "given key type miss match to persistent key type".to_string(),
            ));
        }
        if index.value_type != V::get_id() {
            return Err(PersyError::IndexTypeMismatch(
                "given value type miss match to persistent key type".to_string(),
            ));
        }
        Ok(index)
    }

    pub fn check_and_get_index_keeper<'a, K: IndexType, V: IndexType>(
        p: &'a PersyImpl,
        tx: Option<&'a mut Transaction>,
        snapshot: Option<SnapshotId>,
        name: &str,
    ) -> PRes<IndexSegmentKeeper<'a, K, V>> {
        let (config, tx) = if let Some(t) = tx {
            (Indexes::check_and_get_index::<K, V>(p, Some(t), name)?, Some(t))
        } else {
            (Indexes::check_and_get_index::<K, V>(p, None, name)?, None)
        };
        Ok(IndexSegmentKeeper::new(
            name,
            &format_segment_name_data(name),
            config.root,
            p,
            tx,
            snapshot,
            config.value_mode,
        ))
    }

    pub fn write_lock(&self, indexes: &[String]) -> PRes<()> {
        for index in indexes {
            let seg_lock = IndexLock::new_write();
            let mut lock_manager = self.index_locks.lock()?;
            loop {
                let cond = match lock_manager.entry(index.clone()) {
                    Entry::Occupied(o) => o.get().cond.clone(),
                    Entry::Vacant(v) => {
                        v.insert(seg_lock);
                        break;
                    }
                };
                let result = cond.wait_timeout(lock_manager, self.config.transaction_lock_timeout().clone())?;
                lock_manager = result.0;
            }
        }
        Ok(())
    }

    pub fn read_lock(&self, index: String) -> PRes<()> {
        let mut lock_manager = self.index_locks.lock()?;
        loop {
            let cond;
            match lock_manager.entry(index.clone()) {
                Entry::Occupied(mut o) => {
                    if o.get().write {
                        cond = o.get().cond.clone();
                    } else {
                        o.get_mut().inc_read();
                        break;
                    }
                }
                Entry::Vacant(v) => {
                    v.insert(IndexLock::new_read());
                    break;
                }
            };
            let result = cond.wait_timeout(lock_manager, self.config.transaction_lock_timeout().clone())?;
            lock_manager = result.0;
        }
        Ok(())
    }

    pub fn read_unlock(&self, index: String) -> PRes<()> {
        let mut lock_manager = self.index_locks.lock()?;
        if let Entry::Occupied(mut lock) = lock_manager.entry(index) {
            if lock.get_mut().dec_read() {
                let cond = lock.get().cond.clone();
                lock.remove();
                cond.notify_one();
            }
        }
        Ok(())
    }

    pub fn write_unlock(&self, indexes: &[String]) -> PRes<()> {
        for index in indexes {
            let mut lock_manager = self.index_locks.lock()?;
            if let Some(lock) = lock_manager.remove(index) {
                lock.cond.notify_one();
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::{IndexConfig, ValueMode};
    use std::io::Cursor;

    #[test()]
    fn test_config_ser_des() {
        let cfg = IndexConfig {
            name: "abc".to_string(),
            root: None,
            key_type: 1,
            value_type: 1,
            page_min: 10,
            page_max: 30,
            value_mode: ValueMode::REPLACE,
        };

        let mut buff = Vec::new();
        cfg.serialize(&mut Cursor::new(&mut buff)).expect("serialization works");
        let read = IndexConfig::deserialize(&mut Cursor::new(&mut buff)).expect("deserialization works");
        assert_eq!(cfg.name, read.name);
        assert_eq!(cfg.root, read.root);
        assert_eq!(cfg.key_type, read.key_type);
        assert_eq!(cfg.value_type, read.value_type);
        assert_eq!(cfg.page_min, read.page_min);
        assert_eq!(cfg.page_max, read.page_max);
        assert_eq!(cfg.value_mode, read.value_mode);
    }
}