mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Stopped long queries, Read is_open() through TLS, Simplified answers and paging
- [server] query_time_limit (20 s by default) stops a client's query through SQLite's progress handler: refused with QueryTimedOut (11). A client closing while its query runs stops it too. - The answer timeout in the DLL (BakaShrot_SetAnswerTimeout / GetAnswerTimeout, kept across connections), Python (answer_timeout) and C# (AnswerTimeoutMs); QueryTimedOut in every binding. - is_open() reads what's waiting through TLS: a close_notify says closed, TLS's own records keep it open, unasked data or a broken stream close it. - The Rust client checks an answer's type in one place (TryFrom per packet); Client::wait() pings while waiting (the tool's --follow). - Pair::from(&Head), heads_after taking a Pair; simpler SyncState paging on both ends; the writer's redundant rollback check dropped. - codes.rs: the bindings' error codes and copied values match Rust's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -125,6 +125,20 @@ ptrdiff_t BakaShrot_Disconnect(int64_t client);
|
||||
*/
|
||||
ptrdiff_t BakaShrot_Ping(int64_t client);
|
||||
|
||||
/**
|
||||
* Sets how long an answer may take, in milliseconds (more than 0; 30000
|
||||
* until changed): longer for a slow query, say. Past it, the request
|
||||
* fails with `ConnectionLost`, the connection closed (the server then
|
||||
* stops the query it was running). Kept for the next connections, and
|
||||
* applied to the current one: 1, or 0 if refused.
|
||||
*/
|
||||
ptrdiff_t BakaShrot_SetAnswerTimeout(int64_t client, int64_t milliseconds);
|
||||
|
||||
/**
|
||||
* How long an answer may take, in milliseconds (`BakaShrot_SetAnswerTimeout()`).
|
||||
*/
|
||||
int64_t BakaShrot_GetAnswerTimeout(int64_t client);
|
||||
|
||||
/**
|
||||
* The node this client is, as the server said when connecting: its
|
||||
* certificate's name. Empty when not connected.
|
||||
|
||||
@@ -301,6 +301,26 @@ namespace NibblePoker.BakaShrot.Tests
|
||||
Assert.That(kitchen.Connected, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnswerTimeouts()
|
||||
{
|
||||
const string forever =
|
||||
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n";
|
||||
using Client kitchen = Server.Connect("kitchen");
|
||||
Assert.That(kitchen.AnswerTimeoutMs, Is.EqualTo(Client.DefaultAnswerTimeoutMs));
|
||||
BakaShrotException refused = Assert.Throws<BakaShrotException>(() => kitchen.AnswerTimeoutMs = 0)!;
|
||||
Assert.That(refused.Code, Is.EqualTo(ErrorCode.InvalidArgument));
|
||||
kitchen.AnswerTimeoutMs = 300;
|
||||
Assert.That(kitchen.Connected, Is.True, "set while connected");
|
||||
ConnectionLostException lost = Assert.Throws<ConnectionLostException>(() => kitchen.Query(forever))!;
|
||||
Assert.That(lost.Code, Is.EqualTo(ErrorCode.ConnectionLost));
|
||||
Assert.That(kitchen.Connected, Is.False);
|
||||
kitchen.Connect();
|
||||
Assert.That(kitchen.AnswerTimeoutMs, Is.EqualTo(300), "kept across connections");
|
||||
lost = Assert.Throws<ConnectionLostException>(() => kitchen.Query(forever))!;
|
||||
Assert.That(lost.Code, Is.EqualTo(ErrorCode.ConnectionLost));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Connecting()
|
||||
{
|
||||
|
||||
@@ -31,7 +31,7 @@ namespace NibblePoker.BakaShrot
|
||||
{
|
||||
None = 0,
|
||||
NotAllowed = 1, UnknownName = 2, NotFound = 3, NotReady = 4, TooBig = 5,
|
||||
InvalidRequest = 7, DataMismatch = 8, QueryFailed = 9, ServerError = 10,
|
||||
InvalidRequest = 7, DataMismatch = 8, QueryFailed = 9, ServerError = 10, QueryTimedOut = 11,
|
||||
NotConnected = 100, ConnectFailed = 101, AuthRejected = 102, ServerNotVerified = 103,
|
||||
ConnectionLost = 104, ProtocolError = 105, InvalidArgument = 106, FileError = 107,
|
||||
AttachmentMismatch = 108, AlreadyConnected = 109, Internal = 110, VersionMismatch = 111
|
||||
@@ -137,6 +137,7 @@ namespace NibblePoker.BakaShrot
|
||||
public readonly int Port;
|
||||
private readonly object sync = new object();
|
||||
private string node = "";
|
||||
private int answerTimeoutMs = DefaultAnswerTimeoutMs;
|
||||
private long handle; // its client in the library, 0 before Connect() and after Close()
|
||||
|
||||
/// <summary>host: a name or an address. The certificates and the CRL
|
||||
@@ -167,6 +168,7 @@ namespace NibblePoker.BakaShrot
|
||||
throw new BakaShrotException("The library made no client", ErrorCode.Internal);
|
||||
if (Native.BakaShrot_IsConnected(handle) != IntPtr.Zero)
|
||||
return this;
|
||||
Check(Native.BakaShrot_SetAnswerTimeout(handle, answerTimeoutMs), "AnswerTimeoutMs");
|
||||
Check(Native.BakaShrot_SetCaCertificateW(handle, Text(Ca)), "Certificates");
|
||||
Check(Native.BakaShrot_SetCertificateW(handle, Text(Certificate)), "Certificates");
|
||||
Check(Native.BakaShrot_SetPrivateKeyW(handle, Text(Key)), "Certificates");
|
||||
@@ -213,6 +215,30 @@ namespace NibblePoker.BakaShrot
|
||||
/// <summary>How often to Ping() while waiting between requests, in ms.</summary>
|
||||
public const int KeepAliveMs = 60000;
|
||||
|
||||
/// <summary>AnswerTimeoutMs until changed.</summary>
|
||||
public const int DefaultAnswerTimeoutMs = 30000;
|
||||
|
||||
/// <summary>How long an answer may take, in ms (more than 0): longer
|
||||
/// for a slow query, say. Past it, the request throws
|
||||
/// ConnectionLostException and the connection is closed (the server
|
||||
/// stops the query it was running then). Kept across connections.</summary>
|
||||
public int AnswerTimeoutMs
|
||||
{
|
||||
get { lock (sync) return answerTimeoutMs; }
|
||||
set
|
||||
{
|
||||
if (value <= 0)
|
||||
throw new BakaShrotException("An answer timeout of " + value + " ms: more than 0",
|
||||
ErrorCode.InvalidArgument);
|
||||
lock (sync)
|
||||
{
|
||||
if (handle != 0)
|
||||
Check(Native.BakaShrot_SetAnswerTimeout(handle, value), "AnswerTimeoutMs");
|
||||
answerTimeoutMs = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Pushes data (JSON or not) to topic, as this client's node: its id.</summary>
|
||||
public long Push(string topic, string data)
|
||||
{
|
||||
@@ -592,6 +618,7 @@ namespace NibblePoker.BakaShrot
|
||||
[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_Ping(long client);
|
||||
[DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_SetAnswerTimeout(long client, long milliseconds);
|
||||
[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 IntPtr BakaShrot_GetLatestMessageOfW(long client, string topic, string node);
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
; ==- Compatibility -=============================
|
||||
; Tested compiler versions:
|
||||
; * PureBasic 5.73 LTS (Windows x64)
|
||||
; * PureBasic 6.41 (Windows x64)
|
||||
;
|
||||
; ==- Links -=====================================
|
||||
; GitHub: https://github.com/aziascreations/BakaShrot
|
||||
@@ -63,6 +64,8 @@ PrototypeC.i BakaShrot_Connect_Prototype(Client.q, Host.p-unicode, Port.l)
|
||||
PrototypeC.i BakaShrot_IsConnected_Prototype(Client.q)
|
||||
PrototypeC.i BakaShrot_Disconnect_Prototype(Client.q)
|
||||
PrototypeC.i BakaShrot_Ping_Prototype(Client.q)
|
||||
PrototypeC.i BakaShrot_SetAnswerTimeout_Prototype(Client.q, Milliseconds.q)
|
||||
PrototypeC.q BakaShrot_GetAnswerTimeout_Prototype(Client.q)
|
||||
PrototypeC.i BakaShrot_GetNode_Prototype(Client.q, *Buffer, BufferSize.i)
|
||||
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)
|
||||
@@ -114,6 +117,8 @@ Global BakaShrot_Connect.BakaShrot_Connect_Prototype
|
||||
Global BakaShrot_IsConnected.BakaShrot_IsConnected_Prototype
|
||||
Global BakaShrot_Disconnect.BakaShrot_Disconnect_Prototype
|
||||
Global BakaShrot_Ping.BakaShrot_Ping_Prototype
|
||||
Global BakaShrot_SetAnswerTimeout.BakaShrot_SetAnswerTimeout_Prototype
|
||||
Global BakaShrot_GetAnswerTimeout.BakaShrot_GetAnswerTimeout_Prototype
|
||||
Global BakaShrot_GetNode.BakaShrot_GetNode_Prototype
|
||||
Global BakaShrot_PushMessageTo.BakaShrot_PushMessageTo_Prototype
|
||||
Global BakaShrot_GetLatestMessageOf.BakaShrot_GetLatestMessageOf_Prototype
|
||||
@@ -202,6 +207,8 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
|
||||
BakaShrot_IsConnected = BakaShrot_ClientFunction("BakaShrot_IsConnected")
|
||||
BakaShrot_Disconnect = BakaShrot_ClientFunction("BakaShrot_Disconnect")
|
||||
BakaShrot_Ping = BakaShrot_ClientFunction("BakaShrot_Ping")
|
||||
BakaShrot_SetAnswerTimeout = BakaShrot_ClientFunction("BakaShrot_SetAnswerTimeout")
|
||||
BakaShrot_GetAnswerTimeout = BakaShrot_ClientFunction("BakaShrot_GetAnswerTimeout")
|
||||
BakaShrot_GetNode = BakaShrot_ClientFunction("BakaShrot_GetNodeW")
|
||||
BakaShrot_PushMessageTo = BakaShrot_ClientFunction("BakaShrot_PushMessageToW")
|
||||
BakaShrot_GetLatestMessageOf = BakaShrot_ClientFunction("BakaShrot_GetLatestMessageOfW")
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
; ==- Compatibility -=============================
|
||||
; Tested compiler versions:
|
||||
; * PureBasic 5.73 LTS (Windows x64)
|
||||
; * PureBasic 6.41 (Windows x64)
|
||||
;
|
||||
; ==- Links -=====================================
|
||||
; GitHub: https://github.com/aziascreations/BakaShrot
|
||||
@@ -30,7 +31,8 @@
|
||||
; reconnect, then retry: NotConnected, ConnectFailed, ConnectionLost,
|
||||
; ProtocolError (the connection is closed)
|
||||
; retry later: NotReady (an attachment still on its way),
|
||||
; ServerError (the server's storage failed)
|
||||
; ServerError (the server's storage failed),
|
||||
; QueryTimedOut (or narrow the query)
|
||||
; fix the certificates or
|
||||
; the server's config: AuthRejected, ServerNotVerified, NotAllowed,
|
||||
; UnknownName, VersionMismatch
|
||||
@@ -67,6 +69,9 @@
|
||||
#BakaShrot_Refused_QueryFailed = 9
|
||||
; The server couldn't store or read something: its database failed.
|
||||
#BakaShrot_Refused_ServerError = 10
|
||||
; A query ran past the server's time limit (query_time_limit) and was
|
||||
; stopped: narrow it, or retry when the server is less busy.
|
||||
#BakaShrot_Refused_QueryTimedOut = 11
|
||||
|
||||
; The highest a refusal can have, anything above is the client's own.
|
||||
#BakaShrot_Refused_Max = 99
|
||||
@@ -119,6 +124,7 @@ Procedure.s BakaShrot_ErrorName(Code.l)
|
||||
Case #BakaShrot_Refused_DataMismatch : ProcedureReturn "DataMismatch"
|
||||
Case #BakaShrot_Refused_QueryFailed : ProcedureReturn "QueryFailed"
|
||||
Case #BakaShrot_Refused_ServerError : ProcedureReturn "ServerError"
|
||||
Case #BakaShrot_Refused_QueryTimedOut : ProcedureReturn "QueryTimedOut"
|
||||
Case #BakaShrot_Error_NotConnected : ProcedureReturn "NotConnected"
|
||||
Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "ConnectFailed"
|
||||
Case #BakaShrot_Error_AuthRejected : ProcedureReturn "AuthRejected"
|
||||
|
||||
@@ -63,7 +63,7 @@ __version__ = "0.4.0"
|
||||
__all__ = [
|
||||
"Client", "Message", "MessagesPage", "NamesList",
|
||||
"BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode",
|
||||
"MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE", "KEEPALIVE_SECONDS",
|
||||
"MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE", "KEEPALIVE_SECONDS", "ANSWER_TIMEOUT_SECONDS",
|
||||
]
|
||||
|
||||
# The protocol's: crates/bakashrot-proto/src/limits.rs.
|
||||
@@ -72,6 +72,8 @@ 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
|
||||
# How long an answer may take until Client.answer_timeout is changed.
|
||||
ANSWER_TIMEOUT_SECONDS = 30.0
|
||||
|
||||
DLL_NAME = "bakashrot.dll" if sys.platform == "win32" else "libbakashrot.so"
|
||||
|
||||
@@ -90,6 +92,7 @@ class ErrorCode(enum.IntEnum):
|
||||
DATA_MISMATCH = 8 # an upload that doesn't match its SHA-256
|
||||
QUERY_FAILED = 9 # the SQL failed
|
||||
SERVER_ERROR = 10 # the server's database failed: retry later
|
||||
QUERY_TIMED_OUT = 11 # a query past the server's time limit, stopped: narrow it or retry later
|
||||
# The client's own.
|
||||
NOT_CONNECTED = 100 # never connected, or closed or lost before
|
||||
CONNECT_FAILED = 101 # nothing answers at that host and port
|
||||
@@ -254,6 +257,8 @@ class _Dll:
|
||||
"BakaShrot_IsConnected": (I, [H]),
|
||||
"BakaShrot_Disconnect": (I, [H]),
|
||||
"BakaShrot_Ping": (I, [H]),
|
||||
"BakaShrot_SetAnswerTimeout": (I, [H, Q]),
|
||||
"BakaShrot_GetAnswerTimeout": (Q, [H]),
|
||||
"BakaShrot_GetNodeA": (I, [H, S, I]),
|
||||
"BakaShrot_PushMessageToA": (Q, [H, P, P]),
|
||||
"BakaShrot_GetLatestMessageOfA": (I, [H, P, P]),
|
||||
@@ -326,6 +331,7 @@ class Client:
|
||||
self.key = os.fspath(key)
|
||||
self.crl = os.fspath(crl) if crl else None
|
||||
self.node = ""
|
||||
self._answer_timeout = ANSWER_TIMEOUT_SECONDS
|
||||
# Its client in the DLL, from connect() to close().
|
||||
self._handle: Optional[int] = None
|
||||
|
||||
@@ -378,6 +384,8 @@ class Client:
|
||||
raise BakaShrotError("The DLL made no client", ErrorCode.INTERNAL)
|
||||
self._handle = handle
|
||||
handle = self._handle
|
||||
if not dll.SetAnswerTimeout(handle, self._milliseconds(self._answer_timeout)):
|
||||
raise self._failed("Answer timeout")
|
||||
for setter, value in ((dll.SetCaCertificateA, self.ca), (dll.SetCertificateA, self.certificate),
|
||||
(dll.SetPrivateKeyA, self.key), (dll.SetCrlA, self.crl or "")):
|
||||
if not setter(handle, value.encode("utf-8")):
|
||||
@@ -401,6 +409,29 @@ class Client:
|
||||
except Exception: # noqa: BLE001 - the interpreter may be shutting down
|
||||
pass
|
||||
|
||||
@property
|
||||
def answer_timeout(self) -> float:
|
||||
"""How long an answer may take, in seconds (ANSWER_TIMEOUT_SECONDS
|
||||
until changed): longer for a slow query, say. Past it, the request
|
||||
raises ConnectionLostError and the connection is closed (the server
|
||||
stops the query it was running then). Kept across connections."""
|
||||
return self._answer_timeout
|
||||
|
||||
@answer_timeout.setter
|
||||
def answer_timeout(self, seconds: float) -> None:
|
||||
milliseconds = self._milliseconds(seconds)
|
||||
with self._lock:
|
||||
if self._handle is not None and not self._dll.SetAnswerTimeout(self._handle, milliseconds):
|
||||
raise self._failed("Answer timeout")
|
||||
self._answer_timeout = milliseconds / 1000
|
||||
|
||||
@staticmethod
|
||||
def _milliseconds(seconds: float) -> int:
|
||||
milliseconds = round(seconds * 1000)
|
||||
if milliseconds < 1 or milliseconds >= 2 ** 63:
|
||||
raise BakaShrotError(f"An answer timeout of {seconds} s: 1 ms or more", ErrorCode.INVALID_ARGUMENT)
|
||||
return milliseconds
|
||||
|
||||
@property
|
||||
def connected(self) -> bool:
|
||||
handle = self._handle
|
||||
|
||||
@@ -16,7 +16,7 @@ import threading
|
||||
import time
|
||||
|
||||
import bakashrot
|
||||
from bakashrot import AuthError, BakaShrotError, Client, ConnectionLostError, ErrorCode, RefusedError
|
||||
from bakashrot import ANSWER_TIMEOUT_SECONDS, AuthError, BakaShrotError, Client, ConnectionLostError, ErrorCode, RefusedError
|
||||
|
||||
dll_path, folder = sys.argv[1:3]
|
||||
fails = 0
|
||||
@@ -226,6 +226,26 @@ with kitchen:
|
||||
kitchen.ping()
|
||||
check("ping(): answered, still connected", kitchen.connected)
|
||||
|
||||
# --- The answer timeout ----------------------------------------------------
|
||||
check("answer_timeout: 30 s until changed", kitchen.answer_timeout == ANSWER_TIMEOUT_SECONDS, kitchen.answer_timeout)
|
||||
ok, detail = raises(lambda: setattr(kitchen, "answer_timeout", 0), BakaShrotError, "1 ms or more", ErrorCode.INVALID_ARGUMENT)
|
||||
check("answer_timeout = 0: refused", ok and kitchen.answer_timeout == ANSWER_TIMEOUT_SECONDS, detail)
|
||||
slow = Client.from_file(os.path.join(folder, "kitchen.toml"), dll_path)
|
||||
slow.answer_timeout = 0.3
|
||||
slow.connect()
|
||||
forever = "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n"
|
||||
started = time.perf_counter()
|
||||
ok, detail = raises(lambda: slow.query(forever), ConnectionLostError, code=ErrorCode.CONNECTION_LOST)
|
||||
elapsed = time.perf_counter() - started
|
||||
check("A query past answer_timeout (0.3 s, set before connecting): ConnectionLostError, disconnected",
|
||||
ok and elapsed < 5 and not slow.connected, f"{detail}, {elapsed * 1000:.0f} ms")
|
||||
slow.connect()
|
||||
slow.answer_timeout = 0.2
|
||||
check("answer_timeout set while connected: kept, the connection too", slow.answer_timeout == 0.2 and slow.connected)
|
||||
ok, detail = raises(lambda: slow.query(forever), ConnectionLostError, code=ErrorCode.CONNECTION_LOST)
|
||||
check("A query past it again: ConnectionLostError", ok, detail)
|
||||
slow.close()
|
||||
|
||||
# --- Two Clients, two threads, at the same time --------------------------
|
||||
other = Client.from_file(os.path.join(folder, "kitchen.toml"), dll_path).connect()
|
||||
pushed = {}
|
||||
|
||||
@@ -36,7 +36,7 @@ mod enumerations;
|
||||
pub use enumerations::*;
|
||||
mod text;
|
||||
|
||||
use bakashrot_client::{Client, Error, Settings};
|
||||
use bakashrot_client::{ANSWER_TIMEOUT, Client, Error, Settings};
|
||||
use bakashrot_proto::ErrorCode;
|
||||
use bakashrot_proto::packets::{MessageEntry, NameKind, NamesList};
|
||||
use std::collections::BTreeMap;
|
||||
@@ -46,6 +46,7 @@ use std::io::Cursor;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::Duration;
|
||||
use text::{Text, Utf8, Utf16};
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
@@ -81,6 +82,8 @@ struct State {
|
||||
certificate: Option<String>,
|
||||
key: Option<String>,
|
||||
crl: Option<String>,
|
||||
/// Given to each connection, and to the current one when set.
|
||||
answer_timeout: Duration,
|
||||
client: Option<Client>,
|
||||
/// The last call's error code, 0 if it succeeded.
|
||||
last_error: u32,
|
||||
@@ -107,6 +110,7 @@ impl State {
|
||||
certificate: None,
|
||||
key: None,
|
||||
crl: None,
|
||||
answer_timeout: ANSWER_TIMEOUT,
|
||||
client: None,
|
||||
last_error: 0,
|
||||
reason: String::new(),
|
||||
@@ -124,14 +128,10 @@ impl State {
|
||||
fn fail(&mut self, error: Error) {
|
||||
self.last_error = error.code();
|
||||
self.reason = error.message().to_owned();
|
||||
// The client closes its connection on those, and on others that
|
||||
// leave it out of step (a file failing mid-upload): forgotten then,
|
||||
// so connecting again works.
|
||||
let closed = [ErrorCode::ConnectionLost, ErrorCode::ProtocolError]
|
||||
.iter()
|
||||
.any(|code| code.code() == error.code())
|
||||
|| self.client.as_ref().is_some_and(Client::is_closed);
|
||||
if closed {
|
||||
// The client closes its connection on every failure that leaves it
|
||||
// out of step (`ConnectionLost`, `ProtocolError`, a file failing
|
||||
// mid-upload): forgotten then, so connecting again works.
|
||||
if self.client.as_ref().is_some_and(Client::is_closed) {
|
||||
self.client = None;
|
||||
}
|
||||
}
|
||||
@@ -465,7 +465,8 @@ unsafe fn connect<T: Text>(client: i64, host: *const T::Unit, port: i32) -> isiz
|
||||
true => format!("[{host}]:{port}"),
|
||||
false => format!("{host}:{port}"),
|
||||
};
|
||||
let client = Client::connect(&address, &settings)?;
|
||||
let mut client = Client::connect(&address, &settings)?;
|
||||
client.set_answer_timeout(state.answer_timeout)?;
|
||||
state.client = Some(client);
|
||||
Ok(1)
|
||||
})
|
||||
@@ -492,7 +493,7 @@ pub unsafe extern "C" fn BakaShrot_ConnectW(client: i64, host: *const u16, port:
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_IsConnected(client: i64) -> isize {
|
||||
get(client, 0, |state| {
|
||||
let open = state.client.as_ref().is_some_and(Client::is_open);
|
||||
let open = state.client.as_mut().is_some_and(Client::is_open);
|
||||
if !open {
|
||||
state.client = None;
|
||||
}
|
||||
@@ -520,6 +521,39 @@ pub extern "C" fn BakaShrot_Ping(client: i64) -> isize {
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets how long an answer may take, in milliseconds (more than 0; 30000
|
||||
/// until changed): longer for a slow query, say. Past it, the request
|
||||
/// fails with `ConnectionLost`, the connection closed (the server then
|
||||
/// stops the query it was running). Kept for the next connections, and
|
||||
/// applied to the current one: 1, or 0 if refused.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_SetAnswerTimeout(client: i64, milliseconds: i64) -> isize {
|
||||
call(client, 0, |state| {
|
||||
let timeout = u64::try_from(milliseconds)
|
||||
.ok()
|
||||
.filter(|ms| *ms > 0)
|
||||
.map(Duration::from_millis)
|
||||
.ok_or_else(|| {
|
||||
invalid(format!(
|
||||
"an answer timeout of {milliseconds} ms: more than 0"
|
||||
))
|
||||
})?;
|
||||
if let Some(connected) = state.client.as_mut() {
|
||||
connected.set_answer_timeout(timeout)?;
|
||||
}
|
||||
state.answer_timeout = timeout;
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
|
||||
/// How long an answer may take, in milliseconds (`BakaShrot_SetAnswerTimeout()`).
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_GetAnswerTimeout(client: i64) -> i64 {
|
||||
get(client, -1, |state| {
|
||||
i64::try_from(state.answer_timeout.as_millis()).unwrap_or(i64::MAX)
|
||||
})
|
||||
}
|
||||
|
||||
fn node(state: &State) -> &str {
|
||||
state.client.as_ref().map_or("", Client::node)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! The bindings' error codes are the protocol's, every one, by the same
|
||||
//! numbers: Python's `ErrorCode`, C#'s `ErrorCode`, PureBasic's constants.
|
||||
//! And the values they copy are the Rust side's.
|
||||
|
||||
use bakashrot_client::ANSWER_TIMEOUT;
|
||||
use bakashrot_proto::ErrorCode;
|
||||
use bakashrot_proto::limits::{KEEPALIVE_SECS, MAX_MESSAGES_PER_PACKET};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn binding(path: &str) -> String {
|
||||
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../bindings")
|
||||
.join(path);
|
||||
std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{}: {error}", path.display()))
|
||||
}
|
||||
|
||||
/// The protocol's codes, by number: their names as `name` writes them.
|
||||
fn expected(name: impl Fn(ErrorCode) -> String) -> BTreeMap<u32, String> {
|
||||
ErrorCode::ALL
|
||||
.iter()
|
||||
.map(|&code| (code.code(), name(code)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `NotFound` as `NOT_FOUND`.
|
||||
fn upper_snake(name: &str) -> String {
|
||||
let mut snake = String::new();
|
||||
for (at, c) in name.char_indices() {
|
||||
if c.is_ascii_uppercase() && at > 0 {
|
||||
snake.push('_');
|
||||
}
|
||||
snake.push(c.to_ascii_uppercase());
|
||||
}
|
||||
snake
|
||||
}
|
||||
|
||||
/// `NAME = 12` in `text`, one per line or comma: the names and numbers.
|
||||
fn assignments<'a>(text: impl Iterator<Item = &'a str>) -> BTreeMap<u32, String> {
|
||||
let mut found = BTreeMap::new();
|
||||
for item in text.flat_map(|line| line.split(',')) {
|
||||
// Comments: PureBasic's `;`, Python's ` #` (PureBasic's constants
|
||||
// start with `#`).
|
||||
let item = item.split(';').next().unwrap_or("");
|
||||
let item = item.split(" #").next().unwrap_or("").trim();
|
||||
let Some((name, number)) = item.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
let Ok(number) = number.trim().parse::<u32>() else {
|
||||
continue;
|
||||
};
|
||||
let before = found.insert(number, name.trim().to_owned());
|
||||
assert!(before.is_none(), "{number} twice: {before:?}, {name}");
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The lines of `text` from the one starting with `start` to the next
|
||||
/// starting with `end`.
|
||||
fn section<'a>(text: &'a str, start: &str, end: &str) -> impl Iterator<Item = &'a str> {
|
||||
text.lines()
|
||||
.skip_while(move |line| !line.trim_start().starts_with(start))
|
||||
.skip(1)
|
||||
.take_while(move |line| !line.trim_start().starts_with(end))
|
||||
}
|
||||
|
||||
/// The number `name` is set to in `text`: `NAME = 12`, a `;` after or not.
|
||||
fn number(text: &str, name: &str) -> f64 {
|
||||
let set = format!("{name} = ");
|
||||
let line = text.lines().find(|line| line.contains(&set));
|
||||
let line = line.unwrap_or_else(|| panic!("no {set}"));
|
||||
let value = line.split(&set).nth(1).unwrap_or("");
|
||||
let value = value.trim().trim_end_matches(';');
|
||||
value.parse().unwrap_or_else(|_| panic!("{set}{value}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_values() {
|
||||
let python = binding("python/bakashrot.py");
|
||||
let csharp = binding("csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs");
|
||||
let answer = ANSWER_TIMEOUT.as_secs_f64();
|
||||
let keepalive = KEEPALIVE_SECS as f64;
|
||||
assert_eq!(number(&python, "ANSWER_TIMEOUT_SECONDS"), answer);
|
||||
assert_eq!(number(&python, "KEEPALIVE_SECONDS"), keepalive);
|
||||
assert_eq!(
|
||||
number(&python, "MAX_GET_MESSAGES"),
|
||||
f64::from(MAX_MESSAGES_PER_PACKET)
|
||||
);
|
||||
assert_eq!(number(&csharp, "DefaultAnswerTimeoutMs"), answer * 1000.0);
|
||||
assert_eq!(number(&csharp, "KeepAliveMs"), keepalive * 1000.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python() {
|
||||
let text = binding("python/bakashrot.py");
|
||||
let found = assignments(section(&text, "class ErrorCode", "@property"));
|
||||
let mut expected = expected(|code| upper_snake(code.name()));
|
||||
expected.insert(0, "NONE".into());
|
||||
assert_eq!(found, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csharp() {
|
||||
let text = binding("csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs");
|
||||
let found = assignments(section(&text, "public enum ErrorCode", "}"));
|
||||
let mut expected = expected(|code| code.name().to_owned());
|
||||
expected.insert(0, "None".into());
|
||||
assert_eq!(found, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn purebasic() {
|
||||
let text = binding("purebasic/BakaShrot_ErrorCodes.pbi");
|
||||
let constants = text
|
||||
.lines()
|
||||
.filter(|line| line.starts_with("#BakaShrot_") && !line.contains("_Max"));
|
||||
let found = assignments(constants);
|
||||
let mut expected = expected(|code| {
|
||||
let kind = if code.is_refusal() {
|
||||
"Refused"
|
||||
} else {
|
||||
"Error"
|
||||
};
|
||||
format!("#BakaShrot_{kind}_{}", code.name())
|
||||
});
|
||||
expected.insert(0, "#BakaShrot_Error_None".into());
|
||||
assert_eq!(found, expected);
|
||||
// Each named by BakaShrot_ErrorName().
|
||||
for code in ErrorCode::ALL {
|
||||
let case = format!("ProcedureReturn \"{}\"", code.name());
|
||||
assert!(text.contains(&case), "BakaShrot_ErrorName() lacks {code}");
|
||||
}
|
||||
}
|
||||
@@ -434,6 +434,45 @@ fn exports() {
|
||||
assert_eq!(BakaShrot_FreeClient(client), 1);
|
||||
}
|
||||
|
||||
/// The answer timeout: set before connecting or while connected, kept
|
||||
/// across connections; past it, `ConnectionLost` and the connection closed.
|
||||
#[test]
|
||||
fn answer_timeouts() {
|
||||
let running = common::Running::start("answer-timeouts");
|
||||
running.issue("kitchen", &["home"]);
|
||||
let client = BakaShrot_CreateClient();
|
||||
assert_eq!(BakaShrot_GetAnswerTimeout(client), 30_000);
|
||||
for refused in [0, -1, i64::MIN] {
|
||||
assert_eq!(BakaShrot_SetAnswerTimeout(client, refused), 0);
|
||||
assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
|
||||
}
|
||||
assert_eq!(BakaShrot_SetAnswerTimeout(client, 60_000), 1);
|
||||
assert_eq!(BakaShrot_FreeClient(client), 1);
|
||||
|
||||
let client = connected(&running, "kitchen");
|
||||
assert_eq!(BakaShrot_SetAnswerTimeout(client, 300), 1);
|
||||
assert_eq!(BakaShrot_GetAnswerTimeout(client), 300);
|
||||
let forever =
|
||||
a("WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n");
|
||||
let started = std::time::Instant::now();
|
||||
unsafe {
|
||||
assert_eq!(BakaShrot_QueryA(client, forever.as_ptr()), 0);
|
||||
assert_eq!(error(client).0, code(ErrorCode::ConnectionLost));
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5));
|
||||
assert_eq!(BakaShrot_IsConnected(client), 0);
|
||||
// Connected again: the timeout kept.
|
||||
let host = a("127.0.0.1");
|
||||
assert_eq!(
|
||||
BakaShrot_ConnectA(client, host.as_ptr(), i32::from(running.port)),
|
||||
1
|
||||
);
|
||||
assert_eq!(BakaShrot_GetAnswerTimeout(client), 300);
|
||||
assert_eq!(BakaShrot_QueryA(client, forever.as_ptr()), 0);
|
||||
assert_eq!(error(client).0, code(ErrorCode::ConnectionLost));
|
||||
}
|
||||
assert_eq!(BakaShrot_FreeClient(client), 1);
|
||||
}
|
||||
|
||||
/// A new client, connected as `name` (its certificate and key in files).
|
||||
fn connected(running: &common::Running, name: &str) -> i64 {
|
||||
let client = BakaShrot_CreateClient();
|
||||
@@ -476,6 +515,8 @@ fn clients() {
|
||||
assert!(why.contains("no client 99"), "{why}");
|
||||
assert_eq!(BakaShrot_IsConnected(99), 0);
|
||||
assert_eq!(BakaShrot_Ping(99), 0);
|
||||
assert_eq!(BakaShrot_SetAnswerTimeout(99, 1000), 0);
|
||||
assert_eq!(BakaShrot_GetAnswerTimeout(99), -1);
|
||||
assert_eq!(BakaShrot_GetMessageId(-5), 0);
|
||||
assert_eq!(get_w(99, BakaShrot_GetMessageDataW), "");
|
||||
assert_eq!(BakaShrot_FreeClient(99), 0);
|
||||
|
||||
@@ -28,13 +28,13 @@
|
||||
use aws_lc_rs::digest;
|
||||
use bakashrot_pki::{Revocations, tls};
|
||||
use bakashrot_proto::limits::{
|
||||
ALPN, ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGE_SIZE,
|
||||
MAX_MESSAGES_PER_PACKET, MAX_PACKET_SIZE,
|
||||
ALPN, ATTACHMENT_PART_SIZE, KEEPALIVE_SECS, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID,
|
||||
MAX_MESSAGE_SIZE, MAX_MESSAGES_PER_PACKET, MAX_PACKET_SIZE,
|
||||
};
|
||||
use bakashrot_proto::names::{is_valid_name, is_valid_name_or_pattern};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, GetAttachment, GetMessages, ListNames, Messages, NameKind,
|
||||
NamesList, Ping, PushMessage, Query,
|
||||
Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed,
|
||||
Messages, NameKind, NamesList, Ping, Pong, PushMessage, Query, QueryResult, Welcome,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use rustls::{ClientConnection, StreamOwned};
|
||||
@@ -104,6 +104,16 @@ impl std::error::Error for Error {}
|
||||
/// A result of this crate.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// What [`Client::is_open`] found waiting.
|
||||
enum Look {
|
||||
/// Nothing, or only what TLS keeps for itself.
|
||||
Open,
|
||||
/// The server closed it: the socket's end, or TLS's close_notify.
|
||||
Gone,
|
||||
/// Data sent unasked, or a broken TLS stream.
|
||||
OutOfStep,
|
||||
}
|
||||
|
||||
/// A connection to a server.
|
||||
pub struct Client {
|
||||
stream: StreamOwned<ClientConnection, TcpStream>,
|
||||
@@ -181,13 +191,8 @@ impl Client {
|
||||
answer_timeout: CONNECT_TIMEOUT,
|
||||
closed: false,
|
||||
};
|
||||
match client.answer()? {
|
||||
Packet::Welcome(welcome) => {
|
||||
client.server = welcome.server;
|
||||
client.node = welcome.node;
|
||||
}
|
||||
other => return Err(client.unexpected(&other)),
|
||||
}
|
||||
let welcome: Welcome = client.answer()?;
|
||||
(client.server, client.node) = (welcome.server, welcome.node);
|
||||
client.set_answer_timeout(ANSWER_TIMEOUT)?;
|
||||
Ok(client)
|
||||
}
|
||||
@@ -226,23 +231,60 @@ impl Client {
|
||||
}
|
||||
|
||||
/// Whether the connection still looks open: the server hasn't closed
|
||||
/// it (after its idle timeout, say). Only a request tells for sure.
|
||||
pub fn is_open(&self) -> bool {
|
||||
/// it (after its idle timeout, say, or with TLS's close_notify). Only a
|
||||
/// request tells for sure.
|
||||
///
|
||||
/// It reads what's waiting without blocking, through TLS: what TLS
|
||||
/// keeps for itself (session tickets) leaves it open, a close or a
|
||||
/// broken stream doesn't. Data the server sent unasked leaves the
|
||||
/// connection out of step: closed then, as [`Client::is_closed`] says.
|
||||
pub fn is_open(&mut self) -> bool {
|
||||
if self.closed {
|
||||
return false;
|
||||
}
|
||||
let tcp = &self.stream.sock;
|
||||
if tcp.set_nonblocking(true).is_err() {
|
||||
if self.stream.sock.set_nonblocking(true).is_err() {
|
||||
return false;
|
||||
}
|
||||
let open = match tcp.peek(&mut [0]) {
|
||||
Ok(read) => read > 0,
|
||||
Err(error) => error.kind() == io::ErrorKind::WouldBlock,
|
||||
};
|
||||
let looked = self.look();
|
||||
// Blocking again whatever it found: the next request waits for
|
||||
// its answer.
|
||||
let blocking = tcp.set_nonblocking(false).is_ok();
|
||||
open && blocking
|
||||
let blocking = self.stream.sock.set_nonblocking(false).is_ok();
|
||||
match looked {
|
||||
Look::Open => blocking,
|
||||
Look::Gone => false,
|
||||
Look::OutOfStep => {
|
||||
self.close();
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What's waiting on the (non-blocking) socket, read into TLS, which
|
||||
/// keeps what it read for the next request.
|
||||
fn look(&mut self) -> Look {
|
||||
let StreamOwned { conn, sock } = &mut self.stream;
|
||||
loop {
|
||||
// What TLS holds already, then what it reads below.
|
||||
let state = match conn.process_new_packets() {
|
||||
Ok(state) => state,
|
||||
Err(_) => return Look::OutOfStep,
|
||||
};
|
||||
if state.peer_has_closed() {
|
||||
return Look::Gone;
|
||||
}
|
||||
// Nothing is sent unasked: never an answer's start.
|
||||
if state.plaintext_bytes_to_read() > 0 || !conn.wants_read() {
|
||||
return Look::OutOfStep;
|
||||
}
|
||||
match conn.read_tls(sock) {
|
||||
// The socket's end, without close_notify.
|
||||
Ok(0) => return Look::Gone,
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == io::ErrorKind::WouldBlock => return Look::Open,
|
||||
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
|
||||
Err(_) => return Look::Gone,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a failure closed the connection: every request fails with
|
||||
@@ -256,10 +298,23 @@ impl Client {
|
||||
/// `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(self.unexpected(&other)),
|
||||
let Pong {} = self.request(Ping {}.into())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Waits `duration`, pinging every `KEEPALIVE_SECS` meanwhile
|
||||
/// ([`Client::ping`]): for an app waiting longer than the server's idle
|
||||
/// timeout between requests. A failed ping ends it.
|
||||
pub fn wait(&mut self, duration: Duration) -> Result<()> {
|
||||
let keepalive = Duration::from_secs(KEEPALIVE_SECS);
|
||||
let mut left = duration;
|
||||
while left > keepalive {
|
||||
std::thread::sleep(keepalive);
|
||||
left -= keepalive;
|
||||
self.ping()?;
|
||||
}
|
||||
std::thread::sleep(left);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pushes a message to `topic`, as this client's node: its id.
|
||||
@@ -271,10 +326,8 @@ impl Client {
|
||||
data: data.to_owned(),
|
||||
attachment: None,
|
||||
};
|
||||
match self.request(push.into())? {
|
||||
Packet::MessagePushed(pushed) => Ok(pushed.message_id),
|
||||
other => Err(self.unexpected(&other)),
|
||||
}
|
||||
let pushed: MessagePushed = self.request(push.into())?;
|
||||
Ok(pushed.message_id)
|
||||
}
|
||||
|
||||
/// Pushes a message with an attachment read from `source` (a `File`, a
|
||||
@@ -318,10 +371,7 @@ impl Client {
|
||||
data: data.to_owned(),
|
||||
attachment: Some(attachment.clone()),
|
||||
};
|
||||
match self.request(push.into())? {
|
||||
Packet::Continue(_) => {}
|
||||
other => return Err(self.unexpected(&other)),
|
||||
}
|
||||
let Continue {} = self.request(push.into())?;
|
||||
for part in 0..attachment.part_count() {
|
||||
let part = &mut buffer[..attachment.part_len(part) as usize];
|
||||
if let Err(error) = source.read_exact(part) {
|
||||
@@ -333,10 +383,8 @@ impl Client {
|
||||
}))?;
|
||||
}
|
||||
self.flush()?;
|
||||
match self.answer()? {
|
||||
Packet::MessagePushed(pushed) => Ok(pushed.message_id),
|
||||
other => Err(self.unexpected(&other)),
|
||||
}
|
||||
let pushed: MessagePushed = self.answer()?;
|
||||
Ok(pushed.message_id)
|
||||
}
|
||||
|
||||
/// Writes a message's attachment into `out`, a part at a time, checked
|
||||
@@ -360,10 +408,7 @@ impl Client {
|
||||
message_id,
|
||||
from_part: 0,
|
||||
};
|
||||
let attachment = match self.request(get.into())? {
|
||||
Packet::Attachment(attachment) => attachment,
|
||||
other => return Err(self.unexpected(&other)),
|
||||
};
|
||||
let attachment: Attachment = self.request(get.into())?;
|
||||
let mut sha256 = digest::Context::new(&digest::SHA256);
|
||||
// A failing `out`: the parts are still all read, the connection
|
||||
// stays usable.
|
||||
@@ -371,11 +416,8 @@ impl Client {
|
||||
for part in 0..attachment.part_count() {
|
||||
// Parts come without a request each: anything else, a refusal
|
||||
// too, leaves the rest of them unread.
|
||||
let data = match self.answer() {
|
||||
Ok(Packet::AttachmentPart(part)) => part.data,
|
||||
Ok(other) => return Err(self.unexpected(&other)),
|
||||
Err(error) => return Err(self.out_of_step(error)),
|
||||
};
|
||||
let read: Result<AttachmentPart> = self.answer();
|
||||
let data = read.map_err(|error| self.out_of_step(error))?.data;
|
||||
let expected = attachment.part_len(part);
|
||||
if data.len() as u64 != expected {
|
||||
return Err(self.out_of_step(Error::new(
|
||||
@@ -451,10 +493,7 @@ impl Client {
|
||||
after,
|
||||
limit,
|
||||
};
|
||||
match self.request(get.into())? {
|
||||
Packet::Messages(messages) => Ok(messages),
|
||||
other => Err(self.unexpected(&other)),
|
||||
}
|
||||
self.request(get.into())
|
||||
}
|
||||
|
||||
/// The topics with messages that this client may push to or read, or
|
||||
@@ -481,10 +520,7 @@ impl Client {
|
||||
topics: topics.map(str::to_owned),
|
||||
nodes: nodes.map(str::to_owned),
|
||||
};
|
||||
match self.request(list.into())? {
|
||||
Packet::NamesList(names) => Ok(names),
|
||||
other => Err(self.unexpected(&other)),
|
||||
}
|
||||
self.request(list.into())
|
||||
}
|
||||
|
||||
/// Runs read-only SQL: `{"columns":[...],"rows":[[...],...]}`, every
|
||||
@@ -494,10 +530,8 @@ impl Client {
|
||||
let query = Query {
|
||||
sql: sql.to_owned(),
|
||||
};
|
||||
match self.request(query.into())? {
|
||||
Packet::QueryResult(result) => Ok(result.json),
|
||||
other => Err(self.unexpected(&other)),
|
||||
}
|
||||
let result: QueryResult = self.request(query.into())?;
|
||||
Ok(result.json)
|
||||
}
|
||||
|
||||
/// Closes the connection for good: every request fails then
|
||||
@@ -544,11 +578,6 @@ impl Client {
|
||||
self.out_of_step(error)
|
||||
}
|
||||
|
||||
/// An answer that isn't the request's: `ProtocolError`, closed.
|
||||
fn unexpected(&mut self, packet: &Packet) -> Error {
|
||||
self.out_of_step(unexpected(packet))
|
||||
}
|
||||
|
||||
/// Writes a packet's frame (not flushed).
|
||||
fn send(&mut self, packet: &Packet) -> Result<()> {
|
||||
self.check_open()?;
|
||||
@@ -564,16 +593,30 @@ impl Client {
|
||||
flushed.map_err(|error| self.io_failed(error))
|
||||
}
|
||||
|
||||
/// Sends a request, reads its answer.
|
||||
fn request(&mut self, packet: Packet) -> Result<Packet> {
|
||||
/// Sends a request, reads its answer ([`Client::answer`]).
|
||||
fn request<T: TryFrom<Packet, Error = Packet>>(&mut self, packet: Packet) -> Result<T> {
|
||||
self.send(&packet)?;
|
||||
self.flush()?;
|
||||
self.answer()
|
||||
}
|
||||
|
||||
/// Reads the server's next packet, a `T`: a refusal is an error (the
|
||||
/// connection kept), any other packet closes it (`ProtocolError`, the
|
||||
/// answer isn't the request's), as anything else wrong does.
|
||||
fn answer<T: TryFrom<Packet, Error = Packet>>(&mut self) -> Result<T> {
|
||||
let packet = self.receive()?;
|
||||
T::try_from(packet).map_err(|other| {
|
||||
let error = Error::new(
|
||||
ErrorCode::ProtocolError,
|
||||
format!("the server answered {}", other.packet_type().name()),
|
||||
);
|
||||
self.out_of_step(error)
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads the server's next packet: a refusal is an error (the
|
||||
/// connection kept), anything else wrong closes it.
|
||||
fn answer(&mut self) -> Result<Packet> {
|
||||
fn receive(&mut self) -> Result<Packet> {
|
||||
self.check_open()?;
|
||||
let bytes = match frame::read(&mut self.stream, MAX_PACKET_SIZE) {
|
||||
Ok(Some(bytes)) => bytes,
|
||||
@@ -662,10 +705,3 @@ fn check_size(text: &str, what: &str) -> Result<()> {
|
||||
fn file_error(error: io::Error) -> Error {
|
||||
Error::new(ErrorCode::FileError, format!("the attachment: {error}"))
|
||||
}
|
||||
|
||||
fn unexpected(packet: &Packet) -> Error {
|
||||
Error::new(
|
||||
ErrorCode::ProtocolError,
|
||||
format!("the server answered {}", packet.packet_type().name()),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -21,12 +21,15 @@ use std::time::Duration;
|
||||
type Stream = StreamOwned<ServerConnection, TcpStream>;
|
||||
|
||||
/// A fake server for one connection, running its script once the client
|
||||
/// is welcomed, and the client's certificates.
|
||||
/// is connected ([`Fake::connect`] returned: what the script sends is
|
||||
/// never read while connecting), and the client's certificates.
|
||||
struct Fake {
|
||||
address: String,
|
||||
ca: String,
|
||||
client: Issued,
|
||||
script: Option<JoinHandle<()>>,
|
||||
/// Lets the script run.
|
||||
connected: mpsc::Sender<()>,
|
||||
script: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl Fake {
|
||||
@@ -49,6 +52,7 @@ impl Fake {
|
||||
.unwrap();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap().to_string();
|
||||
let (connected, wait_connected) = mpsc::channel();
|
||||
let script = thread::spawn(move || {
|
||||
let (tcp, _) = listener.accept().unwrap();
|
||||
tcp.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
|
||||
@@ -65,18 +69,21 @@ impl Fake {
|
||||
node: "kitchen".into(),
|
||||
},
|
||||
);
|
||||
// Gone without connecting: run all the same.
|
||||
let _ = wait_connected.recv();
|
||||
script(&mut stream);
|
||||
});
|
||||
Fake {
|
||||
address,
|
||||
ca: ca.certificate,
|
||||
client,
|
||||
script: Some(script),
|
||||
connected,
|
||||
script,
|
||||
}
|
||||
}
|
||||
|
||||
fn connect(&self) -> Client {
|
||||
Client::connect(
|
||||
let client = Client::connect(
|
||||
&self.address,
|
||||
&Settings {
|
||||
ca: &self.ca,
|
||||
@@ -85,12 +92,15 @@ impl Fake {
|
||||
crl: None,
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let _ = self.connected.send(());
|
||||
client
|
||||
}
|
||||
|
||||
/// Waits for the script to end (its asserts included).
|
||||
fn finish(mut self) {
|
||||
self.script.take().unwrap().join().unwrap();
|
||||
fn finish(self) {
|
||||
drop(self.connected);
|
||||
self.script.join().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,20 +116,24 @@ fn answer(stream: &mut Stream, packet: impl Into<Packet>) {
|
||||
}
|
||||
|
||||
/// Whether the client closed the connection without sending anything
|
||||
/// more: what the script reports after its answer.
|
||||
/// more: what a script asserts after its answer.
|
||||
fn nothing_more(stream: &mut Stream) -> bool {
|
||||
request(stream).is_none()
|
||||
}
|
||||
|
||||
/// The error `result` failed with, of `code`.
|
||||
#[track_caller]
|
||||
fn fails(result: Result<impl std::fmt::Debug, bakashrot_client::Error>, code: ErrorCode) {
|
||||
fn fails(
|
||||
result: Result<impl std::fmt::Debug, bakashrot_client::Error>,
|
||||
code: ErrorCode,
|
||||
) -> bakashrot_client::Error {
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(error.code(), code.code(), "{error}");
|
||||
error
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_answer_is_never_taken_for_the_next_request() {
|
||||
let (report, reported) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
assert!(matches!(request(stream), Some(Packet::PushMessage(_))));
|
||||
thread::sleep(Duration::from_millis(600));
|
||||
@@ -129,14 +143,13 @@ fn a_late_answer_is_never_taken_for_the_next_request() {
|
||||
&Packet::from(MessagePushed { message_id: 1 }).encode(),
|
||||
);
|
||||
let _ = stream.flush();
|
||||
report.send(nothing_more(stream)).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
client
|
||||
.set_answer_timeout(Duration::from_millis(200))
|
||||
.unwrap();
|
||||
let error = client.push("logs", "{}").unwrap_err();
|
||||
assert_eq!(error.code(), ErrorCode::ConnectionLost.code(), "{error}");
|
||||
let error = fails(client.push("logs", "{}"), ErrorCode::ConnectionLost);
|
||||
assert!(
|
||||
error.message().contains("no answer within 200ms"),
|
||||
"{error}"
|
||||
@@ -147,40 +160,35 @@ fn a_late_answer_is_never_taken_for_the_next_request() {
|
||||
thread::sleep(Duration::from_millis(700));
|
||||
fails(client.push("logs", "{}"), ErrorCode::NotConnected);
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
assert!(reported.recv().unwrap(), "the client sent something more");
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_answer_closes() {
|
||||
let (report, reported) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
assert!(matches!(request(stream), Some(Packet::PushMessage(_))));
|
||||
answer(stream, Pong {});
|
||||
report.send(nothing_more(stream)).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
fails(client.push("logs", "{}"), ErrorCode::ProtocolError);
|
||||
assert!(!client.is_open() && client.is_closed());
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
assert!(reported.recv().unwrap());
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_answer_closes() {
|
||||
let (report, reported) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
assert!(matches!(request(stream), Some(Packet::Ping(_))));
|
||||
// 0xc1 is never MessagePack.
|
||||
frame::write(stream, &[0xc1]).unwrap();
|
||||
stream.flush().unwrap();
|
||||
report.send(nothing_more(stream)).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
fails(client.ping(), ErrorCode::ProtocolError);
|
||||
fails(client.query("SELECT 1"), ErrorCode::NotConnected);
|
||||
assert!(reported.recv().unwrap());
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
@@ -217,8 +225,7 @@ fn a_refusal_keeps_the_connection() {
|
||||
answer(stream, MessagePushed { message_id: 7 });
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
let error = client.push("logs", "{}").unwrap_err();
|
||||
assert_eq!(error.code(), ErrorCode::NotAllowed.code());
|
||||
let error = fails(client.push("logs", "{}"), ErrorCode::NotAllowed);
|
||||
assert_eq!(error.message(), "not this topic");
|
||||
assert!(client.is_open() && !client.is_closed());
|
||||
client.ping().unwrap();
|
||||
@@ -287,19 +294,107 @@ fn a_connection_the_server_closed() {
|
||||
let mut client = fake.connect();
|
||||
let address = fake.address.clone();
|
||||
fake.finish();
|
||||
let mut waited = 0;
|
||||
while client.is_open() && waited < 50 {
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
waited += 1;
|
||||
}
|
||||
assert!(!client.is_open(), "{address}: still open");
|
||||
assert!(gone(&mut client), "{address}: still open");
|
||||
assert!(!client.is_open() && !client.is_closed());
|
||||
fails(client.ping(), ErrorCode::ConnectionLost);
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
}
|
||||
|
||||
/// Whether `is_open()` says closed within a second (what the fake sent
|
||||
/// on its way).
|
||||
fn gone(client: &mut Client) -> bool {
|
||||
for _ in 0..50 {
|
||||
if !client.is_open() {
|
||||
return true;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Sends what TLS holds, without waiting for anything back.
|
||||
fn send_tls(stream: &mut Stream) {
|
||||
while stream.conn.wants_write() {
|
||||
stream.conn.write_tls(&mut stream.sock).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS's close_notify, the socket kept open (as a proxy closing politely
|
||||
/// might): `is_open()` notices it from TLS alone, and keeps saying so.
|
||||
/// The next request fails as lost, those after as not connected.
|
||||
#[test]
|
||||
fn a_close_notify_is_noticed() {
|
||||
let (done, wait_done) = mpsc::channel::<()>();
|
||||
let fake = Fake::start(move |stream| {
|
||||
stream.conn.send_close_notify();
|
||||
send_tls(stream);
|
||||
// The socket open until the client looked.
|
||||
let _ = wait_done.recv();
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
assert!(gone(&mut client), "still open after close_notify");
|
||||
assert!(!client.is_open() && !client.is_open() && !client.is_closed());
|
||||
fails(client.ping(), ErrorCode::ConnectionLost);
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
done.send(()).unwrap();
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
/// An answer to no request: the connection is out of step, so
|
||||
/// `is_open()` closes it, and nothing more is sent.
|
||||
#[test]
|
||||
fn data_sent_unasked_closes() {
|
||||
let fake = Fake::start(move |stream| {
|
||||
answer(stream, Pong {});
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
assert!(gone(&mut client), "still open with data sent unasked");
|
||||
assert!(client.is_closed());
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
/// Bytes that aren't TLS (a record of no known type): broken, closed.
|
||||
#[test]
|
||||
fn a_broken_tls_stream_closes() {
|
||||
let fake = Fake::start(move |stream| {
|
||||
stream.sock.write_all(&[0x99, 3, 3, 0, 1, 0]).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
assert!(gone(&mut client), "still open with a broken TLS stream");
|
||||
assert!(client.is_closed());
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
/// What TLS sends for itself (a key update here, like the session
|
||||
/// tickets after the handshake) isn't data: `is_open()` reads it, stays
|
||||
/// open, and the next request works, under the new keys.
|
||||
#[test]
|
||||
fn tls_records_of_its_own_keep_it_open() {
|
||||
let (sent, wait_sent) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
stream.conn.refresh_traffic_keys().unwrap();
|
||||
send_tls(stream);
|
||||
sent.send(()).unwrap();
|
||||
assert!(matches!(request(stream), Some(Packet::Ping(_))));
|
||||
answer(stream, Pong {});
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
wait_sent.recv().unwrap();
|
||||
// The record on its way over loopback.
|
||||
thread::sleep(Duration::from_millis(200));
|
||||
for _ in 0..3 {
|
||||
assert!(client.is_open() && !client.is_closed());
|
||||
}
|
||||
client.ping().unwrap();
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_part_of_the_wrong_size_closes() {
|
||||
let (report, reported) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
assert!(matches!(request(stream), Some(Packet::GetAttachment(_))));
|
||||
answer(
|
||||
@@ -310,7 +405,7 @@ fn a_part_of_the_wrong_size_closes() {
|
||||
},
|
||||
);
|
||||
answer(stream, AttachmentPart { data: vec![1; 5] });
|
||||
report.send(nothing_more(stream)).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
let mut out = Vec::new();
|
||||
@@ -319,7 +414,6 @@ fn a_part_of_the_wrong_size_closes() {
|
||||
ErrorCode::ProtocolError,
|
||||
);
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
assert!(reported.recv().unwrap());
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
@@ -327,7 +421,6 @@ fn a_part_of_the_wrong_size_closes() {
|
||||
/// the next request's answers.
|
||||
#[test]
|
||||
fn a_refusal_among_the_parts_closes() {
|
||||
let (report, reported) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
assert!(matches!(request(stream), Some(Packet::GetAttachment(_))));
|
||||
answer(
|
||||
@@ -347,7 +440,7 @@ fn a_refusal_among_the_parts_closes() {
|
||||
stream,
|
||||
RequestRefused::new(ErrorCode::ServerError, "a disk"),
|
||||
);
|
||||
report.send(nothing_more(stream)).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
let mut out = Vec::new();
|
||||
@@ -356,7 +449,6 @@ fn a_refusal_among_the_parts_closes() {
|
||||
ErrorCode::ServerError,
|
||||
);
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
assert!(reported.recv().unwrap());
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
@@ -386,23 +478,21 @@ impl Seek for FailingSecondTime {
|
||||
/// for parts that won't come, the connection closes.
|
||||
#[test]
|
||||
fn a_source_failing_mid_upload_closes() {
|
||||
let (report, reported) = mpsc::channel();
|
||||
let fake = Fake::start(move |stream| {
|
||||
assert!(matches!(request(stream), Some(Packet::PushMessage(_))));
|
||||
answer(stream, Continue {});
|
||||
report.send(nothing_more(stream)).unwrap();
|
||||
assert!(nothing_more(stream), "the client sent something more");
|
||||
});
|
||||
let mut client = fake.connect();
|
||||
let mut source = FailingSecondTime {
|
||||
data: Cursor::new(vec![7; 100]),
|
||||
rewinds: 0,
|
||||
};
|
||||
let error = client
|
||||
.push_with_attachment("logs", "{}", &mut source)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.code(), ErrorCode::FileError.code(), "{error}");
|
||||
fails(
|
||||
client.push_with_attachment("logs", "{}", &mut source),
|
||||
ErrorCode::FileError,
|
||||
);
|
||||
assert!(!client.is_open() && client.is_closed());
|
||||
fails(client.ping(), ErrorCode::NotConnected);
|
||||
assert!(reported.recv().unwrap());
|
||||
fake.finish();
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ synchronous = "full"
|
||||
max_attachment_size = "1G" # bytes, or K M G T (1024-based); 0: none
|
||||
retention_interval = "1m" # how often old messages are deleted
|
||||
idle_database_connections = 8 # kept open once idle, for reads and as many for queries; closed after 1 min unused
|
||||
query_time_limit = "20s" # a client's query stopped (refused) past it; keep it under the clients' answer timeout (30 s)
|
||||
|
||||
# How long each topic's messages are kept, from when they were first
|
||||
# pushed: 100 years ("36500d") at most, or "forever". A topic takes its
|
||||
|
||||
@@ -108,6 +108,14 @@ pub struct Server {
|
||||
deserialize_with = "values::idle_connections"
|
||||
)]
|
||||
pub idle_database_connections: usize,
|
||||
/// How long a client's query may run before it's stopped and refused
|
||||
/// (`QueryTimedOut`); 20 s by default. Under the clients' answer timeout
|
||||
/// (30 s by default), so they get the refusal rather than give up.
|
||||
#[serde(
|
||||
default = "defaults::query_time_limit",
|
||||
deserialize_with = "values::duration"
|
||||
)]
|
||||
pub query_time_limit: Duration,
|
||||
}
|
||||
|
||||
/// How hard the database makes sure a push is on disk before answering it
|
||||
@@ -267,6 +275,9 @@ mod defaults {
|
||||
pub(crate) fn idle_database_connections() -> usize {
|
||||
8
|
||||
}
|
||||
pub(crate) fn query_time_limit() -> Duration {
|
||||
Duration::from_secs(20)
|
||||
}
|
||||
}
|
||||
|
||||
/// `[roles.*]`: each section's name is its role's, none twice.
|
||||
|
||||
@@ -60,6 +60,7 @@ fn defaults() {
|
||||
assert_eq!(server.max_attachment_size, 1 << 30);
|
||||
assert_eq!(server.retention_interval, Duration::from_secs(60));
|
||||
assert_eq!(server.idle_database_connections, 8);
|
||||
assert_eq!(server.query_time_limit, Duration::from_secs(20));
|
||||
assert_eq!(config.retention.age("logs"), None);
|
||||
assert_eq!(config.replication.retry_delay, Duration::from_secs(10));
|
||||
assert_eq!(config.replication.sync_interval, Duration::from_secs(5));
|
||||
@@ -77,6 +78,7 @@ synchronous = "NORMAL"
|
||||
max_attachment_size = 0
|
||||
retention_interval = "1h30m"
|
||||
idle_database_connections = 0
|
||||
query_time_limit = "2m"
|
||||
|
||||
[replication]
|
||||
push_to = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"]
|
||||
@@ -92,6 +94,7 @@ batch_size = 10000
|
||||
assert_eq!(config.server.max_attachment_size, 0);
|
||||
assert_eq!(config.server.retention_interval, Duration::from_secs(5400));
|
||||
assert_eq!(config.server.idle_database_connections, 0);
|
||||
assert_eq!(config.server.query_time_limit, Duration::from_secs(120));
|
||||
assert_eq!(config.replication.push_to.len(), 3);
|
||||
assert_eq!(config.replication.accept_from[2], "fd00::4");
|
||||
assert_eq!(config.replication.retry_delay, Duration::from_secs(60));
|
||||
@@ -306,6 +309,10 @@ fn refusals() {
|
||||
&with("idle_database_connections = -1\n"),
|
||||
"invalid value: integer `-1`",
|
||||
),
|
||||
(
|
||||
&with("query_time_limit = \"0s\"\n"),
|
||||
"'0s' isn't a duration",
|
||||
),
|
||||
// [retention]
|
||||
(
|
||||
&with("[retention]\nlogs = \"30\"\n"),
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
//! What to do about each:
|
||||
//! - reconnect, then retry: `NotConnected`, `ConnectFailed`,
|
||||
//! `ConnectionLost`, `ProtocolError` (the connection is closed);
|
||||
//! - retry later: `NotReady`, `ServerError`;
|
||||
//! - retry later: `NotReady`, `ServerError`, `QueryTimedOut` (or narrow
|
||||
//! the query);
|
||||
//! - fix the configuration: `AuthRejected`, `ServerNotVerified`,
|
||||
//! `NotAllowed`, `UnknownName`;
|
||||
//! - update one end: `VersionMismatch`;
|
||||
@@ -74,6 +75,7 @@ error_codes! {
|
||||
DataMismatch = 8, "An uploaded attachment that doesn't match its SHA-256: dropped.";
|
||||
QueryFailed = 9, "The SQL of a query failed (its error in the reason).";
|
||||
ServerError = 10, "The server couldn't store or read something: its database failed.";
|
||||
QueryTimedOut = 11, "A query ran past the server's time limit (query_time_limit) and was stopped: narrow it, or retry when the server is less busy.";
|
||||
|
||||
// The client's own.
|
||||
NotConnected = 100, "Not connected: never, or the connection was closed or lost before.";
|
||||
@@ -140,6 +142,7 @@ mod tests {
|
||||
(8, "DataMismatch"),
|
||||
(9, "QueryFailed"),
|
||||
(10, "ServerError"),
|
||||
(11, "QueryTimedOut"),
|
||||
(100, "NotConnected"),
|
||||
(101, "ConnectFailed"),
|
||||
(102, "AuthRejected"),
|
||||
|
||||
@@ -144,6 +144,17 @@ macro_rules! packets {
|
||||
Packet::$name(body)
|
||||
}
|
||||
}
|
||||
|
||||
/// The body of a packet of this type, or the packet back.
|
||||
impl TryFrom<Packet> for $name {
|
||||
type Error = Packet;
|
||||
fn try_from(packet: Packet) -> Result<$name, Packet> {
|
||||
match packet {
|
||||
Packet::$name(body) => Ok(body),
|
||||
other => Err(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
)*
|
||||
|
||||
impl Packet {
|
||||
|
||||
@@ -57,6 +57,16 @@ pub struct Head {
|
||||
pub last_id: u64,
|
||||
}
|
||||
|
||||
impl From<&Head> for Pair {
|
||||
/// Its pair: to ask the page after it.
|
||||
fn from(head: &Head) -> Pair {
|
||||
Pair {
|
||||
topic: head.topic.clone(),
|
||||
node: head.node.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An attachment the server lacks, and where to go on from.
|
||||
///
|
||||
/// `[topic, node, message_id, next_part]`
|
||||
|
||||
@@ -9,8 +9,8 @@ use bakashrot_proto::limits::{
|
||||
ATTACHMENT_PART_SIZE, MAX_HEADS_PER_PACKET, MAX_MESSAGE_SIZE, MAX_MISSING_ATTACHMENTS,
|
||||
};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, Continue, Head, MessagePushed, ReplicateAttachment, ReplicateMessages, SyncState,
|
||||
SyncStateRequest,
|
||||
Attachment, Continue, Head, MessagePushed, Pair, ReplicateAttachment, ReplicateMessages,
|
||||
SyncState, SyncStateRequest,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
@@ -124,24 +124,21 @@ pub(crate) async fn sync_state(
|
||||
return refusal;
|
||||
}
|
||||
let first = request.after.is_none();
|
||||
let mut after = request.after.map(|pair| (pair.topic, pair.node));
|
||||
let mut after = request.after;
|
||||
let (mut heads, mut more) = (Vec::new(), false);
|
||||
// Read in pages too, those it doesn't take from this peer skipped:
|
||||
// until the page is full and one more is found, or none is left.
|
||||
'pages: loop {
|
||||
let from = after.clone();
|
||||
let from = after.take();
|
||||
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)
|
||||
})
|
||||
.read(move |reader| reader.heads_after(from.as_ref(), MAX_HEADS_PER_PACKET))
|
||||
.await;
|
||||
let read: Vec<Head> = match read {
|
||||
Ok(read) => read,
|
||||
Err(refusal) => return refusal.into(),
|
||||
};
|
||||
let last_page = read.len() < MAX_HEADS_PER_PACKET;
|
||||
after = read.last().map(|h| (h.topic.clone(), h.node.clone()));
|
||||
after = read.last().map(Pair::from);
|
||||
for head in read {
|
||||
if peer.permissions.accepts(&head.topic, &head.node) {
|
||||
if heads.len() == MAX_HEADS_PER_PACKET {
|
||||
|
||||
@@ -109,7 +109,9 @@ async fn serve(shared: &Arc<Shared>, tcp: TcpStream, address: IpAddr) -> Result<
|
||||
}
|
||||
Packet::GetMessages(get) => get_messages(shared, &peer, get).await,
|
||||
Packet::ListNames(list) => list_names(shared, &peer, list).await,
|
||||
Packet::Query(query) => self::query(shared, &peer, query).await,
|
||||
Packet::Query(query) => self::query(shared, &peer, &mut frames, query)
|
||||
.await
|
||||
.map_err(failed)?,
|
||||
Packet::Ping(_) => Pong {}.into(),
|
||||
Packet::SyncStateRequest(request) => {
|
||||
accept_from::sync_state(shared, &mut peer, request).await
|
||||
@@ -546,16 +548,27 @@ async fn list_names(shared: &Arc<Shared>, peer: &Peer, list: ListNames) -> Packe
|
||||
.into()
|
||||
}
|
||||
|
||||
async fn query(shared: &Arc<Shared>, peer: &Peer, query: Query) -> Packet {
|
||||
/// A query's answer. Nothing comes while it runs: what does (the client
|
||||
/// closing, having given up) stops it and closes the connection.
|
||||
async fn query(
|
||||
shared: &Arc<Shared>,
|
||||
peer: &Peer,
|
||||
frames: &mut Frames,
|
||||
query: Query,
|
||||
) -> Result<Packet, String> {
|
||||
if !peer.permissions.can_query() {
|
||||
return refused(
|
||||
return Ok(refused(
|
||||
ErrorCode::NotAllowed,
|
||||
format!("{} may not run queries", peer.node),
|
||||
);
|
||||
));
|
||||
}
|
||||
match shared.query(query.sql).await {
|
||||
tokio::select! {
|
||||
answer = shared.query(query.sql) => Ok(match answer {
|
||||
Ok(json) => QueryResult { json }.into(),
|
||||
Err(refused) => refused.into(),
|
||||
}),
|
||||
// Dropping the query stops it.
|
||||
_ = frames.next() => Err("left while its query ran: stopped".into()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,10 +27,11 @@ use bakashrot_config::Config;
|
||||
use bakashrot_pki::{Revocations, SharedRevocations, summarize, tls};
|
||||
use bakashrot_proto::ErrorCode;
|
||||
use bakashrot_proto::packets::RequestRefused;
|
||||
use bakashrot_storage::{Database, QueryRunner, Reader};
|
||||
use bakashrot_storage::{Database, QueryRunner, Reader, Stop};
|
||||
use std::collections::HashSet;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
use tokio::net::TcpListener;
|
||||
@@ -73,6 +74,8 @@ struct Shared {
|
||||
readers: Pool<Reader>,
|
||||
/// Query connections not in use.
|
||||
queries: Pool<QueryRunner>,
|
||||
/// Clients' queries running now.
|
||||
queries_running: AtomicUsize,
|
||||
/// The replicated attachments being received (topic, node, message
|
||||
/// id): one peer at a time each (`accept_from.rs`).
|
||||
receiving: Mutex<HashSet<(String, String, u64)>>,
|
||||
@@ -117,6 +120,7 @@ impl Server {
|
||||
pushes,
|
||||
readers: Pool::new(),
|
||||
queries: Pool::new(),
|
||||
queries_running: AtomicUsize::new(0),
|
||||
receiving: Mutex::new(HashSet::new()),
|
||||
config,
|
||||
});
|
||||
@@ -185,6 +189,13 @@ impl Server {
|
||||
self.shared.pushes.stop().await;
|
||||
}
|
||||
|
||||
/// How many clients' queries are running now: each until it's
|
||||
/// answered, stopped past `query_time_limit`, or stopped as its client
|
||||
/// leaves.
|
||||
pub fn queries_running(&self) -> usize {
|
||||
self.shared.queries_running.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Reloads the CRL file now: how many certificates it revokes.
|
||||
pub fn reload_revocations(&self) -> Result<usize, String> {
|
||||
let shared = &self.shared;
|
||||
@@ -226,12 +237,21 @@ impl Shared {
|
||||
Ok(sha256)
|
||||
}
|
||||
|
||||
/// Runs a client's SQL on a query connection, off the async threads.
|
||||
/// Runs a client's SQL on a query connection, off the async threads:
|
||||
/// stopped past `query_time_limit`, or once this future is dropped
|
||||
/// (its client left), not left running on its thread.
|
||||
async fn query(self: &Arc<Self>, sql: String) -> Result<String, RequestRefused> {
|
||||
let stop = Stop::new();
|
||||
let _stop_if_dropped = StopOnDrop(stop.clone());
|
||||
let limit = self.config.server.query_time_limit;
|
||||
let shared = self.clone();
|
||||
self.pooled(
|
||||
|shared| &shared.queries,
|
||||
Database::query_runner,
|
||||
move |runner: &QueryRunner| runner.run(&sql),
|
||||
move |runner: &QueryRunner| {
|
||||
let _running = Counted::new(&shared.queries_running);
|
||||
runner.run_limited(&sql, limit, &stop)
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -260,6 +280,31 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops a query when dropped: answered by then, or its client gone.
|
||||
struct StopOnDrop(Stop);
|
||||
|
||||
impl Drop for StopOnDrop {
|
||||
fn drop(&mut self) {
|
||||
self.0.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts one in its counter while it lives (a panic included).
|
||||
struct Counted<'a>(&'a AtomicUsize);
|
||||
|
||||
impl<'a> Counted<'a> {
|
||||
fn new(counter: &'a AtomicUsize) -> Counted<'a> {
|
||||
counter.fetch_add(1, Ordering::Relaxed);
|
||||
Counted(counter)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Counted<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
@@ -296,14 +341,12 @@ impl<C> Pool<C> {
|
||||
|
||||
/// 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
|
||||
};
|
||||
let stale: Vec<(C, Instant)> = self
|
||||
.lock()
|
||||
.extract_if(.., |(_, since)| {
|
||||
now.saturating_duration_since(*since) >= idle_for
|
||||
})
|
||||
.collect();
|
||||
drop(stale);
|
||||
}
|
||||
|
||||
@@ -362,6 +405,7 @@ fn refusal(error: bakashrot_storage::Error) -> RequestRefused {
|
||||
Error::UnknownName(_) => ErrorCode::UnknownName,
|
||||
Error::TooBig(_) => ErrorCode::TooBig,
|
||||
Error::Query(_) => ErrorCode::QueryFailed,
|
||||
Error::QueryTimedOut(_) => ErrorCode::QueryTimedOut,
|
||||
Error::Sqlite(_) | Error::Unusable(_) | Error::RolledBack => {
|
||||
warn!("the database: {error}");
|
||||
return server_error("the database failed");
|
||||
|
||||
@@ -168,34 +168,31 @@ impl Link {
|
||||
/// 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 first = self.sync_page(None).await?;
|
||||
let (mut heads, mut more) = (std::mem::take(&mut first.heads), first.more);
|
||||
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,
|
||||
};
|
||||
let after = heads.last().filter(|_| more).map(Pair::from);
|
||||
theirs.extend(
|
||||
page.heads
|
||||
.drain(..)
|
||||
heads
|
||||
.into_iter()
|
||||
.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));
|
||||
let Some(after) = after else {
|
||||
return Ok((first, theirs));
|
||||
};
|
||||
let page = self.sync_page(Some(after)).await?;
|
||||
(heads, more) = (page.heads, page.more);
|
||||
}
|
||||
}
|
||||
|
||||
/// A page of its `SyncState`, after the pair `after`.
|
||||
async fn sync_page(&mut self, after: Option<Pair>) -> Result<SyncState, String> {
|
||||
match self.ask(SyncStateRequest { after }.into()).await? {
|
||||
Packet::SyncState(page) => Ok(page),
|
||||
Packet::RequestRefused(refused) => Err(format!("refused: {}", refused.reason)),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether it takes `node`'s messages in `topic` (its `SyncState`) and
|
||||
@@ -323,18 +320,16 @@ impl Link {
|
||||
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(());
|
||||
}
|
||||
while left > keepalive {
|
||||
sleep(keepalive).await;
|
||||
left -= keepalive;
|
||||
match self.ask(Ping {}.into()).await? {
|
||||
Packet::Pong(_) => {}
|
||||
other => return Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
sleep(left).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ask(&mut self, packet: Packet) -> Result<Packet, String> {
|
||||
@@ -375,11 +370,10 @@ async fn check_own_copy(
|
||||
.hash_parts(attachment_id, 0..attachment.part_count())
|
||||
.await
|
||||
.map(|sha256| sha256.finish().as_ref() == attachment.sha256);
|
||||
match judge(&read) {
|
||||
match judge(read) {
|
||||
OwnCopy::Intact => return,
|
||||
OwnCopy::Damaged => {}
|
||||
OwnCopy::Unknown => {
|
||||
let why = read.err().map(|refused| refused.reason).unwrap_or_default();
|
||||
OwnCopy::Unknown(why) => {
|
||||
warn!(
|
||||
"{message}: this server's copy of its attachment couldn't be read back ({why}): \
|
||||
kept, checked again when a peer refuses it again"
|
||||
@@ -406,20 +400,21 @@ enum OwnCopy {
|
||||
/// Read whole and not matching, or a part missing: dropped and asked
|
||||
/// for again.
|
||||
Damaged,
|
||||
/// The read failed (the database busy, a connection not opened...):
|
||||
/// nothing is known, the copy is kept. Dropping it then could lose the
|
||||
/// only one there is (this server the attachment's origin).
|
||||
Unknown,
|
||||
/// The read failed (the database busy, a connection not opened...),
|
||||
/// saying why: nothing is known, the copy is kept. Dropping it then
|
||||
/// could lose the only one there is (this server the attachment's
|
||||
/// origin).
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
/// The verdict on a read-back: whether its SHA-256 matched, or why it
|
||||
/// failed.
|
||||
fn judge(read: &Result<bool, RequestRefused>) -> OwnCopy {
|
||||
fn judge(read: Result<bool, RequestRefused>) -> OwnCopy {
|
||||
match read {
|
||||
Ok(true) => OwnCopy::Intact,
|
||||
Ok(false) => OwnCopy::Damaged,
|
||||
Err(refused) if refused.code == ErrorCode::NotFound.code() => OwnCopy::Damaged,
|
||||
Err(_) => OwnCopy::Unknown,
|
||||
Err(refused) => OwnCopy::Unknown(refused.reason),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,12 +434,13 @@ mod tests {
|
||||
#[test]
|
||||
fn only_a_copy_read_whole_or_missing_a_part_is_damaged() {
|
||||
let refused = |code| Err(RequestRefused::new(code, "why"));
|
||||
assert_eq!(judge(&Ok(true)), OwnCopy::Intact);
|
||||
assert_eq!(judge(&Ok(false)), OwnCopy::Damaged);
|
||||
let unknown = || OwnCopy::Unknown("why".into());
|
||||
assert_eq!(judge(Ok(true)), OwnCopy::Intact);
|
||||
assert_eq!(judge(Ok(false)), OwnCopy::Damaged);
|
||||
// A part missing (read_part's NotFound): damaged too.
|
||||
assert_eq!(judge(&refused(ErrorCode::NotFound)), OwnCopy::Damaged);
|
||||
// A read that failed says nothing about the copy: kept.
|
||||
assert_eq!(judge(&refused(ErrorCode::ServerError)), OwnCopy::Unknown);
|
||||
assert_eq!(judge(&refused(ErrorCode::InvalidRequest)), OwnCopy::Unknown);
|
||||
assert_eq!(judge(refused(ErrorCode::NotFound)), OwnCopy::Damaged);
|
||||
// A read that failed says nothing about the copy: kept, saying why.
|
||||
assert_eq!(judge(refused(ErrorCode::ServerError)), unknown());
|
||||
assert_eq!(judge(refused(ErrorCode::InvalidRequest)), unknown());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,12 +195,9 @@ fn write(writer: &mut Writer, group: Vec<(Write, oneshot::Sender<Outcome>)>) {
|
||||
}
|
||||
let mut outcomes = Vec::with_capacity(group.len());
|
||||
let committed = writer.batch(|batch| {
|
||||
// SQLite rolling the group back (a full disk...) fails the batch:
|
||||
// every write in it is refused below, none stored.
|
||||
for (write, _) in &group {
|
||||
// SQLite rolled the group back (a full disk...): the batch
|
||||
// fails, every write in it is refused below, none stored.
|
||||
if batch.is_rolled_back() {
|
||||
break;
|
||||
}
|
||||
outcomes.push(write.run(batch).map_err(refusal));
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -265,6 +265,60 @@ fn no_idle_database_connections() {
|
||||
assert_eq!(json, r#"{"columns":["n"],"rows":[["3"]]}"#);
|
||||
}
|
||||
|
||||
/// A query that never ends.
|
||||
const FOREVER: &str =
|
||||
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n";
|
||||
|
||||
/// Past `query_time_limit`, a query is stopped and refused, the connection
|
||||
/// kept; a client giving up first (its answer timeout) closes, and its
|
||||
/// query is stopped then.
|
||||
#[test]
|
||||
fn queries_are_stopped() {
|
||||
let running = Running::start_with("query-time-limit", "query_time_limit = \"1s\"\n");
|
||||
let analyst = running.issue("analyst-1", &["analyst"]);
|
||||
let mut client = running.connect(&analyst).unwrap();
|
||||
let started = Instant::now();
|
||||
let error = client.query(FOREVER).unwrap_err();
|
||||
let took = started.elapsed();
|
||||
assert_eq!(error.code(), ErrorCode::QueryTimedOut.code(), "{error}");
|
||||
assert!(
|
||||
error
|
||||
.message()
|
||||
.contains("stopped after 1s, the server's time limit"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
took >= Duration::from_secs(1) && took < Duration::from_secs(5),
|
||||
"{took:?}"
|
||||
);
|
||||
assert_eq!(running.server.queries_running(), 0);
|
||||
assert_eq!(
|
||||
client.query("SELECT 1 AS one").unwrap(),
|
||||
r#"{"columns":["one"],"rows":[["1"]]}"#
|
||||
);
|
||||
|
||||
// The client gives up long before the server's limit.
|
||||
let running = Running::start_with("query-left", "query_time_limit = \"1h\"\n");
|
||||
let mut client = running
|
||||
.connect(&running.issue("analyst-1", &["analyst"]))
|
||||
.unwrap();
|
||||
client
|
||||
.set_answer_timeout(Duration::from_millis(300))
|
||||
.unwrap();
|
||||
let error = client.query(FOREVER).unwrap_err();
|
||||
assert_eq!(code(error), ErrorCode::ConnectionLost.code());
|
||||
assert!(client.is_closed());
|
||||
wait_for("its query stopped", || {
|
||||
running.server.queries_running() == 0
|
||||
});
|
||||
// Its connection is closed; the next one is answered.
|
||||
let mut client = running
|
||||
.connect(&running.issue("analyst-2", &["analyst"]))
|
||||
.unwrap();
|
||||
assert!(client.query("SELECT 1").is_ok());
|
||||
assert_eq!(running.server.queries_running(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refusals_keep_the_connection() {
|
||||
let running = Running::start("refusals");
|
||||
@@ -1542,14 +1596,6 @@ fn add_pairs(path: &std::path::Path, prefix: &str, count: usize) {
|
||||
.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
|
||||
@@ -1589,7 +1635,7 @@ fn sync_state_in_pages() {
|
||||
(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()));
|
||||
let second = sync_page(&mut peer, first.heads.last().map(Pair::from));
|
||||
assert!(!second.more);
|
||||
assert!(second.topics.is_empty() && second.nodes.is_empty() && second.missing.is_empty());
|
||||
let mut both = triples(&first.heads);
|
||||
@@ -1613,7 +1659,7 @@ fn sync_state_in_pages() {
|
||||
"b000005"
|
||||
);
|
||||
// After the very last: nothing, nothing more.
|
||||
let end = sync_page(&mut peer, after(second.heads.last().unwrap()));
|
||||
let end = sync_page(&mut peer, second.heads.last().map(Pair::from));
|
||||
assert!(end.heads.is_empty() && !end.more);
|
||||
|
||||
// A peer taking only "b": the others are skipped, not counted. Exactly
|
||||
@@ -1628,7 +1674,7 @@ fn sync_state_in_pages() {
|
||||
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()));
|
||||
let second = sync_page(&mut picky, first.heads.last().map(Pair::from));
|
||||
assert!(!second.more);
|
||||
assert_eq!(
|
||||
triples(&second.heads),
|
||||
|
||||
@@ -64,8 +64,8 @@ impl Batch<'_> {
|
||||
}
|
||||
|
||||
/// Whether SQLite rolled the transaction back by itself: nothing more
|
||||
/// may run in it.
|
||||
pub fn is_rolled_back(&self) -> bool {
|
||||
/// may run in it, every operation is refused ([`Error::RolledBack`]).
|
||||
fn is_rolled_back(&self) -> bool {
|
||||
self.transaction.is_autocommit()
|
||||
}
|
||||
|
||||
|
||||
@@ -148,7 +148,7 @@ impl Database {
|
||||
AuthAction::Pragma { .. } => Authorization::Deny,
|
||||
_ => Authorization::Allow,
|
||||
}))?;
|
||||
Ok(QueryRunner::new(connection))
|
||||
QueryRunner::new(connection)
|
||||
}
|
||||
|
||||
/// A connection with this database's settings: WAL, `synchronous`, the
|
||||
|
||||
@@ -22,7 +22,7 @@ mod reader;
|
||||
|
||||
pub use batch::{Batch, Writer};
|
||||
pub use database::{Checkpointer, Database, WRITER_CHECKPOINT_PAGES};
|
||||
pub use query::{MAX_QUERY_BYTES, MAX_QUERY_ROWS, QueryRunner};
|
||||
pub use query::{MAX_QUERY_BYTES, MAX_QUERY_ROWS, QueryRunner, Stop};
|
||||
pub use reader::{Attachment, MESSAGES_BYTES, Reader};
|
||||
|
||||
use bakashrot_proto::limits::{MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID};
|
||||
@@ -55,6 +55,8 @@ pub enum Error {
|
||||
TooBig(String),
|
||||
/// A client's query that failed or isn't read-only: `QueryFailed`.
|
||||
Query(String),
|
||||
/// A client's query stopped past its time limit: `QueryTimedOut`.
|
||||
QueryTimedOut(String),
|
||||
/// SQLite rolled the batch's transaction back by itself (disk full,
|
||||
/// an I/O error...): nothing in it is stored, and nothing more runs in
|
||||
/// it (it would be written outside the transaction): `ServerError`.
|
||||
@@ -73,7 +75,8 @@ impl fmt::Display for Error {
|
||||
| Error::NotFound(what)
|
||||
| Error::UnknownName(what)
|
||||
| Error::TooBig(what)
|
||||
| Error::Query(what) => f.write_str(what),
|
||||
| Error::Query(what)
|
||||
| Error::QueryTimedOut(what) => f.write_str(what),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,12 +9,20 @@
|
||||
//! connection, `query_only` included, before the statement is looked
|
||||
//! at. The result is JSON, every value a string or null:
|
||||
//! `{"columns":[...],"rows":[[...],...]}`.
|
||||
//!
|
||||
//! A query can be stopped while it runs ([`QueryRunner::run_limited`]):
|
||||
//! past a time limit, or from another thread ([`Stop`]: its client left).
|
||||
//! SQLite looks every few thousand steps (its progress handler) and ends
|
||||
//! the statement there.
|
||||
|
||||
use crate::{Error, Result};
|
||||
use bakashrot_proto::limits::MAX_MESSAGE_SIZE;
|
||||
use rusqlite::Connection;
|
||||
use rusqlite::types::ValueRef;
|
||||
use serde_json::Value;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The most rows a query returns, as before.
|
||||
pub const MAX_QUERY_ROWS: usize = 10_000;
|
||||
@@ -22,22 +30,111 @@ pub const MAX_QUERY_ROWS: usize = 10_000;
|
||||
/// The biggest result, in bytes of JSON: what a packet carries.
|
||||
pub const MAX_QUERY_BYTES: usize = MAX_MESSAGE_SIZE;
|
||||
|
||||
/// How many of SQLite's steps between two looks at the time limit and the
|
||||
/// [`Stop`]: about a tenth of a millisecond.
|
||||
const STEPS_BETWEEN_LOOKS: i32 = 10_000;
|
||||
|
||||
/// Stops a query run with [`QueryRunner::run_limited`], from any thread:
|
||||
/// within a few steps, refused then ([`Error::Query`], "stopped while it
|
||||
/// ran"). Clones stop the same query.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Stop(Arc<AtomicBool>);
|
||||
|
||||
impl Stop {
|
||||
/// Not stopped yet.
|
||||
pub fn new() -> Stop {
|
||||
Stop::default()
|
||||
}
|
||||
|
||||
/// Stops the query now, or as soon as it starts.
|
||||
pub fn stop(&self) {
|
||||
self.0.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Whether [`Stop::stop`] was called.
|
||||
pub fn is_stopped(&self) -> bool {
|
||||
self.0.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the progress handler looks at during a query.
|
||||
#[derive(Debug, Default)]
|
||||
struct Watch {
|
||||
/// The deadline and the limit it came from: none past `Instant`'s end.
|
||||
limit: Option<(Instant, Duration)>,
|
||||
stop: Stop,
|
||||
/// Why it was interrupted, once it was: the refusal.
|
||||
interrupted: Option<Error>,
|
||||
}
|
||||
|
||||
impl Watch {
|
||||
/// Whether to interrupt the query now, and why.
|
||||
fn look(&mut self) -> bool {
|
||||
if self.interrupted.is_some() {
|
||||
return true;
|
||||
}
|
||||
let why = if self.stop.is_stopped() {
|
||||
Error::Query("stopped while it ran".to_owned())
|
||||
} else {
|
||||
match self.limit {
|
||||
Some((deadline, limit)) if Instant::now() >= deadline => Error::QueryTimedOut(
|
||||
format!("stopped after {limit:?}, the server's time limit: narrow the query"),
|
||||
),
|
||||
_ => return false,
|
||||
}
|
||||
};
|
||||
self.interrupted = Some(why);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// A read-only connection for clients' queries.
|
||||
#[derive(Debug)]
|
||||
pub struct QueryRunner {
|
||||
connection: Connection,
|
||||
watch: Arc<Mutex<Watch>>,
|
||||
}
|
||||
|
||||
fn lock(watch: &Mutex<Watch>) -> std::sync::MutexGuard<'_, Watch> {
|
||||
watch.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
impl QueryRunner {
|
||||
pub(crate) fn new(connection: Connection) -> QueryRunner {
|
||||
QueryRunner { connection }
|
||||
pub(crate) fn new(mut connection: Connection) -> Result<QueryRunner> {
|
||||
let watch = Arc::new(Mutex::new(Watch::default()));
|
||||
let looking = watch.clone();
|
||||
connection.progress_handler(STEPS_BETWEEN_LOOKS, Some(move || lock(&looking).look()))?;
|
||||
Ok(QueryRunner { connection, watch })
|
||||
}
|
||||
|
||||
/// Runs one read-only statement: its result as JSON. Refused
|
||||
/// ([`Error::Query`]) if it isn't one, or fails (SQLite's message, a
|
||||
/// failing row included: never a partial result); [`Error::TooBig`]
|
||||
/// past [`MAX_QUERY_ROWS`] or [`MAX_QUERY_BYTES`].
|
||||
/// past [`MAX_QUERY_ROWS`] or [`MAX_QUERY_BYTES`]. No time limit.
|
||||
pub fn run(&self, sql: &str) -> Result<String> {
|
||||
self.run_limited(sql, Duration::MAX, &Stop::new())
|
||||
}
|
||||
|
||||
/// [`QueryRunner::run`], stopped past `time_limit`
|
||||
/// ([`Error::QueryTimedOut`]) or by `stop` ([`Error::Query`]).
|
||||
pub fn run_limited(&self, sql: &str, time_limit: Duration, stop: &Stop) -> Result<String> {
|
||||
*lock(&self.watch) = Watch {
|
||||
limit: Instant::now()
|
||||
.checked_add(time_limit)
|
||||
.map(|deadline| (deadline, time_limit)),
|
||||
stop: stop.clone(),
|
||||
interrupted: None,
|
||||
};
|
||||
let result = self.query(sql);
|
||||
let interrupted = std::mem::take(&mut *lock(&self.watch)).interrupted;
|
||||
match (result, interrupted) {
|
||||
// Interrupted, whatever SQLite made of it.
|
||||
(Err(_), Some(why)) => Err(why),
|
||||
(result, _) => result,
|
||||
}
|
||||
}
|
||||
|
||||
fn query(&self, sql: &str) -> Result<String> {
|
||||
let failed = |error: rusqlite::Error| Error::Query(explain(error.to_string()));
|
||||
let mut statement = self.connection.prepare(sql).map_err(failed)?;
|
||||
if !statement.readonly() || statement.column_count() == 0 {
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::{
|
||||
};
|
||||
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, ReplicatedMessage,
|
||||
Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, Pair, ReplicatedMessage,
|
||||
StoredAttachment,
|
||||
};
|
||||
use rusqlite::{Connection, OptionalExtension, Row, params};
|
||||
@@ -169,9 +169,9 @@ impl Reader {
|
||||
/// 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>> {
|
||||
pub fn heads_after(&self, after: Option<&Pair>, limit: usize) -> Result<Vec<Head>> {
|
||||
// No name is empty: ("", "") comes before every pair.
|
||||
let (topic, node) = after.unwrap_or(("", ""));
|
||||
let (topic, node) = after.map_or(("", ""), |pair| (&pair.topic, &pair.node));
|
||||
let limit = i64::try_from(limit).unwrap_or(i64::MAX);
|
||||
self.connection
|
||||
.prepare_cached(
|
||||
|
||||
@@ -3,10 +3,11 @@
|
||||
|
||||
use bakashrot_config::Synchronous;
|
||||
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID};
|
||||
use bakashrot_proto::packets::{Attachment as Sent, ReplicatedMessage};
|
||||
use bakashrot_storage::{AttachmentState, Database, Error, MAX_QUERY_ROWS, MAX_STREAMS};
|
||||
use bakashrot_proto::packets::{Attachment as Sent, Pair, ReplicatedMessage};
|
||||
use bakashrot_storage::{AttachmentState, Database, Error, MAX_QUERY_ROWS, MAX_STREAMS, Stop};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const PART: usize = ATTACHMENT_PART_SIZE as usize;
|
||||
|
||||
@@ -174,9 +175,13 @@ fn pushing_and_reading() {
|
||||
]
|
||||
);
|
||||
// In pages: after a pair (its names without case), so many at most.
|
||||
let page = |after, limit| -> Vec<_> {
|
||||
let page = |after: Option<(&str, &str)>, limit| -> Vec<_> {
|
||||
let after = after.map(|(topic, node)| Pair {
|
||||
topic: topic.into(),
|
||||
node: node.into(),
|
||||
});
|
||||
reader
|
||||
.heads_after(after, limit)
|
||||
.heads_after(after.as_ref(), limit)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|h| (h.topic, h.node))
|
||||
@@ -754,6 +759,58 @@ fn queries() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queries_are_stopped() {
|
||||
let (database, _) = open("stopped-queries");
|
||||
let _writer = database.writer().unwrap();
|
||||
let runner = database.query_runner().unwrap();
|
||||
let forever =
|
||||
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n";
|
||||
let refused = |result: bakashrot_storage::Result<String>| match result {
|
||||
Err(Error::Query(why)) => why,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
|
||||
// Past its time limit.
|
||||
let started = Instant::now();
|
||||
let why = match runner.run_limited(forever, Duration::from_millis(200), &Stop::new()) {
|
||||
Err(Error::QueryTimedOut(why)) => why,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let took = started.elapsed();
|
||||
assert!(why.contains("200ms, the server's time limit"), "{why}");
|
||||
assert!(
|
||||
took >= Duration::from_millis(200) && took < Duration::from_secs(5),
|
||||
"{took:?}"
|
||||
);
|
||||
|
||||
// From another thread, long before its time limit.
|
||||
let stop = Stop::new();
|
||||
let stopping = stop.clone();
|
||||
let started = Instant::now();
|
||||
let thread = std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
stopping.stop();
|
||||
});
|
||||
let why = refused(runner.run_limited(forever, Duration::from_secs(3600), &stop));
|
||||
thread.join().unwrap();
|
||||
assert_eq!(why, "stopped while it ran");
|
||||
assert!(started.elapsed() < Duration::from_secs(5));
|
||||
// Stopped before it starts: at its first look.
|
||||
refused(runner.run_limited(forever, Duration::from_secs(3600), &stop));
|
||||
|
||||
// The next queries aren't: the connection is as before.
|
||||
let short = "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 100000) SELECT count(*) FROM n";
|
||||
let counted = r#"{"columns":["count(*)"],"rows":[["100000"]]}"#;
|
||||
assert_eq!(
|
||||
runner
|
||||
.run_limited(short, Duration::from_secs(60), &Stop::new())
|
||||
.unwrap(),
|
||||
counted
|
||||
);
|
||||
assert_eq!(runner.run(short).unwrap(), counted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_view_reads_by_key_range() {
|
||||
let (database, path) = open("plans");
|
||||
|
||||
@@ -7,7 +7,7 @@ mod cert;
|
||||
|
||||
use bakashrot_client::{Client, Error, Settings};
|
||||
use bakashrot_proto::error::{code_name, is_refusal_code};
|
||||
use bakashrot_proto::limits::{KEEPALIVE_SECS, MAX_MESSAGES_PER_PACKET};
|
||||
use bakashrot_proto::limits::MAX_MESSAGES_PER_PACKET;
|
||||
use bakashrot_proto::packets::{MessageEntry, NameKind};
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
use serde::Deserialize;
|
||||
@@ -266,7 +266,10 @@ fn run(config: &Path, command: Command) -> Result<(), String> {
|
||||
break;
|
||||
}
|
||||
if !batch.more {
|
||||
wait(&mut client, Duration::from_millis(interval))?;
|
||||
// Pinging meanwhile: `--interval` goes up to 1 h.
|
||||
client
|
||||
.wait(Duration::from_millis(interval))
|
||||
.map_err(failed)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -317,22 +320,6 @@ fn run(config: &Path, command: Command) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Waits `duration`, pinging every `KEEPALIVE_SECS` meanwhile: the server
|
||||
/// closes a connection silent for 5 min, and `--interval` goes up to 1 h.
|
||||
fn wait(client: &mut Client, duration: Duration) -> Result<(), String> {
|
||||
let keepalive = Duration::from_secs(KEEPALIVE_SECS);
|
||||
let mut left = duration;
|
||||
loop {
|
||||
let step = left.min(keepalive);
|
||||
std::thread::sleep(step);
|
||||
left -= step;
|
||||
if left.is_zero() {
|
||||
return Ok(());
|
||||
}
|
||||
client.ping().map_err(failed)?;
|
||||
}
|
||||
}
|
||||
|
||||
/// A topic and node's latest message, if any.
|
||||
fn latest(client: &mut Client, topic: &str, node: &str) -> Result<Option<MessageEntry>, String> {
|
||||
let latest = client.get_messages(topic, node, None, 1).map_err(failed)?;
|
||||
|
||||
+33
-8
@@ -37,11 +37,20 @@ works; Python and C# go through it.
|
||||
|
||||
- `set_answer_timeout()`: how long an answer, or sending a packet, may
|
||||
take: 30 s (`ANSWER_TIMEOUT`) until changed, more than 0. Longer for a
|
||||
slow query, say.
|
||||
- `is_open()`: false once closed; it looks at the socket without
|
||||
blocking, then always makes it blocking again (it was left
|
||||
non-blocking when it found the connection gone).
|
||||
slow query, say (the server's own limit, `query_time_limit`, is 20 s
|
||||
by default: `config.md`). Giving up closes the connection, and the
|
||||
server stops the query it was running then.
|
||||
- `is_open()` (`&mut self`): false once closed. It reads what's waiting
|
||||
without blocking, through TLS, then always makes the socket blocking
|
||||
again (it was left non-blocking when it found the connection gone).
|
||||
What TLS sends for itself (session tickets, key updates) leaves it
|
||||
open; the socket's end or TLS's close_notify says the server closed it
|
||||
(the next request fails with `ConnectionLost`); data sent unasked or a
|
||||
broken TLS stream leave it out of step, so it's closed (`NotConnected`
|
||||
after).
|
||||
- `ping()`: keeps an idle connection open (`protocol.md`, "Rules").
|
||||
`wait()` sleeps, pinging every `KEEPALIVE_SECS` meanwhile (the
|
||||
tool's `--follow` uses it).
|
||||
|
||||
## Who connects: certificates
|
||||
|
||||
@@ -102,6 +111,7 @@ a client's, or an enumeration's for the enumeration getters.
|
||||
| `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 |
|
||||
| `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 |
|
||||
| `SetAnswerTimeout(Milliseconds)`, `GetAnswerTimeout` | how long an answer may take: 30000 until changed, more than 0 (`InvalidArgument`). Kept across connections, and applied to the current one too (unlike the other settings). Past it, `ConnectionLost`, the connection closed and the server's query stopped |
|
||||
| `GetNode` (`A`/`W`) | the node the server says this client is |
|
||||
| `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 |
|
||||
@@ -149,6 +159,8 @@ on 3.8), `client.node` once connected, `push(data, topic,
|
||||
attachment=None)` (the topic required; the attachment bytes or a path),
|
||||
`latest()`, `get_messages()`, `iter_messages()`, `follow()` (pinging
|
||||
every minute while it waits longer), `ping()` (`KEEPALIVE_SECONDS`),
|
||||
`answer_timeout` (seconds, `ANSWER_TIMEOUT_SECONDS` until set; before
|
||||
connecting or while connected),
|
||||
`get_attachment()` (bytes), `save_attachment()` (a file),
|
||||
`list_topics()` / `list_nodes()` (names; `topic=` and `node=`, a name or
|
||||
a pattern each, filter them: `list_topics(node="kitchen")` the topics
|
||||
@@ -194,6 +206,7 @@ using (Client client = new Client("10.0.0.2", 7000, "ca.crt", "kitchen.crt", "ki
|
||||
data[, byte[]])`, `PushFile(topic, data, path)`, `Latest()` (null if
|
||||
none), `GetMessages()` (a `MessagesPage`), `IterMessages()`, `Follow()`
|
||||
(pinging every minute while it waits longer), `Ping()` (`KeepAliveMs`),
|
||||
`AnswerTimeoutMs` (`DefaultAnswerTimeoutMs` until set),
|
||||
`GetAttachment()` (bytes), `SaveAttachment()` (a file), `ListTopics()` /
|
||||
`ListNodes()` / `Query()` (the library's JSON, as a string: parsing it
|
||||
is the app's; `ListTopics(topic, node)` / `ListNodes(topic, node)`
|
||||
@@ -275,8 +288,11 @@ wrong size, a refusal among the parts, a source failing mid-upload, a
|
||||
connection the server closed (each: closed, `NotConnected` after,
|
||||
nothing more sent); a refusal and an argument refused before sending
|
||||
keeping it; a longer timeout waiting for a slow answer; `is_open()`
|
||||
leaving it blocking. Each closing path broken on purpose once: the
|
||||
tests caught it.
|
||||
leaving it blocking, noticing a close_notify with the socket still open,
|
||||
closing on data sent unasked or a broken TLS stream, and staying open
|
||||
past a key update (the next request under the new keys). Each closing
|
||||
path broken on purpose once: the tests caught it (`is_open()` five ways,
|
||||
2026-11-20, the old socket peek among them).
|
||||
|
||||
`crates/bakashrot-capi/tests/`, each against a server on a free port:
|
||||
|
||||
@@ -288,12 +304,20 @@ tests caught it.
|
||||
- `exports.rs`, `clients`: two clients at once, each with its own answers
|
||||
and errors; bad and freed handles; 4 threads on 4 clients; a client
|
||||
freed while another thread uses it.
|
||||
- `exports.rs`, `answer_timeouts`: the answer timeout refused at 0 or
|
||||
less, kept across connections; a query past it `ConnectionLost`.
|
||||
- `codes.rs`: Python's, C#'s and PureBasic's error codes are the
|
||||
protocol's (`error.rs`), every one by the same number and name; the
|
||||
values Python and C# copy (the answer timeout, the keepalive,
|
||||
`MAX_GET_MESSAGES`) are the Rust side's.
|
||||
- `python.rs`: runs `bindings/python/check_bakashrot.py` on the DLL (two
|
||||
`Client`s at once, too); skipped, saying so, without Python 3.11+.
|
||||
- PureBasic, by hand (no PureBasic in CI): run
|
||||
`BakaShrot_Client_Prototypes.pbi` directly, `ClientExample <DllPath>
|
||||
<CaFile> <CertificateFile> <KeyFile> <Host> <Port>`. Passed 2026-11-17
|
||||
with PureBasic 5.73 LTS and 6.41 (C backend), x64.
|
||||
with PureBasic 5.73 LTS and 6.41 (C backend), x64. 2026-11-20, both
|
||||
again: the answer timeout exports and `QueryTimedOut` (11) through
|
||||
the DLL against a server with `query_time_limit = "1s"`.
|
||||
- C#, by hand (not in `test.ps1`): `cargo build`, then `dotnet test
|
||||
bindings/csharp/NibblePoker.BakaShrot.Client.Tests` (NUnit). Its `[SetUpFixture]`
|
||||
makes the certificates with `target/debug`'s `bakashrot cert`
|
||||
@@ -301,7 +325,8 @@ tests caught it.
|
||||
port in `target/csharp-tests/`, copies the library next to the tests.
|
||||
On `net48` (the `net35` build) and `net8.0` (`netstandard2.0`), on Linux
|
||||
`net8.0` only. Passed 2026-11-18 on both, and on `net11.0`
|
||||
(`-p:TargetFrameworks=net11.0`).
|
||||
(`-p:TargetFrameworks=net11.0`); 2026-11-20 on both again
|
||||
(`AnswerTimeouts`).
|
||||
- `header.rs`: `bindings/c/bakashrot.h` matches the exports (rewritten
|
||||
when it doesn't: check it in).
|
||||
|
||||
|
||||
@@ -105,6 +105,16 @@ 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.
|
||||
|
||||
## Query time limit
|
||||
|
||||
`[server] query_time_limit` (20 s by default) is how long a client's
|
||||
query may run. Past it, SQLite stops it (it looks every 10,000 steps, a
|
||||
fraction of a millisecond) and the client is refused with `QueryTimedOut` (11):
|
||||
"stopped after 20s, the server's time limit". Keep it under the clients'
|
||||
answer timeout (30 s by default; `BakaShrot_SetAnswerTimeout()`), or they
|
||||
give up first. A client that gives up closes its connection, and the
|
||||
server stops its query then too (`protocol.md`, "Rules").
|
||||
|
||||
## Retention
|
||||
|
||||
A topic takes its name's line, else the first pattern matching it in the
|
||||
|
||||
+4
-1
@@ -157,7 +157,10 @@ Keeping alive C: Ping (every minute while idle) S: Pong
|
||||
## Rules
|
||||
|
||||
- **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). While a
|
||||
`Query` runs, anything from the client (its closing, having given up
|
||||
waiting) stops the query and closes the connection (2026-11-20); the
|
||||
server's own limit stops it past `query_time_limit` (`QueryTimedOut`).
|
||||
- **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
|
||||
|
||||
+8
-1
@@ -184,7 +184,8 @@ the same ids with different messages, undetected.
|
||||
| TLS, versions, welcome | 10 s (the server); the client's connect too |
|
||||
| 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 |
|
||||
| An answer | 30 s (the client) |
|
||||
| An answer | 30 s (the client; `set_answer_timeout()`, `BakaShrot_SetAnswerTimeout()`), then it closes: the server stops the query it was running |
|
||||
| A query | 20 s (`[server] query_time_limit`), then SQLite stops it: `QueryTimedOut` |
|
||||
| An attachment's next part | 30 s (the server), then it closes |
|
||||
|
||||
## Requests so far
|
||||
@@ -232,6 +233,10 @@ the same ids with different messages, undetected.
|
||||
refused with SQLite's message (`QueryFailed`, with a hint to add
|
||||
`is_json = 1` on "malformed JSON"), over 10,000 rows or 16 MB
|
||||
(`TooBig`), never a partial result (`storage.md`, "The query surface").
|
||||
Stopped past `query_time_limit` (`QueryTimedOut`, "stopped after 20s,
|
||||
the server's time limit"), or when the client closes meanwhile (it
|
||||
gave up): its thread isn't left running. `Server::queries_running()`
|
||||
says how many run.
|
||||
- **Sizes:** frames up to 16 MB (`MAX_PACKET_SIZE`), a bigger one drops the
|
||||
connection; messages up to `MAX_MESSAGE_SIZE` (16 MB less 4 KB), the
|
||||
server refusing bigger ones (`TooBig`); the client refuses messages and
|
||||
@@ -358,6 +363,8 @@ each:
|
||||
part on, something else than a part (closed, dropped);
|
||||
- queries: not allowed, results, a non-JSON row
|
||||
refused with the hint, errors, writes and two statements refused;
|
||||
one past `query_time_limit` refused, the connection kept; one whose
|
||||
client gave up first stopped (`queries_are_stopped`);
|
||||
- refusals keeping the connection (not allowed, unknown topic, a bad name
|
||||
the client catches);
|
||||
- certificates refused (no known role, with why; another CA's client; a
|
||||
|
||||
+1
-3
@@ -74,7 +74,7 @@ batch goes on after one fails: the server queues pushes and stores them
|
||||
together, one disk flush for all.
|
||||
|
||||
Except when SQLite rolls the whole transaction back by itself, which it
|
||||
may on a full disk, an I/O error or out of memory (`Batch::is_rolled_back()`).
|
||||
may on a full disk, an I/O error or out of memory.
|
||||
What came after then ran outside any transaction, each operation
|
||||
committed alone, while the batch failed and every write in it was
|
||||
answered as failed: a retried push stored twice. Since 2026-11-19 every
|
||||
@@ -271,7 +271,5 @@ big), the view's plans, and readers with two writers at once. In
|
||||
- **A time index**, if time queries over big streams get slow: a v10
|
||||
migration adding an index on `(stream_id, pushed_at)` and joining the
|
||||
view on it too (measured above: twice the write cost).
|
||||
- **Interrupting long queries** (a time limit): the server's, with
|
||||
SQLite's interrupt.
|
||||
- **Attachments as files** next to the database instead of in it, if their
|
||||
size calls for it.
|
||||
|
||||
@@ -244,7 +244,25 @@ Also decided (2026-11-13):
|
||||
batch back by itself; the writes after it then committed one at a
|
||||
time while all were answered `ServerError` (retried, stored twice).
|
||||
Every `Batch` operation after is refused now (`Error::RolledBack`),
|
||||
the batch fails, nothing in it stored; the writer stops the group.
|
||||
the batch fails, nothing in it stored; the group's later writes are
|
||||
refused too.
|
||||
- **Long queries stopped** (2026-11-20): `[server] query_time_limit`
|
||||
(20 s by default, under the clients' 30 s answer timeout) stops a
|
||||
query through SQLite's progress handler (a look every 10,000 steps)
|
||||
and refuses it with a code of its own, `QueryTimedOut` (11), so apps
|
||||
tell it from SQL that fails (`QueryFailed`). A client closing while its query
|
||||
runs (having given up) stops it too: the connection's task watches
|
||||
it meanwhile, and dropping the query stops it, so no thread keeps
|
||||
running one nobody waits for. The answer timeout reaches the DLL
|
||||
(`BakaShrot_SetAnswerTimeout()` / `GetAnswerTimeout()`, kept across
|
||||
connections), Python (`answer_timeout`) and C# (`AnswerTimeoutMs`).
|
||||
- **`is_open()` reads through TLS** (2026-11-20): it peeked at the
|
||||
socket, so a server's close_notify (bytes waiting) looked open
|
||||
until the next request failed. It reads what's waiting into rustls
|
||||
now, without blocking: TLS's own records (tickets, key updates)
|
||||
keep it open, close_notify or the socket's end say closed, data
|
||||
sent unasked or a broken TLS stream close it (out of step).
|
||||
`&mut self` now; the DLL's `IsConnected` unchanged.
|
||||
- **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).
|
||||
`docs/storage.md`:
|
||||
@@ -468,7 +486,7 @@ by hand.
|
||||
| 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 |
|
||||
| 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; a damaged copy told from a failed read-back; the Rust client closing a connection left out of step, `set_answer_timeout`; nothing written once SQLite rolled a batch back | `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` and `only_a_copy_read_whole_or_missing_a_part_is_damaged` (with `replication` for the damaged copy still dropped); the client's `failures.rs` (a fake server: late, wrong, cut answers and parts) and `revoked_certificates_are_dropped`; storage's `nothing_runs_once_sqlite_rolled_back`; `packets.rs` samples and bytes; `exports.rs`, `check_bakashrot.py`, the NUnit `Closing` | 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; a damaged copy told from a failed read-back; the Rust client closing a connection left out of step, `set_answer_timeout`; nothing written once SQLite rolled a batch back; `query_time_limit`, queries stopped when their client leaves, `BakaShrot_SetAnswerTimeout` | `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` and `only_a_copy_read_whole_or_missing_a_part_is_damaged` (with `replication` for the damaged copy still dropped); the client's `failures.rs` (a fake server: late, wrong, cut answers and parts) and `revoked_certificates_are_dropped`; storage's `nothing_runs_once_sqlite_rolled_back` and `queries_are_stopped`; `end_to_end.rs` `queries_are_stopped`; `exports.rs` `answer_timeouts`, `codes.rs` (the bindings' codes and copied values), the NUnit `AnswerTimeouts`, PureBasic 5.73 and 6.41 by hand; `packets.rs` samples and bytes; `exports.rs`, `check_bakashrot.py`, the NUnit `Closing` | Decided 2026-11-19 | Done 2026-11-20 |
|
||||
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user