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:
@@ -9,8 +9,8 @@ use bakashrot_proto::limits::{
|
||||
ATTACHMENT_PART_SIZE, MAX_HEADS_PER_PACKET, MAX_MESSAGE_SIZE, MAX_MISSING_ATTACHMENTS,
|
||||
};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, Continue, Head, MessagePushed, ReplicateAttachment, ReplicateMessages, SyncState,
|
||||
SyncStateRequest,
|
||||
Attachment, Continue, Head, MessagePushed, Pair, ReplicateAttachment, ReplicateMessages,
|
||||
SyncState, SyncStateRequest,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
@@ -124,24 +124,21 @@ pub(crate) async fn sync_state(
|
||||
return refusal;
|
||||
}
|
||||
let first = request.after.is_none();
|
||||
let mut after = request.after.map(|pair| (pair.topic, pair.node));
|
||||
let mut after = request.after;
|
||||
let (mut heads, mut more) = (Vec::new(), false);
|
||||
// Read in pages too, those it doesn't take from this peer skipped:
|
||||
// until the page is full and one more is found, or none is left.
|
||||
'pages: loop {
|
||||
let from = after.clone();
|
||||
let from = after.take();
|
||||
let read = shared
|
||||
.read(move |reader| {
|
||||
let from = from.as_ref().map(|(t, n)| (t.as_str(), n.as_str()));
|
||||
reader.heads_after(from, MAX_HEADS_PER_PACKET)
|
||||
})
|
||||
.read(move |reader| reader.heads_after(from.as_ref(), MAX_HEADS_PER_PACKET))
|
||||
.await;
|
||||
let read: Vec<Head> = match read {
|
||||
Ok(read) => read,
|
||||
Err(refusal) => return refusal.into(),
|
||||
};
|
||||
let last_page = read.len() < MAX_HEADS_PER_PACKET;
|
||||
after = read.last().map(|h| (h.topic.clone(), h.node.clone()));
|
||||
after = read.last().map(Pair::from);
|
||||
for head in read {
|
||||
if peer.permissions.accepts(&head.topic, &head.node) {
|
||||
if heads.len() == MAX_HEADS_PER_PACKET {
|
||||
|
||||
@@ -109,7 +109,9 @@ async fn serve(shared: &Arc<Shared>, tcp: TcpStream, address: IpAddr) -> Result<
|
||||
}
|
||||
Packet::GetMessages(get) => get_messages(shared, &peer, get).await,
|
||||
Packet::ListNames(list) => list_names(shared, &peer, list).await,
|
||||
Packet::Query(query) => self::query(shared, &peer, query).await,
|
||||
Packet::Query(query) => self::query(shared, &peer, &mut frames, query)
|
||||
.await
|
||||
.map_err(failed)?,
|
||||
Packet::Ping(_) => Pong {}.into(),
|
||||
Packet::SyncStateRequest(request) => {
|
||||
accept_from::sync_state(shared, &mut peer, request).await
|
||||
@@ -546,16 +548,27 @@ async fn list_names(shared: &Arc<Shared>, peer: &Peer, list: ListNames) -> Packe
|
||||
.into()
|
||||
}
|
||||
|
||||
async fn query(shared: &Arc<Shared>, peer: &Peer, query: Query) -> Packet {
|
||||
/// A query's answer. Nothing comes while it runs: what does (the client
|
||||
/// closing, having given up) stops it and closes the connection.
|
||||
async fn query(
|
||||
shared: &Arc<Shared>,
|
||||
peer: &Peer,
|
||||
frames: &mut Frames,
|
||||
query: Query,
|
||||
) -> Result<Packet, String> {
|
||||
if !peer.permissions.can_query() {
|
||||
return refused(
|
||||
return Ok(refused(
|
||||
ErrorCode::NotAllowed,
|
||||
format!("{} may not run queries", peer.node),
|
||||
);
|
||||
));
|
||||
}
|
||||
match shared.query(query.sql).await {
|
||||
Ok(json) => QueryResult { json }.into(),
|
||||
Err(refused) => refused.into(),
|
||||
tokio::select! {
|
||||
answer = shared.query(query.sql) => Ok(match answer {
|
||||
Ok(json) => QueryResult { json }.into(),
|
||||
Err(refused) => refused.into(),
|
||||
}),
|
||||
// Dropping the query stops it.
|
||||
_ = frames.next() => Err("left while its query ran: stopped".into()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,10 +27,11 @@ use bakashrot_config::Config;
|
||||
use bakashrot_pki::{Revocations, SharedRevocations, summarize, tls};
|
||||
use bakashrot_proto::ErrorCode;
|
||||
use bakashrot_proto::packets::RequestRefused;
|
||||
use bakashrot_storage::{Database, QueryRunner, Reader};
|
||||
use bakashrot_storage::{Database, QueryRunner, Reader, Stop};
|
||||
use std::collections::HashSet;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
use tokio::net::TcpListener;
|
||||
@@ -73,6 +74,8 @@ struct Shared {
|
||||
readers: Pool<Reader>,
|
||||
/// Query connections not in use.
|
||||
queries: Pool<QueryRunner>,
|
||||
/// Clients' queries running now.
|
||||
queries_running: AtomicUsize,
|
||||
/// The replicated attachments being received (topic, node, message
|
||||
/// id): one peer at a time each (`accept_from.rs`).
|
||||
receiving: Mutex<HashSet<(String, String, u64)>>,
|
||||
@@ -117,6 +120,7 @@ impl Server {
|
||||
pushes,
|
||||
readers: Pool::new(),
|
||||
queries: Pool::new(),
|
||||
queries_running: AtomicUsize::new(0),
|
||||
receiving: Mutex::new(HashSet::new()),
|
||||
config,
|
||||
});
|
||||
@@ -185,6 +189,13 @@ impl Server {
|
||||
self.shared.pushes.stop().await;
|
||||
}
|
||||
|
||||
/// How many clients' queries are running now: each until it's
|
||||
/// answered, stopped past `query_time_limit`, or stopped as its client
|
||||
/// leaves.
|
||||
pub fn queries_running(&self) -> usize {
|
||||
self.shared.queries_running.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Reloads the CRL file now: how many certificates it revokes.
|
||||
pub fn reload_revocations(&self) -> Result<usize, String> {
|
||||
let shared = &self.shared;
|
||||
@@ -226,12 +237,21 @@ impl Shared {
|
||||
Ok(sha256)
|
||||
}
|
||||
|
||||
/// Runs a client's SQL on a query connection, off the async threads.
|
||||
/// Runs a client's SQL on a query connection, off the async threads:
|
||||
/// stopped past `query_time_limit`, or once this future is dropped
|
||||
/// (its client left), not left running on its thread.
|
||||
async fn query(self: &Arc<Self>, sql: String) -> Result<String, RequestRefused> {
|
||||
let stop = Stop::new();
|
||||
let _stop_if_dropped = StopOnDrop(stop.clone());
|
||||
let limit = self.config.server.query_time_limit;
|
||||
let shared = self.clone();
|
||||
self.pooled(
|
||||
|shared| &shared.queries,
|
||||
Database::query_runner,
|
||||
move |runner: &QueryRunner| runner.run(&sql),
|
||||
move |runner: &QueryRunner| {
|
||||
let _running = Counted::new(&shared.queries_running);
|
||||
runner.run_limited(&sql, limit, &stop)
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -260,6 +280,31 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops a query when dropped: answered by then, or its client gone.
|
||||
struct StopOnDrop(Stop);
|
||||
|
||||
impl Drop for StopOnDrop {
|
||||
fn drop(&mut self) {
|
||||
self.0.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts one in its counter while it lives (a panic included).
|
||||
struct Counted<'a>(&'a AtomicUsize);
|
||||
|
||||
impl<'a> Counted<'a> {
|
||||
fn new(counter: &'a AtomicUsize) -> Counted<'a> {
|
||||
counter.fetch_add(1, Ordering::Relaxed);
|
||||
Counted(counter)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Counted<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Database connections not in use, each with when it was put back: the
|
||||
/// last one put back is taken first, so the others age out.
|
||||
struct Pool<C> {
|
||||
@@ -296,14 +341,12 @@ impl<C> Pool<C> {
|
||||
|
||||
/// Closes the connections unused for `idle_for` or more at `now`.
|
||||
fn sweep(&self, now: Instant, idle_for: Duration) {
|
||||
let stale: Vec<(C, Instant)> = {
|
||||
let mut idle = self.lock();
|
||||
let (stale, fresh) = idle
|
||||
.drain(..)
|
||||
.partition(|(_, since)| now.saturating_duration_since(*since) >= idle_for);
|
||||
*idle = fresh;
|
||||
stale
|
||||
};
|
||||
let stale: Vec<(C, Instant)> = self
|
||||
.lock()
|
||||
.extract_if(.., |(_, since)| {
|
||||
now.saturating_duration_since(*since) >= idle_for
|
||||
})
|
||||
.collect();
|
||||
drop(stale);
|
||||
}
|
||||
|
||||
@@ -362,6 +405,7 @@ fn refusal(error: bakashrot_storage::Error) -> RequestRefused {
|
||||
Error::UnknownName(_) => ErrorCode::UnknownName,
|
||||
Error::TooBig(_) => ErrorCode::TooBig,
|
||||
Error::Query(_) => ErrorCode::QueryFailed,
|
||||
Error::QueryTimedOut(_) => ErrorCode::QueryTimedOut,
|
||||
Error::Sqlite(_) | Error::Unusable(_) | Error::RolledBack => {
|
||||
warn!("the database: {error}");
|
||||
return server_error("the database failed");
|
||||
|
||||
@@ -168,33 +168,30 @@ impl Link {
|
||||
/// Its `SyncState`, every page: the first (the lists), and the last
|
||||
/// id of each topic and node.
|
||||
async fn sync_state(&mut self) -> Result<(SyncState, HashMap<(String, String), u64>), String> {
|
||||
let mut first = self.sync_page(None).await?;
|
||||
let (mut heads, mut more) = (std::mem::take(&mut first.heads), first.more);
|
||||
let mut theirs = HashMap::new();
|
||||
let mut first = None;
|
||||
let mut after = None;
|
||||
loop {
|
||||
let mut page = match self.ask(SyncStateRequest { after }.into()).await? {
|
||||
Packet::SyncState(page) => page,
|
||||
Packet::RequestRefused(refused) => {
|
||||
return Err(format!("refused: {}", refused.reason));
|
||||
}
|
||||
other => return Err(unexpected(&other)),
|
||||
};
|
||||
after = match page.more {
|
||||
true => page.heads.last().map(|head| Pair {
|
||||
topic: head.topic.clone(),
|
||||
node: head.node.clone(),
|
||||
}),
|
||||
false => None,
|
||||
};
|
||||
let after = heads.last().filter(|_| more).map(Pair::from);
|
||||
theirs.extend(
|
||||
page.heads
|
||||
.drain(..)
|
||||
heads
|
||||
.into_iter()
|
||||
.map(|head| (key(&head.topic, &head.node), head.last_id)),
|
||||
);
|
||||
first.get_or_insert(page);
|
||||
if after.is_none() {
|
||||
return Ok((first.expect("a page came"), theirs));
|
||||
}
|
||||
let Some(after) = after else {
|
||||
return Ok((first, theirs));
|
||||
};
|
||||
let page = self.sync_page(Some(after)).await?;
|
||||
(heads, more) = (page.heads, page.more);
|
||||
}
|
||||
}
|
||||
|
||||
/// A page of its `SyncState`, after the pair `after`.
|
||||
async fn sync_page(&mut self, after: Option<Pair>) -> Result<SyncState, String> {
|
||||
match self.ask(SyncStateRequest { after }.into()).await? {
|
||||
Packet::SyncState(page) => Ok(page),
|
||||
Packet::RequestRefused(refused) => Err(format!("refused: {}", refused.reason)),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,18 +320,16 @@ impl Link {
|
||||
async fn wait(&mut self, duration: Duration) -> Result<(), String> {
|
||||
let keepalive = Duration::from_secs(KEEPALIVE_SECS);
|
||||
let mut left = duration;
|
||||
loop {
|
||||
let step = left.min(keepalive);
|
||||
sleep(step).await;
|
||||
left -= step;
|
||||
if left.is_zero() {
|
||||
return Ok(());
|
||||
}
|
||||
while left > keepalive {
|
||||
sleep(keepalive).await;
|
||||
left -= keepalive;
|
||||
match self.ask(Ping {}.into()).await? {
|
||||
Packet::Pong(_) => {}
|
||||
other => return Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
sleep(left).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ask(&mut self, packet: Packet) -> Result<Packet, String> {
|
||||
@@ -375,11 +370,10 @@ async fn check_own_copy(
|
||||
.hash_parts(attachment_id, 0..attachment.part_count())
|
||||
.await
|
||||
.map(|sha256| sha256.finish().as_ref() == attachment.sha256);
|
||||
match judge(&read) {
|
||||
match judge(read) {
|
||||
OwnCopy::Intact => return,
|
||||
OwnCopy::Damaged => {}
|
||||
OwnCopy::Unknown => {
|
||||
let why = read.err().map(|refused| refused.reason).unwrap_or_default();
|
||||
OwnCopy::Unknown(why) => {
|
||||
warn!(
|
||||
"{message}: this server's copy of its attachment couldn't be read back ({why}): \
|
||||
kept, checked again when a peer refuses it again"
|
||||
@@ -406,20 +400,21 @@ enum OwnCopy {
|
||||
/// Read whole and not matching, or a part missing: dropped and asked
|
||||
/// for again.
|
||||
Damaged,
|
||||
/// The read failed (the database busy, a connection not opened...):
|
||||
/// nothing is known, the copy is kept. Dropping it then could lose the
|
||||
/// only one there is (this server the attachment's origin).
|
||||
Unknown,
|
||||
/// The read failed (the database busy, a connection not opened...),
|
||||
/// saying why: nothing is known, the copy is kept. Dropping it then
|
||||
/// could lose the only one there is (this server the attachment's
|
||||
/// origin).
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
/// The verdict on a read-back: whether its SHA-256 matched, or why it
|
||||
/// failed.
|
||||
fn judge(read: &Result<bool, RequestRefused>) -> OwnCopy {
|
||||
fn judge(read: Result<bool, RequestRefused>) -> OwnCopy {
|
||||
match read {
|
||||
Ok(true) => OwnCopy::Intact,
|
||||
Ok(false) => OwnCopy::Damaged,
|
||||
Err(refused) if refused.code == ErrorCode::NotFound.code() => OwnCopy::Damaged,
|
||||
Err(_) => OwnCopy::Unknown,
|
||||
Err(refused) => OwnCopy::Unknown(refused.reason),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,12 +434,13 @@ mod tests {
|
||||
#[test]
|
||||
fn only_a_copy_read_whole_or_missing_a_part_is_damaged() {
|
||||
let refused = |code| Err(RequestRefused::new(code, "why"));
|
||||
assert_eq!(judge(&Ok(true)), OwnCopy::Intact);
|
||||
assert_eq!(judge(&Ok(false)), OwnCopy::Damaged);
|
||||
let unknown = || OwnCopy::Unknown("why".into());
|
||||
assert_eq!(judge(Ok(true)), OwnCopy::Intact);
|
||||
assert_eq!(judge(Ok(false)), OwnCopy::Damaged);
|
||||
// A part missing (read_part's NotFound): damaged too.
|
||||
assert_eq!(judge(&refused(ErrorCode::NotFound)), OwnCopy::Damaged);
|
||||
// A read that failed says nothing about the copy: kept.
|
||||
assert_eq!(judge(&refused(ErrorCode::ServerError)), OwnCopy::Unknown);
|
||||
assert_eq!(judge(&refused(ErrorCode::InvalidRequest)), OwnCopy::Unknown);
|
||||
assert_eq!(judge(refused(ErrorCode::NotFound)), OwnCopy::Damaged);
|
||||
// A read that failed says nothing about the copy: kept, saying why.
|
||||
assert_eq!(judge(refused(ErrorCode::ServerError)), unknown());
|
||||
assert_eq!(judge(refused(ErrorCode::InvalidRequest)), unknown());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,12 +195,9 @@ fn write(writer: &mut Writer, group: Vec<(Write, oneshot::Sender<Outcome>)>) {
|
||||
}
|
||||
let mut outcomes = Vec::with_capacity(group.len());
|
||||
let committed = writer.batch(|batch| {
|
||||
// SQLite rolling the group back (a full disk...) fails the batch:
|
||||
// every write in it is refused below, none stored.
|
||||
for (write, _) in &group {
|
||||
// SQLite rolled the group back (a full disk...): the batch
|
||||
// fails, every write in it is refused below, none stored.
|
||||
if batch.is_rolled_back() {
|
||||
break;
|
||||
}
|
||||
outcomes.push(write.run(batch).map_err(refusal));
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -265,6 +265,60 @@ fn no_idle_database_connections() {
|
||||
assert_eq!(json, r#"{"columns":["n"],"rows":[["3"]]}"#);
|
||||
}
|
||||
|
||||
/// A query that never ends.
|
||||
const FOREVER: &str =
|
||||
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n";
|
||||
|
||||
/// Past `query_time_limit`, a query is stopped and refused, the connection
|
||||
/// kept; a client giving up first (its answer timeout) closes, and its
|
||||
/// query is stopped then.
|
||||
#[test]
|
||||
fn queries_are_stopped() {
|
||||
let running = Running::start_with("query-time-limit", "query_time_limit = \"1s\"\n");
|
||||
let analyst = running.issue("analyst-1", &["analyst"]);
|
||||
let mut client = running.connect(&analyst).unwrap();
|
||||
let started = Instant::now();
|
||||
let error = client.query(FOREVER).unwrap_err();
|
||||
let took = started.elapsed();
|
||||
assert_eq!(error.code(), ErrorCode::QueryTimedOut.code(), "{error}");
|
||||
assert!(
|
||||
error
|
||||
.message()
|
||||
.contains("stopped after 1s, the server's time limit"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
took >= Duration::from_secs(1) && took < Duration::from_secs(5),
|
||||
"{took:?}"
|
||||
);
|
||||
assert_eq!(running.server.queries_running(), 0);
|
||||
assert_eq!(
|
||||
client.query("SELECT 1 AS one").unwrap(),
|
||||
r#"{"columns":["one"],"rows":[["1"]]}"#
|
||||
);
|
||||
|
||||
// The client gives up long before the server's limit.
|
||||
let running = Running::start_with("query-left", "query_time_limit = \"1h\"\n");
|
||||
let mut client = running
|
||||
.connect(&running.issue("analyst-1", &["analyst"]))
|
||||
.unwrap();
|
||||
client
|
||||
.set_answer_timeout(Duration::from_millis(300))
|
||||
.unwrap();
|
||||
let error = client.query(FOREVER).unwrap_err();
|
||||
assert_eq!(code(error), ErrorCode::ConnectionLost.code());
|
||||
assert!(client.is_closed());
|
||||
wait_for("its query stopped", || {
|
||||
running.server.queries_running() == 0
|
||||
});
|
||||
// Its connection is closed; the next one is answered.
|
||||
let mut client = running
|
||||
.connect(&running.issue("analyst-2", &["analyst"]))
|
||||
.unwrap();
|
||||
assert!(client.query("SELECT 1").is_ok());
|
||||
assert_eq!(running.server.queries_running(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refusals_keep_the_connection() {
|
||||
let running = Running::start("refusals");
|
||||
@@ -1542,14 +1596,6 @@ fn add_pairs(path: &std::path::Path, prefix: &str, count: usize) {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// The pair of a head, to ask the page after it.
|
||||
fn after(head: &Head) -> Option<Pair> {
|
||||
Some(Pair {
|
||||
topic: head.topic.clone(),
|
||||
node: head.node.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Heads as (topic, node, last id), to compare.
|
||||
fn triples(heads: &[Head]) -> Vec<(String, String, u64)> {
|
||||
heads
|
||||
@@ -1589,7 +1635,7 @@ fn sync_state_in_pages() {
|
||||
(first.topics.as_slice(), first.nodes.as_slice()),
|
||||
(["*".to_string()].as_slice(), ["*".to_string()].as_slice())
|
||||
);
|
||||
let second = sync_page(&mut peer, after(first.heads.last().unwrap()));
|
||||
let second = sync_page(&mut peer, first.heads.last().map(Pair::from));
|
||||
assert!(!second.more);
|
||||
assert!(second.topics.is_empty() && second.nodes.is_empty() && second.missing.is_empty());
|
||||
let mut both = triples(&first.heads);
|
||||
@@ -1613,7 +1659,7 @@ fn sync_state_in_pages() {
|
||||
"b000005"
|
||||
);
|
||||
// After the very last: nothing, nothing more.
|
||||
let end = sync_page(&mut peer, after(second.heads.last().unwrap()));
|
||||
let end = sync_page(&mut peer, second.heads.last().map(Pair::from));
|
||||
assert!(end.heads.is_empty() && !end.more);
|
||||
|
||||
// A peer taking only "b": the others are skipped, not counted. Exactly
|
||||
@@ -1628,7 +1674,7 @@ fn sync_state_in_pages() {
|
||||
let first = sync_page(&mut picky, None);
|
||||
assert!(first.more);
|
||||
assert_eq!(first.heads.len(), PAGE);
|
||||
let second = sync_page(&mut picky, after(first.heads.last().unwrap()));
|
||||
let second = sync_page(&mut picky, first.heads.last().map(Pair::from));
|
||||
assert!(!second.more);
|
||||
assert_eq!(
|
||||
triples(&second.heads),
|
||||
|
||||
Reference in New Issue
Block a user