mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Paged SyncState, Added Ping, Required ALPN on the server, Capped retention ages, Closed idle database connections
- Protocol 8: SyncStateRequest takes `after` (a Pair), SyncState has `more` and 32768 heads at most (MAX_HEADS_PER_PACKET), the lists and missing attachments in the first page only; heads_after in storage, both ends of replication read in pages (step 17) - Protocol 8: Ping / Pong (19, 20) keep an idle connection open (IDLE_TIMEOUT_SECS 300, KEEPALIVE_SECS 60). Client::ping, BakaShrot_Ping, Python ping(), C# Ping(), the PureBasic prototype; the tool's --follow, Python's follow(), C#'s Follow() and the replication links ping every minute while waiting longer, so sync_interval over 5 min works now (dropped from known-issues.md) - The server closes a client offering no ALPN right after TLS: rustls only refused one offering other protocols - Retention ages are 100 years at most (MAX_RETENTION_AGE); the cutoff is computed once, saturating (Retention::cutoff): a huge age wrapped around to almost nothing in milliseconds - [server] idle_database_connections (8 by default, 0-512): the idle read and query connections each pool keeps, those unused for a minute closed by a sweeping thread - Tests for each, docs, the C header, revamp.md (step 18) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -117,6 +117,14 @@ ptrdiff_t BakaShrot_IsConnected(int64_t client);
|
||||
*/
|
||||
ptrdiff_t BakaShrot_Disconnect(int64_t client);
|
||||
|
||||
/**
|
||||
* Keeps the connection open: 1, or 0 if it failed (`ConnectionLost`:
|
||||
* connect again). The server closes a connection silent for 5 min; an
|
||||
* app waiting longer between requests calls this every minute or so
|
||||
* (the DLL has no thread of its own to do it).
|
||||
*/
|
||||
ptrdiff_t BakaShrot_Ping(int64_t client);
|
||||
|
||||
/**
|
||||
* The node this client is, as the server said when connecting: its
|
||||
* certificate's name. Empty when not connected.
|
||||
|
||||
@@ -287,10 +287,14 @@ namespace NibblePoker.BakaShrot.Tests
|
||||
public void Closing()
|
||||
{
|
||||
Client kitchen = Server.Connect("kitchen");
|
||||
kitchen.Ping();
|
||||
Assert.That(kitchen.Connected, Is.True, "still connected after a ping");
|
||||
kitchen.Close();
|
||||
Assert.That(kitchen.Connected, Is.False);
|
||||
ConnectionLostException lost = Assert.Throws<ConnectionLostException>(() => kitchen.Push("logs", "x"))!;
|
||||
Assert.That(lost.Code, Is.EqualTo(ErrorCode.NotConnected));
|
||||
lost = Assert.Throws<ConnectionLostException>(() => kitchen.Ping())!;
|
||||
Assert.That(lost.Code, Is.EqualTo(ErrorCode.NotConnected));
|
||||
kitchen.Connect();
|
||||
Assert.That(kitchen.Connected, Is.True, "connects again");
|
||||
kitchen.Dispose();
|
||||
|
||||
@@ -201,6 +201,18 @@ namespace NibblePoker.BakaShrot
|
||||
Native.BakaShrot_FreeClient(handle);
|
||||
}
|
||||
|
||||
/// <summary>Keeps the connection open: the server closes one silent
|
||||
/// for 5 min. An app waiting longer between requests calls it every
|
||||
/// minute or so (KeepAliveMs); Follow() does it itself.</summary>
|
||||
public void Ping()
|
||||
{
|
||||
lock (sync)
|
||||
Check(Native.BakaShrot_Ping(Handle()), "Ping");
|
||||
}
|
||||
|
||||
/// <summary>How often to Ping() while waiting between requests, in ms.</summary>
|
||||
public const int KeepAliveMs = 60000;
|
||||
|
||||
/// <summary>Pushes data (JSON or not) to topic, as this client's node: its id.</summary>
|
||||
public long Push(string topic, string data)
|
||||
{
|
||||
@@ -278,8 +290,9 @@ namespace NibblePoker.BakaShrot
|
||||
}
|
||||
|
||||
/// <summary>Every message after id after, then new ones as they
|
||||
/// come, checking every intervalMs: forever, stop enumerating to
|
||||
/// stop. Nothing reconnects by itself.</summary>
|
||||
/// come, checking every intervalMs (pinging every minute meanwhile
|
||||
/// if it's longer): forever, stop enumerating to stop. Nothing
|
||||
/// reconnects by itself.</summary>
|
||||
public IEnumerable<Message> Follow(string topic, string node, long after, int intervalMs)
|
||||
{
|
||||
while (true)
|
||||
@@ -289,7 +302,7 @@ namespace NibblePoker.BakaShrot
|
||||
yield return message;
|
||||
after = Math.Max(after, page.LastId);
|
||||
if (!page.More)
|
||||
Thread.Sleep(intervalMs);
|
||||
Wait(intervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -419,6 +432,21 @@ namespace NibblePoker.BakaShrot
|
||||
|
||||
// --- Inside ---------------------------------------------------------
|
||||
|
||||
// Sleeps intervalMs, pinging every KeepAliveMs meanwhile.
|
||||
private void Wait(int intervalMs)
|
||||
{
|
||||
int left = intervalMs;
|
||||
while (true)
|
||||
{
|
||||
int step = Math.Min(left, KeepAliveMs);
|
||||
Thread.Sleep(step);
|
||||
left -= step;
|
||||
if (left <= 0)
|
||||
return;
|
||||
Ping();
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerable<string> EnumerateNames(int kind, string topic, string node)
|
||||
{
|
||||
long enumeration;
|
||||
@@ -563,6 +591,7 @@ namespace NibblePoker.BakaShrot
|
||||
[DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_SetCrlW(long client, string crl);
|
||||
[DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_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_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);
|
||||
|
||||
@@ -62,6 +62,7 @@ PrototypeC.i BakaShrot_SetCrl_Prototype(Client.q, Crl.p-unicode)
|
||||
PrototypeC.i BakaShrot_Connect_Prototype(Client.q, Host.p-unicode, Port.l)
|
||||
PrototypeC.i BakaShrot_IsConnected_Prototype(Client.q)
|
||||
PrototypeC.i BakaShrot_Disconnect_Prototype(Client.q)
|
||||
PrototypeC.i BakaShrot_Ping_Prototype(Client.q)
|
||||
PrototypeC.i BakaShrot_GetNode_Prototype(Client.q, *Buffer, BufferSize.i)
|
||||
PrototypeC.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)
|
||||
@@ -112,6 +113,7 @@ Global BakaShrot_SetCrl.BakaShrot_SetCrl_Prototype
|
||||
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_GetNode.BakaShrot_GetNode_Prototype
|
||||
Global BakaShrot_PushMessageTo.BakaShrot_PushMessageTo_Prototype
|
||||
Global BakaShrot_GetLatestMessageOf.BakaShrot_GetLatestMessageOf_Prototype
|
||||
@@ -199,6 +201,7 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
|
||||
BakaShrot_Connect = BakaShrot_ClientFunction("BakaShrot_ConnectW")
|
||||
BakaShrot_IsConnected = BakaShrot_ClientFunction("BakaShrot_IsConnected")
|
||||
BakaShrot_Disconnect = BakaShrot_ClientFunction("BakaShrot_Disconnect")
|
||||
BakaShrot_Ping = BakaShrot_ClientFunction("BakaShrot_Ping")
|
||||
BakaShrot_GetNode = BakaShrot_ClientFunction("BakaShrot_GetNodeW")
|
||||
BakaShrot_PushMessageTo = BakaShrot_ClientFunction("BakaShrot_PushMessageToW")
|
||||
BakaShrot_GetLatestMessageOf = BakaShrot_ClientFunction("BakaShrot_GetLatestMessageOfW")
|
||||
|
||||
@@ -63,12 +63,15 @@ __version__ = "0.4.0"
|
||||
__all__ = [
|
||||
"Client", "Message", "MessagesPage", "NamesList",
|
||||
"BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode",
|
||||
"MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE",
|
||||
"MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE", "KEEPALIVE_SECONDS",
|
||||
]
|
||||
|
||||
# The protocol's: crates/bakashrot-proto/src/limits.rs.
|
||||
MAX_GET_MESSAGES = 10000
|
||||
MAX_MESSAGE_SIZE = 16 * 1024 * 1024 - 4096
|
||||
# The server closes a connection silent for 5 min: ping() every minute or
|
||||
# so while waiting longer than that (follow() does it itself).
|
||||
KEEPALIVE_SECONDS = 60
|
||||
|
||||
DLL_NAME = "bakashrot.dll" if sys.platform == "win32" else "libbakashrot.so"
|
||||
|
||||
@@ -250,6 +253,7 @@ class _Dll:
|
||||
"BakaShrot_ConnectA": (I, [H, P, L]),
|
||||
"BakaShrot_IsConnected": (I, [H]),
|
||||
"BakaShrot_Disconnect": (I, [H]),
|
||||
"BakaShrot_Ping": (I, [H]),
|
||||
"BakaShrot_GetNodeA": (I, [H, S, I]),
|
||||
"BakaShrot_PushMessageToA": (Q, [H, P, P]),
|
||||
"BakaShrot_GetLatestMessageOfA": (I, [H, P, P]),
|
||||
@@ -429,6 +433,27 @@ class Client:
|
||||
|
||||
# --- Requests ----------------------------------------------------------
|
||||
|
||||
def ping(self) -> None:
|
||||
"""Keeps the connection open: the server closes one silent for 5
|
||||
min. An app waiting longer than that between requests calls it
|
||||
every minute or so (KEEPALIVE_SECONDS). ConnectionLostError if
|
||||
the connection is gone."""
|
||||
with self._lock:
|
||||
self._check_connected()
|
||||
if not self._dll.Ping(self._handle):
|
||||
raise self._failed("Ping")
|
||||
|
||||
def _wait(self, seconds: float) -> None:
|
||||
"""Sleeps `seconds`, pinging every KEEPALIVE_SECONDS meanwhile."""
|
||||
left = seconds
|
||||
while True:
|
||||
step = min(left, KEEPALIVE_SECONDS)
|
||||
time.sleep(step)
|
||||
left -= step
|
||||
if left <= 0:
|
||||
return
|
||||
self.ping()
|
||||
|
||||
def push(self, data: Any, topic: str,
|
||||
attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int:
|
||||
"""Pushes a message into topic, under the client's node. data is
|
||||
@@ -538,8 +563,9 @@ class Client:
|
||||
def follow(self, topic: str, node: str, after: Union[int, str] = "latest",
|
||||
interval: float = 0.5, batch: int = 1000) -> Iterator[Message]:
|
||||
"""Every message of topic/node after `after`, then new ones as they
|
||||
come, checking every `interval` seconds once caught up. Forever:
|
||||
stop iterating to stop. after="latest" starts with the next new one.
|
||||
come, checking every `interval` seconds once caught up (pinging
|
||||
every minute meanwhile if it's longer). Forever: stop iterating to
|
||||
stop. after="latest" starts with the next new one.
|
||||
Raises ConnectionLostError if the connection fails: nothing
|
||||
reconnects by itself, connect() again and follow from the last id."""
|
||||
if after == "latest":
|
||||
@@ -553,7 +579,7 @@ class Client:
|
||||
if page.messages:
|
||||
after = page.last_id
|
||||
if not page.more:
|
||||
time.sleep(interval)
|
||||
self._wait(interval)
|
||||
|
||||
def list_topics(self, topic: Optional[str] = None, node: Optional[str] = None) -> NamesList:
|
||||
"""The topics with messages that the client may push to or read (every one with list_topics or query).
|
||||
|
||||
@@ -223,6 +223,8 @@ with kitchen:
|
||||
"missing.bin", ErrorCode.FILE_ERROR)
|
||||
check("A missing file: refused before sending", ok, detail)
|
||||
check("Still connected", kitchen.connected)
|
||||
kitchen.ping()
|
||||
check("ping(): answered, still connected", kitchen.connected)
|
||||
|
||||
# --- Two Clients, two threads, at the same time --------------------------
|
||||
other = Client.from_file(os.path.join(folder, "kitchen.toml"), dll_path).connect()
|
||||
@@ -247,6 +249,8 @@ with kitchen:
|
||||
check("close(): disconnected", not kitchen.connected)
|
||||
ok, detail = raises(lambda: kitchen.push("x", "logs"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED)
|
||||
check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail)
|
||||
ok, detail = raises(kitchen.ping, ConnectionLostError, code=ErrorCode.NOT_CONNECTED)
|
||||
check("ping() once closed: ConnectionLostError, NOT_CONNECTED", ok, detail)
|
||||
|
||||
# --- Connecting: unreachable, refused, PEM text ----------------------------------
|
||||
with open(kitchen.ca) as ca, open(kitchen.certificate) as certificate, open(kitchen.key) as key:
|
||||
|
||||
Reference in New Issue
Block a user