use core::fmt;
use core::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;
use wire_mesh_wire::DecodeError;
use wire_mesh_wire::identity::DeviceId;
use wire_mesh_wire::minicbor::{Decode, Decoder, Encode, Encoder};
use wire_mesh_wire::strict;
pub const DOMAIN_ID: &str = "exadev.io/gitiverse";
pub const CAP_READ: &str = "exadev.io/gitiverse:read";
pub const CAP_WRITE: &str = "exadev.io/gitiverse:write";
pub const CAP_MAINTAIN: &str = "exadev.io/gitiverse:maintain";
pub const CAP_CI: &str = "exadev.io/gitiverse:ci";
pub const REPO_ID_PREFIX: &str = "gitiverse:";
const ID_BYTE_LEN: usize = 32;
const ID_HEX_LEN: usize = ID_BYTE_LEN * 2;
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum IdParseError {
#[error("repository identifier must start with 'gitiverse:'")]
MissingPrefix,
#[error("expected {expected} lowercase hex characters, found {found}")]
InvalidHexLength { expected: usize, found: usize },
#[error("identifier contains non-hex or uppercase characters")]
InvalidHex,
}
fn parse_lowercase_hex_32(s: &str) -> Result<[u8; ID_BYTE_LEN], IdParseError> {
if s.len() != ID_HEX_LEN {
return Err(IdParseError::InvalidHexLength {
expected: ID_HEX_LEN,
found: s.len(),
});
}
if !s
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
{
return Err(IdParseError::InvalidHex);
}
let decoded = hex::decode(s).map_err(|_| IdParseError::InvalidHex)?;
let arr: [u8; ID_BYTE_LEN] =
decoded
.try_into()
.map_err(|v: Vec<u8>| IdParseError::InvalidHexLength {
expected: ID_HEX_LEN,
found: v.len() * 2,
})?;
Ok(arr)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RepoId(pub [u8; ID_BYTE_LEN]);
impl RepoId {
pub const SIZE: usize = ID_BYTE_LEN;
#[must_use]
pub const fn from_bytes(bytes: [u8; ID_BYTE_LEN]) -> Self {
Self(bytes)
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; ID_BYTE_LEN] {
&self.0
}
#[must_use]
pub fn to_hex(&self) -> String {
hex::encode(self.0)
}
pub fn from_hex(hex_str: &str) -> Result<Self, IdParseError> {
parse_lowercase_hex_32(hex_str).map(Self)
}
}
impl AsRef<[u8]> for RepoId {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl fmt::Display for RepoId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{REPO_ID_PREFIX}{}", self.to_hex())
}
}
impl FromStr for RepoId {
type Err = IdParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let hex_part = s
.strip_prefix(REPO_ID_PREFIX)
.ok_or(IdParseError::MissingPrefix)?;
Self::from_hex(hex_part)
}
}
impl Serialize for RepoId {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for RepoId {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
Self::from_str(&s).map_err(serde::de::Error::custom)
}
}
impl Encode<()> for RepoId {
fn encode<W: wire_mesh_wire::minicbor::encode::Write>(
&self,
e: &mut Encoder<W>,
_ctx: &mut (),
) -> Result<(), wire_mesh_wire::minicbor::encode::Error<W::Error>> {
e.bytes(&self.0)?.ok()
}
}
impl Decode<'_, ()> for RepoId {
fn decode(
d: &mut Decoder<'_>,
_ctx: &mut (),
) -> Result<Self, wire_mesh_wire::minicbor::decode::Error> {
decode_repo_id(d).map_err(wire_mesh_wire::minicbor::decode::Error::custom)
}
}
pub(crate) fn decode_repo_id(d: &mut Decoder<'_>) -> Result<RepoId, DecodeError> {
let bytes = strict::bytes_value(d)?;
let arr: [u8; ID_BYTE_LEN] =
bytes
.try_into()
.map_err(|v: Vec<u8>| DecodeError::InvalidLength {
field: "repo-id",
expected: ID_BYTE_LEN,
found: v.len(),
})?;
Ok(RepoId(arr))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ActorId(pub DeviceId);
impl ActorId {
pub const SIZE: usize = DeviceId::SIZE;
#[must_use]
pub const fn from_device_id(device_id: DeviceId) -> Self {
Self(device_id)
}
#[must_use]
pub const fn from_bytes(bytes: [u8; ID_BYTE_LEN]) -> Self {
Self(DeviceId(bytes))
}
#[must_use]
pub const fn as_device_id(&self) -> &DeviceId {
&self.0
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; ID_BYTE_LEN] {
&self.0.0
}
#[must_use]
pub fn to_hex(&self) -> String {
hex::encode(self.0.0)
}
pub fn from_hex(hex_str: &str) -> Result<Self, IdParseError> {
parse_lowercase_hex_32(hex_str).map(|arr| Self(DeviceId(arr)))
}
}
impl From<DeviceId> for ActorId {
fn from(value: DeviceId) -> Self {
Self(value)
}
}
impl From<ActorId> for DeviceId {
fn from(value: ActorId) -> Self {
value.0
}
}
impl AsRef<[u8]> for ActorId {
fn as_ref(&self) -> &[u8] {
&self.0.0
}
}
impl fmt::Display for ActorId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_hex())
}
}
impl FromStr for ActorId {
type Err = IdParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::from_hex(s)
}
}
impl Serialize for ActorId {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for ActorId {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
Self::from_str(&s).map_err(serde::de::Error::custom)
}
}
impl Encode<()> for ActorId {
fn encode<W: wire_mesh_wire::minicbor::encode::Write>(
&self,
e: &mut Encoder<W>,
ctx: &mut (),
) -> Result<(), wire_mesh_wire::minicbor::encode::Error<W::Error>> {
self.0.encode(e, ctx)
}
}
impl Decode<'_, ()> for ActorId {
fn decode(
d: &mut Decoder<'_>,
ctx: &mut (),
) -> Result<Self, wire_mesh_wire::minicbor::decode::Error> {
DeviceId::decode(d, ctx).map(Self)
}
}
pub mod serde_device_id {
use super::*;
pub fn serialize<S: Serializer>(id: &DeviceId, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&hex::encode(id.0))
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<DeviceId, D::Error> {
let s = String::deserialize(deserializer)?;
parse_lowercase_hex_32(&s)
.map(DeviceId)
.map_err(serde::de::Error::custom)
}
}
pub mod serde_identity_key {
use super::*;
use wire_mesh_wire::identity::IdentityKey;
#[derive(Serialize, Deserialize)]
struct WireIdentityKey<'a> {
alg: i64,
#[serde(borrow)]
public_key: &'a str,
}
#[derive(Serialize)]
struct WireIdentityKeyOwned {
alg: i64,
public_key: String,
}
pub fn serialize<S: Serializer>(key: &IdentityKey, serializer: S) -> Result<S::Ok, S::Error> {
let repr = WireIdentityKeyOwned {
alg: key.alg,
public_key: hex::encode(&key.public_key),
};
repr.serialize(serializer)
}
pub fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<IdentityKey, D::Error> {
let repr = WireIdentityKey::deserialize(deserializer)?;
if !repr
.public_key
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
{
return Err(serde::de::Error::custom("public_key must be lowercase hex"));
}
let public_key = hex::decode(repr.public_key).map_err(serde::de::Error::custom)?;
Ok(IdentityKey {
alg: repr.alg,
public_key,
})
}
}
pub mod serde_hex_bytes {
use super::*;
pub fn serialize<S: Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&hex::encode(bytes))
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
let s = String::deserialize(deserializer)?;
if !s
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
{
return Err(serde::de::Error::custom("expected lowercase hex string"));
}
hex::decode(&s).map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
use wire_mesh_wire::tokens::CapabilityVerb;
use wire_mesh_wire::{decode_exact, to_vec};
#[test]
fn capability_verbs_pass_wire_mesh_grammar() {
for verb in [CAP_READ, CAP_WRITE, CAP_MAINTAIN, CAP_CI] {
assert_eq!(CapabilityVerb::validate(verb), Ok(()), "{verb}");
}
}
#[test]
fn repo_id_display_parse_and_cbor_round_trip() {
let id = RepoId::from_bytes([0xAB; 32]);
let formatted = id.to_string();
assert_eq!(formatted, format!("gitiverse:{}", "ab".repeat(32)));
assert_eq!(RepoId::from_str(&formatted).unwrap(), id);
let json = serde_json::to_string(&id).unwrap();
assert_eq!(serde_json::from_str::<RepoId>(&json).unwrap(), id);
let cbor = to_vec(&id);
assert_eq!(decode_exact::<RepoId>(&cbor).unwrap(), id);
}
#[test]
fn repo_id_rejects_malformed_inputs() {
let valid_hex = "ab".repeat(32);
assert_eq!(
RepoId::from_str(&valid_hex),
Err(IdParseError::MissingPrefix)
);
assert_eq!(
RepoId::from_str(&format!("gitiverse:{}", "AB".repeat(32))),
Err(IdParseError::InvalidHex)
);
assert_eq!(
RepoId::from_str("gitiverse:abcd"),
Err(IdParseError::InvalidHexLength {
expected: 64,
found: 4,
})
);
}
#[test]
fn actor_id_round_trips_text_json_and_cbor() {
let actor = ActorId::from_bytes([0x42; 32]);
let text = actor.to_string();
assert_eq!(text, "42".repeat(32));
assert_eq!(ActorId::from_str(&text).unwrap(), actor);
assert_eq!(
ActorId::from_str(&"42".repeat(31)),
Err(IdParseError::InvalidHexLength {
expected: 64,
found: 62
})
);
let json = serde_json::to_string(&actor).unwrap();
assert_eq!(serde_json::from_str::<ActorId>(&json).unwrap(), actor);
let cbor = to_vec(&actor);
assert_eq!(decode_exact::<ActorId>(&cbor).unwrap(), actor);
}
}