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
use std::{
    io,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
};

use super::errors;
use tokio::sync::RwLock;

#[derive(Clone)]
pub struct Database {
    db: Box<dyn crate::rpcchainvm::database::Database + Send + Sync>,
    corrupted: Arc<AtomicBool>,
    corrupted_error: Arc<RwLock<String>>,
}

impl Database {
    pub fn new(
        db: Box<dyn crate::rpcchainvm::database::Database + Send + Sync>,
    ) -> Box<dyn crate::rpcchainvm::database::Database + Send + Sync> {
        Box::new(Database {
            db,
            corrupted: Arc::new(AtomicBool::new(false)),
            corrupted_error: Arc::new(RwLock::new("".into())),
        })
    }
}

/// Database is a wrapper around Database it prevents any future calls
/// in case a corruption occurs.
/// ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/database/corruptabledb#Database
impl crate::rpcchainvm::database::Database for Database {}

#[tonic::async_trait]
impl crate::rpcchainvm::database::KeyValueReaderWriterDeleter for Database {
    /// Attempts to return if the database has a key with the provided value.
    async fn has(&self, key: &[u8]) -> io::Result<bool> {
        if self.corrupted.load(Ordering::Relaxed) {
            return Err(errors::from_string(
                self.corrupted_error.read().await.to_string(),
            ));
        }

        let db = &self.db;
        match db.get(key).await {
            Ok(_) => Ok(true),
            Err(err) => {
                let (is_corrupted, err) = errors::is_corruptible(err).await;
                if is_corrupted {
                    *self.corrupted_error.write().await = err.to_string();
                    self.corrupted.store(true, Ordering::Relaxed);
                    return Err(errors::from_string(
                        self.corrupted_error.read().await.to_string(),
                    ));
                }
                if errors::is_not_found(&err) {
                    return Ok(false);
                }
                return Err(err);
            }
        }
    }

    /// Attempts to return the value that was mapped to the key that was provided.
    async fn get(&self, key: &[u8]) -> io::Result<Vec<u8>> {
        if self.corrupted.load(Ordering::Relaxed) {
            return Err(errors::from_string(
                self.corrupted_error.read().await.to_string(),
            ));
        }

        let db = &self.db;
        match db.get(key).await {
            Ok(resp) => Ok(resp),
            Err(err) => {
                let (is_corrupted, err) = errors::is_corruptible(err).await;
                if is_corrupted {
                    *self.corrupted_error.write().await = err.to_string();
                    self.corrupted.store(true, Ordering::Relaxed);
                    return Err(errors::from_string(
                        self.corrupted_error.read().await.to_string(),
                    ));
                }
                return Err(err);
            }
        }
    }

    /// Attempts to set the value this key maps to.
    async fn put(&mut self, key: &[u8], value: &[u8]) -> io::Result<()> {
        if self.corrupted.load(Ordering::Relaxed) {
            return Err(errors::from_string(
                self.corrupted_error.read().await.to_string(),
            ));
        }

        let db = &mut self.db;
        match db.put(key, value).await {
            Ok(_) => Ok(()),
            Err(err) => {
                let (is_corrupted, err) = errors::is_corruptible(err).await;
                if is_corrupted {
                    *self.corrupted_error.write().await = err.to_string();
                    self.corrupted.store(true, Ordering::Relaxed);
                    return Err(errors::from_string(
                        self.corrupted_error.read().await.to_string(),
                    ));
                }
                return Err(err);
            }
        }
    }

    /// Attempts to remove any mapping from the key.
    async fn delete(&mut self, key: &[u8]) -> io::Result<()> {
        if self.corrupted.load(Ordering::Relaxed) {
            return Err(errors::from_string(
                self.corrupted_error.read().await.to_string(),
            ));
        }

        let db = &mut self.db;
        match db.delete(key).await {
            Ok(_) => Ok(()),
            Err(err) => {
                let (is_corrupted, err) = errors::is_corruptible(err).await;
                if is_corrupted {
                    *self.corrupted_error.write().await = err.to_string();
                    self.corrupted.store(true, Ordering::Relaxed);
                    return Err(errors::from_string(
                        self.corrupted_error.read().await.to_string(),
                    ));
                }
                return Err(err);
            }
        }
    }
}

#[tonic::async_trait]
impl crate::rpcchainvm::database::Closer for Database {
    /// Attempts to close the database.
    async fn close(&self) -> io::Result<()> {
        if self.corrupted.load(Ordering::Relaxed) {
            return Err(errors::from_string(
                self.corrupted_error.read().await.to_string(),
            ));
        }

        let db = &self.db;
        match db.close().await {
            Ok(_) => Ok(()),
            Err(err) => {
                let (is_corrupted, err) = errors::is_corruptible(err).await;
                if is_corrupted {
                    *self.corrupted_error.write().await = err.to_string();
                    self.corrupted.store(true, Ordering::Relaxed);
                    return Err(errors::from_string(
                        self.corrupted_error.read().await.to_string(),
                    ));
                }
                return Err(err);
            }
        }
    }
}

#[tonic::async_trait]
impl crate::rpcchainvm::health::Checkable for Database {
    /// Checks if the database has been closed.
    async fn health_check(&self) -> io::Result<Vec<u8>> {
        if self.corrupted.load(Ordering::Relaxed) {
            return Err(errors::from_string(
                self.corrupted_error.read().await.to_string(),
            ));
        }

        let db = &self.db;
        match db.health_check().await {
            Ok(resp) => Ok(resp),
            Err(err) => {
                let (is_corrupted, err) = errors::is_corruptible(err).await;
                if is_corrupted {
                    *self.corrupted_error.write().await = err.to_string();
                    self.corrupted.store(true, Ordering::Relaxed);
                    return Err(errors::from_string(
                        self.corrupted_error.read().await.to_string(),
                    ));
                }
                return Err(err);
            }
        }
    }
}