Skip to main content

sqlive/
live_judging.rs

1//! A connection's part in live queries' judging of writes (§4): a live
2//! query's run, which judges the writes that committed while it ran, a
3//! write's judging before it commits, and the lookups both run in their own
4//! transaction.
5
6use super::HostSql;
7use crate::authorization::Policy;
8use crate::authorization::PolicyError;
9use crate::{Judging, Lookups, NoAnswer, ReadSet};
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::Arc;
12
13impl<P: Policy> HostSql<P> {
14    /// A live query's run on one snapshot. What its statements read goes
15    /// to `judge` before the snapshot ends, which judges the writes that
16    /// committed during the run by lookups in that snapshot (§4).
17    pub fn live_read<F, R, E>(
18        &self,
19        judge: &mut dyn FnMut(ReadSet, &mut Lookups<'_>) -> rusqlite::Result<()>,
20        read: F,
21    ) -> Result<R, E>
22    where
23        F: FnOnce(&Self) -> Result<R, E>,
24        E: From<PolicyError<P>>,
25    {
26        let mut finished = false;
27        let result = self.read_transaction(|| {
28            let _reading = self.authorization.live_reading();
29            let result = read(self);
30            let reads = self.authorization.reads();
31            finished = true;
32            let judged = judge(reads, &mut |judging| self.ask_judged(judging));
33            let value = result?;
34            judged.map_err(crate::Error::from)?;
35            Ok(value)
36        });
37        // A run that never began read nothing.
38        if !finished {
39            judge(ReadSet::new(), &mut |_| unreachable!("a run that read nothing reads no join"))
40                .expect("judging without lookups can't fail");
41        }
42        result
43    }
44
45    /// Judge a write's changes for every waiting live query, in the
46    /// write's own transaction before it commits: a lookup reads the rows
47    /// the write leaves (§4).
48    pub(super) fn judge(
49        &self,
50        handle: &crate::Handle<P::Failure>,
51        changes: Vec<crate::RowChange>,
52    ) -> Result<crate::Judged, PolicyError<P>> {
53        let _reading = self.authorization.reading();
54        let judged =
55            handle.judge(changes, crate::committing(), &mut |judging| self.ask_judged(judging))?;
56        #[cfg(any(test, feature = "test-utils"))]
57        self.record_work(|work| work.judged_queries += judged.judgments());
58        Ok(judged)
59    }
60
61    /// Answer one question about a changed row, read in this connection's
62    /// transaction, judged as app SQL is without recording its reads.
63    fn ask_judged(&self, judging: Judging<'_>) -> Result<bool, NoAnswer> {
64        self.authorization.judged_unrecorded(|| Ok(self.ask(judging)))?
65    }
66
67    /// Answer one question about a changed row, read in this connection's
68    /// transaction: a write's own, or a live query's run. The caller sets
69    /// how the authorizer judges it.
70    fn ask(&self, judging: Judging<'_>) -> Result<bool, NoAnswer> {
71        match judging {
72            Judging::Partner(lookup, value) => {
73                let (sql, parameters) = lookup.sql(value);
74                self.run_limited(sql, &parameters)
75            }
76            // An error SQLite gives for this question, as for malformed JSON
77            // a condition reads or an overflow, says nothing of whether the
78            // row passes: it counts as a match.
79            Judging::Row(sql, parameters) => match self.run_limited(sql, parameters) {
80                Err(NoAnswer::Failed(
81                    rusqlite::Error::SqliteFailure(..) | rusqlite::Error::SqlInputError { .. },
82                )) => Ok(true),
83                found => found,
84            },
85        }
86    }
87
88    /// Whether `sql` finds a row. A question that runs past `LOOKUP_STEPS`
89    /// stops with no answer (§4).
90    fn run_limited(&self, sql: &str, parameters: &[crate::SqlValue]) -> Result<bool, NoAnswer> {
91        let mut statement = self.connection.prepare_cached(sql)?;
92        for (index, value) in parameters.iter().enumerate() {
93            statement.raw_bind_parameter(index + 1, value)?;
94        }
95        // SQLite calls the handler as a statement's count of steps passes
96        // each multiple of the limit, so the count starts at zero.
97        statement.reset_status(rusqlite::StatementStatus::VmStep);
98        self.lookups.arm();
99        let found = self.counting_steps(&mut statement, super::StepsOf::Lookup, |statement| {
100            statement.raw_query().next().map(|row| row.is_some())
101        });
102        let stopped = self.lookups.disarm();
103        match found {
104            Err(rusqlite::Error::SqliteFailure(error, _))
105                if error.code == rusqlite::ErrorCode::OperationInterrupted && stopped =>
106            {
107                #[cfg(any(test, feature = "test-utils"))]
108                self.record_work(|work| work.stopped_questions += 1);
109                Err(NoAnswer::Stopped)
110            }
111            found => found.map_err(NoAnswer::Failed),
112        }
113    }
114}
115
116/// What stops a lookup that runs past `LOOKUP_STEPS`. The connection's
117/// progress handler, set once as it opens, runs every `LOOKUP_STEPS` steps
118/// of any statement and interrupts one only while a lookup has armed it.
119pub(super) struct LookupLimit(Arc<LookupState>);
120
121struct LookupState {
122    armed: AtomicBool,
123    stopped: AtomicBool,
124}
125
126impl LookupLimit {
127    pub(super) fn install(connection: &mut rusqlite::Connection) -> rusqlite::Result<Self> {
128        let state = Arc::new(LookupState {
129            armed: AtomicBool::new(false),
130            stopped: AtomicBool::new(false),
131        });
132        let handler = Arc::clone(&state);
133        connection.progress_handler(
134            crate::LOOKUP_STEPS,
135            Some(move || {
136                let stop = handler.armed.load(Ordering::Relaxed);
137                if stop {
138                    handler.stopped.store(true, Ordering::Relaxed);
139                }
140                stop
141            }),
142        )?;
143        Ok(Self(state))
144    }
145
146    fn arm(&self) {
147        self.0.stopped.store(false, Ordering::Relaxed);
148        self.0.armed.store(true, Ordering::Relaxed);
149    }
150
151    /// Whether the lookup armed since was stopped.
152    fn disarm(&self) -> bool {
153        self.0.armed.store(false, Ordering::Relaxed);
154        self.0.stopped.load(Ordering::Relaxed)
155    }
156}
157
158#[cfg(test)]
159#[path = "live_judging_tests.rs"]
160mod tests;