heliosdb-proxy 0.4.1

HeliosProxy - Intelligent connection router and failover manager for HeliosDB and PostgreSQL
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
//! Node Filter
//!
//! Filters nodes based on routing hints and consistency requirements.

use super::{
    ConsistencyLevel, ParsedHints, RouteTarget, RoutingConfig, RoutingError, Result,
};
use std::time::Duration;

/// Node information for filtering
#[derive(Debug, Clone)]
pub struct NodeInfo {
    /// Node name/identifier
    pub name: String,
    /// Node role (primary/standby)
    pub role: NodeRole,
    /// Sync mode
    pub sync_mode: SyncMode,
    /// Current replication lag
    pub lag_ms: u64,
    /// Is node healthy
    pub healthy: bool,
    /// Is node enabled for routing
    pub enabled: bool,
    /// Node weight for load balancing
    pub weight: u32,
    /// Tags for custom routing (e.g., "vector", "analytics")
    pub tags: Vec<String>,
    /// Zone/region for locality routing
    pub zone: Option<String>,
}

impl NodeInfo {
    /// Create a new primary node
    pub fn primary(name: &str) -> Self {
        Self {
            name: name.to_string(),
            role: NodeRole::Primary,
            sync_mode: SyncMode::Primary,
            lag_ms: 0,
            healthy: true,
            enabled: true,
            weight: 100,
            tags: Vec::new(),
            zone: None,
        }
    }

    /// Create a new standby node
    pub fn standby(name: &str, sync_mode: SyncMode) -> Self {
        Self {
            name: name.to_string(),
            role: NodeRole::Standby,
            sync_mode,
            lag_ms: 0,
            healthy: true,
            enabled: true,
            weight: 100,
            tags: Vec::new(),
            zone: None,
        }
    }

    /// Set lag
    pub fn with_lag(mut self, lag_ms: u64) -> Self {
        self.lag_ms = lag_ms;
        self
    }

    /// Set tags
    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }

    /// Set zone
    pub fn with_zone(mut self, zone: &str) -> Self {
        self.zone = Some(zone.to_string());
        self
    }

    /// Check if node has a specific tag
    pub fn has_tag(&self, tag: &str) -> bool {
        self.tags.iter().any(|t| t == tag)
    }
}

/// Node role
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NodeRole {
    Primary,
    Standby,
    ReadReplica,
}

/// Sync mode for standby nodes
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncMode {
    /// Primary node
    Primary,
    /// Fully synchronous replication
    Sync,
    /// Semi-synchronous replication
    SemiSync,
    /// Asynchronous replication
    Async,
}

impl SyncMode {
    /// Check if this mode matches a route target
    pub fn matches_target(&self, target: RouteTarget) -> bool {
        match target {
            RouteTarget::Primary => *self == SyncMode::Primary,
            RouteTarget::Sync => *self == SyncMode::Sync,
            RouteTarget::SemiSync => *self == SyncMode::SemiSync,
            RouteTarget::Async => *self == SyncMode::Async,
            RouteTarget::Standby => matches!(self, SyncMode::Sync | SyncMode::SemiSync | SyncMode::Async),
            RouteTarget::Any => true,
            RouteTarget::Local => true, // Handled separately
            RouteTarget::Vector => true, // Handled via tags
        }
    }
}

/// Node filter for routing decisions
#[derive(Debug)]
pub struct NodeFilter {
    /// Routing configuration
    config: RoutingConfig,
    /// Local zone (for local routing)
    local_zone: Option<String>,
}

impl NodeFilter {
    /// Create a new node filter
    pub fn new(config: RoutingConfig) -> Self {
        Self {
            config,
            local_zone: None,
        }
    }

    /// Set local zone
    pub fn with_local_zone(mut self, zone: &str) -> Self {
        self.local_zone = Some(zone.to_string());
        self
    }

