Skip to main content

oxirs_cluster/region_manager/
types.rs

1//! Auto-generated module
2//!
3//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)
4
5use crate::raft::OxirsNodeId;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::time::{Duration, SystemTime};
9
10/// Geographic coordinates for latency estimation
11#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
12pub struct GeoCoordinates {
13    pub latitude: f64,
14    pub longitude: f64,
15}
16/// Cross-region replication strategy
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
18pub enum CrossRegionStrategy {
19    /// Asynchronous replication to all regions
20    AsyncAll,
21    /// Replication to specific backup regions
22    SelectiveSync { target_regions: Vec<String> },
23    /// Eventual consistency with conflict resolution
24    EventualConsistency { reconciliation_interval_ms: u64 },
25    /// Chain replication across regions
26    ChainReplication { replication_chain: Vec<String> },
27}
28/// Metadata for eventual consistency replication
29#[derive(Debug, Clone)]
30pub struct EventualConsistencyMetadata {
31    pub timestamp: SystemTime,
32    pub vector_clock: VectorClock,
33    pub source_region: String,
34    pub reconciliation_interval: Duration,
35}
36/// Region-specific configuration
37#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
38pub struct RegionConfig {
39    /// Preferred replication factor within region
40    pub local_replication_factor: usize,
41    /// Cross-region replication factor
42    pub cross_region_replication_factor: usize,
43    /// Maximum acceptable latency for regional operations (ms)
44    pub max_regional_latency_ms: u64,
45    /// Enable region-local leader preference
46    pub prefer_local_leader: bool,
47    /// Enable cross-region backup consensus
48    pub enable_cross_region_backup: bool,
49    /// Enable relay routing for high-latency paths
50    pub enable_relay: bool,
51    /// Relay latency threshold (ms) - use relay if improvement > threshold
52    pub relay_latency_threshold_ms: f64,
53    /// Enable compression for cross-region data
54    pub enable_compression: bool,
55    /// Enable read-local routing (route reads to nearest replica)
56    pub enable_read_local: bool,
57    /// Routing strategy to use
58    pub routing_strategy: RoutingStrategy,
59    /// Custom region properties
60    pub properties: HashMap<String, String>,
61}
62/// Performance metrics for multi-region operations
63#[derive(Debug)]
64pub struct RegionPerformanceMetrics {
65    /// Latency measurements between regions
66    pub inter_region_latencies: HashMap<(String, String), LatencyStats>,
67    /// Throughput metrics per region
68    pub region_throughput: HashMap<String, ThroughputStats>,
69    /// Error rates per region
70    pub region_error_rates: HashMap<String, ErrorRateStats>,
71    /// Last update timestamp
72    pub last_updated: SystemTime,
73    /// Whether monitoring is currently active
74    pub monitoring_enabled: bool,
75}
76/// Routing strategy for cross-region communication
77#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
78pub enum RoutingStrategy {
79    /// Always use direct connection
80    Direct,
81    /// Use Dijkstra for minimum latency path
82    LatencyAware,
83    /// Consider both latency and bandwidth
84    BandwidthAware,
85    /// Minimize cross-region data transfer costs
86    CostAware,
87}
88/// Route between regions
89#[derive(Debug, Clone)]
90pub struct Route {
91    /// Hops in the route (e.g., [us-west, us-east, eu-central])
92    pub hops: Vec<String>,
93    /// Total latency of the route in milliseconds
94    pub total_latency: f64,
95    /// Whether to use compression for this route
96    pub use_compression: bool,
97}
98impl Route {
99    /// Create a direct route between two regions
100    pub fn direct(source: String, dest: String) -> Self {
101        Self {
102            hops: vec![source, dest],
103            total_latency: 0.0,
104            use_compression: true,
105        }
106    }
107}
108/// Vector clock for distributed consistency
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct VectorClock {
111    pub clocks: HashMap<String, u64>,
112}
113impl VectorClock {
114    /// Create a new empty vector clock
115    pub fn new() -> Self {
116        Self {
117            clocks: HashMap::new(),
118        }
119    }
120    /// Compare two vector clocks for ordering
121    pub fn compare(&self, other: &VectorClock) -> VectorClockOrdering {
122        let mut self_greater = false;
123        let mut other_greater = false;
124        let all_keys: std::collections::HashSet<_> =
125            self.clocks.keys().chain(other.clocks.keys()).collect();
126        for key in all_keys {
127            let self_value = self.clocks.get(key).unwrap_or(&0);
128            let other_value = other.clocks.get(key).unwrap_or(&0);
129            if self_value > other_value {
130                self_greater = true;
131            } else if other_value > self_value {
132                other_greater = true;
133            }
134        }
135        match (self_greater, other_greater) {
136            (true, false) => VectorClockOrdering::Greater,
137            (false, true) => VectorClockOrdering::Less,
138            (false, false) => VectorClockOrdering::Equal,
139            (true, true) => VectorClockOrdering::Concurrent,
140        }
141    }
142}
143/// Throughput statistics
144#[derive(Debug, Clone)]
145pub struct ThroughputStats {
146    pub operations_per_second: f64,
147    pub bytes_per_second: f64,
148    pub peak_ops_per_second: f64,
149    pub last_measurement: SystemTime,
150}
151/// Region status enumeration
152#[derive(Debug, Clone, PartialEq)]
153pub enum RegionStatus {
154    Healthy,
155    Degraded,
156    Unavailable,
157}
158/// Status of connectivity between regions
159#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
160pub enum ConnectivityStatus {
161    /// Full connectivity with low latency
162    Optimal,
163    /// Connectivity with elevated latency
164    Degraded { latency_ms: u64 },
165    /// Partial connectivity or intermittent issues
166    Unstable { error_rate: f64 },
167    /// No connectivity
168    Disconnected,
169}
170/// Conflict resolution strategy for multi-region
171#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
172pub enum ConflictResolutionStrategy {
173    /// Last writer wins with timestamp
174    LastWriterWins,
175    /// Vector clock based resolution
176    VectorClock,
177    /// Application-defined custom resolution
178    Custom { resolution_function: String },
179    /// Manual resolution required
180    Manual,
181}
182/// Latency statistics
183#[derive(Debug, Default)]
184pub struct LatencyStats {
185    pub min_ms: f64,
186    pub max_ms: f64,
187    pub avg_ms: f64,
188    pub p95_ms: f64,
189    pub p99_ms: f64,
190    pub sample_count: u64,
191}
192/// Multi-region deployment topology
193#[derive(Debug, Clone)]
194pub struct RegionTopology {
195    /// All regions in the deployment
196    pub regions: HashMap<String, Region>,
197    /// Node placement mapping
198    pub node_placements: HashMap<OxirsNodeId, NodePlacement>,
199    /// Inter-region latency matrix (in milliseconds, f64 for precision)
200    pub latency_matrix: HashMap<(String, String), f64>,
201    /// Region-to-region connectivity status
202    pub connectivity_status: HashMap<(String, String), ConnectivityStatus>,
203}
204/// Availability zone within a region
205#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
206pub struct AvailabilityZone {
207    /// AZ identifier (e.g., "us-east-1a")
208    pub id: String,
209    /// Human-readable AZ name
210    pub name: String,
211    /// Region this AZ belongs to
212    pub region_id: String,
213}
214/// Package containing data and metadata for replication
215#[derive(Debug, Clone)]
216pub struct ReplicationPackage {
217    pub data: Vec<u8>,
218    pub metadata: EventualConsistencyMetadata,
219}
220/// Error rate statistics
221#[derive(Debug, Clone)]
222pub struct ErrorRateStats {
223    pub total_operations: u64,
224    pub failed_operations: u64,
225    pub error_rate: f64,
226    pub last_error: Option<SystemTime>,
227}
228/// Region health information
229#[derive(Debug, Clone)]
230pub struct RegionHealth {
231    pub region_id: String,
232    pub total_nodes: usize,
233    pub healthy_nodes: usize,
234    pub throughput: ThroughputStats,
235    pub error_rate: ErrorRateStats,
236    pub status: RegionStatus,
237}
238/// Replication strategy for multi-region deployment
239#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
240pub struct MultiRegionReplicationStrategy {
241    /// Strategy for intra-region replication
242    pub intra_region: IntraRegionStrategy,
243    /// Strategy for cross-region replication
244    pub cross_region: CrossRegionStrategy,
245    /// Conflict resolution approach
246    pub conflict_resolution: ConflictResolutionStrategy,
247}
248/// Multi-region consensus strategy
249#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
250pub enum ConsensusStrategy {
251    /// Standard Raft across all regions
252    GlobalRaft,
253    /// Regional Raft with cross-region coordination
254    RegionalRaft {
255        /// Primary consensus region
256        primary_region: String,
257        /// Backup regions for failover
258        backup_regions: Vec<String>,
259    },
260    /// Byzantine fault tolerant consensus for high security
261    ByzantineConsensus {
262        /// Required byzantine quorum size
263        byzantine_quorum: usize,
264    },
265    /// Hybrid approach with regional leaders
266    HybridConsensus {
267        /// Regional leader preferences
268        region_preferences: HashMap<String, f64>,
269    },
270}
271/// Vector clock comparison result
272#[derive(Debug, Clone, PartialEq)]
273pub enum VectorClockOrdering {
274    Less,
275    Greater,
276    Equal,
277    Concurrent,
278}
279/// Geographic region configuration
280#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
281pub struct Region {
282    /// Region identifier (e.g., "us-east-1", "eu-west-1")
283    pub id: String,
284    /// Human-readable region name
285    pub name: String,
286    /// Geographic coordinates for latency calculations
287    pub coordinates: Option<GeoCoordinates>,
288    /// Availability zones within this region
289    pub availability_zones: Vec<AvailabilityZone>,
290    /// Region-specific configuration
291    pub config: RegionConfig,
292}
293/// Node placement information
294#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
295pub struct NodePlacement {
296    /// Node identifier
297    pub node_id: OxirsNodeId,
298    /// Region where the node is located
299    pub region_id: String,
300    /// Availability zone where the node is located
301    pub availability_zone_id: String,
302    /// Data center or specific location within AZ
303    pub data_center: Option<String>,
304    /// Rack identifier for fine-grained placement
305    pub rack: Option<String>,
306}
307/// Intra-region replication strategy
308#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
309pub enum IntraRegionStrategy {
310    /// Synchronous replication within region
311    Synchronous { min_replicas: usize },
312    /// Asynchronous replication with batching
313    Asynchronous {
314        batch_size: usize,
315        batch_timeout_ms: u64,
316    },
317    /// Quorum-based replication
318    Quorum { quorum_size: usize },
319}