upend/base/src/entry.rs

250 lines
7.5 KiB
Rust

use crate::addressing::{Address, Addressable};
use crate::error::UpEndError;
use crate::hash::{b58_decode, sha256hash, AsMultihash, AsMultihashError, UpMultihash};
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::io::{Cursor, Write};
use url::Url;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Entry {
pub entity: Address,
pub attribute: String,
pub value: EntryValue,
pub provenance: String,
pub timestamp: NaiveDateTime,
}
#[derive(Debug, Clone)]
pub struct ImmutableEntry(pub Entry);
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InvariantEntry {
pub attribute: String,
pub value: EntryValue,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "t", content = "c")]
pub enum EntryValue {
Address(Address),
Number(f64),
Null,
}
impl Default for Entry {
fn default() -> Self {
Self {
entity: Address::Uuid(uuid::Uuid::nil()),
attribute: Default::default(),
value: EntryValue::Null,
provenance: "SYSTEM".into(),
timestamp: NaiveDateTime::from_timestamp_opt(0, 0).unwrap(),
}
}
}
impl TryFrom<&InvariantEntry> for Entry {
type Error = UpEndError;
fn try_from(invariant: &InvariantEntry) -> Result<Self, Self::Error> {
Ok(Entry {
entity: invariant.entity()?,
attribute: invariant.attribute.clone(),
value: invariant.value.clone(),
provenance: "INVARIANT".to_string(),
..Default::default()
})
}
}
impl InvariantEntry {
pub fn entity(&self) -> Result<Address, UpEndError> {
let mut entity = Cursor::new(vec![0u8; 0]);
entity
.write_all(self.attribute.as_bytes())
.map_err(UpEndError::from_any)?;
entity
.write_all(self.value.to_string().as_bytes())
.map_err(UpEndError::from_any)?;
Ok(Address::Hash(
sha256hash(entity.into_inner()).map_err(UpEndError::from_any)?,
))
}
}
impl std::fmt::Display for Entry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} | {} | {}", self.entity, self.attribute, self.value)
}
}
impl AsMultihash for Entry {
fn as_multihash(&self) -> Result<UpMultihash, AsMultihashError> {
let mut result = Cursor::new(vec![0u8; 0]);
result.write_all(
self.entity
.encode()
.map_err(|e| AsMultihashError(e.to_string()))?
.as_slice(),
)?;
result.write_all(self.attribute.as_bytes())?;
result.write_all(self.value.to_string().as_bytes())?;
sha256hash(result.get_ref())
}
}
impl AsMultihash for InvariantEntry {
fn as_multihash(&self) -> Result<UpMultihash, AsMultihashError> {
Entry::try_from(self)
.map_err(|e| AsMultihashError(e.to_string()))?
.as_multihash()
}
}
impl EntryValue {
pub fn to_string(&self) -> String {
let (type_char, content) = match self {
EntryValue::Address(address) => ('O', address.to_string()),
EntryValue::Number(n) => ('N', n.to_string()),
EntryValue::Null => ('X', "".to_string()),
};
format!("{}{}", type_char, content)
}
pub fn guess_from<S: AsRef<str>>(string: S) -> Result<Self, UpEndError> {
let string = string.as_ref();
match string.parse::<f64>() {
Ok(num) => Ok(EntryValue::Number(num)),
Err(_) => {
if let Ok(url) = Url::parse(string) {
Ok(EntryValue::Address(Address::Url(url)))
} else {
Ok(EntryValue::Address(string.address()?))
}
}
}
}
}
impl std::str::FromStr for EntryValue {
type Err = UpEndError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.len() < 2 {
match s.chars().next() {
Some('X') => Ok(EntryValue::Null),
_ => Err(UpEndError::EntryValueInvalid(s.to_string())),
}
} else {
let (type_char, content) = s.split_at(1);
match (type_char, content) {
("N", content) => {
if let Ok(n) = content.parse::<f64>() {
Ok(EntryValue::Number(n))
} else {
Err(UpEndError::EntryValueInvalid(s.to_string()))
}
}
("O", content) => {
if let Ok(addr) = b58_decode(content).and_then(|v| Address::decode(&v)) {
Ok(EntryValue::Address(addr))
} else {
Err(UpEndError::EntryValueInvalid(s.to_string()))
}
}
_ => Err(UpEndError::EntryValueInvalid(s.to_string())),
}
}
}
}
impl From<Url> for EntryValue {
fn from(value: Url) -> Self {
EntryValue::Address(Address::Url(value))
}
}
impl std::fmt::Display for EntryValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (entry_type, entry_value) = match self {
EntryValue::Address(address) => ("ADDRESS", address.to_string()),
EntryValue::Number(n) => ("NUMBER", n.to_string()),
EntryValue::Null => ("NULL", "NULL".to_string()),
};
write!(f, "{}: {}", entry_type, entry_value)
}
}
impl From<f64> for EntryValue {
fn from(num: f64) -> Self {
Self::Number(num)
}
}
impl From<Address> for EntryValue {
fn from(address: Address) -> Self {
Self::Address(address)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_value_from_to_string() -> Result<(), UpEndError> {
let entry = EntryValue::Address("hello".address().unwrap());
let encoded = entry.to_string();
let decoded = encoded.parse::<EntryValue>().unwrap();
assert_eq!(entry, decoded);
let entry = EntryValue::Number(1337.93);
let encoded = entry.to_string();
let decoded = encoded.parse::<EntryValue>().unwrap();
assert_eq!(entry, decoded);
let entry = EntryValue::Address(Address::Url(Url::parse("https://upend.dev").unwrap()));
let encoded = entry.to_string();
let decoded = encoded.parse::<EntryValue>().unwrap();
assert_eq!(entry, decoded);
let entry = EntryValue::Address("".address().unwrap());
let encoded = entry.to_string();
let decoded = encoded.parse::<EntryValue>().unwrap();
assert_eq!(entry, decoded);
let entry = EntryValue::Null;
let encoded = entry.to_string();
let decoded = encoded.parse::<EntryValue>().unwrap();
assert_eq!(entry, decoded);
Ok(())
}
#[test]
fn test_into() {
assert_eq!(EntryValue::Number(1337.93), 1337.93.into());
let addr = Address::Url(Url::parse("https://upend.dev").unwrap());
assert_eq!(EntryValue::Address(addr.clone()), addr.into());
}
#[test]
fn test_guess_value() {
assert_eq!(
EntryValue::guess_from("UPEND").unwrap(),
EntryValue::Address("UPEND".address().unwrap())
);
assert_eq!(
EntryValue::guess_from("1337.93").unwrap(),
EntryValue::Number(1337.93)
);
assert_eq!(
EntryValue::guess_from("https://upend.dev").unwrap(),
EntryValue::Address(Address::Url(Url::parse("https://upend.dev").unwrap()))
);
}
}