Add validated identifiers, Hash32, Timestamp and DataClass to proto

Implemented-By: Laguna S 2.1 (OpenCode)
This commit is contained in:
2026-09-17 07:41:49 -07:00
parent 8dc04b1d48
commit 1e1b543a7c
9 changed files with 484 additions and 0 deletions
Generated
+107
View File
@@ -23,6 +23,12 @@ dependencies = [
"proto",
]
[[package]]
name = "humantime"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15"
[[package]]
name = "inferproxy"
version = "0.1.0"
@@ -30,6 +36,12 @@ dependencies = [
"proto",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "loopd"
version = "0.1.0"
@@ -37,9 +49,92 @@ dependencies = [
"proto",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "proto"
version = "0.1.0"
dependencies = [
"humantime",
"serde",
"serde_json",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.151"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "toolkit"
@@ -47,3 +142,15 @@ version = "0.1.0"
dependencies = [
"proto",
]
[[package]]
name = "unicode-ident"
version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+4
View File
@@ -20,3 +20,7 @@ unsafe_code = "forbid"
[workspace.dependencies]
proto = { path = "crates/proto" }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151"
humantime = "2.4.0"
+4
View File
@@ -9,3 +9,7 @@ publish.workspace = true
workspace = true
[dependencies]
serde.workspace = true
serde_json.workspace = true
humantime.workspace = true
+9
View File
@@ -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,
}
+180
View File
@@ -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()
}
}
+6
View File
@@ -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};
+170
View File
@@ -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());
}
+3
View File
@@ -4,3 +4,6 @@ Every external crate has a row here. `scripts/check-dep-docs.sh` enforces it.
| Crate | Version | Used by | Why |
|---|---|---|---|
| `serde` | 1.0.229 | `proto` | Derives serialization for every shared type. MIT OR Apache-2.0. |
| `serde_json` | 1.0.151 | `proto` | JSON for frames and log files. MIT OR Apache-2.0. |
| `humantime` | 2.4.0 | `proto` | RFC 3339 timestamps. No dependencies of its own. MIT OR Apache-2.0. |
+1
View File
@@ -6,5 +6,6 @@ reviewer adds findings under "Reviews" once per milestone.
| Task | Date | Status | Gate runs | First gate | Deviations | Notes |
|---|---|---|---|---|---|---|
| M1/01-workspace-and-gate | 2026-09-17 | done | 1 | pass | none | Crate skeletons, Cargo files and the given Makefile/deny.toml/test-gate-scripts.sh were already present untracked from a prior attempt; I verified them against the plan and created only the missing gate scripts, dependencies.md, egress.md and this log row. |
| M1/02-proto-values | 2026-09-17 | done | 1 | pass | none | Implemented ValueError, SessionId, Epoch, CallId, Hash32 and Timestamp in crates/proto/src/ids.rs and DataClass in class.rs, using serde try_from/into for string-backed JSON validation, a hand-written hex encoder and humantime for RFC 3339 parsing with canonical re-serialization. |
## Reviews