dynomite-engine 0.0.1

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

use std::fmt;

use serde::de::{self, Deserializer, Visitor};
use serde::{Deserialize, Serialize};

use super::error::ConfError;

macro_rules! string_enum_serde {
    ($t:ty) => {
        impl Serialize for $t {
            fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
                ser.serialize_str(self.as_str())
            }
        }

        impl<'de> Deserialize<'de> for $t {
            fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
                struct V;
                impl Visitor<'_> for V {
                    type Value = $t;
                    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                        f.write_str(concat!("a string naming a ", stringify!($t)))
                    }
                    fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
                        <$t>::parse(v).map_err(|e| E::custom(e.to_string()))
                    }
                    fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
                        self.visit_str(&v)
                    }
                }
                de.deserialize_str(V)
            }
        }
    };
}

string_enum_serde!(SecureServerOption);
string_enum_serde!(HashType);
string_enum_serde!(Distribution);

/// Distribution algorithm selected by the pool's `distribution:`
/// directive.
///
/// `Vnode` is the historical default and the only mode the C
/// reference engine supported in the Rust port until
/// `RandomSlicing` was added. `Ketama`, `Modula`, and `Random`
/// are accepted for backward compatibility with the C
/// configuration vocabulary; they collapse to `Vnode` at
/// runtime and emit a deprecation warning at config-load time.
///
/// # Examples
///
/// ```
/// use dynomite::conf::Distribution;
/// assert_eq!(Distribution::parse("vnode").unwrap(), Distribution::Vnode);
/// assert_eq!(
///     Distribution::parse("random_slicing").unwrap(),
///     Distribution::RandomSlicing
/// );
/// ```
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Distribution {
    /// Per-rack continuum keyed by per-peer token lists. The
    /// historical default.
    Vnode,
    /// Compatibility alias accepted by the C reference; collapsed
    /// to [`Self::Vnode`] at runtime with a deprecation warning.
    Ketama,
    /// Compatibility alias accepted by the C reference; collapsed
    /// to [`Self::Vnode`] at runtime with a deprecation warning.
    Modula,
    /// Compatibility alias accepted by the C reference; collapsed
    /// to [`Self::Vnode`] at runtime with a deprecation warning.
    Random,
    /// Random-slicing distribution: a small, gap-free `(name,
    /// size)` partition table over the 64-bit hash space. See
    /// [`crate::hashkit::random_slicing`].
    RandomSlicing,
}

impl Default for Distribution {
    fn default() -> Self {
        Self::Vnode
    }
}

impl Distribution {
    /// Parse a `distribution:` value (case-insensitive).
    ///
    /// # Errors
    /// Returns [`ConfError::BadDistribution`] when the value is
    /// not a recognised mode.
    ///
    /// # Examples
    ///
    /// ```
    /// use dynomite::conf::Distribution;
    /// assert_eq!(Distribution::parse("VNODE").unwrap(), Distribution::Vnode);
    /// assert!(Distribution::parse("sphere").is_err());
    /// ```
    pub fn parse(s: &str) -> Result<Self, ConfError> {
        Ok(match s.to_ascii_lowercase().as_str() {
            "vnode" => Distribution::Vnode,
            "ketama" => Distribution::Ketama,
            "modula" => Distribution::Modula,
            "random" => Distribution::Random,
            "random_slicing" | "random-slicing" => Distribution::RandomSlicing,
            _ => return Err(ConfError::BadDistribution(s.to_string())),
        })
    }

