1use crate::handle::{CommitSubscription, Failed, Handle, Stop};
4#[cfg(any(test, feature = "test-utils"))]
5use crate::live_query_runs::LiveQueryRuns;
6use futures_lite::future::block_on;
7use panic_as_error::locks::lock_unpoisoned;
8use panic_as_error::{caught_sync, BugSinkRef, CarriesBug};
9use std::{
10 future::{poll_fn, Future},
11 pin::pin,
12 sync::{Arc, Mutex},
13 task::Poll,
14};
15use tokio::sync::Notify;
16
17pub type Run<Q, T, E> = Arc<dyn Fn(&Q, &CommitSubscription) -> Result<T, E> + Send + Sync>;
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
23pub struct LiveQueryRevision(pub u64);
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
27#[error("live query is closed")]
28pub struct LiveQueryClosed;
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub enum LiveQueryCause {
33 Request,
35 Write,
38 RequestAndWrite,
40}
41
42#[derive(Debug)]
44pub struct ReconfigurableLiveQueryEvent<Q, T, E> {
45 pub request: Q,
47 pub revision: LiveQueryRevision,
49 pub cause: LiveQueryCause,
51 pub result: Result<T, E>,
54}
55
56struct Requests<Q> {
57 open: bool,
58 latest: Q,
59 revision: LiveQueryRevision,
60 pending: Option<(Q, LiveQueryRevision)>,
61}
62
63struct RequestState<Q> {
64 requests: Mutex<Requests<Q>>,
65 changed: Notify,
66}
67
68pub struct LiveQueryRequests<Q> {
70 state: Arc<RequestState<Q>>,
71}
72
73impl<Q> Clone for LiveQueryRequests<Q> {
74 fn clone(&self) -> Self {
75 Self { state: Arc::clone(&self.state) }
76 }
77}
78
79impl<Q: Clone + PartialEq> LiveQueryRequests<Q> {
80 pub fn set(&self, request: Q) -> Result<LiveQueryRevision, LiveQueryClosed> {
84 let mut state = lock_unpoisoned(&self.state.requests);
85 if !state.open {
86 return Err(LiveQueryClosed);
87 }
88 if request == state.latest {
89 return Ok(state.revision);
90 }
91 let revision =
92 LiveQueryRevision(state.revision.0.checked_add(1).expect("request revision exhausted"));
93 state.latest = request.clone();
94 state.revision = revision;
95 state.pending = Some((request, revision));
96 self.state.changed.notify_one();
97 Ok(revision)
98 }
99}
100
101struct QueryLifetime<Q>(Arc<RequestState<Q>>);
103
104impl<Q> Drop for QueryLifetime<Q> {
105 fn drop(&mut self) {
106 let mut state = lock_unpoisoned(&self.0.requests);
107 state.open = false;
108 state.pending = None;
109 }
110}
111
112pub struct ReconfigurableLiveQuery<Q, T, E> {
115 lifetime: QueryLifetime<Q>,
116 run: Run<Q, T, E>,
117 failed: Failed<E>,
118 commits: CommitSubscription,
119 bugs: BugSinkRef,
121 current: Option<(Q, LiveQueryRevision)>,
122 previous: Option<T>,
123 ended: bool,
127 #[cfg(any(test, feature = "test-utils"))]
128 runs: LiveQueryRuns,
129}
130
131impl<Q, T, E> ReconfigurableLiveQuery<Q, T, E>
132where
133 Q: Clone + PartialEq + Send + Sync + 'static,
134 T: Send + 'static,
135 E: CarriesBug + Send + 'static,
136{
137 pub fn new<F: Clone + Send + Sync + 'static, R: 'static>(
140 request: Q,
141 run: Run<Q, T, E>,
142 failed: fn(crate::Error<F, R>) -> E,
143 handle: &Handle<F>,
144 bugs: BugSinkRef,
145 ) -> Self {
146 let commits = handle.subscribe();
147 let failed = Handle::failed(failed);
148 Self {
149 lifetime: QueryLifetime(Arc::new(RequestState {
150 requests: Mutex::new(Requests {
151 open: true,
152 latest: request.clone(),
153 revision: LiveQueryRevision(0),
154 pending: Some((request, LiveQueryRevision(0))),
155 }),
156 changed: Notify::new(),
157 })),
158 run,
159 failed,
160 commits,
161 bugs,
162 current: None,
163 previous: None,
164 ended: false,
165 #[cfg(any(test, feature = "test-utils"))]
166 runs: LiveQueryRuns::default(),
167 }
168 }
169
170 #[cfg(any(test, feature = "test-utils"))]
172 pub fn runs(&self) -> LiveQueryRuns {
173 self.runs
174 }
175
176 #[cfg(any(test, feature = "test-utils"))]
180 pub fn is_marked_for_rerun(&self) -> bool {
181 assert!(self.current.is_some(), "probe requires a completed query");
182 self.commits.state().changed
183 }
184
185 pub fn bugs(&self) -> &BugSinkRef {
187 &self.bugs
188 }
189
190 #[cfg(any(test, feature = "test-utils"))]
192 pub fn has_pending_request(&self) -> bool {
193 lock_unpoisoned(&self.lifetime.0.requests).pending.is_some()
194 }
195
196 pub fn requests(&self) -> LiveQueryRequests<Q> {
198 LiveQueryRequests { state: Arc::clone(&self.lifetime.0) }
199 }
200
201 pub fn process<P, U>(self, process: P) -> ReconfigurableLiveQuery<Q, U, E>
204 where
205 T: Clone + PartialEq,
206 P: Fn(T) -> Result<U, E> + Send + Sync + 'static,
207 U: Send + 'static,
208 {
209 let ReconfigurableLiveQuery {
210 lifetime,
211 run,
212 failed,
213 commits,
214 bugs,
215 current,
216 previous: _,
217 ended,
218 #[cfg(any(test, feature = "test-utils"))]
219 runs,
220 } = self;
221 let failing = Arc::clone(&failed);
222 let mapped: Run<Q, U, E> = Arc::new(move |request, commits| {
223 let value = run(request, commits)?;
224 caught_sync("process a read", || process(value))
225 .unwrap_or_else(|bug| Err(failing(Stop::Bug(bug))))
226 });
227 if let Some(request) = ¤t {
230 let mut requests = lock_unpoisoned(&lifetime.0.requests);
231 if requests.pending.is_none() {
232 requests.pending = Some(request.clone());
233 }
234 }
235 ReconfigurableLiveQuery {
236 lifetime,
237 run: mapped,
238 failed,
239 commits,
240 bugs,
241 current,
242 previous: None,
243 ended,
244 #[cfg(any(test, feature = "test-utils"))]
245 runs,
246 }
247 }
248
249 pub fn changed(&self) -> impl Future<Output = ()> + Send + 'static {
254 let mut commits = self.commits.clone();
255 let requests = Arc::clone(&self.lifetime.0);
256 let settled = self.ended || self.current.is_none();
257 async move {
258 loop {
259 let commit = commits.observe();
260 if settled
261 || commit.changed
262 || commit.stopped()
263 || lock_unpoisoned(&requests.requests).pending.is_some()
264 {
265 return;
266 }
267 let mut commit_wait = pin!(commits.changed());
268 let mut request_wait = pin!(requests.changed.notified());
269 poll_fn(|context| {
270 if commit_wait.as_mut().poll(context).is_ready()
271 || request_wait.as_mut().poll(context).is_ready()
272 {
273 Poll::Ready(())
274 } else {
275 Poll::Pending
276 }
277 })
278 .await;
279 }
280 }
281 }
282
283 pub fn run_changed(&mut self) -> Option<ReconfigurableLiveQueryEvent<Q, T, E>>
289 where
290 T: Clone + PartialEq,
291 {
292 if self.ended {
293 return None;
294 }
295 let commits = self.commits.state();
296 let failure = commits.stopped_by();
297 let changed = commits.changed;
298 let request = lock_unpoisoned(&self.lifetime.0.requests).pending.take();
299 let next = match (request, changed) {
300 (Some(request), true) => Some((request, LiveQueryCause::RequestAndWrite)),
301 (Some(request), false) => Some((request, LiveQueryCause::Request)),
302 (None, true) => Some((
303 self.current.as_ref().expect("a previous run read columns").clone(),
304 LiveQueryCause::Write,
305 )),
306 (None, false) if failure.is_some() => Some((
307 self.current.as_ref().expect("initial request was answered").clone(),
308 LiveQueryCause::Write,
309 )),
310 (None, false) => None,
311 };
312 let ((request, revision), cause) = next?;
313 let result = if let Some(stop) = failure {
314 Err((self.failed)(stop))
315 } else {
316 self.commits.begin();
317 caught_sync("live query", || (self.run)(&request, &self.commits))
318 .unwrap_or_else(|bug| Err((self.failed)(Stop::Bug(bug))))
319 };
320 self.current = Some((request.clone(), revision));
321 let equal = match &result {
322 Ok(value) => self.previous.as_ref() == Some(value),
323 Err(_) => false,
324 };
325 self.previous = match &result {
329 Ok(value) => Some(value.clone()),
330 Err(_) => None,
331 };
332 #[cfg(any(test, feature = "test-utils"))]
333 self.runs.count(cause, equal);
334 if cause == LiveQueryCause::Write && equal {
335 return None;
336 }
337 let bug = result.as_ref().err().and_then(CarriesBug::bug).is_some();
341 if bug {
342 self.commits.stop();
343 }
344 self.ended = bug || (result.is_err() && self.commits.state().stopped());
345 Some(ReconfigurableLiveQueryEvent { request, revision, cause, result })
346 }
347
348 pub fn has_ended(&self) -> bool {
351 self.ended
352 }
353
354 pub fn next_blocking(&mut self) -> Option<ReconfigurableLiveQueryEvent<Q, T, E>>
363 where
364 T: Clone + PartialEq,
365 {
366 while !self.ended {
367 block_on(self.changed());
368 if let Some(event) = self.run_changed() {
369 return Some(event);
370 }
371 }
372 None
373 }
374
375 #[cfg(any(test, feature = "test-utils"))]
378 pub async fn next_inline(&mut self) -> Option<ReconfigurableLiveQueryEvent<Q, T, E>>
379 where
380 T: Clone + PartialEq,
381 {
382 while !self.ended {
383 self.changed().await;
384 if let Some(event) = self.run_changed() {
385 return Some(event);
386 }
387 }
388 None
389 }
390}
391
392pub struct LiveQuery<T, E> {
395 inner: ReconfigurableLiveQuery<(), T, E>,
396}
397
398impl<T: Send + 'static, E: CarriesBug + Send + 'static> LiveQuery<T, E> {
399 pub fn new(inner: ReconfigurableLiveQuery<(), T, E>) -> Self {
401 Self { inner }
402 }
403
404 pub fn changed(&self) -> impl Future<Output = ()> + Send + 'static {
409 self.inner.changed()
410 }
411
412 pub fn run_changed(&mut self) -> Option<Result<T, E>>
417 where
418 T: Clone + PartialEq,
419 {
420 Some(self.inner.run_changed()?.result)
421 }
422
423 pub fn has_ended(&self) -> bool {
426 self.inner.has_ended()
427 }
428
429 pub fn next_blocking(&mut self) -> Option<Result<T, E>>
436 where
437 T: Clone + PartialEq,
438 {
439 Some(self.inner.next_blocking()?.result)
440 }
441
442 #[cfg(any(test, feature = "test-utils"))]
444 pub async fn next_inline(&mut self) -> Option<Result<T, E>>
445 where
446 T: Clone + PartialEq,
447 {
448 Some(self.inner.next_inline().await?.result)
449 }
450
451 pub fn bugs(&self) -> &BugSinkRef {
453 self.inner.bugs()
454 }
455
456 #[cfg(any(test, feature = "test-utils"))]
458 pub fn runs(&self) -> LiveQueryRuns {
459 self.inner.runs()
460 }
461
462 #[cfg(any(test, feature = "test-utils"))]
465 pub fn is_marked_for_rerun(&self) -> bool {
466 self.inner.is_marked_for_rerun()
467 }
468
469 pub fn process<P, U>(self, process: P) -> LiveQuery<U, E>
472 where
473 T: Clone + PartialEq,
474 P: Fn(T) -> Result<U, E> + Send + Sync + 'static,
475 U: Send + 'static,
476 {
477 LiveQuery { inner: self.inner.process(process) }
478 }
479}