use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, BTreeSet};
use crate::Engine;
use crate::error::{Diagnostic, Error};
use crate::model::{Cap, CapPeriod, Part, RangesQuery, RequiredRanges, RuleKind};
use crate::rules::{REST_REACH_MINUTES, RuleMatcher};
use crate::time::{Date, Instant, RuleZone, TimeZoneDatabase, Zone, ZoneSchedule};
pub(crate) fn required_ranges(
engine: &Engine,
query: &RangesQuery,
) -> Result<RequiredRanges, Error> {
let part = query.goal.part().ok_or(Error::PartCount {
parts: query.goal.parts.len(),
})?;
let over_cap: Vec<Diagnostic> =
crate::validate::size_limit_diagnostics(engine.limits(), &query.participants, &query.rules)
.collect();
if !over_cap.is_empty() {
return Err(Error::invalid_request(over_cap));
}
let db = engine.time_zone_database();
let mut clearance_before = 0;
let mut clearance_after = 0;
let mut has_rest = Vec::with_capacity(query.participants.len());
let matcher = RuleMatcher::new(&query.rules, &part.tags);
for participant in &query.participants {
let context = participant.context();
let applicable = matcher.select(context);
let clearance = applicable.clearance;
clearance_before = clearance_before.max(clearance.before.max(clearance.min_gap).minutes());
clearance_after = clearance_after.max(clearance.after.max(clearance.min_gap).minutes());
has_rest.push(!applicable.rests.is_empty());
}
let before = part.travel.largest_before().minutes() + clearance_before;
let after = part.duration.minutes() + part.travel.largest_after().minutes() + clearance_after;
let padded_start = Instant::from_minutes(
query
.goal
.search_window
.start()
.minutes()
.saturating_sub(before)
.max(Instant::MIN.minutes()),
)?;
let padded_end = Instant::from_minutes(
query
.goal
.search_window
.end()
.minutes()
.saturating_add(after)
.min(Instant::MAX.minutes()),
)?;
let rest_start = Instant::from_minutes(
padded_start
.minutes()
.saturating_sub(REST_REACH_MINUTES)
.max(Instant::MIN.minutes()),
)?;
let rest_end = Instant::from_minutes(
padded_end
.minutes()
.saturating_add(REST_REACH_MINUTES)
.min(Instant::MAX.minutes()),
)?;
let mut earliest = Instant::MAX;
let mut latest = Instant::MIN;
let mut resolved_zones: BTreeMap<&str, Zone> = BTreeMap::new();
let mut hulled: BTreeSet<(&str, bool)> = BTreeSet::new();
for (participant, &rest) in query.participants.iter().zip(&has_rest) {
let (reach_start, reach_end) = if rest {
(rest_start, rest_end)
} else {
(padded_start, padded_end)
};
let home = participant.zone.as_str();
let overlapping = participant
.zone_periods
.iter()
.filter(|period| reach_start < period.until() && period.from() < reach_end)
.map(|period| period.zone().as_str());
for zone_name in std::iter::once(home).chain(overlapping) {
if !hulled.insert((zone_name, rest)) {
continue;
}
let zone = match resolved_zones.entry(zone_name) {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(db.zone(zone_name)?),
};
let Some((from, until)) = hull_for(zone, reach_start, reach_end)? else {
continue;
};
earliest = earliest.min(from);
latest = latest.max(until);
}
}
let calendar = if earliest < latest {
crate::model::Span::new(earliest, latest)?
} else {
crate::model::Span::new(padded_start, padded_end)?
};
Ok(RequiredRanges {
calendar,
occurrences: occurrences_hull(query, db, part)?,
})
}
fn occurrences_hull(
query: &RangesQuery,
db: &TimeZoneDatabase,
part: &Part,
) -> Result<Option<crate::model::Span>, Error> {
let window = query.goal.search_window;
let mut earliest = Instant::MAX;
let mut latest = Instant::MIN;
let mut applies = false;
let mut reads: BTreeMap<usize, ParticipantRead> = BTreeMap::new();
let mut hulls: BTreeMap<HullKey, Hull> = BTreeMap::new();
for rule in &query.rules {
let RuleKind::Cap(cap) = &rule.kind else {
continue;
};
if !rule.when.matches_item(&part.tags) || !cap.count.matches_item(&part.tags) {
continue;
}
let covered: Vec<usize> = query
.participants
.iter()
.enumerate()
.filter(|(_, participant)| rule.who.matches_participant(participant.context()))
.map(|(index, _)| index)
.collect();
if covered.is_empty() {
continue;
}
applies = true;
match &cap.zone {
RuleZone::Participant => {
for index in covered {
let key = (index, cap.period.as_str(), cap.week_starts.index());
let hull = if let Some(hull) = hulls.get(&key) {
*hull
} else {
let read = match reads.entry(index) {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert({
let schedule =
crate::eval::resolve_schedule(db, &query.participants[index])?;
let dates = window_dates(&schedule, window)?;
ParticipantRead {
runs: zone_runs(&schedule),
dates,
}
}),
};
let hull = schedule_hull(read, cap)?;
hulls.insert(key, hull);
hull
};
if let Some((from, until)) = hull {
earliest = earliest.min(from);
latest = latest.max(until);
}
}
}
RuleZone::Event | RuleZone::Named(_) => {
let zone = fixed_zone(cap, db, query)?;
if let Some((from, until)) = zone_hull(&zone, cap, window.start(), window.end())? {
earliest = earliest.min(from);
latest = latest.max(until);
}
}
}
}
if !applies {
return Ok(None);
}
Ok(Some(crate::model::Span::new(earliest, latest)?))
}
struct ParticipantRead {
runs: Vec<ZoneRuns>,
dates: Option<(Date, Date)>,
}
struct ZoneRuns {
zone: Zone,
runs: Vec<(Instant, Instant)>,
}
type GroupedRuns<'a> = BTreeMap<&'a str, (Zone, Vec<(Instant, Instant)>)>;
fn zone_runs(schedule: &ZoneSchedule) -> Vec<ZoneRuns> {
let mut grouped: GroupedRuns<'_> = BTreeMap::new();
let mut cursor = Instant::MIN;
for period in schedule.periods() {
group(&mut grouped, schedule.home(), cursor, period.from());
group(&mut grouped, period.zone(), period.from(), period.until());
cursor = cursor.max(period.until());
}
if cursor < Instant::MAX {
group(&mut grouped, schedule.home(), cursor, Instant::MAX);
}
grouped
.into_values()
.map(|(zone, runs)| ZoneRuns { zone, runs })
.collect()
}
fn group<'a>(grouped: &mut GroupedRuns<'a>, zone: &'a Zone, from: Instant, until: Instant) {
if from < until {
grouped
.entry(zone.name())
.or_insert_with(|| (zone.clone(), Vec::new()))
.1
.push((from, until));
}
}
type HullKey = (usize, &'static str, u8);
type Hull = Option<(Instant, Instant)>;
fn fixed_zone(cap: &Cap, db: &TimeZoneDatabase, query: &RangesQuery) -> Result<Zone, Error> {
Ok(match &cap.zone {
RuleZone::Named(name) => db.zone(name.as_str())?,
RuleZone::Event | RuleZone::Participant => db.zone(query.goal.zone.as_str())?,
})
}
fn schedule_hull(read: &ParticipantRead, cap: &Cap) -> Result<Hull, Error> {
let Some((first, last)) = read.dates else {
return Ok(None);
};
let label_min = crate::caps::bucket_label(first, cap.period, cap.week_starts);
let label_after = bucket_after(
crate::caps::bucket_label(last, cap.period, cap.week_starts),
cap.period,
)?;
let mut hull: Option<(Instant, Instant)> = None;
for ZoneRuns { zone, runs } in &read.runs {
let bucket_from = day_start_clamped(zone, label_min, Instant::MIN);
let bucket_until = bucket_end(zone, label_after)?;
if bucket_from >= bucket_until {
continue;
}
let Some(&(from, _)) = runs.get(runs.partition_point(|(_, until)| *until <= bucket_from))
else {
continue;
};
let Some(index) = runs
.partition_point(|(start, _)| *start < bucket_until)
.checked_sub(1)
else {
continue;
};
let start = from.max(bucket_from);
let end = runs[index].1.min(bucket_until);
if start >= end {
continue;
}
hull = Some(match hull {
Some((earliest, latest)) => (earliest.min(start), latest.max(end)),
None => (start, end),
});
}
Ok(hull)
}
fn window_dates(
schedule: &ZoneSchedule,
window: crate::model::Span,
) -> Result<Option<(Date, Date)>, Error> {
let mut first: Option<Date> = None;
let mut last: Option<Date> = None;
for (zone, from, until) in schedule.legs(window.start(), window.end()) {
if until <= from {
continue;
}
let (earliest, latest) = zone.local_date_bounds(from, until)?;
first = Some(first.map_or(earliest, |current| current.min(earliest)));
last = Some(last.map_or(latest, |current| current.max(latest)));
}
Ok(first.zip(last))
}
fn zone_hull(
zone: &Zone,
cap: &Cap,
from: Instant,
until: Instant,
) -> Result<Option<(Instant, Instant)>, Error> {
if until <= from {
return Ok(None);
}
let (first, last) = zone.local_date_bounds(from, until)?;
let first_label = crate::caps::bucket_label(first, cap.period, cap.week_starts);
let last_label = crate::caps::bucket_label(last, cap.period, cap.week_starts);
let start = day_start_clamped(zone, first_label, Instant::MIN);
let end = bucket_end(zone, bucket_after(last_label, cap.period)?)?;
Ok((start < end).then_some((start, end)))
}
fn bucket_end(zone: &Zone, date: Date) -> Result<Instant, Error> {
let Some(previous) = date.plus_days(-1).ok() else {
return Ok(day_start_clamped(zone, date, Instant::MAX));
};
match zone.last_instant_on(previous)? {
Some(last) => Ok(Instant::from_minutes(last.minutes() + 1).unwrap_or(Instant::MAX)),
None => Ok(day_start_clamped(zone, date, Instant::MAX)),
}
}
fn bucket_after(label: Date, period: CapPeriod) -> Result<Date, Error> {
Ok(match period {
CapPeriod::Day => label.plus_days(1)?,
CapPeriod::Week => label.plus_days(7)?,
CapPeriod::Month => label.next_month_start()?,
})
}
fn hull_for(
zone: &Zone,
padded_start: Instant,
padded_end: Instant,
) -> Result<Option<(Instant, Instant)>, Error> {
if padded_end <= padded_start {
return Ok(None);
}
let (first, last) = zone.local_date_bounds(padded_start, padded_end)?;
let Some(from_date) = first.plus_days(-1).ok() else {
return Ok(Some((Instant::MIN, Instant::MAX)));
};
let Some(until_date) = last.plus_days(2).ok() else {
return Ok(Some((Instant::MIN, Instant::MAX)));
};
let from = day_start_clamped(zone, from_date, Instant::MIN);
let until = bucket_end(zone, until_date)?;
Ok(Some((from, until)))
}
fn day_start_clamped(zone: &Zone, date: Date, at_edge: Instant) -> Instant {
if date <= Instant::MIN.zoned(zone).date() {
return Instant::MIN;
}
if date > Instant::MAX.zoned(zone).date() {
return Instant::MAX;
}
zone.day_start(date).unwrap_or(at_edge)
}
#[cfg(all(test, feature = "bundled-tzdb"))]
mod tests {
use super::bucket_end;
use crate::time::{Date, LocalResolution, TimeOfDay, TimeZoneDatabase};
#[test]
fn a_bucket_ending_on_a_midnight_starting_fold_stops_at_the_first_midnight() {
let db = TimeZoneDatabase::bundled().unwrap();
let havana = db.zone("America/Havana").unwrap();
let next = Date::new(2018, 11, 4).unwrap();
let LocalResolution::Repeated(first, second) =
havana.resolve_local(next, TimeOfDay::MIDNIGHT).unwrap()
else {
panic!("2018-11-04 begins twice in Havana");
};
assert_eq!(second.minutes() - first.minutes(), 60);
assert_eq!(
havana.zoned(second).date(),
next,
"the second midnight already reads the next date"
);
assert_eq!(bucket_end(&havana, next).unwrap(), first);
}
}