use std::collections::BTreeMap;
use thiserror::Error;
use crate::cbor::{self, Value};
use crate::{CanonError, Cid, CidError};
#[derive(Debug, Error, PartialEq, Eq, Clone)]
#[non_exhaustive]
pub enum ObjectError {
#[error(transparent)]
Canonical(#[from] CanonError),
#[error("an object must be a map, found {found}")]
NotAMap {
found: &'static str,
},
#[error("missing required field `{field}`")]
MissingField {
field: &'static str,
},
#[error("field `{field}` must be {expected}")]
WrongType {
field: &'static str,
expected: &'static str,
},
#[error("unsupported protocol version {found}; this build implements {expected}")]
UnsupportedVersion {
found: String,
expected: &'static str,
},
#[error("unknown top-level field `{field}`; extensions belong in `ext`")]
UnknownField {
field: String,
},
#[error("field `{field}`: {source}")]
BadCid {
field: &'static str,
#[source]
source: CidError,
},
#[error("identifier mismatch: bytes hash to {actual}, not {expected}")]
IdentifierMismatch {
expected: String,
actual: String,
},
}
pub const PROTOCOL_VERSION: &str = "1";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Object {
protocol: String,
kind: String,
created: String,
author: Cid,
body: BTreeMap<String, Value>,
prev: Option<Cid>,
basis: Option<Cid>,
ext: Option<BTreeMap<String, Value>>,
bytes: Vec<u8>,
}
const HEADER_FIELDS: [&str; 8] = [
"author", "basis", "body", "created", "ext", "prev", "pub", "type",
];
impl Object {
pub fn parse(bytes: &[u8]) -> Result<Unverified<Self>, ObjectError> {
let value = cbor::decode(bytes)?;
let Value::Map(map) = value else {
return Err(ObjectError::NotAMap {
found: describe(&value),
});
};
for key in map.keys() {
if !HEADER_FIELDS.contains(&key.as_str()) {
return Err(ObjectError::UnknownField { field: key.clone() });
}
}
let protocol = text_field(&map, "pub")?;
if protocol != PROTOCOL_VERSION {
return Err(ObjectError::UnsupportedVersion {
found: protocol,
expected: PROTOCOL_VERSION,
});
}
let object = Self {
protocol,
kind: text_field(&map, "type")?,
created: text_field(&map, "created")?,
author: cid_field(&map, "author")?,
body: match map.get("body") {
Some(Value::Map(m)) => m.clone(),
Some(_) => {
return Err(ObjectError::WrongType {
field: "body",
expected: "a map",
});
}
None => return Err(ObjectError::MissingField { field: "body" }),
},
prev: match map.get("prev") {
Some(_) => Some(cid_field(&map, "prev")?),
None => None,
},
basis: match map.get("basis") {
Some(_) => Some(cid_field(&map, "basis")?),
None => None,
},
ext: match map.get("ext") {
Some(Value::Map(m)) => Some(m.clone()),
Some(_) => {
return Err(ObjectError::WrongType {
field: "ext",
expected: "a map",
});
}
None => None,
},
bytes: bytes.to_vec(),
};
Ok(Unverified(object))
}
#[must_use]
pub fn builder(kind: &str, author: &str) -> Builder {
Builder {
kind: kind.to_owned(),
author: author.to_owned(),
protocol: "1".to_owned(),
created: None,
body: BTreeMap::new(),
prev: None,
basis: None,
ext: None,
}
}
#[must_use]
pub fn protocol(&self) -> &str {
&self.protocol
}
#[must_use]
pub fn kind(&self) -> &str {
&self.kind
}
#[must_use]
pub fn created(&self) -> &str {
&self.created
}
#[must_use]
pub fn author(&self) -> &Cid {
&self.author
}
#[must_use]
pub fn body(&self) -> &BTreeMap<String, Value> {
&self.body
}
#[must_use]
pub fn prev(&self) -> Option<&Cid> {
self.prev.as_ref()
}
#[must_use]
pub fn basis(&self) -> Option<&Cid> {
self.basis.as_ref()
}
#[must_use]
pub fn ext(&self) -> Option<&BTreeMap<String, Value>> {
self.ext.as_ref()
}
#[must_use]
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unverified<T>(T);
impl Unverified<Object> {
pub fn verify(self, expected: &Cid) -> Result<Verified<Object>, ObjectError> {
if expected.verifies(&self.0.bytes) {
Ok(Verified(self.0))
} else {
Err(ObjectError::IdentifierMismatch {
expected: expected.to_string(),
actual: Cid::of(&self.0.bytes, expected.alg()).to_string(),
})
}
}
#[must_use]
pub fn peek(&self) -> &Object {
&self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Verified<T>(T);
impl Verified<Object> {
#[must_use]
pub fn object(&self) -> &Object {
&self.0
}
#[must_use]
pub fn into_inner(self) -> Object {
self.0
}
}
#[derive(Debug, Clone)]
pub struct Builder {
kind: String,
author: String,
protocol: String,
created: Option<String>,
body: BTreeMap<String, Value>,
prev: Option<String>,
basis: Option<String>,
ext: Option<BTreeMap<String, Value>>,
}
impl Builder {
#[must_use]
pub fn created(mut self, when: &str) -> Self {
self.created = Some(when.to_owned());
self
}
#[must_use]
pub fn field(mut self, key: &str, value: Value) -> Self {
self.body.insert(key.to_owned(), value);
self
}
#[must_use]
pub fn prev(mut self, cid: &str) -> Self {
self.prev = Some(cid.to_owned());
self
}
#[must_use]
pub fn basis(mut self, cid: &str) -> Self {
self.basis = Some(cid.to_owned());
self
}
pub fn build(self) -> Result<Vec<u8>, ObjectError> {
let created = self
.created
.ok_or(ObjectError::MissingField { field: "created" })?;
let author: Cid = self.author.parse().map_err(|source| ObjectError::BadCid {
field: "author",
source,
})?;
let mut map = BTreeMap::new();
map.insert("author".to_owned(), Value::Text(author.to_string()));
map.insert("body".to_owned(), Value::Map(self.body));
map.insert("created".to_owned(), Value::Text(created));
map.insert("pub".to_owned(), Value::Text(self.protocol));
map.insert("type".to_owned(), Value::Text(self.kind));
if let Some(prev) = self.prev {
let parsed: Cid = prev.parse().map_err(|source| ObjectError::BadCid {
field: "prev",
source,
})?;
map.insert("prev".to_owned(), Value::Text(parsed.to_string()));
}
if let Some(basis) = self.basis {
let parsed: Cid = basis.parse().map_err(|source| ObjectError::BadCid {
field: "basis",
source,
})?;
map.insert("basis".to_owned(), Value::Text(parsed.to_string()));
}
if let Some(ext) = self.ext {
map.insert("ext".to_owned(), Value::Map(ext));
}
Ok(cbor::encode(&Value::Map(map)))
}
}
fn describe(value: &Value) -> &'static str {
match value {
Value::Uint(_) | Value::Nint(_) => "an integer",
Value::Bytes(_) => "a byte string",
Value::Text(_) => "a text string",
Value::Array(_) => "an array",
Value::Map(_) => "a map",
Value::Bool(_) => "a boolean",
Value::Null => "null",
}
}
fn text_field(map: &BTreeMap<String, Value>, field: &'static str) -> Result<String, ObjectError> {
match map.get(field) {
Some(Value::Text(s)) => Ok(s.clone()),
Some(_) => Err(ObjectError::WrongType {
field,
expected: "a text string",
}),
None => Err(ObjectError::MissingField { field }),
}
}
fn cid_field(map: &BTreeMap<String, Value>, field: &'static str) -> Result<Cid, ObjectError> {
let text = text_field(map, field)?;
text.parse()
.map_err(|source| ObjectError::BadCid { field, source })
}