coven_database/
live_results.rs1use 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
8pub 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 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;