1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Kept attachments whose read-back failed, Closed the Rust client's connection when out of step

- Replication: a peer's DataMismatch has the sender read its own copy
  back. Dropped as damaged only when read whole and not matching, or a
  part missing; a read-back that failed otherwise (a busy database, a
  connection not opened) dropped it too, the only copy if this server
  was its origin: now kept and warned about (push_to.rs, judge)
- bakashrot-client: an I/O error, a timeout, an answer that isn't the
  request's or doesn't decode, parts cut short or interrupted, a source
  failing mid-upload close the connection; requests after fail with
  NotConnected without reading, so a late answer is never taken for
  the next request's (a push could return the previous one's id).
  is_closed(), set_answer_timeout() / answer_timeout() (30 s by
  default), is_open() always blocking again
- The DLL forgets a client its connection closed that way, whatever the
  code, so connecting again works
- tests/failures.rs in bakashrot-client: a fake TLS server answering
  late, wrongly, cut short; end_to_end.rs for a revoked certificate and
  a failed upload; docs (client.md, server.md) and revamp.md (step 18)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 23:37:01 +01:00
parent 6fae7e61c9
commit 8ebac633d0
8 changed files with 681 additions and 50 deletions
+5 -1
View File
@@ -124,9 +124,13 @@ 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());
.any(|code| code.code() == error.code())
|| self.client.as_ref().is_some_and(Client::is_closed);
if closed {
self.client = None;
}
+150 -40
View File
@@ -17,6 +17,13 @@
//! ALPN `bakashrot`, both ends' protocol versions, then the server's
//! `Welcome` (`docs/protocol.md`). Errors carry the protocol's codes
//! (`bakashrot_proto::ErrorCode`): a server's refusal keeps its own.
//!
//! **A failure that leaves the connection out of step closes it:** an
//! I/O error, an answer that didn't come in time ([`Client::answer_timeout`]),
//! one that isn't the request's, a part cut short. Every request after
//! fails with `NotConnected` at once, without reading: a late answer is
//! never taken for the next request's. Connect again. A refusal, or an
//! argument refused before sending, keeps it.
use aws_lc_rs::digest;
use bakashrot_pki::{Revocations, tls};
@@ -102,6 +109,11 @@ pub struct Client {
stream: StreamOwned<ClientConnection, TcpStream>,
server: String,
node: String,
/// How long an answer may take: [`ANSWER_TIMEOUT`] until changed.
answer_timeout: Duration,
/// Closed, after a failure that left it out of step: requests fail
/// with `NotConnected`.
closed: bool,
}
impl fmt::Debug for Client {
@@ -166,20 +178,43 @@ impl Client {
stream,
server: String::new(),
node: String::new(),
answer_timeout: CONNECT_TIMEOUT,
closed: false,
};
match client.answer()? {
Packet::Welcome(welcome) => {
client.server = welcome.server;
client.node = welcome.node;
}
other => return Err(unexpected(&other)),
other => return Err(client.unexpected(&other)),
}
let tcp = &client.stream.sock;
tcp.set_read_timeout(Some(ANSWER_TIMEOUT)).map_err(lost)?;
tcp.set_write_timeout(Some(ANSWER_TIMEOUT)).map_err(lost)?;
client.set_answer_timeout(ANSWER_TIMEOUT)?;
Ok(client)
}
/// How long an answer may take before its request fails
/// (`ConnectionLost`, the connection closed): [`ANSWER_TIMEOUT`] (30 s)
/// until changed.
pub fn answer_timeout(&self) -> Duration {
self.answer_timeout
}
/// Sets how long an answer may take, more than 0: longer for a slow
/// query, say. It's also how long sending a packet may take. Past it,
/// the request fails and the connection is closed (a late answer would
/// be taken for the next request's).
pub fn set_answer_timeout(&mut self, timeout: Duration) -> Result<()> {
require(!timeout.is_zero(), || "an answer timeout of 0".to_owned())?;
self.check_open()?;
let tcp = &self.stream.sock;
let set = tcp
.set_read_timeout(Some(timeout))
.and_then(|()| tcp.set_write_timeout(Some(timeout)));
set.map_err(|error| self.io_failed(error))?;
self.answer_timeout = timeout;
Ok(())
}
/// The server's name.
pub fn server(&self) -> &str {
&self.server
@@ -193,6 +228,9 @@ 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 {
if self.closed {
return false;
}
let tcp = &self.stream.sock;
if tcp.set_nonblocking(true).is_err() {
return false;
@@ -201,7 +239,17 @@ impl Client {
Ok(read) => read > 0,
Err(error) => error.kind() == io::ErrorKind::WouldBlock,
};
open && tcp.set_nonblocking(false).is_ok()
// Blocking again whatever it found: the next request waits for
// its answer.
let blocking = tcp.set_nonblocking(false).is_ok();
open && blocking
}
/// Whether a failure closed the connection: every request fails with
/// `NotConnected` now, connect again. Unlike [`Client::is_open`], it
/// doesn't look at the socket.
pub fn is_closed(&self) -> bool {
self.closed
}
/// Keeps the connection open: the server closes one silent for
@@ -210,7 +258,7 @@ impl Client {
pub fn ping(&mut self) -> Result<()> {
match self.request(Ping {}.into())? {
Packet::Pong(_) => Ok(()),
other => Err(unexpected(&other)),
other => Err(self.unexpected(&other)),
}
}
@@ -225,7 +273,7 @@ impl Client {
};
match self.request(push.into())? {
Packet::MessagePushed(pushed) => Ok(pushed.message_id),
other => Err(unexpected(&other)),
other => Err(self.unexpected(&other)),
}
}
@@ -272,23 +320,22 @@ impl Client {
};
match self.request(push.into())? {
Packet::Continue(_) => {}
other => return Err(unexpected(&other)),
other => return Err(self.unexpected(&other)),
}
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) {
self.close();
return Err(file_error(error));
// The server waits for parts that won't come.
return Err(self.out_of_step(file_error(error)));
}
let packet = Packet::from(AttachmentPart {
self.send(&Packet::from(AttachmentPart {
data: part.to_vec(),
});
frame::write(&mut self.stream, &packet.encode()).map_err(lost)?;
}))?;
}
self.stream.flush().map_err(lost)?;
self.flush()?;
match self.answer()? {
Packet::MessagePushed(pushed) => Ok(pushed.message_id),
other => Err(unexpected(&other)),
other => Err(self.unexpected(&other)),
}
}
@@ -315,27 +362,26 @@ impl Client {
};
let attachment = match self.request(get.into())? {
Packet::Attachment(attachment) => attachment,
other => return Err(unexpected(&other)),
other => return Err(self.unexpected(&other)),
};
let mut sha256 = digest::Context::new(&digest::SHA256);
// A failing `out`: the parts are still all read, the connection
// stays usable.
let mut failed = None;
for part in 0..attachment.part_count() {
let data = match self.answer()? {
Packet::AttachmentPart(part) => part.data,
other => {
self.close();
return Err(unexpected(&other));
}
// 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 expected = attachment.part_len(part);
if data.len() as u64 != expected {
self.close();
return Err(Error::new(
return Err(self.out_of_step(Error::new(
ErrorCode::ProtocolError,
format!("part {part}: {} bytes, {expected} expected", data.len()),
));
)));
}
sha256.update(&data);
if failed.is_none() {
@@ -407,7 +453,7 @@ impl Client {
};
match self.request(get.into())? {
Packet::Messages(messages) => Ok(messages),
other => Err(unexpected(&other)),
other => Err(self.unexpected(&other)),
}
}
@@ -437,7 +483,7 @@ impl Client {
};
match self.request(list.into())? {
Packet::NamesList(names) => Ok(names),
other => Err(unexpected(&other)),
other => Err(self.unexpected(&other)),
}
}
@@ -450,40 +496,104 @@ impl Client {
};
match self.request(query.into())? {
Packet::QueryResult(result) => Ok(result.json),
other => Err(unexpected(&other)),
other => Err(self.unexpected(&other)),
}
}
/// Closes the connection: it's out of step (a part not sent, or not
/// as expected). Every request fails then (`ConnectionLost`).
/// Closes the connection for good: every request fails then
/// (`NotConnected`).
fn close(&mut self) {
self.closed = true;
let _ = self.stream.sock.shutdown(Shutdown::Both);
}
/// `NotConnected` once closed.
fn check_open(&self) -> Result<()> {
match self.closed {
false => Ok(()),
true => Err(Error::new(
ErrorCode::NotConnected,
"the connection was closed after an earlier failure: connect again",
)),
}
}
/// `error`, which left the connection out of step: closed.
fn out_of_step(&mut self, error: Error) -> Error {
self.close();
error
}
/// An I/O error on the connection: closed. A timeout says so (its
/// answer may still come, after the next request).
fn io_failed(&mut self, error: io::Error) -> Error {
let timed_out = matches!(
error.kind(),
io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
);
let error = match timed_out {
true => Error::new(
ErrorCode::ConnectionLost,
format!(
"no answer within {:?}: the connection is closed",
self.answer_timeout
),
),
false => lost(error),
};
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()?;
// Refused before anything is written: the connection stays.
let frame = frame::encode(&packet.encode())
.map_err(|error| Error::new(ErrorCode::InvalidArgument, error.to_string()))?;
let written = self.stream.write_all(&frame);
written.map_err(|error| self.io_failed(error))
}
fn flush(&mut self) -> Result<()> {
let flushed = self.stream.flush();
flushed.map_err(|error| self.io_failed(error))
}
/// Sends a request, reads its answer.
fn request(&mut self, packet: Packet) -> Result<Packet> {
frame::write(&mut self.stream, &packet.encode()).map_err(lost)?;
self.stream.flush().map_err(lost)?;
self.send(&packet)?;
self.flush()?;
self.answer()
}
/// Reads the server's next packet: a refusal is an 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> {
let bytes = frame::read(&mut self.stream, MAX_PACKET_SIZE)
.map_err(lost)?
.ok_or_else(|| {
Error::new(
self.check_open()?;
let bytes = match frame::read(&mut self.stream, MAX_PACKET_SIZE) {
Ok(Some(bytes)) => bytes,
Ok(None) => {
return Err(self.out_of_step(Error::new(
ErrorCode::ConnectionLost,
"the server closed the connection",
)
})?;
)));
}
Err(error) => return Err(self.io_failed(error)),
};
match Packet::decode(&bytes) {
Ok(Packet::RequestRefused(refused)) => Err(Error {
code: refused.code,
message: refused.reason,
}),
Ok(packet) => Ok(packet),
Err(error) => Err(Error::new(ErrorCode::ProtocolError, error.to_string())),
Err(error) => {
Err(self.out_of_step(Error::new(ErrorCode::ProtocolError, error.to_string())))
}
}
}
}
+408
View File
@@ -0,0 +1,408 @@
//! What a failure does to the connection, against a fake server that
//! answers late, wrongly or not at all: a refusal keeps it, anything that
//! leaves it out of step closes it, and nothing is read after (a late
//! answer is never taken for the next request's).
use bakashrot_client::{ANSWER_TIMEOUT, Client, Settings};
use bakashrot_pki::{Ca, Identity, Issued, Revocations, Usage, tls};
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_PACKET_SIZE};
use bakashrot_proto::packets::{
Attachment, AttachmentPart, Continue, MessagePushed, Pong, RequestRefused, Welcome,
};
use bakashrot_proto::{ErrorCode, Packet, frame};
use rustls::{ServerConnection, StreamOwned};
use std::io::{self, Cursor, Read, Seek, SeekFrom, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::mpsc;
use std::thread::{self, JoinHandle};
use std::time::Duration;
/// The fake server's end of the connection.
type Stream = StreamOwned<ServerConnection, TcpStream>;
/// A fake server for one connection, running its script once the client
/// is welcomed, and the client's certificates.
struct Fake {
address: String,
ca: String,
client: Issued,
script: Option<JoinHandle<()>>,
}
impl Fake {
fn start(script: impl FnOnce(&mut Stream) + Send + 'static) -> Fake {
let ca = Ca::create("Fake CA", 1).unwrap();
let loaded = Ca::load(&ca.certificate, &ca.key).unwrap();
let issue = |name: &str, usage| {
loaded
.issue(&Identity::new(name, &["sensor"]).unwrap(), usage, 1)
.unwrap()
};
let server = issue("fake", Usage::Server);
let client = issue("kitchen", Usage::Client);
let config = tls::server_config(
&ca.certificate,
&server.certificate,
&server.key,
Revocations::none().shared(),
)
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap().to_string();
let script = thread::spawn(move || {
let (tcp, _) = listener.accept().unwrap();
tcp.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
let mut stream = StreamOwned::new(ServerConnection::new(config).unwrap(), tcp);
while stream.conn.is_handshaking() {
stream.conn.complete_io(&mut stream.sock).unwrap();
}
frame::write_version(&mut stream).unwrap();
frame::read_version(&mut stream).unwrap();
answer(
&mut stream,
Welcome {
server: "fake".into(),
node: "kitchen".into(),
},
);
script(&mut stream);
});
Fake {
address,
ca: ca.certificate,
client,
script: Some(script),
}
}
fn connect(&self) -> Client {
Client::connect(
&self.address,
&Settings {
ca: &self.ca,
certificate: &self.client.certificate,
key: &self.client.key,
crl: None,
},
)
.unwrap()
}
/// Waits for the script to end (its asserts included).
fn finish(mut self) {
self.script.take().unwrap().join().unwrap();
}
}
/// The client's next packet, none once it closed the connection.
fn request(stream: &mut Stream) -> Option<Packet> {
let bytes = frame::read(stream, MAX_PACKET_SIZE).ok()??;
Some(Packet::decode(&bytes).unwrap())
}
fn answer(stream: &mut Stream, packet: impl Into<Packet>) {
frame::write(stream, &packet.into().encode()).unwrap();
stream.flush().unwrap();
}
/// Whether the client closed the connection without sending anything
/// more: what the script reports after its answer.
fn nothing_more(stream: &mut Stream) -> bool {
request(stream).is_none()
}
#[track_caller]
fn fails(result: Result<impl std::fmt::Debug, bakashrot_client::Error>, code: ErrorCode) {
let error = result.unwrap_err();
assert_eq!(error.code(), code.code(), "{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));
// Too late: the client gave up, and closed.
let _ = frame::write(
stream,
&Packet::from(MessagePushed { message_id: 1 }).encode(),
);
let _ = stream.flush();
report.send(nothing_more(stream)).unwrap();
});
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}");
assert!(
error.message().contains("no answer within 200ms"),
"{error}"
);
assert!(!client.is_open() && client.is_closed());
// Once the late answer is there, the next push mustn't read it as its
// own (it got #1 before).
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();
});
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();
});
let mut client = fake.connect();
fails(client.ping(), ErrorCode::ProtocolError);
fails(client.query("SELECT 1"), ErrorCode::NotConnected);
assert!(reported.recv().unwrap());
fake.finish();
}
#[test]
fn an_answer_cut_short_closes() {
let fake = Fake::start(|stream| {
assert!(matches!(request(stream), Some(Packet::GetMessages(_))));
// A frame of 100 bytes, 3 of them sent, then the connection gone.
stream.write_all(&[100, 0, 0, 0, 1, 2, 3]).unwrap();
stream.flush().unwrap();
stream.conn.send_close_notify();
let _ = stream.conn.complete_io(&mut stream.sock);
});
let mut client = fake.connect();
fails(
client.get_messages("logs", "kitchen", Some(0), 10),
ErrorCode::ConnectionLost,
);
fails(client.ping(), ErrorCode::NotConnected);
fake.finish();
}
#[test]
fn a_refusal_keeps_the_connection() {
let fake = Fake::start(|stream| {
assert!(matches!(request(stream), Some(Packet::PushMessage(_))));
answer(
stream,
RequestRefused::new(ErrorCode::NotAllowed, "not this topic"),
);
assert!(matches!(request(stream), Some(Packet::Ping(_))));
answer(stream, Pong {});
assert!(matches!(request(stream), Some(Packet::PushMessage(_))));
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());
assert_eq!(error.message(), "not this topic");
assert!(client.is_open() && !client.is_closed());
client.ping().unwrap();
assert_eq!(client.push("logs", "{}").unwrap(), 7);
fake.finish();
}
#[test]
fn an_argument_refused_before_sending_keeps_the_connection() {
let fake = Fake::start(|stream| {
assert!(matches!(request(stream), Some(Packet::Ping(_))));
answer(stream, Pong {});
});
let mut client = fake.connect();
fails(client.push("not a name", "{}"), ErrorCode::InvalidArgument);
fails(
client.get_messages("logs", "kitchen", Some(0), 0),
ErrorCode::InvalidArgument,
);
fails(
client.set_answer_timeout(Duration::ZERO),
ErrorCode::InvalidArgument,
);
assert_eq!(client.answer_timeout(), ANSWER_TIMEOUT);
client.ping().unwrap();
fake.finish();
}
#[test]
fn a_longer_timeout_waits_for_a_slow_answer() {
let fake = Fake::start(|stream| {
assert!(matches!(request(stream), Some(Packet::Ping(_))));
thread::sleep(Duration::from_millis(500));
answer(stream, Pong {});
});
let mut client = fake.connect();
client.set_answer_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(client.answer_timeout(), Duration::from_secs(5));
client.ping().unwrap();
fake.finish();
}
/// `is_open()` looks without blocking, then blocks again: the next
/// request waits for its answer, slow as it is.
#[test]
fn is_open_leaves_the_connection_blocking() {
let fake = Fake::start(|stream| {
assert!(matches!(request(stream), Some(Packet::Ping(_))));
thread::sleep(Duration::from_millis(300));
answer(stream, Pong {});
});
let mut client = fake.connect();
assert!(client.is_open() && !client.is_closed());
client.ping().unwrap();
fake.finish();
}
/// The server gone (closed as it closes an idle one: the socket, no TLS
/// close_notify): `is_open()` says so, the next request fails as lost,
/// those after as not connected.
#[test]
fn a_connection_the_server_closed() {
let fake = Fake::start(|stream| {
let _ = stream.sock.shutdown(std::net::Shutdown::Both);
});
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");
fails(client.ping(), ErrorCode::ConnectionLost);
fails(client.ping(), ErrorCode::NotConnected);
}
#[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(
stream,
Attachment {
size: 10,
sha256: [0; 32],
},
);
answer(stream, AttachmentPart { data: vec![1; 5] });
report.send(nothing_more(stream)).unwrap();
});
let mut client = fake.connect();
let mut out = Vec::new();
fails(
client.get_attachment("logs", "kitchen", 1, &mut out),
ErrorCode::ProtocolError,
);
fails(client.ping(), ErrorCode::NotConnected);
assert!(reported.recv().unwrap());
fake.finish();
}
/// A refusal where a part should be: the parts after it would be read as
/// 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(
stream,
Attachment {
size: ATTACHMENT_PART_SIZE + 1,
sha256: [0; 32],
},
);
answer(
stream,
AttachmentPart {
data: vec![1; ATTACHMENT_PART_SIZE as usize],
},
);
answer(
stream,
RequestRefused::new(ErrorCode::ServerError, "a disk"),
);
report.send(nothing_more(stream)).unwrap();
});
let mut client = fake.connect();
let mut out = Vec::new();
fails(
client.get_attachment("logs", "kitchen", 1, &mut out),
ErrorCode::ServerError,
);
fails(client.ping(), ErrorCode::NotConnected);
assert!(reported.recv().unwrap());
fake.finish();
}
/// Bytes that read the first time through, and fail the second.
struct FailingSecondTime {
data: Cursor<Vec<u8>>,
rewinds: usize,
}
impl Read for FailingSecondTime {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
if self.rewinds > 1 {
return Err(io::Error::other("the disk went away"));
}
self.data.read(buffer)
}
}
impl Seek for FailingSecondTime {
fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
self.rewinds += 1;
self.data.seek(to)
}
}
/// The source failing once the server said `Continue`: the server waits
/// 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();
});
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}");
assert!(!client.is_open() && client.is_closed());
fails(client.ping(), ErrorCode::NotConnected);
assert!(reported.recv().unwrap());
fake.finish();
}
+58 -6
View File
@@ -15,7 +15,7 @@ use bakashrot_proto::limits::{ALPN, KEEPALIVE_SECS, MAX_PACKET_SIZE};
use bakashrot_proto::names::name_matches;
use bakashrot_proto::packets::{
Attachment, AttachmentPart, MissingAttachment, Pair, Ping, ReplicateAttachment,
ReplicateMessages, SyncState, SyncStateRequest,
ReplicateMessages, RequestRefused, SyncState, SyncStateRequest,
};
use bakashrot_proto::{ErrorCode, Packet, frame};
use bakashrot_storage::AttachmentState;
@@ -371,11 +371,21 @@ async fn check_own_copy(
attachment: &Attachment,
message: &str,
) {
let read = shared.hash_parts(attachment_id, 0..attachment.part_count());
if let Ok(sha256) = read.await
&& sha256.finish().as_ref() == attachment.sha256
{
return;
let read = shared
.hash_parts(attachment_id, 0..attachment.part_count())
.await
.map(|sha256| sha256.finish().as_ref() == attachment.sha256);
match judge(&read) {
OwnCopy::Intact => return,
OwnCopy::Damaged => {}
OwnCopy::Unknown => {
let why = read.err().map(|refused| refused.reason).unwrap_or_default();
warn!(
"{message}: this server's copy of its attachment couldn't be read back ({why}): \
kept, checked again when a peer refuses it again"
);
return;
}
}
let damaged = Write::Damaged {
attachment: attachment_id as u64,
@@ -388,6 +398,31 @@ async fn check_own_copy(
}
}
/// What reading back this server's copy of an attachment says about it.
#[derive(Debug, PartialEq, Eq)]
enum OwnCopy {
/// Read whole, matching its SHA-256.
Intact,
/// 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 verdict on a read-back: whether its SHA-256 matched, or why it
/// failed.
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,
}
}
/// A topic and node, to compare without case.
fn key(topic: &str, node: &str) -> (String, String) {
(topic.to_ascii_lowercase(), node.to_ascii_lowercase())
@@ -396,3 +431,20 @@ fn key(topic: &str, node: &str) -> (String, String) {
fn unexpected(packet: &Packet) -> String {
format!("answered {}", packet.packet_type().name())
}
#[cfg(test)]
mod tests {
use super::*;
#[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);
// 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);
}
}
+5 -1
View File
@@ -389,6 +389,10 @@ fn revoked_certificates_are_dropped() {
// Its open connection goes at its next request, a new one is refused.
let error = connected.push("logs", "{}").unwrap_err();
assert_eq!(error.code(), ErrorCode::ConnectionLost.code(), "{error}");
// Closed by the client too: the next one isn't even sent.
let error = connected.push("logs", "{}").unwrap_err();
assert_eq!(error.code(), ErrorCode::NotConnected.code(), "{error}");
assert!(!connected.is_open());
let error = running.connect(&kitchen).unwrap_err();
assert_eq!(error.code(), ErrorCode::AuthRejected.code(), "{error}");
// Others go on.
@@ -1098,7 +1102,7 @@ fn attachment_edges() {
.unwrap_err();
assert_eq!(error.code(), ErrorCode::FileError.code(), "{error}");
let error = kitchen.push("logs", "{}").unwrap_err();
assert_eq!(error.code(), ErrorCode::ConnectionLost.code(), "{error}");
assert_eq!(error.code(), ErrorCode::NotConnected.code(), "{error}");
let started = Instant::now();
while uploads(&mut analyst) != none_left {
assert!(
+35
View File
@@ -18,6 +18,31 @@ wire: `protocol.md`; the server's side: `server.md`.
**Status:** steps 7 to 9: connecting, pushes, messages, attachments,
names, queries, several clients.
## The Rust client
`bakashrot_client::Client`, blocking, one request at a time. A refusal
(1-99), or an argument refused before anything is sent
(`InvalidArgument`), keeps the connection. **Anything that leaves it out
of step closes it** (2026-11-19): an I/O error, no answer within
`answer_timeout()` (`ConnectionLost`), an answer that isn't the
request's or doesn't decode (`ProtocolError`), an attachment's parts cut
short or of the wrong size, a refusal among them, a source failing
mid-upload (`FileError`). Every request after fails with `NotConnected`
without reading anything: before, the socket stayed open, and a late
answer could be read as the next request's (a push returning the
previous push's id). `is_closed()` says so. The DLL forgets its client
whenever it's closed so (it did on `ConnectionLost` and `ProtocolError`
already; now on a file failing mid-upload too), so connecting again
works; Python and C# go through it.
- `set_answer_timeout()`: how long an answer, or sending a packet, may
take: 30 s (`ANSWER_TIMEOUT`) until changed, more than 0. Longer for a
slow query, say.
- `is_open()`: false once closed; it looks at the socket without
blocking, then always makes it blocking again (it was left
non-blocking when it found the connection gone).
- `ping()`: keeps an idle connection open (`protocol.md`, "Rules").
## Who connects: certificates
A client is its certificate, issued by the CA the servers trust
@@ -243,6 +268,16 @@ bakashrot list nodes --topics 'sensors.*' Nodes (2): those that pushed to s
## Tests
`crates/bakashrot-client/tests/failures.rs`, against a fake server (TLS
with a test CA, then scripted answers): a late answer never taken for
the next request's, a wrong, malformed or cut answer, a part of the
wrong size, a refusal among the parts, a source failing mid-upload, a
connection the server closed (each: closed, `NotConnected` after,
nothing more sent); a refusal and an argument refused before sending
keeping it; a longer timeout waiting for a slow answer; `is_open()`
leaving it blocking. Each closing path broken on purpose once: the
tests caught it.
`crates/bakashrot-capi/tests/`, each against a server on a free port:
- `exports.rs`, `exports`: the exports as C calls them, on one client: certificates from files and
+4 -1
View File
@@ -131,7 +131,10 @@ otherwise:
part it needs. One it says doesn't match its SHA-256 is read back
here: damaged (a disk, a bug), this server's copy is dropped and asked
for again from its own peers (`replicating`, not served meanwhile),
instead of sent again at every check-in.
instead of sent again at every check-in. Damaged means read whole and
not matching, or a part missing; a read-back that fails otherwise (the
database busy, a connection not opened) says nothing, so the copy is
kept and warned about (2026-11-19): it may be the only one there is.
**Receiving** (`accept_from.rs`): replication requests are answered only
if the connection comes from `accept_from` (a hostname looked up at its
+16 -1
View File
@@ -224,6 +224,21 @@ Also decided (2026-11-13):
idle read and query connections each pool keeps (they were all
kept, as many as ever ran at once); one idle for a minute is
closed (a thread looks every 10 s).
- **An attachment dropped as damaged only when it is:** a peer
refusing it (`DataMismatch`) has the sender read its own copy
back; read whole and not matching, or a part missing, it's
dropped and asked for again as before. A read-back that failed
otherwise (a busy database, a connection not opened) dropped it
too, the only copy if this server was its origin: now it's kept
and warned about (`push_to.rs`, `judge`).
- **The Rust client closes a connection left out of step**
(`client.md`, "The Rust client"): an I/O error, a timeout, an
answer that isn't the request's, parts cut short or interrupted, a
source failing mid-upload. Requests after fail with `NotConnected`
without reading: a late answer was read as the next request's (a
push returning the previous one's id). `set_answer_timeout()` /
`answer_timeout()` (30 s by default); `is_open()` always blocking
again. The DLL already dropped its client on those.
- **Schema v9, not compatible with v8** (2026-11-13): old databases aren't
opened, their data isn't carried over (the real-life tests start empty).
`docs/storage.md`:
@@ -447,7 +462,7 @@ by hand.
| 15 | Filtered lists | `ListNames`' `topics` and `nodes` filters (protocol 8): server, client, `BakaShrot_ListNames` (`A`/`W`), Python, C#, PureBasic, `bakashrot list --topics/--nodes` | `end_to_end.rs` `names` (patterns, case, permissions), `exports.rs`, `check_bakashrot.py`, the NUnit tests | Decided 2026-11-19 | Done 2026-11-19 |
| 16 | The DLL's enumerations | `GetNamesListAsJson`, `GetQueryResultAsJson`; `EnumerateNames` / `EnumerateQuery`, `Next...`, their getters, `CloseEnum` (`enumerations.rs`); `ListTopics` / `ListNodes` dropped; PureBasic's example on them; C#'s `EnumerateTopics` / `EnumerateNodes` / `EnumerateQuery` (`IEnumerable`, asked at each `foreach`) | `exports.rs` `enumerations` (names, query rows and nulls, several at once, bad and closed handles, freed with the client); the NUnit `Enumerations` test | Decided 2026-11-19 | Done 2026-11-19 |
| 17 | `SyncState` in pages | `SyncStateRequest.after`, `SyncState.more`, `MAX_HEADS_PER_PACKET` (protocol 8); `heads_after` in storage; both ends of replication | `packets.rs` `the_biggest_sync_state_fits` and the page rules; `storage.rs` heads in pages; `end_to_end.rs` `sync_state_in_pages` (full and partial pages, the lists in the first only, a cursor in another case or not stored, pairs a peer doesn't take skipped, exactly a page, a pattern refused) and `replication_across_pages` (only what's after a head of the second page sent); each part broken on purpose once, every test caught it | Decided 2026-11-19 | Done 2026-11-19 |
| 18 | Fixes from a read of the code | The server requiring ALPN; retention ages capped at 100 years; `Ping` / `Pong` (protocol 8) with `BakaShrot_Ping`, Python's and C#'s `ping`, pings in the follows and the replication links; `idle_database_connections` and idle connections closed | `end_to_end.rs` `certificates_refused` (no ALPN: closed), `pings`, `no_idle_database_connections`; `config.rs` the cap, `retention_cutoff`, the key; the server's `pools_keep_few_and_close_the_idle`; `packets.rs` samples and bytes; `exports.rs`, `check_bakashrot.py`, the NUnit `Closing` | Decided 2026-11-19 | Done 2026-11-19 |
| 18 | Fixes from a read of the code | The server requiring ALPN; retention ages capped at 100 years; `Ping` / `Pong` (protocol 8) with `BakaShrot_Ping`, Python's and C#'s `ping`, pings in the follows and the replication links; `idle_database_connections` and idle connections closed; a damaged copy told from a failed read-back; the Rust client closing a connection left out of step, `set_answer_timeout` | `end_to_end.rs` `certificates_refused` (no ALPN: closed), `pings`, `no_idle_database_connections`; `config.rs` the cap, `retention_cutoff`, the key; the server's `pools_keep_few_and_close_the_idle` and `only_a_copy_read_whole_or_missing_a_part_is_damaged` (with `replication` for the damaged copy still dropped); the client's `failures.rs` (a fake server: late, wrong, cut answers and parts) and `revoked_certificates_are_dropped`; `packets.rs` samples and bytes; `exports.rs`, `check_bakashrot.py`, the NUnit `Closing` | Decided 2026-11-19 | Done 2026-11-19 |
Each step ends with its tests passing and its docs updated (the crate's
docs, `docs/`, this file's status), then a commit when the owner