mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Added replication, Added clean stops, logs and releases (0.2.0)
Step 11: the servers replicate by name (push_to and accept_from), their messages and attachments, damaged copies asked for again. Step 12: the server stops cleanly on SIGTERM/SIGINT (Ctrl+C, Ctrl+Break and the console closing on Windows), committing what was queued; logs go to the console, BAKASHROT_LOG sets the level. release.py builds a release per platform (the programs, the DLL, a Python wheel with the library, THIRD-PARTY.txt) and smoke-tests it; CI runs it on v* tags. Built for size (opt-level "s"): 25-31% smaller. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -39,14 +39,17 @@ logs = "30d"
|
||||
"sensors.*" = "12h"
|
||||
"*" = "forever"
|
||||
|
||||
# Who this server replicates with, by address. A link carries messages
|
||||
# one way: the server that dials sends, the one dialed takes them.
|
||||
[replication]
|
||||
peers = [] # dialed: ["10.0.0.2:7000", "server-2.lan:7000"]
|
||||
push_to = [] # dialed and sent to: ["10.0.0.2:7000", "server-2.lan:7000"]
|
||||
accept_from = [] # taken from: ["10.0.0.2", "server-2.lan"], or ["*"]
|
||||
# The only topics replicated at all, whatever the roles say: a filter for
|
||||
# edge nodes. Without it, no filter; [] replicates nothing.
|
||||
# replicated_topics = ["logs", "alerts.*"]
|
||||
retry_delay = "10s"
|
||||
sync_interval = "5s"
|
||||
batch_size = 100 # messages per packet, 1-10000
|
||||
batch_size = 1000 # messages per packet, 1-10000
|
||||
|
||||
# What certificates with a role may do. A certificate gets everything its
|
||||
# roles allow; one without any role listed here is refused. Every key is
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//!
|
||||
//! - [`Server`]: where it listens, its files, its topics, its database.
|
||||
//! - [`Retention`]: how long each topic's messages are kept.
|
||||
//! - [`Replication`]: the peers it dials, what it replicates, how often.
|
||||
//! - [`Replication`]: the servers it sends to and takes from, what it
|
||||
//! replicates, how often.
|
||||
//! - [`Role`]: what certificates with a role may do; [`Permissions`]: what
|
||||
//! a certificate's roles allow together.
|
||||
//!
|
||||
@@ -200,20 +201,26 @@ impl Retention {
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Replication {
|
||||
/// The peers it dials (`host:port`); peers dialing in come by
|
||||
/// themselves. What's replicated with each is its roles'.
|
||||
/// The servers it dials and sends to (`host:port`). What's sent to
|
||||
/// each is its roles' `send_*`.
|
||||
#[serde(deserialize_with = "values::peers")]
|
||||
pub peers: Vec<String>,
|
||||
pub push_to: Vec<String>,
|
||||
/// The servers it takes replicated messages from: IP addresses or
|
||||
/// hostnames, `*` for all; none by default. What's taken is their
|
||||
/// roles' `accept_*`.
|
||||
#[serde(deserialize_with = "values::hosts")]
|
||||
pub accept_from: Vec<String>,
|
||||
/// The only topics replicated at all, whatever the roles say (an edge
|
||||
/// node's filter); none: no filter.
|
||||
pub replicated_topics: Option<NameList>,
|
||||
/// How long to wait before dialing a peer again; 10s by default.
|
||||
#[serde(deserialize_with = "values::duration")]
|
||||
pub retry_delay: Duration,
|
||||
/// How often a linked peer is sent what it misses; 5s by default.
|
||||
/// How long a link waits, once nothing was left to send, before it
|
||||
/// looks again; 5s by default.
|
||||
#[serde(deserialize_with = "values::duration")]
|
||||
pub sync_interval: Duration,
|
||||
/// The most messages sent to a peer per packet; 100 by default.
|
||||
/// The most messages sent to a peer per packet; 1000 by default.
|
||||
#[serde(deserialize_with = "values::batch_size")]
|
||||
pub batch_size: u32,
|
||||
}
|
||||
@@ -221,11 +228,12 @@ pub struct Replication {
|
||||
impl Default for Replication {
|
||||
fn default() -> Self {
|
||||
Replication {
|
||||
peers: Vec::new(),
|
||||
push_to: Vec::new(),
|
||||
accept_from: Vec::new(),
|
||||
replicated_topics: None,
|
||||
retry_delay: Duration::from_secs(10),
|
||||
sync_interval: Duration::from_secs(5),
|
||||
batch_size: 100,
|
||||
batch_size: 1000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,6 +128,30 @@ impl Permissions {
|
||||
.any(|role| role.accept_topics.matches(topic) && role.accept_nodes.matches(node))
|
||||
}
|
||||
|
||||
/// The topics and the nodes taken from it, as `SyncState` lists them:
|
||||
/// its roles' `accept_*` (of those that accept topics), none twice.
|
||||
/// What's taken is still [`Permissions::accepts`]'.
|
||||
pub fn accepted(&self) -> (Vec<String>, Vec<String>) {
|
||||
let (mut topics, mut nodes) = (Vec::<String>::new(), Vec::<String>::new());
|
||||
for role in self
|
||||
.roles
|
||||
.iter()
|
||||
.filter(|role| !role.accept_topics.is_empty())
|
||||
{
|
||||
for (list, entries) in [
|
||||
(&mut topics, role.accept_topics.entries()),
|
||||
(&mut nodes, role.accept_nodes.entries()),
|
||||
] {
|
||||
for entry in entries {
|
||||
if !list.iter().any(|known| names_equal(known, entry)) {
|
||||
list.push(entry.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(topics, nodes)
|
||||
}
|
||||
|
||||
/// Whether it replicates at all: a peer.
|
||||
pub fn replicates(&self) -> bool {
|
||||
self.roles
|
||||
|
||||
@@ -91,16 +91,19 @@ pub(crate) fn is_peer_address(text: &str) -> bool {
|
||||
let port = port.parse::<u16>().is_ok_and(|port| port != 0);
|
||||
let host = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
|
||||
Some(v6) => v6.parse::<Ipv6Addr>().is_ok(),
|
||||
None => {
|
||||
!host.is_empty()
|
||||
&& host
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'-')
|
||||
}
|
||||
None => is_hostname(host),
|
||||
};
|
||||
port && host
|
||||
}
|
||||
|
||||
/// A hostname or an IPv4 address: letters, digits, dots and dashes.
|
||||
fn is_hostname(host: &str) -> bool {
|
||||
!host.is_empty()
|
||||
&& host
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'-')
|
||||
}
|
||||
|
||||
// As serde reads them (`deserialize_with`): a value that's wrong fails
|
||||
// there, and toml says on which line.
|
||||
|
||||
@@ -149,6 +152,27 @@ pub(crate) fn peers<'de, D: Deserializer<'de>>(reader: D) -> Result<Vec<String>,
|
||||
Ok(peers)
|
||||
}
|
||||
|
||||
/// Hosts without a port: IP addresses or hostnames, or `*` for all; none
|
||||
/// twice.
|
||||
pub(crate) fn hosts<'de, D: Deserializer<'de>>(reader: D) -> Result<Vec<String>, D::Error> {
|
||||
let hosts = Vec::<String>::deserialize(reader)?;
|
||||
for (at, host) in hosts.iter().enumerate() {
|
||||
if host != "*" && !is_hostname(host) && host.parse::<Ipv6Addr>().is_err() {
|
||||
return Err(D::Error::custom(format!(
|
||||
"'{host}' isn't an IP address or a hostname (without a port), like \
|
||||
\"10.0.0.2\" or \"server-2.lan\", or \"*\" for all"
|
||||
)));
|
||||
}
|
||||
if hosts[..at]
|
||||
.iter()
|
||||
.any(|before| before.eq_ignore_ascii_case(host))
|
||||
{
|
||||
return Err(D::Error::custom(format!("'{host}' is given twice")));
|
||||
}
|
||||
}
|
||||
Ok(hosts)
|
||||
}
|
||||
|
||||
/// A batch size, 1 to `MAX_MESSAGES_PER_PACKET`.
|
||||
pub(crate) fn batch_size<'de, D: Deserializer<'de>>(reader: D) -> Result<u32, D::Error> {
|
||||
let size = u32::deserialize(reader)?;
|
||||
|
||||
@@ -42,7 +42,8 @@ fn the_example() {
|
||||
assert!(!server.has_topic("sensors"));
|
||||
assert_eq!(server.synchronous, Synchronous::Full);
|
||||
assert_eq!(server.max_attachment_size, 1 << 30);
|
||||
assert_eq!(config.replication.peers, Vec::<String>::new());
|
||||
assert_eq!(config.replication.push_to, Vec::<String>::new());
|
||||
assert_eq!(config.replication.accept_from, Vec::<String>::new());
|
||||
assert_eq!(config.retention.age("logs"), days(30));
|
||||
assert_eq!(
|
||||
config.retention.age("sensors.kitchen"),
|
||||
@@ -65,7 +66,7 @@ fn defaults() {
|
||||
assert_eq!(config.retention.age("logs"), None);
|
||||
assert_eq!(config.replication.retry_delay, Duration::from_secs(10));
|
||||
assert_eq!(config.replication.sync_interval, Duration::from_secs(5));
|
||||
assert_eq!(config.replication.batch_size, 100);
|
||||
assert_eq!(config.replication.batch_size, 1000);
|
||||
assert_eq!(config.replication.replicated_topics, None);
|
||||
assert!(config.roles.is_empty());
|
||||
assert!(config.permissions(&["anything"]).is_none());
|
||||
@@ -81,7 +82,8 @@ max_attachment_size = 0
|
||||
retention_interval = "1h30m"
|
||||
|
||||
[replication]
|
||||
peers = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"]
|
||||
push_to = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"]
|
||||
accept_from = ["10.0.0.2", "server-3.lan", "fd00::4"]
|
||||
retry_delay = "1m"
|
||||
sync_interval = "2s"
|
||||
batch_size = 10000
|
||||
@@ -93,7 +95,8 @@ replicated_topics = ["logs"]
|
||||
assert_eq!(config.server.synchronous, Synchronous::Normal);
|
||||
assert_eq!(config.server.max_attachment_size, 0);
|
||||
assert_eq!(config.server.retention_interval, Duration::from_secs(5400));
|
||||
assert_eq!(config.replication.peers.len(), 3);
|
||||
assert_eq!(config.replication.push_to.len(), 3);
|
||||
assert_eq!(config.replication.accept_from[2], "fd00::4");
|
||||
assert_eq!(config.replication.retry_delay, Duration::from_secs(60));
|
||||
assert_eq!(config.replication.batch_size, 10_000);
|
||||
}
|
||||
@@ -181,6 +184,10 @@ accept_nodes = ["garage"]
|
||||
// A role without the topics replicates nothing, whatever its nodes.
|
||||
let only_peer = config.permissions(&["peer"]).unwrap();
|
||||
assert!(!only_peer.accepts("logs", "kitchen-1"));
|
||||
// What SyncState lists: the accepting roles' lists only.
|
||||
let strings = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(peer.accepted(), (strings(&["*"]), strings(&["garage"])));
|
||||
assert_eq!(only_peer.accepted(), (vec![], vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -324,13 +331,25 @@ fn refusals() {
|
||||
),
|
||||
// [replication]
|
||||
(
|
||||
&with("[replication]\npeers = [\"10.0.0.2\"]\n"),
|
||||
&with("[replication]\npush_to = [\"10.0.0.2\"]\n"),
|
||||
"isn't a host and a port",
|
||||
),
|
||||
(
|
||||
&with("[replication]\npeers = [\"a:1\", \"a:1\"]\n"),
|
||||
&with("[replication]\npush_to = [\"a:1\", \"a:1\"]\n"),
|
||||
"'a:1' is given twice",
|
||||
),
|
||||
(
|
||||
&with("[replication]\naccept_from = [\"10.0.0.2:7000\"]\n"),
|
||||
"without a port",
|
||||
),
|
||||
(
|
||||
&with("[replication]\naccept_from = [\"a.lan\", \"A.lan\"]\n"),
|
||||
"'A.lan' is given twice",
|
||||
),
|
||||
(
|
||||
&with("[replication]\npeers = []\n"),
|
||||
"unknown field `peers`",
|
||||
),
|
||||
(
|
||||
&with("[replication]\nbatch_size = 0\n"),
|
||||
"batch size must be 1 to 10000",
|
||||
|
||||
@@ -29,3 +29,5 @@ workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
bakashrot-client = { path = "../bakashrot-client" }
|
||||
# To damage a stored attachment from a test (the storage's own version).
|
||||
rusqlite = { version = "0.42.0", features = ["bundled"] }
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Replication's receiving end: a server that dialed in sends what this
|
||||
//! one lacks (`push_to.rs` is the other end). Taken only from addresses in
|
||||
//! `[replication] accept_from`, and only what its roles' `accept_*` allow.
|
||||
|
||||
use crate::connection::{Frames, Peer, receive_parts, refused, send};
|
||||
use crate::writer::Write;
|
||||
use crate::{Shared, now};
|
||||
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_SIZE, MAX_MISSING_ATTACHMENTS};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, Continue, MessagePushed, ReplicateAttachment, ReplicateMessages, SyncState,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Whether `address` is in `accept_from`: `*`, an address as written, or
|
||||
/// a hostname resolving to it (looked up now).
|
||||
async fn is_accepted(shared: &Shared, address: IpAddr) -> bool {
|
||||
let address = address.to_canonical();
|
||||
for host in &shared.config.replication.accept_from {
|
||||
if host == "*" {
|
||||
return true;
|
||||
}
|
||||
if let Ok(ip) = host.parse::<IpAddr>() {
|
||||
if ip.to_canonical() == address {
|
||||
return true;
|
||||
}
|
||||
} else if let Ok(found) = tokio::net::lookup_host((host.as_str(), 0)).await
|
||||
&& found
|
||||
.into_iter()
|
||||
.any(|at| at.ip().to_canonical() == address)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Refused unless the connection comes from `accept_from` (looked up at
|
||||
/// its first replication request).
|
||||
async fn check_address(shared: &Shared, peer: &mut Peer) -> Result<(), Packet> {
|
||||
let accepted = match peer.accepted {
|
||||
Some(accepted) => accepted,
|
||||
None => *peer
|
||||
.accepted
|
||||
.insert(is_accepted(shared, peer.address).await),
|
||||
};
|
||||
match accepted {
|
||||
true => Ok(()),
|
||||
false => Err(refused(
|
||||
ErrorCode::NotAllowed,
|
||||
format!(
|
||||
"this server doesn't take replication from {} ({}): not in its accept_from",
|
||||
peer.node, peer.address
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Refused unless the connection comes from `accept_from` and its roles
|
||||
/// accept `node`'s messages in `topic`.
|
||||
async fn check(shared: &Shared, peer: &mut Peer, topic: &str, node: &str) -> Result<(), Packet> {
|
||||
check_address(shared, peer).await?;
|
||||
match peer.permissions.accepts(topic, node) {
|
||||
true => Ok(()),
|
||||
false => Err(refused(
|
||||
ErrorCode::NotAllowed,
|
||||
format!("this server doesn't take {topic}:{node} from {}", peer.node),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// What it takes from this peer, how far it is in those, and the
|
||||
/// attachments it lacks among them.
|
||||
pub(crate) async fn sync_state(shared: &Arc<Shared>, peer: &mut Peer) -> Packet {
|
||||
if let Err(refusal) = check_address(shared, peer).await {
|
||||
return refusal;
|
||||
}
|
||||
let (topics, nodes) = peer.permissions.accepted();
|
||||
let found = shared
|
||||
.read(|reader| {
|
||||
Ok((
|
||||
reader.heads()?,
|
||||
reader.missing_attachments(MAX_MISSING_ATTACHMENTS)?,
|
||||
))
|
||||
})
|
||||
.await;
|
||||
let (mut heads, mut missing) = match found {
|
||||
Ok(found) => found,
|
||||
Err(refusal) => return refusal.into(),
|
||||
};
|
||||
heads.retain(|head| peer.permissions.accepts(&head.topic, &head.node));
|
||||
missing.retain(|missing| peer.permissions.accepts(&missing.topic, &missing.node));
|
||||
SyncState {
|
||||
topics,
|
||||
nodes,
|
||||
heads,
|
||||
missing,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// A batch of a topic and node's messages: stored (those past their age
|
||||
/// here only counted), answered with its last id.
|
||||
pub(crate) async fn replicate_messages(
|
||||
shared: &Arc<Shared>,
|
||||
peer: &mut Peer,
|
||||
batch: ReplicateMessages,
|
||||
) -> Packet {
|
||||
if let Err(refusal) = check(shared, peer, &batch.topic, &batch.node).await {
|
||||
return refusal;
|
||||
}
|
||||
if let Some(big) = batch
|
||||
.messages
|
||||
.iter()
|
||||
.find(|m| m.data.len() > MAX_MESSAGE_SIZE)
|
||||
{
|
||||
return refused(
|
||||
ErrorCode::TooBig,
|
||||
format!("message #{}: {MAX_MESSAGE_SIZE} bytes at most", big.id),
|
||||
);
|
||||
}
|
||||
let skip_before = shared
|
||||
.config
|
||||
.retention
|
||||
.age(&batch.topic)
|
||||
.map_or(0, |age| now().saturating_sub(age.as_millis() as u64));
|
||||
let write = Write::Replicate {
|
||||
topic: batch.topic,
|
||||
node: batch.node,
|
||||
messages: batch.messages,
|
||||
max_attachment_size: shared.config.server.max_attachment_size,
|
||||
skip_before,
|
||||
};
|
||||
match shared.pushes.send(write).await {
|
||||
Ok(message_id) => MessagePushed { message_id }.into(),
|
||||
Err(refusal) => refusal.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// An attachment this server lacks: `Continue`, its parts from where it
|
||||
/// stopped, checked with its SHA-256 (the parts it had read back for it).
|
||||
/// An error closes the connection.
|
||||
pub(crate) async fn replicate_attachment(
|
||||
shared: &Arc<Shared>,
|
||||
peer: &mut Peer,
|
||||
frames: &mut Frames,
|
||||
request: ReplicateAttachment,
|
||||
) -> Result<Packet, String> {
|
||||
if let Err(refusal) = check(shared, peer, &request.topic, &request.node).await {
|
||||
return Ok(refusal);
|
||||
}
|
||||
let message = format!("{}:{}#{}", request.topic, request.node, request.message_id);
|
||||
let ReplicateAttachment {
|
||||
topic,
|
||||
node,
|
||||
message_id,
|
||||
from_part,
|
||||
} = request;
|
||||
let stored = match shared
|
||||
.read(move |reader| reader.attachment(&topic, &node, message_id))
|
||||
.await
|
||||
{
|
||||
Ok(Some(stored)) if stored.state == AttachmentState::Replicating => stored,
|
||||
Ok(_) => {
|
||||
return Ok(refused(
|
||||
ErrorCode::NotFound,
|
||||
format!("{message}: no attachment missing here"),
|
||||
));
|
||||
}
|
||||
Err(refusal) => return Ok(refusal.into()),
|
||||
};
|
||||
let attachment = Attachment {
|
||||
size: stored.size,
|
||||
sha256: stored.sha256,
|
||||
};
|
||||
let next = stored.received / ATTACHMENT_PART_SIZE;
|
||||
if from_part != next || stored.received == stored.size {
|
||||
return Ok(refused(
|
||||
ErrorCode::InvalidRequest,
|
||||
format!("{message}: part {next} is the next one here, not {from_part}"),
|
||||
));
|
||||
}
|
||||
|
||||
// The parts it has, read back for the SHA-256.
|
||||
let sha256 = match shared.hash_parts(stored.id, 0..from_part).await {
|
||||
Ok(sha256) => sha256,
|
||||
Err(refusal) => return Ok(refusal.into()),
|
||||
};
|
||||
let attachment_id = stored.id as u64;
|
||||
send(frames, Continue {}.into())
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
let refusal = receive_parts(
|
||||
shared,
|
||||
frames,
|
||||
attachment_id,
|
||||
&attachment,
|
||||
from_part,
|
||||
sha256,
|
||||
)
|
||||
.await?;
|
||||
if let Some(refusal) = &refusal
|
||||
&& refusal.code != ErrorCode::DataMismatch.code()
|
||||
{
|
||||
// A part not written: it goes on from there next time.
|
||||
return Ok(refusal.clone().into());
|
||||
}
|
||||
let finish = Write::FinishReplicated {
|
||||
attachment: attachment_id,
|
||||
matches: refusal.is_none(),
|
||||
};
|
||||
Ok(match (shared.pushes.send(finish).await, refusal) {
|
||||
(Err(refusal), _) | (Ok(_), Some(refusal)) => refusal.into(),
|
||||
(Ok(_), None) => MessagePushed { message_id }.into(),
|
||||
})
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! a time (`Source/docs/protocol.md`).
|
||||
|
||||
use crate::writer::Write;
|
||||
use crate::{Shared, now};
|
||||
use crate::{Shared, accept_from, now};
|
||||
use aws_lc_rs::digest;
|
||||
use bakashrot_config::Permissions;
|
||||
use bakashrot_pki::Identity;
|
||||
@@ -12,11 +12,11 @@ use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed,
|
||||
Messages, NameKind, NamesList, PushMessage, Query, QueryResult, RequestRefused, Welcome,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, PacketType, frame};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use std::collections::VecDeque;
|
||||
use std::net::SocketAddr;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
@@ -39,27 +39,30 @@ const PART_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// next ones wait (the client with them, through TCP).
|
||||
const PARTS_IN_FLIGHT: usize = 4;
|
||||
|
||||
type Frames = Framed<TlsStream<TcpStream>, LengthDelimitedCodec>;
|
||||
pub(crate) type Frames = Framed<TlsStream<TcpStream>, LengthDelimitedCodec>;
|
||||
|
||||
/// Serves one connection until it ends, logging why.
|
||||
pub(crate) async fn handle(shared: Arc<Shared>, tcp: TcpStream, peer: SocketAddr) {
|
||||
match serve(&shared, tcp).await {
|
||||
match serve(&shared, tcp, peer.ip()).await {
|
||||
Ok(node) => debug!("{peer} ({node}): closed"),
|
||||
Err(why) => info!("{peer}: {why}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Who it is once checked: its node, its certificate's serial (for later
|
||||
/// revocations), what it may do.
|
||||
struct Peer {
|
||||
node: String,
|
||||
/// revocations), what it may do, where it connects from.
|
||||
pub(crate) struct Peer {
|
||||
pub(crate) node: String,
|
||||
serial: Vec<u8>,
|
||||
permissions: Permissions,
|
||||
pub(crate) permissions: Permissions,
|
||||
pub(crate) address: IpAddr,
|
||||
/// Whether `accept_from` has it, once a replication request asked.
|
||||
pub(crate) accepted: Option<bool>,
|
||||
}
|
||||
|
||||
async fn serve(shared: &Arc<Shared>, tcp: TcpStream) -> Result<String, String> {
|
||||
async fn serve(shared: &Arc<Shared>, tcp: TcpStream, address: IpAddr) -> Result<String, String> {
|
||||
tcp.set_nodelay(true).map_err(|error| error.to_string())?;
|
||||
let (mut frames, peer) = timeout(HANDSHAKE_TIMEOUT, open(shared, tcp))
|
||||
let (mut frames, mut peer) = timeout(HANDSHAKE_TIMEOUT, open(shared, tcp, address))
|
||||
.await
|
||||
.map_err(|_| "too slow to connect".to_owned())??;
|
||||
debug!("{} connected", peer.node);
|
||||
@@ -95,11 +98,15 @@ async fn serve(shared: &Arc<Shared>, tcp: TcpStream) -> Result<String, String> {
|
||||
Packet::GetMessages(get) => get_messages(shared, &peer, get).await,
|
||||
Packet::ListNames(list) => list_names(shared, &peer, list).await,
|
||||
Packet::Query(query) => self::query(shared, &peer, query).await,
|
||||
other if is_request(other.packet_type()) => RequestRefused::new(
|
||||
ErrorCode::InvalidRequest,
|
||||
format!("{} isn't answered yet", other.packet_type().name()),
|
||||
)
|
||||
.into(),
|
||||
Packet::SyncStateRequest(_) => accept_from::sync_state(shared, &mut peer).await,
|
||||
Packet::ReplicateMessages(batch) => {
|
||||
accept_from::replicate_messages(shared, &mut peer, batch).await
|
||||
}
|
||||
Packet::ReplicateAttachment(request) => {
|
||||
accept_from::replicate_attachment(shared, &mut peer, &mut frames, request)
|
||||
.await
|
||||
.map_err(|why| format!("{}: {why}", peer.node))?
|
||||
}
|
||||
other => {
|
||||
return Err(format!(
|
||||
"{}: sent {}, not a request",
|
||||
@@ -115,7 +122,11 @@ async fn serve(shared: &Arc<Shared>, tcp: TcpStream) -> Result<String, String> {
|
||||
}
|
||||
|
||||
/// TLS, the versions, the identity, the welcome (or the refusal).
|
||||
async fn open(shared: &Arc<Shared>, tcp: TcpStream) -> Result<(Frames, Peer), String> {
|
||||
async fn open(
|
||||
shared: &Arc<Shared>,
|
||||
tcp: TcpStream,
|
||||
address: IpAddr,
|
||||
) -> Result<(Frames, Peer), String> {
|
||||
let mut stream = shared
|
||||
.acceptor
|
||||
.accept(tcp)
|
||||
@@ -172,6 +183,8 @@ async fn open(shared: &Arc<Shared>, tcp: TcpStream) -> Result<(Frames, Peer), St
|
||||
node: identity.name,
|
||||
serial,
|
||||
permissions,
|
||||
address,
|
||||
accepted: None,
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -238,8 +251,9 @@ async fn push(
|
||||
Ok(upload) => upload,
|
||||
Err(refusal) => return Ok(refusal.into()),
|
||||
};
|
||||
let sha256 = digest::Context::new(&digest::SHA256);
|
||||
let received = match send(frames, Continue {}.into()).await {
|
||||
Ok(()) => receive_parts(shared, frames, upload, &attachment).await,
|
||||
Ok(()) => receive_parts(shared, frames, upload, &attachment, 0, sha256).await,
|
||||
Err(error) => Err(error.to_string()),
|
||||
};
|
||||
let refusal = match received {
|
||||
@@ -264,19 +278,22 @@ async fn push(
|
||||
refusal.map(Packet::from)
|
||||
}
|
||||
|
||||
/// Reads every part of an upload, has the writer store them while the next
|
||||
/// ones come, checks the SHA-256: the refusal if one is due (the parts all
|
||||
/// read even then), an error if the connection must close.
|
||||
async fn receive_parts(
|
||||
/// Reads an attachment's parts from `from_part` on (an upload's, or a
|
||||
/// replicated one's), has the writer store them while the next ones come,
|
||||
/// checks the SHA-256 (`sha256` has the parts before): the refusal if one
|
||||
/// is due (the parts all read even then; `DataMismatch` for the SHA-256),
|
||||
/// an error if the connection must close.
|
||||
pub(crate) async fn receive_parts(
|
||||
shared: &Arc<Shared>,
|
||||
frames: &mut Frames,
|
||||
upload: u64,
|
||||
attachment: &Attachment,
|
||||
from_part: u64,
|
||||
mut sha256: digest::Context,
|
||||
) -> Result<Option<RequestRefused>, String> {
|
||||
let mut sha256 = digest::Context::new(&digest::SHA256);
|
||||
let mut writing = VecDeque::new();
|
||||
let mut refusal = None;
|
||||
for part in 0..attachment.part_count() {
|
||||
for part in from_part..attachment.part_count() {
|
||||
let bytes = match timeout(PART_TIMEOUT, frames.next()).await {
|
||||
Err(_) => return Err(format!("part {part} of an attachment: too slow")),
|
||||
Ok(None) => return Err(format!("closed at part {part} of an attachment")),
|
||||
@@ -495,25 +512,10 @@ async fn query(shared: &Arc<Shared>, peer: &Peer, query: Query) -> Packet {
|
||||
}
|
||||
}
|
||||
|
||||
fn refused(code: ErrorCode, reason: String) -> Packet {
|
||||
pub(crate) fn refused(code: ErrorCode, reason: String) -> Packet {
|
||||
RequestRefused::new(code, reason).into()
|
||||
}
|
||||
|
||||
/// The packets a client or a peer sends: the others are answers.
|
||||
fn is_request(kind: PacketType) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
PacketType::PushMessage
|
||||
| PacketType::GetMessages
|
||||
| PacketType::GetAttachment
|
||||
| PacketType::ListNames
|
||||
| PacketType::Query
|
||||
| PacketType::SyncStateRequest
|
||||
| PacketType::ReplicateMessages
|
||||
| PacketType::ReplicateAttachment
|
||||
)
|
||||
}
|
||||
|
||||
async fn send(frames: &mut Frames, packet: Packet) -> std::io::Result<()> {
|
||||
pub(crate) async fn send(frames: &mut Frames, packet: Packet) -> std::io::Result<()> {
|
||||
frames.send(bytes::Bytes::from(packet.encode())).await
|
||||
}
|
||||
|
||||
@@ -11,12 +11,15 @@
|
||||
//! a revoked certificate's connection is dropped at its next request.
|
||||
//! - [`Server::apply_retention`]: deletes messages past their topic's age
|
||||
//! (`retention.rs`).
|
||||
//!
|
||||
//! What it answers so far: pushes and their attachments, messages,
|
||||
//! attachments, names and queries. Replication comes with step 11
|
||||
//! (`../../revamp.md`, "Plan").
|
||||
//! - [`Server::replicate`]: sends what the servers of `push_to` lack
|
||||
//! (`push_to.rs`); those dialing in, if in `accept_from`, are answered
|
||||
//! by `accept_from.rs`.
|
||||
//! - [`Server::stop`]: commits what was queued for the writer, refuses
|
||||
//! the rest.
|
||||
|
||||
mod accept_from;
|
||||
mod connection;
|
||||
mod push_to;
|
||||
mod retention;
|
||||
mod writer;
|
||||
|
||||
@@ -30,7 +33,7 @@ use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_rustls::TlsAcceptor;
|
||||
use tokio_rustls::{TlsAcceptor, TlsConnector};
|
||||
use tracing::{info, warn};
|
||||
use writer::Pushes;
|
||||
|
||||
@@ -52,6 +55,8 @@ struct Shared {
|
||||
/// The server's own name: its certificate's.
|
||||
name: String,
|
||||
acceptor: TlsAcceptor,
|
||||
/// To dial the servers of `push_to`.
|
||||
connector: TlsConnector,
|
||||
revocations: SharedRevocations,
|
||||
/// The CA's certificate, to check CRLs with.
|
||||
ca: String,
|
||||
@@ -84,6 +89,8 @@ impl Server {
|
||||
let revocations = load_revocations(server.crl.as_deref(), &ca)?.shared();
|
||||
let tls = tls::server_config(&ca, &certificate, &key, revocations.clone())
|
||||
.map_err(|error| format!("the server's TLS: {error}"))?;
|
||||
let dialing = tls::client_config(&ca, &certificate, &key, revocations.clone())
|
||||
.map_err(|error| format!("the TLS to peers: {error}"))?;
|
||||
let database = Database::open(&server.database, server.synchronous)
|
||||
.map_err(|error| error.to_string())?;
|
||||
let pushes = Pushes::start(database.writer().map_err(|error| error.to_string())?)
|
||||
@@ -93,6 +100,7 @@ impl Server {
|
||||
shared: Arc::new(Shared {
|
||||
name,
|
||||
acceptor: TlsAcceptor::from(tls),
|
||||
connector: TlsConnector::from(dialing),
|
||||
revocations,
|
||||
ca,
|
||||
database,
|
||||
@@ -151,6 +159,20 @@ impl Server {
|
||||
retention::run(&self.shared).await
|
||||
}
|
||||
|
||||
/// Keeps a link to each server of `[replication] push_to`, sending
|
||||
/// each what it lacks (again at once after sending, after `sync_interval`
|
||||
/// when there was nothing). Never returns.
|
||||
pub async fn replicate(&self) {
|
||||
push_to::run(self.shared.clone()).await
|
||||
}
|
||||
|
||||
/// Stops writing: every write queued before is committed (and so
|
||||
/// answered), the ones after are refused (`ServerError`, the server
|
||||
/// stopping). Then the server can be dropped, its runtime stopped.
|
||||
pub async fn stop(&self) {
|
||||
self.shared.pushes.stop().await;
|
||||
}
|
||||
|
||||
/// Reloads the CRL file now: how many certificates it revokes.
|
||||
pub fn reload_revocations(&self) -> Result<usize, String> {
|
||||
let shared = &self.shared;
|
||||
@@ -175,6 +197,23 @@ impl Shared {
|
||||
.await
|
||||
}
|
||||
|
||||
/// The SHA-256 of an attachment's stored `parts`, read back one at a
|
||||
/// time (to go on with more, or to compare).
|
||||
async fn hash_parts(
|
||||
self: &Arc<Self>,
|
||||
attachment_id: i64,
|
||||
parts: std::ops::Range<u64>,
|
||||
) -> Result<aws_lc_rs::digest::Context, RequestRefused> {
|
||||
let mut sha256 = aws_lc_rs::digest::Context::new(&aws_lc_rs::digest::SHA256);
|
||||
for part in parts {
|
||||
let data = self
|
||||
.read(move |reader| reader.read_part(attachment_id, part))
|
||||
.await?;
|
||||
sha256.update(&data);
|
||||
}
|
||||
Ok(sha256)
|
||||
}
|
||||
|
||||
/// Runs a client's SQL on a query connection, off the async threads.
|
||||
async fn query(self: &Arc<Self>, sql: String) -> Result<String, RequestRefused> {
|
||||
self.pooled(
|
||||
|
||||
@@ -1,15 +1,33 @@
|
||||
//! `bakashrot-server <config.toml>`: runs a server until Ctrl+C.
|
||||
//! `bakashrot-server <config.toml>`: runs a server until it's told to stop
|
||||
//! (SIGTERM or SIGINT on Linux; Ctrl+C, Ctrl+Break or its console closed
|
||||
//! on Windows), then stops cleanly: what was queued for the database is
|
||||
//! committed first.
|
||||
//!
|
||||
//! Logs go to the console (stdout), `BAKASHROT_LOG` sets their level
|
||||
//! (`error`, `warn`, `info` by default, `debug`, `trace`).
|
||||
|
||||
use bakashrot_config::Config;
|
||||
use bakashrot_server::Server;
|
||||
use std::io::IsTerminal;
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
use tokio::net::TcpListener;
|
||||
use tracing::level_filters::LevelFilter;
|
||||
use tracing::{error, info};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExitCode {
|
||||
tracing_subscriber::fmt().with_target(false).init();
|
||||
let level = std::env::var("BAKASHROT_LOG").ok();
|
||||
let filter = level.as_deref().map_or(Ok(LevelFilter::INFO), str::parse);
|
||||
tracing_subscriber::fmt()
|
||||
.with_target(false)
|
||||
.with_max_level(*filter.as_ref().unwrap_or(&LevelFilter::INFO))
|
||||
// No colour codes in a file or a journal.
|
||||
.with_ansi(std::io::stdout().is_terminal())
|
||||
.init();
|
||||
if filter.is_err() {
|
||||
error!("BAKASHROT_LOG: not a level (error, warn, info, debug, trace), logging info");
|
||||
}
|
||||
let Some(path) = std::env::args_os().nth(1).map(PathBuf::from) else {
|
||||
eprintln!("usage: bakashrot-server <config.toml>");
|
||||
return ExitCode::from(2);
|
||||
@@ -30,11 +48,48 @@ async fn run(path: &std::path::Path) -> Result<(), String> {
|
||||
.await
|
||||
.map_err(|error| format!("listening on {}: {error}", server.listen()))?;
|
||||
info!("{} listening on {}", server.name(), server.listen());
|
||||
tokio::select! {
|
||||
served = server.serve(listener) => served.map_err(|error| format!("accepting: {error}"))?,
|
||||
_ = server.watch_revocations() => {}
|
||||
_ = server.apply_retention() => {}
|
||||
_ = tokio::signal::ctrl_c() => info!("stopping"),
|
||||
}
|
||||
Ok(())
|
||||
let outcome = tokio::select! {
|
||||
served = server.serve(listener) => served.map_err(|error| format!("accepting: {error}")),
|
||||
_ = server.watch_revocations() => Ok(()),
|
||||
_ = server.apply_retention() => Ok(()),
|
||||
_ = server.replicate() => Ok(()),
|
||||
signal = stop_signal() => {
|
||||
info!("{}, stopping", signal?);
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
server.stop().await;
|
||||
info!("stopped");
|
||||
outcome
|
||||
}
|
||||
|
||||
/// The first stop signal: its name.
|
||||
#[cfg(unix)]
|
||||
async fn stop_signal() -> Result<&'static str, String> {
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
let listen = |kind| signal(kind).map_err(|error| format!("listening for signals: {error}"));
|
||||
let (mut terminate, mut interrupt) = (
|
||||
listen(SignalKind::terminate())?,
|
||||
listen(SignalKind::interrupt())?,
|
||||
);
|
||||
Ok(tokio::select! {
|
||||
_ = terminate.recv() => "SIGTERM",
|
||||
_ = interrupt.recv() => "SIGINT",
|
||||
})
|
||||
}
|
||||
|
||||
/// The first stop signal: its name. Closing the console leaves a few
|
||||
/// seconds before Windows ends the process, enough to commit.
|
||||
#[cfg(windows)]
|
||||
async fn stop_signal() -> Result<&'static str, String> {
|
||||
use tokio::signal::windows;
|
||||
let failed = |error: std::io::Error| format!("listening for Ctrl+C: {error}");
|
||||
let mut c = windows::ctrl_c().map_err(failed)?;
|
||||
let mut r#break = windows::ctrl_break().map_err(failed)?;
|
||||
let mut close = windows::ctrl_close().map_err(failed)?;
|
||||
Ok(tokio::select! {
|
||||
_ = c.recv() => "Ctrl+C",
|
||||
_ = r#break.recv() => "Ctrl+Break",
|
||||
_ = close.recv() => "the console closed",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
//! Replication's sending end: a link to each server of
|
||||
//! `[replication] push_to`, kept up (dialed again after `retry_delay`).
|
||||
//! It checks in: asks what the other server takes and has (`SyncState`),
|
||||
//! sends the messages it lacks, by topic and node name, then the
|
||||
//! 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'
|
||||
//! `send_*` allow. `accept_from.rs` is the other end.
|
||||
|
||||
use crate::Shared;
|
||||
use crate::writer::Write;
|
||||
use bakashrot_config::Permissions;
|
||||
use bakashrot_pki::tls;
|
||||
use bakashrot_proto::limits::{ALPN, MAX_PACKET_SIZE};
|
||||
use bakashrot_proto::names::{names_equal, pattern_matches};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, MissingAttachment, ReplicateAttachment, ReplicateMessages,
|
||||
SyncState, SyncStateRequest,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::task::JoinSet;
|
||||
use tokio::time::{sleep, timeout};
|
||||
use tokio_rustls::client::TlsStream;
|
||||
use tokio_util::codec::{Framed, LengthDelimitedCodec};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
/// How long connecting may take: TCP, TLS, the versions, the welcome.
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// How long an answer may take.
|
||||
const ANSWER_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Keeps a link to each server of `push_to`. Never returns.
|
||||
pub(crate) async fn run(shared: Arc<Shared>) {
|
||||
let mut links = JoinSet::new();
|
||||
for address in &shared.config.replication.push_to {
|
||||
links.spawn(keep_linked(shared.clone(), address.clone()));
|
||||
}
|
||||
while links.join_next().await.is_some() {}
|
||||
std::future::pending().await
|
||||
}
|
||||
|
||||
/// Links to `address`, checks in until the link fails, then again after
|
||||
/// `retry_delay`. A failure is logged once until it changes.
|
||||
async fn keep_linked(shared: Arc<Shared>, address: String) {
|
||||
let replication = &shared.config.replication;
|
||||
let mut last_failure = String::new();
|
||||
loop {
|
||||
let failure = match Link::open(&shared, &address).await {
|
||||
Ok(mut link) => {
|
||||
info!("{address}: linked to {}", link.name);
|
||||
last_failure.clear();
|
||||
loop {
|
||||
match link.check_in(&shared).await {
|
||||
Ok(true) => {}
|
||||
Ok(false) => sleep(replication.sync_interval).await,
|
||||
Err(why) => break format!("{} ({address}): {why}", link.name),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(why) => format!("{address}: {why}"),
|
||||
};
|
||||
if failure != last_failure {
|
||||
warn!("{failure}");
|
||||
last_failure = failure;
|
||||
}
|
||||
sleep(replication.retry_delay).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A link to a server: what it is, what it may be sent.
|
||||
struct Link {
|
||||
frames: Framed<TlsStream<TcpStream>, LengthDelimitedCodec>,
|
||||
name: String,
|
||||
permissions: Permissions,
|
||||
/// Whether this check-in sent something it took.
|
||||
sent: bool,
|
||||
}
|
||||
|
||||
impl Link {
|
||||
async fn open(shared: &Shared, address: &str) -> Result<Link, String> {
|
||||
timeout(CONNECT_TIMEOUT, Link::connect(shared, address))
|
||||
.await
|
||||
.map_err(|_| "too slow to connect".to_owned())?
|
||||
}
|
||||
|
||||
/// TCP, TLS, the versions, its roles here, the welcome.
|
||||
async fn connect(shared: &Shared, address: &str) -> Result<Link, String> {
|
||||
let text = |error: std::io::Error| error.to_string();
|
||||
let tcp = TcpStream::connect(address).await.map_err(text)?;
|
||||
tcp.set_nodelay(true).map_err(text)?;
|
||||
let mut stream = shared
|
||||
.connector
|
||||
.connect(tls::server_name(), tcp)
|
||||
.await
|
||||
.map_err(|error| format!("TLS: {error}"))?;
|
||||
if stream.get_ref().1.alpn_protocol() != Some(ALPN) {
|
||||
return Err("not a BakaShrot server".into());
|
||||
}
|
||||
stream
|
||||
.write_all(&frame::version_bytes())
|
||||
.await
|
||||
.map_err(text)?;
|
||||
stream.flush().await.map_err(text)?;
|
||||
let mut theirs = [0; frame::VERSION_SIZE];
|
||||
stream.read_exact(&mut theirs).await.map_err(text)?;
|
||||
frame::check_version(theirs).map_err(|version| format!("speaks protocol {version}"))?;
|
||||
|
||||
let identity = tls::peer_identity(stream.get_ref().1.peer_certificates())
|
||||
.map_err(|error| error.to_string())?;
|
||||
let permissions = shared.config.permissions(&identity.roles).ok_or_else(|| {
|
||||
format!(
|
||||
"{}: none of its roles ({}) is in this server's config",
|
||||
identity.name,
|
||||
identity.roles.join(", ")
|
||||
)
|
||||
})?;
|
||||
let mut link = Link {
|
||||
frames: Framed::new(stream, frame::codec(MAX_PACKET_SIZE)),
|
||||
name: identity.name,
|
||||
permissions,
|
||||
sent: false,
|
||||
};
|
||||
match link.receive().await? {
|
||||
Packet::Welcome(_) => Ok(link),
|
||||
Packet::RequestRefused(refused) => Err(format!("refused: {}", refused.reason)),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// One check-in: what it lacks, the messages then the attachments.
|
||||
/// Whether it sent something it took.
|
||||
async fn check_in(&mut self, shared: &Arc<Shared>) -> Result<bool, String> {
|
||||
self.sent = false;
|
||||
let state = match self.ask(SyncStateRequest {}.into()).await? {
|
||||
Packet::SyncState(state) => state,
|
||||
Packet::RequestRefused(refused) => return Err(format!("refused: {}", refused.reason)),
|
||||
other => return Err(unexpected(&other)),
|
||||
};
|
||||
let heads = shared
|
||||
.read(|reader| reader.heads())
|
||||
.await
|
||||
.map_err(|refused| refused.reason)?;
|
||||
let theirs: HashMap<(String, String), u64> = state
|
||||
.heads
|
||||
.iter()
|
||||
.map(|head| (key(&head.topic, &head.node), head.last_id))
|
||||
.collect();
|
||||
for head in heads {
|
||||
let (topic, node) = (head.topic, head.node);
|
||||
if !self.sends(&state, &topic, &node) {
|
||||
continue;
|
||||
}
|
||||
let after = theirs.get(&key(&topic, &node)).copied().unwrap_or(0);
|
||||
if after < head.last_id {
|
||||
self.send_messages(shared, topic, node, after).await?;
|
||||
}
|
||||
}
|
||||
for missing in state.missing {
|
||||
if self.permissions.sends(&missing.topic, &missing.node) {
|
||||
self.send_attachment(shared, missing).await?;
|
||||
}
|
||||
}
|
||||
Ok(self.sent)
|
||||
}
|
||||
|
||||
/// 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| names_equal(entry, name) || pattern_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
|
||||
/// leaves them for the next check-in.
|
||||
async fn send_messages(
|
||||
&mut self,
|
||||
shared: &Arc<Shared>,
|
||||
topic: String,
|
||||
node: String,
|
||||
mut after: u64,
|
||||
) -> Result<(), String> {
|
||||
let limit = shared.config.replication.batch_size;
|
||||
loop {
|
||||
let (t, n) = (topic.clone(), node.clone());
|
||||
let messages = shared
|
||||
.read(move |reader| reader.to_replicate(&t, &n, after, limit))
|
||||
.await
|
||||
.map_err(|refused| refused.reason)?;
|
||||
let Some(last) = messages.last().map(|message| message.id) else {
|
||||
return Ok(());
|
||||
};
|
||||
let batch = ReplicateMessages {
|
||||
topic: topic.clone(),
|
||||
node: node.clone(),
|
||||
messages,
|
||||
};
|
||||
match self.ask(batch.into()).await? {
|
||||
Packet::MessagePushed(_) => {
|
||||
after = last;
|
||||
self.sent = true;
|
||||
}
|
||||
Packet::RequestRefused(refused) => {
|
||||
debug!("{}: {topic}:{node} refused: {}", self.name, refused.reason);
|
||||
return Ok(());
|
||||
}
|
||||
other => return Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An attachment it lacks, from the part it needs, if this server has
|
||||
/// it. One it says doesn't match its SHA-256 is checked here: a
|
||||
/// damaged copy is asked for again from this server's own peers.
|
||||
async fn send_attachment(
|
||||
&mut self,
|
||||
shared: &Arc<Shared>,
|
||||
missing: MissingAttachment,
|
||||
) -> Result<(), String> {
|
||||
let message = format!("{}:{}#{}", missing.topic, missing.node, missing.message_id);
|
||||
let (topic, node, id) = (
|
||||
missing.topic.clone(),
|
||||
missing.node.clone(),
|
||||
missing.message_id,
|
||||
);
|
||||
let stored = shared
|
||||
.read(move |reader| reader.attachment(&topic, &node, id))
|
||||
.await
|
||||
.map_err(|refused| refused.reason)?;
|
||||
let Some(stored) = stored.filter(|stored| stored.state == AttachmentState::Ready) else {
|
||||
return Ok(());
|
||||
};
|
||||
let attachment = Attachment {
|
||||
size: stored.size,
|
||||
sha256: stored.sha256,
|
||||
};
|
||||
let from_part = missing.next_part;
|
||||
if from_part >= attachment.part_count() {
|
||||
return Ok(());
|
||||
}
|
||||
let request = ReplicateAttachment {
|
||||
topic: missing.topic,
|
||||
node: missing.node,
|
||||
message_id: missing.message_id,
|
||||
from_part,
|
||||
};
|
||||
match self.ask(request.into()).await? {
|
||||
Packet::Continue(_) => {}
|
||||
Packet::RequestRefused(refused) => {
|
||||
debug!(
|
||||
"{}: {message}'s attachment refused: {}",
|
||||
self.name, refused.reason
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
other => return Err(unexpected(&other)),
|
||||
}
|
||||
for part in from_part..attachment.part_count() {
|
||||
// A part that can't be read: the link closes, it asks again.
|
||||
let data = shared
|
||||
.read(move |reader| reader.read_part(stored.id, part))
|
||||
.await
|
||||
.map_err(|refused| format!("part {part} of {message}: {}", refused.reason))?;
|
||||
self.send(AttachmentPart { data }.into()).await?;
|
||||
}
|
||||
match self.receive().await? {
|
||||
Packet::MessagePushed(_) => {
|
||||
debug!("{}: sent {message}'s attachment", self.name);
|
||||
self.sent = true;
|
||||
}
|
||||
Packet::RequestRefused(refused) if refused.code == ErrorCode::DataMismatch.code() => {
|
||||
check_own_copy(shared, stored.id, &attachment, &message).await
|
||||
}
|
||||
Packet::RequestRefused(refused) => debug!(
|
||||
"{}: {message}'s attachment refused: {}",
|
||||
self.name, refused.reason
|
||||
),
|
||||
other => return Err(unexpected(&other)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ask(&mut self, packet: Packet) -> Result<Packet, String> {
|
||||
self.send(packet).await?;
|
||||
self.receive().await
|
||||
}
|
||||
|
||||
async fn send(&mut self, packet: Packet) -> Result<(), String> {
|
||||
self.frames
|
||||
.send(bytes::Bytes::from(packet.encode()))
|
||||
.await
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
async fn receive(&mut self) -> Result<Packet, String> {
|
||||
match timeout(ANSWER_TIMEOUT, self.frames.next()).await {
|
||||
Err(_) => Err("no answer in time".into()),
|
||||
Ok(None) => Err("closed the link".into()),
|
||||
Ok(Some(bytes)) => {
|
||||
let bytes = bytes.map_err(|error| error.to_string())?;
|
||||
Packet::decode(&bytes).map_err(|error| error.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The other server said this server's copy doesn't match its SHA-256:
|
||||
/// read it back; damaged, it's asked for again from this server's peers
|
||||
/// (and not served meanwhile), instead of sent again and again.
|
||||
async fn check_own_copy(
|
||||
shared: &Arc<Shared>,
|
||||
attachment_id: i64,
|
||||
attachment: &Attachment,
|
||||
message: &str,
|
||||
) {
|
||||
let read = shared.hash_parts(attachment_id, 0..attachment.part_count());
|
||||
if let Ok(sha256) = read.await
|
||||
&& sha256.finish().as_ref() == attachment.sha256
|
||||
{
|
||||
return;
|
||||
}
|
||||
let damaged = Write::Damaged {
|
||||
attachment: attachment_id as u64,
|
||||
};
|
||||
match shared.pushes.send(damaged).await {
|
||||
Ok(_) => {
|
||||
warn!("{message}: this server's copy of its attachment is damaged, asked for again")
|
||||
}
|
||||
Err(refused) => warn!("{message}: a damaged attachment: {}", refused.reason),
|
||||
}
|
||||
}
|
||||
|
||||
/// A topic and node, to compare without case.
|
||||
fn key(topic: &str, node: &str) -> (String, String) {
|
||||
(topic.to_ascii_lowercase(), node.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
fn unexpected(packet: &Packet) -> String {
|
||||
format!("answered {}", packet.packet_type().name())
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
//! The writer's thread: every write goes through one queue, and the thread
|
||||
//! writes whatever is queued in one transaction (a group commit): the
|
||||
//! busier, the bigger the groups.
|
||||
//! busier, the bigger the groups. [`Pushes::stop`] ends it once what was
|
||||
//! queued before is committed.
|
||||
|
||||
use crate::refusal;
|
||||
use bakashrot_proto::packets::RequestRefused;
|
||||
use bakashrot_proto::packets::{ReplicatedMessage, RequestRefused};
|
||||
use bakashrot_storage::{Batch, Writer};
|
||||
use std::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
@@ -52,6 +53,19 @@ pub(crate) enum Write {
|
||||
/// Deletes deleted messages' attachment parts, `max_parts` at most:
|
||||
/// how many.
|
||||
PurgeAttachments { max_parts: usize },
|
||||
/// A peer's messages: the topic and node's last id.
|
||||
Replicate {
|
||||
topic: String,
|
||||
node: String,
|
||||
messages: Vec<ReplicatedMessage>,
|
||||
max_attachment_size: u64,
|
||||
skip_before: u64,
|
||||
},
|
||||
/// A replicated attachment all of whose parts came: ready if it
|
||||
/// `matches` its SHA-256, started over otherwise. 0.
|
||||
FinishReplicated { attachment: u64, matches: bool },
|
||||
/// This server's own copy found damaged: asked for again. 0.
|
||||
Damaged { attachment: u64 },
|
||||
}
|
||||
|
||||
impl Write {
|
||||
@@ -88,13 +102,32 @@ impl Write {
|
||||
Write::PurgeAttachments { max_parts } => batch
|
||||
.purge_attachments(*max_parts)
|
||||
.map(|count| count as u64),
|
||||
Write::Replicate {
|
||||
topic,
|
||||
node,
|
||||
messages,
|
||||
max_attachment_size,
|
||||
skip_before,
|
||||
} => batch.replicate(topic, node, messages, *max_attachment_size, *skip_before),
|
||||
Write::FinishReplicated {
|
||||
attachment,
|
||||
matches,
|
||||
} => batch
|
||||
.finish_replicated(*attachment as i64, *matches)
|
||||
.map(|()| 0),
|
||||
Write::Damaged { attachment } => batch.damaged(*attachment as i64).map(|()| 0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Job {
|
||||
write: Write,
|
||||
done: oneshot::Sender<Outcome>,
|
||||
/// What the writer's thread is sent.
|
||||
enum Job {
|
||||
Write {
|
||||
write: Write,
|
||||
done: oneshot::Sender<Outcome>,
|
||||
},
|
||||
/// Stop once the writes queued before are committed, then say so.
|
||||
Stop(oneshot::Sender<()>),
|
||||
}
|
||||
|
||||
/// The queue to the writer's thread.
|
||||
@@ -103,30 +136,51 @@ pub(crate) struct Pushes {
|
||||
}
|
||||
|
||||
impl Pushes {
|
||||
/// Starts the writer's thread on `writer`. It ends with the queue.
|
||||
/// Starts the writer's thread on `writer`. It ends with the queue, or
|
||||
/// at [`Pushes::stop`].
|
||||
pub(crate) fn start(mut writer: Writer) -> std::io::Result<Pushes> {
|
||||
let (queue, pending) = mpsc::channel::<Job>();
|
||||
std::thread::Builder::new()
|
||||
.name("writer".into())
|
||||
.spawn(move || {
|
||||
while let Ok(first) = pending.recv() {
|
||||
let mut group = vec![first];
|
||||
while group.len() < MAX_GROUP {
|
||||
let Ok(next) = pending.try_recv() else { break };
|
||||
group.push(next);
|
||||
let (mut group, mut stopped) = (Vec::new(), None);
|
||||
for job in std::iter::once(first).chain(pending.try_iter()) {
|
||||
match job {
|
||||
Job::Write { write, done } => group.push((write, done)),
|
||||
Job::Stop(done) => stopped = Some(done),
|
||||
}
|
||||
if stopped.is_some() || group.len() == MAX_GROUP {
|
||||
break;
|
||||
}
|
||||
}
|
||||
write(&mut writer, group);
|
||||
if let Some(done) = stopped {
|
||||
// Writes queued after are dropped with the queue,
|
||||
// refused as the server stopping.
|
||||
let _ = done.send(());
|
||||
return;
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(Pushes { queue })
|
||||
}
|
||||
|
||||
/// Stops the writer's thread once every write queued before is
|
||||
/// committed; the ones after are refused, the server stopping.
|
||||
pub(crate) async fn stop(&self) {
|
||||
let (done, stopped) = oneshot::channel();
|
||||
if self.queue.send(Job::Stop(done)).is_ok() {
|
||||
let _ = stopped.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Queues a write now (writes are done in the order queued), its
|
||||
/// outcome once its group is committed. Dropping the future doesn't
|
||||
/// take the write back.
|
||||
pub(crate) fn send(&self, write: Write) -> impl Future<Output = Outcome> + use<> {
|
||||
let (done, outcome) = oneshot::channel();
|
||||
let queued = self.queue.send(Job { write, done });
|
||||
let queued = self.queue.send(Job::Write { write, done });
|
||||
async move {
|
||||
queued.map_err(|_| stopped())?;
|
||||
outcome.await.unwrap_or_else(|_| Err(stopped()))
|
||||
@@ -135,11 +189,14 @@ impl Pushes {
|
||||
}
|
||||
|
||||
/// Writes a group in one transaction, then answers each write.
|
||||
fn write(writer: &mut Writer, group: Vec<Job>) {
|
||||
fn write(writer: &mut Writer, group: Vec<(Write, oneshot::Sender<Outcome>)>) {
|
||||
if group.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut outcomes = Vec::with_capacity(group.len());
|
||||
let committed = writer.batch(|batch| {
|
||||
for job in &group {
|
||||
outcomes.push(job.write.run(batch).map_err(refusal));
|
||||
for (write, _) in &group {
|
||||
outcomes.push(write.run(batch).map_err(refusal));
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
@@ -147,9 +204,9 @@ fn write(writer: &mut Writer, group: Vec<Job>) {
|
||||
let refused = refusal(error);
|
||||
outcomes = group.iter().map(|_| Err(refused.clone())).collect();
|
||||
}
|
||||
for (job, outcome) in group.into_iter().zip(outcomes) {
|
||||
for ((_, done), outcome) in group.into_iter().zip(outcomes) {
|
||||
// Its connection may be gone: nothing to answer then.
|
||||
let _ = job.done.send(outcome);
|
||||
let _ = done.send(outcome);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
//! A server on a free port, clients over TLS: pushes and reads, runs of
|
||||
//! messages, big ones, names, queries, attachments, retention, refusals,
|
||||
//! certificates refused, revoked ones dropped, pushes at once.
|
||||
//! messages, big ones, names, queries, attachments, retention, replication
|
||||
//! between servers, refusals, certificates refused, revoked ones dropped,
|
||||
//! pushes at once.
|
||||
|
||||
use bakashrot_client::{Client, Settings};
|
||||
use bakashrot_config::Config;
|
||||
use bakashrot_pki::{Ca, Identity, Issued, Revocations, Usage, summarize, tls};
|
||||
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_SIZE, MAX_PACKET_SIZE};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, GetAttachment, Messages, NameKind, PushMessage, StoredAttachment,
|
||||
Attachment, AttachmentPart, GetAttachment, MessagePushed, Messages, NameKind, PushMessage,
|
||||
ReplicateAttachment, ReplicateMessages, ReplicatedMessage, StoredAttachment, SyncState,
|
||||
SyncStateRequest,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use bakashrot_server::Server;
|
||||
@@ -38,17 +41,22 @@ read_topics = ["logs"]
|
||||
|
||||
[roles.analyst]
|
||||
query = true
|
||||
|
||||
[roles.peer]
|
||||
send_topics = ["*"]
|
||||
accept_topics = ["*"]
|
||||
"#;
|
||||
|
||||
/// A server running on a free port, its CA and folder.
|
||||
struct Running {
|
||||
folder: PathBuf,
|
||||
ca: Ca,
|
||||
ca_issued: Issued,
|
||||
ca_certificate: String,
|
||||
server: Server,
|
||||
address: String,
|
||||
// Kept for the server's tasks to run.
|
||||
_runtime: tokio::runtime::Runtime,
|
||||
runtime: tokio::runtime::Runtime,
|
||||
}
|
||||
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
@@ -68,19 +76,30 @@ impl Running {
|
||||
Running::start_with(name, "")
|
||||
}
|
||||
|
||||
/// With more `[server]` settings.
|
||||
/// With more `[server]` settings (and sections after them).
|
||||
fn start_with(name: &str, settings: &str) -> Running {
|
||||
let folder = folder(name);
|
||||
let issued = Ca::create("Test CA", 10).unwrap();
|
||||
let ca = Ca::load(&issued.certificate, &issued.key).unwrap();
|
||||
let ca = Ca::create("Test CA", 10).unwrap();
|
||||
Running::start_in(folder(name), ca, "server-1", settings, "127.0.0.1:0")
|
||||
}
|
||||
|
||||
/// Another server with the same CA, named `server`.
|
||||
fn peer(&self, name: &str, server: &str, settings: &str) -> Running {
|
||||
let ca = self.ca_issued.clone();
|
||||
Running::start_in(folder(name), ca, server, settings, "127.0.0.1:0")
|
||||
}
|
||||
|
||||
fn start_in(
|
||||
folder: PathBuf,
|
||||
ca_issued: Issued,
|
||||
name: &str,
|
||||
settings: &str,
|
||||
bind: &str,
|
||||
) -> Running {
|
||||
let ca = Ca::load(&ca_issued.certificate, &ca_issued.key).unwrap();
|
||||
let server = ca
|
||||
.issue(
|
||||
&Identity::new("server-1", &["peer"]).unwrap(),
|
||||
Usage::Server,
|
||||
10,
|
||||
)
|
||||
.issue(&Identity::new(name, &["peer"]).unwrap(), Usage::Server, 10)
|
||||
.unwrap();
|
||||
std::fs::write(folder.join("ca.crt"), &issued.certificate).unwrap();
|
||||
std::fs::write(folder.join("ca.crt"), &ca_issued.certificate).unwrap();
|
||||
std::fs::write(folder.join("server.crt"), &server.certificate).unwrap();
|
||||
std::fs::write(folder.join("server.key"), &server.key).unwrap();
|
||||
let config = CONFIG.replace(
|
||||
@@ -91,25 +110,50 @@ impl Running {
|
||||
),
|
||||
);
|
||||
std::fs::write(folder.join("server.toml"), config).unwrap();
|
||||
Running::run(folder, ca, ca_issued, bind)
|
||||
}
|
||||
|
||||
/// Stopped as `bakashrot-server` stops, `meanwhile` run, then started
|
||||
/// again on the same database and address.
|
||||
fn restart_after(self, meanwhile: impl FnOnce()) -> Running {
|
||||
let Running {
|
||||
folder,
|
||||
ca,
|
||||
ca_issued,
|
||||
server,
|
||||
address,
|
||||
runtime,
|
||||
..
|
||||
} = self;
|
||||
runtime.block_on(server.stop());
|
||||
runtime.shutdown_background();
|
||||
meanwhile();
|
||||
Running::run(folder, ca, ca_issued, &address)
|
||||
}
|
||||
|
||||
/// Its `server.toml` served on `bind`, retention and replication going.
|
||||
fn run(folder: PathBuf, ca: Ca, ca_issued: Issued, bind: &str) -> Running {
|
||||
let config = Config::load(&folder.join("server.toml")).unwrap();
|
||||
let server = Server::start(config).unwrap();
|
||||
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
let listener = runtime
|
||||
.block_on(tokio::net::TcpListener::bind("127.0.0.1:0"))
|
||||
.block_on(tokio::net::TcpListener::bind(bind))
|
||||
.unwrap();
|
||||
let address = listener.local_addr().unwrap().to_string();
|
||||
let serving = server.clone();
|
||||
runtime.spawn(async move { serving.serve(listener).await });
|
||||
let retaining = server.clone();
|
||||
runtime.spawn(async move { retaining.apply_retention().await });
|
||||
let replicating = server.clone();
|
||||
runtime.spawn(async move { replicating.replicate().await });
|
||||
Running {
|
||||
folder,
|
||||
ca,
|
||||
ca_certificate: issued.certificate,
|
||||
ca_certificate: ca_issued.certificate.clone(),
|
||||
ca_issued,
|
||||
server,
|
||||
address,
|
||||
_runtime: runtime,
|
||||
runtime,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -997,6 +1041,44 @@ fn attachment_edges() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_cleanly() {
|
||||
// 8 nodes pushing flat out, the server stopped under them: every push
|
||||
// answered is stored, the ones after refused as the server stopping.
|
||||
let running = Running::start("stop");
|
||||
let threads: Vec<_> = (0..8)
|
||||
.map(|n| {
|
||||
let mut client = running
|
||||
.connect(&running.issue(&format!("n{n}"), &["sensor"]))
|
||||
.unwrap();
|
||||
std::thread::spawn(move || {
|
||||
let mut answered = 0;
|
||||
loop {
|
||||
match client.push("logs", "{}") {
|
||||
Ok(id) => answered = id,
|
||||
Err(error) => return (answered, error.code()),
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
running.runtime.block_on(running.server.stop());
|
||||
let stopped: Vec<(u64, u32)> = threads.into_iter().map(|t| t.join().unwrap()).collect();
|
||||
|
||||
let running = running.restart_after(|| {});
|
||||
let mut reader = running
|
||||
.connect(&running.issue("reader", &["reader"]))
|
||||
.unwrap();
|
||||
for (n, (answered, code)) in stopped.into_iter().enumerate() {
|
||||
assert_eq!(code, ErrorCode::ServerError.code(), "n{n}");
|
||||
assert!(answered > 0, "n{n} pushed nothing");
|
||||
let latest = reader.get_messages("logs", &format!("n{n}"), None, 1);
|
||||
// The last push may have been committed after its answer was lost.
|
||||
assert!(latest.unwrap().messages[0].id >= answered, "n{n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retention() {
|
||||
// logs kept 2 s, sensors forever; looked at every second.
|
||||
@@ -1050,3 +1132,393 @@ fn retention() {
|
||||
let latest = kitchen.get_messages("logs", "kitchen", None, 1).unwrap();
|
||||
assert_eq!(latest.messages[0].id, 4);
|
||||
}
|
||||
|
||||
/// Replication flat out, as the old `Tests/Bench/Bench-Replication.ps1`
|
||||
/// (`-Parts Ramp -Ramp 10x0`): 4 servers in a Y (a hub pushing to 3
|
||||
/// leaves, each pushing to the hub), `NODES` nodes (10) pushing to each
|
||||
/// as fast as they're answered for `SECONDS` (30), then how far behind
|
||||
/// each server is and how long until every one has every message. Run
|
||||
/// with `cargo test --release -p bakashrot-server --test end_to_end
|
||||
/// replication_rate -- --ignored --nocapture` (`SYNC`: `full`, the
|
||||
/// default, or `normal`).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn replication_rate() {
|
||||
let env =
|
||||
|name: &str, default: u64| std::env::var(name).map_or(default, |v| v.parse().unwrap());
|
||||
let (nodes, seconds) = (env("NODES", 10), env("SECONDS", 30));
|
||||
let sync = std::env::var("SYNC").unwrap_or_else(|_| "full".into());
|
||||
let batch = env("BATCH", 1000);
|
||||
// Free ports first: every server's push_to names the others.
|
||||
let addresses: Vec<String> = (0..4)
|
||||
.map(|_| {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
listener.local_addr().unwrap().to_string()
|
||||
})
|
||||
.collect();
|
||||
let ca = Ca::create("Bench CA", 10).unwrap();
|
||||
let servers: Vec<Running> = (0..4)
|
||||
.map(|n| {
|
||||
let push_to = match n {
|
||||
0 => addresses[1..].join("\", \""),
|
||||
_ => addresses[0].clone(),
|
||||
};
|
||||
let settings = format!(
|
||||
"synchronous = \"{sync}\"\n\n[replication]\npush_to = [\"{push_to}\"]\n\
|
||||
accept_from = [\"127.0.0.1\"]\nbatch_size = {batch}\n"
|
||||
);
|
||||
let name = format!("server-{n}");
|
||||
Running::start_in(folder(&name), ca.clone(), &name, &settings, &addresses[n])
|
||||
})
|
||||
.collect();
|
||||
let json = format!(
|
||||
r#"{{"kind":"temp","value":21.37,"pad":"{}"}}"#,
|
||||
"x".repeat(160)
|
||||
);
|
||||
let clients: Vec<Client> = servers
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(s, server)| {
|
||||
(0..nodes).map(move |n| {
|
||||
server
|
||||
.connect(&server.issue(&format!("s{s}n{n}"), &["sensor"]))
|
||||
.unwrap()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut analysts: Vec<Client> = servers
|
||||
.iter()
|
||||
.map(|server| {
|
||||
server
|
||||
.connect(&server.issue("analyst", &["analyst"]))
|
||||
.unwrap()
|
||||
})
|
||||
.collect();
|
||||
let mut counts = || -> Vec<u64> {
|
||||
analysts
|
||||
.iter_mut()
|
||||
.map(|analyst| {
|
||||
let result = analyst.query("SELECT COUNT(*) AS n FROM data").unwrap();
|
||||
result[r#"{"columns":["n"],"rows":[[""#.len()..result.len() - 4]
|
||||
.parse()
|
||||
.unwrap()
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
|
||||
let start = Instant::now();
|
||||
let until = start + Duration::from_secs(seconds);
|
||||
let threads: Vec<_> = clients
|
||||
.into_iter()
|
||||
.map(|mut client| {
|
||||
let json = json.clone();
|
||||
std::thread::spawn(move || {
|
||||
let (mut pushed, mut slowest) = (0u64, Duration::ZERO);
|
||||
while Instant::now() < until {
|
||||
let push = Instant::now();
|
||||
client.push("logs", &json).unwrap();
|
||||
slowest = slowest.max(push.elapsed());
|
||||
pushed += 1;
|
||||
}
|
||||
(pushed, slowest)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let results: Vec<(u64, Duration)> = threads.into_iter().map(|t| t.join().unwrap()).collect();
|
||||
let pushing = start.elapsed().as_secs_f64();
|
||||
let total: u64 = results.iter().map(|(pushed, _)| pushed).sum();
|
||||
let slowest = results.iter().map(|(_, slowest)| *slowest).max().unwrap();
|
||||
let at_end = counts();
|
||||
let drain = Instant::now();
|
||||
while counts().iter().any(|&count| count < total) {
|
||||
assert!(drain.elapsed() < Duration::from_secs(300), "not drained");
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
let drained = drain.elapsed().as_secs_f64();
|
||||
let behind: Vec<String> = at_end
|
||||
.iter()
|
||||
.map(|&count| format!("{:.1} s", (total - count) as f64 / (total as f64 / pushing)))
|
||||
.collect();
|
||||
println!(
|
||||
"{sync}, 4 servers x {nodes} nodes, {seconds} s: {total} pushes, {:.0}/s, slowest {} ms; \
|
||||
behind at the end (s of pushes; hub, leaves): {}; all everywhere {drained:.1} s later",
|
||||
total as f64 / pushing,
|
||||
slowest.as_millis(),
|
||||
behind.join(", ")
|
||||
);
|
||||
}
|
||||
|
||||
/// Waits up to 15 s for `done`, every 100 ms.
|
||||
fn wait_for(what: &str, mut done: impl FnMut() -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_secs(15);
|
||||
while !done() {
|
||||
assert!(Instant::now() < deadline, "{what}: not in time");
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replication() {
|
||||
// a pushes to b (and c); b takes from 127.0.0.1, c from elsewhere only.
|
||||
let b = Running::start_with(
|
||||
"replication-b",
|
||||
"\n[replication]\naccept_from = [\"127.0.0.1\"]\n",
|
||||
);
|
||||
let c = b.peer(
|
||||
"replication-c",
|
||||
"server-c",
|
||||
"\n[replication]\naccept_from = [\"10.9.9.9\"]\n",
|
||||
);
|
||||
let a = b.peer(
|
||||
"replication-a",
|
||||
"server-a",
|
||||
&format!(
|
||||
"\n[replication]\npush_to = [\"{}\", \"{}\"]\nsync_interval = \"1s\"\n\
|
||||
retry_delay = \"1s\"\n",
|
||||
b.address, c.address
|
||||
),
|
||||
);
|
||||
let kitchen = a.issue("kitchen", &["sensor", "reader"]);
|
||||
let mut on_a = a.connect(&kitchen).unwrap();
|
||||
let file = bytes(2 * MIB + 5, 9);
|
||||
on_a.push_with_attachment("logs", "{\"n\":1}", &mut Cursor::new(&file))
|
||||
.unwrap();
|
||||
on_a.push("logs", "{\"n\":2}").unwrap();
|
||||
on_a.push("logs", "not json").unwrap();
|
||||
on_a.push("sensors", "{}").unwrap();
|
||||
|
||||
// b gets them all, by name, with their ids, times and attachment.
|
||||
let mut on_b = b.connect(&b.issue("watcher", &["reader"])).unwrap();
|
||||
let read = |client: &mut Client, topic: &str| {
|
||||
client
|
||||
.get_messages(topic, "kitchen", Some(0), 100)
|
||||
.map(|answer| answer.messages)
|
||||
.unwrap_or_default()
|
||||
};
|
||||
wait_for("the messages on b", || {
|
||||
read(&mut on_b, "logs").len() == 3 && read(&mut on_b, "sensors").len() == 1
|
||||
});
|
||||
let (sent, got) = (read(&mut on_a, "logs"), read(&mut on_b, "logs"));
|
||||
let fields = |m: &bakashrot_proto::packets::MessageEntry| (m.id, m.pushed_at, m.data.clone());
|
||||
assert_eq!(
|
||||
sent.iter().map(fields).collect::<Vec<_>>(),
|
||||
got.iter().map(fields).collect::<Vec<_>>()
|
||||
);
|
||||
wait_for("the attachment on b", || {
|
||||
let mut out = Vec::new();
|
||||
on_b.get_attachment("logs", "kitchen", 1, &mut out).is_ok() && out == file
|
||||
});
|
||||
|
||||
// c doesn't take from a: not in its accept_from.
|
||||
let mut analyst = c.connect(&c.issue("analyst", &["analyst"])).unwrap();
|
||||
assert_eq!(
|
||||
analyst.query("SELECT COUNT(*) AS n FROM messages").unwrap(),
|
||||
r#"{"columns":["n"],"rows":[["0"]]}"#
|
||||
);
|
||||
|
||||
// One way: b's own pushes don't go to a (b has no push_to).
|
||||
let mut garage = b.connect(&b.issue("garage", &["sensor"])).unwrap();
|
||||
garage.push("logs", "{}").unwrap();
|
||||
std::thread::sleep(Duration::from_millis(2500));
|
||||
assert_eq!(
|
||||
code(
|
||||
on_a.get_messages("logs", "garage", Some(0), 10)
|
||||
.unwrap_err()
|
||||
),
|
||||
ErrorCode::UnknownName.code()
|
||||
);
|
||||
|
||||
// b stopped: a links again once it's back, sends what came meanwhile,
|
||||
// ids go on. Meanwhile a's copy of #6's attachment got damaged.
|
||||
drop((on_b, garage));
|
||||
let b = b.restart_after(|| {
|
||||
assert_eq!(on_a.push("logs", "{\"n\":4}").unwrap(), 4);
|
||||
assert_eq!(on_a.push("logs", "{\"n\":5}").unwrap(), 5);
|
||||
let other = bytes(MIB + 1, 3);
|
||||
let id = on_a
|
||||
.push_with_attachment("logs", "{\"n\":6}", &mut Cursor::new(&other))
|
||||
.unwrap();
|
||||
assert_eq!(id, 6);
|
||||
let raw = rusqlite::Connection::open(a.folder.join("bakashrot.sqlite")).unwrap();
|
||||
raw.execute(
|
||||
"UPDATE attachment_parts SET part_data = zeroblob(length(part_data)) \
|
||||
WHERE key = (SELECT max(key) FROM attachment_parts)",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
let mut on_b = b.connect(&b.issue("watcher", &["reader"])).unwrap();
|
||||
wait_for("the messages on b, restarted", || {
|
||||
read(&mut on_b, "logs")
|
||||
.iter()
|
||||
.map(|m| m.id)
|
||||
.collect::<Vec<_>>()
|
||||
== [1, 2, 3, 4, 5, 6]
|
||||
});
|
||||
|
||||
// b refuses the damaged copy; a finds its own damaged and asks for it
|
||||
// again, instead of sending it again and again.
|
||||
wait_for("a's damaged copy noticed", || {
|
||||
on_a.get_attachment("logs", "kitchen", 6, &mut Vec::new())
|
||||
.is_err_and(|error| error.code() == ErrorCode::NotReady.code())
|
||||
});
|
||||
assert_eq!(
|
||||
code(
|
||||
on_b.get_attachment("logs", "kitchen", 6, &mut Vec::new())
|
||||
.unwrap_err()
|
||||
),
|
||||
ErrorCode::NotReady.code()
|
||||
);
|
||||
}
|
||||
|
||||
/// A server's `SyncState`, asked over `raw`.
|
||||
fn sync_state(raw: &mut Raw) -> SyncState {
|
||||
raw.send(SyncStateRequest {});
|
||||
match raw.receive() {
|
||||
Some(Packet::SyncState(state)) => state,
|
||||
other => panic!("expected a SyncState, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replication_edges() {
|
||||
// The test plays the peer, over a raw connection.
|
||||
let running = Running::start_with(
|
||||
"replication-edges",
|
||||
"\n[replication]\naccept_from = [\"127.0.0.1\"]\n\n[retention]\nold = \"1h\"\n",
|
||||
);
|
||||
let peer = running.issue("server-x", &["peer"]);
|
||||
let mut raw = Raw::connect(&running, &peer);
|
||||
let state = sync_state(&mut raw);
|
||||
assert_eq!(
|
||||
(state.topics, state.nodes),
|
||||
(vec!["*".into()], vec!["*".into()])
|
||||
);
|
||||
assert!(state.heads.is_empty() && state.missing.is_empty());
|
||||
|
||||
let file = bytes(2 * MIB + 1, 5);
|
||||
let message = |id, pushed_at, attachment| ReplicatedMessage {
|
||||
id,
|
||||
pushed_at,
|
||||
data: format!("m{id}"),
|
||||
attachment,
|
||||
};
|
||||
let now = 1_800_000_000_000;
|
||||
raw.send(ReplicateMessages {
|
||||
topic: "logs".into(),
|
||||
node: "far".into(),
|
||||
messages: vec![
|
||||
message(
|
||||
3,
|
||||
now,
|
||||
Some(Attachment {
|
||||
size: file.len() as u64,
|
||||
sha256: sha256(&file),
|
||||
}),
|
||||
),
|
||||
message(7, now, None),
|
||||
],
|
||||
});
|
||||
assert_eq!(raw.receive(), Some(MessagePushed { message_id: 7 }.into()));
|
||||
// Past its age here: not stored, but counted as received.
|
||||
raw.send(ReplicateMessages {
|
||||
topic: "old".into(),
|
||||
node: "far".into(),
|
||||
messages: vec![message(1, 1000, None)],
|
||||
});
|
||||
assert_eq!(raw.receive(), Some(MessagePushed { message_id: 1 }.into()));
|
||||
let mut analyst = running
|
||||
.connect(&running.issue("analyst", &["analyst"]))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
analyst
|
||||
.query("SELECT group_concat(topic || '#' || message_id) AS n FROM messages")
|
||||
.unwrap(),
|
||||
r#"{"columns":["n"],"rows":[["logs#3,logs#7"]]}"#
|
||||
);
|
||||
let state = sync_state(&mut raw);
|
||||
let heads: Vec<_> = state
|
||||
.heads
|
||||
.iter()
|
||||
.map(|head| (head.topic.as_str(), head.last_id))
|
||||
.collect();
|
||||
assert_eq!(heads, [("logs", 7), ("old", 1)]);
|
||||
let missing: Vec<_> = state
|
||||
.missing
|
||||
.iter()
|
||||
.map(|missing| (missing.message_id, missing.next_part))
|
||||
.collect();
|
||||
assert_eq!(missing, [(3, 0)]);
|
||||
|
||||
// From the part it needs only.
|
||||
let ask = |raw: &mut Raw, message_id, from_part| {
|
||||
raw.send(ReplicateAttachment {
|
||||
topic: "logs".into(),
|
||||
node: "far".into(),
|
||||
message_id,
|
||||
from_part,
|
||||
})
|
||||
};
|
||||
ask(&mut raw, 3, 1);
|
||||
raw.refused(ErrorCode::InvalidRequest);
|
||||
ask(&mut raw, 7, 0);
|
||||
raw.refused(ErrorCode::NotFound);
|
||||
|
||||
// Cut after its first part: it goes on from the second.
|
||||
ask(&mut raw, 3, 0);
|
||||
assert!(matches!(raw.receive(), Some(Packet::Continue(_))));
|
||||
raw.send(AttachmentPart {
|
||||
data: file[..MIB].to_vec(),
|
||||
});
|
||||
drop(raw);
|
||||
let mut raw = Raw::connect(&running, &peer);
|
||||
wait_for("the first part kept", || {
|
||||
sync_state(&mut raw).missing[0].next_part == 1
|
||||
});
|
||||
ask(&mut raw, 3, 1);
|
||||
assert!(matches!(raw.receive(), Some(Packet::Continue(_))));
|
||||
for part in file[MIB..].chunks(MIB) {
|
||||
raw.send(AttachmentPart {
|
||||
data: part.to_vec(),
|
||||
});
|
||||
}
|
||||
assert_eq!(raw.receive(), Some(MessagePushed { message_id: 3 }.into()));
|
||||
let mut reader = running
|
||||
.connect(&running.issue("watcher", &["reader"]))
|
||||
.unwrap();
|
||||
let mut out = Vec::new();
|
||||
reader.get_attachment("logs", "far", 3, &mut out).unwrap();
|
||||
assert!(out == file);
|
||||
assert!(sync_state(&mut raw).missing.is_empty());
|
||||
|
||||
// Not matching its SHA-256: refused, asked for again from the start.
|
||||
raw.send(ReplicateMessages {
|
||||
topic: "logs".into(),
|
||||
node: "far".into(),
|
||||
messages: vec![message(
|
||||
8,
|
||||
now,
|
||||
Some(Attachment {
|
||||
size: 10,
|
||||
sha256: [0; 32],
|
||||
}),
|
||||
)],
|
||||
});
|
||||
assert_eq!(raw.receive(), Some(MessagePushed { message_id: 8 }.into()));
|
||||
ask(&mut raw, 8, 0);
|
||||
assert!(matches!(raw.receive(), Some(Packet::Continue(_))));
|
||||
raw.send(AttachmentPart { data: vec![1; 10] });
|
||||
raw.refused(ErrorCode::DataMismatch);
|
||||
assert_eq!(sync_state(&mut raw).missing[0].next_part, 0);
|
||||
|
||||
// A certificate whose roles take nothing: refused.
|
||||
let mut other = Raw::connect(&running, &running.issue("nosy", &["reader"]));
|
||||
let state = sync_state(&mut other);
|
||||
assert!(state.topics.is_empty() && state.heads.is_empty());
|
||||
other.send(ReplicateMessages {
|
||||
topic: "logs".into(),
|
||||
node: "far".into(),
|
||||
messages: vec![message(9, now, None)],
|
||||
});
|
||||
other.refused(ErrorCode::NotAllowed);
|
||||
}
|
||||
|
||||
@@ -156,14 +156,16 @@ impl Batch<'_> {
|
||||
/// Stores messages a peer sent for `topic` and `node`, with their own
|
||||
/// ids, in order; ones already here are kept as they are. Their
|
||||
/// attachments are noted, to be asked for (`replicating`), or never if
|
||||
/// bigger than `max_attachment_size` (`too_big`). Returns the topic and
|
||||
/// node's last id.
|
||||
/// bigger than `max_attachment_size` (`too_big`). Ones pushed before
|
||||
/// `skip_before` (ms, past their age here) aren't stored, but count as
|
||||
/// received. Returns the topic and node's last id.
|
||||
pub fn replicate(
|
||||
&mut self,
|
||||
topic: &str,
|
||||
node: &str,
|
||||
messages: &[ReplicatedMessage],
|
||||
max_attachment_size: u64,
|
||||
skip_before: u64,
|
||||
) -> Result<u64> {
|
||||
self.atomic(|db| {
|
||||
let (stream, mut last_id) = stream(db, topic, node)?;
|
||||
@@ -177,6 +179,11 @@ impl Batch<'_> {
|
||||
if !(1..=MAX_MESSAGE_ID).contains(&message.id) {
|
||||
return Err(Error::Invalid(format!("message id {}", message.id)));
|
||||
}
|
||||
// What the trigger keeps: one ignored was here, below it.
|
||||
last_id = last_id.max(message.id);
|
||||
if message.pushed_at < skip_before {
|
||||
continue;
|
||||
}
|
||||
let key = message_key(stream, message.id);
|
||||
let stored = insert.execute((key, message.pushed_at, &message.data))? == 1;
|
||||
if let (true, Some(attachment)) = (stored, &message.attachment) {
|
||||
@@ -187,9 +194,10 @@ impl Batch<'_> {
|
||||
};
|
||||
attach.execute((key, attachment.size, &attachment.sha256, state))?;
|
||||
}
|
||||
// What the trigger keeps: one ignored was here, below it.
|
||||
last_id = last_id.max(message.id);
|
||||
}
|
||||
// The skipped ones move it too.
|
||||
db.prepare_cached("UPDATE streams SET last_id = ?2 WHERE stream_id = ?1")?
|
||||
.execute((stream, last_id))?;
|
||||
Ok(last_id)
|
||||
})
|
||||
}
|
||||
@@ -214,6 +222,26 @@ impl Batch<'_> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A ready attachment found not to match its SHA-256 (a damaged
|
||||
/// disk, a bug): its parts go, it's asked for again from its peers
|
||||
/// (`replicating`), and not served meanwhile.
|
||||
pub fn damaged(&mut self, attachment_id: i64) -> Result<()> {
|
||||
self.atomic(|db| {
|
||||
if attachment(db, attachment_id)?.0 != AttachmentState::Ready {
|
||||
return Err(Error::Invalid(format!(
|
||||
"attachment {attachment_id} isn't a ready one"
|
||||
)));
|
||||
}
|
||||
delete_parts(db, attachment_id, None)?;
|
||||
db.prepare_cached(
|
||||
"UPDATE attachments SET state = 'replicating', received = 0 \
|
||||
WHERE attachment_id = ?1",
|
||||
)?
|
||||
.execute([attachment_id])?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Retention: deletes `topic`'s messages pushed before `cutoff` (ms),
|
||||
/// `limit` at most (call again while it returns `limit`). Each stream
|
||||
/// is read from its oldest message and stops at the first one it keeps:
|
||||
@@ -381,8 +409,21 @@ fn delete_attachment(db: &Connection, attachment_id: i64) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deletes every upload: at start, none of them can be pushed any more.
|
||||
pub(crate) fn delete_uploads(db: &Connection) -> Result<()> {
|
||||
/// At start: deletes every upload (none of them can be pushed any more),
|
||||
/// and starts over the replicated attachments all of whose parts came but
|
||||
/// weren't checked (stopped in between).
|
||||
pub(crate) fn clean_up(db: &Connection) -> Result<()> {
|
||||
let unchecked: Vec<i64> = db
|
||||
.prepare(
|
||||
"SELECT attachment_id FROM attachments \
|
||||
WHERE state = 'replicating' AND received = size",
|
||||
)?
|
||||
.query_map([], |row| row.get(0))?
|
||||
.collect::<rusqlite::Result<_>>()?;
|
||||
for attachment_id in unchecked {
|
||||
delete_parts(db, attachment_id, None)?;
|
||||
set_attachment(db, attachment_id, "received = ?2", 0)?;
|
||||
}
|
||||
let uploads: Vec<i64> = db
|
||||
.prepare("SELECT attachment_id FROM attachments WHERE state = 'uploading'")?
|
||||
.query_map([], |row| row.get(0))?
|
||||
|
||||
@@ -98,7 +98,7 @@ impl Database {
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
crate::batch::delete_uploads(&transaction)?;
|
||||
crate::batch::clean_up(&transaction)?;
|
||||
transaction.commit()?;
|
||||
Ok(database)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,10 @@ use crate::{
|
||||
AttachmentState, Error, Result, find_stream, message_id, message_key, part_key, stream_keys,
|
||||
};
|
||||
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID};
|
||||
use bakashrot_proto::packets::{Head, MessageEntry, Messages, MissingAttachment, StoredAttachment};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, ReplicatedMessage,
|
||||
StoredAttachment,
|
||||
};
|
||||
use rusqlite::{Connection, OptionalExtension, Row};
|
||||
|
||||
/// About how many bytes of messages one answer carries: past it, the rest
|
||||
@@ -23,6 +26,11 @@ const LATEST: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.state
|
||||
FROM data d LEFT JOIN attachments a ON a.message_key = d.key \
|
||||
WHERE d.key >= ?1 AND d.key <= ?2 ORDER BY d.key DESC LIMIT ?3";
|
||||
|
||||
/// A stream's messages after a key, as replication sends them.
|
||||
const TO_REPLICATE: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.sha256 \
|
||||
FROM data d LEFT JOIN attachments a ON a.message_key = d.key \
|
||||
WHERE d.key > ?1 AND d.key <= ?2 ORDER BY d.key LIMIT ?3";
|
||||
|
||||
/// A connection that reads.
|
||||
#[derive(Debug)]
|
||||
pub struct Reader {
|
||||
@@ -97,6 +105,48 @@ impl Reader {
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// A topic and node's messages after an id, as replication sends them:
|
||||
/// `limit` at most, about [`MESSAGES_BYTES`] at most (a bigger one
|
||||
/// alone). None once there are no more.
|
||||
pub fn to_replicate(
|
||||
&self,
|
||||
topic: &str,
|
||||
node: &str,
|
||||
after: u64,
|
||||
limit: u32,
|
||||
) -> Result<Vec<ReplicatedMessage>> {
|
||||
let mut messages = Vec::new();
|
||||
let Some((stream, _)) = find_stream(&self.connection, topic, node)? else {
|
||||
return Ok(messages);
|
||||
};
|
||||
let (_, last) = stream_keys(stream);
|
||||
let mut statement = self.connection.prepare_cached(TO_REPLICATE)?;
|
||||
let from = message_key(stream, after.min(MAX_MESSAGE_ID));
|
||||
let mut rows = statement.query((from, last, i64::from(limit)))?;
|
||||
let mut bytes = 0;
|
||||
while let Some(row) = rows.next()? {
|
||||
let data: String = row.get(2)?;
|
||||
if !messages.is_empty() && bytes + data.len() > MESSAGES_BYTES {
|
||||
break;
|
||||
}
|
||||
bytes += data.len();
|
||||
let attachment = match row.get::<_, Option<u64>>(3)? {
|
||||
Some(size) => Some(Sent {
|
||||
size,
|
||||
sha256: row.get(4)?,
|
||||
}),
|
||||
None => None,
|
||||
};
|
||||
messages.push(ReplicatedMessage {
|
||||
id: message_id(row.get(0)?),
|
||||
pushed_at: row.get(1)?,
|
||||
data,
|
||||
attachment,
|
||||
});
|
||||
}
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
/// Every topic with messages (or that had some), in order.
|
||||
pub fn topics(&self) -> Result<Vec<String>> {
|
||||
self.strings("SELECT DISTINCT topic FROM streams ORDER BY topic")
|
||||
|
||||
@@ -316,6 +316,7 @@ fn replication() {
|
||||
replicated(12, 300, Some((50, sha))),
|
||||
],
|
||||
1000,
|
||||
0,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
@@ -331,6 +332,7 @@ fn replication() {
|
||||
..replicated(5, 1, None)
|
||||
}],
|
||||
1000,
|
||||
0,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
@@ -407,6 +409,7 @@ fn replication() {
|
||||
"garage",
|
||||
&[replicated(1, 1, Some((2 * PART as u64, sha)))],
|
||||
u64::MAX,
|
||||
0,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
@@ -420,9 +423,78 @@ fn replication() {
|
||||
("garage", 1)
|
||||
);
|
||||
|
||||
// What's sent on: after an id, with its attachments' SHA-256s.
|
||||
let sent = reader.to_replicate("logs", "kitchen", 5, 10).unwrap();
|
||||
let sent_ids: Vec<u64> = sent.iter().map(|m| m.id).collect();
|
||||
assert_eq!(sent_ids, [9, 12, 13]);
|
||||
assert_eq!(
|
||||
sent[0].attachment,
|
||||
Some(Sent {
|
||||
size: PART as u64 + 1,
|
||||
sha256: sha
|
||||
})
|
||||
);
|
||||
assert_eq!(sent[2].attachment, None);
|
||||
assert_eq!(
|
||||
reader.to_replicate("logs", "kitchen", 9, 1).unwrap()[0].id,
|
||||
12
|
||||
);
|
||||
assert!(
|
||||
reader
|
||||
.to_replicate("logs", "kitchen", 13, 10)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
reader
|
||||
.to_replicate("logs", "nobody", 0, 10)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
// A damaged ready copy: its parts go, asked for again.
|
||||
writer.batch(|b| b.damaged(small.id)).unwrap();
|
||||
let again = reader.attachment("logs", "kitchen", 12).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
(again.state, again.received),
|
||||
(AttachmentState::Replicating, 0)
|
||||
);
|
||||
assert!(reader.read_part(small.id, 0).is_err());
|
||||
assert!(matches!(
|
||||
writer.batch(|b| b.damaged(small.id)),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
|
||||
// Past their age here: not stored, but counted.
|
||||
let last = writer
|
||||
.batch(|b| {
|
||||
b.replicate(
|
||||
"logs",
|
||||
"attic",
|
||||
&[
|
||||
replicated(1, 100, Some((50, sha))),
|
||||
replicated(2, 200, None),
|
||||
replicated(3, 300, None),
|
||||
],
|
||||
1000,
|
||||
201,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(last, 3);
|
||||
assert_eq!(
|
||||
ids(&reader.messages("logs", "attic", Some(0), 10).unwrap()),
|
||||
[3]
|
||||
);
|
||||
assert_eq!(reader.last_id("logs", "attic").unwrap(), 3);
|
||||
let skipped = writer
|
||||
.batch(|b| b.replicate("logs", "cellar", &[replicated(7, 100, None)], 1000, 201))
|
||||
.unwrap();
|
||||
assert_eq!((skipped, reader.last_id("logs", "cellar").unwrap()), (7, 7));
|
||||
|
||||
// Ids out of range.
|
||||
assert!(matches!(
|
||||
writer.batch(|b| b.replicate("logs", "kitchen", &[replicated(0, 1, None)], 0)),
|
||||
writer.batch(|b| b.replicate("logs", "kitchen", &[replicated(0, 1, None)], 0, 0)),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user