minikv 2.0.1

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

use crate::common::Result;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::{Arc, RwLock};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeoConfig {
    #[serde(default)]
    pub enabled: bool,

    /// This node's region
    pub local_region: String,

    /// This node's zone (availability zone)
    #[serde(default)]
    pub local_zone: String,

    #[serde(default)]
    pub regions: Vec<RegionConfig>,

    #[serde(default)]
    pub default_region: Option<String>,

    #[serde(default)]
    pub routing: RoutingStrategy,

    #[serde(default)]
    pub geo_fencing: bool,

    #[serde(default)]
    pub replication_mode: ReplicationMode,
}

impl Default for GeoConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            local_region: "default".to_string(),
            local_zone: "".to_string(),
            regions: vec![],
            default_region: None,
            routing: RoutingStrategy::default(),
            geo_fencing: false,
            replication_mode: ReplicationMode::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegionConfig {
    /// Region identifier (e.g., "us-east-1", "eu-west-1")
    pub id: String,

    pub name: String,

    #[serde(default)]
    pub location: Option<GeoLocation>,

    pub endpoints: Vec<String>,

    /// Is this the primary region?
    #[serde(default)]
    pub primary: bool,

    /// Priority for failover (lower = higher priority)
    #[serde(default)]
    pub priority: u32,

    #[serde(default)]
    pub settings: RegionSettings,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct GeoLocation {
    pub latitude: f64,
    pub longitude: f64,
}

impl GeoLocation {
    pub fn new(latitude: f64, longitude: f64) -> Self {
        Self {
            latitude,
            longitude,
        }
    }

    pub fn distance_km(&self, other: &GeoLocation) -> f64 {
        const EARTH_RADIUS_KM: f64 = 6371.0;

        let lat1 = self.latitude.to_radians();
        let lat2 = other.latitude.to_radians();
        let delta_lat = (other.latitude - self.latitude).to_radians();
        let delta_lon = (other.longitude - self.longitude).to_radians();

        let a = (delta_lat / 2.0).sin().powi(2)
            + lat1.cos() * lat2.cos() * (delta_lon / 2.0).sin().powi(2);
        let c = 2.0 * a.sqrt().asin();

        EARTH_RADIUS_KM * c
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RegionSettings {
    #[serde(default)]
    pub read_replicas: u32,

    #[serde(default = "default_true")]
    pub write_enabled: bool,

    #[serde(default)]
    pub compliance: Vec<String>,
}

fn default_true() -> bool {
    true
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum RoutingStrategy {
    #[default]
    LatencyBased,

    KeyBased,

    /// Route based on client's geographic location
    GeoBased,

    RoundRobin,

    PrimaryOnly,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ReplicationMode {
    Sync,

    #[default]
    Async,

    SemiSync,
}

pub struct GeoRouter {
    config: GeoConfig,
    region_health: Arc<RwLock<HashMap<String, RegionHealth>>>,
    latencies: Arc<RwLock<HashMap<String, LatencyStats>>>,
    ip_location_cache: Arc<RwLock<HashMap<IpAddr, GeoLocation>>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegionHealth {
    pub region_id: String,
    pub healthy: bool,
    pub available_endpoints: usize,
    pub last_check: DateTime<Utc>,
    pub latency_ms: Option<f64>,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Default)]
pub struct LatencyStats {
    pub samples: Vec<f64>,
    pub avg_ms: f64,
    pub p50_ms: f64,
    pub p95_ms: f64,
    pub p99_ms: f64,
}

impl LatencyStats {
    pub fn add_sample(&mut self, latency_ms: f64) {
        self.samples.push(latency_ms);
        if self.samples.len() > 1000 {
            self.samples.remove(0);
        }
        self.recalculate();
    }

    fn recalculate(&mut self) {
        if self.samples.is_empty() {
            return;
        }

        let mut sorted = self.samples.clone();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());

        self.avg_ms = sorted.iter().sum::<f64>() / sorted.len() as f64;
        self.p50_ms = sorted[sorted.len() / 2];
        self.p95_ms = sorted[(sorted.len() as f64 * 0.95) as usize];
        self.p99_ms = sorted[(sorted.len() as f64 * 0.99) as usize];
    }
}

impl GeoRouter {
    pub fn new(config: GeoConfig) -> Self {
        Self {
            config,
            region_health: Arc::new(RwLock::new(HashMap::new())),
            latencies: Arc::new(RwLock::new(HashMap::new())),
            ip_location_cache: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    pub fn route(&self, request: &GeoRequest) -> Result<RoutingDecision> {
        if !self.config.enabled {
            return Ok(RoutingDecision {
                region: self.config.local_region.clone(),
                endpoints: vec![],
                reason: "Geo-partitioning disabled".to_string(),
            });
        }

        match self.config.routing {
            RoutingStrategy::LatencyBased => self.route_by_latency(request),
            RoutingStrategy::KeyBased => self.route_by_key(request),
            RoutingStrategy::GeoBased => self.route_by_geo(request),
            RoutingStrategy::RoundRobin => self.route_round_robin(request),
            RoutingStrategy::PrimaryOnly => self.route_to_primary(request),
        }
    }

    fn route_by_latency(&self, _request: &GeoRequest) -> Result<RoutingDecision> {
        let latencies = self.latencies.read().unwrap();
        let health = self.region_health.read().unwrap();

        let mut best_region = None;
        let mut best_latency = f64::MAX;

        for region in &self.config.regions {
            if let Some(h) = health.get(&region.id) {
                if !h.healthy {
                    continue;
                }
            }

            if let Some(stats) = latencies.get(&region.id) {
                if stats.avg_ms < best_latency {
                    best_latency = stats.avg_ms;
                    best_region = Some(region.clone());
                }
            }
        }

        match best_region {
            Some(region) => Ok(RoutingDecision {
                region: region.id.clone(),
                endpoints: region.endpoints.clone(),
                reason: format!("Lowest latency: {:.2}ms", best_latency),
            }),
            None => Ok(RoutingDecision {
                region: self.config.local_region.clone(),
                endpoints: vec![],
                reason: "Fallback to local region".to_string(),
            }),
        }
    }

    fn route_by_key(&self, request: &GeoRequest) -> Result<RoutingDecision> {
        if let Some(key) = &request.key {
            if let Some(region_prefix) = key.split(':').next() {
                if let Some(region) = self.config.regions.iter().find(|r| r.id == region_prefix) {
                    return Ok(RoutingDecision {
                        region: region.id.clone(),
                        endpoints: region.endpoints.clone(),
                        reason: format!("Key prefix match: {}", region_prefix),
                    });
                }
            }
        }

        let region = self
            .config
            .default_region
            .clone()
            .unwrap_or_else(|| self.config.local_region.clone());

        Ok(RoutingDecision {
            region,
            endpoints: vec![],
            reason: "Default region".to_string(),
        })
    }

    /// Route based on client's geographic location
    fn route_by_geo(&self, request: &GeoRequest) -> Result<RoutingDecision> {
        let client_location = match &request.client_location {
            Some(loc) => *loc,
            None => {
                if let Some(ip) = &request.client_ip {
                    let cache = self.ip_location_cache.read().unwrap();
                    cache.get(ip).copied().unwrap_or(GeoLocation::new(0.0, 0.0))
                } else {
                    GeoLocation::new(0.0, 0.0)
                }
            }
        };

        let mut nearest = None;
        let mut min_distance = f64::MAX;

        for region in &self.config.regions {
            if let Some(loc) = &region.location {
                let distance = client_location.distance_km(loc);
                if distance < min_distance {
                    min_distance = distance;
                    nearest = Some(region.clone());
                }
            }
        }

        match nearest {
            Some(region) => Ok(RoutingDecision {
                region: region.id.clone(),
                endpoints: region.endpoints.clone(),
                reason: format!("Nearest region: {:.0}km", min_distance),
            }),
            None => Ok(RoutingDecision {
                region: self.config.local_region.clone(),
                endpoints: vec![],
                reason: "No geo data, using local".to_string(),
            }),
        }
    }

    fn route_round_robin(&self, _request: &GeoRequest) -> Result<RoutingDecision> {
        use std::sync::atomic::{AtomicUsize, Ordering};
        static COUNTER: AtomicUsize = AtomicUsize::new(0);

        let healthy_regions: Vec<_> = self
            .config
            .regions
            .iter()
            .filter(|r| {
                let health = self.region_health.read().unwrap();
                health.get(&r.id).map(|h| h.healthy).unwrap_or(true)
            })
            .collect();

        if healthy_regions.is_empty() {
            return Ok(RoutingDecision {
                region: self.config.local_region.clone(),
                endpoints: vec![],
                reason: "No healthy regions".to_string(),
            });
        }

        let idx = COUNTER.fetch_add(1, Ordering::Relaxed) % healthy_regions.len();
        let region = healthy_regions[idx];

        Ok(RoutingDecision {
            region: region.id.clone(),
            endpoints: region.endpoints.clone(),
            reason: format!("Round-robin index: {}", idx),
        })
    }

    fn route_to_primary(&self, _request: &GeoRequest) -> Result<RoutingDecision> {
        let primary = self
            .config
            .regions
            .iter()
            .find(|r| r.primary)
            .or_else(|| self.config.regions.first());

        match primary {
            Some(region) => Ok(RoutingDecision {
                region: region.id.clone(),
                endpoints: region.endpoints.clone(),
                reason: "Primary region".to_string(),
            }),
            None => Ok(RoutingDecision {
                region: self.config.local_region.clone(),
                endpoints: vec![],
                reason: "No primary defined".to_string(),
            }),
        }
    }

    pub fn check_geo_fence(&self, key: &str, region: &str) -> Result<bool> {
        if !self.config.geo_fencing {
            return Ok(true);
        }

        if key.starts_with("__geo:") {
            let parts: Vec<&str> = key.splitn(3, ':').collect();
            if parts.len() >= 2 {
                let allowed_region = parts[1];
                return Ok(allowed_region == region || allowed_region == "*");
            }
        }

        Ok(true)
    }

    pub fn update_health(
        &self,
        region_id: &str,
        healthy: bool,
        latency_ms: Option<f64>,
        error: Option<String>,
    ) {
        let mut health = self.region_health.write().unwrap();
        let region = self.config.regions.iter().find(|r| r.id == region_id);

        health.insert(
            region_id.to_string(),
            RegionHealth {
                region_id: region_id.to_string(),
                healthy,
                available_endpoints: region.map(|r| r.endpoints.len()).unwrap_or(0),
                last_check: Utc::now(),
                latency_ms,
                error,
            },
        );

        if let Some(latency) = latency_ms {
            let mut latencies = self.latencies.write().unwrap();
            let stats = latencies.entry(region_id.to_string()).or_default();
            stats.add_sample(latency);
        }
    }

    pub fn get_health_status(&self) -> Vec<RegionHealth> {
        let health = self.region_health.read().unwrap();
        health.values().cloned().collect()
    }

    pub fn local_region(&self) -> &str {
        &self.config.local_region
    }

    pub fn use_local_replica(&self, request: &GeoRequest) -> bool {
        if request.operation != GeoOperation::Read {
            return false;
        }

        if request.consistency == Some(Consistency::Strong) {
            return false;
        }

        let local = self
            .config
            .regions
            .iter()
            .find(|r| r.id == self.config.local_region);

        local.map(|r| r.settings.read_replicas > 0).unwrap_or(false)
    }
}

#[derive(Debug, Clone)]
pub struct GeoRequest {
    pub operation: GeoOperation,
    pub key: Option<String>,
    pub client_ip: Option<IpAddr>,
    pub client_location: Option<GeoLocation>,
    pub consistency: Option<Consistency>,
    pub preferred_region: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GeoOperation {
    Read,
    Write,
    Delete,
    Scan,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Consistency {
    Eventual,
    Local,
    Strong,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoutingDecision {
    pub region: String,
    pub endpoints: Vec<String>,
    pub reason: String,
}

use once_cell::sync::Lazy;

pub static GEO_ROUTER: Lazy<RwLock<Option<GeoRouter>>> = Lazy::new(|| RwLock::new(None));

pub fn init_geo(config: GeoConfig) {
    let router = GeoRouter::new(config);
    let mut guard = GEO_ROUTER.write().unwrap();
    *guard = Some(router);
}

pub fn get_geo_router() -> Option<std::sync::RwLockReadGuard<'static, Option<GeoRouter>>> {
    let guard = GEO_ROUTER.read().ok()?;
    if guard.is_some() {
        Some(guard)
    } else {
        None
    }
}

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

    fn test_config() -> GeoConfig {
        GeoConfig {
            enabled: true,
            local_region: "us-east".to_string(),
            local_zone: "us-east-1a".to_string(),
            regions: vec![
                RegionConfig {
                    id: "us-east".to_string(),
                    name: "US East".to_string(),
                    location: Some(GeoLocation::new(39.0, -77.0)),
                    endpoints: vec!["us-east-1.example.com:5000".to_string()],
                    primary: true,
                    priority: 1,
                    settings: RegionSettings::default(),
                },
                RegionConfig {
                    id: "eu-west".to_string(),
                    name: "EU West".to_string(),
                    location: Some(GeoLocation::new(53.0, -8.0)),
                    endpoints: vec!["eu-west-1.example.com:5000".to_string()],
                    primary: false,
                    priority: 2,
                    settings: RegionSettings::default(),
                },
            ],
            default_region: Some("us-east".to_string()),
            routing: RoutingStrategy::GeoBased,
            geo_fencing: false,
            replication_mode: ReplicationMode::Async,
        }
    }

    #[test]
    fn test_geo_location_distance() {
        let nyc = GeoLocation::new(40.7128, -74.0060);
        let london = GeoLocation::new(51.5074, -0.1278);

        let distance = nyc.distance_km(&london);
        assert!(distance > 5500.0 && distance < 5700.0);
    }

    #[test]
    fn test_geo_routing() {
        let config = test_config();
        let router = GeoRouter::new(config);

        let request = GeoRequest {
            operation: GeoOperation::Read,
            key: Some("test-key".to_string()),
            client_ip: None,
            client_location: Some(GeoLocation::new(48.8566, 2.3522)), // Paris
            consistency: None,
            preferred_region: None,
        };

        let decision = router.route(&request).unwrap();
        assert_eq!(decision.region, "eu-west");
    }

    #[test]
    fn test_key_based_routing() {
        let mut config = test_config();
        config.routing = RoutingStrategy::KeyBased;
        let router = GeoRouter::new(config);

        let request = GeoRequest {
            operation: GeoOperation::Read,
            key: Some("eu-west:user:123".to_string()),
            client_ip: None,
            client_location: None,
            consistency: None,
            preferred_region: None,
        };

        let decision = router.route(&request).unwrap();
        assert_eq!(decision.region, "eu-west");
    }

    #[test]
    fn test_primary_only_routing() {
        let mut config = test_config();
        config.routing = RoutingStrategy::PrimaryOnly;
        let router = GeoRouter::new(config);

        let request = GeoRequest {
            operation: GeoOperation::Write,
            key: Some("test-key".to_string()),
            client_ip: None,
            client_location: Some(GeoLocation::new(48.8566, 2.3522)),
            consistency: Some(Consistency::Strong),
            preferred_region: None,
        };

        let decision = router.route(&request).unwrap();
        assert_eq!(decision.region, "us-east"); // Primary region
    }

    #[test]
    fn test_health_update() {
        let config = test_config();
        let router = GeoRouter::new(config);

        router.update_health("us-east", true, Some(10.5), None);
        router.update_health("eu-west", true, Some(50.2), None);

        let health = router.get_health_status();
        assert_eq!(health.len(), 2);
    }
}