1
0
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:
2026-11-19 23:19:58 +01:00
parent c513d8bf05
commit 6fae7e61c9
34 changed files with 1066 additions and 164 deletions
+14
View File
@@ -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;
+7 -3
View File
@@ -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 {}
+86 -4
View File
@@ -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);