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:
@@ -504,6 +504,18 @@ pub extern "C" fn BakaShrot_Disconnect(client: i64) -> isize {
|
||||
})
|
||||
}
|
||||
|
||||
/// Keeps the connection open: 1, or 0 if it failed (`ConnectionLost`:
|
||||
/// connect again). The server closes a connection silent for 5 min; an
|
||||
/// app waiting longer between requests calls this every minute or so
|
||||
/// (the DLL has no thread of its own to do it).
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_Ping(client: i64) -> isize {
|
||||
call(client, 0, |state| {
|
||||
state.client()?.ping()?;
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
|
||||
fn node(state: &State) -> &str {
|
||||
state.client.as_ref().map_or("", Client::node)
|
||||
}
|
||||
|
||||
@@ -391,11 +391,16 @@ fn exports() {
|
||||
assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
|
||||
}
|
||||
assert_eq!(BakaShrot_IsConnected(client), 1);
|
||||
// A ping keeps it open, its last error cleared.
|
||||
assert_eq!(BakaShrot_Ping(client), 1);
|
||||
assert_eq!(error(client).0, 0);
|
||||
|
||||
// Closed: requests refused, the settings kept.
|
||||
assert_eq!(BakaShrot_Disconnect(client), 1);
|
||||
assert_eq!(BakaShrot_Disconnect(client), 0);
|
||||
assert_eq!(BakaShrot_IsConnected(client), 0);
|
||||
assert_eq!(BakaShrot_Ping(client), 0);
|
||||
assert_eq!(error(client).0, code(ErrorCode::NotConnected));
|
||||
assert_eq!(get_w(client, BakaShrot_GetNodeW), "");
|
||||
assert_eq!(BakaShrot_QueryW(client, w("SELECT 1").as_ptr()), 0);
|
||||
assert_eq!(error(client).0, code(ErrorCode::NotConnected));
|
||||
@@ -470,6 +475,7 @@ fn clients() {
|
||||
assert_eq!(failed, code(ErrorCode::InvalidArgument));
|
||||
assert!(why.contains("no client 99"), "{why}");
|
||||
assert_eq!(BakaShrot_IsConnected(99), 0);
|
||||
assert_eq!(BakaShrot_Ping(99), 0);
|
||||
assert_eq!(BakaShrot_GetMessageId(-5), 0);
|
||||
assert_eq!(get_w(99, BakaShrot_GetMessageDataW), "");
|
||||
assert_eq!(BakaShrot_FreeClient(99), 0);
|
||||
|
||||
@@ -27,7 +27,7 @@ use bakashrot_proto::limits::{
|
||||
use bakashrot_proto::names::{is_valid_name, is_valid_name_or_pattern};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, GetAttachment, GetMessages, ListNames, Messages, NameKind,
|
||||
NamesList, PushMessage, Query,
|
||||
NamesList, Ping, PushMessage, Query,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use rustls::{ClientConnection, StreamOwned};
|
||||
@@ -204,6 +204,16 @@ impl Client {
|
||||
open && tcp.set_nonblocking(false).is_ok()
|
||||
}
|
||||
|
||||
/// Keeps the connection open: the server closes one silent for
|
||||
/// `IDLE_TIMEOUT_SECS` (5 min). An app waiting longer than that
|
||||
/// between requests calls this every `KEEPALIVE_SECS` (1 min) or so.
|
||||
pub fn ping(&mut self) -> Result<()> {
|
||||
match self.request(Ping {}.into())? {
|
||||
Packet::Pong(_) => Ok(()),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pushes a message to `topic`, as this client's node: its id.
|
||||
pub fn push(&mut self, topic: &str, data: &str) -> Result<u64> {
|
||||
check_name(topic, "topic")?;
|
||||
|
||||
@@ -32,10 +32,12 @@ synchronous = "full"
|
||||
# well under it (more than a few GB is a lot for this anyway).
|
||||
max_attachment_size = "1G" # bytes, or K M G T (1024-based); 0: none
|
||||
retention_interval = "1m" # how often old messages are deleted
|
||||
idle_database_connections = 8 # kept open once idle, for reads and as many for queries; closed after 1 min unused
|
||||
|
||||
# How long each topic's messages are kept, from when they were first
|
||||
# pushed. A topic takes its name's line, else the first pattern matching
|
||||
# it, else "*"'s; without any, it's kept forever.
|
||||
# pushed: 100 years ("36500d") at most, or "forever". A topic takes its
|
||||
# name's line, else the first pattern matching it, else "*"'s; without
|
||||
# any, it's kept forever.
|
||||
[retention]
|
||||
logs = "30d"
|
||||
"sensors.*" = "12h"
|
||||
@@ -47,7 +49,7 @@ logs = "30d"
|
||||
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 ["*"]
|
||||
retry_delay = "10s"
|
||||
sync_interval = "5s" # keep it under 5 min: a link idle that long is closed
|
||||
sync_interval = "5s" # a link waiting longer than a minute pings meanwhile
|
||||
batch_size = 1000 # messages per packet, 1-10000
|
||||
|
||||
# What certificates with a role may do. A certificate gets everything its
|
||||
|
||||
@@ -29,6 +29,11 @@ use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
use values::{DURATION_HELP, NAME_HELP, parse_age};
|
||||
|
||||
/// The longest retention age: 100 years (36500 days). Longer is
|
||||
/// "forever"; past about 584 million years, an age wouldn't even fit in
|
||||
/// milliseconds.
|
||||
pub const MAX_RETENTION_AGE: Duration = Duration::from_secs(36_500 * 86_400);
|
||||
|
||||
/// What's wrong with a config, in words: where (the file, the line) and why.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Error(String);
|
||||
@@ -95,6 +100,14 @@ pub struct Server {
|
||||
deserialize_with = "values::duration"
|
||||
)]
|
||||
pub retention_interval: Duration,
|
||||
/// The most database connections kept open once idle, for reads, and
|
||||
/// as many for queries (0 to 512); 8 by default. More are opened
|
||||
/// while they're needed, and closed after a minute unused.
|
||||
#[serde(
|
||||
default = "defaults::idle_database_connections",
|
||||
deserialize_with = "values::idle_connections"
|
||||
)]
|
||||
pub idle_database_connections: usize,
|
||||
}
|
||||
|
||||
/// How hard the database makes sure a push is on disk before answering it
|
||||
@@ -165,6 +178,11 @@ impl TryFrom<IndexMap<String, toml::Value>> for Retention {
|
||||
let age = age.ok_or_else(|| {
|
||||
format!("{key} = {value} isn't an age: {DURATION_HELP}, or \"forever\"")
|
||||
})?;
|
||||
if age.is_some_and(|age| age > MAX_RETENTION_AGE) {
|
||||
return Err(format!(
|
||||
"{key} = {value}: 100 years (36500d) at most, or \"forever\""
|
||||
));
|
||||
}
|
||||
lines.push((key, age));
|
||||
}
|
||||
Ok(Retention { lines })
|
||||
@@ -185,6 +203,14 @@ impl Retention {
|
||||
.or_else(|| self.lines.iter().find(|(key, _)| key == "*"))
|
||||
.and_then(|(_, age)| *age)
|
||||
}
|
||||
|
||||
/// When `topic`'s messages pushed before are past their age, for a
|
||||
/// clock at `now` (both in ms since 1970), `None` if they're kept
|
||||
/// forever. 0 while the clock is earlier than the age.
|
||||
pub fn cutoff(&self, topic: &str, now: u64) -> Option<u64> {
|
||||
let age = self.age(topic)?;
|
||||
Some(now.saturating_sub(u64::try_from(age.as_millis()).unwrap_or(u64::MAX)))
|
||||
}
|
||||
}
|
||||
|
||||
/// `[replication]`.
|
||||
@@ -238,6 +264,9 @@ mod defaults {
|
||||
pub(crate) fn retention_interval() -> Duration {
|
||||
Duration::from_secs(60)
|
||||
}
|
||||
pub(crate) fn idle_database_connections() -> usize {
|
||||
8
|
||||
}
|
||||
}
|
||||
|
||||
/// `[roles.*]`: each section's name is its role's, none twice.
|
||||
|
||||
@@ -184,6 +184,21 @@ pub(crate) fn batch_size<'de, D: Deserializer<'de>>(reader: D) -> Result<u32, D:
|
||||
Ok(size)
|
||||
}
|
||||
|
||||
/// The most idle database connections a server keeps per pool.
|
||||
pub(crate) const MAX_IDLE_CONNECTIONS: u32 = 512;
|
||||
|
||||
/// How many idle database connections to keep, 0 to
|
||||
/// `MAX_IDLE_CONNECTIONS`.
|
||||
pub(crate) fn idle_connections<'de, D: Deserializer<'de>>(reader: D) -> Result<usize, D::Error> {
|
||||
let count = u32::deserialize(reader)?;
|
||||
if count > MAX_IDLE_CONNECTIONS {
|
||||
return Err(D::Error::custom(format!(
|
||||
"{count} idle database connections: 0 to {MAX_IDLE_CONNECTIONS}"
|
||||
)));
|
||||
}
|
||||
Ok(count as usize)
|
||||
}
|
||||
|
||||
/// Checks a list of names or patterns, none twice.
|
||||
pub(crate) fn check_names(list: &[String]) -> Result<(), String> {
|
||||
for (at, entry) in list.iter().enumerate() {
|
||||
|
||||
@@ -59,6 +59,7 @@ fn defaults() {
|
||||
assert_eq!(server.synchronous, Synchronous::Full);
|
||||
assert_eq!(server.max_attachment_size, 1 << 30);
|
||||
assert_eq!(server.retention_interval, Duration::from_secs(60));
|
||||
assert_eq!(server.idle_database_connections, 8);
|
||||
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));
|
||||
@@ -75,6 +76,7 @@ database = "data/messages.sqlite"
|
||||
synchronous = "NORMAL"
|
||||
max_attachment_size = 0
|
||||
retention_interval = "1h30m"
|
||||
idle_database_connections = 0
|
||||
|
||||
[replication]
|
||||
push_to = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"]
|
||||
@@ -89,6 +91,7 @@ batch_size = 10000
|
||||
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.server.idle_database_connections, 0);
|
||||
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));
|
||||
@@ -122,6 +125,24 @@ logs = "30d"
|
||||
assert_eq!(age("other"), days(365));
|
||||
}
|
||||
|
||||
/// Ages go up to 100 years, and the cutoff never wraps around.
|
||||
#[test]
|
||||
fn retention_cutoff() {
|
||||
let config = Config::parse(&with(
|
||||
"[retention]\nlogs = \"36500d\"\nsensors = \"1h\"\n\"*\" = \"forever\"\n",
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(config.retention.age("logs"), days(36_500));
|
||||
let now = 2_000_000_000_000;
|
||||
assert_eq!(
|
||||
config.retention.cutoff("sensors", now),
|
||||
Some(now - 3_600_000)
|
||||
);
|
||||
// Longer than the clock is old: nothing is past it yet.
|
||||
assert_eq!(config.retention.cutoff("logs", now), Some(0));
|
||||
assert_eq!(config.retention.cutoff("other", now), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permissions() {
|
||||
let config = Config::parse(&with(
|
||||
@@ -277,6 +298,14 @@ fn refusals() {
|
||||
&with("retention_interval = \"0s\"\n"),
|
||||
"'0s' isn't a duration",
|
||||
),
|
||||
(
|
||||
&with("idle_database_connections = 513\n"),
|
||||
"513 idle database connections: 0 to 512",
|
||||
),
|
||||
(
|
||||
&with("idle_database_connections = -1\n"),
|
||||
"invalid value: integer `-1`",
|
||||
),
|
||||
// [retention]
|
||||
(
|
||||
&with("[retention]\nlogs = \"30\"\n"),
|
||||
@@ -295,6 +324,16 @@ fn refusals() {
|
||||
&with("[retention]\nsensors.kitchen = \"1d\"\n"),
|
||||
"quote names with dots",
|
||||
),
|
||||
// 100 years at most: past 2^64 ms an age once wrapped around to
|
||||
// almost nothing ("18446744073709552s" was 384 ms).
|
||||
(
|
||||
&with("[retention]\nlogs = \"36501d\"\n"),
|
||||
"100 years (36500d) at most",
|
||||
),
|
||||
(
|
||||
&with("[retention]\nlogs = \"18446744073709552s\"\n"),
|
||||
"100 years (36500d) at most",
|
||||
),
|
||||
// [replication]
|
||||
(
|
||||
&with("[replication]\npush_to = [\"10.0.0.2\"]\n"),
|
||||
|
||||
@@ -12,6 +12,15 @@ pub const PROTOCOL_VERSION: u32 = 8;
|
||||
/// checked once connected, so a mismatch is told as such.
|
||||
pub const ALPN: &[u8] = b"bakashrot";
|
||||
|
||||
/// How long a server lets a connection stay silent between requests
|
||||
/// before it closes it, in seconds (5 min). An end that waits longer
|
||||
/// between requests sends a `Ping` every [`KEEPALIVE_SECS`] meanwhile.
|
||||
pub const IDLE_TIMEOUT_SECS: u64 = 300;
|
||||
|
||||
/// How often an end waiting between requests sends a `Ping` to keep the
|
||||
/// connection open, in seconds: well under [`IDLE_TIMEOUT_SECS`].
|
||||
pub const KEEPALIVE_SECS: u64 = 60;
|
||||
|
||||
/// The biggest packet on the wire, in bytes (a frame's size field).
|
||||
pub const MAX_PACKET_SIZE: usize = 16 * 1024 * 1024;
|
||||
|
||||
@@ -43,6 +52,11 @@ pub const MAX_NAMES_LIST_ENTRIES: usize = 65_536;
|
||||
/// The most attachments a `SyncState` lists as missing at once.
|
||||
pub const MAX_MISSING_ATTACHMENTS: usize = 256;
|
||||
|
||||
/// The most heads in one `SyncState`: the others come in the next ones
|
||||
/// (`more`). With every list of the first full and every name 64
|
||||
/// characters long, it still fits in a packet (about 13.3 MB).
|
||||
pub const MAX_HEADS_PER_PACKET: usize = 32_768;
|
||||
|
||||
/// Attachments go in parts of this many bytes, the last one what's left.
|
||||
pub const ATTACHMENT_PART_SIZE: u64 = 1024 * 1024;
|
||||
|
||||
|
||||
@@ -33,10 +33,10 @@ pub use messages::{
|
||||
PushMessage, Query, QueryResult, StoredAttachment,
|
||||
};
|
||||
pub use replication::{
|
||||
Head, MissingAttachment, ReplicateAttachment, ReplicateMessages, ReplicatedMessage, SyncState,
|
||||
SyncStateRequest,
|
||||
Head, MissingAttachment, Pair, ReplicateAttachment, ReplicateMessages, ReplicatedMessage,
|
||||
SyncState, SyncStateRequest,
|
||||
};
|
||||
pub use session::{Continue, RequestRefused, Welcome};
|
||||
pub use session::{Continue, Ping, Pong, RequestRefused, Welcome};
|
||||
|
||||
use serde::de::{self, DeserializeOwned, IgnoredAny, SeqAccess, Visitor};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
@@ -244,6 +244,10 @@ packets! {
|
||||
ReplicateMessages = 17,
|
||||
/// P→S: an attachment the server is missing, its parts after it (`Continue`, then `MessagePushed` / `RequestRefused`).
|
||||
ReplicateAttachment = 18,
|
||||
/// C→S, P→S: keeps an idle connection open (`Pong`).
|
||||
Ping = 19,
|
||||
/// S→C, S→P: the answer to a `Ping`.
|
||||
Pong = 20,
|
||||
}
|
||||
|
||||
impl Packet {
|
||||
|
||||
@@ -6,19 +6,43 @@
|
||||
use super::rules;
|
||||
use super::{Attachment, Check, DecodeError};
|
||||
use crate::limits::{
|
||||
MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_MISSING_ATTACHMENTS,
|
||||
MAX_NAMES_LIST_ENTRIES,
|
||||
MAX_ATTACHMENT_PARTS, MAX_HEADS_PER_PACKET, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET,
|
||||
MAX_MISSING_ATTACHMENTS, MAX_NAMES_LIST_ENTRIES,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// What the server takes from this peer, how far it is, and the
|
||||
/// attachments it lacks.
|
||||
/// attachments it lacks: a page of its `SyncState`, the first without
|
||||
/// `after`.
|
||||
///
|
||||
/// `[15, []]`
|
||||
/// `[15, [after]]`
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SyncStateRequest {}
|
||||
pub struct SyncStateRequest {
|
||||
/// The heads after this pair (the last of the previous page), or none
|
||||
/// for the first page.
|
||||
pub after: Option<Pair>,
|
||||
}
|
||||
|
||||
impl Check for SyncStateRequest {}
|
||||
impl Check for SyncStateRequest {
|
||||
fn check(&self) -> Result<(), DecodeError> {
|
||||
if let Some(after) = &self.after {
|
||||
rules::name(&after.topic, "SyncStateRequest.after.topic")?;
|
||||
rules::name(&after.node, "SyncStateRequest.after.node")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A topic/node pair, by name.
|
||||
///
|
||||
/// `[topic, node]`
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Pair {
|
||||
/// The topic.
|
||||
pub topic: String,
|
||||
/// The node.
|
||||
pub node: String,
|
||||
}
|
||||
|
||||
/// How far the server is in a topic/node pair.
|
||||
///
|
||||
@@ -49,25 +73,38 @@ pub struct MissingAttachment {
|
||||
}
|
||||
|
||||
/// What the server takes from this peer, how far it is, and the
|
||||
/// attachments it lacks: all a check-in needs.
|
||||
/// attachments it lacks: all a check-in needs, in pages of
|
||||
/// `MAX_HEADS_PER_PACKET` heads. The first page has the lists; the next
|
||||
/// ones, asked `after` the last head of the previous one, only heads.
|
||||
///
|
||||
/// `[16, [[topic...], [node...], [head...], [missing...]]]`
|
||||
/// `[16, [more, [topic...], [node...], [head...], [missing...]]]`
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SyncState {
|
||||
/// Whether other heads follow: ask again `after` the last one here.
|
||||
pub more: bool,
|
||||
/// The topics it takes from this peer: names, and wildcards (it takes
|
||||
/// the names they match, even those it doesn't have yet).
|
||||
/// the names they match, even those it doesn't have yet). Empty after
|
||||
/// the first page.
|
||||
pub topics: Vec<String>,
|
||||
/// The nodes it takes from this peer, the same way.
|
||||
pub nodes: Vec<String>,
|
||||
/// Its highest message id in each topic/node pair of those.
|
||||
/// Its highest message id in each topic/node pair of those, in the
|
||||
/// order of their names (without case), `MAX_HEADS_PER_PACKET` at
|
||||
/// most.
|
||||
pub heads: Vec<Head>,
|
||||
/// The attachments it lacks among those, `MAX_MISSING_ATTACHMENTS` at
|
||||
/// most.
|
||||
/// most. Empty after the first page.
|
||||
pub missing: Vec<MissingAttachment>,
|
||||
}
|
||||
|
||||
impl Check for SyncState {
|
||||
fn check(&self) -> Result<(), DecodeError> {
|
||||
rules::most(self.heads.len(), MAX_HEADS_PER_PACKET, "SyncState.heads")?;
|
||||
rules::require(
|
||||
!self.more || !self.heads.is_empty(),
|
||||
"SyncState.heads",
|
||||
"one at least when more follow",
|
||||
)?;
|
||||
for (list, field) in [
|
||||
(&self.topics, "SyncState.topics"),
|
||||
(&self.nodes, "SyncState.nodes"),
|
||||
|
||||
@@ -74,3 +74,21 @@ impl Check for RequestRefused {
|
||||
pub struct Continue {}
|
||||
|
||||
impl Check for Continue {}
|
||||
|
||||
/// Keeps an idle connection open: the server answers `Pong`, and counts
|
||||
/// it as a request (`IDLE_TIMEOUT_SECS`). For a client or a peer waiting
|
||||
/// longer than that between requests.
|
||||
///
|
||||
/// `[19, []]`
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Ping {}
|
||||
|
||||
impl Check for Ping {}
|
||||
|
||||
/// The answer to a `Ping`.
|
||||
///
|
||||
/// `[20, []]`
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Pong {}
|
||||
|
||||
impl Check for Pong {}
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//! refuses, and that no input makes it panic.
|
||||
|
||||
use bakashrot_proto::limits::{
|
||||
ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET,
|
||||
MAX_TIMESTAMP,
|
||||
ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_PARTS, MAX_ATTACHMENT_SIZE, MAX_HEADS_PER_PACKET,
|
||||
MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_MISSING_ATTACHMENTS, MAX_NAMES_LIST_ENTRIES,
|
||||
MAX_PACKET_SIZE, MAX_TIMESTAMP,
|
||||
};
|
||||
use bakashrot_proto::packets::*;
|
||||
use bakashrot_proto::{Body, DecodeError, ErrorCode, Packet, PacketType};
|
||||
@@ -35,6 +36,8 @@ fn samples() -> Vec<Packet> {
|
||||
.into(),
|
||||
RequestRefused::new(ErrorCode::UnknownName, "Unknown topic 'nope'").into(),
|
||||
Continue {}.into(),
|
||||
Ping {}.into(),
|
||||
Pong {}.into(),
|
||||
PushMessage {
|
||||
topic: "logs".into(),
|
||||
data: "é€ \u{1F600} {\"a\":[1,2]}".into(),
|
||||
@@ -122,8 +125,16 @@ fn samples() -> Vec<Packet> {
|
||||
json: r#"{"columns":["a"],"rows":[[1],[null]]}"#.into(),
|
||||
}
|
||||
.into(),
|
||||
SyncStateRequest {}.into(),
|
||||
SyncStateRequest { after: None }.into(),
|
||||
SyncStateRequest {
|
||||
after: Some(Pair {
|
||||
topic: "logs".into(),
|
||||
node: "kitchen".into(),
|
||||
}),
|
||||
}
|
||||
.into(),
|
||||
SyncState {
|
||||
more: true,
|
||||
topics: vec!["logs".into(), "sensors.*".into()],
|
||||
nodes: vec!["*".into()],
|
||||
heads: vec![
|
||||
@@ -245,6 +256,8 @@ fn golden_bytes() {
|
||||
]
|
||||
);
|
||||
assert_eq!(Continue {}.encode(), [0x92, 0x03, 0x90]);
|
||||
assert_eq!(Ping {}.encode(), [0x92, 0x13, 0x90]);
|
||||
assert_eq!(Pong {}.encode(), [0x92, 0x14, 0x90]);
|
||||
assert_eq!(
|
||||
MessagePushed { message_id: 300 }.encode(),
|
||||
[0x92, 0x05, 0x91, 0xcd, 0x01, 0x2c]
|
||||
@@ -298,6 +311,7 @@ fn shapes() {
|
||||
assert!(malformed(&raw(PacketType::MessagePushed, ((),))));
|
||||
assert!(malformed(&raw(PacketType::MessagePushed, (1u64, 2u64))));
|
||||
assert!(malformed(&raw(PacketType::Continue, (1u64,))));
|
||||
assert!(malformed(&raw(PacketType::Ping, (1u64,))));
|
||||
// The wrong types.
|
||||
assert!(malformed(&raw(PacketType::MessagePushed, ("1",))));
|
||||
assert!(malformed(&raw(PacketType::MessagePushed, (-1i64,))));
|
||||
@@ -479,7 +493,26 @@ fn too_many_items() {
|
||||
};
|
||||
assert!(invalid(&too_many.encode()));
|
||||
|
||||
let head = |n: usize| Head {
|
||||
topic: "t".into(),
|
||||
node: format!("n{n}"),
|
||||
last_id: 1,
|
||||
};
|
||||
let heads = |count: usize, more: bool| SyncState {
|
||||
more,
|
||||
topics: vec![],
|
||||
nodes: vec![],
|
||||
heads: (0..count).map(head).collect(),
|
||||
missing: vec![],
|
||||
};
|
||||
assert!(Packet::decode(&heads(MAX_HEADS_PER_PACKET, true).encode()).is_ok());
|
||||
assert!(invalid(&heads(MAX_HEADS_PER_PACKET + 1, false).encode()));
|
||||
assert!(Packet::decode(&heads(0, false).encode()).is_ok());
|
||||
// More to come, but no head to ask after.
|
||||
assert!(invalid(&heads(0, true).encode()));
|
||||
|
||||
let missing = SyncState {
|
||||
more: false,
|
||||
topics: vec![],
|
||||
nodes: vec![],
|
||||
heads: vec![],
|
||||
@@ -532,6 +565,7 @@ fn names_everywhere() {
|
||||
|
||||
let state = |topic: &str| {
|
||||
SyncState {
|
||||
more: false,
|
||||
topics: vec![topic.into()],
|
||||
nodes: vec![],
|
||||
heads: vec![],
|
||||
@@ -543,6 +577,20 @@ fn names_everywhere() {
|
||||
assert!(Packet::decode(&state("logs")).is_ok());
|
||||
assert!(invalid(&state("12")));
|
||||
assert!(invalid(&state("a b*")));
|
||||
let after = |topic: &str, node: &str| {
|
||||
SyncStateRequest {
|
||||
after: Some(Pair {
|
||||
topic: topic.into(),
|
||||
node: node.into(),
|
||||
}),
|
||||
}
|
||||
.encode()
|
||||
};
|
||||
assert!(Packet::decode(&after("logs", "kitchen")).is_ok());
|
||||
assert!(invalid(&after("logs*", "kitchen")));
|
||||
assert!(invalid(&after("logs", "*")));
|
||||
assert!(invalid(&after("", "kitchen")));
|
||||
assert!(invalid(&after("logs", "12")));
|
||||
|
||||
let welcome = Welcome {
|
||||
server: "s".into(),
|
||||
@@ -551,6 +599,40 @@ fn names_everywhere() {
|
||||
assert!(invalid(&welcome.encode()));
|
||||
}
|
||||
|
||||
/// The biggest `SyncState` there can be still fits in a packet: every list
|
||||
/// full, every name 64 characters, every number its largest.
|
||||
#[test]
|
||||
fn the_biggest_sync_state_fits() {
|
||||
let name = |prefix: char, n: usize| format!("{prefix}{n:0>63}");
|
||||
let state = SyncState {
|
||||
more: true,
|
||||
topics: (0..MAX_NAMES_LIST_ENTRIES).map(|n| name('t', n)).collect(),
|
||||
nodes: (0..MAX_NAMES_LIST_ENTRIES).map(|n| name('n', n)).collect(),
|
||||
heads: (0..MAX_HEADS_PER_PACKET)
|
||||
.map(|n| Head {
|
||||
topic: name('t', n),
|
||||
node: name('n', n),
|
||||
last_id: MAX_MESSAGE_ID,
|
||||
})
|
||||
.collect(),
|
||||
missing: (0..MAX_MISSING_ATTACHMENTS)
|
||||
.map(|n| MissingAttachment {
|
||||
topic: name('t', n),
|
||||
node: name('n', n),
|
||||
message_id: MAX_MESSAGE_ID,
|
||||
next_part: MAX_ATTACHMENT_PARTS - 1,
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let bytes = state.encode();
|
||||
assert!(
|
||||
bytes.len() <= MAX_PACKET_SIZE,
|
||||
"{} bytes, {MAX_PACKET_SIZE} at most",
|
||||
bytes.len()
|
||||
);
|
||||
assert_eq!(Packet::decode(&bytes), Ok(state.into()));
|
||||
}
|
||||
|
||||
/// xorshift64*, enough to make bytes that look like anything.
|
||||
struct Random(u64);
|
||||
|
||||
@@ -572,7 +654,7 @@ fn nothing_makes_it_panic() {
|
||||
let mut bytes: Vec<u8> = (0..len).map(|_| random.next() as u8).collect();
|
||||
if round % 2 == 0 && bytes.len() > 2 {
|
||||
bytes[0] = 0x92;
|
||||
bytes[1] = 1 + (bytes[1] % 18);
|
||||
bytes[1] = 1 + (bytes[1] % PacketType::ALL.len() as u8);
|
||||
bytes[2] = 0x90 | (bytes[2] & 0x0f);
|
||||
}
|
||||
let _ = Packet::decode(&bytes);
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -9,7 +9,7 @@ use bakashrot_proto::packets::{
|
||||
Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, ReplicatedMessage,
|
||||
StoredAttachment,
|
||||
};
|
||||
use rusqlite::{Connection, OptionalExtension, Row};
|
||||
use rusqlite::{Connection, OptionalExtension, Row, params};
|
||||
|
||||
/// About how many bytes of messages one answer carries: past it, the rest
|
||||
/// is left for the next request (`more`). A bigger message goes alone.
|
||||
@@ -160,11 +160,25 @@ impl Reader {
|
||||
.map_err(Error::from)
|
||||
}
|
||||
|
||||
/// Every topic and node's last id: what `SyncState` compares.
|
||||
/// Every topic and node's last id, in the order of their names
|
||||
/// (without case).
|
||||
pub fn heads(&self) -> Result<Vec<Head>> {
|
||||
self.heads_after(None, usize::MAX)
|
||||
}
|
||||
|
||||
/// Topics and nodes' last ids, what `SyncState` compares: `limit` at
|
||||
/// most, in the order of their names (without case), those after the
|
||||
/// pair `after` (from the first without).
|
||||
pub fn heads_after(&self, after: Option<(&str, &str)>, limit: usize) -> Result<Vec<Head>> {
|
||||
// No name is empty: ("", "") comes before every pair.
|
||||
let (topic, node) = after.unwrap_or(("", ""));
|
||||
let limit = i64::try_from(limit).unwrap_or(i64::MAX);
|
||||
self.connection
|
||||
.prepare_cached("SELECT topic, node, last_id FROM streams ORDER BY topic, node")?
|
||||
.query_map([], |row| {
|
||||
.prepare_cached(
|
||||
"SELECT topic, node, last_id FROM streams WHERE (topic, node) > (?1, ?2) \
|
||||
ORDER BY topic, node LIMIT ?3",
|
||||
)?
|
||||
.query_map(params![topic, node, limit], |row| {
|
||||
Ok(Head {
|
||||
topic: row.get(0)?,
|
||||
node: row.get(1)?,
|
||||
|
||||
@@ -173,6 +173,31 @@ fn pushing_and_reading() {
|
||||
("sensors".into(), "kitchen".into(), 1)
|
||||
]
|
||||
);
|
||||
// In pages: after a pair (its names without case), so many at most.
|
||||
let page = |after, limit| -> Vec<_> {
|
||||
reader
|
||||
.heads_after(after, limit)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|h| (h.topic, h.node))
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(
|
||||
page(None, 2),
|
||||
[
|
||||
("logs".into(), "garage".into()),
|
||||
("logs".into(), "kitchen".into())
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
page(Some(("LOGS", "Kitchen")), 2),
|
||||
[("sensors".into(), "kitchen".into())]
|
||||
);
|
||||
assert_eq!(
|
||||
page(Some(("logs", "h")), 1),
|
||||
[("logs".into(), "kitchen".into())]
|
||||
);
|
||||
assert!(page(Some(("sensors", "kitchen")), 2).is_empty());
|
||||
assert_eq!(reader.last_id("logs", "kitchen").unwrap(), 3);
|
||||
assert_eq!(reader.last_id("nope", "kitchen").unwrap(), 0);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ mod cert;
|
||||
|
||||
use bakashrot_client::{Client, Error, Settings};
|
||||
use bakashrot_proto::error::{code_name, is_refusal_code};
|
||||
use bakashrot_proto::limits::MAX_MESSAGES_PER_PACKET;
|
||||
use bakashrot_proto::limits::{KEEPALIVE_SECS, MAX_MESSAGES_PER_PACKET};
|
||||
use bakashrot_proto::packets::{MessageEntry, NameKind};
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
use serde::Deserialize;
|
||||
@@ -266,7 +266,7 @@ fn run(config: &Path, command: Command) -> Result<(), String> {
|
||||
break;
|
||||
}
|
||||
if !batch.more {
|
||||
std::thread::sleep(Duration::from_millis(interval));
|
||||
wait(&mut client, Duration::from_millis(interval))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -317,6 +317,22 @@ fn run(config: &Path, command: Command) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Waits `duration`, pinging every `KEEPALIVE_SECS` meanwhile: the server
|
||||
/// closes a connection silent for 5 min, and `--interval` goes up to 1 h.
|
||||
fn wait(client: &mut Client, duration: Duration) -> Result<(), String> {
|
||||
let keepalive = Duration::from_secs(KEEPALIVE_SECS);
|
||||
let mut left = duration;
|
||||
loop {
|
||||
let step = left.min(keepalive);
|
||||
std::thread::sleep(step);
|
||||
left -= step;
|
||||
if left.is_zero() {
|
||||
return Ok(());
|
||||
}
|
||||
client.ping().map_err(failed)?;
|
||||
}
|
||||
}
|
||||
|
||||
/// A topic and node's latest message, if any.
|
||||
fn latest(client: &mut Client, topic: &str, node: &str) -> Result<Option<MessageEntry>, String> {
|
||||
let latest = client.get_messages(topic, node, None, 1).map_err(failed)?;
|
||||
|
||||
Reference in New Issue
Block a user