1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Moved the workspace to the root, Added the build scripts, ARM64 releases and the Docker image

Source/'s content is at the root now, Source/README.md merged into
readme.md. Scripts at the root: build.ps1, test.ps1 (was check.ps1),
release.ps1 (over release.py) and clean.ps1. Everything is LF except the
.ps1 files.

CI (.github/workflows/ci.yml) runs on a v* tag or by hand: the checks,
then a release for Windows x64 and ARM64 and Linux x64 and ARM64, each on
its own kind of runner, the archives kept as artifacts. release.py names
the platform from the Rust host, make_wheel.py tags the wheel from the
library's header.

docker/: the server's image (built from source, the tools beside it, uid
10001), compose.yml and test.sh. CI builds amd64 and arm64 natively,
checks them, and on a tag pushes them to ghcr.io with an index for
<version> and latest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 01:13:44 +01:00
parent 17ec69c03c
commit 5045019df4
93 changed files with 634 additions and 277 deletions
+355
View File
@@ -0,0 +1,355 @@
/*
* BakaShrot's client DLL: bakashrot.dll (Windows), libbakashrot.so (Linux).
* Generated by cbindgen from crates/bakashrot-capi: don't edit.
* docs/client.md has the conventions and the whole API.
*/
#ifndef BAKASHROT_H
#define BAKASHROT_H
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
* Why the last call failed: a protocol error code (1-99 a server's
* refusal, the connection still open; 100 and up the client's own), 0 if
* it succeeded. Getters don't change it.
*/
int32_t BakaShrot_GetLastError(void);
/**
* Why the last call failed, in words: the server's reason for a refusal,
* the client's otherwise. Empty if it succeeded.
*/
ptrdiff_t BakaShrot_GetRefusalReasonA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetRefusalReasonA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetRefusalReasonW(uint16_t *buffer, ptrdiff_t size);
/**
* Sets the CA's certificate, which the server's must be issued by: PEM
* text, or the path of a file holding it. Before connecting.
*/
ptrdiff_t BakaShrot_SetCaCertificateA(const char *certificate);
/**
* The same as `BakaShrot_SetCaCertificateA`, in UTF-16.
*/
ptrdiff_t BakaShrot_SetCaCertificateW(const uint16_t *certificate);
/**
* Sets this client's certificate, which says its node and its roles: PEM
* text, or the path of a file holding it. Before connecting.
*/
ptrdiff_t BakaShrot_SetCertificateA(const char *certificate);
/**
* The same as `BakaShrot_SetCertificateA`, in UTF-16.
*/
ptrdiff_t BakaShrot_SetCertificateW(const uint16_t *certificate);
/**
* Sets this client's private key, its certificate's: PEM text, or the path
* of a file holding it. Before connecting.
*/
ptrdiff_t BakaShrot_SetPrivateKeyA(const char *key);
/**
* The same as `BakaShrot_SetPrivateKeyA`, in UTF-16.
*/
ptrdiff_t BakaShrot_SetPrivateKeyW(const uint16_t *key);
/**
* Sets the CA's CRL, optional: servers it revokes are refused. PEM text,
* or the path of a file holding it; null or empty for none. Before
* connecting.
*/
ptrdiff_t BakaShrot_SetCrlA(const char *crl);
/**
* The same as `BakaShrot_SetCrlA`, in UTF-16.
*/
ptrdiff_t BakaShrot_SetCrlW(const uint16_t *crl);
/**
* Connects to the server at `host` (a name or an address) and `port`:
* TLS with the certificates set, then the server says who this client is
* (`BakaShrot_GetNode()`). Refused: the code says by whom (`AuthRejected`
* the server refused the certificate, `ServerNotVerified` this client
* refused the server's, `NotAllowed` none of its roles is the server's).
*/
ptrdiff_t BakaShrot_ConnectA(const char *host, int32_t port);
/**
* The same as `BakaShrot_ConnectA`, in UTF-16.
*/
ptrdiff_t BakaShrot_ConnectW(const uint16_t *host, int32_t port);
/**
* 1 while connected: notices when the server closed the connection
* (forgotten then: connect again).
*/
ptrdiff_t BakaShrot_IsConnected(void);
/**
* Closes the connection: 0 if there was none. The settings stay.
*/
ptrdiff_t BakaShrot_Disconnect(void);
/**
* The node this client is, as the server said when connecting: its
* certificate's name. Empty when not connected.
*/
ptrdiff_t BakaShrot_GetNodeA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetNodeA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetNodeW(uint16_t *buffer, ptrdiff_t size);
/**
* Pushes a message (JSON or not) to `topic`, as this client's node: its
* id (1 and up), -1 on failure. A push whose answer was lost
* (`ConnectionLost`) may have been stored all the same.
*/
int64_t BakaShrot_PushMessageToA(const char *topic, const char *data);
/**
* The same as `BakaShrot_PushMessageToA`, in UTF-16.
*/
int64_t BakaShrot_PushMessageToW(const uint16_t *topic, const uint16_t *data);
/**
* Gets the latest message of `topic` and `node`, then read with the
* `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet.
*/
ptrdiff_t BakaShrot_GetLatestMessageOfA(const char *topic, const char *node);
/**
* The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetLatestMessageOfW(const uint16_t *topic, const uint16_t *node);
/**
* Gets the messages of `topic` and `node` after id `after` (0 for the
* first ones), in order: `limit` at most (1-10000), fewer past about
* 1 MB. Returns how many came (none isn't a failure), -1 on failure. The
* first is selected; `BakaShrot_SelectMessage()` selects the others,
* `BakaShrot_HasMoreMessages()` says whether more follow the last one.
*/
int32_t BakaShrot_GetMessagesA(const char *topic, const char *node, int64_t after, int32_t limit);
/**
* The same as `BakaShrot_GetMessagesA`, in UTF-16.
*/
int32_t BakaShrot_GetMessagesW(const uint16_t *topic,
const uint16_t *node,
int64_t after,
int32_t limit);
/**
* How many messages the last `GetMessages` or `GetLatestMessageOf` got.
*/
int32_t BakaShrot_GetMessageCount(void);
/**
* Selects the message at `index` (0 to the count - 1) for the getters: 0
* if there's none there (`InvalidArgument`), the selection unchanged.
*/
ptrdiff_t BakaShrot_SelectMessage(int32_t index);
/**
* 1 if more messages follow the last one the last `GetMessages` got: ask
* again after its id.
*/
ptrdiff_t BakaShrot_HasMoreMessages(void);
/**
* The selected message's id, 0 if none.
*/
int64_t BakaShrot_GetMessageId(void);
/**
* When the selected message was pushed, by the server it was pushed to:
* milliseconds since 1970-01-01 UTC, 0 if none.
*/
int64_t BakaShrot_GetMessagePushedAt(void);
/**
* The selected message's attachment's size, 0 without one.
*/
int64_t BakaShrot_GetMessageAttachmentSize(void);
/**
* 1 if the selected message's attachment is all on this server (a
* replicated one may still be on its way).
*/
ptrdiff_t BakaShrot_IsMessageAttachmentReady(void);
/**
* The selected message's data, as pushed (JSON or not).
*/
ptrdiff_t BakaShrot_GetMessageDataA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetMessageDataA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetMessageDataW(uint16_t *buffer, ptrdiff_t size);
/**
* The topic the last `GetMessages` or `GetLatestMessageOf` asked for.
*/
ptrdiff_t BakaShrot_GetMessageTopicA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetMessageTopicA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetMessageTopicW(uint16_t *buffer, ptrdiff_t size);
/**
* The node the last `GetMessages` or `GetLatestMessageOf` asked for.
*/
ptrdiff_t BakaShrot_GetMessageNodeA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetMessageNodeA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetMessageNodeW(uint16_t *buffer, ptrdiff_t size);
/**
* Lists the topics this client may push to or read (every one if it may
* query): how many, -1 on failure. Then `BakaShrot_GetNamesList()`.
*/
int32_t BakaShrot_ListTopics(void);
/**
* Lists every node with messages: how many, -1 on failure. Then
* `BakaShrot_GetNamesList()`.
*/
int32_t BakaShrot_ListNodes(void);
/**
* The last list, as JSON:
* `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated`
* if some didn't fit.
*/
ptrdiff_t BakaShrot_GetNamesListA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetNamesListA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetNamesListW(uint16_t *buffer, ptrdiff_t size);
/**
* Runs read-only SQL on the server (one SELECT or WITH), if this client
* may query. Then `BakaShrot_GetQueryResult()`.
*/
ptrdiff_t BakaShrot_QueryA(const char *sql);
/**
* The same as `BakaShrot_QueryA`, in UTF-16.
*/
ptrdiff_t BakaShrot_QueryW(const uint16_t *sql);
/**
* The last query's result, as JSON:
* `{"columns":[...],"rows":[[...],...]}`, every value a string or null.
*/
ptrdiff_t BakaShrot_GetQueryResultA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetQueryResultA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetQueryResultW(uint16_t *buffer, ptrdiff_t size);
/**
* Pushes a message with the file at `FilePath` as its attachment (1 byte
* to 1 TiB, the server may take less: `TooBig`): uploaded with it, the
* message stored once all of it came. Its id, -1 on failure. The file is
* read twice (its SHA-256 first): one changed in between is refused
* (`DataMismatch`).
*/
int64_t BakaShrot_PushMessageWithFileA(const char *topic, const char *data, const char *file_path);
/**
* The same as `BakaShrot_PushMessageWithFileA`, in UTF-16.
*/
int64_t BakaShrot_PushMessageWithFileW(const uint16_t *topic,
const uint16_t *data,
const uint16_t *file_path);
/**
* Pushes a message with the `Size` bytes at `Data` as its attachment, as
* `BakaShrot_PushMessageWithFileA` does.
*/
int64_t BakaShrot_PushMessageWithDataA(const char *topic,
const char *data,
const void *attachment,
int64_t size);
/**
* The same as `BakaShrot_PushMessageWithDataA`, in UTF-16.
*/
int64_t BakaShrot_PushMessageWithDataW(const uint16_t *topic,
const uint16_t *data,
const void *attachment,
int64_t size);
/**
* Saves the attachment of `Topic`, `Node`'s message `MessageId` as the
* file at `FilePath` (replaced), read a part at a time and checked with
* its SHA-256: its size, -1 on failure (`NotFound` without one,
* `NotReady` if it isn't on this server yet, `AttachmentMismatch`). A
* failed one leaves no file.
*/
int64_t BakaShrot_SaveAttachmentA(const char *topic,
const char *node,
int64_t message_id,
const char *file_path);
/**
* The same as `BakaShrot_SaveAttachmentA`, in UTF-16.
*/
int64_t BakaShrot_SaveAttachmentW(const uint16_t *topic,
const uint16_t *node,
int64_t message_id,
const uint16_t *file_path);
/**
* Reads the attachment of `Topic`, `Node`'s message `MessageId` into
* memory, checked with its SHA-256 (`BakaShrot_SaveAttachmentA` for big
* ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`.
*/
int64_t BakaShrot_LoadAttachmentA(const char *topic, const char *node, int64_t message_id);
/**
* The same as `BakaShrot_LoadAttachmentA`, in UTF-16.
*/
int64_t BakaShrot_LoadAttachmentW(const uint16_t *topic, const uint16_t *node, int64_t message_id);
/**
* Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if
* `BufferSize` is enough: returns its size (0 if none), copies nothing if
* it doesn't fit (a null `Buffer` asks for the size).
*/
int64_t BakaShrot_GetAttachmentData(void *buffer, int64_t buffer_size);
/**
* Frees what `BakaShrot_LoadAttachment()` read: 1.
*/
ptrdiff_t BakaShrot_FreeAttachmentData(void);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif /* BAKASHROT_H */
@@ -0,0 +1,322 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrot_Client_Prototypes.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot client DLL - Prototypes
;
; Include this in an app to use bakashrot.dll (libbakashrot.so on Linux):
; XIncludeFile "BakaShrot_Client_Prototypes.pbi"
; If BakaShrot_LoadClient("bakashrot.dll")
; BakaShrot_SetCaCertificate("ca.crt") ; a file, or PEM text
; BakaShrot_SetCertificate("kitchen.crt")
; BakaShrot_SetPrivateKey("kitchen.key")
; If BakaShrot_Connect("10.0.0.2", 7000)
; BakaShrot_PushMessageTo("logs", ~"{\"temp\": 21}")
; ...
; EndIf
; BakaShrot_UnloadClient()
; EndIf
;
; docs/client.md has what each function does (and
; bindings/c/bakashrot.h, generated from the DLL). The string
; functions are mapped to the DLL's W (UTF-16) variants. After a failed
; call, BakaShrot_GetLastError() tells why: the codes and what to do about
; each are in BakaShrot_ErrorCodes.pbi, next to this file (included below),
; BakaShrot_ErrorName() names them; BakaShrot_GetRefusalReasonString() says
; why in words.
;
; Changed from the PureBasic DLL (protocol 6): certificates instead of keys
; and a node (BakaShrot_SetCaCertificate(), _SetCertificate(),
; _SetPrivateKey() now a PEM key, _SetCrl()); a push always names its topic
; (BakaShrot_PushMessage() is gone); no ids (_GetLatestMessage(TopicId,
; NodeId), _SetNodeId(), _GetMessageTopicId/NodeId(), _ResolveTopic/Node(),
; _GetResolvedName() are gone); _GetNamesList() is
; {"kind":"topic","names":[...],"truncated":false}. New: _GetNode().
; Attachments: the same six as before, by names.
; ============================================================================
XIncludeFile "BakaShrot_ErrorCodes.pbi"
PrototypeC.l BakaShrot_GetLastError_Prototype()
PrototypeC.i BakaShrot_GetRefusalReason_Prototype(*Buffer, BufferSize.i)
PrototypeC.i BakaShrot_SetCaCertificate_Prototype(Certificate.p-unicode)
PrototypeC.i BakaShrot_SetCertificate_Prototype(Certificate.p-unicode)
PrototypeC.i BakaShrot_SetPrivateKey_Prototype(PrivateKey.p-unicode)
PrototypeC.i BakaShrot_SetCrl_Prototype(Crl.p-unicode)
PrototypeC.i BakaShrot_Connect_Prototype(Host.p-unicode, Port.l)
PrototypeC.i BakaShrot_IsConnected_Prototype()
PrototypeC.i BakaShrot_Disconnect_Prototype()
PrototypeC.i BakaShrot_GetNode_Prototype(*Buffer, BufferSize.i)
PrototypeC.q BakaShrot_PushMessageTo_Prototype(Topic.p-unicode, JsonData.p-unicode)
PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Topic.p-unicode, Node.p-unicode)
PrototypeC.l BakaShrot_GetMessages_Prototype(Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l)
PrototypeC.l BakaShrot_GetMessageCount_Prototype()
PrototypeC.i BakaShrot_SelectMessage_Prototype(Index.l)
PrototypeC.i BakaShrot_HasMoreMessages_Prototype()
PrototypeC.q BakaShrot_GetMessageId_Prototype()
PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype()
PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype()
PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype()
PrototypeC.i BakaShrot_GetMessageData_Prototype(*Buffer, BufferSize.i)
PrototypeC.i BakaShrot_GetMessageTopic_Prototype(*Buffer, BufferSize.i)
PrototypeC.i BakaShrot_GetMessageNode_Prototype(*Buffer, BufferSize.i)
PrototypeC.l BakaShrot_ListTopics_Prototype()
PrototypeC.l BakaShrot_ListNodes_Prototype()
PrototypeC.i BakaShrot_GetNamesList_Prototype(*Buffer, BufferSize.i)
PrototypeC.i BakaShrot_Query_Prototype(Sql.p-unicode)
PrototypeC.i BakaShrot_GetQueryResult_Prototype(*Buffer, BufferSize.i)
PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode)
PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Topic.p-unicode, JsonData.p-unicode, *Data, Size.q)
PrototypeC.q BakaShrot_SaveAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode)
PrototypeC.q BakaShrot_LoadAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q)
PrototypeC.q BakaShrot_GetAttachmentData_Prototype(*Buffer, BufferSize.q)
PrototypeC.i BakaShrot_FreeAttachmentData_Prototype()
Global BakaShrot_GetLastError.BakaShrot_GetLastError_Prototype
Global BakaShrot_GetRefusalReason.BakaShrot_GetRefusalReason_Prototype
Global BakaShrot_SetCaCertificate.BakaShrot_SetCaCertificate_Prototype
Global BakaShrot_SetCertificate.BakaShrot_SetCertificate_Prototype
Global BakaShrot_SetPrivateKey.BakaShrot_SetPrivateKey_Prototype
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_GetNode.BakaShrot_GetNode_Prototype
Global BakaShrot_PushMessageTo.BakaShrot_PushMessageTo_Prototype
Global BakaShrot_GetLatestMessageOf.BakaShrot_GetLatestMessageOf_Prototype
Global BakaShrot_GetMessages.BakaShrot_GetMessages_Prototype
Global BakaShrot_GetMessageCount.BakaShrot_GetMessageCount_Prototype
Global BakaShrot_SelectMessage.BakaShrot_SelectMessage_Prototype
Global BakaShrot_HasMoreMessages.BakaShrot_HasMoreMessages_Prototype
Global BakaShrot_GetMessageId.BakaShrot_GetMessageId_Prototype
Global BakaShrot_GetMessagePushedAt.BakaShrot_GetMessagePushedAt_Prototype
Global BakaShrot_GetMessageAttachmentSize.BakaShrot_GetMessageAttachmentSize_Prototype
Global BakaShrot_IsMessageAttachmentReady.BakaShrot_IsMessageAttachmentReady_Prototype
Global BakaShrot_GetMessageData.BakaShrot_GetMessageData_Prototype
Global BakaShrot_GetMessageTopic.BakaShrot_GetMessageTopic_Prototype
Global BakaShrot_GetMessageNode.BakaShrot_GetMessageNode_Prototype
Global BakaShrot_ListTopics.BakaShrot_ListTopics_Prototype
Global BakaShrot_ListNodes.BakaShrot_ListNodes_Prototype
Global BakaShrot_GetNamesList.BakaShrot_GetNamesList_Prototype
Global BakaShrot_Query.BakaShrot_Query_Prototype
Global BakaShrot_GetQueryResult.BakaShrot_GetQueryResult_Prototype
Global BakaShrot_PushMessageWithFile.BakaShrot_PushMessageWithFile_Prototype
Global BakaShrot_PushMessageWithData.BakaShrot_PushMessageWithData_Prototype
Global BakaShrot_SaveAttachment.BakaShrot_SaveAttachment_Prototype
Global BakaShrot_LoadAttachment.BakaShrot_LoadAttachment_Prototype
Global BakaShrot_GetAttachmentData.BakaShrot_GetAttachmentData_Prototype
Global BakaShrot_FreeAttachmentData.BakaShrot_FreeAttachmentData_Prototype
Global BakaShrot_ClientLibrary.i = 0
; The first export BakaShrot_LoadClient() didn't find, "" if none.
Global BakaShrot_ClientMissing.s = ""
; Unloads the DLL loaded by BakaShrot_LoadClient().
Procedure BakaShrot_UnloadClient()
If BakaShrot_ClientLibrary
CloseLibrary(BakaShrot_ClientLibrary)
BakaShrot_ClientLibrary = 0
EndIf
EndProcedure
; An export of the DLL, noted in BakaShrot_ClientMissing if it has none.
Procedure.i BakaShrot_ClientFunction(Name.s)
Protected *Function = GetFunction(BakaShrot_ClientLibrary, Name)
If Not *Function And BakaShrot_ClientMissing = ""
BakaShrot_ClientMissing = Name
EndIf
ProcedureReturn *Function
EndProcedure
; Loads the DLL at DllPath and fills the function pointers above.
; Returns #False if the DLL can't be loaded or an export is missing (an
; older DLL: BakaShrot_ClientMissing says which).
Procedure.i BakaShrot_LoadClient(DllPath.s)
If BakaShrot_ClientLibrary
ProcedureReturn #False
EndIf
BakaShrot_ClientLibrary = OpenLibrary(#PB_Any, DllPath)
If Not BakaShrot_ClientLibrary
ProcedureReturn #False
EndIf
BakaShrot_ClientMissing = ""
; PureBasic strings are UTF-16, so the W variants are used.
BakaShrot_GetLastError = BakaShrot_ClientFunction("BakaShrot_GetLastError")
BakaShrot_GetRefusalReason = BakaShrot_ClientFunction("BakaShrot_GetRefusalReasonW")
BakaShrot_SetCaCertificate = BakaShrot_ClientFunction("BakaShrot_SetCaCertificateW")
BakaShrot_SetCertificate = BakaShrot_ClientFunction("BakaShrot_SetCertificateW")
BakaShrot_SetPrivateKey = BakaShrot_ClientFunction("BakaShrot_SetPrivateKeyW")
BakaShrot_SetCrl = BakaShrot_ClientFunction("BakaShrot_SetCrlW")
BakaShrot_Connect = BakaShrot_ClientFunction("BakaShrot_ConnectW")
BakaShrot_IsConnected = BakaShrot_ClientFunction("BakaShrot_IsConnected")
BakaShrot_Disconnect = BakaShrot_ClientFunction("BakaShrot_Disconnect")
BakaShrot_GetNode = BakaShrot_ClientFunction("BakaShrot_GetNodeW")
BakaShrot_PushMessageTo = BakaShrot_ClientFunction("BakaShrot_PushMessageToW")
BakaShrot_GetLatestMessageOf = BakaShrot_ClientFunction("BakaShrot_GetLatestMessageOfW")
BakaShrot_GetMessages = BakaShrot_ClientFunction("BakaShrot_GetMessagesW")
BakaShrot_GetMessageCount = BakaShrot_ClientFunction("BakaShrot_GetMessageCount")
BakaShrot_SelectMessage = BakaShrot_ClientFunction("BakaShrot_SelectMessage")
BakaShrot_HasMoreMessages = BakaShrot_ClientFunction("BakaShrot_HasMoreMessages")
BakaShrot_GetMessageId = BakaShrot_ClientFunction("BakaShrot_GetMessageId")
BakaShrot_GetMessagePushedAt = BakaShrot_ClientFunction("BakaShrot_GetMessagePushedAt")
BakaShrot_GetMessageAttachmentSize = BakaShrot_ClientFunction("BakaShrot_GetMessageAttachmentSize")
BakaShrot_IsMessageAttachmentReady = BakaShrot_ClientFunction("BakaShrot_IsMessageAttachmentReady")
BakaShrot_GetMessageData = BakaShrot_ClientFunction("BakaShrot_GetMessageDataW")
BakaShrot_GetMessageTopic = BakaShrot_ClientFunction("BakaShrot_GetMessageTopicW")
BakaShrot_GetMessageNode = BakaShrot_ClientFunction("BakaShrot_GetMessageNodeW")
BakaShrot_ListTopics = BakaShrot_ClientFunction("BakaShrot_ListTopics")
BakaShrot_ListNodes = BakaShrot_ClientFunction("BakaShrot_ListNodes")
BakaShrot_GetNamesList = BakaShrot_ClientFunction("BakaShrot_GetNamesListW")
BakaShrot_Query = BakaShrot_ClientFunction("BakaShrot_QueryW")
BakaShrot_GetQueryResult = BakaShrot_ClientFunction("BakaShrot_GetQueryResultW")
BakaShrot_PushMessageWithFile = BakaShrot_ClientFunction("BakaShrot_PushMessageWithFileW")
BakaShrot_PushMessageWithData = BakaShrot_ClientFunction("BakaShrot_PushMessageWithDataW")
BakaShrot_SaveAttachment = BakaShrot_ClientFunction("BakaShrot_SaveAttachmentW")
BakaShrot_LoadAttachment = BakaShrot_ClientFunction("BakaShrot_LoadAttachmentW")
BakaShrot_GetAttachmentData = BakaShrot_ClientFunction("BakaShrot_GetAttachmentData")
BakaShrot_FreeAttachmentData = BakaShrot_ClientFunction("BakaShrot_FreeAttachmentData")
If BakaShrot_ClientMissing <> ""
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Calls a string getter of the DLL (Getter(*Buffer, BufferSize)) and
; returns the string: asks for the size, then copies.
PrototypeC.i BakaShrot_StringGetter_Prototype(*Buffer, BufferSize.i)
Procedure.s BakaShrot_GetString(Getter.BakaShrot_StringGetter_Prototype)
Protected *Buffer, BufferSize.i, Text.s
BufferSize = Getter(0, 0)
*Buffer = AllocateMemory(BufferSize)
If Not *Buffer
ProcedureReturn ""
EndIf
Getter(*Buffer, BufferSize)
Text = PeekS(*Buffer, -1, #PB_Unicode)
FreeMemory(*Buffer)
ProcedureReturn Text
EndProcedure
; The string getters, as strings.
Procedure.s BakaShrot_GetRefusalReasonString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetRefusalReason)
EndProcedure
Procedure.s BakaShrot_GetNodeString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetNode)
EndProcedure
Procedure.s BakaShrot_GetMessageDataString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageData)
EndProcedure
Procedure.s BakaShrot_GetMessageTopicString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageTopic)
EndProcedure
Procedure.s BakaShrot_GetMessageNodeString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageNode)
EndProcedure
Procedure.s BakaShrot_GetNamesListString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetNamesList)
EndProcedure
Procedure.s BakaShrot_GetQueryResultString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetQueryResult)
EndProcedure
; Usage example. Only compiled when this file is run directly (F5 in the
; IDE), not when it's included by an app.
; ClientExample <DllPath> <CaFile> <CertificateFile> <KeyFile> <Host> <Port>
; Pushes a message to "logs", reads it back, pushes one with an
; attachment and reads that back, lists the topics.
CompilerIf #PB_Compiler_IsMainFile
Define Id.q, Size.q, *Attachment, *Copy
; Prints why the last call failed, then ends.
Procedure Failed(What.s)
PrintN(What + " failed: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString())
BakaShrot_UnloadClient()
End 1
EndProcedure
OpenConsole()
If CountProgramParameters() < 6
PrintN("Usage: ClientExample <DllPath> <CaFile> <CertificateFile> <KeyFile> <Host> <Port>")
End 2
EndIf
If Not BakaShrot_LoadClient(ProgramParameter(0))
PrintN("Failed to load " + ProgramParameter(0) + " " + BakaShrot_ClientMissing)
End 1
EndIf
If Not BakaShrot_SetCaCertificate(ProgramParameter(1)) : Failed("Setting the CA's certificate") : EndIf
If Not BakaShrot_SetCertificate(ProgramParameter(2)) : Failed("Setting the certificate") : EndIf
If Not BakaShrot_SetPrivateKey(ProgramParameter(3)) : Failed("Setting the private key") : EndIf
If Not BakaShrot_Connect(ProgramParameter(4), Val(ProgramParameter(5))) : Failed("Connecting") : EndIf
PrintN("Connected as " + BakaShrot_GetNodeString())
Id = BakaShrot_PushMessageTo("logs", ~"{\"from\": \"PureBasic\", \"text\": \"hello\"}")
If Id < 1 : Failed("Pushing") : EndIf
PrintN("Pushed #" + Str(Id))
If Not BakaShrot_GetLatestMessageOf("logs", BakaShrot_GetNodeString()) : Failed("Reading") : EndIf
PrintN("Latest: #" + Str(BakaShrot_GetMessageId()) + " " + BakaShrot_GetMessageDataString())
*Attachment = AllocateMemory(3000)
FillMemory(*Attachment, 3000, 42, #PB_Byte)
Id = BakaShrot_PushMessageWithData("logs", ~"{\"photo\": 1}", *Attachment, 3000)
If Id < 1 : Failed("Pushing an attachment") : EndIf
Size = BakaShrot_LoadAttachment("logs", BakaShrot_GetNodeString(), Id)
If Size < 0 : Failed("Reading the attachment") : EndIf
*Copy = AllocateMemory(Size)
BakaShrot_GetAttachmentData(*Copy, Size)
BakaShrot_FreeAttachmentData()
If CompareMemory(*Attachment, *Copy, 3000)
PrintN("Pushed #" + Str(Id) + " with " + Str(Size) + " bytes, read back the same")
Else
PrintN("The attachment read back differs")
End 1
EndIf
FreeMemory(*Attachment) : FreeMemory(*Copy)
If BakaShrot_ListTopics() < 0 : Failed("Listing") : EndIf
PrintN("Topics: " + BakaShrot_GetNamesListString())
If BakaShrot_PushMessageTo("nothing", "{}") < 0
PrintN("A push to an unknown topic: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString())
EndIf
BakaShrot_Disconnect()
PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected()))
BakaShrot_UnloadClient()
End 0
CompilerEndIf
+144
View File
@@ -0,0 +1,144 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrot_ErrorCodes.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot error codes
;
; What BakaShrot_GetLastError() returns after a failed call of the client DLL
; (bakashrot.dll), and the code a server sends with each refusal (protocol 7,
; crates/bakashrot-proto/src/error.rs, the same numbers as protocol 6).
; The Python client has them in bakashrot.ErrorCode. Shipped next to
; BakaShrot_Client_Prototypes.pbi, which includes it.
;
; 0 no error (the last call succeeded)
; 1-99 refused by the server: the connection is still open, see
; BakaShrot_GetRefusalReason() for the details
; 100+ the client's own: the connection, the arguments, the files
;
; What to do about each:
; reconnect, then retry: NotConnected, ConnectFailed, ConnectionLost,
; ProtocolError (the connection is closed)
; retry later: NotReady (an attachment still on its way),
; ServerError (the server's storage failed)
; fix the certificates or
; the server's config: AuthRejected, ServerNotVerified, NotAllowed,
; UnknownName, VersionMismatch
; fix the call: InvalidArgument, InvalidRequest, TooBig,
; QueryFailed, FileError
; gone, or not yet there: NotFound
; sent again by itself: DataMismatch, AttachmentMismatch
;
; A push whose answer was lost (ConnectionLost) may still have been stored:
; pushing it again can store it twice, under the next id. Delivery is at
; least once; check the latest message first if a duplicate matters.
; ============================================================================
; --- Refused by the server (RequestRefused's code) ----------------------------
; Not allowed to this client: its roles' permissions (or, when connecting,
; none of its roles is the server's).
#BakaShrot_Refused_NotAllowed = 1
; A topic or node this server doesn't know.
#BakaShrot_Refused_UnknownName = 2
; No such message or attachment.
#BakaShrot_Refused_NotFound = 3
; The attachment isn't on this server yet (still being replicated).
#BakaShrot_Refused_NotReady = 4
; A message, attachment or query result over a limit, or an attachment
; bigger than this server keeps.
#BakaShrot_Refused_TooBig = 5
; Protocol 6's (a push without a topic): never sent any more.
#BakaShrot_Refused_NoDefaultTopic = 6
; A request that doesn't fit: an attachment's parts not matching its size,
; a part that doesn't exist...
#BakaShrot_Refused_InvalidRequest = 7
; An uploaded attachment that doesn't match its SHA-256: dropped.
#BakaShrot_Refused_DataMismatch = 8
; The SQL of a query failed (its error in the reason).
#BakaShrot_Refused_QueryFailed = 9
; The server couldn't store or read something: its database failed.
#BakaShrot_Refused_ServerError = 10
; The highest a refusal can have, anything above is the client's own.
#BakaShrot_Refused_Max = 99
; --- The client's own (BakaShrot_GetLastError()) --------------------------------
#BakaShrot_Error_None = 0
; Not connected: never, or the connection was closed or lost before.
#BakaShrot_Error_NotConnected = 100
; The server couldn't be reached at that host and port.
#BakaShrot_Error_ConnectFailed = 101
; The server refused this client's certificate: another CA's, revoked,
; expired.
#BakaShrot_Error_AuthRejected = 102
; This client refused the server's certificate: not the CA's, or revoked.
#BakaShrot_Error_ServerNotVerified = 103
; The connection broke during a request (it's closed now). A push may
; still have been stored.
#BakaShrot_Error_ConnectionLost = 104
; The server answered something unexpected or malformed: the connection is
; closed.
#BakaShrot_Error_ProtocolError = 105
; A bad argument: a topic or node that isn't a name, a null pointer, a
; message over the limit, a certificate missing before connecting.
#BakaShrot_Error_InvalidArgument = 106
; A file couldn't be opened, read or written.
#BakaShrot_Error_FileError = 107
; A downloaded attachment doesn't match its SHA-256.
#BakaShrot_Error_AttachmentMismatch = 108
; Already connected: disconnect first.
#BakaShrot_Error_AlreadyConnected = 109
; A failure inside the DLL.
#BakaShrot_Error_Internal = 110
; The server speaks another version of the protocol: update one or the
; other.
#BakaShrot_Error_VersionMismatch = 111
; The name of an error code, as the constants have it ("NotFound"), or
; "Error <code>" for an unknown one.
Procedure.s BakaShrot_ErrorName(Code.l)
Select Code
Case #BakaShrot_Error_None : ProcedureReturn "None"
Case #BakaShrot_Refused_NotAllowed : ProcedureReturn "NotAllowed"
Case #BakaShrot_Refused_UnknownName : ProcedureReturn "UnknownName"
Case #BakaShrot_Refused_NotFound : ProcedureReturn "NotFound"
Case #BakaShrot_Refused_NotReady : ProcedureReturn "NotReady"
Case #BakaShrot_Refused_TooBig : ProcedureReturn "TooBig"
Case #BakaShrot_Refused_NoDefaultTopic : ProcedureReturn "NoDefaultTopic"
Case #BakaShrot_Refused_InvalidRequest : ProcedureReturn "InvalidRequest"
Case #BakaShrot_Refused_DataMismatch : ProcedureReturn "DataMismatch"
Case #BakaShrot_Refused_QueryFailed : ProcedureReturn "QueryFailed"
Case #BakaShrot_Refused_ServerError : ProcedureReturn "ServerError"
Case #BakaShrot_Error_NotConnected : ProcedureReturn "NotConnected"
Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "ConnectFailed"
Case #BakaShrot_Error_AuthRejected : ProcedureReturn "AuthRejected"
Case #BakaShrot_Error_ServerNotVerified : ProcedureReturn "ServerNotVerified"
Case #BakaShrot_Error_ConnectionLost : ProcedureReturn "ConnectionLost"
Case #BakaShrot_Error_ProtocolError : ProcedureReturn "ProtocolError"
Case #BakaShrot_Error_InvalidArgument : ProcedureReturn "InvalidArgument"
Case #BakaShrot_Error_FileError : ProcedureReturn "FileError"
Case #BakaShrot_Error_AttachmentMismatch : ProcedureReturn "AttachmentMismatch"
Case #BakaShrot_Error_AlreadyConnected : ProcedureReturn "AlreadyConnected"
Case #BakaShrot_Error_Internal : ProcedureReturn "Internal"
Case #BakaShrot_Error_VersionMismatch : ProcedureReturn "VersionMismatch"
EndSelect
ProcedureReturn "Error " + Str(Code)
EndProcedure
; #True for a code a server sends with a refusal (1-99).
Procedure.i BakaShrot_IsRefusalCode(Code.l)
ProcedureReturn Bool(Code >= 1 And Code <= #BakaShrot_Refused_Max)
EndProcedure
+577
View File
@@ -0,0 +1,577 @@
"""BakaShrot client for Python, over the client DLL (bakashrot.dll,
libbakashrot.so).
No dependencies beyond the standard library: the DLL is loaded with ctypes
and does the connecting 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_file("client.toml") as client:
message_id = client.push({"temperature": 21.5}, "sensors")
for message in client.get_messages("sensors", client.node, after=0):
print(message.id, message.data)
for message in client.follow("logs", "kitchen"): # until stopped
print(message.id, message.json())
Who the client is comes from its certificate, issued by the CA the server
trusts (bakashrot-cert): its name is its node, its roles say what it may
do. client.toml says where the server is and where the certificates are
(docs/client.md):
server = "10.0.0.2:7000"
ca = "ca.crt"
certificate = "kitchen.crt"
key = "kitchen.key"
# crl = "ca.crl"
Errors are exceptions with a code (`error.code`, an ErrorCode, the same
numbers as the DLL's BakaShrot_GetLastError()):
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 a certificate refused, either way, or none of its
roles allowed: fix the certificates, 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 looked for, in order: the dll_path given, the BAKASHROT_DLL
environment variable, next to this file, then in the current directory.
"""
from __future__ import annotations
import ctypes
import enum
import json
import os
import sys
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Iterator, Optional, Union
__version__ = "0.2.0"
__all__ = [
"Client", "Message", "MessagesPage", "NamesList",
"BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode",
"MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE",
]
# The protocol's: crates/bakashrot-proto/src/limits.rs.
MAX_GET_MESSAGES = 10000
MAX_MESSAGE_SIZE = 16 * 1024 * 1024 - 4096
DLL_NAME = "bakashrot.dll" if sys.platform == "win32" else "libbakashrot.so"
class ErrorCode(enum.IntEnum):
"""What failed: the protocol's codes (crates/bakashrot-proto/src/error.rs).
1-99: refused by the server, 100+: the client's own."""
NONE = 0
# Refused by the server, the connection still open.
NOT_ALLOWED = 1 # its roles don't allow it (or none is the server's, when connecting)
UNKNOWN_NAME = 2 # a topic or node this server doesn't know
NOT_FOUND = 3 # no such message or attachment
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 # protocol 6's, never sent any more
INVALID_REQUEST = 7 # a request that doesn't fit (parts out of order...)
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 refused this client's certificate
SERVER_NOT_VERIFIED = 103 # this client refused the server's certificate
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 # a failure inside the DLL, or the DLL missing or too old
VERSION_MISMATCH = 111 # the server speaks another protocol version
@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):
"""Connecting was refused for good: the server refused this client's
certificate (AUTH_REJECTED), this client the server's
(SERVER_NOT_VERIFIED), none of its roles is allowed (NOT_ALLOWED), or
another protocol version (VERSION_MISMATCH). Retrying won't help."""
@dataclass(frozen=True)
class Message:
"""A stored message. data is as stored: JSON or not (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."""
id: int
topic: str
node: str
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 NamesList:
kind: str # "topic" or "node"
names: list
truncated: bool # True if they didn't all fit in one answer
def _name(value: str) -> bytes:
if not isinstance(value, str):
raise TypeError(f"a topic or node is a name, not {value!r}")
return 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__)), DLL_NAME))
candidates.append(os.path.join(os.getcwd(), DLL_NAME))
for candidate in candidates:
if os.path.isfile(candidate):
return os.path.abspath(candidate)
raise BakaShrotError(f"{DLL_NAME} 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):
try:
self.lib = ctypes.CDLL(path)
except OSError as error:
raise BakaShrotError(f"Failed to load {path}: {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_GetRefusalReasonA": (I, [S, I]),
"BakaShrot_SetCaCertificateA": (I, [P]),
"BakaShrot_SetCertificateA": (I, [P]),
"BakaShrot_SetPrivateKeyA": (I, [P]),
"BakaShrot_SetCrlA": (I, [P]),
"BakaShrot_ConnectA": (I, [P, L]),
"BakaShrot_IsConnected": (I, []),
"BakaShrot_Disconnect": (I, []),
"BakaShrot_GetNodeA": (I, [S, 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_GetMessageTopicA": (I, [S, I]),
"BakaShrot_GetMessageNodeA": (I, [S, I]),
"BakaShrot_GetMessageDataA": (I, [S, I]),
"BakaShrot_ListTopics": (L, []),
"BakaShrot_ListNodes": (L, []),
"BakaShrot_GetNamesListA": (I, [S, I]),
"BakaShrot_QueryA": (I, [P]),
"BakaShrot_GetQueryResultA": (I, [S, I]),
"BakaShrot_PushMessageWithFileA": (Q, [P, P, P]),
"BakaShrot_PushMessageWithDataA": (Q, [P, P, P, Q]),
"BakaShrot_SaveAttachmentA": (Q, [P, P, Q, P]),
"BakaShrot_LoadAttachmentA": (Q, [P, P, Q]),
"BakaShrot_GetAttachmentData": (Q, [S, Q]),
"BakaShrot_FreeAttachmentData": (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")
def _split_server(server: str) -> tuple:
""""host:port" (an IPv6 address in brackets) as (host, port)."""
host, _, port = server.rpartition(":")
if not host or not port.isdigit():
raise BakaShrotError(f"server is host:port, not {server!r}", ErrorCode.INVALID_ARGUMENT)
return host.strip("[]"), int(port)
class Client:
"""A connection to a BakaShrot server, through the DLL.
server: "host:port". ca, certificate, key, crl (optional): PEM text, or
the paths of files holding it: the CA's certificate (the server's must
be issued by it), this client's certificate (its node, its roles) and
its private key, the CA's CRL (servers it revokes are refused).
"""
_connected_client: Optional["Client"] = None
def __init__(self, server: str, ca: str, certificate: str, key: str, crl: Optional[str] = None,
dll_path: Optional[str] = None):
self._dll = _Dll.get(dll_path)
self._lock = threading.RLock()
self.host, self.port = _split_server(server)
self.ca = os.fspath(ca)
self.certificate = os.fspath(certificate)
self.key = os.fspath(key)
self.crl = os.fspath(crl) if crl else None
self.node = ""
@classmethod
def from_file(cls, path: Union[str, os.PathLike], dll_path: Optional[str] = None) -> "Client":
"""From a client.toml (server, ca, certificate, key, crl), the tools'
too; paths in it are relative to its folder. Needs Python 3.11+
(tomllib)."""
import tomllib
try:
with open(path, "rb") as file:
settings = tomllib.load(file)
except OSError as error:
raise BakaShrotError(f"Failed to open '{path}': {error}", ErrorCode.FILE_ERROR) from error
except tomllib.TOMLDecodeError as error:
raise BakaShrotError(f"'{path}': {error}", ErrorCode.INVALID_ARGUMENT) from error
folder = os.path.dirname(os.path.abspath(path))
def get(key, required=True):
value = settings.get(key)
if value is None and required:
raise BakaShrotError(f"'{path}' has no {key}", ErrorCode.INVALID_ARGUMENT)
if not isinstance(value, (str, type(None))):
raise BakaShrotError(f"'{path}': {key} is a string", ErrorCode.INVALID_ARGUMENT)
return value
def file(key, required=True):
value = get(key, required)
return os.path.join(folder, value) if value else None
return cls(get("server"), file("ca"), file("certificate"), file("key"), file("crl", False), dll_path)
# --- Connection --------------------------------------------------------
def connect(self) -> "Client":
"""Connects. Raises ConnectionLostError when the server can't be
reached (CONNECT_FAILED), AuthError when a certificate is refused,
BakaShrotError on a bad setting (INVALID_ARGUMENT, FILE_ERROR) 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
for setter, value in ((dll.SetCaCertificateA, self.ca), (dll.SetCertificateA, self.certificate),
(dll.SetPrivateKeyA, self.key), (dll.SetCrlA, self.crl or "")):
if not setter(value.encode("utf-8")):
raise self._failed("Certificates")
if not dll.ConnectA(self.host.encode("utf-8"), self.port):
raise self._failed(f"Connect to {self.host}:{self.port}", connecting=True)
self.node = dll.string(dll.GetNodeA)
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)
def _failed(self, what: str, connecting: bool = False) -> 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 connecting and code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED,
ErrorCode.NOT_ALLOWED, ErrorCode.VERSION_MISMATCH):
return AuthError(f"{what}: {reason}", code)
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 'failed'}"
if code in (ErrorCode.NOT_CONNECTED, ErrorCode.CONNECT_FAILED, ErrorCode.CONNECTION_LOST, ErrorCode.PROTOCOL_ERROR):
return ConnectionLostError(message, code)
return BakaShrotError(message, code if code else ErrorCode.INTERNAL)
# --- Requests ----------------------------------------------------------
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
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 with it (1 byte
and up, as much as the server's max_attachment_size takes): the
message is only stored once all of it came."""
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)
with self._lock:
self._check_connected()
if attachment is None:
message_id = self._dll.PushMessageToA(_name(topic), encoded)
elif isinstance(attachment, (bytes, bytearray, memoryview)):
raw = bytes(attachment)
message_id = self._dll.PushMessageWithDataA(_name(topic), encoded, raw, len(raw))
else:
path = os.fspath(attachment).encode("utf-8")
message_id = self._dll.PushMessageWithFileA(_name(topic), encoded, path)
if message_id < 1:
raise self._failed("Push")
return message_id
def get_attachment(self, topic: str, node: str, message_id: int) -> bytes:
"""The attachment of a message, all of it in memory (save_attachment()
for big ones), checked with its SHA-256. RefusedError if it has none
(NOT_FOUND) or it isn't on this server yet (NOT_READY)."""
with self._lock:
self._check_connected()
size = self._dll.LoadAttachmentA(_name(topic), _name(node), int(message_id))
if size < 0:
raise self._failed("Attachment")
try:
buffer = ctypes.create_string_buffer(size)
self._dll.GetAttachmentData(buffer, size)
return buffer.raw[:size]
finally:
self._dll.FreeAttachmentData()
def save_attachment(self, topic: str, node: str, message_id: int, path: Union[str, os.PathLike]) -> int:
"""Saves the attachment of a message as 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(_name(topic), _name(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.string(dll.GetMessageDataA), dll.GetMessagePushedAt(), dll.GetMessageAttachmentSize(),
bool(dll.IsMessageAttachmentReady()))
def latest(self, topic: str, node: str) -> 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(_name(topic), _name(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: str, node: str, 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(_name(topic), _name(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: str, node: str, 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: 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.
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 list_topics(self) -> NamesList:
"""The topics the client may push to or read (every one if it may query)."""
return self._list(self._dll.ListTopics, "List topics")
def list_nodes(self) -> NamesList:
"""Every node with messages."""
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"], parsed["names"], bool(parsed["truncated"]))
def query_raw(self, sql: str) -> str:
"""Runs one read-only SELECT on the server (a role with query =
true), 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 "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"]]
+247
View File
@@ -0,0 +1,247 @@
"""Checks bakashrot.py and the DLL against a running server, run by
crates/bakashrot-capi/tests/python.rs (which starts the server and writes
the certificates and client.toml files).
Usage: python check_bakashrot.py <DllPath> <Folder>
Folder/kitchen.toml node kitchen: may push to logs and secret, read everything, query.
Folder/lounge.toml node lounge: may read logs only.
Folder/guest.toml node guest: none of its roles is the server's.
Expects an empty database. Prints PASS/FAIL per check, exits 1 if any failed.
"""
import hashlib
import os
import sys
import threading
import time
import bakashrot
from bakashrot import AuthError, BakaShrotError, Client, ConnectionLostError, ErrorCode, RefusedError
dll_path, folder = sys.argv[1:3]
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, "no exception"
kitchen = Client.from_file(os.path.join(folder, "kitchen.toml"), dll_path)
lounge = Client.from_file(os.path.join(folder, "lounge.toml"), dll_path)
with kitchen:
check("Connects from kitchen.toml, the node from its certificate", kitchen.connected and kitchen.node == "kitchen",
f"{kitchen.node!r}, {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}, "logs") 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)
# --- 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.data, first.json(), first.attachment_size)
== ("logs", "kitchen", '{"i":1}', {"i": 1}, 0), 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("LOGS", "Kitchen", after=250)
check("After the last one, names in another case: 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", "logs")
unicode_id = kitchen.push("héllo wörld, 🌍, 日本語", "logs")
empty_id = kitchen.push("", "logs")
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, "logs") 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", "nothing"), RefusedError, "unknown topic", ErrorCode.UNKNOWN_NAME)
check("Push to an unknown topic: RefusedError, UNKNOWN_NAME", ok, detail)
ok, detail = raises(lambda: kitchen.push("x", "a b"), BakaShrotError, "isn't a topic name", ErrorCode.INVALID_ARGUMENT)
check("A topic that isn't a name: refused before sending", ok, detail)
ok, detail = raises(lambda: kitchen.push("x" * (bakashrot.MAX_MESSAGE_SIZE + 1), "logs"), BakaShrotError, "too big",
ErrorCode.INVALID_ARGUMENT)
check("A message over the limit: refused before sending", ok, detail)
secret_id = kitchen.push({"s": 1}, "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 topics.names == ["logs", "secret"] and not topics.truncated, topics)
nodes = kitchen.list_nodes()
check("list_nodes()", nodes.kind == "node" and nodes.names == ["kitchen"], nodes)
# --- 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}, "logs") 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"}, "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")
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", "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", "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)
none = os.path.join(folder, "none.bin")
ok, detail = raises(lambda: kitchen.save_attachment("secret", "kitchen", plain_id, none), RefusedError, code=ErrorCode.NOT_FOUND)
check("save_attachment() refused: no file left", ok and not os.path.exists(none), detail)
ok, detail = raises(lambda: kitchen.push("x", "secret", attachment=b""), BakaShrotError, "0 bytes", ErrorCode.INVALID_ARGUMENT)
check("An empty attachment: refused before sending", ok, detail)
ok, detail = raises(lambda: kitchen.push("x", "secret", attachment=os.path.join(folder, "missing.bin")), BakaShrotError,
"missing.bin", 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", "logs"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED)
check("A request 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:
pem = (ca.read(), certificate.read(), key.read())
nowhere = Client("127.0.0.1:1", *pem, dll_path=dll_path)
ok, detail = raises(nowhere.connect, ConnectionLostError, code=ErrorCode.CONNECT_FAILED)
check("Nothing listening: ConnectionLostError, CONNECT_FAILED", ok, detail)
guest = Client.from_file(os.path.join(folder, "guest.toml"), dll_path)
ok, detail = raises(guest.connect, AuthError, "guest", ErrorCode.NOT_ALLOWED)
check("None of its roles allowed: AuthError, NOT_ALLOWED", ok, detail)
missing = Client(f"{kitchen.host}:{kitchen.port}", os.path.join(folder, "missing.crt"), *pem[1:], dll_path=dll_path)
ok, detail = raises(missing.connect, BakaShrotError, "missing.crt", ErrorCode.FILE_ERROR)
check("A certificate file that isn't there: FILE_ERROR", ok, detail)
with Client(f"{kitchen.host}:{kitchen.port}", *pem, dll_path=dll_path) as again:
check("The same identity from PEM text: connected", again.connected and again.node == "kitchen", again.node)
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, "may not read 'secret'", ErrorCode.NOT_ALLOWED)
check("A topic not in its read_topics: RefusedError, NOT_ALLOWED", ok, detail)
ok, detail = raises(lambda: lounge.query("SELECT 1"), RefusedError, "may not run queries", ErrorCode.NOT_ALLOWED)
check("Not allowed to query: RefusedError, NOT_ALLOWED", ok, detail)
check("list_topics(): only what it may read", lounge.list_topics().names == ["logs"])
ok, detail = raises(lambda: lounge.get_attachment("secret", "kitchen", blob_id), RefusedError, code=ErrorCode.NOT_ALLOWED)
check("An attachment in a topic it may not read: 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)
+147
View File
@@ -0,0 +1,147 @@
"""Builds the bakashrot wheel: bakashrot.py with the client library in it,
so `pip install` is all a Python app needs, nothing to compile.
python make_wheel.py <library> <out_dir> [license files...]
<library> is bakashrot.dll (Windows) or libbakashrot.so (Linux), x64 or ARM64,
from `cargo build --release`; the license files go in the wheel's
dist-info/licenses/ (release.py gives LICENSE and THIRD-PARTY.txt). Prints
the wheel's path.
The wheel is bakashrot-<version>-py3-none-<platform>.whl, the version
being bakashrot.py's __version__ (release.py checks it's the workspace's):
win_amd64 or win_arm64, or manylinux_<glibc>_<x86_64|aarch64> with the glibc it was built
against (a Rust library only needs libc, libm and libgcc_s, which
manylinux allows). Inside, bakashrot.py is bakashrot/__init__.py with the
library next to it, where it looks first. Only the standard library, and
the same inputs give the same wheel (fixed timestamps).
"""
import base64
import hashlib
import os
import platform
import re
import sys
import zipfile
HERE = os.path.dirname(os.path.abspath(__file__))
NAME = "bakashrot"
# Zip entries' timestamp, so the wheel only changes when its content does.
FIXED_TIME = (2026, 1, 1, 0, 0, 0)
DESCRIPTION = """\
# bakashrot
Python client for [BakaShrot](https://github.com/aziascreations/BakaShrot)
servers: push messages and attachments, read them back, list names, query.
The client library is included: nothing else to install or build. 64-bit
Python 3.8+ (`Client.from_file()` needs 3.11+). The server must speak the
same protocol: use the release this package comes from.
```python
from bakashrot import Client
with Client.from_file("client.toml") as client:
message_id = client.push({"temperature": 21.5}, "logs")
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.
"""
def version():
with open(os.path.join(HERE, "bakashrot.py"), encoding="utf-8") as file:
match = re.search(r'^__version__ = "([^"]+)"', file.read(), re.MULTILINE)
if not match:
sys.exit("No __version__ in bakashrot.py")
return match.group(1)
def platform_tag(library):
"""The wheel's platform, from the library's kind and machine (its
header's)."""
with open(library, "rb") as file:
header = file.read(4096)
if header[:2] == b"MZ":
# The PE header's offset at 0x3C, its machine after "PE\0\0".
pe = int.from_bytes(header[0x3C:0x40], "little")
machine = {0x8664: "amd64", 0xAA64: "arm64"}.get(int.from_bytes(header[pe + 4:pe + 6], "little"))
if machine is None or header[pe:pe + 4] != b"PE\0\0":
sys.exit(f"{library}: neither an x64 nor an ARM64 DLL")
return f"win_{machine}", "Operating System :: Microsoft :: Windows"
if header[:4] == b"\x7fELF":
# e_machine, little-endian on both.
machine = {62: "x86_64", 183: "aarch64"}.get(int.from_bytes(header[18:20], "little"))
if machine is None:
sys.exit(f"{library}: neither an x86-64 nor an ARM64 shared object")
libc, glibc = platform.libc_ver()
if libc != "glibc":
sys.exit("Built against another libc than glibc: no manylinux tag")
major, minor = glibc.split(".")[:2]
return f"manylinux_{major}_{minor}_{machine}", "Operating System :: POSIX :: Linux"
sys.exit(f"{library}: neither a Windows DLL nor a Linux shared object")
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():
if len(sys.argv) < 3:
sys.exit(__doc__)
library, out_dir, licenses = sys.argv[1], sys.argv[2], sys.argv[3:]
tag, classifier = platform_tag(library)
tag = f"py3-none-{tag}"
dist_info = f"{NAME}-{version()}.dist-info"
def read(path):
with open(path, "rb") as file:
return file.read()
files = [
(f"{NAME}/__init__.py", read(os.path.join(HERE, "bakashrot.py"))),
(f"{NAME}/{os.path.basename(library)}", read(library)),
]
# Metadata 2.4 (PEP 639): the license files, no expression (the
# library bundles its dependencies' code, THIRD-PARTY.txt lists them).
metadata = "\n".join([
"Metadata-Version: 2.4",
f"Name: {NAME}",
f"Version: {version()}",
"Summary: Python client for BakaShrot servers, with the client library included",
"Author: Herwin Bozet (NibblePoker)",
] + [f"License-File: {os.path.basename(path)}" for path in licenses] + [
"Project-URL: GitHub, https://github.com/aziascreations/BakaShrot",
f"Classifier: {classifier}",
"Classifier: Programming Language :: Python :: 3",
"Requires-Python: >=3.8",
"Description-Content-Type: text/markdown",
"",
DESCRIPTION,
])
files.append((f"{dist_info}/METADATA", metadata.encode("utf-8")))
wheel = f"Wheel-Version: 1.0\nGenerator: BakaShrot make_wheel.py\nRoot-Is-Purelib: false\nTag: {tag}\n"
files.append((f"{dist_info}/WHEEL", wheel.encode("utf-8")))
for path in licenses:
files.append((f"{dist_info}/licenses/{os.path.basename(path)}", read(path)))
record = [record_line(path, data) for path, data in files] + [f"{dist_info}/RECORD,,", ""]
files.append((f"{dist_info}/RECORD", "\n".join(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 archive:
for path, data in files:
info = zipfile.ZipInfo(path, FIXED_TIME)
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = (0o755 if path.endswith(".so") else 0o644) << 16
archive.writestr(info, data)
print(wheel_path)
if __name__ == "__main__":
main()