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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
use metfor::Quantity;
use std::io::Write;

use super::{Archive, InternalSiteInfo};

use crate::{
    errors::BufkitDataErr,
    models::Model,
    site::{SiteInfo, StationNumber},
};

/// The end result of adding a file to the archive.
#[derive(Debug)]
pub enum AddFileResult {
    /// No site conflicts or changes. Includes the site as parsed from the file.
    Ok(StationNumber),
    /// This is a new site and it was added to the database as a new site.
    New(StationNumber),
    /// Some error occurred during processing.
    Error(BufkitDataErr),
    /// The site identifier provided with this file has moved to a new station number. The
    /// correlation between station numbers has been updated.
    IdMovedStation {
        /// The site information before the update.
        old: StationNumber,
        /// The site information as it exists now.
        new: StationNumber,
    },
}

impl Archive {
    /// Add a bufkit file to the archive.
    pub fn add(&self, site_id_hint: &str, model: Model, text_data: &str) -> AddFileResult {
        let site_id_hint = site_id_hint.to_uppercase();

        let InternalSiteInfo {
            station_num,
            id: parsed_site_id,
            init_time,
            end_time,
            coords,
            elevation,
        } = match Self::parse_site_info(text_data) {
            Ok(val) => val,
            Err(err) => return AddFileResult::Error(err),
        };

        let mut site_id = &site_id_hint;
        if let Some(parsed_id) = parsed_site_id.as_ref() {
            if parsed_id != &site_id_hint {
                site_id = parsed_id
            }
        }
        let site_id = site_id;

        if self.site(station_num).is_none() {
            let new_site = SiteInfo {
                station_num,
                ..SiteInfo::default()
            };
            match self.add_site(&new_site) {
                Ok(()) => {}
                Err(err) => return AddFileResult::Error(err),
            }
        }

        let file_name = self.compressed_file_name(site_id, model, init_time);
        let site_id = Some(site_id);

        match std::fs::File::create(self.data_root().join(&file_name))
            .map_err(BufkitDataErr::IO)
            .and_then(|file| {
                let mut encoder =
                    flate2::write::GzEncoder::new(file, flate2::Compression::default());
                encoder
                    .write_all(text_data.as_bytes())
                    .map_err(BufkitDataErr::IO)
            })
            .and_then(|_| {
                self.db_conn
                    .execute(
                        include_str!("modify/add_file.sql"),
                        &[
                            &Into::<u32>::into(station_num) as &dyn rusqlite::types::ToSql,
                            &model.as_static_str() as &dyn rusqlite::types::ToSql,
                            &init_time as &dyn rusqlite::types::ToSql,
                            &end_time,
                            &file_name,
                            &site_id,
                            &coords.lat,
                            &coords.lon,
                            &elevation.unpack(),
                        ],
                    )
                    .map_err(BufkitDataErr::Database)
            }) {
            Ok(_) => AddFileResult::Ok(station_num),
            Err(err) => AddFileResult::Error(err),
        }
    }

    /// Add a site to the list of sites.
    ///
    /// If a site with this station number already exists, return an error from the underlying
    /// database.
    pub fn add_site(&self, site: &SiteInfo) -> Result<(), BufkitDataErr> {
        self.db_conn.execute(
            include_str!("modify/add_site.sql"),
            &[
                &Into::<u32>::into(site.station_num) as &dyn rusqlite::ToSql,
                &site.name,
                &site.state.map(|state_prov| state_prov.as_static_str())
                    as &dyn rusqlite::types::ToSql,
                &site.notes,
                &site.time_zone.map(|tz| tz.local_minus_utc()),
                &site.auto_download,
            ],
        )?;

        Ok(())
    }

    /// Modify a site's values.
    pub fn update_site(&self, site: &SiteInfo) -> Result<(), BufkitDataErr> {
        self.db_conn
            .execute(
                include_str!("modify/update_site.sql"),
                &[
                    &Into::<u32>::into(site.station_num),
                    &site.state.map(|state_prov| state_prov.as_static_str())
                        as &dyn rusqlite::types::ToSql,
                    &site.name,
                    &site.notes,
                    &site.time_zone.map(|tz| tz.local_minus_utc()),
                    &site.auto_download,
                ],
            )
            .map_err(|err| err.into())
            .map(|_| {})
    }

    /// Remove a file from the archive.
    pub fn remove(
        &self,
        station_num: StationNumber,
        model: Model,
        init_time: chrono::NaiveDateTime,
    ) -> Result<(), BufkitDataErr> {
        let station_num: u32 = Into::<u32>::into(station_num);

        let file_name: String = self.db_conn.query_row(
            include_str!("modify/find_file_name.sql"),
            &[
                &station_num as &dyn rusqlite::types::ToSql,
                &model.as_static_str() as &dyn rusqlite::types::ToSql,
                &init_time as &dyn rusqlite::types::ToSql,
            ],
            |row| row.get(0),
        )?;

        std::fs::remove_file(self.data_root().join(file_name)).map_err(BufkitDataErr::IO)?;

        self.db_conn.execute(
            include_str!("modify/delete_file_from_index.sql"),
            &[
                &station_num as &dyn rusqlite::types::ToSql,
                &model.as_static_str() as &dyn rusqlite::types::ToSql,
                &init_time as &dyn rusqlite::types::ToSql,
            ],
        )?;

        Ok(())
    }