    /// Render back to the canonical YAML name.
    ///
    /// # Examples
    ///
    /// ```
    /// use dynomite::conf::Distribution;
    /// assert_eq!(Distribution::Vnode.as_str(), "vnode");
    /// assert_eq!(Distribution::RandomSlicing.as_str(), "random_slicing");
    /// ```
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Distribution::Vnode => "vnode",
            Distribution::Ketama => "ketama",
            Distribution::Modula => "modula",
            Distribution::Random => "random",
            Distribution::RandomSlicing => "random_slicing",
        }
    }

    /// True for the modes that survived the C-to-Rust port
    /// untouched; `Ketama`, `Modula`, and `Random` are accepted
    /// for backward compatibility but collapse to `Vnode` at
    /// runtime.
    ///
    /// # Examples
    ///
    /// ```
    /// use dynomite::conf::Distribution;
    /// assert!(Distribution::Vnode.is_supported());
    /// assert!(Distribution::RandomSlicing.is_supported());
    /// assert!(!Distribution::Ketama.is_supported());
    /// ```
    #[must_use]
    pub const fn is_supported(self) -> bool {
        matches!(self, Distribution::Vnode | Distribution::RandomSlicing)
    }
}

impl fmt::Display for Distribution {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Datastore family selected by `data_store:`.
///
/// # Examples
///
/// ```
/// use dynomite::conf::DataStore;
/// assert_eq!(DataStore::from_int(0).unwrap(), DataStore::Redis);
/// assert_eq!(DataStore::Redis.as_int(), 0);
/// assert_eq!(DataStore::from_name("noxu").unwrap(), DataStore::Noxu);
/// ```
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum DataStore {
    /// Redis (RESP) datastore. Encoded as `0` in YAML.
    Redis,
    /// Memcached ASCII datastore. Encoded as `1` in YAML.
    Memcache,
    /// In-process Noxu DB datastore (Riak-shaped). Encoded as
    /// `2` in YAML, or as the string `noxu`. Selecting this
    /// variant requires `dynomited` to be built with
    /// `--features riak` and a sibling `noxu_path:` knob.
    Noxu,
}

impl DataStore {
    /// Parse a `data_store:` value as it appears in YAML.
    ///
    /// # Examples
    ///
    /// ```
    /// use dynomite::conf::DataStore;
    /// assert_eq!(DataStore::from_int(1).unwrap(), DataStore::Memcache);
    /// assert_eq!(DataStore::from_int(2).unwrap(), DataStore::Noxu);
    /// assert!(DataStore::from_int(7).is_err());
    /// ```
    pub fn from_int(v: i64) -> Result<Self, ConfError> {
        match v {
            0 => Ok(DataStore::Redis),
            1 => Ok(DataStore::Memcache),
            2 => Ok(DataStore::Noxu),
            n => Err(ConfError::BadDataStore(n)),
        }
    }

    /// Parse the textual form of a `data_store:` value, as
    /// accepted in YAML alongside the integer form.
    ///
    /// Comparison is case-insensitive against `redis`,
    /// `memcache`, `memcached`, and `noxu`.
    ///
    /// # Examples
    ///
    /// ```
    /// use dynomite::conf::DataStore;
    /// assert_eq!(DataStore::from_name("REDIS").unwrap(), DataStore::Redis);
    /// assert!(DataStore::from_name("sql").is_err());
    /// ```
    pub fn from_name(s: &str) -> Result<Self, ConfError> {
        if s.eq_ignore_ascii_case("redis") {
            Ok(DataStore::Redis)
        } else if s.eq_ignore_ascii_case("memcache") || s.eq_ignore_ascii_case("memcached") {
            Ok(DataStore::Memcache)
        } else if s.eq_ignore_ascii_case("noxu") {
            Ok(DataStore::Noxu)
        } else {
            Err(ConfError::BadDataStore(-1))
        }
    }

    /// Encode back to the small integer used in YAML.
    ///
    /// # Examples
    ///
    /// ```
    /// use dynomite::conf::DataStore;
    /// assert_eq!(DataStore::Memcache.as_int(), 1);
    /// assert_eq!(DataStore::Noxu.as_int(), 2);
    /// ```
    pub fn as_int(self) -> i64 {
        match self {
            DataStore::Redis => 0,
            DataStore::Memcache => 1,
            DataStore::Noxu => 2,
        }
    }

