Skip to main content

adk_kernel/control/store/
mod.rs

1//! What the control plane keeps between restarts (spec 3.3 §10 K3, K4): the settings a
2//! person changed while the kernel ran, by area, and how far each device has read "While
3//! you were away".
4//!
5//! | Record | Key | Written by |
6//! |---|---|---|
7//! | [`AreaSettings`] | partition | `POST /kernel/settings/{partition}/{quiet-time,spending-limit,mode}` |
8//! | [`AwayCursor`] | user and viewer | `POST /kernel/away/seen` |
9//!
10//! [`ControlStore`] runs on the backends the device store runs on, with one conformance
11//! suite (`control_store_conformance_tests!`, feature `conformance`):
12//!
13//! | Backend | Type | Feature |
14//! |---|---|---|
15//! | In-memory | [`InMemoryControlStore`] | — |
16//! | SQLite | `SqliteControlStore` | `sqlite` (default) |
17//! | PostgreSQL | `PostgresControlStore` | `postgres` |
18//! | Redis | `RedisControlStore` | `redis` |
19
20use std::collections::BTreeMap;
21
22use async_trait::async_trait;
23use chrono::{DateTime, Utc};
24use serde::{Deserialize, Serialize};
25use tokio::sync::RwLock;
26
27use crate::error::Result;
28use crate::partition::{PartitionId, PartitionMode};
29use crate::sched::QuietHours;
30
31#[cfg(feature = "postgres")]
32mod postgres;
33#[cfg(feature = "redis")]
34mod redis;
35#[cfg(any(feature = "sqlite", feature = "postgres"))]
36mod sql;
37#[cfg(feature = "sqlite")]
38mod sqlite;
39
40#[cfg(feature = "postgres")]
41pub use postgres::PostgresControlStore;
42#[cfg(feature = "redis")]
43pub use redis::RedisControlStore;
44#[cfg(feature = "sqlite")]
45pub use sqlite::SqliteControlStore;
46
47/// One setting a person changed while the kernel ran (spec 3.3 §10 K3): the value, and when
48/// and by whom it was set.
49///
50/// # Example
51///
52/// ```rust
53/// use adk_kernel::control::Change;
54///
55/// let change = Change::new(Some(5_000_000_u64), "ana", chrono::Utc::now());
56/// assert_eq!(serde_json::to_value(&change).unwrap()["value"], 5_000_000);
57/// ```
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "camelCase")]
60#[non_exhaustive]
61pub struct Change<T> {
62    /// The value set; for quiet time and the spending limit, `None` turns it off.
63    pub value: T,
64    /// When it was set.
65    pub at: DateTime<Utc>,
66    /// Who set it: the subject of the control-plane caller.
67    pub by: String,
68}
69
70impl<T> Change<T> {
71    /// `value`, set by `by` at `at`.
72    pub fn new(value: T, by: impl Into<String>, at: DateTime<Utc>) -> Self {
73        Self { value, at, by: by.into() }
74    }
75}
76
77/// What an area started with when its settings were last changed (spec 3.3 §10 K3): the
78/// values the changes replace.
79///
80/// A change holds while the area still starts with the value it replaced; a different start
81/// value — a later `adk-rust up --mode`, `adk-rust partitions set-mode`, or quiet hours and
82/// a cap set at start — is newer, and takes over from it.
83///
84/// # Example
85///
86/// ```rust
87/// use adk_kernel::control::AreaStart;
88/// use adk_kernel::PartitionMode;
89///
90/// let start = AreaStart::new(Vec::new(), Some(5_000_000), Some(PartitionMode::Ask));
91/// assert_eq!(serde_json::to_value(&start).unwrap()["mode"], "ask");
92/// ```
93#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(rename_all = "camelCase")]
95#[non_exhaustive]
96pub struct AreaStart {
97    /// The quiet windows the kernel and the partition record started with.
98    #[serde(default)]
99    pub quiet_time: Vec<QuietHours>,
100    /// The daily spend cap it started with, in micro-USD; `None` is no cap.
101    #[serde(default)]
102    pub daily_spending_limit: Option<u64>,
103    /// The mode its agents started in; `None` when the kernel was not told.
104    #[serde(default)]
105    pub mode: Option<PartitionMode>,
106}
107
108impl AreaStart {
109    /// An area that started with `quiet_time`, `daily_spending_limit` and `mode`.
110    pub fn new(
111        quiet_time: Vec<QuietHours>,
112        daily_spending_limit: Option<u64>,
113        mode: Option<PartitionMode>,
114    ) -> Self {
115        Self { quiet_time, daily_spending_limit, mode }
116    }
117}
118
119/// The settings a person changed for one area while the kernel ran (spec 3.3 §8.1 "Areas",
120/// §10 K3). Each one set replaces, for the area, the value the kernel and the area's
121/// partition record started with, while the area still starts with that value
122/// ([`start`](Self::start)); one never set leaves the start value in force.
123///
124/// # Example
125///
126/// ```rust
127/// use adk_kernel::control::{AreaSettings, Change};
128/// use adk_kernel::{PartitionMode, QuietHours};
129///
130/// let now = chrono::Utc::now();
131/// let settings = AreaSettings::new("work")
132///     .with_quiet_time(Change::new(Some("22:00-07:00".parse::<QuietHours>().unwrap()), "ana", now))
133///     .with_mode(Change::new(PartitionMode::Ask, "ana", now));
134/// let wire = serde_json::to_value(&settings).unwrap();
135/// assert_eq!(wire["quietTime"]["value"]["start"], "22:00");
136/// assert_eq!(wire["mode"]["value"], "ask");
137/// assert!(wire.get("dailySpendingLimit").is_none());
138/// ```
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "camelCase")]
141#[non_exhaustive]
142pub struct AreaSettings {
143    /// The area: a partition, `default` on a kernel without partitions.
144    pub partition: PartitionId,
145    /// Quiet time; `value: None` is no quiet time.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub quiet_time: Option<Change<Option<QuietHours>>>,
148    /// The daily spending limit in micro-USD; `value: None` is no limit.
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub daily_spending_limit: Option<Change<Option<u64>>>,
151    /// How much the area's agents act alone.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub mode: Option<Change<PartitionMode>>,
154    /// What the area started with when a setting was last changed; `None` on a record
155    /// written without it, whose changes hold whatever the area starts with.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub start: Option<AreaStart>,
158    /// The quiet times earlier changes set, oldest first, at most
159    /// [`QUIET_TIME_HISTORY`](Self::QUIET_TIME_HISTORY): past work is judged against the
160    /// quiet time in force when it started.
161    #[serde(default, skip_serializing_if = "Vec::is_empty")]
162    pub earlier_quiet_time: Vec<Change<Option<QuietHours>>>,
163}
164
165impl AreaSettings {
166    /// How many earlier quiet times a record keeps.
167    pub const QUIET_TIME_HISTORY: usize = 32;
168
169    /// No changed setting for `partition`.
170    pub fn new(partition: impl Into<PartitionId>) -> Self {
171        Self {
172            partition: partition.into(),
173            quiet_time: None,
174            daily_spending_limit: None,
175            mode: None,
176            start: None,
177            earlier_quiet_time: Vec::new(),
178        }
179    }
180
181    /// Records that the area started with `start`.
182    #[must_use]
183    pub fn with_start(mut self, start: AreaStart) -> Self {
184        self.start = Some(start);
185        self
186    }
187
188    /// The changed quiet time, when the area still starts with the windows it replaced.
189    pub fn quiet_time_over(&self, start: &[QuietHours]) -> Option<&Change<Option<QuietHours>>> {
190        self.quiet_time
191            .as_ref()
192            .filter(|_| self.start.as_ref().is_none_or(|was| was.quiet_time == start))
193    }
194
195    /// The changed daily spending limit, when the area still starts with the cap it
196    /// replaced.
197    pub fn daily_spending_limit_over(&self, start: Option<u64>) -> Option<&Change<Option<u64>>> {
198        self.daily_spending_limit
199            .as_ref()
200            .filter(|_| self.start.as_ref().is_none_or(|was| was.daily_spending_limit == start))
201    }
202
203    /// The changed mode, when the area's agents still start in the mode it replaced.
204    pub fn mode_over(&self, start: Option<PartitionMode>) -> Option<&Change<PartitionMode>> {
205        self.mode.as_ref().filter(|_| self.start.as_ref().is_none_or(|was| was.mode == start))
206    }
207
208    /// Drops every change whose start value `start` has replaced since, then records
209    /// `start` (spec 3.3 §10 K3): call it before changing a setting.
210    pub fn settle(&mut self, start: &AreaStart) {
211        if self.quiet_time_over(&start.quiet_time).is_none() {
212            self.quiet_time = None;
213        }
214        if self.daily_spending_limit_over(start.daily_spending_limit).is_none() {
215            self.daily_spending_limit = None;
216        }
217        if self.mode_over(start.mode).is_none() {
218            self.mode = None;
219        }
220        self.start = Some(start.clone());
221    }
222
223    /// Sets the changed quiet time, keeping the one it replaces among the earlier ones.
224    pub fn change_quiet_time(&mut self, change: Change<Option<QuietHours>>) {
225        if let Some(earlier) = self.quiet_time.replace(change) {
226            self.earlier_quiet_time.push(earlier);
227            let excess = self.earlier_quiet_time.len().saturating_sub(Self::QUIET_TIME_HISTORY);
228            self.earlier_quiet_time.drain(..excess);
229        }
230    }
231
232    /// The person's quiet time in force at `at`, as the area's changes record it: the
233    /// newest change made at or before `at`, to the millisecond the ledger stamps its rows
234    /// with, or `None` before the first one, when the start windows held.
235    pub fn quiet_time_at(&self, at: DateTime<Utc>) -> Option<&Change<Option<QuietHours>>> {
236        let at = at.timestamp_millis();
237        self.earlier_quiet_time
238            .iter()
239            .chain(self.quiet_time.as_ref())
240            .filter(|change| change.at.timestamp_millis() <= at)
241            .max_by_key(|change| change.at)
242    }
243
244    /// Sets the changed quiet time.
245    #[must_use]
246    pub fn with_quiet_time(mut self, change: Change<Option<QuietHours>>) -> Self {
247        self.quiet_time = Some(change);
248        self
249    }
250
251    /// Sets the changed daily spending limit.
252    #[must_use]
253    pub fn with_daily_spending_limit(mut self, change: Change<Option<u64>>) -> Self {
254        self.daily_spending_limit = Some(change);
255        self
256    }
257
258    /// Sets the changed mode.
259    #[must_use]
260    pub fn with_mode(mut self, change: Change<PartitionMode>) -> Self {
261        self.mode = Some(change);
262        self
263    }
264}
265
266/// How far one viewer of one person has read "While you were away" (spec 3.3 §10 K4): the
267/// last `/proc` ledger row it marked seen.
268///
269/// The viewer is `device:<id>` for a paired device, else the name a surface gives itself
270/// (`home`, `terminal`).
271///
272/// # Example
273///
274/// ```rust
275/// use adk_kernel::control::AwayCursor;
276///
277/// let cursor = AwayCursor::new("ana", "device:0123456789abcdef", 41, chrono::Utc::now());
278/// assert_eq!(serde_json::to_value(&cursor).unwrap()["seq"], 41);
279/// ```
280#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
281#[serde(rename_all = "camelCase")]
282#[non_exhaustive]
283pub struct AwayCursor {
284    /// The person.
285    pub user: String,
286    /// The viewer.
287    pub viewer: String,
288    /// The last ledger row seen; rows after it are new to the viewer.
289    pub seq: u64,
290    /// When the viewer marked it seen.
291    pub seen_at: DateTime<Utc>,
292}
293
294impl AwayCursor {
295    /// `viewer` of `user` has seen every row up to `seq`, at `seen_at`.
296    pub fn new(
297        user: impl Into<String>,
298        viewer: impl Into<String>,
299        seq: u64,
300        seen_at: DateTime<Utc>,
301    ) -> Self {
302        Self { user: user.into(), viewer: viewer.into(), seq, seen_at }
303    }
304}
305
306/// Where the control plane keeps [`AreaSettings`] and [`AwayCursor`]s (spec 3.3 §10 K3,
307/// K4).
308///
309/// | Method | Contract |
310/// |---|---|
311/// | `area_settings`, `list_area_settings` | One area's record, or every one ordered by partition id |
312/// | `put_area_settings` | Replaces the area's record |
313/// | `update_area_settings` | Changes the area's record with no other write in between, so concurrent changes all hold |
314/// | `cursor` | One viewer's cursor |
315/// | `advance_cursor` | Stores the cursor unless the stored one is past its `seq`, and returns the stored one: a cursor never moves back |
316///
317/// # Example
318///
319/// ```rust
320/// use adk_kernel::control::{AwayCursor, ControlStore, InMemoryControlStore};
321///
322/// # #[tokio::main(flavor = "current_thread")]
323/// # async fn main() -> adk_kernel::Result<()> {
324/// let store = InMemoryControlStore::new();
325/// let now = chrono::Utc::now();
326/// store.advance_cursor(AwayCursor::new("ana", "home", 9, now)).await?;
327/// let stored = store.advance_cursor(AwayCursor::new("ana", "home", 4, now)).await?;
328/// assert_eq!(stored.seq, 9, "a cursor never moves back");
329/// # Ok(())
330/// # }
331/// ```
332#[async_trait]
333pub trait ControlStore: Send + Sync {
334    /// The settings changed for `partition`, or `None`.
335    ///
336    /// # Errors
337    ///
338    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
339    async fn area_settings(&self, partition: &PartitionId) -> Result<Option<AreaSettings>>;
340
341    /// Every area's changed settings, ordered by partition id.
342    ///
343    /// # Errors
344    ///
345    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
346    async fn list_area_settings(&self) -> Result<Vec<AreaSettings>>;
347
348    /// Replaces the changed settings of `settings.partition`.
349    ///
350    /// # Errors
351    ///
352    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
353    async fn put_area_settings(&self, settings: AreaSettings) -> Result<()>;
354
355    /// Applies `change` to the record of `partition`, an empty one when it has none, and
356    /// stores it with no other write in between: when another write changed the record
357    /// meanwhile, `change` is applied again to that one, so concurrent changes of different
358    /// settings all hold (spec 3.3 §10 K3). Returns the record stored.
359    ///
360    /// The default reads, applies and puts, which keeps that promise only for a store with
361    /// one writer; every store of this crate overrides it.
362    ///
363    /// # Errors
364    ///
365    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
366    async fn update_area_settings(
367        &self,
368        partition: &PartitionId,
369        change: &(dyn for<'a> Fn(&'a mut AreaSettings) + Send + Sync),
370    ) -> Result<AreaSettings> {
371        let mut settings = self
372            .area_settings(partition)
373            .await?
374            .unwrap_or_else(|| AreaSettings::new(partition.clone()));
375        change(&mut settings);
376        self.put_area_settings(settings.clone()).await?;
377        Ok(settings)
378    }
379
380    /// The cursor of `viewer` of `user`, or `None` before it first marks anything seen.
381    ///
382    /// # Errors
383    ///
384    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
385    async fn cursor(&self, user: &str, viewer: &str) -> Result<Option<AwayCursor>>;
386
387    /// Stores `cursor` when the stored cursor of its viewer is at or before its `seq`, and
388    /// returns the cursor stored after the call.
389    ///
390    /// # Errors
391    ///
392    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
393    async fn advance_cursor(&self, cursor: AwayCursor) -> Result<AwayCursor>;
394}
395
396/// A [`ControlStore`] that answers a read of an area's settings the backend fails with the
397/// settings it last read (spec 3.3 §10 K3): admission keeps the person's quiet time and
398/// limit through a store outage rather than falling back to the start settings.
399pub(crate) struct LastRead {
400    inner: std::sync::Arc<dyn ControlStore>,
401    read: std::sync::Mutex<BTreeMap<PartitionId, Option<AreaSettings>>>,
402}
403
404impl LastRead {
405    /// Remembers what `inner` answers.
406    pub(crate) fn new(inner: std::sync::Arc<dyn ControlStore>) -> Self {
407        Self { inner, read: std::sync::Mutex::default() }
408    }
409
410    fn remembered(&self) -> std::sync::MutexGuard<'_, BTreeMap<PartitionId, Option<AreaSettings>>> {
411        self.read.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
412    }
413}
414
415#[async_trait]
416impl ControlStore for LastRead {
417    async fn area_settings(&self, partition: &PartitionId) -> Result<Option<AreaSettings>> {
418        match self.inner.area_settings(partition).await {
419            Ok(settings) => {
420                self.remembered().insert(partition.clone(), settings.clone());
421                Ok(settings)
422            }
423            Err(error) => match self.remembered().get(partition) {
424                Some(settings) => {
425                    tracing::warn!(partition = %partition, error = %error, "could not read the changed settings; the ones read last apply");
426                    Ok(settings.clone())
427                }
428                None => Err(error),
429            },
430        }
431    }
432
433    async fn list_area_settings(&self) -> Result<Vec<AreaSettings>> {
434        self.inner.list_area_settings().await
435    }
436
437    async fn put_area_settings(&self, settings: AreaSettings) -> Result<()> {
438        self.inner.put_area_settings(settings).await
439    }
440
441    async fn update_area_settings(
442        &self,
443        partition: &PartitionId,
444        change: &(dyn for<'a> Fn(&'a mut AreaSettings) + Send + Sync),
445    ) -> Result<AreaSettings> {
446        self.inner.update_area_settings(partition, change).await
447    }
448
449    async fn cursor(&self, user: &str, viewer: &str) -> Result<Option<AwayCursor>> {
450        self.inner.cursor(user, viewer).await
451    }
452
453    async fn advance_cursor(&self, cursor: AwayCursor) -> Result<AwayCursor> {
454        self.inner.advance_cursor(cursor).await
455    }
456}
457
458/// A [`ControlStore`] in process memory (spec 3.3 §10 K3, K4): changed settings and cursors
459/// end with the process, so a restart brings back the start settings.
460///
461/// # Example
462///
463/// ```rust
464/// use adk_kernel::control::{AreaSettings, ControlStore, InMemoryControlStore};
465///
466/// # #[tokio::main(flavor = "current_thread")]
467/// # async fn main() -> adk_kernel::Result<()> {
468/// let store = InMemoryControlStore::new();
469/// store.put_area_settings(AreaSettings::new("work")).await?;
470/// assert_eq!(store.list_area_settings().await?.len(), 1);
471/// # Ok(())
472/// # }
473/// ```
474#[derive(Debug, Default)]
475pub struct InMemoryControlStore {
476    settings: RwLock<BTreeMap<PartitionId, AreaSettings>>,
477    cursors: RwLock<BTreeMap<(String, String), AwayCursor>>,
478}
479
480impl InMemoryControlStore {
481    /// An empty store.
482    pub fn new() -> Self {
483        Self::default()
484    }
485}
486
487#[async_trait]
488impl ControlStore for InMemoryControlStore {
489    async fn area_settings(&self, partition: &PartitionId) -> Result<Option<AreaSettings>> {
490        Ok(self.settings.read().await.get(partition).cloned())
491    }
492
493    async fn list_area_settings(&self) -> Result<Vec<AreaSettings>> {
494        Ok(self.settings.read().await.values().cloned().collect())
495    }
496
497    async fn put_area_settings(&self, settings: AreaSettings) -> Result<()> {
498        self.settings.write().await.insert(settings.partition.clone(), settings);
499        Ok(())
500    }
501
502    async fn update_area_settings(
503        &self,
504        partition: &PartitionId,
505        change: &(dyn for<'a> Fn(&'a mut AreaSettings) + Send + Sync),
506    ) -> Result<AreaSettings> {
507        let mut all = self.settings.write().await;
508        let settings =
509            all.entry(partition.clone()).or_insert_with(|| AreaSettings::new(partition.clone()));
510        change(settings);
511        Ok(settings.clone())
512    }
513
514    async fn cursor(&self, user: &str, viewer: &str) -> Result<Option<AwayCursor>> {
515        Ok(self.cursors.read().await.get(&(user.to_string(), viewer.to_string())).cloned())
516    }
517
518    async fn advance_cursor(&self, cursor: AwayCursor) -> Result<AwayCursor> {
519        let mut cursors = self.cursors.write().await;
520        let key = (cursor.user.clone(), cursor.viewer.clone());
521        match cursors.get(&key) {
522            Some(stored) if stored.seq > cursor.seq => Ok(stored.clone()),
523            _ => {
524                cursors.insert(key, cursor.clone());
525                Ok(cursor)
526            }
527        }
528    }
529}
530
531#[cfg(test)]
532mod tests {
533    use std::sync::Arc;
534    use std::sync::atomic::{AtomicBool, Ordering};
535
536    use super::*;
537
538    /// A store whose reads of area settings fail while `down` is set.
539    struct Flaky {
540        inner: InMemoryControlStore,
541        down: AtomicBool,
542    }
543
544    #[async_trait]
545    impl ControlStore for Flaky {
546        async fn area_settings(&self, partition: &PartitionId) -> Result<Option<AreaSettings>> {
547            if self.down.load(Ordering::SeqCst) {
548                return Err(crate::KernelError::Store {
549                    backend: "test",
550                    reason: "the pool timed out".into(),
551                });
552            }
553            self.inner.area_settings(partition).await
554        }
555        async fn list_area_settings(&self) -> Result<Vec<AreaSettings>> {
556            self.inner.list_area_settings().await
557        }
558        async fn put_area_settings(&self, settings: AreaSettings) -> Result<()> {
559            self.inner.put_area_settings(settings).await
560        }
561        async fn cursor(&self, user: &str, viewer: &str) -> Result<Option<AwayCursor>> {
562            self.inner.cursor(user, viewer).await
563        }
564        async fn advance_cursor(&self, cursor: AwayCursor) -> Result<AwayCursor> {
565            self.inner.advance_cursor(cursor).await
566        }
567    }
568
569    /// Through a store outage, admission keeps the quiet time and limit the person set: a
570    /// read that fails answers what was read last, and one that never succeeded fails (spec
571    /// 3.3 §10 K3).
572    #[tokio::test]
573    async fn a_failed_read_answers_the_settings_read_last() {
574        let flaky = Arc::new(Flaky { inner: InMemoryControlStore::new(), down: false.into() });
575        let limit = Change::new(Some(1_000_000), "ana", Utc::now());
576        let lowered = AreaSettings::new("default").with_daily_spending_limit(limit);
577        flaky.put_area_settings(lowered.clone()).await.unwrap();
578        let store = LastRead::new(flaky.clone());
579        let default = PartitionId::default();
580        assert_eq!(store.area_settings(&default).await.unwrap(), Some(lowered.clone()));
581
582        flaky.down.store(true, Ordering::SeqCst);
583        assert_eq!(store.area_settings(&default).await.unwrap(), Some(lowered));
584        let never_read = PartitionId::new("work");
585        assert!(store.area_settings(&never_read).await.is_err(), "nothing read before");
586    }
587
588    /// A quiet time is in force from the millisecond it was set, the precision the ledger
589    /// stamps its rows with, until the next one.
590    #[test]
591    fn the_quiet_time_in_force_at_an_instant() {
592        let at = |millis: i64| DateTime::from_timestamp_millis(millis).unwrap();
593        let window = "22:00-07:00".parse::<QuietHours>().unwrap();
594        let mut settings = AreaSettings::new("default");
595        let mut set = Change::new(Some(window), "ana", at(1_000));
596        set.at += chrono::Duration::microseconds(400);
597        settings.change_quiet_time(set);
598        settings.change_quiet_time(Change::new(None, "ana", at(5_000)));
599        assert_eq!(settings.quiet_time_at(at(999)), None, "the start windows held");
600        assert_eq!(settings.quiet_time_at(at(1_000)).unwrap().value, Some(window));
601        assert_eq!(settings.quiet_time_at(at(4_999)).unwrap().value, Some(window));
602        assert_eq!(settings.quiet_time_at(at(5_000)).unwrap().value, None);
603    }
604}