    /// Filter nodes based on criteria
    pub fn filter<'a>(
        &self,
        nodes: &'a [NodeInfo],
        criteria: &NodeCriteria,
    ) -> FilterResult<'a> {
        let mut eligible: Vec<&NodeInfo> = nodes.iter()
            .filter(|n| n.healthy && n.enabled)
            .collect();

        let mut reasons = Vec::new();

        // Filter by specific node name
        if let Some(ref name) = criteria.node_name {
            let count_before = eligible.len();
            eligible.retain(|n| n.name == *name);
            if eligible.len() < count_before {
                reasons.push(format!("Filtered to node: {}", name));
            }
        }

        // Filter by route target
        if let Some(target) = criteria.route {
            let count_before = eligible.len();
            eligible.retain(|n| self.matches_route_target(n, target));
            if eligible.len() < count_before {
                reasons.push(format!("Filtered by route target: {:?}", target));
            }
        }

        // Filter by consistency level
        if let Some(consistency) = criteria.consistency {
            let count_before = eligible.len();
            eligible.retain(|n| self.meets_consistency(n, consistency, criteria.max_lag));
            if eligible.len() < count_before {
                reasons.push(format!("Filtered by consistency: {:?}", consistency));
            }
        }

        // Filter by max lag
        if let Some(max_lag) = criteria.max_lag {
            let count_before = eligible.len();
            let max_lag_ms = max_lag.as_millis() as u64;
            eligible.retain(|n| n.lag_ms <= max_lag_ms);
            if eligible.len() < count_before {
                reasons.push(format!("Filtered by max lag: {}ms", max_lag_ms));
            }
        }

        // Filter by tags
        if !criteria.required_tags.is_empty() {
            let count_before = eligible.len();
            eligible.retain(|n| criteria.required_tags.iter().all(|tag| n.has_tag(tag)));
            if eligible.len() < count_before {
                reasons.push(format!("Filtered by tags: {:?}", criteria.required_tags));
            }
        }

        // Handle local routing
        if criteria.route == Some(RouteTarget::Local) {
            if let Some(ref local_zone) = self.local_zone {
                let local_nodes: Vec<_> = eligible.iter()
                    .filter(|n| n.zone.as_ref() == Some(local_zone))
                    .copied()
                    .collect();

                if !local_nodes.is_empty() {
                    eligible = local_nodes;
                    reasons.push(format!("Preferred local zone: {}", local_zone));
                }
            }
        }

        // Handle vector routing
        if criteria.route == Some(RouteTarget::Vector) {
            let vector_nodes: Vec<_> = eligible.iter()
                .filter(|n| n.has_tag("vector"))
                .copied()
                .collect();

            if !vector_nodes.is_empty() {
                eligible = vector_nodes;
                reasons.push("Filtered to vector-capable nodes".to_string());
            }
        }

        // Resolve aliases
        if let Some(ref alias) = criteria.alias {
            if let Some(alias_nodes) = self.config.resolve_alias(alias) {
                let count_before = eligible.len();
                eligible.retain(|n| alias_nodes.contains(&n.name));
                if eligible.len() < count_before {
                    reasons.push(format!("Resolved alias: {}", alias));
                }
            }
        }

        FilterResult {
            eligible,
            reasons,
            fallback_used: false,
        }
    }

    /// Check if node matches route target
    fn matches_route_target(&self, node: &NodeInfo, target: RouteTarget) -> bool {
        match target {
            RouteTarget::Primary => node.role == NodeRole::Primary,
            RouteTarget::Standby => node.role == NodeRole::Standby,
            RouteTarget::Sync => node.sync_mode == SyncMode::Sync,
            RouteTarget::SemiSync => node.sync_mode == SyncMode::SemiSync,
            RouteTarget::Async => node.sync_mode == SyncMode::Async,
            RouteTarget::Any => true,
            RouteTarget::Local => true, // Handled in filter()
            RouteTarget::Vector => node.has_tag("vector"),
        }
    }

    /// Check if node meets consistency requirements
    fn meets_consistency(&self, node: &NodeInfo, level: ConsistencyLevel, max_lag: Option<Duration>) -> bool {
        let config = match self.config.get_consistency_config(level) {
            Some(c) => c,
            None => return true, // No config = allow all
        };

        // Check if node name matches allowed patterns
        if !config.allows_node(&node.name) && !config.allows_node(&format!("{:?}", node.role).to_lowercase()) {
            return false;
        }

        // Check lag constraint
        let max_lag_ms = max_lag
            .map(|d| d.as_millis() as u64)
            .unwrap_or(config.max_lag_ms);

        if max_lag_ms < u64::MAX && node.lag_ms > max_lag_ms {
            return false;
        }

        true
    }

    /// Get default criteria for a query type
    pub fn default_criteria_for_read(&self) -> NodeCriteria {
        NodeCriteria {
            route: Some(self.config.default.read_target),
            consistency: Some(self.config.default.consistency),
            ..Default::default()
        }
    }

    /// Get default criteria for a write
    pub fn default_criteria_for_write(&self) -> NodeCriteria {
        NodeCriteria {
            route: Some(self.config.default.write_target),
            consistency: Some(ConsistencyLevel::Strong),
            ..Default::default()
        }
    }
}