    /// Return the canonical lower-case textual name.
    ///
    /// # Examples
    ///
    /// ```
    /// use dynomite::conf::DataStore;
    /// assert_eq!(DataStore::Noxu.as_name(), "noxu");
    /// ```
    pub fn as_name(self) -> &'static str {
        match self {
            DataStore::Redis => "redis",
            DataStore::Memcache => "memcache",
            DataStore::Noxu => "noxu",
        }
    }
}

/// Inter-node security mode selected by `secure_server_option:`.
///
/// # Examples
///
/// ```
/// use dynomite::conf::SecureServerOption;
/// assert_eq!(
///     SecureServerOption::parse("datacenter").unwrap(),
///     SecureServerOption::Datacenter,
/// );
/// ```
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum SecureServerOption {
    /// No inter-node TLS.
    None,
    /// TLS only between racks (within a DC).
    Rack,
    /// TLS only between datacenters.
    Datacenter,
    /// TLS between all nodes.
    All,
}

impl SecureServerOption {
    /// Parse a `secure_server_option:` value, case-sensitively.
    ///
    /// # Examples
    ///
    /// ```
    /// use dynomite::conf::SecureServerOption;
    /// assert_eq!(SecureServerOption::parse("none").unwrap(), SecureServerOption::None);
    /// assert!(SecureServerOption::parse("NONE").is_err());
    /// ```
    pub fn parse(s: &str) -> Result<Self, ConfError> {
        match s {
            "none" => Ok(SecureServerOption::None),
            "rack" => Ok(SecureServerOption::Rack),
            "datacenter" => Ok(SecureServerOption::Datacenter),
            "all" => Ok(SecureServerOption::All),
            other => Err(ConfError::BadSecure(other.to_string())),
        }
    }

    /// Render back to the YAML string form.
    ///
    /// # Examples
    ///
    /// ```
    /// use dynomite::conf::SecureServerOption;
    /// assert_eq!(SecureServerOption::All.as_str(), "all");
    /// ```
    pub fn as_str(self) -> &'static str {
        match self {
            SecureServerOption::None => "none",
            SecureServerOption::Rack => "rack",
            SecureServerOption::Datacenter => "datacenter",
            SecureServerOption::All => "all",
        }
    }
}

impl fmt::Display for SecureServerOption {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Quorum policy for read or write paths.
///
/// # Examples
///
/// ```
/// use dynomite::conf::ConsistencyLevel;
/// let lvl = ConsistencyLevel::parse("read_consistency", "DC_QUORUM").unwrap();
/// assert_eq!(lvl, ConsistencyLevel::DcQuorum);
/// ```
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum ConsistencyLevel {
    /// Single replica acknowledgement.
    DcOne,
    /// Majority within a single datacenter.
    DcQuorum,
    /// Majority within a single datacenter with checksum repair.
    DcSafeQuorum,
    /// Majority within every datacenter, with checksum repair.
    DcEachSafeQuorum,
}

impl ConsistencyLevel {
    /// Parse a `read_consistency` or `write_consistency` value.
    ///
    /// Comparison is case-insensitive against the canonical names
    /// `DC_ONE`, `DC_QUORUM`, `DC_SAFE_QUORUM`, and
    /// `DC_EACH_SAFE_QUORUM`.
    ///
    /// # Examples
    ///
    /// ```
    /// use dynomite::conf::ConsistencyLevel;
    /// assert_eq!(
    ///     ConsistencyLevel::parse("read_consistency", "dc_one").unwrap(),
    ///     ConsistencyLevel::DcOne,
    /// );
    /// assert!(ConsistencyLevel::parse("read_consistency", "nope").is_err());
    /// ```
    pub fn parse(field: &'static str, s: &str) -> Result<Self, ConfError> {
        if s.eq_ignore_ascii_case("dc_one") {
            Ok(ConsistencyLevel::DcOne)
        } else if s.eq_ignore_ascii_case("dc_quorum") {
            Ok(ConsistencyLevel::DcQuorum)
        } else if s.eq_ignore_ascii_case("dc_safe_quorum") {
            Ok(ConsistencyLevel::DcSafeQuorum)
        } else if s.eq_ignore_ascii_case("dc_each_safe_quorum") {
            Ok(ConsistencyLevel::DcEachSafeQuorum)
        } else {
            Err(ConfError::BadConsistency {
                field,
                value: s.to_string(),
            })
        }
    }

