opportune/model/rule.rs
1//! The rule envelope and the seven rule kinds version 1 evaluates.
2
3use crate::error::Error;
4use crate::model::BlockStatus;
5use crate::tags::{Role, Selector};
6use crate::time::{BlackoutSpec, Date, Duration, RuleZone, TimeOfDay, Weekday, WindowSpec};
7/// One rule: an ID, which participants it constrains, which bookings it applies
8/// to, and the kind-specific parameters.
9///
10/// A rule with no `who` applies to every host, and a rule with no `when` applies
11/// to every booking. Rules are the caller's final list: the engine combines them
12/// by fixed semantics and never decides which rules apply in a governance sense.
13///
14/// # How rules of one kind combine
15///
16/// Every rule that applies to the participant and to the booking is applied; a
17/// later rule never replaces an earlier one. Combination is per kind:
18///
19/// - `window` rules **intersect**: a booking has to lie inside every applicable
20/// window, so two windows that both apply leave only the hours they share. A
21/// week with different hours per day is therefore one window (see
22/// [`crate::presets::weekly_hours`]), not one rule per day.
23/// - `blackout` rules **union**: a booking is blocked when any applicable
24/// blackout covers it.
25/// - `clearance` rules take the **field-wise maximum**: `before`, `after` and
26/// `min_gap` are each the largest value any applicable rule asks for, never a
27/// sum, so ten minutes of buffer beside a five-minute buffer stays ten.
28/// - `lead_time` rules take the **strictest** of every bound: the largest `min`
29/// is the notice required, and of every `max` the one that permits the fewest
30/// starts wins, so the shortest allowed range results.
31/// - `status_policy` entries are tried **in request order across every
32/// applicable policy**, and the first entry that matches a block decides
33/// whether it blocks.
34/// - `rest` rules are **independent**: one rule's `late_after` is never paired
35/// with another rule's `not_before`.
36/// - `cap` rules are **independent and all binding**: a booking has to fit under
37/// every applicable cap's own bucket. A cap applies only when its `when` and
38/// its `count` both select the booking, so a cap measuring another kind of
39/// event does not constrain this one.
40///
41/// ```
42/// use opportune::model::{Rule, RuleKind, StatusEffect, StatusPolicy, StatusPolicyEntry};
43///
44/// let policy = StatusPolicy {
45/// entries: vec![StatusPolicyEntry::status(
46/// opportune::model::BlockStatus::Tentative,
47/// StatusEffect::Ignore,
48/// )],
49/// };
50/// let rule = Rule::new("r_7f3c", RuleKind::StatusPolicy(policy));
51/// assert_eq!(rule.who, opportune::tags::Selector::Role(opportune::tags::Role::Host));
52/// assert_eq!(rule.when, opportune::tags::Selector::True);
53/// ```
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct Rule {
56 /// The rule's ID, unique in the request. Reasons cite it.
57 pub id: String,
58 /// The kind and its parameters.
59 pub kind: RuleKind,
60 /// Which participants the rule constrains. Defaults to every host.
61 pub who: Selector,
62 /// Which bookings it applies to, matched against the part's tags. Defaults
63 /// to all of them.
64 pub when: Selector,
65}
66
67impl Rule {
68 /// A rule applying to every host and every booking.
69 #[must_use]
70 pub fn new(id: impl Into<String>, kind: RuleKind) -> Self {
71 Self {
72 id: id.into(),
73 kind,
74 who: Selector::Role(Role::Host),
75 when: Selector::True,
76 }
77 }
78
79 /// The rule with its ID replaced.
80 #[must_use]
81 pub fn with_id(mut self, id: impl Into<String>) -> Self {
82 self.id = id.into();
83 self
84 }
85
86 /// The rule with its `who` selector replaced.
87 #[must_use]
88 pub fn with_who(mut self, who: Selector) -> Self {
89 self.who = who;
90 self
91 }
92
93 /// The rule with its `when` selector replaced.
94 #[must_use]
95 pub fn with_when(mut self, when: Selector) -> Self {
96 self.when = when;
97 self
98 }
99
100 /// The rule with `who` narrowed to the participants `selector` also selects.
101 ///
102 /// This is the participant-side twin of [`Rule::unless`]: it **intersects**
103 /// with the rule's existing `who` instead of replacing it, so a rule that
104 /// already applies to every host keeps applying to hosts and only to those
105 /// hosts the selector picks out. [`Rule::with_who`] replaces the default
106 /// `{"role": "host"}` outright, so `with_who(Selector::kind(Person))` reaches
107 /// every person, attendees included; `and_who` keeps the `Role::Host` clause
108 /// beside the new one and reaches human hosts alone.
109 ///
110 /// An unconditional `who` becomes `selector`; an `all` gains the selector as
111 /// one more clause, so chained calls stay flat rather than nesting an `all`
112 /// in an `all`; anything else becomes `all([existing, selector])`.
113 ///
114 /// ```
115 /// use opportune::model::ParticipantKind;
116 /// use opportune::presets;
117 /// use opportune::tags::{ParticipantContext, Role, Selector};
118 /// use opportune::time::{RuleZone, TimeOfDay, WallEnd, Weekday, Weekdays};
119 ///
120 /// let hours = presets::business_hours(
121 /// RuleZone::Participant,
122 /// Weekdays::single(Weekday::Monday),
123 /// TimeOfDay::new(9, 0).unwrap(),
124 /// WallEnd::Time(TimeOfDay::new(17, 0).unwrap()),
125 /// )
126 /// .unwrap()
127 /// .and_who(Selector::kind(ParticipantKind::Person));
128 /// assert_eq!(
129 /// hours.who,
130 /// Selector::all([
131 /// Selector::role(Role::Host),
132 /// Selector::kind(ParticipantKind::Person),
133 /// ]),
134 /// );
135 ///
136 /// let human_host = ParticipantContext {
137 /// id: "ana",
138 /// kind: ParticipantKind::Person,
139 /// role: Role::Host,
140 /// tags: &[],
141 /// };
142 /// let room_host = ParticipantContext {
143 /// id: "room-4",
144 /// kind: ParticipantKind::Resource,
145 /// role: Role::Host,
146 /// tags: &[],
147 /// };
148 /// let human_attendee = ParticipantContext {
149 /// id: "tom",
150 /// kind: ParticipantKind::Person,
151 /// role: Role::Attendee,
152 /// tags: &[],
153 /// };
154 /// assert!(hours.who.matches_participant(human_host));
155 /// assert!(!hours.who.matches_participant(room_host), "the room is not a person");
156 /// assert!(!hours.who.matches_participant(human_attendee), "an attendee is not a host");
157 /// ```
158 #[must_use]
159 pub fn and_who(mut self, selector: Selector) -> Self {
160 let existing = core::mem::replace(&mut self.who, Selector::True);
161 self.who = match existing {
162 Selector::True => selector,
163 Selector::All(mut clauses) => {
164 clauses.push(selector);
165 Selector::All(clauses)
166 }
167 other => Selector::all([other, selector]),
168 };
169 self
170 }
171
172 /// The rule with the participants `selector` selects excepted from `who`.
173 ///
174 /// This is the participant-side twin of [`Rule::unless`] and is written in
175 /// terms of [`Rule::and_who`]: it narrows `who` by `not(selector)`, so the
176 /// rule keeps applying to every host but the excepted ones.
177 ///
178 /// ```
179 /// use opportune::presets;
180 /// use opportune::tags::{ParticipantContext, Role, Selector, Tag};
181 ///
182 /// let cap = presets::cap_per_day(Selector::Tag(Tag::new("interview").unwrap()), 2)
183 /// .except_who(Selector::ids(["ceo"]));
184 /// assert_eq!(
185 /// cap.who,
186 /// Selector::all([Selector::role(Role::Host), Selector::not(Selector::ids(["ceo"]))]),
187 /// );
188 ///
189 /// let host = ParticipantContext {
190 /// id: "ana",
191 /// kind: opportune::model::ParticipantKind::Person,
192 /// role: Role::Host,
193 /// tags: &[],
194 /// };
195 /// let ceo = ParticipantContext { id: "ceo", ..host };
196 /// assert!(cap.who.matches_participant(host), "the cap still reaches ordinary hosts");
197 /// assert!(!cap.who.matches_participant(ceo), "the cap exempts the CEO");
198 /// ```
199 #[must_use]
200 pub fn except_who(self, selector: Selector) -> Self {
201 self.and_who(Selector::not(selector))
202 }
203
204 /// The rule with `selector` excepted from the bookings it applies to.
205 ///
206 /// This is how a broad tier is loosened for a narrow one. A rule whose
207 /// `when` is unconditional becomes `not(selector)`; one that is already
208 /// scoped keeps its scope and adds the exception, as
209 /// `all([existing, not(selector)])`.
210 ///
211 /// Excluding the exception from the broad rule is what makes a hierarchy
212 /// work: a window rule intersected with a second window leaves only the hours
213 /// the two share, so an exception written as another window on the narrow
214 /// tier could only narrow the booking further. A tier that should apply to
215 /// everything *but* the exception excludes it here instead.
216 ///
217 /// [`Rule::and_who`] and [`Rule::except_who`] are the participant-side twins
218 /// of this method, narrowing `who` rather than `when`.
219 ///
220 /// ```
221 /// use opportune::presets;
222 /// use opportune::tags::{Selector, Tag};
223 /// use opportune::time::{Duration, RuleZone, TimeOfDay, WallEnd, Weekday, Weekdays};
224 ///
225 /// let vip = Selector::tag(Tag::new("vip").unwrap());
226 /// let hours = presets::business_hours(
227 /// RuleZone::Participant,
228 /// Weekdays::single(Weekday::Monday),
229 /// TimeOfDay::new(9, 0).unwrap(),
230 /// WallEnd::Time(TimeOfDay::new(17, 0).unwrap()),
231 /// )
232 /// .unwrap()
233 /// .unless(vip.clone());
234 /// assert_eq!(hours.when, Selector::not(vip.clone()));
235 ///
236 /// let interview = Selector::tag(Tag::new("interview").unwrap());
237 /// let scoped = presets::buffers(Duration::from_minutes(10), Duration::from_minutes(10))
238 /// .with_when(interview.clone())
239 /// .unless(vip.clone());
240 /// assert_eq!(scoped.when, Selector::all([interview, Selector::not(vip)]));
241 /// ```
242 #[must_use]
243 pub fn unless(mut self, selector: Selector) -> Self {
244 let excluded = Selector::not(selector);
245 let existing = core::mem::replace(&mut self.when, Selector::True);
246 self.when = if matches!(existing, Selector::True) {
247 excluded
248 } else {
249 Selector::all([existing, excluded])
250 };
251 self
252 }
253
254 /// The window specification, when the rule is a window.
255 #[must_use]
256 pub fn window(&self) -> Option<&WindowSpec> {
257 match &self.kind {
258 RuleKind::Window(spec) => Some(spec),
259 _ => None,
260 }
261 }
262
263 /// The blackout specification, when the rule is a blackout.
264 #[must_use]
265 pub fn blackout(&self) -> Option<&BlackoutSpec> {
266 match &self.kind {
267 RuleKind::Blackout(spec) => Some(spec),
268 _ => None,
269 }
270 }
271
272 /// The clearance parameters, when the rule is a clearance.
273 #[must_use]
274 pub fn clearance(&self) -> Option<&Clearance> {
275 match &self.kind {
276 RuleKind::Clearance(clearance) => Some(clearance),
277 _ => None,
278 }
279 }
280
281 /// The lead-time parameters, when the rule is a lead-time rule.
282 #[must_use]
283 pub fn lead_time(&self) -> Option<&LeadTime> {
284 match &self.kind {
285 RuleKind::LeadTime(lead_time) => Some(lead_time),
286 _ => None,
287 }
288 }
289
290 /// The status policy, when the rule is a status policy.
291 #[must_use]
292 pub fn status_policy(&self) -> Option<&StatusPolicy> {
293 match &self.kind {
294 RuleKind::StatusPolicy(policy) => Some(policy),
295 _ => None,
296 }
297 }
298
299 /// The rest parameters, when the rule is a rest rule.
300 #[must_use]
301 pub fn rest(&self) -> Option<&Rest> {
302 match &self.kind {
303 RuleKind::Rest(rest) => Some(rest),
304 _ => None,
305 }
306 }
307
308 /// The cap parameters, when the rule is a cap.
309 #[must_use]
310 pub fn cap(&self) -> Option<&Cap> {
311 match &self.kind {
312 RuleKind::Cap(cap) => Some(cap),
313 _ => None,
314 }
315 }
316}
317
318/// The kinds of rule the engine evaluates. Each kind has one fixed meaning,
319/// which is what makes rules validatable, combinable and explainable.
320///
321/// The enum is `#[non_exhaustive]`: `0.2+` may add kinds without a breaking Rust
322/// bump, so a `match` outside this crate needs a `_` arm. Every kind listed here
323/// keeps its meaning.
324#[derive(Clone, Debug, PartialEq, Eq)]
325#[non_exhaustive]
326pub enum RuleKind {
327 /// When bookings may happen.
328 Window(WindowSpec),
329 /// When bookings may not happen.
330 Blackout(BlackoutSpec),
331 /// The gaps the new booking needs between meetings.
332 Clearance(Clearance),
333 /// How soon and how far ahead a booking may start.
334 LeadTime(LeadTime),
335 /// How statuses and tags affect availability.
336 StatusPolicy(StatusPolicy),
337 /// A late finish blocks an early start.
338 Rest(Rest),
339 /// A limit on how much of a period may be booked.
340 Cap(Cap),
341}
342
343impl RuleKind {
344 /// The kind's wire name: the `kind` a rule stores.
345 #[must_use]
346 pub const fn as_str(&self) -> &'static str {
347 match self {
348 Self::Window(_) => "window",
349 Self::Blackout(_) => "blackout",
350 Self::Clearance(_) => "clearance",
351 Self::LeadTime(_) => "lead_time",
352 Self::StatusPolicy(_) => "status_policy",
353 Self::Rest(_) => "rest",
354 Self::Cap(_) => "cap",
355 }
356 }
357}
358
359impl core::fmt::Display for RuleKind {
360 /// Formats the kind as its wire name.
361 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
362 f.write_str(self.as_str())
363 }
364}
365
366/// A `cap` rule: a limit on how much of a civil period a participant, or a pool
367/// of them, may already have booked.
368///
369/// `count` selects the events the cap measures, matched against occurrence and
370/// block tags whatever their status or `status_policy`: a cap measures workload,
371/// not availability. An all-day block is time away from work rather than meeting
372/// workload, so it never counts toward a cap itself, whatever its key or tags,
373/// though its tags still join the event an occurrence identifies. `measure` is the
374/// number of events or their minutes, where minutes are each event's own duration
375/// without travel. `period` is a civil day, week or month in `zone`, and a week
376/// starts on `week_starts` and runs seven civil days rather than following ISO
377/// weeks.
378///
379/// `per: each` limits each participant in `who` on their own; `per: pooled`
380/// limits them together and therefore needs a zone every event shares, so
381/// `pooled` with `zone: participant` is a validation error.
382///
383/// A cap applies to a booking only when the part's tags match both the rule's
384/// `when` and this `count`.
385///
386/// ```
387/// use opportune::model::{Cap, CapMeasure, CapPer, CapPeriod};
388/// use opportune::tags::{Selector, Tag};
389/// use opportune::time::{RuleZone, Weekday};
390///
391/// let cap = Cap::new(
392/// Selector::Tag(Tag::new("interview").unwrap()),
393/// CapMeasure::Count,
394/// 2,
395/// CapPeriod::Day,
396/// CapPer::Each,
397/// RuleZone::Participant,
398/// Weekday::Monday,
399/// );
400/// assert_eq!(cap.limit, 2);
401/// assert_eq!(cap.period, CapPeriod::Day);
402/// ```
403#[derive(Clone, Debug, PartialEq, Eq)]
404pub struct Cap {
405 /// Which events the cap measures, matched against their tags.
406 pub count: Selector,
407 /// Whether events or their minutes count.
408 pub measure: CapMeasure,
409 /// The most the period may hold, once the booking's contribution is added.
410 pub limit: u32,
411 /// The civil period a bucket covers.
412 pub period: CapPeriod,
413 /// Whether the limit applies to each participant or to the pool together.
414 pub per: CapPer,
415 /// The zone the bucket labels are read in. `pooled` requires `event` or a
416 /// named zone.
417 pub zone: RuleZone,
418 /// The weekday a week bucket starts on.
419 pub week_starts: Weekday,
420}
421
422impl Cap {
423 /// A cap over the events `count` selects, with the given measure, limit,
424 /// period, per-participant scope and bucket zone.
425 #[must_use]
426 pub const fn new(
427 count: Selector,
428 measure: CapMeasure,
429 limit: u32,
430 period: CapPeriod,
431 per: CapPer,
432 zone: RuleZone,
433 week_starts: Weekday,
434 ) -> Self {
435 Self {
436 count,
437 measure,
438 limit,
439 period,
440 per,
441 zone,
442 week_starts,
443 }
444 }
445}
446
447/// What a `cap` measures: the number of events, or their minutes.
448#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
449pub enum CapMeasure {
450 /// Each matching event counts once.
451 Count,
452 /// Each matching event contributes its own duration, excluding travel.
453 Minutes,
454}
455
456impl CapMeasure {
457 /// The measure's wire name: `count` or `minutes`.
458 #[must_use]
459 pub const fn as_str(&self) -> &'static str {
460 match self {
461 Self::Count => "count",
462 Self::Minutes => "minutes",
463 }
464 }
465}
466
467impl core::fmt::Display for CapMeasure {
468 /// Formats the measure as its wire name.
469 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
470 f.write_str(self.as_str())
471 }
472}
473
474/// The civil period a `cap` bucket covers.
475///
476/// The enum is `#[non_exhaustive]`: `0.2+` may add periods — a quarter, a rolling
477/// window — without a breaking Rust bump, so a `match` outside this crate needs a
478/// `_` arm.
479#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
480#[non_exhaustive]
481pub enum CapPeriod {
482 /// One civil day.
483 Day,
484 /// Seven civil days from the configured `week_starts` weekday.
485 Week,
486 /// One civil month.
487 Month,
488}
489
490impl CapPeriod {
491 /// The period's wire name: `day`, `week` or `month`.
492 #[must_use]
493 pub const fn as_str(&self) -> &'static str {
494 match self {
495 Self::Day => "day",
496 Self::Week => "week",
497 Self::Month => "month",
498 }
499 }
500}
501
502impl core::fmt::Display for CapPeriod {
503 /// Formats the period as its wire name.
504 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
505 f.write_str(self.as_str())
506 }
507}
508
509/// Whether a `cap` limits each participant or the pool together.
510#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
511pub enum CapPer {
512 /// Each participant in `who` is limited on their own.
513 Each,
514 /// The participants in `who` are limited together, which needs one bucket
515 /// zone they all share.
516 Pooled,
517}
518
519impl CapPer {
520 /// The scope's wire name: `each` or `pooled`.
521 #[must_use]
522 pub const fn as_str(&self) -> &'static str {
523 match self {
524 Self::Each => "each",
525 Self::Pooled => "pooled",
526 }
527 }
528}
529
530impl core::fmt::Display for CapPer {
531 /// Formats the scope as its wire name.
532 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
533 f.write_str(self.as_str())
534 }
535}
536
537/// A `rest` rule: a late finish blocks an early start.
538///
539/// Several rest rules in one request never combine: each is evaluated on its own
540/// pair of times (see [`Rule`] for the combination semantics per kind).
541///
542/// *Activity* is the occupied spans of a participant's blocking, non-all-day
543/// blocks plus the booking being offered, where an occupied span is widened by
544/// its travel. For a local date `D`, `late(D)` is the part of `D` at or after
545/// `late_after` and `early(D)` the part before `not_before`, both read in the
546/// participant's zone at each instant. A booking is excluded when activity
547/// overlaps both `late(D)` and `early(D + 1)` for some `D`, and the booking
548/// itself is part of one of those overlaps.
549///
550/// All-day blocks and blackouts never count as activity, `status_policy`
551/// decides which blocks block, and each rest rule is evaluated independently of
552/// the others: two rules never combine one rule's `late_after` with another
553/// rule's `not_before`.
554///
555/// ```
556/// use opportune::model::Rest;
557/// use opportune::time::TimeOfDay;
558///
559/// let rest = Rest::new(TimeOfDay::new(18, 0).unwrap(), TimeOfDay::new(10, 0).unwrap());
560/// assert_eq!(rest.late_after.to_string(), "18:00");
561/// assert_eq!(rest.not_before.to_string(), "10:00");
562/// ```
563#[derive(Clone, Copy, Debug, PartialEq, Eq)]
564pub struct Rest {
565 /// The local time from which a finish counts as late.
566 pub late_after: TimeOfDay,
567 /// The local time before which a start counts as early.
568 pub not_before: TimeOfDay,
569}
570
571impl Rest {
572 /// A rest rule protecting the hours before `not_before` after any activity
573 /// at or after `late_after` the day before.
574 #[must_use]
575 pub const fn new(late_after: TimeOfDay, not_before: TimeOfDay) -> Self {
576 Self {
577 late_after,
578 not_before,
579 }
580 }
581}
582
583/// The gaps a booking needs between it and the participant's other events.
584///
585/// `before` and `after` are the gaps the new booking needs; `min_gap` is the
586/// least gap between any two events. The gap required between an event and the
587/// booking is the largest that applies, never a sum.
588///
589/// ```
590/// use opportune::model::Clearance;
591/// use opportune::time::Duration;
592///
593/// let buffers = Clearance {
594/// before: Duration::from_hours_minutes(0, 10),
595/// after: Duration::from_hours_minutes(0, 10),
596/// min_gap: Duration::from_hours_minutes(0, 5),
597/// };
598/// assert_eq!(buffers.before.minutes(), 10);
599/// ```
600#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
601pub struct Clearance {
602 /// The gap the booking needs before it.
603 pub before: Duration,
604 /// The gap the booking needs after it.
605 pub after: Duration,
606 /// The least gap between any two events.
607 pub min_gap: Duration,
608}
609
610/// How soon and how far ahead a booking may start.
611///
612/// ```
613/// use opportune::model::{LeadTime, LeadTimeMax};
614/// use opportune::time::Duration;
615///
616/// let notice = LeadTime {
617/// min: Duration::from_hours_minutes(4, 0),
618/// max: Some(LeadTimeMax::Days(3)),
619/// };
620/// assert_eq!(notice.min.minutes(), 240);
621/// ```
622#[derive(Clone, Debug, Default, PartialEq, Eq)]
623pub struct LeadTime {
624 /// The booking's occupied start must be at least `now + min`, so travel
625 /// counts.
626 pub min: Duration,
627 /// The latest start allowed, in one of the four forms. `None` leaves the
628 /// search window as the only limit.
629 pub max: Option<LeadTimeMax>,
630}
631
632/// A `lead_time` maximum: how far ahead a start may be.
633///
634/// A working-day count names its calendar, so the request stays independent of
635/// the calendar's resolved zone.
636#[derive(Clone, Debug, PartialEq, Eq)]
637pub enum LeadTimeMax {
638 /// At most `now + duration`.
639 Duration(Duration),
640 /// At most `today + days` calendar days, where today is `now`'s local date
641 /// in the event zone.
642 Days(u32),
643 /// At most the `count`-th working day after today, on the named calendar.
644 WorkingDays {
645 /// How many working days after today remain inside the horizon.
646 count: u32,
647 /// The name of the request calendar that decides which days are working
648 /// days.
649 calendar: String,
650 },
651 /// At most this local date in the event zone.
652 Date(Date),
653}
654
655/// How statuses and tags affect availability.
656///
657/// Entries are tried in order, across rules in request order: the first entry
658/// that matches a block decides whether it blocks.
659///
660/// ```
661/// use opportune::model::{BlockStatus, StatusEffect, StatusPolicy, StatusPolicyEntry};
662///
663/// let policy = StatusPolicy {
664/// entries: vec![StatusPolicyEntry::status(BlockStatus::Tentative, StatusEffect::Ignore)],
665/// };
666/// assert_eq!(policy.decide(BlockStatus::Tentative, &[]), Some(StatusEffect::Ignore));
667/// assert_eq!(policy.decide(BlockStatus::Busy, &[]), None);
668/// ```
669#[derive(Clone, Debug, Default, PartialEq, Eq)]
670pub struct StatusPolicy {
671 /// The entries, in the order the caller wrote them.
672 pub entries: Vec<StatusPolicyEntry>,
673}
674
675impl StatusPolicy {
676 /// The effect the first matching entry names for a block with `status` and
677 /// `tags`, or `None` when no entry matches.
678 #[must_use]
679 pub fn decide(&self, status: BlockStatus, tags: &[crate::tags::Tag]) -> Option<StatusEffect> {
680 self.entries
681 .iter()
682 .find(|entry| entry.matches(status, tags))
683 .map(|entry| entry.effect)
684 }
685}
686
687/// One status-policy entry: what it matches and what it decides.
688///
689/// An entry matches on a status, a tag selector, or both. An entry that matches
690/// neither is rejected at construction, because it could never apply while
691/// reading as if it would.
692#[derive(Clone, Debug, PartialEq, Eq)]
693pub struct StatusPolicyEntry {
694 /// The block status this entry matches, if it matches on status.
695 pub status: Option<BlockStatus>,
696 /// The tag selector this entry matches, if it matches on tags.
697 pub tags: Option<Selector>,
698 /// What happens to a block the entry matches.
699 pub effect: StatusEffect,
700}
701
702impl StatusPolicyEntry {
703 /// An entry matching one status.
704 #[must_use]
705 pub fn status(status: BlockStatus, effect: StatusEffect) -> Self {
706 Self {
707 status: Some(status),
708 tags: None,
709 effect,
710 }
711 }
712
713 /// An entry matching a tag selector.
714 #[must_use]
715 pub fn tags(tags: Selector, effect: StatusEffect) -> Self {
716 Self {
717 status: None,
718 tags: Some(tags),
719 effect,
720 }
721 }
722
723 /// An entry matching both a status and a tag selector.
724 #[must_use]
725 pub fn status_and_tags(status: BlockStatus, tags: Selector, effect: StatusEffect) -> Self {
726 Self {
727 status: Some(status),
728 tags: Some(tags),
729 effect,
730 }
731 }
732
733 /// Whether the entry matches a block.
734 #[must_use]
735 pub fn matches(&self, status: BlockStatus, tags: &[crate::tags::Tag]) -> bool {
736 if self.status.is_some_and(|matched| matched != status) {
737 return false;
738 }
739 self.tags
740 .as_ref()
741 .is_none_or(|selector| selector.matches_item(tags))
742 }
743
744 /// Checks that the entry matches something at all.
745 ///
746 /// # Errors
747 /// Returns [`Error::StatusPolicyEntryEmpty`] when the entry names neither a
748 /// status nor a tag selector.
749 pub fn validate(&self) -> Result<(), Error> {
750 if self.status.is_none() && self.tags.is_none() {
751 return Err(Error::StatusPolicyEntryEmpty);
752 }
753 Ok(())
754 }
755}
756
757/// What a matching status-policy entry does to a block.
758#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
759pub enum StatusEffect {
760 /// The block is ignored: its occupied span does not block, and its travel is
761 /// ignored with it.
762 Ignore,
763 /// The block blocks. The default for `tentative` and `busy` blocks, and the
764 /// effect that makes a `free` block block.
765 Block,
766}
767
768impl StatusEffect {
769 /// The effect's wire name: `ignore` or `block`.
770 #[must_use]
771 pub const fn as_str(&self) -> &'static str {
772 match self {
773 Self::Ignore => "ignore",
774 Self::Block => "block",
775 }
776 }
777}
778
779impl core::fmt::Display for StatusEffect {
780 /// Formats the effect as its wire name.
781 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
782 f.write_str(self.as_str())
783 }
784}