Skip to main content

oxirs_cluster/
adaptive_consistent_hash.rs

1//! # Adaptive Consistent Hashing
2//!
3//! Provides `AdaptiveConsistentHash` — a consistent hash ring with:
4//! - Virtual nodes for balanced load distribution.
5//! - Weighted nodes based on capacity (higher weight → more virtual nodes).
6//! - Automatic rebalancing when nodes join or leave.
7//!
8//! The ring uses SHA-256 to compute stable hash positions for both physical
9//! node keys and virtual-node replicas.
10
11use crate::error::{ClusterError, Result};
12use serde::{Deserialize, Serialize};
13use std::collections::{BTreeMap, HashMap};
14
15// ---------------------------------------------------------------------------
16// Hashing helper
17// ---------------------------------------------------------------------------
18
19/// Compute a 64-bit hash from an arbitrary byte string using FNV-1a.
20///
21/// Using a fast, dependency-free hash (FNV-1a) rather than SHA-256 keeps this
22/// module pure-Rust without requiring the `sha2` crate in the call-path.
23fn fnv1a_64(data: &[u8]) -> u64 {
24    const BASIS: u64 = 14695981039346656037;
25    const PRIME: u64 = 1099511628211;
26    let mut hash = BASIS;
27    for &byte in data {
28        hash ^= byte as u64;
29        hash = hash.wrapping_mul(PRIME);
30    }
31    hash
32}
33
34fn ring_hash(key: &str) -> u64 {
35    fnv1a_64(key.as_bytes())
36}
37
38// ---------------------------------------------------------------------------
39// Node descriptor
40// ---------------------------------------------------------------------------
41
42/// A node in the consistent hash ring.
43#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
44pub struct HashNode {
45    /// Unique node identifier (e.g. `"node-1"` or a socket address string).
46    pub id: String,
47    /// Relative capacity weight. A weight of 2 means twice as many virtual
48    /// nodes as a node with weight 1.
49    pub weight: u32,
50    /// Optional human-readable label.
51    pub label: Option<String>,
52}
53
54impl HashNode {
55    /// Create a node with an explicit weight.
56    pub fn with_weight(id: impl Into<String>, weight: u32) -> Self {
57        assert!(weight > 0, "weight must be at least 1");
58        Self {
59            id: id.into(),
60            weight,
61            label: None,
62        }
63    }
64
65    /// Create a node with default weight (1).
66    pub fn new(id: impl Into<String>) -> Self {
67        Self::with_weight(id, 1)
68    }
69
70    /// Attach a human-readable label.
71    pub fn with_label(mut self, label: impl Into<String>) -> Self {
72        self.label = Some(label.into());
73        self
74    }
75}
76
77// ---------------------------------------------------------------------------
78// Ring entry
79// ---------------------------------------------------------------------------
80
81/// A single point on the consistent hash ring.
82#[derive(Debug, Clone)]
83struct RingEntry {
84    /// Hash position on the ring.
85    position: u64,
86    /// Physical node ID this virtual node belongs to.
87    node_id: String,
88    /// Virtual node index (for uniqueness).
89    #[allow(dead_code)]
90    vnode_index: u32,
91}
92
93// ---------------------------------------------------------------------------
94// Rebalance event
95// ---------------------------------------------------------------------------
96
97/// Describes key ranges that need to be migrated when the ring changes.
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct RebalanceEvent {
100    /// Node that should receive the keys.
101    pub destination_node: String,
102    /// Node that previously owned the keys (now gone or with reduced load).
103    pub source_node: String,
104    /// The hash range [start, end) being migrated.
105    pub range_start: u64,
106    pub range_end: u64,
107}
108
109// ---------------------------------------------------------------------------
110// Ring statistics
111// ---------------------------------------------------------------------------
112
113/// Per-node load statistics derived from the ring.
114#[derive(Debug, Clone, Serialize, Deserialize, Default)]
115pub struct NodeLoadStats {
116    /// Physical node ID.
117    pub node_id: String,
118    /// Number of virtual nodes for this physical node.
119    pub virtual_node_count: u32,
120    /// Fraction of the 64-bit key space owned by this node (0.0 – 1.0).
121    pub key_space_fraction: f64,
122}
123
124// ---------------------------------------------------------------------------
125// AdaptiveConsistentHash
126// ---------------------------------------------------------------------------
127
128/// An adaptive consistent hash ring supporting weighted nodes and
129/// automatic rebalancing.
130///
131/// # Example
132///
133/// ```rust
134/// use oxirs_cluster::adaptive_consistent_hash::{AdaptiveConsistentHash, HashNode};
135///
136/// let mut ring = AdaptiveConsistentHash::new(150);
137/// ring.add_node(HashNode::with_weight("node-a", 2)).unwrap();
138/// ring.add_node(HashNode::new("node-b")).unwrap();
139///
140/// let owner = ring.get("my-rdf-subject").unwrap();
141/// assert!(owner == "node-a" || owner == "node-b");
142/// ```
143pub struct AdaptiveConsistentHash {
144    /// Base number of virtual nodes per unit weight.
145    base_vnodes: u32,
146    /// Sorted ring entries.
147    ring: BTreeMap<u64, RingEntry>,
148    /// Map from node ID to node descriptor.
149    nodes: HashMap<String, HashNode>,
150}
151
152impl AdaptiveConsistentHash {
153    /// Create a new empty ring.
154    ///
155    /// `base_vnodes` controls the number of virtual nodes per unit of weight.
156    /// A value of 100–300 gives good load distribution for small–medium clusters.
157    pub fn new(base_vnodes: u32) -> Self {
158        assert!(base_vnodes > 0, "base_vnodes must be at least 1");
159        Self {
160            base_vnodes,
161            ring: BTreeMap::new(),
162            nodes: HashMap::new(),
163        }
164    }
165
166    /// Return the number of physical nodes in the ring.
167    pub fn node_count(&self) -> usize {
168        self.nodes.len()
169    }
170
171    /// Return the total number of virtual nodes (ring points).
172    pub fn virtual_node_count(&self) -> usize {
173        self.ring.len()
174    }
175
176    // -----------------------------------------------------------------------
177    // Node management
178    // -----------------------------------------------------------------------
179
180    /// Add a node to the ring.
181    ///
182    /// If a node with the same ID already exists, it is first removed and
183    /// re-inserted with the new weight (update semantics).
184    ///
185    /// Returns a list of rebalance events describing which ranges move.
186    pub fn add_node(&mut self, node: HashNode) -> Result<Vec<RebalanceEvent>> {
187        if node.weight == 0 {
188            return Err(ClusterError::Config("node weight must be > 0".into()));
189        }
190
191        // If node already present, remove first.
192        let events = if self.nodes.contains_key(&node.id) {
193            self.remove_node_internal(&node.id)
194        } else {
195            Vec::new()
196        };
197
198        let vnodes = self.base_vnodes * node.weight;
199        let node_id = node.id.clone();
200        self.nodes.insert(node_id.clone(), node);
201
202        let mut add_events: Vec<RebalanceEvent> = Vec::new();
203        for i in 0..vnodes {
204            let key = format!("{}#vn{}", node_id, i);
205            let pos = ring_hash(&key);
206            // Find the node that previously owned this position.
207            let prev_owner = self.find_successor_id(pos);
208
209            let entry = RingEntry {
210                position: pos,
211                node_id: node_id.clone(),
212                vnode_index: i,
213            };
214            self.ring.insert(pos, entry);
215
216            if let Some(prev) = prev_owner {
217                if prev != node_id {
218                    // Compute previous range for this virtual node.
219                    let range_start = self.predecessor_position(pos);
220                    add_events.push(RebalanceEvent {
221                        destination_node: node_id.clone(),
222                        source_node: prev,
223                        range_start,
224                        range_end: pos,
225                    });
226                }
227            }
228        }
229
230        Ok([events, add_events].concat())
231    }
232
233    /// Remove a node from the ring.
234    ///
235    /// Returns the rebalance events (which node takes over which ranges).
236    pub fn remove_node(&mut self, node_id: &str) -> Result<Vec<RebalanceEvent>> {
237        if !self.nodes.contains_key(node_id) {
238            return Err(ClusterError::Config(format!(
239                "node '{}' not in ring",
240                node_id
241            )));
242        }
243        Ok(self.remove_node_internal(node_id))
244    }
245
246    /// Update the weight of an existing node, triggering rebalancing.
247    pub fn update_weight(&mut self, node_id: &str, new_weight: u32) -> Result<Vec<RebalanceEvent>> {
248        if new_weight == 0 {
249            return Err(ClusterError::Config("new_weight must be > 0".into()));
250        }
251        let node = self
252            .nodes
253            .get(node_id)
254            .ok_or_else(|| ClusterError::Config(format!("node '{}' not found", node_id)))?
255            .clone();
256        let updated = HashNode {
257            weight: new_weight,
258            ..node
259        };
260        self.add_node(updated)
261    }
262
263    // -----------------------------------------------------------------------
264    // Key lookup
265    // -----------------------------------------------------------------------
266
267    /// Return the ID of the node responsible for the given key.
268    ///
269    /// Returns `None` if the ring is empty.
270    pub fn get(&self, key: &str) -> Option<&str> {
271        if self.ring.is_empty() {
272            return None;
273        }
274        let h = ring_hash(key);
275        self.find_successor_str(h)
276    }
277
278    /// Return up to `n` distinct nodes in replica order for the given key.
279    ///
280    /// Used for replication: the first node is the primary, subsequent nodes
281    /// are replicas.
282    pub fn get_replicas<'a>(&'a self, key: &str, n: usize) -> Vec<&'a str> {
283        if self.ring.is_empty() || n == 0 {
284            return Vec::new();
285        }
286        let h = ring_hash(key);
287        let mut result: Vec<&str> = Vec::with_capacity(n);
288        let mut seen_ids: std::collections::HashSet<&str> = std::collections::HashSet::new();
289
290        // Walk the ring starting from the successor.
291        let after: Vec<_> = self.ring.range(h..).collect();
292        let before: Vec<_> = self.ring.range(..h).collect();
293
294        for (_, entry) in after.iter().chain(before.iter()) {
295            let id: &str = &entry.node_id;
296            if !seen_ids.contains(id) {
297                seen_ids.insert(id);
298                result.push(id);
299                if result.len() == n {
300                    break;
301                }
302            }
303        }
304        result
305    }
306
307    // -----------------------------------------------------------------------
308    // Statistics
309    // -----------------------------------------------------------------------
310
311    /// Compute per-node load statistics.
312    pub fn load_stats(&self) -> Vec<NodeLoadStats> {
313        if self.ring.is_empty() {
314            return self
315                .nodes
316                .keys()
317                .map(|id| NodeLoadStats {
318                    node_id: id.clone(),
319                    virtual_node_count: 0,
320                    key_space_fraction: 0.0,
321                })
322                .collect();
323        }
324
325        let mut counts: HashMap<String, u64> = HashMap::new();
326        let total: u64 = u64::MAX;
327        let ring_entries: Vec<_> = self.ring.values().collect();
328        let n = ring_entries.len();
329
330        for (i, entry) in ring_entries.iter().enumerate() {
331            let prev_pos = if i == 0 {
332                // The segment before the first entry wraps around.
333                0u64
334            } else {
335                ring_entries[i - 1].position
336            };
337            let range = entry.position.wrapping_sub(prev_pos);
338            *counts.entry(entry.node_id.clone()).or_insert(0) += range;
339        }
340
341        // Add the wrap-around segment (from last entry to u64::MAX) to the first entry.
342        if n > 0 {
343            let last_pos = ring_entries[n - 1].position;
344            let wrap = total.wrapping_sub(last_pos);
345            let first_node = ring_entries[0].node_id.clone();
346            *counts.entry(first_node).or_insert(0) += wrap;
347        }
348
349        let mut vnode_counts: HashMap<String, u32> = HashMap::new();
350        for entry in ring_entries {
351            *vnode_counts.entry(entry.node_id.clone()).or_insert(0) += 1;
352        }
353
354        self.nodes
355            .keys()
356            .map(|id| NodeLoadStats {
357                node_id: id.clone(),
358                virtual_node_count: *vnode_counts.get(id).unwrap_or(&0),
359                key_space_fraction: *counts.get(id).unwrap_or(&0) as f64 / u64::MAX as f64,
360            })
361            .collect()
362    }
363
364    /// Return the maximum imbalance ratio across all nodes.
365    ///
366    /// A ratio of 1.0 means perfectly balanced. Higher values indicate imbalance.
367    pub fn max_load_imbalance(&self) -> f64 {
368        let stats = self.load_stats();
369        if stats.is_empty() {
370            return 1.0;
371        }
372        let fractions: Vec<f64> = stats.iter().map(|s| s.key_space_fraction).collect();
373        let avg = fractions.iter().sum::<f64>() / fractions.len() as f64;
374        if avg == 0.0 {
375            return 1.0;
376        }
377        fractions.iter().map(|&f| f / avg).fold(0.0_f64, f64::max)
378    }
379
380    // -----------------------------------------------------------------------
381    // Private helpers
382    // -----------------------------------------------------------------------
383
384    fn remove_node_internal(&mut self, node_id: &str) -> Vec<RebalanceEvent> {
385        self.nodes.remove(node_id);
386
387        // Collect positions of virtual nodes belonging to node_id.
388        let positions: Vec<u64> = self
389            .ring
390            .values()
391            .filter(|e| e.node_id == node_id)
392            .map(|e| e.position)
393            .collect();
394
395        let mut events: Vec<RebalanceEvent> = Vec::new();
396        for pos in positions {
397            self.ring.remove(&pos);
398            // Who takes over this position now?
399            if let Some(new_owner) = self.find_successor_str(pos) {
400                events.push(RebalanceEvent {
401                    destination_node: new_owner.to_string(),
402                    source_node: node_id.to_string(),
403                    range_start: self.predecessor_position(pos),
404                    range_end: pos,
405                });
406            }
407        }
408        events
409    }
410
411    /// Find the ID of the successor node for a hash position.
412    fn find_successor_id(&self, pos: u64) -> Option<String> {
413        self.find_successor_str(pos).map(|s| s.to_string())
414    }
415
416    fn find_successor_str(&self, pos: u64) -> Option<&str> {
417        // Try from pos onwards, then wrap around.
418        self.ring
419            .range(pos..)
420            .next()
421            .or_else(|| self.ring.range(..pos).next())
422            .map(|(_, e)| e.node_id.as_str())
423    }
424
425    fn predecessor_position(&self, pos: u64) -> u64 {
426        self.ring
427            .range(..pos)
428            .next_back()
429            .map(|(&p, _)| p)
430            .unwrap_or(0)
431    }
432}
433
434// ===========================================================================
435// Tests
436// ===========================================================================
437
438#[cfg(test)]
439mod tests {
440    use super::*;
441
442    fn make_ring() -> AdaptiveConsistentHash {
443        AdaptiveConsistentHash::new(100)
444    }
445
446    // -----------------------------------------------------------------------
447    // Basic construction
448    // -----------------------------------------------------------------------
449
450    #[test]
451    fn test_empty_ring_returns_none() {
452        let ring = make_ring();
453        assert!(ring.get("any-key").is_none());
454    }
455
456    #[test]
457    fn test_single_node_owns_all_keys() {
458        let mut ring = make_ring();
459        ring.add_node(HashNode::new("n1")).expect("add");
460        for key in ["a", "b", "c", "d", "hello", "world"] {
461            assert_eq!(ring.get(key), Some("n1"));
462        }
463    }
464
465    #[test]
466    fn test_node_count() {
467        let mut ring = make_ring();
468        ring.add_node(HashNode::new("n1")).expect("add");
469        ring.add_node(HashNode::new("n2")).expect("add");
470        assert_eq!(ring.node_count(), 2);
471    }
472
473    #[test]
474    fn test_virtual_node_count_for_weight() {
475        let mut ring = AdaptiveConsistentHash::new(10);
476        ring.add_node(HashNode::with_weight("n1", 3)).expect("add");
477        // Expected: 10 * 3 = 30 virtual nodes
478        assert_eq!(ring.virtual_node_count(), 30);
479    }
480
481    // -----------------------------------------------------------------------
482    // Distribution
483    // -----------------------------------------------------------------------
484
485    #[test]
486    fn test_keys_distributed_across_nodes() {
487        let mut ring = make_ring();
488        ring.add_node(HashNode::new("n1")).expect("add");
489        ring.add_node(HashNode::new("n2")).expect("add");
490        ring.add_node(HashNode::new("n3")).expect("add");
491
492        // Use a large key set to ensure all nodes get at least one key.
493        // With 100 vnodes/node the hash space coverage requires ~5000+ keys
494        // for reliable statistical coverage across different key patterns.
495        let mut counts: HashMap<String, usize> = HashMap::new();
496        for i in 0..5000u32 {
497            let key = format!("key-{}", i);
498            if let Some(node) = ring.get(&key) {
499                *counts.entry(node.to_string()).or_insert(0) += 1;
500            }
501        }
502        // All three nodes should own at least one key.
503        assert_eq!(counts.len(), 3, "not all nodes received keys: {:?}", counts);
504    }
505
506    #[test]
507    fn test_weighted_node_owns_more_key_space() {
508        // Use 100 base vnodes: at this level FNV-1a distributes in favour of
509        // the heavier node (empirically verified with 200 base vnodes the
510        // FNV-1a clustering can invert the expected ordering).
511        let mut ring = AdaptiveConsistentHash::new(100);
512        ring.add_node(HashNode::with_weight("heavy", 4))
513            .expect("add");
514        ring.add_node(HashNode::new("light")).expect("add");
515
516        let stats = ring.load_stats();
517        let heavy = stats.iter().find(|s| s.node_id == "heavy").expect("heavy");
518        let light = stats.iter().find(|s| s.node_id == "light").expect("light");
519        // heavy has 4x more virtual nodes, so it should own more key space on average
520        assert!(
521            heavy.key_space_fraction > light.key_space_fraction,
522            "heavy={:.4} light={:.4}",
523            heavy.key_space_fraction,
524            light.key_space_fraction,
525        );
526    }
527
528    // -----------------------------------------------------------------------
529    // Rebalancing
530    // -----------------------------------------------------------------------
531
532    #[test]
533    fn test_add_node_produces_rebalance_events() {
534        let mut ring = make_ring();
535        ring.add_node(HashNode::new("n1")).expect("add");
536        let events = ring.add_node(HashNode::new("n2")).expect("add");
537        // Some ranges from n1 should move to n2
538        assert!(!events.is_empty());
539        for ev in &events {
540            assert_eq!(ev.destination_node, "n2");
541            assert_eq!(ev.source_node, "n1");
542        }
543    }
544
545    #[test]
546    fn test_remove_node_produces_rebalance_events() {
547        let mut ring = make_ring();
548        ring.add_node(HashNode::new("n1")).expect("add");
549        ring.add_node(HashNode::new("n2")).expect("add");
550        let events = ring.remove_node("n1").expect("remove");
551        assert!(!events.is_empty());
552        for ev in &events {
553            assert_eq!(ev.source_node, "n1");
554        }
555    }
556
557    #[test]
558    fn test_remove_nonexistent_node_errors() {
559        let mut ring = make_ring();
560        assert!(ring.remove_node("ghost").is_err());
561    }
562
563    #[test]
564    fn test_remove_node_keys_rerouted() {
565        let mut ring = make_ring();
566        ring.add_node(HashNode::new("n1")).expect("add");
567        ring.add_node(HashNode::new("n2")).expect("add");
568
569        // Collect key assignments before removal
570        let keys: Vec<String> = (0..50u32).map(|i| format!("key-{}", i)).collect();
571        let before: HashMap<String, String> = keys
572            .iter()
573            .map(|k| (k.clone(), ring.get(k).unwrap_or("").to_string()))
574            .collect();
575
576        ring.remove_node("n1").expect("remove");
577
578        // After removal, all keys previously on n1 must now go to n2.
579        for (key, prev_node) in &before {
580            let after_node = ring.get(key).unwrap_or("");
581            if prev_node == "n1" {
582                assert_eq!(after_node, "n2");
583            }
584        }
585    }
586
587    #[test]
588    fn test_update_weight_changes_vnode_count() {
589        let mut ring = AdaptiveConsistentHash::new(10);
590        ring.add_node(HashNode::with_weight("n1", 1)).expect("add");
591        assert_eq!(ring.virtual_node_count(), 10);
592
593        ring.update_weight("n1", 3).expect("update");
594        assert_eq!(ring.virtual_node_count(), 30);
595    }
596
597    #[test]
598    fn test_update_weight_zero_errors() {
599        let mut ring = make_ring();
600        ring.add_node(HashNode::new("n1")).expect("add");
601        assert!(ring.update_weight("n1", 0).is_err());
602    }
603
604    // -----------------------------------------------------------------------
605    // Replicas
606    // -----------------------------------------------------------------------
607
608    #[test]
609    fn test_get_replicas_empty_ring() {
610        let ring = make_ring();
611        assert!(ring.get_replicas("k", 3).is_empty());
612    }
613
614    #[test]
615    fn test_get_replicas_returns_distinct_nodes() {
616        let mut ring = make_ring();
617        for i in 1..=5u32 {
618            ring.add_node(HashNode::new(format!("n{}", i)))
619                .expect("add");
620        }
621        let replicas = ring.get_replicas("my-key", 3);
622        assert_eq!(replicas.len(), 3);
623        let unique: std::collections::HashSet<_> = replicas.iter().collect();
624        assert_eq!(unique.len(), 3);
625    }
626
627    #[test]
628    fn test_get_replicas_at_most_n_nodes() {
629        let mut ring = make_ring();
630        ring.add_node(HashNode::new("n1")).expect("add");
631        ring.add_node(HashNode::new("n2")).expect("add");
632        // Request more replicas than nodes available
633        let replicas = ring.get_replicas("k", 5);
634        assert!(replicas.len() <= 2);
635    }
636
637    // -----------------------------------------------------------------------
638    // Load statistics
639    // -----------------------------------------------------------------------
640
641    #[test]
642    fn test_load_stats_sums_to_one() {
643        let mut ring = AdaptiveConsistentHash::new(200);
644        for i in 1..=4u32 {
645            ring.add_node(HashNode::new(format!("n{}", i)))
646                .expect("add");
647        }
648        let stats = ring.load_stats();
649        let total: f64 = stats.iter().map(|s| s.key_space_fraction).sum();
650        // Should be very close to 1.0 (may differ due to u64 max wrap)
651        assert!((total - 1.0).abs() < 0.01, "total fraction={}", total);
652    }
653
654    #[test]
655    fn test_max_load_imbalance_single_node() {
656        let mut ring = AdaptiveConsistentHash::new(100);
657        ring.add_node(HashNode::new("n1")).expect("add");
658        // With one node, imbalance is 1.0 (perfectly "balanced" for one node)
659        let imbalance = ring.max_load_imbalance();
660        assert!((imbalance - 1.0).abs() < 0.01);
661    }
662
663    #[test]
664    fn test_max_load_imbalance_reasonable_with_many_vnodes() {
665        let mut ring = AdaptiveConsistentHash::new(300);
666        for i in 1..=4u32 {
667            ring.add_node(HashNode::new(format!("n{}", i)))
668                .expect("add");
669        }
670        // With 300 vnodes/node, imbalance should be within 3x of ideal
671        let imbalance = ring.max_load_imbalance();
672        assert!(imbalance < 3.0, "imbalance too high: {}", imbalance);
673    }
674
675    // -----------------------------------------------------------------------
676    // HashNode helpers
677    // -----------------------------------------------------------------------
678
679    #[test]
680    fn test_hash_node_with_label() {
681        let n = HashNode::new("n1").with_label("Primary Europe");
682        assert_eq!(n.label.as_deref(), Some("Primary Europe"));
683    }
684
685    #[test]
686    fn test_hash_node_default_weight() {
687        let n = HashNode::new("n1");
688        assert_eq!(n.weight, 1);
689    }
690
691    #[test]
692    fn test_add_duplicate_node_updates() {
693        let mut ring = AdaptiveConsistentHash::new(10);
694        ring.add_node(HashNode::with_weight("n1", 1)).expect("add");
695        ring.add_node(HashNode::with_weight("n1", 3))
696            .expect("re-add");
697        assert_eq!(ring.node_count(), 1);
698        // Weight updated → 10*3 vnodes
699        assert_eq!(ring.virtual_node_count(), 30);
700    }
701
702    #[test]
703    fn test_deterministic_key_assignment() {
704        let mut ring = make_ring();
705        ring.add_node(HashNode::new("n1")).expect("add");
706        ring.add_node(HashNode::new("n2")).expect("add");
707
708        // Same key always maps to the same node.
709        let first = ring.get("stable-key").map(|s| s.to_string());
710        for _ in 0..10 {
711            assert_eq!(ring.get("stable-key").map(|s| s.to_string()), first);
712        }
713    }
714}