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:
@@ -3,7 +3,7 @@
|
||||
//! Python (ctypes) and anything that loads a DLL. `docs/client.md`
|
||||
//! has the whole API; `bindings/c/bakashrot.h` is generated from this file.
|
||||
//!
|
||||
//! The conventions, the old DLL's:
|
||||
//! The conventions:
|
||||
//!
|
||||
//! - **One connection per process:** set the certificates, connect, send
|
||||
//! requests, one at a time (calls from several threads wait for each
|
||||
|
||||
@@ -54,7 +54,9 @@ batch_size = 1000 # messages per packet, 1-10000
|
||||
# roles allow; one without any role listed here is refused. Every key is
|
||||
# optional: an empty list allows nothing. The topics are only named here:
|
||||
# one exists from its first message, pushed (push_topics) or replicated
|
||||
# (accept_topics).
|
||||
# (accept_topics). A database holds 1,048,575 topic and node pairs at
|
||||
# most, all topics together, never freed: patterns like "*" in
|
||||
# push_topics let clients make as many as they like.
|
||||
[roles.sensor]
|
||||
push_topics = ["sensors.*"] # always as its own node (its name)
|
||||
|
||||
|
||||
@@ -235,12 +235,6 @@ fn refusals() {
|
||||
("", "missing field `server`"),
|
||||
(&with("lsiten = \"x\"\n"), "unknown field `lsiten`"),
|
||||
(&with("[other]\n"), "unknown field `other`"),
|
||||
// The old ini's keys.
|
||||
(&with("PrivateKey = \"x\"\n"), "unknown field `PrivateKey`"),
|
||||
(
|
||||
&with("[roles.sensor]\nAllowWrite = 1\n"),
|
||||
"unknown field `AllowWrite`",
|
||||
),
|
||||
(
|
||||
&with("[roles.sensor]\ndefault_topic = \"x\"\n"),
|
||||
"unknown field `default_topic`",
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
//! The error codes: what a server sends with each refusal (1-99, in a
|
||||
//! `RequestRefused`), and the client's own (100 and up, what the DLL's
|
||||
//! `BakaShrot_GetLastError()` returns). The same numbers as protocol 6
|
||||
//! (`OldSource/Client/BakaShrot_ErrorCodes.pbi`): never renumber one, only
|
||||
//! add new ones.
|
||||
//! `BakaShrot_GetLastError()` returns). Never renumber one, only add new
|
||||
//! ones; 6 is retired, never reuse it.
|
||||
//!
|
||||
//! What to do about each:
|
||||
//! - reconnect, then retry: `NotConnected`, `ConnectFailed`,
|
||||
//! `ConnectionLost`, `ProtocolError` (the connection is closed);
|
||||
//! - retry later: `NotReady`, `ServerError`;
|
||||
//! - fix the configuration: `AuthRejected`, `ServerNotVerified`,
|
||||
//! `NotAllowed`, `UnknownName`, `NoDefaultTopic`;
|
||||
//! `NotAllowed`, `UnknownName`;
|
||||
//! - update one end: `VersionMismatch`;
|
||||
//! - fix the call: `InvalidArgument`, `InvalidRequest`, `TooBig`,
|
||||
//! `QueryFailed`, `FileError`;
|
||||
@@ -71,7 +70,6 @@ error_codes! {
|
||||
NotFound = 3, "No such message or attachment.";
|
||||
NotReady = 4, "The attachment isn't on this server yet (still being replicated).";
|
||||
TooBig = 5, "A message, attachment or query result over a limit, or an attachment bigger than this server keeps.";
|
||||
NoDefaultTopic = 6, "Protocol 6's: a push without a topic and no default one. Protocol 7 pushes always name their topic: never sent, kept so the number isn't reused.";
|
||||
InvalidRequest = 7, "A request that doesn't fit: an attachment's parts not matching its size, a part that doesn't exist...";
|
||||
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).";
|
||||
@@ -131,14 +129,13 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_numbers_of_protocol_6() {
|
||||
fn the_numbers_never_change() {
|
||||
let expected: &[(u32, &str)] = &[
|
||||
(1, "NotAllowed"),
|
||||
(2, "UnknownName"),
|
||||
(3, "NotFound"),
|
||||
(4, "NotReady"),
|
||||
(5, "TooBig"),
|
||||
(6, "NoDefaultTopic"),
|
||||
(7, "InvalidRequest"),
|
||||
(8, "DataMismatch"),
|
||||
(9, "QueryFailed"),
|
||||
@@ -164,6 +161,8 @@ mod tests {
|
||||
assert_eq!(known.is_refusal(), *code < 100);
|
||||
assert!(!known.description().is_empty());
|
||||
}
|
||||
// Retired: never given to another code.
|
||||
assert_eq!(ErrorCode::from_code(6), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
//! waiting for the rest. An empty one is too (as a frame here, as a packet
|
||||
//! that doesn't decode with [`codec()`]).
|
||||
//!
|
||||
//! Over TLS, which takes care of the encryption: unlike protocol 6, frames
|
||||
//! carry packets as they are.
|
||||
//! Over TLS, which takes care of the encryption: frames carry packets as
|
||||
//! they are.
|
||||
//!
|
||||
//! Before any frame, right after TLS, each end sends its protocol version
|
||||
//! (4 bytes, little-endian) and reads the other's: [`write_version()`],
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! through `serde` and `rmp-serde`.
|
||||
//!
|
||||
//! - [`limits`]: the protocol's numbers (sizes, counts, the version).
|
||||
//! - [`error`]: the error codes, the same numbers as protocol 6.
|
||||
//! - [`error`]: the error codes, never renumbered.
|
||||
//! - [`names`]: topic and node names, wildcards.
|
||||
//! - [`frame`]: frames, a 4-byte size then a packet.
|
||||
//! - [`packets`]: every packet, and [`Packet`] to encode and decode them.
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
|
||||
/// The protocol's version. Both ends must have the same: they tell each
|
||||
/// other first thing (`frame::write_version()`), and abandon the
|
||||
/// connection if it differs. 6 was the last PureBasic one (`OldSource/`);
|
||||
/// 7 runs over TLS.
|
||||
/// connection if it differs.
|
||||
pub const PROTOCOL_VERSION: u32 = 7;
|
||||
|
||||
/// The ALPN protocol name both ends offer during the TLS handshake: what
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Topic and node names, and wildcards: the rules of protocol 6
|
||||
//! (`OldSource/Commons/Networking/Names.pbi`), without its ids.
|
||||
//! Topic and node names, and wildcards.
|
||||
//!
|
||||
//! Topics and nodes go by name everywhere on the wire: a server's ids for
|
||||
//! them are its own business, in its database.
|
||||
|
||||
@@ -93,8 +93,7 @@ pub trait Body: Serialize + DeserializeOwned + Check + Into<Packet> {
|
||||
}
|
||||
|
||||
// The one table of packets: their names (the struct's and the variant's)
|
||||
// and ids. Protocol 7's own: protocol 6's ids don't apply (the versions are
|
||||
// checked before any packet).
|
||||
// and ids (the versions are checked before any packet).
|
||||
macro_rules! packets {
|
||||
($( $(#[$doc:meta])* $name:ident = $id:literal, )*) => {
|
||||
/// The type of a packet: its first value.
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
//! Replication, between servers: at each check-in a peer (P) asks the
|
||||
//! server (S) what it takes and has, then sends what it's missing,
|
||||
//! messages first, then attachments (`OldSource/Design/Packets.md`,
|
||||
//! "Replication"). Servers only ever send each other names: each has its
|
||||
//! own ids.
|
||||
//! messages first, then attachments. Servers only ever send each other
|
||||
//! names: each has its own ids.
|
||||
|
||||
use super::rules;
|
||||
use super::{Attachment, Check, DecodeError};
|
||||
|
||||
@@ -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}"),
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -36,18 +36,6 @@ impl Writer {
|
||||
batch.transaction.commit()?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Gives the space of deleted messages back to the disk: rewrites the
|
||||
/// database (`VACUUM`), then empties the WAL. SQLite reuses that space
|
||||
/// by itself; this only shrinks the file. Slow on a big database, and
|
||||
/// every other write waits meanwhile: the old server's `vacuum`
|
||||
/// command.
|
||||
pub fn vacuum(&mut self) -> Result<()> {
|
||||
self.connection.execute_batch("VACUUM")?;
|
||||
self.connection
|
||||
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// What's written in one transaction ([`Writer::batch`]). Names come
|
||||
|
||||
@@ -28,8 +28,7 @@ const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
pub const WRITER_CHECKPOINT_PAGES: u32 = 10_000;
|
||||
|
||||
/// Copies the WAL into the database on a connection of its own, so the
|
||||
/// writer doesn't do it in the middle of a commit (the old server's way:
|
||||
/// `OldSource/Server/Storage/Writer.pbi`).
|
||||
/// writer doesn't do it in the middle of a commit.
|
||||
#[derive(Debug)]
|
||||
pub struct Checkpointer {
|
||||
connection: Connection,
|
||||
@@ -74,7 +73,10 @@ impl Database {
|
||||
[concat!("bakashrot-storage ", env!("CARGO_PKG_VERSION"))],
|
||||
)?;
|
||||
} else if application_id != APPLICATION_ID {
|
||||
return Err(Error::Unusable(unusable(&transaction, path)?));
|
||||
return Err(Error::Unusable(format!(
|
||||
"{}: not a BakaShrot database",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
let mut version = schema_version(&transaction)?;
|
||||
if version > SCHEMA_VERSION {
|
||||
@@ -184,20 +186,3 @@ fn schema_version(connection: &Connection) -> Result<i64> {
|
||||
};
|
||||
version.ok_or_else(|| Error::Unusable("a BakaShrot database without its schema version".into()))
|
||||
}
|
||||
|
||||
/// Why a database that isn't ours can't be opened, in words.
|
||||
fn unusable(connection: &Connection, path: &Path) -> Result<String> {
|
||||
let old: bool = connection.query_row(
|
||||
"SELECT count(*) > 0 FROM sqlite_schema WHERE type = 'table' AND name = 'node_heads'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
Ok(if old {
|
||||
format!(
|
||||
"{}: made by the old server (schema v8), which this one doesn't read: start a new database",
|
||||
path.display()
|
||||
)
|
||||
} else {
|
||||
format!("{}: not a BakaShrot database", path.display())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
//! and hands out connections.
|
||||
//! - [`Writer`]: the one connection that writes. Everything is written in
|
||||
//! a [`Batch`], one transaction: pushes, replication, attachments,
|
||||
//! retention. Many pushes in one batch is a group commit. And
|
||||
//! [`Writer::vacuum`], to shrink the file.
|
||||
//! retention. Many pushes in one batch is a group commit.
|
||||
//! - [`Reader`]: as many as needed, reading while the writer writes (WAL).
|
||||
//! - [`QueryRunner`]: clients' read-only SQL, on a read-only connection.
|
||||
//!
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Clients' read-only SQL (`Query`), as the old server ran it.
|
||||
//! Clients' read-only SQL (`Query`).
|
||||
//!
|
||||
//! Read-only three ways: the connection has `query_only` on (SQLite
|
||||
//! refuses any write), the statement must be one SQLite says only reads
|
||||
@@ -6,8 +6,8 @@
|
||||
//! error, not ignored). PRAGMAs are refused as they're prepared
|
||||
//! (`Database::query_runner`'s authorizer): some would change the
|
||||
//! connection, `query_only` included, before the statement is looked
|
||||
//! at. The result is JSON, every value a string or null
|
||||
//! (as in protocol 6): `{"columns":[...],"rows":[[...],...]}`.
|
||||
//! at. The result is JSON, every value a string or null:
|
||||
//! `{"columns":[...],"rows":[[...],...]}`.
|
||||
|
||||
use crate::{Error, Result};
|
||||
use bakashrot_proto::limits::MAX_MESSAGE_SIZE;
|
||||
@@ -77,7 +77,7 @@ impl QueryRunner {
|
||||
}
|
||||
}
|
||||
|
||||
/// SQLite's error, with a hint where the old server gave one.
|
||||
/// SQLite's error, with a hint where one helps.
|
||||
fn explain(why: String) -> String {
|
||||
if why.contains("malformed JSON") {
|
||||
format!("{why} (a row isn't JSON: add is_json = 1 to the WHERE)")
|
||||
|
||||
@@ -190,17 +190,23 @@ impl Reader {
|
||||
pub fn missing_attachments(&self, limit: usize) -> Result<Vec<MissingAttachment>> {
|
||||
self.connection
|
||||
.prepare_cached(
|
||||
"SELECT s.topic, s.node, d.message_id, a.received FROM attachments a \
|
||||
"SELECT s.topic, s.node, d.message_id, a.received, a.size FROM attachments a \
|
||||
JOIN data d ON d.key = a.message_key \
|
||||
JOIN streams s ON s.stream_id = d.stream_id \
|
||||
WHERE a.state = 'replicating' ORDER BY a.attachment_id LIMIT ?1",
|
||||
)?
|
||||
.query_map([limit as i64], |row| {
|
||||
let (received, size): (u64, u64) = (row.get(3)?, row.get(4)?);
|
||||
Ok(MissingAttachment {
|
||||
topic: row.get(0)?,
|
||||
node: row.get(1)?,
|
||||
message_id: row.get(2)?,
|
||||
next_part: row.get::<_, u64>(3)? / ATTACHMENT_PART_SIZE,
|
||||
// Whole but not checked: it starts over from the first.
|
||||
next_part: if received == size {
|
||||
0
|
||||
} else {
|
||||
received / ATTACHMENT_PART_SIZE
|
||||
},
|
||||
})
|
||||
})?
|
||||
.collect::<rusqlite::Result<_>>()
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
-- keys below are packed integers, on purpose, and only bakashrot-storage
|
||||
-- packs and unpacks them.
|
||||
--
|
||||
-- Not compatible with v8 (OldSource/Server/Storage/db_schema_v8.dbml): a
|
||||
-- database of the old server isn't opened, its data isn't carried over.
|
||||
-- Needs SQLite 3.38+ (JSON functions, ->>), bundled with the crate.
|
||||
--
|
||||
-- Run once, in one transaction, on an empty database (Database::open).
|
||||
@@ -128,7 +126,7 @@ FROM streams s
|
||||
JOIN data d ON d.key BETWEEN (s.stream_id << 43) AND (s.stream_id << 43) + 8796093022207
|
||||
LEFT JOIN attachments a ON a.message_key = d.key;
|
||||
|
||||
-- What to browse with a database tool (v8's): set topic, and node or NULL
|
||||
-- What to browse with a database tool: set topic, and node or NULL
|
||||
-- for all, in its one row, open browse_messages. Never written by the
|
||||
-- server.
|
||||
CREATE TABLE browse (
|
||||
|
||||
@@ -84,10 +84,6 @@ fn refused_databases() {
|
||||
}
|
||||
};
|
||||
refused("CREATE TABLE other (x);", "not a BakaShrot database");
|
||||
refused(
|
||||
"CREATE TABLE data (x); CREATE TABLE node_heads (y);",
|
||||
"made by the old server (schema v8)",
|
||||
);
|
||||
refused(
|
||||
"PRAGMA application_id = 1112754260; CREATE TABLE x (y);",
|
||||
"without its schema version",
|
||||
@@ -580,36 +576,6 @@ fn retention() {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vacuum() {
|
||||
let (database, path) = open("vacuum");
|
||||
let mut writer = database.writer().unwrap();
|
||||
let big = "x".repeat(10_000);
|
||||
writer
|
||||
.batch(|b| {
|
||||
for _ in 0..1000 {
|
||||
b.push("logs", "kitchen", 1, &big)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
writer.vacuum().unwrap();
|
||||
let full = std::fs::metadata(&path).unwrap().len();
|
||||
writer
|
||||
.batch(|b| b.delete_before("logs", u64::MAX, 10_000))
|
||||
.unwrap();
|
||||
writer.vacuum().unwrap();
|
||||
let emptied = std::fs::metadata(&path).unwrap().len();
|
||||
assert!(emptied * 10 < full, "{full} -> {emptied}");
|
||||
// Still the same database: ids go on.
|
||||
assert_eq!(
|
||||
writer
|
||||
.batch(|b| b.push("logs", "kitchen", 2, "{}"))
|
||||
.unwrap(),
|
||||
1001
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limits() {
|
||||
let (database, path) = open("limits");
|
||||
@@ -829,8 +795,7 @@ fn readers_while_writing() {
|
||||
assert_eq!(reader.last_id("logs", "garage").unwrap(), 2000);
|
||||
}
|
||||
|
||||
/// The same workload as the old storage's benchmark
|
||||
/// (`OldSource\Build\Bench\StorageBenchOld.exe`), to compare them: pushes
|
||||
/// The storage alone, flat out (`docs/storage.md`, "The benchmark"): pushes
|
||||
/// over 100 topics x 5 nodes (an LCG picks them), 100 per batch, 200-byte
|
||||
/// JSON; 2000 latest-message reads, 500 reads of 1000 messages after the
|
||||
/// middle id, the file's size, retention of 10% of one topic. Not run by
|
||||
@@ -838,7 +803,7 @@ fn readers_while_writing() {
|
||||
/// bakashrot-storage -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn compare_with_old() {
|
||||
fn storage_rate() {
|
||||
use std::time::Instant;
|
||||
let count: u64 = std::env::var("PUSHES").map_or(1_000_000, |n| n.parse().unwrap());
|
||||
let sync = std::env::var("SYNC").unwrap_or_else(|_| "normal".into());
|
||||
@@ -847,7 +812,7 @@ fn compare_with_old() {
|
||||
} else {
|
||||
Synchronous::Normal
|
||||
};
|
||||
let path = path("compare");
|
||||
let path = path("rate");
|
||||
let database = Database::open(&path, synchronous).unwrap();
|
||||
let mut writer = database.writer().unwrap();
|
||||
|
||||
@@ -858,7 +823,7 @@ fn compare_with_old() {
|
||||
let nodes: Vec<String> = (0..5).map(|n| format!("node{n}")).collect();
|
||||
|
||||
// Checkpoints every second on their own connection, as the server's
|
||||
// (and the old server's) thread does.
|
||||
// thread does.
|
||||
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let checkpoints = {
|
||||
let checkpointer = database.checkpointer().unwrap();
|
||||
@@ -932,7 +897,7 @@ fn compare_with_old() {
|
||||
let retention = start.elapsed().as_secs_f64() * 1000.0;
|
||||
|
||||
println!(
|
||||
"new {sync}: {count} pushes in {pushing:.1} s = {:.0}/s | file {:.0} MB | latest {latest:.3} ms | 1000 after {after:.3} ms ({read} read) | retention {deleted} in {retention:.0} ms",
|
||||
"{sync}: {count} pushes in {pushing:.1} s = {:.0}/s | file {:.0} MB | latest {latest:.3} ms | 1000 after {after:.3} ms ({read} read) | retention {deleted} in {retention:.0} ms",
|
||||
count as f64 / pushing,
|
||||
size as f64 / 1e6
|
||||
);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! `bakashrot`: pushes messages, reads them and their attachments, runs
|
||||
//! queries and lists names from the command line, connecting with a
|
||||
//! `client.toml`. The old `BakaShrot*` tools in one program; see
|
||||
//! `docs/client.md`, "The tools".
|
||||
//! `client.toml`; see `docs/client.md`, "The tools".
|
||||
|
||||
use bakashrot_client::{Client, Error, Settings};
|
||||
use bakashrot_proto::error::{code_name, is_refusal_code};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! `bakashrot` end to end against a server on a free port: the old suites'
|
||||
//! tool checks (GetMessages, Names, BigMessages).
|
||||
//! `bakashrot` end to end against a server on a free port: messages,
|
||||
//! pushes and refusals, big messages, attachments, queries, lists.
|
||||
|
||||
use bakashrot_client::{Client, Settings};
|
||||
use bakashrot_config::Config;
|
||||
|
||||
Reference in New Issue
Block a user