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
use microkv::namespace::NamespaceMicroKV;
use std::fmt::{Debug, Formatter};

// discuss: https://github.com/darwinia-network/bridger/issues/284
/// Tracker
/// Block scan status
#[derive(Clone)]
pub struct Tracker {
    microkv: NamespaceMicroKV,
    /// Current scan value, the next value is current+1
    key_current: String,
    /// Planned to execute, after to running the next value is planned+1
    key_planned: String,
    /// Control running
    key_running: String,
}

impl Debug for Tracker {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str("Tracker {\n")?;
        f.write_str("  microkv: ***,\n")?;
        f.write_str(&format!("  key_current: {}\n", self.key_current))?;
        f.write_str(&format!("  key_planned: {}\n", self.key_planned))?;
        f.write_str(&format!("  key_running: {}\n", self.key_running))?;
        f.write_str("}")?;
        Ok(())
    }
}

impl Tracker {
    /// Create a new tracker, the key is prefix
    pub fn new(microkv: NamespaceMicroKV, key: impl AsRef<str>) -> Self {
        let key = key.as_ref();
        Self {
            microkv,
            key_current: format!("{}.current", key),
            key_planned: format!("{}.planned", key),
            key_running: format!("{}.running", key),
        }
    }
}

impl Tracker {
    pub fn is_running(&self) -> color_eyre::Result<bool> {
        self.read_bool(&self.key_running)
    }

    pub fn stop_running(&self) -> color_eyre::Result<()> {
        self.microkv.put(&self.key_running, &false)?;
        Ok(())
    }

    pub fn start_running(&self) -> color_eyre::Result<()> {
        self.microkv.put(&self.key_running, &true)?;
        Ok(())
    }

    /// Read current value
    pub async fn current(&self) -> color_eyre::Result<usize> {
        let is_running = self.is_running()?;
        if !is_running {
            loop {
                let secs = 3;
                tracing::warn!(
                    target: "tracker",
                    "The track key [{}] isn't running (value is not `true`), wait {} seconds check again.",
                    &self.key_running,
                    secs
                );
                tokio::time::sleep(std::time::Duration::from_secs(secs)).await;
                if self.is_running()? {
                    break;
                }
            }
        }

        match self.read_u64(&self.key_planned)? {
            Some(planned) => {
                self.microkv.put(&self.key_current, &planned)?;
                self.microkv.delete(&self.key_planned)?;
                Ok(planned as usize)
            }
            None => {
                let current = self.read_u64(&self.key_current)?.unwrap_or(0);
                Ok(current as usize)
            }
        }
    }

    /// Read the next value
    /// Generally the value is current+1, but if the planned have value, will use planned+1
    pub async fn next(&self) -> color_eyre::Result<usize> {
        self.current().await.map(|v| v + 1)
    }

    /// Update current
    pub fn finish(&self, block: usize) -> color_eyre::Result<()> {
        self.microkv.put(&self.key_current, &block)?;
        Ok(())
    }

    pub fn planned(&self, block: usize) -> color_eyre::Result<()> {
        self.microkv.put(&self.key_planned, &block)?;
        Ok(())
    }
}

impl Tracker {
    /// Read bool value by a key
    fn read_bool(&self, key: impl AsRef<str>) -> color_eyre::Result<bool> {
        let value = self
            .microkv
            .get(key.as_ref())?
            .unwrap_or(serde_json::Value::Bool(false));
        if value.is_boolean() {
            return Ok(value.as_bool().unwrap_or(false));
        }
        if value.is_string() {
            let text = value.as_str().unwrap_or("false");
            return Ok(text == "true" || text == "1");
        }
        Ok(false)
    }

    fn read_u64(&self, key: impl AsRef<str>) -> color_eyre::Result<Option<u64>> {
        let value = self.microkv.get(key.as_ref())?;
        match value {
            Some(v) => {
                if v.is_number() {
                    return Ok(v.as_u64());
                }
                if v.is_boolean() {
                    return Ok(v.as_bool().map(|b| if b { 1 } else { 0 }));
                }
                if v.is_string() {
                    return match v.as_str() {
                        Some(t) => {
                            let t = t.trim();
                            Ok(Some(t.parse()?))
                        }
                        None => Ok(None),
                    };
                }
                Ok(None)
            }
            None => Ok(None),
        }
    }
}