2023-02-11 17:59:15 +00:00
|
|
|
/*
|
|
|
|
Copyright 2020-2023, Savanni D'Gerinel <savanni@luminescent-dreams.com>
|
|
|
|
|
|
|
|
This file is part of the Luminescent Dreams Tools.
|
|
|
|
|
|
|
|
Luminescent Dreams Tools is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
|
|
|
|
|
|
|
Luminescent Dreams Tools is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
|
|
|
|
|
|
|
You should have received a copy of the GNU General Public License along with Lumeto. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
*/
|
|
|
|
|
2022-04-20 13:01:39 +00:00
|
|
|
extern crate serde;
|
|
|
|
extern crate serde_json;
|
|
|
|
extern crate uuid;
|
|
|
|
|
|
|
|
use serde::de::DeserializeOwned;
|
|
|
|
use serde::ser::Serialize;
|
|
|
|
use std::cmp::Ordering;
|
|
|
|
use std::collections::HashMap;
|
2023-12-27 21:13:47 +00:00
|
|
|
use std::convert::TryFrom;
|
2022-04-20 13:01:39 +00:00
|
|
|
use std::fs::File;
|
|
|
|
use std::fs::OpenOptions;
|
|
|
|
use std::io::{BufRead, BufReader, LineWriter, Write};
|
|
|
|
use std::iter::Iterator;
|
|
|
|
|
|
|
|
use criteria::Criteria;
|
2023-12-26 17:33:52 +00:00
|
|
|
use types::{EmseriesReadError, EmseriesWriteError, Record, RecordId, Recordable};
|
2022-04-20 13:01:39 +00:00
|
|
|
|
2023-12-27 21:13:47 +00:00
|
|
|
// A RecordOnDisk, a private data structure, is useful for handling all of the on-disk
|
|
|
|
// representations of a record. Unlike [Record], this one can accept an empty data value to
|
|
|
|
// represent that the data may have been deleted. This is not made public because, so far as the
|
|
|
|
// user is concerned, any record in the system must have data associated with it.
|
|
|
|
#[derive(Clone, Deserialize, Serialize)]
|
|
|
|
struct RecordOnDisk<T: Clone + Recordable> {
|
|
|
|
id: RecordId,
|
|
|
|
data: Option<T>,
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
impl<T> FromStr for RecordOnDisk<T>
|
|
|
|
where
|
|
|
|
T: Clone + Recordable + DeserializeOwned + Serialize,
|
|
|
|
{
|
|
|
|
type Err = EmseriesReadError;
|
|
|
|
|
|
|
|
fn from_str(line: &str) -> Result<Self, Self::Err> {
|
|
|
|
serde_json::from_str(line).map_err(EmseriesReadError::JSONParseError)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
*/
|
|
|
|
|
|
|
|
impl<T: Clone + Recordable> TryFrom<RecordOnDisk<T>> for Record<T> {
|
|
|
|
type Error = EmseriesReadError;
|
|
|
|
|
|
|
|
fn try_from(disk_record: RecordOnDisk<T>) -> Result<Self, Self::Error> {
|
|
|
|
match disk_record.data {
|
|
|
|
Some(data) => Ok(Record {
|
|
|
|
id: disk_record.id,
|
|
|
|
data,
|
|
|
|
}),
|
|
|
|
None => Err(Self::Error::RecordDeleted(disk_record.id)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-20 13:01:39 +00:00
|
|
|
/// An open time series database.
|
|
|
|
///
|
|
|
|
/// Any given database can store only one data type, T. The data type must be determined when the
|
|
|
|
/// database is opened.
|
|
|
|
pub struct Series<T: Clone + Recordable + DeserializeOwned + Serialize> {
|
|
|
|
//path: String,
|
|
|
|
writer: LineWriter<File>,
|
2023-12-27 21:13:47 +00:00
|
|
|
records: HashMap<RecordId, Record<T>>,
|
2022-04-20 13:01:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> Series<T>
|
|
|
|
where
|
|
|
|
T: Clone + Recordable + DeserializeOwned + Serialize,
|
|
|
|
{
|
|
|
|
/// Open a time series database at the specified path. `path` is the full path and filename for
|
|
|
|
/// the database.
|
2023-12-07 04:32:33 +00:00
|
|
|
pub fn open<P: AsRef<std::path::Path>>(path: P) -> Result<Series<T>, EmseriesReadError> {
|
2022-04-20 13:01:39 +00:00
|
|
|
let f = OpenOptions::new()
|
|
|
|
.read(true)
|
|
|
|
.append(true)
|
|
|
|
.create(true)
|
2023-10-05 15:19:55 +00:00
|
|
|
.open(path)
|
2022-04-20 13:01:39 +00:00
|
|
|
.map_err(EmseriesReadError::IOError)?;
|
|
|
|
|
|
|
|
let records = Series::load_file(&f)?;
|
|
|
|
|
|
|
|
let writer = LineWriter::new(f);
|
|
|
|
|
|
|
|
Ok(Series {
|
|
|
|
//path: String::from(path),
|
|
|
|
writer,
|
|
|
|
records,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Load a file and return all of the records in it.
|
2023-12-27 21:13:47 +00:00
|
|
|
fn load_file(f: &File) -> Result<HashMap<RecordId, Record<T>>, EmseriesReadError> {
|
|
|
|
let mut records: HashMap<RecordId, Record<T>> = HashMap::new();
|
2022-04-20 13:01:39 +00:00
|
|
|
let reader = BufReader::new(f);
|
|
|
|
for line in reader.lines() {
|
|
|
|
match line {
|
|
|
|
Ok(line_) => {
|
2023-12-27 21:13:47 +00:00
|
|
|
match serde_json::from_str::<RecordOnDisk<T>>(line_.as_ref())
|
|
|
|
.map_err(EmseriesReadError::JSONParseError)
|
2024-01-20 19:35:10 +00:00
|
|
|
.and_then(Record::try_from)
|
2023-12-27 21:13:47 +00:00
|
|
|
{
|
|
|
|
Ok(record) => records.insert(record.id.clone(), record.clone()),
|
|
|
|
Err(EmseriesReadError::RecordDeleted(id)) => records.remove(&id),
|
2022-04-20 13:01:39 +00:00
|
|
|
Err(err) => return Err(err),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
Err(err) => return Err(EmseriesReadError::IOError(err)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(records)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Put a new record into the database. A unique id will be assigned to the record and
|
|
|
|
/// returned.
|
2023-12-26 17:33:52 +00:00
|
|
|
pub fn put(&mut self, entry: T) -> Result<RecordId, EmseriesWriteError> {
|
|
|
|
let uuid = RecordId::default();
|
2023-12-27 21:13:47 +00:00
|
|
|
let record = Record {
|
|
|
|
id: uuid.clone(),
|
|
|
|
data: entry,
|
|
|
|
};
|
|
|
|
self.update(record)?;
|
|
|
|
Ok(uuid)
|
2022-04-20 13:01:39 +00:00
|
|
|
}
|
|
|
|
|
2023-12-26 17:33:52 +00:00
|
|
|
/// Update an existing record. The [RecordId] of the record passed into this function must match
|
|
|
|
/// the [RecordId] of a record already in the database.
|
2023-12-27 21:13:47 +00:00
|
|
|
pub fn update(&mut self, record: Record<T>) -> Result<(), EmseriesWriteError> {
|
|
|
|
self.records.insert(record.id.clone(), record.clone());
|
|
|
|
let write_res = match serde_json::to_string(&RecordOnDisk {
|
|
|
|
id: record.id,
|
|
|
|
data: Some(record.data),
|
2022-04-20 13:01:39 +00:00
|
|
|
}) {
|
|
|
|
Ok(rec_str) => self
|
|
|
|
.writer
|
|
|
|
.write_fmt(format_args!("{}\n", rec_str.as_str()))
|
|
|
|
.map_err(EmseriesWriteError::IOError),
|
|
|
|
Err(err) => Err(EmseriesWriteError::JSONWriteError(err)),
|
|
|
|
};
|
|
|
|
|
|
|
|
match write_res {
|
|
|
|
Ok(_) => Ok(()),
|
|
|
|
Err(err) => Err(err),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Delete a record from the database
|
|
|
|
///
|
|
|
|
/// Future note: while this deletes a record from the view, it only adds an entry to the
|
|
|
|
/// database that indicates `data: null`. If record histories ever become important, the record
|
|
|
|
/// and its entire history (including this delete) will still be available.
|
2023-12-26 17:33:52 +00:00
|
|
|
pub fn delete(&mut self, uuid: &RecordId) -> Result<(), EmseriesWriteError> {
|
2022-04-20 13:01:39 +00:00
|
|
|
if !self.records.contains_key(uuid) {
|
|
|
|
return Ok(());
|
|
|
|
};
|
|
|
|
self.records.remove(uuid);
|
|
|
|
|
2023-12-27 21:13:47 +00:00
|
|
|
let rec: RecordOnDisk<T> = RecordOnDisk {
|
2022-04-20 13:01:39 +00:00
|
|
|
id: uuid.clone(),
|
|
|
|
data: None,
|
|
|
|
};
|
|
|
|
match serde_json::to_string(&rec) {
|
|
|
|
Ok(rec_str) => self
|
|
|
|
.writer
|
|
|
|
.write_fmt(format_args!("{}\n", rec_str.as_str()))
|
|
|
|
.map_err(EmseriesWriteError::IOError),
|
|
|
|
Err(err) => Err(EmseriesWriteError::JSONWriteError(err)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get all of the records in the database.
|
2023-12-27 21:13:47 +00:00
|
|
|
pub fn records(&self) -> impl Iterator<Item = &Record<T>> {
|
|
|
|
self.records.values()
|
2022-04-20 13:01:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/* The point of having Search is so that a lot of internal optimizations can happen once the
|
|
|
|
* data sets start getting large. */
|
|
|
|
/// Perform a search on the records in a database, based on the given criteria.
|
|
|
|
pub fn search<'s>(
|
|
|
|
&'s self,
|
|
|
|
criteria: impl Criteria + 's,
|
2023-12-27 21:13:47 +00:00
|
|
|
) -> impl Iterator<Item = &'s Record<T>> + 's {
|
|
|
|
self.records().filter(move |&tr| criteria.apply(&tr.data))
|
2022-04-20 13:01:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Perform a search and sort the resulting records based on the comparison.
|
2023-12-27 21:13:47 +00:00
|
|
|
pub fn search_sorted<'s, C, CMP>(&'s self, criteria: C, compare: CMP) -> Vec<&'s Record<T>>
|
2022-04-20 13:01:39 +00:00
|
|
|
where
|
|
|
|
C: Criteria + 's,
|
2023-12-27 21:13:47 +00:00
|
|
|
CMP: FnMut(&&Record<T>, &&Record<T>) -> Ordering,
|
2022-04-20 13:01:39 +00:00
|
|
|
{
|
|
|
|
let search_iter = self.search(criteria);
|
2023-12-27 21:13:47 +00:00
|
|
|
let mut records: Vec<&Record<T>> = search_iter.collect();
|
2022-04-20 13:01:39 +00:00
|
|
|
records.sort_by(compare);
|
|
|
|
records
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get an exact record from the database based on unique id.
|
2023-12-27 21:13:47 +00:00
|
|
|
pub fn get(&self, uuid: &RecordId) -> Option<Record<T>> {
|
2023-10-05 15:19:55 +00:00
|
|
|
self.records.get(uuid).cloned()
|
2022-04-20 13:01:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
2023-12-26 17:33:52 +00:00
|
|
|
pub fn remove(&self, uuid: RecordId) -> Result<(), EmseriesError> {
|
2022-04-20 13:01:39 +00:00
|
|
|
unimplemented!()
|
|
|
|
}
|
|
|
|
*/
|
|
|
|
}
|