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:
@@ -36,7 +36,7 @@ mod enumerations;
|
||||
pub use enumerations::*;
|
||||
mod text;
|
||||
|
||||
use bakashrot_client::{Client, Error, Settings};
|
||||
use bakashrot_client::{ANSWER_TIMEOUT, Client, Error, Settings};
|
||||
use bakashrot_proto::ErrorCode;
|
||||
use bakashrot_proto::packets::{MessageEntry, NameKind, NamesList};
|
||||
use std::collections::BTreeMap;
|
||||
@@ -46,6 +46,7 @@ use std::io::Cursor;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::Duration;
|
||||
use text::{Text, Utf8, Utf16};
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
@@ -81,6 +82,8 @@ struct State {
|
||||
certificate: Option<String>,
|
||||
key: Option<String>,
|
||||
crl: Option<String>,
|
||||
/// Given to each connection, and to the current one when set.
|
||||
answer_timeout: Duration,
|
||||
client: Option<Client>,
|
||||
/// The last call's error code, 0 if it succeeded.
|
||||
last_error: u32,
|
||||
@@ -107,6 +110,7 @@ impl State {
|
||||
certificate: None,
|
||||
key: None,
|
||||
crl: None,
|
||||
answer_timeout: ANSWER_TIMEOUT,
|
||||
client: None,
|
||||
last_error: 0,
|
||||
reason: String::new(),
|
||||
@@ -124,14 +128,10 @@ impl State {
|
||||
fn fail(&mut self, error: Error) {
|
||||
self.last_error = error.code();
|
||||
self.reason = error.message().to_owned();
|
||||
// The client closes its connection on those, and on others that
|
||||
// leave it out of step (a file failing mid-upload): forgotten then,
|
||||
// so connecting again works.
|
||||
let closed = [ErrorCode::ConnectionLost, ErrorCode::ProtocolError]
|
||||
.iter()
|
||||
.any(|code| code.code() == error.code())
|
||||
|| self.client.as_ref().is_some_and(Client::is_closed);
|
||||
if closed {
|
||||
// The client closes its connection on every failure that leaves it
|
||||
// out of step (`ConnectionLost`, `ProtocolError`, a file failing
|
||||
// mid-upload): forgotten then, so connecting again works.
|
||||
if self.client.as_ref().is_some_and(Client::is_closed) {
|
||||
self.client = None;
|
||||
}
|
||||
}
|
||||
@@ -465,7 +465,8 @@ unsafe fn connect<T: Text>(client: i64, host: *const T::Unit, port: i32) -> isiz
|
||||
true => format!("[{host}]:{port}"),
|
||||
false => format!("{host}:{port}"),
|
||||
};
|
||||
let client = Client::connect(&address, &settings)?;
|
||||
let mut client = Client::connect(&address, &settings)?;
|
||||
client.set_answer_timeout(state.answer_timeout)?;
|
||||
state.client = Some(client);
|
||||
Ok(1)
|
||||
})
|
||||
@@ -492,7 +493,7 @@ pub unsafe extern "C" fn BakaShrot_ConnectW(client: i64, host: *const u16, port:
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_IsConnected(client: i64) -> isize {
|
||||
get(client, 0, |state| {
|
||||
let open = state.client.as_ref().is_some_and(Client::is_open);
|
||||
let open = state.client.as_mut().is_some_and(Client::is_open);
|
||||
if !open {
|
||||
state.client = None;
|
||||
}
|
||||
@@ -520,6 +521,39 @@ pub extern "C" fn BakaShrot_Ping(client: i64) -> isize {
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets how long an answer may take, in milliseconds (more than 0; 30000
|
||||
/// until changed): longer for a slow query, say. Past it, the request
|
||||
/// fails with `ConnectionLost`, the connection closed (the server then
|
||||
/// stops the query it was running). Kept for the next connections, and
|
||||
/// applied to the current one: 1, or 0 if refused.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_SetAnswerTimeout(client: i64, milliseconds: i64) -> isize {
|
||||
call(client, 0, |state| {
|
||||
let timeout = u64::try_from(milliseconds)
|
||||
.ok()
|
||||
.filter(|ms| *ms > 0)
|
||||
.map(Duration::from_millis)
|
||||
.ok_or_else(|| {
|
||||
invalid(format!(
|
||||
"an answer timeout of {milliseconds} ms: more than 0"
|
||||
))
|
||||
})?;
|
||||
if let Some(connected) = state.client.as_mut() {
|
||||
connected.set_answer_timeout(timeout)?;
|
||||
}
|
||||
state.answer_timeout = timeout;
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
|
||||
/// How long an answer may take, in milliseconds (`BakaShrot_SetAnswerTimeout()`).
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_GetAnswerTimeout(client: i64) -> i64 {
|
||||
get(client, -1, |state| {
|
||||
i64::try_from(state.answer_timeout.as_millis()).unwrap_or(i64::MAX)
|
||||
})
|
||||
}
|
||||
|
||||
fn node(state: &State) -> &str {
|
||||
state.client.as_ref().map_or("", Client::node)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! The bindings' error codes are the protocol's, every one, by the same
|
||||
//! numbers: Python's `ErrorCode`, C#'s `ErrorCode`, PureBasic's constants.
|
||||
//! And the values they copy are the Rust side's.
|
||||
|
||||
use bakashrot_client::ANSWER_TIMEOUT;
|
||||
use bakashrot_proto::ErrorCode;
|
||||
use bakashrot_proto::limits::{KEEPALIVE_SECS, MAX_MESSAGES_PER_PACKET};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn binding(path: &str) -> String {
|
||||
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../bindings")
|
||||
.join(path);
|
||||
std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{}: {error}", path.display()))
|
||||
}
|
||||
|
||||
/// The protocol's codes, by number: their names as `name` writes them.
|
||||
fn expected(name: impl Fn(ErrorCode) -> String) -> BTreeMap<u32, String> {
|
||||
ErrorCode::ALL
|
||||
.iter()
|
||||
.map(|&code| (code.code(), name(code)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `NotFound` as `NOT_FOUND`.
|
||||
fn upper_snake(name: &str) -> String {
|
||||
let mut snake = String::new();
|
||||
for (at, c) in name.char_indices() {
|
||||
if c.is_ascii_uppercase() && at > 0 {
|
||||
snake.push('_');
|
||||
}
|
||||
snake.push(c.to_ascii_uppercase());
|
||||
}
|
||||
snake
|
||||
}
|
||||
|
||||
/// `NAME = 12` in `text`, one per line or comma: the names and numbers.
|
||||
fn assignments<'a>(text: impl Iterator<Item = &'a str>) -> BTreeMap<u32, String> {
|
||||
let mut found = BTreeMap::new();
|
||||
for item in text.flat_map(|line| line.split(',')) {
|
||||
// Comments: PureBasic's `;`, Python's ` #` (PureBasic's constants
|
||||
// start with `#`).
|
||||
let item = item.split(';').next().unwrap_or("");
|
||||
let item = item.split(" #").next().unwrap_or("").trim();
|
||||
let Some((name, number)) = item.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
let Ok(number) = number.trim().parse::<u32>() else {
|
||||
continue;
|
||||
};
|
||||
let before = found.insert(number, name.trim().to_owned());
|
||||
assert!(before.is_none(), "{number} twice: {before:?}, {name}");
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The lines of `text` from the one starting with `start` to the next
|
||||
/// starting with `end`.
|
||||
fn section<'a>(text: &'a str, start: &str, end: &str) -> impl Iterator<Item = &'a str> {
|
||||
text.lines()
|
||||
.skip_while(move |line| !line.trim_start().starts_with(start))
|
||||
.skip(1)
|
||||
.take_while(move |line| !line.trim_start().starts_with(end))
|
||||
}
|
||||
|
||||
/// The number `name` is set to in `text`: `NAME = 12`, a `;` after or not.
|
||||
fn number(text: &str, name: &str) -> f64 {
|
||||
let set = format!("{name} = ");
|
||||
let line = text.lines().find(|line| line.contains(&set));
|
||||
let line = line.unwrap_or_else(|| panic!("no {set}"));
|
||||
let value = line.split(&set).nth(1).unwrap_or("");
|
||||
let value = value.trim().trim_end_matches(';');
|
||||
value.parse().unwrap_or_else(|_| panic!("{set}{value}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_values() {
|
||||
let python = binding("python/bakashrot.py");
|
||||
let csharp = binding("csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs");
|
||||
let answer = ANSWER_TIMEOUT.as_secs_f64();
|
||||
let keepalive = KEEPALIVE_SECS as f64;
|
||||
assert_eq!(number(&python, "ANSWER_TIMEOUT_SECONDS"), answer);
|
||||
assert_eq!(number(&python, "KEEPALIVE_SECONDS"), keepalive);
|
||||
assert_eq!(
|
||||
number(&python, "MAX_GET_MESSAGES"),
|
||||
f64::from(MAX_MESSAGES_PER_PACKET)
|
||||
);
|
||||
assert_eq!(number(&csharp, "DefaultAnswerTimeoutMs"), answer * 1000.0);
|
||||
assert_eq!(number(&csharp, "KeepAliveMs"), keepalive * 1000.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python() {
|
||||
let text = binding("python/bakashrot.py");
|
||||
let found = assignments(section(&text, "class ErrorCode", "@property"));
|
||||
let mut expected = expected(|code| upper_snake(code.name()));
|
||||
expected.insert(0, "NONE".into());
|
||||
assert_eq!(found, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csharp() {
|
||||
let text = binding("csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs");
|
||||
let found = assignments(section(&text, "public enum ErrorCode", "}"));
|
||||
let mut expected = expected(|code| code.name().to_owned());
|
||||
expected.insert(0, "None".into());
|
||||
assert_eq!(found, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn purebasic() {
|
||||
let text = binding("purebasic/BakaShrot_ErrorCodes.pbi");
|
||||
let constants = text
|
||||
.lines()
|
||||
.filter(|line| line.starts_with("#BakaShrot_") && !line.contains("_Max"));
|
||||
let found = assignments(constants);
|
||||
let mut expected = expected(|code| {
|
||||
let kind = if code.is_refusal() {
|
||||
"Refused"
|
||||
} else {
|
||||
"Error"
|
||||
};
|
||||
format!("#BakaShrot_{kind}_{}", code.name())
|
||||
});
|
||||
expected.insert(0, "#BakaShrot_Error_None".into());
|
||||
assert_eq!(found, expected);
|
||||
// Each named by BakaShrot_ErrorName().
|
||||
for code in ErrorCode::ALL {
|
||||
let case = format!("ProcedureReturn \"{}\"", code.name());
|
||||
assert!(text.contains(&case), "BakaShrot_ErrorName() lacks {code}");
|
||||
}
|
||||
}
|
||||
@@ -434,6 +434,45 @@ fn exports() {
|
||||
assert_eq!(BakaShrot_FreeClient(client), 1);
|
||||
}
|
||||
|
||||
/// The answer timeout: set before connecting or while connected, kept
|
||||
/// across connections; past it, `ConnectionLost` and the connection closed.
|
||||
#[test]
|
||||
fn answer_timeouts() {
|
||||
let running = common::Running::start("answer-timeouts");
|
||||
running.issue("kitchen", &["home"]);
|
||||
let client = BakaShrot_CreateClient();
|
||||
assert_eq!(BakaShrot_GetAnswerTimeout(client), 30_000);
|
||||
for refused in [0, -1, i64::MIN] {
|
||||
assert_eq!(BakaShrot_SetAnswerTimeout(client, refused), 0);
|
||||
assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
|
||||
}
|
||||
assert_eq!(BakaShrot_SetAnswerTimeout(client, 60_000), 1);
|
||||
assert_eq!(BakaShrot_FreeClient(client), 1);
|
||||
|
||||
let client = connected(&running, "kitchen");
|
||||
assert_eq!(BakaShrot_SetAnswerTimeout(client, 300), 1);
|
||||
assert_eq!(BakaShrot_GetAnswerTimeout(client), 300);
|
||||
let forever =
|
||||
a("WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n");
|
||||
let started = std::time::Instant::now();
|
||||
unsafe {
|
||||
assert_eq!(BakaShrot_QueryA(client, forever.as_ptr()), 0);
|
||||
assert_eq!(error(client).0, code(ErrorCode::ConnectionLost));
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5));
|
||||
assert_eq!(BakaShrot_IsConnected(client), 0);
|
||||
// Connected again: the timeout kept.
|
||||
let host = a("127.0.0.1");
|
||||
assert_eq!(
|
||||
BakaShrot_ConnectA(client, host.as_ptr(), i32::from(running.port)),
|
||||
1
|
||||
);
|
||||
assert_eq!(BakaShrot_GetAnswerTimeout(client), 300);
|
||||
assert_eq!(BakaShrot_QueryA(client, forever.as_ptr()), 0);
|
||||
assert_eq!(error(client).0, code(ErrorCode::ConnectionLost));
|
||||
}
|
||||
assert_eq!(BakaShrot_FreeClient(client), 1);
|
||||
}
|
||||
|
||||
/// A new client, connected as `name` (its certificate and key in files).
|
||||
fn connected(running: &common::Running, name: &str) -> i64 {
|
||||
let client = BakaShrot_CreateClient();
|
||||
@@ -476,6 +515,8 @@ fn clients() {
|
||||
assert!(why.contains("no client 99"), "{why}");
|
||||
assert_eq!(BakaShrot_IsConnected(99), 0);
|
||||
assert_eq!(BakaShrot_Ping(99), 0);
|
||||
assert_eq!(BakaShrot_SetAnswerTimeout(99, 1000), 0);
|
||||
assert_eq!(BakaShrot_GetAnswerTimeout(99), -1);
|
||||
assert_eq!(BakaShrot_GetMessageId(-5), 0);
|
||||
assert_eq!(get_w(99, BakaShrot_GetMessageDataW), "");
|
||||
assert_eq!(BakaShrot_FreeClient(99), 0);
|
||||
|
||||
@@ -28,13 +28,13 @@
|
||||
use aws_lc_rs::digest;
|
||||
use bakashrot_pki::{Revocations, tls};
|
||||
use bakashrot_proto::limits::{
|
||||
ALPN, ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGE_SIZE,
|
||||
MAX_MESSAGES_PER_PACKET, MAX_PACKET_SIZE,
|
||||
ALPN, ATTACHMENT_PART_SIZE, KEEPALIVE_SECS, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID,
|
||||
MAX_MESSAGE_SIZE, MAX_MESSAGES_PER_PACKET, MAX_PACKET_SIZE,
|
||||
};
|
||||
use bakashrot_proto::names::{is_valid_name, is_valid_name_or_pattern};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, GetAttachment, GetMessages, ListNames, Messages, NameKind,
|
||||
NamesList, Ping, PushMessage, Query,
|
||||
Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed,
|
||||
Messages, NameKind, NamesList, Ping, Pong, PushMessage, Query, QueryResult, Welcome,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use rustls::{ClientConnection, StreamOwned};
|
||||
@@ -104,6 +104,16 @@ impl std::error::Error for Error {}
|
||||
/// A result of this crate.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// What [`Client::is_open`] found waiting.
|
||||
enum Look {
|
||||
/// Nothing, or only what TLS keeps for itself.
|
||||
Open,
|
||||
/// The server closed it: the socket's end, or TLS's close_notify.
|
||||
Gone,
|
||||
/// Data sent unasked, or a broken TLS stream.
|
||||
OutOfStep,
|
||||
}
|
||||
|
||||
/// A connection to a server.
|
||||
pub struct Client {
|
||||
stream: StreamOwned<ClientConnection, TcpStream>,
|
||||
@@ -181,13 +191,8 @@ impl Client {
|
||||
answer_timeout: CONNECT_TIMEOUT,
|
||||
closed: false,
|
||||
};
|
||||
match client.answer()? {
|
||||
Packet::Welcome(welcome) => {
|
||||
client.server = welcome.server;
|
||||
client.node = welcome.node;
|
||||
}
|
||||
other => return Err(client.unexpected(&other)),
|
||||
}
|
||||
let welcome: Welcome = client.answer()?;
|
||||
(client.server, client.node) = (welcome.server, welcome.node);
|
||||
client.set_answer_timeout(ANSWER_TIMEOUT)?;
|
||||
Ok(client)
|
||||
}
|
||||
@@ -226,23 +231,60 @@ impl Client {
|
||||
}
|
||||
|
||||
/// Whether the connection still looks open: the server hasn't closed
|
||||
/// it (after its idle timeout, say). Only a request tells for sure.
|
||||
pub fn is_open(&self) -> bool {
|
||||
/// it (after its idle timeout, say, or with TLS's close_notify). Only a
|
||||
/// request tells for sure.
|
||||
///
|
||||
/// It reads what's waiting without blocking, through TLS: what TLS
|
||||
/// keeps for itself (session tickets) leaves it open, a close or a
|
||||
/// broken stream doesn't. Data the server sent unasked leaves the
|
||||
/// connection out of step: closed then, as [`Client::is_closed`] says.
|
||||
pub fn is_open(&mut self) -> bool {
|
||||
if self.closed {
|
||||
return false;
|
||||
}
|
||||
let tcp = &self.stream.sock;
|
||||
if tcp.set_nonblocking(true).is_err() {
|
||||
if self.stream.sock.set_nonblocking(true).is_err() {
|
||||
return false;
|
||||
}
|
||||
let open = match tcp.peek(&mut [0]) {
|
||||
Ok(read) => read > 0,
|
||||
Err(error) => error.kind() == io::ErrorKind::WouldBlock,
|
||||
};
|
||||
let looked = self.look();
|
||||
// Blocking again whatever it found: the next request waits for
|
||||
// its answer.
|
||||
let blocking = tcp.set_nonblocking(false).is_ok();
|
||||
open && blocking
|
||||
let blocking = self.stream.sock.set_nonblocking(false).is_ok();
|
||||
match looked {
|
||||
Look::Open => blocking,
|
||||
Look::Gone => false,
|
||||
Look::OutOfStep => {
|
||||
self.close();
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What's waiting on the (non-blocking) socket, read into TLS, which
|
||||
/// keeps what it read for the next request.
|
||||
fn look(&mut self) -> Look {
|
||||
let StreamOwned { conn, sock } = &mut self.stream;
|
||||
loop {
|
||||
// What TLS holds already, then what it reads below.
|
||||
let state = match conn.process_new_packets() {
|
||||
Ok(state) => state,
|
||||
Err(_) => return Look::OutOfStep,
|
||||
};
|
||||
if state.peer_has_closed() {
|
||||
return Look::Gone;
|
||||
}
|
||||
// Nothing is sent unasked: never an answer's start.
|
||||
if state.plaintext_bytes_to_read() > 0 || !conn.wants_read() {
|
||||
return Look::OutOfStep;
|
||||
}
|
||||
match conn.read_tls(sock) {
|
||||
// The socket's end, without close_notify.
|
||||
Ok(0) => return Look::Gone,
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == io::ErrorKind::WouldBlock => return Look::Open,
|
||||
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
|
||||
Err(_) => return Look::Gone,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a failure closed the connection: every request fails with
|
||||
@@ -256,10 +298,23 @@ impl Client {
|
||||
/// `IDLE_TIMEOUT_SECS` (5 min). An app waiting longer than that
|
||||
/// between requests calls this every `KEEPALIVE_SECS` (1 min) or so.
|
||||
pub fn ping(&mut self) -> Result<()> {
|
||||
match self.request(Ping {}.into())? {
|
||||
Packet::Pong(_) => Ok(()),
|
||||
other => Err(self.unexpected(&other)),
|
||||
let Pong {} = self.request(Ping {}.into())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Waits `duration`, pinging every `KEEPALIVE_SECS` meanwhile
|
||||
/// ([`Client::ping`]): for an app waiting longer than the server's idle
|
||||
/// timeout between requests. A failed ping ends it.
|
||||
pub fn wait(&mut self, duration: Duration) -> Result<()> {
|
||||
let keepalive = Duration::from_secs(KEEPALIVE_SECS);
|
||||
let mut left = duration;
|
||||
while left > keepalive {
|
||||
std::thread::sleep(keepalive);
|
||||
left -= keepalive;
|
||||
self.ping()?;
|
||||
}
|
||||
std::thread::sleep(left);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pushes a message to `topic`, as this client's node: its id.
|
||||
@@ -271,10 +326,8 @@ impl Client {
|
||||
data: data.to_owned(),
|
||||
attachment: None,
|
||||
};
|
||||
match self.request(push.into())? {
|
||||
Packet::MessagePushed(pushed) => Ok(pushed.message_id),
|
||||
other => Err(self.unexpected(&other)),
|
||||
}
|
||||
let pushed: MessagePushed = self.request(push.into())?;
|
||||
Ok(pushed.message_id)
|
||||
}
|
||||
|
||||
/// Pushes a message with an attachment read from `source` (a `File`, a
|
||||
@@ -318,10 +371,7 @@ impl Client {
|
||||
data: data.to_owned(),
|
||||
attachment: Some(attachment.clone()),
|
||||
};
|
||||
match self.request(push.into())? {
|
||||
Packet::Continue(_) => {}
|
||||
other => return Err(self.unexpected(&other)),
|
||||
}
|
||||
let Continue {} = self.request(push.into())?;
|
||||
for part in 0..attachment.part_count() {
|
||||
let part = &mut buffer[..attachment.part_len(part) as usize];
|
||||
if let Err(error) = source.read_exact(part) {
|
||||
@@ -333,10 +383,8 @@ impl Client {
|
||||
}))?;
|
||||
}
|
||||
self.flush()?;
|
||||
match self.answer()? {
|
||||
Packet::MessagePushed(pushed) => Ok(pushed.message_id),
|
||||
other => Err(self.unexpected(&other)),
|
||||
}
|
||||
let pushed: MessagePushed = self.answer()?;
|
||||
Ok(pushed.message_id)
|
||||
}
|
||||
|
||||
/// Writes a message's attachment into `out`, a part at a time, checked
|
||||
@@ -360,10 +408,7 @@ impl Client {
|
||||
message_id,
|
||||
from_part: 0,
|
||||
};
|
||||
let attachment = match self.request(get.into())? {
|
||||
Packet::Attachment(attachment) => attachment,
|
||||
other => return Err(self.unexpected(&other)),
|
||||
};
|
||||
let attachment: Attachment = self.request(get.into())?;
|
||||
let mut sha256 = digest::Context::new(&digest::SHA256);
|
||||
// A failing `out`: the parts are still all read, the connection
|
||||
// stays usable.
|
||||
@@ -371,11 +416,8 @@ impl Client {
|
||||
for part in 0..attachment.part_count() {
|
||||
// Parts come without a request each: anything else, a refusal
|
||||
// too, leaves the rest of them unread.
|
||||
let data = match self.answer() {
|
||||
Ok(Packet::AttachmentPart(part)) => part.data,
|
||||
Ok(other) => return Err(self.unexpected(&other)),
|
||||
Err(error) => return Err(self.out_of_step(error)),
|
||||
};
|
||||
let read: Result<AttachmentPart> = self.answer();
|
||||
let data = read.map_err(|error| self.out_of_step(error))?.data;
|
||||
let expected = attachment.part_len(part);
|
||||
if data.len() as u64 != expected {
|
||||
return Err(self.out_of_step(Error::new(
|
||||
@@ -451,10 +493,7 @@ impl Client {
|
||||
after,
|
||||
limit,
|
||||
};
|
||||
match self.request(get.into())? {
|
||||
Packet::Messages(messages) => Ok(messages),
|
||||
other => Err(self.unexpected(&other)),
|
||||
}
|
||||
self.request(get.into())
|
||||
}
|
||||
|
||||
/// The topics with messages that this client may push to or read, or
|
||||
@@ -481,10 +520,7 @@ impl Client {
|
||||
topics: topics.map(str::to_owned),
|
||||
nodes: nodes.map(str::to_owned),
|
||||
};
|
||||
match self.request(list.into())? {
|
||||
Packet::NamesList(names) => Ok(names),
|
||||
other => Err(self.unexpected(&other)),
|
||||
}
|
||||
self.request(list.into())
|
||||
}
|
||||
|
||||
/// Runs read-only SQL: `{"columns":[...],"rows":[[...],...]}`, every
|
||||
@@ -494,10 +530,8 @@ impl Client {
|
||||
let query = Query {
|
||||
sql: sql.to_owned(),
|
||||
};
|
||||
match self.request(query.into())? {
|
||||
Packet::QueryResult(result) => Ok(result.json),
|
||||
other => Err(self.unexpected(&other)),
|
||||
}
|
||||
let result: QueryResult = self.request(query.into())?;
|
||||
Ok(result.json)
|
||||
}
|
||||
|
||||
/// Closes the connection for good: every request fails then
|
||||
@@ -544,11 +578,6 @@ impl Client {
|
||||
self.out_of_step(error)
|
||||
}
|
||||
|
||||
/// An answer that isn't the request's: `ProtocolError`, closed.
|
||||
fn unexpected(&mut self, packet: &Packet) -> Error {
|
||||
self.out_of_step(unexpected(packet))
|
||||
}
|
||||
|
||||
/// Writes a packet's frame (not flushed).
|
||||
fn send(&mut self, packet: &Packet) -> Result<()> {
|
||||
self.check_open()?;
|
||||
@@ -564,16 +593,30 @@ impl Client {
|
||||
flushed.map_err(|error| self.io_failed(error))
|
||||
}
|
||||
|
||||
/// Sends a request, reads its answer.
|
||||
fn request(&mut self, packet: Packet) -> Result<Packet> {
|
||||
/// Sends a request, reads its answer ([`Client::answer`]).
|
||||
fn request<T: TryFrom<Packet, Error = Packet>>(&mut self, packet: Packet) -> Result<T> {
|
||||
self.send(&packet)?;
|
||||
self.flush()?;
|
||||
self.answer()
|
||||
}
|
||||
|
||||
/// Reads the server's next packet, a `T`: a refusal is an error (the
|
||||
/// connection kept), any other packet closes it (`ProtocolError`, the
|
||||
/// answer isn't the request's), as anything else wrong does.
|
||||
fn answer<T: TryFrom<Packet, Error = Packet>>(&mut self) -> Result<T> {
|
||||
let packet = self.receive()?;
|
||||
T::try_from(packet).map_err(|other| {
|
||||
let error = Error::new(
|
||||
ErrorCode::ProtocolError,
|
||||
format!("the server answered {}", other.packet_type().name()),
|
||||
);
|
||||
self.out_of_step(error)
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads the server's next packet: a refusal is an error (the
|
||||
/// connection kept), anything else wrong closes it.
|
||||
fn answer(&mut self) -> Result<Packet> {
|
||||
fn receive(&mut self) -> Result<Packet> {
|
||||
self.check_open()?;
|
||||
let bytes = match frame::read(&mut self.stream, MAX_PACKET_SIZE) {
|
||||
Ok(Some(bytes)) => bytes,
|
||||
@@ -662,10 +705,3 @@ fn check_size(text: &str, what: &str) -> Result<()> {
|
||||
fn file_error(error: io::Error) -> Error {
|
||||
Error::new(ErrorCode::FileError, format!("the attachment: {error}"))
|
||||
}
|
||||
|
||||
fn unexpected(packet: &Packet) -> Error {
|
||||
Error::new(
|
||||
ErrorCode::ProtocolError,
|
||||
format!("the server answered {}", packet.packet_type().name()),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -21,12 +21,15 @@ use std::time::Duration;
|
||||
type Stream = StreamOwned<ServerConnection, TcpStream>;
|
||||
|
||||
/// A fake server for one connection, running its script once the client
|
||||
/// is welcomed, and the client's certificates.
|
||||
/// is connected ([`Fake::connect`] returned: what the script sends is
|
||||
/// never read while connecting), and the client's certificates.
|
||||
struct Fake {
|
||||
address: String,
|
||||
ca: String,
|
||||
client: Issued,
|
||||
script: Option<JoinHandle<()>>,
|
||||
/// Lets the script run.
|
||||
connected: mpsc::Sender<()>,
|
||||
script: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl Fake {
|
||||
@@ -49,6 +52,7 @@ impl Fake {
|
||||
.unwrap();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap().to_string();
|
||||
let (connected, wait_connected) = mpsc::channel();
|
||||
let script = thread::spawn(move || {
|
||||
let (tcp, _) = listener.accept().unwrap();
|
||||
tcp.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
|
||||
@@ -65,18 +69,21 @@ impl Fake {
|
||||
node: "kitchen".into(),
|
||||
},
|
||||
);
|
||||
// Gone without connecting: run all the same.
|
||||
let _ = wait_connected.recv();
|
||||
script(&mut stream);
|
||||
});
|
||||
Fake {
|
||||
address,
|
||||
ca: ca.certificate,
|
||||
client,
|
||||
script: Some(script),
|
||||
connected,
|
||||
script,
|
||||
}
|
||||
}
|
||||
|
||||
fn connect(&self) -> Client {
|
||||
Client::connect(
|
||||
let client = Client::connect(
|
||||
&self.address,
|
||||
&Settings {
|
||||
ca: &self.ca,
|
||||
@@ -85,12 +92,15 @@ impl Fake {
|
||||
crl: None,
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let _ = self.connected.send(());
|
||||
client
|
||||
}
|
||||
|
||||
/// Waits for the script to end (its asserts included).
|
||||
fn finish(mut self) {
|
||||
self.script.take().unwrap().join().unwrap();
|
||||
fn finish(self) {
|
||||
drop(self.connected);
|
||||
self.script.join().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,20 +116,24 @@ fn answer(stream: &mut Stream, packet: impl Into<Packet>) {
|
||||
}
|
||||
|
||||
/// Whether the client closed the connection without sending anything
|
||||
/// more: what the script reports after its answer.
|
||||
/// more: what a script asserts after its answer.
|
||||
fn nothing_more(stream: &mut Stream) -> bool {
|
||||
request(stream).is_none()
|
||||
}
|
||||
|
||||
/// The error `result` failed with, of `code`.
|
||||
#[track_caller]
|
||||
fn fails(result: Result<impl std::fmt::Debug, bakashrot_client::Error>, code: ErrorCode) {
|
||||
fn fails(
|
||||
result: Result<impl std::fmt::Debug, bakashrot_client::Error>,
|
||||
code: ErrorCode,
|
||||
) -> bakashrot_client::Error {
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(error.code(), code.code(), "{error}");
|
||||
error
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_answer_is_never_taken_for_the_next_request() {
|
||||
let (report, reported) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
assert!(matches!(request(stream), Some(Packet::PushMessage(_))));
|
||||
thread::sleep(Duration::from_millis(600));
|
||||
@@ -129,14 +143,13 @@ fn a_late_answer_is_never_taken_for_the_next_request() {
|
||||
&Packet::from(MessagePushed { message_id: 1 }).encode(),
|
||||
);
|
||||
let _ = stream.flush();
|
||||
report.send(nothing_more(stream)).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
client
|
||||
.set_answer_timeout(Duration::from_millis(200))
|
||||
.unwrap();
|
||||
let error = client.push("logs", "{}").unwrap_err();
|
||||
assert_eq!(error.code(), ErrorCode::ConnectionLost.code(), "{error}");
|
||||
let error = fails(client.push("logs", "{}"), ErrorCode::ConnectionLost);
|
||||
assert!(
|
||||
error.message().contains("no answer within 200ms"),
|
||||
"{error}"
|
||||
@@ -147,40 +160,35 @@ fn a_late_answer_is_never_taken_for_the_next_request() {
|
||||
thread::sleep(Duration::from_millis(700));
|
||||
fails(client.push("logs", "{}"), ErrorCode::NotConnected);
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
assert!(reported.recv().unwrap(), "the client sent something more");
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_answer_closes() {
|
||||
let (report, reported) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
assert!(matches!(request(stream), Some(Packet::PushMessage(_))));
|
||||
answer(stream, Pong {});
|
||||
report.send(nothing_more(stream)).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
fails(client.push("logs", "{}"), ErrorCode::ProtocolError);
|
||||
assert!(!client.is_open() && client.is_closed());
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
assert!(reported.recv().unwrap());
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_answer_closes() {
|
||||
let (report, reported) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
assert!(matches!(request(stream), Some(Packet::Ping(_))));
|
||||
// 0xc1 is never MessagePack.
|
||||
frame::write(stream, &[0xc1]).unwrap();
|
||||
stream.flush().unwrap();
|
||||
report.send(nothing_more(stream)).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
fails(client.ping(), ErrorCode::ProtocolError);
|
||||
fails(client.query("SELECT 1"), ErrorCode::NotConnected);
|
||||
assert!(reported.recv().unwrap());
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
@@ -217,8 +225,7 @@ fn a_refusal_keeps_the_connection() {
|
||||
answer(stream, MessagePushed { message_id: 7 });
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
let error = client.push("logs", "{}").unwrap_err();
|
||||
assert_eq!(error.code(), ErrorCode::NotAllowed.code());
|
||||
let error = fails(client.push("logs", "{}"), ErrorCode::NotAllowed);
|
||||
assert_eq!(error.message(), "not this topic");
|
||||
assert!(client.is_open() && !client.is_closed());
|
||||
client.ping().unwrap();
|
||||
@@ -287,19 +294,107 @@ fn a_connection_the_server_closed() {
|
||||
let mut client = fake.connect();
|
||||
let address = fake.address.clone();
|
||||
fake.finish();
|
||||
let mut waited = 0;
|
||||
while client.is_open() && waited < 50 {
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
waited += 1;
|
||||
}
|
||||
assert!(!client.is_open(), "{address}: still open");
|
||||
assert!(gone(&mut client), "{address}: still open");
|
||||
assert!(!client.is_open() && !client.is_closed());
|
||||
fails(client.ping(), ErrorCode::ConnectionLost);
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
}
|
||||
|
||||
/// Whether `is_open()` says closed within a second (what the fake sent
|
||||
/// on its way).
|
||||
fn gone(client: &mut Client) -> bool {
|
||||
for _ in 0..50 {
|
||||
if !client.is_open() {
|
||||
return true;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Sends what TLS holds, without waiting for anything back.
|
||||
fn send_tls(stream: &mut Stream) {
|
||||
while stream.conn.wants_write() {
|
||||
stream.conn.write_tls(&mut stream.sock).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS's close_notify, the socket kept open (as a proxy closing politely
|
||||
/// might): `is_open()` notices it from TLS alone, and keeps saying so.
|
||||
/// The next request fails as lost, those after as not connected.
|
||||
#[test]
|
||||
fn a_close_notify_is_noticed() {
|
||||
let (done, wait_done) = mpsc::channel::<()>();
|
||||
let fake = Fake::start(move |stream| {
|
||||
stream.conn.send_close_notify();
|
||||
send_tls(stream);
|
||||
// The socket open until the client looked.
|
||||
let _ = wait_done.recv();
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
assert!(gone(&mut client), "still open after close_notify");
|
||||
assert!(!client.is_open() && !client.is_open() && !client.is_closed());
|
||||
fails(client.ping(), ErrorCode::ConnectionLost);
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
done.send(()).unwrap();
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
/// An answer to no request: the connection is out of step, so
|
||||
/// `is_open()` closes it, and nothing more is sent.
|
||||
#[test]
|
||||
fn data_sent_unasked_closes() {
|
||||
let fake = Fake::start(move |stream| {
|
||||
answer(stream, Pong {});
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
assert!(gone(&mut client), "still open with data sent unasked");
|
||||
assert!(client.is_closed());
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
/// Bytes that aren't TLS (a record of no known type): broken, closed.
|
||||
#[test]
|
||||
fn a_broken_tls_stream_closes() {
|
||||
let fake = Fake::start(move |stream| {
|
||||
stream.sock.write_all(&[0x99, 3, 3, 0, 1, 0]).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
assert!(gone(&mut client), "still open with a broken TLS stream");
|
||||
assert!(client.is_closed());
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
/// What TLS sends for itself (a key update here, like the session
|
||||
/// tickets after the handshake) isn't data: `is_open()` reads it, stays
|
||||
/// open, and the next request works, under the new keys.
|
||||
#[test]
|
||||
fn tls_records_of_its_own_keep_it_open() {
|
||||
let (sent, wait_sent) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
stream.conn.refresh_traffic_keys().unwrap();
|
||||
send_tls(stream);
|
||||
sent.send(()).unwrap();
|
||||
assert!(matches!(request(stream), Some(Packet::Ping(_))));
|
||||
answer(stream, Pong {});
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
wait_sent.recv().unwrap();
|
||||
// The record on its way over loopback.
|
||||
thread::sleep(Duration::from_millis(200));
|
||||
for _ in 0..3 {
|
||||
assert!(client.is_open() && !client.is_closed());
|
||||
}
|
||||
client.ping().unwrap();
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_part_of_the_wrong_size_closes() {
|
||||
let (report, reported) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
assert!(matches!(request(stream), Some(Packet::GetAttachment(_))));
|
||||
answer(
|
||||
@@ -310,7 +405,7 @@ fn a_part_of_the_wrong_size_closes() {
|
||||
},
|
||||
);
|
||||
answer(stream, AttachmentPart { data: vec![1; 5] });
|
||||
report.send(nothing_more(stream)).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
let mut out = Vec::new();
|
||||
@@ -319,7 +414,6 @@ fn a_part_of_the_wrong_size_closes() {
|
||||
ErrorCode::ProtocolError,
|
||||
);
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
assert!(reported.recv().unwrap());
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
@@ -327,7 +421,6 @@ fn a_part_of_the_wrong_size_closes() {
|
||||
/// the next request's answers.
|
||||
#[test]
|
||||
fn a_refusal_among_the_parts_closes() {
|
||||
let (report, reported) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
assert!(matches!(request(stream), Some(Packet::GetAttachment(_))));
|
||||
answer(
|
||||
@@ -347,7 +440,7 @@ fn a_refusal_among_the_parts_closes() {
|
||||
stream,
|
||||
RequestRefused::new(ErrorCode::ServerError, "a disk"),
|
||||
);
|
||||
report.send(nothing_more(stream)).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
let mut out = Vec::new();
|
||||
@@ -356,7 +449,6 @@ fn a_refusal_among_the_parts_closes() {
|
||||
ErrorCode::ServerError,
|
||||
);
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
assert!(reported.recv().unwrap());
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
@@ -386,23 +478,21 @@ impl Seek for FailingSecondTime {
|
||||
/// for parts that won't come, the connection closes.
|
||||
#[test]
|
||||
fn a_source_failing_mid_upload_closes() {
|
||||
let (report, reported) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
assert!(matches!(request(stream), Some(Packet::PushMessage(_))));
|
||||
answer(stream, Continue {});
|
||||
report.send(nothing_more(stream)).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
let mut source = FailingSecondTime {
|
||||
data: Cursor::new(vec![7; 100]),
|
||||
rewinds: 0,
|
||||
};
|
||||
let error = client
|
||||
.push_with_attachment("logs", "{}", &mut source)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.code(), ErrorCode::FileError.code(), "{error}");
|
||||
fails(
|
||||
client.push_with_attachment("logs", "{}", &mut source),
|
||||
ErrorCode::FileError,
|
||||
);
|
||||
assert!(!client.is_open() && client.is_closed());
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
assert!(reported.recv().unwrap());
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ synchronous = "full"
|
||||
max_attachment_size = "1G" # bytes, or K M G T (1024-based); 0: none
|
||||
retention_interval = "1m" # how often old messages are deleted
|
||||
idle_database_connections = 8 # kept open once idle, for reads and as many for queries; closed after 1 min unused
|
||||
query_time_limit = "20s" # a client's query stopped (refused) past it; keep it under the clients' answer timeout (30 s)
|
||||
|
||||
# How long each topic's messages are kept, from when they were first
|
||||
# pushed: 100 years ("36500d") at most, or "forever". A topic takes its
|
||||
|
||||
@@ -108,6 +108,14 @@ pub struct Server {
|
||||
deserialize_with = "values::idle_connections"
|
||||
)]
|
||||
pub idle_database_connections: usize,
|
||||
/// How long a client's query may run before it's stopped and refused
|
||||
/// (`QueryTimedOut`); 20 s by default. Under the clients' answer timeout
|
||||
/// (30 s by default), so they get the refusal rather than give up.
|
||||
#[serde(
|
||||
default = "defaults::query_time_limit",
|
||||
deserialize_with = "values::duration"
|
||||
)]
|
||||
pub query_time_limit: Duration,
|
||||
}
|
||||
|
||||
/// How hard the database makes sure a push is on disk before answering it
|
||||
@@ -267,6 +275,9 @@ mod defaults {
|
||||
pub(crate) fn idle_database_connections() -> usize {
|
||||
8
|
||||
}
|
||||
pub(crate) fn query_time_limit() -> Duration {
|
||||
Duration::from_secs(20)
|
||||
}
|
||||
}
|
||||
|
||||
/// `[roles.*]`: each section's name is its role's, none twice.
|
||||
|
||||
@@ -60,6 +60,7 @@ fn defaults() {
|
||||
assert_eq!(server.max_attachment_size, 1 << 30);
|
||||
assert_eq!(server.retention_interval, Duration::from_secs(60));
|
||||
assert_eq!(server.idle_database_connections, 8);
|
||||
assert_eq!(server.query_time_limit, Duration::from_secs(20));
|
||||
assert_eq!(config.retention.age("logs"), None);
|
||||
assert_eq!(config.replication.retry_delay, Duration::from_secs(10));
|
||||
assert_eq!(config.replication.sync_interval, Duration::from_secs(5));
|
||||
@@ -77,6 +78,7 @@ synchronous = "NORMAL"
|
||||
max_attachment_size = 0
|
||||
retention_interval = "1h30m"
|
||||
idle_database_connections = 0
|
||||
query_time_limit = "2m"
|
||||
|
||||
[replication]
|
||||
push_to = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"]
|
||||
@@ -92,6 +94,7 @@ batch_size = 10000
|
||||
assert_eq!(config.server.max_attachment_size, 0);
|
||||
assert_eq!(config.server.retention_interval, Duration::from_secs(5400));
|
||||
assert_eq!(config.server.idle_database_connections, 0);
|
||||
assert_eq!(config.server.query_time_limit, Duration::from_secs(120));
|
||||
assert_eq!(config.replication.push_to.len(), 3);
|
||||
assert_eq!(config.replication.accept_from[2], "fd00::4");
|
||||
assert_eq!(config.replication.retry_delay, Duration::from_secs(60));
|
||||
@@ -306,6 +309,10 @@ fn refusals() {
|
||||
&with("idle_database_connections = -1\n"),
|
||||
"invalid value: integer `-1`",
|
||||
),
|
||||
(
|
||||
&with("query_time_limit = \"0s\"\n"),
|
||||
"'0s' isn't a duration",
|
||||
),
|
||||
// [retention]
|
||||
(
|
||||
&with("[retention]\nlogs = \"30\"\n"),
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
//! What to do about each:
|
||||
//! - reconnect, then retry: `NotConnected`, `ConnectFailed`,
|
||||
//! `ConnectionLost`, `ProtocolError` (the connection is closed);
|
||||
//! - retry later: `NotReady`, `ServerError`;
|
||||
//! - retry later: `NotReady`, `ServerError`, `QueryTimedOut` (or narrow
|
||||
//! the query);
|
||||
//! - fix the configuration: `AuthRejected`, `ServerNotVerified`,
|
||||
//! `NotAllowed`, `UnknownName`;
|
||||
//! - update one end: `VersionMismatch`;
|
||||
@@ -74,6 +75,7 @@ error_codes! {
|
||||
DataMismatch = 8, "An uploaded attachment that doesn't match its SHA-256: dropped.";
|
||||
QueryFailed = 9, "The SQL of a query failed (its error in the reason).";
|
||||
ServerError = 10, "The server couldn't store or read something: its database failed.";
|
||||
QueryTimedOut = 11, "A query ran past the server's time limit (query_time_limit) and was stopped: narrow it, or retry when the server is less busy.";
|
||||
|
||||
// The client's own.
|
||||
NotConnected = 100, "Not connected: never, or the connection was closed or lost before.";
|
||||
@@ -140,6 +142,7 @@ mod tests {
|
||||
(8, "DataMismatch"),
|
||||
(9, "QueryFailed"),
|
||||
(10, "ServerError"),
|
||||
(11, "QueryTimedOut"),
|
||||
(100, "NotConnected"),
|
||||
(101, "ConnectFailed"),
|
||||
(102, "AuthRejected"),
|
||||
|
||||
@@ -144,6 +144,17 @@ macro_rules! packets {
|
||||
Packet::$name(body)
|
||||
}
|
||||
}
|
||||
|
||||
/// The body of a packet of this type, or the packet back.
|
||||
impl TryFrom<Packet> for $name {
|
||||
type Error = Packet;
|
||||
fn try_from(packet: Packet) -> Result<$name, Packet> {
|
||||
match packet {
|
||||
Packet::$name(body) => Ok(body),
|
||||
other => Err(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
)*
|
||||
|
||||
impl Packet {
|
||||
|
||||
@@ -57,6 +57,16 @@ pub struct Head {
|
||||
pub last_id: u64,
|
||||
}
|
||||
|
||||
impl From<&Head> for Pair {
|
||||
/// Its pair: to ask the page after it.
|
||||
fn from(head: &Head) -> Pair {
|
||||
Pair {
|
||||
topic: head.topic.clone(),
|
||||
node: head.node.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An attachment the server lacks, and where to go on from.
|
||||
///
|
||||
/// `[topic, node, message_id, next_part]`
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -7,7 +7,7 @@ mod cert;
|
||||
|
||||
use bakashrot_client::{Client, Error, Settings};
|
||||
use bakashrot_proto::error::{code_name, is_refusal_code};
|
||||
use bakashrot_proto::limits::{KEEPALIVE_SECS, MAX_MESSAGES_PER_PACKET};
|
||||
use bakashrot_proto::limits::MAX_MESSAGES_PER_PACKET;
|
||||
use bakashrot_proto::packets::{MessageEntry, NameKind};
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
use serde::Deserialize;
|
||||
@@ -266,7 +266,10 @@ fn run(config: &Path, command: Command) -> Result<(), String> {
|
||||
break;
|
||||
}
|
||||
if !batch.more {
|
||||
wait(&mut client, Duration::from_millis(interval))?;
|
||||
// Pinging meanwhile: `--interval` goes up to 1 h.
|
||||
client
|
||||
.wait(Duration::from_millis(interval))
|
||||
.map_err(failed)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -317,22 +320,6 @@ fn run(config: &Path, command: Command) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Waits `duration`, pinging every `KEEPALIVE_SECS` meanwhile: the server
|
||||
/// closes a connection silent for 5 min, and `--interval` goes up to 1 h.
|
||||
fn wait(client: &mut Client, duration: Duration) -> Result<(), String> {
|
||||
let keepalive = Duration::from_secs(KEEPALIVE_SECS);
|
||||
let mut left = duration;
|
||||
loop {
|
||||
let step = left.min(keepalive);
|
||||
std::thread::sleep(step);
|
||||
left -= step;
|
||||
if left.is_zero() {
|
||||
return Ok(());
|
||||
}
|
||||
client.ping().map_err(failed)?;
|
||||
}
|
||||
}
|
||||
|
||||
/// A topic and node's latest message, if any.
|
||||
fn latest(client: &mut Client, topic: &str, node: &str) -> Result<Option<MessageEntry>, String> {
|
||||
let latest = client.get_messages(topic, node, None, 1).map_err(failed)?;
|
||||
|
||||
Reference in New Issue
Block a user