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
use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use chrono::Utc;

use mithril_common::StdResult;
use mithril_persistence::sqlite::{ConnectionExtensions, SqliteConnection};

use crate::database::query::{
    GetSignerRecordQuery, ImportSignerRecordQuery, RegisterSignerRecordQuery,
};
use crate::database::record::SignerRecord;
use crate::SignerRecorder;

/// Service to get [SignerRecord].
#[cfg_attr(test, mockall::automock)]
#[async_trait]
pub trait SignerGetter: Sync + Send {
    /// Return all stored records.
    async fn get_all(&self) -> StdResult<Vec<SignerRecord>>;
}

/// Service to deal with signer (read & write).
pub struct SignerStore {
    connection: Arc<SqliteConnection>,
}

impl SignerStore {
    /// Create a new SignerStore service
    pub fn new(connection: Arc<SqliteConnection>) -> Self {
        Self { connection }
    }

    /// Import a signer in the database, its last_registered_at date will be left empty
    pub async fn import_signer(
        &self,
        signer_id: String,
        pool_ticker: Option<String>,
    ) -> StdResult<()> {
        let created_at = Utc::now();
        let updated_at = created_at;
        let signer_record = SignerRecord {
            signer_id,
            pool_ticker,
            created_at,
            updated_at,
            last_registered_at: None,
        };
        self.connection
            .fetch_first(ImportSignerRecordQuery::one(signer_record))?;

        Ok(())
    }

    /// Create many signers at once in the database, their last_registered_at date will be left empty
    pub async fn import_many_signers(
        &self,
        pool_ticker_by_id: HashMap<String, Option<String>>,
    ) -> StdResult<()> {
        let created_at = Utc::now();
        let updated_at = created_at;
        let signer_records: Vec<_> = pool_ticker_by_id
            .into_iter()
            .map(|(signer_id, pool_ticker)| SignerRecord {
                signer_id,
                pool_ticker,
                created_at,
                updated_at,
                last_registered_at: None,
            })
            .collect();
        self.connection
            .fetch_first(ImportSignerRecordQuery::many(signer_records))?;

        Ok(())
    }
}

#[async_trait]
impl SignerRecorder for SignerStore {
    async fn record_signer_registration(&self, signer_id: String) -> StdResult<()> {
        let created_at = Utc::now();
        let updated_at = created_at;
        let registered_at = Some(created_at);
        let signer_record = SignerRecord {
            signer_id,
            pool_ticker: None,
            created_at,
            updated_at,
            last_registered_at: registered_at,
        };
        self.connection
            .fetch_first(RegisterSignerRecordQuery::one(signer_record))?;

        Ok(())
    }
}

#[async_trait]
impl SignerGetter for SignerStore {
    async fn get_all(&self) -> StdResult<Vec<SignerRecord>> {
        self.connection.fetch_collect(GetSignerRecordQuery::all())
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use crate::database::test_helper::{insert_signers, main_db_connection};

    use super::*;

    #[tokio::test]
    async fn test_get_all_signers() {
        let signer_records = SignerRecord::fake_records(5);
        let expected: Vec<_> = signer_records.iter().rev().cloned().collect();
        let connection = main_db_connection().unwrap();
        insert_signers(&connection, signer_records).unwrap();

        let store = SignerStore::new(Arc::new(connection));

        let stored_signers = store
            .get_all()
            .await
            .expect("getting all signers should not fail");

        assert_eq!(expected, stored_signers);
    }

    #[tokio::test]
    async fn test_signer_recorder() {
        let signer_records_fake = SignerRecord::fake_records(5);

        let connection = Arc::new(main_db_connection().unwrap());
        let store_recorder = SignerStore::new(connection.clone());

        for signer_record in signer_records_fake.clone() {
            store_recorder
                .record_signer_registration(signer_record.signer_id.clone())
                .await
                .expect("record_signer_registration should not fail");
            let signer_record_stored = connection
                .fetch_first(GetSignerRecordQuery::by_signer_id(signer_record.signer_id))
                .unwrap();
            assert!(signer_record_stored.is_some());
            assert!(
                signer_record_stored.unwrap().last_registered_at.is_some(),
                "registering a signer should set the registration date"
            )
        }
    }

    #[tokio::test]
    async fn test_store_import_signer() {
        let signer_records_fake = SignerRecord::fake_records(5);

        let connection = Arc::new(main_db_connection().unwrap());
        let store = SignerStore::new(connection.clone());

        for signer_record in signer_records_fake {
            store
                .import_signer(
                    signer_record.signer_id.clone(),
                    signer_record.pool_ticker.clone(),
                )
                .await
                .expect("import_signer should not fail");
            let signer_record_stored = connection
                .fetch_first(GetSignerRecordQuery::by_signer_id(signer_record.signer_id))
                .unwrap();
            assert!(signer_record_stored.is_some());
            assert!(
                signer_record_stored.unwrap().last_registered_at.is_none(),
                "imported signer should not have a registration date"
            )
        }
    }

    #[tokio::test]
    async fn test_store_import_many_signers() {
        let signers_fake: BTreeMap<_, _> = SignerRecord::fake_records(5)
            .into_iter()
            .map(|r| (r.signer_id, r.pool_ticker))
            .collect();

        let connection = main_db_connection().unwrap();
        let store = SignerStore::new(Arc::new(connection));

        store
            .import_many_signers(signers_fake.clone().into_iter().collect())
            .await
            .expect("import_many_signers should not fail");

        let signer_records_stored = store.get_all().await.unwrap();
        let signers_stored = signer_records_stored
            .iter()
            .cloned()
            .map(|r| (r.signer_id, r.pool_ticker))
            .collect();
        assert_eq!(signers_fake, signers_stored);
        assert!(
            signer_records_stored
                .iter()
                .all(|s| s.last_registered_at.is_none()),
            "imported signer should not have a registration date"
        );
    }
}