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 = {}
|
||||
|
||||
Reference in New Issue
Block a user