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
+8
View File
@@ -117,6 +117,14 @@ ptrdiff_t BakaShrot_IsConnected(int64_t client);
*/ */
ptrdiff_t BakaShrot_Disconnect(int64_t client); ptrdiff_t BakaShrot_Disconnect(int64_t client);
/**
* 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).
*/
ptrdiff_t BakaShrot_Ping(int64_t client);
/** /**
* The node this client is, as the server said when connecting: its * The node this client is, as the server said when connecting: its
* certificate's name. Empty when not connected. * certificate's name. Empty when not connected.
@@ -287,10 +287,14 @@ namespace NibblePoker.BakaShrot.Tests
public void Closing() public void Closing()
{ {
Client kitchen = Server.Connect("kitchen"); Client kitchen = Server.Connect("kitchen");
kitchen.Ping();
Assert.That(kitchen.Connected, Is.True, "still connected after a ping");
kitchen.Close(); kitchen.Close();
Assert.That(kitchen.Connected, Is.False); Assert.That(kitchen.Connected, Is.False);
ConnectionLostException lost = Assert.Throws<ConnectionLostException>(() => kitchen.Push("logs", "x"))!; ConnectionLostException lost = Assert.Throws<ConnectionLostException>(() => kitchen.Push("logs", "x"))!;
Assert.That(lost.Code, Is.EqualTo(ErrorCode.NotConnected)); Assert.That(lost.Code, Is.EqualTo(ErrorCode.NotConnected));
lost = Assert.Throws<ConnectionLostException>(() => kitchen.Ping())!;
Assert.That(lost.Code, Is.EqualTo(ErrorCode.NotConnected));
kitchen.Connect(); kitchen.Connect();
Assert.That(kitchen.Connected, Is.True, "connects again"); Assert.That(kitchen.Connected, Is.True, "connects again");
kitchen.Dispose(); kitchen.Dispose();
@@ -201,6 +201,18 @@ namespace NibblePoker.BakaShrot
Native.BakaShrot_FreeClient(handle); Native.BakaShrot_FreeClient(handle);
} }
/// <summary>Keeps the connection open: the server closes one silent
/// for 5 min. An app waiting longer between requests calls it every
/// minute or so (KeepAliveMs); Follow() does it itself.</summary>
public void Ping()
{
lock (sync)
Check(Native.BakaShrot_Ping(Handle()), "Ping");
}
/// <summary>How often to Ping() while waiting between requests, in ms.</summary>
public const int KeepAliveMs = 60000;
/// <summary>Pushes data (JSON or not) to topic, as this client's node: its id.</summary> /// <summary>Pushes data (JSON or not) to topic, as this client's node: its id.</summary>
public long Push(string topic, string data) public long Push(string topic, string data)
{ {
@@ -278,8 +290,9 @@ namespace NibblePoker.BakaShrot
} }
/// <summary>Every message after id after, then new ones as they /// <summary>Every message after id after, then new ones as they
/// come, checking every intervalMs: forever, stop enumerating to /// come, checking every intervalMs (pinging every minute meanwhile
/// stop. Nothing reconnects by itself.</summary> /// if it's longer): forever, stop enumerating to stop. Nothing
/// reconnects by itself.</summary>
public IEnumerable<Message> Follow(string topic, string node, long after, int intervalMs) public IEnumerable<Message> Follow(string topic, string node, long after, int intervalMs)
{ {
while (true) while (true)
@@ -289,7 +302,7 @@ namespace NibblePoker.BakaShrot
yield return message; yield return message;
after = Math.Max(after, page.LastId); after = Math.Max(after, page.LastId);
if (!page.More) if (!page.More)
Thread.Sleep(intervalMs); Wait(intervalMs);
} }
} }
@@ -419,6 +432,21 @@ namespace NibblePoker.BakaShrot
// --- Inside --------------------------------------------------------- // --- Inside ---------------------------------------------------------
// Sleeps intervalMs, pinging every KeepAliveMs meanwhile.
private void Wait(int intervalMs)
{
int left = intervalMs;
while (true)
{
int step = Math.Min(left, KeepAliveMs);
Thread.Sleep(step);
left -= step;
if (left <= 0)
return;
Ping();
}
}
private IEnumerable<string> EnumerateNames(int kind, string topic, string node) private IEnumerable<string> EnumerateNames(int kind, string topic, string node)
{ {
long enumeration; long enumeration;
@@ -563,6 +591,7 @@ namespace NibblePoker.BakaShrot
[DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_SetCrlW(long client, string crl); [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_SetCrlW(long client, string crl);
[DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_ConnectW(long client, string host, int port); [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_ConnectW(long client, string host, int port);
[DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_IsConnected(long client); [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_IsConnected(long client);
[DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_Ping(long client);
[DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_GetNodeW(long client, byte[] buffer, IntPtr size); [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_GetNodeW(long client, byte[] buffer, IntPtr size);
[DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern long BakaShrot_PushMessageToW(long client, string topic, string data); [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern long BakaShrot_PushMessageToW(long client, string topic, string data);
[DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_GetLatestMessageOfW(long client, string topic, string node); [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_GetLatestMessageOfW(long client, string topic, string node);
@@ -62,6 +62,7 @@ PrototypeC.i BakaShrot_SetCrl_Prototype(Client.q, Crl.p-unicode)
PrototypeC.i BakaShrot_Connect_Prototype(Client.q, Host.p-unicode, Port.l) PrototypeC.i BakaShrot_Connect_Prototype(Client.q, Host.p-unicode, Port.l)
PrototypeC.i BakaShrot_IsConnected_Prototype(Client.q) PrototypeC.i BakaShrot_IsConnected_Prototype(Client.q)
PrototypeC.i BakaShrot_Disconnect_Prototype(Client.q) PrototypeC.i BakaShrot_Disconnect_Prototype(Client.q)
PrototypeC.i BakaShrot_Ping_Prototype(Client.q)
PrototypeC.i BakaShrot_GetNode_Prototype(Client.q, *Buffer, BufferSize.i) PrototypeC.i BakaShrot_GetNode_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.q BakaShrot_PushMessageTo_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode) PrototypeC.q BakaShrot_PushMessageTo_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode)
PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Client.q, Topic.p-unicode, Node.p-unicode) PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Client.q, Topic.p-unicode, Node.p-unicode)
@@ -112,6 +113,7 @@ Global BakaShrot_SetCrl.BakaShrot_SetCrl_Prototype
Global BakaShrot_Connect.BakaShrot_Connect_Prototype Global BakaShrot_Connect.BakaShrot_Connect_Prototype
Global BakaShrot_IsConnected.BakaShrot_IsConnected_Prototype Global BakaShrot_IsConnected.BakaShrot_IsConnected_Prototype
Global BakaShrot_Disconnect.BakaShrot_Disconnect_Prototype Global BakaShrot_Disconnect.BakaShrot_Disconnect_Prototype
Global BakaShrot_Ping.BakaShrot_Ping_Prototype
Global BakaShrot_GetNode.BakaShrot_GetNode_Prototype Global BakaShrot_GetNode.BakaShrot_GetNode_Prototype
Global BakaShrot_PushMessageTo.BakaShrot_PushMessageTo_Prototype Global BakaShrot_PushMessageTo.BakaShrot_PushMessageTo_Prototype
Global BakaShrot_GetLatestMessageOf.BakaShrot_GetLatestMessageOf_Prototype Global BakaShrot_GetLatestMessageOf.BakaShrot_GetLatestMessageOf_Prototype
@@ -199,6 +201,7 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
BakaShrot_Connect = BakaShrot_ClientFunction("BakaShrot_ConnectW") BakaShrot_Connect = BakaShrot_ClientFunction("BakaShrot_ConnectW")
BakaShrot_IsConnected = BakaShrot_ClientFunction("BakaShrot_IsConnected") BakaShrot_IsConnected = BakaShrot_ClientFunction("BakaShrot_IsConnected")
BakaShrot_Disconnect = BakaShrot_ClientFunction("BakaShrot_Disconnect") BakaShrot_Disconnect = BakaShrot_ClientFunction("BakaShrot_Disconnect")
BakaShrot_Ping = BakaShrot_ClientFunction("BakaShrot_Ping")
BakaShrot_GetNode = BakaShrot_ClientFunction("BakaShrot_GetNodeW") BakaShrot_GetNode = BakaShrot_ClientFunction("BakaShrot_GetNodeW")
BakaShrot_PushMessageTo = BakaShrot_ClientFunction("BakaShrot_PushMessageToW") BakaShrot_PushMessageTo = BakaShrot_ClientFunction("BakaShrot_PushMessageToW")
BakaShrot_GetLatestMessageOf = BakaShrot_ClientFunction("BakaShrot_GetLatestMessageOfW") BakaShrot_GetLatestMessageOf = BakaShrot_ClientFunction("BakaShrot_GetLatestMessageOfW")
+30 -4
View File
@@ -63,12 +63,15 @@ __version__ = "0.4.0"
__all__ = [ __all__ = [
"Client", "Message", "MessagesPage", "NamesList", "Client", "Message", "MessagesPage", "NamesList",
"BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode", "BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode",
"MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE", "MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE", "KEEPALIVE_SECONDS",
] ]
# The protocol's: crates/bakashrot-proto/src/limits.rs. # The protocol's: crates/bakashrot-proto/src/limits.rs.
MAX_GET_MESSAGES = 10000 MAX_GET_MESSAGES = 10000
MAX_MESSAGE_SIZE = 16 * 1024 * 1024 - 4096 MAX_MESSAGE_SIZE = 16 * 1024 * 1024 - 4096
# The server closes a connection silent for 5 min: ping() every minute or
# so while waiting longer than that (follow() does it itself).
KEEPALIVE_SECONDS = 60
DLL_NAME = "bakashrot.dll" if sys.platform == "win32" else "libbakashrot.so" DLL_NAME = "bakashrot.dll" if sys.platform == "win32" else "libbakashrot.so"
@@ -250,6 +253,7 @@ class _Dll:
"BakaShrot_ConnectA": (I, [H, P, L]), "BakaShrot_ConnectA": (I, [H, P, L]),
"BakaShrot_IsConnected": (I, [H]), "BakaShrot_IsConnected": (I, [H]),
"BakaShrot_Disconnect": (I, [H]), "BakaShrot_Disconnect": (I, [H]),
"BakaShrot_Ping": (I, [H]),
"BakaShrot_GetNodeA": (I, [H, S, I]), "BakaShrot_GetNodeA": (I, [H, S, I]),
"BakaShrot_PushMessageToA": (Q, [H, P, P]), "BakaShrot_PushMessageToA": (Q, [H, P, P]),
"BakaShrot_GetLatestMessageOfA": (I, [H, P, P]), "BakaShrot_GetLatestMessageOfA": (I, [H, P, P]),
@@ -429,6 +433,27 @@ class Client:
# --- Requests ---------------------------------------------------------- # --- Requests ----------------------------------------------------------
def ping(self) -> None:
"""Keeps the connection open: the server closes one silent for 5
min. An app waiting longer than that between requests calls it
every minute or so (KEEPALIVE_SECONDS). ConnectionLostError if
the connection is gone."""
with self._lock:
self._check_connected()
if not self._dll.Ping(self._handle):
raise self._failed("Ping")
def _wait(self, seconds: float) -> None:
"""Sleeps `seconds`, pinging every KEEPALIVE_SECONDS meanwhile."""
left = seconds
while True:
step = min(left, KEEPALIVE_SECONDS)
time.sleep(step)
left -= step
if left <= 0:
return
self.ping()
def push(self, data: Any, topic: str, def push(self, data: Any, topic: str,
attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int: attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int:
"""Pushes a message into topic, under the client's node. data is """Pushes a message into topic, under the client's node. data is
@@ -538,8 +563,9 @@ class Client:
def follow(self, topic: str, node: str, after: Union[int, str] = "latest", def follow(self, topic: str, node: str, after: Union[int, str] = "latest",
interval: float = 0.5, batch: int = 1000) -> Iterator[Message]: interval: float = 0.5, batch: int = 1000) -> Iterator[Message]:
"""Every message of topic/node after `after`, then new ones as they """Every message of topic/node after `after`, then new ones as they
come, checking every `interval` seconds once caught up. Forever: come, checking every `interval` seconds once caught up (pinging
stop iterating to stop. after="latest" starts with the next new one. every minute meanwhile if it's longer). Forever: stop iterating to
stop. after="latest" starts with the next new one.
Raises ConnectionLostError if the connection fails: nothing Raises ConnectionLostError if the connection fails: nothing
reconnects by itself, connect() again and follow from the last id.""" reconnects by itself, connect() again and follow from the last id."""
if after == "latest": if after == "latest":
@@ -553,7 +579,7 @@ class Client:
if page.messages: if page.messages:
after = page.last_id after = page.last_id
if not page.more: if not page.more:
time.sleep(interval) self._wait(interval)
def list_topics(self, topic: Optional[str] = None, node: Optional[str] = None) -> NamesList: def list_topics(self, topic: Optional[str] = None, node: Optional[str] = None) -> NamesList:
"""The topics with messages that the client may push to or read (every one with list_topics or query). """The topics with messages that the client may push to or read (every one with list_topics or query).
+4
View File
@@ -223,6 +223,8 @@ with kitchen:
"missing.bin", ErrorCode.FILE_ERROR) "missing.bin", ErrorCode.FILE_ERROR)
check("A missing file: refused before sending", ok, detail) check("A missing file: refused before sending", ok, detail)
check("Still connected", kitchen.connected) check("Still connected", kitchen.connected)
kitchen.ping()
check("ping(): answered, still connected", kitchen.connected)
# --- Two Clients, two threads, at the same time -------------------------- # --- Two Clients, two threads, at the same time --------------------------
other = Client.from_file(os.path.join(folder, "kitchen.toml"), dll_path).connect() other = Client.from_file(os.path.join(folder, "kitchen.toml"), dll_path).connect()
@@ -247,6 +249,8 @@ with kitchen:
check("close(): disconnected", not kitchen.connected) check("close(): disconnected", not kitchen.connected)
ok, detail = raises(lambda: kitchen.push("x", "logs"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED) ok, detail = raises(lambda: kitchen.push("x", "logs"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED)
check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail) check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail)
ok, detail = raises(kitchen.ping, ConnectionLostError, code=ErrorCode.NOT_CONNECTED)
check("ping() once closed: ConnectionLostError, NOT_CONNECTED", ok, detail)
# --- Connecting: unreachable, refused, PEM text ---------------------------------- # --- Connecting: unreachable, refused, PEM text ----------------------------------
with open(kitchen.ca) as ca, open(kitchen.certificate) as certificate, open(kitchen.key) as key: with open(kitchen.ca) as ca, open(kitchen.certificate) as certificate, open(kitchen.key) as key:
+12
View File
@@ -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 { fn node(state: &State) -> &str {
state.client.as_ref().map_or("", Client::node) state.client.as_ref().map_or("", Client::node)
} }
+6
View File
@@ -391,11 +391,16 @@ fn exports() {
assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
} }
assert_eq!(BakaShrot_IsConnected(client), 1); 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. // Closed: requests refused, the settings kept.
assert_eq!(BakaShrot_Disconnect(client), 1); assert_eq!(BakaShrot_Disconnect(client), 1);
assert_eq!(BakaShrot_Disconnect(client), 0); assert_eq!(BakaShrot_Disconnect(client), 0);
assert_eq!(BakaShrot_IsConnected(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!(get_w(client, BakaShrot_GetNodeW), "");
assert_eq!(BakaShrot_QueryW(client, w("SELECT 1").as_ptr()), 0); assert_eq!(BakaShrot_QueryW(client, w("SELECT 1").as_ptr()), 0);
assert_eq!(error(client).0, code(ErrorCode::NotConnected)); assert_eq!(error(client).0, code(ErrorCode::NotConnected));
@@ -470,6 +475,7 @@ fn clients() {
assert_eq!(failed, code(ErrorCode::InvalidArgument)); assert_eq!(failed, code(ErrorCode::InvalidArgument));
assert!(why.contains("no client 99"), "{why}"); assert!(why.contains("no client 99"), "{why}");
assert_eq!(BakaShrot_IsConnected(99), 0); assert_eq!(BakaShrot_IsConnected(99), 0);
assert_eq!(BakaShrot_Ping(99), 0);
assert_eq!(BakaShrot_GetMessageId(-5), 0); assert_eq!(BakaShrot_GetMessageId(-5), 0);
assert_eq!(get_w(99, BakaShrot_GetMessageDataW), ""); assert_eq!(get_w(99, BakaShrot_GetMessageDataW), "");
assert_eq!(BakaShrot_FreeClient(99), 0); assert_eq!(BakaShrot_FreeClient(99), 0);
+11 -1
View File
@@ -27,7 +27,7 @@ use bakashrot_proto::limits::{
use bakashrot_proto::names::{is_valid_name, is_valid_name_or_pattern}; use bakashrot_proto::names::{is_valid_name, is_valid_name_or_pattern};
use bakashrot_proto::packets::{ use bakashrot_proto::packets::{
Attachment, AttachmentPart, GetAttachment, GetMessages, ListNames, Messages, NameKind, Attachment, AttachmentPart, GetAttachment, GetMessages, ListNames, Messages, NameKind,
NamesList, PushMessage, Query, NamesList, Ping, PushMessage, Query,
}; };
use bakashrot_proto::{ErrorCode, Packet, frame}; use bakashrot_proto::{ErrorCode, Packet, frame};
use rustls::{ClientConnection, StreamOwned}; use rustls::{ClientConnection, StreamOwned};
@@ -204,6 +204,16 @@ impl Client {
open && tcp.set_nonblocking(false).is_ok() 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. /// Pushes a message to `topic`, as this client's node: its id.
pub fn push(&mut self, topic: &str, data: &str) -> Result<u64> { pub fn push(&mut self, topic: &str, data: &str) -> Result<u64> {
check_name(topic, "topic")?; check_name(topic, "topic")?;
+5 -3
View File
@@ -32,10 +32,12 @@ synchronous = "full"
# well under it (more than a few GB is a lot for this anyway). # 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 max_attachment_size = "1G" # bytes, or K M G T (1024-based); 0: none
retention_interval = "1m" # how often old messages are deleted 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 # 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 # pushed: 100 years ("36500d") at most, or "forever". A topic takes its
# it, else "*"'s; without any, it's kept forever. # name's line, else the first pattern matching it, else "*"'s; without
# any, it's kept forever.
[retention] [retention]
logs = "30d" logs = "30d"
"sensors.*" = "12h" "sensors.*" = "12h"
@@ -47,7 +49,7 @@ logs = "30d"
push_to = [] # dialed and sent to: ["10.0.0.2:7000", "server-2.lan:7000"] push_to = [] # dialed and sent to: ["10.0.0.2:7000", "server-2.lan:7000"]
accept_from = [] # taken from: ["10.0.0.2", "server-2.lan"], or ["*"] accept_from = [] # taken from: ["10.0.0.2", "server-2.lan"], or ["*"]
retry_delay = "10s" 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 batch_size = 1000 # messages per packet, 1-10000
# What certificates with a role may do. A certificate gets everything its # What certificates with a role may do. A certificate gets everything its
+29
View File
@@ -29,6 +29,11 @@ use std::path::{Path, PathBuf};
use std::time::Duration; use std::time::Duration;
use values::{DURATION_HELP, NAME_HELP, parse_age}; 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. /// What's wrong with a config, in words: where (the file, the line) and why.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error(String); pub struct Error(String);
@@ -95,6 +100,14 @@ pub struct Server {
deserialize_with = "values::duration" deserialize_with = "values::duration"
)] )]
pub retention_interval: 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 /// 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(|| { let age = age.ok_or_else(|| {
format!("{key} = {value} isn't an age: {DURATION_HELP}, or \"forever\"") 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)); lines.push((key, age));
} }
Ok(Retention { lines }) Ok(Retention { lines })
@@ -185,6 +203,14 @@ impl Retention {
.or_else(|| self.lines.iter().find(|(key, _)| key == "*")) .or_else(|| self.lines.iter().find(|(key, _)| key == "*"))
.and_then(|(_, age)| *age) .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]`. /// `[replication]`.
@@ -238,6 +264,9 @@ mod defaults {
pub(crate) fn retention_interval() -> Duration { pub(crate) fn retention_interval() -> Duration {
Duration::from_secs(60) Duration::from_secs(60)
} }
pub(crate) fn idle_database_connections() -> usize {
8
}
} }
/// `[roles.*]`: each section's name is its role's, none twice. /// `[roles.*]`: each section's name is its role's, none twice.
+15
View File
@@ -184,6 +184,21 @@ pub(crate) fn batch_size<'de, D: Deserializer<'de>>(reader: D) -> Result<u32, D:
Ok(size) 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. /// Checks a list of names or patterns, none twice.
pub(crate) fn check_names(list: &[String]) -> Result<(), String> { pub(crate) fn check_names(list: &[String]) -> Result<(), String> {
for (at, entry) in list.iter().enumerate() { for (at, entry) in list.iter().enumerate() {
+39
View File
@@ -59,6 +59,7 @@ fn defaults() {
assert_eq!(server.synchronous, Synchronous::Full); assert_eq!(server.synchronous, Synchronous::Full);
assert_eq!(server.max_attachment_size, 1 << 30); assert_eq!(server.max_attachment_size, 1 << 30);
assert_eq!(server.retention_interval, Duration::from_secs(60)); 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.retention.age("logs"), None);
assert_eq!(config.replication.retry_delay, Duration::from_secs(10)); assert_eq!(config.replication.retry_delay, Duration::from_secs(10));
assert_eq!(config.replication.sync_interval, Duration::from_secs(5)); assert_eq!(config.replication.sync_interval, Duration::from_secs(5));
@@ -75,6 +76,7 @@ database = "data/messages.sqlite"
synchronous = "NORMAL" synchronous = "NORMAL"
max_attachment_size = 0 max_attachment_size = 0
retention_interval = "1h30m" retention_interval = "1h30m"
idle_database_connections = 0
[replication] [replication]
push_to = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"] push_to = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"]
@@ -89,6 +91,7 @@ batch_size = 10000
assert_eq!(config.server.synchronous, Synchronous::Normal); assert_eq!(config.server.synchronous, Synchronous::Normal);
assert_eq!(config.server.max_attachment_size, 0); assert_eq!(config.server.max_attachment_size, 0);
assert_eq!(config.server.retention_interval, Duration::from_secs(5400)); 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.push_to.len(), 3);
assert_eq!(config.replication.accept_from[2], "fd00::4"); assert_eq!(config.replication.accept_from[2], "fd00::4");
assert_eq!(config.replication.retry_delay, Duration::from_secs(60)); assert_eq!(config.replication.retry_delay, Duration::from_secs(60));
@@ -122,6 +125,24 @@ logs = "30d"
assert_eq!(age("other"), days(365)); 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] #[test]
fn permissions() { fn permissions() {
let config = Config::parse(&with( let config = Config::parse(&with(
@@ -277,6 +298,14 @@ fn refusals() {
&with("retention_interval = \"0s\"\n"), &with("retention_interval = \"0s\"\n"),
"'0s' isn't a duration", "'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] // [retention]
( (
&with("[retention]\nlogs = \"30\"\n"), &with("[retention]\nlogs = \"30\"\n"),
@@ -295,6 +324,16 @@ fn refusals() {
&with("[retention]\nsensors.kitchen = \"1d\"\n"), &with("[retention]\nsensors.kitchen = \"1d\"\n"),
"quote names with dots", "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] // [replication]
( (
&with("[replication]\npush_to = [\"10.0.0.2\"]\n"), &with("[replication]\npush_to = [\"10.0.0.2\"]\n"),
+14
View File
@@ -12,6 +12,15 @@ pub const PROTOCOL_VERSION: u32 = 8;
/// checked once connected, so a mismatch is told as such. /// checked once connected, so a mismatch is told as such.
pub const ALPN: &[u8] = b"bakashrot"; 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). /// The biggest packet on the wire, in bytes (a frame's size field).
pub const MAX_PACKET_SIZE: usize = 16 * 1024 * 1024; 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. /// The most attachments a `SyncState` lists as missing at once.
pub const MAX_MISSING_ATTACHMENTS: usize = 256; 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. /// Attachments go in parts of this many bytes, the last one what's left.
pub const ATTACHMENT_PART_SIZE: u64 = 1024 * 1024; pub const ATTACHMENT_PART_SIZE: u64 = 1024 * 1024;
+7 -3
View File
@@ -33,10 +33,10 @@ pub use messages::{
PushMessage, Query, QueryResult, StoredAttachment, PushMessage, Query, QueryResult, StoredAttachment,
}; };
pub use replication::{ pub use replication::{
Head, MissingAttachment, ReplicateAttachment, ReplicateMessages, ReplicatedMessage, SyncState, Head, MissingAttachment, Pair, ReplicateAttachment, ReplicateMessages, ReplicatedMessage,
SyncStateRequest, 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::de::{self, DeserializeOwned, IgnoredAny, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::{Deserialize, Deserializer, Serialize, Serializer};
@@ -244,6 +244,10 @@ packets! {
ReplicateMessages = 17, ReplicateMessages = 17,
/// P→S: an attachment the server is missing, its parts after it (`Continue`, then `MessagePushed` / `RequestRefused`). /// P→S: an attachment the server is missing, its parts after it (`Continue`, then `MessagePushed` / `RequestRefused`).
ReplicateAttachment = 18, 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 { impl Packet {
@@ -6,19 +6,43 @@
use super::rules; use super::rules;
use super::{Attachment, Check, DecodeError}; use super::{Attachment, Check, DecodeError};
use crate::limits::{ use crate::limits::{
MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_MISSING_ATTACHMENTS, MAX_ATTACHMENT_PARTS, MAX_HEADS_PER_PACKET, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET,
MAX_NAMES_LIST_ENTRIES, MAX_MISSING_ATTACHMENTS, MAX_NAMES_LIST_ENTRIES,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// What the server takes from this peer, how far it is, and the /// 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)] #[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. /// 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 /// 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)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncState { 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 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>, pub topics: Vec<String>,
/// The nodes it takes from this peer, the same way. /// The nodes it takes from this peer, the same way.
pub nodes: Vec<String>, 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>, pub heads: Vec<Head>,
/// The attachments it lacks among those, `MAX_MISSING_ATTACHMENTS` at /// The attachments it lacks among those, `MAX_MISSING_ATTACHMENTS` at
/// most. /// most. Empty after the first page.
pub missing: Vec<MissingAttachment>, pub missing: Vec<MissingAttachment>,
} }
impl Check for SyncState { impl Check for SyncState {
fn check(&self) -> Result<(), DecodeError> { 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 [ for (list, field) in [
(&self.topics, "SyncState.topics"), (&self.topics, "SyncState.topics"),
(&self.nodes, "SyncState.nodes"), (&self.nodes, "SyncState.nodes"),
@@ -74,3 +74,21 @@ impl Check for RequestRefused {
pub struct Continue {} pub struct Continue {}
impl Check for 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. //! refuses, and that no input makes it panic.
use bakashrot_proto::limits::{ use bakashrot_proto::limits::{
ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_PARTS, MAX_ATTACHMENT_SIZE, MAX_HEADS_PER_PACKET,
MAX_TIMESTAMP, 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::packets::*;
use bakashrot_proto::{Body, DecodeError, ErrorCode, Packet, PacketType}; use bakashrot_proto::{Body, DecodeError, ErrorCode, Packet, PacketType};
@@ -35,6 +36,8 @@ fn samples() -> Vec<Packet> {
.into(), .into(),
RequestRefused::new(ErrorCode::UnknownName, "Unknown topic 'nope'").into(), RequestRefused::new(ErrorCode::UnknownName, "Unknown topic 'nope'").into(),
Continue {}.into(), Continue {}.into(),
Ping {}.into(),
Pong {}.into(),
PushMessage { PushMessage {
topic: "logs".into(), topic: "logs".into(),
data: "é€ \u{1F600} {\"a\":[1,2]}".into(), data: "é€ \u{1F600} {\"a\":[1,2]}".into(),
@@ -122,8 +125,16 @@ fn samples() -> Vec<Packet> {
json: r#"{"columns":["a"],"rows":[[1],[null]]}"#.into(), json: r#"{"columns":["a"],"rows":[[1],[null]]}"#.into(),
} }
.into(), .into(),
SyncStateRequest {}.into(), SyncStateRequest { after: None }.into(),
SyncStateRequest {
after: Some(Pair {
topic: "logs".into(),
node: "kitchen".into(),
}),
}
.into(),
SyncState { SyncState {
more: true,
topics: vec!["logs".into(), "sensors.*".into()], topics: vec!["logs".into(), "sensors.*".into()],
nodes: vec!["*".into()], nodes: vec!["*".into()],
heads: vec![ heads: vec![
@@ -245,6 +256,8 @@ fn golden_bytes() {
] ]
); );
assert_eq!(Continue {}.encode(), [0x92, 0x03, 0x90]); assert_eq!(Continue {}.encode(), [0x92, 0x03, 0x90]);
assert_eq!(Ping {}.encode(), [0x92, 0x13, 0x90]);
assert_eq!(Pong {}.encode(), [0x92, 0x14, 0x90]);
assert_eq!( assert_eq!(
MessagePushed { message_id: 300 }.encode(), MessagePushed { message_id: 300 }.encode(),
[0x92, 0x05, 0x91, 0xcd, 0x01, 0x2c] [0x92, 0x05, 0x91, 0xcd, 0x01, 0x2c]
@@ -298,6 +311,7 @@ fn shapes() {
assert!(malformed(&raw(PacketType::MessagePushed, ((),)))); assert!(malformed(&raw(PacketType::MessagePushed, ((),))));
assert!(malformed(&raw(PacketType::MessagePushed, (1u64, 2u64)))); assert!(malformed(&raw(PacketType::MessagePushed, (1u64, 2u64))));
assert!(malformed(&raw(PacketType::Continue, (1u64,)))); assert!(malformed(&raw(PacketType::Continue, (1u64,))));
assert!(malformed(&raw(PacketType::Ping, (1u64,))));
// The wrong types. // The wrong types.
assert!(malformed(&raw(PacketType::MessagePushed, ("1",)))); assert!(malformed(&raw(PacketType::MessagePushed, ("1",))));
assert!(malformed(&raw(PacketType::MessagePushed, (-1i64,)))); assert!(malformed(&raw(PacketType::MessagePushed, (-1i64,))));
@@ -479,7 +493,26 @@ fn too_many_items() {
}; };
assert!(invalid(&too_many.encode())); 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 { let missing = SyncState {
more: false,
topics: vec![], topics: vec![],
nodes: vec![], nodes: vec![],
heads: vec![], heads: vec![],
@@ -532,6 +565,7 @@ fn names_everywhere() {
let state = |topic: &str| { let state = |topic: &str| {
SyncState { SyncState {
more: false,
topics: vec![topic.into()], topics: vec![topic.into()],
nodes: vec![], nodes: vec![],
heads: vec![], heads: vec![],
@@ -543,6 +577,20 @@ fn names_everywhere() {
assert!(Packet::decode(&state("logs")).is_ok()); assert!(Packet::decode(&state("logs")).is_ok());
assert!(invalid(&state("12"))); assert!(invalid(&state("12")));
assert!(invalid(&state("a b*"))); 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 { let welcome = Welcome {
server: "s".into(), server: "s".into(),
@@ -551,6 +599,40 @@ fn names_everywhere() {
assert!(invalid(&welcome.encode())); 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. /// xorshift64*, enough to make bytes that look like anything.
struct Random(u64); 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(); let mut bytes: Vec<u8> = (0..len).map(|_| random.next() as u8).collect();
if round % 2 == 0 && bytes.len() > 2 { if round % 2 == 0 && bytes.len() > 2 {
bytes[0] = 0x92; 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); bytes[2] = 0x90 | (bytes[2] & 0x0f);
} }
let _ = Packet::decode(&bytes); let _ = Packet::decode(&bytes);
+53 -16
View File
@@ -5,9 +5,12 @@
use crate::connection::{Frames, Peer, receive_parts, refused, send}; use crate::connection::{Frames, Peer, receive_parts, refused, send};
use crate::writer::Write; use crate::writer::Write;
use crate::{Shared, now}; 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::{ 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_proto::{ErrorCode, Packet};
use bakashrot_storage::AttachmentState; 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 /// What it takes from this peer, how far it is in those, and the
/// attachments it lacks among them. /// 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) -> Packet { pub(crate) async fn sync_state(
shared: &Arc<Shared>,
peer: &mut Peer,
request: SyncStateRequest,
) -> Packet {
if let Err(refusal) = check_address(shared, peer).await { if let Err(refusal) = check_address(shared, peer).await {
return refusal; return refusal;
} }
let (topics, nodes) = peer.permissions.accepted(); let first = request.after.is_none();
let found = shared let mut after = request.after.map(|pair| (pair.topic, pair.node));
.read(|reader| { let (mut heads, mut more) = (Vec::new(), false);
Ok(( // Read in pages too, those it doesn't take from this peer skipped:
reader.heads()?, // until the page is full and one more is found, or none is left.
reader.missing_attachments(MAX_MISSING_ATTACHMENTS)?, '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; .await;
let (mut heads, mut missing) = match found { let read: Vec<Head> = match read {
Ok(found) => found, 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(), 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)); missing.retain(|missing| peer.permissions.accepts(&missing.topic, &missing.node));
}
SyncState { SyncState {
more,
topics, topics,
nodes, nodes,
heads, heads,
@@ -163,8 +200,8 @@ pub(crate) async fn replicate_messages(
let skip_before = shared let skip_before = shared
.config .config
.retention .retention
.age(&batch.topic) .cutoff(&batch.topic, now())
.map_or(0, |age| now().saturating_sub(age.as_millis() as u64)); .unwrap_or(0);
let write = Write::Replicate { let write = Write::Replicate {
topic: batch.topic, topic: batch.topic,
node: batch.node, node: batch.node,
+17 -5
View File
@@ -6,11 +6,13 @@ use crate::{Shared, accept_from, now};
use aws_lc_rs::digest; use aws_lc_rs::digest;
use bakashrot_config::Permissions; use bakashrot_config::Permissions;
use bakashrot_pki::Identity; 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::names::{name_matches, names_equal};
use bakashrot_proto::packets::{ use bakashrot_proto::packets::{
Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed, 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_proto::{ErrorCode, Packet, frame};
use bakashrot_storage::AttachmentState; use bakashrot_storage::AttachmentState;
@@ -29,8 +31,9 @@ use tracing::{debug, info};
/// How long TLS and the versions may take. /// How long TLS and the versions may take.
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10); const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
/// How long a connection may stay silent between requests. /// How long a connection may stay silent between requests (a `Ping`
const IDLE_TIMEOUT: Duration = Duration::from_secs(300); /// counts).
const IDLE_TIMEOUT: Duration = Duration::from_secs(IDLE_TIMEOUT_SECS);
/// How long an attachment's next part may take to come. /// How long an attachment's next part may take to come.
const PART_TIMEOUT: Duration = Duration::from_secs(30); 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::GetMessages(get) => get_messages(shared, &peer, get).await,
Packet::ListNames(list) => list_names(shared, &peer, list).await, Packet::ListNames(list) => list_names(shared, &peer, list).await,
Packet::Query(query) => self::query(shared, &peer, query).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) => { Packet::ReplicateMessages(batch) => {
accept_from::replicate_messages(shared, &mut peer, batch).await accept_from::replicate_messages(shared, &mut peer, batch).await
} }
@@ -158,6 +164,12 @@ async fn open(
return Err(format!("TLS: {error}")); 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 stream
.write_all(&frame::version_bytes()) .write_all(&frame::version_bytes())
+116 -17
View File
@@ -31,8 +31,8 @@ use bakashrot_storage::{Database, QueryRunner, Reader};
use std::collections::HashSet; use std::collections::HashSet;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::Path; use std::path::Path;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, SystemTime, UNIX_EPOCH}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::net::TcpListener; use tokio::net::TcpListener;
use tokio_rustls::{TlsAcceptor, TlsConnector}; use tokio_rustls::{TlsAcceptor, TlsConnector};
use tracing::{info, warn}; use tracing::{info, warn};
@@ -44,6 +44,12 @@ const CRL_POLL: Duration = Duration::from_secs(5);
/// How often the WAL is checkpointed. /// How often the WAL is checkpointed.
const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(1); 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. /// A server, ready to take connections.
#[derive(Clone)] #[derive(Clone)]
pub struct Server { pub struct Server {
@@ -64,9 +70,9 @@ struct Shared {
database: Database, database: Database,
pushes: Pushes, pushes: Pushes,
/// Read connections not in use. /// Read connections not in use.
readers: Mutex<Vec<Reader>>, readers: Pool<Reader>,
/// Query connections not in use. /// Query connections not in use.
queries: Mutex<Vec<QueryRunner>>, queries: Pool<QueryRunner>,
/// The replicated attachments being received (topic, node, message /// The replicated attachments being received (topic, node, message
/// id): one peer at a time each (`accept_from.rs`). /// id): one peer at a time each (`accept_from.rs`).
receiving: Mutex<HashSet<(String, String, u64)>>, receiving: Mutex<HashSet<(String, String, u64)>>,
@@ -101,8 +107,7 @@ impl Server {
let pushes = Pushes::start(database.writer().map_err(|error| error.to_string())?) let pushes = Pushes::start(database.writer().map_err(|error| error.to_string())?)
.map_err(|error| format!("the writer's thread: {error}"))?; .map_err(|error| format!("the writer's thread: {error}"))?;
start_checkpoints(&database)?; start_checkpoints(&database)?;
Ok(Server { let shared = Arc::new(Shared {
shared: Arc::new(Shared {
name, name,
acceptor: TlsAcceptor::from(tls), acceptor: TlsAcceptor::from(tls),
connector: TlsConnector::from(dialing), connector: TlsConnector::from(dialing),
@@ -110,12 +115,13 @@ impl Server {
ca, ca,
database, database,
pushes, pushes,
readers: Mutex::new(Vec::new()), readers: Pool::new(),
queries: Mutex::new(Vec::new()), queries: Pool::new(),
receiving: Mutex::new(HashSet::new()), receiving: Mutex::new(HashSet::new()),
config, config,
}), });
}) start_pool_sweeps(&shared)?;
Ok(Server { shared })
} }
/// The server's name: its certificate's. /// 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 /// 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>( async fn pooled<C: Send + 'static, T: Send + 'static>(
self: &Arc<Self>, self: &Arc<Self>,
pool: fn(&Shared) -> &Mutex<Vec<C>>, pool: fn(&Shared) -> &Pool<C>,
open: fn(&Database) -> bakashrot_storage::Result<C>, open: fn(&Database) -> bakashrot_storage::Result<C>,
work: impl FnOnce(&C) -> bakashrot_storage::Result<T> + Send + 'static, work: impl FnOnce(&C) -> bakashrot_storage::Result<T> + Send + 'static,
) -> Result<T, RequestRefused> { ) -> Result<T, RequestRefused> {
let shared = self.clone(); let shared = self.clone();
tokio::task::spawn_blocking(move || { tokio::task::spawn_blocking(move || {
let idle = pool(&shared).lock().ok().and_then(|mut idle| idle.pop()); let connection = match pool(&shared).take() {
let connection = match idle {
Some(connection) => connection, Some(connection) => connection,
None => open(&shared.database).map_err(refusal)?, None => open(&shared.database).map_err(refusal)?,
}; };
let value = work(&connection).map_err(refusal); let value = work(&connection).map_err(refusal);
if let Ok(mut idle) = pool(&shared).lock() { let max = shared.config.server.idle_database_connections;
idle.push(connection); pool(&shared).put_back(connection, max, Instant::now());
}
value value
}) })
.await .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 /// 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 /// own, so the writer doesn't do it in the middle of a commit (2.5 times
/// the pushes: `docs/storage.md`, "The benchmark"). /// the pushes: `docs/storage.md`, "The benchmark").
@@ -339,6 +417,27 @@ fn stamp(path: &Path) -> Option<(SystemTime, u64)> {
mod tests { mod tests {
use super::*; 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] #[test]
fn a_clock_before_1970_is_refused() { fn a_clock_before_1970_is_refused() {
assert!(check_clock(UNIX_EPOCH).is_ok()); assert!(check_clock(UNIX_EPOCH).is_ok());
+67 -22
View File
@@ -11,11 +11,11 @@ use crate::connection::SEND_TIMEOUT;
use crate::writer::Write; use crate::writer::Write;
use bakashrot_config::Permissions; use bakashrot_config::Permissions;
use bakashrot_pki::tls; use bakashrot_pki::tls;
use bakashrot_proto::limits::{ALPN, MAX_PACKET_SIZE}; use bakashrot_proto::limits::{ALPN, KEEPALIVE_SECS, MAX_PACKET_SIZE};
use bakashrot_proto::names::{names_equal, pattern_matches}; use bakashrot_proto::names::name_matches;
use bakashrot_proto::packets::{ use bakashrot_proto::packets::{
Attachment, AttachmentPart, MissingAttachment, ReplicateAttachment, ReplicateMessages, Attachment, AttachmentPart, MissingAttachment, Pair, Ping, ReplicateAttachment,
SyncState, SyncStateRequest, ReplicateMessages, SyncState, SyncStateRequest,
}; };
use bakashrot_proto::{ErrorCode, Packet, frame}; use bakashrot_proto::{ErrorCode, Packet, frame};
use bakashrot_storage::AttachmentState; use bakashrot_storage::AttachmentState;
@@ -58,10 +58,13 @@ async fn keep_linked(shared: Arc<Shared>, address: String) {
info!("{address}: linked to {}", link.name); info!("{address}: linked to {}", link.name);
last_failure.clear(); last_failure.clear();
loop { loop {
match link.check_in(&shared).await { let checked = match link.check_in(&shared).await {
Ok(true) => {} Ok(true) => Ok(()),
Ok(false) => sleep(replication.sync_interval).await, Ok(false) => link.wait(replication.sync_interval).await,
Err(why) => break format!("{} ({address}): {why}", link.name), 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. /// Whether it sent something it took.
async fn check_in(&mut self, shared: &Arc<Shared>) -> Result<bool, String> { async fn check_in(&mut self, shared: &Arc<Shared>) -> Result<bool, String> {
self.sent = false; self.sent = false;
let state = match self.ask(SyncStateRequest {}.into()).await? { let (state, theirs) = self.sync_state().await?;
Packet::SyncState(state) => state,
Packet::RequestRefused(refused) => return Err(format!("refused: {}", refused.reason)),
other => return Err(unexpected(&other)),
};
let heads = shared let heads = shared
.read(|reader| reader.heads()) .read(|reader| reader.heads())
.await .await
.map_err(|refused| refused.reason)?; .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 { for head in heads {
let (topic, node) = (head.topic, head.node); let (topic, node) = (head.topic, head.node);
if !self.sends(&state, &topic, &node) { if !self.sends(&state, &topic, &node) {
@@ -171,13 +165,44 @@ impl Link {
Ok(self.sent) 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 /// Whether it takes `node`'s messages in `topic` (its `SyncState`) and
/// may be sent them (its roles here). /// may be sent them (its roles here).
fn sends(&self, state: &SyncState, topic: &str, node: &str) -> bool { fn sends(&self, state: &SyncState, topic: &str, node: &str) -> bool {
let listed = |list: &[String], name: &str| { let listed =
list.iter() |list: &[String], name: &str| list.iter().any(|entry| name_matches(entry, name));
.any(|entry| names_equal(entry, name) || pattern_matches(entry, name))
};
listed(&state.topics, topic) listed(&state.topics, topic)
&& listed(&state.nodes, node) && listed(&state.nodes, node)
&& self.permissions.sends(topic, node) && self.permissions.sends(topic, node)
@@ -292,6 +317,26 @@ impl Link {
Ok(()) 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> { async fn ask(&mut self, packet: Packet) -> Result<Packet, String> {
self.send(packet).await?; self.send(packet).await?;
self.receive().await self.receive().await
+1 -2
View File
@@ -31,10 +31,9 @@ pub(crate) async fn run(shared: &Arc<Shared>) {
async fn once(shared: &Arc<Shared>) -> Result<(), RequestRefused> { async fn once(shared: &Arc<Shared>) -> Result<(), RequestRefused> {
let now = crate::now(); let now = crate::now();
for topic in shared.read(|reader| reader.topics()).await? { 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; continue;
}; };
let cutoff = now.saturating_sub(age.as_millis() as u64);
let deleted = repeat(shared, MESSAGES_PER_WRITE, |limit| Write::DeleteBefore { let deleted = repeat(shared, MESSAGES_PER_WRITE, |limit| Write::DeleteBefore {
topic: topic.clone(), topic: topic.clone(),
cutoff, cutoff,
+257 -18
View File
@@ -6,20 +6,23 @@
use bakashrot_client::{Client, Settings}; use bakashrot_client::{Client, Settings};
use bakashrot_config::Config; use bakashrot_config::Config;
use bakashrot_pki::{Ca, Identity, Issued, Revocations, Usage, summarize, tls}; 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::{ use bakashrot_proto::packets::{
Attachment, AttachmentPart, GetAttachment, MessagePushed, Messages, NameKind, PushMessage, Attachment, AttachmentPart, GetAttachment, Head, MessagePushed, Messages, NameKind, Pair, Ping,
ReplicateAttachment, ReplicateMessages, ReplicatedMessage, StoredAttachment, SyncState, Pong, PushMessage, ReplicateAttachment, ReplicateMessages, ReplicatedMessage, StoredAttachment,
SyncStateRequest, SyncState, SyncStateRequest,
}; };
use bakashrot_proto::{ErrorCode, Packet, frame}; use bakashrot_proto::{ErrorCode, Packet, frame};
use bakashrot_server::Server; use bakashrot_server::Server;
use std::io::{Cursor, Read, Seek, SeekFrom, Write}; use std::io::{Cursor, Read, Seek, SeekFrom, Write};
use std::net::TcpStream; use std::net::TcpStream;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use tokio_rustls::rustls::{ClientConnection, StreamOwned}; use tokio_rustls::rustls::{ClientConfig, ClientConnection, StreamOwned};
const CONFIG: &str = r#" const CONFIG: &str = r#"
[server] [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] #[test]
fn refusals_keep_the_connection() { fn refusals_keep_the_connection() {
let running = Running::start("refusals"); let running = Running::start("refusals");
@@ -298,6 +344,20 @@ fn certificates_refused() {
.unwrap_err(); .unwrap_err();
assert_eq!(error.code(), ErrorCode::ServerNotVerified.code(), "{error}"); 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. // Nothing listening.
let error = Client::connect( let error = Client::connect(
"127.0.0.1:1", "127.0.0.1:1",
@@ -922,17 +982,7 @@ struct Raw(StreamOwned<ClientConnection, TcpStream>);
impl Raw { impl Raw {
fn connect(running: &Running, issued: &Issued) -> Raw { fn connect(running: &Running, issued: &Issued) -> Raw {
let config = tls::client_config( let mut raw = Raw::open(running, issued, |_| {});
&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));
frame::write_version(&mut raw.0).unwrap(); frame::write_version(&mut raw.0).unwrap();
raw.0.flush().unwrap(); raw.0.flush().unwrap();
frame::read_version(&mut raw.0).unwrap(); frame::read_version(&mut raw.0).unwrap();
@@ -940,6 +990,24 @@ impl Raw {
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>) { fn send(&mut self, packet: impl Into<Packet>) {
frame::write(&mut self.0, &packet.into().encode()).unwrap(); frame::write(&mut self.0, &packet.into().encode()).unwrap();
self.0.flush().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 { 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() { match raw.receive() {
Some(Packet::SyncState(state)) => state, Some(Packet::SyncState(state)) => state,
other => panic!("expected a SyncState, got {other:?}"), 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] #[test]
fn replication_edges() { fn replication_edges() {
// The test plays the peer, over a raw connection. // The test plays the peer, over a raw connection.
+18 -4
View File
@@ -9,7 +9,7 @@ use bakashrot_proto::packets::{
Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, ReplicatedMessage, Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, ReplicatedMessage,
StoredAttachment, 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 /// 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. /// is left for the next request (`more`). A bigger message goes alone.
@@ -160,11 +160,25 @@ impl Reader {
.map_err(Error::from) .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>> { 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 self.connection
.prepare_cached("SELECT topic, node, last_id FROM streams ORDER BY topic, node")? .prepare_cached(
.query_map([], |row| { "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 { Ok(Head {
topic: row.get(0)?, topic: row.get(0)?,
node: row.get(1)?, node: row.get(1)?,
+25
View File
@@ -173,6 +173,31 @@ fn pushing_and_reading() {
("sensors".into(), "kitchen".into(), 1) ("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("logs", "kitchen").unwrap(), 3);
assert_eq!(reader.last_id("nope", "kitchen").unwrap(), 0); assert_eq!(reader.last_id("nope", "kitchen").unwrap(), 0);
} }
+18 -2
View File
@@ -7,7 +7,7 @@ mod cert;
use bakashrot_client::{Client, Error, Settings}; use bakashrot_client::{Client, Error, Settings};
use bakashrot_proto::error::{code_name, is_refusal_code}; 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 bakashrot_proto::packets::{MessageEntry, NameKind};
use clap::{Parser, Subcommand, ValueEnum}; use clap::{Parser, Subcommand, ValueEnum};
use serde::Deserialize; use serde::Deserialize;
@@ -266,7 +266,7 @@ fn run(config: &Path, command: Command) -> Result<(), String> {
break; break;
} }
if !batch.more { 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(()) 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. /// A topic and node's latest message, if any.
fn latest(client: &mut Client, topic: &str, node: &str) -> Result<Option<MessageEntry>, String> { 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)?; let latest = client.get_messages(topic, node, None, 1).map_err(failed)?;
+7 -4
View File
@@ -76,6 +76,7 @@ a client's, or an enumeration's for the enumeration getters.
| `SetCaCertificate`, `SetCertificate`, `SetPrivateKey`, `SetCrl` (`A`/`W`) | PEM text (starting with `-----BEGIN`), or the path of a file holding it; `SetCrl` null or empty for none. Before connecting (`AlreadyConnected`); a file that can't be read is `FileError` | | `SetCaCertificate`, `SetCertificate`, `SetPrivateKey`, `SetCrl` (`A`/`W`) | PEM text (starting with `-----BEGIN`), or the path of a file holding it; `SetCrl` null or empty for none. Before connecting (`AlreadyConnected`); a file that can't be read is `FileError` |
| `Connect(Host, Port)` (`A`/`W`) | TLS with those; refused: `AuthRejected` (the server refused the certificate), `ServerNotVerified` (this client refused the server's), `NotAllowed` (none of its roles is the server's), `VersionMismatch` | | `Connect(Host, Port)` (`A`/`W`) | TLS with those; refused: `AuthRejected` (the server refused the certificate), `ServerNotVerified` (this client refused the server's), `NotAllowed` (none of its roles is the server's), `VersionMismatch` |
| `IsConnected`, `Disconnect` | `IsConnected` notices a connection the server closed | | `IsConnected`, `Disconnect` | `IsConnected` notices a connection the server closed |
| `Ping` | 1, or 0 if the connection is gone: keeps it open. The server closes one silent for 5 min; the DLL has no thread of its own, so an app idle longer calls it every minute or so |
| `GetNode` (`A`/`W`) | the node the server says this client is | | `GetNode` (`A`/`W`) | the node the server says this client is |
| `PushMessageTo(Topic, Data)` (`A`/`W`) | the id, -1 on failure | | `PushMessageTo(Topic, Data)` (`A`/`W`) | the id, -1 on failure |
| `GetLatestMessageOf(Topic, Node)` (`A`/`W`) | 1, or 0 with `NotFound` when there's none yet | | `GetLatestMessageOf(Topic, Node)` (`A`/`W`) | 1, or 0 with `NotFound` when there's none yet |
@@ -121,7 +122,8 @@ certificate, key, crl=None)` (PEM text or paths) or
`Client.from_file("client.toml")` (Python 3.11+, `tomllib`; the rest runs `Client.from_file("client.toml")` (Python 3.11+, `tomllib`; the rest runs
on 3.8), `client.node` once connected, `push(data, topic, on 3.8), `client.node` once connected, `push(data, topic,
attachment=None)` (the topic required; the attachment bytes or a path), attachment=None)` (the topic required; the attachment bytes or a path),
`latest()`, `get_messages()`, `iter_messages()`, `follow()`, `latest()`, `get_messages()`, `iter_messages()`, `follow()` (pinging
every minute while it waits longer), `ping()` (`KEEPALIVE_SECONDS`),
`get_attachment()` (bytes), `save_attachment()` (a file), `get_attachment()` (bytes), `save_attachment()` (a file),
`list_topics()` / `list_nodes()` (names; `topic=` and `node=`, a name or `list_topics()` / `list_nodes()` (names; `topic=` and `node=`, a name or
a pattern each, filter them: `list_topics(node="kitchen")` the topics a pattern each, filter them: `list_topics(node="kitchen")` the topics
@@ -165,7 +167,8 @@ using (Client client = new Client("10.0.0.2", 7000, "ca.crt", "kitchen.crt", "ki
`new Client(host, port, ca, certificate, key, crl)` (PEM text or paths, `new Client(host, port, ca, certificate, key, crl)` (PEM text or paths,
`crl` null for none), `Connect()`, `Node`, `Connected`, `Push(topic, `crl` null for none), `Connect()`, `Node`, `Connected`, `Push(topic,
data[, byte[]])`, `PushFile(topic, data, path)`, `Latest()` (null if data[, byte[]])`, `PushFile(topic, data, path)`, `Latest()` (null if
none), `GetMessages()` (a `MessagesPage`), `IterMessages()`, `Follow()`, none), `GetMessages()` (a `MessagesPage`), `IterMessages()`, `Follow()`
(pinging every minute while it waits longer), `Ping()` (`KeepAliveMs`),
`GetAttachment()` (bytes), `SaveAttachment()` (a file), `ListTopics()` / `GetAttachment()` (bytes), `SaveAttachment()` (a file), `ListTopics()` /
`ListNodes()` / `Query()` (the library's JSON, as a string: parsing it `ListNodes()` / `Query()` (the library's JSON, as a string: parsing it
is the app's; `ListTopics(topic, node)` / `ListNodes(topic, node)` is the app's; `ListTopics(topic, node)` / `ListNodes(topic, node)`
@@ -224,8 +227,8 @@ bakashrot list nodes --topics 'sensors.*' Nodes (2): those that pushed to s
- **`messages`:** the first 100 by default (`--limit 0` for all), `--after - **`messages`:** the first 100 by default (`--limit 0` for all), `--after
<id>` or `latest`; data as stored, a line break in it spanning lines; <id>` or `latest`; data as stored, a line break in it spanning lines;
`--follow` checks every `--interval` ms (500) until stopped or the `--follow` checks every `--interval` ms (500, up to an hour, pinging
connection fails (exit 1); `--time` adds the push time between the id and every minute meanwhile) until stopped or the connection fails (exit 1); `--time` adds the push time between the id and
the data. the data.
- **Attachments:** `push -a <file>`; `attachment` replaces the file, - **Attachments:** `push -a <file>`; `attachment` replaces the file,
leaves none if it fails; `latest` says a message's (", not on this leaves none if it fails; `latest` says a message's (", not on this
+13 -1
View File
@@ -89,10 +89,22 @@ peers' `send_topics`.
`[roles."site.reader"]`. Unquoted, TOML reads dots as tables: refused, `[roles."site.reader"]`. Unquoted, TOML reads dots as tables: refused,
`[retention]` says to quote. `[retention]` says to quote.
- **Durations:** numbers with a unit (`s m h d w`), added up: `"30s"`, - **Durations:** numbers with a unit (`s m h d w`), added up: `"30s"`,
`"1d12h"`. Ages in `[retention]` can also be `"forever"`. `"1d12h"`. Ages in `[retention]` can also be `"forever"`, and are 100
years (`"36500d"`) at most (2026-11-19): longer ones once overflowed
when turned into milliseconds, a huge age wrapping around to almost
nothing.
- **Sizes:** bytes, or `"500M"` with `K M G T` (1024-based), up to 1T. - **Sizes:** bytes, or `"500M"` with `K M G T` (1024-based), up to 1T.
- **Paths:** relative ones are from the config file's folder. - **Paths:** relative ones are from the config file's folder.
## Database connections
Reads and queries each have a pool of SQLite connections: one is opened
when none is idle, then kept for the next request.
`[server] idle_database_connections` (8 by default, 0 to 512) is how many
idle ones each pool keeps; more are closed as they're put back, and an
idle one is closed after a minute unused (looked at every 10 s). 0 opens
one per request.
## Retention ## Retention
A topic takes its name's line, else the first pattern matching it in the A topic takes its name's line, else the first pattern matching it in the
-12
View File
@@ -61,13 +61,6 @@ network**, not exposed to the internet. So:
From a read of the source on 2026-11-15: no test shows any of these yet. From a read of the source on 2026-11-15: no test shows any of these yet.
Reproduce one before fixing it, and move it up (or drop it) once known. Reproduce one before fixing it, and move it up (or drop it) once known.
- **`sync_interval` over 5 min.** The server dialed closes the idle link
(`IDLE_TIMEOUT`), so every check-in fails once ("closed the link",
warned), then the link is dialed again after `retry_delay`. Nothing
in the config caps `sync_interval`. Left as it is (the owner,
2026-11-16): replicating every 5 min or more isn't a real use, the
example config says to keep it under. Fix if needed: cap it under the
idle timeout, or have an idle link ask its `SyncState` more often.
- **Resuming a big replicated attachment.** Before answering `Continue`, - **Resuming a big replicated attachment.** Before answering `Continue`,
the receiver reads back and hashes every part it already has the receiver reads back and hashes every part it already has
(`accept_from.rs`, `replicate_attachment`, `hash_parts`), while the (`accept_from.rs`, `replicate_attachment`, `hash_parts`), while the
@@ -79,11 +72,6 @@ Reproduce one before fixing it, and move it up (or drop it) once known.
the example config says so by `max_attachment_size` (1 GiB by the example config says so by `max_attachment_size` (1 GiB by
default). Fix if needed: a wait scaled to the parts already received, default). Fix if needed: a wait scaled to the parts already received,
or the hash's state kept with the attachment. or the hash's state kept with the attachment.
- **`SyncState` in one packet.** Every head the peer may
send goes in one frame of 16 MiB at most: with very many topic and
node pairs (hundreds of thousands) it doesn't fit, the packet can't
be sent and replication stops. Fix: heads in several packets, or only
those that changed.
- **Peers with several roles.** `SyncState` lists the union of its - **Peers with several roles.** `SyncState` lists the union of its
roles' `accept_topics` and the union of their `accept_nodes` roles' `accept_topics` and the union of their `accept_nodes`
(`Permissions::accepted`), while what's taken is each role on its (`Permissions::accepted`), while what's taken is each role on its
+33 -9
View File
@@ -20,8 +20,11 @@ connecting, pushes and messages (`server.md`).
expected), no host names or IPs. Revoked certificates are in the CA's expected), no host names or IPs. Revoked certificates are in the CA's
CRL: servers check it, and so do clients given it (servers dialing their CRL: servers check it, and so do clients given it (servers dialing their
peers too). peers too).
- **ALPN `bakashrot`** (`limits::ALPN`): both ends offer it, what isn't - **ALPN `bakashrot`** (`limits::ALPN`): both ends offer it and check it
BakaShrot doesn't get past the TLS handshake. It isn't versioned. was agreed on, what isn't BakaShrot doesn't get past TLS. rustls only
refuses a client offering other protocols, so the server closes one
offering none right after the handshake, before the versions
(2026-11-19). It isn't versioned.
- **The versions, first:** right after TLS, each end sends its protocol - **The versions, first:** right after TLS, each end sends its protocol
version, 4 bytes little-endian (`frame::write_version()`), and reads the version, 4 bytes little-endian (`frame::write_version()`), and reads the
other's (`frame::check_version()`). Different versions: both ends other's (`frame::check_version()`). Different versions: both ends
@@ -36,6 +39,11 @@ connecting, pushes and messages (`server.md`).
or over `MAX_PACKET_SIZE` (16 MiB), aborts the connection as soon as it or over `MAX_PACKET_SIZE` (16 MiB), aborts the connection as soon as it
arrived. The blocking client reads and writes them with `frame::read()` arrived. The blocking client reads and writes them with `frame::read()`
/ `write()`, the async server with `frame::codec()` (`tokio-util`). / `write()`, the async server with `frame::codec()` (`tokio-util`).
The limit applies to authenticated links only, as the owner asked
(2026-11-08, then 4 KB before authenticating): TLS authenticates both
ends before any frame, so nothing unauthenticated reaches one (rustls
bounds the handshake itself). Kept rather than lifted (2026-11-19): a
buggy peer announcing gigabytes would make the other end hold them.
## Packets ## Packets
@@ -84,8 +92,8 @@ format, its values are checked all the same.)
Direction: **C** client, **S** server, **P** peer (a server linked to Direction: **C** client, **S** server, **P** peer (a server linked to
another, as its client). Ids are protocol 7's own (6 can't connect; 8 another, as its client). Ids are protocol 7's own (6 can't connect; 8
added `ListNames`' filters); a new packet takes the next one, none is added `ListNames`' filters and `SyncState`'s pages); a new packet takes
ever reused. the next one, none is ever reused.
| Id | Packet | Dir | Fields | Answered by | | Id | Packet | Dir | Fields | Answered by |
|---|---|---|---|---| |---|---|---|---|---|
@@ -103,10 +111,12 @@ ever reused.
| 12 | NamesList | S→C | `kind`, `truncated` bool, `[name...]` (65536 at most) | | | 12 | NamesList | S→C | `kind`, `truncated` bool, `[name...]` (65536 at most) | |
| 13 | Query | C→S | `sql` str | QueryResult / RequestRefused | | 13 | Query | C→S | `sql` str | QueryResult / RequestRefused |
| 14 | QueryResult | S→C | `json` str: `{"columns":[...],"rows":[[...],...]}` | | | 14 | QueryResult | S→C | `json` str: `{"columns":[...],"rows":[[...],...]}` | |
| 15 | SyncStateRequest | P→S | none | SyncState / RequestRefused | | 15 | SyncStateRequest | P→S | `after`: `[topic, node]`, the last head of the previous page, or nil for the first | SyncState / RequestRefused |
| 16 | SyncState | S→P | `[topic...]`, `[node...]` (names and patterns it takes from P), `[[topic, node, last_id]...]`, `[[topic, node, message_id, next_part]...]` (attachments it lacks, 256 at most) | | | 16 | SyncState | S→P | `more` bool, `[topic...]`, `[node...]` (names and patterns it takes from P), `[[topic, node, last_id]...]` (in the order of their names, 32768 at most), `[[topic, node, message_id, next_part]...]` (attachments it lacks, 256 at most); the lists and attachments in the first page only | |
| 17 | ReplicateMessages | P→S | `topic`, `node`, `[[id, pushed_at, data, [size, sha256] or nil]...]` (1-10000, ids strictly increasing) | MessagePushed (the last id) / RequestRefused | | 17 | ReplicateMessages | P→S | `topic`, `node`, `[[id, pushed_at, data, [size, sha256] or nil]...]` (1-10000, ids strictly increasing) | MessagePushed (the last id) / RequestRefused |
| 18 | ReplicateAttachment | P→S | `topic`, `node`, `message_id`, `from_part` | Continue, then its parts, then MessagePushed / RequestRefused | | 18 | ReplicateAttachment | P→S | `topic`, `node`, `message_id`, `from_part` | Continue, then its parts, then MessagePushed / RequestRefused |
| 19 | Ping | C→S, P→S | none: keeps an idle connection open | Pong |
| 20 | Pong | S→C, S→P | none | |
## Flows ## Flows
@@ -118,11 +128,13 @@ Reading C: GetMessages(after: id) S: Messages, `more` if other
the latest C: GetMessages(after: nil, 1) S: Messages (empty if none) the latest C: GetMessages(after: nil, 1) S: Messages (empty if none)
An attachment C: GetAttachment(from_part) S: Attachment, then AttachmentPart x the rest An attachment C: GetAttachment(from_part) S: Attachment, then AttachmentPart x the rest
/ RequestRefused (NotFound, NotReady) / RequestRefused (NotFound, NotReady)
Replicating P: SyncStateRequest S: SyncState Replicating P: SyncStateRequest S: SyncState, `more` if others follow
P: SyncStateRequest(after) x pages S: SyncState
P: ReplicateMessages x the batches S: MessagePushed each / RequestRefused P: ReplicateMessages x the batches S: MessagePushed each / RequestRefused
P: ReplicateAttachment x missing S: Continue / RequestRefused P: ReplicateAttachment x missing S: Continue / RequestRefused
(NotReady: another peer sending it) (NotReady: another peer sending it)
P: AttachmentPart x from next_part S: MessagePushed / RequestRefused P: AttachmentPart x from next_part S: MessagePushed / RequestRefused
Keeping alive C: Ping (every minute while idle) S: Pong
``` ```
- **Parts are streamed:** no request or answer per part, TCP paces them. - **Parts are streamed:** no request or answer per part, TCP paces them.
@@ -133,8 +145,12 @@ Replicating P: SyncStateRequest S: SyncState
them failed, then refuses: the client never has to read while sending. them failed, then refuses: the client never has to read while sending.
- **A server failing while it sends parts** closes the connection; the - **A server failing while it sends parts** closes the connection; the
client asks again `from_part` the next one it needs. client asks again `from_part` the next one it needs.
- **Replication:** `SyncState` is all a check-in needs. The peer compares - **Replication:** `SyncState` is all a check-in needs. Its heads come
it with what it has, by name, sends the messages the server lacks in in pages of `MAX_HEADS_PER_PACKET` (32768): the biggest first page,
every list full and every name 64 characters, is about 13.3 MB, in a
16 MiB frame (`the_biggest_sync_state_fits`). The peer asks for the
next `after` the last head while `more`, then compares them all with
what it has, by name, sends the messages the server lacks in
batches of up to `batch_size` messages and about 1 MiB (a bigger batches of up to `batch_size` messages and about 1 MiB (a bigger
message alone), then the attachments it listed. message alone), then the attachments it listed.
@@ -142,6 +158,14 @@ Replicating P: SyncStateRequest S: SyncState
- **One request at a time:** a client sends one, waits for its answer (the - **One request at a time:** a client sends one, waits for its answer (the
parts of an attachment being part of its request or answer). parts of an attachment being part of its request or answer).
- **Silence:** the server closes a connection with no request for
`IDLE_TIMEOUT_SECS` (5 min). An end waiting longer between requests
sends a `Ping` every `KEEPALIVE_SECS` (1 min) meanwhile (added
2026-11-19, protocol 8 not released yet): the tool's and the bindings'
follows and the replication links do it themselves; the DLL has no
thread of its own, so an app idle that long calls `BakaShrot_Ping()`.
A `Ping` needs no permission; a revoked certificate's is dropped like
any request.
- **Refuse or abort:** valid but not allowed or not found (permissions, - **Refuse or abort:** valid but not allowed or not found (permissions,
unknown names, over a limit, a failed query) is a `RequestRefused` with a unknown names, over a limit, a failed query) is a `RequestRefused` with a
code, the connection stays. Malformed or out of order (a bad frame, a code, the connection stays. Malformed or out of order (a bad frame, a
+11 -4
View File
@@ -118,7 +118,9 @@ otherwise:
1. `SyncStateRequest`: the other server answers what it takes from this 1. `SyncStateRequest`: the other server answers what it takes from this
one (topics and nodes, patterns included), its last id in each topic one (topics and nodes, patterns included), its last id in each topic
and node, and the attachments it lacks (256 at most). and node, and the attachments it lacks (256 at most). The last ids
come in pages of 32768, each asked after the last of the previous
one, until none follow.
2. **The messages:** for each topic and node here that it takes and that 2. **The messages:** for each topic and node here that it takes and that
its roles here may be sent (`send_topics`, `send_nodes`), and where its roles here may be sent (`send_topics`, `send_nodes`), and where
it's behind, the messages after its it's behind, the messages after its
@@ -157,7 +159,8 @@ the same ids with different messages, undetected.
## A connection ## A connection
1. **TLS:** the client's certificate must be the CA's, valid, not revoked, 1. **TLS:** the client's certificate must be the CA's, valid, not revoked,
with an identity (`certificates.md`). A refused one gets TLS's alert, with an identity (`certificates.md`), and ALPN `bakashrot` agreed on
(a client offering none is closed at once). A refused one gets TLS's alert,
then a gentle close: the server shuts down and reads until the client then a gentle close: the server shuts down and reads until the client
closes (1 s at most). Closing at once reset the connection (the closes (1 s at most). Closing at once reset the connection (the
client's version bytes unread), which could beat the alert to the client's version bytes unread), which could beat the alert to the
@@ -176,7 +179,7 @@ the same ids with different messages, undetected.
| Timeout | | | Timeout | |
|---|---| |---|---|
| TLS, versions, welcome | 10 s (the server); the client's connect too | | TLS, versions, welcome | 10 s (the server); the client's connect too |
| Silence between requests | 5 min, then the server closes | | Silence between requests | 5 min, then the server closes (a `Ping` is a request: links and follows send one every minute while they wait) |
| A packet sent (an answer, an attachment's part, to a peer too) | 30 s (the server), then it closes: a client that stopped reading doesn't hold a connection | | A packet sent (an answer, an attachment's part, to a peer too) | 30 s (the server), then it closes: a client that stopped reading doesn't hold a connection |
| An answer | 30 s (the client) | | An answer | 30 s (the client) |
| An attachment's next part | 30 s (the server), then it closes | | An attachment's next part | 30 s (the server), then it closes |
@@ -355,7 +358,11 @@ each:
- refusals keeping the connection (not allowed, unknown topic, a bad name - refusals keeping the connection (not allowed, unknown topic, a bad name
the client catches); the client catches);
- certificates refused (no known role, with why; another CA's client; a - certificates refused (no known role, with why; another CA's client; a
client trusting another CA; nothing listening); client trusting another CA; a client offering no ALPN; nothing
listening);
- pings (answered with no permission needed, a `Pong` sent to the server
closing it, a revoked certificate's ping dropped); a server keeping no
idle database connection still serving reads and queries;
- revoked certificates (an open connection dropped at its next request, a - revoked certificates (an open connection dropped at its next request, a
new one refused, others going on, a bad CRL refused); new one refused, others going on, a bad CRL refused);
- six connections pushing at once (one id stream per node, none lost or - six connections pushing at once (one id stream per node, none lost or
+2 -2
View File
@@ -97,8 +97,8 @@ read while the writer writes. Answers are the protocol's own types:
| Reader | Gives | How | | Reader | Gives | How |
|---|---|---| |---|---|---|
| `messages(topic, node, after, limit)` | `Messages`: after an id in order, or the last ones; about 1 MiB at most (a bigger message alone), `more` if others follow | a range of keys | | `messages(topic, node, after, limit)` | `Messages`: after an id in order, or the last ones; about 1 MiB at most (a bigger message alone), `more` if others follow | a range of keys |
| `topics()`, `nodes()` | the names with messages | `streams` | | `topics()` | the topics with messages | `streams` |
| `heads()`, `last_id(topic, node)` | each stream's last id: `SyncState` | `streams` | | `heads()`, `heads_after(after, limit)`, `last_id(topic, node)` | each stream's last id, all or a page after a pair (names without case): `SyncState` | `streams` (its `(topic, node)` index) |
| `to_replicate(topic, node, after, limit)` | messages after an id as replication sends them (attachments' SHA-256s), about 1 MiB at most | a range of keys | | `to_replicate(topic, node, after, limit)` | messages after an id as replication sends them (attachments' SHA-256s), about 1 MiB at most | a range of keys |
| `missing_attachments(limit)` | replicated attachments not all here, from which part | `attachments` (index on states) | | `missing_attachments(limit)` | replicated attachments not all here, from which part | `attachments` (index on states) |
| `attachment(topic, node, id)`, `read_part(id, part)` | an attachment, its parts | the message's key; a part's key | | `attachment(topic, node, id)`, `read_part(id, part)` | an attachment, its parts | the message's key; a part's key |
+43 -3
View File
@@ -188,6 +188,42 @@ Also decided (2026-11-13):
writes, asked by the owner: the query connection opens the file writes, asked by the owner: the query connection opens the file
read-only (`SQLITE_OPEN_READONLY`), beside `query_only`, the read-only (`SQLITE_OPEN_READONLY`), beside `query_only`, the
read-only statement check, one statement only and no PRAGMAs. read-only statement check, one statement only and no PRAGMAs.
- **The 16 MiB frame limit stays** (2026-11-19): it was the limit once
authenticated (2026-11-08, 4 KB before); since TLS authenticates
both ends before any frame, it's the only one left. Not lifted: a
buggy peer announcing gigabytes would make the other end hold them.
- **`SyncState` in pages** (2026-11-19, protocol 8, asked by the owner
for the worst case): `SyncStateRequest` takes `after` (the last head
received, a `Pair`), `SyncState` has `more` and 32768 heads at most
(`MAX_HEADS_PER_PACKET`), the lists and missing attachments in the
first page only. The biggest first page (every list full, every name
64 characters) is about 13.3 MB, tested. A cursor by names, like
`GetMessages`' `after`, rather than several answers to one request
(one request, one answer) or ids (each server's own). The receiver
reads its heads in pages too (`heads_after`, on the `(topic, node)`
index); the sender gathers every page before comparing.
- **Fixes from a read of the code** (2026-11-19, asked by the owner):
- **ALPN required by the server too:** rustls only refuses a client
offering other protocols; one offering none is now closed right
after TLS, before the versions.
- **Retention ages, 100 years at most** (`MAX_RETENTION_AGE`,
`"36500d"`): turning a huge one into milliseconds wrapped around
(`"18446744073709552s"` was 384 ms). The cutoff is computed in one
place (`Retention::cutoff`), saturating.
- **`Ping` / `Pong`** (19, 20; protocol 8, not released yet): the
server closes a connection silent for 5 min
(`IDLE_TIMEOUT_SECS`). A ping every minute (`KEEPALIVE_SECS`) keeps
one open: the tool's `--follow`, Python's `follow()`, C#'s
`Follow()` and the replication links send it while waiting longer
(so `sync_interval` over 5 min works now). The DLL has no thread of
its own, so it can't on its own: `BakaShrot_Ping()` for apps, with
`ping()` / `Ping()` in Python and C#. Preferred to a longer idle
timeout (connections of dead clients would linger) or to
reconnecting by itself (nothing does, on purpose).
- **`[server] idle_database_connections`** (8 by default, 0-512): the
idle read and query connections each pool keeps (they were all
kept, as many as ever ran at once); one idle for a minute is
closed (a thread looks every 10 s).
- **Schema v9, not compatible with v8** (2026-11-13): old databases aren't - **Schema v9, not compatible with v8** (2026-11-13): old databases aren't
opened, their data isn't carried over (the real-life tests start empty). opened, their data isn't carried over (the real-life tests start empty).
`docs/storage.md`: `docs/storage.md`:
@@ -279,7 +315,8 @@ Also decided (2026-11-13):
- **version 0.2.0**; **0.3.0** on 2026-11-16 (the identity OID under - **version 0.2.0**; **0.3.0** on 2026-11-16 (the identity OID under
NibblePoker's PEN, the roles as the only lists of topics, NibblePoker's PEN, the roles as the only lists of topics,
`list_topics` / `list_nodes`); **0.4.0** on 2026-11-19 (protocol 8: `list_topics` / `list_nodes`); **0.4.0** on 2026-11-19 (protocol 8:
filtered lists; the DLL's enumerations; the C# binding). filtered lists, `SyncState` in pages; the DLL's enumerations; the C#
binding).
- **The PureBasic version removed** (2026-11-15): `OldSource/` deleted, - **The PureBasic version removed** (2026-11-15): `OldSource/` deleted,
kept in git history (up to `68966a8`). What of its notes and designs kept in git history (up to `68966a8`). What of its notes and designs
still holds went to `docs/known-issues.md`; the rest was already still holds went to `docs/known-issues.md`; the rest was already
@@ -357,8 +394,9 @@ None right now.
The PureBasic version's, still not fixed: The PureBasic version's, still not fixed:
- **Gaps in a topic and node's ids** aren't detected on replication (6), - **Gaps in a topic and node's ids** aren't detected on replication (6):
and **`SyncState` is one packet** (9): `docs/known-issues.md`. `docs/known-issues.md`. (**`SyncState` in one packet**, 9, fixed
2026-11-19: its pages.)
- **Peers are trusted with what they replicate** (12), unless messages - **Peers are trusted with what they replicate** (12), unless messages
get signed by their node: `docs/known-issues.md`. get signed by their node: `docs/known-issues.md`.
- **Names left out of replication aren't warned about:** a topic or - **Names left out of replication aren't warned about:** a topic or
@@ -408,6 +446,8 @@ by hand.
| 14 | C# binding | `bindings/csharp`: `Client` over the `W` exports, C# 2 and .NET 2.0's library only (net35, netstandard2.0); the NuGet package `NibblePoker.BakaShrot.Client` with the four platforms' libraries, packed by CI after the releases (an artifact) | Its NUnit tests pass on net48 and net8.0 (by hand, not in `test.ps1`); the package loads the library on net8.0 and net48 | Asked by the owner 2026-11-18 (the name too) | Done 2026-11-18 | | 14 | C# binding | `bindings/csharp`: `Client` over the `W` exports, C# 2 and .NET 2.0's library only (net35, netstandard2.0); the NuGet package `NibblePoker.BakaShrot.Client` with the four platforms' libraries, packed by CI after the releases (an artifact) | Its NUnit tests pass on net48 and net8.0 (by hand, not in `test.ps1`); the package loads the library on net8.0 and net48 | Asked by the owner 2026-11-18 (the name too) | Done 2026-11-18 |
| 15 | Filtered lists | `ListNames`' `topics` and `nodes` filters (protocol 8): server, client, `BakaShrot_ListNames` (`A`/`W`), Python, C#, PureBasic, `bakashrot list --topics/--nodes` | `end_to_end.rs` `names` (patterns, case, permissions), `exports.rs`, `check_bakashrot.py`, the NUnit tests | Decided 2026-11-19 | Done 2026-11-19 | | 15 | Filtered lists | `ListNames`' `topics` and `nodes` filters (protocol 8): server, client, `BakaShrot_ListNames` (`A`/`W`), Python, C#, PureBasic, `bakashrot list --topics/--nodes` | `end_to_end.rs` `names` (patterns, case, permissions), `exports.rs`, `check_bakashrot.py`, the NUnit tests | Decided 2026-11-19 | Done 2026-11-19 |
| 16 | The DLL's enumerations | `GetNamesListAsJson`, `GetQueryResultAsJson`; `EnumerateNames` / `EnumerateQuery`, `Next...`, their getters, `CloseEnum` (`enumerations.rs`); `ListTopics` / `ListNodes` dropped; PureBasic's example on them; C#'s `EnumerateTopics` / `EnumerateNodes` / `EnumerateQuery` (`IEnumerable`, asked at each `foreach`) | `exports.rs` `enumerations` (names, query rows and nulls, several at once, bad and closed handles, freed with the client); the NUnit `Enumerations` test | Decided 2026-11-19 | Done 2026-11-19 | | 16 | The DLL's enumerations | `GetNamesListAsJson`, `GetQueryResultAsJson`; `EnumerateNames` / `EnumerateQuery`, `Next...`, their getters, `CloseEnum` (`enumerations.rs`); `ListTopics` / `ListNodes` dropped; PureBasic's example on them; C#'s `EnumerateTopics` / `EnumerateNodes` / `EnumerateQuery` (`IEnumerable`, asked at each `foreach`) | `exports.rs` `enumerations` (names, query rows and nulls, several at once, bad and closed handles, freed with the client); the NUnit `Enumerations` test | Decided 2026-11-19 | Done 2026-11-19 |
| 17 | `SyncState` in pages | `SyncStateRequest.after`, `SyncState.more`, `MAX_HEADS_PER_PACKET` (protocol 8); `heads_after` in storage; both ends of replication | `packets.rs` `the_biggest_sync_state_fits` and the page rules; `storage.rs` heads in pages; `end_to_end.rs` `sync_state_in_pages` (full and partial pages, the lists in the first only, a cursor in another case or not stored, pairs a peer doesn't take skipped, exactly a page, a pattern refused) and `replication_across_pages` (only what's after a head of the second page sent); each part broken on purpose once, every test caught it | Decided 2026-11-19 | Done 2026-11-19 |
| 18 | Fixes from a read of the code | The server requiring ALPN; retention ages capped at 100 years; `Ping` / `Pong` (protocol 8) with `BakaShrot_Ping`, Python's and C#'s `ping`, pings in the follows and the replication links; `idle_database_connections` and idle connections closed | `end_to_end.rs` `certificates_refused` (no ALPN: closed), `pings`, `no_idle_database_connections`; `config.rs` the cap, `retention_cutoff`, the key; the server's `pools_keep_few_and_close_the_idle`; `packets.rs` samples and bytes; `exports.rs`, `check_bakashrot.py`, the NUnit `Closing` | Decided 2026-11-19 | Done 2026-11-19 |
Each step ends with its tests passing and its docs updated (the crate's Each step ends with its tests passing and its docs updated (the crate's
docs, `docs/`, this file's status), then a commit when the owner docs, `docs/`, this file's status), then a commit when the owner