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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
use std::collections::HashMap;
use std::sync::Mutex;

use chrono::Duration;
use diesel::{self, prelude::*};
#[cfg(test)] use matches::assert_matches;
#[cfg(test)] use tempfile::NamedTempFile;

use crate::core::{GenericResult, GenericError, EmptyResult};
use crate::currency::CurrencyRate;
use crate::db::{self, schema::currency_rates, models};
use crate::formatting;
use crate::time;
use crate::types::{Date, Decimal};
use crate::util::{self, DecimalRestrictions};

// Official CBR currency rate is calculated as following:
// 1. Every weekday a weighted average price is calculated for 10:00 - 11:30 period.
// 2. The calculated value is published around 15:00 and will be the official currency rate starting
//    from the next day.
// 3. The calculated currency rate will be valid until the next official currency rate.
//
// See https://bcs-express.ru/novosti-i-analitika/ofitsial-nyi-kurs-tsb-rf-kak-on-schitaetsia-i-kto-im-pol-zuetsia
// for details.
//
// We request data until tomorrow only to be able to fill today date if it's monday (when there is
// no data from sunday for monday, but will be data from monday for tuesday), but don't save
// tomorrow's currency rates - just in case: we don't actually need them, but by not saving them we
// can handle a possible corrections, for example.
pub struct CurrencyRateCache {
    today: Date,
    tomorrow: Date,

    db: db::Connection,
    cache: Mutex<HashMap<String, HashMap<Date, Option<Decimal>>>>,
}

impl CurrencyRateCache {
    pub fn new(connection: db::Connection) -> CurrencyRateCache {
        let today = time::today();
        CurrencyRateCache {
            today: today,
            tomorrow: today.succ(),

            db: connection,
            cache: Mutex::new(HashMap::new()),
        }
    }

    #[cfg(test)]
    pub fn new_temporary() -> (NamedTempFile, CurrencyRateCache) {
        let (database, connection) = db::new_temporary();
        (database, CurrencyRateCache::new(connection))
    }

    pub fn today(&self) -> Date {
        self.today
    }

    pub fn get(&self, currency: &str, date: Date) -> GenericResult<CurrencyRateCacheResult> {
        if date > self.today {
            return Err!("An attempt to get currency rate for the future")
        }

        if let Some(cache) = self.cache.lock().unwrap().get(currency) {
            if let Some(price) = cache.get(&date).copied() {
                return Ok(CurrencyRateCacheResult::Exists(price));
            }
        }

        self.db.transaction::<_, GenericError, _>(|| {
            let result = currency_rates::table
                .select(currency_rates::price)
                .filter(currency_rates::currency.eq(currency))
                .filter(currency_rates::date.eq(date))
                .get_result::<Option<String>>(&*self.db).optional()?;

            if let Some(price) = result {
                let price = match price {
                    Some(price) => Some(
                        util::parse_decimal(&price, DecimalRestrictions::StrictlyPositive).map_err(|_| format!(
                            "Got an invalid price from the database: {:?}", price))?
                    ),
                    None => None,
                };

                self.cache.lock().unwrap()
                    .entry(currency.to_owned()).or_default()
                    .insert(date, price);

                return Ok(CurrencyRateCacheResult::Exists(price));
            }

            let start_date = {
                let result = currency_rates::table
                    .select(currency_rates::date)
                    .filter(currency_rates::currency.eq(currency))
                    .filter(currency_rates::date.lt(date))
                    .order(currency_rates::date.desc())
                    .limit(1)
                    .get_result::<Date>(&*self.db).optional()?;

                match result {
                    Some(last_date) => last_date.succ(),
                    None => date - Duration::days(365),
                }
            };

            let end_date = {
                let result = currency_rates::table
                    .select(currency_rates::date)
                    .filter(currency_rates::currency.eq(currency))
                    .filter(currency_rates::date.gt(date))
                    .filter(currency_rates::price.is_not_null())
                    .order(currency_rates::date.asc())
                    .limit(1)
                    .get_result::<Date>(&*self.db).optional()?;

                match result {
                    Some(first_date) => first_date,
                    None => self.tomorrow,
                }
            };

            assert!(start_date <= end_date);
            Ok(CurrencyRateCacheResult::Missing(start_date, end_date))
        })
    }

