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:
@@ -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()),
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user