Add validated identifiers, Hash32, Timestamp and DataClass to proto
Implemented-By: Laguna S 2.1 (OpenCode)
This commit is contained in:
@@ -9,3 +9,7 @@ publish.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
humantime.workspace = true
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum DataClass {
|
||||
Public,
|
||||
Private,
|
||||
Secret,
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ValueError {
|
||||
SessionId,
|
||||
Hash32,
|
||||
Timestamp,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ValueError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ValueError::SessionId => write!(f, "invalid session id"),
|
||||
ValueError::Hash32 => write!(f, "invalid hash32"),
|
||||
ValueError::Timestamp => write!(f, "invalid timestamp"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ValueError {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(try_from = "String", into = "String")]
|
||||
pub struct SessionId(String);
|
||||
|
||||
impl SessionId {
|
||||
pub fn new(s: &str) -> Result<Self, ValueError> {
|
||||
if s.is_empty() || s.len() > 64 {
|
||||
return Err(ValueError::SessionId);
|
||||
}
|
||||
if !s
|
||||
.bytes()
|
||||
.all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'-'))
|
||||
{
|
||||
return Err(ValueError::SessionId);
|
||||
}
|
||||
Ok(SessionId(s.to_string()))
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<String> for SessionId {
|
||||
type Error = ValueError;
|
||||
|
||||
fn try_from(s: String) -> Result<Self, Self::Error> {
|
||||
SessionId::new(&s)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SessionId> for String {
|
||||
fn from(id: SessionId) -> String {
|
||||
id.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct Epoch(pub u32);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct CallId(pub u64);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(try_from = "String", into = "String")]
|
||||
pub struct Hash32([u8; 32]);
|
||||
|
||||
impl Hash32 {
|
||||
pub const ZERO: Hash32 = Hash32([0; 32]);
|
||||
|
||||
pub fn from_bytes(bytes: [u8; 32]) -> Self {
|
||||
Hash32(bytes)
|
||||
}
|
||||
|
||||
pub fn as_bytes(&self) -> &[u8; 32] {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn to_hex(&self) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut out = String::with_capacity(64);
|
||||
for &byte in &self.0 {
|
||||
out.push(char::from(HEX[usize::from(byte >> 4)]));
|
||||
out.push(char::from(HEX[usize::from(byte & 0x0f)]));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn from_hex(s: &str) -> Result<Self, ValueError> {
|
||||
if s.len() != 64 {
|
||||
return Err(ValueError::Hash32);
|
||||
}
|
||||
let mut out = [0u8; 32];
|
||||
for (i, pair) in s.as_bytes().chunks(2).enumerate() {
|
||||
let hi = hex_val(pair[0])?;
|
||||
let lo = hex_val(pair[1])?;
|
||||
out[i] = (hi << 4) | lo;
|
||||
}
|
||||
Ok(Hash32(out))
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<String> for Hash32 {
|
||||
type Error = ValueError;
|
||||
|
||||
fn try_from(s: String) -> Result<Self, Self::Error> {
|
||||
Hash32::from_hex(&s)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Hash32> for String {
|
||||
fn from(h: Hash32) -> String {
|
||||
h.to_hex()
|
||||
}
|
||||
}
|
||||
|
||||
fn hex_val(c: u8) -> Result<u8, ValueError> {
|
||||
match c {
|
||||
b'0'..=b'9' => Ok(c - b'0'),
|
||||
b'a'..=b'f' => Ok(c - b'a' + 10),
|
||||
_ => Err(ValueError::Hash32),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(try_from = "String", into = "String")]
|
||||
pub struct Timestamp(u64);
|
||||
|
||||
impl Timestamp {
|
||||
pub fn from_unix_millis(ms: u64) -> Self {
|
||||
Timestamp(ms)
|
||||
}
|
||||
|
||||
pub fn unix_millis(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub fn now() -> Self {
|
||||
let dur = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default();
|
||||
let ms = u64::try_from(dur.as_millis()).unwrap_or(u64::MAX);
|
||||
Timestamp(ms)
|
||||
}
|
||||
|
||||
pub fn to_rfc3339(&self) -> String {
|
||||
let t = std::time::UNIX_EPOCH
|
||||
.checked_add(std::time::Duration::from_millis(self.0))
|
||||
.unwrap_or(std::time::UNIX_EPOCH);
|
||||
humantime::format_rfc3339_millis(t).to_string()
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Result<Self, ValueError> {
|
||||
let t = humantime::parse_rfc3339(s).map_err(|_| ValueError::Timestamp)?;
|
||||
let dur = t
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_err(|_| ValueError::Timestamp)?;
|
||||
let ms = u64::try_from(dur.as_millis()).map_err(|_| ValueError::Timestamp)?;
|
||||
let parsed = Timestamp(ms);
|
||||
if parsed.to_rfc3339() != s {
|
||||
return Err(ValueError::Timestamp);
|
||||
}
|
||||
Ok(parsed)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<String> for Timestamp {
|
||||
type Error = ValueError;
|
||||
|
||||
fn try_from(s: String) -> Result<Self, Self::Error> {
|
||||
Timestamp::parse(&s)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Timestamp> for String {
|
||||
fn from(t: Timestamp) -> String {
|
||||
t.to_rfc3339()
|
||||
}
|
||||
}
|
||||
@@ -1 +1,7 @@
|
||||
//! Shared data types and the frame codec for Boxmaker. No policy and no I/O beyond frames.
|
||||
|
||||
pub mod class;
|
||||
pub mod ids;
|
||||
|
||||
pub use class::DataClass;
|
||||
pub use ids::{CallId, Epoch, Hash32, SessionId, Timestamp, ValueError};
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
//! Tests for identifiers and primitive values. Do not edit: these define the required behaviour.
|
||||
|
||||
use proto::{CallId, DataClass, Epoch, Hash32, SessionId, Timestamp, ValueError};
|
||||
|
||||
#[test]
|
||||
fn session_id_accepts_lowercase_digits_and_hyphen() {
|
||||
for ok in ["a", "mm-thread-42", "0", "a-b-c", &"x".repeat(64)] {
|
||||
assert_eq!(SessionId::new(ok).unwrap().as_str(), ok);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_id_rejects_everything_else() {
|
||||
let too_long = "x".repeat(65);
|
||||
for bad in [
|
||||
"",
|
||||
"A",
|
||||
"a b",
|
||||
"a/b",
|
||||
"../etc",
|
||||
"a.b",
|
||||
"a_b",
|
||||
"é",
|
||||
"a\n",
|
||||
too_long.as_str(),
|
||||
] {
|
||||
assert_eq!(
|
||||
SessionId::new(bad),
|
||||
Err(ValueError::SessionId),
|
||||
"accepted {bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_id_json_is_a_plain_string_and_is_validated() {
|
||||
let id = SessionId::new("mm-thread-42").unwrap();
|
||||
assert_eq!(serde_json::to_string(&id).unwrap(), r#""mm-thread-42""#);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<SessionId>(r#""mm-thread-42""#).unwrap(),
|
||||
id
|
||||
);
|
||||
assert!(serde_json::from_str::<SessionId>(r#""../etc""#).is_err());
|
||||
assert!(serde_json::from_str::<SessionId>("42").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn epoch_and_call_id_are_plain_numbers() {
|
||||
assert_eq!(serde_json::to_string(&Epoch(3)).unwrap(), "3");
|
||||
assert_eq!(
|
||||
serde_json::to_string(&CallId(18446744073709551615)).unwrap(),
|
||||
"18446744073709551615"
|
||||
);
|
||||
assert_eq!(serde_json::from_str::<CallId>("7").unwrap(), CallId(7));
|
||||
assert!(serde_json::from_str::<CallId>("-1").is_err());
|
||||
assert!(serde_json::from_str::<CallId>("1.5").is_err());
|
||||
assert!(serde_json::from_str::<Epoch>("4294967296").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash32_hex_round_trip() {
|
||||
let mut bytes = [0u8; 32];
|
||||
for (i, b) in bytes.iter_mut().enumerate() {
|
||||
*b = i as u8;
|
||||
}
|
||||
let h = Hash32::from_bytes(bytes);
|
||||
let hex = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
|
||||
assert_eq!(h.to_hex(), hex);
|
||||
assert_eq!(Hash32::from_hex(hex).unwrap(), h);
|
||||
assert_eq!(h.as_bytes(), &bytes);
|
||||
assert_eq!(serde_json::to_string(&h).unwrap(), format!("\"{hex}\""));
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Hash32>(&format!("\"{hex}\"")).unwrap(),
|
||||
h
|
||||
);
|
||||
assert_eq!(Hash32::ZERO.to_hex(), "0".repeat(64));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash32_rejects_wrong_length_uppercase_and_non_hex() {
|
||||
let upper = "000102030405060708090A0B0C0D0E0F101112131415161718191a1b1c1d1e1f";
|
||||
let non_hex = "g00102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
|
||||
let non_ascii = format!("é{}", "0".repeat(62));
|
||||
for bad in [
|
||||
"",
|
||||
"00",
|
||||
&"0".repeat(63),
|
||||
&"0".repeat(65),
|
||||
upper,
|
||||
non_hex,
|
||||
non_ascii.as_str(),
|
||||
] {
|
||||
assert_eq!(
|
||||
Hash32::from_hex(bad),
|
||||
Err(ValueError::Hash32),
|
||||
"accepted {bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timestamp_has_one_spelling() {
|
||||
let t = Timestamp::from_unix_millis(1_789_632_300_000);
|
||||
assert_eq!(t.unix_millis(), 1_789_632_300_000);
|
||||
assert_eq!(t.to_rfc3339(), "2026-09-17T08:05:00.000Z");
|
||||
assert_eq!(Timestamp::parse("2026-09-17T08:05:00.000Z").unwrap(), t);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&t).unwrap(),
|
||||
r#""2026-09-17T08:05:00.000Z""#
|
||||
);
|
||||
assert_eq!(
|
||||
Timestamp::from_unix_millis(0).to_rfc3339(),
|
||||
"1970-01-01T00:00:00.000Z"
|
||||
);
|
||||
assert_eq!(
|
||||
Timestamp::from_unix_millis(1_789_632_300_007).to_rfc3339(),
|
||||
"2026-09-17T08:05:00.007Z"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timestamp_rejects_other_spellings() {
|
||||
for bad in [
|
||||
"2026-09-17T08:05:00Z",
|
||||
"2026-09-17T08:05:00.0Z",
|
||||
"2026-09-17T08:05:00.000000Z",
|
||||
"2026-09-17 08:05:00.000Z",
|
||||
"2026-09-17T08:05:00.000+00:00",
|
||||
"2026-09-17t08:05:00.000z",
|
||||
"2026-09-17",
|
||||
"",
|
||||
"now",
|
||||
] {
|
||||
assert_eq!(
|
||||
Timestamp::parse(bad),
|
||||
Err(ValueError::Timestamp),
|
||||
"accepted {bad:?}"
|
||||
);
|
||||
assert!(serde_json::from_str::<Timestamp>(&format!("\"{bad}\"")).is_err());
|
||||
}
|
||||
assert!(serde_json::from_str::<Timestamp>("1789632300000").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timestamp_now_is_after_2026() {
|
||||
assert!(Timestamp::now() > Timestamp::parse("2026-01-01T00:00:00.000Z").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_class_is_ordered_and_lowercase() {
|
||||
assert!(DataClass::Public < DataClass::Private);
|
||||
assert!(DataClass::Private < DataClass::Secret);
|
||||
assert_eq!(DataClass::Private.max(DataClass::Secret), DataClass::Secret);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&DataClass::Secret).unwrap(),
|
||||
r#""secret""#
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<DataClass>(r#""public""#).unwrap(),
|
||||
DataClass::Public
|
||||
);
|
||||
assert!(serde_json::from_str::<DataClass>(r#""Public""#).is_err());
|
||||
assert!(serde_json::from_str::<DataClass>(r#""internal""#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_error_is_a_std_error_with_a_message() {
|
||||
let e: Box<dyn std::error::Error> = Box::new(ValueError::Hash32);
|
||||
assert!(!e.to_string().is_empty());
|
||||
}
|
||||
Reference in New Issue
Block a user