    pub fn save(&self, currency: &str, start_date: Date, end_date: Date, mut rates: Vec<CurrencyRate>) -> EmptyResult {
        if start_date > end_date {
            return Err!("Invalid date range: {} - {}",
                formatting::format_date(start_date), formatting::format_date(end_date));
        } else if end_date > self.tomorrow {
            return Err!("An attempt to save currency rates for the future");
        }

        if !rates.is_empty() {
            rates.sort_by_key(|rate| rate.date);
            if rates.first().unwrap().date < start_date || rates.last().unwrap().date > end_date {
                return Err!("The specified currency rates don't match the specified date range");
            }
        }

        let mut last_date: Option<Date> = None;
        let mut rows = Vec::new();

        for rate in &rates {
            {
                let mut date = match last_date {
                    Some(date) => date.succ(),
                    None => start_date,
                };

                while date < rate.date {
                    rows.push(models::NewCurrencyRate {
                        currency: currency,
                        date: date,
                        price: None,
                    });
                    date = date.succ();
                }
            }
            last_date.replace(rate.date);

            if rate.date == self.tomorrow {
                continue;
            }
            assert!(rate.date <= self.today);

            rows.push(models::NewCurrencyRate {
                currency: currency,
                date: rate.date,
                price: Some(rate.price.to_string()),
            });
        }

        {
            let mut date = match last_date {
                Some(date) => date.succ(),
                None => start_date,
            };
            debug_assert!(date > end_date || end_date == self.tomorrow);

            while date <= std::cmp::min(end_date, self.today) {
                self.cache.lock().unwrap()
                    .entry(currency.to_owned())
                    .or_default()
                    .insert(date, None);
                date = date.succ();
            }
        }

        diesel::replace_into(currency_rates::table)
            .values(rows)
            .execute(&*self.db)?;

        Ok(())
    }
}

#[derive(Debug)]
pub enum CurrencyRateCacheResult {
    Exists(Option<Decimal>),
    Missing(Date, Date),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rate_cache() {
        let currency = "USD";
        let (_database, mut cache) = CurrencyRateCache::new_temporary();

        let today = date!(8, 2, 2018);
        let tomorrow = today.succ();
        cache.today = today;
        cache.tomorrow = tomorrow;

        let first_date = date!(10, 1, 2018);
        let last_date = date!(4, 2, 2018);
        let currency_rates = vec![CurrencyRate {
            date: last_date,
            price: dec!(1) / dec!(3),
        }, CurrencyRate {
            date: first_date,
            price: dec!(1) / dec!(7),
        }];

        let cache_start_date = last_date - Duration::days(365);
        let cache_end_date = today;

        assert_matches!(
            cache.get(currency, tomorrow),
            Err(ref e) if e.to_string() == "An attempt to get currency rate for the future"
        );

        assert_matches!(
            cache.get(currency, last_date).unwrap(),
            CurrencyRateCacheResult::Missing(from, to) if from == cache_start_date && to == tomorrow
        );
        cache.save(currency, cache_start_date, tomorrow, currency_rates.clone()).unwrap();

        for &clear_in_memory_cache in &[false, true] {
            let mut date = cache_start_date.pred();
            if clear_in_memory_cache {
                cache.cache.lock().unwrap().clear();
            }

            assert_matches!(
                cache.get(currency, date).unwrap(),
                CurrencyRateCacheResult::Missing(from, to)
                    if from == date - Duration::days(365) && to == first_date
            );

            'date_loop: loop {
                date = date.succ();
                if date > cache_end_date {
                    break;
                }

                for currency_rate in &currency_rates {
                    if date == currency_rate.date {
                        assert_matches!(
                            cache.get(currency, date).unwrap(),
                            CurrencyRateCacheResult::Exists(Some(ref price)) if *price == currency_rate.price
                        );
                        continue 'date_loop;
                    }
                }

                let result = cache.get(currency, date).unwrap();

                if clear_in_memory_cache && last_date < date {
                    assert_matches!(result, CurrencyRateCacheResult::Missing(from, to)
                        if from == last_date.succ() && to == tomorrow);
                } else {
                    assert_matches!(result, CurrencyRateCacheResult::Exists(None));
                }
            }

            assert_matches!(
                cache.get(currency, date),
                Err(ref e) if e.to_string() == "An attempt to get currency rate for the future"
            );
        }

        cache.today += Duration::days(10);
        cache.tomorrow += Duration::days(10);

        assert_matches!(
            cache.get(currency, tomorrow).unwrap(),
            CurrencyRateCacheResult::Missing(from, to)
                if from == last_date.succ() && to == cache.tomorrow
        );
    }
}