mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Moved the PureBasic version to OldSource/, Started the Rust rewrite in Source/
The rewrite's plan and decisions are in revamp.md. Steps 0 to 10 are done: the workspace and checks, bakashrot-proto, bakashrot-pki and bakashrot-cert, bakashrot-config, bakashrot-storage (schema v9), the server and the client library (every request but replication's, attachments and retention included), the C DLL with its C, PureBasic and Python bindings, and the bakashrot tool. Step 11 (replication) is next. OldSource/ is the old implementation, kept building and passing as the reference. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RwFeVTGs2SsufaH6zquzcb
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
# BakaShrot - Python client
|
||||
Python client for BakaShrot servers, over `BakaShrot_Client.dll`, without dependencies.
|
||||
|
||||
The wheel includes the DLLs it needs, nothing else to install or compile. \
|
||||
Windows 10 or later, 64-bit Python 3.8+.
|
||||
|
||||
> [!NOTE]
|
||||
> The client and the server must come from the same release, any other protocol version refuses the connection.
|
||||
|
||||
|
||||
## Linux
|
||||
The Linux wheel (`bakashrot-<version>-py3-none-linux_x86_64.whl`) holds only the client library,
|
||||
libsodium comes from the system: `apt install libsodium23` on Debian and Ubuntu. \
|
||||
Linux x86-64 with glibc 2.34+ (Debian 12, Ubuntu 22.04 or later), 64-bit Python 3.8+.
|
||||
|
||||
It's tagged `linux_x86_64`, not `manylinux`: manylinux doesn't allow depending on libsodium,
|
||||
so it goes on Gitea, not PyPI.
|
||||
|
||||
Building it: compile the client in the Docker compiler image (Debian 13, so glibc 2.34 is enough),
|
||||
named `BakaShrot_Client.dll` as the repository does on Linux, then `make_wheel.py --linux`:
|
||||
```shell
|
||||
docker run --rm -v "$PWD":/src:ro -v "$PWD/dist":/out -w /src git.nibblepoker.lu/packages/purebasic:6.41-linux3-trixie-slim \
|
||||
sh -c 'apt-get update -qq && apt-get install -y -qq libsodium-dev >/dev/null && pbcompilerc -t --optimizer Client/BakaShrot_Client.pbi -so /out/BakaShrot_Client.dll'
|
||||
python3 Interactors/Python/make_wheel.py dist dist --linux
|
||||
```
|
||||
|
||||
|
||||
## Installing
|
||||
From Gitea:
|
||||
```shell
|
||||
pip install --index-url https://git.nibblepoker.lu/api/packages/aziascreations/pypi/simple/ bakashrot
|
||||
```
|
||||
|
||||
From a GitHub release, or a release folder:
|
||||
```shell
|
||||
pip install https://github.com/aziascreations/BakaShrot/releases/download/v0.0.1/bakashrot-0.0.1-py3-none-win_amd64.whl
|
||||
pip install python\bakashrot-0.0.1-py3-none-win_amd64.whl
|
||||
```
|
||||
|
||||
Usage is in [bakashrot.py](bakashrot.py)'s docstring, and in [example.py](example.py).
|
||||
|
||||
|
||||
## Building
|
||||
`Release.ps1` builds the wheel into `Release\<version>\python\`, and checks it once installed by pip.
|
||||
|
||||
By hand, from the DLLs of a release folder or of `Build\`:
|
||||
```shell
|
||||
python Interactors/Python/make_wheel.py Release/<version> dist
|
||||
```
|
||||
|
||||
The version comes from `__version__` in [bakashrot.py](bakashrot.py).
|
||||
|
||||
|
||||
## Licenses
|
||||
The wheel's license is `CC0-1.0 AND ISC`:
|
||||
* BakaShrot is in the public domain ([CC0](../../LICENSE)).
|
||||
* The included `libsodium.dll` is under the [ISC license](../../Libs/libsodium/LICENSE),
|
||||
whose notice must ship with it: it's in the wheel's `dist-info/licenses/`.
|
||||
|
||||
`vcruntime140.dll`, which libsodium needs, isn't included: Python already loads its own.
|
||||
|
||||
|
||||
## Uploading
|
||||
|
||||
### Gitea
|
||||
Requires [twine](https://pypi.org/project/twine/) 6.1+ (for the license metadata), and your Gitea login or an access token with the `write:package` scope.
|
||||
```shell
|
||||
pip install twine
|
||||
twine upload --repository-url https://git.nibblepoker.lu/api/packages/aziascreations/pypi -u aziascreations dist/bakashrot-0.0.1-py3-none-win_amd64.whl
|
||||
```
|
||||
|
||||
### GitHub
|
||||
GitHub has no Python registry, the wheel is attached to the release instead.
|
||||
|
||||
Requires the [GitHub CLI](https://cli.github.com/), logged in with `gh auth login`.
|
||||
```shell
|
||||
gh release create v0.0.1 --repo aziascreations/BakaShrot --title "0.0.1" dist/bakashrot-0.0.1-py3-none-win_amd64.whl
|
||||
```
|
||||
|
||||
Or, if the release already exists:
|
||||
```shell
|
||||
gh release upload v0.0.1 --repo aziascreations/BakaShrot dist/bakashrot-0.0.1-py3-none-win_amd64.whl
|
||||
```
|
||||
@@ -0,0 +1,622 @@
|
||||
"""BakaShrot client for Python, over BakaShrot_Client.dll.
|
||||
|
||||
No dependencies beyond the standard library: the DLL is loaded with ctypes
|
||||
and does the connecting, authenticating and talking to the server. Messages
|
||||
come back as stored, a str that may or may not be JSON: parsing them is up
|
||||
to the app (Message.json() helps).
|
||||
|
||||
from bakashrot import Client
|
||||
|
||||
with Client.from_ini("client.ini") as client:
|
||||
message_id = client.push({"temperature": 21.5})
|
||||
for message in client.get_messages("logs", "kitchen", after=0).messages:
|
||||
print(message.id, message.data)
|
||||
for message in client.follow("logs", "kitchen"): # until stopped
|
||||
print(message.id, message.json())
|
||||
photo_id = client.push({"kind": "photo"}, attachment="photo.jpg")
|
||||
client.save_attachment("logs", "kitchen", photo_id, "copy.jpg")
|
||||
|
||||
Topics and nodes are "refs": a name ("logs") or an id (12, or "12"), ids
|
||||
being the server's own.
|
||||
|
||||
A message can have one attachment (a file, or bytes), of any size the
|
||||
server takes: uploaded in parts before the message is stored, read back in
|
||||
parts, checked with its SHA-256 (Design/Attachments.md).
|
||||
|
||||
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.
|
||||
|
||||
The DLL is 64-bit, so is the Python running this. It's looked for, in order:
|
||||
the dll_path given, the BAKASHROT_DLL environment variable, next to this
|
||||
file, then in the current directory. libsodium.dll must be next to it.
|
||||
The wheel (make_wheel.py, `pip install bakashrot`) has them all next to
|
||||
this file: nothing else to install or build.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import configparser
|
||||
import ctypes
|
||||
import enum
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Iterator, Optional, Union
|
||||
|
||||
# The release's, and the wheel's (make_wheel.py reads it from here).
|
||||
__version__ = "0.0.1"
|
||||
|
||||
__all__ = [
|
||||
"Client", "Message", "MessagesPage", "NameEntry", "NamesList",
|
||||
"BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode",
|
||||
"MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE",
|
||||
]
|
||||
|
||||
# Same as the server: Commons/Networking/Packets.pbi, GetMessagesPacket.pbi.
|
||||
MAX_GET_MESSAGES = 10000
|
||||
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: 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. code
|
||||
says why (1-99, e.g. ErrorCode.NOT_FOUND), reason in the server's words."""
|
||||
|
||||
def __init__(self, reason: str, code: int):
|
||||
super().__init__(reason or "Refused", code)
|
||||
self.reason = reason
|
||||
|
||||
|
||||
class ConnectionLostError(BakaShrotError):
|
||||
"""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)
|
||||
class Message:
|
||||
"""A stored message. data is as stored: JSON or not (the server's
|
||||
is_json column tells which, json() parses it). pushed_at: when it was
|
||||
pushed, to whichever server it was pushed to, in milliseconds since
|
||||
1970-01-01 UTC (pushed is the same as a datetime). attachment_size: its
|
||||
attachment's, 0 for none; attachment_ready: whether all of it is on
|
||||
this server (a replicated one comes after its message), see
|
||||
Client.get_attachment() and save_attachment()."""
|
||||
|
||||
id: int
|
||||
topic: str
|
||||
node: str
|
||||
topic_id: int
|
||||
node_id: int
|
||||
data: str
|
||||
pushed_at: int = 0
|
||||
attachment_size: int = 0
|
||||
attachment_ready: bool = False
|
||||
|
||||
def json(self) -> Any:
|
||||
"""The data parsed as JSON, raises ValueError if it isn't."""
|
||||
return json.loads(self.data)
|
||||
|
||||
@property
|
||||
def pushed(self) -> datetime:
|
||||
"""When it was pushed, as an aware datetime in UTC."""
|
||||
return datetime.fromtimestamp(self.pushed_at / 1000, tz=timezone.utc)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MessagesPage:
|
||||
"""One answer to get_messages(): in message id order. more is True if
|
||||
more follow the last one, ask again with after=last_id."""
|
||||
|
||||
messages: list = field(default_factory=list)
|
||||
more: bool = False
|
||||
|
||||
@property
|
||||
def last_id(self) -> Optional[int]:
|
||||
return self.messages[-1].id if self.messages else None
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.messages)
|
||||
|
||||
def __len__(self):
|
||||
return len(self.messages)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NameEntry:
|
||||
id: int
|
||||
name: str # "" if unnamed: those don't replicate
|
||||
origin: str # "config", "id", "peer"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NamesList:
|
||||
kind: str # "topic" or "node"
|
||||
items: list
|
||||
truncated: bool # True if they didn't all fit in one answer
|
||||
|
||||
|
||||
def _ref(value: Ref) -> bytes:
|
||||
if isinstance(value, bool) or not isinstance(value, (str, int)):
|
||||
raise TypeError(f"a topic or node is a name or an id, not {value!r}")
|
||||
if isinstance(value, int) and not 0 <= value <= 65535:
|
||||
raise ValueError(f"an id is 0-65535, not {value}")
|
||||
return str(value).encode("utf-8")
|
||||
|
||||
|
||||
def _find_dll(dll_path: Optional[str]) -> str:
|
||||
candidates = []
|
||||
if dll_path:
|
||||
candidates.append(dll_path)
|
||||
if os.environ.get("BAKASHROT_DLL"):
|
||||
candidates.append(os.environ["BAKASHROT_DLL"])
|
||||
candidates.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "BakaShrot_Client.dll"))
|
||||
candidates.append(os.path.join(os.getcwd(), "BakaShrot_Client.dll"))
|
||||
for candidate in candidates:
|
||||
if os.path.isfile(candidate):
|
||||
return os.path.abspath(candidate)
|
||||
raise BakaShrotError("BakaShrot_Client.dll not found, looked at: " + ", ".join(candidates))
|
||||
|
||||
|
||||
class _Dll:
|
||||
"""The DLL's functions, with their types. Loaded once per process."""
|
||||
|
||||
_instance: Optional["_Dll"] = None
|
||||
_instance_lock = threading.Lock()
|
||||
|
||||
@classmethod
|
||||
def get(cls, dll_path: Optional[str]) -> "_Dll":
|
||||
with cls._instance_lock:
|
||||
if cls._instance is None:
|
||||
cls._instance = cls(_find_dll(dll_path))
|
||||
return cls._instance
|
||||
|
||||
def __init__(self, path: str):
|
||||
if ctypes.sizeof(ctypes.c_void_p) != 8:
|
||||
raise BakaShrotError("BakaShrot_Client.dll is 64-bit, this Python is 32-bit")
|
||||
try:
|
||||
self.lib = ctypes.CDLL(path)
|
||||
except OSError as error:
|
||||
raise BakaShrotError(f"Failed to load {path} (is libsodium.dll next to it?): {error}") from error
|
||||
self.path = path
|
||||
|
||||
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_SetNodeA": (I, [P]),
|
||||
"BakaShrot_ConnectA": (I, [P, L]),
|
||||
"BakaShrot_IsConnected": (I, []),
|
||||
"BakaShrot_Disconnect": (I, []),
|
||||
"BakaShrot_PushMessageToA": (Q, [P, P]),
|
||||
"BakaShrot_GetLatestMessageOfA": (I, [P, P]),
|
||||
"BakaShrot_GetMessagesA": (L, [P, P, Q, L]),
|
||||
"BakaShrot_GetMessageCount": (L, []),
|
||||
"BakaShrot_SelectMessage": (I, [L]),
|
||||
"BakaShrot_HasMoreMessages": (I, []),
|
||||
"BakaShrot_GetMessageId": (Q, []),
|
||||
"BakaShrot_GetMessagePushedAt": (Q, []),
|
||||
"BakaShrot_GetMessageAttachmentSize": (Q, []),
|
||||
"BakaShrot_IsMessageAttachmentReady": (I, []),
|
||||
"BakaShrot_PushMessageWithFileA": (Q, [P, P, P]),
|
||||
"BakaShrot_PushMessageWithDataA": (Q, [P, P, S, Q]),
|
||||
"BakaShrot_SaveAttachmentA": (Q, [P, P, Q, P]),
|
||||
"BakaShrot_LoadAttachmentA": (Q, [P, P, Q]),
|
||||
"BakaShrot_GetAttachmentData": (Q, [S, Q]),
|
||||
"BakaShrot_FreeAttachmentData": (I, []),
|
||||
"BakaShrot_GetMessageTopicId": (L, []),
|
||||
"BakaShrot_GetMessageNodeId": (L, []),
|
||||
"BakaShrot_GetMessageTopicA": (I, [S, I]),
|
||||
"BakaShrot_GetMessageNodeA": (I, [S, I]),
|
||||
"BakaShrot_GetMessageDataA": (I, [S, I]),
|
||||
"BakaShrot_ResolveTopicA": (L, [P]),
|
||||
"BakaShrot_ResolveNodeA": (L, [P]),
|
||||
"BakaShrot_GetResolvedNameA": (I, [S, I]),
|
||||
"BakaShrot_ListTopics": (L, []),
|
||||
"BakaShrot_ListNodes": (L, []),
|
||||
"BakaShrot_GetNamesListA": (I, [S, I]),
|
||||
"BakaShrot_QueryA": (I, [P]),
|
||||
"BakaShrot_GetQueryResultA": (I, [S, I]),
|
||||
"BakaShrot_GetRefusalReasonA": (I, [S, I]),
|
||||
}
|
||||
for name, (restype, argtypes) in signatures.items():
|
||||
try:
|
||||
function = getattr(self.lib, name)
|
||||
except AttributeError as 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)
|
||||
|
||||
def string(self, getter) -> str:
|
||||
"""Calls a string getter: asks for the size, then copies (UTF-8)."""
|
||||
size = getter(None, 0)
|
||||
if size <= 1:
|
||||
return ""
|
||||
buffer = ctypes.create_string_buffer(size)
|
||||
getter(buffer, size)
|
||||
return buffer.raw[: size - 1].decode("utf-8")
|
||||
|
||||
|
||||
class Client:
|
||||
"""A connection to a BakaShrot server, through the DLL.
|
||||
|
||||
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.
|
||||
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, 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.node = node
|
||||
self.host = host
|
||||
self.port = int(port)
|
||||
|
||||
@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, 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}'", 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}", ErrorCode.INVALID_ARGUMENT)
|
||||
return value.strip()
|
||||
|
||||
return cls(get("PrivateKey"), get("PublicKey"), get("ServerPublicKey"),
|
||||
get("Node", section.get("NodeId")),
|
||||
get("ServerHost"), int(get("ServerPort")), dll_path)
|
||||
|
||||
# --- Connection --------------------------------------------------------
|
||||
|
||||
def connect(self) -> "Client":
|
||||
"""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", 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", dll.GetLastError())
|
||||
if not dll.SetPublicKeyA(self.public_key.encode("ascii")):
|
||||
raise BakaShrotError("Invalid public key", dll.GetLastError())
|
||||
if not dll.SetServerPublicKeyA(self.server_public_key.encode("ascii")):
|
||||
raise BakaShrotError("Invalid server public key", dll.GetLastError())
|
||||
if not dll.SetNodeA(_ref(self.node)):
|
||||
raise BakaShrotError(f"Invalid node {self.node!r}", dll.GetLastError())
|
||||
if not dll.ConnectA(self.host.encode("utf-8"), self.port):
|
||||
raise self._failed(f"Connect to {self.host}:{self.port}")
|
||||
Client._connected_client = self
|
||||
return self
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
if Client._connected_client is self:
|
||||
self._dll.Disconnect()
|
||||
Client._connected_client = None
|
||||
|
||||
@property
|
||||
def connected(self) -> bool:
|
||||
return Client._connected_client is self and bool(self._dll.IsConnected())
|
||||
|
||||
def __enter__(self) -> "Client":
|
||||
return self.connect()
|
||||
|
||||
def __exit__(self, *_) -> None:
|
||||
self.close()
|
||||
|
||||
def _check_connected(self) -> None:
|
||||
if not self.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 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
|
||||
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 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.
|
||||
|
||||
attachment: bytes, or the path of a file, uploaded first (in parts,
|
||||
any size the server's MaxAttachmentSize allows): the message is only
|
||||
stored once all of it is."""
|
||||
if not isinstance(data, str):
|
||||
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}", ErrorCode.INVALID_ARGUMENT)
|
||||
topic_ref = b"" if topic is None else _ref(topic)
|
||||
with self._lock:
|
||||
self._check_connected()
|
||||
if attachment is None:
|
||||
message_id = self._dll.PushMessageToA(topic_ref, encoded)
|
||||
elif isinstance(attachment, (bytes, bytearray, memoryview)):
|
||||
raw = bytes(attachment)
|
||||
if not raw:
|
||||
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", ErrorCode.FILE_ERROR)
|
||||
message_id = self._dll.PushMessageWithFileA(topic_ref, encoded, path.encode("utf-8"))
|
||||
if message_id < 1:
|
||||
raise self._failed("Push")
|
||||
return message_id
|
||||
|
||||
def get_attachment(self, topic: Ref, node: Ref, message_id: int) -> bytes:
|
||||
"""The attachment of topic:node#message_id, all of it in memory
|
||||
(save_attachment() for big ones), checked with its SHA-256. Raises
|
||||
RefusedError if the message has none, or it isn't on this server
|
||||
yet."""
|
||||
with self._lock:
|
||||
self._check_connected()
|
||||
size = self._dll.LoadAttachmentA(_ref(topic), _ref(node), int(message_id))
|
||||
if size < 0:
|
||||
raise self._failed("Attachment")
|
||||
try:
|
||||
buffer = ctypes.create_string_buffer(size)
|
||||
self._dll.GetAttachmentData(ctypes.cast(buffer, ctypes.c_void_p), size)
|
||||
return buffer.raw[:size]
|
||||
finally:
|
||||
self._dll.FreeAttachmentData()
|
||||
|
||||
def save_attachment(self, topic: Ref, node: Ref, message_id: int, path: Union[str, os.PathLike]) -> int:
|
||||
"""Saves the attachment of topic:node#message_id to path (replaced),
|
||||
a part at a time, checked with its SHA-256. Returns its size. A
|
||||
failed one leaves no file."""
|
||||
with self._lock:
|
||||
self._check_connected()
|
||||
size = self._dll.SaveAttachmentA(_ref(topic), _ref(node), int(message_id), os.fspath(path).encode("utf-8"))
|
||||
if size < 0:
|
||||
raise self._failed("Attachment")
|
||||
return size
|
||||
|
||||
def _current(self) -> Message:
|
||||
dll = self._dll
|
||||
return Message(dll.GetMessageId(), dll.string(dll.GetMessageTopicA), dll.string(dll.GetMessageNodeA),
|
||||
dll.GetMessageTopicId(), dll.GetMessageNodeId(), dll.string(dll.GetMessageDataA),
|
||||
dll.GetMessagePushedAt(), dll.GetMessageAttachmentSize(), bool(dll.IsMessageAttachmentReady()))
|
||||
|
||||
def latest(self, topic: Ref, node: Ref) -> Optional[Message]:
|
||||
"""The latest message of topic/node, None if there's none yet."""
|
||||
with self._lock:
|
||||
self._check_connected()
|
||||
if not self._dll.GetLatestMessageOfA(_ref(topic), _ref(node)):
|
||||
error = self._failed("Latest message")
|
||||
if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND:
|
||||
return None
|
||||
raise error
|
||||
return self._current()
|
||||
|
||||
def get_messages(self, topic: Ref, node: Ref, after: int = 0, limit: int = 1000) -> MessagesPage:
|
||||
"""The messages of topic/node after message id `after` (0: from the
|
||||
first), in id order: at most limit (1-10000), fewer if they didn't
|
||||
fit in about 1 MB (a bigger one comes alone). None if there are no
|
||||
more, that's not an error."""
|
||||
if not 1 <= limit <= MAX_GET_MESSAGES:
|
||||
raise ValueError(f"limit is 1-{MAX_GET_MESSAGES}, not {limit}")
|
||||
if after < 0:
|
||||
raise ValueError(f"after is 0 or more, not {after}")
|
||||
with self._lock:
|
||||
self._check_connected()
|
||||
dll = self._dll
|
||||
count = dll.GetMessagesA(_ref(topic), _ref(node), after, limit)
|
||||
if count < 0:
|
||||
raise self._failed("Get messages")
|
||||
messages = []
|
||||
for index in range(count):
|
||||
dll.SelectMessage(index)
|
||||
messages.append(self._current())
|
||||
return MessagesPage(messages, bool(dll.HasMoreMessages()))
|
||||
|
||||
def iter_messages(self, topic: Ref, node: Ref, after: int = 0, batch: int = 1000) -> Iterator[Message]:
|
||||
"""Every message of topic/node after `after`, asking for batch at a
|
||||
time, until there are no more."""
|
||||
while True:
|
||||
page = self.get_messages(topic, node, after, batch)
|
||||
yield from page.messages
|
||||
if page.messages:
|
||||
after = page.last_id
|
||||
if not page.more:
|
||||
return
|
||||
|
||||
def follow(self, topic: Ref, node: Ref, 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.
|
||||
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
|
||||
elif not isinstance(after, int):
|
||||
raise ValueError(f"after is a message id or 'latest', not {after!r}")
|
||||
while True:
|
||||
page = self.get_messages(topic, node, after, batch)
|
||||
yield from page.messages
|
||||
if page.messages:
|
||||
after = page.last_id
|
||||
if not page.more:
|
||||
time.sleep(interval)
|
||||
|
||||
def resolve_topic(self, ref: Ref) -> tuple:
|
||||
"""(id, name) of a topic on this server, name "" if unnamed."""
|
||||
return self._resolve(self._dll.ResolveTopicA, ref, "Resolve topic")
|
||||
|
||||
def resolve_node(self, ref: Ref) -> tuple:
|
||||
"""(id, name) of a node on this server, name "" if unnamed."""
|
||||
return self._resolve(self._dll.ResolveNodeA, ref, "Resolve node")
|
||||
|
||||
def _resolve(self, function, ref: Ref, what: str) -> tuple:
|
||||
with self._lock:
|
||||
self._check_connected()
|
||||
resolved = function(_ref(ref))
|
||||
if resolved < 0:
|
||||
raise self._failed(what)
|
||||
return resolved, self._dll.string(self._dll.GetResolvedNameA)
|
||||
|
||||
def list_topics(self) -> NamesList:
|
||||
"""Every topic the client may see, with this server's ids."""
|
||||
return self._list(self._dll.ListTopics, "List topics")
|
||||
|
||||
def list_nodes(self) -> NamesList:
|
||||
"""Every node, with this server's ids."""
|
||||
return self._list(self._dll.ListNodes, "List nodes")
|
||||
|
||||
def _list(self, function, what: str) -> NamesList:
|
||||
with self._lock:
|
||||
self._check_connected()
|
||||
if function() < 0:
|
||||
raise self._failed(what)
|
||||
parsed = json.loads(self._dll.string(self._dll.GetNamesListA))
|
||||
return NamesList(parsed["kind"], [NameEntry(i["id"], i["name"], i["origin"]) for i in parsed["items"]],
|
||||
bool(parsed["truncated"]))
|
||||
|
||||
def query_raw(self, sql: str) -> str:
|
||||
"""Runs one read-only SELECT on the server (the client needs
|
||||
AllowQuery = 1), returns its result as the server's JSON text:
|
||||
{"columns": [...], "rows": [[...], ...]}, every value a str or null.
|
||||
JSON functions on message_data need "is_json = 1" in the WHERE (or
|
||||
CASE WHEN is_json THEN ... END) when some rows aren't JSON, or the
|
||||
query is refused: RefusedError "Query failed: malformed JSON"."""
|
||||
with self._lock:
|
||||
self._check_connected()
|
||||
if not self._dll.QueryA(sql.encode("utf-8")):
|
||||
raise self._failed("Query")
|
||||
return self._dll.string(self._dll.GetQueryResultA)
|
||||
|
||||
def query(self, sql: str) -> list:
|
||||
"""query_raw(), as a list of dicts, one per row, by column name."""
|
||||
result = json.loads(self.query_raw(sql))
|
||||
columns = result["columns"]
|
||||
return [dict(zip(columns, row)) for row in result["rows"]]
|
||||
@@ -0,0 +1,229 @@
|
||||
"""Checks bakashrot.py against a running server, run by Tests/Python-Test.ps1.
|
||||
|
||||
Usage: python check_bakashrot.py <DllPath> <KitchenIni> <LoungeIni>
|
||||
KitchenIni logs:kitchen, may push to logs and secret, read everything, query.
|
||||
LoungeIni logs:lounge, may read logs only.
|
||||
Expects an empty database. Prints PASS/FAIL per check, exits 1 if any failed.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
import bakashrot
|
||||
from bakashrot import AuthError, BakaShrotError, Client, ConnectionLostError, ErrorCode, RefusedError
|
||||
|
||||
dll_path, kitchen_ini, lounge_ini = sys.argv[1:4]
|
||||
fails = 0
|
||||
|
||||
|
||||
def check(what, ok, detail=""):
|
||||
global fails
|
||||
if not ok:
|
||||
fails += 1
|
||||
detail = str(detail)
|
||||
if len(detail) > 300:
|
||||
detail = detail[:300] + f"... ({len(detail)} chars)"
|
||||
print(f"{'PASS' if ok else 'FAIL'} {what}\n -> {detail}", flush=True)
|
||||
|
||||
|
||||
def raises(function, error_type, contains="", code=None):
|
||||
try:
|
||||
function()
|
||||
except error_type as 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"
|
||||
|
||||
|
||||
kitchen = Client.from_ini(kitchen_ini, dll_path)
|
||||
lounge = Client.from_ini(lounge_ini, dll_path)
|
||||
|
||||
with kitchen:
|
||||
check("Connects from client.ini", kitchen.connected, kitchen._dll.path)
|
||||
|
||||
# --- Nothing yet ---------------------------------------------------------
|
||||
check("latest() with no messages: None", kitchen.latest("logs", "kitchen") is None)
|
||||
page = kitchen.get_messages("logs", "kitchen")
|
||||
check("get_messages() with no messages: empty, no more", len(page) == 0 and not page.more and page.last_id is None, page)
|
||||
|
||||
# --- Pushes --------------------------------------------------------------
|
||||
started = time.perf_counter()
|
||||
ids = [kitchen.push({"i": i}) for i in range(1, 251)]
|
||||
elapsed = time.perf_counter() - started
|
||||
check("250 pushes on one connection, ids 1-250", ids == list(range(1, 251)),
|
||||
f"{elapsed * 1000:.0f} ms, {250 / elapsed:.0f} msg/s")
|
||||
|
||||
latest = kitchen.latest("logs", "kitchen")
|
||||
check("latest(): #250", latest is not None and latest.id == 250 and latest.json() == {"i": 250}, latest)
|
||||
now_ms = int(time.time() * 1000)
|
||||
check("latest().pushed_at: just now, UTC ms", latest is not None and now_ms - 60000 < latest.pushed_at <= now_ms + 1000,
|
||||
f"{latest.pushed_at if latest else None} vs {now_ms}")
|
||||
check("latest().pushed: the same, an aware datetime in UTC",
|
||||
latest is not None and latest.pushed.tzinfo is not None and latest.pushed.utcoffset().total_seconds() == 0
|
||||
and int(latest.pushed.timestamp() * 1000) == latest.pushed_at, latest.pushed if latest else None)
|
||||
|
||||
topic_id, topic_name = kitchen.resolve_topic("logs")
|
||||
node_id, node_name = kitchen.resolve_node("kitchen")
|
||||
check("resolve_topic/node()", (topic_id, topic_name, node_id, node_name) == (1, "logs", 5, "kitchen"),
|
||||
(topic_id, topic_name, node_id, node_name))
|
||||
|
||||
# --- Pages ---------------------------------------------------------------
|
||||
page = kitchen.get_messages("logs", "kitchen", after=0, limit=100)
|
||||
check("First page: 1-100, more", [m.id for m in page] == list(range(1, 101)) and page.more and page.last_id == 100,
|
||||
f"{len(page)} messages, more={page.more}")
|
||||
first = page.messages[0]
|
||||
check("A message's fields", (first.topic, first.node, first.topic_id, first.node_id, first.data, first.json())
|
||||
== ("logs", "kitchen", 1, 5, '{"i":1}', {"i": 1}), first)
|
||||
stamps = [m.pushed_at for m in page]
|
||||
check("Each message of a page has its pushed_at, in push order", all(stamps) and stamps == sorted(stamps),
|
||||
f"{stamps[0]} .. {stamps[-1]}")
|
||||
|
||||
page = kitchen.get_messages("logs", "kitchen", after=200, limit=100)
|
||||
check("Last page: 201-250, no more", [m.id for m in page] == list(range(201, 251)) and not page.more,
|
||||
f"{len(page)} messages, more={page.more}")
|
||||
|
||||
page = kitchen.get_messages("logs", "kitchen", after=150, limit=100)
|
||||
check("Exactly up to the last one: 151-250, no more", [m.id for m in page] == list(range(151, 251)) and not page.more,
|
||||
f"{len(page)} messages, more={page.more}")
|
||||
|
||||
page = kitchen.get_messages("1", 5, after=250)
|
||||
check("After the last one, by ids: empty, no more", len(page) == 0 and not page.more, page)
|
||||
|
||||
every = list(kitchen.iter_messages("logs", "kitchen", batch=37))
|
||||
check("iter_messages(batch=37): all 250 in order", [m.id for m in every] == list(range(1, 251)), f"{len(every)} messages")
|
||||
|
||||
# --- Data ----------------------------------------------------------------
|
||||
text_id = kitchen.push("plain text, not JSON")
|
||||
unicode_id = kitchen.push("héllo wörld, 🌍, 日本語")
|
||||
empty_id = kitchen.push("")
|
||||
page = kitchen.get_messages("logs", "kitchen", after=250)
|
||||
data = [m.data for m in page]
|
||||
check("Non-JSON, non-ASCII and empty data read back as pushed",
|
||||
data == ["plain text, not JSON", "héllo wörld, 🌍, 日本語", ""] and [m.id for m in page] == [text_id, unicode_id, empty_id],
|
||||
data)
|
||||
ok, detail = raises(lambda: page.messages[0].json(), ValueError)
|
||||
check("json() on non-JSON data raises ValueError", ok, detail)
|
||||
|
||||
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)
|
||||
big_ids = [kitchen.push(big) for _ in range(3)]
|
||||
page = kitchen.get_messages("logs", "kitchen", after=empty_id, limit=10)
|
||||
check("3 x 700 KB: one per answer, more", [m.id for m in page] == big_ids[:1] and page.more and page.messages[0].data == big,
|
||||
f"{len(page)} messages, more={page.more}")
|
||||
every = list(kitchen.iter_messages("logs", "kitchen", after=empty_id))
|
||||
check("iter_messages() over them: all 3, whole", [m.id for m in every] == big_ids and all(m.data == big for m in every),
|
||||
[len(m.data) for m in every])
|
||||
|
||||
# --- Refusals ------------------------------------------------------------
|
||||
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", 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", ErrorCode.ALREADY_CONNECTED)
|
||||
check("A second Client can't connect while one is", ok and not lounge.connected, detail)
|
||||
|
||||
topics = kitchen.list_topics()
|
||||
check("list_topics()", topics.kind == "topic" and {"logs", "secret"} <= {t.name for t in topics.items}, topics)
|
||||
|
||||
# --- follow() ------------------------------------------------------------
|
||||
followed = []
|
||||
errors = []
|
||||
|
||||
def follower():
|
||||
try:
|
||||
for message in kitchen.follow("logs", "kitchen", after="latest", interval=0.05):
|
||||
followed.append(message)
|
||||
if len(followed) == 5:
|
||||
return
|
||||
except Exception as error: # noqa: BLE001 - reported below
|
||||
errors.append(error)
|
||||
|
||||
thread = threading.Thread(target=follower, daemon=True)
|
||||
thread.start()
|
||||
time.sleep(0.5)
|
||||
new_ids = [kitchen.push({"f": i}) for i in range(5)]
|
||||
thread.join(10)
|
||||
check("follow(after='latest') from another thread: only the 5 new ones",
|
||||
not thread.is_alive() and not errors and [m.id for m in followed] == new_ids,
|
||||
f"{[m.id for m in followed]} vs {new_ids}, errors {errors}")
|
||||
|
||||
# --- Attachments (in secret, the other checks count logs) -------------------
|
||||
blob = os.urandom(3 * 1024 * 1024 + 7)
|
||||
started = time.perf_counter()
|
||||
blob_id = kitchen.push({"kind": "blob"}, topic="secret", attachment=blob)
|
||||
up = time.perf_counter() - started
|
||||
message = kitchen.latest("secret", "kitchen")
|
||||
check("push(attachment=bytes): the message has it, ready",
|
||||
message is not None and message.id == blob_id and message.attachment_size == len(blob) and message.attachment_ready,
|
||||
message)
|
||||
started = time.perf_counter()
|
||||
data = kitchen.get_attachment("secret", "kitchen", blob_id)
|
||||
down = time.perf_counter() - started
|
||||
check("get_attachment(): the same bytes", data == blob, f"{len(data)} bytes, {up * 1000:.0f} ms up, {down * 1000:.0f} ms down")
|
||||
|
||||
folder = tempfile.mkdtemp()
|
||||
source = os.path.join(folder, "source.bin")
|
||||
with open(source, "wb") as file:
|
||||
file.write(os.urandom(1500 * 1024))
|
||||
file_id = kitchen.push("from a file", topic="secret", attachment=source)
|
||||
copy = os.path.join(folder, "copy.bin")
|
||||
size = kitchen.save_attachment("secret", "kitchen", file_id, copy)
|
||||
with open(source, "rb") as a, open(copy, "rb") as b:
|
||||
same = hashlib.sha256(a.read()).digest() == hashlib.sha256(b.read()).digest()
|
||||
check("push(attachment=path), save_attachment(): the same file", size == os.path.getsize(source) and same, size)
|
||||
|
||||
plain_id = kitchen.push("no attachment", topic="secret")
|
||||
page = kitchen.get_messages("secret", "kitchen", after=blob_id - 1)
|
||||
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", 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", 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, 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'", 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")
|
||||
sys.exit(1 if fails else 0)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Example app: catches up on a topic/node's messages, then follows new ones.
|
||||
|
||||
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:
|
||||
.\\BakaShrotPushMessage.exe @msg.json client.ini
|
||||
Ctrl+C to stop.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from bakashrot import Client, ConnectionLostError # noqa: E402
|
||||
|
||||
if len(sys.argv) < 4:
|
||||
print(__doc__)
|
||||
sys.exit(1)
|
||||
|
||||
ini, topic, node = sys.argv[1:4]
|
||||
after = 0 if "--from-start" in sys.argv[4:] else "latest"
|
||||
|
||||
# The DLL next to the ini (Build\), unless BAKASHROT_DLL says otherwise.
|
||||
dll = os.environ.get("BAKASHROT_DLL") or os.path.join(os.path.dirname(os.path.abspath(ini)), "BakaShrot_Client.dll")
|
||||
|
||||
try:
|
||||
with Client.from_ini(ini, dll) as client:
|
||||
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:
|
||||
shown = json.dumps(message.json())
|
||||
except ValueError:
|
||||
shown = f"(not JSON) {message.data!r}"
|
||||
print(f"{message.topic}:{message.node}#{message.id} {shown}")
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
except ConnectionLostError as error:
|
||||
print(error)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,204 @@
|
||||
"""Builds the bakashrot wheel: bakashrot.py with the client library it
|
||||
needs, so that `pip install` is all a Python app needs, nothing to compile.
|
||||
|
||||
python make_wheel.py <BinDir> [OutDir] [--linux]
|
||||
|
||||
BinDir holds BakaShrot_Client.dll and libsodium.dll (a release folder, or
|
||||
Build\\). OutDir defaults to the current directory. Release.ps1 runs it.
|
||||
Prints the wheel's path.
|
||||
|
||||
--linux: the Linux wheel instead, from a Linux build's BakaShrot_Client.dll
|
||||
(the .so, named as on Windows: bakashrot.py and the tools look for that
|
||||
name). libsodium isn't in it: it comes from the system (Debian/Ubuntu:
|
||||
libsodium23), and the wheel needs glibc 2.34+. Tagged linux_x86_64, not
|
||||
manylinux: manylinux doesn't allow depending on libsodium. Build the .so on
|
||||
an old enough glibc (the Docker compiler image, Debian 13, needs 2.34).
|
||||
|
||||
Licenses: BakaShrot is CC0-1.0, libsodium ISC, which asks for its notice
|
||||
in every copy: both are in the Windows wheel's dist-info/licenses/ (LICENSE,
|
||||
and Libs/libsodium/LICENSE), the metadata says "CC0-1.0 AND ISC". The Linux
|
||||
wheel only has LICENSE, "CC0-1.0", libsodium not being in it.
|
||||
vcruntime140.dll, which libsodium.dll needs, isn't in the Windows wheel:
|
||||
every CPython on Windows has loaded its own already, and that's the one used.
|
||||
|
||||
The wheel is bakashrot-<version>-py3-none-win_amd64.whl (or
|
||||
-linux_x86_64.whl), the version being bakashrot.py's __version__. Inside
|
||||
it, bakashrot.py is bakashrot/__init__.py, the libraries next to it, where
|
||||
bakashrot.py looks first. Only the standard library: no setuptools, no
|
||||
build step, and the same inputs give the same wheel (fixed timestamps).
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.normpath(os.path.join(HERE, "..", ".."))
|
||||
|
||||
NAME = "bakashrot"
|
||||
# Zip entries' timestamp, so the wheel only changes when its content does.
|
||||
FIXED_TIME = (2026, 1, 1, 0, 0, 0)
|
||||
|
||||
USAGE_EXAMPLE = """\
|
||||
```python
|
||||
from bakashrot import Client
|
||||
|
||||
with Client.from_ini("client.ini") as client:
|
||||
message_id = client.push({"temperature": 21.5})
|
||||
for message in client.get_messages("logs", "kitchen", after=0).messages:
|
||||
print(message.id, message.data)
|
||||
```
|
||||
|
||||
See the module's docstring (`help(bakashrot)`) for the rest.
|
||||
"""
|
||||
|
||||
WINDOWS = {
|
||||
"tag": "py3-none-win_amd64",
|
||||
"libraries": ["BakaShrot_Client.dll", "libsodium.dll"],
|
||||
# In the wheel's dist-info/licenses/, from the repository's root.
|
||||
"licenses": {"LICENSE": "../LICENSE", "libsodium/LICENSE": "Libs/libsodium/LICENSE"},
|
||||
"license_expression": "CC0-1.0 AND ISC",
|
||||
"classifier": "Operating System :: Microsoft :: Windows :: Windows 10",
|
||||
"summary": "Python client for BakaShrot servers, with the client DLL included",
|
||||
"description": """\
|
||||
# bakashrot
|
||||
|
||||
Python client for [BakaShrot](https://github.com/aziascreations/BakaShrot)
|
||||
servers: push messages and attachments, read them back, resolve names, query.
|
||||
|
||||
Includes `BakaShrot_Client.dll` and `libsodium.dll`: nothing else to install
|
||||
or build. Windows 10 or later, 64-bit Python 3.8+. The server must speak the
|
||||
same protocol: use the release this package comes from.
|
||||
|
||||
BakaShrot is CC0-1.0 (public domain). The included libsodium is Frank
|
||||
Denis's, under the ISC license: its notice is in this package's
|
||||
`licenses/libsodium/LICENSE`.
|
||||
|
||||
""" + USAGE_EXAMPLE,
|
||||
}
|
||||
|
||||
LINUX = {
|
||||
"tag": "py3-none-linux_x86_64",
|
||||
"libraries": ["BakaShrot_Client.dll"],
|
||||
"licenses": {"LICENSE": "../LICENSE"},
|
||||
"license_expression": "CC0-1.0",
|
||||
"classifier": "Operating System :: POSIX :: Linux",
|
||||
"summary": "Python client for BakaShrot servers, with the client library included",
|
||||
"description": """\
|
||||
# bakashrot
|
||||
|
||||
Python client for [BakaShrot](https://github.com/aziascreations/BakaShrot)
|
||||
servers: push messages and attachments, read them back, resolve names, query.
|
||||
|
||||
Includes the client library (`BakaShrot_Client.dll`, a Linux shared object
|
||||
named as on Windows). Needs libsodium from the system, nothing else to build:
|
||||
`apt install libsodium23` on Debian and Ubuntu. Linux x86-64 with glibc 2.34+
|
||||
(Debian 12, Ubuntu 22.04 or later), 64-bit Python 3.8+. The server must speak
|
||||
the same protocol: use the release this package comes from.
|
||||
|
||||
BakaShrot is CC0-1.0 (public domain).
|
||||
|
||||
""" + USAGE_EXAMPLE,
|
||||
}
|
||||
|
||||
|
||||
def read_version(module_path):
|
||||
with open(module_path, encoding="utf-8") as file:
|
||||
match = re.search(r'^__version__ = "([^"]+)"', file.read(), re.MULTILINE)
|
||||
if not match:
|
||||
sys.exit(f"No __version__ in {module_path}")
|
||||
return match.group(1)
|
||||
|
||||
|
||||
def record_line(path, data):
|
||||
digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode("ascii")
|
||||
return f"{path},sha256={digest},{len(data)}"
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
platform = WINDOWS
|
||||
if "--linux" in args:
|
||||
args.remove("--linux")
|
||||
platform = LINUX
|
||||
if len(args) not in (1, 2):
|
||||
sys.exit(__doc__)
|
||||
bin_dir = args[0]
|
||||
out_dir = args[1] if len(args) == 2 else os.getcwd()
|
||||
tag = platform["tag"]
|
||||
|
||||
module_path = os.path.join(HERE, "bakashrot.py")
|
||||
version = read_version(module_path)
|
||||
dist_info = f"{NAME}-{version}.dist-info"
|
||||
|
||||
files = [] # (path in the wheel, bytes)
|
||||
with open(module_path, "rb") as file:
|
||||
files.append((f"{NAME}/__init__.py", file.read()))
|
||||
for library in platform["libraries"]:
|
||||
path = os.path.join(bin_dir, library)
|
||||
if not os.path.isfile(path):
|
||||
sys.exit(f"Missing {path}")
|
||||
with open(path, "rb") as file:
|
||||
data = file.read()
|
||||
# A Windows DLL starts with "MZ", a Linux .so with "\x7fELF": a
|
||||
# library from the other platform would only fail once imported.
|
||||
if platform is LINUX and not data.startswith(b"\x7fELF"):
|
||||
sys.exit(f"{path} isn't a Linux shared object (build it on Linux, or drop --linux)")
|
||||
if platform is WINDOWS and data.startswith(b"\x7fELF"):
|
||||
sys.exit(f"{path} is a Linux shared object (add --linux)")
|
||||
files.append((f"{NAME}/{library}", data))
|
||||
|
||||
# Metadata 2.4 (PEP 639): an SPDX expression and the license files,
|
||||
# without license classifiers (not allowed with an expression).
|
||||
metadata = "\n".join([
|
||||
"Metadata-Version: 2.4",
|
||||
f"Name: {NAME}",
|
||||
f"Version: {version}",
|
||||
f"Summary: {platform['summary']}",
|
||||
"Author: Herwin Bozet (NibblePoker)",
|
||||
f"License-Expression: {platform['license_expression']}",
|
||||
] + [f"License-File: {name}" for name in platform["licenses"]] + [
|
||||
"Project-URL: GitHub, https://github.com/aziascreations/BakaShrot",
|
||||
"Project-URL: Gitea, https://git.nibblepoker.lu/aziascreations/BakaShrot",
|
||||
f"Classifier: {platform['classifier']}",
|
||||
"Classifier: Programming Language :: Python :: 3",
|
||||
"Requires-Python: >=3.8",
|
||||
"Description-Content-Type: text/markdown",
|
||||
"",
|
||||
platform["description"],
|
||||
]).encode("utf-8")
|
||||
files.append((f"{dist_info}/METADATA", metadata))
|
||||
files.append((f"{dist_info}/WHEEL", "\n".join([
|
||||
"Wheel-Version: 1.0",
|
||||
"Generator: BakaShrot make_wheel.py",
|
||||
"Root-Is-Purelib: false",
|
||||
f"Tag: {tag}",
|
||||
"",
|
||||
]).encode("utf-8")))
|
||||
for name, source in platform["licenses"].items():
|
||||
path = os.path.join(ROOT, source)
|
||||
if not os.path.isfile(path):
|
||||
sys.exit(f"Missing {path}")
|
||||
with open(path, "rb") as file:
|
||||
files.append((f"{dist_info}/licenses/{name}", file.read()))
|
||||
|
||||
record = "\n".join([record_line(path, data) for path, data in files] + [f"{dist_info}/RECORD,,", ""])
|
||||
files.append((f"{dist_info}/RECORD", record.encode("utf-8")))
|
||||
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
wheel_path = os.path.join(out_dir, f"{NAME}-{version}-{tag}.whl")
|
||||
with zipfile.ZipFile(wheel_path, "w", zipfile.ZIP_DEFLATED) as wheel:
|
||||
for path, data in files:
|
||||
info = zipfile.ZipInfo(path, FIXED_TIME)
|
||||
info.compress_type = zipfile.ZIP_DEFLATED
|
||||
# The shared object must stay executable for some loaders.
|
||||
info.external_attr = (0o755 if path.endswith(".dll") and platform is LINUX else 0o644) << 16
|
||||
wheel.writestr(info, data)
|
||||
print(wheel_path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,2 @@
|
||||
This interactor should be able toquery a server via a client app.
|
||||
The client should never parse the JSON, only the final app should.
|
||||
Reference in New Issue
Block a user