Skip to main content

printobserver_server/
events.rs

1//! The event log, followed in the order it was stored.
2//!
3//! # One read, and a wait that every waiter wakes from
4//!
5//! [`events`] answers the events stored after a cursor that pass its filters,
6//! and when none has been stored yet it waits — up to [`MAX_EVENTS_WAIT_S`]
7//! seconds — for one to be. The wait is on a broadcast of the store's own
8//! signal: every write that stores an event raises it once committed, and
9//! every waiting read wakes, reads again and answers or waits on. Twenty reads
10//! waiting at once are twenty receivers of one channel rather than twenty
11//! takers of one arrival, and none of them holds a runtime worker while it
12//! waits, so a status read made meanwhile is answered meanwhile.
13//!
14//! # The cursor is the last event examined
15//!
16//! Not the last event answered: a row the filters dropped is still a row this
17//! read examined, so the next read starts after it rather than examining it
18//! again. With no cursor the read starts after the newest event stored at the
19//! request — or, scoped to a print, at that print's first event, so a print is
20//! replayed and then followed.
21//!
22//! # The end of a print is told whatever the filters say
23//!
24//! A read scoped to a print answers that print's end as stored — its
25//! `print_ended` event's identifier, instant and outcome — beside the events,
26//! and null while it is open, so a reader filtering that event out still learns
27//! the print is over.
28
29use std::time::Duration;
30
31use axum::extract::{Extension, Query, State};
32use axum::http::StatusCode;
33use axum::response::Response;
34use printobserver_core::PrintEndedPayload;
35use printobserver_core::store::{HistoryQuery, StoreError, StoredQuery};
36use printobserver_types::{EventId, EventKind, EventPayload, EventRecord, PrintId};
37use tokio::sync::watch;
38use tokio::time::Instant;
39
40use crate::api::{ApiState, Caller, answer, refusal, scope_refused, store_status};
41use crate::wire::{EventsAnswer, PrintEnded};
42
43/// The longest an events read waits for one to pass, in seconds.
44pub const MAX_EVENTS_WAIT_S: u32 = 60;
45
46/// How many events one read answers when it asks for no number.
47pub const DEFAULT_EVENTS_LIMIT: u32 = 100;
48
49/// The most events one read answers.
50pub const MAX_EVENTS_LIMIT: u32 = 500;
51
52/// How many stored events one read examines per read of the store, while it
53/// looks for events that pass its filters.
54const EXAMINED_PER_READ: u32 = 500;
55
56/// A broadcast that some event was stored, which every waiting read holds a
57/// receiver of.
58#[derive(Debug, Clone)]
59pub struct Stored {
60    /// What a read waits on.
61    receiver: watch::Receiver<u64>,
62}
63
64impl Stored {
65    /// The broadcast, and the signal a store raises it by.
66    #[must_use]
67    pub fn channel() -> (Self, printobserver_core::store::StoredSignal) {
68        let (sender, receiver) = watch::channel(0_u64);
69        let signal = std::sync::Arc::new(move || {
70            sender.send_modify(|stored| *stored = stored.wrapping_add(1));
71        });
72        (Self { receiver }, signal)
73    }
74}
75
76/// What one events read asked for.
77#[derive(Debug, Clone, PartialEq, Eq)]
78struct Asked {
79    /// The event to read after.
80    after: Option<EventId>,
81    /// The print to scope to.
82    print_id: Option<PrintId>,
83    /// Only these kinds; empty, every kind.
84    kinds: Vec<EventKind>,
85    /// Never these kinds.
86    exclude_kinds: Vec<EventKind>,
87    /// How long to wait for an event to pass.
88    wait_s: u32,
89    /// How many events to answer.
90    limit: u32,
91}
92
93impl Asked {
94    /// Whether one event passes this read's filters.
95    fn passes(&self, event: &EventRecord) -> bool {
96        (self.kinds.is_empty() || self.kinds.contains(event.kind()))
97            && !self.exclude_kinds.contains(event.kind())
98    }
99}
100
101/// One value of an events read, refused naming it when it is not one.
102fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
103where
104    T::Err: core::fmt::Display,
105{
106    text.parse()
107        .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
108}
109
110/// One bounded whole number of an events read.
111fn bounded(name: &str, text: &str, low: u32, high: u32) -> Result<u32, String> {
112    let read: u32 = read_one(name, text)?;
113    if (low..=high).contains(&read) {
114        Ok(read)
115    } else {
116        Err(format!(
117            "`{name}` may be from {low} to {high}; {read} was asked for"
118        ))
119    }
120}
121
122/// What a request's values ask for.
123///
124/// `kinds` and `exclude_kinds` may be given any number of times, each one kind
125/// matching the event log's own pattern; a kind no crate declares is taken,
126/// because the log is open. Every other value is given at most once, and a
127/// value this read does not take is refused naming it rather than ignored.
128fn asked(values: &[(String, String)]) -> Result<Asked, String> {
129    let mut asked = Asked {
130        after: None,
131        print_id: None,
132        kinds: Vec::new(),
133        exclude_kinds: Vec::new(),
134        wait_s: 0,
135        limit: DEFAULT_EVENTS_LIMIT,
136    };
137    let mut seen: Vec<&str> = Vec::new();
138    for (name, text) in values {
139        let repeated = name == "kinds" || name == "exclude_kinds";
140        if !repeated {
141            if seen.contains(&name.as_str()) {
142                return Err(format!(
143                    "`{name}` was given more than once, and this read takes one"
144                ));
145            }
146            seen.push(name);
147        }
148        match name.as_str() {
149            "after" => asked.after = Some(read_one(name, text)?),
150            "print_id" => asked.print_id = Some(read_one(name, text)?),
151            "kinds" => asked.kinds.push(read_one(name, text)?),
152            "exclude_kinds" => asked.exclude_kinds.push(read_one(name, text)?),
153            "wait_s" => asked.wait_s = bounded(name, text, 0, MAX_EVENTS_WAIT_S)?,
154            "limit" => asked.limit = bounded(name, text, 1, MAX_EVENTS_LIMIT)?,
155            other => return Err(format!("an events read takes no `{other}`")),
156        }
157    }
158    Ok(asked)
159}
160
161/// Read the event log after a cursor, waiting for an event to pass.
162///
163/// A supervision turn's credential reaches its own print alone, so a turn's
164/// read names that print; a read of every print's events is the operator's.
165pub async fn events(
166    State(state): State<ApiState>,
167    Extension(caller): Extension<Caller>,
168    Query(values): Query<Vec<(String, String)>>,
169) -> Response {
170    let asked = match asked(&values) {
171        Ok(asked) => asked,
172        Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
173    };
174    match (&caller, asked.print_id) {
175        (Caller::Turn(binding), None) => {
176            return refusal(
177                StatusCode::FORBIDDEN,
178                format!(
179                    "this request authenticated as the agent on print {} and names no print: a \
180                     supervision turn's credential reads its own print's events alone, so name \
181                     it with `print_id`",
182                    binding.print_id()
183                ),
184            );
185        }
186        (_, Some(print_id)) => {
187            if let Some(refused) = scope_refused(&caller, print_id) {
188                return refused;
189            }
190            match state.prints.print(print_id).await {
191                Ok(Some(_)) => {}
192                Ok(None) => {
193                    return refusal(
194                        StatusCode::NOT_FOUND,
195                        format!("there is no print {print_id}"),
196                    );
197                }
198                Err(error) => return refusal(store_status(&error), error),
199            }
200        }
201        (Caller::Operator, None) => {}
202    }
203    match follow(&state, &asked).await {
204        Ok(answered) => answer(StatusCode::OK, &answered),
205        Err(error) => refusal(store_status(&error), error),
206    }
207}
208
209/// Where a read with no cursor starts: after the newest event stored, unless
210/// it is scoped to a print with events of its own, which it replays from the
211/// first of them — which the store's own read starts at when given none.
212async fn start(state: &ApiState, asked: &Asked) -> Result<Option<EventId>, StoreError> {
213    if asked.after.is_some() {
214        return Ok(asked.after);
215    }
216    if let Some(print_id) = asked.print_id {
217        let own = state
218            .events
219            .history(HistoryQuery {
220                print_id,
221                kinds: Vec::new(),
222                since: None,
223                until: None,
224                limit: Some(1),
225            })
226            .await?;
227        if !own.is_empty() {
228            return Ok(None);
229        }
230    }
231    state.events.newest_stored().await
232}
233
234/// Answer the events after the cursor that pass, waiting for one when none
235/// has been stored yet.
236async fn follow(state: &ApiState, asked: &Asked) -> Result<EventsAnswer, StoreError> {
237    let deadline = Instant::now() + Duration::from_secs(u64::from(asked.wait_s));
238    let mut stored = state.stored.receiver.clone();
239    let mut cursor = start(state, asked).await?;
240    loop {
241        // Marked seen before the store is read, so an event stored between the
242        // read and the wait is one the wait wakes for.
243        stored.borrow_and_update();
244        let (passing, examined) = examine(state, asked, cursor).await?;
245        cursor = examined;
246        let waited_out = Instant::now() >= deadline;
247        if !passing.is_empty() || waited_out {
248            return Ok(EventsAnswer {
249                events: passing,
250                cursor,
251                print_ended: match asked.print_id {
252                    Some(print_id) => Some(ended(state, print_id).await?),
253                    None => None,
254                },
255            });
256        }
257        // A sender that is gone is a server shutting down; the deadline still
258        // ends the read, rather than a loop that spins on a closed channel.
259        if tokio::time::timeout_at(deadline, stored.changed())
260            .await
261            .is_ok_and(|changed| changed.is_err())
262        {
263            tokio::time::sleep_until(deadline).await;
264        }
265    }
266}
267
268/// The events after a cursor that pass, up to the limit, and the last event
269/// examined to find them.
270async fn examine(
271    state: &ApiState,
272    asked: &Asked,
273    mut cursor: Option<EventId>,
274) -> Result<(Vec<EventRecord>, Option<EventId>), StoreError> {
275    let mut passing = Vec::new();
276    loop {
277        let read = state
278            .events
279            .stored_after(StoredQuery {
280                after: cursor,
281                print_id: asked.print_id,
282                limit: Some(EXAMINED_PER_READ),
283            })
284            .await?;
285        let exhausted = read.len() < EXAMINED_PER_READ as usize;
286        for event in read {
287            cursor = Some(event.id);
288            if asked.passes(&event) {
289                passing.push(event);
290                if passing.len() >= asked.limit as usize {
291                    return Ok((passing, cursor));
292                }
293            }
294        }
295        if exhausted {
296            return Ok((passing, cursor));
297        }
298    }
299}
300
301/// One print's end as stored, when it has ended.
302async fn ended(state: &ApiState, print_id: PrintId) -> Result<Option<PrintEnded>, StoreError> {
303    let kind = EventKind::new(PrintEndedPayload::KIND).map_err(|error| StoreError::Database {
304        detail: error.to_string(),
305    })?;
306    let found = state
307        .events
308        .history(HistoryQuery {
309            print_id,
310            kinds: vec![kind],
311            since: None,
312            until: None,
313            limit: Some(1),
314        })
315        .await?;
316    Ok(found.into_iter().find_map(|event| {
317        let payload: PrintEndedPayload = event.body.read()?.ok()?;
318        Some(PrintEnded {
319            event_id: event.id,
320            received_at: event.received_at,
321            outcome: payload.outcome,
322        })
323    }))
324}