/// Criteria for node filtering
#[derive(Debug, Clone, Default)]
pub struct NodeCriteria {
    /// Specific node name
    pub node_name: Option<String>,
    /// Route target
    pub route: Option<RouteTarget>,
    /// Consistency level
    pub consistency: Option<ConsistencyLevel>,
    /// Maximum acceptable lag
    pub max_lag: Option<Duration>,
    /// Required tags
    pub required_tags: Vec<String>,
    /// Alias to resolve
    pub alias: Option<String>,
    /// Branch name (for branch-aware routing)
    pub branch: Option<String>,
}

impl NodeCriteria {
    /// Create criteria from parsed hints
    pub fn from_hints(hints: &ParsedHints) -> Self {
        Self {
            node_name: hints.node.clone(),
            route: hints.route,
            consistency: hints.consistency,
            max_lag: hints.max_lag,
            required_tags: Vec::new(),
            alias: None,
            branch: hints.branch.clone(),
        }
    }

    /// Add a required tag
    pub fn with_tag(mut self, tag: &str) -> Self {
        self.required_tags.push(tag.to_string());
        self
    }

    /// Set alias
    pub fn with_alias(mut self, alias: &str) -> Self {
        self.alias = Some(alias.to_string());
        self
    }
}

/// Result of node filtering
#[derive(Debug)]
pub struct FilterResult<'a> {
    /// Eligible nodes after filtering
    pub eligible: Vec<&'a NodeInfo>,
    /// Reasons for filtering decisions
    pub reasons: Vec<String>,
    /// Whether fallback was used
    pub fallback_used: bool,
}

impl<'a> FilterResult<'a> {
    /// Check if any nodes match
    pub fn has_matches(&self) -> bool {
        !self.eligible.is_empty()
    }

    /// Get number of matches
    pub fn count(&self) -> usize {
        self.eligible.len()
    }

