mod types;
use std::collections::HashMap;
use std::fmt;
use crate::proto::com::arcadedb::grpc::{grpc_value::Kind, GrpcMap, GrpcRecord, GrpcValue};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RecordDecodeError {
MissingField {
path: String,
},
TypeMismatch {
path: String,
expected: &'static str,
actual: &'static str,
},
Conversion { message: String },
}
impl RecordDecodeError {
pub fn missing_field(field: &str) -> Self {
Self::MissingField {
path: field.to_string(),
}
}
pub fn type_mismatch(expected: &'static str, actual: &'static str) -> Self {
Self::TypeMismatch {
path: String::new(),
expected,
actual,
}
}
pub fn conversion(message: impl Into<String>) -> Self {
Self::Conversion {
message: message.into(),
}
}
pub fn unknown_variant(variant: &str) -> Self {
Self::conversion(format!("unknown variant `{variant}`"))
}
pub fn with_field(self, field: &str) -> Self {
match self {
RecordDecodeError::MissingField { mut path } => {
if path.is_empty() {
path = field.to_string();
} else {
path = format!("{field}.{path}");
}
Self::MissingField { path }
}
RecordDecodeError::TypeMismatch {
mut path,
expected,
actual,
} => {
if path.is_empty() {
path = field.to_string();
} else {
path = format!("{field}.{path}");
}
Self::TypeMismatch {
path,
expected,
actual,
}
}
RecordDecodeError::Conversion { message } => Self::Conversion {
message: format!("field `{field}`: {message}"),
},
}
}
}
impl fmt::Display for RecordDecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RecordDecodeError::MissingField { path } => {
write!(f, "missing property `{path}`")
}
RecordDecodeError::TypeMismatch {
path,
expected,
actual,
} => {
if path.is_empty() {
write!(f, "expected {expected}, got {actual}")
} else {
write!(f, "property `{path}`: expected {expected}, got {actual}")
}
}
RecordDecodeError::Conversion { message } => f.write_str(message),
}
}
}
impl std::error::Error for RecordDecodeError {}
pub fn kind_name(kind: &Option<Kind>) -> &'static str {
match kind {
None => "null",
Some(Kind::BoolValue(_)) => "bool",
Some(Kind::Int32Value(_)) => "int32",
Some(Kind::Int64Value(_)) => "int64",
Some(Kind::FloatValue(_)) => "float",
Some(Kind::DoubleValue(_)) => "double",
Some(Kind::StringValue(_)) => "string",
Some(Kind::BytesValue(_)) => "bytes",
Some(Kind::TimestampValue(_)) => "timestamp",
Some(Kind::ListValue(_)) => "list",
Some(Kind::MapValue(_)) => "map",
Some(Kind::EmbeddedValue(_)) => "embedded",
Some(Kind::LinkValue(_)) => "link",
Some(Kind::DecimalValue(_)) => "decimal",
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Link {
pub bucket: i32,
pub pos: i64,
}
impl Link {
pub fn new(bucket: i32, pos: i64) -> Self {
Self { bucket, pos }
}
pub fn parse(s: &str) -> Result<Self, RecordDecodeError> {
let invalid = || RecordDecodeError::conversion(format!("invalid rid `{s}`"));
let (bucket, pos) = s
.strip_prefix('#')
.and_then(|body| body.split_once(':'))
.ok_or_else(invalid)?;
let bucket = bucket.parse::<i32>().map_err(|_| invalid())?;
let pos = pos.parse::<i64>().map_err(|_| invalid())?;
if bucket < 0 || pos < 0 {
return Err(invalid());
}
Ok(Self { bucket, pos })
}
pub fn to_rid_string(&self) -> String {
format!("#{}:{}", self.bucket, self.pos)
}
}
impl fmt::Display for Link {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{}:{}", self.bucket, self.pos)
}
}
impl std::str::FromStr for Link {
type Err = RecordDecodeError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse(s)
}
}
#[cfg(feature = "serde")]
mod link_serde {
use super::*;
impl serde::Serialize for Link {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_rid_string())
}
}
impl<'de> serde::Deserialize<'de> for Link {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
Self::parse(&s).map_err(serde::de::Error::custom)
}
}
}
pub trait FromGrpcValue<'de>: Sized {
fn from_grpc_value(value: &'de GrpcValue) -> Result<Self, RecordDecodeError>;
}
pub trait ToGrpcRecord {
const KEY_COLUMNS: &'static [&'static str] = &[];
fn props(&self) -> Vec<(&str, GrpcValue)>;
fn to_grpc_record(&self, class: &str) -> GrpcRecord {
crate::rec(class, self.props())
}
fn to_grpc_value(&self) -> GrpcValue {
GrpcValue {
kind: Some(Kind::MapValue(GrpcMap {
entries: self
.props()
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
})),
logical_type: String::new(),
}
}
fn to_param_map<M: FromIterator<(String, GrpcValue)>>(&self) -> M
where
Self: Sized,
{
self.props()
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect()
}
fn changed_wires(&self, other: &Self) -> Vec<String> {
props_diff(self, other)
.into_iter()
.map(|(k, _)| k)
.collect()
}
fn into_grpc_record(self, class: &str) -> GrpcRecord
where
Self: Sized,
{
self.to_grpc_record(class)
}
}
pub fn props_diff<T: ToGrpcRecord + ?Sized>(old: &T, new: &T) -> Vec<(String, GrpcValue)> {
let old_props_vec = old.props();
let old_props: HashMap<&str, &GrpcValue> = old_props_vec.iter().map(|(k, v)| (*k, v)).collect();
new.props()
.into_iter()
.filter(|(k, v)| old_props.get(*k) != Some(&v))
.map(|(k, v)| (k.to_string(), v))
.collect()
}
pub fn changed_param_map<M: FromIterator<(String, GrpcValue)>, T: ToGrpcRecord + ?Sized>(
old: &T,
new: &T,
) -> M {
props_diff(old, new).into_iter().collect()
}
pub trait DecodeFromMap<'de>: Sized {
fn from_map(
props: &'de HashMap<String, GrpcValue>,
taken: &[&str],
syn_rid: Option<&'de String>,
syn_type: Option<&'de String>,
) -> Result<Self, RecordDecodeError>;
}
pub fn from_map_via_value<T>(
props: &HashMap<String, GrpcValue>,
taken: &[&str],
) -> Result<T, RecordDecodeError>
where
T: for<'a> FromGrpcValue<'a>,
{
let rest: HashMap<String, GrpcValue> = props
.iter()
.filter(|(k, _)| !taken.contains(&k.as_str()))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let gv = crate::GrpcValue {
kind: Some(Kind::EmbeddedValue(crate::GrpcEmbedded {
fields: rest,
r#type: String::new(),
})),
logical_type: String::new(),
};
T::from_grpc_value(&gv)
}
#[doc(hidden)]
pub fn visible<'a>(
props: &'a HashMap<String, GrpcValue>,
key: &str,
taken: &[&str],
) -> Option<&'a GrpcValue> {
if taken.contains(&key) {
None
} else {
props.get(key)
}
}
pub fn get<'de, T: FromGrpcValue<'de>>(
props: &'de HashMap<String, GrpcValue>,
taken: &[&str],
key: &str,
) -> Result<T, RecordDecodeError> {
match visible(props, key, taken) {
Some(v) => T::from_grpc_value(v).map_err(|e| e.with_field(key)),
None => Err(RecordDecodeError::missing_field(key)),
}
}
pub fn get_opt<'de, T: FromGrpcValue<'de>>(
props: &'de HashMap<String, GrpcValue>,
taken: &[&str],
key: &str,
) -> Result<Option<T>, RecordDecodeError> {
match visible(props, key, taken) {
Some(v) => Option::<T>::from_grpc_value(v).map_err(|e| e.with_field(key)),
None => Ok(None),
}
}
pub fn get_or<'de, T: FromGrpcValue<'de>, F>(
props: &'de HashMap<String, GrpcValue>,
taken: &[&str],
key: &str,
def: F,
) -> Result<T, RecordDecodeError>
where
F: FnOnce() -> T,
{
match visible(props, key, taken) {
Some(v) => T::from_grpc_value(v).map_err(|e| e.with_field(key)),
None => Ok(def()),
}
}
pub fn get_with<T>(
props: &HashMap<String, GrpcValue>,
taken: &[&str],
key: &str,
f: fn(&GrpcValue) -> Result<T, RecordDecodeError>,
) -> Result<T, RecordDecodeError> {
match visible(props, key, taken) {
Some(v) => f(v).map_err(|e| e.with_field(key)),
None => Err(RecordDecodeError::missing_field(key)),
}
}
pub fn get_with_or<T>(
props: &HashMap<String, GrpcValue>,
taken: &[&str],
key: &str,
f: fn(&GrpcValue) -> Result<T, RecordDecodeError>,
def: impl FnOnce() -> T,
) -> Result<T, RecordDecodeError> {
match visible(props, key, taken) {
Some(v) => f(v).map_err(|e| e.with_field(key)),
None => Ok(def()),
}
}
pub fn get_opt_with<T>(
props: &HashMap<String, GrpcValue>,
taken: &[&str],
key: &str,
f: fn(&GrpcValue) -> Result<T, RecordDecodeError>,
) -> Result<Option<T>, RecordDecodeError> {
match visible(props, key, taken) {
Some(v) => match &v.kind {
None => Ok(None),
Some(_) => f(v).map(Some).map_err(|e| e.with_field(key)),
},
None => Ok(None),
}
}
pub fn get_bytes(
props: &HashMap<String, GrpcValue>,
taken: &[&str],
key: &str,
) -> Result<Vec<u8>, RecordDecodeError> {
match visible(props, key, taken) {
Some(v) => decode_bytes(v).map_err(|e| e.with_field(key)),
None => Err(RecordDecodeError::missing_field(key)),
}
}
pub fn get_opt_bytes(
props: &HashMap<String, GrpcValue>,
taken: &[&str],
key: &str,
) -> Result<Option<Vec<u8>>, RecordDecodeError> {
match visible(props, key, taken) {
Some(v) => match &v.kind {
None => Ok(None),
Some(_) => decode_bytes(v).map(Some).map_err(|e| e.with_field(key)),
},
None => Ok(None),
}
}
pub fn get_bytes_or(
props: &HashMap<String, GrpcValue>,
taken: &[&str],
key: &str,
def: impl FnOnce() -> Vec<u8>,
) -> Result<Vec<u8>, RecordDecodeError> {
match visible(props, key, taken) {
Some(v) => decode_bytes(v).map_err(|e| e.with_field(key)),
None => Ok(def()),
}
}
impl GrpcRecord {
pub fn get<'a, T: FromGrpcValue<'a>>(&'a self, key: &str) -> Result<T, RecordDecodeError> {
get(&self.properties, &[], key)
}
pub fn get_opt<'a, T: FromGrpcValue<'a>>(
&'a self,
key: &str,
) -> Result<Option<T>, RecordDecodeError> {
get_opt(&self.properties, &[], key)
}
pub fn get_or<'a, T: FromGrpcValue<'a>>(
&'a self,
key: &str,
default: T,
) -> Result<T, RecordDecodeError> {
get_or(&self.properties, &[], key, || default)
}
}
fn decode_bytes(v: &GrpcValue) -> Result<Vec<u8>, RecordDecodeError> {
match &v.kind {
Some(Kind::BytesValue(b)) => Ok(b.clone()),
Some(Kind::ListValue(l)) => {
l.values
.iter()
.map(|item| match &item.kind {
Some(Kind::Int32Value(n)) => u8::try_from(*n)
.map_err(|_| RecordDecodeError::type_mismatch("u8", "int32")),
Some(Kind::Int64Value(n)) => u8::try_from(*n)
.map_err(|_| RecordDecodeError::type_mismatch("u8", "int64")),
_ => Err(RecordDecodeError::type_mismatch(
"u8",
kind_name(&item.kind),
)),
})
.collect()
}
_ => Err(RecordDecodeError::type_mismatch(
"bytes",
kind_name(&v.kind),
)),
}
}