mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Protocol 6: node identities, error codes, Synchronous, schema v8, examples
- Protocol 5: a client authenticates as a node (Node), its pushes go to the section's DefaultTopic unless they name one; old Identities refused at start with what to write instead. - Topics listed by name, ids picked and kept by the server; nodes come from client sections, [BakaShrot.Nodes] optional, AcceptNodes = * by default. - Protocol 6: every refusal carries a code, every client failure too (BakaShrot_ErrorCodes.pbi, BakaShrot_GetLastError(), ErrorCode in Python); nothing reconnects by itself, delivery is at least once. - [BakaShrot.Server] Synchronous = FULL (default) or NORMAL, benchmarked. - Schema v8: browse table and browse_messages view for database tools. - Tools renamed BakaShrot<Name>, wait for Enter when started from Explorer. - Examples/SingleServer: a server and a client with scripts (example keys, public on purpose). - Restart-Test.ps1: servers killed mid-traffic and mid-catch-up. - Docs: one server per node rule, DatabaseError() checked per thread, release notes' Compatibility section, Notes "Right now". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RwFeVQrLqMQPw9AZnsHqQH
This commit is contained in:
+129
-39
@@ -27,6 +27,18 @@ The connection only goes through to the server holding the private key of
|
||||
server_public_key (client.ini's ServerPublicKey, the server logs it when it
|
||||
starts), and everything on it is encrypted.
|
||||
|
||||
Errors are exceptions with a code (`error.code`, an ErrorCode, the same
|
||||
numbers as the DLL's BakaShrot_GetLastError(), see
|
||||
Client/BakaShrot_ErrorCodes.pbi):
|
||||
RefusedError the server refused (codes 1-99), still connected
|
||||
ConnectionLostError not connected, unreachable, the connection lost or
|
||||
broken: connect() again (nothing reconnects by itself)
|
||||
AuthError the server rejected the handshake or couldn't prove
|
||||
its key: fix the config, retrying won't help
|
||||
BakaShrotError the rest: a bad argument, a file, the DLL itself
|
||||
A push whose answer was lost (ConnectionLostError) may have been stored all
|
||||
the same: pushed again, it's stored twice. Delivery is at least once.
|
||||
|
||||
The DLL holds a single connection per process: only one Client may be
|
||||
connected at a time. Calls are serialized with a lock, so a Client can be
|
||||
shared between threads, one request at a time.
|
||||
@@ -40,6 +52,7 @@ from __future__ import annotations
|
||||
|
||||
import configparser
|
||||
import ctypes
|
||||
import enum
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
@@ -50,7 +63,7 @@ from typing import Any, Iterator, Optional, Union
|
||||
|
||||
__all__ = [
|
||||
"Client", "Message", "MessagesPage", "NameEntry", "NamesList",
|
||||
"BakaShrotError", "RefusedError", "ConnectionLostError",
|
||||
"BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode",
|
||||
"MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE",
|
||||
]
|
||||
|
||||
@@ -61,20 +74,75 @@ MAX_MESSAGE_SIZE = 16 * 1024 * 1024 - 4096
|
||||
Ref = Union[str, int]
|
||||
|
||||
|
||||
class ErrorCode(enum.IntEnum):
|
||||
"""What failed: Client/BakaShrot_ErrorCodes.pbi, the same numbers.
|
||||
1-99: refused by the server, 100+: the client's own."""
|
||||
NONE = 0
|
||||
# Refused by the server, the connection still open.
|
||||
NOT_ALLOWED = 1 # AllowRead/Write/Query, PushTopics/ReadTopics
|
||||
UNKNOWN_NAME = 2 # a topic or node this server doesn't know
|
||||
NOT_FOUND = 3 # no such message, attachment or upload
|
||||
NOT_READY = 4 # the attachment isn't on this server yet: retry later
|
||||
TOO_BIG = 5 # over a limit, or more than this server keeps
|
||||
NO_DEFAULT_TOPIC = 6 # a push without a topic, and no DefaultTopic
|
||||
INVALID_REQUEST = 7 # parts out of order, an upload for another topic...
|
||||
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
|
||||
# The client's own.
|
||||
NOT_CONNECTED = 100 # never connected, or closed or lost before
|
||||
CONNECT_FAILED = 101 # nothing answers at that host and port
|
||||
AUTH_REJECTED = 102 # the server closed the handshake: wrong ServerPublicKey,
|
||||
# a key or node it doesn't allow, another version
|
||||
SERVER_NOT_VERIFIED = 103 # the server couldn't prove its key
|
||||
CONNECTION_LOST = 104 # broke during a request (a push may still be stored)
|
||||
PROTOCOL_ERROR = 105 # an unexpected answer, the connection is closed
|
||||
INVALID_ARGUMENT = 106
|
||||
FILE_ERROR = 107
|
||||
ATTACHMENT_MISMATCH = 108 # a downloaded attachment that doesn't match its SHA-256
|
||||
ALREADY_CONNECTED = 109
|
||||
INTERNAL = 110 # out of memory, the DLL missing or too old...
|
||||
|
||||
@property
|
||||
def is_refusal(self) -> bool:
|
||||
return 1 <= self.value <= 99
|
||||
|
||||
|
||||
def _error_code(value: int):
|
||||
"""An ErrorCode, or the int itself if this module doesn't know it."""
|
||||
try:
|
||||
return ErrorCode(value)
|
||||
except ValueError:
|
||||
return value
|
||||
|
||||
|
||||
class BakaShrotError(Exception):
|
||||
"""Something failed: the DLL couldn't be loaded, a bad argument, ..."""
|
||||
"""Something failed: code (an ErrorCode) tells what, see ErrorCode."""
|
||||
|
||||
def __init__(self, message: str, code: int = ErrorCode.INTERNAL):
|
||||
super().__init__(message)
|
||||
self.code = _error_code(code)
|
||||
|
||||
|
||||
class RefusedError(BakaShrotError):
|
||||
"""The server refused the request, the connection is still open."""
|
||||
"""The server refused the request, the connection is still open. code
|
||||
says why (1-99, e.g. ErrorCode.NOT_FOUND), reason in the server's words."""
|
||||
|
||||
def __init__(self, reason: str):
|
||||
super().__init__(reason or "Refused")
|
||||
def __init__(self, reason: str, code: int):
|
||||
super().__init__(reason or "Refused", code)
|
||||
self.reason = reason
|
||||
|
||||
|
||||
class ConnectionLostError(BakaShrotError):
|
||||
"""The connection failed or was closed, connect() again to go on."""
|
||||
"""Not connected, or the connection failed or was closed (code:
|
||||
NOT_CONNECTED, CONNECT_FAILED, CONNECTION_LOST, PROTOCOL_ERROR):
|
||||
connect() again to go on."""
|
||||
|
||||
|
||||
class AuthError(BakaShrotError):
|
||||
"""The server rejected the handshake (AUTH_REJECTED) or couldn't prove it
|
||||
holds server_public_key's private key (SERVER_NOT_VERIFIED): a config to
|
||||
fix, connecting again won't help."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -186,10 +254,10 @@ class _Dll:
|
||||
|
||||
I, L, Q, P, S = ctypes.c_ssize_t, ctypes.c_int32, ctypes.c_int64, ctypes.c_char_p, ctypes.c_void_p
|
||||
signatures = {
|
||||
"BakaShrot_GetLastError": (L, []),
|
||||
"BakaShrot_SetPrivateKeyA": (I, [P]),
|
||||
"BakaShrot_SetPublicKeyA": (I, [P]),
|
||||
"BakaShrot_SetServerPublicKeyA": (I, [P]),
|
||||
"BakaShrot_SetTopicA": (I, [P]),
|
||||
"BakaShrot_SetNodeA": (I, [P]),
|
||||
"BakaShrot_ConnectA": (I, [P, L]),
|
||||
"BakaShrot_IsConnected": (I, []),
|
||||
@@ -229,7 +297,7 @@ class _Dll:
|
||||
try:
|
||||
function = getattr(self.lib, name)
|
||||
except AttributeError as error:
|
||||
raise BakaShrotError(f"{path} has no {name}, is it an older build?") from error
|
||||
raise BakaShrotError(f"{path} has no {name}, is it an older build?", ErrorCode.INTERNAL) from error
|
||||
function.restype = restype
|
||||
function.argtypes = argtypes
|
||||
setattr(self, name[len("BakaShrot_"):], function)
|
||||
@@ -247,23 +315,24 @@ class _Dll:
|
||||
class Client:
|
||||
"""A connection to a BakaShrot server, through the DLL.
|
||||
|
||||
private_key, public_key: the client's Ed25519 keys in Base64 (KeyGen.exe).
|
||||
private_key, public_key: the client's Ed25519 keys in Base64 (BakaShrotGenerateKeyPairs.exe).
|
||||
server_public_key: the server's Ed25519 public key in Base64, it must
|
||||
prove it holds the matching private key.
|
||||
topic, node: who the client is, names or ids, as the server's
|
||||
[BakaShrot.Client.<name>] Identities lists them.
|
||||
node: the node the client writes as, a name or an id, which the
|
||||
server's [BakaShrot.Client.<name>] must give its key (Node). Its
|
||||
default topic, for pushes that don't name one, is the server's to say
|
||||
(that section's DefaultTopic).
|
||||
"""
|
||||
|
||||
_connected_client: Optional["Client"] = None
|
||||
|
||||
def __init__(self, private_key: str, public_key: str, server_public_key: str, topic: Ref, node: Ref,
|
||||
def __init__(self, private_key: str, public_key: str, server_public_key: str, node: Ref,
|
||||
host: str = "127.0.0.1", port: int = 12345, dll_path: Optional[str] = None):
|
||||
self._dll = _Dll.get(dll_path)
|
||||
self._lock = threading.RLock()
|
||||
self.private_key = private_key
|
||||
self.public_key = public_key
|
||||
self.server_public_key = server_public_key
|
||||
self.topic = topic
|
||||
self.node = node
|
||||
self.host = host
|
||||
self.port = int(port)
|
||||
@@ -271,45 +340,48 @@ class Client:
|
||||
@classmethod
|
||||
def from_ini(cls, path: str, dll_path: Optional[str] = None) -> "Client":
|
||||
"""From a client.ini as the tools read it: [BakaShrot] PrivateKey,
|
||||
PublicKey, ServerPublicKey, Topic, Node, ServerHost, ServerPort."""
|
||||
PublicKey, ServerPublicKey, Node, ServerHost, ServerPort (a Topic
|
||||
left in it is ignored)."""
|
||||
parser = configparser.ConfigParser(interpolation=None)
|
||||
if not parser.read(path, encoding="utf-8-sig"):
|
||||
raise BakaShrotError(f"Failed to open '{path}'")
|
||||
raise BakaShrotError(f"Failed to open '{path}'", ErrorCode.FILE_ERROR)
|
||||
section = parser["BakaShrot"] if parser.has_section("BakaShrot") else {}
|
||||
|
||||
def get(key, fallback=None):
|
||||
value = section.get(key, fallback)
|
||||
if value is None:
|
||||
raise BakaShrotError(f"'{path}' has no [BakaShrot] {key}")
|
||||
raise BakaShrotError(f"'{path}' has no [BakaShrot] {key}", ErrorCode.INVALID_ARGUMENT)
|
||||
return value.strip()
|
||||
|
||||
return cls(get("PrivateKey"), get("PublicKey"), get("ServerPublicKey"),
|
||||
get("Topic", section.get("TopicId")), get("Node", section.get("NodeId")),
|
||||
get("Node", section.get("NodeId")),
|
||||
get("ServerHost"), int(get("ServerPort")), dll_path)
|
||||
|
||||
# --- Connection --------------------------------------------------------
|
||||
|
||||
def connect(self) -> "Client":
|
||||
"""Connects and authenticates, raises BakaShrotError on failure."""
|
||||
"""Connects and authenticates. Raises ConnectionLostError when the
|
||||
server can't be reached (CONNECT_FAILED), AuthError when it rejects
|
||||
the handshake or can't prove its key, BakaShrotError on a bad setting
|
||||
(INVALID_ARGUMENT) or another Client holding the DLL's connection
|
||||
(ALREADY_CONNECTED)."""
|
||||
with self._lock:
|
||||
owner = Client._connected_client
|
||||
if owner is not None and owner is not self and owner.connected:
|
||||
raise BakaShrotError("The DLL holds one connection, another Client is connected")
|
||||
raise BakaShrotError("The DLL holds one connection, another Client is connected", ErrorCode.ALREADY_CONNECTED)
|
||||
if self.connected:
|
||||
return self
|
||||
dll = self._dll
|
||||
if not dll.SetPrivateKeyA(self.private_key.encode("ascii")):
|
||||
raise BakaShrotError("Invalid private key")
|
||||
raise BakaShrotError("Invalid private key", dll.GetLastError())
|
||||
if not dll.SetPublicKeyA(self.public_key.encode("ascii")):
|
||||
raise BakaShrotError("Invalid public key")
|
||||
raise BakaShrotError("Invalid public key", dll.GetLastError())
|
||||
if not dll.SetServerPublicKeyA(self.server_public_key.encode("ascii")):
|
||||
raise BakaShrotError("Invalid server public key")
|
||||
if not dll.SetTopicA(_ref(self.topic)):
|
||||
raise BakaShrotError(f"Invalid topic {self.topic!r}")
|
||||
raise BakaShrotError("Invalid server public key", dll.GetLastError())
|
||||
if not dll.SetNodeA(_ref(self.node)):
|
||||
raise BakaShrotError(f"Invalid node {self.node!r}")
|
||||
raise BakaShrotError(f"Invalid node {self.node!r}", dll.GetLastError())
|
||||
if not dll.ConnectA(self.host.encode("utf-8"), self.port):
|
||||
raise ConnectionLostError(f"Failed to connect and authenticate to {self.host}:{self.port}")
|
||||
raise self._failed(f"Connect to {self.host}:{self.port}")
|
||||
Client._connected_client = self
|
||||
return self
|
||||
|
||||
@@ -331,22 +403,39 @@ class Client:
|
||||
|
||||
def _check_connected(self) -> None:
|
||||
if not self.connected:
|
||||
raise ConnectionLostError("Not connected")
|
||||
raise ConnectionLostError("Not connected", ErrorCode.NOT_CONNECTED)
|
||||
|
||||
_MESSAGES = {
|
||||
ErrorCode.NOT_CONNECTED: "not connected",
|
||||
ErrorCode.CONNECT_FAILED: "nothing answers there",
|
||||
ErrorCode.AUTH_REJECTED: "the server closed the connection during the handshake: wrong server public key, "
|
||||
"a key or node it doesn't allow, or another version (its log says which)",
|
||||
ErrorCode.SERVER_NOT_VERIFIED: "the server couldn't prove it holds the server public key's private key",
|
||||
ErrorCode.CONNECTION_LOST: "the connection to the server failed",
|
||||
ErrorCode.PROTOCOL_ERROR: "the server answered something unexpected, the connection is closed",
|
||||
}
|
||||
|
||||
def _failed(self, what: str) -> BakaShrotError:
|
||||
"""The error for a failed request: refused, or the connection is gone."""
|
||||
if self._dll.IsConnected():
|
||||
reason = self._dll.string(self._dll.GetRefusalReasonA)
|
||||
return RefusedError(reason) if reason else BakaShrotError(f"{what} failed")
|
||||
if Client._connected_client is self:
|
||||
"""The error for a failed call, by the DLL's BakaShrot_GetLastError()."""
|
||||
code = _error_code(self._dll.GetLastError())
|
||||
reason = self._dll.string(self._dll.GetRefusalReasonA)
|
||||
if isinstance(code, int) and 1 <= int(code) <= 99:
|
||||
return RefusedError(reason, code)
|
||||
if not self._dll.IsConnected() and Client._connected_client is self:
|
||||
Client._connected_client = None
|
||||
return ConnectionLostError(f"{what}: the connection to the server failed")
|
||||
name = code.name if isinstance(code, ErrorCode) else str(code)
|
||||
message = f"{what} ({name}): {reason or self._MESSAGES.get(code, 'failed')}"
|
||||
if code in (ErrorCode.NOT_CONNECTED, ErrorCode.CONNECT_FAILED, ErrorCode.CONNECTION_LOST, ErrorCode.PROTOCOL_ERROR):
|
||||
return ConnectionLostError(message, code)
|
||||
if code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED):
|
||||
return AuthError(message, code)
|
||||
return BakaShrotError(message, code if code else ErrorCode.INTERNAL)
|
||||
|
||||
# --- Requests ----------------------------------------------------------
|
||||
|
||||
def push(self, data: Any, topic: Optional[Ref] = None,
|
||||
attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int:
|
||||
"""Pushes a message into topic (default: the client's own), under
|
||||
"""Pushes a message into topic (default: the client's default one, its server's DefaultTopic), under
|
||||
the client's node. data is stored as is if it's a str (JSON or not),
|
||||
anything else is turned into JSON first. Returns its message id.
|
||||
|
||||
@@ -357,7 +446,7 @@ class Client:
|
||||
data = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
|
||||
encoded = data.encode("utf-8")
|
||||
if len(encoded) > MAX_MESSAGE_SIZE:
|
||||
raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}")
|
||||
raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}", ErrorCode.INVALID_ARGUMENT)
|
||||
topic_ref = b"" if topic is None else _ref(topic)
|
||||
with self._lock:
|
||||
self._check_connected()
|
||||
@@ -366,13 +455,13 @@ class Client:
|
||||
elif isinstance(attachment, (bytes, bytearray, memoryview)):
|
||||
raw = bytes(attachment)
|
||||
if not raw:
|
||||
raise BakaShrotError("The attachment is empty")
|
||||
raise BakaShrotError("The attachment is empty", ErrorCode.INVALID_ARGUMENT)
|
||||
buffer = ctypes.create_string_buffer(raw, len(raw))
|
||||
message_id = self._dll.PushMessageWithDataA(topic_ref, encoded, ctypes.cast(buffer, ctypes.c_void_p), len(raw))
|
||||
else:
|
||||
path = os.fspath(attachment)
|
||||
if not os.path.isfile(path) or os.path.getsize(path) == 0:
|
||||
raise BakaShrotError(f"Can't attach {path!r}: no such file, or empty")
|
||||
raise BakaShrotError(f"Can't attach {path!r}: no such file, or empty", ErrorCode.FILE_ERROR)
|
||||
message_id = self._dll.PushMessageWithFileA(topic_ref, encoded, path.encode("utf-8"))
|
||||
if message_id < 1:
|
||||
raise self._failed("Push")
|
||||
@@ -418,7 +507,7 @@ class Client:
|
||||
self._check_connected()
|
||||
if not self._dll.GetLatestMessageOfA(_ref(topic), _ref(node)):
|
||||
error = self._failed("Latest message")
|
||||
if isinstance(error, RefusedError) and error.reason.startswith("No message for"):
|
||||
if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND:
|
||||
return None
|
||||
raise error
|
||||
return self._current()
|
||||
@@ -460,7 +549,8 @@ class Client:
|
||||
"""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.
|
||||
Raises ConnectionLostError if the connection fails."""
|
||||
Raises ConnectionLostError if the connection fails: nothing
|
||||
reconnects by itself, connect() again and follow from the last id."""
|
||||
if after == "latest":
|
||||
latest = self.latest(topic, node)
|
||||
after = latest.id if latest else 0
|
||||
|
||||
@@ -14,7 +14,7 @@ import threading
|
||||
import time
|
||||
|
||||
import bakashrot
|
||||
from bakashrot import BakaShrotError, Client, ConnectionLostError, RefusedError
|
||||
from bakashrot import AuthError, BakaShrotError, Client, ConnectionLostError, ErrorCode, RefusedError
|
||||
|
||||
dll_path, kitchen_ini, lounge_ini = sys.argv[1:4]
|
||||
fails = 0
|
||||
@@ -30,11 +30,12 @@ def check(what, ok, detail=""):
|
||||
print(f"{'PASS' if ok else 'FAIL'} {what}\n -> {detail}", flush=True)
|
||||
|
||||
|
||||
def raises(function, error_type, contains=""):
|
||||
def raises(function, error_type, contains="", code=None):
|
||||
try:
|
||||
function()
|
||||
except error_type as error:
|
||||
return contains in str(error), f"{type(error).__name__}: {error}"
|
||||
got = getattr(error, "code", None)
|
||||
return contains in str(error) and (code is None or got == code), f"{type(error).__name__} [{got!r}]: {error}"
|
||||
except Exception as error: # noqa: BLE001 - reported as a failure
|
||||
return False, f"{type(error).__name__}: {error}"
|
||||
return False, "didn't raise"
|
||||
@@ -111,6 +112,8 @@ with kitchen:
|
||||
|
||||
rows = kitchen.query("SELECT is_json, COUNT(*) AS n FROM data GROUP BY is_json ORDER BY is_json")
|
||||
check("query(): is_json flags 3 non-JSON, 250 JSON", rows == [{"is_json": "0", "n": "3"}, {"is_json": "1", "n": "250"}], rows)
|
||||
ok, detail = raises(lambda: kitchen.query("SELECT nope FROM data"), RefusedError, "nope", ErrorCode.QUERY_FAILED)
|
||||
check("A query that fails: RefusedError, QUERY_FAILED", ok, detail)
|
||||
|
||||
# --- Answers split at ~1 MB ----------------------------------------------
|
||||
big = "x" * (700 * 1024)
|
||||
@@ -123,18 +126,18 @@ with kitchen:
|
||||
[len(m.data) for m in every])
|
||||
|
||||
# --- Refusals ------------------------------------------------------------
|
||||
ok, detail = raises(lambda: kitchen.get_messages("logs", "nobody"), RefusedError, "Unknown node 'nobody'")
|
||||
check("Unknown node: RefusedError", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.get_messages("logs", "nobody"), RefusedError, "Unknown node 'nobody'", ErrorCode.UNKNOWN_NAME)
|
||||
check("Unknown node: RefusedError, UNKNOWN_NAME", ok, detail)
|
||||
check("Still connected after a refusal", kitchen.connected and kitchen.latest("logs", "kitchen").id == big_ids[-1])
|
||||
ok, detail = raises(lambda: kitchen.get_messages("logs", "kitchen", limit=0), ValueError)
|
||||
check("limit 0: ValueError, before asking", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.get_messages("logs", "kitchen", after=-1), ValueError)
|
||||
check("after -1: ValueError", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.push("x", topic="nothing"), RefusedError, "Unknown topic")
|
||||
check("Push to an unknown topic: RefusedError", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.push("x", topic="nothing"), RefusedError, "Unknown topic", ErrorCode.UNKNOWN_NAME)
|
||||
check("Push to an unknown topic: RefusedError, UNKNOWN_NAME", ok, detail)
|
||||
secret_id = kitchen.push({"s": 1}, topic="secret")
|
||||
check("Push to another allowed topic", secret_id == 1, secret_id)
|
||||
ok, detail = raises(lambda: lounge.connect(), BakaShrotError, "one connection")
|
||||
ok, detail = raises(lambda: lounge.connect(), BakaShrotError, "one connection", ErrorCode.ALREADY_CONNECTED)
|
||||
check("A second Client can't connect while one is", ok and not lounge.connected, detail)
|
||||
|
||||
topics = kitchen.list_topics()
|
||||
@@ -192,26 +195,34 @@ with kitchen:
|
||||
sizes = [(m.id, m.attachment_size, m.attachment_ready) for m in page]
|
||||
check("get_messages(): each message's attachment",
|
||||
sizes == [(blob_id, len(blob), True), (file_id, os.path.getsize(source), True), (plain_id, 0, False)], sizes)
|
||||
ok, detail = raises(lambda: kitchen.get_attachment("secret", "kitchen", plain_id), RefusedError, "No attachment")
|
||||
check("get_attachment() of a message without: RefusedError", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=b""), BakaShrotError, "empty")
|
||||
ok, detail = raises(lambda: kitchen.get_attachment("secret", "kitchen", plain_id), RefusedError, "No attachment", ErrorCode.NOT_FOUND)
|
||||
check("get_attachment() of a message without: RefusedError, NOT_FOUND", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=b""), BakaShrotError, "empty", ErrorCode.INVALID_ARGUMENT)
|
||||
check("An empty attachment: refused before sending", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=os.path.join(folder, "missing.bin")), BakaShrotError, "no such file")
|
||||
ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=os.path.join(folder, "missing.bin")), BakaShrotError, "no such file", ErrorCode.FILE_ERROR)
|
||||
check("A missing file: refused before sending", ok, detail)
|
||||
check("Still connected", kitchen.connected)
|
||||
|
||||
check("close(): disconnected", not kitchen.connected)
|
||||
ok, detail = raises(lambda: kitchen.push("x"), ConnectionLostError)
|
||||
check("A request once closed: ConnectionLostError", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.push("x"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED)
|
||||
check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail)
|
||||
|
||||
# --- Connecting: unreachable, rejected ---------------------------------------
|
||||
nowhere = Client(kitchen.private_key, kitchen.public_key, kitchen.server_public_key, kitchen.node, "127.0.0.1", 1, dll_path)
|
||||
ok, detail = raises(nowhere.connect, ConnectionLostError, code=ErrorCode.CONNECT_FAILED)
|
||||
check("Nothing listening: ConnectionLostError, CONNECT_FAILED", ok, detail)
|
||||
stranger = Client(kitchen.private_key, kitchen.public_key, kitchen.server_public_key, "nobody", kitchen.host, kitchen.port, dll_path)
|
||||
ok, detail = raises(stranger.connect, AuthError, code=ErrorCode.AUTH_REJECTED)
|
||||
check("A node the server doesn't give this key: AuthError, AUTH_REJECTED", ok, detail)
|
||||
|
||||
with lounge:
|
||||
page = lounge.get_messages("logs", "kitchen", after=245, limit=3)
|
||||
check("Another identity once the first closed: reads logs", [m.id for m in page] == [246, 247, 248] and page.more,
|
||||
f"{[m.id for m in page]}, more={page.more}")
|
||||
ok, detail = raises(lambda: lounge.get_messages("secret", "kitchen"), RefusedError, "Not allowed to read topic 'secret'")
|
||||
check("A topic not in its ReadTopics: RefusedError", ok, detail)
|
||||
ok, detail = raises(lambda: lounge.query("SELECT 1"), RefusedError, "Not allowed to query")
|
||||
check("Not allowed to query: RefusedError", ok, detail)
|
||||
ok, detail = raises(lambda: lounge.get_messages("secret", "kitchen"), RefusedError, "Not allowed to read topic 'secret'", ErrorCode.NOT_ALLOWED)
|
||||
check("A topic not in its ReadTopics: RefusedError, NOT_ALLOWED", ok, detail)
|
||||
ok, detail = raises(lambda: lounge.query("SELECT 1"), RefusedError, "Not allowed to query", ErrorCode.NOT_ALLOWED)
|
||||
check("Not allowed to query: RefusedError, NOT_ALLOWED", ok, detail)
|
||||
|
||||
print()
|
||||
print("All checks passed" if fails == 0 else f"{fails} check(s) failed")
|
||||
|
||||
@@ -4,7 +4,7 @@ Usage: python example.py <ClientIni> <Topic> <Node> [--from-start]
|
||||
Run it from Build\\ (Build.ps1) while BakaShrot_Server.exe runs, e.g.:
|
||||
python ..\\Interactors\\Python\\example.py client.ini logs local
|
||||
and push from another terminal:
|
||||
.\\PushMessage.exe @msg.json client.ini
|
||||
.\\BakaShrotPushMessage.exe @msg.json client.ini
|
||||
Ctrl+C to stop.
|
||||
"""
|
||||
|
||||
@@ -27,7 +27,7 @@ dll = os.environ.get("BAKASHROT_DLL") or os.path.join(os.path.dirname(os.path.ab
|
||||
|
||||
try:
|
||||
with Client.from_ini(ini, dll) as client:
|
||||
print(f"Connected to {client.host}:{client.port} as {client.topic}:{client.node}, following {topic}:{node}")
|
||||
print(f"Connected to {client.host}:{client.port} as node {client.node}, following {topic}:{node}")
|
||||
for message in client.follow(topic, node, after=after):
|
||||
# Parsing is the app's business: the server stores anything.
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user