    /// Get first match
    pub fn first(&self) -> Option<&'a NodeInfo> {
        self.eligible.first().copied()
    }

    /// Convert to error if no matches
    pub fn require_match(&self, context: &str) -> Result<&'a NodeInfo> {
        self.first().ok_or_else(|| {
            RoutingError::NoMatchingNodes(format!(
                "{}: reasons: {}",
                context,
                self.reasons.join(", ")
            ))
        })
    }
}

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

    fn test_nodes() -> Vec<NodeInfo> {
        vec![
            NodeInfo::primary("primary"),
            NodeInfo::standby("standby-sync-1", SyncMode::Sync),
            NodeInfo::standby("standby-async-1", SyncMode::Async).with_lag(500),
            NodeInfo::standby("standby-async-2", SyncMode::Async).with_lag(5000),
            NodeInfo::standby("standby-vector-1", SyncMode::Async)
                .with_tags(vec!["vector".to_string()]),
        ]
    }

    #[test]
    fn test_filter_by_route_target() {
        let filter = NodeFilter::new(RoutingConfig::default());
        let nodes = test_nodes();

        // Filter for primary
        let criteria = NodeCriteria {
            route: Some(RouteTarget::Primary),
            ..Default::default()
        };
        let result = filter.filter(&nodes, &criteria);
        assert_eq!(result.count(), 1);
        assert_eq!(result.first().unwrap().name, "primary");

        // Filter for any standby
        let criteria = NodeCriteria {
            route: Some(RouteTarget::Standby),
            ..Default::default()
        };
        let result = filter.filter(&nodes, &criteria);
        assert_eq!(result.count(), 4);
    }

    #[test]
    fn test_filter_by_sync_mode() {
        let filter = NodeFilter::new(RoutingConfig::default());
        let nodes = test_nodes();

        let criteria = NodeCriteria {
            route: Some(RouteTarget::Sync),
            ..Default::default()
        };
        let result = filter.filter(&nodes, &criteria);
        assert_eq!(result.count(), 1);
        assert_eq!(result.first().unwrap().name, "standby-sync-1");
    }

    #[test]
    fn test_filter_by_max_lag() {
        let filter = NodeFilter::new(RoutingConfig::default());
        let nodes = test_nodes();

        let criteria = NodeCriteria {
            max_lag: Some(Duration::from_millis(1000)),
            ..Default::default()
        };
        let result = filter.filter(&nodes, &criteria);

        // Should exclude standby-async-2 (5000ms lag)
        assert!(result.eligible.iter().all(|n| n.lag_ms <= 1000));
    }

    #[test]
    fn test_filter_by_node_name() {
        let filter = NodeFilter::new(RoutingConfig::default());
        let nodes = test_nodes();

        let criteria = NodeCriteria {
            node_name: Some("standby-sync-1".to_string()),
            ..Default::default()
        };
        let result = filter.filter(&nodes, &criteria);
        assert_eq!(result.count(), 1);
        assert_eq!(result.first().unwrap().name, "standby-sync-1");
    }

    #[test]
    fn test_filter_by_tag() {
        let filter = NodeFilter::new(RoutingConfig::default());
        let nodes = test_nodes();

        let criteria = NodeCriteria {
            route: Some(RouteTarget::Vector),
            ..Default::default()
        };
        let result = filter.filter(&nodes, &criteria);
        assert_eq!(result.count(), 1);
        assert_eq!(result.first().unwrap().name, "standby-vector-1");
    }

    #[test]
    fn test_filter_with_alias() {
        let mut config = RoutingConfig::default();
        config.add_alias("analytics", vec![
            "standby-async-1".to_string(),
            "standby-async-2".to_string(),
        ]);

        let filter = NodeFilter::new(config);
        let nodes = test_nodes();

        let criteria = NodeCriteria {
            alias: Some("analytics".to_string()),
            ..Default::default()
        };
        let result = filter.filter(&nodes, &criteria);
        assert_eq!(result.count(), 2);
    }

    #[test]
    fn test_local_zone_preference() {
        let filter = NodeFilter::new(RoutingConfig::default())
            .with_local_zone("us-west-1");

        let nodes = vec![
            NodeInfo::standby("standby-1", SyncMode::Async).with_zone("us-east-1"),
            NodeInfo::standby("standby-2", SyncMode::Async).with_zone("us-west-1"),
        ];

        let criteria = NodeCriteria {
            route: Some(RouteTarget::Local),
            ..Default::default()
        };
        let result = filter.filter(&nodes, &criteria);
        assert_eq!(result.count(), 1);
        assert_eq!(result.first().unwrap().name, "standby-2");
    }

    #[test]
    fn test_no_match_error() {
        let filter = NodeFilter::new(RoutingConfig::default());
        let nodes = test_nodes();

        let criteria = NodeCriteria {
            node_name: Some("nonexistent".to_string()),
            ..Default::default()
        };
        let result = filter.filter(&nodes, &criteria);
        assert!(!result.has_matches());

        let err = result.require_match("test context");
        assert!(err.is_err());
    }

    #[test]
    fn test_from_hints() {
        let parser = super::super::HintParser::new();
        let hints = parser.parse("/*helios:route=sync,lag=100ms*/ SELECT 1");

        let criteria = NodeCriteria::from_hints(&hints);
        assert_eq!(criteria.route, Some(RouteTarget::Sync));
        assert_eq!(criteria.max_lag, Some(Duration::from_millis(100)));
    }
}