use thiserror::Error;
use crate::intervals::IntervalError;
use crate::time::{Instant, TimeError};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Diagnostics {
pub errors: Vec<Diagnostic>,
pub warnings: Vec<Diagnostic>,
}
impl Diagnostics {
#[must_use]
pub fn is_valid(&self) -> bool {
self.errors.is_empty()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Diagnostic {
code: &'static str,
message: String,
path: Option<String>,
}
impl Diagnostic {
#[must_use]
pub fn new(code: &'static str, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
path: None,
}
}
#[must_use]
pub const fn code(&self) -> &'static str {
self.code
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
#[must_use]
pub fn path(&self) -> Option<&str> {
self.path.as_deref()
}
#[must_use]
pub fn with_path(mut self, path: impl Into<String>) -> Self {
self.path = Some(path.into());
self
}
}
impl core::fmt::Display for Diagnostic {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}: {}", self.code, self.message)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Time(TimeError),
#[error(transparent)]
Intervals(IntervalError),
#[error(transparent)]
Window(crate::time::WindowError),
#[error(transparent)]
Blackout(crate::time::BlackoutError),
#[error(transparent)]
Tag(crate::tags::TagError),
#[error("a span must cover at least one minute, but {start} to {end} covers none")]
SpanEmpty {
start: Instant,
end: Instant,
},
#[error("a span must end after it starts, but {start} is after {end}")]
SpanReversed {
start: Instant,
end: Instant,
},
#[error("zone period is empty: {from} is not before {until}")]
ZonePeriodEmpty {
from: Instant,
until: Instant,
},
#[error("occurrence `{event_key}` names no participants")]
OccurrenceWithoutParticipants {
event_key: String,
},
#[error("event key `{event_key}` is empty or whitespace, so it names no event")]
EventKeyEmpty {
event_key: String,
},
#[error("a status policy entry must match a status, a tag selector, or both")]
StatusPolicyEntryEmpty,
#[error("the request is invalid: {}", DisplayFirst(.errors))]
InvalidRequest {
errors: Vec<Diagnostic>,
},
#[error(
"version 1 books exactly one part per request, but the goal has {parts}: model each \
stage as its own request and pass the gap between them as the next request's \
`search_window` or `candidates`"
)]
PartCount {
parts: usize,
},
#[error("malformed proposal: {message}")]
MalformedProposal {
code: &'static str,
message: String,
path: Option<String>,
},
}
impl Error {
#[must_use]
pub const fn invalid_request(errors: Vec<Diagnostic>) -> Self {
Self::InvalidRequest { errors }
}
#[must_use]
pub fn malformed_proposal(
code: &'static str,
message: impl Into<String>,
path: impl Into<String>,
) -> Self {
Self::MalformedProposal {
code,
message: message.into(),
path: Some(path.into()),
}
}
#[must_use]
pub fn path(&self) -> Option<&str> {
match self {
Self::MalformedProposal { path, .. } => path.as_deref(),
_ => None,
}
}
#[must_use]
pub const fn code(&self) -> &'static str {
match self {
Self::Time(err) => err.code(),
Self::Intervals(err) => err.code(),
Self::Window(err) => err.code(),
Self::Blackout(err) => err.code(),
Self::Tag(err) => err.code(),
Self::SpanEmpty { .. } => "span_empty",
Self::SpanReversed { .. } => "span_reversed",
Self::ZonePeriodEmpty { .. } => "zone_period_empty",
Self::OccurrenceWithoutParticipants { .. } => "occurrence_without_participants",
Self::EventKeyEmpty { .. } => "event_key_empty",
Self::StatusPolicyEntryEmpty => "status_policy_entry_empty",
Self::InvalidRequest { .. } => "invalid_request",
Self::PartCount { .. } => "part_count",
Self::MalformedProposal { code, .. } => code,
}
}
}
impl From<TimeError> for Error {
fn from(err: TimeError) -> Self {
Self::Time(err)
}
}
impl From<IntervalError> for Error {
fn from(err: IntervalError) -> Self {
Self::Intervals(err)
}
}
impl From<crate::tags::TagError> for Error {
fn from(err: crate::tags::TagError) -> Self {
Self::Tag(err)
}
}
impl From<crate::time::WindowError> for Error {
fn from(err: crate::time::WindowError) -> Self {
Self::Window(err)
}
}
impl From<crate::time::BlackoutError> for Error {
fn from(err: crate::time::BlackoutError) -> Self {
Self::Blackout(err)
}
}
struct DisplayFirst<'a>(&'a [Diagnostic]);
impl std::fmt::Display for DisplayFirst<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0.first() {
Some(first) => first.fmt(f),
None => f.write_str("the request failed validation"),
}
}
}
pub(crate) fn escape_pointer_token(token: &str) -> String {
let mut escaped = String::with_capacity(token.len());
for character in token.chars() {
match character {
'~' => escaped.push_str("~0"),
'/' => escaped.push_str("~1"),
other => escaped.push(other),
}
}
escaped
}
#[cfg(test)]
mod tests {
use super::Error;
#[test]
fn invalid_request_with_no_diagnostics_does_not_panic() {
let err = Error::invalid_request(Vec::new());
assert_eq!(err.code(), "invalid_request");
assert!(!err.to_string().is_empty());
}
}