    /// Render back to the canonical YAML name.
    ///
    /// # Examples
    ///
    /// ```
    /// use dynomite::conf::ConsistencyLevel;
    /// assert_eq!(ConsistencyLevel::DcSafeQuorum.as_str(), "DC_SAFE_QUORUM");
    /// ```
    pub fn as_str(self) -> &'static str {
        match self {
            ConsistencyLevel::DcOne => "DC_ONE",
            ConsistencyLevel::DcQuorum => "DC_QUORUM",
            ConsistencyLevel::DcSafeQuorum => "DC_SAFE_QUORUM",
            ConsistencyLevel::DcEachSafeQuorum => "DC_EACH_SAFE_QUORUM",
        }
    }
}

impl fmt::Display for ConsistencyLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Hash algorithm selected by `hash:`.
///
/// The names mirror the algorithm tags accepted by the YAML parser.
/// Stage 3 owns the hashing math; this enum models only the configured
/// choice so the parser can echo it back without depending on the
/// hashkit module.
///
/// # Examples
///
/// ```
/// use dynomite::conf::HashType;
/// assert_eq!(HashType::parse("murmur3").unwrap(), HashType::Murmur3);
/// assert_eq!(HashType::Md5.as_str(), "md5");
/// ```
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum HashType {
    /// One-at-a-time hash.
    OneAtATime,
    /// MD5 (truncated for ketama).
    Md5,
    /// CRC-16.
    Crc16,
    /// CRC-32.
    Crc32,
    /// CRC-32 ARM.
    Crc32a,
    /// 64-bit FNV-1.
    Fnv1_64,
    /// 64-bit FNV-1a.
    Fnv1a64,
    /// 32-bit FNV-1.
    Fnv1_32,
    /// 32-bit FNV-1a.
    Fnv1a32,
    /// Paul Hsieh's hash.
    Hsieh,
    /// Murmur hash (32-bit, version 1).
    Murmur,
    /// Bob Jenkins's hash.
    Jenkins,
    /// Murmur hash 3 (128-bit).
    Murmur3,
    /// MurmurHash3 truncated to 64 bits (used by random
    /// slicing).
    #[allow(non_camel_case_types)]
    Murmur3X64_64,
}

impl HashType {
    /// Parse a `hash:` value (case-sensitive).
    ///
    /// # Examples
    ///
    /// ```
    /// use dynomite::conf::HashType;
    /// assert_eq!(HashType::parse("fnv1a_64").unwrap(), HashType::Fnv1a64);
    /// assert!(HashType::parse("FNV1A_64").is_err());
    /// ```
    pub fn parse(s: &str) -> Result<Self, ConfError> {
        Ok(match s {
            "one_at_a_time" => HashType::OneAtATime,
            "md5" => HashType::Md5,
            "crc16" => HashType::Crc16,
            "crc32" => HashType::Crc32,
            "crc32a" => HashType::Crc32a,
            "fnv1_64" => HashType::Fnv1_64,
            "fnv1a_64" => HashType::Fnv1a64,
            "fnv1_32" => HashType::Fnv1_32,
            "fnv1a_32" => HashType::Fnv1a32,
            "hsieh" => HashType::Hsieh,
            "murmur" => HashType::Murmur,
            "jenkins" => HashType::Jenkins,
            "murmur3" => HashType::Murmur3,
            "murmur3_x64_64" => HashType::Murmur3X64_64,
            other => return Err(ConfError::BadHash(other.to_string())),
        })
    }

