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 #endif // __cplusplus
/** /**
* Why the last call failed: a protocol error code (1-99 a server's * Makes a client: its handle (1 and up, never reused), 0 if it failed.
* 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); int64_t BakaShrot_CreateClient(void);
/** /**
* Why the last call failed, in words: the server's reason for a refusal, * Frees a client and closes its connection (once a call on it in another
* the client's otherwise. Empty if it succeeded. * 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. * 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 * 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. * 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. * 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. * 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. * 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. * 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. * 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, * 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 * or the path of a file holding it (one that isn't there is a
* `FileError`); null or empty for none. Before connecting. * `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. * 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`: * 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 * the server refused the certificate, `ServerNotVerified` this client
* refused the server's, `NotAllowed` none of its roles is the server's). * 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. * 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 * 1 while connected: notices when the server closed the connection
* (forgotten then: connect again). * (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. * 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 * The node this client is, as the server said when connecting: its
* certificate's name. Empty when not connected. * 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. * 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 * 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 * id (1 and up), -1 on failure. A push whose answer was lost
* (`ConnectionLost`) may have been stored all the same. * (`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. * 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 * Gets the latest message of `topic` and `node`, then read with the
* `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet. * `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. * 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 * 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, * first is selected; `BakaShrot_SelectMessage()` selects the others,
* `BakaShrot_HasMoreMessages()` says whether more follow the last one. * `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. * 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, const uint16_t *node,
int64_t after, int64_t after,
int32_t limit); int32_t limit);
@@ -159,119 +178,119 @@ int32_t BakaShrot_GetMessagesW(const uint16_t *topic,
/** /**
* How many messages the last `GetMessages` or `GetLatestMessageOf` got. * 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 * Selects the message at `index` (0 to the count - 1) for the getters: 0
* if there's none there (`InvalidArgument`), the selection unchanged. * 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 * 1 if more messages follow the last one the last `GetMessages` got: ask
* again after its id. * again after its id.
*/ */
ptrdiff_t BakaShrot_HasMoreMessages(void); ptrdiff_t BakaShrot_HasMoreMessages(int64_t client);
/** /**
* The selected message's id, 0 if none. * 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: * When the selected message was pushed, by the server it was pushed to:
* milliseconds since 1970-01-01 UTC, 0 if none. * 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. * 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 * 1 if the selected message's attachment is all on this server (a
* replicated one may still be on its way). * 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). * 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. * 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. * 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. * 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. * 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. * 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 * 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 * (every one if its roles have `list_topics` or `query`): how many, -1 on
* failure. Then `BakaShrot_GetNamesList()`. * 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 * 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 * one if its roles have `list_nodes` or `query`): how many, -1 on failure. Then
* `BakaShrot_GetNamesList()`. * `BakaShrot_GetNamesList()`.
*/ */
int32_t BakaShrot_ListNodes(void); int32_t BakaShrot_ListNodes(int64_t client);
/** /**
* The last list, as JSON: * The last list, as JSON:
* `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated` * `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated`
* if some didn't fit. * 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. * 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 * Runs read-only SQL on the server (one SELECT or WITH), if this client
* may query. Then `BakaShrot_GetQueryResult()`. * 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. * 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: * The last query's result, as JSON:
* `{"columns":[...],"rows":[[...],...]}`, every value a string or null. * `{"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. * 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 * 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 * read twice (its SHA-256 first): one changed in between is refused
* (`DataMismatch`). * (`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. * 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 *data,
const uint16_t *file_path); 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 * Pushes a message with the `Size` bytes at `Data` as its attachment, as
* `BakaShrot_PushMessageWithFileA` does. * `BakaShrot_PushMessageWithFileA` does.
*/ */
int64_t BakaShrot_PushMessageWithDataA(const char *topic, int64_t BakaShrot_PushMessageWithDataA(int64_t client,
const char *topic,
const char *data, const char *data,
const void *attachment, const void *attachment,
int64_t size); int64_t size);
@@ -301,7 +325,8 @@ int64_t BakaShrot_PushMessageWithDataA(const char *topic,
/** /**
* The same as `BakaShrot_PushMessageWithDataA`, in UTF-16. * 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 uint16_t *data,
const void *attachment, const void *attachment,
int64_t size); 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 * `NotReady` if it isn't on this server yet, `AttachmentMismatch`). A
* failed one leaves no file. * 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, const char *node,
int64_t message_id, int64_t message_id,
const char *file_path); const char *file_path);
@@ -321,7 +347,8 @@ int64_t BakaShrot_SaveAttachmentA(const char *topic,
/** /**
* The same as `BakaShrot_SaveAttachmentA`, in UTF-16. * 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, const uint16_t *node,
int64_t message_id, int64_t message_id,
const uint16_t *file_path); 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 * memory, checked with its SHA-256 (`BakaShrot_SaveAttachmentA` for big
* ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`. * 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. * 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 * Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if
* `BufferSize` is enough: returns its size (0 if none), copies nothing if * `BufferSize` is enough: returns its size (0 if none), copies nothing if
* it doesn't fit (a null `Buffer` asks for the size). * 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. * Frees what `BakaShrot_LoadAttachment()` read: 1.
*/ */
ptrdiff_t BakaShrot_FreeAttachmentData(void); ptrdiff_t BakaShrot_FreeAttachmentData(int64_t client);
#ifdef __cplusplus #ifdef __cplusplus
} // extern "C" } // extern "C"
@@ -18,65 +18,74 @@
; Include this in an app to use bakashrot.dll (libbakashrot.so on Linux): ; Include this in an app to use bakashrot.dll (libbakashrot.so on Linux):
; XIncludeFile "BakaShrot_Client_Prototypes.pbi" ; XIncludeFile "BakaShrot_Client_Prototypes.pbi"
; If BakaShrot_LoadClient("bakashrot.dll") ; If BakaShrot_LoadClient("bakashrot.dll")
; BakaShrot_SetCaCertificate("ca.crt") ; a file, or PEM text ; Client = BakaShrot_CreateClient()
; BakaShrot_SetCertificate("kitchen.crt") ; BakaShrot_SetCaCertificate(Client, "ca.crt") ; a file, or PEM text
; BakaShrot_SetPrivateKey("kitchen.key") ; BakaShrot_SetCertificate(Client, "kitchen.crt")
; If BakaShrot_Connect("10.0.0.2", 7000) ; BakaShrot_SetPrivateKey(Client, "kitchen.key")
; BakaShrot_PushMessageTo("logs", ~"{\"temp\": 21}") ; If BakaShrot_Connect(Client, "10.0.0.2", 7000)
; BakaShrot_PushMessageTo(Client, "logs", ~"{\"temp\": 21}")
; ... ; ...
; EndIf ; EndIf
; BakaShrot_FreeClient(Client)
; BakaShrot_UnloadClient() ; BakaShrot_UnloadClient()
; EndIf ; 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 ; docs/client.md has what each function does (and
; bindings/c/bakashrot.h, generated from the DLL). The string ; bindings/c/bakashrot.h, generated from the DLL). The string
; functions are mapped to the DLL's W (UTF-16) variants. After a failed ; 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 ; call, BakaShrot_GetLastError(Client) tells why: the codes and what to do
; each are in BakaShrot_ErrorCodes.pbi, next to this file (included below), ; about each are in BakaShrot_ErrorCodes.pbi, next to this file (included
; BakaShrot_ErrorName() names them; BakaShrot_GetRefusalReasonString() says ; below), BakaShrot_ErrorName() names them;
; why in words. _GetNamesList() is ; BakaShrot_GetRefusalReasonString(Client) says why in words.
; {"kind":"topic","names":[...],"truncated":false}. ; _GetNamesList() is {"kind":"topic","names":[...],"truncated":false}.
; ============================================================================ ; ============================================================================
XIncludeFile "BakaShrot_ErrorCodes.pbi" XIncludeFile "BakaShrot_ErrorCodes.pbi"
PrototypeC.l BakaShrot_GetLastError_Prototype() PrototypeC.q BakaShrot_CreateClient_Prototype()
PrototypeC.i BakaShrot_GetRefusalReason_Prototype(*Buffer, BufferSize.i) PrototypeC.i BakaShrot_FreeClient_Prototype(Client.q)
PrototypeC.i BakaShrot_SetCaCertificate_Prototype(Certificate.p-unicode) PrototypeC.l BakaShrot_GetLastError_Prototype(Client.q)
PrototypeC.i BakaShrot_SetCertificate_Prototype(Certificate.p-unicode) PrototypeC.i BakaShrot_GetRefusalReason_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.i BakaShrot_SetPrivateKey_Prototype(PrivateKey.p-unicode) PrototypeC.i BakaShrot_SetCaCertificate_Prototype(Client.q, Certificate.p-unicode)
PrototypeC.i BakaShrot_SetCrl_Prototype(Crl.p-unicode) PrototypeC.i BakaShrot_SetCertificate_Prototype(Client.q, Certificate.p-unicode)
PrototypeC.i BakaShrot_Connect_Prototype(Host.p-unicode, Port.l) PrototypeC.i BakaShrot_SetPrivateKey_Prototype(Client.q, PrivateKey.p-unicode)
PrototypeC.i BakaShrot_IsConnected_Prototype() PrototypeC.i BakaShrot_SetCrl_Prototype(Client.q, Crl.p-unicode)
PrototypeC.i BakaShrot_Disconnect_Prototype() PrototypeC.i BakaShrot_Connect_Prototype(Client.q, Host.p-unicode, Port.l)
PrototypeC.i BakaShrot_GetNode_Prototype(*Buffer, BufferSize.i) PrototypeC.i BakaShrot_IsConnected_Prototype(Client.q)
PrototypeC.q BakaShrot_PushMessageTo_Prototype(Topic.p-unicode, JsonData.p-unicode) PrototypeC.i BakaShrot_Disconnect_Prototype(Client.q)
PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Topic.p-unicode, Node.p-unicode) PrototypeC.i BakaShrot_GetNode_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.l BakaShrot_GetMessages_Prototype(Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l) PrototypeC.q BakaShrot_PushMessageTo_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode)
PrototypeC.l BakaShrot_GetMessageCount_Prototype() PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Client.q, Topic.p-unicode, Node.p-unicode)
PrototypeC.i BakaShrot_SelectMessage_Prototype(Index.l) PrototypeC.l BakaShrot_GetMessages_Prototype(Client.q, Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l)
PrototypeC.i BakaShrot_HasMoreMessages_Prototype() PrototypeC.l BakaShrot_GetMessageCount_Prototype(Client.q)
PrototypeC.q BakaShrot_GetMessageId_Prototype() PrototypeC.i BakaShrot_SelectMessage_Prototype(Client.q, Index.l)
PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype() PrototypeC.i BakaShrot_HasMoreMessages_Prototype(Client.q)
PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype() PrototypeC.q BakaShrot_GetMessageId_Prototype(Client.q)
PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype() PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype(Client.q)
PrototypeC.i BakaShrot_GetMessageData_Prototype(*Buffer, BufferSize.i) PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype(Client.q)
PrototypeC.i BakaShrot_GetMessageTopic_Prototype(*Buffer, BufferSize.i) PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype(Client.q)
PrototypeC.i BakaShrot_GetMessageNode_Prototype(*Buffer, BufferSize.i) PrototypeC.i BakaShrot_GetMessageData_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.l BakaShrot_ListTopics_Prototype() PrototypeC.i BakaShrot_GetMessageTopic_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.l BakaShrot_ListNodes_Prototype() PrototypeC.i BakaShrot_GetMessageNode_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.i BakaShrot_GetNamesList_Prototype(*Buffer, BufferSize.i) PrototypeC.l BakaShrot_ListTopics_Prototype(Client.q)
PrototypeC.i BakaShrot_Query_Prototype(Sql.p-unicode) PrototypeC.l BakaShrot_ListNodes_Prototype(Client.q)
PrototypeC.i BakaShrot_GetQueryResult_Prototype(*Buffer, BufferSize.i) PrototypeC.i BakaShrot_GetNamesList_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode) PrototypeC.i BakaShrot_Query_Prototype(Client.q, Sql.p-unicode)
PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Topic.p-unicode, JsonData.p-unicode, *Data, Size.q) PrototypeC.i BakaShrot_GetQueryResult_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.q BakaShrot_SaveAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode) PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode)
PrototypeC.q BakaShrot_LoadAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q) PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode, *Data, Size.q)
PrototypeC.q BakaShrot_GetAttachmentData_Prototype(*Buffer, BufferSize.q) PrototypeC.q BakaShrot_SaveAttachment_Prototype(Client.q, Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode)
PrototypeC.i BakaShrot_FreeAttachmentData_Prototype() 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_GetLastError.BakaShrot_GetLastError_Prototype
Global BakaShrot_GetRefusalReason.BakaShrot_GetRefusalReason_Prototype Global BakaShrot_GetRefusalReason.BakaShrot_GetRefusalReason_Prototype
Global BakaShrot_SetCaCertificate.BakaShrot_SetCaCertificate_Prototype Global BakaShrot_SetCaCertificate.BakaShrot_SetCaCertificate_Prototype
@@ -151,6 +160,8 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
BakaShrot_ClientMissing = "" BakaShrot_ClientMissing = ""
; PureBasic strings are UTF-16, so the W variants are used. ; PureBasic strings are UTF-16, so the W variants are used.
BakaShrot_CreateClient = BakaShrot_ClientFunction("BakaShrot_CreateClient")
BakaShrot_FreeClient = BakaShrot_ClientFunction("BakaShrot_FreeClient")
BakaShrot_GetLastError = BakaShrot_ClientFunction("BakaShrot_GetLastError") BakaShrot_GetLastError = BakaShrot_ClientFunction("BakaShrot_GetLastError")
BakaShrot_GetRefusalReason = BakaShrot_ClientFunction("BakaShrot_GetRefusalReasonW") BakaShrot_GetRefusalReason = BakaShrot_ClientFunction("BakaShrot_GetRefusalReasonW")
BakaShrot_SetCaCertificate = BakaShrot_ClientFunction("BakaShrot_SetCaCertificateW") BakaShrot_SetCaCertificate = BakaShrot_ClientFunction("BakaShrot_SetCaCertificateW")
@@ -194,18 +205,21 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
EndProcedure 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. ; returns the string: asks for the size, then copies.
PrototypeC.i BakaShrot_StringGetter_Prototype(*Buffer, BufferSize.i) PrototypeC.i BakaShrot_StringGetter_Prototype(Client.q, *Buffer, BufferSize.i)
Procedure.s BakaShrot_GetString(Getter.BakaShrot_StringGetter_Prototype) Procedure.s BakaShrot_GetString(Client.q, Getter.BakaShrot_StringGetter_Prototype)
Protected *Buffer, BufferSize.i, Text.s Protected *Buffer, BufferSize.i, Text.s
BufferSize = Getter(0, 0) BufferSize = Getter(Client, 0, 0)
If BufferSize <= 0
ProcedureReturn ""
EndIf
*Buffer = AllocateMemory(BufferSize) *Buffer = AllocateMemory(BufferSize)
If Not *Buffer If Not *Buffer
ProcedureReturn "" ProcedureReturn ""
EndIf EndIf
Getter(*Buffer, BufferSize) Getter(Client, *Buffer, BufferSize)
Text = PeekS(*Buffer, -1, #PB_Unicode) Text = PeekS(*Buffer, -1, #PB_Unicode)
FreeMemory(*Buffer) FreeMemory(*Buffer)
@@ -213,32 +227,32 @@ Procedure.s BakaShrot_GetString(Getter.BakaShrot_StringGetter_Prototype)
EndProcedure EndProcedure
; The string getters, as strings. ; The string getters, as strings.
Procedure.s BakaShrot_GetRefusalReasonString() Procedure.s BakaShrot_GetRefusalReasonString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetRefusalReason) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetRefusalReason)
EndProcedure EndProcedure
Procedure.s BakaShrot_GetNodeString() Procedure.s BakaShrot_GetNodeString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetNode) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetNode)
EndProcedure EndProcedure
Procedure.s BakaShrot_GetMessageDataString() Procedure.s BakaShrot_GetMessageDataString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageData) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageData)
EndProcedure EndProcedure
Procedure.s BakaShrot_GetMessageTopicString() Procedure.s BakaShrot_GetMessageTopicString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageTopic) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageTopic)
EndProcedure EndProcedure
Procedure.s BakaShrot_GetMessageNodeString() Procedure.s BakaShrot_GetMessageNodeString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageNode) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageNode)
EndProcedure EndProcedure
Procedure.s BakaShrot_GetNamesListString() Procedure.s BakaShrot_GetNamesListString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetNamesList) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetNamesList)
EndProcedure EndProcedure
Procedure.s BakaShrot_GetQueryResultString() Procedure.s BakaShrot_GetQueryResultString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetQueryResult) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetQueryResult)
EndProcedure EndProcedure
@@ -246,18 +260,29 @@ EndProcedure
; IDE), not when it's included by an app. ; IDE), not when it's included by an app.
; ClientExample <DllPath> <CaFile> <CertificateFile> <KeyFile> <Host> <Port> ; ClientExample <DllPath> <CaFile> <CertificateFile> <KeyFile> <Host> <Port>
; Pushes a message to "logs", reads it back, pushes one with an ; 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 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. ; Prints why a client's last call failed, then ends.
Procedure Failed(What.s) Procedure Failed(Client.q, What.s)
PrintN(What + " failed: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString()) PrintN(What + " failed: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client)) + ", " + BakaShrot_GetRefusalReasonString(Client))
BakaShrot_UnloadClient() BakaShrot_UnloadClient()
End 1 End 1
EndProcedure 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() OpenConsole()
If CountProgramParameters() < 6 If CountProgramParameters() < 6
PrintN("Usage: ClientExample <DllPath> <CaFile> <CertificateFile> <KeyFile> <Host> <Port>") PrintN("Usage: ClientExample <DllPath> <CaFile> <CertificateFile> <KeyFile> <Host> <Port>")
@@ -269,28 +294,25 @@ CompilerIf #PB_Compiler_IsMainFile
End 1 End 1
EndIf EndIf
If Not BakaShrot_SetCaCertificate(ProgramParameter(1)) : Failed("Setting the CA's certificate") : EndIf Client = Connected("The client")
If Not BakaShrot_SetCertificate(ProgramParameter(2)) : Failed("Setting the certificate") : EndIf PrintN("Client #" + Str(Client) + " connected as " + BakaShrot_GetNodeString(Client))
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\"}") Id = BakaShrot_PushMessageTo(Client, "logs", ~"{\"from\": \"PureBasic\", \"text\": \"hello\"}")
If Id < 1 : Failed("Pushing") : EndIf If Id < 1 : Failed(Client, "Pushing") : EndIf
PrintN("Pushed #" + Str(Id)) PrintN("Pushed #" + Str(Id))
If Not BakaShrot_GetLatestMessageOf("logs", BakaShrot_GetNodeString()) : Failed("Reading") : EndIf If Not BakaShrot_GetLatestMessageOf(Client, "logs", BakaShrot_GetNodeString(Client)) : Failed(Client, "Reading") : EndIf
PrintN("Latest: #" + Str(BakaShrot_GetMessageId()) + " " + BakaShrot_GetMessageDataString()) PrintN("Latest: #" + Str(BakaShrot_GetMessageId(Client)) + " " + BakaShrot_GetMessageDataString(Client))
*Attachment = AllocateMemory(3000) *Attachment = AllocateMemory(3000)
FillMemory(*Attachment, 3000, 42, #PB_Byte) FillMemory(*Attachment, 3000, 42, #PB_Byte)
Id = BakaShrot_PushMessageWithData("logs", ~"{\"photo\": 1}", *Attachment, 3000) Id = BakaShrot_PushMessageWithData(Client, "logs", ~"{\"photo\": 1}", *Attachment, 3000)
If Id < 1 : Failed("Pushing an attachment") : EndIf If Id < 1 : Failed(Client, "Pushing an attachment") : EndIf
Size = BakaShrot_LoadAttachment("logs", BakaShrot_GetNodeString(), Id) Size = BakaShrot_LoadAttachment(Client, "logs", BakaShrot_GetNodeString(Client), Id)
If Size < 0 : Failed("Reading the attachment") : EndIf If Size < 0 : Failed(Client, "Reading the attachment") : EndIf
*Copy = AllocateMemory(Size) *Copy = AllocateMemory(Size)
BakaShrot_GetAttachmentData(*Copy, Size) BakaShrot_GetAttachmentData(Client, *Copy, Size)
BakaShrot_FreeAttachmentData() BakaShrot_FreeAttachmentData(Client)
If CompareMemory(*Attachment, *Copy, 3000) If CompareMemory(*Attachment, *Copy, 3000)
PrintN("Pushed #" + Str(Id) + " with " + Str(Size) + " bytes, read back the same") PrintN("Pushed #" + Str(Id) + " with " + Str(Size) + " bytes, read back the same")
Else Else
@@ -299,15 +321,28 @@ CompilerIf #PB_Compiler_IsMainFile
EndIf EndIf
FreeMemory(*Attachment) : FreeMemory(*Copy) FreeMemory(*Attachment) : FreeMemory(*Copy)
If BakaShrot_ListTopics() < 0 : Failed("Listing") : EndIf If BakaShrot_ListTopics(Client) < 0 : Failed(Client, "Listing") : EndIf
PrintN("Topics: " + BakaShrot_GetNamesListString()) PrintN("Topics: " + BakaShrot_GetNamesListString(Client))
If BakaShrot_PushMessageTo("nothing", "{}") < 0 If BakaShrot_PushMessageTo(Client, "nothing", "{}") < 0
PrintN("A push to a topic it may not push to: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString()) PrintN("A push to a topic it may not push to: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client)) + ", " + BakaShrot_GetRefusalReasonString(Client))
EndIf EndIf
BakaShrot_Disconnect() ; A second client, connected at the same time.
PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected())) 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() BakaShrot_UnloadClient()
End 0 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 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 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 Each Client has its own client in the DLL, so several can be connected at
connected at a time. Calls are serialized with a lock, so a Client can be once, from different threads. A Client's own calls are serialized with a
shared between threads, one request at a time. 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 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. environment variable, next to this file, then in the current directory.
@@ -237,41 +237,44 @@ class _Dll:
self.path = path 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 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 = { signatures = {
"BakaShrot_GetLastError": (L, []), "BakaShrot_CreateClient": (Q, []),
"BakaShrot_GetRefusalReasonA": (I, [S, I]), "BakaShrot_FreeClient": (I, [H]),
"BakaShrot_SetCaCertificateA": (I, [P]), "BakaShrot_GetLastError": (L, [H]),
"BakaShrot_SetCertificateA": (I, [P]), "BakaShrot_GetRefusalReasonA": (I, [H, S, I]),
"BakaShrot_SetPrivateKeyA": (I, [P]), "BakaShrot_SetCaCertificateA": (I, [H, P]),
"BakaShrot_SetCrlA": (I, [P]), "BakaShrot_SetCertificateA": (I, [H, P]),
"BakaShrot_ConnectA": (I, [P, L]), "BakaShrot_SetPrivateKeyA": (I, [H, P]),
"BakaShrot_IsConnected": (I, []), "BakaShrot_SetCrlA": (I, [H, P]),
"BakaShrot_Disconnect": (I, []), "BakaShrot_ConnectA": (I, [H, P, L]),
"BakaShrot_GetNodeA": (I, [S, I]), "BakaShrot_IsConnected": (I, [H]),
"BakaShrot_PushMessageToA": (Q, [P, P]), "BakaShrot_Disconnect": (I, [H]),
"BakaShrot_GetLatestMessageOfA": (I, [P, P]), "BakaShrot_GetNodeA": (I, [H, S, I]),
"BakaShrot_GetMessagesA": (L, [P, P, Q, L]), "BakaShrot_PushMessageToA": (Q, [H, P, P]),
"BakaShrot_GetMessageCount": (L, []), "BakaShrot_GetLatestMessageOfA": (I, [H, P, P]),
"BakaShrot_SelectMessage": (I, [L]), "BakaShrot_GetMessagesA": (L, [H, P, P, Q, L]),
"BakaShrot_HasMoreMessages": (I, []), "BakaShrot_GetMessageCount": (L, [H]),
"BakaShrot_GetMessageId": (Q, []), "BakaShrot_SelectMessage": (I, [H, L]),
"BakaShrot_GetMessagePushedAt": (Q, []), "BakaShrot_HasMoreMessages": (I, [H]),
"BakaShrot_GetMessageAttachmentSize": (Q, []), "BakaShrot_GetMessageId": (Q, [H]),
"BakaShrot_IsMessageAttachmentReady": (I, []), "BakaShrot_GetMessagePushedAt": (Q, [H]),
"BakaShrot_GetMessageTopicA": (I, [S, I]), "BakaShrot_GetMessageAttachmentSize": (Q, [H]),
"BakaShrot_GetMessageNodeA": (I, [S, I]), "BakaShrot_IsMessageAttachmentReady": (I, [H]),
"BakaShrot_GetMessageDataA": (I, [S, I]), "BakaShrot_GetMessageTopicA": (I, [H, S, I]),
"BakaShrot_ListTopics": (L, []), "BakaShrot_GetMessageNodeA": (I, [H, S, I]),
"BakaShrot_ListNodes": (L, []), "BakaShrot_GetMessageDataA": (I, [H, S, I]),
"BakaShrot_GetNamesListA": (I, [S, I]), "BakaShrot_ListTopics": (L, [H]),
"BakaShrot_QueryA": (I, [P]), "BakaShrot_ListNodes": (L, [H]),
"BakaShrot_GetQueryResultA": (I, [S, I]), "BakaShrot_GetNamesListA": (I, [H, S, I]),
"BakaShrot_PushMessageWithFileA": (Q, [P, P, P]), "BakaShrot_QueryA": (I, [H, P]),
"BakaShrot_PushMessageWithDataA": (Q, [P, P, P, Q]), "BakaShrot_GetQueryResultA": (I, [H, S, I]),
"BakaShrot_SaveAttachmentA": (Q, [P, P, Q, P]), "BakaShrot_PushMessageWithFileA": (Q, [H, P, P, P]),
"BakaShrot_LoadAttachmentA": (Q, [P, P, Q]), "BakaShrot_PushMessageWithDataA": (Q, [H, P, P, P, Q]),
"BakaShrot_GetAttachmentData": (Q, [S, Q]), "BakaShrot_SaveAttachmentA": (Q, [H, P, P, Q, P]),
"BakaShrot_FreeAttachmentData": (I, []), "BakaShrot_LoadAttachmentA": (Q, [H, P, P, Q]),
"BakaShrot_GetAttachmentData": (Q, [H, S, Q]),
"BakaShrot_FreeAttachmentData": (I, [H]),
} }
for name, (restype, argtypes) in signatures.items(): for name, (restype, argtypes) in signatures.items():
try: try:
@@ -280,15 +283,16 @@ class _Dll:
raise BakaShrotError(f"{path} has no {name}, is it an older build?", ErrorCode.INTERNAL) from error raise BakaShrotError(f"{path} has no {name}, is it an older build?", ErrorCode.INTERNAL) from error
function.restype = restype function.restype = restype
function.argtypes = argtypes function.argtypes = argtypes
# BakaShrot_PushMessageToA as PushMessageToA.
setattr(self, name[len("BakaShrot_"):], function) setattr(self, name[len("BakaShrot_"):], function)
def string(self, getter) -> str: def string(self, getter, handle: int) -> str:
"""Calls a string getter: asks for the size, then copies (UTF-8).""" """Calls a client's string getter: asks for the size, then copies (UTF-8)."""
size = getter(None, 0) size = getter(handle, None, 0)
if size <= 1: if size <= 1:
return "" return ""
buffer = ctypes.create_string_buffer(size) buffer = ctypes.create_string_buffer(size)
getter(buffer, size) getter(handle, buffer, size)
return buffer.raw[: size - 1].decode("utf-8") 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). 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, def __init__(self, server: str, ca: str, certificate: str, key: str, crl: Optional[str] = None,
dll_path: Optional[str] = None): dll_path: Optional[str] = None):
self._dll = _Dll.get(dll_path) self._dll = _Dll.get(dll_path)
@@ -321,6 +323,8 @@ class Client:
self.key = os.fspath(key) self.key = os.fspath(key)
self.crl = os.fspath(crl) if crl else None self.crl = os.fspath(crl) if crl else None
self.node = "" self.node = ""
# Its client in the DLL, from connect() to close().
self._handle: Optional[int] = None
@classmethod @classmethod
def from_file(cls, path: Union[str, os.PathLike], dll_path: Optional[str] = None) -> "Client": 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": def connect(self) -> "Client":
"""Connects. Raises ConnectionLostError when the server can't be """Connects. Raises ConnectionLostError when the server can't be
reached (CONNECT_FAILED), AuthError when a certificate is refused, reached (CONNECT_FAILED), AuthError when a certificate is refused,
BakaShrotError on a bad setting (INVALID_ARGUMENT, FILE_ERROR) or BakaShrotError on a bad setting (INVALID_ARGUMENT, FILE_ERROR)."""
another Client holding the DLL's connection (ALREADY_CONNECTED)."""
with self._lock: 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: if self.connected:
return self return self
dll = self._dll 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), for setter, value in ((dll.SetCaCertificateA, self.ca), (dll.SetCertificateA, self.certificate),
(dll.SetPrivateKeyA, self.key), (dll.SetCrlA, self.crl or "")): (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") 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) raise self._failed(f"Connect to {self.host}:{self.port}", connecting=True)
self.node = dll.string(dll.GetNodeA) self.node = dll.string(dll.GetNodeA, handle)
Client._connected_client = self
return self return self
def close(self) -> None: def close(self) -> None:
"""Disconnects, and frees its client in the DLL. connect() again
reconnects."""
with self._lock: with self._lock:
if Client._connected_client is self: if self._handle is not None:
self._dll.Disconnect() self._dll.FreeClient(self._handle)
Client._connected_client = None self._handle = None
def __del__(self):
try:
self.close()
except Exception: # noqa: BLE001 - the interpreter may be shutting down
pass
@property @property
def connected(self) -> bool: 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": def __enter__(self) -> "Client":
return self.connect() return self.connect()
@@ -401,15 +415,13 @@ class Client:
def _failed(self, what: str, connecting: bool = False) -> BakaShrotError: def _failed(self, what: str, connecting: bool = False) -> BakaShrotError:
"""The error for a failed call, by the DLL's BakaShrot_GetLastError().""" """The error for a failed call, by the DLL's BakaShrot_GetLastError()."""
code = _error_code(self._dll.GetLastError()) code = _error_code(self._dll.GetLastError(self._handle))
reason = self._dll.string(self._dll.GetRefusalReasonA) reason = self._dll.string(self._dll.GetRefusalReasonA, self._handle)
if connecting and code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED, if connecting and code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED,
ErrorCode.NOT_ALLOWED, ErrorCode.VERSION_MISMATCH): ErrorCode.NOT_ALLOWED, ErrorCode.VERSION_MISMATCH):
return AuthError(f"{what}: {reason}", code) return AuthError(f"{what}: {reason}", code)
if isinstance(code, int) and 1 <= int(code) <= 99: if isinstance(code, int) and 1 <= int(code) <= 99:
return RefusedError(reason, code) 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) name = code.name if isinstance(code, ErrorCode) else str(code)
message = f"{what} ({name}): {reason or 'failed'}" message = f"{what} ({name}): {reason or 'failed'}"
if code in (ErrorCode.NOT_CONNECTED, ErrorCode.CONNECT_FAILED, ErrorCode.CONNECTION_LOST, ErrorCode.PROTOCOL_ERROR): if code in (ErrorCode.NOT_CONNECTED, ErrorCode.CONNECT_FAILED, ErrorCode.CONNECTION_LOST, ErrorCode.PROTOCOL_ERROR):
@@ -435,13 +447,13 @@ class Client:
with self._lock: with self._lock:
self._check_connected() self._check_connected()
if attachment is None: 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)): elif isinstance(attachment, (bytes, bytearray, memoryview)):
raw = bytes(attachment) 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: else:
path = os.fspath(attachment).encode("utf-8") 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: if message_id < 1:
raise self._failed("Push") raise self._failed("Push")
return message_id return message_id
@@ -452,15 +464,15 @@ class Client:
(NOT_FOUND) or it isn't on this server yet (NOT_READY).""" (NOT_FOUND) or it isn't on this server yet (NOT_READY)."""
with self._lock: with self._lock:
self._check_connected() 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: if size < 0:
raise self._failed("Attachment") raise self._failed("Attachment")
try: try:
buffer = ctypes.create_string_buffer(size) buffer = ctypes.create_string_buffer(size)
self._dll.GetAttachmentData(buffer, size) self._dll.GetAttachmentData(self._handle, buffer, size)
return buffer.raw[:size] return buffer.raw[:size]
finally: 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: 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 """Saves the attachment of a message as path (replaced), a part at a
@@ -468,23 +480,24 @@ class Client:
leaves no file.""" leaves no file."""
with self._lock: with self._lock:
self._check_connected() 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")) os.fspath(path).encode("utf-8"))
if size < 0: if size < 0:
raise self._failed("Attachment") raise self._failed("Attachment")
return size return size
def _current(self) -> Message: def _current(self) -> Message:
dll = self._dll dll, handle = self._dll, self._handle
return Message(dll.GetMessageId(), dll.string(dll.GetMessageTopicA), dll.string(dll.GetMessageNodeA), return Message(dll.GetMessageId(handle), dll.string(dll.GetMessageTopicA, handle),
dll.string(dll.GetMessageDataA), dll.GetMessagePushedAt(), dll.GetMessageAttachmentSize(), dll.string(dll.GetMessageNodeA, handle), dll.string(dll.GetMessageDataA, handle),
bool(dll.IsMessageAttachmentReady())) dll.GetMessagePushedAt(handle), dll.GetMessageAttachmentSize(handle),
bool(dll.IsMessageAttachmentReady(handle)))
def latest(self, topic: str, node: str) -> Optional[Message]: def latest(self, topic: str, node: str) -> Optional[Message]:
"""The latest message of topic/node, None if there's none yet.""" """The latest message of topic/node, None if there's none yet."""
with self._lock: with self._lock:
self._check_connected() 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") error = self._failed("Latest message")
if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND: if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND:
return None return None
@@ -503,14 +516,14 @@ class Client:
with self._lock: with self._lock:
self._check_connected() self._check_connected()
dll = self._dll 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: if count < 0:
raise self._failed("Get messages") raise self._failed("Get messages")
messages = [] messages = []
for index in range(count): for index in range(count):
dll.SelectMessage(index) dll.SelectMessage(self._handle, index)
messages.append(self._current()) 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]: 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 """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: def _list(self, function, what: str) -> NamesList:
with self._lock: with self._lock:
self._check_connected() self._check_connected()
if function() < 0: if function(self._handle) < 0:
raise self._failed(what) 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"])) return NamesList(parsed["kind"], parsed["names"], bool(parsed["truncated"]))
def query_raw(self, sql: str) -> str: def query_raw(self, sql: str) -> str:
@@ -568,9 +581,9 @@ class Client:
query is refused: RefusedError "malformed JSON".""" query is refused: RefusedError "malformed JSON"."""
with self._lock: with self._lock:
self._check_connected() 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") 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: def query(self, sql: str) -> list:
"""query_raw(), as a list of dicts, one per row, by column name.""" """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) check("A message over the limit: refused before sending", ok, detail)
secret_id = kitchen.push({"s": 1}, "secret") secret_id = kitchen.push({"s": 1}, "secret")
check("Push to another allowed topic", secret_id == 1, secret_id) check("Push to another allowed topic", secret_id == 1, secret_id)
ok, detail = raises(lambda: lounge.connect(), BakaShrotError, "one connection", ErrorCode.ALREADY_CONNECTED) with lounge:
check("A second Client can't connect while one is", ok and not lounge.connected, detail) 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() topics = kitchen.list_topics()
check("list_topics()", topics.kind == "topic" and topics.names == ["logs", "secret"] and not topics.truncated, 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("A missing file: refused before sending", ok, detail)
check("Still connected", kitchen.connected) 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) check("close(): disconnected", not kitchen.connected)
ok, detail = raises(lambda: kitchen.push("x", "logs"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED) ok, detail = raises(lambda: kitchen.push("x", "logs"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED)
check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail) check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail)
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "bakashrot-capi" name = "bakashrot-capi"
description = "BakaShrot's C DLL: the BakaShrot_* exports over bakashrot-client, one connection per process." description = "BakaShrot's C DLL: the BakaShrot_* exports over bakashrot-client, as many clients as needed."
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
+317 -153
View File
@@ -1,27 +1,29 @@
//! BakaShrot's C DLL (`bakashrot.dll`, `libbakashrot.so`): the old //! BakaShrot's C DLL (`bakashrot.dll`, `libbakashrot.so`): the
//! `BakaShrot_*` exports over [`bakashrot_client`], for C, PureBasic, //! `BakaShrot_*` exports over [`bakashrot_client`], for C, PureBasic,
//! Python (ctypes) and anything that loads a DLL. `docs/client.md` //! Python (ctypes) and anything that loads a DLL. `docs/client.md`
//! has the whole API; `bindings/c/bakashrot.h` is generated from this file. //! has the whole API; `bindings/c/bakashrot.h` is generated from this file.
//! //!
//! The conventions: //! The conventions:
//! //!
//! - **One connection per process:** set the certificates, connect, send //! - **Clients:** `BakaShrot_CreateClient()` makes one; its handle is the
//! requests, one at a time (calls from several threads wait for each //! first argument of every other export. Each has its own connection,
//! other). //! answers and errors; different clients can be used from different
//! threads at once.
//! - **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or //! - **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or
//! UTF-16 (`uint16_t*`, `wchar_t*` on Windows), null-terminated. //! UTF-16 (`uint16_t*`, `wchar_t*` on Windows), null-terminated.
//! - **Strings out** are copied into the caller's buffer of `BufferSize` //! - **Strings out** are copied into the caller's buffer of `BufferSize`
//! bytes: the getter returns the bytes needed, terminator included, and //! bytes: the getter returns the bytes needed, terminator included, and
//! copies nothing if they don't fit (a null buffer asks for the size). //! copies nothing if they don't fit (a null buffer asks for the size).
//! - **Failures:** 0 (or -1 where a count or an id is returned), then //! - **Failures:** 0 (or -1 where a count or an id is returned), then
//! `BakaShrot_GetLastError()` gives the code (1-99 a server's refusal, the //! `BakaShrot_GetLastError(Client)` gives the code (1-99 a server's
//! connection still open; 100 and up the client's own) and //! refusal, the connection still open; 100 and up the client's own) and
//! `BakaShrot_GetRefusalReason()` why, in words. After `ConnectionLost` //! `BakaShrot_GetRefusalReason()` why, in words. After `ConnectionLost`
//! or `ProtocolError` the connection is closed: connect again. //! or `ProtocolError` the connection is closed: connect again.
//! - **Safety:** pointers are null or valid for what's said, strings //! - **Safety:** pointers are null or valid for what's said, strings
//! terminated, buffers writable for their size. A panic inside is caught //! terminated, buffers writable for their size. A bad handle fails
//! and reported as `Internal`; nothing allocated here is freed by the //! (`InvalidArgument`). A panic inside is caught and reported as
//! caller, or the other way. //! `Internal`; nothing allocated here is freed by the caller, or the
//! other way.
#![allow(unsafe_code, non_snake_case, clippy::missing_safety_doc)] #![allow(unsafe_code, non_snake_case, clippy::missing_safety_doc)]
@@ -30,20 +32,24 @@ mod text;
use bakashrot_client::{Client, Error, Settings}; use bakashrot_client::{Client, Error, Settings};
use bakashrot_proto::ErrorCode; use bakashrot_proto::ErrorCode;
use bakashrot_proto::packets::{MessageEntry, NameKind}; use bakashrot_proto::packets::{MessageEntry, NameKind};
use std::collections::BTreeMap;
use std::ffi::{c_char, c_void}; use std::ffi::{c_char, c_void};
use std::fs::File; use std::fs::File;
use std::io::Cursor; use std::io::Cursor;
use std::panic::{AssertUnwindSafe, catch_unwind}; use std::panic::{AssertUnwindSafe, catch_unwind};
use std::path::Path; use std::path::Path;
use std::sync::{Mutex, MutexGuard, PoisonError}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use text::{Text, Utf8, Utf16}; use text::{Text, Utf8, Utf16};
type Result<T> = std::result::Result<T, Error>; type Result<T> = std::result::Result<T, Error>;
/// Everything the DLL holds: its one connection, its settings, the last /// The next handle, and the clients by handle. A call holds its client's
/// answers. /// `Arc`, so a client freed during a call goes when the call ends.
static STATE: Mutex<State> = Mutex::new(State::new()); static CLIENTS: Mutex<(i64, BTreeMap<i64, Shared>)> = Mutex::new((1, BTreeMap::new()));
type Shared = Arc<Mutex<State>>;
/// A client: its settings, its connection, the last answers.
struct State { struct State {
ca: Option<String>, ca: Option<String>,
certificate: Option<String>, certificate: Option<String>,
@@ -124,15 +130,22 @@ impl State {
} }
} }
fn state() -> MutexGuard<'static, State> { fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
STATE.lock().unwrap_or_else(PoisonError::into_inner) mutex.lock().unwrap_or_else(PoisonError::into_inner)
} }
/// Runs a call that can fail: the last error reset, then set if it fails fn find(client: i64) -> Option<Shared> {
/// (or panics), `failed` returned then. lock(&CLIENTS).1.get(&client).cloned()
fn call<T>(failed: T, run: impl FnOnce(&mut State) -> Result<T>) -> T { }
/// Runs a call that can fail on a client: its last error reset, then set
/// if it fails (or panics). `failed` then, or for a bad handle.
fn call<T>(client: i64, failed: T, run: impl FnOnce(&mut State) -> Result<T>) -> T {
let Some(shared) = find(client) else {
return failed;
};
let outcome = catch_unwind(AssertUnwindSafe(|| { let outcome = catch_unwind(AssertUnwindSafe(|| {
let mut state = state(); let mut state = lock(&shared);
state.last_error = 0; state.last_error = 0;
state.reason.clear(); state.reason.clear();
let outcome = run(&mut state); let outcome = run(&mut state);
@@ -142,20 +155,29 @@ fn call<T>(failed: T, run: impl FnOnce(&mut State) -> Result<T>) -> T {
Ok(Ok(value)) => value, Ok(Ok(value)) => value,
Ok(Err(())) => failed, Ok(Err(())) => failed,
Err(_) => { Err(_) => {
state().fail(Error::new(ErrorCode::Internal, "the DLL panicked")); lock(&shared).fail(Error::new(ErrorCode::Internal, "the DLL panicked"));
failed failed
} }
} }
} }
/// Runs a getter: the last error stays as it is. /// Runs a getter on a client, its last error unchanged. `default` for a
fn get<T>(default: T, read: impl FnOnce(&State) -> T) -> T { /// bad handle.
catch_unwind(AssertUnwindSafe(|| read(&state()))).unwrap_or(default) fn get<T>(client: i64, default: T, read: impl FnOnce(&mut State) -> T) -> T {
let Some(shared) = find(client) else {
return default;
};
catch_unwind(AssertUnwindSafe(|| read(&mut lock(&shared)))).unwrap_or(default)
} }
/// Copies a string of the state into the caller's buffer. /// Copies a string of a client's state into the caller's buffer.
unsafe fn get_text<T: Text>(buffer: *mut T::Unit, size: isize, text: fn(&State) -> &str) -> isize { unsafe fn get_text<T: Text>(
get(0, |state| unsafe { client: i64,
buffer: *mut T::Unit,
size: isize,
text: fn(&State) -> &str,
) -> isize {
get(client, 0, |state| unsafe {
text::copy::<T>(text(state), buffer, size) text::copy::<T>(text(state), buffer, size)
}) })
} }
@@ -172,29 +194,71 @@ fn bool_result(ok: bool) -> isize {
isize::from(ok) isize::from(ok)
} }
// --- Clients -----------------------------------------------------------------
/// Makes a client: its handle (1 and up, never reused), 0 if it failed.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_CreateClient() -> i64 {
let made = catch_unwind(|| {
let (next, clients) = &mut *lock(&CLIENTS);
clients.insert(*next, Arc::new(Mutex::new(State::new())));
*next += 1;
*next - 1
});
made.unwrap_or(0)
}
/// Frees a client and closes its connection (once a call on it in another
/// thread ends): 1, or 0 if it wasn't one.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_FreeClient(client: i64) -> isize {
let freed = catch_unwind(|| lock(&CLIENTS).1.remove(&client).is_some());
bool_result(freed.unwrap_or(false))
}
// --- Errors ------------------------------------------------------------------ // --- Errors ------------------------------------------------------------------
/// Why the last call failed: a protocol error code (1-99 a server's /// Why the client's last call failed: a protocol error code (1-99 a
/// refusal, the connection still open; 100 and up the client's own), 0 if /// server's refusal, the connection still open; 100 and up the client's
/// it succeeded. Getters don't change it. /// own), 0 if it succeeded. Getters don't change it. `InvalidArgument` for
/// a bad handle.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_GetLastError() -> i32 { pub extern "C" fn BakaShrot_GetLastError(client: i64) -> i32 {
get(ErrorCode::Internal.code() as i32, |state| { get(client, ErrorCode::InvalidArgument.code() as i32, |state| {
state.last_error as i32 state.last_error as i32
}) })
} }
/// Why the last call failed, in words: the server's reason for a refusal, /// The client's reason, or why its handle is bad.
/// the client's otherwise. Empty if it succeeded. unsafe fn refusal_reason<T: Text>(client: i64, buffer: *mut T::Unit, size: isize) -> isize {
match find(client) {
Some(_) => unsafe { get_text::<T>(client, buffer, size, |state| &state.reason) },
None => {
let why = format!("no client {client}: never made, or freed");
unsafe { text::copy::<T>(&why, buffer, size) }
}
}
}
/// Why the client's last call failed, in words: the server's reason for a
/// refusal, the client's otherwise. Empty if it succeeded.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetRefusalReasonA(buffer: *mut c_char, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetRefusalReasonA(
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.reason) } client: i64,
buffer: *mut c_char,
size: isize,
) -> isize {
unsafe { refusal_reason::<Utf8>(client, buffer.cast(), size) }
} }
/// The same as `BakaShrot_GetRefusalReasonA`, in UTF-16. /// The same as `BakaShrot_GetRefusalReasonA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetRefusalReasonW(buffer: *mut u16, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetRefusalReasonW(
unsafe { get_text::<Utf16>(buffer, size, |state| &state.reason) } client: i64,
buffer: *mut u16,
size: isize,
) -> isize {
unsafe { refusal_reason::<Utf16>(client, buffer, size) }
} }
// --- Settings ---------------------------------------------------------------- // --- Settings ----------------------------------------------------------------
@@ -218,12 +282,13 @@ fn pem_or_file(value: Option<String>, what: &str, optional: bool) -> Result<Opti
/// Sets one of the certificates' settings, before connecting. /// Sets one of the certificates' settings, before connecting.
unsafe fn set<T: Text>( unsafe fn set<T: Text>(
client: i64,
value: *const T::Unit, value: *const T::Unit,
what: &str, what: &str,
optional: bool, optional: bool,
slot: fn(&mut State) -> &mut Option<String>, slot: fn(&mut State) -> &mut Option<String>,
) -> isize { ) -> isize {
call(0, |state| { call(client, 0, |state| {
if state.client.is_some() { if state.client.is_some() {
return Err(Error::new( return Err(Error::new(
ErrorCode::AlreadyConnected, ErrorCode::AlreadyConnected,
@@ -239,26 +304,43 @@ unsafe fn set<T: Text>(
/// Sets the CA's certificate, which the server's must be issued by: PEM /// 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. /// text, or the path of a file holding it. Before connecting.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetCaCertificateA(certificate: *const c_char) -> isize { pub unsafe extern "C" fn BakaShrot_SetCaCertificateA(
client: i64,
certificate: *const c_char,
) -> isize {
unsafe { unsafe {
set::<Utf8>(certificate.cast(), "CA certificate", false, |state| { set::<Utf8>(
&mut state.ca client,
}) certificate.cast(),
"CA certificate",
false,
|state| &mut state.ca,
)
} }
} }
/// The same as `BakaShrot_SetCaCertificateA`, in UTF-16. /// The same as `BakaShrot_SetCaCertificateA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetCaCertificateW(certificate: *const u16) -> isize { pub unsafe extern "C" fn BakaShrot_SetCaCertificateW(
unsafe { set::<Utf16>(certificate, "CA certificate", false, |state| &mut state.ca) } client: i64,
certificate: *const u16,
) -> isize {
unsafe {
set::<Utf16>(client, certificate, "CA certificate", false, |state| {
&mut state.ca
})
}
} }
/// 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. /// text, or the path of a file holding it. Before connecting.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetCertificateA(certificate: *const c_char) -> isize { pub unsafe extern "C" fn BakaShrot_SetCertificateA(
client: i64,
certificate: *const c_char,
) -> isize {
unsafe { unsafe {
set::<Utf8>(certificate.cast(), "certificate", false, |state| { set::<Utf8>(client, certificate.cast(), "certificate", false, |state| {
&mut state.certificate &mut state.certificate
}) })
} }
@@ -266,45 +348,49 @@ pub unsafe extern "C" fn BakaShrot_SetCertificateA(certificate: *const c_char) -
/// The same as `BakaShrot_SetCertificateA`, in UTF-16. /// The same as `BakaShrot_SetCertificateA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetCertificateW(certificate: *const u16) -> isize { pub unsafe extern "C" fn BakaShrot_SetCertificateW(client: i64, certificate: *const u16) -> isize {
unsafe { unsafe {
set::<Utf16>(certificate, "certificate", false, |state| { set::<Utf16>(client, certificate, "certificate", false, |state| {
&mut state.certificate &mut state.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. /// of a file holding it. Before connecting.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetPrivateKeyA(key: *const c_char) -> isize { pub unsafe extern "C" fn BakaShrot_SetPrivateKeyA(client: i64, key: *const c_char) -> isize {
unsafe { set::<Utf8>(key.cast(), "private key", false, |state| &mut state.key) } unsafe {
set::<Utf8>(client, key.cast(), "private key", false, |state| {
&mut state.key
})
}
} }
/// The same as `BakaShrot_SetPrivateKeyA`, in UTF-16. /// The same as `BakaShrot_SetPrivateKeyA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetPrivateKeyW(key: *const u16) -> isize { pub unsafe extern "C" fn BakaShrot_SetPrivateKeyW(client: i64, key: *const u16) -> isize {
unsafe { set::<Utf16>(key, "private key", false, |state| &mut state.key) } unsafe { set::<Utf16>(client, key, "private key", false, |state| &mut state.key) }
} }
/// Sets the CA's CRL, optional: servers it revokes are refused. PEM text, /// 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 /// or the path of a file holding it (one that isn't there is a
/// `FileError`); null or empty for none. Before connecting. /// `FileError`); null or empty for none. Before connecting.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetCrlA(crl: *const c_char) -> isize { pub unsafe extern "C" fn BakaShrot_SetCrlA(client: i64, crl: *const c_char) -> isize {
unsafe { set::<Utf8>(crl.cast(), "CRL", true, |state| &mut state.crl) } unsafe { set::<Utf8>(client, crl.cast(), "CRL", true, |state| &mut state.crl) }
} }
/// The same as `BakaShrot_SetCrlA`, in UTF-16. /// The same as `BakaShrot_SetCrlA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetCrlW(crl: *const u16) -> isize { pub unsafe extern "C" fn BakaShrot_SetCrlW(client: i64, crl: *const u16) -> isize {
unsafe { set::<Utf16>(crl, "CRL", true, |state| &mut state.crl) } unsafe { set::<Utf16>(client, crl, "CRL", true, |state| &mut state.crl) }
} }
// --- The connection ---------------------------------------------------------- // --- The connection ----------------------------------------------------------
unsafe fn connect<T: Text>(host: *const T::Unit, port: i32) -> isize { unsafe fn connect<T: Text>(client: i64, host: *const T::Unit, port: i32) -> isize {
call(0, |state| { call(client, 0, |state| {
if state.client.is_some() { if state.client.is_some() {
return Err(Error::new( return Err(Error::new(
ErrorCode::AlreadyConnected, ErrorCode::AlreadyConnected,
@@ -349,44 +435,47 @@ unsafe fn connect<T: Text>(host: *const T::Unit, port: i32) -> isize {
/// the server refused the certificate, `ServerNotVerified` this client /// the server refused the certificate, `ServerNotVerified` this client
/// refused the server's, `NotAllowed` none of its roles is the server's). /// refused the server's, `NotAllowed` none of its roles is the server's).
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_ConnectA(host: *const c_char, port: i32) -> isize { pub unsafe extern "C" fn BakaShrot_ConnectA(client: i64, host: *const c_char, port: i32) -> isize {
unsafe { connect::<Utf8>(host.cast(), port) } unsafe { connect::<Utf8>(client, host.cast(), port) }
} }
/// The same as `BakaShrot_ConnectA`, in UTF-16. /// The same as `BakaShrot_ConnectA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_ConnectW(host: *const u16, port: i32) -> isize { pub unsafe extern "C" fn BakaShrot_ConnectW(client: i64, host: *const u16, port: i32) -> isize {
unsafe { connect::<Utf16>(host, port) } unsafe { connect::<Utf16>(client, host, port) }
} }
/// 1 while connected: notices when the server closed the connection /// 1 while connected: notices when the server closed the connection
/// (forgotten then: connect again). /// (forgotten then: connect again).
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_IsConnected() -> isize { pub extern "C" fn BakaShrot_IsConnected(client: i64) -> isize {
let open = catch_unwind(AssertUnwindSafe(|| { get(client, 0, |state| {
let mut state = state();
let open = state.client.as_ref().is_some_and(Client::is_open); let open = state.client.as_ref().is_some_and(Client::is_open);
if !open { if !open {
state.client = None; state.client = None;
} }
open bool_result(open)
})); })
bool_result(open.unwrap_or(false))
} }
/// Closes the connection: 0 if there was none. The settings stay. /// Closes the connection: 0 if there was none. The settings stay.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_Disconnect() -> isize { pub extern "C" fn BakaShrot_Disconnect(client: i64) -> isize {
let closed = catch_unwind(AssertUnwindSafe(|| state().client.take().is_some())); get(client, 0, |state| {
bool_result(closed.unwrap_or(false)) bool_result(state.client.take().is_some())
})
} }
/// The node this client is, as the server said when connecting: its /// The node this client is, as the server said when connecting: its
/// certificate's name. Empty when not connected. /// certificate's name. Empty when not connected.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetNodeA(buffer: *mut c_char, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetNodeA(
client: i64,
buffer: *mut c_char,
size: isize,
) -> isize {
unsafe { unsafe {
get_text::<Utf8>(buffer.cast(), size, |state| { get_text::<Utf8>(client, buffer.cast(), size, |state| {
state.client.as_ref().map_or("", Client::node) state.client.as_ref().map_or("", Client::node)
}) })
} }
@@ -394,9 +483,9 @@ pub unsafe extern "C" fn BakaShrot_GetNodeA(buffer: *mut c_char, size: isize) ->
/// The same as `BakaShrot_GetNodeA`, in UTF-16. /// The same as `BakaShrot_GetNodeA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetNodeW(buffer: *mut u16, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetNodeW(client: i64, buffer: *mut u16, size: isize) -> isize {
unsafe { unsafe {
get_text::<Utf16>(buffer, size, |state| { get_text::<Utf16>(client, buffer, size, |state| {
state.client.as_ref().map_or("", Client::node) state.client.as_ref().map_or("", Client::node)
}) })
} }
@@ -415,8 +504,8 @@ unsafe fn topic_and_data<T: Text>(
Ok((topic, data)) Ok((topic, data))
} }
unsafe fn push_to<T: Text>(topic: *const T::Unit, data: *const T::Unit) -> i64 { unsafe fn push_to<T: Text>(client: i64, topic: *const T::Unit, data: *const T::Unit) -> i64 {
call(-1, |state| { call(client, -1, |state| {
let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? }; let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? };
let id = state.client()?.push(&topic, &data)?; let id = state.client()?.push(&topic, &data)?;
Ok(id as i64) Ok(id as i64)
@@ -428,16 +517,21 @@ unsafe fn push_to<T: Text>(topic: *const T::Unit, data: *const T::Unit) -> i64 {
/// (`ConnectionLost`) may have been stored all the same. /// (`ConnectionLost`) may have been stored all the same.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_PushMessageToA( pub unsafe extern "C" fn BakaShrot_PushMessageToA(
client: i64,
topic: *const c_char, topic: *const c_char,
data: *const c_char, data: *const c_char,
) -> i64 { ) -> i64 {
unsafe { push_to::<Utf8>(topic.cast(), data.cast()) } unsafe { push_to::<Utf8>(client, topic.cast(), data.cast()) }
} }
/// The same as `BakaShrot_PushMessageToA`, in UTF-16. /// The same as `BakaShrot_PushMessageToA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_PushMessageToW(topic: *const u16, data: *const u16) -> i64 { pub unsafe extern "C" fn BakaShrot_PushMessageToW(
unsafe { push_to::<Utf16>(topic, data) } client: i64,
topic: *const u16,
data: *const u16,
) -> i64 {
unsafe { push_to::<Utf16>(client, topic, data) }
} }
// --- Reading ----------------------------------------------------------------- // --- Reading -----------------------------------------------------------------
@@ -452,8 +546,8 @@ unsafe fn topic_and_node<T: Text>(
Ok((topic, node)) Ok((topic, node))
} }
unsafe fn latest_of<T: Text>(topic: *const T::Unit, node: *const T::Unit) -> isize { unsafe fn latest_of<T: Text>(client: i64, topic: *const T::Unit, node: *const T::Unit) -> isize {
call(0, |state| { call(client, 0, |state| {
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? }; let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
state.clear_messages(&topic, &node); state.clear_messages(&topic, &node);
let answer = state.client()?.get_messages(&topic, &node, None, 1)?; let answer = state.client()?.get_messages(&topic, &node, None, 1)?;
@@ -472,28 +566,31 @@ unsafe fn latest_of<T: Text>(topic: *const T::Unit, node: *const T::Unit) -> isi
/// `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet. /// `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfA( pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfA(
client: i64,
topic: *const c_char, topic: *const c_char,
node: *const c_char, node: *const c_char,
) -> isize { ) -> isize {
unsafe { latest_of::<Utf8>(topic.cast(), node.cast()) } unsafe { latest_of::<Utf8>(client, topic.cast(), node.cast()) }
} }
/// The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16. /// The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfW( pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfW(
client: i64,
topic: *const u16, topic: *const u16,
node: *const u16, node: *const u16,
) -> isize { ) -> isize {
unsafe { latest_of::<Utf16>(topic, node) } unsafe { latest_of::<Utf16>(client, topic, node) }
} }
unsafe fn messages<T: Text>( unsafe fn messages<T: Text>(
client: i64,
topic: *const T::Unit, topic: *const T::Unit,
node: *const T::Unit, node: *const T::Unit,
after: i64, after: i64,
limit: i32, limit: i32,
) -> i32 { ) -> i32 {
call(-1, |state| { call(client, -1, |state| {
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? }; let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
state.clear_messages(&topic, &node); state.clear_messages(&topic, &node);
let after = let after =
@@ -515,36 +612,38 @@ unsafe fn messages<T: Text>(
/// `BakaShrot_HasMoreMessages()` says whether more follow the last one. /// `BakaShrot_HasMoreMessages()` says whether more follow the last one.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessagesA( pub unsafe extern "C" fn BakaShrot_GetMessagesA(
client: i64,
topic: *const c_char, topic: *const c_char,
node: *const c_char, node: *const c_char,
after: i64, after: i64,
limit: i32, limit: i32,
) -> i32 { ) -> i32 {
unsafe { messages::<Utf8>(topic.cast(), node.cast(), after, limit) } unsafe { messages::<Utf8>(client, topic.cast(), node.cast(), after, limit) }
} }
/// The same as `BakaShrot_GetMessagesA`, in UTF-16. /// The same as `BakaShrot_GetMessagesA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessagesW( pub unsafe extern "C" fn BakaShrot_GetMessagesW(
client: i64,
topic: *const u16, topic: *const u16,
node: *const u16, node: *const u16,
after: i64, after: i64,
limit: i32, limit: i32,
) -> i32 { ) -> i32 {
unsafe { messages::<Utf16>(topic, node, after, limit) } unsafe { messages::<Utf16>(client, topic, node, after, limit) }
} }
/// How many messages the last `GetMessages` or `GetLatestMessageOf` got. /// How many messages the last `GetMessages` or `GetLatestMessageOf` got.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_GetMessageCount() -> i32 { pub extern "C" fn BakaShrot_GetMessageCount(client: i64) -> i32 {
get(0, |state| state.messages.len() as i32) get(client, 0, |state| state.messages.len() as i32)
} }
/// Selects the message at `index` (0 to the count - 1) for the getters: 0 /// Selects the message at `index` (0 to the count - 1) for the getters: 0
/// if there's none there (`InvalidArgument`), the selection unchanged. /// if there's none there (`InvalidArgument`), the selection unchanged.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_SelectMessage(index: i32) -> isize { pub extern "C" fn BakaShrot_SelectMessage(client: i64, index: i32) -> isize {
call(0, |state| { call(client, 0, |state| {
let index = usize::try_from(index) let index = usize::try_from(index)
.ok() .ok()
.filter(|index| *index < state.messages.len()) .filter(|index| *index < state.messages.len())
@@ -557,14 +656,14 @@ pub extern "C" fn BakaShrot_SelectMessage(index: i32) -> isize {
/// 1 if more messages follow the last one the last `GetMessages` got: ask /// 1 if more messages follow the last one the last `GetMessages` got: ask
/// again after its id. /// again after its id.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_HasMoreMessages() -> isize { pub extern "C" fn BakaShrot_HasMoreMessages(client: i64) -> isize {
get(0, |state| bool_result(state.more)) get(client, 0, |state| bool_result(state.more))
} }
/// The selected message's id, 0 if none. /// The selected message's id, 0 if none.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_GetMessageId() -> i64 { pub extern "C" fn BakaShrot_GetMessageId(client: i64) -> i64 {
get(0, |state| { get(client, 0, |state| {
state.message().map_or(0, |message| message.id as i64) state.message().map_or(0, |message| message.id as i64)
}) })
} }
@@ -572,8 +671,8 @@ pub extern "C" fn BakaShrot_GetMessageId() -> i64 {
/// When the selected message was pushed, by the server it was pushed to: /// When the selected message was pushed, by the server it was pushed to:
/// milliseconds since 1970-01-01 UTC, 0 if none. /// milliseconds since 1970-01-01 UTC, 0 if none.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_GetMessagePushedAt() -> i64 { pub extern "C" fn BakaShrot_GetMessagePushedAt(client: i64) -> i64 {
get(0, |state| { get(client, 0, |state| {
state state
.message() .message()
.map_or(0, |message| message.pushed_at as i64) .map_or(0, |message| message.pushed_at as i64)
@@ -582,8 +681,8 @@ pub extern "C" fn BakaShrot_GetMessagePushedAt() -> i64 {
/// The selected message's attachment's size, 0 without one. /// The selected message's attachment's size, 0 without one.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_GetMessageAttachmentSize() -> i64 { pub extern "C" fn BakaShrot_GetMessageAttachmentSize(client: i64) -> i64 {
get(0, |state| { get(client, 0, |state| {
state state
.message() .message()
.and_then(|message| message.attachment.as_ref()) .and_then(|message| message.attachment.as_ref())
@@ -594,8 +693,8 @@ pub extern "C" fn BakaShrot_GetMessageAttachmentSize() -> i64 {
/// 1 if the selected message's attachment is all on this server (a /// 1 if the selected message's attachment is all on this server (a
/// replicated one may still be on its way). /// replicated one may still be on its way).
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_IsMessageAttachmentReady() -> isize { pub extern "C" fn BakaShrot_IsMessageAttachmentReady(client: i64) -> isize {
get(0, |state| { get(client, 0, |state| {
let attachment = state let attachment = state
.message() .message()
.and_then(|message| message.attachment.as_ref()); .and_then(|message| message.attachment.as_ref());
@@ -605,9 +704,13 @@ pub extern "C" fn BakaShrot_IsMessageAttachmentReady() -> isize {
/// The selected message's data, as pushed (JSON or not). /// The selected message's data, as pushed (JSON or not).
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessageDataA(buffer: *mut c_char, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetMessageDataA(
client: i64,
buffer: *mut c_char,
size: isize,
) -> isize {
unsafe { unsafe {
get_text::<Utf8>(buffer.cast(), size, |state| { get_text::<Utf8>(client, buffer.cast(), size, |state| {
state.message().map_or("", |message| &message.data) state.message().map_or("", |message| &message.data)
}) })
} }
@@ -615,9 +718,13 @@ pub unsafe extern "C" fn BakaShrot_GetMessageDataA(buffer: *mut c_char, size: is
/// The same as `BakaShrot_GetMessageDataA`, in UTF-16. /// The same as `BakaShrot_GetMessageDataA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessageDataW(buffer: *mut u16, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetMessageDataW(
client: i64,
buffer: *mut u16,
size: isize,
) -> isize {
unsafe { unsafe {
get_text::<Utf16>(buffer, size, |state| { get_text::<Utf16>(client, buffer, size, |state| {
state.message().map_or("", |message| &message.data) state.message().map_or("", |message| &message.data)
}) })
} }
@@ -625,32 +732,48 @@ pub unsafe extern "C" fn BakaShrot_GetMessageDataW(buffer: *mut u16, size: isize
/// The topic the last `GetMessages` or `GetLatestMessageOf` asked for. /// The topic the last `GetMessages` or `GetLatestMessageOf` asked for.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessageTopicA(buffer: *mut c_char, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetMessageTopicA(
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.topic) } client: i64,
buffer: *mut c_char,
size: isize,
) -> isize {
unsafe { get_text::<Utf8>(client, buffer.cast(), size, |state| &state.topic) }
} }
/// The same as `BakaShrot_GetMessageTopicA`, in UTF-16. /// The same as `BakaShrot_GetMessageTopicA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessageTopicW(buffer: *mut u16, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetMessageTopicW(
unsafe { get_text::<Utf16>(buffer, size, |state| &state.topic) } client: i64,
buffer: *mut u16,
size: isize,
) -> isize {
unsafe { get_text::<Utf16>(client, buffer, size, |state| &state.topic) }
} }
/// The node the last `GetMessages` or `GetLatestMessageOf` asked for. /// The node the last `GetMessages` or `GetLatestMessageOf` asked for.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessageNodeA(buffer: *mut c_char, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetMessageNodeA(
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.node) } client: i64,
buffer: *mut c_char,
size: isize,
) -> isize {
unsafe { get_text::<Utf8>(client, buffer.cast(), size, |state| &state.node) }
} }
/// The same as `BakaShrot_GetMessageNodeA`, in UTF-16. /// The same as `BakaShrot_GetMessageNodeA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessageNodeW(buffer: *mut u16, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetMessageNodeW(
unsafe { get_text::<Utf16>(buffer, size, |state| &state.node) } client: i64,
buffer: *mut u16,
size: isize,
) -> isize {
unsafe { get_text::<Utf16>(client, buffer, size, |state| &state.node) }
} }
// --- Names ------------------------------------------------------------------- // --- Names -------------------------------------------------------------------
fn list(kind: NameKind) -> i32 { fn list(client: i64, kind: NameKind) -> i32 {
call(-1, |state| { call(client, -1, |state| {
state.names.clear(); state.names.clear();
let list = state.client()?.list_names(kind)?; let list = state.client()?.list_names(kind)?;
let kind = match kind { let kind = match kind {
@@ -672,36 +795,44 @@ fn list(kind: NameKind) -> i32 {
/// (every one if its roles have `list_topics` or `query`): how many, -1 on /// (every one if its roles have `list_topics` or `query`): how many, -1 on
/// failure. Then `BakaShrot_GetNamesList()`. /// failure. Then `BakaShrot_GetNamesList()`.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_ListTopics() -> i32 { pub extern "C" fn BakaShrot_ListTopics(client: i64) -> i32 {
list(NameKind::Topic) list(client, NameKind::Topic)
} }
/// Lists the nodes with messages in the topics this client may read (every /// 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 /// one if its roles have `list_nodes` or `query`): how many, -1 on failure. Then
/// `BakaShrot_GetNamesList()`. /// `BakaShrot_GetNamesList()`.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_ListNodes() -> i32 { pub extern "C" fn BakaShrot_ListNodes(client: i64) -> i32 {
list(NameKind::Node) list(client, NameKind::Node)
} }
/// The last list, as JSON: /// The last list, as JSON:
/// `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated` /// `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated`
/// if some didn't fit. /// if some didn't fit.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetNamesListA(buffer: *mut c_char, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetNamesListA(
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.names) } client: i64,
buffer: *mut c_char,
size: isize,
) -> isize {
unsafe { get_text::<Utf8>(client, buffer.cast(), size, |state| &state.names) }
} }
/// The same as `BakaShrot_GetNamesListA`, in UTF-16. /// The same as `BakaShrot_GetNamesListA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetNamesListW(buffer: *mut u16, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetNamesListW(
unsafe { get_text::<Utf16>(buffer, size, |state| &state.names) } client: i64,
buffer: *mut u16,
size: isize,
) -> isize {
unsafe { get_text::<Utf16>(client, buffer, size, |state| &state.names) }
} }
// --- Queries ----------------------------------------------------------------- // --- Queries -----------------------------------------------------------------
unsafe fn query<T: Text>(sql: *const T::Unit) -> isize { unsafe fn query<T: Text>(client: i64, sql: *const T::Unit) -> isize {
call(0, |state| { call(client, 0, |state| {
state.query.clear(); state.query.clear();
let sql = required(unsafe { text::read::<T>(sql, "query")? }, "query")?; let sql = required(unsafe { text::read::<T>(sql, "query")? }, "query")?;
state.query = state.client()?.query(&sql)?; state.query = state.client()?.query(&sql)?;
@@ -712,27 +843,35 @@ unsafe fn query<T: Text>(sql: *const T::Unit) -> isize {
/// Runs read-only SQL on the server (one SELECT or WITH), if this client /// Runs read-only SQL on the server (one SELECT or WITH), if this client
/// may query. Then `BakaShrot_GetQueryResult()`. /// may query. Then `BakaShrot_GetQueryResult()`.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_QueryA(sql: *const c_char) -> isize { pub unsafe extern "C" fn BakaShrot_QueryA(client: i64, sql: *const c_char) -> isize {
unsafe { query::<Utf8>(sql.cast()) } unsafe { query::<Utf8>(client, sql.cast()) }
} }
/// The same as `BakaShrot_QueryA`, in UTF-16. /// The same as `BakaShrot_QueryA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_QueryW(sql: *const u16) -> isize { pub unsafe extern "C" fn BakaShrot_QueryW(client: i64, sql: *const u16) -> isize {
unsafe { query::<Utf16>(sql) } unsafe { query::<Utf16>(client, sql) }
} }
/// The last query's result, as JSON: /// The last query's result, as JSON:
/// `{"columns":[...],"rows":[[...],...]}`, every value a string or null. /// `{"columns":[...],"rows":[[...],...]}`, every value a string or null.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetQueryResultA(buffer: *mut c_char, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetQueryResultA(
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.query) } client: i64,
buffer: *mut c_char,
size: isize,
) -> isize {
unsafe { get_text::<Utf8>(client, buffer.cast(), size, |state| &state.query) }
} }
/// The same as `BakaShrot_GetQueryResultA`, in UTF-16. /// The same as `BakaShrot_GetQueryResultA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetQueryResultW(buffer: *mut u16, size: isize) -> isize { pub unsafe extern "C" fn BakaShrot_GetQueryResultW(
unsafe { get_text::<Utf16>(buffer, size, |state| &state.query) } client: i64,
buffer: *mut u16,
size: isize,
) -> isize {
unsafe { get_text::<Utf16>(client, buffer, size, |state| &state.query) }
} }
// --- Attachments ------------------------------------------------------------- // --- Attachments -------------------------------------------------------------
@@ -743,11 +882,12 @@ fn message_id(id: i64) -> Result<u64> {
} }
unsafe fn push_with_file<T: Text>( unsafe fn push_with_file<T: Text>(
client: i64,
topic: *const T::Unit, topic: *const T::Unit,
data: *const T::Unit, data: *const T::Unit,
path: *const T::Unit, path: *const T::Unit,
) -> i64 { ) -> i64 {
call(-1, |state| { call(client, -1, |state| {
let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? }; let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? };
let path = required(unsafe { text::read::<T>(path, "the file")? }, "file")?; let path = required(unsafe { text::read::<T>(path, "the file")? }, "file")?;
let mut file = File::open(&path) let mut file = File::open(&path)
@@ -766,30 +906,33 @@ unsafe fn push_with_file<T: Text>(
/// (`DataMismatch`). /// (`DataMismatch`).
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_PushMessageWithFileA( pub unsafe extern "C" fn BakaShrot_PushMessageWithFileA(
client: i64,
topic: *const c_char, topic: *const c_char,
data: *const c_char, data: *const c_char,
file_path: *const c_char, file_path: *const c_char,
) -> i64 { ) -> i64 {
unsafe { push_with_file::<Utf8>(topic.cast(), data.cast(), file_path.cast()) } unsafe { push_with_file::<Utf8>(client, topic.cast(), data.cast(), file_path.cast()) }
} }
/// The same as `BakaShrot_PushMessageWithFileA`, in UTF-16. /// The same as `BakaShrot_PushMessageWithFileA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_PushMessageWithFileW( pub unsafe extern "C" fn BakaShrot_PushMessageWithFileW(
client: i64,
topic: *const u16, topic: *const u16,
data: *const u16, data: *const u16,
file_path: *const u16, file_path: *const u16,
) -> i64 { ) -> i64 {
unsafe { push_with_file::<Utf16>(topic, data, file_path) } unsafe { push_with_file::<Utf16>(client, topic, data, file_path) }
} }
unsafe fn push_with_data<T: Text>( unsafe fn push_with_data<T: Text>(
client: i64,
topic: *const T::Unit, topic: *const T::Unit,
data: *const T::Unit, data: *const T::Unit,
attachment: *const c_void, attachment: *const c_void,
size: i64, size: i64,
) -> i64 { ) -> i64 {
call(-1, |state| { call(client, -1, |state| {
let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? }; let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? };
if attachment.is_null() { if attachment.is_null() {
return Err(invalid("no attachment (a null pointer)")); return Err(invalid("no attachment (a null pointer)"));
@@ -810,32 +953,35 @@ unsafe fn push_with_data<T: Text>(
/// `BakaShrot_PushMessageWithFileA` does. /// `BakaShrot_PushMessageWithFileA` does.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_PushMessageWithDataA( pub unsafe extern "C" fn BakaShrot_PushMessageWithDataA(
client: i64,
topic: *const c_char, topic: *const c_char,
data: *const c_char, data: *const c_char,
attachment: *const c_void, attachment: *const c_void,
size: i64, size: i64,
) -> i64 { ) -> i64 {
unsafe { push_with_data::<Utf8>(topic.cast(), data.cast(), attachment, size) } unsafe { push_with_data::<Utf8>(client, topic.cast(), data.cast(), attachment, size) }
} }
/// The same as `BakaShrot_PushMessageWithDataA`, in UTF-16. /// The same as `BakaShrot_PushMessageWithDataA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_PushMessageWithDataW( pub unsafe extern "C" fn BakaShrot_PushMessageWithDataW(
client: i64,
topic: *const u16, topic: *const u16,
data: *const u16, data: *const u16,
attachment: *const c_void, attachment: *const c_void,
size: i64, size: i64,
) -> i64 { ) -> i64 {
unsafe { push_with_data::<Utf16>(topic, data, attachment, size) } unsafe { push_with_data::<Utf16>(client, topic, data, attachment, size) }
} }
unsafe fn save<T: Text>( unsafe fn save<T: Text>(
client: i64,
topic: *const T::Unit, topic: *const T::Unit,
node: *const T::Unit, node: *const T::Unit,
id: i64, id: i64,
path: *const T::Unit, path: *const T::Unit,
) -> i64 { ) -> i64 {
call(-1, |state| { call(client, -1, |state| {
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? }; let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
let path = required(unsafe { text::read::<T>(path, "the file")? }, "file")?; let path = required(unsafe { text::read::<T>(path, "the file")? }, "file")?;
let size = let size =
@@ -853,27 +999,37 @@ unsafe fn save<T: Text>(
/// failed one leaves no file. /// failed one leaves no file.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SaveAttachmentA( pub unsafe extern "C" fn BakaShrot_SaveAttachmentA(
client: i64,
topic: *const c_char, topic: *const c_char,
node: *const c_char, node: *const c_char,
message_id: i64, message_id: i64,
file_path: *const c_char, file_path: *const c_char,
) -> i64 { ) -> i64 {
unsafe { save::<Utf8>(topic.cast(), node.cast(), message_id, file_path.cast()) } unsafe {
save::<Utf8>(
client,
topic.cast(),
node.cast(),
message_id,
file_path.cast(),
)
}
} }
/// The same as `BakaShrot_SaveAttachmentA`, in UTF-16. /// The same as `BakaShrot_SaveAttachmentA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SaveAttachmentW( pub unsafe extern "C" fn BakaShrot_SaveAttachmentW(
client: i64,
topic: *const u16, topic: *const u16,
node: *const u16, node: *const u16,
message_id: i64, message_id: i64,
file_path: *const u16, file_path: *const u16,
) -> i64 { ) -> i64 {
unsafe { save::<Utf16>(topic, node, message_id, file_path) } unsafe { save::<Utf16>(client, topic, node, message_id, file_path) }
} }
unsafe fn load<T: Text>(topic: *const T::Unit, node: *const T::Unit, id: i64) -> i64 { unsafe fn load<T: Text>(client: i64, topic: *const T::Unit, node: *const T::Unit, id: i64) -> i64 {
call(-1, |state| { call(client, -1, |state| {
state.attachment = Vec::new(); state.attachment = Vec::new();
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? }; let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
let mut attachment = Vec::new(); let mut attachment = Vec::new();
@@ -891,29 +1047,35 @@ unsafe fn load<T: Text>(topic: *const T::Unit, node: *const T::Unit, id: i64) ->
/// ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`. /// ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_LoadAttachmentA( pub unsafe extern "C" fn BakaShrot_LoadAttachmentA(
client: i64,
topic: *const c_char, topic: *const c_char,
node: *const c_char, node: *const c_char,
message_id: i64, message_id: i64,
) -> i64 { ) -> i64 {
unsafe { load::<Utf8>(topic.cast(), node.cast(), message_id) } unsafe { load::<Utf8>(client, topic.cast(), node.cast(), message_id) }
} }
/// The same as `BakaShrot_LoadAttachmentA`, in UTF-16. /// The same as `BakaShrot_LoadAttachmentA`, in UTF-16.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_LoadAttachmentW( pub unsafe extern "C" fn BakaShrot_LoadAttachmentW(
client: i64,
topic: *const u16, topic: *const u16,
node: *const u16, node: *const u16,
message_id: i64, message_id: i64,
) -> i64 { ) -> i64 {
unsafe { load::<Utf16>(topic, node, message_id) } unsafe { load::<Utf16>(client, topic, node, message_id) }
} }
/// Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if /// Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if
/// `BufferSize` is enough: returns its size (0 if none), copies nothing if /// `BufferSize` is enough: returns its size (0 if none), copies nothing if
/// it doesn't fit (a null `Buffer` asks for the size). /// it doesn't fit (a null `Buffer` asks for the size).
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetAttachmentData(buffer: *mut c_void, buffer_size: i64) -> i64 { pub unsafe extern "C" fn BakaShrot_GetAttachmentData(
get(0, |state| { client: i64,
buffer: *mut c_void,
buffer_size: i64,
) -> i64 {
get(client, 0, |state| {
let data = &state.attachment; let data = &state.attachment;
if !buffer.is_null() && usize::try_from(buffer_size).is_ok_and(|size| size >= data.len()) { if !buffer.is_null() && usize::try_from(buffer_size).is_ok_and(|size| size >= data.len()) {
unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), buffer.cast(), data.len()) }; unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), buffer.cast(), data.len()) };
@@ -924,7 +1086,9 @@ pub unsafe extern "C" fn BakaShrot_GetAttachmentData(buffer: *mut c_void, buffer
/// Frees what `BakaShrot_LoadAttachment()` read: 1. /// Frees what `BakaShrot_LoadAttachment()` read: 1.
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_FreeAttachmentData() -> isize { pub extern "C" fn BakaShrot_FreeAttachmentData(client: i64) -> isize {
let freed = catch_unwind(AssertUnwindSafe(|| state().attachment = Vec::new())); get(client, 0, |state| {
bool_result(freed.is_ok()) state.attachment = Vec::new();
1
})
} }
+348 -127
View File
@@ -1,6 +1,7 @@
//! The exports called as C would, against a server: the `W` ones (what //! The exports called as C would, against a server. `exports`: one client,
//! PureBasic uses; Python's check covers the `A` ones), the buffers, the //! the `W` exports (what PureBasic uses; Python's check covers the `A`
//! errors. One test: the DLL holds one connection per process. //! ones), the buffers, the errors. `clients`: several clients at once, bad
//! handles, threads.
#![allow(unsafe_code)] #![allow(unsafe_code)]
@@ -9,6 +10,8 @@ mod common;
use bakashrot::*; use bakashrot::*;
use bakashrot_proto::ErrorCode; use bakashrot_proto::ErrorCode;
use std::ffi::{CString, c_char}; use std::ffi::{CString, c_char};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
fn w(text: &str) -> Vec<u16> { fn w(text: &str) -> Vec<u16> {
text.encode_utf16().chain([0]).collect() text.encode_utf16().chain([0]).collect()
@@ -19,25 +22,28 @@ fn a(text: &str) -> CString {
} }
/// A `W` getter's string: asks for the size, then copies. /// A `W` getter's string: asks for the size, then copies.
fn get_w(getter: unsafe extern "C" fn(*mut u16, isize) -> isize) -> String { fn get_w(client: i64, getter: unsafe extern "C" fn(i64, *mut u16, isize) -> isize) -> String {
let size = unsafe { getter(std::ptr::null_mut(), 0) }; let size = unsafe { getter(client, std::ptr::null_mut(), 0) };
if size == 0 {
return String::new();
}
let mut buffer = vec![0u16; size as usize / 2]; let mut buffer = vec![0u16; size as usize / 2];
unsafe { getter(buffer.as_mut_ptr(), size) }; unsafe { getter(client, buffer.as_mut_ptr(), size) };
String::from_utf16(&buffer[..buffer.len() - 1]).unwrap() String::from_utf16(&buffer[..buffer.len() - 1]).unwrap()
} }
fn get_a(getter: unsafe extern "C" fn(*mut c_char, isize) -> isize) -> String { fn get_a(client: i64, getter: unsafe extern "C" fn(i64, *mut c_char, isize) -> isize) -> String {
let size = unsafe { getter(std::ptr::null_mut(), 0) }; let size = unsafe { getter(client, std::ptr::null_mut(), 0) };
let mut buffer = vec![0u8; size as usize]; let mut buffer = vec![0u8; size as usize];
unsafe { getter(buffer.as_mut_ptr().cast(), size) }; unsafe { getter(client, buffer.as_mut_ptr().cast(), size) };
String::from_utf8(buffer[..buffer.len() - 1].to_vec()).unwrap() String::from_utf8(buffer[..buffer.len() - 1].to_vec()).unwrap()
} }
/// The last error's code and reason. /// The client's last error: its code and reason.
fn error() -> (u32, String) { fn error(client: i64) -> (u32, String) {
( (
BakaShrot_GetLastError() as u32, BakaShrot_GetLastError(client) as u32,
get_w(BakaShrot_GetRefusalReasonW), get_w(client, BakaShrot_GetRefusalReasonW),
) )
} }
@@ -54,172 +60,205 @@ fn exports() {
let pem = |name: &str| std::fs::read_to_string(running.folder.join(name)).unwrap(); let pem = |name: &str| std::fs::read_to_string(running.folder.join(name)).unwrap();
let localhost = w("127.0.0.1"); let localhost = w("127.0.0.1");
let port = i32::from(running.port); let port = i32::from(running.port);
let client = BakaShrot_CreateClient();
assert!(client >= 1);
unsafe { unsafe {
// Nothing set, not connected. // Nothing set, not connected.
assert_eq!( assert_eq!(
BakaShrot_PushMessageToW(w("logs").as_ptr(), w("{}").as_ptr()), BakaShrot_PushMessageToW(client, w("logs").as_ptr(), w("{}").as_ptr()),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::NotConnected)); assert_eq!(error(client).0, code(ErrorCode::NotConnected));
assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0); assert_eq!(BakaShrot_ConnectW(client, localhost.as_ptr(), port), 0);
let (failed, why) = error(); let (failed, why) = error(client);
assert_eq!(failed, code(ErrorCode::InvalidArgument)); assert_eq!(failed, code(ErrorCode::InvalidArgument));
assert!(why.contains("BakaShrot_SetCaCertificate"), "{why}"); assert!(why.contains("BakaShrot_SetCaCertificate"), "{why}");
// Files or PEM text; a missing file, an empty setting. // Files or PEM text; a missing file, an empty setting.
assert_eq!( assert_eq!(
BakaShrot_SetCaCertificateW(w(&file("missing.crt")).as_ptr()), BakaShrot_SetCaCertificateW(client, w(&file("missing.crt")).as_ptr()),
0 0
); );
assert_eq!(error().0, code(ErrorCode::FileError)); assert_eq!(error(client).0, code(ErrorCode::FileError));
assert_eq!(BakaShrot_SetCertificateW(std::ptr::null()), 0); assert_eq!(BakaShrot_SetCertificateW(client, std::ptr::null()), 0);
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 1);
assert_eq!(BakaShrot_GetLastError(), 0);
assert_eq!( assert_eq!(
BakaShrot_SetCertificateW(w(&pem("kitchen.crt")).as_ptr()), BakaShrot_SetCaCertificateW(client, w(&file("ca.crt")).as_ptr()),
1
);
assert_eq!(BakaShrot_GetLastError(client), 0);
assert_eq!(
BakaShrot_SetCertificateW(client, w(&pem("kitchen.crt")).as_ptr()),
1 1
); );
assert_eq!( assert_eq!(
BakaShrot_SetPrivateKeyA(a(&file("kitchen.key")).as_ptr()), BakaShrot_SetPrivateKeyA(client, a(&file("kitchen.key")).as_ptr()),
1 1
); );
// A CRL file asked for is needed (client.toml's may be missing). // A CRL file asked for is needed (client.toml's may be missing).
assert_eq!(BakaShrot_SetCrlW(w(&file("missing.crl")).as_ptr()), 0); assert_eq!(
assert_eq!(error().0, code(ErrorCode::FileError)); BakaShrot_SetCrlW(client, w(&file("missing.crl")).as_ptr()),
assert_eq!(BakaShrot_SetCrlW(std::ptr::null()), 1); 0
assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), 0), 0); );
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::FileError));
assert_eq!(BakaShrot_SetCrlW(client, std::ptr::null()), 1);
assert_eq!(BakaShrot_ConnectW(client, localhost.as_ptr(), 0), 0);
assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
assert_eq!( assert_eq!(
BakaShrot_ConnectW(localhost.as_ptr(), port), BakaShrot_ConnectW(client, localhost.as_ptr(), port),
1, 1,
"{:?}", "{:?}",
error() error(client)
); );
assert_eq!(BakaShrot_IsConnected(), 1); assert_eq!(BakaShrot_IsConnected(client), 1);
assert_eq!(get_w(BakaShrot_GetNodeW), "kitchen"); assert_eq!(get_w(client, BakaShrot_GetNodeW), "kitchen");
assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0); assert_eq!(BakaShrot_ConnectW(client, localhost.as_ptr(), port), 0);
assert_eq!(error().0, code(ErrorCode::AlreadyConnected)); assert_eq!(error(client).0, code(ErrorCode::AlreadyConnected));
assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 0); assert_eq!(
assert_eq!(error().0, code(ErrorCode::AlreadyConnected)); BakaShrot_SetCaCertificateW(client, w(&file("ca.crt")).as_ptr()),
0
);
assert_eq!(error(client).0, code(ErrorCode::AlreadyConnected));
// Pushes: UTF-16, a null message is an empty one. // Pushes: UTF-16, a null message is an empty one.
assert_eq!( assert_eq!(
BakaShrot_PushMessageToW(w("logs").as_ptr(), w(r#"{"i":1}"#).as_ptr()), BakaShrot_PushMessageToW(client, w("logs").as_ptr(), w(r#"{"i":1}"#).as_ptr()),
1 1
); );
assert_eq!( assert_eq!(
BakaShrot_PushMessageToW(w("logs").as_ptr(), w("héllo 🌍").as_ptr()), BakaShrot_PushMessageToW(client, w("logs").as_ptr(), w("héllo 🌍").as_ptr()),
2 2
); );
assert_eq!( assert_eq!(
BakaShrot_PushMessageToW(w("logs").as_ptr(), std::ptr::null()), BakaShrot_PushMessageToW(client, w("logs").as_ptr(), std::ptr::null()),
3 3
); );
assert_eq!( assert_eq!(
BakaShrot_PushMessageToW(std::ptr::null(), w("{}").as_ptr()), BakaShrot_PushMessageToW(client, std::ptr::null(), w("{}").as_ptr()),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
assert_eq!( assert_eq!(
BakaShrot_PushMessageToW(w("nothing").as_ptr(), w("{}").as_ptr()), BakaShrot_PushMessageToW(client, w("nothing").as_ptr(), w("{}").as_ptr()),
-1 -1
); );
let (failed, why) = error(); let (failed, why) = error(client);
assert_eq!(failed, code(ErrorCode::NotAllowed)); assert_eq!(failed, code(ErrorCode::NotAllowed));
assert!(why.contains("may not push to 'nothing'"), "{why}"); assert!(why.contains("may not push to 'nothing'"), "{why}");
// The latest; none yet in another topic. // The latest; none yet in another topic.
assert_eq!( assert_eq!(
BakaShrot_GetLatestMessageOfW(w("logs").as_ptr(), w("kitchen").as_ptr()), BakaShrot_GetLatestMessageOfW(client, w("logs").as_ptr(), w("kitchen").as_ptr()),
1 1
); );
assert_eq!( assert_eq!(
(BakaShrot_GetMessageCount(), BakaShrot_GetMessageId()), (
BakaShrot_GetMessageCount(client),
BakaShrot_GetMessageId(client)
),
(1, 3) (1, 3)
); );
assert_eq!(get_w(BakaShrot_GetMessageDataW), ""); assert_eq!(get_w(client, BakaShrot_GetMessageDataW), "");
assert!(BakaShrot_GetMessagePushedAt() > 1_700_000_000_000); assert!(BakaShrot_GetMessagePushedAt(client) > 1_700_000_000_000);
assert_eq!(BakaShrot_GetMessageAttachmentSize(), 0); assert_eq!(BakaShrot_GetMessageAttachmentSize(client), 0);
assert_eq!(BakaShrot_IsMessageAttachmentReady(), 0); assert_eq!(BakaShrot_IsMessageAttachmentReady(client), 0);
assert_eq!( assert_eq!(
BakaShrot_GetLatestMessageOfW(w("secret").as_ptr(), w("kitchen").as_ptr()), BakaShrot_GetLatestMessageOfW(client, w("secret").as_ptr(), w("kitchen").as_ptr()),
0 0
); );
assert_eq!(error().0, code(ErrorCode::NotFound)); assert_eq!(error(client).0, code(ErrorCode::NotFound));
assert_eq!(BakaShrot_GetMessageCount(), 0); assert_eq!(BakaShrot_GetMessageCount(client), 0);
// A run of messages, selected one by one. // A run of messages, selected one by one.
assert_eq!( assert_eq!(
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 2), BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 2),
2 2
); );
assert_eq!(BakaShrot_HasMoreMessages(), 1); assert_eq!(BakaShrot_HasMoreMessages(client), 1);
assert_eq!(get_w(BakaShrot_GetMessageTopicW), "logs"); assert_eq!(get_w(client, BakaShrot_GetMessageTopicW), "logs");
assert_eq!(get_w(BakaShrot_GetMessageNodeW), "kitchen"); assert_eq!(get_w(client, BakaShrot_GetMessageNodeW), "kitchen");
assert_eq!(BakaShrot_GetMessageId(), 1); assert_eq!(BakaShrot_GetMessageId(client), 1);
assert_eq!(BakaShrot_SelectMessage(1), 1); assert_eq!(BakaShrot_SelectMessage(client, 1), 1);
assert_eq!(get_w(BakaShrot_GetMessageDataW), "héllo 🌍"); assert_eq!(get_w(client, BakaShrot_GetMessageDataW), "héllo 🌍");
assert_eq!(get_a(BakaShrot_GetMessageDataA), "héllo 🌍"); assert_eq!(get_a(client, BakaShrot_GetMessageDataA), "héllo 🌍");
assert_eq!(BakaShrot_SelectMessage(2), 0); assert_eq!(BakaShrot_SelectMessage(client, 2), 0);
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
assert_eq!(BakaShrot_GetMessageId(), 2, "the selection stays"); assert_eq!(BakaShrot_GetMessageId(client), 2, "the selection stays");
assert_eq!( assert_eq!(
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 3, 10), BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("kitchen").as_ptr(), 3, 10),
0 0
); );
assert_eq!(BakaShrot_HasMoreMessages(), 0); assert_eq!(BakaShrot_HasMoreMessages(client), 0);
assert_eq!(BakaShrot_GetMessageId(), 0); assert_eq!(BakaShrot_GetMessageId(client), 0);
for (after, limit) in [(-1, 10), (0, 0), (0, 10_001)] { for (after, limit) in [(-1, 10), (0, 0), (0, 10_001)] {
assert_eq!( assert_eq!(
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), after, limit), BakaShrot_GetMessagesW(
client,
w("logs").as_ptr(),
w("kitchen").as_ptr(),
after,
limit
),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
} }
assert_eq!( assert_eq!(
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("nobody").as_ptr(), 0, 10), BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("nobody").as_ptr(), 0, 10),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::UnknownName)); assert_eq!(error(client).0, code(ErrorCode::UnknownName));
assert_eq!(BakaShrot_IsConnected(), 1, "a refusal keeps the connection"); assert_eq!(
BakaShrot_IsConnected(client),
1,
"a refusal keeps the connection"
);
// The buffers: the size needed, nothing copied if it doesn't fit. // The buffers: the size needed, nothing copied if it doesn't fit.
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 1); BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 1);
assert_eq!(BakaShrot_GetMessageDataW(std::ptr::null_mut(), 0), 16); assert_eq!(
assert_eq!(BakaShrot_GetMessageDataA(std::ptr::null_mut(), 0), 8); BakaShrot_GetMessageDataW(client, std::ptr::null_mut(), 0),
16
);
assert_eq!(
BakaShrot_GetMessageDataA(client, std::ptr::null_mut(), 0),
8
);
let mut small = [7u16; 7]; let mut small = [7u16; 7];
assert_eq!(BakaShrot_GetMessageDataW(small.as_mut_ptr(), 14), 16); assert_eq!(
BakaShrot_GetMessageDataW(client, small.as_mut_ptr(), 14),
16
);
assert_eq!(small, [7; 7]); assert_eq!(small, [7; 7]);
// Unaligned: a byte buffer. // Unaligned: a byte buffer.
let mut bytes = [0u8; 17]; let mut bytes = [0u8; 17];
assert_eq!( assert_eq!(
BakaShrot_GetMessageDataW(bytes[1..].as_mut_ptr().cast(), 16), BakaShrot_GetMessageDataW(client, bytes[1..].as_mut_ptr().cast(), 16),
16 16
); );
assert_eq!(bytes[1..3], [b'{', 0]); assert_eq!(bytes[1..3], [b'{', 0]);
// Names, queries. // Names, queries.
// Topics: those with messages (nothing in `secret` yet). // Topics: those with messages (nothing in `secret` yet).
assert_eq!(BakaShrot_ListTopics(), 1); assert_eq!(BakaShrot_ListTopics(client), 1);
assert_eq!( assert_eq!(
get_w(BakaShrot_GetNamesListW), get_w(client, BakaShrot_GetNamesListW),
r#"{"kind":"topic","names":["logs"],"truncated":false}"# r#"{"kind":"topic","names":["logs"],"truncated":false}"#
); );
assert_eq!(BakaShrot_ListNodes(), 1); assert_eq!(BakaShrot_ListNodes(client), 1);
assert_eq!( assert_eq!(
BakaShrot_QueryW(w("SELECT COUNT(*) AS n FROM data").as_ptr()), BakaShrot_QueryW(client, w("SELECT COUNT(*) AS n FROM data").as_ptr()),
1 1
); );
assert_eq!( assert_eq!(
get_w(BakaShrot_GetQueryResultW), get_w(client, BakaShrot_GetQueryResultW),
r#"{"columns":["n"],"rows":[["3"]]}"# r#"{"columns":["n"],"rows":[["3"]]}"#
); );
assert_eq!(BakaShrot_QueryW(w("SELECT nope").as_ptr()), 0); assert_eq!(BakaShrot_QueryW(client, w("SELECT nope").as_ptr()), 0);
assert_eq!(error().0, code(ErrorCode::QueryFailed)); assert_eq!(error(client).0, code(ErrorCode::QueryFailed));
assert_eq!(get_w(BakaShrot_GetQueryResultW), ""); assert_eq!(get_w(client, BakaShrot_GetQueryResultW), "");
// Attachments: from a file or memory, saved or loaded back. // Attachments: from a file or memory, saved or loaded back.
let (logs, kitchen) = (w("logs"), w("kitchen")); let (logs, kitchen) = (w("logs"), w("kitchen"));
@@ -227,34 +266,36 @@ fn exports() {
std::fs::write(running.folder.join("photo.bin"), &photo).unwrap(); std::fs::write(running.folder.join("photo.bin"), &photo).unwrap();
let photo_file = w(&file("photo.bin")); let photo_file = w(&file("photo.bin"));
let pushed = BakaShrot_PushMessageWithFileW( let pushed = BakaShrot_PushMessageWithFileW(
client,
logs.as_ptr(), logs.as_ptr(),
w(r#"{"photo":1}"#).as_ptr(), w(r#"{"photo":1}"#).as_ptr(),
photo_file.as_ptr(), photo_file.as_ptr(),
); );
assert_eq!(pushed, 4, "{:?}", error()); assert_eq!(pushed, 4, "{:?}", error(client));
let tiny = b"tiny"; let tiny = b"tiny";
let pushed = BakaShrot_PushMessageWithDataW( let pushed = BakaShrot_PushMessageWithDataW(
client,
logs.as_ptr(), logs.as_ptr(),
std::ptr::null(), std::ptr::null(),
tiny.as_ptr().cast(), tiny.as_ptr().cast(),
4, 4,
); );
assert_eq!(pushed, 5, "{:?}", error()); assert_eq!(pushed, 5, "{:?}", error(client));
assert_eq!( assert_eq!(
BakaShrot_GetLatestMessageOfW(logs.as_ptr(), kitchen.as_ptr()), BakaShrot_GetLatestMessageOfW(client, logs.as_ptr(), kitchen.as_ptr()),
1 1
); );
assert_eq!( assert_eq!(
( (
BakaShrot_GetMessageId(), BakaShrot_GetMessageId(client),
BakaShrot_GetMessageAttachmentSize(), BakaShrot_GetMessageAttachmentSize(client),
BakaShrot_IsMessageAttachmentReady() BakaShrot_IsMessageAttachmentReady(client)
), ),
(5, 4, 1) (5, 4, 1)
); );
let saved = w(&file("saved.bin")); let saved = w(&file("saved.bin"));
assert_eq!( assert_eq!(
BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 4, saved.as_ptr()), BakaShrot_SaveAttachmentW(client, logs.as_ptr(), kitchen.as_ptr(), 4, saved.as_ptr()),
1_500_000 1_500_000
); );
assert_eq!( assert_eq!(
@@ -262,84 +303,264 @@ fn exports() {
photo photo
); );
assert_eq!( assert_eq!(
BakaShrot_LoadAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 5), BakaShrot_LoadAttachmentW(client, logs.as_ptr(), kitchen.as_ptr(), 5),
4
);
assert_eq!(
BakaShrot_GetAttachmentData(client, std::ptr::null_mut(), 0),
4 4
); );
assert_eq!(BakaShrot_GetAttachmentData(std::ptr::null_mut(), 0), 4);
let mut small = [9u8; 3]; let mut small = [9u8; 3];
assert_eq!(BakaShrot_GetAttachmentData(small.as_mut_ptr().cast(), 3), 4); assert_eq!(
BakaShrot_GetAttachmentData(client, small.as_mut_ptr().cast(), 3),
4
);
assert_eq!(small, [9; 3], "nothing copied if it doesn't fit"); assert_eq!(small, [9; 3], "nothing copied if it doesn't fit");
let mut data = [0u8; 4]; let mut data = [0u8; 4];
assert_eq!(BakaShrot_GetAttachmentData(data.as_mut_ptr().cast(), 4), 4);
assert_eq!(&data, tiny);
assert_eq!(BakaShrot_FreeAttachmentData(), 1);
assert_eq!(BakaShrot_GetAttachmentData(std::ptr::null_mut(), 0), 0);
assert_eq!( assert_eq!(
BakaShrot_LoadAttachmentA(a("logs").as_ptr(), a("kitchen").as_ptr(), 4), BakaShrot_GetAttachmentData(client, data.as_mut_ptr().cast(), 4),
4
);
assert_eq!(&data, tiny);
assert_eq!(BakaShrot_FreeAttachmentData(client), 1);
assert_eq!(
BakaShrot_GetAttachmentData(client, std::ptr::null_mut(), 0),
0
);
assert_eq!(
BakaShrot_LoadAttachmentA(client, a("logs").as_ptr(), a("kitchen").as_ptr(), 4),
1_500_000 1_500_000
); );
BakaShrot_FreeAttachmentData(); BakaShrot_FreeAttachmentData(client);
// Refused, or the client's own failures: -1, no file. // Refused, or the client's own failures: -1, no file.
let none = w(&file("none.bin")); let none = w(&file("none.bin"));
assert_eq!( assert_eq!(
BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 1, none.as_ptr()), BakaShrot_SaveAttachmentW(client, logs.as_ptr(), kitchen.as_ptr(), 1, none.as_ptr()),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::NotFound)); assert_eq!(error(client).0, code(ErrorCode::NotFound));
assert!(!running.folder.join("none.bin").exists()); assert!(!running.folder.join("none.bin").exists());
assert_eq!( assert_eq!(
BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), -1, none.as_ptr()), BakaShrot_SaveAttachmentW(client, logs.as_ptr(), kitchen.as_ptr(), -1, none.as_ptr()),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
let missing = w(&file("missing.bin")); let missing = w(&file("missing.bin"));
assert_eq!( assert_eq!(
BakaShrot_PushMessageWithFileW(logs.as_ptr(), std::ptr::null(), missing.as_ptr()), BakaShrot_PushMessageWithFileW(
client,
logs.as_ptr(),
std::ptr::null(),
missing.as_ptr()
),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::FileError)); assert_eq!(error(client).0, code(ErrorCode::FileError));
for (pointer, size) in [(std::ptr::null(), 4), (tiny.as_ptr(), 0)] { for (pointer, size) in [(std::ptr::null(), 4), (tiny.as_ptr(), 0)] {
let pushed = BakaShrot_PushMessageWithDataW( let pushed = BakaShrot_PushMessageWithDataW(
client,
logs.as_ptr(), logs.as_ptr(),
std::ptr::null(), std::ptr::null(),
pointer.cast(), pointer.cast(),
size, size,
); );
assert_eq!(pushed, -1); assert_eq!(pushed, -1);
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
} }
assert_eq!(BakaShrot_IsConnected(), 1); assert_eq!(BakaShrot_IsConnected(client), 1);
// Closed: requests refused, the settings kept. // Closed: requests refused, the settings kept.
assert_eq!(BakaShrot_Disconnect(), 1); assert_eq!(BakaShrot_Disconnect(client), 1);
assert_eq!(BakaShrot_Disconnect(), 0); assert_eq!(BakaShrot_Disconnect(client), 0);
assert_eq!(BakaShrot_IsConnected(), 0); assert_eq!(BakaShrot_IsConnected(client), 0);
assert_eq!(get_w(BakaShrot_GetNodeW), ""); assert_eq!(get_w(client, BakaShrot_GetNodeW), "");
assert_eq!(BakaShrot_QueryW(w("SELECT 1").as_ptr()), 0); assert_eq!(BakaShrot_QueryW(client, w("SELECT 1").as_ptr()), 0);
assert_eq!(error().0, code(ErrorCode::NotConnected)); assert_eq!(error(client).0, code(ErrorCode::NotConnected));
// Another identity, by the A exports: not allowed to query. // Another identity, by the A exports: not allowed to query.
assert_eq!( assert_eq!(
BakaShrot_SetCertificateA(a(&file("lounge.crt")).as_ptr()), BakaShrot_SetCertificateA(client, a(&file("lounge.crt")).as_ptr()),
1 1
); );
assert_eq!(BakaShrot_SetPrivateKeyA(a(&pem("lounge.key")).as_ptr()), 1);
assert_eq!( assert_eq!(
BakaShrot_ConnectA(a("localhost").as_ptr(), port), BakaShrot_SetPrivateKeyA(client, a(&pem("lounge.key")).as_ptr()),
1
);
assert_eq!(
BakaShrot_ConnectA(client, a("localhost").as_ptr(), port),
1, 1,
"{:?}", "{:?}",
error() error(client)
); );
assert_eq!(get_a(BakaShrot_GetNodeA), "lounge"); assert_eq!(get_a(client, BakaShrot_GetNodeA), "lounge");
assert_eq!(BakaShrot_QueryA(a("SELECT 1").as_ptr()), 0); assert_eq!(BakaShrot_QueryA(client, a("SELECT 1").as_ptr()), 0);
let (failed, why) = error(); let (failed, why) = error(client);
assert_eq!(failed, code(ErrorCode::NotAllowed)); assert_eq!(failed, code(ErrorCode::NotAllowed));
assert_eq!(get_a(BakaShrot_GetRefusalReasonA), why); assert_eq!(get_a(client, BakaShrot_GetRefusalReasonA), why);
BakaShrot_Disconnect(); BakaShrot_Disconnect(client);
// Nothing listening there. // Nothing listening there.
assert_eq!(BakaShrot_ConnectA(a("127.0.0.1").as_ptr(), 1), 0); assert_eq!(BakaShrot_ConnectA(client, a("127.0.0.1").as_ptr(), 1), 0);
assert_eq!(error().0, code(ErrorCode::ConnectFailed)); assert_eq!(error(client).0, code(ErrorCode::ConnectFailed));
} }
assert_eq!(BakaShrot_FreeClient(client), 1);
}
/// A new client, connected as `name` (its certificate and key in files).
fn connected(running: &common::Running, name: &str) -> i64 {
let client = BakaShrot_CreateClient();
assert!(client >= 1);
let file = |name: &str| w(&running.folder.join(name).display().to_string());
unsafe {
assert_eq!(
BakaShrot_SetCaCertificateW(client, file("ca.crt").as_ptr()),
1
);
assert_eq!(
BakaShrot_SetCertificateW(client, file(&format!("{name}.crt")).as_ptr()),
1
);
assert_eq!(
BakaShrot_SetPrivateKeyW(client, file(&format!("{name}.key")).as_ptr()),
1
);
let host = w("127.0.0.1");
let connected = BakaShrot_ConnectW(client, host.as_ptr(), i32::from(running.port));
assert_eq!(connected, 1, "{name}: {:?}", error(client));
}
client
}
#[test]
fn clients() {
let running = common::Running::start("clients");
running.issue("kitchen", &["home"]);
running.issue("lounge", &["lounge"]);
unsafe {
// Handles that aren't a client's: refused, never a crash.
assert_eq!(
BakaShrot_PushMessageToW(99, w("logs").as_ptr(), w("{}").as_ptr()),
-1
);
let (failed, why) = error(99);
assert_eq!(failed, code(ErrorCode::InvalidArgument));
assert!(why.contains("no client 99"), "{why}");
assert_eq!(BakaShrot_IsConnected(99), 0);
assert_eq!(BakaShrot_GetMessageId(-5), 0);
assert_eq!(get_w(99, BakaShrot_GetMessageDataW), "");
assert_eq!(BakaShrot_FreeClient(99), 0);
assert_eq!(BakaShrot_FreeClient(0), 0);
let (failed, why) = error(0);
assert_eq!(failed, code(ErrorCode::InvalidArgument), "0 is never one");
assert!(why.contains("no client 0"), "{why}");
// Two identities connected at once.
let kitchen = connected(&running, "kitchen");
let lounge = connected(&running, "lounge");
assert_ne!(kitchen, lounge);
assert_eq!(get_w(kitchen, BakaShrot_GetNodeW), "kitchen");
assert_eq!(get_w(lounge, BakaShrot_GetNodeW), "lounge");
for i in 1..=3 {
let data = w(&format!(r#"{{"i":{i}}}"#));
assert_eq!(
BakaShrot_PushMessageToW(kitchen, w("logs").as_ptr(), data.as_ptr()),
i
);
}
// Each its answers: one reads, the other's selection stays.
assert_eq!(
BakaShrot_GetLatestMessageOfW(kitchen, w("logs").as_ptr(), w("kitchen").as_ptr()),
1
);
assert_eq!(
BakaShrot_GetMessagesW(lounge, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 10),
3
);
assert_eq!(BakaShrot_SelectMessage(lounge, 1), 1);
assert_eq!(get_w(lounge, BakaShrot_GetMessageDataW), r#"{"i":2}"#);
assert_eq!(BakaShrot_GetMessageId(kitchen), 3);
assert_eq!(get_w(kitchen, BakaShrot_GetMessageDataW), r#"{"i":3}"#);
assert_eq!(BakaShrot_GetMessageCount(kitchen), 1);
// Each its errors: lounge may only read logs.
assert_eq!(
BakaShrot_PushMessageToW(lounge, w("logs").as_ptr(), w("{}").as_ptr()),
-1
);
let (failed, why) = error(lounge);
assert_eq!(failed, code(ErrorCode::NotAllowed));
assert!(why.contains("may not push"), "{why}");
assert_eq!(error(kitchen), (0, String::new()));
// Freed: closed, its handle refused, never given again.
assert_eq!(BakaShrot_FreeClient(lounge), 1);
assert_eq!(BakaShrot_FreeClient(lounge), 0);
assert_eq!(BakaShrot_IsConnected(lounge), 0);
assert_eq!(
BakaShrot_GetMessagesW(lounge, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 10),
-1
);
assert_eq!(error(lounge).0, code(ErrorCode::InvalidArgument));
assert!(BakaShrot_CreateClient() > lounge.max(kitchen));
assert_eq!(BakaShrot_IsConnected(kitchen), 1, "the other stays");
assert_eq!(BakaShrot_Disconnect(kitchen), 1);
assert_eq!(BakaShrot_IsConnected(kitchen), 0);
assert_eq!(BakaShrot_FreeClient(kitchen), 1);
}
// Threads, each with its client, pushing at once: every push stored,
// each id once.
let threads: Vec<_> = (0..4)
.map(|_| {
let client = connected(&running, "kitchen");
std::thread::spawn(move || {
let ids: Vec<i64> = (0..50)
.map(|i| unsafe {
let data = w(&format!(r#"{{"t":{i}}}"#));
BakaShrot_PushMessageToW(client, w("logs").as_ptr(), data.as_ptr())
})
.collect();
assert_eq!(BakaShrot_FreeClient(client), 1);
ids
})
})
.collect();
let mut ids: Vec<i64> = threads
.into_iter()
.flat_map(|thread| thread.join().unwrap())
.collect();
ids.sort_unstable();
assert_eq!(ids, (4..=203).collect::<Vec<i64>>());
// A client freed while another thread uses it: that thread's calls
// fail from then on, nothing crashes.
let client = connected(&running, "kitchen");
let started = Arc::new(AtomicBool::new(false));
let reader = {
let started = started.clone();
std::thread::spawn(move || {
let mut reads = 0;
loop {
let count = unsafe {
BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 50)
};
started.store(true, Ordering::SeqCst);
if count < 0 {
return (reads, error(client).0);
}
reads += 1;
}
})
};
while !started.load(Ordering::SeqCst) {
std::thread::yield_now();
}
assert_eq!(BakaShrot_FreeClient(client), 1);
let (reads, failed) = reader.join().unwrap();
assert!(reads >= 1);
assert_eq!(failed, code(ErrorCode::InvalidArgument));
} }
+27 -11
View File
@@ -5,7 +5,7 @@ What apps connect with, in layers:
| Layer | Where | For | | Layer | Where | For |
|---|---|---| |---|---|---|
| `bakashrot-client` | `crates/bakashrot-client` | Rust: blocking, one connection per `Client` | | `bakashrot-client` | `crates/bakashrot-client` | Rust: blocking, one connection per `Client` |
| The DLL | `crates/bakashrot-capi`: `bakashrot.dll`, `libbakashrot.so` | C and anything that loads a DLL: the `BakaShrot_*` exports, one connection per process | | The DLL | `crates/bakashrot-capi`: `bakashrot.dll`, `libbakashrot.so` | C and anything that loads a DLL: the `BakaShrot_*` exports, as many clients as needed |
| C header | `bindings/c/bakashrot.h` | generated from the DLL (cbindgen) | | C header | `bindings/c/bakashrot.h` | generated from the DLL (cbindgen) |
| PureBasic | `bindings/purebasic/` | the prototypes and the error codes | | PureBasic | `bindings/purebasic/` | the prototypes and the error codes |
| Python | `bindings/python/bakashrot.py` | `Client` over the DLL (ctypes), standard library only | | Python | `bindings/python/bakashrot.py` | `Client` over the DLL (ctypes), standard library only |
@@ -15,7 +15,7 @@ Decided in `../revamp.md`, "Decided" (2026-11-13). What goes over the
wire: `protocol.md`; the server's side: `server.md`. wire: `protocol.md`; the server's side: `server.md`.
**Status:** steps 7 to 9: connecting, pushes, messages, attachments, **Status:** steps 7 to 9: connecting, pushes, messages, attachments,
names, queries. names, queries, several clients.
## Who connects: certificates ## Who connects: certificates
@@ -42,8 +42,11 @@ crl = "ca.crl" # optional; a file not there yet: none
Its conventions: Its conventions:
- **One connection per process.** Calls from several threads wait for each - **Clients.** `BakaShrot_CreateClient()` makes one and returns its
other. handle, the first argument of every other export;
`BakaShrot_FreeClient(Client)` frees it. Each client has its own
connection, answers and errors, and different clients can be used from
different threads at once. A bad handle fails with `InvalidArgument`.
- **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or UTF-16 - **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or UTF-16
(`uint16_t*`, `wchar_t*` on Windows; PureBasic uses these), (`uint16_t*`, `wchar_t*` on Windows; PureBasic uses these),
null-terminated. A null string is an empty one where that means null-terminated. A null string is an empty one where that means
@@ -63,8 +66,11 @@ Its conventions:
on the other; the C runtime linked statically on Windows (the release on the other; the C runtime linked statically on Windows (the release
DLL imports system DLLs only). DLL imports system DLLs only).
Every export but `CreateClient` takes the handle first (left out below).
| Exports | What | | Exports | What |
|---|---| |---|---|
| `CreateClient()`, `FreeClient` | a new client's handle (0 if it failed); freed, 1 |
| `SetCaCertificate`, `SetCertificate`, `SetPrivateKey`, `SetCrl` (`A`/`W`) | PEM text (starting with `-----BEGIN`), or the path of a file holding it; `SetCrl` null or empty for none. Before connecting (`AlreadyConnected`); a file that can't be read is `FileError` | | `SetCaCertificate`, `SetCertificate`, `SetPrivateKey`, `SetCrl` (`A`/`W`) | PEM text (starting with `-----BEGIN`), or the path of a file holding it; `SetCrl` null or empty for none. Before connecting (`AlreadyConnected`); a file that can't be read is `FileError` |
| `Connect(Host, Port)` (`A`/`W`) | TLS with those; refused: `AuthRejected` (the server refused the certificate), `ServerNotVerified` (this client refused the server's), `NotAllowed` (none of its roles is the server's), `VersionMismatch` | | `Connect(Host, Port)` (`A`/`W`) | TLS with those; refused: `AuthRejected` (the server refused the certificate), `ServerNotVerified` (this client refused the server's), `NotAllowed` (none of its roles is the server's), `VersionMismatch` |
| `IsConnected`, `Disconnect` | `IsConnected` notices a connection the server closed | | `IsConnected`, `Disconnect` | `IsConnected` notices a connection the server closed |
@@ -78,7 +84,7 @@ Its conventions:
| `PushMessageWithFile(Topic, Data, FilePath)`, `PushMessageWithData(Topic, Data, *Data, Size)` (`A`/`W`) | the id, -1 on failure; the attachment 1 byte and up, as much as the server takes (`TooBig`); a file read twice (its SHA-256 first), one changed in between refused (`DataMismatch`) | | `PushMessageWithFile(Topic, Data, FilePath)`, `PushMessageWithData(Topic, Data, *Data, Size)` (`A`/`W`) | the id, -1 on failure; the attachment 1 byte and up, as much as the server takes (`TooBig`); a file read twice (its SHA-256 first), one changed in between refused (`DataMismatch`) |
| `SaveAttachment(Topic, Node, MessageId, FilePath)` (`A`/`W`) | its size, -1 on failure (`NotFound`, `NotReady`, `AttachmentMismatch`); a failed one leaves no file | | `SaveAttachment(Topic, Node, MessageId, FilePath)` (`A`/`W`) | its size, -1 on failure (`NotFound`, `NotReady`, `AttachmentMismatch`); a failed one leaves no file |
| `LoadAttachment(Topic, Node, MessageId)` (`A`/`W`), then `GetAttachmentData(*Buffer, Size)`, `FreeAttachmentData()` | into memory, for small ones; the getter returns the size, copies nothing if it doesn't fit | | `LoadAttachment(Topic, Node, MessageId)` (`A`/`W`), then `GetAttachmentData(*Buffer, Size)`, `FreeAttachmentData()` | into memory, for small ones; the getter returns the size, copies nothing if it doesn't fit |
| `GetLastError`, `GetRefusalReason` (`A`/`W`) | why the last call failed | | `GetLastError`, `GetRefusalReason` (`A`/`W`) | why the client's last call failed |
The header has each one's comment. Every name starts with `BakaShrot_`. The header has each one's comment. Every name starts with `BakaShrot_`.
@@ -92,6 +98,8 @@ attachment=None)` (the topic required; the attachment bytes or a path),
`latest()`, `get_messages()`, `iter_messages()`, `follow()`, `latest()`, `get_messages()`, `iter_messages()`, `follow()`,
`get_attachment()` (bytes), `save_attachment()` (a file), `get_attachment()` (bytes), `save_attachment()` (a file),
`list_topics()` / `list_nodes()` (names), `query()` / `query_raw()`. `list_topics()` / `list_nodes()` (names), `query()` / `query_raw()`.
Each `Client` has its own client in the DLL: several can be connected at
once, from any threads.
Errors: `RefusedError`, `ConnectionLostError`, `AuthError` (a certificate Errors: `RefusedError`, `ConnectionLostError`, `AuthError` (a certificate
refused, either way, or no role allowed), `BakaShrotError`. The DLL is refused, either way, or no role allowed), `BakaShrotError`. The DLL is
looked for next to the module, or `BAKASHROT_DLL`. The release has a looked for next to the module, or `BAKASHROT_DLL`. The release has a
@@ -102,11 +110,11 @@ wheel with the library in it (`pip install bakashrot-*.whl`, nothing else:
`bindings/purebasic/BakaShrot_Client_Prototypes.pbi` (with `bindings/purebasic/BakaShrot_Client_Prototypes.pbi` (with
`BakaShrot_ErrorCodes.pbi`): `BakaShrot_LoadClient("bakashrot.dll")`, then `BakaShrot_ErrorCodes.pbi`): `BakaShrot_LoadClient("bakashrot.dll")`, then
the `W` exports without their suffix, `BakaShrot_*String()` helpers for the the `W` exports without their suffix, the client first, and
getters. Run directly, it's an example: `ClientExample <DllPath> <CaFile> `BakaShrot_*String(Client)` helpers for the getters. Run directly, it's an example: `ClientExample <DllPath> <CaFile>
<CertificateFile> <KeyFile> <Host> <Port>`, pushing a message and one <CertificateFile> <KeyFile> <Host> <Port>`, pushing a message and one
with an attachment, reading both back (run by hand against a server; with an attachment, reading both back, then a second client at the same
not in CI, which has no PureBasic). time (run by hand against a server; not in CI, which has no PureBasic).
## The tool ## The tool
@@ -152,12 +160,20 @@ bakashrot list nodes --json {"kind":"node","names":["kitchen"
`crates/bakashrot-capi/tests/`, each against a server on a free port: `crates/bakashrot-capi/tests/`, each against a server on a free port:
- `exports.rs`: the exports as C calls them: certificates from files and - `exports.rs`, `exports`: the exports as C calls them, on one client: certificates from files and
PEM, the `W` strings (and some `A`), the buffers (the size, too small, PEM, the `W` strings (and some `A`), the buffers (the size, too small,
unaligned), selecting messages, attachments (from a file and memory, unaligned), selecting messages, attachments (from a file and memory,
saved and loaded, the buffer, refused ones), every refusal and the saved and loaded, the buffer, refused ones), every refusal and the
client's own errors, closing, another identity. client's own errors, closing, another identity.
- `python.rs`: runs `bindings/python/check_bakashrot.py` on the DLL; skipped, saying so, without Python 3.11+. - `exports.rs`, `clients`: two clients at once, each with its own answers
and errors; bad and freed handles; 4 threads on 4 clients; a client
freed while another thread uses it.
- `python.rs`: runs `bindings/python/check_bakashrot.py` on the DLL (two
`Client`s at once, too); skipped, saying so, without Python 3.11+.
- PureBasic, by hand (no PureBasic in CI): run
`BakaShrot_Client_Prototypes.pbi` directly, `ClientExample <DllPath>
<CaFile> <CertificateFile> <KeyFile> <Host> <Port>`. Passed 2026-11-17
with PureBasic 5.73 LTS and 6.41 (C backend), x64.
- `header.rs`: `bindings/c/bakashrot.h` matches the exports (rewritten - `header.rs`: `bindings/c/bakashrot.h` matches the exports (rewritten
when it doesn't: check it in). when it doesn't: check it in).
+2 -3
View File
@@ -42,9 +42,8 @@ network**, not exposed to the internet. So:
server then needs every node's public key). server then needs every node's public key).
- **Private keys sit in PEM files**, readable by whoever can read them: on - **Private keys sit in PEM files**, readable by whoever can read them: on
trusted machines, file permissions are enough. trusted machines, file permissions are enough.
- **One connection per process in the DLL** (`revamp.md`, - **Polling rather than pushed subscriptions;** nothing reconnects by
"Open questions"): a handle-based API for several. Polling rather than itself, on purpose.
pushed subscriptions; nothing reconnects by itself, on purpose.
- **At least once:** a push whose answer was lost (the server stopped - **At least once:** a push whose answer was lost (the server stopped
between committing and answering) is stored twice if retried. A client between committing and answering) is stored twice if retried. A client
that minds reads the latest message before retrying. that minds reads the latest message before retrying.
+10 -3
View File
@@ -189,7 +189,8 @@ Also decided (2026-11-13):
- **the old exports that don't fit any more are dropped**, not kept - **the old exports that don't fit any more are dropped**, not kept
failing: the keys and node setters, the id-based ones, the default failing: the keys and node setters, the id-based ones, the default
topic's `PushMessage()`; topic's `PushMessage()`;
- **one connection per process**, as before (handles maybe later); - **one connection per process**, as before (replaced by handles
2026-11-17, below);
- **`client.toml`** (server, ca, certificate, key, crl) replaces - **`client.toml`** (server, ca, certificate, key, crl) replaces
`client.ini`: Python's `Client.from_file()`, the tools at step 8. `client.ini`: Python's `Client.from_file()`, the tools at step 8.
- **The tools** (2026-11-14), `docs/client.md`, "The tools": one - **The tools** (2026-11-14), `docs/client.md`, "The tools": one
@@ -299,6 +300,13 @@ Also decided (2026-11-13):
not for production. Worth another look if rustls-graviola lets a not for production. Worth another look if rustls-graviola lets a
provider name its algorithms one by one, or ring gets ML-KEM. provider name its algorithms one by one, or ring gets ML-KEM.
- **Several clients per process in the DLL** (2026-11-17, the owner;
old open item 10): `BakaShrot_CreateClient()` returns a handle, the
first argument of every other export (same names as before);
`BakaShrot_FreeClient()` frees it. No default client and no exports
without a handle ("keep something clean"): apps built for the old DLL
need updating. A bad handle fails (`InvalidArgument`).
## Proposed, to confirm ## Proposed, to confirm
- **A GUI explorer** (2026-11-16, set aside for later): likely **egui** - **A GUI explorer** (2026-11-16, set aside for later): likely **egui**
@@ -311,8 +319,7 @@ Also decided (2026-11-13):
## Open questions ## Open questions
- **A handle-based DLL API** (several connections per process, old open item None right now.
10): later maybe, the owner's call (one connection per process for now).
## The old open items ## The old open items