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

Made the DLL handle-based: several clients per process

- BakaShrot_CreateClient() returns a handle, the first argument of every
  other export (same names); BakaShrot_FreeClient() frees it. No default
  client, no exports without a handle: apps built for the old DLL need
  updating
- Each client has its own settings, connection, answers and errors;
  different clients run at once from threads. A bad handle (freed, made
  up, 0) fails with InvalidArgument, never crashes; handles are never
  reused
- Python: each Client has its own handle, so several can be connected at
  once (the one-Client restriction is gone)
- PureBasic: the prototypes take the handle first; the example runs a
  second client beside the first. Passed with 5.73 LTS and 6.41
- Tests: exports.rs `clients` (two identities at once, bad and freed
  handles, 4 threads on 4 clients, a client freed mid-call); the Python
  check connects two Clients and pushes from two threads

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 23:17:48 +01:00
parent 5b41a06d0c
commit d061ff6f80
10 changed files with 1074 additions and 561 deletions
+94 -61
View File
@@ -18,67 +18,79 @@ 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.
* Makes a client: its handle (1 and up, never reused), 0 if it failed.
*/
int32_t BakaShrot_GetLastError(void);
int64_t BakaShrot_CreateClient(void);
/**
* Why the last call failed, in words: the server's reason for a refusal,
* the client's otherwise. Empty if it succeeded.
* Frees a client and closes its connection (once a call on it in another
* thread ends): 1, or 0 if it wasn't one.
*/
ptrdiff_t BakaShrot_GetRefusalReasonA(char *buffer, ptrdiff_t size);
ptrdiff_t BakaShrot_FreeClient(int64_t client);
/**
* Why the client's 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. `InvalidArgument` for
* a bad handle.
*/
int32_t BakaShrot_GetLastError(int64_t client);
/**
* Why the client's last call failed, in words: the server's reason for a
* refusal, the client's otherwise. Empty if it succeeded.
*/
ptrdiff_t BakaShrot_GetRefusalReasonA(int64_t client, char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetRefusalReasonA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetRefusalReasonW(uint16_t *buffer, ptrdiff_t size);
ptrdiff_t BakaShrot_GetRefusalReasonW(int64_t client, 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);
ptrdiff_t BakaShrot_SetCaCertificateA(int64_t client, const char *certificate);
/**
* The same as `BakaShrot_SetCaCertificateA`, in UTF-16.
*/
ptrdiff_t BakaShrot_SetCaCertificateW(const uint16_t *certificate);
ptrdiff_t BakaShrot_SetCaCertificateW(int64_t client, const uint16_t *certificate);
/**
* Sets this client's certificate, which says its node and its roles: PEM
* Sets the 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);
ptrdiff_t BakaShrot_SetCertificateA(int64_t client, const char *certificate);
/**
* The same as `BakaShrot_SetCertificateA`, in UTF-16.
*/
ptrdiff_t BakaShrot_SetCertificateW(const uint16_t *certificate);
ptrdiff_t BakaShrot_SetCertificateW(int64_t client, const uint16_t *certificate);
/**
* Sets this client's private key, its certificate's: PEM text, or the path
* Sets the 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);
ptrdiff_t BakaShrot_SetPrivateKeyA(int64_t client, const char *key);
/**
* The same as `BakaShrot_SetPrivateKeyA`, in UTF-16.
*/
ptrdiff_t BakaShrot_SetPrivateKeyW(const uint16_t *key);
ptrdiff_t BakaShrot_SetPrivateKeyW(int64_t client, 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 (one that isn't there is a
* `FileError`); null or empty for none. Before connecting.
*/
ptrdiff_t BakaShrot_SetCrlA(const char *crl);
ptrdiff_t BakaShrot_SetCrlA(int64_t client, const char *crl);
/**
* The same as `BakaShrot_SetCrlA`, in UTF-16.
*/
ptrdiff_t BakaShrot_SetCrlW(const uint16_t *crl);
ptrdiff_t BakaShrot_SetCrlW(int64_t client, const uint16_t *crl);
/**
* Connects to the server at `host` (a name or an address) and `port`:
@@ -87,57 +99,59 @@ ptrdiff_t BakaShrot_SetCrlW(const uint16_t *crl);
* 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);
ptrdiff_t BakaShrot_ConnectA(int64_t client, 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);
ptrdiff_t BakaShrot_ConnectW(int64_t client, 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);
ptrdiff_t BakaShrot_IsConnected(int64_t client);
/**
* Closes the connection: 0 if there was none. The settings stay.
*/
ptrdiff_t BakaShrot_Disconnect(void);
ptrdiff_t BakaShrot_Disconnect(int64_t client);
/**
* 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);
ptrdiff_t BakaShrot_GetNodeA(int64_t client, char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetNodeA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetNodeW(uint16_t *buffer, ptrdiff_t size);
ptrdiff_t BakaShrot_GetNodeW(int64_t client, 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);
int64_t BakaShrot_PushMessageToA(int64_t client, 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);
int64_t BakaShrot_PushMessageToW(int64_t client, 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);
ptrdiff_t BakaShrot_GetLatestMessageOfA(int64_t client, 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);
ptrdiff_t BakaShrot_GetLatestMessageOfW(int64_t client,
const uint16_t *topic,
const uint16_t *node);
/**
* Gets the messages of `topic` and `node` after id `after` (0 for the
@@ -146,12 +160,17 @@ ptrdiff_t BakaShrot_GetLatestMessageOfW(const uint16_t *topic, const uint16_t *n
* 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);
int32_t BakaShrot_GetMessagesA(int64_t client,
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,
int32_t BakaShrot_GetMessagesW(int64_t client,
const uint16_t *topic,
const uint16_t *node,
int64_t after,
int32_t limit);
@@ -159,119 +178,119 @@ int32_t BakaShrot_GetMessagesW(const uint16_t *topic,
/**
* How many messages the last `GetMessages` or `GetLatestMessageOf` got.
*/
int32_t BakaShrot_GetMessageCount(void);
int32_t BakaShrot_GetMessageCount(int64_t client);
/**
* 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);
ptrdiff_t BakaShrot_SelectMessage(int64_t client, 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);
ptrdiff_t BakaShrot_HasMoreMessages(int64_t client);
/**
* The selected message's id, 0 if none.
*/
int64_t BakaShrot_GetMessageId(void);
int64_t BakaShrot_GetMessageId(int64_t client);
/**
* 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);
int64_t BakaShrot_GetMessagePushedAt(int64_t client);
/**
* The selected message's attachment's size, 0 without one.
*/
int64_t BakaShrot_GetMessageAttachmentSize(void);
int64_t BakaShrot_GetMessageAttachmentSize(int64_t client);
/**
* 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);
ptrdiff_t BakaShrot_IsMessageAttachmentReady(int64_t client);
/**
* The selected message's data, as pushed (JSON or not).
*/
ptrdiff_t BakaShrot_GetMessageDataA(char *buffer, ptrdiff_t size);
ptrdiff_t BakaShrot_GetMessageDataA(int64_t client, char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetMessageDataA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetMessageDataW(uint16_t *buffer, ptrdiff_t size);
ptrdiff_t BakaShrot_GetMessageDataW(int64_t client, uint16_t *buffer, ptrdiff_t size);
/**
* The topic the last `GetMessages` or `GetLatestMessageOf` asked for.
*/
ptrdiff_t BakaShrot_GetMessageTopicA(char *buffer, ptrdiff_t size);
ptrdiff_t BakaShrot_GetMessageTopicA(int64_t client, char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetMessageTopicA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetMessageTopicW(uint16_t *buffer, ptrdiff_t size);
ptrdiff_t BakaShrot_GetMessageTopicW(int64_t client, uint16_t *buffer, ptrdiff_t size);
/**
* The node the last `GetMessages` or `GetLatestMessageOf` asked for.
*/
ptrdiff_t BakaShrot_GetMessageNodeA(char *buffer, ptrdiff_t size);
ptrdiff_t BakaShrot_GetMessageNodeA(int64_t client, char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetMessageNodeA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetMessageNodeW(uint16_t *buffer, ptrdiff_t size);
ptrdiff_t BakaShrot_GetMessageNodeW(int64_t client, uint16_t *buffer, ptrdiff_t size);
/**
* Lists the topics with messages that this client may push to or read
* (every one if its roles have `list_topics` or `query`): how many, -1 on
* failure. Then `BakaShrot_GetNamesList()`.
*/
int32_t BakaShrot_ListTopics(void);
int32_t BakaShrot_ListTopics(int64_t client);
/**
* Lists the nodes with messages in the topics this client may read (every
* one if its roles have `list_nodes` or `query`): how many, -1 on failure. Then
* `BakaShrot_GetNamesList()`.
*/
int32_t BakaShrot_ListNodes(void);
int32_t BakaShrot_ListNodes(int64_t client);
/**
* 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);
ptrdiff_t BakaShrot_GetNamesListA(int64_t client, char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetNamesListA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetNamesListW(uint16_t *buffer, ptrdiff_t size);
ptrdiff_t BakaShrot_GetNamesListW(int64_t client, 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);
ptrdiff_t BakaShrot_QueryA(int64_t client, const char *sql);
/**
* The same as `BakaShrot_QueryA`, in UTF-16.
*/
ptrdiff_t BakaShrot_QueryW(const uint16_t *sql);
ptrdiff_t BakaShrot_QueryW(int64_t client, 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);
ptrdiff_t BakaShrot_GetQueryResultA(int64_t client, char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetQueryResultA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetQueryResultW(uint16_t *buffer, ptrdiff_t size);
ptrdiff_t BakaShrot_GetQueryResultW(int64_t client, uint16_t *buffer, ptrdiff_t size);
/**
* Pushes a message with the file at `FilePath` as its attachment (1 byte
@@ -280,12 +299,16 @@ ptrdiff_t BakaShrot_GetQueryResultW(uint16_t *buffer, ptrdiff_t size);
* 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);
int64_t BakaShrot_PushMessageWithFileA(int64_t client,
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,
int64_t BakaShrot_PushMessageWithFileW(int64_t client,
const uint16_t *topic,
const uint16_t *data,
const uint16_t *file_path);
@@ -293,7 +316,8 @@ int64_t BakaShrot_PushMessageWithFileW(const uint16_t *topic,
* Pushes a message with the `Size` bytes at `Data` as its attachment, as
* `BakaShrot_PushMessageWithFileA` does.
*/
int64_t BakaShrot_PushMessageWithDataA(const char *topic,
int64_t BakaShrot_PushMessageWithDataA(int64_t client,
const char *topic,
const char *data,
const void *attachment,
int64_t size);
@@ -301,7 +325,8 @@ int64_t BakaShrot_PushMessageWithDataA(const char *topic,
/**
* The same as `BakaShrot_PushMessageWithDataA`, in UTF-16.
*/
int64_t BakaShrot_PushMessageWithDataW(const uint16_t *topic,
int64_t BakaShrot_PushMessageWithDataW(int64_t client,
const uint16_t *topic,
const uint16_t *data,
const void *attachment,
int64_t size);
@@ -313,7 +338,8 @@ int64_t BakaShrot_PushMessageWithDataW(const uint16_t *topic,
* `NotReady` if it isn't on this server yet, `AttachmentMismatch`). A
* failed one leaves no file.
*/
int64_t BakaShrot_SaveAttachmentA(const char *topic,
int64_t BakaShrot_SaveAttachmentA(int64_t client,
const char *topic,
const char *node,
int64_t message_id,
const char *file_path);
@@ -321,7 +347,8 @@ int64_t BakaShrot_SaveAttachmentA(const char *topic,
/**
* The same as `BakaShrot_SaveAttachmentA`, in UTF-16.
*/
int64_t BakaShrot_SaveAttachmentW(const uint16_t *topic,
int64_t BakaShrot_SaveAttachmentW(int64_t client,
const uint16_t *topic,
const uint16_t *node,
int64_t message_id,
const uint16_t *file_path);
@@ -331,24 +358,30 @@ int64_t BakaShrot_SaveAttachmentW(const uint16_t *topic,
* 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);
int64_t BakaShrot_LoadAttachmentA(int64_t client,
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);
int64_t BakaShrot_LoadAttachmentW(int64_t client,
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);
int64_t BakaShrot_GetAttachmentData(int64_t client, void *buffer, int64_t buffer_size);
/**
* Frees what `BakaShrot_LoadAttachment()` read: 1.
*/
ptrdiff_t BakaShrot_FreeAttachmentData(void);
ptrdiff_t BakaShrot_FreeAttachmentData(int64_t client);
#ifdef __cplusplus
} // extern "C"
+156 -121
View File
@@ -18,65 +18,74 @@
; 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}")
; Client = BakaShrot_CreateClient()
; BakaShrot_SetCaCertificate(Client, "ca.crt") ; a file, or PEM text
; BakaShrot_SetCertificate(Client, "kitchen.crt")
; BakaShrot_SetPrivateKey(Client, "kitchen.key")
; If BakaShrot_Connect(Client, "10.0.0.2", 7000)
; BakaShrot_PushMessageTo(Client, "logs", ~"{\"temp\": 21}")
; ...
; EndIf
; BakaShrot_FreeClient(Client)
; BakaShrot_UnloadClient()
; EndIf
;
; Every function but BakaShrot_CreateClient() takes the client first (a
; quad). Make as many as needed: each has its own connection and errors.
;
; 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. _GetNamesList() is
; {"kind":"topic","names":[...],"truncated":false}.
; call, BakaShrot_GetLastError(Client) 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(Client) says why in words.
; _GetNamesList() is {"kind":"topic","names":[...],"truncated":false}.
; ============================================================================
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()
PrototypeC.q BakaShrot_CreateClient_Prototype()
PrototypeC.i BakaShrot_FreeClient_Prototype(Client.q)
PrototypeC.l BakaShrot_GetLastError_Prototype(Client.q)
PrototypeC.i BakaShrot_GetRefusalReason_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.i BakaShrot_SetCaCertificate_Prototype(Client.q, Certificate.p-unicode)
PrototypeC.i BakaShrot_SetCertificate_Prototype(Client.q, Certificate.p-unicode)
PrototypeC.i BakaShrot_SetPrivateKey_Prototype(Client.q, PrivateKey.p-unicode)
PrototypeC.i BakaShrot_SetCrl_Prototype(Client.q, Crl.p-unicode)
PrototypeC.i BakaShrot_Connect_Prototype(Client.q, Host.p-unicode, Port.l)
PrototypeC.i BakaShrot_IsConnected_Prototype(Client.q)
PrototypeC.i BakaShrot_Disconnect_Prototype(Client.q)
PrototypeC.i BakaShrot_GetNode_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.q BakaShrot_PushMessageTo_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode)
PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Client.q, Topic.p-unicode, Node.p-unicode)
PrototypeC.l BakaShrot_GetMessages_Prototype(Client.q, Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l)
PrototypeC.l BakaShrot_GetMessageCount_Prototype(Client.q)
PrototypeC.i BakaShrot_SelectMessage_Prototype(Client.q, Index.l)
PrototypeC.i BakaShrot_HasMoreMessages_Prototype(Client.q)
PrototypeC.q BakaShrot_GetMessageId_Prototype(Client.q)
PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype(Client.q)
PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype(Client.q)
PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype(Client.q)
PrototypeC.i BakaShrot_GetMessageData_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.i BakaShrot_GetMessageTopic_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.i BakaShrot_GetMessageNode_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.l BakaShrot_ListTopics_Prototype(Client.q)
PrototypeC.l BakaShrot_ListNodes_Prototype(Client.q)
PrototypeC.i BakaShrot_GetNamesList_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.i BakaShrot_Query_Prototype(Client.q, Sql.p-unicode)
PrototypeC.i BakaShrot_GetQueryResult_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode)
PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode, *Data, Size.q)
PrototypeC.q BakaShrot_SaveAttachment_Prototype(Client.q, Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode)
PrototypeC.q BakaShrot_LoadAttachment_Prototype(Client.q, Topic.p-unicode, Node.p-unicode, MessageId.q)
PrototypeC.q BakaShrot_GetAttachmentData_Prototype(Client.q, *Buffer, BufferSize.q)
PrototypeC.i BakaShrot_FreeAttachmentData_Prototype(Client.q)
Global BakaShrot_CreateClient.BakaShrot_CreateClient_Prototype
Global BakaShrot_FreeClient.BakaShrot_FreeClient_Prototype
Global BakaShrot_GetLastError.BakaShrot_GetLastError_Prototype
Global BakaShrot_GetRefusalReason.BakaShrot_GetRefusalReason_Prototype
Global BakaShrot_SetCaCertificate.BakaShrot_SetCaCertificate_Prototype
@@ -151,40 +160,42 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
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_CreateClient = BakaShrot_ClientFunction("BakaShrot_CreateClient")
BakaShrot_FreeClient = BakaShrot_ClientFunction("BakaShrot_FreeClient")
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")
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()
@@ -194,18 +205,21 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
EndProcedure
; Calls a string getter of the DLL (Getter(*Buffer, BufferSize)) and
; Calls a client's string getter (Getter(Client, *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)
PrototypeC.i BakaShrot_StringGetter_Prototype(Client.q, *Buffer, BufferSize.i)
Procedure.s BakaShrot_GetString(Client.q, Getter.BakaShrot_StringGetter_Prototype)
Protected *Buffer, BufferSize.i, Text.s
BufferSize = Getter(0, 0)
BufferSize = Getter(Client, 0, 0)
If BufferSize <= 0
ProcedureReturn ""
EndIf
*Buffer = AllocateMemory(BufferSize)
If Not *Buffer
ProcedureReturn ""
EndIf
Getter(*Buffer, BufferSize)
Getter(Client, *Buffer, BufferSize)
Text = PeekS(*Buffer, -1, #PB_Unicode)
FreeMemory(*Buffer)
@@ -213,32 +227,32 @@ Procedure.s BakaShrot_GetString(Getter.BakaShrot_StringGetter_Prototype)
EndProcedure
; The string getters, as strings.
Procedure.s BakaShrot_GetRefusalReasonString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetRefusalReason)
Procedure.s BakaShrot_GetRefusalReasonString(Client.q)
ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetRefusalReason)
EndProcedure
Procedure.s BakaShrot_GetNodeString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetNode)
Procedure.s BakaShrot_GetNodeString(Client.q)
ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetNode)
EndProcedure
Procedure.s BakaShrot_GetMessageDataString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageData)
Procedure.s BakaShrot_GetMessageDataString(Client.q)
ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageData)
EndProcedure
Procedure.s BakaShrot_GetMessageTopicString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageTopic)
Procedure.s BakaShrot_GetMessageTopicString(Client.q)
ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageTopic)
EndProcedure
Procedure.s BakaShrot_GetMessageNodeString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageNode)
Procedure.s BakaShrot_GetMessageNodeString(Client.q)
ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageNode)
EndProcedure
Procedure.s BakaShrot_GetNamesListString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetNamesList)
Procedure.s BakaShrot_GetNamesListString(Client.q)
ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetNamesList)
EndProcedure
Procedure.s BakaShrot_GetQueryResultString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetQueryResult)
Procedure.s BakaShrot_GetQueryResultString(Client.q)
ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetQueryResult)
EndProcedure
@@ -246,18 +260,29 @@ EndProcedure
; 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.
; attachment and reads that back, lists the topics; then a second client
; connected at the same time reads it too.
CompilerIf #PB_Compiler_IsMainFile
Define Id.q, Size.q, *Attachment, *Copy
Define Client.q, Second.q, 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())
; Prints why a client's last call failed, then ends.
Procedure Failed(Client.q, What.s)
PrintN(What + " failed: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client)) + ", " + BakaShrot_GetRefusalReasonString(Client))
BakaShrot_UnloadClient()
End 1
EndProcedure
; A new client, connected with the certificates given.
Procedure.q Connected(What.s)
Protected Client.q = BakaShrot_CreateClient()
If Not BakaShrot_SetCaCertificate(Client, ProgramParameter(1)) : Failed(Client, What + ": setting the CA's certificate") : EndIf
If Not BakaShrot_SetCertificate(Client, ProgramParameter(2)) : Failed(Client, What + ": setting the certificate") : EndIf
If Not BakaShrot_SetPrivateKey(Client, ProgramParameter(3)) : Failed(Client, What + ": setting the private key") : EndIf
If Not BakaShrot_Connect(Client, ProgramParameter(4), Val(ProgramParameter(5))) : Failed(Client, What + ": connecting") : EndIf
ProcedureReturn Client
EndProcedure
OpenConsole()
If CountProgramParameters() < 6
PrintN("Usage: ClientExample <DllPath> <CaFile> <CertificateFile> <KeyFile> <Host> <Port>")
@@ -269,28 +294,25 @@ CompilerIf #PB_Compiler_IsMainFile
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())
Client = Connected("The client")
PrintN("Client #" + Str(Client) + " connected as " + BakaShrot_GetNodeString(Client))
Id = BakaShrot_PushMessageTo("logs", ~"{\"from\": \"PureBasic\", \"text\": \"hello\"}")
If Id < 1 : Failed("Pushing") : EndIf
Id = BakaShrot_PushMessageTo(Client, "logs", ~"{\"from\": \"PureBasic\", \"text\": \"hello\"}")
If Id < 1 : Failed(Client, "Pushing") : EndIf
PrintN("Pushed #" + Str(Id))
If Not BakaShrot_GetLatestMessageOf("logs", BakaShrot_GetNodeString()) : Failed("Reading") : EndIf
PrintN("Latest: #" + Str(BakaShrot_GetMessageId()) + " " + BakaShrot_GetMessageDataString())
If Not BakaShrot_GetLatestMessageOf(Client, "logs", BakaShrot_GetNodeString(Client)) : Failed(Client, "Reading") : EndIf
PrintN("Latest: #" + Str(BakaShrot_GetMessageId(Client)) + " " + BakaShrot_GetMessageDataString(Client))
*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
Id = BakaShrot_PushMessageWithData(Client, "logs", ~"{\"photo\": 1}", *Attachment, 3000)
If Id < 1 : Failed(Client, "Pushing an attachment") : EndIf
Size = BakaShrot_LoadAttachment(Client, "logs", BakaShrot_GetNodeString(Client), Id)
If Size < 0 : Failed(Client, "Reading the attachment") : EndIf
*Copy = AllocateMemory(Size)
BakaShrot_GetAttachmentData(*Copy, Size)
BakaShrot_FreeAttachmentData()
BakaShrot_GetAttachmentData(Client, *Copy, Size)
BakaShrot_FreeAttachmentData(Client)
If CompareMemory(*Attachment, *Copy, 3000)
PrintN("Pushed #" + Str(Id) + " with " + Str(Size) + " bytes, read back the same")
Else
@@ -299,15 +321,28 @@ CompilerIf #PB_Compiler_IsMainFile
EndIf
FreeMemory(*Attachment) : FreeMemory(*Copy)
If BakaShrot_ListTopics() < 0 : Failed("Listing") : EndIf
PrintN("Topics: " + BakaShrot_GetNamesListString())
If BakaShrot_ListTopics(Client) < 0 : Failed(Client, "Listing") : EndIf
PrintN("Topics: " + BakaShrot_GetNamesListString(Client))
If BakaShrot_PushMessageTo("nothing", "{}") < 0
PrintN("A push to a topic it may not push to: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString())
If BakaShrot_PushMessageTo(Client, "nothing", "{}") < 0
PrintN("A push to a topic it may not push to: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client)) + ", " + BakaShrot_GetRefusalReasonString(Client))
EndIf
BakaShrot_Disconnect()
PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected()))
; A second client, connected at the same time.
Second = Connected("The second client")
If Not BakaShrot_GetLatestMessageOf(Second, "logs", BakaShrot_GetNodeString(Second)) : Failed(Second, "The second client reading") : EndIf
PrintN("Second client #" + Str(Second) + ", both connected (" + Str(BakaShrot_IsConnected(Client)) + Str(BakaShrot_IsConnected(Second)) + "), its latest: #" + Str(BakaShrot_GetMessageId(Second)))
; Its errors are its own: the first client's last call succeeds, its fails.
BakaShrot_GetLatestMessageOf(Client, "logs", BakaShrot_GetNodeString(Client))
If BakaShrot_PushMessageTo(Second, "nothing", "{}") < 0
PrintN("Its own error: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Second)) + ", the first client's: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client)))
EndIf
BakaShrot_FreeClient(Second)
PrintN("Freed, IsConnected: " + Str(BakaShrot_IsConnected(Second)) + ", its error now: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Second)))
BakaShrot_Disconnect(Client)
PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected(Client)))
BakaShrot_FreeClient(Client)
BakaShrot_UnloadClient()
End 0
+92 -79
View File
@@ -37,9 +37,9 @@ numbers as the DLL's BakaShrot_GetLastError()):
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.
Each Client has its own client in the DLL, so several can be connected at
once, from different threads. A Client's own calls are serialized with a
lock: one 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.
@@ -237,41 +237,44 @@ class _Dll:
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
H = Q # a client's handle
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, []),
"BakaShrot_CreateClient": (Q, []),
"BakaShrot_FreeClient": (I, [H]),
"BakaShrot_GetLastError": (L, [H]),
"BakaShrot_GetRefusalReasonA": (I, [H, S, I]),
"BakaShrot_SetCaCertificateA": (I, [H, P]),
"BakaShrot_SetCertificateA": (I, [H, P]),
"BakaShrot_SetPrivateKeyA": (I, [H, P]),
"BakaShrot_SetCrlA": (I, [H, P]),
"BakaShrot_ConnectA": (I, [H, P, L]),
"BakaShrot_IsConnected": (I, [H]),
"BakaShrot_Disconnect": (I, [H]),
"BakaShrot_GetNodeA": (I, [H, S, I]),
"BakaShrot_PushMessageToA": (Q, [H, P, P]),
"BakaShrot_GetLatestMessageOfA": (I, [H, P, P]),
"BakaShrot_GetMessagesA": (L, [H, P, P, Q, L]),
"BakaShrot_GetMessageCount": (L, [H]),
"BakaShrot_SelectMessage": (I, [H, L]),
"BakaShrot_HasMoreMessages": (I, [H]),
"BakaShrot_GetMessageId": (Q, [H]),
"BakaShrot_GetMessagePushedAt": (Q, [H]),
"BakaShrot_GetMessageAttachmentSize": (Q, [H]),
"BakaShrot_IsMessageAttachmentReady": (I, [H]),
"BakaShrot_GetMessageTopicA": (I, [H, S, I]),
"BakaShrot_GetMessageNodeA": (I, [H, S, I]),
"BakaShrot_GetMessageDataA": (I, [H, S, I]),
"BakaShrot_ListTopics": (L, [H]),
"BakaShrot_ListNodes": (L, [H]),
"BakaShrot_GetNamesListA": (I, [H, S, I]),
"BakaShrot_QueryA": (I, [H, P]),
"BakaShrot_GetQueryResultA": (I, [H, S, I]),
"BakaShrot_PushMessageWithFileA": (Q, [H, P, P, P]),
"BakaShrot_PushMessageWithDataA": (Q, [H, P, P, P, Q]),
"BakaShrot_SaveAttachmentA": (Q, [H, P, P, Q, P]),
"BakaShrot_LoadAttachmentA": (Q, [H, P, P, Q]),
"BakaShrot_GetAttachmentData": (Q, [H, S, Q]),
"BakaShrot_FreeAttachmentData": (I, [H]),
}
for name, (restype, argtypes) in signatures.items():
try:
@@ -280,15 +283,16 @@ class _Dll:
raise BakaShrotError(f"{path} has no {name}, is it an older build?", ErrorCode.INTERNAL) from error
function.restype = restype
function.argtypes = argtypes
# BakaShrot_PushMessageToA as PushMessageToA.
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)
def string(self, getter, handle: int) -> str:
"""Calls a client's string getter: asks for the size, then copies (UTF-8)."""
size = getter(handle, None, 0)
if size <= 1:
return ""
buffer = ctypes.create_string_buffer(size)
getter(buffer, size)
getter(handle, buffer, size)
return buffer.raw[: size - 1].decode("utf-8")
@@ -309,8 +313,6 @@ class Client:
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)
@@ -321,6 +323,8 @@ class Client:
self.key = os.fspath(key)
self.crl = os.fspath(crl) if crl else None
self.node = ""
# Its client in the DLL, from connect() to close().
self._handle: Optional[int] = None
@classmethod
def from_file(cls, path: Union[str, os.PathLike], dll_path: Optional[str] = None) -> "Client":
@@ -360,34 +364,44 @@ class Client:
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)."""
BakaShrotError on a bad setting (INVALID_ARGUMENT, FILE_ERROR)."""
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 self._handle is None:
handle = dll.CreateClient()
if handle < 1:
raise BakaShrotError("The DLL made no client", ErrorCode.INTERNAL)
self._handle = handle
handle = self._handle
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")):
if not setter(handle, value.encode("utf-8")):
raise self._failed("Certificates")
if not dll.ConnectA(self.host.encode("utf-8"), self.port):
if not dll.ConnectA(handle, 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
self.node = dll.string(dll.GetNodeA, handle)
return self
def close(self) -> None:
"""Disconnects, and frees its client in the DLL. connect() again
reconnects."""
with self._lock:
if Client._connected_client is self:
self._dll.Disconnect()
Client._connected_client = None
if self._handle is not None:
self._dll.FreeClient(self._handle)
self._handle = None
def __del__(self):
try:
self.close()
except Exception: # noqa: BLE001 - the interpreter may be shutting down
pass
@property
def connected(self) -> bool:
return Client._connected_client is self and bool(self._dll.IsConnected())
handle = self._handle
return handle is not None and bool(self._dll.IsConnected(handle))
def __enter__(self) -> "Client":
return self.connect()
@@ -401,15 +415,13 @@ class Client:
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)
code = _error_code(self._dll.GetLastError(self._handle))
reason = self._dll.string(self._dll.GetRefusalReasonA, self._handle)
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):
@@ -435,13 +447,13 @@ class Client:
with self._lock:
self._check_connected()
if attachment is None:
message_id = self._dll.PushMessageToA(_name(topic), encoded)
message_id = self._dll.PushMessageToA(self._handle, _name(topic), encoded)
elif isinstance(attachment, (bytes, bytearray, memoryview)):
raw = bytes(attachment)
message_id = self._dll.PushMessageWithDataA(_name(topic), encoded, raw, len(raw))
message_id = self._dll.PushMessageWithDataA(self._handle, _name(topic), encoded, raw, len(raw))
else:
path = os.fspath(attachment).encode("utf-8")
message_id = self._dll.PushMessageWithFileA(_name(topic), encoded, path)
message_id = self._dll.PushMessageWithFileA(self._handle, _name(topic), encoded, path)
if message_id < 1:
raise self._failed("Push")
return message_id
@@ -452,15 +464,15 @@ class Client:
(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))
size = self._dll.LoadAttachmentA(self._handle, _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)
self._dll.GetAttachmentData(self._handle, buffer, size)
return buffer.raw[:size]
finally:
self._dll.FreeAttachmentData()
self._dll.FreeAttachmentData(self._handle)
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
@@ -468,23 +480,24 @@ class Client:
leaves no file."""
with self._lock:
self._check_connected()
size = self._dll.SaveAttachmentA(_name(topic), _name(node), int(message_id),
size = self._dll.SaveAttachmentA(self._handle, _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()))
dll, handle = self._dll, self._handle
return Message(dll.GetMessageId(handle), dll.string(dll.GetMessageTopicA, handle),
dll.string(dll.GetMessageNodeA, handle), dll.string(dll.GetMessageDataA, handle),
dll.GetMessagePushedAt(handle), dll.GetMessageAttachmentSize(handle),
bool(dll.IsMessageAttachmentReady(handle)))
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)):
if not self._dll.GetLatestMessageOfA(self._handle, _name(topic), _name(node)):
error = self._failed("Latest message")
if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND:
return None
@@ -503,14 +516,14 @@ class Client:
with self._lock:
self._check_connected()
dll = self._dll
count = dll.GetMessagesA(_name(topic), _name(node), after, limit)
count = dll.GetMessagesA(self._handle, _name(topic), _name(node), after, limit)
if count < 0:
raise self._failed("Get messages")
messages = []
for index in range(count):
dll.SelectMessage(index)
dll.SelectMessage(self._handle, index)
messages.append(self._current())
return MessagesPage(messages, bool(dll.HasMoreMessages()))
return MessagesPage(messages, bool(dll.HasMoreMessages(self._handle)))
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
@@ -554,9 +567,9 @@ class Client:
def _list(self, function, what: str) -> NamesList:
with self._lock:
self._check_connected()
if function() < 0:
if function(self._handle) < 0:
raise self._failed(what)
parsed = json.loads(self._dll.string(self._dll.GetNamesListA))
parsed = json.loads(self._dll.string(self._dll.GetNamesListA, self._handle))
return NamesList(parsed["kind"], parsed["names"], bool(parsed["truncated"]))
def query_raw(self, sql: str) -> str:
@@ -568,9 +581,9 @@ class Client:
query is refused: RefusedError "malformed JSON"."""
with self._lock:
self._check_connected()
if not self._dll.QueryA(sql.encode("utf-8")):
if not self._dll.QueryA(self._handle, sql.encode("utf-8")):
raise self._failed("Query")
return self._dll.string(self._dll.GetQueryResultA)
return self._dll.string(self._dll.GetQueryResultA, self._handle)
def query(self, sql: str) -> list:
"""query_raw(), as a list of dicts, one per row, by column name."""
+27 -2
View File
@@ -140,8 +140,13 @@ with kitchen:
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)
with lounge:
page = lounge.get_messages("logs", "kitchen", after=0, limit=2)
check("A second Client connected at the same time: both work",
lounge.connected and lounge.node == "lounge" and [m.id for m in page] == [1, 2]
and kitchen.connected and kitchen.latest("secret", "kitchen").id == secret_id,
f"{lounge.node}, {[m.id for m in page]}")
check("Closing one leaves the other connected", kitchen.connected and not lounge.connected)
topics = kitchen.list_topics()
check("list_topics()", topics.kind == "topic" and topics.names == ["logs", "secret"] and not topics.truncated, topics)
@@ -211,6 +216,26 @@ with kitchen:
check("A missing file: refused before sending", ok, detail)
check("Still connected", kitchen.connected)
# --- Two Clients, two threads, at the same time --------------------------
other = Client.from_file(os.path.join(folder, "kitchen.toml"), dll_path).connect()
pushed = {}
def pusher(name, client):
pushed[name] = [client.push({"thread": name, "n": n}, "secret") for n in range(30)]
threads = [threading.Thread(target=pusher, args=("a", kitchen)), threading.Thread(target=pusher, args=("b", other))]
started = time.perf_counter()
for thread in threads:
thread.start()
for thread in threads:
thread.join(30)
elapsed = time.perf_counter() - started
every = sorted(pushed.get("a", []) + pushed.get("b", []))
check("Two Clients pushing from two threads at once: every push stored, each id once",
len(every) == 60 and every == list(range(every[0], every[0] + 60)),
f"{len(every)} pushes in {elapsed * 1000:.0f} ms")
other.close()
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)