#[allow(unused_imports)]
use crate::prelude::*;
use serde_json::{json, Value};
use crate::error::{CoreError, Result};
use crate::time::{self, WindowState, MAX_CLOCK_SKEW_SECONDS};
const NS_PER_SECOND: i128 = 1_000_000_000;
const MIN_NS: i128 = -62_135_596_800 * NS_PER_SECOND;
const MAX_NS: i128 = 253_402_300_799 * NS_PER_SECOND + 999_999_999;
fn refuse(msg: String) -> CoreError {
CoreError::Json(msg)
}
fn quoted(value: &str) -> String {
let head: String = value.chars().take(64).collect();
crate::grant_chain::py_repr_str(&head)
}
pub fn py_type_name(v: &Value) -> &'static str {
match v {
Value::Null => "NoneType",
Value::Bool(_) => "bool",
Value::Number(n) if n.is_f64() => "float",
Value::Number(_) => "int",
Value::String(_) => "str",
Value::Array(_) => "list",
Value::Object(_) => "dict",
}
}
pub fn parse_ns(value: &str) -> Result<i128> {
let b = value.as_bytes();
let not_time = || refuse(format!("not a protocol time: {}", quoted(value)));
let digits = |from: usize, len: usize| -> Option<i64> {
let part = b.get(from..from + len)?;
part.iter().all(u8::is_ascii_digit).then(|| {
part.iter()
.fold(0i64, |acc, d| acc * 10 + i64::from(d - b'0'))
})
};
let at = |i: usize, c: u8| b.get(i) == Some(&c);
let fields = (|| {
if !(at(4, b'-') && at(7, b'-') && at(10, b'T') && at(13, b':') && at(16, b':')) {
return None;
}
Some((
digits(0, 4)?,
digits(5, 2)?,
digits(8, 2)?,
digits(11, 2)?,
digits(14, 2)?,
digits(17, 2)?,
))
})();
let Some((year, month, day, hour, minute, second)) = fields else {
return Err(not_time());
};
let mut j = 19;
let mut nanos: i128 = 0;
if at(j, b'.') {
let start = j + 1;
let mut end = start;
while end < b.len() && b[end].is_ascii_digit() {
end += 1;
}
let n = end - start;
if n == 0 || n > 9 {
return Err(not_time());
}
for &d in &b[start..end] {
nanos = nanos * 10 + i128::from(d - b'0');
}
for _ in n..9 {
nanos *= 10;
}
j = end;
}
let offset = match b.get(j) {
Some(b'Z') if j + 1 == b.len() => None,
Some(sign @ (b'+' | b'-')) if j + 6 == b.len() && at(j + 3, b':') => {
match (digits(j + 1, 2), digits(j + 4, 2)) {
(Some(h), Some(m)) => Some((*sign, h, m)),
_ => return Err(not_time()),
}
}
_ => return Err(not_time()),
};
let range = |what: &str| refuse(format!("{what}: {}", quoted(value)));
if !(1..=9999).contains(&year) {
return Err(range("year out of range"));
}
if !(1..=12).contains(&month) {
return Err(range("month out of range"));
}
if day < 1 || day > days_in_month(year, month) {
return Err(range("no such calendar day"));
}
if hour > 23 || minute > 59 || second > 59 {
return Err(range("time of day out of range"));
}
let offset_seconds = match offset {
None => 0,
Some((sign, h, m)) => {
if h > 23 || m > 59 {
return Err(range("offset out of range"));
}
(h * 3600 + m * 60) * if sign == b'+' { 1 } else { -1 }
}
};
let seconds = days_from_civil(year, month, day) * 86_400 + hour * 3_600 + minute * 60 + second
- offset_seconds;
let total = i128::from(seconds) * NS_PER_SECOND + nanos;
if !(MIN_NS..=MAX_NS).contains(&total) {
return Err(range("instant out of range once moved to UTC"));
}
Ok(total)
}
fn days_in_month(year: i64, month: i64) -> i64 {
match month {
2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
let y = if month <= 2 { year - 1 } else { year };
let era = (if y >= 0 { y } else { y - 399 }).div_euclid(400);
let yoe = y - era * 400;
let mp = (month + 9) % 12;
let doy = (153 * mp + 2) / 5 + day - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
pub fn parse_value_ns(v: &Value) -> Result<i128> {
match v {
Value::String(s) => parse_ns(s),
other => Err(refuse(format!(
"a protocol time is a string, not {}",
py_type_name(other)
))),
}
}
pub fn check_skew(v: &Value) -> Result<i64> {
let Value::Number(n) = v else {
return Err(refuse(format!(
"clock skew must be a number of seconds, not {}",
py_type_name(v)
)));
};
let whole = if let Some(i) = n.as_i64() {
Some(i as f64)
} else if let Some(u) = n.as_u64() {
Some(u as f64)
} else {
n.as_f64()
};
let f = whole.unwrap_or(f64::NAN);
if !f.is_finite() {
return Err(refuse("clock skew must be finite".into()));
}
if crate::float::fract(f) != 0.0 {
return Err(refuse(
"clock skew must be a whole number of seconds".into(),
));
}
if f < 0.0 || f > MAX_CLOCK_SKEW_SECONDS as f64 {
return Err(refuse(format!(
"clock skew must be between 0 and {MAX_CLOCK_SKEW_SECONDS} seconds"
)));
}
Ok(f as i64)
}
fn instant_json(ns: i128) -> Value {
json!({
"ns": ns.to_string(),
"epochSeconds": ns.div_euclid(NS_PER_SECOND) as i64,
"nanos": ns.rem_euclid(NS_PER_SECOND) as i64,
})
}
fn optional_bound(request: &Value, name: &str) -> Result<Option<i128>> {
match request.get(name) {
None | Some(Value::Null) => Ok(None),
Some(v) => parse_value_ns(v).map(Some),
}
}
pub fn rules_json(request: &Value) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
let op = request
.get("op")
.and_then(Value::as_str)
.ok_or_else(|| refuse("op is required".into()))?;
let field = |name: &str| request.get(name).unwrap_or(&Value::Null);
match op {
"parse" => Ok(instant_json(parse_value_ns(field("value"))?)),
"isTime" => Ok(json!({"ok": parse_value_ns(field("value")).is_ok()})),
"window" => {
let skew = match request.get("clockSkewSeconds") {
None => 0,
Some(v) => check_skew(v)?,
};
let now = parse_value_ns(field("now"))?;
let from = optional_bound(request, "validFrom")?;
let until = optional_bound(request, "validUntil")?;
let state: WindowState =
time::window_state_ns(now, from, until, time::seconds_to_ns(skew));
Ok(json!({"state": state.as_str()}))
}
"checkSkew" => Ok(json!({"seconds": check_skew(field("seconds"))?})),
"compare" => {
let a = parse_value_ns(field("a"))?;
let b = parse_value_ns(field("b"))?;
Ok(json!({"sign": a.cmp(&b) as i8}))
}
"format" => {
let secs = field("epochSeconds")
.as_i64()
.ok_or_else(|| refuse("epochSeconds must be a whole number".into()))?;
if !(MIN_NS / NS_PER_SECOND..=MAX_NS / NS_PER_SECOND).contains(&i128::from(secs)) {
return Err(refuse(
"the instant is outside the years 0001-9999 in UTC".into(),
));
}
Ok(json!({"text": time::epoch_seconds_to_iso(secs)}))
}
other => Err(refuse(format!(
"unknown time op {}",
crate::grant_chain::py_repr_str(other)
))),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn vector() -> Value {
let path = format!(
"{}/../../test-vectors/time/vector.json",
env!("CARGO_MANIFEST_DIR")
);
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}
#[test]
fn parse_matches_the_vector_and_the_core_grammar() {
let v = vector();
for case in v["parse"].as_array().unwrap() {
let input = case["input"].as_str().unwrap();
let got = parse_ns(input);
assert_eq!(got.is_ok(), case["valid"].as_bool().unwrap(), "{input}");
assert_eq!(
got.is_ok(),
time::parse_protocol_time_ns(input).is_ok(),
"{input}"
);
if let Ok(ns) = got {
assert_eq!(
ns.div_euclid(NS_PER_SECOND) as i64,
case["epoch_seconds"].as_i64().unwrap()
);
assert_eq!(
ns.rem_euclid(NS_PER_SECOND) as i64,
case["nanos"].as_i64().unwrap()
);
}
}
for case in v["non_string"].as_array().unwrap() {
let value = case.get("input").unwrap_or(case);
assert!(parse_value_ns(value).is_err());
}
}
#[test]
fn refusal_texts_are_the_references() {
assert_eq!(
parse_ns("2026-02-30T00:00:00Z").unwrap_err(),
refuse("no such calendar day: '2026-02-30T00:00:00Z'".into())
);
assert_eq!(
parse_ns("nope").unwrap_err(),
refuse("not a protocol time: 'nope'".into())
);
assert_eq!(
check_skew(&json!(0.5)).unwrap_err(),
refuse("clock skew must be a whole number of seconds".into())
);
assert_eq!(check_skew(&json!(30.0)).unwrap(), 30);
assert_eq!(
check_skew(&json!(true)).unwrap_err(),
refuse("clock skew must be a number of seconds, not bool".into())
);
}
#[test]
fn window_and_clock_skew_match_the_vector() {
let v = vector();
for case in v["window"].as_array().unwrap() {
let mut req = case.clone();
req["op"] = json!("window");
let obj = req.as_object_mut().unwrap();
for (from, to) in [
("valid_from", "validFrom"),
("valid_until", "validUntil"),
("clock_skew_seconds", "clockSkewSeconds"),
("skew", "clockSkewSeconds"),
] {
if let Some(x) = obj.remove(from) {
obj.insert(to.into(), x);
}
}
if let Some(want) = case.get("expected").and_then(Value::as_str) {
assert_eq!(rules_json(&req).unwrap()["state"], json!(want), "{case}");
}
}
for case in v["clock_skew"].as_array().unwrap() {
let ok = check_skew(case.get("input").unwrap_or(&Value::Null)).is_ok();
assert_eq!(ok, case["valid"].as_bool().unwrap(), "{case}");
}
}
}