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

Fixed two peers sending the same attachment at once, Noted the stream limits, Removed the PureBasic-era leftovers

- An attachment is received from one peer at a time: the others are
  refused NotReady and ask again at their next sync; one cut short lets
  the next one take it over
- A 'replicating' row with all its bytes but never checked is asked
  again from part 0, and a peer asking from the wrong part resets it
- Noted the stream limit (1,048,575 topic/node pairs, 2^43-1 message ids
  each) in the example config and known-issues.md
- Removed NoDefaultTopic (code 6, retired), Writer::vacuum, the v8
  detection and the old ini key tests
- Cleared the PureBasic-era notes from the docs, revamp.md keeping only
  the old open items still unfixed; noted the GUI explorer (egui)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 17:23:33 +01:00
parent 764bc3652a
commit a5a2f65442
38 changed files with 436 additions and 907 deletions
+66 -3
View File
@@ -12,7 +12,46 @@ use bakashrot_proto::packets::{
use bakashrot_proto::{ErrorCode, Packet};
use bakashrot_storage::AttachmentState;
use std::net::IpAddr;
use std::sync::Arc;
use std::sync::{Arc, PoisonError};
use tracing::warn;
/// A replicated attachment being received over one connection: another
/// asking for it is refused until this is dropped (finished, refused,
/// the connection gone).
struct Receiving<'a> {
shared: &'a Shared,
key: (String, String, u64),
}
impl<'a> Receiving<'a> {
/// None when it's being received already. Names without case, as
/// everywhere ("Logs" is "logs").
fn claim(shared: &'a Shared, topic: &str, node: &str, message_id: u64) -> Option<Self> {
let key = (
topic.to_ascii_lowercase(),
node.to_ascii_lowercase(),
message_id,
);
let claimed = shared
.receiving
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(key.clone());
// Made only when claimed, the lock let go: dropping one releases it.
claimed.then(|| Receiving { shared, key })
}
}
impl Drop for Receiving<'_> {
fn drop(&mut self) {
let mut receiving = self
.shared
.receiving
.lock()
.unwrap_or_else(PoisonError::into_inner);
receiving.remove(&self.key);
}
}
/// Whether `address` is in `accept_from`: `*`, an address as written, or
/// a hostname resolving to it (looked up now).
@@ -152,6 +191,16 @@ pub(crate) async fn replicate_attachment(
return Ok(refusal);
}
let message = format!("{}:{}#{}", request.topic, request.node, request.message_id);
// One peer at a time per attachment, until this returns (or the
// connection goes): two at once would both be refused a part.
let Some(_receiving) =
Receiving::claim(shared, &request.topic, &request.node, request.message_id)
else {
return Ok(refused(
ErrorCode::NotReady,
format!("{message}: being received from another server"),
));
};
let ReplicateAttachment {
topic,
node,
@@ -175,8 +224,22 @@ pub(crate) async fn replicate_attachment(
size: stored.size,
sha256: stored.sha256,
};
let next = stored.received / ATTACHMENT_PART_SIZE;
if from_part != next || stored.received == stored.size {
// Every part came but nobody is checking them (finishing it failed):
// started over, it's never taken unchecked.
let mut received = stored.received;
if received == stored.size {
warn!("{message}: its attachment came whole but wasn't checked, asked for again");
let restart = Write::FinishReplicated {
attachment: stored.id as u64,
matches: false,
};
if let Err(refusal) = shared.pushes.send(restart).await {
return Ok(refusal.into());
}
received = 0;
}
let next = received / ATTACHMENT_PART_SIZE;
if from_part != next {
return Ok(refused(
ErrorCode::InvalidRequest,
format!("{message}: part {next} is the next one here, not {from_part}"),
+6 -1
View File
@@ -28,6 +28,7 @@ use bakashrot_pki::{Revocations, SharedRevocations, summarize, tls};
use bakashrot_proto::ErrorCode;
use bakashrot_proto::packets::RequestRefused;
use bakashrot_storage::{Database, QueryRunner, Reader};
use std::collections::HashSet;
use std::net::SocketAddr;
use std::path::Path;
use std::sync::{Arc, Mutex};
@@ -66,6 +67,9 @@ struct Shared {
readers: Mutex<Vec<Reader>>,
/// Query connections not in use.
queries: Mutex<Vec<QueryRunner>>,
/// The replicated attachments being received (topic, node, message
/// id): one peer at a time each (`accept_from.rs`).
receiving: Mutex<HashSet<(String, String, u64)>>,
}
impl Server {
@@ -108,6 +112,7 @@ impl Server {
pushes,
readers: Mutex::new(Vec::new()),
queries: Mutex::new(Vec::new()),
receiving: Mutex::new(HashSet::new()),
config,
}),
})
@@ -253,7 +258,7 @@ impl Shared {
/// Checkpoints the WAL every second, on a thread and a connection of its
/// own, so the writer doesn't do it in the middle of a commit (2.5 times
/// the pushes: `docs/storage.md`, "Against the old storage").
/// the pushes: `docs/storage.md`, "The benchmark").
fn start_checkpoints(database: &Database) -> Result<(), String> {
let checkpointer = database.checkpointer().map_err(|error| error.to_string())?;
std::thread::Builder::new()
+141 -7
View File
@@ -429,8 +429,7 @@ fn ids(messages: &Messages) -> Vec<u64> {
messages.messages.iter().map(|message| message.id).collect()
}
/// `OldSource/Tests/GetMessages-Test.ps1`, the server's part (the tool's
/// is step 8).
/// Runs of messages: after an id, limits, `more`, the latest.
#[test]
fn runs_of_messages() {
let running = Running::start("runs");
@@ -515,8 +514,7 @@ fn runs_of_messages() {
assert_eq!(run(&mut kitchen, None, 1).messages[0].data, text);
}
/// `OldSource/Tests/BigMessages-Test.ps1`, one server's part (replicating
/// them is step 11): up to the limit, answers split at about 1 MB.
/// Big messages: up to the limit, answers split at about 1 MB.
#[test]
fn big_messages() {
let running = Running::start("big");
@@ -628,7 +626,7 @@ fn names() {
);
}
/// The query parts of `OldSource/Tests/BigMessages-Test.ps1`.
/// Queries: allowed or not, results, refusals.
#[test]
fn queries() {
let running = Running::start("queries");
@@ -1157,8 +1155,7 @@ fn retention() {
assert_eq!(latest.messages[0].id, 4);
}
/// Replication flat out, as the old `Tests/Bench/Bench-Replication.ps1`
/// (`-Parts Ramp -Ramp 10x0`): 4 servers in a Y (a hub pushing to 3
/// Replication flat out: 4 servers in a Y (a hub pushing to 3
/// leaves, each pushing to the hub), `NODES` nodes (10) pushing to each
/// as fast as they're answered for `SECONDS` (30), then how far behind
/// each server is and how long until every one has every message. Run
@@ -1582,3 +1579,140 @@ fn replication_edges() {
});
other.refused(ErrorCode::NotAllowed);
}
/// Message `id`'s attachment in `running`'s database: its state and
/// how much of it came.
fn attachment_row(running: &Running, id: u64) -> (String, u64) {
let raw = rusqlite::Connection::open(running.folder.join("bakashrot.sqlite")).unwrap();
raw.query_row(
"SELECT a.state, a.received FROM attachments a \
JOIN data d ON d.key = a.message_key WHERE d.message_id = ?1",
[id],
|row| Ok((row.get(0)?, row.get(1)?)),
)
.unwrap()
}
#[test]
fn two_peers_one_attachment() {
// The test plays two peers having the same attachments.
let running = Running::start_with(
"two-peers",
"\n[replication]\naccept_from = [\"127.0.0.1\"]\n",
);
let x = running.issue("server-x", &["peer"]);
let mut a = Raw::connect(&running, &x);
let mut b = Raw::connect(&running, &running.issue("server-y", &["peer"]));
let small = bytes(MIB + 10, 7);
let whole = bytes(2 * MIB, 8);
let message = |id, file: &[u8]| ReplicatedMessage {
id,
pushed_at: 1_800_000_000_000,
data: format!("m{id}"),
attachment: Some(Attachment {
size: file.len() as u64,
sha256: sha256(file),
}),
};
a.send(ReplicateMessages {
topic: "logs".into(),
node: "far".into(),
messages: vec![message(1, &small), message(2, &small), message(3, &whole)],
});
assert_eq!(a.receive(), Some(MessagePushed { message_id: 3 }.into()));
let ask = |raw: &mut Raw, topic: &str, message_id, from_part| {
raw.send(ReplicateAttachment {
topic: topic.into(),
node: "far".into(),
message_id,
from_part,
})
};
let send_parts = |raw: &mut Raw, file: &[u8]| {
for part in file.chunks(MIB) {
raw.send(AttachmentPart {
data: part.to_vec(),
});
}
};
let mut reader = running
.connect(&running.issue("watcher", &["reader"]))
.unwrap();
let mut got = |id| {
let mut out = Vec::new();
reader.get_attachment("logs", "far", id, &mut out).unwrap();
out
};
// One peer at a time: the other is refused before any part (in any
// case of the names), the first one finishes it.
ask(&mut a, "logs", 1, 0);
assert!(matches!(a.receive(), Some(Packet::Continue(_))));
ask(&mut b, "logs", 1, 0);
b.refused(ErrorCode::NotReady);
ask(&mut b, "LOGS", 1, 0);
b.refused(ErrorCode::NotReady);
send_parts(&mut a, &small);
assert_eq!(a.receive(), Some(MessagePushed { message_id: 1 }.into()));
assert!(got(1) == small);
ask(&mut b, "logs", 1, 0);
b.refused(ErrorCode::NotFound);
// A peer gone partway: the next one takes it from there.
ask(&mut a, "logs", 2, 0);
assert!(matches!(a.receive(), Some(Packet::Continue(_))));
a.send(AttachmentPart {
data: small[..MIB].to_vec(),
});
wait_for("the first part", || {
attachment_row(&running, 2).1 == MIB as u64
});
drop(a);
wait_for("the attachment let go", || {
ask(&mut b, "logs", 2, 1);
match b.receive() {
Some(Packet::Continue(_)) => true,
Some(Packet::RequestRefused(refused)) => {
assert_eq!(refused.code, ErrorCode::NotReady.code(), "{refused:?}");
false
}
other => panic!("expected Continue or NotReady, got {other:?}"),
}
});
send_parts(&mut b, &small[MIB..]);
assert_eq!(b.receive(), Some(MessagePushed { message_id: 2 }.into()));
assert!(got(2) == small);
// Whole but never checked (finishing it failed): asked for from the
// first part, not past its last; started over, never taken unchecked.
let mut a = Raw::connect(&running, &x);
ask(&mut a, "logs", 3, 0);
assert!(matches!(a.receive(), Some(Packet::Continue(_))));
send_parts(&mut a, &whole);
assert_eq!(a.receive(), Some(MessagePushed { message_id: 3 }.into()));
let raw = rusqlite::Connection::open(running.folder.join("bakashrot.sqlite")).unwrap();
raw.execute(
"UPDATE attachments SET state = 'replicating' \
WHERE message_key = (SELECT key FROM data WHERE message_id = 3)",
[],
)
.unwrap();
assert_eq!(
attachment_row(&running, 3),
("replicating".into(), whole.len() as u64)
);
let missing: Vec<_> = sync_state(&mut a)
.missing
.iter()
.map(|missing| (missing.message_id, missing.next_part))
.collect();
assert_eq!(missing, [(3, 0)], "not part 2: then it's never asked for");
ask(&mut a, "logs", 3, 2);
a.refused(ErrorCode::InvalidRequest);
assert_eq!(attachment_row(&running, 3), ("replicating".into(), 0));
ask(&mut a, "logs", 3, 0);
assert!(matches!(a.receive(), Some(Packet::Continue(_))));
send_parts(&mut a, &whole);
assert_eq!(a.receive(), Some(MessagePushed { message_id: 3 }.into()));
assert!(got(3) == whole);
}