mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Paged SyncState, Added Ping, Required ALPN on the server, Capped retention ages, Closed idle database connections
- Protocol 8: SyncStateRequest takes `after` (a Pair), SyncState has `more` and 32768 heads at most (MAX_HEADS_PER_PACKET), the lists and missing attachments in the first page only; heads_after in storage, both ends of replication read in pages (step 17) - Protocol 8: Ping / Pong (19, 20) keep an idle connection open (IDLE_TIMEOUT_SECS 300, KEEPALIVE_SECS 60). Client::ping, BakaShrot_Ping, Python ping(), C# Ping(), the PureBasic prototype; the tool's --follow, Python's follow(), C#'s Follow() and the replication links ping every minute while waiting longer, so sync_interval over 5 min works now (dropped from known-issues.md) - The server closes a client offering no ALPN right after TLS: rustls only refused one offering other protocols - Retention ages are 100 years at most (MAX_RETENTION_AGE); the cutoff is computed once, saturating (Retention::cutoff): a huge age wrapped around to almost nothing in milliseconds - [server] idle_database_connections (8 by default, 0-512): the idle read and query connections each pool keeps, those unused for a minute closed by a sweeping thread - Tests for each, docs, the C header, revamp.md (step 18) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,9 +5,12 @@
|
||||
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::limits::{
|
||||
ATTACHMENT_PART_SIZE, MAX_HEADS_PER_PACKET, MAX_MESSAGE_SIZE, MAX_MISSING_ATTACHMENTS,
|
||||
};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, Continue, MessagePushed, ReplicateAttachment, ReplicateMessages, SyncState,
|
||||
Attachment, Continue, Head, MessagePushed, ReplicateAttachment, ReplicateMessages, SyncState,
|
||||
SyncStateRequest,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
@@ -111,27 +114,61 @@ async fn check(shared: &Shared, peer: &mut Peer, topic: &str, node: &str) -> Res
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// attachments it lacks among them: a page of it, the lists in the first.
|
||||
pub(crate) async fn sync_state(
|
||||
shared: &Arc<Shared>,
|
||||
peer: &mut Peer,
|
||||
request: SyncStateRequest,
|
||||
) -> 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));
|
||||
let first = request.after.is_none();
|
||||
let mut after = request.after.map(|pair| (pair.topic, pair.node));
|
||||
let (mut heads, mut more) = (Vec::new(), false);
|
||||
// Read in pages too, those it doesn't take from this peer skipped:
|
||||
// until the page is full and one more is found, or none is left.
|
||||
'pages: loop {
|
||||
let from = after.clone();
|
||||
let read = shared
|
||||
.read(move |reader| {
|
||||
let from = from.as_ref().map(|(t, n)| (t.as_str(), n.as_str()));
|
||||
reader.heads_after(from, MAX_HEADS_PER_PACKET)
|
||||
})
|
||||
.await;
|
||||
let read: Vec<Head> = match read {
|
||||
Ok(read) => read,
|
||||
Err(refusal) => return refusal.into(),
|
||||
};
|
||||
let last_page = read.len() < MAX_HEADS_PER_PACKET;
|
||||
after = read.last().map(|h| (h.topic.clone(), h.node.clone()));
|
||||
for head in read {
|
||||
if peer.permissions.accepts(&head.topic, &head.node) {
|
||||
if heads.len() == MAX_HEADS_PER_PACKET {
|
||||
more = true;
|
||||
break 'pages;
|
||||
}
|
||||
heads.push(head);
|
||||
}
|
||||
}
|
||||
if last_page {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (mut topics, mut nodes, mut missing) = (Vec::new(), Vec::new(), Vec::new());
|
||||
if first {
|
||||
(topics, nodes) = peer.permissions.accepted();
|
||||
missing = match shared
|
||||
.read(|reader| reader.missing_attachments(MAX_MISSING_ATTACHMENTS))
|
||||
.await
|
||||
{
|
||||
Ok(missing) => missing,
|
||||
Err(refusal) => return refusal.into(),
|
||||
};
|
||||
missing.retain(|missing| peer.permissions.accepts(&missing.topic, &missing.node));
|
||||
}
|
||||
SyncState {
|
||||
more,
|
||||
topics,
|
||||
nodes,
|
||||
heads,
|
||||
@@ -163,8 +200,8 @@ pub(crate) async fn replicate_messages(
|
||||
let skip_before = shared
|
||||
.config
|
||||
.retention
|
||||
.age(&batch.topic)
|
||||
.map_or(0, |age| now().saturating_sub(age.as_millis() as u64));
|
||||
.cutoff(&batch.topic, now())
|
||||
.unwrap_or(0);
|
||||
let write = Write::Replicate {
|
||||
topic: batch.topic,
|
||||
node: batch.node,
|
||||
|
||||
@@ -6,11 +6,13 @@ use crate::{Shared, accept_from, now};
|
||||
use aws_lc_rs::digest;
|
||||
use bakashrot_config::Permissions;
|
||||
use bakashrot_pki::Identity;
|
||||
use bakashrot_proto::limits::{MAX_MESSAGE_SIZE, MAX_NAMES_LIST_ENTRIES, MAX_PACKET_SIZE};
|
||||
use bakashrot_proto::limits::{
|
||||
ALPN, IDLE_TIMEOUT_SECS, MAX_MESSAGE_SIZE, MAX_NAMES_LIST_ENTRIES, MAX_PACKET_SIZE,
|
||||
};
|
||||
use bakashrot_proto::names::{name_matches, names_equal};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed,
|
||||
Messages, NameKind, NamesList, PushMessage, Query, QueryResult, RequestRefused, Welcome,
|
||||
Messages, NameKind, NamesList, Pong, PushMessage, Query, QueryResult, RequestRefused, Welcome,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
@@ -29,8 +31,9 @@ use tracing::{debug, info};
|
||||
/// How long TLS and the versions may take.
|
||||
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// How long a connection may stay silent between requests.
|
||||
const IDLE_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
/// How long a connection may stay silent between requests (a `Ping`
|
||||
/// counts).
|
||||
const IDLE_TIMEOUT: Duration = Duration::from_secs(IDLE_TIMEOUT_SECS);
|
||||
|
||||
/// How long an attachment's next part may take to come.
|
||||
const PART_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
@@ -107,7 +110,10 @@ async fn serve(shared: &Arc<Shared>, tcp: TcpStream, address: IpAddr) -> Result<
|
||||
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,
|
||||
Packet::SyncStateRequest(_) => accept_from::sync_state(shared, &mut peer).await,
|
||||
Packet::Ping(_) => Pong {}.into(),
|
||||
Packet::SyncStateRequest(request) => {
|
||||
accept_from::sync_state(shared, &mut peer, request).await
|
||||
}
|
||||
Packet::ReplicateMessages(batch) => {
|
||||
accept_from::replicate_messages(shared, &mut peer, batch).await
|
||||
}
|
||||
@@ -158,6 +164,12 @@ async fn open(
|
||||
return Err(format!("TLS: {error}"));
|
||||
}
|
||||
};
|
||||
// rustls refuses a client offering other protocols, not one offering
|
||||
// none: that one is refused here, before the versions.
|
||||
if stream.get_ref().1.alpn_protocol() != Some(ALPN) {
|
||||
let _ = stream.shutdown().await;
|
||||
return Err("TLS: no ALPN \"bakashrot\" offered, not a BakaShrot client".into());
|
||||
}
|
||||
|
||||
stream
|
||||
.write_all(&frame::version_bytes())
|
||||
|
||||
@@ -31,8 +31,8 @@ use bakashrot_storage::{Database, QueryRunner, Reader};
|
||||
use std::collections::HashSet;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_rustls::{TlsAcceptor, TlsConnector};
|
||||
use tracing::{info, warn};
|
||||
@@ -44,6 +44,12 @@ const CRL_POLL: Duration = Duration::from_secs(5);
|
||||
/// How often the WAL is checkpointed.
|
||||
const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(1);
|
||||
|
||||
/// How long an idle database connection is kept before it's closed.
|
||||
const POOL_IDLE: Duration = Duration::from_secs(60);
|
||||
|
||||
/// How often the idle database connections are looked at.
|
||||
const POOL_SWEEP: Duration = Duration::from_secs(10);
|
||||
|
||||
/// A server, ready to take connections.
|
||||
#[derive(Clone)]
|
||||
pub struct Server {
|
||||
@@ -64,9 +70,9 @@ struct Shared {
|
||||
database: Database,
|
||||
pushes: Pushes,
|
||||
/// Read connections not in use.
|
||||
readers: Mutex<Vec<Reader>>,
|
||||
readers: Pool<Reader>,
|
||||
/// Query connections not in use.
|
||||
queries: Mutex<Vec<QueryRunner>>,
|
||||
queries: Pool<QueryRunner>,
|
||||
/// The replicated attachments being received (topic, node, message
|
||||
/// id): one peer at a time each (`accept_from.rs`).
|
||||
receiving: Mutex<HashSet<(String, String, u64)>>,
|
||||
@@ -101,21 +107,21 @@ impl Server {
|
||||
let pushes = Pushes::start(database.writer().map_err(|error| error.to_string())?)
|
||||
.map_err(|error| format!("the writer's thread: {error}"))?;
|
||||
start_checkpoints(&database)?;
|
||||
Ok(Server {
|
||||
shared: Arc::new(Shared {
|
||||
name,
|
||||
acceptor: TlsAcceptor::from(tls),
|
||||
connector: TlsConnector::from(dialing),
|
||||
revocations,
|
||||
ca,
|
||||
database,
|
||||
pushes,
|
||||
readers: Mutex::new(Vec::new()),
|
||||
queries: Mutex::new(Vec::new()),
|
||||
receiving: Mutex::new(HashSet::new()),
|
||||
config,
|
||||
}),
|
||||
})
|
||||
let shared = Arc::new(Shared {
|
||||
name,
|
||||
acceptor: TlsAcceptor::from(tls),
|
||||
connector: TlsConnector::from(dialing),
|
||||
revocations,
|
||||
ca,
|
||||
database,
|
||||
pushes,
|
||||
readers: Pool::new(),
|
||||
queries: Pool::new(),
|
||||
receiving: Mutex::new(HashSet::new()),
|
||||
config,
|
||||
});
|
||||
start_pool_sweeps(&shared)?;
|
||||
Ok(Server { shared })
|
||||
}
|
||||
|
||||
/// The server's name: its certificate's.
|
||||
@@ -231,24 +237,22 @@ impl Shared {
|
||||
}
|
||||
|
||||
/// Runs `work` on an idle connection of `pool`, or a new one, then
|
||||
/// puts it back.
|
||||
/// puts it back (closed if the pool has enough idle ones already).
|
||||
async fn pooled<C: Send + 'static, T: Send + 'static>(
|
||||
self: &Arc<Self>,
|
||||
pool: fn(&Shared) -> &Mutex<Vec<C>>,
|
||||
pool: fn(&Shared) -> &Pool<C>,
|
||||
open: fn(&Database) -> bakashrot_storage::Result<C>,
|
||||
work: impl FnOnce(&C) -> bakashrot_storage::Result<T> + Send + 'static,
|
||||
) -> Result<T, RequestRefused> {
|
||||
let shared = self.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let idle = pool(&shared).lock().ok().and_then(|mut idle| idle.pop());
|
||||
let connection = match idle {
|
||||
let connection = match pool(&shared).take() {
|
||||
Some(connection) => connection,
|
||||
None => open(&shared.database).map_err(refusal)?,
|
||||
};
|
||||
let value = work(&connection).map_err(refusal);
|
||||
if let Ok(mut idle) = pool(&shared).lock() {
|
||||
idle.push(connection);
|
||||
}
|
||||
let max = shared.config.server.idle_database_connections;
|
||||
pool(&shared).put_back(connection, max, Instant::now());
|
||||
value
|
||||
})
|
||||
.await
|
||||
@@ -256,6 +260,80 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
/// Database connections not in use, each with when it was put back: the
|
||||
/// last one put back is taken first, so the others age out.
|
||||
struct Pool<C> {
|
||||
idle: Mutex<Vec<(C, Instant)>>,
|
||||
}
|
||||
|
||||
impl<C> Pool<C> {
|
||||
fn new() -> Self {
|
||||
Pool {
|
||||
idle: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, Vec<(C, Instant)>> {
|
||||
self.idle.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// The idle connection used last, if any.
|
||||
fn take(&self) -> Option<C> {
|
||||
self.lock().pop().map(|(connection, _)| connection)
|
||||
}
|
||||
|
||||
/// Keeps `connection` for later, unused since `now`, unless `max` are
|
||||
/// kept already: then it's closed (outside the lock).
|
||||
fn put_back(&self, connection: C, max: usize, now: Instant) {
|
||||
let mut idle = self.lock();
|
||||
if idle.len() < max {
|
||||
idle.push((connection, now));
|
||||
} else {
|
||||
drop(idle);
|
||||
drop(connection);
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes the connections unused for `idle_for` or more at `now`.
|
||||
fn sweep(&self, now: Instant, idle_for: Duration) {
|
||||
let stale: Vec<(C, Instant)> = {
|
||||
let mut idle = self.lock();
|
||||
let (stale, fresh) = idle
|
||||
.drain(..)
|
||||
.partition(|(_, since)| now.saturating_duration_since(*since) >= idle_for);
|
||||
*idle = fresh;
|
||||
stale
|
||||
};
|
||||
drop(stale);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn len(&self) -> usize {
|
||||
self.lock().len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes the pools' connections unused for [`POOL_IDLE`], looked at every
|
||||
/// [`POOL_SWEEP`] on a thread of its own, until the server is dropped.
|
||||
fn start_pool_sweeps(shared: &Arc<Shared>) -> Result<(), String> {
|
||||
let shared = Arc::downgrade(shared);
|
||||
std::thread::Builder::new()
|
||||
.name("pool sweeps".into())
|
||||
.spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(POOL_SWEEP);
|
||||
let Some(shared) = shared.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let now = Instant::now();
|
||||
shared.readers.sweep(now, POOL_IDLE);
|
||||
shared.queries.sweep(now, POOL_IDLE);
|
||||
}
|
||||
})
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("the pool sweeps' thread: {error}"))
|
||||
}
|
||||
|
||||
/// Checkpoints the WAL every second, on a thread and a connection of its
|
||||
/// own, so the writer doesn't do it in the middle of a commit (2.5 times
|
||||
/// the pushes: `docs/storage.md`, "The benchmark").
|
||||
@@ -339,6 +417,27 @@ fn stamp(path: &Path) -> Option<(SystemTime, u64)> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pools_keep_few_and_close_the_idle() {
|
||||
let pool = Pool::new();
|
||||
let start = Instant::now();
|
||||
// Three back at once, two kept at most: the third closed.
|
||||
for connection in [1, 2, 3] {
|
||||
pool.put_back(connection, 2, start);
|
||||
}
|
||||
assert_eq!(pool.len(), 2);
|
||||
// The last one put back is taken first.
|
||||
assert_eq!(pool.take(), Some(2));
|
||||
pool.put_back(2, 2, start + Duration::from_secs(30));
|
||||
// At 60 s, the one idle since the start goes, not the other.
|
||||
pool.sweep(start + POOL_IDLE, POOL_IDLE);
|
||||
assert_eq!(pool.take(), Some(2));
|
||||
assert_eq!(pool.take(), None);
|
||||
// None kept at all.
|
||||
pool.put_back(4, 0, start);
|
||||
assert_eq!(pool.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clock_before_1970_is_refused() {
|
||||
assert!(check_clock(UNIX_EPOCH).is_ok());
|
||||
|
||||
@@ -11,11 +11,11 @@ use crate::connection::SEND_TIMEOUT;
|
||||
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::limits::{ALPN, KEEPALIVE_SECS, MAX_PACKET_SIZE};
|
||||
use bakashrot_proto::names::name_matches;
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, MissingAttachment, ReplicateAttachment, ReplicateMessages,
|
||||
SyncState, SyncStateRequest,
|
||||
Attachment, AttachmentPart, MissingAttachment, Pair, Ping, ReplicateAttachment,
|
||||
ReplicateMessages, SyncState, SyncStateRequest,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
@@ -58,10 +58,13 @@ async fn keep_linked(shared: Arc<Shared>, address: String) {
|
||||
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),
|
||||
let checked = match link.check_in(&shared).await {
|
||||
Ok(true) => Ok(()),
|
||||
Ok(false) => link.wait(replication.sync_interval).await,
|
||||
Err(why) => Err(why),
|
||||
};
|
||||
if let Err(why) = checked {
|
||||
break format!("{} ({address}): {why}", link.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,20 +142,11 @@ impl Link {
|
||||
/// 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 (state, theirs) = self.sync_state().await?;
|
||||
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) {
|
||||
@@ -171,13 +165,44 @@ impl Link {
|
||||
Ok(self.sent)
|
||||
}
|
||||
|
||||
/// Its `SyncState`, every page: the first (the lists), and the last
|
||||
/// id of each topic and node.
|
||||
async fn sync_state(&mut self) -> Result<(SyncState, HashMap<(String, String), u64>), String> {
|
||||
let mut theirs = HashMap::new();
|
||||
let mut first = None;
|
||||
let mut after = None;
|
||||
loop {
|
||||
let mut page = match self.ask(SyncStateRequest { after }.into()).await? {
|
||||
Packet::SyncState(page) => page,
|
||||
Packet::RequestRefused(refused) => {
|
||||
return Err(format!("refused: {}", refused.reason));
|
||||
}
|
||||
other => return Err(unexpected(&other)),
|
||||
};
|
||||
after = match page.more {
|
||||
true => page.heads.last().map(|head| Pair {
|
||||
topic: head.topic.clone(),
|
||||
node: head.node.clone(),
|
||||
}),
|
||||
false => None,
|
||||
};
|
||||
theirs.extend(
|
||||
page.heads
|
||||
.drain(..)
|
||||
.map(|head| (key(&head.topic, &head.node), head.last_id)),
|
||||
);
|
||||
first.get_or_insert(page);
|
||||
if after.is_none() {
|
||||
return Ok((first.expect("a page came"), theirs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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))
|
||||
};
|
||||
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)
|
||||
@@ -292,6 +317,26 @@ impl Link {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Waits `duration` before the next check-in, with a `Ping` every
|
||||
/// `KEEPALIVE_SECS` meanwhile: the other server closes a link silent
|
||||
/// for `IDLE_TIMEOUT_SECS`.
|
||||
async fn wait(&mut self, duration: Duration) -> Result<(), String> {
|
||||
let keepalive = Duration::from_secs(KEEPALIVE_SECS);
|
||||
let mut left = duration;
|
||||
loop {
|
||||
let step = left.min(keepalive);
|
||||
sleep(step).await;
|
||||
left -= step;
|
||||
if left.is_zero() {
|
||||
return Ok(());
|
||||
}
|
||||
match self.ask(Ping {}.into()).await? {
|
||||
Packet::Pong(_) => {}
|
||||
other => return Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn ask(&mut self, packet: Packet) -> Result<Packet, String> {
|
||||
self.send(packet).await?;
|
||||
self.receive().await
|
||||
|
||||
@@ -31,10 +31,9 @@ pub(crate) async fn run(shared: &Arc<Shared>) {
|
||||
async fn once(shared: &Arc<Shared>) -> Result<(), RequestRefused> {
|
||||
let now = crate::now();
|
||||
for topic in shared.read(|reader| reader.topics()).await? {
|
||||
let Some(age) = shared.config.retention.age(&topic) else {
|
||||
let Some(cutoff) = shared.config.retention.cutoff(&topic, now) else {
|
||||
continue;
|
||||
};
|
||||
let cutoff = now.saturating_sub(age.as_millis() as u64);
|
||||
let deleted = repeat(shared, MESSAGES_PER_WRITE, |limit| Write::DeleteBefore {
|
||||
topic: topic.clone(),
|
||||
cutoff,
|
||||
|
||||
@@ -6,20 +6,23 @@
|
||||
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::limits::{
|
||||
ATTACHMENT_PART_SIZE, MAX_HEADS_PER_PACKET, MAX_MESSAGE_SIZE, MAX_PACKET_SIZE,
|
||||
};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, GetAttachment, MessagePushed, Messages, NameKind, PushMessage,
|
||||
ReplicateAttachment, ReplicateMessages, ReplicatedMessage, StoredAttachment, SyncState,
|
||||
SyncStateRequest,
|
||||
Attachment, AttachmentPart, GetAttachment, Head, MessagePushed, Messages, NameKind, Pair, Ping,
|
||||
Pong, PushMessage, ReplicateAttachment, ReplicateMessages, ReplicatedMessage, StoredAttachment,
|
||||
SyncState, SyncStateRequest,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use bakashrot_server::Server;
|
||||
use std::io::{Cursor, Read, Seek, SeekFrom, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio_rustls::rustls::{ClientConnection, StreamOwned};
|
||||
use tokio_rustls::rustls::{ClientConfig, ClientConnection, StreamOwned};
|
||||
|
||||
const CONFIG: &str = r#"
|
||||
[server]
|
||||
@@ -219,6 +222,49 @@ fn push_and_read_back() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A ping is answered, needs no permission, and the connection goes on;
|
||||
/// a revoked certificate's ping drops it, as any request.
|
||||
#[test]
|
||||
fn pings() {
|
||||
let running = Running::start("pings");
|
||||
// No role allows anything here but being known.
|
||||
let nobody = running.issue("idle", &["explorer"]);
|
||||
let mut client = running.connect(&nobody).unwrap();
|
||||
client.ping().unwrap();
|
||||
client.ping().unwrap();
|
||||
assert!(client.list_names(NameKind::Topic, None, None).is_ok());
|
||||
|
||||
let mut raw = Raw::connect(&running, &nobody);
|
||||
raw.send(Ping {});
|
||||
assert!(matches!(raw.receive(), Some(Packet::Pong(_))));
|
||||
// An answer, not a request: the server closes.
|
||||
raw.send(Pong {});
|
||||
assert!(raw.receive().is_none());
|
||||
|
||||
let serial = summarize(&nobody.certificate).unwrap().serial;
|
||||
let crl = running.ca.revocation_list(&[serial], 30).unwrap();
|
||||
std::fs::write(running.folder.join("ca.crl"), crl).unwrap();
|
||||
running.server.reload_revocations().unwrap();
|
||||
let error = client.ping().unwrap_err();
|
||||
assert_eq!(error.code(), ErrorCode::ConnectionLost.code(), "{error}");
|
||||
}
|
||||
|
||||
/// No idle database connection kept: each read and query opens its own.
|
||||
#[test]
|
||||
fn no_idle_database_connections() {
|
||||
let running = Running::start_with("no-idle", "idle_database_connections = 0\n");
|
||||
let mut client = running
|
||||
.connect(&running.issue("kitchen", &["sensor", "reader", "analyst"]))
|
||||
.unwrap();
|
||||
for n in 1..=3 {
|
||||
assert_eq!(client.push("logs", &format!("{{\"n\":{n}}}")).unwrap(), n);
|
||||
let latest = client.get_messages("logs", "kitchen", None, 1).unwrap();
|
||||
assert_eq!(latest.messages[0].id, n);
|
||||
}
|
||||
let json = client.query("SELECT count(*) AS n FROM messages").unwrap();
|
||||
assert_eq!(json, r#"{"columns":["n"],"rows":[["3"]]}"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refusals_keep_the_connection() {
|
||||
let running = Running::start("refusals");
|
||||
@@ -298,6 +344,20 @@ fn certificates_refused() {
|
||||
.unwrap_err();
|
||||
assert_eq!(error.code(), ErrorCode::ServerNotVerified.code(), "{error}");
|
||||
|
||||
// A client of the CA offering no ALPN: TLS goes through (rustls only
|
||||
// refuses other protocols), then the server closes before its version.
|
||||
let kitchen = running.issue("kitchen", &["sensor"]);
|
||||
let mut silent = Raw::open(&running, &kitchen, |config| config.alpn_protocols.clear());
|
||||
frame::write_version(&mut silent.0).unwrap();
|
||||
let _ = silent.0.flush();
|
||||
assert!(frame::read_version(&mut silent.0).is_err());
|
||||
// Offering it, the same client gets in.
|
||||
let mut offering = Raw::open(&running, &kitchen, |_| {});
|
||||
frame::write_version(&mut offering.0).unwrap();
|
||||
offering.0.flush().unwrap();
|
||||
frame::read_version(&mut offering.0).unwrap();
|
||||
assert!(matches!(offering.receive(), Some(Packet::Welcome(_))));
|
||||
|
||||
// Nothing listening.
|
||||
let error = Client::connect(
|
||||
"127.0.0.1:1",
|
||||
@@ -922,17 +982,7 @@ struct Raw(StreamOwned<ClientConnection, TcpStream>);
|
||||
|
||||
impl Raw {
|
||||
fn connect(running: &Running, issued: &Issued) -> Raw {
|
||||
let config = tls::client_config(
|
||||
&running.ca_certificate,
|
||||
&issued.certificate,
|
||||
&issued.key,
|
||||
Revocations::none().shared(),
|
||||
)
|
||||
.unwrap();
|
||||
let tcp = TcpStream::connect(&running.address).unwrap();
|
||||
tcp.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
|
||||
let connection = ClientConnection::new(config, tls::server_name()).unwrap();
|
||||
let mut raw = Raw(StreamOwned::new(connection, tcp));
|
||||
let mut raw = Raw::open(running, issued, |_| {});
|
||||
frame::write_version(&mut raw.0).unwrap();
|
||||
raw.0.flush().unwrap();
|
||||
frame::read_version(&mut raw.0).unwrap();
|
||||
@@ -940,6 +990,24 @@ impl Raw {
|
||||
raw
|
||||
}
|
||||
|
||||
/// TLS only, its client config changed by `change` first: the
|
||||
/// versions and the welcome are the caller's.
|
||||
fn open(running: &Running, issued: &Issued, change: impl FnOnce(&mut ClientConfig)) -> Raw {
|
||||
let mut config = (*tls::client_config(
|
||||
&running.ca_certificate,
|
||||
&issued.certificate,
|
||||
&issued.key,
|
||||
Revocations::none().shared(),
|
||||
)
|
||||
.unwrap())
|
||||
.clone();
|
||||
change(&mut config);
|
||||
let tcp = TcpStream::connect(&running.address).unwrap();
|
||||
tcp.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
|
||||
let connection = ClientConnection::new(Arc::new(config), tls::server_name()).unwrap();
|
||||
Raw(StreamOwned::new(connection, tcp))
|
||||
}
|
||||
|
||||
fn send(&mut self, packet: impl Into<Packet>) {
|
||||
frame::write(&mut self.0, &packet.into().encode()).unwrap();
|
||||
self.0.flush().unwrap();
|
||||
@@ -1442,15 +1510,186 @@ fn replication() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A server's `SyncState`, asked over `raw`.
|
||||
/// A server's `SyncState`, asked over `raw`: its first page.
|
||||
fn sync_state(raw: &mut Raw) -> SyncState {
|
||||
raw.send(SyncStateRequest {});
|
||||
sync_page(raw, None)
|
||||
}
|
||||
|
||||
/// A page of a server's `SyncState`, the heads after `after`.
|
||||
fn sync_page(raw: &mut Raw, after: Option<Pair>) -> SyncState {
|
||||
raw.send(SyncStateRequest { after });
|
||||
match raw.receive() {
|
||||
Some(Packet::SyncState(state)) => state,
|
||||
other => panic!("expected a SyncState, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `count` topic and node pairs to the database at `path`, topics
|
||||
/// `{prefix}000001` and on, node "far", each pair's last id its number:
|
||||
/// faster than pushing.
|
||||
fn add_pairs(path: &std::path::Path, prefix: &str, count: usize) {
|
||||
let raw = rusqlite::Connection::open(path).unwrap();
|
||||
raw.execute(
|
||||
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?2) \
|
||||
INSERT INTO streams (topic, node, last_id) \
|
||||
SELECT printf('%s%06d', ?1, i), 'far', i FROM n",
|
||||
rusqlite::params![prefix, count],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// The pair of a head, to ask the page after it.
|
||||
fn after(head: &Head) -> Option<Pair> {
|
||||
Some(Pair {
|
||||
topic: head.topic.clone(),
|
||||
node: head.node.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Heads as (topic, node, last id), to compare.
|
||||
fn triples(heads: &[Head]) -> Vec<(String, String, u64)> {
|
||||
heads
|
||||
.iter()
|
||||
.map(|head| (head.topic.clone(), head.node.clone(), head.last_id))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_state_in_pages() {
|
||||
const PAGE: usize = MAX_HEADS_PER_PACKET;
|
||||
// "picky" takes only topics starting with "b".
|
||||
let b = Running::start_with(
|
||||
"pages",
|
||||
"\n[replication]\naccept_from = [\"127.0.0.1\"]\n\n\
|
||||
[roles.picky]\naccept_topics = [\"b*\"]\n",
|
||||
);
|
||||
// A page of "b" pairs, between 1000 "a" and 1000 "c" ones.
|
||||
let database = b.folder.join("bakashrot.sqlite");
|
||||
let b = b.restart_after(|| {
|
||||
add_pairs(&database, "a", 1000);
|
||||
add_pairs(&database, "b", PAGE);
|
||||
add_pairs(&database, "c", 1000);
|
||||
});
|
||||
let mut every: Vec<(String, String, u64)> = Vec::new();
|
||||
for (prefix, count) in [("a", 1000), ("b", PAGE), ("c", 1000)] {
|
||||
every.extend((1..=count as u64).map(|n| (format!("{prefix}{n:06}"), "far".into(), n)));
|
||||
}
|
||||
|
||||
// A peer taking everything: a full first page with the lists, then the
|
||||
// rest after its last head, without them; every pair once, in order.
|
||||
let mut peer = Raw::connect(&b, &b.issue("server-x", &["peer"]));
|
||||
let first = sync_page(&mut peer, None);
|
||||
assert!(first.more);
|
||||
assert_eq!(first.heads.len(), PAGE);
|
||||
assert_eq!(
|
||||
(first.topics.as_slice(), first.nodes.as_slice()),
|
||||
(["*".to_string()].as_slice(), ["*".to_string()].as_slice())
|
||||
);
|
||||
let second = sync_page(&mut peer, after(first.heads.last().unwrap()));
|
||||
assert!(!second.more);
|
||||
assert!(second.topics.is_empty() && second.nodes.is_empty() && second.missing.is_empty());
|
||||
let mut both = triples(&first.heads);
|
||||
both.extend(triples(&second.heads));
|
||||
assert_eq!(both, every);
|
||||
|
||||
// The pair asked after, its names in another case: the same page.
|
||||
let last = first.heads.last().unwrap();
|
||||
let shouted = Pair {
|
||||
topic: last.topic.to_uppercase(),
|
||||
node: last.node.to_uppercase(),
|
||||
};
|
||||
assert_eq!(sync_page(&mut peer, Some(shouted)).heads, second.heads);
|
||||
// A pair it doesn't have: from the next one after it.
|
||||
let between = Pair {
|
||||
topic: "b000005".into(),
|
||||
node: "a".into(),
|
||||
};
|
||||
assert_eq!(
|
||||
sync_page(&mut peer, Some(between)).heads[0].topic,
|
||||
"b000005"
|
||||
);
|
||||
// After the very last: nothing, nothing more.
|
||||
let end = sync_page(&mut peer, after(second.heads.last().unwrap()));
|
||||
assert!(end.heads.is_empty() && !end.more);
|
||||
|
||||
// A peer taking only "b": the others are skipped, not counted. Exactly
|
||||
// a page of its own: one page, no empty one after it.
|
||||
let mut picky = Raw::connect(&b, &b.issue("server-y", &["picky"]));
|
||||
let only = sync_page(&mut picky, None);
|
||||
assert!(!only.more);
|
||||
assert_eq!(only.topics, ["b*"]);
|
||||
assert_eq!(triples(&only.heads), every[1000..1000 + PAGE]);
|
||||
// One more "b" (made while it runs): two pages, the second just it.
|
||||
add_pairs(&database, "bz", 1);
|
||||
let first = sync_page(&mut picky, None);
|
||||
assert!(first.more);
|
||||
assert_eq!(first.heads.len(), PAGE);
|
||||
let second = sync_page(&mut picky, after(first.heads.last().unwrap()));
|
||||
assert!(!second.more);
|
||||
assert_eq!(
|
||||
triples(&second.heads),
|
||||
[("bz000001".into(), "far".into(), 1)]
|
||||
);
|
||||
|
||||
// A pattern to ask after is malformed: the connection is dropped.
|
||||
let pattern = Pair {
|
||||
topic: "b*".into(),
|
||||
node: "far".into(),
|
||||
};
|
||||
picky.send(SyncStateRequest {
|
||||
after: Some(pattern),
|
||||
});
|
||||
assert_eq!(picky.receive(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replication_across_pages() {
|
||||
// b with a page and more of pairs before "logs", and kitchen's last id
|
||||
// in "logs" 5 (its messages gone): that head is on the second page.
|
||||
let b = Running::start_with(
|
||||
"across-pages-b",
|
||||
"\n[replication]\naccept_from = [\"127.0.0.1\"]\n",
|
||||
);
|
||||
let database = b.folder.join("bakashrot.sqlite");
|
||||
let b = b.restart_after(|| {
|
||||
add_pairs(&database, "a", MAX_HEADS_PER_PACKET + 1000);
|
||||
let raw = rusqlite::Connection::open(&database).unwrap();
|
||||
raw.execute(
|
||||
"INSERT INTO streams (topic, node, last_id) VALUES ('logs', 'kitchen', 5)",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
let a = b.peer(
|
||||
"across-pages-a",
|
||||
"server-a",
|
||||
&format!(
|
||||
"\n[replication]\npush_to = [\"{}\"]\nsync_interval = \"1s\"\n\
|
||||
retry_delay = \"1s\"\n",
|
||||
b.address
|
||||
),
|
||||
);
|
||||
let mut on_a = a.connect(&a.issue("kitchen", &["sensor"])).unwrap();
|
||||
let mut on_b = b.connect(&b.issue("watcher", &["reader"])).unwrap();
|
||||
let ids = |client: &mut Client| {
|
||||
client
|
||||
.get_messages("logs", "kitchen", Some(0), 10)
|
||||
.map(|messages| messages.messages.iter().map(|m| m.id).collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
// a sends only what's after b's 5: the second page was read. (Without
|
||||
// it, a would take b to be at 0 and send all 6.)
|
||||
for n in 1..=6 {
|
||||
on_a.push("logs", &format!("{{\"n\":{n}}}")).unwrap();
|
||||
}
|
||||
wait_for("#6 on b", || ids(&mut on_b) == [6]);
|
||||
on_a.push("logs", "{\"n\":7}").unwrap();
|
||||
wait_for("#7 on b", || ids(&mut on_b) == [6, 7]);
|
||||
// Check-ins after that send nothing more.
|
||||
std::thread::sleep(Duration::from_millis(2500));
|
||||
assert_eq!(ids(&mut on_b), [6, 7]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replication_edges() {
|
||||
// The test plays the peer, over a raw connection.
|
||||
|
||||
Reference in New Issue
Block a user