    /// Render back to the canonical YAML name.
    ///
    /// # Examples
    ///
    /// ```
    /// use dynomite::conf::HashType;
    /// assert_eq!(HashType::Crc32a.as_str(), "crc32a");
    /// ```
    pub fn as_str(self) -> &'static str {
        match self {
            HashType::OneAtATime => "one_at_a_time",
            HashType::Md5 => "md5",
            HashType::Crc16 => "crc16",
            HashType::Crc32 => "crc32",
            HashType::Crc32a => "crc32a",
            HashType::Fnv1_64 => "fnv1_64",
            HashType::Fnv1a64 => "fnv1a_64",
            HashType::Fnv1_32 => "fnv1_32",
            HashType::Fnv1a32 => "fnv1a_32",
            HashType::Hsieh => "hsieh",
            HashType::Murmur => "murmur",
            HashType::Jenkins => "jenkins",
            HashType::Murmur3 => "murmur3",
            HashType::Murmur3X64_64 => "murmur3_x64_64",
        }
    }
}

impl fmt::Display for HashType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn data_store_round_trip() {
        assert_eq!(DataStore::from_int(0).unwrap(), DataStore::Redis);
        assert_eq!(DataStore::from_int(1).unwrap(), DataStore::Memcache);
        assert_eq!(DataStore::from_int(2).unwrap(), DataStore::Noxu);
        assert!(matches!(
            DataStore::from_int(7),
            Err(ConfError::BadDataStore(7))
        ));
        assert_eq!(DataStore::from_name("noxu").unwrap(), DataStore::Noxu);
        assert_eq!(DataStore::from_name("REDIS").unwrap(), DataStore::Redis);
        assert!(DataStore::from_name("sql").is_err());
        assert_eq!(DataStore::Noxu.as_name(), "noxu");
    }

    #[test]
    fn secure_round_trip() {
        for s in ["none", "rack", "datacenter", "all"] {
            assert_eq!(SecureServerOption::parse(s).unwrap().as_str(), s);
        }
        assert!(SecureServerOption::parse("nope").is_err());
    }

    #[test]
    fn consistency_case_insensitive() {
        assert_eq!(
            ConsistencyLevel::parse("read_consistency", "dc_one").unwrap(),
            ConsistencyLevel::DcOne
        );
        assert_eq!(
            ConsistencyLevel::parse("read_consistency", "DC_SAFE_QUORUM").unwrap(),
            ConsistencyLevel::DcSafeQuorum
        );
        assert!(ConsistencyLevel::parse("read_consistency", "garbage").is_err());
    }

    #[test]
    fn hash_round_trip() {
        for &name in &[
            "one_at_a_time",
            "md5",
            "crc16",
            "crc32",
            "crc32a",
            "fnv1_64",
            "fnv1a_64",
            "fnv1_32",
            "fnv1a_32",
            "hsieh",
            "murmur",
            "jenkins",
            "murmur3",
            "murmur3_x64_64",
        ] {
            assert_eq!(HashType::parse(name).unwrap().as_str(), name);
        }
    }

    #[test]
    fn distribution_round_trip() {
        for &name in &["vnode", "ketama", "modula", "random", "random_slicing"] {
            assert_eq!(Distribution::parse(name).unwrap().as_str(), name);
        }
        // Case-insensitive parse for back-compat with the C
        // reference, which accepts upper-case.
        assert_eq!(Distribution::parse("VNODE").unwrap(), Distribution::Vnode);
        // Hyphenated alias accepted.
        assert_eq!(
            Distribution::parse("random-slicing").unwrap(),
            Distribution::RandomSlicing
        );
        assert!(matches!(
            Distribution::parse("sphere"),
            Err(ConfError::BadDistribution(_))
        ));
        assert!(Distribution::Vnode.is_supported());
        assert!(Distribution::RandomSlicing.is_supported());
        assert!(!Distribution::Ketama.is_supported());
    }

    #[test]
    fn distribution_default_is_vnode() {
        assert_eq!(Distribution::default(), Distribution::Vnode);
    }

    #[test]
    fn distribution_yaml_round_trip() {
        // Serialise via serde, then parse back.
        let raw = serde_yaml::to_string(&Distribution::RandomSlicing).unwrap();
        let parsed: Distribution = serde_yaml::from_str(&raw).unwrap();
        assert_eq!(parsed, Distribution::RandomSlicing);
    }
}