use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use crate::Engine;
use crate::error::{Diagnostic, Diagnostics, Error, escape_pointer_token};
use crate::eval::{
FixedMinutes, PreResolved, Settings, WindowContext, candidate_starts_limited, padded_range,
resolve_lead_bound, resolve_schedule,
};
use crate::intervals::{IntervalSet, Span as MinuteSpan};
use crate::limits::Limits;
use crate::matching;
use crate::model::{
Block, Cap, CapPer, LeadTimeMax, Part, Participant, ParticipantKind, Proposal, ProposalEvent,
Request, Rule, RuleKind, Span, Term,
};
use crate::occupancy;
use crate::rules::{Applicable, RuleMatcher, named_ids, named_tags, names_participants};
use crate::tags::{Role, Tag};
use crate::time::{
Duration, GridZone, Instant, RuleZone, StartBound, TimeZoneDatabase, WorkingCalendar,
ZoneSchedule,
};
pub(crate) fn validate(engine: &Engine, request: &Request) -> Diagnostics {
validated_search(engine, request, true).diagnostics
}
pub(crate) struct ValidatedSearch<'a> {
pub(crate) diagnostics: Diagnostics,
pub(crate) candidates: Vec<Instant>,
pub(crate) pre_resolved: Option<PreResolved<'a>>,
}
pub(crate) fn validate_for_search<'a>(
engine: &Engine,
request: &'a Request,
) -> ValidatedSearch<'a> {
validated_search(engine, request, false)
}
fn validated_search<'a>(
engine: &Engine,
request: &'a Request,
check_windows: bool,
) -> ValidatedSearch<'a> {
let mut common = common_checks(engine, request, Some(request.goal.search_window.end()));
let candidates = if common.stopped_at_cap {
Vec::new()
} else {
validate_search(
engine,
request,
&common.schedules,
&common.rules,
check_windows,
&mut common.diagnostics,
)
};
let pre_resolved = common.take_pre_resolved(request.participants.len());
ValidatedSearch {
diagnostics: common.diagnostics,
candidates,
pre_resolved,
}
}
pub(crate) fn validate_for_slot<'a>(
engine: &Engine,
request: &'a Request,
) -> (Diagnostics, Option<PreResolved<'a>>) {
let mut common = common_checks(engine, request, None);
let pre = common.take_pre_resolved(request.participants.len());
(common.diagnostics, pre)
}
pub(crate) fn append_window_warnings(settings: &Settings<'_>, warnings: &mut Vec<Diagnostic>) {
if settings.candidates.is_empty() {
return;
}
for participant in &settings.participants {
let Some(allowed) = &participant.allowed else {
continue;
};
let mut any_span = false;
let mut inside = false;
for &start in &settings.candidates {
let Some(span) = occupied_span(settings.part, &participant.participant.id, start)
else {
continue;
};
let Ok(minutes) = MinuteSpan::new(span.start().minutes(), span.end().minutes()) else {
continue;
};
any_span = true;
if allowed.contains_span(&minutes) {
inside = true;
break;
}
}
if any_span && !inside {
push_no_candidate_in_window(&participant.participant.id, warnings);
}
}
}
#[derive(Default)]
struct CommonChecks<'a> {
diagnostics: Diagnostics,
stopped_at_cap: bool,
calendars: Option<BTreeMap<String, WorkingCalendar>>,
schedules: Vec<Option<ZoneSchedule>>,
rules: Vec<Applicable<'a>>,
lead_bounds: BTreeMap<usize, StartBound>,
}
impl<'a> CommonChecks<'a> {
fn take_pre_resolved(&mut self, participant_count: usize) -> Option<PreResolved<'a>> {
let calendars = self.calendars.take()?;
if self.schedules.len() != participant_count || self.rules.len() != participant_count {
return None;
}
let schedules: Option<Vec<ZoneSchedule>> =
std::mem::take(&mut self.schedules).into_iter().collect();
Some(PreResolved {
calendars,
schedules: schedules?,
rules: std::mem::take(&mut self.rules),
lead_bounds: std::mem::take(&mut self.lead_bounds),
})
}
}
struct StructureResolved<'a> {
participant_ids: BTreeSet<&'a str>,
schedules: Vec<Option<ZoneSchedule>>,
calendars: Option<BTreeMap<String, WorkingCalendar>>,
}
fn common_checks<'a>(
engine: &Engine,
request: &'a Request,
horizon_end: Option<Instant>,
) -> CommonChecks<'a> {
let mut common = CommonChecks::default();
check_limits(engine, request, &mut common.diagnostics);
check_durations(engine, request, &mut common.diagnostics);
if !common.diagnostics.is_valid() {
common.stopped_at_cap = true;
return common;
}
let structure = check_structure(engine, request, &mut common.diagnostics);
common.schedules = structure.schedules;
common.calendars = structure.calendars;
if request.goal.parts.len() == 1 {
check_requirement(request, &structure.participant_ids, &mut common.diagnostics);
}
let Some(part) = request.goal.part() else {
return common;
};
let db = engine.time_zone_database();
let Ok(event) = db.zone(request.goal.zone.as_str()) else {
return common;
};
check_rule_reachability(request, &part.tags, &mut common.diagnostics);
warn_about_ignored_resource_holds(request, &part.tags, &mut common.diagnostics);
warn_about_keyless_blocks(request, &part.tags, &mut common.diagnostics);
let matcher = RuleMatcher::new(&request.rules, &part.tags);
let mut applicable_rules = Vec::with_capacity(request.participants.len());
for participant in &request.participants {
applicable_rules.push(matcher.select(participant.context()));
}
if let Some(calendars) = &common.calendars {
let mut bounds: BTreeMap<usize, StartBound> = BTreeMap::new();
for (participant, applicable) in request.participants.iter().zip(&applicable_rules) {
warn_if_horizon_ends_first(
calendars,
request,
applicable,
&participant.id,
&event,
horizon_end,
&mut bounds,
&mut common.diagnostics,
);
}
common.lead_bounds = bounds;
}
common.rules = applicable_rules;
common
}
fn validate_search<'a>(
engine: &Engine,
request: &'a Request,
schedules: &[Option<ZoneSchedule>],
applicable_rules: &[Applicable<'a>],
check_windows: bool,
diagnostics: &mut Diagnostics,
) -> Vec<Instant> {
check_search_shape(engine, request, diagnostics);
let limit = engine.limits().max_candidate_starts;
let declared_too_long = request
.goal
.candidates
.as_ref()
.is_some_and(|candidates| candidates.len() > limit);
let candidates = if declared_too_long {
Vec::new()
} else {
match candidate_starts_limited(engine, request, limit.saturating_add(1)) {
Ok(candidates) => candidates,
Err(err) => {
let at = if engine
.time_zone_database()
.zone(request.goal.zone.as_str())
.is_err()
{
"/goal/zone".to_owned()
} else {
"/goal/grid".to_owned()
};
diagnostics
.errors
.push(Diagnostic::new(err.code(), err.to_string()).with_path(at));
return Vec::new();
}
}
};
check_search_limits(engine, request, &candidates, diagnostics);
if !check_windows
|| candidates.is_empty()
|| candidates.len() > engine.limits().max_candidate_starts
{
return candidates;
}
let within_window_limit =
search_window_within_limit(engine.limits(), request.goal.search_window);
if !within_window_limit && request.goal.candidates.is_none() {
return candidates;
}
let envelope_limit = search_envelope_limit(engine.limits());
let Some(part) = request.goal.part() else {
return candidates;
};
let db = engine.time_zone_database();
let Ok(event) = db.zone(request.goal.zone.as_str()) else {
return candidates;
};
let default_spans = candidate_occupied_spans(part, None, &candidates);
if within_window_limit {
warn_windows_within_limit(
db,
&event,
request,
part,
schedules,
applicable_rules,
&candidates,
&default_spans,
diagnostics,
);
return candidates;
}
let mut memos: BTreeMap<MinuteSpan, FixedMinutes<'a>> = BTreeMap::new();
for (index, participant) in request.participants.iter().enumerate() {
let Some(schedule) = schedules.get(index).and_then(Option::as_ref) else {
continue;
};
let Some(applicable) = applicable_rules.get(index) else {
continue;
};
if applicable.windows.is_empty() {
continue;
}
let override_spans;
let spans = if part.travel.by_participant.contains_key(&participant.id) {
override_spans = candidate_occupied_spans(part, Some(&participant.id), &candidates);
&override_spans
} else {
&default_spans
};
warn_if_no_candidate_fits_window_over_cap(
db,
&event,
schedule,
participant.zone.as_str(),
&participant.id,
&applicable.windows,
spans,
envelope_limit,
&mut memos,
diagnostics,
);
}
candidates
}
#[allow(clippy::too_many_arguments)]
fn warn_windows_within_limit<'a>(
db: &TimeZoneDatabase,
event: &crate::time::Zone,
request: &'a Request,
part: &Part,
schedules: &[Option<ZoneSchedule>],
applicable_rules: &[Applicable<'a>],
candidates: &[Instant],
default_spans: &[MinuteSpan],
diagnostics: &mut Diagnostics,
) {
let Ok(judged) = padded_range(&request.goal, part) else {
return;
};
let mut fixed = FixedMinutes::default();
for (index, participant) in request.participants.iter().enumerate() {
let Some(schedule) = schedules.get(index).and_then(Option::as_ref) else {
continue;
};
let Some(applicable) = applicable_rules.get(index) else {
continue;
};
if applicable.windows.is_empty() {
continue;
}
let override_spans;
let spans = if part.travel.by_participant.contains_key(&participant.id) {
override_spans = candidate_occupied_spans(part, Some(&participant.id), candidates);
&override_spans
} else {
default_spans
};
if spans.is_empty() {
continue;
}
let ctx = WindowContext {
db,
schedule,
home_zone_name: participant.zone.as_str(),
event,
judged,
};
let mut allowed: Option<Arc<IntervalSet>> = None;
let mut failed_build = false;
for &(_, position, spec) in &applicable.windows {
let Ok(minutes) = fixed.window(position, spec, &ctx) else {
failed_build = true;
break;
};
allowed = Some(match allowed {
Some(current) => Arc::new(current.intersection(&minutes)),
None => minutes,
});
if allowed.as_ref().is_some_and(|set| set.is_empty()) {
break;
}
}
let inside = !failed_build
&& allowed.is_some_and(|allowed| spans.iter().any(|span| allowed.contains_span(span)));
if !inside {
push_no_candidate_in_window(&participant.id, &mut diagnostics.warnings);
}
}
}
fn check_structure<'a>(
engine: &Engine,
request: &'a Request,
diagnostics: &mut Diagnostics,
) -> StructureResolved<'a> {
let db = engine.time_zone_database();
let participant_ids = check_participant_shapes(request, diagnostics);
check_goal_shape(db, request, diagnostics);
let schedules = check_participant_zones(db, request, diagnostics);
let calendars = check_calendars(db, request, diagnostics);
check_rules(db, request, &participant_ids, diagnostics);
check_occurrences(request, diagnostics);
check_weights(request, &participant_ids, diagnostics);
StructureResolved {
participant_ids,
schedules,
calendars,
}
}
fn check_weights(
request: &Request,
participant_ids: &BTreeSet<&str>,
diagnostics: &mut Diagnostics,
) {
for id in request.weights.keys() {
if !participant_ids.contains(id.as_str()) {
diagnostics.errors.push(
Diagnostic::new(
"participant_unknown",
format!("`weights` names participant `{id}`, which the request does not carry"),
)
.with_path(format!("/weights/{}", escape_pointer_token(id))),
);
}
}
}
fn check_participant_shapes<'a>(
request: &'a Request,
diagnostics: &mut Diagnostics,
) -> BTreeSet<&'a str> {
let mut seen = BTreeSet::new();
for (index, participant) in request.participants.iter().enumerate() {
if participant.id.trim().is_empty() {
diagnostics.errors.push(
Diagnostic::new(
"participant_id_empty",
format!(
"participant {index} has an empty or whitespace-only ID, so no reason, \
weight or assignment could name it"
),
)
.with_path(format!("/participants/{index}/id")),
);
}
if !seen.insert(participant.id.as_str()) {
diagnostics.errors.push(
Diagnostic::new(
"participant_duplicate",
format!("participant ID `{}` appears more than once", participant.id),
)
.with_path(format!("/participants/{index}/id")),
);
}
for (block_index, block) in participant.blocks().iter().enumerate() {
if block
.event_key
.as_deref()
.is_some_and(|key| key.trim().is_empty())
{
diagnostics.errors.push(
Diagnostic::new(
"event_key_empty",
format!(
"block {block_index} of participant `{}` has an empty or \
whitespace-only event key, which would merge unrelated events \
into one cap count",
participant.id
),
)
.with_path(format!(
"/participants/{index}/calendar/{block_index}/event_key"
)),
);
}
}
}
seen
}
fn check_goal_shape(db: &TimeZoneDatabase, request: &Request, diagnostics: &mut Diagnostics) {
match request.goal.parts.len() {
1 => {}
count => diagnostics.errors.push(
Diagnostic::new("part_count", Error::PartCount { parts: count }.to_string())
.with_path("/goal/parts".to_owned()),
),
}
for (index, part) in request.goal.parts.iter().enumerate() {
if part.id.trim().is_empty() {
diagnostics.errors.push(
Diagnostic::new(
"part_id_empty",
format!(
"part {index} has an empty or whitespace-only ID, so no proposal event \
could name it"
),
)
.with_path(format!("/goal/parts/{index}/id")),
);
}
if part.duration.minutes() < 1 {
diagnostics.errors.push(
Diagnostic::new(
"part_duration_empty",
format!(
"part `{}` has no length, so it can never be booked",
part.id
),
)
.with_path(format!("/goal/parts/{index}/duration")),
);
}
}
for (what, name, field) in [
("goal zone", &request.goal.zone, "/goal/zone"),
(
"display zone",
&request.goal.display_zone,
"/goal/display_zone",
),
] {
if let Err(err) = db.zone(name.as_str()) {
diagnostics.errors.push(
Diagnostic::new(err.code(), format!("{what} `{name}`: {err}"))
.with_path(field.to_owned()),
);
}
}
}
fn check_search_shape(engine: &Engine, request: &Request, diagnostics: &mut Diagnostics) {
let db = engine.time_zone_database();
if request.goal.grid.is_some() && request.goal.candidates.is_some() {
diagnostics.errors.push(
Diagnostic::new(
"grid_and_candidates",
"a goal cannot have both a grid and candidate starts".to_owned(),
)
.with_path("/goal/candidates".to_owned()),
);
}
if let Some(GridZone::Named(name)) = request
.goal
.grid
.as_ref()
.map(crate::time::Grid::zone_choice)
&& let Err(err) = db.zone(name.as_str())
{
diagnostics.errors.push(
Diagnostic::new(err.code(), format!("grid zone: {err}"))
.with_path("/goal/grid/zone".to_owned()),
);
}
}
fn check_participant_zones(
db: &TimeZoneDatabase,
request: &Request,
diagnostics: &mut Diagnostics,
) -> Vec<Option<ZoneSchedule>> {
let mut schedules = Vec::with_capacity(request.participants.len());
for (index, participant) in request.participants.iter().enumerate() {
match db.zone(participant.zone.as_str()) {
Err(err) => {
diagnostics.errors.push(
Diagnostic::new(
err.code(),
format!("participant `{}` zone: {err}", participant.id),
)
.with_path(format!("/participants/{index}/zone")),
);
schedules.push(None);
}
Ok(_) => match resolve_schedule(db, participant) {
Ok(schedule) => schedules.push(Some(schedule)),
Err(err) => {
diagnostics.errors.push(
Diagnostic::new(
err.code(),
format!("participant `{}` zone periods: {err}", participant.id),
)
.with_path(format!("/participants/{index}/zone_periods")),
);
schedules.push(None);
}
},
}
}
schedules
}
fn check_calendars(
db: &TimeZoneDatabase,
request: &Request,
diagnostics: &mut Diagnostics,
) -> Option<BTreeMap<String, WorkingCalendar>> {
let mut calendars = BTreeMap::new();
let mut all_valid = true;
for (name, calendar) in &request.calendars {
let key = escape_pointer_token(name);
match db.zone(calendar.zone.as_str()) {
Ok(zone) => {
match WorkingCalendar::new(zone, calendar.working_days, calendar.holidays.clone()) {
Ok(resolved) => {
if all_valid {
calendars.insert(name.clone(), resolved);
}
}
Err(err) => {
all_valid = false;
diagnostics.errors.push(
Diagnostic::new(err.code(), format!("calendar `{name}`: {err}"))
.with_path(format!("/calendars/{key}/working_days")),
);
}
}
}
Err(err) => {
all_valid = false;
diagnostics.errors.push(
Diagnostic::new(err.code(), format!("calendar `{name}` zone: {err}"))
.with_path(format!("/calendars/{key}/zone")),
);
}
}
}
all_valid.then_some(calendars)
}
fn check_rules(
db: &TimeZoneDatabase,
request: &Request,
participant_ids: &BTreeSet<&str>,
diagnostics: &mut Diagnostics,
) {
let mut rule_ids = BTreeSet::new();
for (position, rule) in request.rules.iter().enumerate() {
if rule.id.trim().is_empty() {
diagnostics.errors.push(
Diagnostic::new(
"rule_id_empty",
format!(
"rule {position} has an empty or whitespace-only ID, so no finding or reason \
could cite it"
),
)
.with_path(format!("/rules/{position}/id")),
);
}
if !rule_ids.insert(rule.id.as_str()) {
diagnostics.errors.push(
Diagnostic::new(
"rule_id_duplicate",
format!("rule ID `{}` appears more than once", rule.id),
)
.with_path(format!("/rules/{position}/id")),
);
}
check_rule_zones(db, request, position, rule, diagnostics);
if let RuleKind::Rest(rest) = &rule.kind
&& rest.late_after <= rest.not_before
{
diagnostics.warnings.push(
Diagnostic::new(
"rest_window_overlaps_day",
format!(
"rest rule `{}` has `late_after` ({}) at or before `not_before` ({}): \
`late_after` is the evening threshold and `not_before` the next \
morning's, so this order does not protect the night between a late \
finish and an early start",
rule.id, rest.late_after, rest.not_before
),
)
.with_path(format!("/rules/{position}/params")),
);
}
if names_participants(&rule.when) {
diagnostics.errors.push(
Diagnostic::new(
"selector_not_for_items",
format!(
"rule `{}` matches part tags with an `ids`, `role` or `kind` clause, which \
can never match a part's tags",
rule.id
),
)
.with_path(format!("/rules/{position}/when")),
);
}
for id in named_ids(&rule.who) {
if !participant_ids.contains(id) {
diagnostics.errors.push(
Diagnostic::new(
"participant_unknown",
format!(
"rule `{}` names participant `{id}` in `who`, which the request does not \
carry",
rule.id
),
)
.with_path(format!("/rules/{position}/who")),
);
}
}
}
}
fn check_rule_zones(
db: &TimeZoneDatabase,
request: &Request,
position: usize,
rule: &crate::model::Rule,
diagnostics: &mut Diagnostics,
) {
let mut named_zone = |name: &crate::time::ZoneName, what: &str| {
if let Err(err) = db.zone(name.as_str()) {
diagnostics.errors.push(
Diagnostic::new(err.code(), format!("rule `{}` {what} zone: {err}", rule.id))
.with_path(format!("/rules/{position}/params/zone")),
);
}
};
match &rule.kind {
RuleKind::Window(spec) => {
if let RuleZone::Named(name) = spec.zone() {
named_zone(name, "window");
}
}
RuleKind::Blackout(spec) => {
if let RuleZone::Named(name) = spec.zone() {
named_zone(name, "blackout");
}
}
RuleKind::LeadTime(lead_time) => {
if let Some(LeadTimeMax::WorkingDays { calendar, .. }) = &lead_time.max
&& !request.calendars.contains_key(calendar)
{
diagnostics.errors.push(
Diagnostic::new(
"calendar_unknown",
format!(
"rule `{}` names calendar `{calendar}`, which the request does not \
carry",
rule.id
),
)
.with_path(format!("/rules/{position}/params/max/calendar")),
);
}
}
RuleKind::StatusPolicy(policy) => {
for (entry_index, entry) in policy.entries.iter().enumerate() {
if let Err(err) = entry.validate() {
diagnostics.errors.push(
Diagnostic::new(
err.code(),
format!("rule `{}` status policy: {err}", rule.id),
)
.with_path(format!("/rules/{position}/params/entries/{entry_index}")),
);
}
if let Some(selector) = &entry.tags
&& names_participants(selector)
{
diagnostics.errors.push(
Diagnostic::new(
"selector_not_for_items",
format!(
"rule `{}` matches block tags with an `ids`, `role` or `kind` clause, \
which can never match a block's tags",
rule.id
),
)
.with_path(format!(
"/rules/{position}/params/entries/{entry_index}/match"
)),
);
}
}
}
RuleKind::Cap(cap) => {
if let RuleZone::Named(name) = &cap.zone {
named_zone(name, "cap");
}
if cap.per == CapPer::Pooled && cap.zone == RuleZone::Participant {
diagnostics.errors.push(
Diagnostic::new(
"cap_pooled_participant_zone",
format!(
"rule `{}` is pooled, so it must read its buckets in `event` or a named \
zone: a pool has no single participant zone to bucket in",
rule.id
),
)
.with_path(format!("/rules/{position}/params/zone")),
);
}
if names_participants(&cap.count) {
diagnostics.errors.push(
Diagnostic::new(
"selector_not_for_items",
format!(
"rule `{}` counts events with an `ids`, `role` or `kind` clause, which can \
never match an event's tags",
rule.id
),
)
.with_path(format!("/rules/{position}/params/count")),
);
}
}
RuleKind::Clearance(_) | RuleKind::Rest(_) => {}
}
}
fn check_occurrences(request: &Request, diagnostics: &mut Diagnostics) {
let mut seen = BTreeSet::new();
for (index, occurrence) in request.occurrences.iter().enumerate() {
let key = occurrence.event_key.trim();
if key.is_empty() {
diagnostics.errors.push(
Diagnostic::new(
"event_key_empty",
format!(
"occurrence {index} has an empty or whitespace-only event key, which \
would merge unrelated events into one cap count"
),
)
.with_path(format!("/occurrences/{index}/event_key")),
);
} else if !seen.insert(occurrence.event_key.as_str()) {
diagnostics.errors.push(
Diagnostic::new(
"occurrence_key_duplicate",
format!(
"occurrence event key `{}` appears more than once, so the event would have \
two spans",
occurrence.event_key
),
)
.with_path(format!("/occurrences/{index}/event_key")),
);
}
if occurrence.participants.is_empty() {
diagnostics.errors.push(
Diagnostic::new(
"occurrence_without_participants",
format!(
"occurrence `{}` names no participants",
occurrence.event_key
),
)
.with_path(format!("/occurrences/{index}/participants")),
);
}
}
}
fn check_limits(engine: &Engine, request: &Request, diagnostics: &mut Diagnostics) {
let limits = engine.limits();
if let Some(explain) = &request.explain
&& explain.limit > limits.max_explain_limit
{
diagnostics.errors.push(
Diagnostic::new(
"explain_limit",
format!(
"the request asks for {} explanation reasons, above the configured maximum \
of {}",
explain.limit, limits.max_explain_limit
),
)
.with_path("/explain/limit".to_owned()),
);
}
diagnostics.errors.extend(size_limit_diagnostics(
limits,
&request.participants,
&request.rules,
));
for (index, participant) in request.participants.iter().enumerate() {
if participant.blocks().len() > limits.max_blocks_per_participant {
diagnostics.errors.push(
Diagnostic::new(
"blocks_limit",
format!(
"participant `{}` holds {} blocks, above the configured maximum of {}",
participant.id,
participant.blocks().len(),
limits.max_blocks_per_participant
),
)
.with_path(format!("/participants/{index}/calendar")),
);
}
}
if request.occurrences.len() > limits.max_occurrences {
diagnostics.errors.push(
Diagnostic::new(
"occurrences_limit",
format!(
"the request holds {} occurrences, above the configured maximum of {}",
request.occurrences.len(),
limits.max_occurrences
),
)
.with_path("/occurrences".to_owned()),
);
}
check_exclude_event_keys(limits, request, diagnostics);
check_requirement_limits(limits, request, diagnostics);
}
fn check_exclude_event_keys(limits: &Limits, request: &Request, diagnostics: &mut Diagnostics) {
let keys = &request.exclude_event_keys;
if keys.len() > limits.max_occurrences {
diagnostics.errors.push(
Diagnostic::new(
"exclude_event_keys_limit",
format!(
"the request excludes {} event keys, above the configured maximum of {}",
keys.len(),
limits.max_occurrences
),
)
.with_path("/exclude_event_keys".to_owned()),
);
return;
}
for (index, key) in keys.iter().enumerate() {
if key.trim().is_empty() {
diagnostics.errors.push(
Diagnostic::new(
"event_key_empty",
format!(
"excluded event key {index} is empty or whitespace-only, so it would \
exclude no event"
),
)
.with_path(format!("/exclude_event_keys/{index}")),
);
}
}
}
fn check_requirement_limits(limits: &Limits, request: &Request, diagnostics: &mut Diagnostics) {
if request.goal.parts.len() != 1 {
return;
}
for (index, part) in request.goal.parts.iter().enumerate() {
let path = format!("/goal/parts/{index}/requirement/all");
let slots = part.requirement.slots();
if slots > limits.max_requirement_slots {
diagnostics.errors.push(
Diagnostic::new(
"requirement_slots_limit",
format!(
"part `{}` asks for {slots} hosts, above the configured maximum of {}",
part.id, limits.max_requirement_slots
),
)
.with_path(path.clone()),
);
}
let terms = part.requirement.terms.len();
if terms > limits.max_requirement_slots {
diagnostics.errors.push(
Diagnostic::new(
"requirement_terms_limit",
format!(
"part `{}` names {terms} requirement terms, above the configured maximum \
of {}",
part.id, limits.max_requirement_slots
),
)
.with_path(path),
);
}
}
}
pub(crate) fn size_limit_diagnostics<'a>(
limits: &'a Limits,
participants: &'a [Participant],
rules: &'a [Rule],
) -> impl Iterator<Item = Diagnostic> + 'a {
let over_participants = (participants.len() > limits.max_participants).then(|| {
Diagnostic::new(
"participants_limit",
format!(
"the request holds {} participants, above the configured maximum of {}",
participants.len(),
limits.max_participants
),
)
.with_path("/participants".to_owned())
});
let over_rules = (rules.len() > limits.max_rules).then(|| {
Diagnostic::new(
"rules_limit",
format!(
"the request holds {} rules, above the configured maximum of {}",
rules.len(),
limits.max_rules
),
)
.with_path("/rules".to_owned())
});
over_participants
.into_iter()
.chain(zone_periods_diagnostics(
limits.max_zone_periods_per_participant,
participants,
))
.chain(over_rules)
}
fn zone_periods_diagnostics(
cap: usize,
participants: &[Participant],
) -> impl Iterator<Item = Diagnostic> + '_ {
participants
.iter()
.enumerate()
.filter_map(move |(index, participant)| {
let periods = participant.zone_periods.len();
(periods > cap).then(|| {
Diagnostic::new(
"zone_periods_limit",
format!(
"participant `{}` holds {periods} zone periods, above the configured \
maximum of {cap}",
participant.id
),
)
.with_path(format!("/participants/{index}/zone_periods"))
})
})
}
fn check_durations(engine: &Engine, request: &Request, diagnostics: &mut Diagnostics) {
let maximum = i64::from(engine.limits().max_duration_minutes);
for (index, participant) in request.participants.iter().enumerate() {
for (block_index, block) in participant.blocks().iter().enumerate() {
for (field, duration) in [
("before", block.travel_before),
("after", block.travel_after),
] {
if duration.minutes() <= maximum {
continue;
}
check_duration(
diagnostics,
maximum,
duration,
"block_travel_duration_too_long",
&format!(
"the travel {field} block {block_index} of participant `{}`",
participant.id
),
format!("/participants/{index}/calendar/{block_index}/travel_{field}"),
);
}
}
}
for (index, part) in request.goal.parts.iter().enumerate() {
check_duration(
diagnostics,
maximum,
part.duration,
"part_duration_too_long",
&format!("part `{}`'s booking", part.id),
format!("/goal/parts/{index}/duration"),
);
for (field, duration) in [("before", part.travel.before), ("after", part.travel.after)] {
check_duration(
diagnostics,
maximum,
duration,
"travel_duration_too_long",
&format!("part `{}`'s travel {field} the booking", part.id),
format!("/goal/parts/{index}/travel/{field}"),
);
}
for (id, travel) in &part.travel.by_participant {
for (field, duration) in [("before", travel.before), ("after", travel.after)] {
check_duration(
diagnostics,
maximum,
duration,
"travel_duration_too_long",
&format!("participant `{id}`'s travel {field} the booking"),
format!(
"/goal/parts/{index}/travel/by_participant/{}/{field}",
escape_pointer_token(id)
),
);
}
}
}
for (index, rule) in request.rules.iter().enumerate() {
let RuleKind::Clearance(clearance) = &rule.kind else {
continue;
};
for (field, duration) in [
("before", clearance.before),
("after", clearance.after),
("min_gap", clearance.min_gap),
] {
check_duration(
diagnostics,
maximum,
duration,
"clearance_duration_too_long",
&format!("clearance rule `{}`'s `{field}`", rule.id),
format!("/rules/{index}/params/{field}"),
);
}
}
}
fn search_window_within_limit(limits: &Limits, window: Span) -> bool {
window.minutes() <= i64::from(limits.max_search_window_days) * 24 * 60
}
fn search_envelope_limit(limits: &Limits) -> i64 {
(i64::from(limits.max_search_window_days) * 24 * 60)
.saturating_add(i64::from(limits.max_duration_minutes).saturating_mul(3))
.max(1)
}
fn check_duration(
diagnostics: &mut Diagnostics,
maximum: i64,
duration: Duration,
code: &'static str,
what: &str,
path: String,
) {
let minutes = duration.minutes();
if minutes > maximum {
diagnostics.errors.push(
Diagnostic::new(
code,
format!(
"{what} lasts {minutes} minutes, above the configured maximum of {maximum}"
),
)
.with_path(path),
);
}
}
fn check_search_limits(
engine: &Engine,
request: &Request,
candidates: &[Instant],
diagnostics: &mut Diagnostics,
) {
let limits = engine.limits();
let window_minutes = request.goal.search_window.minutes();
if !search_window_within_limit(limits, request.goal.search_window) {
diagnostics.errors.push(
Diagnostic::new(
"search_window_limit",
format!(
"the search window is {window_minutes} minutes, above the configured maximum \
of {} days",
limits.max_search_window_days
),
)
.with_path("/goal/search_window".to_owned()),
);
}
let exact = request.goal.candidates.is_some();
let count = request
.goal
.candidates
.as_ref()
.map_or(candidates.len(), Vec::len);
if count > limits.max_candidate_starts {
let field = if exact {
"/goal/candidates"
} else {
"/goal/grid"
};
diagnostics.errors.push(
Diagnostic::new(
"candidates_limit",
format!(
"the search produces {} candidate starts, above the configured maximum of {}",
if exact {
count.to_string()
} else {
format!("more than {}", limits.max_candidate_starts)
},
limits.max_candidate_starts
),
)
.with_path(field.to_owned()),
);
}
}
fn check_requirement(
request: &Request,
participant_ids: &BTreeSet<&str>,
diagnostics: &mut Diagnostics,
) {
let mut by_id: BTreeMap<&str, &Participant> = BTreeMap::new();
for participant in &request.participants {
by_id.entry(participant.id.as_str()).or_insert(participant);
}
for (part_index, part) in request.goal.parts.iter().enumerate() {
let terms_path = format!("/goal/parts/{part_index}/requirement/all");
if part.requirement.slots() == 0 {
diagnostics.errors.push(
Diagnostic::new(
"requirement_unfillable",
format!(
"part `{}` asks for no host, so no host can be assigned to it",
part.id
),
)
.with_path(terms_path),
);
}
let mut short = false;
for (index, term) in part.requirement.terms.iter().enumerate() {
short |= check_term(
request,
&by_id,
participant_ids,
part,
part_index,
index,
term,
diagnostics,
);
}
if !short {
check_joint_fillability(request, part_index, part, diagnostics);
}
for id in part.travel.by_participant.keys() {
if !participant_ids.contains(id.as_str()) {
diagnostics.errors.push(
Diagnostic::new(
"participant_unknown",
format!(
"part `{}` travel override names participant `{id}`, which the request \
does not carry",
part.id
),
)
.with_path(format!(
"/goal/parts/{part_index}/travel/by_participant/{}",
escape_pointer_token(id)
)),
);
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn check_term(
request: &Request,
by_id: &BTreeMap<&str, &Participant>,
participant_ids: &BTreeSet<&str>,
part: &Part,
part_index: usize,
index: usize,
term: &Term,
diagnostics: &mut Diagnostics,
) -> bool {
let term_path = format!("/goal/parts/{part_index}/requirement/all/{index}");
match term {
Term::Person { id } => match by_id.get(id.as_str()).copied() {
None => {
diagnostics.errors.push(
Diagnostic::new(
"participant_unknown",
format!(
"part `{}` term {index} names participant `{id}`, which the request \
does not carry",
part.id
),
)
.with_path(term_path),
);
true
}
Some(participant) if participant.role != Role::Host => {
diagnostics.errors.push(
Diagnostic::new(
"requirement_unfillable",
format!(
"part `{}` term {index} names `{id}`, who is an attendee and so cannot \
be assigned",
part.id
),
)
.with_path(term_path),
);
true
}
Some(_) => false,
},
Term::AtLeast { count, of } => {
for id in named_ids(of) {
if !participant_ids.contains(id) {
diagnostics.errors.push(
Diagnostic::new(
"participant_unknown",
format!(
"part `{}` term {index} names participant `{id}`, which the \
request does not carry",
part.id
),
)
.with_path(term_path.clone()),
);
}
}
let hosts = request
.participants
.iter()
.filter(|participant| participant.role == Role::Host)
.filter(|participant| of.matches_participant(participant.context()))
.count();
if hosts < *count as usize {
diagnostics.errors.push(
Diagnostic::new(
"requirement_unfillable",
format!(
"part `{}` term {index} needs {count} hosts, but only {hosts} \
participant(s) match it",
part.id
),
)
.with_path(term_path),
);
true
} else {
false
}
}
}
}
fn check_joint_fillability(
request: &Request,
part_index: usize,
part: &Part,
diagnostics: &mut Diagnostics,
) {
let candidates: Vec<Vec<matching::Candidate<'_>>> = part
.requirement
.terms
.iter()
.map(|term| {
request
.participants
.iter()
.filter(|participant| term.filled_by(participant))
.map(|participant| matching::Candidate {
id: &participant.id,
weight: 0,
})
.collect()
})
.collect();
let terms: Vec<matching::Term<'_>> = part
.requirement
.terms
.iter()
.zip(&candidates)
.map(|(term, candidates)| matching::Term {
count: term.slots(),
candidates: candidates.as_slice(),
})
.collect();
if !matching::jointly_fillable(&terms) {
diagnostics.errors.push(
Diagnostic::new(
"requirement_unfillable",
format!(
"part `{}` cannot be filled: its terms cannot jointly be given distinct hosts, \
even if every participant were free",
part.id
),
)
.with_path(format!("/goal/parts/{part_index}/requirement/all")),
);
}
}
fn check_rule_reachability(request: &Request, part_tags: &[Tag], diagnostics: &mut Diagnostics) {
let mut reported = BTreeSet::new();
let mut present = BTreeSet::new();
for (position, rule) in request.rules.iter().enumerate() {
if !rule.when.matches_item(part_tags) {
diagnostics.warnings.push(
Diagnostic::new(
"when_matches_no_part",
format!(
"rule `{}` can never apply: its `when` matches no part of this request",
rule.id
),
)
.with_path(format!("/rules/{position}/when")),
);
}
if let RuleKind::Cap(cap) = &rule.kind
&& rule.when.matches_item(part_tags)
&& !cap.count.matches_item(part_tags)
{
diagnostics.warnings.push(
Diagnostic::new(
"count_matches_no_part",
format!(
"cap `{}` selects this booking but its `count` matches no part of it, so \
it constrains nothing: check `params/count`",
rule.id
),
)
.with_path(format!("/rules/{position}/params/count")),
);
}
warn_about_absent_tags(
named_tags(&rule.who)
.into_iter()
.map(|tag| (tag, format!("/rules/{position}/who"))),
request,
&mut reported,
&mut present,
diagnostics,
);
}
let requirement_tags: Vec<(&Tag, String)> = request
.goal
.parts
.iter()
.enumerate()
.flat_map(|(part_index, part)| {
part.requirement
.terms
.iter()
.enumerate()
.filter_map(move |(term_index, term)| match term {
Term::AtLeast { of, .. } => Some((
of,
format!("/goal/parts/{part_index}/requirement/all/{term_index}"),
)),
Term::Person { .. } => None,
})
})
.flat_map(|(selector, path)| {
named_tags(selector)
.into_iter()
.map(move |tag| (tag, path.clone()))
})
.collect();
warn_about_absent_tags(
requirement_tags,
request,
&mut reported,
&mut present,
diagnostics,
);
}
fn warn_about_ignored_resource_holds(
request: &Request,
part_tags: &[Tag],
diagnostics: &mut Diagnostics,
) {
for (position, rule) in request.rules.iter().enumerate() {
let RuleKind::StatusPolicy(policy) = &rule.kind else {
continue;
};
if !rule.when.matches_item(part_tags)
|| !policy
.entries
.iter()
.any(|entry| entry.effect == crate::model::StatusEffect::Ignore)
{
continue;
}
let mut selected = request
.participants
.iter()
.filter(|participant| participant.kind == ParticipantKind::Resource)
.filter(|participant| rule.who.matches_participant(participant.context()))
.map(|participant| participant.id.as_str());
let Some(first) = selected.next() else {
continue;
};
let others = match selected.count() {
0 => String::new(),
count => format!(" and {count} more"),
};
diagnostics.warnings.push(
Diagnostic::new(
"status_policy_ignores_resource",
format!(
"status policy `{}` ignores blocks for resource participant `{first}`{others}, \
so a block it matches on that room is read as free rather than as taken and a \
second booking can be offered over it: if the policy is meant for people, \
scope `who` to `{{ \"kind\": \"person\" }}`",
rule.id
),
)
.with_path(format!("/rules/{position}")),
);
}
}
fn warn_about_keyless_blocks(request: &Request, part_tags: &[Tag], diagnostics: &mut Diagnostics) {
let pooled: Vec<(&Rule, &Cap)> = request
.rules
.iter()
.filter_map(|rule| match &rule.kind {
RuleKind::Cap(cap)
if cap.per == CapPer::Pooled
&& rule.when.matches_item(part_tags)
&& cap.count.matches_item(part_tags) =>
{
Some((rule, cap))
}
_ => None,
})
.collect();
if pooled.is_empty() {
return;
}
let mut keyless: Vec<Option<Vec<&Block>>> = vec![None; request.participants.len()];
for (rule, cap) in pooled {
for (index, participant) in request.participants.iter().enumerate() {
if !rule.who.matches_participant(participant.context()) {
continue;
}
let blocks = keyless[index].get_or_insert_with(|| {
participant
.blocks()
.iter()
.filter(|block| !block.all_day && block.event_key.is_none())
.collect()
});
let missing = blocks
.iter()
.filter(|block| cap.count.matches_item(&block.tags))
.count();
if missing == 0 {
continue;
}
diagnostics.warnings.push(
Diagnostic::new(
"block_missing_event_key",
format!(
"participant `{}` holds {missing} block(s) with no event key that pooled cap \
`{}` counts one by one; give them a key or an occurrence, or a copy on \
another calendar counts twice",
participant.id, rule.id
),
)
.with_path(format!("/participants/{index}/calendar")),
);
}
}
}
fn warn_about_absent_tags<'a>(
tags: impl IntoIterator<Item = (&'a Tag, String)>,
request: &Request,
reported: &mut BTreeSet<&'a str>,
present: &mut BTreeSet<&'a str>,
diagnostics: &mut Diagnostics,
) {
for (tag, path) in tags {
let name = tag.as_str();
if reported.contains(name) || present.contains(name) {
continue;
}
let carried = request.participants.iter().any(|participant| {
participant
.tags
.iter()
.any(|item| tag.is_ancestor_or_self_of(item))
});
if carried {
present.insert(name);
} else {
reported.insert(name);
diagnostics.warnings.push(
Diagnostic::new(
"selector_matches_no_participant",
format!(
"no participant carries `{tag}`, so a selector naming it matches nobody"
),
)
.with_path(path),
);
}
}
}
fn candidate_occupied_spans(
part: &Part,
participant: Option<&str>,
candidates: &[Instant],
) -> Vec<MinuteSpan> {
let (before, after) = match participant {
Some(id) => part.travel.for_participant(id),
None => (part.travel.before, part.travel.after),
};
candidates
.iter()
.filter_map(|&start| {
if occupancy::overflow(start, part.duration, before, after).is_some() {
return None;
}
let span = Span::new(
Instant::from_minutes(start.minutes() - before.minutes()).ok()?,
Instant::from_minutes(start.minutes() + part.duration.minutes() + after.minutes())
.ok()?,
)
.ok()?;
MinuteSpan::new(span.start().minutes(), span.end().minutes()).ok()
})
.collect()
}
fn push_no_candidate_in_window(participant: &str, warnings: &mut Vec<Diagnostic>) {
warnings.push(
Diagnostic::new(
"no_candidate_in_window",
format!(
"no candidate's booking and travel fits inside every window that applies to \
`{participant}`"
),
)
.with_path("/goal/search_window".to_owned()),
);
}
#[allow(clippy::too_many_arguments)]
fn warn_if_no_candidate_fits_window_over_cap<'a>(
db: &TimeZoneDatabase,
event: &crate::time::Zone,
schedule: &ZoneSchedule,
home_zone_name: &'a str,
participant: &str,
windows: &[(&'a str, usize, &'a crate::time::WindowSpec)],
spans: &[MinuteSpan],
envelope_limit: i64,
memos: &mut BTreeMap<MinuteSpan, FixedMinutes<'a>>,
diagnostics: &mut Diagnostics,
) {
if windows.is_empty() || spans.is_empty() {
return;
}
let mut groups: Vec<(usize, usize, MinuteSpan)> = Vec::new();
let mut total_work = 0_i64;
let mut from = 0;
while from < spans.len() {
let mut until = from + 1;
while until < spans.len()
&& spans[until].end().saturating_sub(spans[from].start()) <= envelope_limit
{
until += 1;
}
let Ok(occupied) = MinuteSpan::new(spans[from].start(), spans[until - 1].end()) else {
from = until;
continue;
};
let group_work = occupied.end().saturating_sub(occupied.start()).max(1_440);
total_work = total_work.saturating_add(group_work);
if total_work > envelope_limit {
return;
}
groups.push((from, until, occupied));
from = until;
}
let mut inside = false;
for (from, until, occupied) in groups {
let group = &spans[from..until];
let memo = memos.entry(occupied).or_default();
let ctx = WindowContext {
db,
schedule,
home_zone_name,
event,
judged: occupied,
};
let mut allowed: Option<Arc<IntervalSet>> = None;
let mut failed_build = false;
for &(_, position, spec) in windows {
let Ok(minutes) = memo.window(position, spec, &ctx) else {
failed_build = true;
break;
};
allowed = Some(match allowed {
Some(current) => Arc::new(current.intersection(&minutes)),
None => minutes,
});
if allowed.as_ref().is_some_and(|set| set.is_empty()) {
break;
}
}
if !failed_build
&& allowed.is_some_and(|allowed| group.iter().any(|span| allowed.contains_span(span)))
{
inside = true;
break;
}
}
if !inside {
push_no_candidate_in_window(participant, &mut diagnostics.warnings);
}
}
fn occupied_span(part: &Part, participant: &str, start: Instant) -> Option<Span> {
let (before, after) = part.travel.for_participant(participant);
if occupancy::overflow(start, part.duration, before, after).is_some() {
return None;
}
Span::new(
Instant::from_minutes(start.minutes() - before.minutes()).ok()?,
Instant::from_minutes(start.minutes() + part.duration.minutes() + after.minutes()).ok()?,
)
.ok()
}
#[allow(clippy::too_many_arguments)]
fn warn_if_horizon_ends_first(
calendars: &BTreeMap<String, WorkingCalendar>,
request: &Request,
applicable: &crate::rules::Applicable<'_>,
participant: &str,
event: &crate::time::Zone,
horizon_end: Option<Instant>,
bounds: &mut BTreeMap<usize, StartBound>,
diagnostics: &mut Diagnostics,
) {
if applicable.lead_max.is_empty() {
return;
}
let travel_before = request.goal.parts.first().map_or(0, |part| {
part.travel.for_participant(participant).0.minutes()
});
let earliest = Instant::from_minutes(
request
.now
.minutes()
.saturating_add(applicable.lead_min.minutes())
.saturating_add(travel_before)
.min(Instant::MAX.minutes()),
)
.expect("a start no earlier than `now` and no later than `Instant::MAX` is supported");
for lead in &applicable.lead_max {
let bound = if let Some(bound) = bounds.get(&lead.position) {
bound.clone()
} else {
let Ok(bound) =
resolve_lead_bound(request.now, calendars, lead.max, event, horizon_end)
else {
continue;
};
bounds.insert(lead.position, bound.clone());
bound
};
if !bound.allows(earliest) {
diagnostics.warnings.push(
Diagnostic::new(
"horizon_before_earliest_start",
format!(
"the `lead_time` maximum ends before `{earliest}`, the earliest start \
`{participant}`'s notice allows"
),
)
.with_path(format!("/rules/{}/params/max", lead.position)),
);
return;
}
}
}
pub(crate) fn check_proposal<'a>(
request: &Request,
proposal: &'a Proposal,
) -> Result<&'a ProposalEvent, Error> {
let mut seen: BTreeSet<&str> = BTreeSet::new();
for (index, event) in proposal.events.iter().enumerate() {
if !request.goal.parts.iter().any(|part| part.id == event.part) {
return Err(Error::malformed_proposal(
"proposal_part_unknown",
format!("the goal has no part `{}`", event.part),
format!("/events/{index}/part"),
));
}
if !seen.insert(event.part.as_str()) {
return Err(Error::malformed_proposal(
"proposal_part_duplicated",
format!("part `{}` is proposed more than once", event.part),
format!("/events/{index}/part"),
));
}
}
let mut only: Option<&'a ProposalEvent> = None;
for part in &request.goal.parts {
let Some((index, event)) = proposal
.events
.iter()
.enumerate()
.find(|(_, event)| event.part == part.id)
else {
return Err(Error::malformed_proposal(
"proposal_part_missing",
format!("the proposal has no event for part `{}`", part.id),
"/events".to_owned(),
));
};
check_assignment(request, part, index, event)?;
check_occupied_range(request, part, index, event)?;
only = Some(event);
}
only.ok_or_else(|| {
Error::malformed_proposal(
"proposal_part_missing",
"the request has no part to propose".to_owned(),
"/events".to_owned(),
)
})
}
fn check_assignment(
request: &Request,
part: &crate::model::Part,
event_index: usize,
event: &ProposalEvent,
) -> Result<(), Error> {
let terms = &part.requirement.terms;
let assignment_path = format!("/events/{event_index}/assignment");
if event.assignment.len() != terms.len() {
return Err(Error::malformed_proposal(
"proposal_term_count",
format!(
"part `{}` has {} term(s), but the proposal lists {}",
part.id,
terms.len(),
event.assignment.len()
),
assignment_path,
));
}
let mut assigned: BTreeSet<&str> = BTreeSet::new();
for (index, (term, hosts)) in terms.iter().zip(&event.assignment).enumerate() {
let term_path = format!("{assignment_path}/{index}");
let expected = match term {
Term::Person { .. } => 1,
Term::AtLeast { count, .. } => *count as usize,
};
if hosts.len() != expected {
return Err(Error::malformed_proposal(
"proposal_host_count",
format!(
"part `{}` term {index} needs {expected} host(s), but the proposal lists {}",
part.id,
hosts.len()
),
term_path,
));
}
for (slot, id) in hosts.iter().enumerate() {
let host_path = format!("{term_path}/{slot}");
let malformed =
|code, message| Error::malformed_proposal(code, message, host_path.clone());
let Some(participant) = request.participants.iter().find(|item| item.id == *id) else {
return Err(malformed(
"proposal_host_unknown",
format!("the request carries no participant `{id}`"),
));
};
if participant.role != Role::Host {
return Err(malformed(
"proposal_host_attendee",
format!("participant `{id}` is an attendee, who is never assigned a booking"),
));
}
if !term.filled_by(participant) {
return Err(malformed(
"proposal_host_mismatch",
format!(
"participant `{id}` does not fill term {index} of part `{}`",
part.id
),
));
}
if !assigned.insert(id.as_str()) {
return Err(malformed(
"proposal_host_duplicated",
format!("participant `{id}` is assigned more than once"),
));
}
}
}
Ok(())
}
fn check_occupied_range(
request: &Request,
part: &crate::model::Part,
event_index: usize,
event: &ProposalEvent,
) -> Result<(), Error> {
let path = format!("/events/{event_index}/start");
let out_of_range =
|message: String| Error::malformed_proposal("proposal_out_of_range", message, path.clone());
if occupancy::overflow(event.start, part.duration, Duration::ZERO, Duration::ZERO).is_some() {
return Err(out_of_range(format!(
"the booking at {} lasts {}, which reaches past the last supported instant {}",
event.start,
part.duration,
Instant::MAX
)));
}
let mut needed: Vec<&str> = event
.assignment
.iter()
.flatten()
.map(String::as_str)
.collect();
needed.extend(
request
.participants
.iter()
.filter(|participant| participant.role == Role::Attendee)
.map(|participant| participant.id.as_str()),
);
needed.sort_unstable();
needed.dedup();
for id in needed {
let (before, after) = part.travel.for_participant(id);
let Some(edge) = occupancy::overflow(event.start, part.duration, before, after) else {
continue;
};
let message = match edge {
occupancy::Edge::Before => format!(
"participant `{id}` needs {before} of travel before the booking at {}, which \
reaches before the first supported instant {}",
event.start,
Instant::MIN
),
occupancy::Edge::After => format!(
"participant `{id}` needs {after} of travel after the booking at {}, which \
reaches past the last supported instant {}",
event.start,
Instant::MAX
),
};
return Err(out_of_range(message));
}
Ok(())
}
#[cfg(all(test, feature = "bundled-tzdb"))]
mod tests {
use crate::Engine;
use crate::error::{Diagnostics, Error};
use crate::model::{
Block, CalendarSpec, Cap, CapMeasure, CapPer, CapPeriod, Clearance, Explain, Goal,
LeadTime, LeadTimeMax, Occurrence, Part, Participant, ParticipantTravel, Proposal, Request,
Requirement, Rule, RuleKind, Span, StatusEffect, StatusPolicy, StatusPolicyEntry, Term,
Travel, ZonePeriod,
};
use crate::tags::{Selector, Tag};
use crate::time::{
Date, Duration, Instant, RuleZone, TimeOfDay, WallEnd, WallRange, Weekday, Weekdays,
WindowSpec, ZoneName,
};
fn engine() -> Engine {
Engine::builder()
.build()
.expect("the bundled database builds")
}
fn zone() -> ZoneName {
ZoneName::new("UTC").unwrap()
}
fn at(minutes: i64) -> Instant {
Instant::from_minutes(Instant::MIN.minutes() + minutes).unwrap()
}
fn span(from: i64, until: i64) -> Span {
Span::new(at(from), at(until)).unwrap()
}
fn tag(path: &str) -> Tag {
Tag::new(path).unwrap()
}
fn base() -> Request {
let mut participant = Participant::new("ana", zone());
participant.calendar = Some(Vec::new());
let part = Part::new(
Duration::from_minutes(30),
Requirement::new(vec![Term::person("ana")]),
);
let mut request = Request::new(at(0), Goal::new(zone(), span(0, 24 * 60), vec![part]));
request.participants = vec![participant];
request
}
fn path(diagnostics: &Diagnostics, code: &str) -> Option<String> {
diagnostics
.errors
.iter()
.chain(&diagnostics.warnings)
.find(|finding| finding.code() == code)
.and_then(|finding| finding.path().map(str::to_owned))
}
#[test]
fn a_participant_finding_points_at_the_participant_field() {
let engine = engine();
let mut request = base();
request.participants.push(Participant::new(
"bo",
ZoneName::new("Mars/Olympus").unwrap(),
));
assert_eq!(
path(&engine.validate(&request), "zone_unknown").as_deref(),
Some("/participants/1/zone")
);
let mut request = base();
request.participants.push(Participant::new("ana", zone()));
assert_eq!(
path(&engine.validate(&request), "participant_duplicate").as_deref(),
Some("/participants/1/id")
);
let mut request = base();
request.occurrences = vec![Occurrence {
event_key: "evt".to_owned(),
span: span(0, 60),
tags: Vec::new(),
participants: Vec::new(),
}];
assert_eq!(
path(
&engine.validate(&request),
"occurrence_without_participants"
)
.as_deref(),
Some("/occurrences/0/participants")
);
}
#[test]
fn a_goal_finding_points_at_the_goal_field() {
let engine = engine();
let mut request = base();
request.goal.zone = ZoneName::new("Mars/Olympus").unwrap();
assert_eq!(
path(&engine.validate(&request), "zone_unknown").as_deref(),
Some("/goal/zone")
);
let mut request = base();
request.goal.parts[0].duration = Duration::ZERO;
assert_eq!(
path(&engine.validate(&request), "part_duration_empty").as_deref(),
Some("/goal/parts/0/duration")
);
let mut request = base();
request.goal.parts.clear();
assert_eq!(
path(&engine.validate(&request), "part_count").as_deref(),
Some("/goal/parts")
);
let mut request = base();
request.goal.grid = Some(
crate::time::Grid::new(
Duration::from_minutes(15),
TimeOfDay::MIDNIGHT,
crate::time::GridZone::Event,
)
.unwrap(),
);
request.goal.candidates = Some(vec![at(0)]);
assert_eq!(
path(&engine.validate(&request), "grid_and_candidates").as_deref(),
Some("/goal/candidates")
);
let mut request = base();
request.goal.parts[0]
.requirement
.terms
.push(Term::person("bo"));
assert_eq!(
path(&engine.validate(&request), "participant_unknown").as_deref(),
Some("/goal/parts/0/requirement/all/1")
);
let mut request = base();
request.goal.parts[0].travel = Travel {
before: Duration::ZERO,
after: Duration::ZERO,
by_participant: [(
"x/y".to_owned(),
ParticipantTravel {
before: Duration::ZERO,
after: Duration::ZERO,
},
)]
.into_iter()
.collect(),
};
assert_eq!(
path(&engine.validate(&request), "participant_unknown").as_deref(),
Some("/goal/parts/0/travel/by_participant/x~1y")
);
}
#[test]
fn a_rule_finding_points_at_the_rule_and_field() {
let engine = engine();
let mut request = base();
request.rules = vec![
Rule::new("r", RuleKind::Clearance(Clearance::default())),
Rule::new("r", RuleKind::Clearance(Clearance::default())),
];
assert_eq!(
path(&engine.validate(&request), "rule_id_duplicate").as_deref(),
Some("/rules/1/id")
);
let mut request = base();
request.rules = vec![
Rule::new("good", RuleKind::Clearance(Clearance::default())),
Rule::new(
"zoned",
RuleKind::Window(
WindowSpec::new(
RuleZone::Named(ZoneName::new("Mars/Olympus").unwrap()),
Vec::new(),
Vec::new(),
)
.unwrap(),
),
),
];
assert_eq!(
path(&engine.validate(&request), "zone_unknown").as_deref(),
Some("/rules/1/params/zone")
);
let mut request = base();
request.rules = vec![Rule::new(
"horizon",
RuleKind::LeadTime(LeadTime {
min: Duration::ZERO,
max: Some(LeadTimeMax::WorkingDays {
count: 3,
calendar: "org".to_owned(),
}),
}),
)];
assert_eq!(
path(&engine.validate(&request), "calendar_unknown").as_deref(),
Some("/rules/0/params/max/calendar")
);
let mut request = base();
request.rules = vec![Rule::new(
"policy",
RuleKind::StatusPolicy(StatusPolicy {
entries: vec![
StatusPolicyEntry::status(
crate::model::BlockStatus::Tentative,
StatusEffect::Ignore,
),
StatusPolicyEntry {
status: None,
tags: None,
effect: StatusEffect::Ignore,
},
],
}),
)];
assert_eq!(
path(&engine.validate(&request), "status_policy_entry_empty").as_deref(),
Some("/rules/0/params/entries/1")
);
let mut request = base();
request.rules = vec![Rule::new(
"policy",
RuleKind::StatusPolicy(StatusPolicy {
entries: vec![StatusPolicyEntry::tags(
Selector::ids(["ana"]),
StatusEffect::Block,
)],
}),
)];
assert_eq!(
path(&engine.validate(&request), "selector_not_for_items").as_deref(),
Some("/rules/0/params/entries/0/match")
);
}
#[test]
fn a_keyed_finding_escapes_the_pointer_token() {
let engine = engine();
let mut request = base();
request.calendars.insert(
"org/eu".to_owned(),
CalendarSpec {
zone: ZoneName::new("Mars/Olympus").unwrap(),
working_days: Weekdays::weekdays(),
holidays: Vec::new(),
},
);
assert_eq!(
path(&engine.validate(&request), "zone_unknown").as_deref(),
Some("/calendars/org~1eu/zone")
);
let mut request = base();
request.calendars.insert(
"org~eu".to_owned(),
CalendarSpec {
zone: ZoneName::new("Mars/Olympus").unwrap(),
working_days: Weekdays::weekdays(),
holidays: Vec::new(),
},
);
assert_eq!(
path(&engine.validate(&request), "zone_unknown").as_deref(),
Some("/calendars/org~0eu/zone")
);
let mut request = base();
request.weights.insert("a/b".to_owned(), 1);
assert_eq!(
path(&engine.validate(&request), "participant_unknown").as_deref(),
Some("/weights/a~1b")
);
}
#[test]
fn a_limit_finding_points_at_the_limited_field() {
let mut request = base();
request.explain = Some(Explain::new(1));
let limited = Engine::builder()
.limits(crate::Limits::default().with_max_explain_limit(0))
.build()
.unwrap();
assert_eq!(
path(&limited.validate(&request), "explain_limit").as_deref(),
Some("/explain/limit")
);
let mut request = base();
request.participants[0].calendar = Some(vec![Block::new(span(0, 30))]);
let limited = Engine::builder()
.limits(crate::Limits::default().with_max_blocks_per_participant(0))
.build()
.unwrap();
assert_eq!(
path(&limited.validate(&request), "blocks_limit").as_deref(),
Some("/participants/0/calendar")
);
let request = base();
let limited = Engine::builder()
.limits(
crate::Limits::default()
.with_max_search_window_days(0)
.with_max_candidate_starts(0),
)
.build()
.unwrap();
let diagnostics = limited.validate(&request);
assert_eq!(
path(&diagnostics, "search_window_limit").as_deref(),
Some("/goal/search_window")
);
assert_eq!(
path(&diagnostics, "candidates_limit").as_deref(),
Some("/goal/grid"),
"a grid that generates too many starts is reported at the grid"
);
let mut request = base();
request.goal.grid = None;
request.goal.candidates = Some(vec![at(0)]);
let diagnostics = limited.validate(&request);
assert_eq!(
path(&diagnostics, "candidates_limit").as_deref(),
Some("/goal/candidates")
);
}
#[test]
fn a_warning_points_at_the_clause_it_is_about() {
let engine = engine();
let mut request = base();
request.rules = vec![
Rule::new("interview", RuleKind::Clearance(Clearance::default()))
.with_when(Selector::tag(tag("interview"))),
];
assert_eq!(
path(&engine.validate(&request), "when_matches_no_part").as_deref(),
Some("/rules/0/when")
);
let mut request = base();
request.rules = vec![
Rule::new("sales", RuleKind::Clearance(Clearance::default()))
.with_who(Selector::tag(tag("team/sales"))),
];
assert_eq!(
path(
&engine.validate(&request),
"selector_matches_no_participant"
)
.as_deref(),
Some("/rules/0/who")
);
let mut request = base();
request.goal.parts[0].requirement.terms =
vec![Term::at_least(1, Selector::tag(tag("pool/missing")))];
assert_eq!(
path(
&engine.validate(&request),
"selector_matches_no_participant"
)
.as_deref(),
Some("/goal/parts/0/requirement/all/0")
);
}
#[test]
fn a_malformed_proposal_points_at_the_field_that_does_not_fit() {
let engine = engine();
let mut request = base();
request
.participants
.push(Participant::attendee("bo", zone()));
request.goal.parts[0].requirement.terms = vec![Term::person("ana")];
let check = |proposal: &Proposal| {
engine
.check_slot(&request, proposal)
.expect_err("the proposal does not fit")
};
let unknown_part = check(&Proposal::single("other", at(0), vec![Vec::new()]));
assert_eq!(unknown_part.path(), Some("/events/0/part"));
assert_eq!(unknown_part.code(), "proposal_part_unknown");
let wrong_terms = check(&Proposal::single("main", at(0), Vec::new()));
assert_eq!(wrong_terms.path(), Some("/events/0/assignment"));
assert_eq!(wrong_terms.code(), "proposal_term_count");
let wrong_hosts = check(&Proposal::single("main", at(0), vec![Vec::new()]));
assert_eq!(wrong_hosts.path(), Some("/events/0/assignment/0"));
assert_eq!(wrong_hosts.code(), "proposal_host_count");
let unknown_host = check(&Proposal::single(
"main",
at(0),
vec![vec!["ghost".to_owned()]],
));
assert_eq!(unknown_host.path(), Some("/events/0/assignment/0/0"));
assert_eq!(unknown_host.code(), "proposal_host_unknown");
let attendee = check(&Proposal::single(
"main",
at(0),
vec![vec!["bo".to_owned()]],
));
assert_eq!(attendee.path(), Some("/events/0/assignment/0/0"));
assert_eq!(attendee.code(), "proposal_host_attendee");
let missing = engine
.check_slot(&request, &Proposal { events: Vec::new() })
.expect_err("the proposal carries no event");
assert_eq!(missing.path(), Some("/events"));
assert_eq!(missing.code(), "proposal_part_missing");
}
#[test]
fn a_cap_reason_path_points_at_the_cap_rule() {
let mut request = base();
let cap = Cap::new(
Selector::True,
CapMeasure::Count,
2,
CapPeriod::Day,
CapPer::Pooled,
RuleZone::Participant,
Weekday::Monday,
);
request.rules = vec![Rule::new("pooled", RuleKind::Cap(cap))];
assert_eq!(
path(&engine().validate(&request), "cap_pooled_participant_zone").as_deref(),
Some("/rules/0/params/zone")
);
}
#[test]
fn an_overlapping_zone_period_points_at_the_periods_list() {
let mut request = base();
request.participants[0].zone_periods = vec![
ZonePeriod::new(zone(), at(60), at(120)).unwrap(),
ZonePeriod::new(zone(), at(90), at(180)).unwrap(),
];
assert_eq!(
path(&engine().validate(&request), "zone_periods_overlap").as_deref(),
Some("/participants/0/zone_periods")
);
}
#[test]
fn the_model_errors_convert_into_the_crate_error() {
let window =
WallRange::new(TimeOfDay::MIDNIGHT, WallEnd::Time(TimeOfDay::MIDNIGHT)).unwrap_err();
assert_eq!(Error::from(window).code(), "window_range_empty");
let tag = Tag::new("").unwrap_err();
assert_eq!(Error::from(tag).code(), "tag_empty");
let blackout = crate::time::BlackoutSpan::new(
crate::time::LocalDateTime::new(Date::new(2027, 3, 10).unwrap(), TimeOfDay::MIDNIGHT),
crate::time::LocalDateTime::new(Date::new(2027, 3, 10).unwrap(), TimeOfDay::MIDNIGHT),
)
.unwrap_err();
assert_eq!(Error::from(blackout).code(), "blackout_span_empty");
}
}