use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, SecondsFormat, Utc};
use num_bigint::{BigInt, Sign};
use toml_edit::{InlineTable, Item, Value};
use crate::{
data::{
BindingSelector, BindingSlice, Date, Duration, ExactInteger, IntervalClosed, IntervalKey,
LocalTimestamp, RawKey, TimeZone, Timestamp, UnavailableKey,
},
Result,
};
use crate::recipe::schema::{self as grammar, Schema};
use super::codec::{choice, field, invalid, Codec};
pub(super) fn integer(value: &ExactInteger) -> BigInt {
BigInt::from_bytes_be(
if value.is_negative() {
Sign::Minus
} else {
Sign::Plus
},
value.magnitude_be(),
)
}
pub(super) fn decode_integer(text: &str) -> Result<ExactInteger> {
let value: BigInt = text
.parse()
.map_err(|_| invalid("expected an exact decimal integer"))?;
let (sign, bytes) = value.to_bytes_be();
ExactInteger::from_parts(sign == Sign::Minus, &bytes)
}
fn decimal_integer_schema(_: &mut Schema) -> serde_json::Value {
serde_json::json!({"type":"string","pattern":"^[+-]?[0-9][0-9_]*$"})
}
const INTEGER_FIELDS: &[grammar::Field] =
&[grammar::custom("integer", true, decimal_integer_schema)];
impl Codec for ExactInteger {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::any_of([
serde_json::json!({"type":"integer","minimum":i64::MIN,"maximum":i64::MAX}),
grammar::record(ctx, INTEGER_FIELDS),
])
}
fn encode(&self) -> Value {
if let Some(value) = self.to_i128().and_then(|value| i64::try_from(value).ok()) {
Value::from(value)
} else {
tagged("integer", Value::from(integer(self).to_string()))
}
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if let Some(value) = item.as_integer() {
return Ok(value.into());
}
let fields = grammar::record_fields(item, INTEGER_FIELDS)?;
decode_integer(&field::<String>(fields, "integer", None)?)
}
}
fn tagged(name: &str, value: Value) -> Value {
let mut record = InlineTable::new();
record.insert(name, value);
record.into()
}
fn date_string(date: Date) -> String {
format!("{:04}-{:02}-{:02}", date.year(), date.month(), date.day())
}
fn native_date(date: NaiveDate) -> Result<Date> {
use chrono::Datelike;
Date::new(
date.year(),
u8::try_from(date.month()).expect("month"),
u8::try_from(date.day()).expect("day"),
)
}
fn native_local(time: NaiveDateTime) -> Result<LocalTimestamp> {
use chrono::Timelike;
LocalTimestamp::new(
native_date(time.date())?,
u8::try_from(time.hour()).expect("hour"),
u8::try_from(time.minute()).expect("minute"),
u8::try_from(time.second()).expect("second"),
time.nanosecond(),
)
}
fn instant(value: &Timestamp) -> Option<Value> {
let utc = DateTime::<Utc>::from_timestamp(value.seconds(), value.nanos())?;
let offset = value.offset_seconds().or_else(|| match value.zone() {
Some(TimeZone::FixedOffset(offset)) => Some(*offset),
_ => None,
});
let iso = if let Some(offset) = offset.filter(|offset| offset % 60 == 0) {
utc.with_timezone(&FixedOffset::east_opt(offset)?)
.to_rfc3339_opts(SecondsFormat::Nanos, false)
} else {
utc.to_rfc3339_opts(SecondsFormat::Nanos, true)
};
let mut record = InlineTable::new();
record.insert("timestamp", Value::from(iso));
if let Some(zone) = value.zone() {
record.insert(
"timezone",
match zone {
TimeZone::Iana(name) => Value::from(name.clone()),
TimeZone::FixedOffset(offset) => {
tagged("offset_seconds", Value::from(i64::from(*offset)))
}
},
);
}
record.insert(
"offset_seconds",
value.offset_seconds().map_or_else(
|| Value::from(false),
|offset| Value::from(i64::from(offset)),
),
);
if let Some(fold) = value.fold() {
record.insert("fold", Value::from(i64::from(fold)));
}
Some(record.into())
}
const ZONE_FIELDS: &[grammar::Field] = &[grammar::mandatory::<i32>("offset_seconds")];
const INSTANT_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<String>("timestamp"),
grammar::custom("timezone", false, |ctx| {
grammar::any_of([ctx.reference::<String>(), grammar::record(ctx, ZONE_FIELDS)])
}),
grammar::optional::<Option<i32>>("offset_seconds"),
grammar::optional::<Option<u32>>("fold"),
];
fn decode_instant(item: &Item) -> Result<RawKey> {
let fields = grammar::record_fields(item, INSTANT_FIELDS)?;
let text: String = field(fields, "timestamp", None)?;
let parsed = DateTime::parse_from_rfc3339(&text)
.map_err(|error| invalid(format!("invalid exact timestamp: {error}")))?;
let actual_offset = parsed.offset().local_minus_utc();
let zone = match fields.get("timezone") {
None => None,
Some(value) if value.is_str() => Some(TimeZone::Iana(String::decode(value, None)?)),
Some(value) => {
let fields = grammar::record_fields(value, ZONE_FIELDS)?;
Some(TimeZone::FixedOffset(field(
fields,
"offset_seconds",
None,
)?))
}
};
let offset = field(fields, "offset_seconds", Some(Some(actual_offset)))?;
let fold: Option<u32> = field(fields, "fold", Some(None))?;
let fold = fold
.map(|value| u8::try_from(value).map_err(|_| invalid("invalid timestamp fold")))
.transpose()?;
let zone = if !fields.contains_key("offset_seconds") && zone.is_none() {
Some(TimeZone::FixedOffset(actual_offset))
} else {
zone
};
Timestamp::new(
parsed.timestamp(),
parsed.timestamp_subsec_nanos(),
zone,
offset,
fold,
)
.map(RawKey::Instant)
}
choice!(IntervalClosed {Left=>"left",Right=>"right",Both=>"both",Neither=>"neither"});
const INTERVAL_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<RawKey>("left"),
grammar::mandatory::<RawKey>("right"),
grammar::mandatory::<IntervalClosed>("closed"),
];
const RAW_TAG_FIELDS: &[grammar::Field] = &[
grammar::custom("integer", false, decimal_integer_schema),
grammar::optional::<String>("date"),
grammar::optional::<String>("duration_ns"),
grammar::optional::<String>("local_timestamp"),
grammar::custom("interval", false, |ctx| {
grammar::record(ctx, INTERVAL_FIELDS)
}),
];
impl Codec for RawKey {
fn schema(ctx: &mut Schema) -> serde_json::Value {
let tags = grammar::with(
grammar::record(ctx, RAW_TAG_FIELDS),
grammar::at_most_one(
&RAW_TAG_FIELDS
.iter()
.map(|field| field.name)
.collect::<Vec<_>>(),
),
);
grammar::any_of([
ctx.reference::<String>(),
ctx.reference::<bool>(),
ctx.reference::<f64>(),
grammar::array(ctx.reference::<RawKey>()),
tags,
grammar::record(ctx, INSTANT_FIELDS),
])
}
fn encode(&self) -> Value {
match self {
Self::String(value) => value.encode(),
Self::Integer(value) => value.encode(),
Self::Boolean(value) => value.encode(),
Self::Float(value) if value.is_finite() => value.encode(),
Self::Tuple(values) => values.encode(),
Self::Date(value) => tagged("date", Value::from(date_string(*value))),
Self::Duration(value) => {
tagged("duration_ns", Value::from(value.nanoseconds().to_string()))
}
Self::LocalTimestamp(value) => tagged(
"local_timestamp",
Value::from(format!(
"{}T{:02}:{:02}:{:02}.{:09}",
date_string(value.date()),
value.hour(),
value.minute(),
value.second(),
value.nanos()
)),
),
Self::Instant(value) => instant(value).unwrap_or_else(|| InlineTable::new().into()),
Self::Interval(value) => {
let mut interval = InlineTable::new();
interval.insert("left", value.left().encode());
interval.insert("right", value.right().encode());
interval.insert("closed", value.closed().encode());
tagged("interval", interval.into())
}
Self::Unavailable(_) | Self::Float(_) => InlineTable::new().into(),
}
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if let Some(value) = item.as_str() {
return Ok(Self::String(value.to_owned()));
}
if let Some(value) = item.as_integer() {
return Ok(Self::Integer(value.into()));
}
if item.is_float() {
return f64::decode(item, None).map(Self::Float);
}
if let Some(value) = item.as_bool() {
return Ok(Self::Boolean(value));
}
if item.is_array() {
return Vec::<Self>::decode(item, None).map(Self::Tuple);
}
let fields = item
.as_table_like()
.ok_or_else(|| invalid("expected a complete raw key"))?;
if fields.is_empty() {
return UnavailableKey::new("recipe key is still required").map(Self::Unavailable);
}
if fields.contains_key("timestamp") {
return decode_instant(item);
}
let fields = grammar::record_fields(item, RAW_TAG_FIELDS)?;
if fields.len() != 1 {
return Err(invalid("raw key requires exactly one type tag"));
}
let (kind, value) = fields.iter().next().expect("one type tag");
match kind {
"integer" => ExactInteger::decode(item, None).map(Self::Integer),
"date" => {
let date = NaiveDate::parse_from_str(&String::decode(value, None)?, "%Y-%m-%d")
.map_err(|error| invalid(format!("invalid date key: {error}")))?;
native_date(date).map(Self::Date)
}
"duration_ns" => {
let nanos = String::decode(value, None)?
.parse::<i128>()
.map_err(|_| invalid("invalid exact duration"))?;
Ok(Self::Duration(Duration::from_nanos(nanos)))
}
"local_timestamp" => {
let time = NaiveDateTime::parse_from_str(
&String::decode(value, None)?,
"%Y-%m-%dT%H:%M:%S%.f",
)
.map_err(|error| invalid(format!("invalid local timestamp key: {error}")))?;
native_local(time).map(Self::LocalTimestamp)
}
"interval" => {
let fields = grammar::record_fields(value, INTERVAL_FIELDS)?;
let left: RawKey = field(fields, "left", None)?;
let right: RawKey = field(fields, "right", None)?;
if unresolved(&left) || unresolved(&right) {
return UnavailableKey::new("recipe interval endpoint is still required")
.map(Self::Unavailable);
}
IntervalKey::new(left, right, field(fields, "closed", None)?).map(Self::Interval)
}
_ => unreachable!("checked raw key tag"),
}
}
}
pub(super) fn unresolved(key: &RawKey) -> bool {
match key {
RawKey::Unavailable(_) => true,
RawKey::Tuple(keys) => keys.iter().any(unresolved),
RawKey::Interval(interval) => unresolved(interval.left()) || unresolved(interval.right()),
RawKey::Float(value) => !value.is_finite(),
RawKey::Instant(value) => instant(value).is_none(),
_ => false,
}
}
const SLICE_FIELDS: &[grammar::Field] = &[
grammar::optional::<Option<ExactInteger>>("start"),
grammar::optional::<Option<ExactInteger>>("stop"),
grammar::optional::<ExactInteger>("step"),
];
impl Codec for BindingSlice {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, SLICE_FIELDS)
}
fn encode(&self) -> Value {
let mut value = InlineTable::new();
if let Some(start) = self.start() {
value.insert("start", start.encode());
}
if let Some(stop) = self.stop() {
value.insert("stop", stop.encode());
}
value.insert("step", self.step().encode());
value.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
let fields = grammar::record_fields(item, SLICE_FIELDS)?;
Self::new(
field(fields, "start", Some(None))?,
field(fields, "stop", Some(None))?,
field(fields, "step", Some(ExactInteger::from(1)))?,
)
}
}
pub(super) const SELECTOR_FIELDS: &[grammar::Field] = &[
grammar::optional::<RawKey>("key"),
grammar::custom(
"keys",
false,
|ctx| serde_json::json!({"type":"array","minItems":1,"items":ctx.reference::<RawKey>()}),
),
grammar::optional::<isize>("index"),
grammar::custom("indices", false, |ctx| {
grammar::any_of([
serde_json::json!({"type":"array","minItems":1,"uniqueItems":true,"items":ctx.reference::<isize>()}),
ctx.reference::<BindingSlice>(),
])
}),
grammar::custom("all", false, |_| grammar::literal(true)),
grammar::custom("numeric_only", false, |_| grammar::literal(true)),
];
pub(super) fn selector_shape(
ctx: &mut Schema,
extra: &[grammar::Field],
selections: &[grammar::Field],
) -> serde_json::Value {
let mut fields = selections.to_vec();
fields.extend_from_slice(extra);
grammar::with(
grammar::record(ctx, &fields),
grammar::at_most_one(
&selections
.iter()
.map(|field| field.name)
.collect::<Vec<_>>(),
),
)
}
pub(super) fn single_selector_schema(ctx: &mut Schema) -> serde_json::Value {
let fields: Vec<_> = SELECTOR_FIELDS
.iter()
.filter(|field| matches!(field.name, "key" | "index"))
.copied()
.collect();
let names: Vec<_> = fields.iter().map(|field| field.name).collect();
let record = grammar::with(grammar::record(ctx, &fields), grammar::exclusive(&names));
grammar::any_of([ctx.reference::<String>(), record])
}
pub(super) fn selector_record(selector: &BindingSelector) -> InlineTable {
let mut fields = InlineTable::new();
let (name, value) = match selector {
BindingSelector::Key(key) => ("key", key.encode()),
BindingSelector::Keys(keys) => ("keys", keys.encode()),
BindingSelector::Index(index) => ("index", index.encode()),
BindingSelector::Indices(indices) => ("indices", indices.encode()),
BindingSelector::Slice(slice) => ("indices", slice.encode()),
BindingSelector::All => ("all", true.encode()),
BindingSelector::NumericOnly => ("numeric_only", true.encode()),
BindingSelector::Whole => return fields,
};
fields.insert(name, value);
fields
}
pub(super) fn selector_pending(selector: &BindingSelector) -> bool {
match selector {
BindingSelector::Key(key) => unresolved(key),
BindingSelector::Keys(keys) => keys.iter().any(unresolved),
_ => false,
}
}
impl Codec for BindingSelector {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::any_of([
ctx.reference::<String>(),
selector_shape(ctx, &[], SELECTOR_FIELDS),
])
}
fn encode(&self) -> Value {
selector_record(self).into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if let Some(key) = item.as_str() {
return Ok(Self::Key(key.into()));
}
let fields = grammar::record_fields(item, SELECTOR_FIELDS)?;
if fields.len() > 1 {
return Err(invalid("selectors are mutually exclusive"));
}
let Some((name, value)) = fields.iter().next() else {
return Ok(Self::Whole);
};
match name {
"key" => RawKey::decode(value, None).map(Self::Key),
"keys" => nonempty(Vec::<RawKey>::decode(value, None)?).map(Self::Keys),
"index" => isize::decode(value, None).map(Self::Index),
"indices" if value.as_table_like().is_some() => {
BindingSlice::decode(value, None).map(Self::Slice)
}
"indices" => nonempty(Vec::<isize>::decode(value, None)?).map(Self::Indices),
"all" if value.as_bool() == Some(true) => Ok(Self::All),
"numeric_only" if value.as_bool() == Some(true) => Ok(Self::NumericOnly),
_ => Err(invalid(format!("invalid selector {name:?}"))),
}
}
}
fn nonempty<T: Eq + std::hash::Hash>(values: Vec<T>) -> Result<Vec<T>> {
if values.is_empty() {
Err(invalid("ordered selection must not be empty"))
} else {
let mut seen = std::collections::HashSet::new();
if values.iter().any(|value| !seen.insert(value)) {
return Err(invalid(
"ordered selection requires distinct keys or positions",
));
}
Ok(values)
}
}