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
+3 -8
View File
@@ -5,16 +5,11 @@ from authenticated clients, store them in SQLite, and replicate them
between peers by name. Clients: a C DLL, CLI tools, a Python module. An between peers by name. Clients: a C DLL, CLI tools, a Python module. An
**internal tool on trusted machines**. **internal tool on trusted machines**.
**Rewritten in Rust** (since 2026-11-13): - `revamp.md`: what's decided, what's proposed and open, the plan and its
status. Read it first.
- `revamp.md`: why, what's decided, what's proposed and open, the plan and
its status. Read it first.
- The implementation is the Cargo workspace at the root (`readme.md`: - The implementation is the Cargo workspace at the root (`readme.md`:
layout, scripts, conventions; `docs/`: designs, `protocol.md` first, layout, scripts, conventions; `docs/`: designs, `protocol.md` first,
`known-issues.md` for what's left). `known-issues.md` for what's left).
- The old PureBasic implementation was removed on 2026-11-15: it's in git
history, `OldSource/` up to commit `68966a8`. Paths starting with
`OldSource/` in the code and docs point there.
## Toolchain ## Toolchain
@@ -30,7 +25,7 @@ between peers by name. Clients: a C DLL, CLI tools, a Python module. An
## Working rules ## Working rules
- **Commit only when the owner asks**, on a branch (`revamp`), not `master`. - **Commit only when the owner asks**, on a branch, not `master`.
- **Follow the plan's order** (`revamp.md`, "Plan"); a step is done when its - **Follow the plan's order** (`revamp.md`, "Plan"); a step is done when its
tests pass and its docs are updated, then its status goes in the table. tests pass and its docs are updated, then its status goes in the table.
- **Decisions go in `revamp.md`**: moved to "Decided" only when the owner - **Decisions go in `revamp.md`**: moved to "Decided" only when the owner
+2 -2
View File
@@ -1,7 +1,7 @@
# Runs the benchmarks, release mode: the tests ignored by default. # Runs the benchmarks, release mode: the tests ignored by default.
# push pushes through one server, 10 clients (end_to_end.rs, push_rate) # push pushes through one server, 10 clients (end_to_end.rs, push_rate)
# replication 4 servers in a Y, pushed to flat out (end_to_end.rs, replication_rate) # replication 4 servers in a Y, pushed to flat out (end_to_end.rs, replication_rate)
# storage the storage alone, the old storage's workload (storage.rs, compare_with_old) # storage the storage alone, pushes then reads (storage.rs, storage_rate)
# docs/server.md and docs/storage.md have the numbers measured so far. # docs/server.md and docs/storage.md have the numbers measured so far.
# Usage: powershell -ExecutionPolicy Bypass -File bench.ps1 [-Only push,replication,storage] [-Sync full|normal] # Usage: powershell -ExecutionPolicy Bypass -File bench.ps1 [-Only push,replication,storage] [-Sync full|normal]
# -Sync sets SQLite's synchronous for all of them (otherwise each one's # -Sync sets SQLite's synchronous for all of them (otherwise each one's
@@ -25,7 +25,7 @@ if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
$benches = [ordered]@{ $benches = [ordered]@{
push = @("bakashrot-server", "end_to_end", "push_rate") push = @("bakashrot-server", "end_to_end", "push_rate")
replication = @("bakashrot-server", "end_to_end", "replication_rate") replication = @("bakashrot-server", "end_to_end", "replication_rate")
storage = @("bakashrot-storage", "storage", "compare_with_old") storage = @("bakashrot-storage", "storage", "storage_rate")
} }
$oldSync = $env:SYNC $oldSync = $env:SYNC
@@ -34,16 +34,8 @@
; call, BakaShrot_GetLastError() tells why: the codes and what to do about ; call, BakaShrot_GetLastError() tells why: the codes and what to do about
; each are in BakaShrot_ErrorCodes.pbi, next to this file (included below), ; each are in BakaShrot_ErrorCodes.pbi, next to this file (included below),
; BakaShrot_ErrorName() names them; BakaShrot_GetRefusalReasonString() says ; BakaShrot_ErrorName() names them; BakaShrot_GetRefusalReasonString() says
; why in words. ; why in words. _GetNamesList() is
; ; {"kind":"topic","names":[...],"truncated":false}.
; Changed from the PureBasic DLL (protocol 6): certificates instead of keys
; and a node (BakaShrot_SetCaCertificate(), _SetCertificate(),
; _SetPrivateKey() now a PEM key, _SetCrl()); a push always names its topic
; (BakaShrot_PushMessage() is gone); no ids (_GetLatestMessage(TopicId,
; NodeId), _SetNodeId(), _GetMessageTopicId/NodeId(), _ResolveTopic/Node(),
; _GetResolvedName() are gone); _GetNamesList() is
; {"kind":"topic","names":[...],"truncated":false}. New: _GetNode().
; Attachments: the same six as before, by names.
; ============================================================================ ; ============================================================================
XIncludeFile "BakaShrot_ErrorCodes.pbi" XIncludeFile "BakaShrot_ErrorCodes.pbi"
+1 -4
View File
@@ -17,7 +17,7 @@
; ;
; What BakaShrot_GetLastError() returns after a failed call of the client DLL ; What BakaShrot_GetLastError() returns after a failed call of the client DLL
; (bakashrot.dll), and the code a server sends with each refusal (protocol 7, ; (bakashrot.dll), and the code a server sends with each refusal (protocol 7,
; crates/bakashrot-proto/src/error.rs, the same numbers as protocol 6). ; crates/bakashrot-proto/src/error.rs).
; The Python client has them in bakashrot.ErrorCode. Shipped next to ; The Python client has them in bakashrot.ErrorCode. Shipped next to
; BakaShrot_Client_Prototypes.pbi, which includes it. ; BakaShrot_Client_Prototypes.pbi, which includes it.
; ;
@@ -58,8 +58,6 @@
; A message, attachment or query result over a limit, or an attachment ; A message, attachment or query result over a limit, or an attachment
; bigger than this server keeps. ; bigger than this server keeps.
#BakaShrot_Refused_TooBig = 5 #BakaShrot_Refused_TooBig = 5
; Protocol 6's (a push without a topic): never sent any more.
#BakaShrot_Refused_NoDefaultTopic = 6
; A request that doesn't fit: an attachment's parts not matching its size, ; A request that doesn't fit: an attachment's parts not matching its size,
; a part that doesn't exist... ; a part that doesn't exist...
#BakaShrot_Refused_InvalidRequest = 7 #BakaShrot_Refused_InvalidRequest = 7
@@ -117,7 +115,6 @@ Procedure.s BakaShrot_ErrorName(Code.l)
Case #BakaShrot_Refused_NotFound : ProcedureReturn "NotFound" Case #BakaShrot_Refused_NotFound : ProcedureReturn "NotFound"
Case #BakaShrot_Refused_NotReady : ProcedureReturn "NotReady" Case #BakaShrot_Refused_NotReady : ProcedureReturn "NotReady"
Case #BakaShrot_Refused_TooBig : ProcedureReturn "TooBig" Case #BakaShrot_Refused_TooBig : ProcedureReturn "TooBig"
Case #BakaShrot_Refused_NoDefaultTopic : ProcedureReturn "NoDefaultTopic"
Case #BakaShrot_Refused_InvalidRequest : ProcedureReturn "InvalidRequest" Case #BakaShrot_Refused_InvalidRequest : ProcedureReturn "InvalidRequest"
Case #BakaShrot_Refused_DataMismatch : ProcedureReturn "DataMismatch" Case #BakaShrot_Refused_DataMismatch : ProcedureReturn "DataMismatch"
Case #BakaShrot_Refused_QueryFailed : ProcedureReturn "QueryFailed" Case #BakaShrot_Refused_QueryFailed : ProcedureReturn "QueryFailed"
-1
View File
@@ -83,7 +83,6 @@ class ErrorCode(enum.IntEnum):
NOT_FOUND = 3 # no such message or attachment NOT_FOUND = 3 # no such message or attachment
NOT_READY = 4 # the attachment isn't on this server yet: retry later NOT_READY = 4 # the attachment isn't on this server yet: retry later
TOO_BIG = 5 # over a limit, or more than this server keeps TOO_BIG = 5 # over a limit, or more than this server keeps
NO_DEFAULT_TOPIC = 6 # protocol 6's, never sent any more
INVALID_REQUEST = 7 # a request that doesn't fit (parts out of order...) INVALID_REQUEST = 7 # a request that doesn't fit (parts out of order...)
DATA_MISMATCH = 8 # an upload that doesn't match its SHA-256 DATA_MISMATCH = 8 # an upload that doesn't match its SHA-256
QUERY_FAILED = 9 # the SQL failed QUERY_FAILED = 9 # the SQL failed
+1 -1
View File
@@ -3,7 +3,7 @@
//! Python (ctypes) and anything that loads a DLL. `docs/client.md` //! Python (ctypes) and anything that loads a DLL. `docs/client.md`
//! has the whole API; `bindings/c/bakashrot.h` is generated from this file. //! 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 //! - **One connection per process:** set the certificates, connect, send
//! requests, one at a time (calls from several threads wait for each //! requests, one at a time (calls from several threads wait for each
+3 -1
View File
@@ -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 # 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: # optional: an empty list allows nothing. The topics are only named here:
# one exists from its first message, pushed (push_topics) or replicated # 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] [roles.sensor]
push_topics = ["sensors.*"] # always as its own node (its name) push_topics = ["sensors.*"] # always as its own node (its name)
-6
View File
@@ -235,12 +235,6 @@ fn refusals() {
("", "missing field `server`"), ("", "missing field `server`"),
(&with("lsiten = \"x\"\n"), "unknown field `lsiten`"), (&with("lsiten = \"x\"\n"), "unknown field `lsiten`"),
(&with("[other]\n"), "unknown field `other`"), (&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"), &with("[roles.sensor]\ndefault_topic = \"x\"\n"),
"unknown field `default_topic`", "unknown field `default_topic`",
+6 -7
View File
@@ -1,15 +1,14 @@
//! The error codes: what a server sends with each refusal (1-99, in a //! 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 //! `RequestRefused`), and the client's own (100 and up, what the DLL's
//! `BakaShrot_GetLastError()` returns). The same numbers as protocol 6 //! `BakaShrot_GetLastError()` returns). Never renumber one, only add new
//! (`OldSource/Client/BakaShrot_ErrorCodes.pbi`): never renumber one, only //! ones; 6 is retired, never reuse it.
//! add new ones.
//! //!
//! What to do about each: //! What to do about each:
//! - reconnect, then retry: `NotConnected`, `ConnectFailed`, //! - reconnect, then retry: `NotConnected`, `ConnectFailed`,
//! `ConnectionLost`, `ProtocolError` (the connection is closed); //! `ConnectionLost`, `ProtocolError` (the connection is closed);
//! - retry later: `NotReady`, `ServerError`; //! - retry later: `NotReady`, `ServerError`;
//! - fix the configuration: `AuthRejected`, `ServerNotVerified`, //! - fix the configuration: `AuthRejected`, `ServerNotVerified`,
//! `NotAllowed`, `UnknownName`, `NoDefaultTopic`; //! `NotAllowed`, `UnknownName`;
//! - update one end: `VersionMismatch`; //! - update one end: `VersionMismatch`;
//! - fix the call: `InvalidArgument`, `InvalidRequest`, `TooBig`, //! - fix the call: `InvalidArgument`, `InvalidRequest`, `TooBig`,
//! `QueryFailed`, `FileError`; //! `QueryFailed`, `FileError`;
@@ -71,7 +70,6 @@ error_codes! {
NotFound = 3, "No such message or attachment."; NotFound = 3, "No such message or attachment.";
NotReady = 4, "The attachment isn't on this server yet (still being replicated)."; 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."; 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..."; 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."; 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)."; QueryFailed = 9, "The SQL of a query failed (its error in the reason).";
@@ -131,14 +129,13 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn the_numbers_of_protocol_6() { fn the_numbers_never_change() {
let expected: &[(u32, &str)] = &[ let expected: &[(u32, &str)] = &[
(1, "NotAllowed"), (1, "NotAllowed"),
(2, "UnknownName"), (2, "UnknownName"),
(3, "NotFound"), (3, "NotFound"),
(4, "NotReady"), (4, "NotReady"),
(5, "TooBig"), (5, "TooBig"),
(6, "NoDefaultTopic"),
(7, "InvalidRequest"), (7, "InvalidRequest"),
(8, "DataMismatch"), (8, "DataMismatch"),
(9, "QueryFailed"), (9, "QueryFailed"),
@@ -164,6 +161,8 @@ mod tests {
assert_eq!(known.is_refusal(), *code < 100); assert_eq!(known.is_refusal(), *code < 100);
assert!(!known.description().is_empty()); assert!(!known.description().is_empty());
} }
// Retired: never given to another code.
assert_eq!(ErrorCode::from_code(6), None);
} }
#[test] #[test]
+2 -2
View File
@@ -4,8 +4,8 @@
//! waiting for the rest. An empty one is too (as a frame here, as a packet //! waiting for the rest. An empty one is too (as a frame here, as a packet
//! that doesn't decode with [`codec()`]). //! that doesn't decode with [`codec()`]).
//! //!
//! Over TLS, which takes care of the encryption: unlike protocol 6, frames //! Over TLS, which takes care of the encryption: frames carry packets as
//! carry packets as they are. //! they are.
//! //!
//! Before any frame, right after TLS, each end sends its protocol version //! Before any frame, right after TLS, each end sends its protocol version
//! (4 bytes, little-endian) and reads the other's: [`write_version()`], //! (4 bytes, little-endian) and reads the other's: [`write_version()`],
+1 -1
View File
@@ -6,7 +6,7 @@
//! through `serde` and `rmp-serde`. //! through `serde` and `rmp-serde`.
//! //!
//! - [`limits`]: the protocol's numbers (sizes, counts, the version). //! - [`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. //! - [`names`]: topic and node names, wildcards.
//! - [`frame`]: frames, a 4-byte size then a packet. //! - [`frame`]: frames, a 4-byte size then a packet.
//! - [`packets`]: every packet, and [`Packet`] to encode and decode them. //! - [`packets`]: every packet, and [`Packet`] to encode and decode them.
+1 -2
View File
@@ -4,8 +4,7 @@
/// The protocol's version. Both ends must have the same: they tell each /// The protocol's version. Both ends must have the same: they tell each
/// other first thing (`frame::write_version()`), and abandon the /// other first thing (`frame::write_version()`), and abandon the
/// connection if it differs. 6 was the last PureBasic one (`OldSource/`); /// connection if it differs.
/// 7 runs over TLS.
pub const PROTOCOL_VERSION: u32 = 7; pub const PROTOCOL_VERSION: u32 = 7;
/// The ALPN protocol name both ends offer during the TLS handshake: what /// The ALPN protocol name both ends offer during the TLS handshake: what
+1 -2
View File
@@ -1,5 +1,4 @@
//! Topic and node names, and wildcards: the rules of protocol 6 //! Topic and node names, and wildcards.
//! (`OldSource/Commons/Networking/Names.pbi`), without its ids.
//! //!
//! Topics and nodes go by name everywhere on the wire: a server's ids for //! Topics and nodes go by name everywhere on the wire: a server's ids for
//! them are its own business, in its database. //! them are its own business, in its database.
+1 -2
View File
@@ -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) // 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 // and ids (the versions are checked before any packet).
// checked before any packet).
macro_rules! packets { macro_rules! packets {
($( $(#[$doc:meta])* $name:ident = $id:literal, )*) => { ($( $(#[$doc:meta])* $name:ident = $id:literal, )*) => {
/// The type of a packet: its first value. /// The type of a packet: its first value.
@@ -1,8 +1,7 @@
//! Replication, between servers: at each check-in a peer (P) asks the //! 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, //! server (S) what it takes and has, then sends what it's missing,
//! messages first, then attachments (`OldSource/Design/Packets.md`, //! messages first, then attachments. Servers only ever send each other
//! "Replication"). Servers only ever send each other names: each has its //! names: each has its own ids.
//! own ids.
use super::rules; use super::rules;
use super::{Attachment, Check, DecodeError}; use super::{Attachment, Check, DecodeError};
+66 -3
View File
@@ -12,7 +12,46 @@ use bakashrot_proto::packets::{
use bakashrot_proto::{ErrorCode, Packet}; use bakashrot_proto::{ErrorCode, Packet};
use bakashrot_storage::AttachmentState; use bakashrot_storage::AttachmentState;
use std::net::IpAddr; 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 /// Whether `address` is in `accept_from`: `*`, an address as written, or
/// a hostname resolving to it (looked up now). /// a hostname resolving to it (looked up now).
@@ -152,6 +191,16 @@ pub(crate) async fn replicate_attachment(
return Ok(refusal); return Ok(refusal);
} }
let message = format!("{}:{}#{}", request.topic, request.node, request.message_id); 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 { let ReplicateAttachment {
topic, topic,
node, node,
@@ -175,8 +224,22 @@ pub(crate) async fn replicate_attachment(
size: stored.size, size: stored.size,
sha256: stored.sha256, sha256: stored.sha256,
}; };
let next = stored.received / ATTACHMENT_PART_SIZE; // Every part came but nobody is checking them (finishing it failed):
if from_part != next || stored.received == stored.size { // 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( return Ok(refused(
ErrorCode::InvalidRequest, ErrorCode::InvalidRequest,
format!("{message}: part {next} is the next one here, not {from_part}"), 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::ErrorCode;
use bakashrot_proto::packets::RequestRefused; use bakashrot_proto::packets::RequestRefused;
use bakashrot_storage::{Database, QueryRunner, Reader}; use bakashrot_storage::{Database, QueryRunner, Reader};
use std::collections::HashSet;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::Path; use std::path::Path;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@@ -66,6 +67,9 @@ struct Shared {
readers: Mutex<Vec<Reader>>, readers: Mutex<Vec<Reader>>,
/// Query connections not in use. /// Query connections not in use.
queries: Mutex<Vec<QueryRunner>>, 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 { impl Server {
@@ -108,6 +112,7 @@ impl Server {
pushes, pushes,
readers: Mutex::new(Vec::new()), readers: Mutex::new(Vec::new()),
queries: Mutex::new(Vec::new()), queries: Mutex::new(Vec::new()),
receiving: Mutex::new(HashSet::new()),
config, config,
}), }),
}) })
@@ -253,7 +258,7 @@ impl Shared {
/// Checkpoints the WAL every second, on a thread and a connection of its /// 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 /// 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> { fn start_checkpoints(database: &Database) -> Result<(), String> {
let checkpointer = database.checkpointer().map_err(|error| error.to_string())?; let checkpointer = database.checkpointer().map_err(|error| error.to_string())?;
std::thread::Builder::new() 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() messages.messages.iter().map(|message| message.id).collect()
} }
/// `OldSource/Tests/GetMessages-Test.ps1`, the server's part (the tool's /// Runs of messages: after an id, limits, `more`, the latest.
/// is step 8).
#[test] #[test]
fn runs_of_messages() { fn runs_of_messages() {
let running = Running::start("runs"); let running = Running::start("runs");
@@ -515,8 +514,7 @@ fn runs_of_messages() {
assert_eq!(run(&mut kitchen, None, 1).messages[0].data, text); assert_eq!(run(&mut kitchen, None, 1).messages[0].data, text);
} }
/// `OldSource/Tests/BigMessages-Test.ps1`, one server's part (replicating /// Big messages: up to the limit, answers split at about 1 MB.
/// them is step 11): up to the limit, answers split at about 1 MB.
#[test] #[test]
fn big_messages() { fn big_messages() {
let running = Running::start("big"); 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] #[test]
fn queries() { fn queries() {
let running = Running::start("queries"); let running = Running::start("queries");
@@ -1157,8 +1155,7 @@ fn retention() {
assert_eq!(latest.messages[0].id, 4); assert_eq!(latest.messages[0].id, 4);
} }
/// Replication flat out, as the old `Tests/Bench/Bench-Replication.ps1` /// Replication flat out: 4 servers in a Y (a hub pushing to 3
/// (`-Parts Ramp -Ramp 10x0`): 4 servers in a Y (a hub pushing to 3
/// leaves, each pushing to the hub), `NODES` nodes (10) pushing to each /// 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 /// 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 /// each server is and how long until every one has every message. Run
@@ -1582,3 +1579,140 @@ fn replication_edges() {
}); });
other.refused(ErrorCode::NotAllowed); 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);
}
-12
View File
@@ -36,18 +36,6 @@ impl Writer {
batch.transaction.commit()?; batch.transaction.commit()?;
Ok(value) 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 /// What's written in one transaction ([`Writer::batch`]). Names come
+5 -20
View File
@@ -28,8 +28,7 @@ const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
pub const WRITER_CHECKPOINT_PAGES: u32 = 10_000; pub const WRITER_CHECKPOINT_PAGES: u32 = 10_000;
/// Copies the WAL into the database on a connection of its own, so the /// 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: /// writer doesn't do it in the middle of a commit.
/// `OldSource/Server/Storage/Writer.pbi`).
#[derive(Debug)] #[derive(Debug)]
pub struct Checkpointer { pub struct Checkpointer {
connection: Connection, connection: Connection,
@@ -74,7 +73,10 @@ impl Database {
[concat!("bakashrot-storage ", env!("CARGO_PKG_VERSION"))], [concat!("bakashrot-storage ", env!("CARGO_PKG_VERSION"))],
)?; )?;
} else if application_id != APPLICATION_ID { } 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)?; let mut version = schema_version(&transaction)?;
if version > SCHEMA_VERSION { 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())) 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())
})
}
+1 -2
View File
@@ -4,8 +4,7 @@
//! and hands out connections. //! and hands out connections.
//! - [`Writer`]: the one connection that writes. Everything is written in //! - [`Writer`]: the one connection that writes. Everything is written in
//! a [`Batch`], one transaction: pushes, replication, attachments, //! a [`Batch`], one transaction: pushes, replication, attachments,
//! retention. Many pushes in one batch is a group commit. And //! retention. Many pushes in one batch is a group commit.
//! [`Writer::vacuum`], to shrink the file.
//! - [`Reader`]: as many as needed, reading while the writer writes (WAL). //! - [`Reader`]: as many as needed, reading while the writer writes (WAL).
//! - [`QueryRunner`]: clients' read-only SQL, on a read-only connection. //! - [`QueryRunner`]: clients' read-only SQL, on a read-only connection.
//! //!
+4 -4
View File
@@ -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 //! Read-only three ways: the connection has `query_only` on (SQLite
//! refuses any write), the statement must be one SQLite says only reads //! 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 //! error, not ignored). PRAGMAs are refused as they're prepared
//! (`Database::query_runner`'s authorizer): some would change the //! (`Database::query_runner`'s authorizer): some would change the
//! connection, `query_only` included, before the statement is looked //! connection, `query_only` included, before the statement is looked
//! at. The result is JSON, every value a string or null //! at. The result is JSON, every value a string or null:
//! (as in protocol 6): `{"columns":[...],"rows":[[...],...]}`. //! `{"columns":[...],"rows":[[...],...]}`.
use crate::{Error, Result}; use crate::{Error, Result};
use bakashrot_proto::limits::MAX_MESSAGE_SIZE; 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 { fn explain(why: String) -> String {
if why.contains("malformed JSON") { if why.contains("malformed JSON") {
format!("{why} (a row isn't JSON: add is_json = 1 to the WHERE)") format!("{why} (a row isn't JSON: add is_json = 1 to the WHERE)")
+8 -2
View File
@@ -190,17 +190,23 @@ impl Reader {
pub fn missing_attachments(&self, limit: usize) -> Result<Vec<MissingAttachment>> { pub fn missing_attachments(&self, limit: usize) -> Result<Vec<MissingAttachment>> {
self.connection self.connection
.prepare_cached( .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 data d ON d.key = a.message_key \
JOIN streams s ON s.stream_id = d.stream_id \ JOIN streams s ON s.stream_id = d.stream_id \
WHERE a.state = 'replicating' ORDER BY a.attachment_id LIMIT ?1", WHERE a.state = 'replicating' ORDER BY a.attachment_id LIMIT ?1",
)? )?
.query_map([limit as i64], |row| { .query_map([limit as i64], |row| {
let (received, size): (u64, u64) = (row.get(3)?, row.get(4)?);
Ok(MissingAttachment { Ok(MissingAttachment {
topic: row.get(0)?, topic: row.get(0)?,
node: row.get(1)?, node: row.get(1)?,
message_id: row.get(2)?, 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<_>>() .collect::<rusqlite::Result<_>>()
+1 -3
View File
@@ -2,8 +2,6 @@
-- keys below are packed integers, on purpose, and only bakashrot-storage -- keys below are packed integers, on purpose, and only bakashrot-storage
-- packs and unpacks them. -- 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. -- Needs SQLite 3.38+ (JSON functions, ->>), bundled with the crate.
-- --
-- Run once, in one transaction, on an empty database (Database::open). -- 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 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; 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 -- for all, in its one row, open browse_messages. Never written by the
-- server. -- server.
CREATE TABLE browse ( CREATE TABLE browse (
+5 -40
View File
@@ -84,10 +84,6 @@ fn refused_databases() {
} }
}; };
refused("CREATE TABLE other (x);", "not a BakaShrot database"); 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( refused(
"PRAGMA application_id = 1112754260; CREATE TABLE x (y);", "PRAGMA application_id = 1112754260; CREATE TABLE x (y);",
"without its schema version", "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] #[test]
fn limits() { fn limits() {
let (database, path) = open("limits"); let (database, path) = open("limits");
@@ -829,8 +795,7 @@ fn readers_while_writing() {
assert_eq!(reader.last_id("logs", "garage").unwrap(), 2000); assert_eq!(reader.last_id("logs", "garage").unwrap(), 2000);
} }
/// The same workload as the old storage's benchmark /// The storage alone, flat out (`docs/storage.md`, "The benchmark"): pushes
/// (`OldSource\Build\Bench\StorageBenchOld.exe`), to compare them: pushes
/// over 100 topics x 5 nodes (an LCG picks them), 100 per batch, 200-byte /// 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 /// 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 /// 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`. /// bakashrot-storage -- --ignored --nocapture`.
#[test] #[test]
#[ignore] #[ignore]
fn compare_with_old() { fn storage_rate() {
use std::time::Instant; use std::time::Instant;
let count: u64 = std::env::var("PUSHES").map_or(1_000_000, |n| n.parse().unwrap()); 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()); let sync = std::env::var("SYNC").unwrap_or_else(|_| "normal".into());
@@ -847,7 +812,7 @@ fn compare_with_old() {
} else { } else {
Synchronous::Normal Synchronous::Normal
}; };
let path = path("compare"); let path = path("rate");
let database = Database::open(&path, synchronous).unwrap(); let database = Database::open(&path, synchronous).unwrap();
let mut writer = database.writer().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(); let nodes: Vec<String> = (0..5).map(|n| format!("node{n}")).collect();
// Checkpoints every second on their own connection, as the server's // 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 stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let checkpoints = { let checkpoints = {
let checkpointer = database.checkpointer().unwrap(); let checkpointer = database.checkpointer().unwrap();
@@ -932,7 +897,7 @@ fn compare_with_old() {
let retention = start.elapsed().as_secs_f64() * 1000.0; let retention = start.elapsed().as_secs_f64() * 1000.0;
println!( 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, count as f64 / pushing,
size as f64 / 1e6 size as f64 / 1e6
); );
+1 -2
View File
@@ -1,7 +1,6 @@
//! `bakashrot`: pushes messages, reads them and their attachments, runs //! `bakashrot`: pushes messages, reads them and their attachments, runs
//! queries and lists names from the command line, connecting with a //! queries and lists names from the command line, connecting with a
//! `client.toml`. The old `BakaShrot*` tools in one program; see //! `client.toml`; see `docs/client.md`, "The tools".
//! `docs/client.md`, "The tools".
use bakashrot_client::{Client, Error, Settings}; use bakashrot_client::{Client, Error, Settings};
use bakashrot_proto::error::{code_name, is_refusal_code}; use bakashrot_proto::error::{code_name, is_refusal_code};
+2 -2
View File
@@ -1,5 +1,5 @@
//! `bakashrot` end to end against a server on a free port: the old suites' //! `bakashrot` end to end against a server on a free port: messages,
//! tool checks (GetMessages, Names, BigMessages). //! pushes and refusals, big messages, attachments, queries, lists.
use bakashrot_client::{Client, Settings}; use bakashrot_client::{Client, Settings};
use bakashrot_config::Config; use bakashrot_config::Config;
+1 -3
View File
@@ -29,9 +29,7 @@ is a CRL file from the CA, pushed to the servers.
only digits), 64 roles at most. Roles mean nothing to the certificates: only digits), 64 roles at most. Roles mean nothing to the certificates:
the server's config says what each may do. the server's config says what each may do.
- **Its OID is `1.3.6.1.4.1.67681.1.1`** (`IDENTITY_OID`), under - **Its OID is `1.3.6.1.4.1.67681.1.1`** (`IDENTITY_OID`), under
NibblePoker's own PEN (67681), since 0.3.0. Certificates made before NibblePoker's own PEN (67681). The branches: `oid.md`.
(a placeholder OID) aren't read: issue them again. The branches:
`oid.md`.
- **The CN is the name too**, for people (`openssl x509 -text`, logs). Only - **The CN is the name too**, for people (`openssl x509 -text`, logs). Only
the extension is trusted. the extension is trusted.
- **Clients' certificates** are for `clientAuth`. **Servers'** are for - **Clients' certificates** are for `clientAuth`. **Servers'** are for
+13 -35
View File
@@ -5,9 +5,9 @@ What apps connect with, in layers:
| Layer | Where | For | | Layer | Where | For |
|---|---|---| |---|---|---|
| `bakashrot-client` | `crates/bakashrot-client` | Rust: blocking, one connection per `Client` | | `bakashrot-client` | `crates/bakashrot-client` | Rust: blocking, one connection per `Client` |
| The DLL | `crates/bakashrot-capi`: `bakashrot.dll`, `libbakashrot.so` | C and anything that loads a DLL: the old `BakaShrot_*` exports, one connection per process | | The DLL | `crates/bakashrot-capi`: `bakashrot.dll`, `libbakashrot.so` | C and anything that loads a DLL: the `BakaShrot_*` exports, one connection per process |
| C header | `bindings/c/bakashrot.h` | generated from the DLL (cbindgen) | | C header | `bindings/c/bakashrot.h` | generated from the DLL (cbindgen) |
| PureBasic | `bindings/purebasic/` | the prototypes and the error codes, as the old DLL's | | PureBasic | `bindings/purebasic/` | the prototypes and the error codes |
| Python | `bindings/python/bakashrot.py` | `Client` over the DLL (ctypes), standard library only | | Python | `bindings/python/bakashrot.py` | `Client` over the DLL (ctypes), standard library only |
| The tools | `crates/bakashrot-tools`: `bakashrot` | the command line, over `bakashrot-client` | | The tools | `crates/bakashrot-tools`: `bakashrot` | the command line, over `bakashrot-client` |
@@ -40,7 +40,7 @@ crl = "ca.crl" # optional; a file not there yet: none
## The DLL ## The DLL
The old DLL's conventions, kept: Its conventions:
- **One connection per process.** Calls from several threads wait for each - **One connection per process.** Calls from several threads wait for each
other. other.
@@ -82,25 +82,9 @@ The old DLL's conventions, kept:
The header has each one's comment. Every name starts with `BakaShrot_`. The header has each one's comment. Every name starts with `BakaShrot_`.
### Changed from the PureBasic DLL
- **Connecting:** certificates instead of keys and a node:
`SetCaCertificate`, `SetCertificate`, `SetCrl` are new, `SetPrivateKey`
takes a PEM key; `SetPublicKey`, `SetServerPublicKey`, `SetNode`,
`SetNodeId` are gone. `GetNode` is new (the node comes from the
certificate).
- **No default topic:** `PushMessage(Data)` is gone, `PushMessageTo` names
its topic.
- **Attachments:** the same six, by names.
- **No ids:** `GetLatestMessage(TopicId, NodeId)`, `GetMessageTopicId`,
`GetMessageNodeId`, `ResolveTopic`, `ResolveNode`, `GetResolvedName` are
gone; `GetNamesList` lists names.
- **The file:** `bakashrot.dll` (`libbakashrot.so`), no libsodium next to
it.
## Python ## Python
`bindings/python/bakashrot.py`, the old module adapted: `Client(server, ca, `bindings/python/bakashrot.py`: `Client(server, ca,
certificate, key, crl=None)` (PEM text or paths) or certificate, key, crl=None)` (PEM text or paths) or
`Client.from_file("client.toml")` (Python 3.11+, `tomllib`; the rest runs `Client.from_file("client.toml")` (Python 3.11+, `tomllib`; the rest runs
on 3.8), `client.node` once connected, `push(data, topic, on 3.8), `client.node` once connected, `push(data, topic,
@@ -118,15 +102,15 @@ wheel with the library in it (`pip install bakashrot-*.whl`, nothing else:
`bindings/purebasic/BakaShrot_Client_Prototypes.pbi` (with `bindings/purebasic/BakaShrot_Client_Prototypes.pbi` (with
`BakaShrot_ErrorCodes.pbi`): `BakaShrot_LoadClient("bakashrot.dll")`, then `BakaShrot_ErrorCodes.pbi`): `BakaShrot_LoadClient("bakashrot.dll")`, then
the `W` exports under the old names, `BakaShrot_*String()` helpers for the the `W` exports without their suffix, `BakaShrot_*String()` helpers for the
getters. Run directly, it's an example: `ClientExample <DllPath> <CaFile> getters. Run directly, it's an example: `ClientExample <DllPath> <CaFile>
<CertificateFile> <KeyFile> <Host> <Port>`, pushing a message and one <CertificateFile> <KeyFile> <Host> <Port>`, pushing a message and one
with an attachment, reading both back (checked by hand with 5.73 against with an attachment, reading both back (run by hand against a server;
a server; not in CI, which has no PureBasic). not in CI, which has no PureBasic).
## The tools ## The tools
`bakashrot`, the old `BakaShrot*` tools in one program (`bakashrot-cert`, `bakashrot`, one program to push, read, query and list (`bakashrot-cert`,
for the CA, is apart: `certificates.md`). Each command connects with for the CA, is apart: `certificates.md`). Each command connects with
`-c <file>` (`client.toml` by default), does one thing and exits: 0, 1 on a `-c <file>` (`client.toml` by default), does one thing and exits: 0, 1 on a
failure (why on stderr: `Refused by the server (NotAllowed): ...`, failure (why on stderr: `Refused by the server (NotAllowed): ...`,
@@ -158,14 +142,10 @@ bakashrot list nodes --json {"kind":"node","names":["kitchen"
- **Messages and SQL:** inline, `@file` or `-` (a UTF-8 BOM dropped). - **Messages and SQL:** inline, `@file` or `-` (a UTF-8 BOM dropped).
PowerShell before 7.3 drops the double quotes inside arguments: use a PowerShell before 7.3 drops the double quotes inside arguments: use a
file there. file there.
- **Changed from the old tools:** one program; `-c` instead of the last
argument, `client.toml` instead of `client.ini`; `push` names its topic;
names only (no ids in the output, `ResolveIds` gone); errors on stderr;
`GetAttachment` is the `attachment` command.
- **Speed** (release, a local server, 2026-11-14): a command takes about - **Speed** (release, a local server, 2026-11-14): a command takes about
11 ms, connecting included (the old tools 8 ms); `messages --limit 0` 11 ms, connecting included; `messages --limit 0`
writes 200,000 messages to a file in 0.26 s (Python's `iter_messages()`: writes 200,000 messages to a file in 0.26 s (Python's `iter_messages()`:
1.5 s). Against the old ones: `server.md`, "Measured". 1.5 s). More: `server.md`, "Measured".
## Tests ## Tests
@@ -176,12 +156,10 @@ bakashrot list nodes --json {"kind":"node","names":["kitchen"
unaligned), selecting messages, attachments (from a file and memory, unaligned), selecting messages, attachments (from a file and memory,
saved and loaded, the buffer, refused ones), every refusal and the saved and loaded, the buffer, refused ones), every refusal and the
client's own errors, closing, another identity. client's own errors, closing, another identity.
- `python.rs`: runs `bindings/python/check_bakashrot.py` (the old one, - `python.rs`: runs `bindings/python/check_bakashrot.py` on the DLL; skipped, saying so, without Python 3.11+.
ported: 52 checks) on the DLL; skipped, saying so, without Python 3.11+.
- `header.rs`: `bindings/c/bakashrot.h` matches the exports (rewritten - `header.rs`: `bindings/c/bakashrot.h` matches the exports (rewritten
when it doesn't: check it in). when it doesn't: check it in).
`crates/bakashrot-tools/tests/bakashrot.rs` runs the tool against a server: `crates/bakashrot-tools/tests/bakashrot.rs` runs the tool against a server:
the old GetMessages suite's checks (`--follow` too), the Names, messages (`--follow` too), pushes and refusals, big messages,
BigMessages and Attachments suites' tool checks, queries, lists, attachments, queries, lists, `client.toml`.
`client.toml`.
+3 -19
View File
@@ -15,7 +15,7 @@ Decided in `../revamp.md`, "Decided".
| `[replication]` | the servers it sends to and takes from, retry and sync pace, batch size | | `[replication]` | the servers it sends to and takes from, retry and sync pace, batch size |
| `[roles.<name>]` | what certificates with that role may do | | `[roles.<name>]` | what certificates with that role may do |
Unknown keys are refused, so a typo or a key of the old ini is caught. Unknown keys are refused, so a typo is caught.
## Who's who: certificates, then roles ## Who's who: certificates, then roles
@@ -100,27 +100,11 @@ file's order, else `"*"`'s line wherever it is; without any, it's kept
forever. Ages count from when a message was first pushed, on whichever forever. Ages count from when a message was first pushed, on whichever
server; each server has its own. server; each server has its own.
## What changed from the old ini
| Old (`OldSource/Server/Config/schema.ini`) | Now |
|---|---|
| `PrivateKey`, `[BakaShrot] Node` | `ca`, `certificate`, `key`: the node is the certificate's name |
| `[BakaShrot.Client.*]`: keys, `Node`, `Allow*` | `[roles.*]`, the node and roles from the certificate |
| `[BakaShrot.Peer.*]`: `Host`, `Port`, `Node`, `PublicKey`, topic and node lists | `[replication] push_to` and `accept_from` (addresses), the lists in the peer's roles |
| `ReplicatingTopics` | each peer role's `send_topics` / `accept_topics` |
| topic and node ids, pins, ranges, `[BakaShrot.Nodes]` | names only: ids are the database's |
| `DefaultTopic` | dropped: a push always names its topic |
| `Host` + `Port` | `listen` |
| seconds | durations (`"10s"`) |
| `NetThreadPoolSize` | gone (tokio) |
| `UploadTimeout` | gone: attachments are streamed in their push (protocol 7), nothing waits |
| `FULL` / `NORMAL` | `"full"` / `"normal"`; `off` still refused |
## Tests ## Tests
`crates/bakashrot-config/tests/config.rs`: the example, the defaults, `crates/bakashrot-config/tests/config.rs`: the example, the defaults,
every setting, retention's order, permissions (several roles, none known, every setting, retention's order, permissions (several roles, none known,
replication per role), the topic lists that are gone, paths from the config's replication per role), the topic lists that are gone, paths from the config's
folder, and the refusals, each with its line: TOML errors, unknown keys folder, and the refusals, each with its line: TOML errors, unknown keys,
(the old ini's too), every value that's wrong, names twice (without case), every value that's wrong, names twice (without case),
unquoted dotted names. unquoted dotted names.
+14 -21
View File
@@ -1,8 +1,7 @@
# Known issues and ideas # Known issues and ideas
What's still true of the PureBasic version's notes, for this one. That What's known to be wrong or missing, what's left as it is and why, and
version was removed on 2026-11-15; it's in git history up to commit ideas for later.
`68966a8` (`OldSource/Notes.md`, "Open items"; `OldSource/Design/`).
## Threat model ## Threat model
@@ -36,19 +35,27 @@ network**, not exposed to the internet. So:
- **The attachments a server lacks:** it reports the 256 oldest at a - **The attachments a server lacks:** it reports the 256 oldest at a
time (`SyncState`). With several peers, ones none of them has can hold time (`SyncState`). With several peers, ones none of them has can hold
back newer ones. back newer ones.
- **Peers are trusted with what they replicate** (old item 12): a server - **Peers are trusted with what they replicate:** a server
in `accept_from` can send any message its roles accept, for any node. in `accept_from` can send any message its roles accept, for any node.
Messages carry no proof of who first wrote them. Fix: sign each message Messages carry no proof of who first wrote them. Fix: sign each message
with its node's key when first stored, check it on replication (every with its node's key when first stored, check it on replication (every
server then needs every node's public key). server then needs every node's public key).
- **Private keys sit in PEM files**, readable by whoever can read them: on - **Private keys sit in PEM files**, readable by whoever can read them: on
trusted machines, file permissions are enough. trusted machines, file permissions are enough.
- **One connection per process in the DLL** (old item 10, `revamp.md`, - **One connection per process in the DLL** (`revamp.md`,
"Open questions"): a handle-based API for several. Polling rather than "Open questions"): a handle-based API for several. Polling rather than
pushed subscriptions; nothing reconnects by itself, on purpose. pushed subscriptions; nothing reconnects by itself, on purpose.
- **At least once:** a push whose answer was lost (the server stopped - **At least once:** a push whose answer was lost (the server stopped
between committing and answering) is stored twice if retried. A client between committing and answering) is stored twice if retried. A client
that minds reads the latest message before retrying. that minds reads the latest message before retrying.
- **1,048,575 topic and node pairs per database** (2^20 - 1,
`MAX_STREAMS`, `bakashrot-storage/src/lib.rs`), for all topics
together, and 2^43 - 1 message ids per pair (`MAX_MESSAGE_ID`): the
20 and 43 bits of a message's packed key (`storage.md`, "Keys"). Past
the first, a new pair is refused from anyone, pushed or replicated;
pairs aren't freed when their messages are deleted. Enough for now
(the owner, 2026-11-16). Raising it means another key layout, so a
new schema version.
## Found by reading the code, not reproduced ## Found by reading the code, not reproduced
@@ -73,20 +80,7 @@ Reproduce one before fixing it, and move it up (or drop it) once known.
the example config says so by `max_attachment_size` (1 GiB by the example config says so by `max_attachment_size` (1 GiB by
default). Fix if needed: a wait scaled to the parts already received, default). Fix if needed: a wait scaled to the parts already received,
or the hash's state kept with the attachment. or the hash's state kept with the attachment.
- **Two peers sending the same attachment at once.** Both can be - **`SyncState` in one packet.** Every head the peer may
answered `Continue` for the same `from_part` (the check and the first
part written aren't one step). Their parts then interleave in the
writer's queue: each part is stored once, from whichever came first,
and each sender has one refused (`InvalidRequest`). With few parts (4
or fewer in flight, `PARTS_IN_FLIGHT`), all of them can be stored
while both senders were refused: neither sends `FinishReplicated`,
and the attachment stays `replicating` with `received = size`, asked
for and refused at every check-in until a restart (`clean_up` starts
it over). Needs two parts at least and a narrow timing: servers that
take from two others having the same attachment. Fix: finish it
whenever the last part is stored, or one receiver at a time per
attachment.
- **`SyncState` in one packet** (old item 9). Every head the peer may
send goes in one frame of 16 MiB at most: with very many topic and send goes in one frame of 16 MiB at most: with very many topic and
node pairs (hundreds of thousands) it doesn't fit, the packet can't node pairs (hundreds of thousands) it doesn't fit, the packet can't
be sent and replication stops. Fix: heads in several packets, or only be sent and replication stops. Fix: heads in several packets, or only
@@ -144,8 +138,7 @@ Reproduce one before fixing it, and move it up (or drop it) once known.
## Ideas for later ## Ideas for later
From the old benchmarks and suggestions (`OldSource/Design/Suggestions.md`), Worth it only when a use calls for them:
worth it only when a use calls for them:
- **Several pushes in flight per connection.** One request at a time - **Several pushes in flight per connection.** One request at a time
(`protocol.md`, "Rules") caps a node at one push per round trip: (`protocol.md`, "Rules") caps a node at one push per round trip:
+1 -2
View File
@@ -6,8 +6,7 @@ machine, 2026-11-15, Windows): the outputs shown are what came back.
Get a release (CI's artifacts, or `release.ps1` / `python release.py`): Get a release (CI's artifacts, or `release.ps1` / `python release.py`):
the programs, `bakashrot.dll` / `libbakashrot.so`, the wheel, the the programs, `bakashrot.dll` / `libbakashrot.so`, the wheel, the
example configs. Certificates made before 0.3.0 had a placeholder example configs.
identity OID (`oid.md`) and aren't read any more: issue them again.
| Machine | What runs there | Files it gets | | Machine | What runs there | Files it gets |
|---|---|---| |---|---|---|
+1 -13
View File
@@ -1,7 +1,6 @@
# The identity extension's OID # The identity extension's OID
`IDENTITY_OID = 1.3.6.1.4.1.67681.1.1` (`crates/bakashrot-pki/src/lib.rs`), `IDENTITY_OID = 1.3.6.1.4.1.67681.1.1` (`crates/bakashrot-pki/src/lib.rs`).
since 0.3.0 (2026-11-16).
## The branches ## The branches
@@ -29,17 +28,6 @@ Within a deployment, only the CA's certificates are read, so another
extension using the same OID somewhere else can't confuse a server. The OID extension using the same OID somewhere else can't confuse a server. The OID
mostly needs to be stable, and properly ours. mostly needs to be stable, and properly ours.
## Before 0.3.0: a placeholder
Up to 0.2.0 the OID was `1.3.6.1.4.1.32473.1.1`, under PEN 32473, "Example
Enterprise Number for Documentation Use" (RFC 5612), and `bakashrot-cert`
warned whenever it made a certificate. **Those certificates aren't read
any more** ("no BakaShrot identity"): make the CA's again or keep it (a
CA has no identity extension), issue every server's and node's again.
`OldSource/`'s UUID arc (`2.25.2320...0981`) couldn't be used: `rcgen`
writes OID parts of 64 bits at most, a UUID is 128.
## Changing the registration ## Changing the registration
The registry lists the organization, the contact's name and the contact's The registry lists the organization, the contact's name and the contact's
+4 -36
View File
@@ -1,10 +1,7 @@
# Protocol 7 # Protocol 7
What goes over a connection between a client and a server, or two servers. What goes over a connection between a client and a server, or two servers.
The code is `crates/bakashrot-proto`; this describes it. Protocol 6, the The code is `crates/bakashrot-proto`; this describes it.
PureBasic one, is `OldSource/Design/Packets.md`: what the requests do is
mostly the same, the transport, the encoding and the packets themselves
were simplified (see the end).
**Status (2026-11-13):** packets, frames, names and error codes are written **Status (2026-11-13):** packets, frames, names and error codes are written
and tested (`bakashrot-proto`), so is the TLS setup (`bakashrot-pki`, and tested (`bakashrot-proto`), so is the TLS setup (`bakashrot-pki`,
@@ -123,6 +120,7 @@ An attachment C: GetAttachment(from_part) S: Attachment, then Attachme
Replicating P: SyncStateRequest S: SyncState Replicating P: SyncStateRequest S: SyncState
P: ReplicateMessages x the batches S: MessagePushed each / RequestRefused P: ReplicateMessages x the batches S: MessagePushed each / RequestRefused
P: ReplicateAttachment x missing S: Continue / RequestRefused P: ReplicateAttachment x missing S: Continue / RequestRefused
(NotReady: another peer sending it)
P: AttachmentPart x from next_part S: MessagePushed / RequestRefused P: AttachmentPart x from next_part S: MessagePushed / RequestRefused
``` ```
@@ -141,8 +139,6 @@ Replicating P: SyncStateRequest S: SyncState
## Rules ## Rules
The same as protocol 6:
- **One request at a time:** a client sends one, waits for its answer (the - **One request at a time:** a client sends one, waits for its answer (the
parts of an attachment being part of its request or answer). parts of an attachment being part of its request or answer).
- **Refuse or abort:** valid but not allowed or not found (permissions, - **Refuse or abort:** valid but not allowed or not found (permissions,
@@ -152,33 +148,5 @@ The same as protocol 6:
to answers. to answers.
- **The identity is the connection's:** requests never say who sends them. - **The identity is the connection's:** requests never say who sends them.
A push picks its topic, never its node. A push picks its topic, never its node.
- **Error codes** (`error`): 1-99 refusals, 100+ the client's own; the - **Error codes** (`error`): 1-99 refusals, 100+ the client's own, never
numbers of protocol 6, never renumbered. renumbered.
## What changed from protocol 6
- **TLS** instead of the sealed Hello, the signed key exchange and the own
cipher: the handshake packets are gone, `Welcome` is new, the identity
comes from the certificate.
- **The version is checked once**, sent by both ends before anything else:
packets lost their magic and version.
- **Names only:** no ids on the wire, no refs. `ResolveName` /
`NameResolved` are gone, answers don't echo ids, `NamesList` is names,
`SyncState` gives its heads by name.
- **No default topic:** a push always names its topic, `Welcome` doesn't
give one (`NoDefaultTopic`, 6, is never sent).
- **Fewer packets, 26 → 18:** `GetMessages` with `after: nil` replaces
`GetLatestMessage`, `Messages` replaces `LatestMessage`; `SyncState`
lists the missing attachments (no `MissingAttachmentsRequest` /
`MissingAttachments`); answers don't echo what was asked.
- **Attachments are streamed in their request:** no upload ids, no uploads
waiting for their push (and no `UploadTimeout`), no request or answer per
part (`UploadStart`, `UploadStarted`, `UploadChunk`, `ChunkStored`,
`AttachmentChunk`, `ReplicateAttachmentChunk` are gone). An upload cut
short starts over (none resumed in protocol 6 either); reads and
replication go on `from_part`.
- **Encoding:** derived with `serde`, `[type, [fields...]]`, booleans and
nil where they belong (were 0/1 and empty values). Nothing may follow a
packet (was ignored).
- **No 4 KB limit before authentication:** TLS has authenticated both ends
before any frame.
+54 -57
View File
@@ -26,10 +26,9 @@ Decided 2026-11-14 (`../revamp.md`, "Operations"):
answered is stored, the ones after are refused (`ServerError`, "the answered is stored, the ones after are refused (`ServerError`, "the
server is stopping"), then it exits with 0. Nothing else to wait for: server is stopping"), then it exits with 0. Nothing else to wait for:
a client whose push wasn't answered pushes it again (at least once). a client whose push wasn't answered pushes it again (at least once).
- **No console commands** (the old `quit`, `restart`, `vacuum`, `names`, - **No console commands:** it needs no console, a service manager runs
`help`): it needs no console, a service manager runs it as is. `names` it as is. Listing names is `bakashrot list`, restarting a stop and a
is `bakashrot list`, `restart` a stop and a start. Maybe an admin start. Maybe an admin channel later.
channel later.
- **Logs go to the console** (stdout, `tracing`), without colours when - **Logs go to the console** (stdout, `tracing`), without colours when
it isn't a terminal: redirect them, or let systemd or Docker keep it isn't a terminal: redirect them, or let systemd or Docker keep
them. `BAKASHROT_LOG` sets the level: `error`, `warn`, `info` (the them. `BAKASHROT_LOG` sets the level: `error`, `warn`, `info` (the
@@ -128,7 +127,7 @@ otherwise:
part it needs. One it says doesn't match its SHA-256 is read back 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 here: damaged (a disk, a bug), this server's copy is dropped and asked
for again from its own peers (`replicating`, not served meanwhile), for again from its own peers (`replicating`, not served meanwhile),
instead of sent again at every check-in (the old open item 3). instead of sent again at every check-in.
**Receiving** (`accept_from.rs`): replication requests are answered only **Receiving** (`accept_from.rs`): replication requests are answered only
if the connection comes from `accept_from` (a hostname looked up at its if the connection comes from `accept_from` (a hostname looked up at its
@@ -142,8 +141,15 @@ needs, the parts it had read back for the SHA-256; matching, it's ready,
otherwise started over (`DataMismatch`). A stop between its last part otherwise started over (`DataMismatch`). A stop between its last part
and the check: started over at the next start. and the check: started over at the next start.
**One server per node** stays the config's rule, as in the old version - **One peer at a time per attachment** (2026-11-16): another asking for
(`known-issues.md`): a node pushing to two servers that replicate makes the same one meanwhile is refused (`NotReady`) and offers it again at
its next check-in. Two at once could both be refused a part while
every part got stored, the attachment left whole and never checked.
- **Never taken unchecked:** one whole but not checked (finishing it
failed) is listed in `SyncState` from its first part and started over
when a peer asks for it, warned in the log.
**One server per node** stays the config's rule (`known-issues.md`): a node pushing to two servers that replicate makes
the same ids with different messages, undetected. the same ids with different messages, undetected.
## A connection ## A connection
@@ -256,8 +262,8 @@ each, 200-byte JSON, 20,000 pushes per client.
a connection's revocation check stopped reading its certificate at a connection's revocation check stopped reading its certificate at
every request (its serial is read once, at connect). every request (its serial is read once, at connect).
- One client waits for each answer: a round trip and a commit per push. - One client waits for each answer: a round trip and a commit per push.
Through Python and the DLL, about 10,700 pushes/s (the old module did Through Python and the DLL, about 10,700 pushes/s, and 140,000
about 9,000), and 140,000 messages/s read. messages/s read.
- With `full`, every group commit waits for the disk's flush (about 1 ms - With `full`, every group commit waits for the disk's flush (about 1 ms
here): 10 clients make groups of about 10. More clients, bigger groups. here): 10 clients make groups of about 10. More clients, bigger groups.
- **Attachments** (release, the tool, `normal`): 200 MB up in 1.3 s and - **Attachments** (release, the tool, `normal`): 200 MB up in 1.3 s and
@@ -267,52 +273,47 @@ each, 200-byte JSON, 20,000 pushes per client.
against 39,800-40,400), `full` the same (the disk's), attachments and against 39,800-40,400), `full` the same (the disk's), attachments and
tool commands the same. The programs and the DLL 25-31% smaller. tool commands the same. The programs and the DLL 25-31% smaller.
### Against the old server (2026-11-14) ### Through the DLL, Python and the tools (2026-11-14)
The same work on the same machine, release builds, one server on Release builds, one server on localhost. Pushes and reads through
localhost: the old one (`OldSource/Build/Bench/BenchServer.exe`, its DLL, Python and the DLL (10 clients: 10 processes, the same node), 200-byte
`bakashrot.py` and tools) and this one. Pushes and reads through each one's
Python module and DLL (10 clients: 10 processes, the same node), 200-byte
JSON; the rest through the tools. JSON; the rest through the tools.
| | Old, `full` | New, `full` | Old, `normal` | New, `normal` | | | `full` | `normal` |
|---|---|---|---|---| |---|---|---|
| One tool command, connecting included | 8 ms | 12 ms | 8 ms | 11 ms | | One tool command, connecting included | 12 ms | 11 ms |
| Pushes, 1 client | 1,945/s | 1,954/s | 9,386/s | 11,600-13,100/s | | Pushes, 1 client | 1,954/s | 11,600-13,100/s |
| Pushes, 10 clients | 9,006/s | 10,072/s | 25,419/s | 56,200-64,300/s | | Pushes, 10 clients | 10,072/s | 56,200-64,300/s |
| Reads, Python | 76,466/s | 130,861/s | 77,526/s | 146,368/s | | Reads, Python | 130,861/s | 146,368/s |
| The tool writing 120,000 messages to a file | | | 45.5 s | 0.14 s | | The tool writing 120,000 messages to a file | | 0.14 s |
| A 200 MB attachment up, the tool | 3.49 s | 1.15 s | 2.84 s | 1.15 s | | A 200 MB attachment up, the tool | 1.15 s | 1.15 s |
| The same down | 1.57 s | 0.59 s | 1.62 s | 0.67 s | | The same down | 0.59 s | 0.67 s |
- **`full`, one client:** both wait for the disk's flush at every push. - **`full`, one client:** it waits for the disk's flush at every push.
- **A command:** the TLS handshake's P-384 signatures and checks, both - **A command:** the TLS handshake's P-384 signatures and checks, both
ends, cost about 7 ms against the old handshake's X25519; aws-lc's CPU ends, cost about 7 ms; aws-lc's CPU Jitter Entropy seeding cost 25 ms
Jitter Entropy seeding cost 25 ms more per process before it was turned more per process before it was turned off (`certificates.md`, "TLS").
off (`certificates.md`, "TLS").
- **The old tool's read** printed a line at a time to the console API.
### Replication, against the old server (2026-11-14) ### Replication (2026-11-14)
`replication_rate` (`tests/end_to_end.rs`, ignored by default) against `replication_rate` (`tests/end_to_end.rs`, ignored by default): 4
the old `Tests/Bench/Bench-Replication.ps1 -Parts Ramp -Ramp 10x0`: 4
servers in a Y (a hub sending to 3 leaves, each sending to the hub), 10 servers in a Y (a hub sending to 3 leaves, each sending to the hub), 10
nodes pushing to each as fast as they're answered for 30 s, 200-byte nodes pushing to each as fast as they're answered for 30 s, 200-byte
JSON, the same machine. The old one's pushers are its PureBasic bench JSON, the same machine, the pushers `bakashrot-client` threads in the
client, the new one's `bakashrot-client` threads in the test's process. test's process.
| | Old, `full` | New, `full` | Old, `normal` | New, `normal` | | | `full` | `normal` |
|---|---|---|---|---| |---|---|---|
| Pushes, all 4 servers | 16,638/s | 16,000-16,300/s | 33,895/s | 35,300-37,500/s | | Pushes, all 4 servers | 16,000-16,300/s | 35,300-37,500/s |
| Slowest push | 134 ms | 50-57 ms | 854 ms | 420-510 ms | | Slowest push | 50-57 ms | 420-510 ms |
| Behind when the pushes stop (most of a server) | 9.0 s of pushes | 0 | 11.4 s | 0.3-0.9 s | | Behind when the pushes stop (most of a server) | 0 | 0.3-0.9 s |
| Until every server has everything | 8.8 s | 0.3 s | 14.8 s | 5.3-5.6 s | | Until every server has everything | 0.3 s | 5.3-5.6 s |
- **Keeping up:** a link checks in again at once after sending; before - **Keeping up:** a link checks in again at once after sending; before
it waited `sync_interval` after every check-in, as the old one did, and it waited `sync_interval` after every check-in, and
pushes went faster (19,300/s `full`, 40,200/s `normal`) while the pushes went faster (19,300/s `full`, 40,200/s `normal`) while the
leaves fell 7-9 s behind and took 10-20 s to catch up. leaves fell 7-9 s behind and took 10-20 s to catch up.
- **`batch_size` 1000** (was 100, the old `PeerBatchSize`): `normal` went - **`batch_size` 1000** (was 100): `normal` went
from 27,500-31,500/s to 35,300-37,500/s, and from 2-2.5 s to under 1 s from 27,500-31,500/s to 35,300-37,500/s, and from 2-2.5 s to under 1 s
behind. Batches stay about 1 MiB at most. behind. Batches stay about 1 MiB at most.
- **The last few seconds** with `normal` are a link's `sync_interval`: - **The last few seconds** with `normal` are a link's `sync_interval`:
@@ -324,25 +325,21 @@ client, the new one's `bakashrot-client` threads in the test's process.
each: each:
- pushes and reads back (ids, data, times, another connection); - pushes and reads back (ids, data, times, another connection);
- runs of messages (`OldSource/Tests/GetMessages-Test.ps1`, the server's - runs of messages: from the start, after an id, with a limit, `more`, the last ones,
part): from the start, after an id, with a limit, `more`, the last ones,
nothing yet, unknown topics and nodes, names without case, data that nothing yet, unknown topics and nodes, names without case, data that
isn't one line of JSON; isn't one line of JSON;
- big messages (`BigMessages-Test.ps1`, one server's part): five of 600 KB - big messages: five of 600 KB and one of the largest size, one per answer, read back whole; one byte
and one of the largest size, one per answer, read back whole; one byte
over refused; a query result over 16 MB refused; over refused; a query result over 16 MB refused;
- names: topics by role, nodes; - names: topics by role, nodes;
- attachments (`Attachments-Test.ps1`, one server's part): 100 KB, 5 MB + - attachments: 100 KB, 5 MB + 123 bytes, exactly 2 MB, 1 byte, 1 MB, read back and saved; the
123 bytes, exactly 2 MB, 1 byte, 1 MB, read back and saved; the
messages saying theirs; none, or no such message, refused leaving no messages saying theirs; none, or no such message, refused leaving no
file; another reader, one not allowed; over the server's limit, 0 for file; another reader, one not allowed; over the server's limit, 0 for
none, empty; the parts stored; none, empty; the parts stored;
- attachment edges (`AttachmentEdges-Test.ps1`'s, through the client and - attachment edges (through the client and a raw connection): a source changed between its SHA-256 and its
a raw connection): a source changed between its SHA-256 and its
sending, one failing half-way (the connection closed, the upload sending, one failing half-way (the connection closed, the upload
dropped), a part of the wrong size, a wrong SHA-256, reading from a dropped), a part of the wrong size, a wrong SHA-256, reading from a
part on, something else than a part (closed, dropped); part on, something else than a part (closed, dropped);
- queries (`BigMessages-Test.ps1`'s): not allowed, results, a non-JSON row - queries: not allowed, results, a non-JSON row
refused with the hint, errors, writes and two statements refused; refused with the hint, errors, writes and two statements refused;
- refusals keeping the connection (not allowed, unknown topic, a bad name - refusals keeping the connection (not allowed, unknown topic, a bad name
the client catches); the client catches);
@@ -355,12 +352,9 @@ each:
- stopping cleanly: eight nodes pushing flat out, the server stopped - stopping cleanly: eight nodes pushing flat out, the server stopped
under them: every push answered is there after a restart, the ones under them: every push answered is there after a restart, the ones
after refused as `ServerError`; after refused as `ServerError`;
- retention (`Retention-Test.ps1`'s local part): a topic's messages and - retention: a topic's messages and their attachment deleted past its age, another topic kept forever, ids
their attachment deleted past its age, another topic kept forever, ids
going on, a younger message kept through a pass; going on, a younger message kept through a pass;
- replication (`Names-Test.ps1`'s replication, `Restart-Test.ps1`, - replication: three servers of one CA, a pushing to b and c. b gets every message by name with its id, time
`AttachmentEdges-Test.ps1`'s corruption): three servers of one CA, a
pushing to b and c. b gets every message by name with its id, time
and data, and the attachment; c, whose `accept_from` hasn't a, gets and data, and the attachment; c, whose `accept_from` hasn't a, gets
nothing; b's own pushes don't go to a. b stopped, a pushes meanwhile nothing; b's own pushes don't go to a. b stopped, a pushes meanwhile
and its copy of an attachment gets damaged; b started again on its and its copy of an attachment gets damaged; b started again on its
@@ -372,8 +366,11 @@ each:
first part going on from the second (the first read back for the first part going on from the second (the first read back for the
SHA-256), one not matching refused and asked for from the start, a SHA-256), one not matching refused and asked for from the start, a
certificate whose roles take nothing refused; certificate whose roles take nothing refused;
- two peers, one attachment (two raw connections): the second refused
while the first sends it (names in any case), the first finishing it;
one gone partway, the other going on from there; one whole but never
checked asked for from its first part and started over;
- `replication_rate`, ignored by default: the benchmark above (`SYNC`, - `replication_rate`, ignored by default: the benchmark above (`SYNC`,
`NODES`, `SECONDS`, `BATCH`). `NODES`, `SECONDS`, `BATCH`).
The old tests' tool parts (`--follow`, the output) are the tools' tests The tool's own (`--follow`, the output): `client.md`.
(`client.md`).
+40 -75
View File
@@ -5,9 +5,6 @@ The server's database: one SQLite file. The code is
`crates/bakashrot-storage/src/schema_v9.sql`, made in one go. Decided in `crates/bakashrot-storage/src/schema_v9.sql`, made in one go. Decided in
`../revamp.md`, "Decided" (2026-11-13). `../revamp.md`, "Decided" (2026-11-13).
**Not compatible with v8:** a database of the old server isn't opened
(refused at start, saying so); its data isn't carried over.
## In short ## In short
- **By name outside, packed integers inside.** The rest of the code (the - **By name outside, packed integers inside.** The rest of the code (the
@@ -17,7 +14,7 @@ The server's database: one SQLite file. The code is
and unpacks keys; the `messages` view shows plain columns. and unpacks keys; the `messages` view shows plain columns.
- **One B-tree per kind of data:** messages, attachment parts. A push - **One B-tree per kind of data:** messages, attachment parts. A push
writes its message's row and nothing else (no index): about 2.3 times writes its message's row and nothing else (no index): about 2.3 times
the pushes of v8's layout, 30% less disk (see "Measured"). the pushes of a layout with an index, 30% less disk (see "Measured").
- **One writer, many readers** (WAL). Writes go in batches, one - **One writer, many readers** (WAL). Writes go in batches, one
transaction each: a group commit. transaction each: a group commit.
@@ -65,8 +62,8 @@ attachment_parts.key = attachment_id << 20 | part
columns**: computed when read, never stored (a test checks the schema columns**: computed when read, never stored (a test checks the schema
unpacks keys as the code does). unpacks keys as the code does).
Why not v8's three columns with an index? A second B-tree to write at every Why no index? A second B-tree to write at every push, and reads going
push, and reads going through the index then to the row. Measured below. through the index then to the row. Measured below.
## Writing ## Writing
@@ -85,7 +82,6 @@ together, one disk flush for all.
| `damaged(id)` | a ready attachment found not matching its SHA-256: its parts dropped, asked for again (`replicating`) | | `damaged(id)` | a ready attachment found not matching its SHA-256: its parts dropped, asked for again (`replicating`) |
| `delete_before(topic, cutoff, limit)` | retention | | `delete_before(topic, cutoff, limit)` | retention |
| `purge_attachments(max_parts)` | deleted messages' attachments | | `purge_attachments(max_parts)` | deleted messages' attachments |
| `Writer::vacuum()` (outside a batch) | the file shrunk to what it holds: the old server's `vacuum` command |
| `Checkpointer::checkpoint()` (its own connection) | the WAL copied into the database, every second, off the writer's way | | `Checkpointer::checkpoint()` (its own connection) | the WAL copied into the database, every second, off the writer's way |
**SHA-256s are the caller's to check:** the server hashes the parts as they **SHA-256s are the caller's to check:** the server hashes the parts as they
@@ -108,8 +104,7 @@ read while the writer writes. Answers are the protocol's own types:
| `attachment(topic, node, id)`, `read_part(id, part)` | an attachment, its parts | the message's key; a part's key | | `attachment(topic, node, id)`, `read_part(id, part)` | an attachment, its parts | the message's key; a part's key |
A topic and node with no messages read as none, unless the node has none A topic and node with no messages read as none, unless the node has none
in any topic: `Error::UnknownName`, as the old server refused unknown in any topic: `Error::UnknownName`. A topic is never unknown: it's allowed or not, by the roles.
nodes. A topic is never unknown: it's allowed or not, by the roles.
## Attachments ## Attachments
@@ -148,7 +143,7 @@ connection's next queries (found 2026-11-15). The result is
`{"columns":[...],"rows":[[...]]}`, every value a string or null (blobs in `{"columns":[...],"rows":[[...]]}`, every value a string or null (blobs in
hex), 10,000 rows and 16 MB at most (`TooBig`). A failing row fails it all, hex), 10,000 rows and 16 MB at most (`TooBig`). A failing row fails it all,
with SQLite's message: never a partial result. "malformed JSON" (a JSON with SQLite's message: never a partial result. "malformed JSON" (a JSON
function on a row that isn't) gets the old server's hint: add function on a row that isn't) gets a hint: add
`is_json = 1` to the WHERE. `is_json = 1` to the WHERE.
The `messages` view, by name: The `messages` view, by name:
@@ -156,7 +151,7 @@ The `messages` view, by name:
| Column | | | Column | |
|---|---| |---|---|
| `topic`, `node` | names | | `topic`, `node` | names |
| `message_id`, `message_data`, `is_json`, `pushed_at`, `pushed_utc` | as in v8 | | `message_id`, `message_data`, `is_json`, `pushed_at`, `pushed_utc` | the message's |
| `attachment_size`, `attachment_state` | NULL without one | | `attachment_size`, `attachment_state` | NULL without one |
```sql ```sql
@@ -170,7 +165,7 @@ SELECT message_data ->> '$.temp' FROM messages WHERE topic = 'sensors' AND is_js
whole: a millisecond or two for 10,000 messages per stream, growing with whole: a millisecond or two for 10,000 messages per stream, growing with
them (see "Measured"). If that gets slow, a time index is one migration them (see "Measured"). If that gets slow, a time index is one migration
away ("For later"). away ("For later").
- `browse` / `browse_messages`: v8's, for database tools (set `browse`'s - `browse` / `browse_messages`: for database tools (set `browse`'s
one row, open the view); no dropdowns any more. one row, open the view); no dropdowns any more.
## The file ## The file
@@ -181,7 +176,7 @@ SELECT message_data ->> '$.temp' FROM messages WHERE topic = 'sensors' AND is_js
- **Opening** (`Database::open`): an empty file is made a v9 database; a - **Opening** (`Database::open`): an empty file is made a v9 database; a
v9 one is opened; an older one is migrated, a version at a time, each v9 one is opened; an older one is migrated, a version at a time, each
step one transaction that also sets `schema_version` (none yet); a newer step one transaction that also sets `schema_version` (none yet); a newer
one, the old server's, or another program's is refused, saying which. one or another program's is refused, saying which.
- Every connection: WAL, `synchronous` from the config (`full`: every - Every connection: WAL, `synchronous` from the config (`full`: every
commit flushed; `normal`: about once a second), a 5 s busy timeout. No commit flushed; `normal`: about once a second), a 5 s busy timeout. No
foreign keys: one writer keeps the tables consistent, `CHECK`s keep the foreign keys: one writer keeps the tables consistent, `CHECK`s keep the
@@ -195,75 +190,58 @@ Python's `sqlite3` (SQLite 3.50), 5,000,000 small JSON messages pushed to
500 streams (100 topics x 5 nodes) at random, 100 per transaction, WAL, 500 streams (100 topics x 5 nodes) at random, 100 per transaction, WAL,
`synchronous = NORMAL`, 16 MB page cache: `synchronous = NORMAL`, 16 MB page cache:
| | v9 (this) | v9 + a time index | the first draft (v8's layout) | | | v9 (this) | v9 + a time index |
|---|---|---|---| |---|---|---|
| Pushes/s | **23k** | 9-10k | 9k | | Pushes/s | **23k** | 9-10k |
| File | **330 MB** | 457 MB | 484 MB | | File | **330 MB** | 457 MB |
| Latest 100 of a stream | 0.05 ms | 0.05 ms | 0.19 ms | | Latest 100 of a stream | 0.05 ms | 0.05 ms |
| 1000 after an id | 0.53 ms | 0.53 ms | 3.04 ms | | 1000 after an id | 0.53 ms | 0.53 ms |
| Retention, 10% of a topic | 5.5 ms | 6.4 ms | 241 ms | | Retention, 10% of a topic | 5.5 ms | 6.4 ms |
| Query: a node's last hour | 1.65 ms | 0.90 ms | 3.29 ms | | Query: a node's last hour | 1.65 ms | 0.90 ms |
| Query: a topic's last hour | 8.4 ms | 4.7 ms | 16.0 ms | | Query: a topic's last hour | 8.4 ms | 4.7 ms |
- A push dirties its stream's page: with pushes spread over many streams, - A push dirties its stream's page: with pushes spread over many streams,
each costs about a page written to the WAL. Any index per stream (v8's, each costs about a page written to the WAL. Any index per stream (a
a time index) doubles that, and a bigger cache doesn't help (it's writes, time index) doubles that, and a bigger cache doesn't help (it's writes,
not reads). not reads).
- Bigger batches over fewer streams share pages: the server's group commit - Bigger batches over fewer streams share pages: the server's group commit
helps most when many pushes come at once. helps most when many pushes come at once.
### Against the old storage (2026-11-13) ### The benchmark (2026-11-13)
The same workload on both, each storage layer alone (no network): pushes `storage_rate` (`tests/storage.rs`, ignored by default:
over 500 streams picked at random, 100 per transaction, 200-byte JSON;
2000 latest-message reads; 500 reads of 1000 messages after a stream's
middle id; retention of 10% of one topic. The new side is
`compare_with_old` (`tests/storage.rs`, ignored by default:
`PUSHES=1000000 SYNC=normal cargo test --release -p bakashrot-storage -- `PUSHES=1000000 SYNC=normal cargo test --release -p bakashrot-storage --
--ignored --nocapture`, or `bench.ps1 -Only storage`). The old side --ignored --nocapture`, or `bench.ps1 -Only storage`): the storage layer
calls `OldSource`'s writer (`BakaShrot_Writer_WriteJobs()`, its group alone (no network), pushes over 500 streams picked at random, 100 per
commit, PureBasic 5.73, SQLite transaction, 200-byte JSON; 2000 latest-message reads; 500 reads of 1000
3.54.1 from `sqlite3.dll`), from a program built outside `OldSource`. messages after a stream's middle id; retention of 10% of one topic. NVMe,
Same machine, NVMe, one run each. one run each.
| | Old, 1M | New, 1M | Old, 1M `full` | New, 1M `full` | Old, 5M | New, 5M | | | 1M | 1M `full` | 5M |
|---|---|---|---|---|---|---| |---|---|---|---|
| Pushes/s, first | **25,874** | 13,803 | **19,976** | 13,205 | **19,558** | 12,184 | | Pushes/s | 37,332 | 29,952 | 29,363 |
| Pushes/s, step 5's writer | 25,874 | **37,332** | 19,976 | **29,952** | 19,558 | **29,363** | | File | 249 MB | 249 MB | 1,239 MB |
| File | 276 MB | 249 MB | 276 MB | 249 MB | 1,380 MB | 1,239 MB | | Latest message | 0.017 ms | 0.017 ms | 0.017 ms |
| Latest message | 0.013 ms | 0.017 ms | 0.013 ms | 0.017 ms | 0.014 ms | 0.017 ms | | 1000 after an id | 0.43 ms | 0.43 ms | 0.45 ms |
| 1000 after an id | 4.26 ms | **0.43 ms** | 4.28 ms | **0.43 ms** | 4.32 ms | **0.45 ms** | | Retention, 10% of a topic | 7 ms | 9 ms | 8 ms |
| Retention, 10% of a topic | 20 ms | **7 ms** | 23 ms | **9 ms** | 98 ms | **8 ms** |
`normal` unless said. At first, the old writer pushed faster, from code the `normal` unless said. Most of the push speed is the writer's: checkpoints
new one didn't have, not from the schema; step 5 brought two of them over off the push path (`Database::checkpointer()`, every second on its own
(the second row, about 1.5 times the old): connection, the writer only checkpointing itself past 10,000 pages,
`WRITER_CHECKPOINT_PAGES`), and no savepoint around a push (a failed one
- **checkpoints off the push path:** `Database::checkpointer()`, every leaves at most its empty stream).
second on its own connection (the server's thread), the writer only
checkpointing itself past 10,000 pages (`WRITER_CHECKPOINT_PAGES`,
SQLite's default is 1,000): 13.8k to 34.7k pushes/s;
- **no savepoint around a push** (a failed one leaves at most its empty
stream): 37.3k;
- **next ids in memory**, left out: an indexed read of the stream's row per
push, not where the time goes.
The new layout reads ranges 10 times faster, deletes faster (and keeps
doing so as the database grows), loses less push speed from 1M to 5M (-12%
against -24%), and makes a file 10% smaller with 200-byte messages (30%
with 45-byte ones: its saving is the indexes, a fixed cost per message).
## Tests ## Tests
`crates/bakashrot-storage/tests/storage.rs`, on database files in `crates/bakashrot-storage/tests/storage.rs`, on database files in
`target/`: opening (made, reopened, an empty file), refused databases `target/`: opening (made, reopened, an empty file), refused databases
(another program's, v8, a newer version, no version), pushes and reads (another program's, a newer version, no version), pushes and reads
(ids per stream, names without case, after/latest/limit/more, the 1 MiB (ids per stream, names without case, after/latest/limit/more, the 1 MiB
cut), uploads (parts in order and of their size, incomplete refused, a cut), uploads (parts in order and of their size, incomplete refused, a
failed operation not spoiling its batch, cancelled and left-over ones failed operation not spoiling its batch, cancelled and left-over ones
deleted), replication (own ids, kept ones, attachments to ask for, too big, deleted), replication (own ids, kept ones, attachments to ask for, too big,
started over, resumed), retention (limits, id order, heads kept, ids going started over, resumed), retention (limits, id order, heads kept, ids going
on, attachments purged in batches), vacuum (the file shrinks, ids go on), on, attachments purged in batches),
the limits (no stream, no id left, the highest key), queries (results, every write refused, failing rows, too the limits (no stream, no id left, the highest key), queries (results, every write refused, failing rows, too
big), the view's plans, and readers with two writers at once. In big), the view's plans, and readers with two writers at once. In
`src/lib.rs`: the keys, the schema unpacking them the same, the states. `src/lib.rs`: the keys, the schema unpacking them the same, the states.
@@ -277,16 +255,3 @@ big), the view's plans, and readers with two writers at once. In
SQLite's interrupt. SQLite's interrupt.
- **Attachments as files** next to the database instead of in it, if their - **Attachments as files** next to the database instead of in it, if their
size calls for it. size calls for it.
## What changed from v8
| v8 | v9 |
|---|---|
| `data(topic_id, node_id, message_id, ...)` + 3 indexes | `data(key, pushed_at, message_data)`, no index |
| `topics`, `nodes` with ids and origins | names in `streams` |
| `node_heads` | `streams.last_id` |
| `attachments` + `blobs` (two sets of states), `blob_chunks` | `attachments` (five states), `attachment_parts` |
| uploads waiting for their message, `UploadTimeout` | uploads inside their push |
| `is_json` stored | computed when read |
| no version in the file | `metadata` with `schema_version`; `application_id` |
| foreign keys declared, not checked | none, `CHECK`s |
+2 -4
View File
@@ -19,8 +19,7 @@ store them in SQLite, and replicate them to other servers by topic and node name
* A CLI tool to push, read, query and list * A CLI tool to push, read, query and list
* A Python module over the library, without dependencies, as a wheel with the library in it * A Python module over the library, without dependencies, as a wheel with the library in it
See [revamp.md](revamp.md) for why it was rewritten in Rust, what was decided, and the plan. See [revamp.md](revamp.md) for what was decided, and the plan.
The PureBasic version it replaced (protocol 6) is in the git history: `OldSource/`, up to commit `68966a8`.
## Building ## Building
@@ -63,7 +62,7 @@ crates/
bakashrot-tools/ the CLI tools: bakashrot (push, read, query, list), bakashrot-cert bakashrot-tools/ the CLI tools: bakashrot (push, read, query, list), bakashrot-cert
bindings/ bindings/
c/ bakashrot.h, generated from bakashrot-capi c/ bakashrot.h, generated from bakashrot-capi
purebasic/ the prototypes and error codes, as the PureBasic version's purebasic/ the prototypes and error codes
python/ bakashrot.py over the DLL, check_bakashrot.py, make_wheel.py python/ bakashrot.py over the DLL, check_bakashrot.py, make_wheel.py
.cargo/config.toml the C runtime linked statically on Windows .cargo/config.toml the C runtime linked statically on Windows
docker/ the server's image: Dockerfile, compose.yml, test.sh docker/ the server's image: Dockerfile, compose.yml, test.sh
@@ -111,7 +110,6 @@ Publishing:
* A crate's root docs say what it does; designs that span crates go in `docs/`, updated with the code. * A crate's root docs say what it does; designs that span crates go in `docs/`, updated with the code.
* Use existing crates rather than reimplementing (MessagePack is `rmp-serde`). * Use existing crates rather than reimplementing (MessagePack is `rmp-serde`).
* Protocol changes update `docs/protocol.md`; error codes are never renumbered, packet ids never reused. * Protocol changes update `docs/protocol.md`; error codes are never renumbered, packet ids never reused.
* `OldSource/` paths in comments and docs: the PureBasic version, in git history up to commit `68966a8`.
## Cloning ## Cloning
+37 -492
View File
@@ -9,36 +9,10 @@ DLL with its C, PureBasic and Python bindings, the `bakashrot` tool,
retention, replication, operations and releases, then the finish: one retention, replication, operations and releases, then the finish: one
test runner, CI, Docker, `bench.ps1`), see "Plan". test runner, CI, Docker, `bench.ps1`), see "Plan".
- **Old implementation:** PureBasic, protocol 6, schema v8. Removed on
2026-11-15 ("The PureBasic version removed"): it's in git history,
`OldSource/` up to commit `68966a8`, which the `OldSource/` paths here
and in the code point to. What of its notes still holds:
`docs/known-issues.md`.
- **New implementation:** the Cargo workspace at the root (in `Source/`
until 2026-11-15, so the paths below are relative to the root now),
see `readme.md`.
## Why
The old code works and is well tested, but every new need costs a lot in
PureBasic, which has no libraries for it:
- The connections' security is a custom protocol (sealed Hello, key
exchange, signed transcript, own cipher framing,
`OldSource/Design/Cryptography.md`), on libsodium.
- The client auth rework needs X.509 certificates: that took writing a DER
reader/writer and an X.509 layer by hand (`OldSource/Commons/Cryptography/Der.pbi`,
`X509.pbi`, `OldSource/Design/Certificates.md`), and TLS would still be
missing.
- Threading traps (lists shared between threads, a listener racing client
threads, item 21), compiler quirks (5.73's `Goto` out of a `Select`),
single-pass includes: see `OldSource/CLAUDE.md`, "Traps".
## Decided ## Decided
1. **Rust**, for the server, the client library and DLL, and the tools: one 1. **Rust**, for the server, the client library and DLL, and the tools: one
Cargo workspace (in `Source/`, at the root since 2026-11-15). Built in Cargo workspace at the root. Built in the order of "Plan" below.
the order of "Plan" below.
2. **A C-compatible client DLL**, usable from any language as today: the 2. **A C-compatible client DLL**, usable from any language as today: the
same kind of exports (`BakaShrot_*A/W`, cdecl), the same conventions same kind of exports (`BakaShrot_*A/W`, cdecl), the same conventions
(strings copied into the caller's buffers, the size needed returned, (strings copied into the caller's buffers, the size needed returned,
@@ -98,8 +72,7 @@ Also decided (2026-11-13):
- Cipher suite: **TLS13_AES_256_GCM_SHA384** only. - Cipher suite: **TLS13_AES_256_GCM_SHA384** only.
- Key exchange: **X25519MLKEM768** only, the X25519 + ML-KEM hybrid - Key exchange: **X25519MLKEM768** only, the X25519 + ML-KEM hybrid
(holds against quantum computers too). (holds against quantum computers too).
- Crypto backend: **aws-lc-rs**, the one with ML-KEM (its Windows build - Crypto backend: **aws-lc-rs**, the one with ML-KEM.
to check at step 2: it may want CMake and NASM).
- The client's certificate is encrypted too: watchers still don't learn - The client's certificate is encrypted too: watchers still don't learn
who connects. Peers the same way, one certificate each instead of a who connects. Peers the same way, one certificate each instead of a
peer section plus a client section on the other server. peer section plus a client section on the other server.
@@ -110,9 +83,7 @@ Also decided (2026-11-13):
roles are free strings with the name rules, their meaning in the roles are free strings with the name rules, their meaning in the
server's config. Only the server reads it. Its OID is server's config. Only the server reads it. Its OID is
`1.3.6.1.4.1.67681.1.1`, under NibblePoker's PEN (2026-11-16, `1.3.6.1.4.1.67681.1.1`, under NibblePoker's PEN (2026-11-16,
`docs/oid.md`; a placeholder until then; the UUID arc of `docs/oid.md`);
`OldSource/` can't be used: `rcgen` writes OID parts of 64 bits at
most);
- the name again as the subject's CN, for people (`openssl x509 -text`, - the name again as the subject's CN, for people (`openssl x509 -text`,
logs); the server only trusts the extension; logs); the server only trusts the extension;
- extended key usage `clientAuth` for clients, `serverAuth` and - extended key usage `clientAuth` for clients, `serverAuth` and
@@ -149,9 +120,7 @@ Also decided (2026-11-13):
block each other whichever end dials; block each other whichever end dials;
- revoked by certificate, not by name: each certificate has its own key - revoked by certificate, not by name: each certificate has its own key
and serial number, so two servers of the same name each have theirs, and serial number, so two servers of the same name each have theirs,
revoked one at a time (`bakashrot-cert issue --file`); revoked one at a time (`bakashrot-cert issue --file`).
- optionally, a node blocked by name in the config, whatever certificate
it has (emergencies, a node taken down).
- **The server's config is TOML** (2026-11-13), `docs/config.md`: - **The server's config is TOML** (2026-11-13), `docs/config.md`:
- `[server]`, `[retention]`, `[replication]`, `[roles.<name>]`; unknown - `[server]`, `[retention]`, `[replication]`, `[roles.<name>]`; unknown
keys refused; names only (no ids, pins or ranges); keys refused; names only (no ids, pins or ranges);
@@ -165,8 +134,7 @@ Also decided (2026-11-13):
- **no peer sections:** peers are roles too (replicating with a server - **no peer sections:** peers are roles too (replicating with a server
whose certificate has a role with `send_topics` / `accept_topics`, whose certificate has a role with `send_topics` / `accept_topics`,
whichever end dials); the config only lists the addresses it dials whichever end dials); the config only lists the addresses it dials
(`[replication] peers`; `push_to` and `accept_from` since 2026-11-14, (`[replication] push_to`, "Replication by address" below);
"Replication by address" below);
- **no default topic** (dropped from the protocol too, 2026-11-13): a - **no default topic** (dropped from the protocol too, 2026-11-13): a
push always names its topic; push always names its topic;
- **the roles are the only lists of topics** (2026-11-16): `[server] - **the roles are the only lists of topics** (2026-11-16): `[server]
@@ -177,9 +145,7 @@ Also decided (2026-11-13):
and is read, listed (`ListNames`: the topics with messages) and and is read, listed (`ListNames`: the topics with messages) and
sent on by the roles that name it. So a topic that only came from a sent on by the roles that name it. So a topic that only came from a
peer is read like any other, and a push to a topic nobody names is peer is read like any other, and a push to a topic nobody names is
`NotAllowed` (`UnknownName` is only for nodes now). Before: `topics` `NotAllowed` (`UnknownName` is only for nodes now);
since 2026-11-13, `replicated_topics` to filter on edge nodes (now
their peers' `send_topics`);
- **`list_topics` and `list_nodes`** (2026-11-16), two booleans of a - **`list_topics` and `list_nodes`** (2026-11-16), two booleans of a
role, for a tool that browses a server: listing answers every topic, role, for a tool that browses a server: listing answers every topic,
every node with messages. Without them (or `query`, which gives every node with messages. Without them (or `query`, which gives
@@ -307,72 +273,40 @@ Also decided (2026-11-13):
## Proposed, to confirm ## Proposed, to confirm
Nothing at the moment. - **A GUI explorer** (2026-11-16, set aside for later): likely **egui**
(`eframe`), the owner leaning to it. One exe in the workspace over
Noted, not planned (dropped 2026-11-13): **typed query results**, numbers as `bakashrot-client`, Windows and Linux, MIT/Apache (Slint's GPLv3 or
numbers in `QueryResult`'s JSON instead of protocol 6's strings. Messages attribution license weighed against the CC0 project; a Win32 `.rc`
come back as text either way; only what SQL computes would gain dialog would be Windows only). To start it: a short spec from the
(`COUNT(*)`, ids, `data->>'$.x'`). Query results stay strings, as before. owner (goal, connecting, a layout sketch, now / later / never,
details such as times and paging, done when).
## Open questions ## Open questions
- **A handle-based DLL API** (several connections per process, old open item - **A handle-based DLL API** (several connections per process, old open item
10): later maybe, the owner's call (one connection per process for now). 10): later maybe, the owner's call (one connection per process for now).
## Kept: the behaviour to carry over
Described in the old version's `OldSource/Notes.md` and
`OldSource/Design/`, tested by `OldSource/Tests/` (git history, see the
top):
- Topics and nodes by name, each server with its own ids (now in its
database only), wildcards, `PushTopics` / `ReadTopics`, `SendTopics` /
`AcceptTopics`, `SendNodes` / `AcceptNodes` (`Packets.md`, "Topics and
nodes").
- Requests: push (JSON or not, `is_json`), latest, runs of messages after
an id (one request now), list names, read-only SQL (`Packets.md`, "Client
requests"; the three read-only guards).
- Replication by name: sync state, batches of ~64 KB, only what's named on
both sides, then attachments (`Packets.md`, "Replication").
- `pushed_at` stamped on arrival, carried by replication; retention per
topic and server (`Notes.md`, "pushed times, retention").
- Attachments: one per message, 1 MB parts, SHA-256, replicated after
their message (`Design/Attachments.md`); streamed inside the push now.
- Limits: 16 MB messages, the reply batch sizes, 1 G attachments by default.
- Error codes: the same numbers and meanings
(`OldSource/Client/BakaShrot_ErrorCodes.pbi`); refuse vs abort; at least
once delivery, nothing reconnects by itself.
- Storage: one writer, WAL, `Synchronous = FULL` by default, `node_heads`
so ids never go back, the `messages` and `browse` views
(`Design/StorageConcurrency.md`).
- Docker image, release zip, Python wheel (`Design/Release.md`,
`OldSource/Docker/`). Not the console commands (dropped 2026-11-14,
"Operations").
## The old open items ## The old open items
From `OldSource/Notes.md`, "Open items": The PureBasic version's, still not fixed:
- **Gone by design:** the custom crypto and its small issues (items 15-16), - **Gaps in a topic and node's ids** aren't detected on replication (6),
keys in plain-text inis as the identity (13, partly: private keys still and **`SyncState` is one packet** (9): `docs/known-issues.md`.
sit in files), the console requirement (1: signals, no console commands), the list and - **Peers are trusted with what they replicate** (12), unless messages
threading traps, the 5.73 quirks. get signed by their node: `docs/known-issues.md`.
- **To carry over and fix:** a corrupted stored attachment re-sent forever - **Names left out of replication aren't warned about:** a topic or
(3, the proposed fix is written there); gaps in a pair's ids not detected node one side doesn't take is skipped silently. Warn once per peer
(6); the sync state in one packet (9); warn once about dropped names; a and name, again only when that changes (a log line at every check-in
leading BOM dropped from messages (22): store the bytes as sent; a NUL would spam).
cutting a message in Python (23): pass lengths, not C strings. - **A NUL cuts a message from Python** (23): `push()` passes it to
- **Still true:** peers trusted with what they replicate (12), unless `PushMessageToA` as a C string, `"a\x00b"` is stored as `a`. Refuse
messages get signed by their origin; rotation (14) becomes reissuing it in `push()`, or pass a length.
certificates.
## Plan ## Plan
Decided 2026-11-13. The crates without networking first, each tested on Decided 2026-11-13. The crates without networking first, each tested on
its own; then one thin path through all of them; then one feature at a its own; then one thin path through all of them; then one feature at a
time, through every layer at once, with its tests and docs. The old suites, time, through every layer at once, with its tests and docs.
ported, say when a step is done; `OldSource/` stayed runnable to compare
until step 13 (removed 2026-11-15).
Dependencies only point downward: Dependencies only point downward:
@@ -384,416 +318,27 @@ proto pki config storage no networking, tested on their own
capi (DLL) tools thin layers over client capi (DLL) tools thin layers over client
``` ```
Error codes, limits and name rules live in `proto` only; the C, PureBasic Error codes, limits and name rules live in `proto` only. The C header is
and Python constants get generated from it (protocol 6 had them copied by generated from the DLL; the PureBasic and Python constants are written
hand in each). by hand.
| # | Step | What | Done when | Decide first | Status | | # | Step | What | Done when | Decide first | Status |
|---|---|---|---|---|---| |---|---|---|---|---|---|
| 0 | Workspace | Cargo workspace, pinned toolchain, `test.ps1`, CI (fmt, clippy, test, doc) | The crates build, the checks pass | Crate names | Done 2026-11-13 | | 0 | Workspace | Cargo workspace, pinned toolchain, `test.ps1`, CI (fmt, clippy, test, doc) | The crates build, the checks pass | Crate names | Done 2026-11-13 |
| 1 | `bakashrot-proto` | Names, error codes, limits, every packet, frames | Round trips, refusals, random input never panics | The packet format | Done 2026-11-13, simplified the same day | | 1 | `bakashrot-proto` | Names, error codes, limits, every packet, frames | Round trips, refusals, random input never panics | The packet format | Done 2026-11-13, simplified the same day |
| 2 | `bakashrot-pki` + certificate tool | CA, server, client, peer certificates (P-384, the identity extension); name and roles read; the TLS setup (AES-256-GCM, X25519MLKEM768, the fixed server name); CRLs and their reload | `openssl verify` takes the tool's certificates; a TLS test accepts and refuses the right ones, a revoked one dropped | Decided 2026-11-13 | Done 2026-11-13 | | 2 | `bakashrot-pki` + certificate tool | CA, server, client, peer certificates (P-384, the identity extension); name and roles read; the TLS setup (AES-256-GCM, X25519MLKEM768, the fixed server name); CRLs and their reload | `openssl verify` takes the tool's certificates; a TLS test accepts and refuses the right ones, a revoked one dropped | Decided 2026-11-13 | Done 2026-11-13 |
| 3 | `bakashrot-config` | Server config: topics, roles to permissions, peers, retention, clear errors | `schema.ini`'s cases, the configs `Names-Test` refuses | TOML, roles (decided 2026-11-13) | Done 2026-11-13 | | 3 | `bakashrot-config` | Server config: topics, roles to permissions, peers, retention, clear errors | Every setting and refusal tested, each with its line | TOML, roles (decided 2026-11-13) | Done 2026-11-13 |
| 4 | `bakashrot-storage` | Schema v9, one writer, reads, names, attachments' states, query guards | Every request's SQL tested; concurrent writes; an old database refused | v9 (decided 2026-11-13) | Done 2026-11-13 | | 4 | `bakashrot-storage` | Schema v9, one writer, reads, names, attachments' states, query guards | Every request's SQL tested; concurrent writes; an old database refused | v9 (decided 2026-11-13) | Done 2026-11-13 |
| 5 | First path end to end | Server: TLS, identity from the certificate, `Welcome`, push and latest. Client library: the same | A Rust test pushes and reads back over TLS, a server on a free port | Decided 2026-11-13 | Done 2026-11-13 | | 5 | First path end to end | Server: TLS, identity from the certificate, `Welcome`, push and latest. Client library: the same | A Rust test pushes and reads back over TLS, a server on a free port | Decided 2026-11-13 | Done 2026-11-13 |
| 6 | The other requests | Runs of messages, names, queries, refusals with codes, 16 MB limits | `GetMessages-Test`, `BigMessages-Test`, ported | | Done 2026-11-13 | | 6 | The other requests | Runs of messages, names, queries, refusals with codes, 16 MB limits | Their end-to-end tests | | Done 2026-11-13 |
| 7 | C DLL | The old exports over the client library, PureBasic prototypes, C header, `bakashrot.py` | `check_bakashrot.py` passes on it | Decided 2026-11-13 | Done 2026-11-13 | | 7 | C DLL | The `BakaShrot_*` exports over the client library, PureBasic prototypes, C header, `bakashrot.py` | `check_bakashrot.py` passes on it | Decided 2026-11-13 | Done 2026-11-13 |
| 8 | Tools | push, get, get-messages `--follow`, query, list (resolve is gone: names only), reading `client.toml` | The tools' parts of the old suites | Decided 2026-11-14 | Done 2026-11-14 | | 8 | Tools | push, get, get-messages `--follow`, query, list (resolve is gone: names only), reading `client.toml` | The tools' end-to-end tests | Decided 2026-11-14 | Done 2026-11-14 |
| 9 | Attachments | Every layer: packets, storage, upload and download, client, DLL, tools | `Attachments-Test`, `AttachmentEdges-Test` | Decided 2026-11-14 | Done 2026-11-14 | | 9 | Attachments | Every layer: packets, storage, upload and download, client, DLL, tools | Every size and edge case, end to end | Decided 2026-11-14 | Done 2026-11-14 |
| 10 | Retention | Background deletion, `node_heads` kept, attachments cleaned up | `Retention-Test`'s local checks | | Done 2026-11-14 | | 10 | Retention | Background deletion, `node_heads` kept, attachments cleaned up | Retention's end-to-end test | | Done 2026-11-14 |
| 11 | Replication | Peer links, sync state, batches by name, wildcards, attachments, skipping on arrival | `Names-Test` (replication), `Restart-Test`; the corrupted-attachment fix | Decided 2026-11-14 | Done 2026-11-14 | | 11 | Replication | Peer links, sync state, batches by name, wildcards, attachments, skipping on arrival | Three servers end to end, a restart; the corrupted-attachment fix | Decided 2026-11-14 | Done 2026-11-14 |
| 12 | Operations | Signals and a clean stop, logs, release, wheel | Runs unattended, stops cleanly, the release's smoke test | Decided 2026-11-14 | Done 2026-11-14 | | 12 | Operations | Signals and a clean stop, logs, release, wheel | Runs unattended, stops cleanly, the release's smoke test | Decided 2026-11-14 | Done 2026-11-14 |
| 13 | Finish | One test runner (the Rust tests, decided 2026-11-15), end-to-end tests in CI, the bench, Docker | Push speed against the old ~17,000 msg/s (4 servers, measured 2026-11-14: `docs/server.md`) | | Done 2026-11-16 (`bench.ps1`) | | 13 | Finish | One test runner (the Rust tests, decided 2026-11-15), end-to-end tests in CI, the bench, Docker | Push speed with 4 servers replicating (`docs/server.md`, "Measured") | | Done 2026-11-16 (`bench.ps1`) |
Each step ends with its tests passing and its docs updated (the crate's 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 docs, `docs/`, this file's status), then a commit when the owner
asks. Open questions get settled at the step that needs them. asks. Open questions get settled at the step that needs them.
### Done: steps 0 and 1 (2026-11-13)
- **Workspace** (`Source/`): `Cargo.toml` (edition 2024, shared lints:
`unsafe_code` denied, docs required, clippy's defaults; release profile
with LTO, `panic = "unwind"` for the DLL's `catch_unwind`),
`rust-toolchain.toml` (1.100.0, rustfmt, clippy), `.gitattributes` (LF),
`test.ps1` (fmt, clippy with warnings as errors, tests, docs),
`../.github/workflows/ci.yml` (the same on Windows and Linux, Gitea
Actions reads it too; not run yet, nothing pushed).
- **`bakashrot-proto`**, on `serde`, `rmp-serde` and `serde_bytes`
(first written over `rmp` with hand-written packets, then simplified the
same day: names only, derived packets, 18 of them, streamed attachments;
the packets' code about half of what it was):
- `limits`, `error` (the protocol 6 numbers, one table for the enum,
names and descriptions), `names` (names and wildcards: the old rules,
tested case by case);
- `frame`: blocking `read()` / `write()` for the DLL, and `codec()`
(feature `tokio`): `tokio-util`'s codec set to the same frames, for the
server (it replaced an own `Decoder`);
- `packets`: one table for the 18 types, the `Packet` enum and its
`serde` form, each packet's struct with its `Check`; decoding reads
with buffers that grow with the data (never from an announced
length), checks every rule and that nothing follows.
- 25 tests: round trips of a sample of every type, golden bytes, every
truncation and trailing byte refused, wrong shapes and types, ranges,
ids in order, names everywhere, a 4 GiB binary announced, and 250,000
random or mutated packets that never make it panic (0.4 s), the
codec's frames the same as the blocking ones.
- Reviewed once more: one text per error code, empty `Check`s by
default, `Attachment::part_count()` / `part_len()` for the receivers,
ALPN tied to the version by a test; the batch sizes (~1 MiB per
`Messages`, ~64 KiB per `ReplicateMessages`) left the protocol crate,
they're the server's to set (steps 6 and 11).
- **`docs/protocol.md`**: protocol 7, every packet, the flows, what
changed from 6.
- **Left for later steps:** the TLS side of the protocol (ALPN, `Welcome`
sent first: steps 2 and 5); generating the C, PureBasic and Python
constants from `error` (step 7); a `cargo fuzz` target, if the random
test ever misses something.
### Done: step 2 (2026-11-13)
`docs/certificates.md` has all of it.
- **`bakashrot-pki`**, on `rcgen`, `rustls` (aws-lc), `x509-parser`
(`verify-aws`, the same aws-lc) and `yasna`:
- `Identity`: the extension read and written, names and roles checked;
- `Ca`: a new CA, loading one (refused if the key isn't its
certificate's), issuing client and server certificates, `issued()`,
CRLs; `summarize()` for people;
- `Revocations`: a CRL's serial numbers, only taken if it's the CA's
(issuer and signature checked); shared with the server's TLS setup, so
replacing it takes effect at the next handshake;
- `tls`: the server's and the client's rustls configurations at the
strongest settings, rustls' own verifiers (the server's wrapped to
check revocation and the identity), `peer_identity()`.
- The server name is fixed (`bakashrot-server`, in every server's
certificate) instead of a verifier of our own: rustls' checks it all.
- **`bakashrot-tools`**: `bakashrot-cert` (`ca`, `issue`, `revoke`,
`show`), never writing over a certificate or key, a CRL written aside
then moved in place, revoking only the CA's certificates.
- **18 tests:** handshakes in memory (the strongest settings negotiated,
identities both ways, servers as their peers' clients; refused: another
CA's client or server, a client posing as a server, a revoked client and
taken again once the CRL changes, no identity, another protocol
version), certificates and CRLs, OpenSSL agreeing (`verify` for clients
and servers, the CRL, a revoked one; Git's OpenSSL found), the tool end
to end.
- **`aws-lc-rs` builds as it is** here (no CMake or NASM to install).
- **Then (2026-11-13):** clients check the CRL too when given one, so
servers block each other both ways; ALPN `bakashrot` with the versions
exchanged right after TLS (`frame::write_version()` / `check_version()`,
error `VersionMismatch`); `--file` for a second certificate of the same
name. 47 tests in the workspace.
- **Left:** the placeholder OID (a PEN, see "Open questions");
`AllowedServerNames` (noted above); exchanging the versions, watching the
CRL file and dropping revoked connections (step 5).
- **Simplified (2026-11-13):** reading PEM and certificates in one place
(`lib.rs`), the EKU through x509-parser's accessor. The verifiers'
delegation stays: rustls' own CRL support would mean a new TLS
configuration per CRL change, and still `Revocations` for open
connections.
### Done: step 3 (2026-11-13)
`docs/config.md` has all of it; every key with its default:
`crates/bakashrot-config/example.toml`.
- **`bakashrot-config`**, on `toml` and `serde` (`indexmap` for the
file's order): `Config::load()` (paths from the config's folder) and
`parse()`, checked in one go: TOML errors with their line, unknown keys,
names, durations, sizes, addresses, ranges, things given twice (without
case), `synchronous = "off"` refused as before.
- `Config::permissions(roles)`: what a certificate's roles allow together,
`None` when none is known; `Permissions::can_push / can_read /
can_query / sends / accepts / replicates`. `Retention::age(topic)`.
- **11 tests** (58 in the workspace): the example, defaults, every
setting, retention's order, permissions, `replicated_topics`, paths, the
refusals, each with its line (the old ini's keys among them).
- **Simplified the same day:** values checked as serde reads them
(`deserialize_with`, `try_from`) instead of raw structs checked after:
one set of structs, and every refusal has its line.
- **`upload_timeout` removed (2026-11-13):** protocol 7 streams an
attachment inside its push, nothing waits for its message any more; a cut
upload goes when its connection ends (schema v9).
- **Left for the server (step 5 on):** loading the certificate files,
refusing a push to a topic it doesn't have, `[replication] peers`
dialed; one server per node (see "Open questions") and the default
topic, for later.
- **The default topic left the protocol too (2026-11-13):** `Welcome` has
none, a push always names its topic (`NoDefaultTopic`, 6, never sent).
### Done: step 4 (2026-11-13)
`docs/storage.md` has all of it (the layout, why, the numbers).
- **`bakashrot-storage`**, on `rusqlite` (SQLite bundled):
- `Database::open`: makes a v9 database, opens one, refuses the old
server's, a newer one's or another program's, migrates (none yet),
deletes left-over uploads;
- `Writer::batch`: one transaction, each operation all or nothing (a
savepoint): pushes, uploads, replication, retention, purging
attachments;
- `Reader`: messages (after an id, the last ones, about 1 MiB per
answer), names, heads, missing attachments, attachments and parts, as
the protocol's types;
- `QueryRunner`: read-only SQL, three guards, results as strings;
- `Writer::vacuum()`: the old `vacuum` command.
- **The schema** moved into the crate (`src/schema_v9.sql`); the keys'
layout is checked against it by a test.
- **15 tests** (73 in the workspace): every operation, the limits, refused
databases, queries, the view's plans, readers with two writers at once;
and `compare_with_old` (ignored by default): the same workload as the
old storage, for comparing.
- **Measured before deciding** (Python, 5M messages): the packed layout
23k pushes/s against 9k for v8's, 330 MB against 484 MB; a time index
costs half the pushes, whatever the cache.
- **Simplified:** the protocol's types as answers (no copies), one stream
lookup, the states typed both ways, `u64`s checked by `rusqlite`, fixed
SQL for reads (the key's layout only in `lib.rs` and the schema).
- **Left for the server:** hashing parts as they stream (SHA-256), which
topics exist (the config), retention's pace, a time limit on queries.
- **Against the old storage** (same workload, storage alone; `storage.md`,
"Against the old storage"): pushes 13.8k/s against the old 25.9k at 1M,
12.2k against 19.6k at 5M; reading 1000 messages 10 times faster,
retention 3 to 12 times. The old writer's speed is its code (checkpoints
in a background thread, next ids in memory, no savepoint per push), not
its schema: two of those brought over at step 5.
### Done: step 5 (2026-11-13)
`docs/server.md` has all of it.
- **`bakashrot-server`**: TLS with `bakashrot-pki`'s settings, the versions,
the identity and its roles (refused with `NotAllowed` when none is
known), `Welcome`; pushes (topic known, allowed, not too big) through
one writer thread doing group commits; messages through a pool of read
connections; the CRL file polled and reloaded, a revoked connection
dropped at its next request; the other requests refused until their
steps. The program: `bakashrot-server <config.toml>`, `tracing` logs,
Ctrl+C.
- **`bakashrot-client`**: blocking; connects (TLS, ALPN checked, the
versions, `Welcome`), `push`, `get_messages`; errors as the protocol's
codes.
- **5 end-to-end tests** (and `push_rate`, ignored): pushes and reads back,
refusals keeping the connection, refused certificates (each with its
code), revoked ones dropped, six connections at once.
- **Then optimized:** checkpoints on their own thread and connection (the
writer only past 10,000 pages): 13.8k to 34.7k pushes/s, storage alone;
no savepoint around a push: 37.3k (the old storage: 25.9k). Next ids in
memory left out: one indexed read per push, not where the time goes.
The whole server, 10 clients over TLS: 36k pushes/s with `normal`, 9.2k
with `full` (a disk flush per group).
### Done: step 6 (2026-11-13)
`docs/server.md`, "Requests so far".
- **`GetMessages`** refuses an unknown topic (not the config's) or node
(no messages in any topic) with `UnknownName`, as the old server did; a
known pair without messages answers none.
- **`ListNames`:** the config's topics the roles may push to or read
(all with `query`), every node with messages.
- **`Query`** on a pool of `query_only` connections; "malformed JSON"
gets the old hint (`is_json = 1`).
- **The client:** `list_names`, `query`; messages and queries over
`MAX_MESSAGE_SIZE` refused before sending.
- **4 more end-to-end tests:** runs of messages and big messages (the old
suites' server parts: the tools' parts are step 8, replication's step
11), names, queries.
### Done: step 7 (2026-11-13)
`docs/client.md` has all of it.
- **`bakashrot-capi`** builds `bakashrot.dll` / `libbakashrot.so`: the old
exports over `bakashrot-client` (A and W, buffers, `GetLastError`, the
same codes), certificates set from PEM or files, one connection per
process, panics caught, the C runtime static on Windows (the release DLL
imports system DLLs only).
- **Bindings:** `bindings/c/bakashrot.h` generated by cbindgen (a test
keeps it current), `bindings/purebasic/` (prototypes, error codes, an
example run by hand against a server), `bindings/python/bakashrot.py`
(certificates, `Client.from_file("client.toml")`, names only).
- **Small changes under it:** the client checks `GetMessages`' limit and
`after` before sending, and says whether the server closed the
connection (`is_open`); the server knows a client's own node before its
first push (none, not `UnknownName`).
- **Tests:** the exports called directly (`exports.rs`),
`check_bakashrot.py` ported (43 checks) run on the DLL (`python.rs`),
the header. The attachment checks come back with step 9.
### Done: step 8 (2026-11-14)
`docs/client.md`, "The tools".
- **`bakashrot`** (`bakashrot-tools`): `push <topic> <message>`, `latest
<topic> <node>`, `messages <topic> <node>` (`--after <id|latest>`,
`--limit`, `--follow`, `--interval`, `--time`), `query <sql>`, `list
[topics|nodes|all] [--json]`, connecting with `client.toml` (`-c`). The
old tools' output, without the ids; errors on stderr.
- **Gone:** `ResolveIds` (no ids), `GenerateKeyPairs` (`bakashrot-cert`),
the default topic (`push` names its topic). `GetAttachment` and `push
-a` come with step 9.
- **Tests** (`tests/bakashrot.rs`, 5): the GetMessages suite's checks
(defaults, `--after`, `--limit`, `latest`, another reader, refusals,
data as stored, big messages, `--follow` taking only new ones and failing
once the server is gone), Names' and BigMessages' tool checks (pushes,
refusals, the size limit, `latest`, `list`), queries, `client.toml`
(relative paths, a typo, an unreachable server).
### Done: step 9 (2026-11-14)
`docs/server.md` ("Requests"), `client.md`.
- **The server:** a push with an attachment is checked (topic, roles,
sizes, the server's `max_attachment_size`), answered `Continue`, then
every part read, written while the next ones come (4 at most waiting
for the writer), the SHA-256 checked as they come; the message is
stored with it once all of it matches. A wrong part, a wrong SHA-256, a
failed write: refused once all parts came, the upload dropped. A cut
connection drops it too. `GetAttachment` sends the size and SHA-256,
then the parts from `from_part` (`NotFound`, `NotReady`, `TooBig` for
one this server doesn't keep). The writer's queue takes every write
now, not only pushes.
- **The client:** `push_with_attachment(topic, data, source)` (anything
`Read + Seek`: read twice, its SHA-256 first), `get_attachment(..., out)`
checked with its SHA-256 (`AttachmentMismatch`), `save_attachment(...,
path)` written aside then moved, so a failed one leaves no file.
- **The DLL, Python, the tool, PureBasic:** as decided; the PureBasic
example pushes an attachment and reads it back (run by hand, 5.73).
- **Tests:** the server's (`attachments`: the Attachments suite's sizes, 1
byte to 5 MB + 123 and exactly 2 MB, read back and saved, none or
missing refused, no file left, the limit, 0 for none, not allowed; and
`attachment_edges`: a source changed between its SHA-256 and its
sending, one failing in the middle, a part of the wrong size, a wrong
SHA-256, reading from a part on, something else than a part; uploads
dropped each time), the DLL's exports, `check_bakashrot.py`'s
attachment checks back (52 checks), the tool's.
- **Measured** (release, local, `normal`): a 200 MB attachment up in 1.3 s
and down in 0.5 s through the tool, its start included.
- **Left for replication (step 11):** replicated attachments
(`replicating`, `too_big`), the corrupted-attachment fix, resuming from
a part.
### Done: step 10 (2026-11-14)
`docs/server.md` ("Retention").
- **The server:** a task (`retention.rs`, `Server::apply_retention()`):
at start, then every `retention_interval`, every topic in the database
by its name, its age from `[retention]`, its messages before now minus
it deleted through the writer's queue (10,000 per write, so pushes go
on between them), then the deleted messages' attachment parts (64 per
write); each topic's count logged. As the old server did, except that
uploads left behind are dropped at once (protocol 7), not on a timeout.
- **Tests:** `end_to_end.rs`'s `retention`: a topic kept 2 s, checked
every second, its messages and attachment gone, another topic kept,
ids going on, a younger message kept through a pass.
- **Left for replication (step 11):** the peer keeping its own copies,
and what arrives already past its age (counted as received, not
stored).
### Done: step 11 (2026-11-14)
`docs/server.md` ("Replication"), `config.md` ("Peers").
- **The config:** `[replication] push_to` (was `peers`) and
`accept_from` (IPs or hostnames, `"*"`), as decided.
- **Sending** (`push_to.rs`): a link per server of `push_to`, dialed
again after `retry_delay`, failures logged once until they change;
a check-in (again at once after sending, after `sync_interval` when
idle): `SyncState`, then the messages it
lacks by name (`batch_size`, about 1 MiB a batch), then the attachments
it lacks from their part. The corrupted-attachment fix (old open item
3): a copy the other server says doesn't match is read back, and if
damaged dropped and asked for again from this server's peers, instead
of sent at every check-in.
- **Receiving** (`accept_from.rs`): only from `accept_from` (hostnames
looked up at a connection's first replication request), only what the
roles' `accept_*` allow; ids and times kept, ones past their age only
counted; attachments resumed from their part (the parts here read back
for the SHA-256), started over when they don't match.
- **Storage:** `replicate(..., skip_before)`, `to_replicate()`,
`damaged()`; a replicated attachment all of whose parts came but that
wasn't checked (a stop in between) starts over at the next start.
- **Tests:** `end_to_end.rs`'s `replication` (three servers: by name,
ids, times and attachments; not from outside `accept_from`; one way;
a server stopped and started again on its database, ids going on; a
damaged copy caught) and `replication_edges` (the test as the peer);
storage's `replication` (skipped on arrival, `to_replicate`,
`damaged`); the config's (`push_to`, `accept_from`, `peers` refused,
`accepted()`).
- **Measured** (`docs/server.md`, "Replication, against the old
server"): 4 servers in a Y, 10 nodes each flat out: 16,000-16,300
pushes/s with `full` (old: 16,638), 35,300-37,500 with `normal` (old:
33,895), and the servers keeping up while pushing (under 1 s behind,
the old ones 9-11 s), a link checking in again at once after sending;
`batch_size` 1000 by default (was 100).
- **Not done:** `SyncState`'s 256 missing attachments are the oldest
ones, whichever peer can send them: with several peers, ones none of
them has can hold back newer ones. Gaps in a pair's ids (old item 6)
still not detected.
### Done: step 12 (2026-11-14)
`docs/server.md` ("Running"), `readme.md` ("Releases").
- **Stopping:** `bakashrot-server` waits for SIGTERM or SIGINT (Linux),
Ctrl+C, Ctrl+Break or its console closed (Windows), stops taking
connections, then `Server::stop()`: the writer's thread commits what
was queued before (so every push answered is stored), refuses what
comes after (`ServerError`, "the server is stopping"), and it exits
with 0.
- **Logs:** the console, no colour codes when redirected,
`BAKASHROT_LOG` for the level. No console commands.
- **The release:** `release.py`, for the platform it runs on:
builds, packages into `target/dist/bakashrot-0.2.0-<platform>/` (the
three programs, the library, `bakashrot.h`, the PureBasic files,
`bakashrot.py` and its wheel, the example configs, the docs, a
`README.txt`, `LICENSE.txt`, `THIRD-PARTY.txt` from `cargo metadata`),
smoke-tests it, archives it (`.zip`, `.tar.gz`). The smoke test: a CA
and certificates by `bakashrot-cert`, the server on a free port, the
tool's push (and a 3 MB attachment), `latest`, `attachment`,
`messages`, `list`, `query`; Python through the library; the wheel
installed by pip, used with no path; the server stopped by Ctrl+Break
(SIGTERM on Linux), exiting cleanly. Passes on Windows (9.6 MB zip).
- **The wheel:** `bindings/python/make_wheel.py`, as the old one (only
the standard library, the same inputs giving the same wheel):
`win_amd64`, or `manylinux_<glibc>_x86_64` from the glibc it's built
against; the licenses in it.
- **CI** (`.github/workflows/ci.yml`): a `release` job on a `v*` tag
or by hand, Windows and Linux (in `manylinux_2_28`), keeping the
archives.
- **The version:** 0.2.0, the workspace's; `release.py` checks
`bakashrot.py`'s is the same.
- **Size:** the release profile optimizes for size (`opt-level = "s"`,
with LTO, one codegen unit, stripped): the server 6.6 MB to 4.7 MB,
`bakashrot` 3.9 to 2.8, `bakashrot-cert` 2.5 to 1.7, the DLL 3.4 to
2.6 (Windows). About 5% fewer pushes with `normal`, the same with
`full`, attachments and tool commands. Tried too: `"z"` (2-4% smaller
still), the C code apart at 3 (1.2 MB more, no faster), `/Gy /Gw` for
the C (100 KB). Not tried: `panic = "abort"` (the DLL catches panics,
and a panic in one connection's task would end the server).
- **Tests:** `end_to_end.rs`'s `stops_cleanly` (eight nodes pushing flat
out, stopped under them: every answered push there after a restart);
`restart_after()` stops as the program does.
- **Not done:** the Linux release hadn't run here (no Linux machine);
CI ran on GitHub after the push (2026-11-15). Docker: step 13.
### For step 13: what the old Docker image did
From `OldSource/Docker/` (git history), kept in `docker/` (the config
in `/etc/bakashrot`, the database in a volume, the source label, a user
of its own; the image is an index now, its annotations hold the label):
- A multi-stage build, the final image only the server and what it
needs; `docker compose up -d --build` with the config in a mounted
folder.
- The label `org.opencontainers.image.source` set to the GitHub
repository, which links the package to it on ghcr.io; built with
`--provenance=false`, or the image is an index and GitHub doesn't see
the label.
- Pushed to both registries, with the version and as `latest`:
`git.nibblepoker.lu/aziascreations/bakashrot-server` and
`ghcr.io/aziascreations/bakashrot-server` (a token with
`write:packages`); the package then linked and made public in its
settings on GitHub.