mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Warned about names a peer doesn't take, Refused a NUL in Python's strings
- Replication: what a link's roles here may send but the peer doesn't take (not in its roles' accept_* there) is skipped as before, and now logged as a warning (the first ten "topic:node" named) once per link, again only when that changes. - Python: every string going to the DLL as a C string (a message, a name, SQL, a path) with a NUL is refused (INVALID_ARGUMENT) rather than cut there, as C# already did. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -202,10 +202,18 @@ class NamesList:
|
|||||||
truncated: bool # True if they didn't all fit in one answer
|
truncated: bool # True if they didn't all fit in one answer
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: str) -> bytes:
|
||||||
|
"""value as the DLL's C string: one with a NUL is refused rather than
|
||||||
|
cut there."""
|
||||||
|
if "\0" in value:
|
||||||
|
raise BakaShrotError("A string with a NUL character", ErrorCode.INVALID_ARGUMENT)
|
||||||
|
return value.encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
def _name(value: str) -> bytes:
|
def _name(value: str) -> bytes:
|
||||||
if not isinstance(value, str):
|
if not isinstance(value, str):
|
||||||
raise TypeError(f"a topic or node is a name, not {value!r}")
|
raise TypeError(f"a topic or node is a name, not {value!r}")
|
||||||
return value.encode("utf-8")
|
return _text(value)
|
||||||
|
|
||||||
|
|
||||||
def _find_dll(dll_path: Optional[str]) -> str:
|
def _find_dll(dll_path: Optional[str]) -> str:
|
||||||
@@ -388,9 +396,9 @@ class Client:
|
|||||||
raise self._failed("Answer timeout")
|
raise self._failed("Answer timeout")
|
||||||
for setter, value in ((dll.SetCaCertificateA, self.ca), (dll.SetCertificateA, self.certificate),
|
for setter, value in ((dll.SetCaCertificateA, self.ca), (dll.SetCertificateA, self.certificate),
|
||||||
(dll.SetPrivateKeyA, self.key), (dll.SetCrlA, self.crl or "")):
|
(dll.SetPrivateKeyA, self.key), (dll.SetCrlA, self.crl or "")):
|
||||||
if not setter(handle, value.encode("utf-8")):
|
if not setter(handle, _text(value)):
|
||||||
raise self._failed("Certificates")
|
raise self._failed("Certificates")
|
||||||
if not dll.ConnectA(handle, self.host.encode("utf-8"), self.port):
|
if not dll.ConnectA(handle, _text(self.host), self.port):
|
||||||
raise self._failed(f"Connect to {self.host}:{self.port}", connecting=True)
|
raise self._failed(f"Connect to {self.host}:{self.port}", connecting=True)
|
||||||
self.node = dll.string(dll.GetNodeA, handle)
|
self.node = dll.string(dll.GetNodeA, handle)
|
||||||
return self
|
return self
|
||||||
@@ -496,7 +504,7 @@ class Client:
|
|||||||
message is only stored once all of it came."""
|
message is only stored once all of it came."""
|
||||||
if not isinstance(data, str):
|
if not isinstance(data, str):
|
||||||
data = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
|
data = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
|
||||||
encoded = data.encode("utf-8")
|
encoded = _text(data)
|
||||||
if len(encoded) > MAX_MESSAGE_SIZE:
|
if len(encoded) > MAX_MESSAGE_SIZE:
|
||||||
raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}", ErrorCode.INVALID_ARGUMENT)
|
raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}", ErrorCode.INVALID_ARGUMENT)
|
||||||
with self._lock:
|
with self._lock:
|
||||||
@@ -507,7 +515,7 @@ class Client:
|
|||||||
raw = bytes(attachment)
|
raw = bytes(attachment)
|
||||||
message_id = self._dll.PushMessageWithDataA(self._handle, _name(topic), encoded, raw, len(raw))
|
message_id = self._dll.PushMessageWithDataA(self._handle, _name(topic), encoded, raw, len(raw))
|
||||||
else:
|
else:
|
||||||
path = os.fspath(attachment).encode("utf-8")
|
path = _text(os.fspath(attachment))
|
||||||
message_id = self._dll.PushMessageWithFileA(self._handle, _name(topic), encoded, path)
|
message_id = self._dll.PushMessageWithFileA(self._handle, _name(topic), encoded, path)
|
||||||
if message_id < 1:
|
if message_id < 1:
|
||||||
raise self._failed("Push")
|
raise self._failed("Push")
|
||||||
@@ -536,7 +544,7 @@ class Client:
|
|||||||
with self._lock:
|
with self._lock:
|
||||||
self._check_connected()
|
self._check_connected()
|
||||||
size = self._dll.SaveAttachmentA(self._handle, _name(topic), _name(node), int(message_id),
|
size = self._dll.SaveAttachmentA(self._handle, _name(topic), _name(node), int(message_id),
|
||||||
os.fspath(path).encode("utf-8"))
|
_text(os.fspath(path)))
|
||||||
if size < 0:
|
if size < 0:
|
||||||
raise self._failed("Attachment")
|
raise self._failed("Attachment")
|
||||||
return size
|
return size
|
||||||
@@ -642,7 +650,7 @@ class Client:
|
|||||||
query is refused: RefusedError "malformed JSON"."""
|
query is refused: RefusedError "malformed JSON"."""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self._check_connected()
|
self._check_connected()
|
||||||
if not self._dll.QueryA(self._handle, sql.encode("utf-8")):
|
if not self._dll.QueryA(self._handle, _text(sql)):
|
||||||
raise self._failed("Query")
|
raise self._failed("Query")
|
||||||
return self._dll.string(self._dll.GetQueryResultAsJsonA, self._handle)
|
return self._dll.string(self._dll.GetQueryResultAsJsonA, self._handle)
|
||||||
|
|
||||||
|
|||||||
@@ -138,6 +138,10 @@ with kitchen:
|
|||||||
ok, detail = raises(lambda: kitchen.push("x" * (bakashrot.MAX_MESSAGE_SIZE + 1), "logs"), BakaShrotError, "too big",
|
ok, detail = raises(lambda: kitchen.push("x" * (bakashrot.MAX_MESSAGE_SIZE + 1), "logs"), BakaShrotError, "too big",
|
||||||
ErrorCode.INVALID_ARGUMENT)
|
ErrorCode.INVALID_ARGUMENT)
|
||||||
check("A message over the limit: refused before sending", ok, detail)
|
check("A message over the limit: refused before sending", ok, detail)
|
||||||
|
ok, detail = raises(lambda: kitchen.push("a\0b", "logs"), BakaShrotError, "NUL", ErrorCode.INVALID_ARGUMENT)
|
||||||
|
check("A message with a NUL: refused rather than cut", ok, detail)
|
||||||
|
ok, detail = raises(lambda: kitchen.query("SELECT 1\0; DELETE"), BakaShrotError, "NUL", ErrorCode.INVALID_ARGUMENT)
|
||||||
|
check("SQL with a NUL: refused too", ok and kitchen.connected, detail)
|
||||||
secret_id = kitchen.push({"s": 1}, "secret")
|
secret_id = kitchen.push({"s": 1}, "secret")
|
||||||
check("Push to another allowed topic", secret_id == 1, secret_id)
|
check("Push to another allowed topic", secret_id == 1, secret_id)
|
||||||
with lounge:
|
with lounge:
|
||||||
|
|||||||
@@ -5,6 +5,10 @@
|
|||||||
//! attachments it lacks; again at once if it sent any (it keeps up under
|
//! attachments it lacks; again at once if it sent any (it keeps up under
|
||||||
//! load), after `sync_interval` otherwise. Only what the other server's roles'
|
//! load), after `sync_interval` otherwise. Only what the other server's roles'
|
||||||
//! `send_*` allow. `accept_from.rs` is the other end.
|
//! `send_*` allow. `accept_from.rs` is the other end.
|
||||||
|
//!
|
||||||
|
//! What it may send but the other server doesn't take (not in its roles'
|
||||||
|
//! `accept_*` there) is skipped, and warned about once per link, again
|
||||||
|
//! only when that changes.
|
||||||
|
|
||||||
use crate::Shared;
|
use crate::Shared;
|
||||||
use crate::connection::SEND_TIMEOUT;
|
use crate::connection::SEND_TIMEOUT;
|
||||||
@@ -14,13 +18,13 @@ use bakashrot_pki::tls;
|
|||||||
use bakashrot_proto::limits::{ALPN, KEEPALIVE_SECS, MAX_PACKET_SIZE};
|
use bakashrot_proto::limits::{ALPN, KEEPALIVE_SECS, MAX_PACKET_SIZE};
|
||||||
use bakashrot_proto::names::name_matches;
|
use bakashrot_proto::names::name_matches;
|
||||||
use bakashrot_proto::packets::{
|
use bakashrot_proto::packets::{
|
||||||
Attachment, AttachmentPart, MissingAttachment, Pair, Ping, ReplicateAttachment,
|
Attachment, AttachmentPart, Head, MissingAttachment, Pair, Ping, ReplicateAttachment,
|
||||||
ReplicateMessages, RequestRefused, SyncState, SyncStateRequest,
|
ReplicateMessages, RequestRefused, SyncState, SyncStateRequest,
|
||||||
};
|
};
|
||||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||||
use bakashrot_storage::AttachmentState;
|
use bakashrot_storage::AttachmentState;
|
||||||
use futures_util::{SinkExt, StreamExt};
|
use futures_util::{SinkExt, StreamExt};
|
||||||
use std::collections::HashMap;
|
use std::collections::{BTreeSet, HashMap};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
@@ -48,10 +52,12 @@ pub(crate) async fn run(shared: Arc<Shared>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Links to `address`, checks in until the link fails, then again after
|
/// Links to `address`, checks in until the link fails, then again after
|
||||||
/// `retry_delay`. A failure is logged once until it changes.
|
/// `retry_delay`. A failure is logged once until it changes, and so is
|
||||||
|
/// what the other server doesn't take (across links too).
|
||||||
async fn keep_linked(shared: Arc<Shared>, address: String) {
|
async fn keep_linked(shared: Arc<Shared>, address: String) {
|
||||||
let replication = &shared.config.replication;
|
let replication = &shared.config.replication;
|
||||||
let mut last_failure = String::new();
|
let mut last_failure = String::new();
|
||||||
|
let mut not_taken = BTreeSet::new();
|
||||||
loop {
|
loop {
|
||||||
let failure = match Link::open(&shared, &address).await {
|
let failure = match Link::open(&shared, &address).await {
|
||||||
Ok(mut link) => {
|
Ok(mut link) => {
|
||||||
@@ -59,8 +65,16 @@ async fn keep_linked(shared: Arc<Shared>, address: String) {
|
|||||||
last_failure.clear();
|
last_failure.clear();
|
||||||
loop {
|
loop {
|
||||||
let checked = match link.check_in(&shared).await {
|
let checked = match link.check_in(&shared).await {
|
||||||
Ok(true) => Ok(()),
|
Ok(sent) => {
|
||||||
Ok(false) => link.wait(replication.sync_interval).await,
|
if link.not_taken != not_taken {
|
||||||
|
not_taken = link.not_taken.clone();
|
||||||
|
log_not_taken(&format!("{} ({address})", link.name), ¬_taken);
|
||||||
|
}
|
||||||
|
match sent {
|
||||||
|
true => Ok(()),
|
||||||
|
false => link.wait(replication.sync_interval).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
Err(why) => Err(why),
|
Err(why) => Err(why),
|
||||||
};
|
};
|
||||||
if let Err(why) = checked {
|
if let Err(why) = checked {
|
||||||
@@ -85,6 +99,9 @@ struct Link {
|
|||||||
permissions: Permissions,
|
permissions: Permissions,
|
||||||
/// Whether this check-in sent something it took.
|
/// Whether this check-in sent something it took.
|
||||||
sent: bool,
|
sent: bool,
|
||||||
|
/// What it may be sent but doesn't take, as of this check-in:
|
||||||
|
/// "topic:node".
|
||||||
|
not_taken: BTreeSet<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Link {
|
impl Link {
|
||||||
@@ -130,6 +147,7 @@ impl Link {
|
|||||||
name: identity.name,
|
name: identity.name,
|
||||||
permissions,
|
permissions,
|
||||||
sent: false,
|
sent: false,
|
||||||
|
not_taken: BTreeSet::new(),
|
||||||
};
|
};
|
||||||
match link.receive().await? {
|
match link.receive().await? {
|
||||||
Packet::Welcome(_) => Ok(link),
|
Packet::Welcome(_) => Ok(link),
|
||||||
@@ -147,14 +165,16 @@ impl Link {
|
|||||||
.read(|reader| reader.heads())
|
.read(|reader| reader.heads())
|
||||||
.await
|
.await
|
||||||
.map_err(|refused| refused.reason)?;
|
.map_err(|refused| refused.reason)?;
|
||||||
for head in heads {
|
let (to_send, not_taken) = sort_heads(&self.permissions, &state, heads);
|
||||||
let (topic, node) = (head.topic, head.node);
|
self.not_taken = not_taken;
|
||||||
if !self.sends(&state, &topic, &node) {
|
for head in to_send {
|
||||||
continue;
|
let after = theirs
|
||||||
}
|
.get(&key(&head.topic, &head.node))
|
||||||
let after = theirs.get(&key(&topic, &node)).copied().unwrap_or(0);
|
.copied()
|
||||||
|
.unwrap_or(0);
|
||||||
if after < head.last_id {
|
if after < head.last_id {
|
||||||
self.send_messages(shared, topic, node, after).await?;
|
self.send_messages(shared, head.topic, head.node, after)
|
||||||
|
.await?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for missing in state.missing {
|
for missing in state.missing {
|
||||||
@@ -195,16 +215,6 @@ impl Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether it takes `node`'s messages in `topic` (its `SyncState`) and
|
|
||||||
/// may be sent them (its roles here).
|
|
||||||
fn sends(&self, state: &SyncState, topic: &str, node: &str) -> bool {
|
|
||||||
let listed =
|
|
||||||
|list: &[String], name: &str| list.iter().any(|entry| name_matches(entry, name));
|
|
||||||
listed(&state.topics, topic)
|
|
||||||
&& listed(&state.nodes, node)
|
|
||||||
&& self.permissions.sends(topic, node)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A topic and node's messages after `after`, in batches. A refusal
|
/// A topic and node's messages after `after`, in batches. A refusal
|
||||||
/// leaves them for the next check-in.
|
/// leaves them for the next check-in.
|
||||||
async fn send_messages(
|
async fn send_messages(
|
||||||
@@ -418,6 +428,54 @@ fn judge(read: Result<bool, RequestRefused>) -> OwnCopy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This server's heads that the other server may be sent (its roles
|
||||||
|
/// here, `permissions`) and takes (its `SyncState`'s lists); and the names
|
||||||
|
/// of those it may be sent but doesn't take, "topic:node".
|
||||||
|
fn sort_heads(
|
||||||
|
permissions: &Permissions,
|
||||||
|
state: &SyncState,
|
||||||
|
heads: Vec<Head>,
|
||||||
|
) -> (Vec<Head>, BTreeSet<String>) {
|
||||||
|
let listed = |list: &[String], name: &str| list.iter().any(|entry| name_matches(entry, name));
|
||||||
|
let mut not_taken = BTreeSet::new();
|
||||||
|
let to_send = heads
|
||||||
|
.into_iter()
|
||||||
|
.filter(|head| permissions.sends(&head.topic, &head.node))
|
||||||
|
.filter(|head| {
|
||||||
|
let taken = listed(&state.topics, &head.topic) && listed(&state.nodes, &head.node);
|
||||||
|
if !taken {
|
||||||
|
not_taken.insert(format!("{}:{}", head.topic, head.node));
|
||||||
|
}
|
||||||
|
taken
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
(to_send, not_taken)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logs what `peer` doesn't take of what it may be sent, now that it
|
||||||
|
/// changed: a warning, or that it takes it all again.
|
||||||
|
fn log_not_taken(peer: &str, not_taken: &BTreeSet<String>) {
|
||||||
|
match not_taken.is_empty() {
|
||||||
|
true => info!("{peer}: takes everything this server may send it now"),
|
||||||
|
false => warn!(
|
||||||
|
"{peer}: doesn't take {}, which this server may send it (not in its roles' \
|
||||||
|
accept_topics and accept_nodes there): skipped",
|
||||||
|
some_names(not_taken)
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first few names, then how many more.
|
||||||
|
fn some_names(names: &BTreeSet<String>) -> String {
|
||||||
|
const SHOWN: usize = 10;
|
||||||
|
let shown: Vec<&str> = names.iter().take(SHOWN).map(String::as_str).collect();
|
||||||
|
let mut text = shown.join(", ");
|
||||||
|
if names.len() > SHOWN {
|
||||||
|
text += &format!(" and {} more", names.len() - SHOWN);
|
||||||
|
}
|
||||||
|
text
|
||||||
|
}
|
||||||
|
|
||||||
/// A topic and node, to compare without case.
|
/// A topic and node, to compare without case.
|
||||||
fn key(topic: &str, node: &str) -> (String, String) {
|
fn key(topic: &str, node: &str) -> (String, String) {
|
||||||
(topic.to_ascii_lowercase(), node.to_ascii_lowercase())
|
(topic.to_ascii_lowercase(), node.to_ascii_lowercase())
|
||||||
@@ -430,6 +488,61 @@ fn unexpected(packet: &Packet) -> String {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use bakashrot_config::Config;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn heads_sent_and_not_taken() {
|
||||||
|
let config = Config::parse(
|
||||||
|
r#"
|
||||||
|
[server]
|
||||||
|
listen = "127.0.0.1:7000"
|
||||||
|
ca = "ca.crt"
|
||||||
|
certificate = "server.crt"
|
||||||
|
key = "server.key"
|
||||||
|
|
||||||
|
[roles.peer]
|
||||||
|
send_topics = ["logs", "secret"]
|
||||||
|
send_nodes = ["kitchen", "garage"]
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let permissions = config.permissions(&["peer"]).unwrap();
|
||||||
|
// It takes logs and metrics, from kitchen and lounge.
|
||||||
|
let state = SyncState {
|
||||||
|
more: false,
|
||||||
|
topics: vec!["logs".into(), "met*".into()],
|
||||||
|
nodes: vec!["kitchen".into(), "lounge".into()],
|
||||||
|
heads: Vec::new(),
|
||||||
|
missing: Vec::new(),
|
||||||
|
};
|
||||||
|
let head = |topic: &str, node: &str| Head {
|
||||||
|
topic: topic.into(),
|
||||||
|
node: node.into(),
|
||||||
|
last_id: 1,
|
||||||
|
};
|
||||||
|
let heads = vec![
|
||||||
|
head("logs", "kitchen"), // sent
|
||||||
|
head("logs", "garage"), // may be sent, its node not taken
|
||||||
|
head("secret", "kitchen"), // may be sent, its topic not taken
|
||||||
|
head("metrics", "kitchen"), // taken, not sent from here: not said
|
||||||
|
head("logs", "lounge"), // the same
|
||||||
|
];
|
||||||
|
let (to_send, not_taken) = sort_heads(&permissions, &state, heads);
|
||||||
|
assert_eq!(to_send, vec![head("logs", "kitchen")]);
|
||||||
|
assert_eq!(
|
||||||
|
not_taken.into_iter().collect::<Vec<_>>(),
|
||||||
|
["logs:garage", "secret:kitchen"]
|
||||||
|
);
|
||||||
|
|
||||||
|
let names: BTreeSet<String> = (0..12).map(|n| format!("t{n:02}:n")).collect();
|
||||||
|
let some = some_names(&names);
|
||||||
|
assert!(some.starts_with("t00:n, t01:n,"), "{some}");
|
||||||
|
assert!(some.ends_with("t09:n and 2 more"), "{some}");
|
||||||
|
assert_eq!(
|
||||||
|
some_names(&names.into_iter().take(2).collect()),
|
||||||
|
"t00:n, t01:n"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn only_a_copy_read_whole_or_missing_a_part_is_damaged() {
|
fn only_a_copy_read_whole_or_missing_a_part_is_damaged() {
|
||||||
|
|||||||
@@ -19,8 +19,8 @@ use bakashrot_server::Server;
|
|||||||
use std::io::{Cursor, Read, Seek, SeekFrom, Write};
|
use std::io::{Cursor, Read, Seek, SeekFrom, Write};
|
||||||
use std::net::TcpStream;
|
use std::net::TcpStream;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::Arc;
|
|
||||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex, Once, PoisonError};
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
use tokio_rustls::rustls::{ClientConfig, ClientConnection, StreamOwned};
|
use tokio_rustls::rustls::{ClientConfig, ClientConnection, StreamOwned};
|
||||||
|
|
||||||
@@ -1692,6 +1692,90 @@ fn sync_state_in_pages() {
|
|||||||
assert_eq!(picky.receive(), None);
|
assert_eq!(picky.receive(), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The servers' log, every test's (tracing's subscriber is global): from
|
||||||
|
/// the first call on.
|
||||||
|
fn log() -> String {
|
||||||
|
static LOG: Mutex<String> = Mutex::new(String::new());
|
||||||
|
struct Writer;
|
||||||
|
impl Write for Writer {
|
||||||
|
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||||
|
let mut log = LOG.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
log.push_str(&String::from_utf8_lossy(bytes));
|
||||||
|
Ok(bytes.len())
|
||||||
|
}
|
||||||
|
fn flush(&mut self) -> std::io::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
static START: Once = Once::new();
|
||||||
|
START.call_once(|| {
|
||||||
|
let _ = tracing_subscriber::fmt()
|
||||||
|
.with_writer(|| Writer)
|
||||||
|
.with_ansi(false)
|
||||||
|
.try_init();
|
||||||
|
});
|
||||||
|
LOG.lock().unwrap_or_else(PoisonError::into_inner).clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a peer doesn't take of what it may be sent is warned about once,
|
||||||
|
/// again when it changes, and not sent.
|
||||||
|
#[test]
|
||||||
|
fn replication_not_taken_is_warned() {
|
||||||
|
log();
|
||||||
|
// b takes only "logs" from its peers.
|
||||||
|
let b = Running::start_with(
|
||||||
|
"not-taken-b",
|
||||||
|
"\n[replication]\naccept_from = [\"127.0.0.1\"]\n",
|
||||||
|
);
|
||||||
|
let config = b.folder.join("server.toml");
|
||||||
|
let b = b.restart_after(|| {
|
||||||
|
let text = std::fs::read_to_string(&config).unwrap();
|
||||||
|
let picky = text.replacen("accept_topics = [\"*\"]", "accept_topics = [\"logs\"]", 1);
|
||||||
|
assert_ne!(text, picky);
|
||||||
|
std::fs::write(&config, picky).unwrap();
|
||||||
|
});
|
||||||
|
let a = b.peer(
|
||||||
|
"not-taken-a",
|
||||||
|
"server-a",
|
||||||
|
&format!(
|
||||||
|
"\n[replication]\npush_to = [\"{}\"]\nsync_interval = \"1s\"\n",
|
||||||
|
b.address
|
||||||
|
),
|
||||||
|
);
|
||||||
|
let mut kitchen = a.connect(&a.issue("kitchen", &["sensor"])).unwrap();
|
||||||
|
kitchen.push("logs", "{}").unwrap();
|
||||||
|
kitchen.push("sensors", "{}").unwrap();
|
||||||
|
|
||||||
|
let mut on_b = b.connect(&b.issue("watcher", &["reader"])).unwrap();
|
||||||
|
let mut on_b_has = |topic: &str| {
|
||||||
|
on_b.get_messages(topic, "kitchen", Some(0), 10)
|
||||||
|
.map(|answer| answer.messages.len())
|
||||||
|
.unwrap_or(0)
|
||||||
|
};
|
||||||
|
wait_for("logs on b", || on_b_has("logs") == 1);
|
||||||
|
let warnings = |names: &str| {
|
||||||
|
let line = format!("({}): doesn't take {names}, which", b.address);
|
||||||
|
log()
|
||||||
|
.lines()
|
||||||
|
.filter(|logged| logged.contains(&line))
|
||||||
|
.count()
|
||||||
|
};
|
||||||
|
wait_for("the warning", || warnings("sensors:kitchen") == 1);
|
||||||
|
// Checked in again and again (every second): not warned again.
|
||||||
|
std::thread::sleep(Duration::from_millis(3500));
|
||||||
|
assert_eq!(warnings("sensors:kitchen"), 1, "{}", log());
|
||||||
|
assert_eq!(on_b_has("sensors"), 0);
|
||||||
|
|
||||||
|
// Another pair it doesn't take: warned again, both named.
|
||||||
|
let mut garage = a.connect(&a.issue("garage", &["sensor"])).unwrap();
|
||||||
|
garage.push("sensors", "{}").unwrap();
|
||||||
|
wait_for("the new warning", || {
|
||||||
|
warnings("sensors:garage, sensors:kitchen") == 1
|
||||||
|
});
|
||||||
|
assert_eq!(warnings("sensors:kitchen"), 1);
|
||||||
|
assert!(!log().contains(&format!("({}): doesn't take logs", b.address)));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn replication_across_pages() {
|
fn replication_across_pages() {
|
||||||
// b with a page and more of pairs before "logs", and kitchen's last id
|
// b with a page and more of pairs before "logs", and kitchen's last id
|
||||||
|
|||||||
@@ -165,6 +165,8 @@ connecting or while connected),
|
|||||||
`list_topics()` / `list_nodes()` (names; `topic=` and `node=`, a name or
|
`list_topics()` / `list_nodes()` (names; `topic=` and `node=`, a name or
|
||||||
a pattern each, filter them: `list_topics(node="kitchen")` the topics
|
a pattern each, filter them: `list_topics(node="kitchen")` the topics
|
||||||
kitchen pushed to), `query()` / `query_raw()`.
|
kitchen pushed to), `query()` / `query_raw()`.
|
||||||
|
Strings go to the DLL as UTF-8 C strings: one with a NUL (a message, a
|
||||||
|
name, SQL, a path) is refused (`INVALID_ARGUMENT`) rather than cut there.
|
||||||
Each `Client` has its own client in the DLL: several can be connected at
|
Each `Client` has its own client in the DLL: several can be connected at
|
||||||
once, from any threads.
|
once, from any threads.
|
||||||
Errors: `RefusedError`, `ConnectionLostError`, `AuthError` (a certificate
|
Errors: `RefusedError`, `ConnectionLostError`, `AuthError` (a certificate
|
||||||
|
|||||||
+10
-1
@@ -126,7 +126,11 @@ otherwise:
|
|||||||
it's behind, the messages after its
|
it's behind, the messages after its
|
||||||
last id, `batch_size` (1000) at a time and about 1 MiB at most (a
|
last id, `batch_size` (1000) at a time and about 1 MiB at most (a
|
||||||
bigger one alone), each batch answered before the next. A refusal
|
bigger one alone), each batch answered before the next. A refusal
|
||||||
leaves that topic and node for the next check-in.
|
leaves that topic and node for the next check-in. Those its roles
|
||||||
|
here may be sent but it doesn't take (not in its roles' `accept_*`
|
||||||
|
there) are skipped and warned about (2026-11-21), the first ten
|
||||||
|
named: once per link, again only when they change, and "takes
|
||||||
|
everything" once none are left. Not at every check-in: it would spam.
|
||||||
3. **The attachments it lacks:** those this server has ready, from the
|
3. **The attachments it lacks:** those this server has ready, from the
|
||||||
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
|
||||||
@@ -394,6 +398,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;
|
||||||
|
- replication not taken (the server's log captured): a topic the peer
|
||||||
|
doesn't take warned about once over several check-ins and not sent,
|
||||||
|
warned again, both named, when another node pushes to it
|
||||||
|
(`replication_not_taken_is_warned`; `push_to.rs`'s
|
||||||
|
`heads_sent_and_not_taken` for what's sent and what's named);
|
||||||
- two peers, one attachment (two raw connections): the second refused
|
- two peers, one attachment (two raw connections): the second refused
|
||||||
while the first sends it (names in any case), the first finishing it;
|
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
|
one gone partway, the other going on from there; one whole but never
|
||||||
|
|||||||
@@ -263,6 +263,15 @@ Also decided (2026-11-13):
|
|||||||
keep it open, close_notify or the socket's end say closed, data
|
keep it open, close_notify or the socket's end say closed, data
|
||||||
sent unasked or a broken TLS stream close it (out of step).
|
sent unasked or a broken TLS stream close it (out of step).
|
||||||
`&mut self` now; the DLL's `IsConnected` unchanged.
|
`&mut self` now; the DLL's `IsConnected` unchanged.
|
||||||
|
- **Names not taken by a peer warned about** (2026-11-21, old open
|
||||||
|
item): what a link's roles here may send but the peer doesn't
|
||||||
|
take is skipped as before, and logged to the console (a warning,
|
||||||
|
the first ten "topic:node" named) once per link, again only when
|
||||||
|
that changes; not at every check-in.
|
||||||
|
- **A NUL refused by Python** (2026-11-21, old item 23): every
|
||||||
|
string going to the DLL as a C string (a message, a name, SQL, a
|
||||||
|
path) with a NUL is refused (`INVALID_ARGUMENT`) rather than cut
|
||||||
|
there, as C# already did.
|
||||||
- **Schema v9, not compatible with v8** (2026-11-13): old databases aren't
|
- **Schema v9, not compatible with v8** (2026-11-13): old databases aren't
|
||||||
opened, their data isn't carried over (the real-life tests start empty).
|
opened, their data isn't carried over (the real-life tests start empty).
|
||||||
`docs/storage.md`:
|
`docs/storage.md`:
|
||||||
@@ -438,13 +447,6 @@ The PureBasic version's, still not fixed:
|
|||||||
2026-11-19: its pages.)
|
2026-11-19: its pages.)
|
||||||
- **Peers are trusted with what they replicate** (12), unless messages
|
- **Peers are trusted with what they replicate** (12), unless messages
|
||||||
get signed by their node: `docs/known-issues.md`.
|
get signed by their node: `docs/known-issues.md`.
|
||||||
- **Names left out of replication aren't warned about:** a topic or
|
|
||||||
node one side doesn't take is skipped silently. Warn once per peer
|
|
||||||
and name, again only when that changes (a log line at every check-in
|
|
||||||
would spam).
|
|
||||||
- **A NUL cuts a message from Python** (23): `push()` passes it to
|
|
||||||
`PushMessageToA` as a C string, `"a\x00b"` is stored as `a`. Refuse
|
|
||||||
it in `push()`, or pass a length.
|
|
||||||
|
|
||||||
## Plan
|
## Plan
|
||||||
|
|
||||||
@@ -486,7 +488,7 @@ by hand.
|
|||||||
| 15 | Filtered lists | `ListNames`' `topics` and `nodes` filters (protocol 8): server, client, `BakaShrot_ListNames` (`A`/`W`), Python, C#, PureBasic, `bakashrot list --topics/--nodes` | `end_to_end.rs` `names` (patterns, case, permissions), `exports.rs`, `check_bakashrot.py`, the NUnit tests | Decided 2026-11-19 | Done 2026-11-19 |
|
| 15 | Filtered lists | `ListNames`' `topics` and `nodes` filters (protocol 8): server, client, `BakaShrot_ListNames` (`A`/`W`), Python, C#, PureBasic, `bakashrot list --topics/--nodes` | `end_to_end.rs` `names` (patterns, case, permissions), `exports.rs`, `check_bakashrot.py`, the NUnit tests | Decided 2026-11-19 | Done 2026-11-19 |
|
||||||
| 16 | The DLL's enumerations | `GetNamesListAsJson`, `GetQueryResultAsJson`; `EnumerateNames` / `EnumerateQuery`, `Next...`, their getters, `CloseEnum` (`enumerations.rs`); `ListTopics` / `ListNodes` dropped; PureBasic's example on them; C#'s `EnumerateTopics` / `EnumerateNodes` / `EnumerateQuery` (`IEnumerable`, asked at each `foreach`) | `exports.rs` `enumerations` (names, query rows and nulls, several at once, bad and closed handles, freed with the client); the NUnit `Enumerations` test | Decided 2026-11-19 | Done 2026-11-19 |
|
| 16 | The DLL's enumerations | `GetNamesListAsJson`, `GetQueryResultAsJson`; `EnumerateNames` / `EnumerateQuery`, `Next...`, their getters, `CloseEnum` (`enumerations.rs`); `ListTopics` / `ListNodes` dropped; PureBasic's example on them; C#'s `EnumerateTopics` / `EnumerateNodes` / `EnumerateQuery` (`IEnumerable`, asked at each `foreach`) | `exports.rs` `enumerations` (names, query rows and nulls, several at once, bad and closed handles, freed with the client); the NUnit `Enumerations` test | Decided 2026-11-19 | Done 2026-11-19 |
|
||||||
| 17 | `SyncState` in pages | `SyncStateRequest.after`, `SyncState.more`, `MAX_HEADS_PER_PACKET` (protocol 8); `heads_after` in storage; both ends of replication | `packets.rs` `the_biggest_sync_state_fits` and the page rules; `storage.rs` heads in pages; `end_to_end.rs` `sync_state_in_pages` (full and partial pages, the lists in the first only, a cursor in another case or not stored, pairs a peer doesn't take skipped, exactly a page, a pattern refused) and `replication_across_pages` (only what's after a head of the second page sent); each part broken on purpose once, every test caught it | Decided 2026-11-19 | Done 2026-11-19 |
|
| 17 | `SyncState` in pages | `SyncStateRequest.after`, `SyncState.more`, `MAX_HEADS_PER_PACKET` (protocol 8); `heads_after` in storage; both ends of replication | `packets.rs` `the_biggest_sync_state_fits` and the page rules; `storage.rs` heads in pages; `end_to_end.rs` `sync_state_in_pages` (full and partial pages, the lists in the first only, a cursor in another case or not stored, pairs a peer doesn't take skipped, exactly a page, a pattern refused) and `replication_across_pages` (only what's after a head of the second page sent); each part broken on purpose once, every test caught it | Decided 2026-11-19 | Done 2026-11-19 |
|
||||||
| 18 | Fixes from a read of the code | The server requiring ALPN; retention ages capped at 100 years; `Ping` / `Pong` (protocol 8) with `BakaShrot_Ping`, Python's and C#'s `ping`, pings in the follows and the replication links; `idle_database_connections` and idle connections closed; a damaged copy told from a failed read-back; the Rust client closing a connection left out of step, `set_answer_timeout`; nothing written once SQLite rolled a batch back; `query_time_limit`, queries stopped when their client leaves, `BakaShrot_SetAnswerTimeout` | `end_to_end.rs` `certificates_refused` (no ALPN: closed), `pings`, `no_idle_database_connections`; `config.rs` the cap, `retention_cutoff`, the key; the server's `pools_keep_few_and_close_the_idle` and `only_a_copy_read_whole_or_missing_a_part_is_damaged` (with `replication` for the damaged copy still dropped); the client's `failures.rs` (a fake server: late, wrong, cut answers and parts) and `revoked_certificates_are_dropped`; storage's `nothing_runs_once_sqlite_rolled_back` and `queries_are_stopped`; `end_to_end.rs` `queries_are_stopped`; `exports.rs` `answer_timeouts`, `codes.rs` (the bindings' codes and copied values), the NUnit `AnswerTimeouts`, PureBasic 5.73 and 6.41 by hand; `packets.rs` samples and bytes; `exports.rs`, `check_bakashrot.py`, the NUnit `Closing` | Decided 2026-11-19 | Done 2026-11-20 |
|
| 18 | Fixes from a read of the code | The server requiring ALPN; retention ages capped at 100 years; `Ping` / `Pong` (protocol 8) with `BakaShrot_Ping`, Python's and C#'s `ping`, pings in the follows and the replication links; `idle_database_connections` and idle connections closed; a damaged copy told from a failed read-back; the Rust client closing a connection left out of step, `set_answer_timeout`; nothing written once SQLite rolled a batch back; `query_time_limit`, queries stopped when their client leaves, `BakaShrot_SetAnswerTimeout`; names a peer doesn't take warned about; a NUL refused by Python | `end_to_end.rs` `certificates_refused` (no ALPN: closed), `pings`, `no_idle_database_connections`; `config.rs` the cap, `retention_cutoff`, the key; the server's `pools_keep_few_and_close_the_idle` and `only_a_copy_read_whole_or_missing_a_part_is_damaged` (with `replication` for the damaged copy still dropped); the client's `failures.rs` (a fake server: late, wrong, cut answers and parts) and `revoked_certificates_are_dropped`; storage's `nothing_runs_once_sqlite_rolled_back` and `queries_are_stopped`; `end_to_end.rs` `queries_are_stopped` and `replication_not_taken_is_warned`, `heads_sent_and_not_taken`; `exports.rs` `answer_timeouts`, `codes.rs` (the bindings' codes and copied values), the NUnit `AnswerTimeouts`, PureBasic 5.73 and 6.41 by hand; `packets.rs` samples and bytes; `exports.rs`, `check_bakashrot.py`, the NUnit `Closing` | Decided 2026-11-19 | Done 2026-11-21 |
|
||||||
|
|
||||||
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
|
||||||
|
|||||||
Reference in New Issue
Block a user