mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Stopped long queries, Read is_open() through TLS, Simplified answers and paging
- [server] query_time_limit (20 s by default) stops a client's query through SQLite's progress handler: refused with QueryTimedOut (11). A client closing while its query runs stops it too. - The answer timeout in the DLL (BakaShrot_SetAnswerTimeout / GetAnswerTimeout, kept across connections), Python (answer_timeout) and C# (AnswerTimeoutMs); QueryTimedOut in every binding. - is_open() reads what's waiting through TLS: a close_notify says closed, TLS's own records keep it open, unasked data or a broken stream close it. - The Rust client checks an answer's type in one place (TryFrom per packet); Client::wait() pings while waiting (the tool's --follow). - Pair::from(&Head), heads_after taking a Pair; simpler SyncState paging on both ends; the writer's redundant rollback check dropped. - codes.rs: the bindings' error codes and copied values match Rust's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -64,8 +64,8 @@ impl Batch<'_> {
|
||||
}
|
||||
|
||||
/// Whether SQLite rolled the transaction back by itself: nothing more
|
||||
/// may run in it.
|
||||
pub fn is_rolled_back(&self) -> bool {
|
||||
/// may run in it, every operation is refused ([`Error::RolledBack`]).
|
||||
fn is_rolled_back(&self) -> bool {
|
||||
self.transaction.is_autocommit()
|
||||
}
|
||||
|
||||
|
||||
@@ -148,7 +148,7 @@ impl Database {
|
||||
AuthAction::Pragma { .. } => Authorization::Deny,
|
||||
_ => Authorization::Allow,
|
||||
}))?;
|
||||
Ok(QueryRunner::new(connection))
|
||||
QueryRunner::new(connection)
|
||||
}
|
||||
|
||||
/// A connection with this database's settings: WAL, `synchronous`, the
|
||||
|
||||
@@ -22,7 +22,7 @@ mod reader;
|
||||
|
||||
pub use batch::{Batch, Writer};
|
||||
pub use database::{Checkpointer, Database, WRITER_CHECKPOINT_PAGES};
|
||||
pub use query::{MAX_QUERY_BYTES, MAX_QUERY_ROWS, QueryRunner};
|
||||
pub use query::{MAX_QUERY_BYTES, MAX_QUERY_ROWS, QueryRunner, Stop};
|
||||
pub use reader::{Attachment, MESSAGES_BYTES, Reader};
|
||||
|
||||
use bakashrot_proto::limits::{MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID};
|
||||
@@ -55,6 +55,8 @@ pub enum Error {
|
||||
TooBig(String),
|
||||
/// A client's query that failed or isn't read-only: `QueryFailed`.
|
||||
Query(String),
|
||||
/// A client's query stopped past its time limit: `QueryTimedOut`.
|
||||
QueryTimedOut(String),
|
||||
/// SQLite rolled the batch's transaction back by itself (disk full,
|
||||
/// an I/O error...): nothing in it is stored, and nothing more runs in
|
||||
/// it (it would be written outside the transaction): `ServerError`.
|
||||
@@ -73,7 +75,8 @@ impl fmt::Display for Error {
|
||||
| Error::NotFound(what)
|
||||
| Error::UnknownName(what)
|
||||
| Error::TooBig(what)
|
||||
| Error::Query(what) => f.write_str(what),
|
||||
| Error::Query(what)
|
||||
| Error::QueryTimedOut(what) => f.write_str(what),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,12 +9,20 @@
|
||||
//! connection, `query_only` included, before the statement is looked
|
||||
//! at. The result is JSON, every value a string or null:
|
||||
//! `{"columns":[...],"rows":[[...],...]}`.
|
||||
//!
|
||||
//! A query can be stopped while it runs ([`QueryRunner::run_limited`]):
|
||||
//! past a time limit, or from another thread ([`Stop`]: its client left).
|
||||
//! SQLite looks every few thousand steps (its progress handler) and ends
|
||||
//! the statement there.
|
||||
|
||||
use crate::{Error, Result};
|
||||
use bakashrot_proto::limits::MAX_MESSAGE_SIZE;
|
||||
use rusqlite::Connection;
|
||||
use rusqlite::types::ValueRef;
|
||||
use serde_json::Value;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The most rows a query returns, as before.
|
||||
pub const MAX_QUERY_ROWS: usize = 10_000;
|
||||
@@ -22,22 +30,111 @@ pub const MAX_QUERY_ROWS: usize = 10_000;
|
||||
/// The biggest result, in bytes of JSON: what a packet carries.
|
||||
pub const MAX_QUERY_BYTES: usize = MAX_MESSAGE_SIZE;
|
||||
|
||||
/// How many of SQLite's steps between two looks at the time limit and the
|
||||
/// [`Stop`]: about a tenth of a millisecond.
|
||||
const STEPS_BETWEEN_LOOKS: i32 = 10_000;
|
||||
|
||||
/// Stops a query run with [`QueryRunner::run_limited`], from any thread:
|
||||
/// within a few steps, refused then ([`Error::Query`], "stopped while it
|
||||
/// ran"). Clones stop the same query.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Stop(Arc<AtomicBool>);
|
||||
|
||||
impl Stop {
|
||||
/// Not stopped yet.
|
||||
pub fn new() -> Stop {
|
||||
Stop::default()
|
||||
}
|
||||
|
||||
/// Stops the query now, or as soon as it starts.
|
||||
pub fn stop(&self) {
|
||||
self.0.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Whether [`Stop::stop`] was called.
|
||||
pub fn is_stopped(&self) -> bool {
|
||||
self.0.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the progress handler looks at during a query.
|
||||
#[derive(Debug, Default)]
|
||||
struct Watch {
|
||||
/// The deadline and the limit it came from: none past `Instant`'s end.
|
||||
limit: Option<(Instant, Duration)>,
|
||||
stop: Stop,
|
||||
/// Why it was interrupted, once it was: the refusal.
|
||||
interrupted: Option<Error>,
|
||||
}
|
||||
|
||||
impl Watch {
|
||||
/// Whether to interrupt the query now, and why.
|
||||
fn look(&mut self) -> bool {
|
||||
if self.interrupted.is_some() {
|
||||
return true;
|
||||
}
|
||||
let why = if self.stop.is_stopped() {
|
||||
Error::Query("stopped while it ran".to_owned())
|
||||
} else {
|
||||
match self.limit {
|
||||
Some((deadline, limit)) if Instant::now() >= deadline => Error::QueryTimedOut(
|
||||
format!("stopped after {limit:?}, the server's time limit: narrow the query"),
|
||||
),
|
||||
_ => return false,
|
||||
}
|
||||
};
|
||||
self.interrupted = Some(why);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// A read-only connection for clients' queries.
|
||||
#[derive(Debug)]
|
||||
pub struct QueryRunner {
|
||||
connection: Connection,
|
||||
watch: Arc<Mutex<Watch>>,
|
||||
}
|
||||
|
||||
fn lock(watch: &Mutex<Watch>) -> std::sync::MutexGuard<'_, Watch> {
|
||||
watch.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
impl QueryRunner {
|
||||
pub(crate) fn new(connection: Connection) -> QueryRunner {
|
||||
QueryRunner { connection }
|
||||
pub(crate) fn new(mut connection: Connection) -> Result<QueryRunner> {
|
||||
let watch = Arc::new(Mutex::new(Watch::default()));
|
||||
let looking = watch.clone();
|
||||
connection.progress_handler(STEPS_BETWEEN_LOOKS, Some(move || lock(&looking).look()))?;
|
||||
Ok(QueryRunner { connection, watch })
|
||||
}
|
||||
|
||||
/// Runs one read-only statement: its result as JSON. Refused
|
||||
/// ([`Error::Query`]) if it isn't one, or fails (SQLite's message, a
|
||||
/// failing row included: never a partial result); [`Error::TooBig`]
|
||||
/// past [`MAX_QUERY_ROWS`] or [`MAX_QUERY_BYTES`].
|
||||
/// past [`MAX_QUERY_ROWS`] or [`MAX_QUERY_BYTES`]. No time limit.
|
||||
pub fn run(&self, sql: &str) -> Result<String> {
|
||||
self.run_limited(sql, Duration::MAX, &Stop::new())
|
||||
}
|
||||
|
||||
/// [`QueryRunner::run`], stopped past `time_limit`
|
||||
/// ([`Error::QueryTimedOut`]) or by `stop` ([`Error::Query`]).
|
||||
pub fn run_limited(&self, sql: &str, time_limit: Duration, stop: &Stop) -> Result<String> {
|
||||
*lock(&self.watch) = Watch {
|
||||
limit: Instant::now()
|
||||
.checked_add(time_limit)
|
||||
.map(|deadline| (deadline, time_limit)),
|
||||
stop: stop.clone(),
|
||||
interrupted: None,
|
||||
};
|
||||
let result = self.query(sql);
|
||||
let interrupted = std::mem::take(&mut *lock(&self.watch)).interrupted;
|
||||
match (result, interrupted) {
|
||||
// Interrupted, whatever SQLite made of it.
|
||||
(Err(_), Some(why)) => Err(why),
|
||||
(result, _) => result,
|
||||
}
|
||||
}
|
||||
|
||||
fn query(&self, sql: &str) -> Result<String> {
|
||||
let failed = |error: rusqlite::Error| Error::Query(explain(error.to_string()));
|
||||
let mut statement = self.connection.prepare(sql).map_err(failed)?;
|
||||
if !statement.readonly() || statement.column_count() == 0 {
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::{
|
||||
};
|
||||
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, ReplicatedMessage,
|
||||
Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, Pair, ReplicatedMessage,
|
||||
StoredAttachment,
|
||||
};
|
||||
use rusqlite::{Connection, OptionalExtension, Row, params};
|
||||
@@ -169,9 +169,9 @@ impl Reader {
|
||||
/// Topics and nodes' last ids, what `SyncState` compares: `limit` at
|
||||
/// most, in the order of their names (without case), those after the
|
||||
/// pair `after` (from the first without).
|
||||
pub fn heads_after(&self, after: Option<(&str, &str)>, limit: usize) -> Result<Vec<Head>> {
|
||||
pub fn heads_after(&self, after: Option<&Pair>, limit: usize) -> Result<Vec<Head>> {
|
||||
// No name is empty: ("", "") comes before every pair.
|
||||
let (topic, node) = after.unwrap_or(("", ""));
|
||||
let (topic, node) = after.map_or(("", ""), |pair| (&pair.topic, &pair.node));
|
||||
let limit = i64::try_from(limit).unwrap_or(i64::MAX);
|
||||
self.connection
|
||||
.prepare_cached(
|
||||
|
||||
@@ -3,10 +3,11 @@
|
||||
|
||||
use bakashrot_config::Synchronous;
|
||||
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID};
|
||||
use bakashrot_proto::packets::{Attachment as Sent, ReplicatedMessage};
|
||||
use bakashrot_storage::{AttachmentState, Database, Error, MAX_QUERY_ROWS, MAX_STREAMS};
|
||||
use bakashrot_proto::packets::{Attachment as Sent, Pair, ReplicatedMessage};
|
||||
use bakashrot_storage::{AttachmentState, Database, Error, MAX_QUERY_ROWS, MAX_STREAMS, Stop};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const PART: usize = ATTACHMENT_PART_SIZE as usize;
|
||||
|
||||
@@ -174,9 +175,13 @@ fn pushing_and_reading() {
|
||||
]
|
||||
);
|
||||
// In pages: after a pair (its names without case), so many at most.
|
||||
let page = |after, limit| -> Vec<_> {
|
||||
let page = |after: Option<(&str, &str)>, limit| -> Vec<_> {
|
||||
let after = after.map(|(topic, node)| Pair {
|
||||
topic: topic.into(),
|
||||
node: node.into(),
|
||||
});
|
||||
reader
|
||||
.heads_after(after, limit)
|
||||
.heads_after(after.as_ref(), limit)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|h| (h.topic, h.node))
|
||||
@@ -754,6 +759,58 @@ fn queries() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queries_are_stopped() {
|
||||
let (database, _) = open("stopped-queries");
|
||||
let _writer = database.writer().unwrap();
|
||||
let runner = database.query_runner().unwrap();
|
||||
let forever =
|
||||
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n";
|
||||
let refused = |result: bakashrot_storage::Result<String>| match result {
|
||||
Err(Error::Query(why)) => why,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
|
||||
// Past its time limit.
|
||||
let started = Instant::now();
|
||||
let why = match runner.run_limited(forever, Duration::from_millis(200), &Stop::new()) {
|
||||
Err(Error::QueryTimedOut(why)) => why,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let took = started.elapsed();
|
||||
assert!(why.contains("200ms, the server's time limit"), "{why}");
|
||||
assert!(
|
||||
took >= Duration::from_millis(200) && took < Duration::from_secs(5),
|
||||
"{took:?}"
|
||||
);
|
||||
|
||||
// From another thread, long before its time limit.
|
||||
let stop = Stop::new();
|
||||
let stopping = stop.clone();
|
||||
let started = Instant::now();
|
||||
let thread = std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
stopping.stop();
|
||||
});
|
||||
let why = refused(runner.run_limited(forever, Duration::from_secs(3600), &stop));
|
||||
thread.join().unwrap();
|
||||
assert_eq!(why, "stopped while it ran");
|
||||
assert!(started.elapsed() < Duration::from_secs(5));
|
||||
// Stopped before it starts: at its first look.
|
||||
refused(runner.run_limited(forever, Duration::from_secs(3600), &stop));
|
||||
|
||||
// The next queries aren't: the connection is as before.
|
||||
let short = "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 100000) SELECT count(*) FROM n";
|
||||
let counted = r#"{"columns":["count(*)"],"rows":[["100000"]]}"#;
|
||||
assert_eq!(
|
||||
runner
|
||||
.run_limited(short, Duration::from_secs(60), &Stop::new())
|
||||
.unwrap(),
|
||||
counted
|
||||
);
|
||||
assert_eq!(runner.run(short).unwrap(), counted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_view_reads_by_key_range() {
|
||||
let (database, path) = open("plans");
|
||||
|
||||
Reference in New Issue
Block a user