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