Skip to main content

coven_database/
live_results.rs

1//! A live query's results for code on an async executor.
2
3use crate::{database::finish_blocking, DbError, LiveQuery};
4use coven_foundation::locks::{into_unpoisoned, lock_unpoisoned};
5use coven_foundation::task::{blocking_completing, CarriesBug};
6use std::sync::{Arc, Mutex};
7
8/// The query's next result, with the query to ask again: it waits for
9/// `changed()` on the executor, runs `run_changed` on tokio's blocking pool,
10/// and waits again when a write-caused result equals the last, so no pool
11/// thread waits. The function returns `None` once the query has ended (E15).
12/// When the pool has begun shutting down, it returns
13/// `Some(Err(DbError::Shutdown))`, and when a panic happens outside the run
14/// itself, it returns `Some(Err(DbError::Bug))`.
15///
16/// Dropping this future loses the query, since the pool's thread holds it. A
17/// run that has already started ends on its own thread, and a bug in its
18/// result goes to the store's bug sink (E15).
19pub async fn next_result<T, E>(
20    mut query: LiveQuery<T, E>,
21) -> (LiveQuery<T, E>, Option<Result<T, E>>)
22where
23    T: Clone + PartialEq + Send + 'static,
24    E: From<DbError> + CarriesBug + Send + 'static,
25{
26    loop {
27        if query.has_ended() {
28            return (query, None);
29        }
30        query.changed().await;
31        let bugs = query.bugs().clone();
32        // The slot keeps the query when the pool drops the work unstarted or
33        // the work panics, so the function can still return the query in both
34        // cases.
35        let slot = Arc::new(Mutex::new(query));
36        let held = Arc::clone(&slot);
37        let result = blocking_completing(
38            "live query",
39            bugs,
40            crate::commit_task::bind(move || match lock_unpoisoned(&held).run_changed() {
41                None => Ok(None),
42                Some(result) => result.map(Some),
43            }),
44        )
45        .await;
46        query = match Arc::try_unwrap(slot) {
47            Ok(slot) => into_unpoisoned(slot),
48            Err(_) => unreachable!("the pool has dropped or ended the work"),
49        };
50        match finish_blocking(result) {
51            Ok(None) => {}
52            Ok(Some(value)) => return (query, Some(Ok(value))),
53            Err(error) => return (query, Some(Err(error))),
54        }
55    }
56}
57
58#[cfg(test)]
59#[path = "live_results_tests.rs"]
60mod tests;