    /// Remove a site and all of its files from the archive.
    pub fn remove_site(&self, station_num: StationNumber) -> Result<(), BufkitDataErr> {
        let station_num: u32 = Into::<u32>::into(station_num);

        let mut qstmt = self
            .db_conn
            .prepare(include_str!("modify/find_all_files_for_site.sql"))?;
        let mut dstmt = self
            .db_conn
            .prepare(include_str!("modify/delete_file_by_name.sql"))?;

        let file_deletion_results: Result<Vec<()>, _> = qstmt
            .query_map(&[&station_num], |row| row.get(0))?
            .map(|res: Result<String, rusqlite::Error>| res.map_err(BufkitDataErr::Database))
            .map(|res| {
                res.and_then(|fname| {
                    std::fs::remove_file(self.data_root().join(&fname))
                        .map_err(BufkitDataErr::IO)
                        .map(|_| fname)
                })
            })
            .map(|res| {
                res.and_then(|fname| {
                    dstmt
                        .execute(&[fname])
                        .map_err(BufkitDataErr::Database)
                        .map(|_num_rows_affected| ())
                })
            })
            .collect();
        file_deletion_results?;

        self.db_conn
            .execute(include_str!("modify/delete_site.sql"), &[&station_num])?;

        Ok(())
    }

    fn compressed_file_name(
        &self,
        station_id: &str,
        model: Model,
        init_time: chrono::NaiveDateTime,
    ) -> String {
        let file_string = init_time.format("%Y%m%d%HZ").to_string();

        format!(
            "{}_{}_{}.buf.gz",
            file_string,
            model.as_static_str(),
            station_id,
        )
    }
}

#[cfg(test)]
mod unit {
    use super::*;
    use crate::archive::unit::*; // Set up and tear down functions.

    use chrono::NaiveDate;

    #[test]
    fn test_no_duplicate_sites() {
        let TestArchive { tmp: _tmp, arch } =
            create_test_archive().expect("Failed to create test archive.");

        let test_sites = &get_test_sites();

        for site in test_sites {
            arch.add_site(site).expect("Error adding site.");
        }

        // Try adding them again, this should fail.
        for site in test_sites {
            assert!(arch.add_site(site).is_err());
        }
    }

    #[test]
    fn test_update_site() {
        let TestArchive { tmp: _tmp, arch } =
            create_test_archive().expect("Failed to create test archive.");

        let test_sites = &get_test_sites();

        for site in test_sites {
            arch.add_site(site).expect("Error adding site.");
        }

        const STN: StationNumber = StationNumber::new(3);

        let zootown = SiteInfo {
            station_num: StationNumber::from(STN),
            name: Some("Zootown".to_owned()),
            notes: Some("Mountains, not coast.".to_owned()),
            state: Some(crate::StateProv::MT),
            time_zone: Some(chrono::FixedOffset::west(7 * 3600)),
            auto_download: false,
        };

        arch.update_site(&zootown).expect("Error updating site.");

        assert_eq!(arch.site(STN).unwrap(), zootown);
        assert_ne!(arch.site(STN).unwrap(), test_sites[2]);
    }

    #[test]
    fn test_add() {
        let TestArchive {
            tmp: _tmp,
            mut arch,
        } = create_test_archive().expect("Failed to create test archive.");

        fill_test_archive(&mut arch);
    }

    #[test]
    fn test_remove_file() {
        let TestArchive {
            tmp: _tmp,
            mut arch,
        } = create_test_archive().expect("Failed to create test archive.");

        fill_test_archive(&mut arch);

        let site = StationNumber::from(727730); // Station number for KMSO
        let init_time = NaiveDate::from_ymd(2017, 4, 1).and_hms(6, 0, 0);
        let model = Model::GFS;

        assert!(arch
            .file_exists(site, model, init_time)
            .expect("Error checking db"));
        arch.remove(site, model, init_time)
            .expect("Error while removing.");
        assert!(!arch
            .file_exists(site, model, init_time)
            .expect("Error checking db"));
    }

    #[test]
    fn test_remove_site() {
        let TestArchive {
            tmp: _tmp,
            mut arch,
        } = create_test_archive().expect("Failed to create test archive.");

        fill_test_archive(&mut arch);

        let station_num = StationNumber::from(727730); // Station number for KMSO
        let init_time_model_pairs = [
            (NaiveDate::from_ymd(2017, 4, 1).and_hms(0, 0, 0), Model::NAM),
            (NaiveDate::from_ymd(2017, 4, 1).and_hms(6, 0, 0), Model::GFS),
            (
                NaiveDate::from_ymd(2017, 4, 1).and_hms(12, 0, 0),
                Model::GFS,
            ),
            (
                NaiveDate::from_ymd(2017, 4, 1).and_hms(12, 0, 0),
                Model::NAM,
            ),
            (
                NaiveDate::from_ymd(2017, 4, 1).and_hms(18, 0, 0),
                Model::GFS,
            ),
            (
                NaiveDate::from_ymd(2017, 4, 1).and_hms(18, 0, 0),
                Model::NAM,
            ),
        ];

        for &(init_time, model) in &init_time_model_pairs {
            assert!(arch
                .file_exists(station_num, model, init_time)
                .expect("Error checking db"));
        }

        arch.remove_site(station_num).expect("db error deleting.");

        for &(init_time, model) in &init_time_model_pairs {
            assert!(!arch
                .file_exists(station_num, model, init_time)
                .expect("Error checking db"));
        }
    }
}