diff --git a/.cargo/config.toml b/.cargo/config.toml index 4c36d2e..44243c5 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -9,3 +9,8 @@ rustflags = ["-C", "target-feature=+crt-static"] # 2026-11-14 (../revamp.md, "Randomness from the OS"; ../docs/certificates.md). [env] AWS_LC_SYS_NO_JITTER_ENTROPY = "1" +# SQLite (rusqlite's `bundled`) without what libsqlite3-sys turns on and +# nothing here uses: full-text search, R-Tree, dbstat, STAT4, soundex(), +# extension loading, column metadata. 310 KB less in the server (6.6%). +# Decided 2026-11-17 (../revamp.md, "One tool, smaller"; ../docs/storage.md). +LIBSQLITE3_FLAGS = "-USQLITE_ENABLE_FTS3 -USQLITE_ENABLE_FTS3_PARENTHESIS -USQLITE_ENABLE_FTS5 -USQLITE_ENABLE_RTREE -USQLITE_ENABLE_DBSTAT_VTAB -USQLITE_ENABLE_STAT4 -USQLITE_SOUNDEX -USQLITE_ENABLE_LOAD_EXTENSION -USQLITE_ENABLE_COLUMN_METADATA" diff --git a/.cargo/hybrid-crt.toml b/.cargo/hybrid-crt.toml new file mode 100644 index 0000000..98ebbb2 --- /dev/null +++ b/.cargo/hybrid-crt.toml @@ -0,0 +1,9 @@ +# The hybrid C runtime on Windows (MSVC), instead of the static one: the +# UCRT from Windows (part of it since Windows 10, which Rust needs anyway), +# VCRuntime still static. About 180 KB less per program, still no Visual +# C++ redistributable; measured 2026-11-17. Not the default (../revamp.md, +# "Decided" 2): build.ps1 -HybridCrt, release.ps1 -HybridCrt, or +# `cargo build --config .cargo/hybrid-crt.toml`. Cargo adds these flags to +# config.toml's (+crt-static stays). Switching rebuilds everything. +[target.'cfg(all(windows, target_env = "msvc"))'] +rustflags = ["-C", "link-arg=/NODEFAULTLIB:libucrt.lib", "-C", "link-arg=/DEFAULTLIB:ucrt.lib"] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9c5baa9..2f0c917 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,6 +1,7 @@ # On a version tag, or run by hand: the same checks as test.ps1 (Windows # and Linux), then a release for each platform (release.py), its archive -# kept as the run's artifact, and the server's Docker image for amd64 and +# kept as the run's artifact, the C# client's NuGet package with their four +# libraries (an artifact too), and the server's Docker image for amd64 and # arm64, checked (docker/test.sh), pushed to ghcr.io on a tag only. Gitea # Actions runs this file too. # @@ -112,6 +113,65 @@ jobs: target/dist/*.tar.gz if-no-files-found: error + nuget: + # The C# client's NuGet package (docs/client.md, "C#"): the four + # releases' libraries in runtimes//native/, packed on Linux + # (nothing in it is built for a platform), kept as the run's artifact. + needs: release + runs-on: ubuntu-latest + timeout-minutes: 30 + defaults: + run: + shell: bash + env: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: bakashrot-* + path: target/releases + # The .NET SDK, where the image has none (Gitea's runners). + - run: | + if ! command -v dotnet; then + curl --proto '=https' --tlsv1.2 -sSfLo dotnet-install.sh https://dot.net/v1/dotnet-install.sh + bash dotnet-install.sh --channel 8.0 --install-dir "$HOME/.dotnet" + rm dotnet-install.sh + echo "$HOME/.dotnet" >> "$GITHUB_PATH" + fi + - name: Pack + run: | + set -euo pipefail + version=$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml | head -n 1) + native="$PWD/target/nuget-native" + for platform in windows-x64 windows-arm64 linux-x64 linux-arm64; do + case "$platform" in windows-*) library=bakashrot.dll ;; *) library=libbakashrot.so ;; esac + rid="${platform/windows/win}" + archive=$(ls target/releases/bakashrot-$platform/bakashrot-$version-$platform.*) + mkdir -p target/unpacked "$native/$rid" + case "$archive" in *.zip) unzip -q "$archive" -d target/unpacked ;; *) tar -xzf "$archive" -C target/unpacked ;; esac + cp "target/unpacked/bakashrot-$version-$platform/$library" \ + "target/unpacked/bakashrot-$version-$platform/THIRD-PARTY.txt" "$native/$rid/" + done + dotnet pack bindings/csharp/NibblePoker.BakaShrot.Client -c Release \ + -p:Version="$version" -p:NativeDir="$native/" -o target/nuget + # Each library in it, or the package is wrong. + listing=$(unzip -l target/nuget/NibblePoker.BakaShrot.Client.$version.nupkg) + for file in runtimes/win-x64/native/bakashrot.dll runtimes/win-arm64/native/bakashrot.dll \ + runtimes/linux-x64/native/libbakashrot.so runtimes/linux-arm64/native/libbakashrot.so \ + build/net35/NibblePoker.BakaShrot.Client.targets lib/net35/NibblePoker.BakaShrot.Client.dll \ + lib/netstandard2.0/NibblePoker.BakaShrot.Client.dll; do + grep -q " $file\$" <<< "$listing" || { echo "Not in the package: $file"; exit 1; } + done + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: bakashrot-nuget + path: target/nuget/*.nupkg + if-no-files-found: error + docker: # The server's image, each architecture built on its own kind of # machine (no emulation), checked, then pushed as - on a diff --git a/.gitignore b/.gitignore index 704996d..d629f54 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,10 @@ # Python __pycache__/ +# C# +bindings/csharp/*/bin/ +bindings/csharp/*/obj/ + # Rust target/ diff --git a/Cargo.lock b/Cargo.lock index 90697b0..c881eb2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,56 +2,12 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - [[package]] name = "anstyle" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - [[package]] name = "asn1-rs" version = "0.7.2" @@ -123,7 +79,7 @@ dependencies = [ [[package]] name = "bakashrot-capi" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bakashrot-client", "bakashrot-config", @@ -137,7 +93,7 @@ dependencies = [ [[package]] name = "bakashrot-client" -version = "0.3.0" +version = "0.4.0" dependencies = [ "aws-lc-rs", "bakashrot-pki", @@ -147,7 +103,7 @@ dependencies = [ [[package]] name = "bakashrot-config" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bakashrot-proto", "indexmap", @@ -157,7 +113,7 @@ dependencies = [ [[package]] name = "bakashrot-pki" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bakashrot-proto", "rcgen", @@ -169,7 +125,7 @@ dependencies = [ [[package]] name = "bakashrot-proto" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bytes", "rmp-serde", @@ -180,7 +136,7 @@ dependencies = [ [[package]] name = "bakashrot-server" -version = "0.3.0" +version = "0.4.0" dependencies = [ "aws-lc-rs", "bakashrot-client", @@ -200,7 +156,7 @@ dependencies = [ [[package]] name = "bakashrot-storage" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bakashrot-config", "bakashrot-proto", @@ -210,7 +166,7 @@ dependencies = [ [[package]] name = "bakashrot-tools" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bakashrot-client", "bakashrot-config", @@ -304,10 +260,8 @@ version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" dependencies = [ - "anstream", "anstyle", "clap_lex", - "strsim", ] [[package]] @@ -337,12 +291,6 @@ dependencies = [ "cc", ] -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - [[package]] name = "data-encoding" version = "2.11.1" @@ -526,12 +474,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - [[package]] name = "itoa" version = "1.0.19" @@ -674,12 +616,6 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - [[package]] name = "pem" version = "4.0.0" @@ -973,12 +909,6 @@ dependencies = [ "rsqlite-vfs", ] -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - [[package]] name = "subtle" version = "2.6.1" @@ -1265,12 +1195,6 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - [[package]] name = "vcpkg" version = "0.2.15" diff --git a/Cargo.toml b/Cargo.toml index cf75ca5..92bf1f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.3.0" +version = "0.4.0" edition = "2024" rust-version = "1.100" license = "CC0-1.0" @@ -34,5 +34,14 @@ lto = true codegen-units = 1 strip = true # Kept on purpose: the C DLL catches panics at every export (catch_unwind), -# which "abort" would make impossible. +# which "abort" would make impossible, and the server loses only the +# connection that panicked (tokio catches it), not every one. panic = "unwind" + +# The tool (bakashrot), released with this (build.ps1, release.py, the +# Dockerfile): a panic ends its command either way, and without unwinding +# it's about 15% smaller (measured 2026-11-17 on Windows: 2.53 MB, its +# certificates' commands in it). Its own folder, target/release-tools/. +[profile.release-tools] +inherits = "release" +panic = "abort" diff --git a/bindings/c/bakashrot.h b/bindings/c/bakashrot.h index 5553e2a..21e7710 100644 --- a/bindings/c/bakashrot.h +++ b/bindings/c/bakashrot.h @@ -18,67 +18,79 @@ extern "C" { #endif // __cplusplus /** - * Why the last call failed: a protocol error code (1-99 a server's - * refusal, the connection still open; 100 and up the client's own), 0 if - * it succeeded. Getters don't change it. + * Makes a client: its handle (1 and up, never reused), 0 if it failed. */ -int32_t BakaShrot_GetLastError(void); +int64_t BakaShrot_CreateClient(void); /** - * Why the last call failed, in words: the server's reason for a refusal, - * the client's otherwise. Empty if it succeeded. + * Frees a client and closes its connection (once a call on it in another + * thread ends), its enumerations closed too: 1, or 0 if it wasn't one. */ -ptrdiff_t BakaShrot_GetRefusalReasonA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_FreeClient(int64_t client); + +/** + * Why the client's last call failed: a protocol error code (1-99 a + * server's refusal, the connection still open; 100 and up the client's + * own), 0 if it succeeded. Getters don't change it. `InvalidArgument` for + * a bad handle. + */ +int32_t BakaShrot_GetLastError(int64_t client); + +/** + * Why the client's last call failed, in words: the server's reason for a + * refusal, the client's otherwise. Empty if it succeeded. + */ +ptrdiff_t BakaShrot_GetRefusalReasonA(int64_t client, char *buffer, ptrdiff_t size); /** * The same as `BakaShrot_GetRefusalReasonA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetRefusalReasonW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetRefusalReasonW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * Sets the CA's certificate, which the server's must be issued by: PEM * text, or the path of a file holding it. Before connecting. */ -ptrdiff_t BakaShrot_SetCaCertificateA(const char *certificate); +ptrdiff_t BakaShrot_SetCaCertificateA(int64_t client, const char *certificate); /** * The same as `BakaShrot_SetCaCertificateA`, in UTF-16. */ -ptrdiff_t BakaShrot_SetCaCertificateW(const uint16_t *certificate); +ptrdiff_t BakaShrot_SetCaCertificateW(int64_t client, const uint16_t *certificate); /** - * Sets this client's certificate, which says its node and its roles: PEM + * Sets the client's certificate, which says its node and its roles: PEM * text, or the path of a file holding it. Before connecting. */ -ptrdiff_t BakaShrot_SetCertificateA(const char *certificate); +ptrdiff_t BakaShrot_SetCertificateA(int64_t client, const char *certificate); /** * The same as `BakaShrot_SetCertificateA`, in UTF-16. */ -ptrdiff_t BakaShrot_SetCertificateW(const uint16_t *certificate); +ptrdiff_t BakaShrot_SetCertificateW(int64_t client, const uint16_t *certificate); /** - * Sets this client's private key, its certificate's: PEM text, or the path + * Sets the client's private key, its certificate's: PEM text, or the path * of a file holding it. Before connecting. */ -ptrdiff_t BakaShrot_SetPrivateKeyA(const char *key); +ptrdiff_t BakaShrot_SetPrivateKeyA(int64_t client, const char *key); /** * The same as `BakaShrot_SetPrivateKeyA`, in UTF-16. */ -ptrdiff_t BakaShrot_SetPrivateKeyW(const uint16_t *key); +ptrdiff_t BakaShrot_SetPrivateKeyW(int64_t client, const uint16_t *key); /** * Sets the CA's CRL, optional: servers it revokes are refused. PEM text, * or the path of a file holding it (one that isn't there is a * `FileError`); null or empty for none. Before connecting. */ -ptrdiff_t BakaShrot_SetCrlA(const char *crl); +ptrdiff_t BakaShrot_SetCrlA(int64_t client, const char *crl); /** * The same as `BakaShrot_SetCrlA`, in UTF-16. */ -ptrdiff_t BakaShrot_SetCrlW(const uint16_t *crl); +ptrdiff_t BakaShrot_SetCrlW(int64_t client, const uint16_t *crl); /** * Connects to the server at `host` (a name or an address) and `port`: @@ -87,57 +99,81 @@ ptrdiff_t BakaShrot_SetCrlW(const uint16_t *crl); * the server refused the certificate, `ServerNotVerified` this client * refused the server's, `NotAllowed` none of its roles is the server's). */ -ptrdiff_t BakaShrot_ConnectA(const char *host, int32_t port); +ptrdiff_t BakaShrot_ConnectA(int64_t client, const char *host, int32_t port); /** * The same as `BakaShrot_ConnectA`, in UTF-16. */ -ptrdiff_t BakaShrot_ConnectW(const uint16_t *host, int32_t port); +ptrdiff_t BakaShrot_ConnectW(int64_t client, const uint16_t *host, int32_t port); /** * 1 while connected: notices when the server closed the connection * (forgotten then: connect again). */ -ptrdiff_t BakaShrot_IsConnected(void); +ptrdiff_t BakaShrot_IsConnected(int64_t client); /** * Closes the connection: 0 if there was none. The settings stay. */ -ptrdiff_t BakaShrot_Disconnect(void); +ptrdiff_t BakaShrot_Disconnect(int64_t client); + +/** + * Keeps the connection open: 1, or 0 if it failed (`ConnectionLost`: + * connect again). The server closes a connection silent for 5 min; an + * app waiting longer between requests calls this every minute or so + * (the DLL has no thread of its own to do it). + */ +ptrdiff_t BakaShrot_Ping(int64_t client); + +/** + * Sets how long an answer may take, in milliseconds (more than 0; 30000 + * until changed): longer for a slow query, say. Past it, the request + * fails with `ConnectionLost`, the connection closed (the server then + * stops the query it was running). Kept for the next connections, and + * applied to the current one: 1, or 0 if refused. + */ +ptrdiff_t BakaShrot_SetAnswerTimeout(int64_t client, int64_t milliseconds); + +/** + * How long an answer may take, in milliseconds (`BakaShrot_SetAnswerTimeout()`). + */ +int64_t BakaShrot_GetAnswerTimeout(int64_t client); /** * The node this client is, as the server said when connecting: its * certificate's name. Empty when not connected. */ -ptrdiff_t BakaShrot_GetNodeA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetNodeA(int64_t client, char *buffer, ptrdiff_t size); /** * The same as `BakaShrot_GetNodeA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetNodeW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetNodeW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * Pushes a message (JSON or not) to `topic`, as this client's node: its * id (1 and up), -1 on failure. A push whose answer was lost * (`ConnectionLost`) may have been stored all the same. */ -int64_t BakaShrot_PushMessageToA(const char *topic, const char *data); +int64_t BakaShrot_PushMessageToA(int64_t client, const char *topic, const char *data); /** * The same as `BakaShrot_PushMessageToA`, in UTF-16. */ -int64_t BakaShrot_PushMessageToW(const uint16_t *topic, const uint16_t *data); +int64_t BakaShrot_PushMessageToW(int64_t client, const uint16_t *topic, const uint16_t *data); /** * Gets the latest message of `topic` and `node`, then read with the * `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet. */ -ptrdiff_t BakaShrot_GetLatestMessageOfA(const char *topic, const char *node); +ptrdiff_t BakaShrot_GetLatestMessageOfA(int64_t client, const char *topic, const char *node); /** * The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetLatestMessageOfW(const uint16_t *topic, const uint16_t *node); +ptrdiff_t BakaShrot_GetLatestMessageOfW(int64_t client, + const uint16_t *topic, + const uint16_t *node); /** * Gets the messages of `topic` and `node` after id `after` (0 for the @@ -146,12 +182,17 @@ ptrdiff_t BakaShrot_GetLatestMessageOfW(const uint16_t *topic, const uint16_t *n * first is selected; `BakaShrot_SelectMessage()` selects the others, * `BakaShrot_HasMoreMessages()` says whether more follow the last one. */ -int32_t BakaShrot_GetMessagesA(const char *topic, const char *node, int64_t after, int32_t limit); +int32_t BakaShrot_GetMessagesA(int64_t client, + const char *topic, + const char *node, + int64_t after, + int32_t limit); /** * The same as `BakaShrot_GetMessagesA`, in UTF-16. */ -int32_t BakaShrot_GetMessagesW(const uint16_t *topic, +int32_t BakaShrot_GetMessagesW(int64_t client, + const uint16_t *topic, const uint16_t *node, int64_t after, int32_t limit); @@ -159,119 +200,128 @@ int32_t BakaShrot_GetMessagesW(const uint16_t *topic, /** * How many messages the last `GetMessages` or `GetLatestMessageOf` got. */ -int32_t BakaShrot_GetMessageCount(void); +int32_t BakaShrot_GetMessageCount(int64_t client); /** * Selects the message at `index` (0 to the count - 1) for the getters: 0 * if there's none there (`InvalidArgument`), the selection unchanged. */ -ptrdiff_t BakaShrot_SelectMessage(int32_t index); +ptrdiff_t BakaShrot_SelectMessage(int64_t client, int32_t index); /** * 1 if more messages follow the last one the last `GetMessages` got: ask * again after its id. */ -ptrdiff_t BakaShrot_HasMoreMessages(void); +ptrdiff_t BakaShrot_HasMoreMessages(int64_t client); /** * The selected message's id, 0 if none. */ -int64_t BakaShrot_GetMessageId(void); +int64_t BakaShrot_GetMessageId(int64_t client); /** * When the selected message was pushed, by the server it was pushed to: * milliseconds since 1970-01-01 UTC, 0 if none. */ -int64_t BakaShrot_GetMessagePushedAt(void); +int64_t BakaShrot_GetMessagePushedAt(int64_t client); /** * The selected message's attachment's size, 0 without one. */ -int64_t BakaShrot_GetMessageAttachmentSize(void); +int64_t BakaShrot_GetMessageAttachmentSize(int64_t client); /** * 1 if the selected message's attachment is all on this server (a * replicated one may still be on its way). */ -ptrdiff_t BakaShrot_IsMessageAttachmentReady(void); +ptrdiff_t BakaShrot_IsMessageAttachmentReady(int64_t client); /** * The selected message's data, as pushed (JSON or not). */ -ptrdiff_t BakaShrot_GetMessageDataA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetMessageDataA(int64_t client, char *buffer, ptrdiff_t size); /** * The same as `BakaShrot_GetMessageDataA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetMessageDataW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetMessageDataW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * The topic the last `GetMessages` or `GetLatestMessageOf` asked for. */ -ptrdiff_t BakaShrot_GetMessageTopicA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetMessageTopicA(int64_t client, char *buffer, ptrdiff_t size); /** * The same as `BakaShrot_GetMessageTopicA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetMessageTopicW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetMessageTopicW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * The node the last `GetMessages` or `GetLatestMessageOf` asked for. */ -ptrdiff_t BakaShrot_GetMessageNodeA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetMessageNodeA(int64_t client, char *buffer, ptrdiff_t size); /** * The same as `BakaShrot_GetMessageNodeA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetMessageNodeW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetMessageNodeW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** - * Lists the topics with messages that this client may push to or read - * (every one if its roles have `list_topics` or `query`): how many, -1 on - * failure. Then `BakaShrot_GetNamesList()`. + * Lists topics (`kind` 1) or nodes (`kind` 2): the topics with messages + * that this client may push to or read (every one if its roles have + * `list_topics` or `query`), the nodes with messages in the topics it may + * read (every one with `list_nodes` or `query`). Only those of the topic + * and node pairs that `topics` and `nodes` match: each a name or a + * pattern (`sensors.*`), null for any. Every topic: 1, null, null; the + * topics a node pushed to: 1, null, the node; the nodes that pushed to a + * topic: 2, the topic, null. How many, -1 on failure. Then + * `BakaShrot_GetNamesListAsJson()`, or `BakaShrot_EnumerateNames()` + * instead. */ -int32_t BakaShrot_ListTopics(void); +int32_t BakaShrot_ListNamesA(int64_t client, int32_t kind, const char *topics, const char *nodes); /** - * Lists the nodes with messages in the topics this client may read (every - * one if its roles have `list_nodes` or `query`): how many, -1 on failure. Then - * `BakaShrot_GetNamesList()`. + * The same as `BakaShrot_ListNamesA`, in UTF-16. */ -int32_t BakaShrot_ListNodes(void); +int32_t BakaShrot_ListNamesW(int64_t client, + int32_t kind, + const uint16_t *topics, + const uint16_t *nodes); /** * The last list, as JSON: * `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated` * if some didn't fit. */ -ptrdiff_t BakaShrot_GetNamesListA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetNamesListAsJsonA(int64_t client, char *buffer, ptrdiff_t size); /** - * The same as `BakaShrot_GetNamesListA`, in UTF-16. + * The same as `BakaShrot_GetNamesListAsJsonA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetNamesListW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetNamesListAsJsonW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * Runs read-only SQL on the server (one SELECT or WITH), if this client - * may query. Then `BakaShrot_GetQueryResult()`. + * may query. Then `BakaShrot_GetQueryResultAsJson()`, or + * `BakaShrot_EnumerateQuery()` instead. */ -ptrdiff_t BakaShrot_QueryA(const char *sql); +ptrdiff_t BakaShrot_QueryA(int64_t client, const char *sql); /** * The same as `BakaShrot_QueryA`, in UTF-16. */ -ptrdiff_t BakaShrot_QueryW(const uint16_t *sql); +ptrdiff_t BakaShrot_QueryW(int64_t client, const uint16_t *sql); /** * The last query's result, as JSON: * `{"columns":[...],"rows":[[...],...]}`, every value a string or null. */ -ptrdiff_t BakaShrot_GetQueryResultA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetQueryResultAsJsonA(int64_t client, char *buffer, ptrdiff_t size); /** - * The same as `BakaShrot_GetQueryResultA`, in UTF-16. + * The same as `BakaShrot_GetQueryResultAsJsonA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetQueryResultW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetQueryResultAsJsonW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * Pushes a message with the file at `FilePath` as its attachment (1 byte @@ -280,12 +330,16 @@ ptrdiff_t BakaShrot_GetQueryResultW(uint16_t *buffer, ptrdiff_t size); * read twice (its SHA-256 first): one changed in between is refused * (`DataMismatch`). */ -int64_t BakaShrot_PushMessageWithFileA(const char *topic, const char *data, const char *file_path); +int64_t BakaShrot_PushMessageWithFileA(int64_t client, + const char *topic, + const char *data, + const char *file_path); /** * The same as `BakaShrot_PushMessageWithFileA`, in UTF-16. */ -int64_t BakaShrot_PushMessageWithFileW(const uint16_t *topic, +int64_t BakaShrot_PushMessageWithFileW(int64_t client, + const uint16_t *topic, const uint16_t *data, const uint16_t *file_path); @@ -293,7 +347,8 @@ int64_t BakaShrot_PushMessageWithFileW(const uint16_t *topic, * Pushes a message with the `Size` bytes at `Data` as its attachment, as * `BakaShrot_PushMessageWithFileA` does. */ -int64_t BakaShrot_PushMessageWithDataA(const char *topic, +int64_t BakaShrot_PushMessageWithDataA(int64_t client, + const char *topic, const char *data, const void *attachment, int64_t size); @@ -301,7 +356,8 @@ int64_t BakaShrot_PushMessageWithDataA(const char *topic, /** * The same as `BakaShrot_PushMessageWithDataA`, in UTF-16. */ -int64_t BakaShrot_PushMessageWithDataW(const uint16_t *topic, +int64_t BakaShrot_PushMessageWithDataW(int64_t client, + const uint16_t *topic, const uint16_t *data, const void *attachment, int64_t size); @@ -313,7 +369,8 @@ int64_t BakaShrot_PushMessageWithDataW(const uint16_t *topic, * `NotReady` if it isn't on this server yet, `AttachmentMismatch`). A * failed one leaves no file. */ -int64_t BakaShrot_SaveAttachmentA(const char *topic, +int64_t BakaShrot_SaveAttachmentA(int64_t client, + const char *topic, const char *node, int64_t message_id, const char *file_path); @@ -321,7 +378,8 @@ int64_t BakaShrot_SaveAttachmentA(const char *topic, /** * The same as `BakaShrot_SaveAttachmentA`, in UTF-16. */ -int64_t BakaShrot_SaveAttachmentW(const uint16_t *topic, +int64_t BakaShrot_SaveAttachmentW(int64_t client, + const uint16_t *topic, const uint16_t *node, int64_t message_id, const uint16_t *file_path); @@ -331,24 +389,150 @@ int64_t BakaShrot_SaveAttachmentW(const uint16_t *topic, * memory, checked with its SHA-256 (`BakaShrot_SaveAttachmentA` for big * ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`. */ -int64_t BakaShrot_LoadAttachmentA(const char *topic, const char *node, int64_t message_id); +int64_t BakaShrot_LoadAttachmentA(int64_t client, + const char *topic, + const char *node, + int64_t message_id); /** * The same as `BakaShrot_LoadAttachmentA`, in UTF-16. */ -int64_t BakaShrot_LoadAttachmentW(const uint16_t *topic, const uint16_t *node, int64_t message_id); +int64_t BakaShrot_LoadAttachmentW(int64_t client, + const uint16_t *topic, + const uint16_t *node, + int64_t message_id); /** * Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if * `BufferSize` is enough: returns its size (0 if none), copies nothing if * it doesn't fit (a null `Buffer` asks for the size). */ -int64_t BakaShrot_GetAttachmentData(void *buffer, int64_t buffer_size); +int64_t BakaShrot_GetAttachmentData(int64_t client, void *buffer, int64_t buffer_size); /** * Frees what `BakaShrot_LoadAttachment()` read: 1. */ -ptrdiff_t BakaShrot_FreeAttachmentData(void); +ptrdiff_t BakaShrot_FreeAttachmentData(int64_t client); + +/** + * Closes an enumeration: 1, or 0 if it wasn't one. + */ +ptrdiff_t BakaShrot_CloseEnum(int64_t enumeration); + +/** + * Lists names as `BakaShrot_ListNames()` does (the same arguments), into + * an enumeration: its handle, 0 on failure (`BakaShrot_GetLastError(client)`). + * Then `BakaShrot_NextName()` and `BakaShrot_GetEnumName()`, and + * `BakaShrot_CloseEnum()`. Closed with its client by + * `BakaShrot_FreeClient()`. + */ +int64_t BakaShrot_EnumerateNamesA(int64_t client, + int32_t kind, + const char *topics, + const char *nodes); + +/** + * The same as `BakaShrot_EnumerateNamesA`, in UTF-16. + */ +int64_t BakaShrot_EnumerateNamesW(int64_t client, + int32_t kind, + const uint16_t *topics, + const uint16_t *nodes); + +/** + * Moves to the next name (the first, the first time): 1, 0 if there are + * no more, -1 if it isn't a names enumeration. + */ +ptrdiff_t BakaShrot_NextName(int64_t enumeration); + +/** + * The current name: the bytes it needs, 0 if there's none (before the + * first, past the last) or it isn't a names enumeration. + */ +ptrdiff_t BakaShrot_GetEnumNameA(int64_t enumeration, char *buffer, ptrdiff_t size); + +/** + * The same as `BakaShrot_GetEnumNameA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetEnumNameW(int64_t enumeration, uint16_t *buffer, ptrdiff_t size); + +/** + * How many names, -1 if it isn't a names enumeration. + */ +int32_t BakaShrot_GetNameCount(int64_t enumeration); + +/** + * Whether some names didn't fit in the server's answer: 1 or 0, -1 if it + * isn't a names enumeration. + */ +ptrdiff_t BakaShrot_IsNamesListTruncated(int64_t enumeration); + +/** + * Runs a query as `BakaShrot_Query()` does, into an enumeration: its + * handle, 0 on failure (`BakaShrot_GetLastError(client)`). Then + * `BakaShrot_GetQueryColumnCount()` and `GetQueryColumnName()`, + * `BakaShrot_NextQueryRow()` and `GetQueryValue()` / `IsQueryValueNull()`, + * and `BakaShrot_CloseEnum()`. Closed with its client by + * `BakaShrot_FreeClient()`. + */ +int64_t BakaShrot_EnumerateQueryA(int64_t client, const char *sql); + +/** + * The same as `BakaShrot_EnumerateQueryA`, in UTF-16. + */ +int64_t BakaShrot_EnumerateQueryW(int64_t client, const uint16_t *sql); + +/** + * How many columns, -1 if it isn't a query enumeration. + */ +int32_t BakaShrot_GetQueryColumnCount(int64_t enumeration); + +/** + * A column's name (`index` 0 to the count - 1): the bytes it needs, 0 if + * there's no such column or it isn't a query enumeration. + */ +ptrdiff_t BakaShrot_GetQueryColumnNameA(int64_t enumeration, + int32_t index, + char *buffer, + ptrdiff_t size); + +/** + * The same as `BakaShrot_GetQueryColumnNameA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetQueryColumnNameW(int64_t enumeration, + int32_t index, + uint16_t *buffer, + ptrdiff_t size); + +/** + * Moves to the next row (the first, the first time): 1, 0 if there are + * no more, -1 if it isn't a query enumeration. + */ +ptrdiff_t BakaShrot_NextQueryRow(int64_t enumeration); + +/** + * The current row's value in a column (`index` 0 to the count - 1): the + * bytes it needs, 0 if it's null (`BakaShrot_IsQueryValueNull()`), there's + * no current row or such column, or it isn't a query enumeration. + */ +ptrdiff_t BakaShrot_GetQueryValueA(int64_t enumeration, + int32_t index, + char *buffer, + ptrdiff_t size); + +/** + * The same as `BakaShrot_GetQueryValueA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetQueryValueW(int64_t enumeration, + int32_t index, + uint16_t *buffer, + ptrdiff_t size); + +/** + * Whether the current row's value in a column is null: 1 or 0, -1 if + * there's no current row or such column, or it isn't a query enumeration. + */ +ptrdiff_t BakaShrot_IsQueryValueNull(int64_t enumeration, int32_t index); #ifdef __cplusplus } // extern "C" diff --git a/bindings/csharp/NibblePoker.BakaShrot.Client.Tests/ClientTests.cs b/bindings/csharp/NibblePoker.BakaShrot.Client.Tests/ClientTests.cs new file mode 100644 index 0000000..750682b --- /dev/null +++ b/bindings/csharp/NibblePoker.BakaShrot.Client.Tests/ClientTests.cs @@ -0,0 +1,348 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Threading; +using NUnit.Framework; + +namespace NibblePoker.BakaShrot.Tests +{ + // Each test pushes to topics of its own: ids start at 1 in each. + public class ClientTests + { + [Test] + public void ConnectsFromAClientToml() + { + using Client kitchen = Server.Connect("kitchen"); + Assert.That(kitchen.Connected, Is.True); + Assert.That(kitchen.Node, Is.EqualTo("kitchen")); + Assert.That(kitchen.Port, Is.EqualTo(Server.Port)); + } + + [Test] + public void NothingYet() + { + using Client kitchen = Server.Connect("kitchen"); + kitchen.Push("nothing-other", "so kitchen has a message somewhere"); + Assert.That(kitchen.Latest("nothing", "kitchen"), Is.Null); + MessagesPage page = kitchen.GetMessages("nothing", "kitchen", 0, 1000); + Assert.That(page.Messages, Is.Empty); + Assert.That(page.More, Is.False); + Assert.That(page.LastId, Is.EqualTo(0)); + } + + [Test] + public void PushesAndPages() + { + using Client kitchen = Server.Connect("kitchen"); + List ids = Enumerable.Range(1, 250).Select(i => kitchen.Push("pages", "{\"i\":" + i + "}")).ToList(); + Assert.That(ids, Is.EqualTo(Enumerable.Range(1, 250).Select(i => (long)i))); + + Message latest = kitchen.Latest("pages", "kitchen"); + Assert.That(latest.Id, Is.EqualTo(250)); + Assert.That(latest.Data, Is.EqualTo("{\"i\":250}")); + Assert.That(latest.Pushed, Is.EqualTo(DateTime.UtcNow).Within(TimeSpan.FromMinutes(1))); + Assert.That(latest.Pushed.Kind, Is.EqualTo(DateTimeKind.Utc)); + + MessagesPage page = kitchen.GetMessages("pages", "kitchen", 0, 100); + Assert.That(page.Messages.Select(m => m.Id), Is.EqualTo(Enumerable.Range(1, 100).Select(i => (long)i))); + Assert.That(page.More, Is.True); + Assert.That(page.LastId, Is.EqualTo(100)); + Message first = page.Messages[0]; + Assert.That((first.Topic, first.Node, first.Data, first.AttachmentSize, first.AttachmentReady), + Is.EqualTo(("pages", "kitchen", "{\"i\":1}", 0L, false))); + Assert.That(page.Messages.Select(m => m.PushedAt), Is.Ordered); + + page = kitchen.GetMessages("pages", "kitchen", 150, 100); + Assert.That(page.Messages.Select(m => m.Id), Is.EqualTo(Enumerable.Range(151, 100).Select(i => (long)i))); + Assert.That(page.More, Is.False); + + page = kitchen.GetMessages("PAGES", "Kitchen", 250, 1000); + Assert.That(page.Messages, Is.Empty, "names in another case, after the last one"); + + Assert.That(kitchen.IterMessages("pages", "kitchen", 0).Select(m => m.Id), + Is.EqualTo(Enumerable.Range(1, 250).Select(i => (long)i))); + } + + [Test] + public void DataAsPushed() + { + using Client kitchen = Server.Connect("kitchen"); + string[] data = { "plain text, not JSON", "héllo wörld, 🌍, 日本語", "", "{\"a\":[1,2]}" }; + foreach (string one in data) + kitchen.Push("data", one); + Assert.That(kitchen.GetMessages("data", "kitchen", 0, 1000).Messages.Select(m => m.Data), Is.EqualTo(data)); + Assert.That(kitchen.Push("data", null!), Is.EqualTo(5), "null data is empty"); + } + + [Test] + public void AnswersSplitAtAboutOneMegabyte() + { + using Client kitchen = Server.Connect("kitchen"); + string big = new string('x', 700 * 1024); + long[] ids = { kitchen.Push("big", big), kitchen.Push("big", big), kitchen.Push("big", big) }; + MessagesPage page = kitchen.GetMessages("big", "kitchen", 0, 10); + Assert.That(page.Messages.Select(m => m.Id), Is.EqualTo(ids.Take(1))); + Assert.That(page.More, Is.True); + List every = kitchen.IterMessages("big", "kitchen", 0).ToList(); + Assert.That(every.Select(m => m.Id), Is.EqualTo(ids)); + Assert.That(every.All(m => m.Data == big), Is.True); + } + + [Test] + public void Refusals() + { + using Client kitchen = Server.Connect("kitchen"); + kitchen.Push("refusals", "x"); + + RefusedException refused = Assert.Throws(() => kitchen.GetMessages("refusals", "nobody", 0, 1000))!; + Assert.That(refused.Code, Is.EqualTo(ErrorCode.UnknownName)); + Assert.That(refused.Message, Does.Contain("nobody")); + Assert.That(kitchen.Connected, Is.True, "still connected after a refusal"); + + BakaShrotException error = Assert.Throws(() => kitchen.Push("a b", "x"))!; + Assert.That(error.Code, Is.EqualTo(ErrorCode.InvalidArgument)); + Assert.That(error.Message, Does.Contain("isn't a topic name")); + + error = Assert.Throws(() => kitchen.Push("refusals", "a\0b"))!; + Assert.That(error.Code, Is.EqualTo(ErrorCode.InvalidArgument), "a NUL would cut the message"); + + error = Assert.Throws(() => kitchen.GetMessages("refusals", "kitchen", 0, 0))!; + Assert.That(error.Code, Is.EqualTo(ErrorCode.InvalidArgument), "limit 0"); + error = Assert.Throws(() => kitchen.GetMessages("refusals", "kitchen", -1, 10))!; + Assert.That(error.Code, Is.EqualTo(ErrorCode.InvalidArgument), "after -1"); + + using Client lounge = Server.Connect("lounge"); + refused = Assert.Throws(() => lounge.Push("logs", "x"))!; + Assert.That(refused.Code, Is.EqualTo(ErrorCode.NotAllowed)); + refused = Assert.Throws(() => lounge.GetMessages("refusals", "kitchen", 0, 1000))!; + Assert.That(refused.Code, Is.EqualTo(ErrorCode.NotAllowed)); + refused = Assert.Throws(() => lounge.Query("SELECT 1"))!; + Assert.That(refused.Code, Is.EqualTo(ErrorCode.NotAllowed)); + Assert.That(kitchen.Connected && lounge.Connected, Is.True, "two clients at once"); + } + + [Test] + public void Queries() + { + using Client kitchen = Server.Connect("kitchen"); + kitchen.Push("query", "{\"t\":21}"); + kitchen.Push("query", "not JSON"); + Assert.That(kitchen.Query( + "SELECT is_json, COUNT(*) AS n FROM messages WHERE topic = 'query' GROUP BY is_json ORDER BY is_json"), + Is.EqualTo("{\"columns\":[\"is_json\",\"n\"],\"rows\":[[\"0\",\"1\"],[\"1\",\"1\"]]}")); + Assert.That(kitchen.Query("SELECT 'é🌍' AS q"), Does.Contain("é🌍"), "UTF-16 both ways"); + + RefusedException refused = Assert.Throws(() => kitchen.Query("SELECT nope FROM data"))!; + Assert.That(refused.Code, Is.EqualTo(ErrorCode.QueryFailed)); + } + + [Test] + public void Lists() + { + using Client kitchen = Server.Connect("kitchen"); + kitchen.Push("listed", "x"); + Assert.That(kitchen.ListTopics(), Does.StartWith("{\"kind\":\"topic\"").And.Contain("\"listed\"")); + Assert.That(kitchen.ListNodes(), Does.StartWith("{\"kind\":\"node\"").And.Contain("\"kitchen\"")); + + // Filtered: the topics a node pushed to, the nodes of a topic. + Assert.That(kitchen.ListTopics(null, "KITCHEN"), Does.Contain("\"listed\"")); + Assert.That(kitchen.ListNodes("list?d", null), Is.EqualTo("{\"kind\":\"node\",\"names\":[\"kitchen\"],\"truncated\":false}")); + Assert.That(kitchen.ListTopics(null, "nobody"), Is.EqualTo("{\"kind\":\"topic\",\"names\":[],\"truncated\":false}")); + BakaShrotException invalid = Assert.Catch(() => kitchen.ListNodes("a b", null))!; + Assert.That(invalid.Code, Is.EqualTo(ErrorCode.InvalidArgument)); + } + + [Test] + public void Enumerations() + { + using Client kitchen = Server.Connect("kitchen"); + kitchen.Push("enumerated", "x"); + kitchen.Push("enumerated", "y"); + Assert.That(kitchen.EnumerateTopics(), Does.Contain("enumerated")); + Assert.That(kitchen.EnumerateTopics(null, "KITCHEN"), Does.Contain("enumerated")); + Assert.That(kitchen.EnumerateNodes("enumer*", null), Is.EqualTo(new[] { "kitchen" })); + Assert.That(kitchen.EnumerateNodes("nothing", null), Is.Empty); + + // Rows: by index or column, NULL as null; asked again each time. + IEnumerable rows = kitchen.EnumerateQuery( + "SELECT message_data AS data, NULL AS missing, '' AS empty FROM messages WHERE topic = 'enumerated' ORDER BY message_id"); + for (int pass = 0; pass < 2; pass++) + { + List got = new List(rows); + Assert.That(got.Count, Is.EqualTo(2)); + Assert.That(got[0].Columns, Is.EqualTo(new[] { "data", "missing", "empty" })); + Assert.That(got[0]["data"], Is.EqualTo("x")); + Assert.That(got[1][0], Is.EqualTo("y")); + Assert.That(got[1]["missing"], Is.Null); + Assert.That(got[1]["empty"], Is.EqualTo("")); + Assert.Throws(() => { string _ = got[0]["nope"]; }); + } + Assert.That(kitchen.EnumerateQuery("SELECT 1 AS a WHERE 0"), Is.Empty); + + // Failures when the foreach starts; closing the client ends one. + IEnumerable bad = kitchen.EnumerateNodes("a b", null); + Assert.That(Assert.Catch(() => bad.GetEnumerator().MoveNext())!.Code, + Is.EqualTo(ErrorCode.InvalidArgument)); + Assert.That(Assert.Throws(() => new List(kitchen.EnumerateQuery("SELECT nope")))!.Code, + Is.EqualTo(ErrorCode.QueryFailed)); + using (IEnumerator topics = kitchen.EnumerateTopics().GetEnumerator()) + { + Assert.That(topics.MoveNext(), Is.True); + kitchen.Close(); + Assert.Throws(() => topics.MoveNext()); + } + } + + [Test] + public void Attachments() + { + using Client kitchen = Server.Connect("kitchen"); + byte[] blob = new byte[3 * 1024 * 1024 + 7]; + new Random(1).NextBytes(blob); + long blobId = kitchen.Push("files", "{\"kind\":\"blob\"}", blob); + Message message = kitchen.Latest("files", "kitchen"); + Assert.That((message.Id, message.AttachmentSize, message.AttachmentReady), + Is.EqualTo((blobId, blob.LongLength, true))); + Assert.That(kitchen.GetAttachment("files", "kitchen", blobId), Is.EqualTo(blob)); + + string source = Server.In("source.bin"); + byte[] contents = new byte[1500 * 1024]; + new Random(2).NextBytes(contents); + File.WriteAllBytes(source, contents); + long fileId = kitchen.PushFile("files", "from a file", source); + string copy = Server.In("copy.bin"); + Assert.That(kitchen.SaveAttachment("files", "kitchen", fileId, copy), Is.EqualTo(contents.Length)); + using (SHA256 sha = SHA256.Create()) + Assert.That(sha.ComputeHash(File.ReadAllBytes(copy)), Is.EqualTo(sha.ComputeHash(contents))); + + long plainId = kitchen.Push("files", "no attachment"); + RefusedException refused = Assert.Throws(() => kitchen.GetAttachment("files", "kitchen", plainId))!; + Assert.That(refused.Code, Is.EqualTo(ErrorCode.NotFound)); + string none = Server.In("none.bin"); + refused = Assert.Throws(() => kitchen.SaveAttachment("files", "kitchen", plainId, none))!; + Assert.That(refused.Code, Is.EqualTo(ErrorCode.NotFound)); + Assert.That(File.Exists(none), Is.False, "a failed one leaves no file"); + + BakaShrotException error = Assert.Throws(() => kitchen.Push("files", "x", new byte[0]))!; + Assert.That(error.Code, Is.EqualTo(ErrorCode.InvalidArgument)); + error = Assert.Throws(() => kitchen.PushFile("files", "x", Server.In("missing.bin")))!; + Assert.That(error.Code, Is.EqualTo(ErrorCode.FileError)); + Assert.That(error.Message, Does.Contain("missing.bin")); + Assert.That(kitchen.Connected, Is.True); + } + + [Test] + public void FollowsFromAnotherThread() + { + using Client kitchen = Server.Connect("kitchen"); + kitchen.Push("follow", "before"); + IEnumerable follow = kitchen.Follow("follow", "kitchen"); + List followed = new List(); + Exception? failed = null; + Thread thread = new Thread(() => + { + try + { + foreach (Message message in follow) + { + followed.Add(message); + if (followed.Count == 5) + return; + } + } + catch (Exception error) + { + failed = error; + } + }); + thread.Start(); + Thread.Sleep(300); + List ids = Enumerable.Range(0, 5).Select(i => kitchen.Push("follow", "{\"f\":" + i + "}")).ToList(); + Assert.That(thread.Join(10000), Is.True); + Assert.That(failed, Is.Null); + Assert.That(followed.Select(m => m.Id), Is.EqualTo(ids), "only the new ones"); + } + + [Test] + public void TwoClientsInTwoThreads() + { + using Client a = Server.Connect("kitchen"); + using Client b = Server.Connect("kitchen"); + List[] pushed = { new List(), new List() }; + Thread[] threads = new[] { a, b }.Select((client, index) => new Thread(() => + { + for (int n = 0; n < 30; n++) + pushed[index].Add(client.Push("threads", "{\"n\":" + n + "}")); + })).ToArray(); + foreach (Thread thread in threads) + thread.Start(); + foreach (Thread thread in threads) + Assert.That(thread.Join(30000), Is.True); + Assert.That(pushed[0].Concat(pushed[1]).OrderBy(id => id), Is.EqualTo(Enumerable.Range(1, 60).Select(i => (long)i))); + } + + [Test] + public void Closing() + { + Client kitchen = Server.Connect("kitchen"); + kitchen.Ping(); + Assert.That(kitchen.Connected, Is.True, "still connected after a ping"); + kitchen.Close(); + Assert.That(kitchen.Connected, Is.False); + ConnectionLostException lost = Assert.Throws(() => kitchen.Push("logs", "x"))!; + Assert.That(lost.Code, Is.EqualTo(ErrorCode.NotConnected)); + lost = Assert.Throws(() => kitchen.Ping())!; + Assert.That(lost.Code, Is.EqualTo(ErrorCode.NotConnected)); + kitchen.Connect(); + Assert.That(kitchen.Connected, Is.True, "connects again"); + kitchen.Dispose(); + Assert.That(kitchen.Connected, Is.False); + } + + [Test] + public void AnswerTimeouts() + { + const string forever = + "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n"; + using Client kitchen = Server.Connect("kitchen"); + Assert.That(kitchen.AnswerTimeoutMs, Is.EqualTo(Client.DefaultAnswerTimeoutMs)); + BakaShrotException refused = Assert.Throws(() => kitchen.AnswerTimeoutMs = 0)!; + Assert.That(refused.Code, Is.EqualTo(ErrorCode.InvalidArgument)); + kitchen.AnswerTimeoutMs = 300; + Assert.That(kitchen.Connected, Is.True, "set while connected"); + ConnectionLostException lost = Assert.Throws(() => kitchen.Query(forever))!; + Assert.That(lost.Code, Is.EqualTo(ErrorCode.ConnectionLost)); + Assert.That(kitchen.Connected, Is.False); + kitchen.Connect(); + Assert.That(kitchen.AnswerTimeoutMs, Is.EqualTo(300), "kept across connections"); + lost = Assert.Throws(() => kitchen.Query(forever))!; + Assert.That(lost.Code, Is.EqualTo(ErrorCode.ConnectionLost)); + } + + [Test] + public void Connecting() + { + string ca = File.ReadAllText(Server.In("ca.crt")); + string certificate = File.ReadAllText(Server.In("kitchen.crt")); + string key = File.ReadAllText(Server.In("kitchen.key")); + using (Client pem = new Client("127.0.0.1", Server.Port, ca, certificate, key, null).Connect()) + Assert.That(pem.Node, Is.EqualTo("kitchen"), "from PEM text"); + + ConnectionLostException lost = Assert.Throws(() => + new Client("127.0.0.1", 1, ca, certificate, key, null).Connect())!; + Assert.That(lost.Code, Is.EqualTo(ErrorCode.ConnectFailed)); + + AuthException auth = Assert.Throws(() => Server.Connect("guest"))!; + Assert.That(auth.Code, Is.EqualTo(ErrorCode.NotAllowed)); + + BakaShrotException error = Assert.Throws(() => + new Client("127.0.0.1", Server.Port, Server.In("missing.crt"), certificate, key, null).Connect())!; + Assert.That(error.Code, Is.EqualTo(ErrorCode.FileError)); + error = Assert.Throws(() => + new Client("127.0.0.1", Server.Port, ca, certificate, key, Server.In("missing.crl")).Connect())!; + Assert.That(error.Code, Is.EqualTo(ErrorCode.FileError), "a CRL given that isn't there"); + } + } +} diff --git a/bindings/csharp/NibblePoker.BakaShrot.Client.Tests/NibblePoker.BakaShrot.Client.Tests.csproj b/bindings/csharp/NibblePoker.BakaShrot.Client.Tests/NibblePoker.BakaShrot.Client.Tests.csproj new file mode 100644 index 0000000..456ef02 --- /dev/null +++ b/bindings/csharp/NibblePoker.BakaShrot.Client.Tests/NibblePoker.BakaShrot.Client.Tests.csproj @@ -0,0 +1,22 @@ + + + + + net48;net8.0 + net8.0 + latest + enable + false + + + + + + + + + + + + + diff --git a/bindings/csharp/NibblePoker.BakaShrot.Client.Tests/Server.cs b/bindings/csharp/NibblePoker.BakaShrot.Client.Tests/Server.cs new file mode 100644 index 0000000..5851208 --- /dev/null +++ b/bindings/csharp/NibblePoker.BakaShrot.Client.Tests/Server.cs @@ -0,0 +1,144 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using NUnit.Framework; + +namespace NibblePoker.BakaShrot.Tests +{ + /// A server for the tests, on a free port, in its own folder + /// under target/csharp-tests/ with its certificates: made with the + /// programs cargo built (target/debug, or BAKASHROT_BIN). + [SetUpFixture] + public class Server + { + public static string Folder = ""; + public static int Port; + private static Process? process; + + private static readonly bool Windows = Path.DirectorySeparatorChar == '\\'; + + [OneTimeSetUp] + public void Start() + { + string root = FindRepository(); + string bin = Environment.GetEnvironmentVariable("BAKASHROT_BIN") ?? Path.Combine(root, "target", "debug"); + string exe = Windows ? ".exe" : ""; + string library = Windows ? "bakashrot.dll" : "libbakashrot.so"; + if (!File.Exists(Path.Combine(bin, library))) + Assert.Fail($"No {library} in {bin}: cargo build first (or set BAKASHROT_BIN)"); + // Before any call into it: DllImport finds it next to the tests. + File.Copy(Path.Combine(bin, library), Path.Combine(TestContext.CurrentContext.TestDirectory, library), true); + + Folder = Path.Combine(root, "target", "csharp-tests", Process.GetCurrentProcess().Id.ToString()); + if (Directory.Exists(Folder)) + Directory.Delete(Folder, true); + Directory.CreateDirectory(Folder); + + string tool = Path.Combine(bin, "bakashrot" + exe); + Run(tool, "cert ca --name test-ca"); + Run(tool, "cert issue --server --name server-1"); + Run(tool, "cert issue --name kitchen --role home"); + Run(tool, "cert issue --name lounge --role lounge"); + Run(tool, "cert issue --name guest --role guest"); + + TcpListener listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + Port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + File.WriteAllText(Path.Combine(Folder, "server.toml"), $@"[server] +listen = ""127.0.0.1:{Port}"" +ca = ""ca.crt"" +certificate = ""server-1.crt"" +key = ""server-1.key"" +database = ""bakashrot.sqlite"" + +[roles.home] +push_topics = [""*""] +read_topics = [""*""] +query = true + +[roles.lounge] +read_topics = [""logs""] +"); + + process = Process.Start(new ProcessStartInfo(Path.Combine(bin, "bakashrot-server" + exe), "server.toml") + { + WorkingDirectory = Folder, + UseShellExecute = false, + CreateNoWindow = true, + }); + DateTime until = DateTime.UtcNow.AddSeconds(15); + while (true) + { + if (process!.HasExited) + Assert.Fail($"bakashrot-server exited ({process.ExitCode})"); + try + { + using (TcpClient client = new TcpClient()) + { + client.Connect(IPAddress.Loopback, Port); + return; + } + } + catch (SocketException) + { + if (DateTime.UtcNow > until) + Assert.Fail("bakashrot-server isn't listening after 15 s"); + Thread.Sleep(100); + } + } + } + + [OneTimeTearDown] + public void Stop() + { + if (process != null && !process.HasExited) + { + process.Kill(); + process.WaitForExit(10000); + } + try + { + Directory.Delete(Folder, true); + } + catch (IOException) + { + } + } + + public static string In(string name) => Path.Combine(Folder, name); + + public static Client Connect(string name) => + new Client("127.0.0.1", Port, In("ca.crt"), In(name + ".crt"), In(name + ".key"), null).Connect(); + + private static void Run(string exe, string arguments) + { + using Process run = Process.Start(new ProcessStartInfo(exe, arguments) + { + WorkingDirectory = Folder, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + })!; + string output = run.StandardOutput.ReadToEnd() + run.StandardError.ReadToEnd(); + run.WaitForExit(); + if (run.ExitCode != 0) + Assert.Fail($"{Path.GetFileName(exe)} {arguments}: {output}"); + } + + // The folder with Cargo.toml, above the tests' build folder. + private static string FindRepository() + { + DirectoryInfo? folder = new DirectoryInfo(TestContext.CurrentContext.TestDirectory); + while (folder != null && !File.Exists(Path.Combine(folder.FullName, "Cargo.toml"))) + folder = folder.Parent; + if (folder == null) + Assert.Fail("No Cargo.toml above " + TestContext.CurrentContext.TestDirectory); + return folder!.FullName; + } + } +} diff --git a/bindings/csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs b/bindings/csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs new file mode 100644 index 0000000..1944829 --- /dev/null +++ b/bindings/csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs @@ -0,0 +1,656 @@ +// BakaShrot client for C#, over the client library (bakashrot.dll, +// libbakashrot.so). One file, C# 2 and the .NET 2.0 class library only: +// .NET Framework 2.0 and 3.x up to the latest .NET. docs/client.md, "C#". +// +// using (Client client = new Client("10.0.0.2", 7000, "ca.crt", "kitchen.crt", "kitchen.key", null)) +// { +// client.Connect(); +// long id = client.Push("sensors", "{\"t\":21}"); +// foreach (Message message in client.IterMessages("sensors", client.Node, 0)) +// Console.WriteLine(message.Id + " " + message.Data); +// } +// +// The library goes next to the app, which must run 64-bit. Errors are +// exceptions with the library's ErrorCode: RefusedException (the server +// refused, still connected), ConnectionLostException (Connect() again), +// AuthException (a certificate or role refused when connecting), +// BakaShrotException (the rest). A Client's calls are serialized: it can be +// shared between threads, and several can be connected at once. + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; + +namespace NibblePoker.BakaShrot +{ + /// crates/bakashrot-proto/src/error.rs: 1-99 refused by the + /// server, 100 and up the client's own. + public enum ErrorCode + { + None = 0, + NotAllowed = 1, UnknownName = 2, NotFound = 3, NotReady = 4, TooBig = 5, + InvalidRequest = 7, DataMismatch = 8, QueryFailed = 9, ServerError = 10, QueryTimedOut = 11, + NotConnected = 100, ConnectFailed = 101, AuthRejected = 102, ServerNotVerified = 103, + ConnectionLost = 104, ProtocolError = 105, InvalidArgument = 106, FileError = 107, + AttachmentMismatch = 108, AlreadyConnected = 109, Internal = 110, VersionMismatch = 111 + } + + public class BakaShrotException : Exception + { + public readonly ErrorCode Code; + + public BakaShrotException(string message, ErrorCode code) : base(message) + { + Code = code; + } + } + + /// The server refused (codes 1-99), the connection still open: + /// Message is its reason. + public class RefusedException : BakaShrotException + { + public RefusedException(string reason, ErrorCode code) : base(reason, code) { } + } + + /// Not connected, unreachable, or the connection broke: + /// Connect() again. A push whose answer was lost may be stored. + public class ConnectionLostException : BakaShrotException + { + public ConnectionLostException(string message, ErrorCode code) : base(message, code) { } + } + + /// Connecting refused for good: a certificate either way, no + /// role allowed, another protocol version. + public class AuthException : BakaShrotException + { + public AuthException(string message, ErrorCode code) : base(message, code) { } + } + + /// A stored message, its data as pushed (JSON or not). + public sealed class Message + { + public long Id; + public string Topic, Node, Data; + /// Milliseconds since 1970-01-01 UTC, by the server it was pushed to. + public long PushedAt; + /// 0 without an attachment. + public long AttachmentSize; + /// All of the attachment is on this server. + public bool AttachmentReady; + + public DateTime Pushed + { + get { return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(PushedAt); } + } + } + + /// One answer of GetMessages(): More if more follow LastId. + public sealed class MessagesPage + { + public List Messages = new List(); + public bool More; + + /// The last message's id, 0 if none. + public long LastId + { + get { return Messages.Count == 0 ? 0 : Messages[Messages.Count - 1].Id; } + } + } + + /// A row of EnumerateQuery(): its values (null for NULL), by + /// index or column name. + public sealed class QueryRow + { + /// The query's columns, the same array for every row. + public readonly string[] Columns; + public readonly string[] Values; + + internal QueryRow(string[] columns, string[] values) + { + Columns = columns; + Values = values; + } + + public string this[int column] + { + get { return Values[column]; } + } + + /// The first column with that name (as the query wrote it). + public string this[string column] + { + get + { + int index = Array.IndexOf(Columns, column); + if (index < 0) + throw new ArgumentException("No column " + column, "column"); + return Values[index]; + } + } + } + + public sealed class Client : IDisposable + { + public readonly string Host, Ca, Certificate, Key, Crl; + public readonly int Port; + private readonly object sync = new object(); + private string node = ""; + private int answerTimeoutMs = DefaultAnswerTimeoutMs; + private long handle; // its client in the library, 0 before Connect() and after Close() + + /// host: a name or an address. The certificates and the CRL + /// (null for none): PEM text or a file's path. + public Client(string host, int port, string ca, string certificate, string key, string crl) + { + Host = host; + Port = port; + Ca = ca; + Certificate = certificate; + Key = key; + Crl = crl; + } + + /// The node the server says this client is, once connected. + public string Node { get { return node; } } + + public bool Connected + { + get { lock (sync) return handle != 0 && Native.BakaShrot_IsConnected(handle) != IntPtr.Zero; } + } + + public Client Connect() + { + lock (sync) + { + if (handle == 0 && (handle = Native.BakaShrot_CreateClient()) == 0) + throw new BakaShrotException("The library made no client", ErrorCode.Internal); + if (Native.BakaShrot_IsConnected(handle) != IntPtr.Zero) + return this; + Check(Native.BakaShrot_SetAnswerTimeout(handle, answerTimeoutMs), "AnswerTimeoutMs"); + Check(Native.BakaShrot_SetCaCertificateW(handle, Text(Ca)), "Certificates"); + Check(Native.BakaShrot_SetCertificateW(handle, Text(Certificate)), "Certificates"); + Check(Native.BakaShrot_SetPrivateKeyW(handle, Text(Key)), "Certificates"); + Check(Native.BakaShrot_SetCrlW(handle, Text(Crl ?? "")), "Certificates"); + if (Native.BakaShrot_ConnectW(handle, Text(Host), Port) == IntPtr.Zero) + throw Failed("Connect to " + Host + ":" + Port, true); + node = GetString(Native.BakaShrot_GetNodeW); + return this; + } + } + + /// Disconnects and frees its client in the library; Connect() reconnects. + public void Close() + { + lock (sync) + { + if (handle != 0) + Native.BakaShrot_FreeClient(handle); + handle = 0; + } + } + + public void Dispose() + { + Close(); + GC.SuppressFinalize(this); + } + + ~Client() + { + if (handle != 0) + Native.BakaShrot_FreeClient(handle); + } + + /// Keeps the connection open: the server closes one silent + /// for 5 min. An app waiting longer between requests calls it every + /// minute or so (KeepAliveMs); Follow() does it itself. + public void Ping() + { + lock (sync) + Check(Native.BakaShrot_Ping(Handle()), "Ping"); + } + + /// How often to Ping() while waiting between requests, in ms. + public const int KeepAliveMs = 60000; + + /// AnswerTimeoutMs until changed. + public const int DefaultAnswerTimeoutMs = 30000; + + /// How long an answer may take, in ms (more than 0): longer + /// for a slow query, say. Past it, the request throws + /// ConnectionLostException and the connection is closed (the server + /// stops the query it was running then). Kept across connections. + public int AnswerTimeoutMs + { + get { lock (sync) return answerTimeoutMs; } + set + { + if (value <= 0) + throw new BakaShrotException("An answer timeout of " + value + " ms: more than 0", + ErrorCode.InvalidArgument); + lock (sync) + { + if (handle != 0) + Check(Native.BakaShrot_SetAnswerTimeout(handle, value), "AnswerTimeoutMs"); + answerTimeoutMs = value; + } + } + } + + /// Pushes data (JSON or not) to topic, as this client's node: its id. + public long Push(string topic, string data) + { + lock (sync) + return Id(Native.BakaShrot_PushMessageToW(Handle(), Text(topic), Text(data ?? "")), "Push"); + } + + /// With an attachment (1 byte and up): the message is stored once all of it came. + public long Push(string topic, string data, byte[] attachment) + { + lock (sync) + return Id(Native.BakaShrot_PushMessageWithDataW(Handle(), Text(topic), Text(data ?? ""), attachment, + attachment == null ? 0 : attachment.LongLength), "Push"); + } + + /// With the file at path as its attachment, read a part at a time. + public long PushFile(string topic, string data, string path) + { + lock (sync) + return Id(Native.BakaShrot_PushMessageWithFileW(Handle(), Text(topic), Text(data ?? ""), Text(path)), "Push"); + } + + /// The latest message of topic and node, null if none yet. + public Message Latest(string topic, string node) + { + lock (sync) + { + if (Native.BakaShrot_GetLatestMessageOfW(Handle(), Text(topic), Text(node)) != IntPtr.Zero) + return Current(); + BakaShrotException error = Failed("Latest message", false); + if (error.Code == ErrorCode.NotFound) + return null; + throw error; + } + } + + /// The messages of topic and node after id after (0 for the + /// first), in order: limit at most (1-10000), fewer past about 1 MB. + public MessagesPage GetMessages(string topic, string node, long after, int limit) + { + lock (sync) + { + int count = Native.BakaShrot_GetMessagesW(Handle(), Text(topic), Text(node), after, limit); + if (count < 0) + throw Failed("Get messages", false); + MessagesPage page = new MessagesPage(); + for (int index = 0; index < count; index++) + { + Native.BakaShrot_SelectMessage(handle, index); + page.Messages.Add(Current()); + } + page.More = Native.BakaShrot_HasMoreMessages(handle) != IntPtr.Zero; + return page; + } + } + + /// Every message of topic and node after id after, until there are no more. + public IEnumerable IterMessages(string topic, string node, long after) + { + MessagesPage page; + do + { + page = GetMessages(topic, node, after, 1000); + foreach (Message message in page.Messages) + yield return message; + after = Math.Max(after, page.LastId); + } while (page.More); + } + + /// The messages pushed from now on, as Follow(topic, node, after, 500) does. + public IEnumerable Follow(string topic, string node) + { + Message latest = Latest(topic, node); + return Follow(topic, node, latest == null ? 0 : latest.Id, 500); + } + + /// Every message after id after, then new ones as they + /// come, checking every intervalMs (pinging every minute meanwhile + /// if it's longer): forever, stop enumerating to stop. Nothing + /// reconnects by itself. + public IEnumerable Follow(string topic, string node, long after, int intervalMs) + { + while (true) + { + MessagesPage page = GetMessages(topic, node, after, 1000); + foreach (Message message in page.Messages) + yield return message; + after = Math.Max(after, page.LastId); + if (!page.More) + Wait(intervalMs); + } + } + + /// A message's attachment, in memory (SaveAttachment() for + /// big ones), checked with its SHA-256. + public byte[] GetAttachment(string topic, string node, long messageId) + { + lock (sync) + { + long size = Id(Native.BakaShrot_LoadAttachmentW(Handle(), Text(topic), Text(node), messageId), "Attachment"); + try + { + byte[] data = new byte[size]; + Native.BakaShrot_GetAttachmentData(handle, data, size); + return data; + } + finally + { + Native.BakaShrot_FreeAttachmentData(handle); + } + } + } + + /// Saves a message's attachment as the file at path + /// (replaced), checked with its SHA-256: its size. A failed one + /// leaves no file. + public long SaveAttachment(string topic, string node, long messageId, string path) + { + lock (sync) + return Id(Native.BakaShrot_SaveAttachmentW(Handle(), Text(topic), Text(node), messageId, Text(path)), "Attachment"); + } + + /// The topics with messages that this client may push to or + /// read, as JSON: {"kind":"topic","truncated":false,"names":[...]}. + public string ListTopics() + { + return ListTopics(null, null); + } + + /// ListTopics(), only those of the topic and node pairs that + /// topic and node match, each a name or a pattern ("sensors.*"), null + /// for any: ListTopics(null, "kitchen") is the topics kitchen pushed to. + public string ListTopics(string topic, string node) + { + lock (sync) + return Names(Native.BakaShrot_ListNamesW(Handle(), 1, Text(topic), Text(node)), "List topics"); + } + + /// The nodes with messages in the topics this client may + /// read, as ListTopics() says them. + public string ListNodes() + { + return ListNodes(null, null); + } + + /// ListNodes(), filtered as ListTopics(topic, node) is: + /// ListNodes("logs", null) is the nodes that pushed to logs. + public string ListNodes(string topic, string node) + { + lock (sync) + return Names(Native.BakaShrot_ListNamesW(Handle(), 2, Text(topic), Text(node)), "List nodes"); + } + + /// Runs one read-only SELECT or WITH: the server's JSON, + /// {"columns":[...],"rows":[[...],...]}. + public string Query(string sql) + { + lock (sync) + { + Check(Native.BakaShrot_QueryW(Handle(), Text(sql)), "Query"); + return GetString(Native.BakaShrot_GetQueryResultAsJsonW); + } + } + + /// The topics ListTopics() lists, one at a time, without + /// JSON. Asked once a foreach starts (each one asks again), closed + /// when it ends. + public IEnumerable EnumerateTopics() + { + return EnumerateNames(1, null, null); + } + + /// The topics ListTopics(topic, node) lists, as EnumerateTopics() gives them. + public IEnumerable EnumerateTopics(string topic, string node) + { + return EnumerateNames(1, topic, node); + } + + /// The nodes ListNodes() lists, as EnumerateTopics() gives them. + public IEnumerable EnumerateNodes() + { + return EnumerateNames(2, null, null); + } + + /// The nodes ListNodes(topic, node) lists, as EnumerateTopics() gives them. + public IEnumerable EnumerateNodes(string topic, string node) + { + return EnumerateNames(2, topic, node); + } + + /// Query(sql)'s rows, one at a time, without JSON. Asked + /// once a foreach starts (each one asks again), closed when it ends. + public IEnumerable EnumerateQuery(string sql) + { + long enumeration; + lock (sync) + enumeration = Opened(Native.BakaShrot_EnumerateQueryW(Handle(), Text(sql)), "Query"); + try + { + string[] columns = new string[Native.BakaShrot_GetQueryColumnCount(enumeration)]; + for (int column = 0; column < columns.Length; column++) + columns[column] = GetString(enumeration, ColumnGetter(Native.BakaShrot_GetQueryColumnNameW, column)); + while (Next(Native.BakaShrot_NextQueryRow(enumeration))) + { + string[] values = new string[columns.Length]; + for (int column = 0; column < values.Length; column++) + if (Native.BakaShrot_IsQueryValueNull(enumeration, column) == IntPtr.Zero) + values[column] = GetString(enumeration, ColumnGetter(Native.BakaShrot_GetQueryValueW, column)); + yield return new QueryRow(columns, values); + } + } + finally + { + Native.BakaShrot_CloseEnum(enumeration); + } + } + + // --- Inside --------------------------------------------------------- + + // Sleeps intervalMs, pinging every KeepAliveMs meanwhile. + private void Wait(int intervalMs) + { + int left = intervalMs; + while (true) + { + int step = Math.Min(left, KeepAliveMs); + Thread.Sleep(step); + left -= step; + if (left <= 0) + return; + Ping(); + } + } + + private IEnumerable EnumerateNames(int kind, string topic, string node) + { + long enumeration; + lock (sync) + enumeration = Opened(Native.BakaShrot_EnumerateNamesW(Handle(), kind, Text(topic), Text(node)), + kind == 1 ? "List topics" : "List nodes"); + try + { + while (Next(Native.BakaShrot_NextName(enumeration))) + yield return GetString(enumeration, Native.BakaShrot_GetEnumNameW); + } + finally + { + Native.BakaShrot_CloseEnum(enumeration); + } + } + + // An enumeration's handle, 0 on failure. + private long Opened(long enumeration, string what) + { + if (enumeration == 0) + throw Failed(what, false); + return enumeration; + } + + // A Next...(): 1 an item, 0 no more, -1 closed (with its client, by Close()). + private static bool Next(IntPtr result) + { + if (result.ToInt64() < 0) + throw new ConnectionLostException("The client was closed while enumerating", ErrorCode.NotConnected); + return result != IntPtr.Zero; + } + + private long Handle() + { + if (handle == 0) + throw new ConnectionLostException("Not connected", ErrorCode.NotConnected); + return handle; + } + + private Message Current() + { + Message message = new Message(); + message.Id = Native.BakaShrot_GetMessageId(handle); + message.Topic = GetString(Native.BakaShrot_GetMessageTopicW); + message.Node = GetString(Native.BakaShrot_GetMessageNodeW); + message.Data = GetString(Native.BakaShrot_GetMessageDataW); + message.PushedAt = Native.BakaShrot_GetMessagePushedAt(handle); + message.AttachmentSize = Native.BakaShrot_GetMessageAttachmentSize(handle); + message.AttachmentReady = Native.BakaShrot_IsMessageAttachmentReady(handle) != IntPtr.Zero; + return message; + } + + private string Names(int count, string what) + { + if (count < 0) + throw Failed(what, false); + return GetString(Native.BakaShrot_GetNamesListAsJsonW); + } + + // Strings go as UTF-16: one with a NUL would be cut there. + private static string Text(string value) + { + if (value != null && value.IndexOf('\0') >= 0) + throw new BakaShrotException("A string with a NUL character", ErrorCode.InvalidArgument); + return value; + } + + private delegate IntPtr Getter(long handle, byte[] buffer, IntPtr size); + private delegate IntPtr IndexGetter(long handle, int index, byte[] buffer, IntPtr size); + + private string GetString(Getter getter) + { + return GetString(handle, getter); + } + + // A string getter, of a client or an enumeration: the size first + // (bytes, the terminator included), then the copy. + private static string GetString(long from, Getter getter) + { + int size = getter(from, null, IntPtr.Zero).ToInt32(); + if (size <= 2) + return ""; + byte[] buffer = new byte[size]; + getter(from, buffer, new IntPtr(size)); + return Encoding.Unicode.GetString(buffer, 0, size - 2); + } + + // A column's getter, as a string getter. + private static Getter ColumnGetter(IndexGetter getter, int column) + { + return delegate(long from, byte[] buffer, IntPtr size) { return getter(from, column, buffer, size); }; + } + + private void Check(IntPtr result, string what) + { + if (result == IntPtr.Zero) + throw Failed(what, false); + } + + // An id or a size, -1 on failure. + private long Id(long result, string what) + { + if (result < 0) + throw Failed(what, false); + return result; + } + + private BakaShrotException Failed(string what, bool connecting) + { + ErrorCode code = (ErrorCode)Native.BakaShrot_GetLastError(handle); + string reason = GetString(Native.BakaShrot_GetRefusalReasonW); + if (connecting && (code == ErrorCode.AuthRejected || code == ErrorCode.ServerNotVerified + || code == ErrorCode.NotAllowed || code == ErrorCode.VersionMismatch)) + return new AuthException(what + ": " + reason, code); + if ((int)code >= 1 && (int)code <= 99) + return new RefusedException(reason, code); + string message = what + " (" + code + "): " + reason; + if (code == ErrorCode.NotConnected || code == ErrorCode.ConnectFailed || code == ErrorCode.ConnectionLost + || code == ErrorCode.ProtocolError) + return new ConnectionLostException(message, code); + return new BakaShrotException(message, code == ErrorCode.None ? ErrorCode.Internal : code); + } + + } + + // The library's exports used here, the W ones (UTF-16): bindings/c/bakashrot.h. + // ptrdiff_t is IntPtr, int64_t long, int32_t int. No calling convention: + // the library is 64-bit only, where there's one. + internal static class Native + { + private const string Dll = "bakashrot"; + private const CharSet Utf16 = CharSet.Unicode; + + [DllImport(Dll, ExactSpelling = true)] internal static extern long BakaShrot_CreateClient(); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_FreeClient(long client); + [DllImport(Dll, ExactSpelling = true)] internal static extern int BakaShrot_GetLastError(long client); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_GetRefusalReasonW(long client, byte[] buffer, IntPtr size); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_SetCaCertificateW(long client, string certificate); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_SetCertificateW(long client, string certificate); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_SetPrivateKeyW(long client, string key); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_SetCrlW(long client, string crl); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_ConnectW(long client, string host, int port); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_IsConnected(long client); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_Ping(long client); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_SetAnswerTimeout(long client, long milliseconds); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_GetNodeW(long client, byte[] buffer, IntPtr size); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern long BakaShrot_PushMessageToW(long client, string topic, string data); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_GetLatestMessageOfW(long client, string topic, string node); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern int BakaShrot_GetMessagesW(long client, string topic, string node, long after, int limit); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_SelectMessage(long client, int index); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_HasMoreMessages(long client); + [DllImport(Dll, ExactSpelling = true)] internal static extern long BakaShrot_GetMessageId(long client); + [DllImport(Dll, ExactSpelling = true)] internal static extern long BakaShrot_GetMessagePushedAt(long client); + [DllImport(Dll, ExactSpelling = true)] internal static extern long BakaShrot_GetMessageAttachmentSize(long client); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_IsMessageAttachmentReady(long client); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_GetMessageDataW(long client, byte[] buffer, IntPtr size); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_GetMessageTopicW(long client, byte[] buffer, IntPtr size); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_GetMessageNodeW(long client, byte[] buffer, IntPtr size); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern int BakaShrot_ListNamesW(long client, int kind, string topics, string nodes); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_GetNamesListAsJsonW(long client, byte[] buffer, IntPtr size); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern IntPtr BakaShrot_QueryW(long client, string sql); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_GetQueryResultAsJsonW(long client, byte[] buffer, IntPtr size); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern long BakaShrot_EnumerateNamesW(long client, int kind, string topics, string nodes); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_NextName(long enumeration); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_GetEnumNameW(long enumeration, byte[] buffer, IntPtr size); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern long BakaShrot_EnumerateQueryW(long client, string sql); + [DllImport(Dll, ExactSpelling = true)] internal static extern int BakaShrot_GetQueryColumnCount(long enumeration); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_GetQueryColumnNameW(long enumeration, int index, byte[] buffer, IntPtr size); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_NextQueryRow(long enumeration); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_GetQueryValueW(long enumeration, int index, byte[] buffer, IntPtr size); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_IsQueryValueNull(long enumeration, int index); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_CloseEnum(long enumeration); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern long BakaShrot_PushMessageWithFileW(long client, string topic, string data, string filePath); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern long BakaShrot_PushMessageWithDataW(long client, string topic, string data, byte[] attachment, long size); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern long BakaShrot_SaveAttachmentW(long client, string topic, string node, long messageId, string filePath); + [DllImport(Dll, ExactSpelling = true, CharSet = Utf16)] internal static extern long BakaShrot_LoadAttachmentW(long client, string topic, string node, long messageId); + [DllImport(Dll, ExactSpelling = true)] internal static extern long BakaShrot_GetAttachmentData(long client, byte[] buffer, long bufferSize); + [DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_FreeAttachmentData(long client); + } +} diff --git a/bindings/csharp/NibblePoker.BakaShrot.Client/NibblePoker.BakaShrot.Client.csproj b/bindings/csharp/NibblePoker.BakaShrot.Client/NibblePoker.BakaShrot.Client.csproj new file mode 100644 index 0000000..574c68b --- /dev/null +++ b/bindings/csharp/NibblePoker.BakaShrot.Client/NibblePoker.BakaShrot.Client.csproj @@ -0,0 +1,42 @@ + + + + + net35;netstandard2.0 + ISO-2 + NibblePoker.BakaShrot + true + + + + + 0.4.0 + Herwin Bozet (NibblePoker) + BakaShrot's client: a message store with replication. Over the client library, its Windows and Linux x64 and ARM64 builds included; .NET Framework 2.0 and up, .NET Core, .NET. + CC0-1.0 + https://github.com/aziascreations/BakaShrot + https://github.com/aziascreations/BakaShrot + bakashrot;messages;replication;sqlite + + + + + + + + + + + + + + + + + + diff --git a/bindings/csharp/NibblePoker.BakaShrot.Client/NibblePoker.BakaShrot.Client.targets b/bindings/csharp/NibblePoker.BakaShrot.Client/NibblePoker.BakaShrot.Client.targets new file mode 100644 index 0000000..8081d17 --- /dev/null +++ b/bindings/csharp/NibblePoker.BakaShrot.Client/NibblePoker.BakaShrot.Client.targets @@ -0,0 +1,13 @@ + + + + win-arm64 + win-x64 + + + + + diff --git a/bindings/purebasic/BakaShrot_Client_Prototypes.pbi b/bindings/purebasic/BakaShrot_Client_Prototypes.pbi index 1308748..59a36c7 100644 --- a/bindings/purebasic/BakaShrot_Client_Prototypes.pbi +++ b/bindings/purebasic/BakaShrot_Client_Prototypes.pbi @@ -1,12 +1,13 @@ ;{- Code Header ; ==- Basic Info -================================ ; Name: BakaShrot_Client_Prototypes.pbi -; Version: 0.0.1 +; Version: 0.4.0 ; Author: Herwin Bozet (NibblePoker) ; ; ==- Compatibility -============================= ; Tested compiler versions: ; * PureBasic 5.73 LTS (Windows x64) +; * PureBasic 6.41 (Windows x64) ; ; ==- Links -===================================== ; GitHub: https://github.com/aziascreations/BakaShrot @@ -18,65 +19,94 @@ ; Include this in an app to use bakashrot.dll (libbakashrot.so on Linux): ; XIncludeFile "BakaShrot_Client_Prototypes.pbi" ; If BakaShrot_LoadClient("bakashrot.dll") -; BakaShrot_SetCaCertificate("ca.crt") ; a file, or PEM text -; BakaShrot_SetCertificate("kitchen.crt") -; BakaShrot_SetPrivateKey("kitchen.key") -; If BakaShrot_Connect("10.0.0.2", 7000) -; BakaShrot_PushMessageTo("logs", ~"{\"temp\": 21}") +; Client = BakaShrot_CreateClient() +; BakaShrot_SetCaCertificate(Client, "ca.crt") ; a file, or PEM text +; BakaShrot_SetCertificate(Client, "kitchen.crt") +; BakaShrot_SetPrivateKey(Client, "kitchen.key") +; If BakaShrot_Connect(Client, "10.0.0.2", 7000) +; BakaShrot_PushMessageTo(Client, "logs", ~"{\"temp\": 21}") ; ... ; EndIf +; BakaShrot_FreeClient(Client) ; BakaShrot_UnloadClient() ; EndIf ; +; Every function but BakaShrot_CreateClient() takes the client first (a +; quad). Make as many as needed: each has its own connection and errors. +; ; docs/client.md has what each function does (and ; bindings/c/bakashrot.h, generated from the DLL). The string ; functions are mapped to the DLL's W (UTF-16) variants. After a failed -; call, BakaShrot_GetLastError() tells why: the codes and what to do about -; each are in BakaShrot_ErrorCodes.pbi, next to this file (included below), -; BakaShrot_ErrorName() names them; BakaShrot_GetRefusalReasonString() says -; why in words. _GetNamesList() is -; {"kind":"topic","names":[...],"truncated":false}. +; call, BakaShrot_GetLastError(Client) tells why: the codes and what to do +; about each are in BakaShrot_ErrorCodes.pbi, next to this file (included +; below), BakaShrot_ErrorName() names them; +; BakaShrot_GetRefusalReasonString(Client) says why in words. +; _GetNamesListAsJson() is {"kind":"topic","names":[...],"truncated":false}. +; _GetQueryResultAsJson() is {"columns":[...],"rows":[[...],...]}. +; Without JSON: _EnumerateNames() / _EnumerateQuery() give an enumeration +; (a quad, like a client's handle); _NextName() / _NextQueryRow() move to +; the next item (the first, the first time: While ... = 1), the getters +; read it, _CloseEnum() closes it (_FreeClient() closes its client's). ; ============================================================================ XIncludeFile "BakaShrot_ErrorCodes.pbi" -PrototypeC.l BakaShrot_GetLastError_Prototype() -PrototypeC.i BakaShrot_GetRefusalReason_Prototype(*Buffer, BufferSize.i) -PrototypeC.i BakaShrot_SetCaCertificate_Prototype(Certificate.p-unicode) -PrototypeC.i BakaShrot_SetCertificate_Prototype(Certificate.p-unicode) -PrototypeC.i BakaShrot_SetPrivateKey_Prototype(PrivateKey.p-unicode) -PrototypeC.i BakaShrot_SetCrl_Prototype(Crl.p-unicode) -PrototypeC.i BakaShrot_Connect_Prototype(Host.p-unicode, Port.l) -PrototypeC.i BakaShrot_IsConnected_Prototype() -PrototypeC.i BakaShrot_Disconnect_Prototype() -PrototypeC.i BakaShrot_GetNode_Prototype(*Buffer, BufferSize.i) -PrototypeC.q BakaShrot_PushMessageTo_Prototype(Topic.p-unicode, JsonData.p-unicode) -PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Topic.p-unicode, Node.p-unicode) -PrototypeC.l BakaShrot_GetMessages_Prototype(Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l) -PrototypeC.l BakaShrot_GetMessageCount_Prototype() -PrototypeC.i BakaShrot_SelectMessage_Prototype(Index.l) -PrototypeC.i BakaShrot_HasMoreMessages_Prototype() -PrototypeC.q BakaShrot_GetMessageId_Prototype() -PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype() -PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype() -PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype() -PrototypeC.i BakaShrot_GetMessageData_Prototype(*Buffer, BufferSize.i) -PrototypeC.i BakaShrot_GetMessageTopic_Prototype(*Buffer, BufferSize.i) -PrototypeC.i BakaShrot_GetMessageNode_Prototype(*Buffer, BufferSize.i) -PrototypeC.l BakaShrot_ListTopics_Prototype() -PrototypeC.l BakaShrot_ListNodes_Prototype() -PrototypeC.i BakaShrot_GetNamesList_Prototype(*Buffer, BufferSize.i) -PrototypeC.i BakaShrot_Query_Prototype(Sql.p-unicode) -PrototypeC.i BakaShrot_GetQueryResult_Prototype(*Buffer, BufferSize.i) -PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode) -PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Topic.p-unicode, JsonData.p-unicode, *Data, Size.q) -PrototypeC.q BakaShrot_SaveAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode) -PrototypeC.q BakaShrot_LoadAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q) -PrototypeC.q BakaShrot_GetAttachmentData_Prototype(*Buffer, BufferSize.q) -PrototypeC.i BakaShrot_FreeAttachmentData_Prototype() +PrototypeC.q BakaShrot_CreateClient_Prototype() +PrototypeC.i BakaShrot_FreeClient_Prototype(Client.q) +PrototypeC.l BakaShrot_GetLastError_Prototype(Client.q) +PrototypeC.i BakaShrot_GetRefusalReason_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.i BakaShrot_SetCaCertificate_Prototype(Client.q, Certificate.p-unicode) +PrototypeC.i BakaShrot_SetCertificate_Prototype(Client.q, Certificate.p-unicode) +PrototypeC.i BakaShrot_SetPrivateKey_Prototype(Client.q, PrivateKey.p-unicode) +PrototypeC.i BakaShrot_SetCrl_Prototype(Client.q, Crl.p-unicode) +PrototypeC.i BakaShrot_Connect_Prototype(Client.q, Host.p-unicode, Port.l) +PrototypeC.i BakaShrot_IsConnected_Prototype(Client.q) +PrototypeC.i BakaShrot_Disconnect_Prototype(Client.q) +PrototypeC.i BakaShrot_Ping_Prototype(Client.q) +PrototypeC.i BakaShrot_SetAnswerTimeout_Prototype(Client.q, Milliseconds.q) +PrototypeC.q BakaShrot_GetAnswerTimeout_Prototype(Client.q) +PrototypeC.i BakaShrot_GetNode_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.q BakaShrot_PushMessageTo_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode) +PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Client.q, Topic.p-unicode, Node.p-unicode) +PrototypeC.l BakaShrot_GetMessages_Prototype(Client.q, Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l) +PrototypeC.l BakaShrot_GetMessageCount_Prototype(Client.q) +PrototypeC.i BakaShrot_SelectMessage_Prototype(Client.q, Index.l) +PrototypeC.i BakaShrot_HasMoreMessages_Prototype(Client.q) +PrototypeC.q BakaShrot_GetMessageId_Prototype(Client.q) +PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype(Client.q) +PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype(Client.q) +PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype(Client.q) +PrototypeC.i BakaShrot_GetMessageData_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.i BakaShrot_GetMessageTopic_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.i BakaShrot_GetMessageNode_Prototype(Client.q, *Buffer, BufferSize.i) +; Kind 1 topics, 2 nodes; Topics and Nodes a name or a pattern, "" for any. +PrototypeC.l BakaShrot_ListNames_Prototype(Client.q, Kind.l, Topics.p-unicode, Nodes.p-unicode) +PrototypeC.i BakaShrot_GetNamesListAsJson_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.i BakaShrot_Query_Prototype(Client.q, Sql.p-unicode) +PrototypeC.i BakaShrot_GetQueryResultAsJson_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.q BakaShrot_EnumerateNames_Prototype(Client.q, Kind.l, Topics.p-unicode, Nodes.p-unicode) +PrototypeC.i BakaShrot_NextName_Prototype(Enum.q) +PrototypeC.i BakaShrot_GetEnumName_Prototype(Enum.q, *Buffer, BufferSize.i) +PrototypeC.l BakaShrot_GetNameCount_Prototype(Enum.q) +PrototypeC.i BakaShrot_IsNamesListTruncated_Prototype(Enum.q) +PrototypeC.q BakaShrot_EnumerateQuery_Prototype(Client.q, Sql.p-unicode) +PrototypeC.l BakaShrot_GetQueryColumnCount_Prototype(Enum.q) +PrototypeC.i BakaShrot_GetQueryColumnName_Prototype(Enum.q, Index.l, *Buffer, BufferSize.i) +PrototypeC.i BakaShrot_NextQueryRow_Prototype(Enum.q) +PrototypeC.i BakaShrot_GetQueryValue_Prototype(Enum.q, Index.l, *Buffer, BufferSize.i) +PrototypeC.i BakaShrot_IsQueryValueNull_Prototype(Enum.q, Index.l) +PrototypeC.i BakaShrot_CloseEnum_Prototype(Enum.q) +PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode) +PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode, *Data, Size.q) +PrototypeC.q BakaShrot_SaveAttachment_Prototype(Client.q, Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode) +PrototypeC.q BakaShrot_LoadAttachment_Prototype(Client.q, Topic.p-unicode, Node.p-unicode, MessageId.q) +PrototypeC.q BakaShrot_GetAttachmentData_Prototype(Client.q, *Buffer, BufferSize.q) +PrototypeC.i BakaShrot_FreeAttachmentData_Prototype(Client.q) +Global BakaShrot_CreateClient.BakaShrot_CreateClient_Prototype +Global BakaShrot_FreeClient.BakaShrot_FreeClient_Prototype Global BakaShrot_GetLastError.BakaShrot_GetLastError_Prototype Global BakaShrot_GetRefusalReason.BakaShrot_GetRefusalReason_Prototype Global BakaShrot_SetCaCertificate.BakaShrot_SetCaCertificate_Prototype @@ -86,6 +116,9 @@ Global BakaShrot_SetCrl.BakaShrot_SetCrl_Prototype Global BakaShrot_Connect.BakaShrot_Connect_Prototype Global BakaShrot_IsConnected.BakaShrot_IsConnected_Prototype Global BakaShrot_Disconnect.BakaShrot_Disconnect_Prototype +Global BakaShrot_Ping.BakaShrot_Ping_Prototype +Global BakaShrot_SetAnswerTimeout.BakaShrot_SetAnswerTimeout_Prototype +Global BakaShrot_GetAnswerTimeout.BakaShrot_GetAnswerTimeout_Prototype Global BakaShrot_GetNode.BakaShrot_GetNode_Prototype Global BakaShrot_PushMessageTo.BakaShrot_PushMessageTo_Prototype Global BakaShrot_GetLatestMessageOf.BakaShrot_GetLatestMessageOf_Prototype @@ -100,11 +133,22 @@ Global BakaShrot_IsMessageAttachmentReady.BakaShrot_IsMessageAttachmentReady_Pro Global BakaShrot_GetMessageData.BakaShrot_GetMessageData_Prototype Global BakaShrot_GetMessageTopic.BakaShrot_GetMessageTopic_Prototype Global BakaShrot_GetMessageNode.BakaShrot_GetMessageNode_Prototype -Global BakaShrot_ListTopics.BakaShrot_ListTopics_Prototype -Global BakaShrot_ListNodes.BakaShrot_ListNodes_Prototype -Global BakaShrot_GetNamesList.BakaShrot_GetNamesList_Prototype +Global BakaShrot_ListNames.BakaShrot_ListNames_Prototype +Global BakaShrot_GetNamesListAsJson.BakaShrot_GetNamesListAsJson_Prototype Global BakaShrot_Query.BakaShrot_Query_Prototype -Global BakaShrot_GetQueryResult.BakaShrot_GetQueryResult_Prototype +Global BakaShrot_GetQueryResultAsJson.BakaShrot_GetQueryResultAsJson_Prototype +Global BakaShrot_EnumerateNames.BakaShrot_EnumerateNames_Prototype +Global BakaShrot_NextName.BakaShrot_NextName_Prototype +Global BakaShrot_GetEnumName.BakaShrot_GetEnumName_Prototype +Global BakaShrot_GetNameCount.BakaShrot_GetNameCount_Prototype +Global BakaShrot_IsNamesListTruncated.BakaShrot_IsNamesListTruncated_Prototype +Global BakaShrot_EnumerateQuery.BakaShrot_EnumerateQuery_Prototype +Global BakaShrot_GetQueryColumnCount.BakaShrot_GetQueryColumnCount_Prototype +Global BakaShrot_GetQueryColumnName.BakaShrot_GetQueryColumnName_Prototype +Global BakaShrot_NextQueryRow.BakaShrot_NextQueryRow_Prototype +Global BakaShrot_GetQueryValue.BakaShrot_GetQueryValue_Prototype +Global BakaShrot_IsQueryValueNull.BakaShrot_IsQueryValueNull_Prototype +Global BakaShrot_CloseEnum.BakaShrot_CloseEnum_Prototype Global BakaShrot_PushMessageWithFile.BakaShrot_PushMessageWithFile_Prototype Global BakaShrot_PushMessageWithData.BakaShrot_PushMessageWithData_Prototype Global BakaShrot_SaveAttachment.BakaShrot_SaveAttachment_Prototype @@ -151,40 +195,56 @@ Procedure.i BakaShrot_LoadClient(DllPath.s) BakaShrot_ClientMissing = "" ; PureBasic strings are UTF-16, so the W variants are used. - BakaShrot_GetLastError = BakaShrot_ClientFunction("BakaShrot_GetLastError") - BakaShrot_GetRefusalReason = BakaShrot_ClientFunction("BakaShrot_GetRefusalReasonW") - BakaShrot_SetCaCertificate = BakaShrot_ClientFunction("BakaShrot_SetCaCertificateW") - BakaShrot_SetCertificate = BakaShrot_ClientFunction("BakaShrot_SetCertificateW") - BakaShrot_SetPrivateKey = BakaShrot_ClientFunction("BakaShrot_SetPrivateKeyW") - BakaShrot_SetCrl = BakaShrot_ClientFunction("BakaShrot_SetCrlW") - BakaShrot_Connect = BakaShrot_ClientFunction("BakaShrot_ConnectW") - BakaShrot_IsConnected = BakaShrot_ClientFunction("BakaShrot_IsConnected") - BakaShrot_Disconnect = BakaShrot_ClientFunction("BakaShrot_Disconnect") - BakaShrot_GetNode = BakaShrot_ClientFunction("BakaShrot_GetNodeW") - BakaShrot_PushMessageTo = BakaShrot_ClientFunction("BakaShrot_PushMessageToW") - BakaShrot_GetLatestMessageOf = BakaShrot_ClientFunction("BakaShrot_GetLatestMessageOfW") - BakaShrot_GetMessages = BakaShrot_ClientFunction("BakaShrot_GetMessagesW") - BakaShrot_GetMessageCount = BakaShrot_ClientFunction("BakaShrot_GetMessageCount") - BakaShrot_SelectMessage = BakaShrot_ClientFunction("BakaShrot_SelectMessage") - BakaShrot_HasMoreMessages = BakaShrot_ClientFunction("BakaShrot_HasMoreMessages") - BakaShrot_GetMessageId = BakaShrot_ClientFunction("BakaShrot_GetMessageId") - BakaShrot_GetMessagePushedAt = BakaShrot_ClientFunction("BakaShrot_GetMessagePushedAt") + BakaShrot_CreateClient = BakaShrot_ClientFunction("BakaShrot_CreateClient") + BakaShrot_FreeClient = BakaShrot_ClientFunction("BakaShrot_FreeClient") + BakaShrot_GetLastError = BakaShrot_ClientFunction("BakaShrot_GetLastError") + BakaShrot_GetRefusalReason = BakaShrot_ClientFunction("BakaShrot_GetRefusalReasonW") + BakaShrot_SetCaCertificate = BakaShrot_ClientFunction("BakaShrot_SetCaCertificateW") + BakaShrot_SetCertificate = BakaShrot_ClientFunction("BakaShrot_SetCertificateW") + BakaShrot_SetPrivateKey = BakaShrot_ClientFunction("BakaShrot_SetPrivateKeyW") + BakaShrot_SetCrl = BakaShrot_ClientFunction("BakaShrot_SetCrlW") + BakaShrot_Connect = BakaShrot_ClientFunction("BakaShrot_ConnectW") + BakaShrot_IsConnected = BakaShrot_ClientFunction("BakaShrot_IsConnected") + BakaShrot_Disconnect = BakaShrot_ClientFunction("BakaShrot_Disconnect") + BakaShrot_Ping = BakaShrot_ClientFunction("BakaShrot_Ping") + BakaShrot_SetAnswerTimeout = BakaShrot_ClientFunction("BakaShrot_SetAnswerTimeout") + BakaShrot_GetAnswerTimeout = BakaShrot_ClientFunction("BakaShrot_GetAnswerTimeout") + BakaShrot_GetNode = BakaShrot_ClientFunction("BakaShrot_GetNodeW") + BakaShrot_PushMessageTo = BakaShrot_ClientFunction("BakaShrot_PushMessageToW") + BakaShrot_GetLatestMessageOf = BakaShrot_ClientFunction("BakaShrot_GetLatestMessageOfW") + BakaShrot_GetMessages = BakaShrot_ClientFunction("BakaShrot_GetMessagesW") + BakaShrot_GetMessageCount = BakaShrot_ClientFunction("BakaShrot_GetMessageCount") + BakaShrot_SelectMessage = BakaShrot_ClientFunction("BakaShrot_SelectMessage") + BakaShrot_HasMoreMessages = BakaShrot_ClientFunction("BakaShrot_HasMoreMessages") + BakaShrot_GetMessageId = BakaShrot_ClientFunction("BakaShrot_GetMessageId") + BakaShrot_GetMessagePushedAt = BakaShrot_ClientFunction("BakaShrot_GetMessagePushedAt") BakaShrot_GetMessageAttachmentSize = BakaShrot_ClientFunction("BakaShrot_GetMessageAttachmentSize") BakaShrot_IsMessageAttachmentReady = BakaShrot_ClientFunction("BakaShrot_IsMessageAttachmentReady") - BakaShrot_GetMessageData = BakaShrot_ClientFunction("BakaShrot_GetMessageDataW") - BakaShrot_GetMessageTopic = BakaShrot_ClientFunction("BakaShrot_GetMessageTopicW") - BakaShrot_GetMessageNode = BakaShrot_ClientFunction("BakaShrot_GetMessageNodeW") - BakaShrot_ListTopics = BakaShrot_ClientFunction("BakaShrot_ListTopics") - BakaShrot_ListNodes = BakaShrot_ClientFunction("BakaShrot_ListNodes") - BakaShrot_GetNamesList = BakaShrot_ClientFunction("BakaShrot_GetNamesListW") - BakaShrot_Query = BakaShrot_ClientFunction("BakaShrot_QueryW") - BakaShrot_GetQueryResult = BakaShrot_ClientFunction("BakaShrot_GetQueryResultW") - BakaShrot_PushMessageWithFile = BakaShrot_ClientFunction("BakaShrot_PushMessageWithFileW") - BakaShrot_PushMessageWithData = BakaShrot_ClientFunction("BakaShrot_PushMessageWithDataW") - BakaShrot_SaveAttachment = BakaShrot_ClientFunction("BakaShrot_SaveAttachmentW") - BakaShrot_LoadAttachment = BakaShrot_ClientFunction("BakaShrot_LoadAttachmentW") - BakaShrot_GetAttachmentData = BakaShrot_ClientFunction("BakaShrot_GetAttachmentData") - BakaShrot_FreeAttachmentData = BakaShrot_ClientFunction("BakaShrot_FreeAttachmentData") + BakaShrot_GetMessageData = BakaShrot_ClientFunction("BakaShrot_GetMessageDataW") + BakaShrot_GetMessageTopic = BakaShrot_ClientFunction("BakaShrot_GetMessageTopicW") + BakaShrot_GetMessageNode = BakaShrot_ClientFunction("BakaShrot_GetMessageNodeW") + BakaShrot_ListNames = BakaShrot_ClientFunction("BakaShrot_ListNamesW") + BakaShrot_GetNamesListAsJson = BakaShrot_ClientFunction("BakaShrot_GetNamesListAsJsonW") + BakaShrot_Query = BakaShrot_ClientFunction("BakaShrot_QueryW") + BakaShrot_GetQueryResultAsJson = BakaShrot_ClientFunction("BakaShrot_GetQueryResultAsJsonW") + BakaShrot_EnumerateNames = BakaShrot_ClientFunction("BakaShrot_EnumerateNamesW") + BakaShrot_NextName = BakaShrot_ClientFunction("BakaShrot_NextName") + BakaShrot_GetEnumName = BakaShrot_ClientFunction("BakaShrot_GetEnumNameW") + BakaShrot_GetNameCount = BakaShrot_ClientFunction("BakaShrot_GetNameCount") + BakaShrot_IsNamesListTruncated = BakaShrot_ClientFunction("BakaShrot_IsNamesListTruncated") + BakaShrot_EnumerateQuery = BakaShrot_ClientFunction("BakaShrot_EnumerateQueryW") + BakaShrot_GetQueryColumnCount = BakaShrot_ClientFunction("BakaShrot_GetQueryColumnCount") + BakaShrot_GetQueryColumnName = BakaShrot_ClientFunction("BakaShrot_GetQueryColumnNameW") + BakaShrot_NextQueryRow = BakaShrot_ClientFunction("BakaShrot_NextQueryRow") + BakaShrot_GetQueryValue = BakaShrot_ClientFunction("BakaShrot_GetQueryValueW") + BakaShrot_IsQueryValueNull = BakaShrot_ClientFunction("BakaShrot_IsQueryValueNull") + BakaShrot_CloseEnum = BakaShrot_ClientFunction("BakaShrot_CloseEnum") + BakaShrot_PushMessageWithFile = BakaShrot_ClientFunction("BakaShrot_PushMessageWithFileW") + BakaShrot_PushMessageWithData = BakaShrot_ClientFunction("BakaShrot_PushMessageWithDataW") + BakaShrot_SaveAttachment = BakaShrot_ClientFunction("BakaShrot_SaveAttachmentW") + BakaShrot_LoadAttachment = BakaShrot_ClientFunction("BakaShrot_LoadAttachmentW") + BakaShrot_GetAttachmentData = BakaShrot_ClientFunction("BakaShrot_GetAttachmentData") + BakaShrot_FreeAttachmentData = BakaShrot_ClientFunction("BakaShrot_FreeAttachmentData") If BakaShrot_ClientMissing <> "" BakaShrot_UnloadClient() @@ -194,18 +254,41 @@ Procedure.i BakaShrot_LoadClient(DllPath.s) EndProcedure -; Calls a string getter of the DLL (Getter(*Buffer, BufferSize)) and +; Calls a client's string getter (Getter(Client, *Buffer, BufferSize)) and ; returns the string: asks for the size, then copies. -PrototypeC.i BakaShrot_StringGetter_Prototype(*Buffer, BufferSize.i) -Procedure.s BakaShrot_GetString(Getter.BakaShrot_StringGetter_Prototype) +PrototypeC.i BakaShrot_StringGetter_Prototype(Client.q, *Buffer, BufferSize.i) +Procedure.s BakaShrot_GetString(Client.q, Getter.BakaShrot_StringGetter_Prototype) Protected *Buffer, BufferSize.i, Text.s - BufferSize = Getter(0, 0) + BufferSize = Getter(Client, 0, 0) + If BufferSize <= 0 + ProcedureReturn "" + EndIf *Buffer = AllocateMemory(BufferSize) If Not *Buffer ProcedureReturn "" EndIf - Getter(*Buffer, BufferSize) + Getter(Client, *Buffer, BufferSize) + Text = PeekS(*Buffer, -1, #PB_Unicode) + FreeMemory(*Buffer) + + ProcedureReturn Text +EndProcedure + +; The same for a getter of a column (Getter(Enum, Index, *Buffer, BufferSize)). +PrototypeC.i BakaShrot_ColumnGetter_Prototype(Enum.q, Index.l, *Buffer, BufferSize.i) +Procedure.s BakaShrot_GetColumnString(Enum.q, Index.l, Getter.BakaShrot_ColumnGetter_Prototype) + Protected *Buffer, BufferSize.i, Text.s + + BufferSize = Getter(Enum, Index, 0, 0) + If BufferSize <= 0 + ProcedureReturn "" + EndIf + *Buffer = AllocateMemory(BufferSize) + If Not *Buffer + ProcedureReturn "" + EndIf + Getter(Enum, Index, *Buffer, BufferSize) Text = PeekS(*Buffer, -1, #PB_Unicode) FreeMemory(*Buffer) @@ -213,32 +296,44 @@ Procedure.s BakaShrot_GetString(Getter.BakaShrot_StringGetter_Prototype) EndProcedure ; The string getters, as strings. -Procedure.s BakaShrot_GetRefusalReasonString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetRefusalReason) +Procedure.s BakaShrot_GetRefusalReasonString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetRefusalReason) EndProcedure -Procedure.s BakaShrot_GetNodeString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetNode) +Procedure.s BakaShrot_GetNodeString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetNode) EndProcedure -Procedure.s BakaShrot_GetMessageDataString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageData) +Procedure.s BakaShrot_GetMessageDataString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageData) EndProcedure -Procedure.s BakaShrot_GetMessageTopicString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageTopic) +Procedure.s BakaShrot_GetMessageTopicString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageTopic) EndProcedure -Procedure.s BakaShrot_GetMessageNodeString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageNode) +Procedure.s BakaShrot_GetMessageNodeString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageNode) EndProcedure -Procedure.s BakaShrot_GetNamesListString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetNamesList) +Procedure.s BakaShrot_GetNamesListAsJsonString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetNamesListAsJson) EndProcedure -Procedure.s BakaShrot_GetQueryResultString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetQueryResult) +Procedure.s BakaShrot_GetQueryResultAsJsonString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetQueryResultAsJson) +EndProcedure + +Procedure.s BakaShrot_GetEnumNameString(Enum.q) + ProcedureReturn BakaShrot_GetString(Enum, BakaShrot_GetEnumName) +EndProcedure + +Procedure.s BakaShrot_GetQueryColumnNameString(Enum.q, Index.l) + ProcedureReturn BakaShrot_GetColumnString(Enum, Index, BakaShrot_GetQueryColumnName) +EndProcedure + +Procedure.s BakaShrot_GetQueryValueString(Enum.q, Index.l) + ProcedureReturn BakaShrot_GetColumnString(Enum, Index, BakaShrot_GetQueryValue) EndProcedure @@ -246,18 +341,29 @@ EndProcedure ; IDE), not when it's included by an app. ; ClientExample ; Pushes a message to "logs", reads it back, pushes one with an -; attachment and reads that back, lists the topics. +; attachment and reads that back, lists the topics; then a second client +; connected at the same time reads it too. CompilerIf #PB_Compiler_IsMainFile - Define Id.q, Size.q, *Attachment, *Copy + Define Client.q, Second.q, Enum.q, Id.q, Size.q, *Attachment, *Copy - ; Prints why the last call failed, then ends. - Procedure Failed(What.s) - PrintN(What + " failed: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString()) + ; Prints why a client's last call failed, then ends. + Procedure Failed(Client.q, What.s) + PrintN(What + " failed: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client)) + ", " + BakaShrot_GetRefusalReasonString(Client)) BakaShrot_UnloadClient() End 1 EndProcedure + ; A new client, connected with the certificates given. + Procedure.q Connected(What.s) + Protected Client.q = BakaShrot_CreateClient() + If Not BakaShrot_SetCaCertificate(Client, ProgramParameter(1)) : Failed(Client, What + ": setting the CA's certificate") : EndIf + If Not BakaShrot_SetCertificate(Client, ProgramParameter(2)) : Failed(Client, What + ": setting the certificate") : EndIf + If Not BakaShrot_SetPrivateKey(Client, ProgramParameter(3)) : Failed(Client, What + ": setting the private key") : EndIf + If Not BakaShrot_Connect(Client, ProgramParameter(4), Val(ProgramParameter(5))) : Failed(Client, What + ": connecting") : EndIf + ProcedureReturn Client + EndProcedure + OpenConsole() If CountProgramParameters() < 6 PrintN("Usage: ClientExample ") @@ -269,28 +375,25 @@ CompilerIf #PB_Compiler_IsMainFile End 1 EndIf - If Not BakaShrot_SetCaCertificate(ProgramParameter(1)) : Failed("Setting the CA's certificate") : EndIf - If Not BakaShrot_SetCertificate(ProgramParameter(2)) : Failed("Setting the certificate") : EndIf - If Not BakaShrot_SetPrivateKey(ProgramParameter(3)) : Failed("Setting the private key") : EndIf - If Not BakaShrot_Connect(ProgramParameter(4), Val(ProgramParameter(5))) : Failed("Connecting") : EndIf - PrintN("Connected as " + BakaShrot_GetNodeString()) + Client = Connected("The client") + PrintN("Client #" + Str(Client) + " connected as " + BakaShrot_GetNodeString(Client)) - Id = BakaShrot_PushMessageTo("logs", ~"{\"from\": \"PureBasic\", \"text\": \"hello\"}") - If Id < 1 : Failed("Pushing") : EndIf + Id = BakaShrot_PushMessageTo(Client, "logs", ~"{\"from\": \"PureBasic\", \"text\": \"hello\"}") + If Id < 1 : Failed(Client, "Pushing") : EndIf PrintN("Pushed #" + Str(Id)) - If Not BakaShrot_GetLatestMessageOf("logs", BakaShrot_GetNodeString()) : Failed("Reading") : EndIf - PrintN("Latest: #" + Str(BakaShrot_GetMessageId()) + " " + BakaShrot_GetMessageDataString()) + If Not BakaShrot_GetLatestMessageOf(Client, "logs", BakaShrot_GetNodeString(Client)) : Failed(Client, "Reading") : EndIf + PrintN("Latest: #" + Str(BakaShrot_GetMessageId(Client)) + " " + BakaShrot_GetMessageDataString(Client)) *Attachment = AllocateMemory(3000) FillMemory(*Attachment, 3000, 42, #PB_Byte) - Id = BakaShrot_PushMessageWithData("logs", ~"{\"photo\": 1}", *Attachment, 3000) - If Id < 1 : Failed("Pushing an attachment") : EndIf - Size = BakaShrot_LoadAttachment("logs", BakaShrot_GetNodeString(), Id) - If Size < 0 : Failed("Reading the attachment") : EndIf + Id = BakaShrot_PushMessageWithData(Client, "logs", ~"{\"photo\": 1}", *Attachment, 3000) + If Id < 1 : Failed(Client, "Pushing an attachment") : EndIf + Size = BakaShrot_LoadAttachment(Client, "logs", BakaShrot_GetNodeString(Client), Id) + If Size < 0 : Failed(Client, "Reading the attachment") : EndIf *Copy = AllocateMemory(Size) - BakaShrot_GetAttachmentData(*Copy, Size) - BakaShrot_FreeAttachmentData() + BakaShrot_GetAttachmentData(Client, *Copy, Size) + BakaShrot_FreeAttachmentData(Client) If CompareMemory(*Attachment, *Copy, 3000) PrintN("Pushed #" + Str(Id) + " with " + Str(Size) + " bytes, read back the same") Else @@ -299,15 +402,36 @@ CompilerIf #PB_Compiler_IsMainFile EndIf FreeMemory(*Attachment) : FreeMemory(*Copy) - If BakaShrot_ListTopics() < 0 : Failed("Listing") : EndIf - PrintN("Topics: " + BakaShrot_GetNamesListString()) + If BakaShrot_ListNames(Client, 1, "", "") < 0 : Failed(Client, "Listing") : EndIf + PrintN("Topics: " + BakaShrot_GetNamesListAsJsonString(Client)) + ; The topics this client's node pushed to ("" for any topic), one at a time. + Enum = BakaShrot_EnumerateNames(Client, 1, "", BakaShrot_GetNodeString(Client)) + If Not Enum : Failed(Client, "Listing") : EndIf + PrintN("Topics it pushed to (" + Str(BakaShrot_GetNameCount(Enum)) + "):") + While BakaShrot_NextName(Enum) = 1 + PrintN(" " + BakaShrot_GetEnumNameString(Enum)) + Wend + BakaShrot_CloseEnum(Enum) - If BakaShrot_PushMessageTo("nothing", "{}") < 0 - PrintN("A push to a topic it may not push to: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString()) + If BakaShrot_PushMessageTo(Client, "nothing", "{}") < 0 + PrintN("A push to a topic it may not push to: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client)) + ", " + BakaShrot_GetRefusalReasonString(Client)) EndIf - BakaShrot_Disconnect() - PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected())) + ; A second client, connected at the same time. + Second = Connected("The second client") + If Not BakaShrot_GetLatestMessageOf(Second, "logs", BakaShrot_GetNodeString(Second)) : Failed(Second, "The second client reading") : EndIf + PrintN("Second client #" + Str(Second) + ", both connected (" + Str(BakaShrot_IsConnected(Client)) + Str(BakaShrot_IsConnected(Second)) + "), its latest: #" + Str(BakaShrot_GetMessageId(Second))) + ; Its errors are its own: the first client's last call succeeds, its fails. + BakaShrot_GetLatestMessageOf(Client, "logs", BakaShrot_GetNodeString(Client)) + If BakaShrot_PushMessageTo(Second, "nothing", "{}") < 0 + PrintN("Its own error: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Second)) + ", the first client's: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client))) + EndIf + BakaShrot_FreeClient(Second) + PrintN("Freed, IsConnected: " + Str(BakaShrot_IsConnected(Second)) + ", its error now: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Second))) + + BakaShrot_Disconnect(Client) + PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected(Client))) + BakaShrot_FreeClient(Client) BakaShrot_UnloadClient() End 0 diff --git a/bindings/purebasic/BakaShrot_ErrorCodes.pbi b/bindings/purebasic/BakaShrot_ErrorCodes.pbi index 2c164fb..6612827 100644 --- a/bindings/purebasic/BakaShrot_ErrorCodes.pbi +++ b/bindings/purebasic/BakaShrot_ErrorCodes.pbi @@ -1,12 +1,13 @@ ;{- Code Header ; ==- Basic Info -================================ ; Name: BakaShrot_ErrorCodes.pbi -; Version: 0.0.1 +; Version: 0.4.0 ; Author: Herwin Bozet (NibblePoker) ; ; ==- Compatibility -============================= ; Tested compiler versions: ; * PureBasic 5.73 LTS (Windows x64) +; * PureBasic 6.41 (Windows x64) ; ; ==- Links -===================================== ; GitHub: https://github.com/aziascreations/BakaShrot @@ -16,7 +17,7 @@ ; BakaShrot error codes ; ; What BakaShrot_GetLastError() returns after a failed call of the client DLL -; (bakashrot.dll), and the code a server sends with each refusal (protocol 7, +; (bakashrot.dll), and the code a server sends with each refusal (protocol 8, ; crates/bakashrot-proto/src/error.rs). ; The Python client has them in bakashrot.ErrorCode. Shipped next to ; BakaShrot_Client_Prototypes.pbi, which includes it. @@ -30,7 +31,8 @@ ; reconnect, then retry: NotConnected, ConnectFailed, ConnectionLost, ; ProtocolError (the connection is closed) ; retry later: NotReady (an attachment still on its way), -; ServerError (the server's storage failed) +; ServerError (the server's storage failed), +; QueryTimedOut (or narrow the query) ; fix the certificates or ; the server's config: AuthRejected, ServerNotVerified, NotAllowed, ; UnknownName, VersionMismatch @@ -67,6 +69,9 @@ #BakaShrot_Refused_QueryFailed = 9 ; The server couldn't store or read something: its database failed. #BakaShrot_Refused_ServerError = 10 +; A query ran past the server's time limit (query_time_limit) and was +; stopped: narrow it, or retry when the server is less busy. +#BakaShrot_Refused_QueryTimedOut = 11 ; The highest a refusal can have, anything above is the client's own. #BakaShrot_Refused_Max = 99 @@ -119,6 +124,7 @@ Procedure.s BakaShrot_ErrorName(Code.l) Case #BakaShrot_Refused_DataMismatch : ProcedureReturn "DataMismatch" Case #BakaShrot_Refused_QueryFailed : ProcedureReturn "QueryFailed" Case #BakaShrot_Refused_ServerError : ProcedureReturn "ServerError" + Case #BakaShrot_Refused_QueryTimedOut : ProcedureReturn "QueryTimedOut" Case #BakaShrot_Error_NotConnected : ProcedureReturn "NotConnected" Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "ConnectFailed" Case #BakaShrot_Error_AuthRejected : ProcedureReturn "AuthRejected" diff --git a/bindings/python/bakashrot.py b/bindings/python/bakashrot.py index c85b635..26d2a65 100644 --- a/bindings/python/bakashrot.py +++ b/bindings/python/bakashrot.py @@ -16,7 +16,7 @@ stored, a str that may or may not be JSON: parsing them is up to the app print(message.id, message.json()) Who the client is comes from its certificate, issued by the CA the server -trusts (bakashrot-cert): its name is its node, its roles say what it may +trusts (bakashrot cert): its name is its node, its roles say what it may do. client.toml says where the server is and where the certificates are (docs/client.md): @@ -37,9 +37,9 @@ numbers as the DLL's BakaShrot_GetLastError()): A push whose answer was lost (ConnectionLostError) may have been stored all the same: pushed again, it's stored twice. Delivery is at least once. -The DLL holds a single connection per process: only one Client may be -connected at a time. Calls are serialized with a lock, so a Client can be -shared between threads, one request at a time. +Each Client has its own client in the DLL, so several can be connected at +once, from different threads. A Client's own calls are serialized with a +lock: one can be shared between threads, one request at a time. The DLL is looked for, in order: the dll_path given, the BAKASHROT_DLL environment variable, next to this file, then in the current directory. @@ -58,17 +58,22 @@ from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Any, Iterator, Optional, Union -__version__ = "0.3.0" +__version__ = "0.4.0" __all__ = [ "Client", "Message", "MessagesPage", "NamesList", "BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode", - "MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE", + "MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE", "KEEPALIVE_SECONDS", "ANSWER_TIMEOUT_SECONDS", ] # The protocol's: crates/bakashrot-proto/src/limits.rs. MAX_GET_MESSAGES = 10000 MAX_MESSAGE_SIZE = 16 * 1024 * 1024 - 4096 +# The server closes a connection silent for 5 min: ping() every minute or +# so while waiting longer than that (follow() does it itself). +KEEPALIVE_SECONDS = 60 +# How long an answer may take until Client.answer_timeout is changed. +ANSWER_TIMEOUT_SECONDS = 30.0 DLL_NAME = "bakashrot.dll" if sys.platform == "win32" else "libbakashrot.so" @@ -87,6 +92,7 @@ class ErrorCode(enum.IntEnum): DATA_MISMATCH = 8 # an upload that doesn't match its SHA-256 QUERY_FAILED = 9 # the SQL failed SERVER_ERROR = 10 # the server's database failed: retry later + QUERY_TIMED_OUT = 11 # a query past the server's time limit, stopped: narrow it or retry later # The client's own. NOT_CONNECTED = 100 # never connected, or closed or lost before CONNECT_FAILED = 101 # nothing answers at that host and port @@ -196,10 +202,18 @@ class NamesList: truncated: bool # True if they didn't all fit in one answer +def _text(value: str) -> bytes: + """value as the DLL's C string: one with a NUL is refused rather than + cut there.""" + if "\0" in value: + raise BakaShrotError("A string with a NUL character", ErrorCode.INVALID_ARGUMENT) + return value.encode("utf-8") + + def _name(value: str) -> bytes: if not isinstance(value, str): raise TypeError(f"a topic or node is a name, not {value!r}") - return value.encode("utf-8") + return _text(value) def _find_dll(dll_path: Optional[str]) -> str: @@ -237,41 +251,46 @@ class _Dll: self.path = path I, L, Q, P, S = ctypes.c_ssize_t, ctypes.c_int32, ctypes.c_int64, ctypes.c_char_p, ctypes.c_void_p + H = Q # a client's handle signatures = { - "BakaShrot_GetLastError": (L, []), - "BakaShrot_GetRefusalReasonA": (I, [S, I]), - "BakaShrot_SetCaCertificateA": (I, [P]), - "BakaShrot_SetCertificateA": (I, [P]), - "BakaShrot_SetPrivateKeyA": (I, [P]), - "BakaShrot_SetCrlA": (I, [P]), - "BakaShrot_ConnectA": (I, [P, L]), - "BakaShrot_IsConnected": (I, []), - "BakaShrot_Disconnect": (I, []), - "BakaShrot_GetNodeA": (I, [S, I]), - "BakaShrot_PushMessageToA": (Q, [P, P]), - "BakaShrot_GetLatestMessageOfA": (I, [P, P]), - "BakaShrot_GetMessagesA": (L, [P, P, Q, L]), - "BakaShrot_GetMessageCount": (L, []), - "BakaShrot_SelectMessage": (I, [L]), - "BakaShrot_HasMoreMessages": (I, []), - "BakaShrot_GetMessageId": (Q, []), - "BakaShrot_GetMessagePushedAt": (Q, []), - "BakaShrot_GetMessageAttachmentSize": (Q, []), - "BakaShrot_IsMessageAttachmentReady": (I, []), - "BakaShrot_GetMessageTopicA": (I, [S, I]), - "BakaShrot_GetMessageNodeA": (I, [S, I]), - "BakaShrot_GetMessageDataA": (I, [S, I]), - "BakaShrot_ListTopics": (L, []), - "BakaShrot_ListNodes": (L, []), - "BakaShrot_GetNamesListA": (I, [S, I]), - "BakaShrot_QueryA": (I, [P]), - "BakaShrot_GetQueryResultA": (I, [S, I]), - "BakaShrot_PushMessageWithFileA": (Q, [P, P, P]), - "BakaShrot_PushMessageWithDataA": (Q, [P, P, P, Q]), - "BakaShrot_SaveAttachmentA": (Q, [P, P, Q, P]), - "BakaShrot_LoadAttachmentA": (Q, [P, P, Q]), - "BakaShrot_GetAttachmentData": (Q, [S, Q]), - "BakaShrot_FreeAttachmentData": (I, []), + "BakaShrot_CreateClient": (Q, []), + "BakaShrot_FreeClient": (I, [H]), + "BakaShrot_GetLastError": (L, [H]), + "BakaShrot_GetRefusalReasonA": (I, [H, S, I]), + "BakaShrot_SetCaCertificateA": (I, [H, P]), + "BakaShrot_SetCertificateA": (I, [H, P]), + "BakaShrot_SetPrivateKeyA": (I, [H, P]), + "BakaShrot_SetCrlA": (I, [H, P]), + "BakaShrot_ConnectA": (I, [H, P, L]), + "BakaShrot_IsConnected": (I, [H]), + "BakaShrot_Disconnect": (I, [H]), + "BakaShrot_Ping": (I, [H]), + "BakaShrot_SetAnswerTimeout": (I, [H, Q]), + "BakaShrot_GetAnswerTimeout": (Q, [H]), + "BakaShrot_GetNodeA": (I, [H, S, I]), + "BakaShrot_PushMessageToA": (Q, [H, P, P]), + "BakaShrot_GetLatestMessageOfA": (I, [H, P, P]), + "BakaShrot_GetMessagesA": (L, [H, P, P, Q, L]), + "BakaShrot_GetMessageCount": (L, [H]), + "BakaShrot_SelectMessage": (I, [H, L]), + "BakaShrot_HasMoreMessages": (I, [H]), + "BakaShrot_GetMessageId": (Q, [H]), + "BakaShrot_GetMessagePushedAt": (Q, [H]), + "BakaShrot_GetMessageAttachmentSize": (Q, [H]), + "BakaShrot_IsMessageAttachmentReady": (I, [H]), + "BakaShrot_GetMessageTopicA": (I, [H, S, I]), + "BakaShrot_GetMessageNodeA": (I, [H, S, I]), + "BakaShrot_GetMessageDataA": (I, [H, S, I]), + "BakaShrot_ListNamesA": (L, [H, L, P, P]), + "BakaShrot_GetNamesListAsJsonA": (I, [H, S, I]), + "BakaShrot_QueryA": (I, [H, P]), + "BakaShrot_GetQueryResultAsJsonA": (I, [H, S, I]), + "BakaShrot_PushMessageWithFileA": (Q, [H, P, P, P]), + "BakaShrot_PushMessageWithDataA": (Q, [H, P, P, P, Q]), + "BakaShrot_SaveAttachmentA": (Q, [H, P, P, Q, P]), + "BakaShrot_LoadAttachmentA": (Q, [H, P, P, Q]), + "BakaShrot_GetAttachmentData": (Q, [H, S, Q]), + "BakaShrot_FreeAttachmentData": (I, [H]), } for name, (restype, argtypes) in signatures.items(): try: @@ -280,15 +299,16 @@ class _Dll: raise BakaShrotError(f"{path} has no {name}, is it an older build?", ErrorCode.INTERNAL) from error function.restype = restype function.argtypes = argtypes + # BakaShrot_PushMessageToA as PushMessageToA. setattr(self, name[len("BakaShrot_"):], function) - def string(self, getter) -> str: - """Calls a string getter: asks for the size, then copies (UTF-8).""" - size = getter(None, 0) + def string(self, getter, handle: int) -> str: + """Calls a client's string getter: asks for the size, then copies (UTF-8).""" + size = getter(handle, None, 0) if size <= 1: return "" buffer = ctypes.create_string_buffer(size) - getter(buffer, size) + getter(handle, buffer, size) return buffer.raw[: size - 1].decode("utf-8") @@ -309,8 +329,6 @@ class Client: its private key, the CA's CRL (servers it revokes are refused). """ - _connected_client: Optional["Client"] = None - def __init__(self, server: str, ca: str, certificate: str, key: str, crl: Optional[str] = None, dll_path: Optional[str] = None): self._dll = _Dll.get(dll_path) @@ -321,6 +339,9 @@ class Client: self.key = os.fspath(key) self.crl = os.fspath(crl) if crl else None self.node = "" + self._answer_timeout = ANSWER_TIMEOUT_SECONDS + # Its client in the DLL, from connect() to close(). + self._handle: Optional[int] = None @classmethod def from_file(cls, path: Union[str, os.PathLike], dll_path: Optional[str] = None) -> "Client": @@ -360,34 +381,69 @@ class Client: def connect(self) -> "Client": """Connects. Raises ConnectionLostError when the server can't be reached (CONNECT_FAILED), AuthError when a certificate is refused, - BakaShrotError on a bad setting (INVALID_ARGUMENT, FILE_ERROR) or - another Client holding the DLL's connection (ALREADY_CONNECTED).""" + BakaShrotError on a bad setting (INVALID_ARGUMENT, FILE_ERROR).""" with self._lock: - owner = Client._connected_client - if owner is not None and owner is not self and owner.connected: - raise BakaShrotError("The DLL holds one connection, another Client is connected", ErrorCode.ALREADY_CONNECTED) if self.connected: return self dll = self._dll + if self._handle is None: + handle = dll.CreateClient() + if handle < 1: + raise BakaShrotError("The DLL made no client", ErrorCode.INTERNAL) + self._handle = handle + handle = self._handle + if not dll.SetAnswerTimeout(handle, self._milliseconds(self._answer_timeout)): + raise self._failed("Answer timeout") for setter, value in ((dll.SetCaCertificateA, self.ca), (dll.SetCertificateA, self.certificate), (dll.SetPrivateKeyA, self.key), (dll.SetCrlA, self.crl or "")): - if not setter(value.encode("utf-8")): + if not setter(handle, _text(value)): raise self._failed("Certificates") - if not dll.ConnectA(self.host.encode("utf-8"), self.port): + if not dll.ConnectA(handle, _text(self.host), self.port): raise self._failed(f"Connect to {self.host}:{self.port}", connecting=True) - self.node = dll.string(dll.GetNodeA) - Client._connected_client = self + self.node = dll.string(dll.GetNodeA, handle) return self def close(self) -> None: + """Disconnects, and frees its client in the DLL. connect() again + reconnects.""" with self._lock: - if Client._connected_client is self: - self._dll.Disconnect() - Client._connected_client = None + if self._handle is not None: + self._dll.FreeClient(self._handle) + self._handle = None + + def __del__(self): + try: + self.close() + except Exception: # noqa: BLE001 - the interpreter may be shutting down + pass + + @property + def answer_timeout(self) -> float: + """How long an answer may take, in seconds (ANSWER_TIMEOUT_SECONDS + until changed): longer for a slow query, say. Past it, the request + raises ConnectionLostError and the connection is closed (the server + stops the query it was running then). Kept across connections.""" + return self._answer_timeout + + @answer_timeout.setter + def answer_timeout(self, seconds: float) -> None: + milliseconds = self._milliseconds(seconds) + with self._lock: + if self._handle is not None and not self._dll.SetAnswerTimeout(self._handle, milliseconds): + raise self._failed("Answer timeout") + self._answer_timeout = milliseconds / 1000 + + @staticmethod + def _milliseconds(seconds: float) -> int: + milliseconds = round(seconds * 1000) + if milliseconds < 1 or milliseconds >= 2 ** 63: + raise BakaShrotError(f"An answer timeout of {seconds} s: 1 ms or more", ErrorCode.INVALID_ARGUMENT) + return milliseconds @property def connected(self) -> bool: - return Client._connected_client is self and bool(self._dll.IsConnected()) + handle = self._handle + return handle is not None and bool(self._dll.IsConnected(handle)) def __enter__(self) -> "Client": return self.connect() @@ -401,15 +457,13 @@ class Client: def _failed(self, what: str, connecting: bool = False) -> BakaShrotError: """The error for a failed call, by the DLL's BakaShrot_GetLastError().""" - code = _error_code(self._dll.GetLastError()) - reason = self._dll.string(self._dll.GetRefusalReasonA) + code = _error_code(self._dll.GetLastError(self._handle)) + reason = self._dll.string(self._dll.GetRefusalReasonA, self._handle) if connecting and code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED, ErrorCode.NOT_ALLOWED, ErrorCode.VERSION_MISMATCH): return AuthError(f"{what}: {reason}", code) if isinstance(code, int) and 1 <= int(code) <= 99: return RefusedError(reason, code) - if not self._dll.IsConnected() and Client._connected_client is self: - Client._connected_client = None name = code.name if isinstance(code, ErrorCode) else str(code) message = f"{what} ({name}): {reason or 'failed'}" if code in (ErrorCode.NOT_CONNECTED, ErrorCode.CONNECT_FAILED, ErrorCode.CONNECTION_LOST, ErrorCode.PROTOCOL_ERROR): @@ -418,6 +472,27 @@ class Client: # --- Requests ---------------------------------------------------------- + def ping(self) -> None: + """Keeps the connection open: the server closes one silent for 5 + min. An app waiting longer than that between requests calls it + every minute or so (KEEPALIVE_SECONDS). ConnectionLostError if + the connection is gone.""" + with self._lock: + self._check_connected() + if not self._dll.Ping(self._handle): + raise self._failed("Ping") + + def _wait(self, seconds: float) -> None: + """Sleeps `seconds`, pinging every KEEPALIVE_SECONDS meanwhile.""" + left = seconds + while True: + step = min(left, KEEPALIVE_SECONDS) + time.sleep(step) + left -= step + if left <= 0: + return + self.ping() + def push(self, data: Any, topic: str, attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int: """Pushes a message into topic, under the client's node. data is @@ -429,19 +504,19 @@ class Client: message is only stored once all of it came.""" if not isinstance(data, str): data = json.dumps(data, separators=(",", ":"), ensure_ascii=False) - encoded = data.encode("utf-8") + encoded = _text(data) if len(encoded) > MAX_MESSAGE_SIZE: raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}", ErrorCode.INVALID_ARGUMENT) with self._lock: self._check_connected() if attachment is None: - message_id = self._dll.PushMessageToA(_name(topic), encoded) + message_id = self._dll.PushMessageToA(self._handle, _name(topic), encoded) elif isinstance(attachment, (bytes, bytearray, memoryview)): raw = bytes(attachment) - message_id = self._dll.PushMessageWithDataA(_name(topic), encoded, raw, len(raw)) + message_id = self._dll.PushMessageWithDataA(self._handle, _name(topic), encoded, raw, len(raw)) else: - path = os.fspath(attachment).encode("utf-8") - message_id = self._dll.PushMessageWithFileA(_name(topic), encoded, path) + path = _text(os.fspath(attachment)) + message_id = self._dll.PushMessageWithFileA(self._handle, _name(topic), encoded, path) if message_id < 1: raise self._failed("Push") return message_id @@ -452,15 +527,15 @@ class Client: (NOT_FOUND) or it isn't on this server yet (NOT_READY).""" with self._lock: self._check_connected() - size = self._dll.LoadAttachmentA(_name(topic), _name(node), int(message_id)) + size = self._dll.LoadAttachmentA(self._handle, _name(topic), _name(node), int(message_id)) if size < 0: raise self._failed("Attachment") try: buffer = ctypes.create_string_buffer(size) - self._dll.GetAttachmentData(buffer, size) + self._dll.GetAttachmentData(self._handle, buffer, size) return buffer.raw[:size] finally: - self._dll.FreeAttachmentData() + self._dll.FreeAttachmentData(self._handle) def save_attachment(self, topic: str, node: str, message_id: int, path: Union[str, os.PathLike]) -> int: """Saves the attachment of a message as path (replaced), a part at a @@ -468,23 +543,24 @@ class Client: leaves no file.""" with self._lock: self._check_connected() - size = self._dll.SaveAttachmentA(_name(topic), _name(node), int(message_id), - os.fspath(path).encode("utf-8")) + size = self._dll.SaveAttachmentA(self._handle, _name(topic), _name(node), int(message_id), + _text(os.fspath(path))) if size < 0: raise self._failed("Attachment") return size def _current(self) -> Message: - dll = self._dll - return Message(dll.GetMessageId(), dll.string(dll.GetMessageTopicA), dll.string(dll.GetMessageNodeA), - dll.string(dll.GetMessageDataA), dll.GetMessagePushedAt(), dll.GetMessageAttachmentSize(), - bool(dll.IsMessageAttachmentReady())) + dll, handle = self._dll, self._handle + return Message(dll.GetMessageId(handle), dll.string(dll.GetMessageTopicA, handle), + dll.string(dll.GetMessageNodeA, handle), dll.string(dll.GetMessageDataA, handle), + dll.GetMessagePushedAt(handle), dll.GetMessageAttachmentSize(handle), + bool(dll.IsMessageAttachmentReady(handle))) def latest(self, topic: str, node: str) -> Optional[Message]: """The latest message of topic/node, None if there's none yet.""" with self._lock: self._check_connected() - if not self._dll.GetLatestMessageOfA(_name(topic), _name(node)): + if not self._dll.GetLatestMessageOfA(self._handle, _name(topic), _name(node)): error = self._failed("Latest message") if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND: return None @@ -503,14 +579,14 @@ class Client: with self._lock: self._check_connected() dll = self._dll - count = dll.GetMessagesA(_name(topic), _name(node), after, limit) + count = dll.GetMessagesA(self._handle, _name(topic), _name(node), after, limit) if count < 0: raise self._failed("Get messages") messages = [] for index in range(count): - dll.SelectMessage(index) + dll.SelectMessage(self._handle, index) messages.append(self._current()) - return MessagesPage(messages, bool(dll.HasMoreMessages())) + return MessagesPage(messages, bool(dll.HasMoreMessages(self._handle))) def iter_messages(self, topic: str, node: str, after: int = 0, batch: int = 1000) -> Iterator[Message]: """Every message of topic/node after `after`, asking for batch at a @@ -526,8 +602,9 @@ class Client: def follow(self, topic: str, node: str, after: Union[int, str] = "latest", interval: float = 0.5, batch: int = 1000) -> Iterator[Message]: """Every message of topic/node after `after`, then new ones as they - come, checking every `interval` seconds once caught up. Forever: - stop iterating to stop. after="latest" starts with the next new one. + come, checking every `interval` seconds once caught up (pinging + every minute meanwhile if it's longer). Forever: stop iterating to + stop. after="latest" starts with the next new one. Raises ConnectionLostError if the connection fails: nothing reconnects by itself, connect() again and follow from the last id.""" if after == "latest": @@ -541,22 +618,27 @@ class Client: if page.messages: after = page.last_id if not page.more: - time.sleep(interval) + self._wait(interval) - def list_topics(self) -> NamesList: - """The topics with messages that the client may push to or read (every one with list_topics or query).""" - return self._list(self._dll.ListTopics, "List topics") + def list_topics(self, topic: Optional[str] = None, node: Optional[str] = None) -> NamesList: + """The topics with messages that the client may push to or read (every one with list_topics or query). + topic and node, each a name or a pattern ("sensors.*"), keep those of the topic/node pairs they + match: list_topics(node="kitchen") is the topics kitchen pushed to.""" + return self._list(1, topic, node, "List topics") - def list_nodes(self) -> NamesList: - """The nodes with messages in the topics the client may read (every one with list_nodes or query).""" - return self._list(self._dll.ListNodes, "List nodes") + def list_nodes(self, topic: Optional[str] = None, node: Optional[str] = None) -> NamesList: + """The nodes with messages in the topics the client may read (every one with list_nodes or query). + topic and node as list_topics() takes them: list_nodes(topic="logs") is the nodes that pushed to logs.""" + return self._list(2, topic, node, "List nodes") - def _list(self, function, what: str) -> NamesList: + def _list(self, kind: int, topic: Optional[str], node: Optional[str], what: str) -> NamesList: + topic = None if topic is None else _name(topic) + node = None if node is None else _name(node) with self._lock: self._check_connected() - if function() < 0: + if self._dll.ListNamesA(self._handle, kind, topic, node) < 0: raise self._failed(what) - parsed = json.loads(self._dll.string(self._dll.GetNamesListA)) + parsed = json.loads(self._dll.string(self._dll.GetNamesListAsJsonA, self._handle)) return NamesList(parsed["kind"], parsed["names"], bool(parsed["truncated"])) def query_raw(self, sql: str) -> str: @@ -568,9 +650,9 @@ class Client: query is refused: RefusedError "malformed JSON".""" with self._lock: self._check_connected() - if not self._dll.QueryA(sql.encode("utf-8")): + if not self._dll.QueryA(self._handle, _text(sql)): raise self._failed("Query") - return self._dll.string(self._dll.GetQueryResultA) + return self._dll.string(self._dll.GetQueryResultAsJsonA, self._handle) def query(self, sql: str) -> list: """query_raw(), as a list of dicts, one per row, by column name.""" diff --git a/bindings/python/check_bakashrot.py b/bindings/python/check_bakashrot.py index baf7e28..1fc7377 100644 --- a/bindings/python/check_bakashrot.py +++ b/bindings/python/check_bakashrot.py @@ -16,7 +16,7 @@ import threading import time import bakashrot -from bakashrot import AuthError, BakaShrotError, Client, ConnectionLostError, ErrorCode, RefusedError +from bakashrot import ANSWER_TIMEOUT_SECONDS, AuthError, BakaShrotError, Client, ConnectionLostError, ErrorCode, RefusedError dll_path, folder = sys.argv[1:3] fails = 0 @@ -138,15 +138,32 @@ with kitchen: ok, detail = raises(lambda: kitchen.push("x" * (bakashrot.MAX_MESSAGE_SIZE + 1), "logs"), BakaShrotError, "too big", ErrorCode.INVALID_ARGUMENT) check("A message over the limit: refused before sending", ok, detail) + ok, detail = raises(lambda: kitchen.push("a\0b", "logs"), BakaShrotError, "NUL", ErrorCode.INVALID_ARGUMENT) + check("A message with a NUL: refused rather than cut", ok, detail) + ok, detail = raises(lambda: kitchen.query("SELECT 1\0; DELETE"), BakaShrotError, "NUL", ErrorCode.INVALID_ARGUMENT) + check("SQL with a NUL: refused too", ok and kitchen.connected, detail) secret_id = kitchen.push({"s": 1}, "secret") check("Push to another allowed topic", secret_id == 1, secret_id) - ok, detail = raises(lambda: lounge.connect(), BakaShrotError, "one connection", ErrorCode.ALREADY_CONNECTED) - check("A second Client can't connect while one is", ok and not lounge.connected, detail) + with lounge: + page = lounge.get_messages("logs", "kitchen", after=0, limit=2) + check("A second Client connected at the same time: both work", + lounge.connected and lounge.node == "lounge" and [m.id for m in page] == [1, 2] + and kitchen.connected and kitchen.latest("secret", "kitchen").id == secret_id, + f"{lounge.node}, {[m.id for m in page]}") + check("Closing one leaves the other connected", kitchen.connected and not lounge.connected) topics = kitchen.list_topics() check("list_topics()", topics.kind == "topic" and topics.names == ["logs", "secret"] and not topics.truncated, topics) nodes = kitchen.list_nodes() check("list_nodes()", nodes.kind == "node" and nodes.names == ["kitchen"], nodes) + topics = kitchen.list_topics(node="KITCHEN") + check("list_topics(node=...): the topics it pushed to", topics.names == ["logs", "secret"], topics) + nodes = kitchen.list_nodes(topic="s*") + check("list_nodes(topic=pattern): the nodes that pushed to those", nodes.names == ["kitchen"], nodes) + check("list_topics(node=...) of a node without messages: none", kitchen.list_topics(node="nobody").names == []) + ok, detail = raises(lambda: kitchen.list_nodes(topic="a b"), BakaShrotError, "isn't a topic name or pattern", + ErrorCode.INVALID_ARGUMENT) + check("list_nodes(topic=...) neither a name nor a pattern: INVALID_ARGUMENT", ok, detail) # --- follow() ------------------------------------------------------------ followed = [] @@ -210,10 +227,54 @@ with kitchen: "missing.bin", ErrorCode.FILE_ERROR) check("A missing file: refused before sending", ok, detail) check("Still connected", kitchen.connected) + kitchen.ping() + check("ping(): answered, still connected", kitchen.connected) + + # --- The answer timeout ---------------------------------------------------- + check("answer_timeout: 30 s until changed", kitchen.answer_timeout == ANSWER_TIMEOUT_SECONDS, kitchen.answer_timeout) + ok, detail = raises(lambda: setattr(kitchen, "answer_timeout", 0), BakaShrotError, "1 ms or more", ErrorCode.INVALID_ARGUMENT) + check("answer_timeout = 0: refused", ok and kitchen.answer_timeout == ANSWER_TIMEOUT_SECONDS, detail) + slow = Client.from_file(os.path.join(folder, "kitchen.toml"), dll_path) + slow.answer_timeout = 0.3 + slow.connect() + forever = "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n" + started = time.perf_counter() + ok, detail = raises(lambda: slow.query(forever), ConnectionLostError, code=ErrorCode.CONNECTION_LOST) + elapsed = time.perf_counter() - started + check("A query past answer_timeout (0.3 s, set before connecting): ConnectionLostError, disconnected", + ok and elapsed < 5 and not slow.connected, f"{detail}, {elapsed * 1000:.0f} ms") + slow.connect() + slow.answer_timeout = 0.2 + check("answer_timeout set while connected: kept, the connection too", slow.answer_timeout == 0.2 and slow.connected) + ok, detail = raises(lambda: slow.query(forever), ConnectionLostError, code=ErrorCode.CONNECTION_LOST) + check("A query past it again: ConnectionLostError", ok, detail) + slow.close() + + # --- Two Clients, two threads, at the same time -------------------------- + other = Client.from_file(os.path.join(folder, "kitchen.toml"), dll_path).connect() + pushed = {} + + def pusher(name, client): + pushed[name] = [client.push({"thread": name, "n": n}, "secret") for n in range(30)] + + threads = [threading.Thread(target=pusher, args=("a", kitchen)), threading.Thread(target=pusher, args=("b", other))] + started = time.perf_counter() + for thread in threads: + thread.start() + for thread in threads: + thread.join(30) + elapsed = time.perf_counter() - started + every = sorted(pushed.get("a", []) + pushed.get("b", [])) + check("Two Clients pushing from two threads at once: every push stored, each id once", + len(every) == 60 and every == list(range(every[0], every[0] + 60)), + f"{len(every)} pushes in {elapsed * 1000:.0f} ms") + other.close() check("close(): disconnected", not kitchen.connected) ok, detail = raises(lambda: kitchen.push("x", "logs"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED) check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail) +ok, detail = raises(kitchen.ping, ConnectionLostError, code=ErrorCode.NOT_CONNECTED) +check("ping() once closed: ConnectionLostError, NOT_CONNECTED", ok, detail) # --- Connecting: unreachable, refused, PEM text ---------------------------------- with open(kitchen.ca) as ca, open(kitchen.certificate) as certificate, open(kitchen.key) as key: diff --git a/build.ps1 b/build.ps1 index 3505129..de0754f 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,7 +1,12 @@ -# Builds everything (the server, the tools, the client library), release -# mode, into target\release\. -# Usage: powershell -ExecutionPolicy Bypass -File build.ps1 +# Builds everything (the server, the tool, the client library), release +# mode, into target\release\: the tool with its own profile (release-tools, +# Cargo.toml) in target\release-tools\, then copied beside the others. +# -HybridCrt: the UCRT from Windows instead of linked in, about 180 KB less +# per program (.cargo/hybrid-crt.toml). +# Usage: powershell -ExecutionPolicy Bypass -File build.ps1 [-HybridCrt] +param([switch]$HybridCrt) $ErrorActionPreference = "Stop" +$crt = if ($HybridCrt) { @("--config", ".cargo/hybrid-crt.toml") } else { @() } # rustup's folder isn't always on the PATH (it isn't in every shell here). if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) { @@ -10,8 +15,12 @@ if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) { Push-Location $PSScriptRoot try { - cargo build --workspace --release --locked + cargo build --workspace --exclude bakashrot-tools --release --locked @crt if ($LASTEXITCODE -ne 0) { "FAILED: cargo build"; exit 1 } + cargo build -p bakashrot-tools --profile release-tools --locked @crt + if ($LASTEXITCODE -ne 0) { "FAILED: cargo build (the tool)"; exit 1 } + $tool = if ($IsLinux -or $IsMacOS) { "bakashrot" } else { "bakashrot.exe" } + Copy-Item (Join-Path "target\release-tools" $tool) "target\release" -Force } finally { Pop-Location } diff --git a/building.md b/building.md index bd963fc..c89e008 100644 --- a/building.md +++ b/building.md @@ -8,13 +8,13 @@ From the repository's root, on Windows (`powershell -ExecutionPolicy Bypass -Fil | Script | What it does | |---|---| -| `build.ps1` | Builds everything, release mode, into `target\release\` | +| `build.ps1` | Builds everything, release mode, into `target\release\` (the tool with the `release-tools` profile, copied there); `-HybridCrt` | | `test.ps1` | What CI runs: formatting, clippy (warnings are errors), the tests, the docs | -| `release.ps1` | A release for this platform, smoke-tested (`release.py`, below); `-SkipTest` | +| `release.ps1` | A release for this platform, smoke-tested (`release.py`, below); `-SkipTest`, `-HybridCrt` | | `clean.ps1` | Deletes `target\` (builds and releases) | | `bench.ps1` | The benchmarks, release mode: pushes, replication, storage (`docs/server.md`, "Measured"); `-Only`, `-Sync full` or `normal` | -Elsewhere, the same with cargo: `cargo build --release`, `cargo test`, `python release.py`, `cargo clean`; +Elsewhere, the same with cargo: `cargo build --release` (and `-p bakashrot-tools --profile release-tools`), `cargo test`, `python release.py`, `cargo clean`; the benchmarks are ignored tests (`cargo test --release -- --ignored`). Generated keys and certificates never go in git. @@ -23,7 +23,7 @@ Generated keys and certificates never go in git. A Cargo workspace: ``` -Cargo.toml the workspace: shared lints, release profile +Cargo.toml the workspace: shared lints, the release profiles (release-tools: the tool's) rust-toolchain.toml the pinned toolchain (1.100.0) build.ps1, test.ps1, release.ps1, clean.ps1, bench.ps1 release.py a release for this platform: build, package, smoke test @@ -37,24 +37,26 @@ crates/ bakashrot-server/ the server: TLS, identities, requests, the writer thread (and its program) bakashrot-client/ the client library, Rust API, blocking bakashrot-capi/ the C DLL over bakashrot-client: the BakaShrot_* exports (bakashrot.dll) - bakashrot-tools/ the CLI tools: bakashrot (push, read, query, list), bakashrot-cert + bakashrot-tools/ the CLI tool: bakashrot (push, read, query, list; cert: the certificates) bindings/ c/ bakashrot.h, generated from bakashrot-capi purebasic/ the prototypes and error codes python/ bakashrot.py over the DLL, check_bakashrot.py, make_wheel.py -.cargo/config.toml the C runtime linked statically on Windows + csharp/ NibblePoker.BakaShrot.Client/: BakaShrot.cs over the DLL (net35, netstandard2.0), the NuGet package; its .Tests/ (NUnit) +.cargo/config.toml the C runtime linked statically on Windows, SQLite's options +.cargo/hybrid-crt.toml -HybridCrt: the UCRT from Windows instead (about 180 KB less per program) docker/ the server's image: Dockerfile, compose.yml, test.sh ``` Dependencies only point downward: `proto`, `pki`, `config` and `storage` don't open sockets and are tested -on their own; `server` and `client` use them; the DLL and the tools only use `client`. +on their own; `server` and `client` use them; the DLL and the tool only use `client`. ## Releases `python release.py` (or `release.ps1`) on Windows or Linux, x64 or ARM64, builds that platform's release into `target/dist/bakashrot--/` and its archive (`.zip`, `.tar.gz`): -the server, `bakashrot`, `bakashrot-cert`, the client library with its C header and PureBasic prototypes, -`bakashrot.py` and a wheel with the library in it (`bindings/python/make_wheel.py`), the example configs, +the server, `bakashrot` (the certificates too: `bakashrot cert`), the client library with its C header and PureBasic prototypes, +`bakashrot.py` and a wheel with the library in it (`bindings/python/make_wheel.py`), `BakaShrot.cs`, the example configs, `docs/`, a `README.txt`, the licenses (`THIRD-PARTY.txt`: every crate built in, from `cargo metadata`). Then it checks it, in the folder's `_test/`: a CA and certificates, the server on a free port, @@ -64,7 +66,9 @@ which must end cleanly (`_test/` kept if not). `--skip-test` skips it. CI ([.github/workflows/ci.yml](.github/workflows/ci.yml)) runs on a version tag (`v*`) or by hand: `test.ps1`'s checks on Windows and Linux, then a release on each of Windows x64 and ARM64, Linux x64 and ARM64, each on its own -kind of machine (so its smoke test runs there), its archive kept as the run's artifact. The Linux ones build +kind of machine (so its smoke test runs there), its archive kept as the run's artifact; then the C# client's +NuGet package, `NibblePoker.BakaShrot.Client`, packed from the four releases' libraries +(`runtimes//native/`) and kept as the `bakashrot-nuget` artifact. The Linux ones build in a manylinux 2.28 container, so they run with glibc 2.28 and later. The version is the workspace's (`Cargo.toml`), and `bindings/python/bakashrot.py`'s `__version__` must be the same. diff --git a/crates/bakashrot-capi/Cargo.toml b/crates/bakashrot-capi/Cargo.toml index 8a1dff3..c2bfb6b 100644 --- a/crates/bakashrot-capi/Cargo.toml +++ b/crates/bakashrot-capi/Cargo.toml @@ -1,6 +1,6 @@ [package] 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 edition.workspace = true rust-version.workspace = true diff --git a/crates/bakashrot-capi/src/enumerations.rs b/crates/bakashrot-capi/src/enumerations.rs new file mode 100644 index 0000000..bba5f99 --- /dev/null +++ b/crates/bakashrot-capi/src/enumerations.rs @@ -0,0 +1,365 @@ +//! Enumerations: a list of names or a query's rows, kept whole, read an +//! item at a time like Win32's `FindFirstFile` / `FindNextFile` / +//! `FindClose`. `Next...()` first (an enumeration starts before its first +//! item), then the getters; `BakaShrot_CloseEnum()` once done, or +//! `BakaShrot_FreeClient()` closes its client's. + +use super::{ + Error, HANDLES, Result, State, Text, Utf8, Utf16, bool_result, call, fetch_names, fetch_query, + invalid, lock, text, +}; +use bakashrot_proto::ErrorCode; +use std::ffi::c_char; +use std::panic::{AssertUnwindSafe, catch_unwind}; + +/// An answer of a client, kept whole. +pub(crate) struct Enumeration { + pub(crate) client: i64, + items: Items, +} + +enum Items { + Names { + names: Cursor, + truncated: bool, + }, + Query { + columns: Vec, + rows: Cursor>>, + }, +} + +/// Items and where it's at: 0 before the first, `n` on the `n`th, the +/// count + 1 past the last. +struct Cursor { + items: Vec, + position: usize, +} + +impl Cursor { + fn new(items: Vec) -> Cursor { + Cursor { items, position: 0 } + } + + /// Moves to the next item: whether there was one. + fn advance(&mut self) -> bool { + self.position = (self.position + 1).min(self.items.len() + 1); + self.position <= self.items.len() + } + + fn current(&self) -> Option<&T> { + self.items.get(self.position.checked_sub(1)?) + } +} + +/// Runs `fetch` on a client, keeps what it gives as an enumeration of that +/// client: its handle, 0 if it failed (the client's last error says why). +fn enumerate(client: i64, fetch: impl FnOnce(&mut State) -> Result) -> i64 { + call(client, 0, |state| { + let items = fetch(state)?; + let handles = &mut *lock(&HANDLES); + // Freed by another thread during the call: its enumerations went. + if !handles.clients.contains_key(&client) { + return Err(invalid(format!("client {client} freed during the call"))); + } + let handle = handles.take(); + handles + .enumerations + .insert(handle, Enumeration { client, items }); + Ok(handle) + }) +} + +/// Reads an enumeration: `default` for a bad handle, or `read` giving +/// `None` (one of the other kind, no current item, no such column). +fn read(handle: i64, default: R, read: impl FnOnce(&mut Items) -> Option) -> R { + catch_unwind(AssertUnwindSafe(|| { + let handles = &mut *lock(&HANDLES); + read(&mut handles.enumerations.get_mut(&handle)?.items) + })) + .ok() + .flatten() + .unwrap_or(default) +} + +/// A column index, as arguments. +fn column(index: i32) -> Option { + usize::try_from(index).ok() +} + +/// Closes an enumeration: 1, or 0 if it wasn't one. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_CloseEnum(enumeration: i64) -> isize { + let closed = catch_unwind(|| lock(&HANDLES).enumerations.remove(&enumeration).is_some()); + bool_result(closed.unwrap_or(false)) +} + +// --- Names ------------------------------------------------------------------- + +unsafe fn enumerate_names( + client: i64, + kind: i32, + topics: *const T::Unit, + nodes: *const T::Unit, +) -> i64 { + enumerate(client, |state| { + let list = unsafe { fetch_names::(state, kind, topics, nodes)? }; + Ok(Items::Names { + names: Cursor::new(list.names), + truncated: list.truncated, + }) + }) +} + +/// Lists names as `BakaShrot_ListNames()` does (the same arguments), into +/// an enumeration: its handle, 0 on failure (`BakaShrot_GetLastError(client)`). +/// Then `BakaShrot_NextName()` and `BakaShrot_GetEnumName()`, and +/// `BakaShrot_CloseEnum()`. Closed with its client by +/// `BakaShrot_FreeClient()`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_EnumerateNamesA( + client: i64, + kind: i32, + topics: *const c_char, + nodes: *const c_char, +) -> i64 { + unsafe { enumerate_names::(client, kind, topics.cast(), nodes.cast()) } +} + +/// The same as `BakaShrot_EnumerateNamesA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_EnumerateNamesW( + client: i64, + kind: i32, + topics: *const u16, + nodes: *const u16, +) -> i64 { + unsafe { enumerate_names::(client, kind, topics, nodes) } +} + +/// Moves to the next name (the first, the first time): 1, 0 if there are +/// no more, -1 if it isn't a names enumeration. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_NextName(enumeration: i64) -> isize { + read(enumeration, -1, |items| match items { + Items::Names { names, .. } => Some(bool_result(names.advance())), + Items::Query { .. } => None, + }) +} + +unsafe fn enum_name(enumeration: i64, buffer: *mut T::Unit, size: isize) -> isize { + read(enumeration, 0, |items| match items { + Items::Names { names, .. } => names + .current() + .map(|name| unsafe { text::copy::(name, buffer, size) }), + Items::Query { .. } => None, + }) +} + +/// The current name: the bytes it needs, 0 if there's none (before the +/// first, past the last) or it isn't a names enumeration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetEnumNameA( + enumeration: i64, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { enum_name::(enumeration, buffer.cast(), size) } +} + +/// The same as `BakaShrot_GetEnumNameA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetEnumNameW( + enumeration: i64, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { enum_name::(enumeration, buffer, size) } +} + +/// How many names, -1 if it isn't a names enumeration. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_GetNameCount(enumeration: i64) -> i32 { + read(enumeration, -1, |items| match items { + Items::Names { names, .. } => Some(names.items.len() as i32), + Items::Query { .. } => None, + }) +} + +/// Whether some names didn't fit in the server's answer: 1 or 0, -1 if it +/// isn't a names enumeration. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_IsNamesListTruncated(enumeration: i64) -> isize { + read(enumeration, -1, |items| match items { + Items::Names { truncated, .. } => Some(bool_result(*truncated)), + Items::Query { .. } => None, + }) +} + +// --- Queries ----------------------------------------------------------------- + +/// The server's `{"columns":[...],"rows":[[...],...]}`, each value a +/// string or null. +fn parse_query(json: &str) -> Option { + let value: serde_json::Value = serde_json::from_str(json).ok()?; + let columns = value + .get("columns")? + .as_array()? + .iter() + .map(|column| column.as_str().map(str::to_owned)) + .collect::>>()?; + let rows = value + .get("rows")? + .as_array()? + .iter() + .map(|row| { + row.as_array()? + .iter() + .map(|value| match value { + serde_json::Value::Null => Some(None), + serde_json::Value::String(text) => Some(Some(text.clone())), + _ => None, + }) + .collect::>>() + }) + .collect::>>()?; + Some(Items::Query { + columns, + rows: Cursor::new(rows), + }) +} + +unsafe fn enumerate_query(client: i64, sql: *const T::Unit) -> i64 { + enumerate(client, |state| { + let json = unsafe { fetch_query::(state, sql)? }; + parse_query(&json) + .ok_or_else(|| Error::new(ErrorCode::Internal, "the server's query result isn't one")) + }) +} + +/// Runs a query as `BakaShrot_Query()` does, into an enumeration: its +/// handle, 0 on failure (`BakaShrot_GetLastError(client)`). Then +/// `BakaShrot_GetQueryColumnCount()` and `GetQueryColumnName()`, +/// `BakaShrot_NextQueryRow()` and `GetQueryValue()` / `IsQueryValueNull()`, +/// and `BakaShrot_CloseEnum()`. Closed with its client by +/// `BakaShrot_FreeClient()`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_EnumerateQueryA(client: i64, sql: *const c_char) -> i64 { + unsafe { enumerate_query::(client, sql.cast()) } +} + +/// The same as `BakaShrot_EnumerateQueryA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_EnumerateQueryW(client: i64, sql: *const u16) -> i64 { + unsafe { enumerate_query::(client, sql) } +} + +/// How many columns, -1 if it isn't a query enumeration. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_GetQueryColumnCount(enumeration: i64) -> i32 { + read(enumeration, -1, |items| match items { + Items::Query { columns, .. } => Some(columns.len() as i32), + Items::Names { .. } => None, + }) +} + +unsafe fn column_name( + enumeration: i64, + index: i32, + buffer: *mut T::Unit, + size: isize, +) -> isize { + read(enumeration, 0, |items| match items { + Items::Query { columns, .. } => columns + .get(column(index)?) + .map(|name| unsafe { text::copy::(name, buffer, size) }), + Items::Names { .. } => None, + }) +} + +/// A column's name (`index` 0 to the count - 1): the bytes it needs, 0 if +/// there's no such column or it isn't a query enumeration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetQueryColumnNameA( + enumeration: i64, + index: i32, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { column_name::(enumeration, index, buffer.cast(), size) } +} + +/// The same as `BakaShrot_GetQueryColumnNameA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetQueryColumnNameW( + enumeration: i64, + index: i32, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { column_name::(enumeration, index, buffer, size) } +} + +/// Moves to the next row (the first, the first time): 1, 0 if there are +/// no more, -1 if it isn't a query enumeration. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_NextQueryRow(enumeration: i64) -> isize { + read(enumeration, -1, |items| match items { + Items::Query { rows, .. } => Some(bool_result(rows.advance())), + Items::Names { .. } => None, + }) +} + +/// The current row's value in a column: `None` without a row or column. +fn value(items: &Items, index: i32) -> Option<&Option> { + match items { + Items::Query { rows, .. } => rows.current()?.get(column(index)?), + Items::Names { .. } => None, + } +} + +unsafe fn query_value( + enumeration: i64, + index: i32, + buffer: *mut T::Unit, + size: isize, +) -> isize { + read(enumeration, 0, |items| { + value(items, index)? + .as_deref() + .map(|text| unsafe { text::copy::(text, buffer, size) }) + }) +} + +/// The current row's value in a column (`index` 0 to the count - 1): the +/// bytes it needs, 0 if it's null (`BakaShrot_IsQueryValueNull()`), there's +/// no current row or such column, or it isn't a query enumeration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetQueryValueA( + enumeration: i64, + index: i32, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { query_value::(enumeration, index, buffer.cast(), size) } +} + +/// The same as `BakaShrot_GetQueryValueA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetQueryValueW( + enumeration: i64, + index: i32, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { query_value::(enumeration, index, buffer, size) } +} + +/// Whether the current row's value in a column is null: 1 or 0, -1 if +/// there's no current row or such column, or it isn't a query enumeration. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_IsQueryValueNull(enumeration: i64, index: i32) -> isize { + read(enumeration, -1, |items| { + value(items, index).map(|value| bool_result(value.is_none())) + }) +} diff --git a/crates/bakashrot-capi/src/lib.rs b/crates/bakashrot-capi/src/lib.rs index ce1deb4..2330a35 100644 --- a/crates/bakashrot-capi/src/lib.rs +++ b/crates/bakashrot-capi/src/lib.rs @@ -1,54 +1,89 @@ -//! 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, //! Python (ctypes) and anything that loads a DLL. `docs/client.md` //! has the whole API; `bindings/c/bakashrot.h` is generated from this file. //! //! The conventions: //! -//! - **One connection per process:** set the certificates, connect, send -//! requests, one at a time (calls from several threads wait for each -//! other). +//! - **Clients:** `BakaShrot_CreateClient()` makes one; its handle is the +//! first argument of every other export. Each has its own connection, +//! answers and errors; different clients can be used from different +//! threads at once. +//! - **Enumerations** (`BakaShrot_EnumerateNames()`, `EnumerateQuery()`): +//! an answer kept whole, read with `Next...()` (before the first item +//! at first) and its getters, closed with `BakaShrot_CloseEnum()` or +//! with their client by `BakaShrot_FreeClient()`. Their handles are +//! numbered with the clients', so one is never the other's. //! - **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or //! UTF-16 (`uint16_t*`, `wchar_t*` on Windows), null-terminated. //! - **Strings out** are copied into the caller's buffer of `BufferSize` //! bytes: the getter returns the bytes needed, terminator included, and //! 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 -//! `BakaShrot_GetLastError()` gives the code (1-99 a server's refusal, the -//! connection still open; 100 and up the client's own) and +//! `BakaShrot_GetLastError(Client)` gives the code (1-99 a server's +//! refusal, the connection still open; 100 and up the client's own) and //! `BakaShrot_GetRefusalReason()` why, in words. After `ConnectionLost` //! or `ProtocolError` the connection is closed: connect again. //! - **Safety:** pointers are null or valid for what's said, strings -//! terminated, buffers writable for their size. A panic inside is caught -//! and reported as `Internal`; nothing allocated here is freed by the -//! caller, or the other way. +//! terminated, buffers writable for their size. A bad handle fails +//! (`InvalidArgument`). A panic inside is caught and reported as +//! `Internal`; nothing allocated here is freed by the caller, or the +//! other way. #![allow(unsafe_code, non_snake_case, clippy::missing_safety_doc)] +mod enumerations; +pub use enumerations::*; mod text; -use bakashrot_client::{Client, Error, Settings}; +use bakashrot_client::{ANSWER_TIMEOUT, Client, Error, Settings}; use bakashrot_proto::ErrorCode; -use bakashrot_proto::packets::{MessageEntry, NameKind}; +use bakashrot_proto::packets::{MessageEntry, NameKind, NamesList}; +use std::collections::BTreeMap; use std::ffi::{c_char, c_void}; use std::fs::File; use std::io::Cursor; use std::panic::{AssertUnwindSafe, catch_unwind}; use std::path::Path; -use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::Duration; use text::{Text, Utf8, Utf16}; type Result = std::result::Result; -/// Everything the DLL holds: its one connection, its settings, the last -/// answers. -static STATE: Mutex = Mutex::new(State::new()); +/// The clients and enumerations by handle. A call holds its client's +/// `Arc`, so a client freed during a call goes when the call ends. +static HANDLES: Mutex = Mutex::new(Handles { + next: 1, + clients: BTreeMap::new(), + enumerations: BTreeMap::new(), +}); +struct Handles { + /// The next handle, of a client or an enumeration: never reused. + next: i64, + clients: BTreeMap, + /// Freed with their client. Only ever copied from, under this lock. + enumerations: BTreeMap, +} + +impl Handles { + fn take(&mut self) -> i64 { + self.next += 1; + self.next - 1 + } +} + +type Shared = Arc>; + +/// A client: its settings, its connection, the last answers. struct State { ca: Option, certificate: Option, key: Option, crl: Option, + /// Given to each connection, and to the current one when set. + answer_timeout: Duration, client: Option, /// The last call's error code, 0 if it succeeded. last_error: u32, @@ -60,7 +95,7 @@ struct State { messages: Vec, selected: usize, more: bool, - /// The last `ListTopics` / `ListNodes`, as JSON. + /// The last `ListNames`, as JSON. names: String, /// The last `Query`'s result. query: String, @@ -75,6 +110,7 @@ impl State { certificate: None, key: None, crl: None, + answer_timeout: ANSWER_TIMEOUT, client: None, last_error: 0, reason: String::new(), @@ -92,10 +128,10 @@ impl State { fn fail(&mut self, error: Error) { self.last_error = error.code(); self.reason = error.message().to_owned(); - let closed = [ErrorCode::ConnectionLost, ErrorCode::ProtocolError] - .iter() - .any(|code| code.code() == error.code()); - if closed { + // The client closes its connection on every failure that leaves it + // out of step (`ConnectionLost`, `ProtocolError`, a file failing + // mid-upload): forgotten then, so connecting again works. + if self.client.as_ref().is_some_and(Client::is_closed) { self.client = None; } } @@ -124,15 +160,22 @@ impl State { } } -fn state() -> MutexGuard<'static, State> { - STATE.lock().unwrap_or_else(PoisonError::into_inner) +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) } -/// Runs a call that can fail: the last error reset, then set if it fails -/// (or panics), `failed` returned then. -fn call(failed: T, run: impl FnOnce(&mut State) -> Result) -> T { +fn find(client: i64) -> Option { + lock(&HANDLES).clients.get(&client).cloned() +} + +/// 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(client: i64, failed: T, run: impl FnOnce(&mut State) -> Result) -> T { + let Some(shared) = find(client) else { + return failed; + }; let outcome = catch_unwind(AssertUnwindSafe(|| { - let mut state = state(); + let mut state = lock(&shared); state.last_error = 0; state.reason.clear(); let outcome = run(&mut state); @@ -142,20 +185,29 @@ fn call(failed: T, run: impl FnOnce(&mut State) -> Result) -> T { Ok(Ok(value)) => value, Ok(Err(())) => failed, Err(_) => { - state().fail(Error::new(ErrorCode::Internal, "the DLL panicked")); + lock(&shared).fail(Error::new(ErrorCode::Internal, "the DLL panicked")); failed } } } -/// Runs a getter: the last error stays as it is. -fn get(default: T, read: impl FnOnce(&State) -> T) -> T { - catch_unwind(AssertUnwindSafe(|| read(&state()))).unwrap_or(default) +/// Runs a getter on a client, its last error unchanged. `default` for a +/// bad handle. +fn get(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. -unsafe fn get_text(buffer: *mut T::Unit, size: isize, text: fn(&State) -> &str) -> isize { - get(0, |state| unsafe { +/// Copies a string of a client's state into the caller's buffer. +unsafe fn get_text( + client: i64, + buffer: *mut T::Unit, + size: isize, + text: fn(&State) -> &str, +) -> isize { + get(client, 0, |state| unsafe { text::copy::(text(state), buffer, size) }) } @@ -164,37 +216,101 @@ fn invalid(why: impl Into) -> Error { Error::new(ErrorCode::InvalidArgument, why) } -fn required(value: Option, what: &str) -> Result { - value.ok_or_else(|| invalid(format!("no {what} (a null pointer)"))) +/// A string argument that must be there: `InvalidArgument` for a null +/// pointer. +unsafe fn required(pointer: *const T::Unit, what: &str) -> Result { + unsafe { text::read::(pointer, what)? } + .ok_or_else(|| invalid(format!("no {what} (a null pointer)"))) +} + +/// Settings change only before connecting. +fn not_connected(state: &State) -> Result<()> { + match state.client { + Some(_) => Err(Error::new( + ErrorCode::AlreadyConnected, + "already connected: disconnect first", + )), + None => Ok(()), + } } fn bool_result(ok: bool) -> isize { 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 handles = &mut *lock(&HANDLES); + let client = handles.take(); + handles + .clients + .insert(client, Arc::new(Mutex::new(State::new()))); + client + }); + made.unwrap_or(0) +} + +/// Frees a client and closes its connection (once a call on it in another +/// thread ends), its enumerations closed too: 1, or 0 if it wasn't one. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_FreeClient(client: i64) -> isize { + let freed = catch_unwind(|| { + let handles = &mut *lock(&HANDLES); + handles + .enumerations + .retain(|_, enumeration| enumeration.client != client); + handles.clients.remove(&client).is_some() + }); + bool_result(freed.unwrap_or(false)) +} + // --- Errors ------------------------------------------------------------------ -/// Why the last call failed: a protocol error code (1-99 a server's -/// refusal, the connection still open; 100 and up the client's own), 0 if -/// it succeeded. Getters don't change it. +/// 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. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_GetLastError() -> i32 { - get(ErrorCode::Internal.code() as i32, |state| { +pub extern "C" fn BakaShrot_GetLastError(client: i64) -> i32 { + get(client, ErrorCode::InvalidArgument.code() as i32, |state| { state.last_error as i32 }) } -/// Why the last call failed, in words: the server's reason for a refusal, -/// the client's otherwise. Empty if it succeeded. +/// The client's reason, or why its handle is bad. +unsafe fn refusal_reason(client: i64, buffer: *mut T::Unit, size: isize) -> isize { + match find(client) { + Some(_) => unsafe { get_text::(client, buffer, size, |state| &state.reason) }, + None => { + let why = format!("no client {client}: never made, or freed"); + unsafe { text::copy::(&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)] -pub unsafe extern "C" fn BakaShrot_GetRefusalReasonA(buffer: *mut c_char, size: isize) -> isize { - unsafe { get_text::(buffer.cast(), size, |state| &state.reason) } +pub unsafe extern "C" fn BakaShrot_GetRefusalReasonA( + client: i64, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { refusal_reason::(client, buffer.cast(), size) } } /// The same as `BakaShrot_GetRefusalReasonA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetRefusalReasonW(buffer: *mut u16, size: isize) -> isize { - unsafe { get_text::(buffer, size, |state| &state.reason) } +pub unsafe extern "C" fn BakaShrot_GetRefusalReasonW( + client: i64, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { refusal_reason::(client, buffer, size) } } // --- Settings ---------------------------------------------------------------- @@ -218,18 +334,14 @@ fn pem_or_file(value: Option, what: &str, optional: bool) -> Result( + client: i64, value: *const T::Unit, what: &str, optional: bool, slot: fn(&mut State) -> &mut Option, ) -> isize { - call(0, |state| { - if state.client.is_some() { - return Err(Error::new( - ErrorCode::AlreadyConnected, - "already connected: disconnect first", - )); - } + call(client, 0, |state| { + not_connected(state)?; let value = unsafe { text::read::(value, what)? }; *slot(state) = pem_or_file(value, what, optional)?; Ok(1) @@ -239,26 +351,43 @@ unsafe fn set( /// 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. #[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 { - set::(certificate.cast(), "CA certificate", false, |state| { - &mut state.ca - }) + set::( + client, + certificate.cast(), + "CA certificate", + false, + |state| &mut state.ca, + ) } } /// The same as `BakaShrot_SetCaCertificateA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_SetCaCertificateW(certificate: *const u16) -> isize { - unsafe { set::(certificate, "CA certificate", false, |state| &mut state.ca) } +pub unsafe extern "C" fn BakaShrot_SetCaCertificateW( + client: i64, + certificate: *const u16, +) -> isize { + unsafe { + set::(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. #[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 { - set::(certificate.cast(), "certificate", false, |state| { + set::(client, certificate.cast(), "certificate", false, |state| { &mut state.certificate }) } @@ -266,52 +395,51 @@ pub unsafe extern "C" fn BakaShrot_SetCertificateA(certificate: *const c_char) - /// The same as `BakaShrot_SetCertificateA`, in UTF-16. #[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 { - set::(certificate, "certificate", false, |state| { + set::(client, certificate, "certificate", false, |state| { &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. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_SetPrivateKeyA(key: *const c_char) -> isize { - unsafe { set::(key.cast(), "private key", false, |state| &mut state.key) } +pub unsafe extern "C" fn BakaShrot_SetPrivateKeyA(client: i64, key: *const c_char) -> isize { + unsafe { + set::(client, key.cast(), "private key", false, |state| { + &mut state.key + }) + } } /// The same as `BakaShrot_SetPrivateKeyA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_SetPrivateKeyW(key: *const u16) -> isize { - unsafe { set::(key, "private key", false, |state| &mut state.key) } +pub unsafe extern "C" fn BakaShrot_SetPrivateKeyW(client: i64, key: *const u16) -> isize { + unsafe { set::(client, key, "private key", false, |state| &mut state.key) } } /// Sets the CA's CRL, optional: servers it revokes are refused. PEM text, /// or the path of a file holding it (one that isn't there is a /// `FileError`); null or empty for none. Before connecting. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_SetCrlA(crl: *const c_char) -> isize { - unsafe { set::(crl.cast(), "CRL", true, |state| &mut state.crl) } +pub unsafe extern "C" fn BakaShrot_SetCrlA(client: i64, crl: *const c_char) -> isize { + unsafe { set::(client, crl.cast(), "CRL", true, |state| &mut state.crl) } } /// The same as `BakaShrot_SetCrlA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_SetCrlW(crl: *const u16) -> isize { - unsafe { set::(crl, "CRL", true, |state| &mut state.crl) } +pub unsafe extern "C" fn BakaShrot_SetCrlW(client: i64, crl: *const u16) -> isize { + unsafe { set::(client, crl, "CRL", true, |state| &mut state.crl) } } // --- The connection ---------------------------------------------------------- -unsafe fn connect(host: *const T::Unit, port: i32) -> isize { - call(0, |state| { - if state.client.is_some() { - return Err(Error::new( - ErrorCode::AlreadyConnected, - "already connected: disconnect first", - )); - } - let host = required(unsafe { text::read::(host, "host")? }, "host")?; +unsafe fn connect(client: i64, host: *const T::Unit, port: i32) -> isize { + call(client, 0, |state| { + not_connected(state)?; + let host = unsafe { required::(host, "host")? }; let port = u16::try_from(port) .ok() .filter(|port| *port != 0) @@ -337,7 +465,8 @@ unsafe fn connect(host: *const T::Unit, port: i32) -> isize { true => format!("[{host}]:{port}"), false => format!("{host}:{port}"), }; - let client = Client::connect(&address, &settings)?; + let mut client = Client::connect(&address, &settings)?; + client.set_answer_timeout(state.answer_timeout)?; state.client = Some(client); Ok(1) }) @@ -349,57 +478,101 @@ unsafe fn connect(host: *const T::Unit, port: i32) -> isize { /// the server refused the certificate, `ServerNotVerified` this client /// refused the server's, `NotAllowed` none of its roles is the server's). #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_ConnectA(host: *const c_char, port: i32) -> isize { - unsafe { connect::(host.cast(), port) } +pub unsafe extern "C" fn BakaShrot_ConnectA(client: i64, host: *const c_char, port: i32) -> isize { + unsafe { connect::(client, host.cast(), port) } } /// The same as `BakaShrot_ConnectA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_ConnectW(host: *const u16, port: i32) -> isize { - unsafe { connect::(host, port) } +pub unsafe extern "C" fn BakaShrot_ConnectW(client: i64, host: *const u16, port: i32) -> isize { + unsafe { connect::(client, host, port) } } /// 1 while connected: notices when the server closed the connection /// (forgotten then: connect again). #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_IsConnected() -> isize { - let open = catch_unwind(AssertUnwindSafe(|| { - let mut state = state(); - let open = state.client.as_ref().is_some_and(Client::is_open); +pub extern "C" fn BakaShrot_IsConnected(client: i64) -> isize { + get(client, 0, |state| { + let open = state.client.as_mut().is_some_and(Client::is_open); if !open { state.client = None; } - open - })); - bool_result(open.unwrap_or(false)) + bool_result(open) + }) } /// Closes the connection: 0 if there was none. The settings stay. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_Disconnect() -> isize { - let closed = catch_unwind(AssertUnwindSafe(|| state().client.take().is_some())); - bool_result(closed.unwrap_or(false)) +pub extern "C" fn BakaShrot_Disconnect(client: i64) -> isize { + get(client, 0, |state| { + bool_result(state.client.take().is_some()) + }) +} + +/// Keeps the connection open: 1, or 0 if it failed (`ConnectionLost`: +/// connect again). The server closes a connection silent for 5 min; an +/// app waiting longer between requests calls this every minute or so +/// (the DLL has no thread of its own to do it). +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_Ping(client: i64) -> isize { + call(client, 0, |state| { + state.client()?.ping()?; + Ok(1) + }) +} + +/// Sets how long an answer may take, in milliseconds (more than 0; 30000 +/// until changed): longer for a slow query, say. Past it, the request +/// fails with `ConnectionLost`, the connection closed (the server then +/// stops the query it was running). Kept for the next connections, and +/// applied to the current one: 1, or 0 if refused. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_SetAnswerTimeout(client: i64, milliseconds: i64) -> isize { + call(client, 0, |state| { + let timeout = u64::try_from(milliseconds) + .ok() + .filter(|ms| *ms > 0) + .map(Duration::from_millis) + .ok_or_else(|| { + invalid(format!( + "an answer timeout of {milliseconds} ms: more than 0" + )) + })?; + if let Some(connected) = state.client.as_mut() { + connected.set_answer_timeout(timeout)?; + } + state.answer_timeout = timeout; + Ok(1) + }) +} + +/// How long an answer may take, in milliseconds (`BakaShrot_SetAnswerTimeout()`). +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_GetAnswerTimeout(client: i64) -> i64 { + get(client, -1, |state| { + i64::try_from(state.answer_timeout.as_millis()).unwrap_or(i64::MAX) + }) +} + +fn node(state: &State) -> &str { + state.client.as_ref().map_or("", Client::node) } /// The node this client is, as the server said when connecting: its /// certificate's name. Empty when not connected. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetNodeA(buffer: *mut c_char, size: isize) -> isize { - unsafe { - get_text::(buffer.cast(), size, |state| { - state.client.as_ref().map_or("", Client::node) - }) - } +pub unsafe extern "C" fn BakaShrot_GetNodeA( + client: i64, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer.cast(), size, node) } } /// The same as `BakaShrot_GetNodeA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetNodeW(buffer: *mut u16, size: isize) -> isize { - unsafe { - get_text::(buffer, size, |state| { - state.client.as_ref().map_or("", Client::node) - }) - } +pub unsafe extern "C" fn BakaShrot_GetNodeW(client: i64, buffer: *mut u16, size: isize) -> isize { + unsafe { get_text::(client, buffer, size, node) } } // --- Pushing ----------------------------------------------------------------- @@ -410,13 +583,13 @@ unsafe fn topic_and_data( topic: *const T::Unit, data: *const T::Unit, ) -> Result<(String, String)> { - let topic = required(unsafe { text::read::(topic, "topic")? }, "topic")?; + let topic = unsafe { required::(topic, "topic")? }; let data = unsafe { text::read::(data, "the message")? }.unwrap_or_default(); Ok((topic, data)) } -unsafe fn push_to(topic: *const T::Unit, data: *const T::Unit) -> i64 { - call(-1, |state| { +unsafe fn push_to(client: i64, topic: *const T::Unit, data: *const T::Unit) -> i64 { + call(client, -1, |state| { let (topic, data) = unsafe { topic_and_data::(topic, data)? }; let id = state.client()?.push(&topic, &data)?; Ok(id as i64) @@ -428,16 +601,21 @@ unsafe fn push_to(topic: *const T::Unit, data: *const T::Unit) -> i64 { /// (`ConnectionLost`) may have been stored all the same. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_PushMessageToA( + client: i64, topic: *const c_char, data: *const c_char, ) -> i64 { - unsafe { push_to::(topic.cast(), data.cast()) } + unsafe { push_to::(client, topic.cast(), data.cast()) } } /// The same as `BakaShrot_PushMessageToA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_PushMessageToW(topic: *const u16, data: *const u16) -> i64 { - unsafe { push_to::(topic, data) } +pub unsafe extern "C" fn BakaShrot_PushMessageToW( + client: i64, + topic: *const u16, + data: *const u16, +) -> i64 { + unsafe { push_to::(client, topic, data) } } // --- Reading ----------------------------------------------------------------- @@ -447,13 +625,13 @@ unsafe fn topic_and_node( topic: *const T::Unit, node: *const T::Unit, ) -> Result<(String, String)> { - let topic = required(unsafe { text::read::(topic, "topic")? }, "topic")?; - let node = required(unsafe { text::read::(node, "node")? }, "node")?; + let topic = unsafe { required::(topic, "topic")? }; + let node = unsafe { required::(node, "node")? }; Ok((topic, node)) } -unsafe fn latest_of(topic: *const T::Unit, node: *const T::Unit) -> isize { - call(0, |state| { +unsafe fn latest_of(client: i64, topic: *const T::Unit, node: *const T::Unit) -> isize { + call(client, 0, |state| { let (topic, node) = unsafe { topic_and_node::(topic, node)? }; state.clear_messages(&topic, &node); let answer = state.client()?.get_messages(&topic, &node, None, 1)?; @@ -472,28 +650,31 @@ unsafe fn latest_of(topic: *const T::Unit, node: *const T::Unit) -> isi /// `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfA( + client: i64, topic: *const c_char, node: *const c_char, ) -> isize { - unsafe { latest_of::(topic.cast(), node.cast()) } + unsafe { latest_of::(client, topic.cast(), node.cast()) } } /// The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfW( + client: i64, topic: *const u16, node: *const u16, ) -> isize { - unsafe { latest_of::(topic, node) } + unsafe { latest_of::(client, topic, node) } } unsafe fn messages( + client: i64, topic: *const T::Unit, node: *const T::Unit, after: i64, limit: i32, ) -> i32 { - call(-1, |state| { + call(client, -1, |state| { let (topic, node) = unsafe { topic_and_node::(topic, node)? }; state.clear_messages(&topic, &node); let after = @@ -515,36 +696,38 @@ unsafe fn messages( /// `BakaShrot_HasMoreMessages()` says whether more follow the last one. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_GetMessagesA( + client: i64, topic: *const c_char, node: *const c_char, after: i64, limit: i32, ) -> i32 { - unsafe { messages::(topic.cast(), node.cast(), after, limit) } + unsafe { messages::(client, topic.cast(), node.cast(), after, limit) } } /// The same as `BakaShrot_GetMessagesA`, in UTF-16. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_GetMessagesW( + client: i64, topic: *const u16, node: *const u16, after: i64, limit: i32, ) -> i32 { - unsafe { messages::(topic, node, after, limit) } + unsafe { messages::(client, topic, node, after, limit) } } /// How many messages the last `GetMessages` or `GetLatestMessageOf` got. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_GetMessageCount() -> i32 { - get(0, |state| state.messages.len() as i32) +pub extern "C" fn BakaShrot_GetMessageCount(client: i64) -> i32 { + get(client, 0, |state| state.messages.len() as i32) } /// Selects the message at `index` (0 to the count - 1) for the getters: 0 /// if there's none there (`InvalidArgument`), the selection unchanged. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_SelectMessage(index: i32) -> isize { - call(0, |state| { +pub extern "C" fn BakaShrot_SelectMessage(client: i64, index: i32) -> isize { + call(client, 0, |state| { let index = usize::try_from(index) .ok() .filter(|index| *index < state.messages.len()) @@ -557,14 +740,14 @@ pub extern "C" fn BakaShrot_SelectMessage(index: i32) -> isize { /// 1 if more messages follow the last one the last `GetMessages` got: ask /// again after its id. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_HasMoreMessages() -> isize { - get(0, |state| bool_result(state.more)) +pub extern "C" fn BakaShrot_HasMoreMessages(client: i64) -> isize { + get(client, 0, |state| bool_result(state.more)) } /// The selected message's id, 0 if none. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_GetMessageId() -> i64 { - get(0, |state| { +pub extern "C" fn BakaShrot_GetMessageId(client: i64) -> i64 { + get(client, 0, |state| { state.message().map_or(0, |message| message.id as i64) }) } @@ -572,8 +755,8 @@ pub extern "C" fn BakaShrot_GetMessageId() -> i64 { /// When the selected message was pushed, by the server it was pushed to: /// milliseconds since 1970-01-01 UTC, 0 if none. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_GetMessagePushedAt() -> i64 { - get(0, |state| { +pub extern "C" fn BakaShrot_GetMessagePushedAt(client: i64) -> i64 { + get(client, 0, |state| { state .message() .map_or(0, |message| message.pushed_at as i64) @@ -582,8 +765,8 @@ pub extern "C" fn BakaShrot_GetMessagePushedAt() -> i64 { /// The selected message's attachment's size, 0 without one. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_GetMessageAttachmentSize() -> i64 { - get(0, |state| { +pub extern "C" fn BakaShrot_GetMessageAttachmentSize(client: i64) -> i64 { + get(client, 0, |state| { state .message() .and_then(|message| message.attachment.as_ref()) @@ -594,8 +777,8 @@ pub extern "C" fn BakaShrot_GetMessageAttachmentSize() -> i64 { /// 1 if the selected message's attachment is all on this server (a /// replicated one may still be on its way). #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_IsMessageAttachmentReady() -> isize { - get(0, |state| { +pub extern "C" fn BakaShrot_IsMessageAttachmentReady(client: i64) -> isize { + get(client, 0, |state| { let attachment = state .message() .and_then(|message| message.attachment.as_ref()); @@ -605,9 +788,13 @@ pub extern "C" fn BakaShrot_IsMessageAttachmentReady() -> isize { /// The selected message's data, as pushed (JSON or not). #[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 { - get_text::(buffer.cast(), size, |state| { + get_text::(client, buffer.cast(), size, |state| { state.message().map_or("", |message| &message.data) }) } @@ -615,9 +802,13 @@ pub unsafe extern "C" fn BakaShrot_GetMessageDataA(buffer: *mut c_char, size: is /// The same as `BakaShrot_GetMessageDataA`, in UTF-16. #[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 { - get_text::(buffer, size, |state| { + get_text::(client, buffer, size, |state| { state.message().map_or("", |message| &message.data) }) } @@ -625,35 +816,75 @@ pub unsafe extern "C" fn BakaShrot_GetMessageDataW(buffer: *mut u16, size: isize /// The topic the last `GetMessages` or `GetLatestMessageOf` asked for. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetMessageTopicA(buffer: *mut c_char, size: isize) -> isize { - unsafe { get_text::(buffer.cast(), size, |state| &state.topic) } +pub unsafe extern "C" fn BakaShrot_GetMessageTopicA( + client: i64, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer.cast(), size, |state| &state.topic) } } /// The same as `BakaShrot_GetMessageTopicA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetMessageTopicW(buffer: *mut u16, size: isize) -> isize { - unsafe { get_text::(buffer, size, |state| &state.topic) } +pub unsafe extern "C" fn BakaShrot_GetMessageTopicW( + client: i64, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer, size, |state| &state.topic) } } /// The node the last `GetMessages` or `GetLatestMessageOf` asked for. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetMessageNodeA(buffer: *mut c_char, size: isize) -> isize { - unsafe { get_text::(buffer.cast(), size, |state| &state.node) } +pub unsafe extern "C" fn BakaShrot_GetMessageNodeA( + client: i64, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer.cast(), size, |state| &state.node) } } /// The same as `BakaShrot_GetMessageNodeA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetMessageNodeW(buffer: *mut u16, size: isize) -> isize { - unsafe { get_text::(buffer, size, |state| &state.node) } +pub unsafe extern "C" fn BakaShrot_GetMessageNodeW( + client: i64, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer, size, |state| &state.node) } } // --- Names ------------------------------------------------------------------- -fn list(kind: NameKind) -> i32 { - call(-1, |state| { +/// Asks for a list of names: `kind` 1 topics, 2 nodes, as on the wire; +/// the filters null for any. +unsafe fn fetch_names( + state: &mut State, + kind: i32, + topics: *const T::Unit, + nodes: *const T::Unit, +) -> Result { + let kind = u8::try_from(kind) + .ok() + .and_then(|kind| NameKind::try_from(kind).ok()) + .ok_or_else(|| invalid(format!("a kind of {kind}: 1 (topics) or 2 (nodes)")))?; + let topics = unsafe { text::read::(topics, "topics")? }; + let nodes = unsafe { text::read::(nodes, "nodes")? }; + state + .client()? + .list_names(kind, topics.as_deref(), nodes.as_deref()) +} + +unsafe fn list( + client: i64, + kind: i32, + topics: *const T::Unit, + nodes: *const T::Unit, +) -> i32 { + call(client, -1, |state| { state.names.clear(); - let list = state.client()?.list_names(kind)?; - let kind = match kind { + let list = unsafe { fetch_names::(state, kind, topics, nodes)? }; + let kind = match list.kind { NameKind::Topic => "topic", NameKind::Node => "node", }; @@ -668,71 +899,108 @@ fn list(kind: NameKind) -> i32 { }) } -/// Lists the topics with messages that this client may push to or read -/// (every one if its roles have `list_topics` or `query`): how many, -1 on -/// failure. Then `BakaShrot_GetNamesList()`. +/// Lists topics (`kind` 1) or nodes (`kind` 2): the topics with messages +/// that this client may push to or read (every one if its roles have +/// `list_topics` or `query`), the nodes with messages in the topics it may +/// read (every one with `list_nodes` or `query`). Only those of the topic +/// and node pairs that `topics` and `nodes` match: each a name or a +/// pattern (`sensors.*`), null for any. Every topic: 1, null, null; the +/// topics a node pushed to: 1, null, the node; the nodes that pushed to a +/// topic: 2, the topic, null. How many, -1 on failure. Then +/// `BakaShrot_GetNamesListAsJson()`, or `BakaShrot_EnumerateNames()` +/// instead. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_ListTopics() -> i32 { - list(NameKind::Topic) +pub unsafe extern "C" fn BakaShrot_ListNamesA( + client: i64, + kind: i32, + topics: *const c_char, + nodes: *const c_char, +) -> i32 { + unsafe { list::(client, kind, topics.cast(), nodes.cast()) } } -/// Lists the nodes with messages in the topics this client may read (every -/// one if its roles have `list_nodes` or `query`): how many, -1 on failure. Then -/// `BakaShrot_GetNamesList()`. +/// The same as `BakaShrot_ListNamesA`, in UTF-16. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_ListNodes() -> i32 { - list(NameKind::Node) +pub unsafe extern "C" fn BakaShrot_ListNamesW( + client: i64, + kind: i32, + topics: *const u16, + nodes: *const u16, +) -> i32 { + unsafe { list::(client, kind, topics, nodes) } } /// The last list, as JSON: /// `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated` /// if some didn't fit. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetNamesListA(buffer: *mut c_char, size: isize) -> isize { - unsafe { get_text::(buffer.cast(), size, |state| &state.names) } +pub unsafe extern "C" fn BakaShrot_GetNamesListAsJsonA( + client: i64, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer.cast(), size, |state| &state.names) } } -/// The same as `BakaShrot_GetNamesListA`, in UTF-16. +/// The same as `BakaShrot_GetNamesListAsJsonA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetNamesListW(buffer: *mut u16, size: isize) -> isize { - unsafe { get_text::(buffer, size, |state| &state.names) } +pub unsafe extern "C" fn BakaShrot_GetNamesListAsJsonW( + client: i64, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer, size, |state| &state.names) } } // --- Queries ----------------------------------------------------------------- -unsafe fn query(sql: *const T::Unit) -> isize { - call(0, |state| { +/// Runs a query: the server's JSON. +unsafe fn fetch_query(state: &mut State, sql: *const T::Unit) -> Result { + let sql = unsafe { required::(sql, "query")? }; + state.client()?.query(&sql) +} + +unsafe fn query(client: i64, sql: *const T::Unit) -> isize { + call(client, 0, |state| { state.query.clear(); - let sql = required(unsafe { text::read::(sql, "query")? }, "query")?; - state.query = state.client()?.query(&sql)?; + state.query = unsafe { fetch_query::(state, sql)? }; Ok(1) }) } /// Runs read-only SQL on the server (one SELECT or WITH), if this client -/// may query. Then `BakaShrot_GetQueryResult()`. +/// may query. Then `BakaShrot_GetQueryResultAsJson()`, or +/// `BakaShrot_EnumerateQuery()` instead. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_QueryA(sql: *const c_char) -> isize { - unsafe { query::(sql.cast()) } +pub unsafe extern "C" fn BakaShrot_QueryA(client: i64, sql: *const c_char) -> isize { + unsafe { query::(client, sql.cast()) } } /// The same as `BakaShrot_QueryA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_QueryW(sql: *const u16) -> isize { - unsafe { query::(sql) } +pub unsafe extern "C" fn BakaShrot_QueryW(client: i64, sql: *const u16) -> isize { + unsafe { query::(client, sql) } } /// The last query's result, as JSON: /// `{"columns":[...],"rows":[[...],...]}`, every value a string or null. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetQueryResultA(buffer: *mut c_char, size: isize) -> isize { - unsafe { get_text::(buffer.cast(), size, |state| &state.query) } +pub unsafe extern "C" fn BakaShrot_GetQueryResultAsJsonA( + client: i64, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer.cast(), size, |state| &state.query) } } -/// The same as `BakaShrot_GetQueryResultA`, in UTF-16. +/// The same as `BakaShrot_GetQueryResultAsJsonA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetQueryResultW(buffer: *mut u16, size: isize) -> isize { - unsafe { get_text::(buffer, size, |state| &state.query) } +pub unsafe extern "C" fn BakaShrot_GetQueryResultAsJsonW( + client: i64, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer, size, |state| &state.query) } } // --- Attachments ------------------------------------------------------------- @@ -743,13 +1011,14 @@ fn message_id(id: i64) -> Result { } unsafe fn push_with_file( + client: i64, topic: *const T::Unit, data: *const T::Unit, path: *const T::Unit, ) -> i64 { - call(-1, |state| { + call(client, -1, |state| { let (topic, data) = unsafe { topic_and_data::(topic, data)? }; - let path = required(unsafe { text::read::(path, "the file")? }, "file")?; + let path = unsafe { required::(path, "file")? }; let mut file = File::open(&path) .map_err(|error| Error::new(ErrorCode::FileError, format!("{path}: {error}")))?; let id = state @@ -766,30 +1035,33 @@ unsafe fn push_with_file( /// (`DataMismatch`). #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_PushMessageWithFileA( + client: i64, topic: *const c_char, data: *const c_char, file_path: *const c_char, ) -> i64 { - unsafe { push_with_file::(topic.cast(), data.cast(), file_path.cast()) } + unsafe { push_with_file::(client, topic.cast(), data.cast(), file_path.cast()) } } /// The same as `BakaShrot_PushMessageWithFileA`, in UTF-16. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_PushMessageWithFileW( + client: i64, topic: *const u16, data: *const u16, file_path: *const u16, ) -> i64 { - unsafe { push_with_file::(topic, data, file_path) } + unsafe { push_with_file::(client, topic, data, file_path) } } unsafe fn push_with_data( + client: i64, topic: *const T::Unit, data: *const T::Unit, attachment: *const c_void, size: i64, ) -> i64 { - call(-1, |state| { + call(client, -1, |state| { let (topic, data) = unsafe { topic_and_data::(topic, data)? }; if attachment.is_null() { return Err(invalid("no attachment (a null pointer)")); @@ -810,34 +1082,37 @@ unsafe fn push_with_data( /// `BakaShrot_PushMessageWithFileA` does. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_PushMessageWithDataA( + client: i64, topic: *const c_char, data: *const c_char, attachment: *const c_void, size: i64, ) -> i64 { - unsafe { push_with_data::(topic.cast(), data.cast(), attachment, size) } + unsafe { push_with_data::(client, topic.cast(), data.cast(), attachment, size) } } /// The same as `BakaShrot_PushMessageWithDataA`, in UTF-16. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_PushMessageWithDataW( + client: i64, topic: *const u16, data: *const u16, attachment: *const c_void, size: i64, ) -> i64 { - unsafe { push_with_data::(topic, data, attachment, size) } + unsafe { push_with_data::(client, topic, data, attachment, size) } } unsafe fn save( + client: i64, topic: *const T::Unit, node: *const T::Unit, id: i64, path: *const T::Unit, ) -> i64 { - call(-1, |state| { + call(client, -1, |state| { let (topic, node) = unsafe { topic_and_node::(topic, node)? }; - let path = required(unsafe { text::read::(path, "the file")? }, "file")?; + let path = unsafe { required::(path, "file")? }; let size = state .client()? @@ -853,27 +1128,37 @@ unsafe fn save( /// failed one leaves no file. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_SaveAttachmentA( + client: i64, topic: *const c_char, node: *const c_char, message_id: i64, file_path: *const c_char, ) -> i64 { - unsafe { save::(topic.cast(), node.cast(), message_id, file_path.cast()) } + unsafe { + save::( + client, + topic.cast(), + node.cast(), + message_id, + file_path.cast(), + ) + } } /// The same as `BakaShrot_SaveAttachmentA`, in UTF-16. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_SaveAttachmentW( + client: i64, topic: *const u16, node: *const u16, message_id: i64, file_path: *const u16, ) -> i64 { - unsafe { save::(topic, node, message_id, file_path) } + unsafe { save::(client, topic, node, message_id, file_path) } } -unsafe fn load(topic: *const T::Unit, node: *const T::Unit, id: i64) -> i64 { - call(-1, |state| { +unsafe fn load(client: i64, topic: *const T::Unit, node: *const T::Unit, id: i64) -> i64 { + call(client, -1, |state| { state.attachment = Vec::new(); let (topic, node) = unsafe { topic_and_node::(topic, node)? }; let mut attachment = Vec::new(); @@ -891,29 +1176,35 @@ unsafe fn load(topic: *const T::Unit, node: *const T::Unit, id: i64) -> /// ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_LoadAttachmentA( + client: i64, topic: *const c_char, node: *const c_char, message_id: i64, ) -> i64 { - unsafe { load::(topic.cast(), node.cast(), message_id) } + unsafe { load::(client, topic.cast(), node.cast(), message_id) } } /// The same as `BakaShrot_LoadAttachmentA`, in UTF-16. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_LoadAttachmentW( + client: i64, topic: *const u16, node: *const u16, message_id: i64, ) -> i64 { - unsafe { load::(topic, node, message_id) } + unsafe { load::(client, topic, node, message_id) } } /// Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if /// `BufferSize` is enough: returns its size (0 if none), copies nothing if /// it doesn't fit (a null `Buffer` asks for the size). #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetAttachmentData(buffer: *mut c_void, buffer_size: i64) -> i64 { - get(0, |state| { +pub unsafe extern "C" fn BakaShrot_GetAttachmentData( + client: i64, + buffer: *mut c_void, + buffer_size: i64, +) -> i64 { + get(client, 0, |state| { let data = &state.attachment; 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()) }; @@ -924,7 +1215,9 @@ pub unsafe extern "C" fn BakaShrot_GetAttachmentData(buffer: *mut c_void, buffer /// Frees what `BakaShrot_LoadAttachment()` read: 1. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_FreeAttachmentData() -> isize { - let freed = catch_unwind(AssertUnwindSafe(|| state().attachment = Vec::new())); - bool_result(freed.is_ok()) +pub extern "C" fn BakaShrot_FreeAttachmentData(client: i64) -> isize { + get(client, 0, |state| { + state.attachment = Vec::new(); + 1 + }) } diff --git a/crates/bakashrot-capi/tests/codes.rs b/crates/bakashrot-capi/tests/codes.rs new file mode 100644 index 0000000..2a6d31a --- /dev/null +++ b/crates/bakashrot-capi/tests/codes.rs @@ -0,0 +1,133 @@ +//! The bindings' error codes are the protocol's, every one, by the same +//! numbers: Python's `ErrorCode`, C#'s `ErrorCode`, PureBasic's constants. +//! And the values they copy are the Rust side's. + +use bakashrot_client::ANSWER_TIMEOUT; +use bakashrot_proto::ErrorCode; +use bakashrot_proto::limits::{KEEPALIVE_SECS, MAX_MESSAGES_PER_PACKET}; +use std::collections::BTreeMap; +use std::path::PathBuf; + +fn binding(path: &str) -> String { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../bindings") + .join(path); + std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{}: {error}", path.display())) +} + +/// The protocol's codes, by number: their names as `name` writes them. +fn expected(name: impl Fn(ErrorCode) -> String) -> BTreeMap { + ErrorCode::ALL + .iter() + .map(|&code| (code.code(), name(code))) + .collect() +} + +/// `NotFound` as `NOT_FOUND`. +fn upper_snake(name: &str) -> String { + let mut snake = String::new(); + for (at, c) in name.char_indices() { + if c.is_ascii_uppercase() && at > 0 { + snake.push('_'); + } + snake.push(c.to_ascii_uppercase()); + } + snake +} + +/// `NAME = 12` in `text`, one per line or comma: the names and numbers. +fn assignments<'a>(text: impl Iterator) -> BTreeMap { + let mut found = BTreeMap::new(); + for item in text.flat_map(|line| line.split(',')) { + // Comments: PureBasic's `;`, Python's ` #` (PureBasic's constants + // start with `#`). + let item = item.split(';').next().unwrap_or(""); + let item = item.split(" #").next().unwrap_or("").trim(); + let Some((name, number)) = item.split_once('=') else { + continue; + }; + let Ok(number) = number.trim().parse::() else { + continue; + }; + let before = found.insert(number, name.trim().to_owned()); + assert!(before.is_none(), "{number} twice: {before:?}, {name}"); + } + found +} + +/// The lines of `text` from the one starting with `start` to the next +/// starting with `end`. +fn section<'a>(text: &'a str, start: &str, end: &str) -> impl Iterator { + text.lines() + .skip_while(move |line| !line.trim_start().starts_with(start)) + .skip(1) + .take_while(move |line| !line.trim_start().starts_with(end)) +} + +/// The number `name` is set to in `text`: `NAME = 12`, a `;` after or not. +fn number(text: &str, name: &str) -> f64 { + let set = format!("{name} = "); + let line = text.lines().find(|line| line.contains(&set)); + let line = line.unwrap_or_else(|| panic!("no {set}")); + let value = line.split(&set).nth(1).unwrap_or(""); + let value = value.trim().trim_end_matches(';'); + value.parse().unwrap_or_else(|_| panic!("{set}{value}")) +} + +#[test] +fn copied_values() { + let python = binding("python/bakashrot.py"); + let csharp = binding("csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs"); + let answer = ANSWER_TIMEOUT.as_secs_f64(); + let keepalive = KEEPALIVE_SECS as f64; + assert_eq!(number(&python, "ANSWER_TIMEOUT_SECONDS"), answer); + assert_eq!(number(&python, "KEEPALIVE_SECONDS"), keepalive); + assert_eq!( + number(&python, "MAX_GET_MESSAGES"), + f64::from(MAX_MESSAGES_PER_PACKET) + ); + assert_eq!(number(&csharp, "DefaultAnswerTimeoutMs"), answer * 1000.0); + assert_eq!(number(&csharp, "KeepAliveMs"), keepalive * 1000.0); +} + +#[test] +fn python() { + let text = binding("python/bakashrot.py"); + let found = assignments(section(&text, "class ErrorCode", "@property")); + let mut expected = expected(|code| upper_snake(code.name())); + expected.insert(0, "NONE".into()); + assert_eq!(found, expected); +} + +#[test] +fn csharp() { + let text = binding("csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs"); + let found = assignments(section(&text, "public enum ErrorCode", "}")); + let mut expected = expected(|code| code.name().to_owned()); + expected.insert(0, "None".into()); + assert_eq!(found, expected); +} + +#[test] +fn purebasic() { + let text = binding("purebasic/BakaShrot_ErrorCodes.pbi"); + let constants = text + .lines() + .filter(|line| line.starts_with("#BakaShrot_") && !line.contains("_Max")); + let found = assignments(constants); + let mut expected = expected(|code| { + let kind = if code.is_refusal() { + "Refused" + } else { + "Error" + }; + format!("#BakaShrot_{kind}_{}", code.name()) + }); + expected.insert(0, "#BakaShrot_Error_None".into()); + assert_eq!(found, expected); + // Each named by BakaShrot_ErrorName(). + for code in ErrorCode::ALL { + let case = format!("ProcedureReturn \"{}\"", code.name()); + assert!(text.contains(&case), "BakaShrot_ErrorName() lacks {code}"); + } +} diff --git a/crates/bakashrot-capi/tests/exports.rs b/crates/bakashrot-capi/tests/exports.rs index ba33904..e7a1081 100644 --- a/crates/bakashrot-capi/tests/exports.rs +++ b/crates/bakashrot-capi/tests/exports.rs @@ -1,6 +1,7 @@ -//! The exports called as C would, against a server: the `W` ones (what -//! PureBasic uses; Python's check covers the `A` ones), the buffers, the -//! errors. One test: the DLL holds one connection per process. +//! The exports called as C would, against a server. `exports`: one client, +//! the `W` exports (what PureBasic uses; Python's check covers the `A` +//! ones), the buffers, the errors. `clients`: several clients at once, bad +//! handles, threads. #![allow(unsafe_code)] @@ -9,6 +10,8 @@ mod common; use bakashrot::*; use bakashrot_proto::ErrorCode; use std::ffi::{CString, c_char}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; fn w(text: &str) -> Vec { 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. -fn get_w(getter: unsafe extern "C" fn(*mut u16, isize) -> isize) -> String { - let size = unsafe { getter(std::ptr::null_mut(), 0) }; +fn get_w(client: i64, getter: unsafe extern "C" fn(i64, *mut u16, isize) -> isize) -> String { + 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]; - unsafe { getter(buffer.as_mut_ptr(), size) }; + unsafe { getter(client, buffer.as_mut_ptr(), size) }; String::from_utf16(&buffer[..buffer.len() - 1]).unwrap() } -fn get_a(getter: unsafe extern "C" fn(*mut c_char, isize) -> isize) -> String { - let size = unsafe { getter(std::ptr::null_mut(), 0) }; +fn get_a(client: i64, getter: unsafe extern "C" fn(i64, *mut c_char, isize) -> isize) -> String { + let size = unsafe { getter(client, std::ptr::null_mut(), 0) }; 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() } -/// The last error's code and reason. -fn error() -> (u32, String) { +/// The client's last error: its code and reason. +fn error(client: i64) -> (u32, String) { ( - BakaShrot_GetLastError() as u32, - get_w(BakaShrot_GetRefusalReasonW), + BakaShrot_GetLastError(client) as u32, + get_w(client, BakaShrot_GetRefusalReasonW), ) } @@ -54,172 +60,227 @@ fn exports() { let pem = |name: &str| std::fs::read_to_string(running.folder.join(name)).unwrap(); let localhost = w("127.0.0.1"); let port = i32::from(running.port); + let client = BakaShrot_CreateClient(); + assert!(client >= 1); unsafe { // Nothing set, not connected. assert_eq!( - BakaShrot_PushMessageToW(w("logs").as_ptr(), w("{}").as_ptr()), + BakaShrot_PushMessageToW(client, w("logs").as_ptr(), w("{}").as_ptr()), -1 ); - assert_eq!(error().0, code(ErrorCode::NotConnected)); - assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0); - let (failed, why) = error(); + assert_eq!(error(client).0, code(ErrorCode::NotConnected)); + assert_eq!(BakaShrot_ConnectW(client, localhost.as_ptr(), port), 0); + let (failed, why) = error(client); assert_eq!(failed, code(ErrorCode::InvalidArgument)); assert!(why.contains("BakaShrot_SetCaCertificate"), "{why}"); // Files or PEM text; a missing file, an empty setting. assert_eq!( - BakaShrot_SetCaCertificateW(w(&file("missing.crt")).as_ptr()), + BakaShrot_SetCaCertificateW(client, w(&file("missing.crt")).as_ptr()), 0 ); - assert_eq!(error().0, code(ErrorCode::FileError)); - assert_eq!(BakaShrot_SetCertificateW(std::ptr::null()), 0); - assert_eq!(error().0, code(ErrorCode::InvalidArgument)); - assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 1); - assert_eq!(BakaShrot_GetLastError(), 0); + assert_eq!(error(client).0, code(ErrorCode::FileError)); + assert_eq!(BakaShrot_SetCertificateW(client, std::ptr::null()), 0); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); 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 ); assert_eq!( - BakaShrot_SetPrivateKeyA(a(&file("kitchen.key")).as_ptr()), + BakaShrot_SetPrivateKeyA(client, a(&file("kitchen.key")).as_ptr()), 1 ); // 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!(error().0, code(ErrorCode::FileError)); - assert_eq!(BakaShrot_SetCrlW(std::ptr::null()), 1); - assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), 0), 0); - assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + assert_eq!( + BakaShrot_SetCrlW(client, w(&file("missing.crl")).as_ptr()), + 0 + ); + 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!( - BakaShrot_ConnectW(localhost.as_ptr(), port), + BakaShrot_ConnectW(client, localhost.as_ptr(), port), 1, "{:?}", - error() + error(client) ); - assert_eq!(BakaShrot_IsConnected(), 1); - assert_eq!(get_w(BakaShrot_GetNodeW), "kitchen"); - assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0); - assert_eq!(error().0, code(ErrorCode::AlreadyConnected)); - assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 0); - assert_eq!(error().0, code(ErrorCode::AlreadyConnected)); + assert_eq!(BakaShrot_IsConnected(client), 1); + assert_eq!(get_w(client, BakaShrot_GetNodeW), "kitchen"); + assert_eq!(BakaShrot_ConnectW(client, localhost.as_ptr(), port), 0); + assert_eq!(error(client).0, code(ErrorCode::AlreadyConnected)); + assert_eq!( + 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. 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 ); 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 ); assert_eq!( - BakaShrot_PushMessageToW(w("logs").as_ptr(), std::ptr::null()), + BakaShrot_PushMessageToW(client, w("logs").as_ptr(), std::ptr::null()), 3 ); assert_eq!( - BakaShrot_PushMessageToW(std::ptr::null(), w("{}").as_ptr()), + BakaShrot_PushMessageToW(client, std::ptr::null(), w("{}").as_ptr()), -1 ); - assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); assert_eq!( - BakaShrot_PushMessageToW(w("nothing").as_ptr(), w("{}").as_ptr()), + BakaShrot_PushMessageToW(client, w("nothing").as_ptr(), w("{}").as_ptr()), -1 ); - let (failed, why) = error(); + let (failed, why) = error(client); assert_eq!(failed, code(ErrorCode::NotAllowed)); assert!(why.contains("may not push to 'nothing'"), "{why}"); // The latest; none yet in another topic. assert_eq!( - BakaShrot_GetLatestMessageOfW(w("logs").as_ptr(), w("kitchen").as_ptr()), + BakaShrot_GetLatestMessageOfW(client, w("logs").as_ptr(), w("kitchen").as_ptr()), 1 ); assert_eq!( - (BakaShrot_GetMessageCount(), BakaShrot_GetMessageId()), + ( + BakaShrot_GetMessageCount(client), + BakaShrot_GetMessageId(client) + ), (1, 3) ); - assert_eq!(get_w(BakaShrot_GetMessageDataW), ""); - assert!(BakaShrot_GetMessagePushedAt() > 1_700_000_000_000); - assert_eq!(BakaShrot_GetMessageAttachmentSize(), 0); - assert_eq!(BakaShrot_IsMessageAttachmentReady(), 0); + assert_eq!(get_w(client, BakaShrot_GetMessageDataW), ""); + assert!(BakaShrot_GetMessagePushedAt(client) > 1_700_000_000_000); + assert_eq!(BakaShrot_GetMessageAttachmentSize(client), 0); + assert_eq!(BakaShrot_IsMessageAttachmentReady(client), 0); assert_eq!( - BakaShrot_GetLatestMessageOfW(w("secret").as_ptr(), w("kitchen").as_ptr()), + BakaShrot_GetLatestMessageOfW(client, w("secret").as_ptr(), w("kitchen").as_ptr()), 0 ); - assert_eq!(error().0, code(ErrorCode::NotFound)); - assert_eq!(BakaShrot_GetMessageCount(), 0); + assert_eq!(error(client).0, code(ErrorCode::NotFound)); + assert_eq!(BakaShrot_GetMessageCount(client), 0); // A run of messages, selected one by one. 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 ); - assert_eq!(BakaShrot_HasMoreMessages(), 1); - assert_eq!(get_w(BakaShrot_GetMessageTopicW), "logs"); - assert_eq!(get_w(BakaShrot_GetMessageNodeW), "kitchen"); - assert_eq!(BakaShrot_GetMessageId(), 1); - assert_eq!(BakaShrot_SelectMessage(1), 1); - assert_eq!(get_w(BakaShrot_GetMessageDataW), "héllo 🌍"); - assert_eq!(get_a(BakaShrot_GetMessageDataA), "héllo 🌍"); - assert_eq!(BakaShrot_SelectMessage(2), 0); - assert_eq!(error().0, code(ErrorCode::InvalidArgument)); - assert_eq!(BakaShrot_GetMessageId(), 2, "the selection stays"); + assert_eq!(BakaShrot_HasMoreMessages(client), 1); + assert_eq!(get_w(client, BakaShrot_GetMessageTopicW), "logs"); + assert_eq!(get_w(client, BakaShrot_GetMessageNodeW), "kitchen"); + assert_eq!(BakaShrot_GetMessageId(client), 1); + assert_eq!(BakaShrot_SelectMessage(client, 1), 1); + assert_eq!(get_w(client, BakaShrot_GetMessageDataW), "héllo 🌍"); + assert_eq!(get_a(client, BakaShrot_GetMessageDataA), "héllo 🌍"); + assert_eq!(BakaShrot_SelectMessage(client, 2), 0); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); + assert_eq!(BakaShrot_GetMessageId(client), 2, "the selection stays"); 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 ); - assert_eq!(BakaShrot_HasMoreMessages(), 0); - assert_eq!(BakaShrot_GetMessageId(), 0); + assert_eq!(BakaShrot_HasMoreMessages(client), 0); + assert_eq!(BakaShrot_GetMessageId(client), 0); for (after, limit) in [(-1, 10), (0, 0), (0, 10_001)] { 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 ); - assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); } 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 ); - assert_eq!(error().0, code(ErrorCode::UnknownName)); - assert_eq!(BakaShrot_IsConnected(), 1, "a refusal keeps the connection"); + assert_eq!(error(client).0, code(ErrorCode::UnknownName)); + assert_eq!( + BakaShrot_IsConnected(client), + 1, + "a refusal keeps the connection" + ); // The buffers: the size needed, nothing copied if it doesn't fit. - BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 1); - assert_eq!(BakaShrot_GetMessageDataW(std::ptr::null_mut(), 0), 16); - assert_eq!(BakaShrot_GetMessageDataA(std::ptr::null_mut(), 0), 8); + BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 1); + assert_eq!( + 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]; - 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]); // Unaligned: a byte buffer. let mut bytes = [0u8; 17]; assert_eq!( - BakaShrot_GetMessageDataW(bytes[1..].as_mut_ptr().cast(), 16), + BakaShrot_GetMessageDataW(client, bytes[1..].as_mut_ptr().cast(), 16), 16 ); assert_eq!(bytes[1..3], [b'{', 0]); // Names, queries. // Topics: those with messages (nothing in `secret` yet). - assert_eq!(BakaShrot_ListTopics(), 1); + let null = std::ptr::null(); + assert_eq!(BakaShrot_ListNamesW(client, 1, null, null), 1); assert_eq!( - get_w(BakaShrot_GetNamesListW), + get_w(client, BakaShrot_GetNamesListAsJsonW), r#"{"kind":"topic","names":["logs"],"truncated":false}"# ); - assert_eq!(BakaShrot_ListNodes(), 1); + assert_eq!(BakaShrot_ListNamesW(client, 2, null, null), 1); + // Filtered: the topics a node pushed to, the nodes of a topic. assert_eq!( - BakaShrot_QueryW(w("SELECT COUNT(*) AS n FROM data").as_ptr()), + BakaShrot_ListNamesW(client, 1, null, w("KITCHEN").as_ptr()), 1 ); assert_eq!( - get_w(BakaShrot_GetQueryResultW), + BakaShrot_ListNamesA(client, 2, a("l*").as_ptr(), null.cast()), + 1 + ); + assert_eq!( + get_w(client, BakaShrot_GetNamesListAsJsonW), + r#"{"kind":"node","names":["kitchen"],"truncated":false}"# + ); + assert_eq!( + BakaShrot_ListNamesW(client, 1, null, w("nobody").as_ptr()), + 0 + ); + assert_eq!(BakaShrot_ListNamesW(client, 3, null, null), -1); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); + assert_eq!(BakaShrot_ListNamesW(client, 1, w("a b").as_ptr(), null), -1); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); + assert_eq!( + BakaShrot_QueryW(client, w("SELECT COUNT(*) AS n FROM data").as_ptr()), + 1 + ); + assert_eq!( + get_w(client, BakaShrot_GetQueryResultAsJsonW), r#"{"columns":["n"],"rows":[["3"]]}"# ); - assert_eq!(BakaShrot_QueryW(w("SELECT nope").as_ptr()), 0); - assert_eq!(error().0, code(ErrorCode::QueryFailed)); - assert_eq!(get_w(BakaShrot_GetQueryResultW), ""); + assert_eq!(BakaShrot_QueryW(client, w("SELECT nope").as_ptr()), 0); + assert_eq!(error(client).0, code(ErrorCode::QueryFailed)); + assert_eq!(get_w(client, BakaShrot_GetQueryResultAsJsonW), ""); // Attachments: from a file or memory, saved or loaded back. let (logs, kitchen) = (w("logs"), w("kitchen")); @@ -227,34 +288,36 @@ fn exports() { std::fs::write(running.folder.join("photo.bin"), &photo).unwrap(); let photo_file = w(&file("photo.bin")); let pushed = BakaShrot_PushMessageWithFileW( + client, logs.as_ptr(), w(r#"{"photo":1}"#).as_ptr(), photo_file.as_ptr(), ); - assert_eq!(pushed, 4, "{:?}", error()); + assert_eq!(pushed, 4, "{:?}", error(client)); let tiny = b"tiny"; let pushed = BakaShrot_PushMessageWithDataW( + client, logs.as_ptr(), std::ptr::null(), tiny.as_ptr().cast(), 4, ); - assert_eq!(pushed, 5, "{:?}", error()); + assert_eq!(pushed, 5, "{:?}", error(client)); assert_eq!( - BakaShrot_GetLatestMessageOfW(logs.as_ptr(), kitchen.as_ptr()), + BakaShrot_GetLatestMessageOfW(client, logs.as_ptr(), kitchen.as_ptr()), 1 ); assert_eq!( ( - BakaShrot_GetMessageId(), - BakaShrot_GetMessageAttachmentSize(), - BakaShrot_IsMessageAttachmentReady() + BakaShrot_GetMessageId(client), + BakaShrot_GetMessageAttachmentSize(client), + BakaShrot_IsMessageAttachmentReady(client) ), (5, 4, 1) ); let saved = w(&file("saved.bin")); 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 ); assert_eq!( @@ -262,84 +325,428 @@ fn exports() { photo ); 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 ); - assert_eq!(BakaShrot_GetAttachmentData(std::ptr::null_mut(), 0), 4); 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"); 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!( - 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 ); - BakaShrot_FreeAttachmentData(); + BakaShrot_FreeAttachmentData(client); // Refused, or the client's own failures: -1, no file. let none = w(&file("none.bin")); 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 ); - assert_eq!(error().0, code(ErrorCode::NotFound)); + assert_eq!(error(client).0, code(ErrorCode::NotFound)); assert!(!running.folder.join("none.bin").exists()); 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 ); - assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); let missing = w(&file("missing.bin")); 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 ); - 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)] { let pushed = BakaShrot_PushMessageWithDataW( + client, logs.as_ptr(), std::ptr::null(), pointer.cast(), size, ); 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); + // A ping keeps it open, its last error cleared. + assert_eq!(BakaShrot_Ping(client), 1); + assert_eq!(error(client).0, 0); // Closed: requests refused, the settings kept. - assert_eq!(BakaShrot_Disconnect(), 1); - assert_eq!(BakaShrot_Disconnect(), 0); - assert_eq!(BakaShrot_IsConnected(), 0); - assert_eq!(get_w(BakaShrot_GetNodeW), ""); - assert_eq!(BakaShrot_QueryW(w("SELECT 1").as_ptr()), 0); - assert_eq!(error().0, code(ErrorCode::NotConnected)); + assert_eq!(BakaShrot_Disconnect(client), 1); + assert_eq!(BakaShrot_Disconnect(client), 0); + assert_eq!(BakaShrot_IsConnected(client), 0); + assert_eq!(BakaShrot_Ping(client), 0); + assert_eq!(error(client).0, code(ErrorCode::NotConnected)); + assert_eq!(get_w(client, BakaShrot_GetNodeW), ""); + assert_eq!(BakaShrot_QueryW(client, w("SELECT 1").as_ptr()), 0); + assert_eq!(error(client).0, code(ErrorCode::NotConnected)); // Another identity, by the A exports: not allowed to query. assert_eq!( - BakaShrot_SetCertificateA(a(&file("lounge.crt")).as_ptr()), + BakaShrot_SetCertificateA(client, a(&file("lounge.crt")).as_ptr()), 1 ); - assert_eq!(BakaShrot_SetPrivateKeyA(a(&pem("lounge.key")).as_ptr()), 1); 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, "{:?}", - error() + error(client) ); - assert_eq!(get_a(BakaShrot_GetNodeA), "lounge"); - assert_eq!(BakaShrot_QueryA(a("SELECT 1").as_ptr()), 0); - let (failed, why) = error(); + assert_eq!(get_a(client, BakaShrot_GetNodeA), "lounge"); + assert_eq!(BakaShrot_QueryA(client, a("SELECT 1").as_ptr()), 0); + let (failed, why) = error(client); assert_eq!(failed, code(ErrorCode::NotAllowed)); - assert_eq!(get_a(BakaShrot_GetRefusalReasonA), why); - BakaShrot_Disconnect(); + assert_eq!(get_a(client, BakaShrot_GetRefusalReasonA), why); + BakaShrot_Disconnect(client); // Nothing listening there. - assert_eq!(BakaShrot_ConnectA(a("127.0.0.1").as_ptr(), 1), 0); - assert_eq!(error().0, code(ErrorCode::ConnectFailed)); + assert_eq!(BakaShrot_ConnectA(client, a("127.0.0.1").as_ptr(), 1), 0); + assert_eq!(error(client).0, code(ErrorCode::ConnectFailed)); + } + assert_eq!(BakaShrot_FreeClient(client), 1); +} + +/// The answer timeout: set before connecting or while connected, kept +/// across connections; past it, `ConnectionLost` and the connection closed. +#[test] +fn answer_timeouts() { + let running = common::Running::start("answer-timeouts"); + running.issue("kitchen", &["home"]); + let client = BakaShrot_CreateClient(); + assert_eq!(BakaShrot_GetAnswerTimeout(client), 30_000); + for refused in [0, -1, i64::MIN] { + assert_eq!(BakaShrot_SetAnswerTimeout(client, refused), 0); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); + } + assert_eq!(BakaShrot_SetAnswerTimeout(client, 60_000), 1); + assert_eq!(BakaShrot_FreeClient(client), 1); + + let client = connected(&running, "kitchen"); + assert_eq!(BakaShrot_SetAnswerTimeout(client, 300), 1); + assert_eq!(BakaShrot_GetAnswerTimeout(client), 300); + let forever = + a("WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n"); + let started = std::time::Instant::now(); + unsafe { + assert_eq!(BakaShrot_QueryA(client, forever.as_ptr()), 0); + assert_eq!(error(client).0, code(ErrorCode::ConnectionLost)); + assert!(started.elapsed() < std::time::Duration::from_secs(5)); + assert_eq!(BakaShrot_IsConnected(client), 0); + // Connected again: the timeout kept. + let host = a("127.0.0.1"); + assert_eq!( + BakaShrot_ConnectA(client, host.as_ptr(), i32::from(running.port)), + 1 + ); + assert_eq!(BakaShrot_GetAnswerTimeout(client), 300); + assert_eq!(BakaShrot_QueryA(client, forever.as_ptr()), 0); + assert_eq!(error(client).0, code(ErrorCode::ConnectionLost)); + } + 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_Ping(99), 0); + assert_eq!(BakaShrot_SetAnswerTimeout(99, 1000), 0); + assert_eq!(BakaShrot_GetAnswerTimeout(99), -1); + 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 = (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 = threads + .into_iter() + .flat_map(|thread| thread.join().unwrap()) + .collect(); + ids.sort_unstable(); + assert_eq!(ids, (4..=203).collect::>()); + + // 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)); +} + +/// An enumeration's string at an index: asks for the size, then copies. +fn get_at( + enumeration: i64, + index: i32, + getter: unsafe extern "C" fn(i64, i32, *mut u16, isize) -> isize, +) -> String { + let size = unsafe { getter(enumeration, index, std::ptr::null_mut(), 0) }; + if size == 0 { + return String::new(); + } + let mut buffer = vec![0u16; size as usize / 2]; + unsafe { getter(enumeration, index, buffer.as_mut_ptr(), size) }; + String::from_utf16(&buffer[..buffer.len() - 1]).unwrap() +} + +/// Every name of an enumeration, `NextName` until it says no more. +fn names_of(enumeration: i64) -> Vec { + let mut names = Vec::new(); + while BakaShrot_NextName(enumeration) == 1 { + names.push(get_w(enumeration, BakaShrot_GetEnumNameW)); + } + names +} + +#[test] +fn enumerations() { + let running = common::Running::start("enumerations"); + running.issue("kitchen", &["home"]); + let client = connected(&running, "kitchen"); + let null = std::ptr::null(); + unsafe { + for (topic, data) in [("logs", "{}"), ("secret", "{}"), ("logs", "{}")] { + assert!(BakaShrot_PushMessageToW(client, w(topic).as_ptr(), w(data).as_ptr()) > 0); + } + + // Names: before the first at first, then each, then no more. + let topics = BakaShrot_EnumerateNamesW(client, 1, null, w("kitchen").as_ptr()); + assert!(topics > client, "numbered with the clients"); + assert_eq!(BakaShrot_GetNameCount(topics), 2); + assert_eq!(BakaShrot_IsNamesListTruncated(topics), 0); + assert_eq!( + get_w(topics, BakaShrot_GetEnumNameW), + "", + "before the first" + ); + assert_eq!(names_of(topics), ["logs", "secret"]); + assert_eq!(BakaShrot_NextName(topics), 0, "still none"); + assert_eq!(get_w(topics, BakaShrot_GetEnumNameW), ""); + // Several at once, each its own; the client's calls don't change them. + let nodes = BakaShrot_EnumerateNamesA(client, 2, a("s*").as_ptr(), null.cast()); + let none = BakaShrot_EnumerateNamesW(client, 2, w("nothing").as_ptr(), null); + assert_eq!(BakaShrot_ListNamesW(client, 1, null, null), 2); + assert_eq!(names_of(nodes), ["kitchen"]); + assert_eq!(BakaShrot_GetNameCount(none), 0); + assert_eq!(BakaShrot_NextName(none), 0); + // A failure: 0, the client's error. + assert_eq!(BakaShrot_EnumerateNamesW(client, 3, null, null), 0); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); + + // Queries: columns, rows, nulls. + let sql = w( + "SELECT topic, CASE WHEN message_id = 1 THEN NULL ELSE message_id END AS id \ + FROM messages ORDER BY topic, message_id", + ); + let query = BakaShrot_EnumerateQueryW(client, sql.as_ptr()); + assert!(query > 0, "{:?}", error(client)); + assert_eq!(BakaShrot_GetQueryColumnCount(query), 2); + assert_eq!(get_at(query, 0, BakaShrot_GetQueryColumnNameW), "topic"); + assert_eq!(get_at(query, 1, BakaShrot_GetQueryColumnNameW), "id"); + assert_eq!(get_at(query, 2, BakaShrot_GetQueryColumnNameW), ""); + assert_eq!(BakaShrot_IsQueryValueNull(query, 0), -1, "no row yet"); + let mut rows = Vec::new(); + while BakaShrot_NextQueryRow(query) == 1 { + let id = match BakaShrot_IsQueryValueNull(query, 1) { + 1 => None, + 0 => Some(get_at(query, 1, BakaShrot_GetQueryValueW)), + other => panic!("{other}"), + }; + rows.push((get_at(query, 0, BakaShrot_GetQueryValueW), id)); + } + let row = |topic: &str, id: Option<&str>| (topic.to_owned(), id.map(str::to_owned)); + assert_eq!( + rows, + [ + row("logs", None), + row("logs", Some("2")), + row("secret", None) + ] + ); + assert_eq!(BakaShrot_IsQueryValueNull(query, 0), -1, "past the last"); + assert_eq!( + BakaShrot_EnumerateQueryW(client, w("SELECT nope").as_ptr()), + 0 + ); + assert_eq!(error(client).0, code(ErrorCode::QueryFailed)); + + // Of the other kind, a client's, made up: refused, never a crash. + assert_eq!(BakaShrot_NextName(query), -1); + assert_eq!(BakaShrot_NextQueryRow(nodes), -1); + assert_eq!(BakaShrot_GetQueryColumnCount(nodes), -1); + assert_eq!(BakaShrot_NextName(client), -1); + assert_eq!(BakaShrot_NextName(99_999), -1); + assert_eq!(get_w(99_999, BakaShrot_GetEnumNameW), ""); + assert_eq!(BakaShrot_CloseEnum(client), 0, "a client isn't one"); + assert_eq!(BakaShrot_FreeClient(topics), 0, "nor the other way"); + + // Closed: refused after. Its client freed: all of its closed. + assert_eq!(BakaShrot_CloseEnum(topics), 1); + assert_eq!(BakaShrot_CloseEnum(topics), 0); + assert_eq!(BakaShrot_GetNameCount(topics), -1); + assert_eq!(BakaShrot_FreeClient(client), 1); + for enumeration in [nodes, none, query] { + assert_eq!(BakaShrot_CloseEnum(enumeration), 0, "{enumeration}"); + } } } diff --git a/crates/bakashrot-client/src/lib.rs b/crates/bakashrot-client/src/lib.rs index f570947..72c0493 100644 --- a/crates/bakashrot-client/src/lib.rs +++ b/crates/bakashrot-client/src/lib.rs @@ -17,17 +17,24 @@ //! ALPN `bakashrot`, both ends' protocol versions, then the server's //! `Welcome` (`docs/protocol.md`). Errors carry the protocol's codes //! (`bakashrot_proto::ErrorCode`): a server's refusal keeps its own. +//! +//! **A failure that leaves the connection out of step closes it:** an +//! I/O error, an answer that didn't come in time ([`Client::answer_timeout`]), +//! one that isn't the request's, a part cut short. Every request after +//! fails with `NotConnected` at once, without reading: a late answer is +//! never taken for the next request's. Connect again. A refusal, or an +//! argument refused before sending, keeps it. use aws_lc_rs::digest; use bakashrot_pki::{Revocations, tls}; use bakashrot_proto::limits::{ - ALPN, ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGE_SIZE, - MAX_MESSAGES_PER_PACKET, MAX_PACKET_SIZE, + ALPN, ATTACHMENT_PART_SIZE, KEEPALIVE_SECS, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, + MAX_MESSAGE_SIZE, MAX_MESSAGES_PER_PACKET, MAX_PACKET_SIZE, }; -use bakashrot_proto::names::is_valid_name; +use bakashrot_proto::names::{is_valid_name, is_valid_name_or_pattern}; use bakashrot_proto::packets::{ - Attachment, AttachmentPart, GetAttachment, GetMessages, ListNames, Messages, NameKind, - NamesList, PushMessage, Query, + Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed, + Messages, NameKind, NamesList, Ping, Pong, PushMessage, Query, QueryResult, Welcome, }; use bakashrot_proto::{ErrorCode, Packet, frame}; use rustls::{ClientConnection, StreamOwned}; @@ -97,11 +104,26 @@ impl std::error::Error for Error {} /// A result of this crate. pub type Result = std::result::Result; +/// What [`Client::is_open`] found waiting. +enum Look { + /// Nothing, or only what TLS keeps for itself. + Open, + /// The server closed it: the socket's end, or TLS's close_notify. + Gone, + /// Data sent unasked, or a broken TLS stream. + OutOfStep, +} + /// A connection to a server. pub struct Client { stream: StreamOwned, server: String, node: String, + /// How long an answer may take: [`ANSWER_TIMEOUT`] until changed. + answer_timeout: Duration, + /// Closed, after a failure that left it out of step: requests fail + /// with `NotConnected`. + closed: bool, } impl fmt::Debug for Client { @@ -166,20 +188,38 @@ impl Client { stream, server: String::new(), node: String::new(), + answer_timeout: CONNECT_TIMEOUT, + closed: false, }; - match client.answer()? { - Packet::Welcome(welcome) => { - client.server = welcome.server; - client.node = welcome.node; - } - other => return Err(unexpected(&other)), - } - let tcp = &client.stream.sock; - tcp.set_read_timeout(Some(ANSWER_TIMEOUT)).map_err(lost)?; - tcp.set_write_timeout(Some(ANSWER_TIMEOUT)).map_err(lost)?; + let welcome: Welcome = client.answer()?; + (client.server, client.node) = (welcome.server, welcome.node); + client.set_answer_timeout(ANSWER_TIMEOUT)?; Ok(client) } + /// How long an answer may take before its request fails + /// (`ConnectionLost`, the connection closed): [`ANSWER_TIMEOUT`] (30 s) + /// until changed. + pub fn answer_timeout(&self) -> Duration { + self.answer_timeout + } + + /// Sets how long an answer may take, more than 0: longer for a slow + /// query, say. It's also how long sending a packet may take. Past it, + /// the request fails and the connection is closed (a late answer would + /// be taken for the next request's). + pub fn set_answer_timeout(&mut self, timeout: Duration) -> Result<()> { + require(!timeout.is_zero(), || "an answer timeout of 0".to_owned())?; + self.check_open()?; + let tcp = &self.stream.sock; + let set = tcp + .set_read_timeout(Some(timeout)) + .and_then(|()| tcp.set_write_timeout(Some(timeout))); + set.map_err(|error| self.io_failed(error))?; + self.answer_timeout = timeout; + Ok(()) + } + /// The server's name. pub fn server(&self) -> &str { &self.server @@ -191,17 +231,90 @@ impl Client { } /// Whether the connection still looks open: the server hasn't closed - /// it (after its idle timeout, say). Only a request tells for sure. - pub fn is_open(&self) -> bool { - let tcp = &self.stream.sock; - if tcp.set_nonblocking(true).is_err() { + /// it (after its idle timeout, say, or with TLS's close_notify). Only a + /// request tells for sure. + /// + /// It reads what's waiting without blocking, through TLS: what TLS + /// keeps for itself (session tickets) leaves it open, a close or a + /// broken stream doesn't. Data the server sent unasked leaves the + /// connection out of step: closed then, as [`Client::is_closed`] says. + pub fn is_open(&mut self) -> bool { + if self.closed { return false; } - let open = match tcp.peek(&mut [0]) { - Ok(read) => read > 0, - Err(error) => error.kind() == io::ErrorKind::WouldBlock, - }; - open && tcp.set_nonblocking(false).is_ok() + if self.stream.sock.set_nonblocking(true).is_err() { + return false; + } + let looked = self.look(); + // Blocking again whatever it found: the next request waits for + // its answer. + let blocking = self.stream.sock.set_nonblocking(false).is_ok(); + match looked { + Look::Open => blocking, + Look::Gone => false, + Look::OutOfStep => { + self.close(); + false + } + } + } + + /// What's waiting on the (non-blocking) socket, read into TLS, which + /// keeps what it read for the next request. + fn look(&mut self) -> Look { + let StreamOwned { conn, sock } = &mut self.stream; + loop { + // What TLS holds already, then what it reads below. + let state = match conn.process_new_packets() { + Ok(state) => state, + Err(_) => return Look::OutOfStep, + }; + if state.peer_has_closed() { + return Look::Gone; + } + // Nothing is sent unasked: never an answer's start. + if state.plaintext_bytes_to_read() > 0 || !conn.wants_read() { + return Look::OutOfStep; + } + match conn.read_tls(sock) { + // The socket's end, without close_notify. + Ok(0) => return Look::Gone, + Ok(_) => {} + Err(error) if error.kind() == io::ErrorKind::WouldBlock => return Look::Open, + Err(error) if error.kind() == io::ErrorKind::Interrupted => {} + Err(_) => return Look::Gone, + } + } + } + + /// Whether a failure closed the connection: every request fails with + /// `NotConnected` now, connect again. Unlike [`Client::is_open`], it + /// doesn't look at the socket. + pub fn is_closed(&self) -> bool { + self.closed + } + + /// Keeps the connection open: the server closes one silent for + /// `IDLE_TIMEOUT_SECS` (5 min). An app waiting longer than that + /// between requests calls this every `KEEPALIVE_SECS` (1 min) or so. + pub fn ping(&mut self) -> Result<()> { + let Pong {} = self.request(Ping {}.into())?; + Ok(()) + } + + /// Waits `duration`, pinging every `KEEPALIVE_SECS` meanwhile + /// ([`Client::ping`]): for an app waiting longer than the server's idle + /// timeout between requests. A failed ping ends it. + pub fn wait(&mut self, duration: Duration) -> Result<()> { + let keepalive = Duration::from_secs(KEEPALIVE_SECS); + let mut left = duration; + while left > keepalive { + std::thread::sleep(keepalive); + left -= keepalive; + self.ping()?; + } + std::thread::sleep(left); + Ok(()) } /// Pushes a message to `topic`, as this client's node: its id. @@ -213,10 +326,8 @@ impl Client { data: data.to_owned(), attachment: None, }; - match self.request(push.into())? { - Packet::MessagePushed(pushed) => Ok(pushed.message_id), - other => Err(unexpected(&other)), - } + let pushed: MessagePushed = self.request(push.into())?; + Ok(pushed.message_id) } /// Pushes a message with an attachment read from `source` (a `File`, a @@ -245,12 +356,9 @@ impl Client { sha256.update(&buffer[..read]); size += read as u64; } - if !(1..=MAX_ATTACHMENT_SIZE).contains(&size) { - return Err(Error::new( - ErrorCode::InvalidArgument, - format!("an attachment of {size} bytes: 1 to {MAX_ATTACHMENT_SIZE}"), - )); - } + require((1..=MAX_ATTACHMENT_SIZE).contains(&size), || { + format!("an attachment of {size} bytes: 1 to {MAX_ATTACHMENT_SIZE}") + })?; source.rewind().map_err(file_error)?; let mut digest = [0; 32]; digest.copy_from_slice(sha256.finish().as_ref()); @@ -263,26 +371,20 @@ impl Client { data: data.to_owned(), attachment: Some(attachment.clone()), }; - match self.request(push.into())? { - Packet::Continue(_) => {} - other => return Err(unexpected(&other)), - } + let Continue {} = self.request(push.into())?; for part in 0..attachment.part_count() { let part = &mut buffer[..attachment.part_len(part) as usize]; if let Err(error) = source.read_exact(part) { - self.close(); - return Err(file_error(error)); + // The server waits for parts that won't come. + return Err(self.out_of_step(file_error(error))); } - let packet = Packet::from(AttachmentPart { + self.send(&Packet::from(AttachmentPart { data: part.to_vec(), - }); - frame::write(&mut self.stream, &packet.encode()).map_err(lost)?; - } - self.stream.flush().map_err(lost)?; - match self.answer()? { - Packet::MessagePushed(pushed) => Ok(pushed.message_id), - other => Err(unexpected(&other)), + }))?; } + self.flush()?; + let pushed: MessagePushed = self.answer()?; + Ok(pushed.message_id) } /// Writes a message's attachment into `out`, a part at a time, checked @@ -297,41 +399,31 @@ impl Client { ) -> Result { check_name(topic, "topic")?; check_name(node, "node")?; - if !(1..=MAX_MESSAGE_ID).contains(&message_id) { - return Err(Error::new( - ErrorCode::InvalidArgument, - format!("message {message_id}: 1 to {MAX_MESSAGE_ID}"), - )); - } + require((1..=MAX_MESSAGE_ID).contains(&message_id), || { + format!("message {message_id}: 1 to {MAX_MESSAGE_ID}") + })?; let get = GetAttachment { topic: topic.to_owned(), node: node.to_owned(), message_id, from_part: 0, }; - let attachment = match self.request(get.into())? { - Packet::Attachment(attachment) => attachment, - other => return Err(unexpected(&other)), - }; + let attachment: Attachment = self.request(get.into())?; let mut sha256 = digest::Context::new(&digest::SHA256); // A failing `out`: the parts are still all read, the connection // stays usable. let mut failed = None; for part in 0..attachment.part_count() { - let data = match self.answer()? { - Packet::AttachmentPart(part) => part.data, - other => { - self.close(); - return Err(unexpected(&other)); - } - }; + // Parts come without a request each: anything else, a refusal + // too, leaves the rest of them unread. + let read: Result = self.answer(); + let data = read.map_err(|error| self.out_of_step(error))?.data; let expected = attachment.part_len(part); if data.len() as u64 != expected { - self.close(); - return Err(Error::new( + return Err(self.out_of_step(Error::new( ErrorCode::ProtocolError, format!("part {part}: {} bytes, {expected} expected", data.len()), - )); + ))); } sha256.update(&data); if failed.is_none() { @@ -389,39 +481,46 @@ impl Client { ) -> Result { check_name(topic, "topic")?; check_name(node, "node")?; - if !(1..=MAX_MESSAGES_PER_PACKET).contains(&limit) { - return Err(Error::new( - ErrorCode::InvalidArgument, - format!("a limit of {limit}: 1 to {MAX_MESSAGES_PER_PACKET}"), - )); - } - if after.is_some_and(|after| after > MAX_MESSAGE_ID) { - return Err(Error::new( - ErrorCode::InvalidArgument, - format!("after {}: {MAX_MESSAGE_ID} at most", after.unwrap_or(0)), - )); - } + require((1..=MAX_MESSAGES_PER_PACKET).contains(&limit), || { + format!("a limit of {limit}: 1 to {MAX_MESSAGES_PER_PACKET}") + })?; + require(after.is_none_or(|after| after <= MAX_MESSAGE_ID), || { + format!("after {}: {MAX_MESSAGE_ID} at most", after.unwrap_or(0)) + })?; let get = GetMessages { topic: topic.to_owned(), node: node.to_owned(), after, limit, }; - match self.request(get.into())? { - Packet::Messages(messages) => Ok(messages), - other => Err(unexpected(&other)), - } + self.request(get.into()) } /// The topics with messages that this client may push to or read, or /// the nodes with messages in the topics it may read; every one if its - /// roles have `list_topics` / `list_nodes`, or `query`. `truncated` if - /// some didn't fit. - pub fn list_names(&mut self, kind: NameKind) -> Result { - match self.request(ListNames { kind }.into())? { - Packet::NamesList(names) => Ok(names), - other => Err(unexpected(&other)), + /// roles have `list_topics` / `list_nodes`, or `query`. `topics` and + /// `nodes` (a name or a pattern, `None` for any) keep those of the + /// topic and node pairs they match: the topics a node pushed to, the + /// nodes that pushed to a topic. `truncated` if some didn't fit. + pub fn list_names( + &mut self, + kind: NameKind, + topics: Option<&str>, + nodes: Option<&str>, + ) -> Result { + for (filter, what) in [(topics, "topic"), (nodes, "node")] { + if let Some(filter) = filter { + require(is_valid_name_or_pattern(filter), || { + format!("'{filter}' isn't a {what} name or pattern") + })?; + } } + let list = ListNames { + kind, + topics: topics.map(str::to_owned), + nodes: nodes.map(str::to_owned), + }; + self.request(list.into()) } /// Runs read-only SQL: `{"columns":[...],"rows":[[...],...]}`, every @@ -431,42 +530,113 @@ impl Client { let query = Query { sql: sql.to_owned(), }; - match self.request(query.into())? { - Packet::QueryResult(result) => Ok(result.json), - other => Err(unexpected(&other)), - } + let result: QueryResult = self.request(query.into())?; + Ok(result.json) } - /// Closes the connection: it's out of step (a part not sent, or not - /// as expected). Every request fails then (`ConnectionLost`). + /// Closes the connection for good: every request fails then + /// (`NotConnected`). fn close(&mut self) { + self.closed = true; let _ = self.stream.sock.shutdown(Shutdown::Both); } - /// Sends a request, reads its answer. - fn request(&mut self, packet: Packet) -> Result { - frame::write(&mut self.stream, &packet.encode()).map_err(lost)?; - self.stream.flush().map_err(lost)?; + /// `NotConnected` once closed. + fn check_open(&self) -> Result<()> { + match self.closed { + false => Ok(()), + true => Err(Error::new( + ErrorCode::NotConnected, + "the connection was closed after an earlier failure: connect again", + )), + } + } + + /// `error`, which left the connection out of step: closed. + fn out_of_step(&mut self, error: Error) -> Error { + self.close(); + error + } + + /// An I/O error on the connection: closed. A timeout says so (its + /// answer may still come, after the next request). + fn io_failed(&mut self, error: io::Error) -> Error { + let timed_out = matches!( + error.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut + ); + let error = match timed_out { + true => Error::new( + ErrorCode::ConnectionLost, + format!( + "no answer within {:?}: the connection is closed", + self.answer_timeout + ), + ), + false => lost(error), + }; + self.out_of_step(error) + } + + /// Writes a packet's frame (not flushed). + fn send(&mut self, packet: &Packet) -> Result<()> { + self.check_open()?; + // Refused before anything is written: the connection stays. + let frame = frame::encode(&packet.encode()) + .map_err(|error| Error::new(ErrorCode::InvalidArgument, error.to_string()))?; + let written = self.stream.write_all(&frame); + written.map_err(|error| self.io_failed(error)) + } + + fn flush(&mut self) -> Result<()> { + let flushed = self.stream.flush(); + flushed.map_err(|error| self.io_failed(error)) + } + + /// Sends a request, reads its answer ([`Client::answer`]). + fn request>(&mut self, packet: Packet) -> Result { + self.send(&packet)?; + self.flush()?; self.answer() } - /// Reads the server's next packet: a refusal is an error. - fn answer(&mut self) -> Result { - let bytes = frame::read(&mut self.stream, MAX_PACKET_SIZE) - .map_err(lost)? - .ok_or_else(|| { - Error::new( + /// Reads the server's next packet, a `T`: a refusal is an error (the + /// connection kept), any other packet closes it (`ProtocolError`, the + /// answer isn't the request's), as anything else wrong does. + fn answer>(&mut self) -> Result { + let packet = self.receive()?; + T::try_from(packet).map_err(|other| { + let error = Error::new( + ErrorCode::ProtocolError, + format!("the server answered {}", other.packet_type().name()), + ); + self.out_of_step(error) + }) + } + + /// Reads the server's next packet: a refusal is an error (the + /// connection kept), anything else wrong closes it. + fn receive(&mut self) -> Result { + self.check_open()?; + let bytes = match frame::read(&mut self.stream, MAX_PACKET_SIZE) { + Ok(Some(bytes)) => bytes, + Ok(None) => { + return Err(self.out_of_step(Error::new( ErrorCode::ConnectionLost, "the server closed the connection", - ) - })?; + ))); + } + Err(error) => return Err(self.io_failed(error)), + }; match Packet::decode(&bytes) { Ok(Packet::RequestRefused(refused)) => Err(Error { code: refused.code, message: refused.reason, }), Ok(packet) => Ok(packet), - Err(error) => Err(Error::new(ErrorCode::ProtocolError, error.to_string())), + Err(error) => { + Err(self.out_of_step(Error::new(ErrorCode::ProtocolError, error.to_string()))) + } } } } @@ -511,35 +681,27 @@ fn lost(error: io::Error) -> Error { } } -fn check_name(name: &str, what: &str) -> Result<()> { - if is_valid_name(name) { - Ok(()) - } else { - Err(Error::new( - ErrorCode::InvalidArgument, - format!("'{name}' isn't a {what} name"), - )) +/// An argument checked before sending: `InvalidArgument`, saying `why`, +/// if it isn't `ok`. +fn require(ok: bool, why: impl FnOnce() -> String) -> Result<()> { + match ok { + true => Ok(()), + false => Err(Error::new(ErrorCode::InvalidArgument, why())), } } +fn check_name(name: &str, what: &str) -> Result<()> { + require(is_valid_name(name), || { + format!("'{name}' isn't a {what} name") + }) +} + fn check_size(text: &str, what: &str) -> Result<()> { - if text.len() <= MAX_MESSAGE_SIZE { - Ok(()) - } else { - Err(Error::new( - ErrorCode::InvalidArgument, - format!("{what} of {} bytes: {MAX_MESSAGE_SIZE} at most", text.len()), - )) - } + require(text.len() <= MAX_MESSAGE_SIZE, || { + format!("{what} of {} bytes: {MAX_MESSAGE_SIZE} at most", text.len()) + }) } fn file_error(error: io::Error) -> Error { Error::new(ErrorCode::FileError, format!("the attachment: {error}")) } - -fn unexpected(packet: &Packet) -> Error { - Error::new( - ErrorCode::ProtocolError, - format!("the server answered {}", packet.packet_type().name()), - ) -} diff --git a/crates/bakashrot-client/tests/failures.rs b/crates/bakashrot-client/tests/failures.rs new file mode 100644 index 0000000..5ee045d --- /dev/null +++ b/crates/bakashrot-client/tests/failures.rs @@ -0,0 +1,498 @@ +//! What a failure does to the connection, against a fake server that +//! answers late, wrongly or not at all: a refusal keeps it, anything that +//! leaves it out of step closes it, and nothing is read after (a late +//! answer is never taken for the next request's). + +use bakashrot_client::{ANSWER_TIMEOUT, Client, Settings}; +use bakashrot_pki::{Ca, Identity, Issued, Revocations, Usage, tls}; +use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_PACKET_SIZE}; +use bakashrot_proto::packets::{ + Attachment, AttachmentPart, Continue, MessagePushed, Pong, RequestRefused, Welcome, +}; +use bakashrot_proto::{ErrorCode, Packet, frame}; +use rustls::{ServerConnection, StreamOwned}; +use std::io::{self, Cursor, Read, Seek, SeekFrom, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::mpsc; +use std::thread::{self, JoinHandle}; +use std::time::Duration; + +/// The fake server's end of the connection. +type Stream = StreamOwned; + +/// A fake server for one connection, running its script once the client +/// is connected ([`Fake::connect`] returned: what the script sends is +/// never read while connecting), and the client's certificates. +struct Fake { + address: String, + ca: String, + client: Issued, + /// Lets the script run. + connected: mpsc::Sender<()>, + script: JoinHandle<()>, +} + +impl Fake { + fn start(script: impl FnOnce(&mut Stream) + Send + 'static) -> Fake { + let ca = Ca::create("Fake CA", 1).unwrap(); + let loaded = Ca::load(&ca.certificate, &ca.key).unwrap(); + let issue = |name: &str, usage| { + loaded + .issue(&Identity::new(name, &["sensor"]).unwrap(), usage, 1) + .unwrap() + }; + let server = issue("fake", Usage::Server); + let client = issue("kitchen", Usage::Client); + let config = tls::server_config( + &ca.certificate, + &server.certificate, + &server.key, + Revocations::none().shared(), + ) + .unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap().to_string(); + let (connected, wait_connected) = mpsc::channel(); + let script = thread::spawn(move || { + let (tcp, _) = listener.accept().unwrap(); + tcp.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let mut stream = StreamOwned::new(ServerConnection::new(config).unwrap(), tcp); + while stream.conn.is_handshaking() { + stream.conn.complete_io(&mut stream.sock).unwrap(); + } + frame::write_version(&mut stream).unwrap(); + frame::read_version(&mut stream).unwrap(); + answer( + &mut stream, + Welcome { + server: "fake".into(), + node: "kitchen".into(), + }, + ); + // Gone without connecting: run all the same. + let _ = wait_connected.recv(); + script(&mut stream); + }); + Fake { + address, + ca: ca.certificate, + client, + connected, + script, + } + } + + fn connect(&self) -> Client { + let client = Client::connect( + &self.address, + &Settings { + ca: &self.ca, + certificate: &self.client.certificate, + key: &self.client.key, + crl: None, + }, + ) + .unwrap(); + let _ = self.connected.send(()); + client + } + + /// Waits for the script to end (its asserts included). + fn finish(self) { + drop(self.connected); + self.script.join().unwrap(); + } +} + +/// The client's next packet, none once it closed the connection. +fn request(stream: &mut Stream) -> Option { + let bytes = frame::read(stream, MAX_PACKET_SIZE).ok()??; + Some(Packet::decode(&bytes).unwrap()) +} + +fn answer(stream: &mut Stream, packet: impl Into) { + frame::write(stream, &packet.into().encode()).unwrap(); + stream.flush().unwrap(); +} + +/// Whether the client closed the connection without sending anything +/// more: what a script asserts after its answer. +fn nothing_more(stream: &mut Stream) -> bool { + request(stream).is_none() +} + +/// The error `result` failed with, of `code`. +#[track_caller] +fn fails( + result: Result, + code: ErrorCode, +) -> bakashrot_client::Error { + let error = result.unwrap_err(); + assert_eq!(error.code(), code.code(), "{error}"); + error +} + +#[test] +fn a_late_answer_is_never_taken_for_the_next_request() { + let fake = Fake::start(move |stream| { + assert!(matches!(request(stream), Some(Packet::PushMessage(_)))); + thread::sleep(Duration::from_millis(600)); + // Too late: the client gave up, and closed. + let _ = frame::write( + stream, + &Packet::from(MessagePushed { message_id: 1 }).encode(), + ); + let _ = stream.flush(); + assert!(nothing_more(stream), "the client sent something more"); + }); + let mut client = fake.connect(); + client + .set_answer_timeout(Duration::from_millis(200)) + .unwrap(); + let error = fails(client.push("logs", "{}"), ErrorCode::ConnectionLost); + assert!( + error.message().contains("no answer within 200ms"), + "{error}" + ); + assert!(!client.is_open() && client.is_closed()); + // Once the late answer is there, the next push mustn't read it as its + // own (it got #1 before). + thread::sleep(Duration::from_millis(700)); + fails(client.push("logs", "{}"), ErrorCode::NotConnected); + fails(client.ping(), ErrorCode::NotConnected); + fake.finish(); +} + +#[test] +fn a_wrong_answer_closes() { + let fake = Fake::start(move |stream| { + assert!(matches!(request(stream), Some(Packet::PushMessage(_)))); + answer(stream, Pong {}); + assert!(nothing_more(stream), "the client sent something more"); + }); + let mut client = fake.connect(); + fails(client.push("logs", "{}"), ErrorCode::ProtocolError); + assert!(!client.is_open() && client.is_closed()); + fails(client.ping(), ErrorCode::NotConnected); + fake.finish(); +} + +#[test] +fn a_malformed_answer_closes() { + let fake = Fake::start(move |stream| { + assert!(matches!(request(stream), Some(Packet::Ping(_)))); + // 0xc1 is never MessagePack. + frame::write(stream, &[0xc1]).unwrap(); + stream.flush().unwrap(); + assert!(nothing_more(stream), "the client sent something more"); + }); + let mut client = fake.connect(); + fails(client.ping(), ErrorCode::ProtocolError); + fails(client.query("SELECT 1"), ErrorCode::NotConnected); + fake.finish(); +} + +#[test] +fn an_answer_cut_short_closes() { + let fake = Fake::start(|stream| { + assert!(matches!(request(stream), Some(Packet::GetMessages(_)))); + // A frame of 100 bytes, 3 of them sent, then the connection gone. + stream.write_all(&[100, 0, 0, 0, 1, 2, 3]).unwrap(); + stream.flush().unwrap(); + stream.conn.send_close_notify(); + let _ = stream.conn.complete_io(&mut stream.sock); + }); + let mut client = fake.connect(); + fails( + client.get_messages("logs", "kitchen", Some(0), 10), + ErrorCode::ConnectionLost, + ); + fails(client.ping(), ErrorCode::NotConnected); + fake.finish(); +} + +#[test] +fn a_refusal_keeps_the_connection() { + let fake = Fake::start(|stream| { + assert!(matches!(request(stream), Some(Packet::PushMessage(_)))); + answer( + stream, + RequestRefused::new(ErrorCode::NotAllowed, "not this topic"), + ); + assert!(matches!(request(stream), Some(Packet::Ping(_)))); + answer(stream, Pong {}); + assert!(matches!(request(stream), Some(Packet::PushMessage(_)))); + answer(stream, MessagePushed { message_id: 7 }); + }); + let mut client = fake.connect(); + let error = fails(client.push("logs", "{}"), ErrorCode::NotAllowed); + assert_eq!(error.message(), "not this topic"); + assert!(client.is_open() && !client.is_closed()); + client.ping().unwrap(); + assert_eq!(client.push("logs", "{}").unwrap(), 7); + fake.finish(); +} + +#[test] +fn an_argument_refused_before_sending_keeps_the_connection() { + let fake = Fake::start(|stream| { + assert!(matches!(request(stream), Some(Packet::Ping(_)))); + answer(stream, Pong {}); + }); + let mut client = fake.connect(); + fails(client.push("not a name", "{}"), ErrorCode::InvalidArgument); + fails( + client.get_messages("logs", "kitchen", Some(0), 0), + ErrorCode::InvalidArgument, + ); + fails( + client.set_answer_timeout(Duration::ZERO), + ErrorCode::InvalidArgument, + ); + assert_eq!(client.answer_timeout(), ANSWER_TIMEOUT); + client.ping().unwrap(); + fake.finish(); +} + +#[test] +fn a_longer_timeout_waits_for_a_slow_answer() { + let fake = Fake::start(|stream| { + assert!(matches!(request(stream), Some(Packet::Ping(_)))); + thread::sleep(Duration::from_millis(500)); + answer(stream, Pong {}); + }); + let mut client = fake.connect(); + client.set_answer_timeout(Duration::from_secs(5)).unwrap(); + assert_eq!(client.answer_timeout(), Duration::from_secs(5)); + client.ping().unwrap(); + fake.finish(); +} + +/// `is_open()` looks without blocking, then blocks again: the next +/// request waits for its answer, slow as it is. +#[test] +fn is_open_leaves_the_connection_blocking() { + let fake = Fake::start(|stream| { + assert!(matches!(request(stream), Some(Packet::Ping(_)))); + thread::sleep(Duration::from_millis(300)); + answer(stream, Pong {}); + }); + let mut client = fake.connect(); + assert!(client.is_open() && !client.is_closed()); + client.ping().unwrap(); + fake.finish(); +} + +/// The server gone (closed as it closes an idle one: the socket, no TLS +/// close_notify): `is_open()` says so, the next request fails as lost, +/// those after as not connected. +#[test] +fn a_connection_the_server_closed() { + let fake = Fake::start(|stream| { + let _ = stream.sock.shutdown(std::net::Shutdown::Both); + }); + let mut client = fake.connect(); + let address = fake.address.clone(); + fake.finish(); + assert!(gone(&mut client), "{address}: still open"); + assert!(!client.is_open() && !client.is_closed()); + fails(client.ping(), ErrorCode::ConnectionLost); + fails(client.ping(), ErrorCode::NotConnected); +} + +/// Whether `is_open()` says closed within a second (what the fake sent +/// on its way). +fn gone(client: &mut Client) -> bool { + for _ in 0..50 { + if !client.is_open() { + return true; + } + thread::sleep(Duration::from_millis(20)); + } + false +} + +/// Sends what TLS holds, without waiting for anything back. +fn send_tls(stream: &mut Stream) { + while stream.conn.wants_write() { + stream.conn.write_tls(&mut stream.sock).unwrap(); + } +} + +/// TLS's close_notify, the socket kept open (as a proxy closing politely +/// might): `is_open()` notices it from TLS alone, and keeps saying so. +/// The next request fails as lost, those after as not connected. +#[test] +fn a_close_notify_is_noticed() { + let (done, wait_done) = mpsc::channel::<()>(); + let fake = Fake::start(move |stream| { + stream.conn.send_close_notify(); + send_tls(stream); + // The socket open until the client looked. + let _ = wait_done.recv(); + }); + let mut client = fake.connect(); + assert!(gone(&mut client), "still open after close_notify"); + assert!(!client.is_open() && !client.is_open() && !client.is_closed()); + fails(client.ping(), ErrorCode::ConnectionLost); + fails(client.ping(), ErrorCode::NotConnected); + done.send(()).unwrap(); + fake.finish(); +} + +/// An answer to no request: the connection is out of step, so +/// `is_open()` closes it, and nothing more is sent. +#[test] +fn data_sent_unasked_closes() { + let fake = Fake::start(move |stream| { + answer(stream, Pong {}); + assert!(nothing_more(stream), "the client sent something more"); + }); + let mut client = fake.connect(); + assert!(gone(&mut client), "still open with data sent unasked"); + assert!(client.is_closed()); + fails(client.ping(), ErrorCode::NotConnected); + fake.finish(); +} + +/// Bytes that aren't TLS (a record of no known type): broken, closed. +#[test] +fn a_broken_tls_stream_closes() { + let fake = Fake::start(move |stream| { + stream.sock.write_all(&[0x99, 3, 3, 0, 1, 0]).unwrap(); + assert!(nothing_more(stream), "the client sent something more"); + }); + let mut client = fake.connect(); + assert!(gone(&mut client), "still open with a broken TLS stream"); + assert!(client.is_closed()); + fails(client.ping(), ErrorCode::NotConnected); + fake.finish(); +} + +/// What TLS sends for itself (a key update here, like the session +/// tickets after the handshake) isn't data: `is_open()` reads it, stays +/// open, and the next request works, under the new keys. +#[test] +fn tls_records_of_its_own_keep_it_open() { + let (sent, wait_sent) = mpsc::channel(); + let fake = Fake::start(move |stream| { + stream.conn.refresh_traffic_keys().unwrap(); + send_tls(stream); + sent.send(()).unwrap(); + assert!(matches!(request(stream), Some(Packet::Ping(_)))); + answer(stream, Pong {}); + }); + let mut client = fake.connect(); + wait_sent.recv().unwrap(); + // The record on its way over loopback. + thread::sleep(Duration::from_millis(200)); + for _ in 0..3 { + assert!(client.is_open() && !client.is_closed()); + } + client.ping().unwrap(); + fake.finish(); +} + +#[test] +fn a_part_of_the_wrong_size_closes() { + let fake = Fake::start(move |stream| { + assert!(matches!(request(stream), Some(Packet::GetAttachment(_)))); + answer( + stream, + Attachment { + size: 10, + sha256: [0; 32], + }, + ); + answer(stream, AttachmentPart { data: vec![1; 5] }); + assert!(nothing_more(stream), "the client sent something more"); + }); + let mut client = fake.connect(); + let mut out = Vec::new(); + fails( + client.get_attachment("logs", "kitchen", 1, &mut out), + ErrorCode::ProtocolError, + ); + fails(client.ping(), ErrorCode::NotConnected); + fake.finish(); +} + +/// A refusal where a part should be: the parts after it would be read as +/// the next request's answers. +#[test] +fn a_refusal_among_the_parts_closes() { + let fake = Fake::start(move |stream| { + assert!(matches!(request(stream), Some(Packet::GetAttachment(_)))); + answer( + stream, + Attachment { + size: ATTACHMENT_PART_SIZE + 1, + sha256: [0; 32], + }, + ); + answer( + stream, + AttachmentPart { + data: vec![1; ATTACHMENT_PART_SIZE as usize], + }, + ); + answer( + stream, + RequestRefused::new(ErrorCode::ServerError, "a disk"), + ); + assert!(nothing_more(stream), "the client sent something more"); + }); + let mut client = fake.connect(); + let mut out = Vec::new(); + fails( + client.get_attachment("logs", "kitchen", 1, &mut out), + ErrorCode::ServerError, + ); + fails(client.ping(), ErrorCode::NotConnected); + fake.finish(); +} + +/// Bytes that read the first time through, and fail the second. +struct FailingSecondTime { + data: Cursor>, + rewinds: usize, +} + +impl Read for FailingSecondTime { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + if self.rewinds > 1 { + return Err(io::Error::other("the disk went away")); + } + self.data.read(buffer) + } +} + +impl Seek for FailingSecondTime { + fn seek(&mut self, to: SeekFrom) -> io::Result { + self.rewinds += 1; + self.data.seek(to) + } +} + +/// The source failing once the server said `Continue`: the server waits +/// for parts that won't come, the connection closes. +#[test] +fn a_source_failing_mid_upload_closes() { + let fake = Fake::start(move |stream| { + assert!(matches!(request(stream), Some(Packet::PushMessage(_)))); + answer(stream, Continue {}); + assert!(nothing_more(stream), "the client sent something more"); + }); + let mut client = fake.connect(); + let mut source = FailingSecondTime { + data: Cursor::new(vec![7; 100]), + rewinds: 0, + }; + fails( + client.push_with_attachment("logs", "{}", &mut source), + ErrorCode::FileError, + ); + assert!(!client.is_open() && client.is_closed()); + fails(client.ping(), ErrorCode::NotConnected); + fake.finish(); +} diff --git a/crates/bakashrot-config/example.toml b/crates/bakashrot-config/example.toml index 14a3772..f1088ba 100644 --- a/crates/bakashrot-config/example.toml +++ b/crates/bakashrot-config/example.toml @@ -11,7 +11,7 @@ [server] listen = "0.0.0.0:7000" # required: address and port -# The certificates (bakashrot-cert), required. The node this server is, +# The certificates (bakashrot cert), required. The node this server is, # for its peers, is its certificate's name. ca = "ca.crt" certificate = "server-1.crt" @@ -32,10 +32,13 @@ synchronous = "full" # well under it (more than a few GB is a lot for this anyway). max_attachment_size = "1G" # bytes, or K M G T (1024-based); 0: none retention_interval = "1m" # how often old messages are deleted +idle_database_connections = 8 # kept open once idle, for reads and as many for queries; closed after 1 min unused +query_time_limit = "20s" # a client's query stopped (refused) past it; keep it under the clients' answer timeout (30 s) # How long each topic's messages are kept, from when they were first -# pushed. A topic takes its name's line, else the first pattern matching -# it, else "*"'s; without any, it's kept forever. +# pushed: 100 years ("36500d") at most, or "forever". A topic takes its +# name's line, else the first pattern matching it, else "*"'s; without +# any, it's kept forever. [retention] logs = "30d" "sensors.*" = "12h" @@ -47,7 +50,7 @@ logs = "30d" push_to = [] # dialed and sent to: ["10.0.0.2:7000", "server-2.lan:7000"] accept_from = [] # taken from: ["10.0.0.2", "server-2.lan"], or ["*"] retry_delay = "10s" -sync_interval = "5s" # keep it under 5 min: a link idle that long is closed +sync_interval = "5s" # a link waiting longer than a minute pings meanwhile batch_size = 1000 # messages per packet, 1-10000 # What certificates with a role may do. A certificate gets everything its diff --git a/crates/bakashrot-config/src/lib.rs b/crates/bakashrot-config/src/lib.rs index 23d70f8..1d18b22 100644 --- a/crates/bakashrot-config/src/lib.rs +++ b/crates/bakashrot-config/src/lib.rs @@ -29,6 +29,11 @@ use std::path::{Path, PathBuf}; use std::time::Duration; use values::{DURATION_HELP, NAME_HELP, parse_age}; +/// The longest retention age: 100 years (36500 days). Longer is +/// "forever"; past about 584 million years, an age wouldn't even fit in +/// milliseconds. +pub const MAX_RETENTION_AGE: Duration = Duration::from_secs(36_500 * 86_400); + /// What's wrong with a config, in words: where (the file, the line) and why. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Error(String); @@ -95,6 +100,22 @@ pub struct Server { deserialize_with = "values::duration" )] pub retention_interval: Duration, + /// The most database connections kept open once idle, for reads, and + /// as many for queries (0 to 512); 8 by default. More are opened + /// while they're needed, and closed after a minute unused. + #[serde( + default = "defaults::idle_database_connections", + deserialize_with = "values::idle_connections" + )] + pub idle_database_connections: usize, + /// How long a client's query may run before it's stopped and refused + /// (`QueryTimedOut`); 20 s by default. Under the clients' answer timeout + /// (30 s by default), so they get the refusal rather than give up. + #[serde( + default = "defaults::query_time_limit", + deserialize_with = "values::duration" + )] + pub query_time_limit: Duration, } /// How hard the database makes sure a push is on disk before answering it @@ -165,6 +186,11 @@ impl TryFrom> for Retention { let age = age.ok_or_else(|| { format!("{key} = {value} isn't an age: {DURATION_HELP}, or \"forever\"") })?; + if age.is_some_and(|age| age > MAX_RETENTION_AGE) { + return Err(format!( + "{key} = {value}: 100 years (36500d) at most, or \"forever\"" + )); + } lines.push((key, age)); } Ok(Retention { lines }) @@ -185,6 +211,14 @@ impl Retention { .or_else(|| self.lines.iter().find(|(key, _)| key == "*")) .and_then(|(_, age)| *age) } + + /// When `topic`'s messages pushed before are past their age, for a + /// clock at `now` (both in ms since 1970), `None` if they're kept + /// forever. 0 while the clock is earlier than the age. + pub fn cutoff(&self, topic: &str, now: u64) -> Option { + let age = self.age(topic)?; + Some(now.saturating_sub(u64::try_from(age.as_millis()).unwrap_or(u64::MAX))) + } } /// `[replication]`. @@ -238,6 +272,12 @@ mod defaults { pub(crate) fn retention_interval() -> Duration { Duration::from_secs(60) } + pub(crate) fn idle_database_connections() -> usize { + 8 + } + pub(crate) fn query_time_limit() -> Duration { + Duration::from_secs(20) + } } /// `[roles.*]`: each section's name is its role's, none twice. diff --git a/crates/bakashrot-config/src/roles.rs b/crates/bakashrot-config/src/roles.rs index 7ae812f..88dce97 100644 --- a/crates/bakashrot-config/src/roles.rs +++ b/crates/bakashrot-config/src/roles.rs @@ -1,7 +1,7 @@ //! Roles, and what a certificate's roles allow together. use crate::values::check_names; -use bakashrot_proto::names::{names_equal, pattern_matches}; +use bakashrot_proto::names::{name_matches, names_equal}; use serde::Deserialize; /// Topic or node names and patterns (`sensors.*`, `*` for all), none twice. @@ -27,9 +27,7 @@ impl NameList { /// Whether `name` is in it: one of its names, or matched by one of its /// patterns (without case). pub fn matches(&self, name: &str) -> bool { - self.0 - .iter() - .any(|entry| names_equal(entry, name) || pattern_matches(entry, name)) + self.0.iter().any(|entry| name_matches(entry, name)) } /// Whether it has nothing: matches nothing. @@ -117,15 +115,24 @@ impl Permissions { self.roles.iter().any(|role| role.query) } - /// Whether listing topics answers every one: `list_topics`, or - /// `query` (which reads them all anyway). - pub fn lists_every_topic(&self) -> bool { - self.roles.iter().any(|role| role.list_topics || role.query) + /// Whether listing names may show `topic`: one it may push to or + /// read, any with `list_topics` or `query` (which reads them all + /// anyway). + pub fn may_list_topic(&self, topic: &str) -> bool { + self.roles.iter().any(|role| { + role.list_topics + || role.query + || role.push_topics.matches(topic) + || role.read_topics.matches(topic) + }) } - /// Whether listing nodes answers every one: `list_nodes`, or `query`. - pub fn lists_every_node(&self) -> bool { - self.roles.iter().any(|role| role.list_nodes || role.query) + /// Whether listing names may show the nodes with messages in `topic`: + /// one it may read, any with `list_nodes` or `query`. + pub fn may_list_nodes_of(&self, topic: &str) -> bool { + self.roles + .iter() + .any(|role| role.list_nodes || role.query || role.read_topics.matches(topic)) } /// Whether `node`'s messages in `topic` are sent to it. diff --git a/crates/bakashrot-config/src/values.rs b/crates/bakashrot-config/src/values.rs index 9a15fe2..8e0ea05 100644 --- a/crates/bakashrot-config/src/values.rs +++ b/crates/bakashrot-config/src/values.rs @@ -184,6 +184,21 @@ pub(crate) fn batch_size<'de, D: Deserializer<'de>>(reader: D) -> Result>(reader: D) -> Result { + let count = u32::deserialize(reader)?; + if count > MAX_IDLE_CONNECTIONS { + return Err(D::Error::custom(format!( + "{count} idle database connections: 0 to {MAX_IDLE_CONNECTIONS}" + ))); + } + Ok(count as usize) +} + /// Checks a list of names or patterns, none twice. pub(crate) fn check_names(list: &[String]) -> Result<(), String> { for (at, entry) in list.iter().enumerate() { diff --git a/crates/bakashrot-config/tests/config.rs b/crates/bakashrot-config/tests/config.rs index 2bed107..ab4dfc6 100644 --- a/crates/bakashrot-config/tests/config.rs +++ b/crates/bakashrot-config/tests/config.rs @@ -59,6 +59,8 @@ fn defaults() { assert_eq!(server.synchronous, Synchronous::Full); assert_eq!(server.max_attachment_size, 1 << 30); assert_eq!(server.retention_interval, Duration::from_secs(60)); + assert_eq!(server.idle_database_connections, 8); + assert_eq!(server.query_time_limit, Duration::from_secs(20)); assert_eq!(config.retention.age("logs"), None); assert_eq!(config.replication.retry_delay, Duration::from_secs(10)); assert_eq!(config.replication.sync_interval, Duration::from_secs(5)); @@ -75,6 +77,8 @@ database = "data/messages.sqlite" synchronous = "NORMAL" max_attachment_size = 0 retention_interval = "1h30m" +idle_database_connections = 0 +query_time_limit = "2m" [replication] push_to = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"] @@ -89,6 +93,8 @@ batch_size = 10000 assert_eq!(config.server.synchronous, Synchronous::Normal); assert_eq!(config.server.max_attachment_size, 0); assert_eq!(config.server.retention_interval, Duration::from_secs(5400)); + assert_eq!(config.server.idle_database_connections, 0); + assert_eq!(config.server.query_time_limit, Duration::from_secs(120)); assert_eq!(config.replication.push_to.len(), 3); assert_eq!(config.replication.accept_from[2], "fd00::4"); assert_eq!(config.replication.retry_delay, Duration::from_secs(60)); @@ -122,6 +128,24 @@ logs = "30d" assert_eq!(age("other"), days(365)); } +/// Ages go up to 100 years, and the cutoff never wraps around. +#[test] +fn retention_cutoff() { + let config = Config::parse(&with( + "[retention]\nlogs = \"36500d\"\nsensors = \"1h\"\n\"*\" = \"forever\"\n", + )) + .unwrap(); + assert_eq!(config.retention.age("logs"), days(36_500)); + let now = 2_000_000_000_000; + assert_eq!( + config.retention.cutoff("sensors", now), + Some(now - 3_600_000) + ); + // Longer than the clock is old: nothing is past it yet. + assert_eq!(config.retention.cutoff("logs", now), Some(0)); + assert_eq!(config.retention.cutoff("other", now), None); +} + #[test] fn permissions() { let config = Config::parse(&with( @@ -164,19 +188,23 @@ accept_nodes = ["garage"] assert!(both.can_read("Logs")); assert!(!both.can_read("sensors.garage")); assert!(!both.can_query()); - assert!(!both.lists_every_topic() && !both.lists_every_node()); + // Listing: the topics it may push to or read, the nodes of those it reads. + assert!(both.may_list_topic("sensors.garage") && both.may_list_topic("logs")); + assert!(!both.may_list_topic("other")); + assert!(both.may_list_nodes_of("logs") && !both.may_list_nodes_of("sensors.garage")); let admin = config.permissions(&["admin"]).unwrap(); assert!(admin.can_query()); - // A query reads them all anyway. - assert!(admin.lists_every_topic() && admin.lists_every_node()); + // A query reads them all anyway; reading messages is still read_topics. + assert!(admin.may_list_topic("other") && admin.may_list_nodes_of("other")); + assert!(!admin.can_read("logs")); let listing = Config::parse(&with( "[roles.a]\nlist_topics = true\n[roles.b]\nlist_nodes = true\n", )) .unwrap(); let a = listing.permissions(&["a"]).unwrap(); - assert!(a.lists_every_topic() && !a.lists_every_node() && !a.can_query()); + assert!(a.may_list_topic("other") && !a.may_list_nodes_of("other") && !a.can_query()); let b = listing.permissions(&["b", "a"]).unwrap(); - assert!(b.lists_every_topic() && b.lists_every_node()); + assert!(b.may_list_topic("other") && b.may_list_nodes_of("other")); // Replication: each role's topics with that role's nodes, not mixed. let peer = config.permissions(&["peer", "backup"]).unwrap(); @@ -273,6 +301,18 @@ fn refusals() { &with("retention_interval = \"0s\"\n"), "'0s' isn't a duration", ), + ( + &with("idle_database_connections = 513\n"), + "513 idle database connections: 0 to 512", + ), + ( + &with("idle_database_connections = -1\n"), + "invalid value: integer `-1`", + ), + ( + &with("query_time_limit = \"0s\"\n"), + "'0s' isn't a duration", + ), // [retention] ( &with("[retention]\nlogs = \"30\"\n"), @@ -291,6 +331,16 @@ fn refusals() { &with("[retention]\nsensors.kitchen = \"1d\"\n"), "quote names with dots", ), + // 100 years at most: past 2^64 ms an age once wrapped around to + // almost nothing ("18446744073709552s" was 384 ms). + ( + &with("[retention]\nlogs = \"36501d\"\n"), + "100 years (36500d) at most", + ), + ( + &with("[retention]\nlogs = \"18446744073709552s\"\n"), + "100 years (36500d) at most", + ), // [replication] ( &with("[replication]\npush_to = [\"10.0.0.2\"]\n"), @@ -338,6 +388,10 @@ fn refusals() { &with("[roles.r]\naccept_nodes = [\"x\", \"X\"]\n"), "'X' is given twice", ), + ( + &with("[roles.r]\nlist_topics = 1\n"), + "invalid type: integer", + ), (&with("[roles.r]\nquery = 1\n"), "invalid type: integer"), (&with("[roles.site.reader]\n"), "unknown field `reader`"), ]; diff --git a/crates/bakashrot-proto/src/error.rs b/crates/bakashrot-proto/src/error.rs index 8b52361..f061af7 100644 --- a/crates/bakashrot-proto/src/error.rs +++ b/crates/bakashrot-proto/src/error.rs @@ -6,7 +6,8 @@ //! What to do about each: //! - reconnect, then retry: `NotConnected`, `ConnectFailed`, //! `ConnectionLost`, `ProtocolError` (the connection is closed); -//! - retry later: `NotReady`, `ServerError`; +//! - retry later: `NotReady`, `ServerError`, `QueryTimedOut` (or narrow +//! the query); //! - fix the configuration: `AuthRejected`, `ServerNotVerified`, //! `NotAllowed`, `UnknownName`; //! - update one end: `VersionMismatch`; @@ -74,6 +75,7 @@ error_codes! { DataMismatch = 8, "An uploaded attachment that doesn't match its SHA-256: dropped."; QueryFailed = 9, "The SQL of a query failed (its error in the reason)."; ServerError = 10, "The server couldn't store or read something: its database failed."; + QueryTimedOut = 11, "A query ran past the server's time limit (query_time_limit) and was stopped: narrow it, or retry when the server is less busy."; // The client's own. NotConnected = 100, "Not connected: never, or the connection was closed or lost before."; @@ -140,6 +142,7 @@ mod tests { (8, "DataMismatch"), (9, "QueryFailed"), (10, "ServerError"), + (11, "QueryTimedOut"), (100, "NotConnected"), (101, "ConnectFailed"), (102, "AuthRejected"), diff --git a/crates/bakashrot-proto/src/frame.rs b/crates/bakashrot-proto/src/frame.rs index 9ffdbe0..ecb9c3e 100644 --- a/crates/bakashrot-proto/src/frame.rs +++ b/crates/bakashrot-proto/src/frame.rs @@ -169,11 +169,11 @@ mod tests { fn versions() { let mut stream = Vec::new(); write_version(&mut stream).unwrap(); - assert_eq!(stream, [7, 0, 0, 0]); + assert_eq!(stream, [8, 0, 0, 0]); let bytes = read_version(&mut &stream[..]).unwrap(); assert_eq!(check_version(bytes), Ok(())); - assert_eq!(check_version([6, 0, 0, 0]), Err(6)); - assert_eq!(check_version([8, 0, 0, 0]), Err(8)); + assert_eq!(check_version([7, 0, 0, 0]), Err(7)); + assert_eq!(check_version([9, 0, 0, 0]), Err(9)); assert!(read_version(&mut &[7u8, 0][..]).is_err()); } diff --git a/crates/bakashrot-proto/src/lib.rs b/crates/bakashrot-proto/src/lib.rs index 8159e8a..32e3bda 100644 --- a/crates/bakashrot-proto/src/lib.rs +++ b/crates/bakashrot-proto/src/lib.rs @@ -1,4 +1,4 @@ -//! BakaShrot's protocol, version 7: what the server, the clients and the +//! BakaShrot's protocol, version 8: what the server, the clients and the //! tools share, and nothing else. //! //! No I/O of its own beyond reading and writing frames on a stream it's diff --git a/crates/bakashrot-proto/src/limits.rs b/crates/bakashrot-proto/src/limits.rs index 487b118..cef4ff3 100644 --- a/crates/bakashrot-proto/src/limits.rs +++ b/crates/bakashrot-proto/src/limits.rs @@ -5,13 +5,22 @@ /// The protocol's version. Both ends must have the same: they tell each /// other first thing (`frame::write_version()`), and abandon the /// connection if it differs. -pub const PROTOCOL_VERSION: u32 = 7; +pub const PROTOCOL_VERSION: u32 = 8; /// The ALPN protocol name both ends offer during the TLS handshake: what /// isn't BakaShrot doesn't get past it. Not versioned: the version is /// checked once connected, so a mismatch is told as such. pub const ALPN: &[u8] = b"bakashrot"; +/// How long a server lets a connection stay silent between requests +/// before it closes it, in seconds (5 min). An end that waits longer +/// between requests sends a `Ping` every [`KEEPALIVE_SECS`] meanwhile. +pub const IDLE_TIMEOUT_SECS: u64 = 300; + +/// How often an end waiting between requests sends a `Ping` to keep the +/// connection open, in seconds: well under [`IDLE_TIMEOUT_SECS`]. +pub const KEEPALIVE_SECS: u64 = 60; + /// The biggest packet on the wire, in bytes (a frame's size field). pub const MAX_PACKET_SIZE: usize = 16 * 1024 * 1024; @@ -43,6 +52,11 @@ pub const MAX_NAMES_LIST_ENTRIES: usize = 65_536; /// The most attachments a `SyncState` lists as missing at once. pub const MAX_MISSING_ATTACHMENTS: usize = 256; +/// The most heads in one `SyncState`: the others come in the next ones +/// (`more`). With every list of the first full and every name 64 +/// characters long, it still fits in a packet (about 13.3 MB). +pub const MAX_HEADS_PER_PACKET: usize = 32_768; + /// Attachments go in parts of this many bytes, the last one what's left. pub const ATTACHMENT_PART_SIZE: u64 = 1024 * 1024; diff --git a/crates/bakashrot-proto/src/names.rs b/crates/bakashrot-proto/src/names.rs index f86d120..b3831f4 100644 --- a/crates/bakashrot-proto/src/names.rs +++ b/crates/bakashrot-proto/src/names.rs @@ -45,6 +45,12 @@ pub fn is_valid_name_or_pattern(text: &str) -> bool { is_valid_name(text) || is_valid_pattern(text) } +/// Whether `name` is `filter` (a name) or matches it (a pattern), without +/// case: what a list of names and patterns holds, one entry. +pub fn name_matches(filter: &str, name: &str) -> bool { + names_equal(filter, name) || pattern_matches(filter, name) +} + /// Whether the name `name` matches `pattern` (without case). Anything that /// isn't a valid name never matches. pub fn pattern_matches(pattern: &str, name: &str) -> bool { @@ -144,4 +150,12 @@ mod tests { ); } } + + #[test] + fn filters() { + assert!(name_matches("Logs", "logs")); + assert!(name_matches("sensors.*", "Sensors.kitchen")); + assert!(!name_matches("logs", "logs-1")); + assert!(!name_matches("sensors.*", "sensor.x")); + } } diff --git a/crates/bakashrot-proto/src/packets/messages.rs b/crates/bakashrot-proto/src/packets/messages.rs index d958d24..c6c94f7 100644 --- a/crates/bakashrot-proto/src/packets/messages.rs +++ b/crates/bakashrot-proto/src/packets/messages.rs @@ -201,16 +201,36 @@ impl TryFrom for NameKind { } } -/// Every topic or node the client may see. +/// The topics or nodes the client may see, of the topic and node pairs +/// with messages that the filters match: the topics a node pushed to, the +/// nodes that pushed to a topic. /// -/// `[11, [kind]]` +/// `[11, [kind, topics, nodes]]` #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListNames { /// Topics or nodes. pub kind: NameKind, + /// Only the pairs whose topic is this name or matches this pattern; + /// nil for any. + pub topics: Option, + /// Only the pairs whose node is this name or matches this pattern; + /// nil for any. + pub nodes: Option, } -impl Check for ListNames {} +impl Check for ListNames { + fn check(&self) -> Result<(), DecodeError> { + for (filter, field) in [ + (&self.topics, "ListNames.topics"), + (&self.nodes, "ListNames.nodes"), + ] { + if let Some(filter) = filter { + rules::name_or_pattern(filter, field)?; + } + } + Ok(()) + } +} /// Topics or nodes. /// diff --git a/crates/bakashrot-proto/src/packets/mod.rs b/crates/bakashrot-proto/src/packets/mod.rs index bb7763e..57835a6 100644 --- a/crates/bakashrot-proto/src/packets/mod.rs +++ b/crates/bakashrot-proto/src/packets/mod.rs @@ -1,4 +1,4 @@ -//! Every packet of protocol 7. +//! Every packet of protocol 8. //! //! A packet is a MessagePack array of two: its type, then its fields as an //! array, `[type, [field, field, ...]]`. Structs inside are arrays of their @@ -33,10 +33,10 @@ pub use messages::{ PushMessage, Query, QueryResult, StoredAttachment, }; pub use replication::{ - Head, MissingAttachment, ReplicateAttachment, ReplicateMessages, ReplicatedMessage, SyncState, - SyncStateRequest, + Head, MissingAttachment, Pair, ReplicateAttachment, ReplicateMessages, ReplicatedMessage, + SyncState, SyncStateRequest, }; -pub use session::{Continue, RequestRefused, Welcome}; +pub use session::{Continue, Ping, Pong, RequestRefused, Welcome}; use serde::de::{self, DeserializeOwned, IgnoredAny, SeqAccess, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; @@ -144,6 +144,17 @@ macro_rules! packets { Packet::$name(body) } } + + /// The body of a packet of this type, or the packet back. + impl TryFrom for $name { + type Error = Packet; + fn try_from(packet: Packet) -> Result<$name, Packet> { + match packet { + Packet::$name(body) => Ok(body), + other => Err(other), + } + } + } )* impl Packet { @@ -244,6 +255,10 @@ packets! { ReplicateMessages = 17, /// P→S: an attachment the server is missing, its parts after it (`Continue`, then `MessagePushed` / `RequestRefused`). ReplicateAttachment = 18, + /// C→S, P→S: keeps an idle connection open (`Pong`). + Ping = 19, + /// S→C, S→P: the answer to a `Ping`. + Pong = 20, } impl Packet { @@ -298,6 +313,15 @@ pub(crate) mod rules { require(names::is_valid_name(value), field, "must be a name") } + /// A topic or node name, or a pattern. + pub fn name_or_pattern(value: &str, field: &'static str) -> Result<(), DecodeError> { + require( + names::is_valid_name_or_pattern(value), + field, + "must be a name or a pattern", + ) + } + /// A message id: 1 and up. pub fn message_id(value: u64, field: &'static str) -> Result<(), DecodeError> { range(value, 1, MAX_MESSAGE_ID, field) diff --git a/crates/bakashrot-proto/src/packets/replication.rs b/crates/bakashrot-proto/src/packets/replication.rs index f407436..1057616 100644 --- a/crates/bakashrot-proto/src/packets/replication.rs +++ b/crates/bakashrot-proto/src/packets/replication.rs @@ -6,20 +6,43 @@ use super::rules; use super::{Attachment, Check, DecodeError}; use crate::limits::{ - MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_MISSING_ATTACHMENTS, - MAX_NAMES_LIST_ENTRIES, + MAX_ATTACHMENT_PARTS, MAX_HEADS_PER_PACKET, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, + MAX_MISSING_ATTACHMENTS, MAX_NAMES_LIST_ENTRIES, }; -use crate::names; use serde::{Deserialize, Serialize}; /// What the server takes from this peer, how far it is, and the -/// attachments it lacks. +/// attachments it lacks: a page of its `SyncState`, the first without +/// `after`. /// -/// `[15, []]` +/// `[15, [after]]` #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct SyncStateRequest {} +pub struct SyncStateRequest { + /// The heads after this pair (the last of the previous page), or none + /// for the first page. + pub after: Option, +} -impl Check for SyncStateRequest {} +impl Check for SyncStateRequest { + fn check(&self) -> Result<(), DecodeError> { + if let Some(after) = &self.after { + rules::name(&after.topic, "SyncStateRequest.after.topic")?; + rules::name(&after.node, "SyncStateRequest.after.node")?; + } + Ok(()) + } +} + +/// A topic/node pair, by name. +/// +/// `[topic, node]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Pair { + /// The topic. + pub topic: String, + /// The node. + pub node: String, +} /// How far the server is in a topic/node pair. /// @@ -34,6 +57,16 @@ pub struct Head { pub last_id: u64, } +impl From<&Head> for Pair { + /// Its pair: to ask the page after it. + fn from(head: &Head) -> Pair { + Pair { + topic: head.topic.clone(), + node: head.node.clone(), + } + } +} + /// An attachment the server lacks, and where to go on from. /// /// `[topic, node, message_id, next_part]` @@ -50,36 +83,45 @@ pub struct MissingAttachment { } /// What the server takes from this peer, how far it is, and the -/// attachments it lacks: all a check-in needs. +/// attachments it lacks: all a check-in needs, in pages of +/// `MAX_HEADS_PER_PACKET` heads. The first page has the lists; the next +/// ones, asked `after` the last head of the previous one, only heads. /// -/// `[16, [[topic...], [node...], [head...], [missing...]]]` +/// `[16, [more, [topic...], [node...], [head...], [missing...]]]` #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SyncState { + /// Whether other heads follow: ask again `after` the last one here. + pub more: bool, /// The topics it takes from this peer: names, and wildcards (it takes - /// the names they match, even those it doesn't have yet). + /// the names they match, even those it doesn't have yet). Empty after + /// the first page. pub topics: Vec, /// The nodes it takes from this peer, the same way. pub nodes: Vec, - /// Its highest message id in each topic/node pair of those. + /// Its highest message id in each topic/node pair of those, in the + /// order of their names (without case), `MAX_HEADS_PER_PACKET` at + /// most. pub heads: Vec, /// The attachments it lacks among those, `MAX_MISSING_ATTACHMENTS` at - /// most. + /// most. Empty after the first page. pub missing: Vec, } impl Check for SyncState { fn check(&self) -> Result<(), DecodeError> { + rules::most(self.heads.len(), MAX_HEADS_PER_PACKET, "SyncState.heads")?; + rules::require( + !self.more || !self.heads.is_empty(), + "SyncState.heads", + "one at least when more follow", + )?; for (list, field) in [ (&self.topics, "SyncState.topics"), (&self.nodes, "SyncState.nodes"), ] { rules::most(list.len(), MAX_NAMES_LIST_ENTRIES, field)?; for item in list { - rules::require( - names::is_valid_name_or_pattern(item), - field, - "must be a name or a pattern", - )?; + rules::name_or_pattern(item, field)?; } } for head in &self.heads { diff --git a/crates/bakashrot-proto/src/packets/session.rs b/crates/bakashrot-proto/src/packets/session.rs index 4396f27..4792c74 100644 --- a/crates/bakashrot-proto/src/packets/session.rs +++ b/crates/bakashrot-proto/src/packets/session.rs @@ -74,3 +74,21 @@ impl Check for RequestRefused { pub struct Continue {} impl Check for Continue {} + +/// Keeps an idle connection open: the server answers `Pong`, and counts +/// it as a request (`IDLE_TIMEOUT_SECS`). For a client or a peer waiting +/// longer than that between requests. +/// +/// `[19, []]` +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Ping {} + +impl Check for Ping {} + +/// The answer to a `Ping`. +/// +/// `[20, []]` +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Pong {} + +impl Check for Pong {} diff --git a/crates/bakashrot-proto/tests/packets.rs b/crates/bakashrot-proto/tests/packets.rs index fcd5459..2f6cc91 100644 --- a/crates/bakashrot-proto/tests/packets.rs +++ b/crates/bakashrot-proto/tests/packets.rs @@ -2,8 +2,9 @@ //! refuses, and that no input makes it panic. use bakashrot_proto::limits::{ - ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, - MAX_TIMESTAMP, + ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_PARTS, MAX_ATTACHMENT_SIZE, MAX_HEADS_PER_PACKET, + MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_MISSING_ATTACHMENTS, MAX_NAMES_LIST_ENTRIES, + MAX_PACKET_SIZE, MAX_TIMESTAMP, }; use bakashrot_proto::packets::*; use bakashrot_proto::{Body, DecodeError, ErrorCode, Packet, PacketType}; @@ -35,6 +36,8 @@ fn samples() -> Vec { .into(), RequestRefused::new(ErrorCode::UnknownName, "Unknown topic 'nope'").into(), Continue {}.into(), + Ping {}.into(), + Pong {}.into(), PushMessage { topic: "logs".into(), data: "é€ \u{1F600} {\"a\":[1,2]}".into(), @@ -98,6 +101,14 @@ fn samples() -> Vec { AttachmentPart { data: vec![1] }.into(), ListNames { kind: NameKind::Topic, + topics: None, + nodes: None, + } + .into(), + ListNames { + kind: NameKind::Node, + topics: Some("sensors.*".into()), + nodes: Some("kitchen".into()), } .into(), NamesList { @@ -114,8 +125,16 @@ fn samples() -> Vec { json: r#"{"columns":["a"],"rows":[[1],[null]]}"#.into(), } .into(), - SyncStateRequest {}.into(), + SyncStateRequest { after: None }.into(), + SyncStateRequest { + after: Some(Pair { + topic: "logs".into(), + node: "kitchen".into(), + }), + } + .into(), SyncState { + more: true, topics: vec!["logs".into(), "sensors.*".into()], nodes: vec!["*".into()], heads: vec![ @@ -237,6 +256,8 @@ fn golden_bytes() { ] ); assert_eq!(Continue {}.encode(), [0x92, 0x03, 0x90]); + assert_eq!(Ping {}.encode(), [0x92, 0x13, 0x90]); + assert_eq!(Pong {}.encode(), [0x92, 0x14, 0x90]); assert_eq!( MessagePushed { message_id: 300 }.encode(), [0x92, 0x05, 0x91, 0xcd, 0x01, 0x2c] @@ -290,6 +311,7 @@ fn shapes() { assert!(malformed(&raw(PacketType::MessagePushed, ((),)))); assert!(malformed(&raw(PacketType::MessagePushed, (1u64, 2u64)))); assert!(malformed(&raw(PacketType::Continue, (1u64,)))); + assert!(malformed(&raw(PacketType::Ping, (1u64,)))); // The wrong types. assert!(malformed(&raw(PacketType::MessagePushed, ("1",)))); assert!(malformed(&raw(PacketType::MessagePushed, (-1i64,)))); @@ -297,8 +319,18 @@ fn shapes() { PacketType::Messages, (1u8, Vec::::new()) ))); - assert!(malformed(&raw(PacketType::ListNames, (3u8,))), "kind 3"); - assert!(malformed(&raw(PacketType::ListNames, (0u8,))), "kind 0"); + assert!( + malformed(&raw(PacketType::ListNames, (3u8, (), ()))), + "kind 3" + ); + assert!( + malformed(&raw(PacketType::ListNames, (0u8, (), ()))), + "kind 0" + ); + assert!( + malformed(&raw(PacketType::ListNames, (1u8,))), + "protocol 7's, no filters" + ); assert!( malformed(&raw( PacketType::Attachment, @@ -365,6 +397,19 @@ fn ranges() { assert!(Packet::decode(&get(Some(MAX_MESSAGE_ID), 1)).is_ok()); assert!(invalid(&get(Some(MAX_MESSAGE_ID + 1), 1))); + let list = |topics: Option<&str>, nodes: Option<&str>| { + ListNames { + kind: NameKind::Node, + topics: topics.map(Into::into), + nodes: nodes.map(Into::into), + } + .encode() + }; + assert!(Packet::decode(&list(Some("sensors.*"), Some("kitchen"))).is_ok()); + assert!(invalid(&list(Some("a b"), None))); + assert!(invalid(&list(None, Some("")))); + assert!(invalid(&list(None, Some("12")))); + let times = |pushed_at| { Messages { more: false, @@ -448,7 +493,26 @@ fn too_many_items() { }; assert!(invalid(&too_many.encode())); + let head = |n: usize| Head { + topic: "t".into(), + node: format!("n{n}"), + last_id: 1, + }; + let heads = |count: usize, more: bool| SyncState { + more, + topics: vec![], + nodes: vec![], + heads: (0..count).map(head).collect(), + missing: vec![], + }; + assert!(Packet::decode(&heads(MAX_HEADS_PER_PACKET, true).encode()).is_ok()); + assert!(invalid(&heads(MAX_HEADS_PER_PACKET + 1, false).encode())); + assert!(Packet::decode(&heads(0, false).encode()).is_ok()); + // More to come, but no head to ask after. + assert!(invalid(&heads(0, true).encode())); + let missing = SyncState { + more: false, topics: vec![], nodes: vec![], heads: vec![], @@ -501,6 +565,7 @@ fn names_everywhere() { let state = |topic: &str| { SyncState { + more: false, topics: vec![topic.into()], nodes: vec![], heads: vec![], @@ -512,6 +577,20 @@ fn names_everywhere() { assert!(Packet::decode(&state("logs")).is_ok()); assert!(invalid(&state("12"))); assert!(invalid(&state("a b*"))); + let after = |topic: &str, node: &str| { + SyncStateRequest { + after: Some(Pair { + topic: topic.into(), + node: node.into(), + }), + } + .encode() + }; + assert!(Packet::decode(&after("logs", "kitchen")).is_ok()); + assert!(invalid(&after("logs*", "kitchen"))); + assert!(invalid(&after("logs", "*"))); + assert!(invalid(&after("", "kitchen"))); + assert!(invalid(&after("logs", "12"))); let welcome = Welcome { server: "s".into(), @@ -520,6 +599,40 @@ fn names_everywhere() { assert!(invalid(&welcome.encode())); } +/// The biggest `SyncState` there can be still fits in a packet: every list +/// full, every name 64 characters, every number its largest. +#[test] +fn the_biggest_sync_state_fits() { + let name = |prefix: char, n: usize| format!("{prefix}{n:0>63}"); + let state = SyncState { + more: true, + topics: (0..MAX_NAMES_LIST_ENTRIES).map(|n| name('t', n)).collect(), + nodes: (0..MAX_NAMES_LIST_ENTRIES).map(|n| name('n', n)).collect(), + heads: (0..MAX_HEADS_PER_PACKET) + .map(|n| Head { + topic: name('t', n), + node: name('n', n), + last_id: MAX_MESSAGE_ID, + }) + .collect(), + missing: (0..MAX_MISSING_ATTACHMENTS) + .map(|n| MissingAttachment { + topic: name('t', n), + node: name('n', n), + message_id: MAX_MESSAGE_ID, + next_part: MAX_ATTACHMENT_PARTS - 1, + }) + .collect(), + }; + let bytes = state.encode(); + assert!( + bytes.len() <= MAX_PACKET_SIZE, + "{} bytes, {MAX_PACKET_SIZE} at most", + bytes.len() + ); + assert_eq!(Packet::decode(&bytes), Ok(state.into())); +} + /// xorshift64*, enough to make bytes that look like anything. struct Random(u64); @@ -541,7 +654,7 @@ fn nothing_makes_it_panic() { let mut bytes: Vec = (0..len).map(|_| random.next() as u8).collect(); if round % 2 == 0 && bytes.len() > 2 { bytes[0] = 0x92; - bytes[1] = 1 + (bytes[1] % 18); + bytes[1] = 1 + (bytes[1] % PacketType::ALL.len() as u8); bytes[2] = 0x90 | (bytes[2] & 0x0f); } let _ = Packet::decode(&bytes); diff --git a/crates/bakashrot-server/src/accept_from.rs b/crates/bakashrot-server/src/accept_from.rs index 075c81d..e758708 100644 --- a/crates/bakashrot-server/src/accept_from.rs +++ b/crates/bakashrot-server/src/accept_from.rs @@ -5,9 +5,12 @@ use crate::connection::{Frames, Peer, receive_parts, refused, send}; use crate::writer::Write; use crate::{Shared, now}; -use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_SIZE, MAX_MISSING_ATTACHMENTS}; +use bakashrot_proto::limits::{ + ATTACHMENT_PART_SIZE, MAX_HEADS_PER_PACKET, MAX_MESSAGE_SIZE, MAX_MISSING_ATTACHMENTS, +}; use bakashrot_proto::packets::{ - Attachment, Continue, MessagePushed, ReplicateAttachment, ReplicateMessages, SyncState, + Attachment, Continue, Head, MessagePushed, Pair, ReplicateAttachment, ReplicateMessages, + SyncState, SyncStateRequest, }; use bakashrot_proto::{ErrorCode, Packet}; use bakashrot_storage::AttachmentState; @@ -111,27 +114,58 @@ async fn check(shared: &Shared, peer: &mut Peer, topic: &str, node: &str) -> Res } /// What it takes from this peer, how far it is in those, and the -/// attachments it lacks among them. -pub(crate) async fn sync_state(shared: &Arc, peer: &mut Peer) -> Packet { +/// attachments it lacks among them: a page of it, the lists in the first. +pub(crate) async fn sync_state( + shared: &Arc, + peer: &mut Peer, + request: SyncStateRequest, +) -> Packet { if let Err(refusal) = check_address(shared, peer).await { return refusal; } - let (topics, nodes) = peer.permissions.accepted(); - let found = shared - .read(|reader| { - Ok(( - reader.heads()?, - reader.missing_attachments(MAX_MISSING_ATTACHMENTS)?, - )) - }) - .await; - let (mut heads, mut missing) = match found { - Ok(found) => found, - Err(refusal) => return refusal.into(), - }; - heads.retain(|head| peer.permissions.accepts(&head.topic, &head.node)); - missing.retain(|missing| peer.permissions.accepts(&missing.topic, &missing.node)); + let first = request.after.is_none(); + let mut after = request.after; + let (mut heads, mut more) = (Vec::new(), false); + // Read in pages too, those it doesn't take from this peer skipped: + // until the page is full and one more is found, or none is left. + 'pages: loop { + let from = after.take(); + let read = shared + .read(move |reader| reader.heads_after(from.as_ref(), MAX_HEADS_PER_PACKET)) + .await; + let read: Vec = match read { + Ok(read) => read, + Err(refusal) => return refusal.into(), + }; + let last_page = read.len() < MAX_HEADS_PER_PACKET; + after = read.last().map(Pair::from); + for head in read { + if peer.permissions.accepts(&head.topic, &head.node) { + if heads.len() == MAX_HEADS_PER_PACKET { + more = true; + break 'pages; + } + heads.push(head); + } + } + if last_page { + break; + } + } + let (mut topics, mut nodes, mut missing) = (Vec::new(), Vec::new(), Vec::new()); + if first { + (topics, nodes) = peer.permissions.accepted(); + missing = match shared + .read(|reader| reader.missing_attachments(MAX_MISSING_ATTACHMENTS)) + .await + { + Ok(missing) => missing, + Err(refusal) => return refusal.into(), + }; + missing.retain(|missing| peer.permissions.accepts(&missing.topic, &missing.node)); + } SyncState { + more, topics, nodes, heads, @@ -163,8 +197,8 @@ pub(crate) async fn replicate_messages( let skip_before = shared .config .retention - .age(&batch.topic) - .map_or(0, |age| now().saturating_sub(age.as_millis() as u64)); + .cutoff(&batch.topic, now()) + .unwrap_or(0); let write = Write::Replicate { topic: batch.topic, node: batch.node, diff --git a/crates/bakashrot-server/src/connection.rs b/crates/bakashrot-server/src/connection.rs index af67693..1573f1b 100644 --- a/crates/bakashrot-server/src/connection.rs +++ b/crates/bakashrot-server/src/connection.rs @@ -6,11 +6,13 @@ use crate::{Shared, accept_from, now}; use aws_lc_rs::digest; use bakashrot_config::Permissions; use bakashrot_pki::Identity; -use bakashrot_proto::limits::{MAX_MESSAGE_SIZE, MAX_NAMES_LIST_ENTRIES, MAX_PACKET_SIZE}; -use bakashrot_proto::names::names_equal; +use bakashrot_proto::limits::{ + ALPN, IDLE_TIMEOUT_SECS, MAX_MESSAGE_SIZE, MAX_NAMES_LIST_ENTRIES, MAX_PACKET_SIZE, +}; +use bakashrot_proto::names::{name_matches, names_equal}; use bakashrot_proto::packets::{ Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed, - Messages, NameKind, NamesList, PushMessage, Query, QueryResult, RequestRefused, Welcome, + Messages, NameKind, NamesList, Pong, PushMessage, Query, QueryResult, RequestRefused, Welcome, }; use bakashrot_proto::{ErrorCode, Packet, frame}; use bakashrot_storage::AttachmentState; @@ -29,8 +31,9 @@ use tracing::{debug, info}; /// How long TLS and the versions may take. const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10); -/// How long a connection may stay silent between requests. -const IDLE_TIMEOUT: Duration = Duration::from_secs(300); +/// How long a connection may stay silent between requests (a `Ping` +/// counts). +const IDLE_TIMEOUT: Duration = Duration::from_secs(IDLE_TIMEOUT_SECS); /// How long an attachment's next part may take to come. const PART_TIMEOUT: Duration = Duration::from_secs(30); @@ -106,8 +109,13 @@ async fn serve(shared: &Arc, tcp: TcpStream, address: IpAddr) -> Result< } Packet::GetMessages(get) => get_messages(shared, &peer, get).await, Packet::ListNames(list) => list_names(shared, &peer, list).await, - Packet::Query(query) => self::query(shared, &peer, query).await, - Packet::SyncStateRequest(_) => accept_from::sync_state(shared, &mut peer).await, + Packet::Query(query) => self::query(shared, &peer, &mut frames, query) + .await + .map_err(failed)?, + Packet::Ping(_) => Pong {}.into(), + Packet::SyncStateRequest(request) => { + accept_from::sync_state(shared, &mut peer, request).await + } Packet::ReplicateMessages(batch) => { accept_from::replicate_messages(shared, &mut peer, batch).await } @@ -158,6 +166,12 @@ async fn open( return Err(format!("TLS: {error}")); } }; + // rustls refuses a client offering other protocols, not one offering + // none: that one is refused here, before the versions. + if stream.get_ref().1.alpn_protocol() != Some(ALPN) { + let _ = stream.shutdown().await; + return Err("TLS: no ALPN \"bakashrot\" offered, not a BakaShrot client".into()); + } stream .write_all(&frame::version_bytes()) @@ -476,38 +490,50 @@ async fn get_messages(shared: &Arc, peer: &Peer, get: GetMessages) -> Pa } } -/// Topics: those with messages (pushed here or replicated) that it may -/// push to or read; every one with `list_topics` or `query`. Nodes: those -/// with messages in the topics it may read; every one with `list_nodes` -/// or `query`. +/// The topics or nodes of the topic and node pairs with messages (pushed +/// here or replicated, or that had some) that the filters match, among +/// those it may see. A pair's topic must be one it may see when the answer +/// is topics or `topics` filters them: one it may push to or read, any +/// with `list_topics` or `query`. Its node, when the answer is nodes or +/// `nodes` filters them: one in a topic it may read, any with +/// `list_nodes` or `query`. Without filters: the topics it may see, the +/// nodes it may. async fn list_names(shared: &Arc, peer: &Peer, list: ListNames) -> Packet { - let permissions = &peer.permissions; - let found = match list.kind { - NameKind::Topic => shared - .read(|reader| reader.topics()) - .await - .map(|mut topics| { - if !permissions.lists_every_topic() { - topics - .retain(|topic| permissions.can_push(topic) || permissions.can_read(topic)); - } - topics - }), - NameKind::Node if permissions.lists_every_node() => { - shared.read(|reader| reader.nodes()).await - } - NameKind::Node => shared.read(|reader| reader.heads()).await.map(|heads| { - let mut nodes: Vec = heads + let permissions = peer.permissions.clone(); + let kind = list.kind; + // A pass over every pair: on the read's thread, off the async ones. + let found = shared + .read(move |reader| { + let matches = |filter: &Option, name: &str| { + filter + .as_deref() + .is_none_or(|filter| name_matches(filter, name)) + }; + let check_topic = kind == NameKind::Topic || list.topics.is_some(); + let check_node = kind == NameKind::Node || list.nodes.is_some(); + let mut names: Vec = reader + .heads()? .into_iter() - .filter(|head| permissions.can_read(&head.topic)) - .map(|head| head.node) + .filter(|head| { + matches(&list.topics, &head.topic) + && matches(&list.nodes, &head.node) + && (!check_topic || permissions.may_list_topic(&head.topic)) + && (!check_node || permissions.may_list_nodes_of(&head.topic)) + }) + .map(|head| match kind { + NameKind::Topic => head.topic, + NameKind::Node => head.node, + }) .collect(); - // As `reader.nodes()` answers them: in order, none twice. - nodes.sort_by_cached_key(|node| node.to_ascii_lowercase()); - nodes.dedup_by(|a, b| names_equal(a, b)); - nodes - }), - }; + // In order, none twice (names are without case). + names.sort_unstable_by(|a, b| { + let a = a.bytes().map(|c| c.to_ascii_lowercase()); + a.cmp(b.bytes().map(|c| c.to_ascii_lowercase())) + }); + names.dedup_by(|a, b| names_equal(a, b)); + Ok(names) + }) + .await; let mut names = match found { Ok(names) => names, Err(refused) => return refused.into(), @@ -515,23 +541,34 @@ async fn list_names(shared: &Arc, peer: &Peer, list: ListNames) -> Packe let truncated = names.len() > MAX_NAMES_LIST_ENTRIES; names.truncate(MAX_NAMES_LIST_ENTRIES); NamesList { - kind: list.kind, + kind, truncated, names, } .into() } -async fn query(shared: &Arc, peer: &Peer, query: Query) -> Packet { +/// A query's answer. Nothing comes while it runs: what does (the client +/// closing, having given up) stops it and closes the connection. +async fn query( + shared: &Arc, + peer: &Peer, + frames: &mut Frames, + query: Query, +) -> Result { if !peer.permissions.can_query() { - return refused( + return Ok(refused( ErrorCode::NotAllowed, format!("{} may not run queries", peer.node), - ); + )); } - match shared.query(query.sql).await { - Ok(json) => QueryResult { json }.into(), - Err(refused) => refused.into(), + tokio::select! { + answer = shared.query(query.sql) => Ok(match answer { + Ok(json) => QueryResult { json }.into(), + Err(refused) => refused.into(), + }), + // Dropping the query stops it. + _ = frames.next() => Err("left while its query ran: stopped".into()), } } diff --git a/crates/bakashrot-server/src/lib.rs b/crates/bakashrot-server/src/lib.rs index fb44f99..12a99ad 100644 --- a/crates/bakashrot-server/src/lib.rs +++ b/crates/bakashrot-server/src/lib.rs @@ -27,12 +27,13 @@ use bakashrot_config::Config; use bakashrot_pki::{Revocations, SharedRevocations, summarize, tls}; use bakashrot_proto::ErrorCode; use bakashrot_proto::packets::RequestRefused; -use bakashrot_storage::{Database, QueryRunner, Reader}; +use bakashrot_storage::{Database, QueryRunner, Reader, Stop}; use std::collections::HashSet; use std::net::SocketAddr; use std::path::Path; -use std::sync::{Arc, Mutex}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use tokio::net::TcpListener; use tokio_rustls::{TlsAcceptor, TlsConnector}; use tracing::{info, warn}; @@ -44,6 +45,12 @@ const CRL_POLL: Duration = Duration::from_secs(5); /// How often the WAL is checkpointed. const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(1); +/// How long an idle database connection is kept before it's closed. +const POOL_IDLE: Duration = Duration::from_secs(60); + +/// How often the idle database connections are looked at. +const POOL_SWEEP: Duration = Duration::from_secs(10); + /// A server, ready to take connections. #[derive(Clone)] pub struct Server { @@ -64,9 +71,11 @@ struct Shared { database: Database, pushes: Pushes, /// Read connections not in use. - readers: Mutex>, + readers: Pool, /// Query connections not in use. - queries: Mutex>, + queries: Pool, + /// Clients' queries running now. + queries_running: AtomicUsize, /// The replicated attachments being received (topic, node, message /// id): one peer at a time each (`accept_from.rs`). receiving: Mutex>, @@ -101,21 +110,22 @@ impl Server { let pushes = Pushes::start(database.writer().map_err(|error| error.to_string())?) .map_err(|error| format!("the writer's thread: {error}"))?; start_checkpoints(&database)?; - Ok(Server { - shared: Arc::new(Shared { - name, - acceptor: TlsAcceptor::from(tls), - connector: TlsConnector::from(dialing), - revocations, - ca, - database, - pushes, - readers: Mutex::new(Vec::new()), - queries: Mutex::new(Vec::new()), - receiving: Mutex::new(HashSet::new()), - config, - }), - }) + let shared = Arc::new(Shared { + name, + acceptor: TlsAcceptor::from(tls), + connector: TlsConnector::from(dialing), + revocations, + ca, + database, + pushes, + readers: Pool::new(), + queries: Pool::new(), + queries_running: AtomicUsize::new(0), + receiving: Mutex::new(HashSet::new()), + config, + }); + start_pool_sweeps(&shared)?; + Ok(Server { shared }) } /// The server's name: its certificate's. @@ -179,6 +189,13 @@ impl Server { self.shared.pushes.stop().await; } + /// How many clients' queries are running now: each until it's + /// answered, stopped past `query_time_limit`, or stopped as its client + /// leaves. + pub fn queries_running(&self) -> usize { + self.shared.queries_running.load(Ordering::Relaxed) + } + /// Reloads the CRL file now: how many certificates it revokes. pub fn reload_revocations(&self) -> Result { let shared = &self.shared; @@ -220,35 +237,42 @@ impl Shared { Ok(sha256) } - /// Runs a client's SQL on a query connection, off the async threads. + /// Runs a client's SQL on a query connection, off the async threads: + /// stopped past `query_time_limit`, or once this future is dropped + /// (its client left), not left running on its thread. async fn query(self: &Arc, sql: String) -> Result { + let stop = Stop::new(); + let _stop_if_dropped = StopOnDrop(stop.clone()); + let limit = self.config.server.query_time_limit; + let shared = self.clone(); self.pooled( |shared| &shared.queries, Database::query_runner, - move |runner: &QueryRunner| runner.run(&sql), + move |runner: &QueryRunner| { + let _running = Counted::new(&shared.queries_running); + runner.run_limited(&sql, limit, &stop) + }, ) .await } /// Runs `work` on an idle connection of `pool`, or a new one, then - /// puts it back. + /// puts it back (closed if the pool has enough idle ones already). async fn pooled( self: &Arc, - pool: fn(&Shared) -> &Mutex>, + pool: fn(&Shared) -> &Pool, open: fn(&Database) -> bakashrot_storage::Result, work: impl FnOnce(&C) -> bakashrot_storage::Result + Send + 'static, ) -> Result { let shared = self.clone(); tokio::task::spawn_blocking(move || { - let idle = pool(&shared).lock().ok().and_then(|mut idle| idle.pop()); - let connection = match idle { + let connection = match pool(&shared).take() { Some(connection) => connection, None => open(&shared.database).map_err(refusal)?, }; let value = work(&connection).map_err(refusal); - if let Ok(mut idle) = pool(&shared).lock() { - idle.push(connection); - } + let max = shared.config.server.idle_database_connections; + pool(&shared).put_back(connection, max, Instant::now()); value }) .await @@ -256,6 +280,103 @@ impl Shared { } } +/// Stops a query when dropped: answered by then, or its client gone. +struct StopOnDrop(Stop); + +impl Drop for StopOnDrop { + fn drop(&mut self) { + self.0.stop(); + } +} + +/// Counts one in its counter while it lives (a panic included). +struct Counted<'a>(&'a AtomicUsize); + +impl<'a> Counted<'a> { + fn new(counter: &'a AtomicUsize) -> Counted<'a> { + counter.fetch_add(1, Ordering::Relaxed); + Counted(counter) + } +} + +impl Drop for Counted<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::Relaxed); + } +} + +/// Database connections not in use, each with when it was put back: the +/// last one put back is taken first, so the others age out. +struct Pool { + idle: Mutex>, +} + +impl Pool { + fn new() -> Self { + Pool { + idle: Mutex::new(Vec::new()), + } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Vec<(C, Instant)>> { + self.idle.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// The idle connection used last, if any. + fn take(&self) -> Option { + self.lock().pop().map(|(connection, _)| connection) + } + + /// Keeps `connection` for later, unused since `now`, unless `max` are + /// kept already: then it's closed (outside the lock). + fn put_back(&self, connection: C, max: usize, now: Instant) { + let mut idle = self.lock(); + if idle.len() < max { + idle.push((connection, now)); + } else { + drop(idle); + drop(connection); + } + } + + /// Closes the connections unused for `idle_for` or more at `now`. + fn sweep(&self, now: Instant, idle_for: Duration) { + let stale: Vec<(C, Instant)> = self + .lock() + .extract_if(.., |(_, since)| { + now.saturating_duration_since(*since) >= idle_for + }) + .collect(); + drop(stale); + } + + #[cfg(test)] + fn len(&self) -> usize { + self.lock().len() + } +} + +/// Closes the pools' connections unused for [`POOL_IDLE`], looked at every +/// [`POOL_SWEEP`] on a thread of its own, until the server is dropped. +fn start_pool_sweeps(shared: &Arc) -> Result<(), String> { + let shared = Arc::downgrade(shared); + std::thread::Builder::new() + .name("pool sweeps".into()) + .spawn(move || { + loop { + std::thread::sleep(POOL_SWEEP); + let Some(shared) = shared.upgrade() else { + return; + }; + let now = Instant::now(); + shared.readers.sweep(now, POOL_IDLE); + shared.queries.sweep(now, POOL_IDLE); + } + }) + .map(|_| ()) + .map_err(|error| format!("the pool sweeps' thread: {error}")) +} + /// Checkpoints the WAL every second, on a thread and a connection of its /// own, so the writer doesn't do it in the middle of a commit (2.5 times /// the pushes: `docs/storage.md`, "The benchmark"). @@ -284,7 +405,8 @@ fn refusal(error: bakashrot_storage::Error) -> RequestRefused { Error::UnknownName(_) => ErrorCode::UnknownName, Error::TooBig(_) => ErrorCode::TooBig, Error::Query(_) => ErrorCode::QueryFailed, - Error::Sqlite(_) | Error::Unusable(_) => { + Error::QueryTimedOut(_) => ErrorCode::QueryTimedOut, + Error::Sqlite(_) | Error::Unusable(_) | Error::RolledBack => { warn!("the database: {error}"); return server_error("the database failed"); } @@ -339,6 +461,27 @@ fn stamp(path: &Path) -> Option<(SystemTime, u64)> { mod tests { use super::*; + #[test] + fn pools_keep_few_and_close_the_idle() { + let pool = Pool::new(); + let start = Instant::now(); + // Three back at once, two kept at most: the third closed. + for connection in [1, 2, 3] { + pool.put_back(connection, 2, start); + } + assert_eq!(pool.len(), 2); + // The last one put back is taken first. + assert_eq!(pool.take(), Some(2)); + pool.put_back(2, 2, start + Duration::from_secs(30)); + // At 60 s, the one idle since the start goes, not the other. + pool.sweep(start + POOL_IDLE, POOL_IDLE); + assert_eq!(pool.take(), Some(2)); + assert_eq!(pool.take(), None); + // None kept at all. + pool.put_back(4, 0, start); + assert_eq!(pool.len(), 0); + } + #[test] fn a_clock_before_1970_is_refused() { assert!(check_clock(UNIX_EPOCH).is_ok()); diff --git a/crates/bakashrot-server/src/push_to.rs b/crates/bakashrot-server/src/push_to.rs index 7fdc644..6b09218 100644 --- a/crates/bakashrot-server/src/push_to.rs +++ b/crates/bakashrot-server/src/push_to.rs @@ -5,22 +5,26 @@ //! attachments it lacks; again at once if it sent any (it keeps up under //! load), after `sync_interval` otherwise. Only what the other server's roles' //! `send_*` allow. `accept_from.rs` is the other end. +//! +//! What it may send but the other server doesn't take (not in its roles' +//! `accept_*` there) is skipped, and warned about once per link, again +//! only when that changes. use crate::Shared; use crate::connection::SEND_TIMEOUT; use crate::writer::Write; use bakashrot_config::Permissions; use bakashrot_pki::tls; -use bakashrot_proto::limits::{ALPN, MAX_PACKET_SIZE}; -use bakashrot_proto::names::{names_equal, pattern_matches}; +use bakashrot_proto::limits::{ALPN, KEEPALIVE_SECS, MAX_PACKET_SIZE}; +use bakashrot_proto::names::name_matches; use bakashrot_proto::packets::{ - Attachment, AttachmentPart, MissingAttachment, ReplicateAttachment, ReplicateMessages, - SyncState, SyncStateRequest, + Attachment, AttachmentPart, Head, MissingAttachment, Pair, Ping, ReplicateAttachment, + ReplicateMessages, RequestRefused, SyncState, SyncStateRequest, }; use bakashrot_proto::{ErrorCode, Packet, frame}; use bakashrot_storage::AttachmentState; use futures_util::{SinkExt, StreamExt}; -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; use std::time::Duration; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -48,20 +52,33 @@ pub(crate) async fn run(shared: Arc) { } /// Links to `address`, checks in until the link fails, then again after -/// `retry_delay`. A failure is logged once until it changes. +/// `retry_delay`. A failure is logged once until it changes, and so is +/// what the other server doesn't take (across links too). async fn keep_linked(shared: Arc, address: String) { let replication = &shared.config.replication; let mut last_failure = String::new(); + let mut not_taken = BTreeSet::new(); loop { let failure = match Link::open(&shared, &address).await { Ok(mut link) => { info!("{address}: linked to {}", link.name); last_failure.clear(); loop { - match link.check_in(&shared).await { - Ok(true) => {} - Ok(false) => sleep(replication.sync_interval).await, - Err(why) => break format!("{} ({address}): {why}", link.name), + let checked = match link.check_in(&shared).await { + Ok(sent) => { + if link.not_taken != not_taken { + not_taken = link.not_taken.clone(); + log_not_taken(&format!("{} ({address})", link.name), ¬_taken); + } + match sent { + true => Ok(()), + false => link.wait(replication.sync_interval).await, + } + } + Err(why) => Err(why), + }; + if let Err(why) = checked { + break format!("{} ({address}): {why}", link.name); } } } @@ -82,6 +99,9 @@ struct Link { permissions: Permissions, /// Whether this check-in sent something it took. sent: bool, + /// What it may be sent but doesn't take, as of this check-in: + /// "topic:node". + not_taken: BTreeSet, } impl Link { @@ -127,6 +147,7 @@ impl Link { name: identity.name, permissions, sent: false, + not_taken: BTreeSet::new(), }; match link.receive().await? { Packet::Welcome(_) => Ok(link), @@ -139,28 +160,21 @@ impl Link { /// Whether it sent something it took. async fn check_in(&mut self, shared: &Arc) -> Result { self.sent = false; - let state = match self.ask(SyncStateRequest {}.into()).await? { - Packet::SyncState(state) => state, - Packet::RequestRefused(refused) => return Err(format!("refused: {}", refused.reason)), - other => return Err(unexpected(&other)), - }; + let (state, theirs) = self.sync_state().await?; let heads = shared .read(|reader| reader.heads()) .await .map_err(|refused| refused.reason)?; - let theirs: HashMap<(String, String), u64> = state - .heads - .iter() - .map(|head| (key(&head.topic, &head.node), head.last_id)) - .collect(); - for head in heads { - let (topic, node) = (head.topic, head.node); - if !self.sends(&state, &topic, &node) { - continue; - } - let after = theirs.get(&key(&topic, &node)).copied().unwrap_or(0); + let (to_send, not_taken) = sort_heads(&self.permissions, &state, heads); + self.not_taken = not_taken; + for head in to_send { + let after = theirs + .get(&key(&head.topic, &head.node)) + .copied() + .unwrap_or(0); if after < head.last_id { - self.send_messages(shared, topic, node, after).await?; + self.send_messages(shared, head.topic, head.node, after) + .await?; } } for missing in state.missing { @@ -171,16 +185,34 @@ impl Link { Ok(self.sent) } - /// Whether it takes `node`'s messages in `topic` (its `SyncState`) and - /// may be sent them (its roles here). - fn sends(&self, state: &SyncState, topic: &str, node: &str) -> bool { - let listed = |list: &[String], name: &str| { - list.iter() - .any(|entry| names_equal(entry, name) || pattern_matches(entry, name)) - }; - listed(&state.topics, topic) - && listed(&state.nodes, node) - && self.permissions.sends(topic, node) + /// Its `SyncState`, every page: the first (the lists), and the last + /// id of each topic and node. + async fn sync_state(&mut self) -> Result<(SyncState, HashMap<(String, String), u64>), String> { + let mut first = self.sync_page(None).await?; + let (mut heads, mut more) = (std::mem::take(&mut first.heads), first.more); + let mut theirs = HashMap::new(); + loop { + let after = heads.last().filter(|_| more).map(Pair::from); + theirs.extend( + heads + .into_iter() + .map(|head| (key(&head.topic, &head.node), head.last_id)), + ); + let Some(after) = after else { + return Ok((first, theirs)); + }; + let page = self.sync_page(Some(after)).await?; + (heads, more) = (page.heads, page.more); + } + } + + /// A page of its `SyncState`, after the pair `after`. + async fn sync_page(&mut self, after: Option) -> Result { + match self.ask(SyncStateRequest { after }.into()).await? { + Packet::SyncState(page) => Ok(page), + Packet::RequestRefused(refused) => Err(format!("refused: {}", refused.reason)), + other => Err(unexpected(&other)), + } } /// A topic and node's messages after `after`, in batches. A refusal @@ -292,6 +324,24 @@ impl Link { Ok(()) } + /// Waits `duration` before the next check-in, with a `Ping` every + /// `KEEPALIVE_SECS` meanwhile: the other server closes a link silent + /// for `IDLE_TIMEOUT_SECS`. + async fn wait(&mut self, duration: Duration) -> Result<(), String> { + let keepalive = Duration::from_secs(KEEPALIVE_SECS); + let mut left = duration; + while left > keepalive { + sleep(keepalive).await; + left -= keepalive; + match self.ask(Ping {}.into()).await? { + Packet::Pong(_) => {} + other => return Err(unexpected(&other)), + } + } + sleep(left).await; + Ok(()) + } + async fn ask(&mut self, packet: Packet) -> Result { self.send(packet).await?; self.receive().await @@ -326,11 +376,20 @@ async fn check_own_copy( attachment: &Attachment, message: &str, ) { - let read = shared.hash_parts(attachment_id, 0..attachment.part_count()); - if let Ok(sha256) = read.await - && sha256.finish().as_ref() == attachment.sha256 - { - return; + let read = shared + .hash_parts(attachment_id, 0..attachment.part_count()) + .await + .map(|sha256| sha256.finish().as_ref() == attachment.sha256); + match judge(read) { + OwnCopy::Intact => return, + OwnCopy::Damaged => {} + OwnCopy::Unknown(why) => { + warn!( + "{message}: this server's copy of its attachment couldn't be read back ({why}): \ + kept, checked again when a peer refuses it again" + ); + return; + } } let damaged = Write::Damaged { attachment: attachment_id as u64, @@ -343,6 +402,80 @@ async fn check_own_copy( } } +/// What reading back this server's copy of an attachment says about it. +#[derive(Debug, PartialEq, Eq)] +enum OwnCopy { + /// Read whole, matching its SHA-256. + Intact, + /// Read whole and not matching, or a part missing: dropped and asked + /// for again. + Damaged, + /// The read failed (the database busy, a connection not opened...), + /// saying why: nothing is known, the copy is kept. Dropping it then + /// could lose the only one there is (this server the attachment's + /// origin). + Unknown(String), +} + +/// The verdict on a read-back: whether its SHA-256 matched, or why it +/// failed. +fn judge(read: Result) -> OwnCopy { + match read { + Ok(true) => OwnCopy::Intact, + Ok(false) => OwnCopy::Damaged, + Err(refused) if refused.code == ErrorCode::NotFound.code() => OwnCopy::Damaged, + Err(refused) => OwnCopy::Unknown(refused.reason), + } +} + +/// This server's heads that the other server may be sent (its roles +/// here, `permissions`) and takes (its `SyncState`'s lists); and the names +/// of those it may be sent but doesn't take, "topic:node". +fn sort_heads( + permissions: &Permissions, + state: &SyncState, + heads: Vec, +) -> (Vec, BTreeSet) { + let listed = |list: &[String], name: &str| list.iter().any(|entry| name_matches(entry, name)); + let mut not_taken = BTreeSet::new(); + let to_send = heads + .into_iter() + .filter(|head| permissions.sends(&head.topic, &head.node)) + .filter(|head| { + let taken = listed(&state.topics, &head.topic) && listed(&state.nodes, &head.node); + if !taken { + not_taken.insert(format!("{}:{}", head.topic, head.node)); + } + taken + }) + .collect(); + (to_send, not_taken) +} + +/// Logs what `peer` doesn't take of what it may be sent, now that it +/// changed: a warning, or that it takes it all again. +fn log_not_taken(peer: &str, not_taken: &BTreeSet) { + match not_taken.is_empty() { + true => info!("{peer}: takes everything this server may send it now"), + false => warn!( + "{peer}: doesn't take {}, which this server may send it (not in its roles' \ + accept_topics and accept_nodes there): skipped", + some_names(not_taken) + ), + } +} + +/// The first few names, then how many more. +fn some_names(names: &BTreeSet) -> String { + const SHOWN: usize = 10; + let shown: Vec<&str> = names.iter().take(SHOWN).map(String::as_str).collect(); + let mut text = shown.join(", "); + if names.len() > SHOWN { + text += &format!(" and {} more", names.len() - SHOWN); + } + text +} + /// A topic and node, to compare without case. fn key(topic: &str, node: &str) -> (String, String) { (topic.to_ascii_lowercase(), node.to_ascii_lowercase()) @@ -351,3 +484,76 @@ fn key(topic: &str, node: &str) -> (String, String) { fn unexpected(packet: &Packet) -> String { format!("answered {}", packet.packet_type().name()) } + +#[cfg(test)] +mod tests { + use super::*; + use bakashrot_config::Config; + + #[test] + fn heads_sent_and_not_taken() { + let config = Config::parse( + r#" +[server] +listen = "127.0.0.1:7000" +ca = "ca.crt" +certificate = "server.crt" +key = "server.key" + +[roles.peer] +send_topics = ["logs", "secret"] +send_nodes = ["kitchen", "garage"] +"#, + ) + .unwrap(); + let permissions = config.permissions(&["peer"]).unwrap(); + // It takes logs and metrics, from kitchen and lounge. + let state = SyncState { + more: false, + topics: vec!["logs".into(), "met*".into()], + nodes: vec!["kitchen".into(), "lounge".into()], + heads: Vec::new(), + missing: Vec::new(), + }; + let head = |topic: &str, node: &str| Head { + topic: topic.into(), + node: node.into(), + last_id: 1, + }; + let heads = vec![ + head("logs", "kitchen"), // sent + head("logs", "garage"), // may be sent, its node not taken + head("secret", "kitchen"), // may be sent, its topic not taken + head("metrics", "kitchen"), // taken, not sent from here: not said + head("logs", "lounge"), // the same + ]; + let (to_send, not_taken) = sort_heads(&permissions, &state, heads); + assert_eq!(to_send, vec![head("logs", "kitchen")]); + assert_eq!( + not_taken.into_iter().collect::>(), + ["logs:garage", "secret:kitchen"] + ); + + let names: BTreeSet = (0..12).map(|n| format!("t{n:02}:n")).collect(); + let some = some_names(&names); + assert!(some.starts_with("t00:n, t01:n,"), "{some}"); + assert!(some.ends_with("t09:n and 2 more"), "{some}"); + assert_eq!( + some_names(&names.into_iter().take(2).collect()), + "t00:n, t01:n" + ); + } + + #[test] + fn only_a_copy_read_whole_or_missing_a_part_is_damaged() { + let refused = |code| Err(RequestRefused::new(code, "why")); + let unknown = || OwnCopy::Unknown("why".into()); + assert_eq!(judge(Ok(true)), OwnCopy::Intact); + assert_eq!(judge(Ok(false)), OwnCopy::Damaged); + // A part missing (read_part's NotFound): damaged too. + assert_eq!(judge(refused(ErrorCode::NotFound)), OwnCopy::Damaged); + // A read that failed says nothing about the copy: kept, saying why. + assert_eq!(judge(refused(ErrorCode::ServerError)), unknown()); + assert_eq!(judge(refused(ErrorCode::InvalidRequest)), unknown()); + } +} diff --git a/crates/bakashrot-server/src/retention.rs b/crates/bakashrot-server/src/retention.rs index da1833a..542ef30 100644 --- a/crates/bakashrot-server/src/retention.rs +++ b/crates/bakashrot-server/src/retention.rs @@ -31,10 +31,9 @@ pub(crate) async fn run(shared: &Arc) { async fn once(shared: &Arc) -> Result<(), RequestRefused> { let now = crate::now(); for topic in shared.read(|reader| reader.topics()).await? { - let Some(age) = shared.config.retention.age(&topic) else { + let Some(cutoff) = shared.config.retention.cutoff(&topic, now) else { continue; }; - let cutoff = now.saturating_sub(age.as_millis() as u64); let deleted = repeat(shared, MESSAGES_PER_WRITE, |limit| Write::DeleteBefore { topic: topic.clone(), cutoff, diff --git a/crates/bakashrot-server/src/writer.rs b/crates/bakashrot-server/src/writer.rs index 2ec3b4d..3d70d22 100644 --- a/crates/bakashrot-server/src/writer.rs +++ b/crates/bakashrot-server/src/writer.rs @@ -195,6 +195,8 @@ fn write(writer: &mut Writer, group: Vec<(Write, oneshot::Sender)>) { } let mut outcomes = Vec::with_capacity(group.len()); let committed = writer.batch(|batch| { + // SQLite rolling the group back (a full disk...) fails the batch: + // every write in it is refused below, none stored. for (write, _) in &group { outcomes.push(write.run(batch).map_err(refusal)); } diff --git a/crates/bakashrot-server/tests/end_to_end.rs b/crates/bakashrot-server/tests/end_to_end.rs index b89046c..6fc8a55 100644 --- a/crates/bakashrot-server/tests/end_to_end.rs +++ b/crates/bakashrot-server/tests/end_to_end.rs @@ -6,11 +6,13 @@ use bakashrot_client::{Client, Settings}; use bakashrot_config::Config; use bakashrot_pki::{Ca, Identity, Issued, Revocations, Usage, summarize, tls}; -use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_SIZE, MAX_PACKET_SIZE}; +use bakashrot_proto::limits::{ + ATTACHMENT_PART_SIZE, MAX_HEADS_PER_PACKET, MAX_MESSAGE_SIZE, MAX_PACKET_SIZE, +}; use bakashrot_proto::packets::{ - Attachment, AttachmentPart, GetAttachment, MessagePushed, Messages, NameKind, PushMessage, - ReplicateAttachment, ReplicateMessages, ReplicatedMessage, StoredAttachment, SyncState, - SyncStateRequest, + Attachment, AttachmentPart, GetAttachment, Head, MessagePushed, Messages, NameKind, Pair, Ping, + Pong, PushMessage, ReplicateAttachment, ReplicateMessages, ReplicatedMessage, StoredAttachment, + SyncState, SyncStateRequest, }; use bakashrot_proto::{ErrorCode, Packet, frame}; use bakashrot_server::Server; @@ -18,8 +20,9 @@ use std::io::{Cursor, Read, Seek, SeekFrom, Write}; use std::net::TcpStream; use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, Once, PoisonError}; use std::time::{Duration, Instant}; -use tokio_rustls::rustls::{ClientConnection, StreamOwned}; +use tokio_rustls::rustls::{ClientConfig, ClientConnection, StreamOwned}; const CONFIG: &str = r#" [server] @@ -219,6 +222,103 @@ fn push_and_read_back() { ); } +/// A ping is answered, needs no permission, and the connection goes on; +/// a revoked certificate's ping drops it, as any request. +#[test] +fn pings() { + let running = Running::start("pings"); + // No role allows anything here but being known. + let nobody = running.issue("idle", &["explorer"]); + let mut client = running.connect(&nobody).unwrap(); + client.ping().unwrap(); + client.ping().unwrap(); + assert!(client.list_names(NameKind::Topic, None, None).is_ok()); + + let mut raw = Raw::connect(&running, &nobody); + raw.send(Ping {}); + assert!(matches!(raw.receive(), Some(Packet::Pong(_)))); + // An answer, not a request: the server closes. + raw.send(Pong {}); + assert!(raw.receive().is_none()); + + let serial = summarize(&nobody.certificate).unwrap().serial; + let crl = running.ca.revocation_list(&[serial], 30).unwrap(); + std::fs::write(running.folder.join("ca.crl"), crl).unwrap(); + running.server.reload_revocations().unwrap(); + let error = client.ping().unwrap_err(); + assert_eq!(error.code(), ErrorCode::ConnectionLost.code(), "{error}"); +} + +/// No idle database connection kept: each read and query opens its own. +#[test] +fn no_idle_database_connections() { + let running = Running::start_with("no-idle", "idle_database_connections = 0\n"); + let mut client = running + .connect(&running.issue("kitchen", &["sensor", "reader", "analyst"])) + .unwrap(); + for n in 1..=3 { + assert_eq!(client.push("logs", &format!("{{\"n\":{n}}}")).unwrap(), n); + let latest = client.get_messages("logs", "kitchen", None, 1).unwrap(); + assert_eq!(latest.messages[0].id, n); + } + let json = client.query("SELECT count(*) AS n FROM messages").unwrap(); + assert_eq!(json, r#"{"columns":["n"],"rows":[["3"]]}"#); +} + +/// A query that never ends. +const FOREVER: &str = + "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n"; + +/// Past `query_time_limit`, a query is stopped and refused, the connection +/// kept; a client giving up first (its answer timeout) closes, and its +/// query is stopped then. +#[test] +fn queries_are_stopped() { + let running = Running::start_with("query-time-limit", "query_time_limit = \"1s\"\n"); + let analyst = running.issue("analyst-1", &["analyst"]); + let mut client = running.connect(&analyst).unwrap(); + let started = Instant::now(); + let error = client.query(FOREVER).unwrap_err(); + let took = started.elapsed(); + assert_eq!(error.code(), ErrorCode::QueryTimedOut.code(), "{error}"); + assert!( + error + .message() + .contains("stopped after 1s, the server's time limit"), + "{error}" + ); + assert!( + took >= Duration::from_secs(1) && took < Duration::from_secs(5), + "{took:?}" + ); + assert_eq!(running.server.queries_running(), 0); + assert_eq!( + client.query("SELECT 1 AS one").unwrap(), + r#"{"columns":["one"],"rows":[["1"]]}"# + ); + + // The client gives up long before the server's limit. + let running = Running::start_with("query-left", "query_time_limit = \"1h\"\n"); + let mut client = running + .connect(&running.issue("analyst-1", &["analyst"])) + .unwrap(); + client + .set_answer_timeout(Duration::from_millis(300)) + .unwrap(); + let error = client.query(FOREVER).unwrap_err(); + assert_eq!(code(error), ErrorCode::ConnectionLost.code()); + assert!(client.is_closed()); + wait_for("its query stopped", || { + running.server.queries_running() == 0 + }); + // Its connection is closed; the next one is answered. + let mut client = running + .connect(&running.issue("analyst-2", &["analyst"])) + .unwrap(); + assert!(client.query("SELECT 1").is_ok()); + assert_eq!(running.server.queries_running(), 0); +} + #[test] fn refusals_keep_the_connection() { let running = Running::start("refusals"); @@ -298,6 +398,20 @@ fn certificates_refused() { .unwrap_err(); assert_eq!(error.code(), ErrorCode::ServerNotVerified.code(), "{error}"); + // A client of the CA offering no ALPN: TLS goes through (rustls only + // refuses other protocols), then the server closes before its version. + let kitchen = running.issue("kitchen", &["sensor"]); + let mut silent = Raw::open(&running, &kitchen, |config| config.alpn_protocols.clear()); + frame::write_version(&mut silent.0).unwrap(); + let _ = silent.0.flush(); + assert!(frame::read_version(&mut silent.0).is_err()); + // Offering it, the same client gets in. + let mut offering = Raw::open(&running, &kitchen, |_| {}); + frame::write_version(&mut offering.0).unwrap(); + offering.0.flush().unwrap(); + frame::read_version(&mut offering.0).unwrap(); + assert!(matches!(offering.receive(), Some(Packet::Welcome(_)))); + // Nothing listening. let error = Client::connect( "127.0.0.1:1", @@ -329,6 +443,10 @@ fn revoked_certificates_are_dropped() { // Its open connection goes at its next request, a new one is refused. let error = connected.push("logs", "{}").unwrap_err(); assert_eq!(error.code(), ErrorCode::ConnectionLost.code(), "{error}"); + // Closed by the client too: the next one isn't even sent. + let error = connected.push("logs", "{}").unwrap_err(); + assert_eq!(error.code(), ErrorCode::NotConnected.code(), "{error}"); + assert!(!connected.is_open()); let error = running.connect(&kitchen).unwrap_err(); assert_eq!(error.code(), ErrorCode::AuthRejected.code(), "{error}"); // Others go on. @@ -596,12 +714,13 @@ fn names() { .connect(&running.issue("analyst-1", &["analyst"])) .unwrap(); - let names = |client: &mut Client, kind| { - let list = client.list_names(kind).unwrap(); + let filtered = |client: &mut Client, kind, topics, nodes| { + let list = client.list_names(kind, topics, nodes).unwrap(); assert_eq!(list.kind, kind); assert!(!list.truncated); list.names }; + let names = |client: &mut Client, kind| filtered(client, kind, None, None); // Topics: those it may push to or read; every one for a query role. assert_eq!(names(&mut sensor, NameKind::Topic), ["logs", "sensors"]); assert_eq!(names(&mut screen, NameKind::Topic), ["logs"]); @@ -624,6 +743,55 @@ fn names() { ), ErrorCode::NotAllowed.code() ); + + // Filtered: the topics a node pushed to, the nodes that pushed to a + // topic; names (without case) or patterns. + sensor.push("sensors", "{}").unwrap(); + let (topic, node) = (NameKind::Topic, NameKind::Node); + let every = &mut analyst; + assert_eq!( + filtered(every, topic, None, Some("kitchen")), + ["logs", "sensors"] + ); + assert_eq!( + filtered(every, topic, None, Some("KITCHEN")), + ["logs", "sensors"] + ); + assert_eq!(filtered(every, topic, None, Some("g*")), ["sensors"]); + assert!(filtered(every, topic, None, Some("nobody")).is_empty()); + assert_eq!( + filtered(every, node, Some("sensors"), None), + ["garage", "kitchen"] + ); + assert_eq!(filtered(every, node, Some("l?gs"), None), ["kitchen"]); + assert_eq!(filtered(every, node, Some("*"), Some("k*")), ["kitchen"]); + assert_eq!( + filtered(every, topic, Some("s*"), Some("kitchen")), + ["sensors"] + ); + // Only what it may see: the nodes of the topics it may read... + assert_eq!( + filtered(&mut screen, topic, None, Some("kitchen")), + ["logs"] + ); + assert!(filtered(&mut screen, topic, None, Some("garage")).is_empty()); + assert_eq!(filtered(&mut screen, node, Some("*"), None), ["kitchen"]); + // ...not of those it may only push to, the topics of those it may. + assert!(filtered(&mut sensor, topic, None, Some("garage")).is_empty()); + assert_eq!(filtered(&mut sensor, topic, Some("s*"), None), ["sensors"]); + assert_eq!( + filtered(&mut explorer, topic, None, Some("garage")), + ["sensors"] + ); + assert_eq!( + filtered(&mut explorer, node, Some("logs"), None), + ["kitchen"] + ); + // Neither a name nor a pattern: refused before it's sent. + let error = analyst + .list_names(NameKind::Node, Some("a b"), None) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::InvalidArgument.code(), "{error}"); } /// Queries: allowed or not, results, refusals. @@ -872,17 +1040,7 @@ struct Raw(StreamOwned); impl Raw { fn connect(running: &Running, issued: &Issued) -> Raw { - let config = tls::client_config( - &running.ca_certificate, - &issued.certificate, - &issued.key, - Revocations::none().shared(), - ) - .unwrap(); - let tcp = TcpStream::connect(&running.address).unwrap(); - tcp.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); - let connection = ClientConnection::new(config, tls::server_name()).unwrap(); - let mut raw = Raw(StreamOwned::new(connection, tcp)); + let mut raw = Raw::open(running, issued, |_| {}); frame::write_version(&mut raw.0).unwrap(); raw.0.flush().unwrap(); frame::read_version(&mut raw.0).unwrap(); @@ -890,6 +1048,24 @@ impl Raw { raw } + /// TLS only, its client config changed by `change` first: the + /// versions and the welcome are the caller's. + fn open(running: &Running, issued: &Issued, change: impl FnOnce(&mut ClientConfig)) -> Raw { + let mut config = (*tls::client_config( + &running.ca_certificate, + &issued.certificate, + &issued.key, + Revocations::none().shared(), + ) + .unwrap()) + .clone(); + change(&mut config); + let tcp = TcpStream::connect(&running.address).unwrap(); + tcp.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let connection = ClientConnection::new(Arc::new(config), tls::server_name()).unwrap(); + Raw(StreamOwned::new(connection, tcp)) + } + fn send(&mut self, packet: impl Into) { frame::write(&mut self.0, &packet.into().encode()).unwrap(); self.0.flush().unwrap(); @@ -980,7 +1156,7 @@ fn attachment_edges() { .unwrap_err(); assert_eq!(error.code(), ErrorCode::FileError.code(), "{error}"); let error = kitchen.push("logs", "{}").unwrap_err(); - assert_eq!(error.code(), ErrorCode::ConnectionLost.code(), "{error}"); + assert_eq!(error.code(), ErrorCode::NotConnected.code(), "{error}"); let started = Instant::now(); while uploads(&mut analyst) != none_left { assert!( @@ -1392,15 +1568,262 @@ fn replication() { ); } -/// A server's `SyncState`, asked over `raw`. +/// A server's `SyncState`, asked over `raw`: its first page. fn sync_state(raw: &mut Raw) -> SyncState { - raw.send(SyncStateRequest {}); + sync_page(raw, None) +} + +/// A page of a server's `SyncState`, the heads after `after`. +fn sync_page(raw: &mut Raw, after: Option) -> SyncState { + raw.send(SyncStateRequest { after }); match raw.receive() { Some(Packet::SyncState(state)) => state, other => panic!("expected a SyncState, got {other:?}"), } } +/// Adds `count` topic and node pairs to the database at `path`, topics +/// `{prefix}000001` and on, node "far", each pair's last id its number: +/// faster than pushing. +fn add_pairs(path: &std::path::Path, prefix: &str, count: usize) { + let raw = rusqlite::Connection::open(path).unwrap(); + raw.execute( + "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?2) \ + INSERT INTO streams (topic, node, last_id) \ + SELECT printf('%s%06d', ?1, i), 'far', i FROM n", + rusqlite::params![prefix, count], + ) + .unwrap(); +} + +/// Heads as (topic, node, last id), to compare. +fn triples(heads: &[Head]) -> Vec<(String, String, u64)> { + heads + .iter() + .map(|head| (head.topic.clone(), head.node.clone(), head.last_id)) + .collect() +} + +#[test] +fn sync_state_in_pages() { + const PAGE: usize = MAX_HEADS_PER_PACKET; + // "picky" takes only topics starting with "b". + let b = Running::start_with( + "pages", + "\n[replication]\naccept_from = [\"127.0.0.1\"]\n\n\ + [roles.picky]\naccept_topics = [\"b*\"]\n", + ); + // A page of "b" pairs, between 1000 "a" and 1000 "c" ones. + let database = b.folder.join("bakashrot.sqlite"); + let b = b.restart_after(|| { + add_pairs(&database, "a", 1000); + add_pairs(&database, "b", PAGE); + add_pairs(&database, "c", 1000); + }); + let mut every: Vec<(String, String, u64)> = Vec::new(); + for (prefix, count) in [("a", 1000), ("b", PAGE), ("c", 1000)] { + every.extend((1..=count as u64).map(|n| (format!("{prefix}{n:06}"), "far".into(), n))); + } + + // A peer taking everything: a full first page with the lists, then the + // rest after its last head, without them; every pair once, in order. + let mut peer = Raw::connect(&b, &b.issue("server-x", &["peer"])); + let first = sync_page(&mut peer, None); + assert!(first.more); + assert_eq!(first.heads.len(), PAGE); + assert_eq!( + (first.topics.as_slice(), first.nodes.as_slice()), + (["*".to_string()].as_slice(), ["*".to_string()].as_slice()) + ); + let second = sync_page(&mut peer, first.heads.last().map(Pair::from)); + assert!(!second.more); + assert!(second.topics.is_empty() && second.nodes.is_empty() && second.missing.is_empty()); + let mut both = triples(&first.heads); + both.extend(triples(&second.heads)); + assert_eq!(both, every); + + // The pair asked after, its names in another case: the same page. + let last = first.heads.last().unwrap(); + let shouted = Pair { + topic: last.topic.to_uppercase(), + node: last.node.to_uppercase(), + }; + assert_eq!(sync_page(&mut peer, Some(shouted)).heads, second.heads); + // A pair it doesn't have: from the next one after it. + let between = Pair { + topic: "b000005".into(), + node: "a".into(), + }; + assert_eq!( + sync_page(&mut peer, Some(between)).heads[0].topic, + "b000005" + ); + // After the very last: nothing, nothing more. + let end = sync_page(&mut peer, second.heads.last().map(Pair::from)); + assert!(end.heads.is_empty() && !end.more); + + // A peer taking only "b": the others are skipped, not counted. Exactly + // a page of its own: one page, no empty one after it. + let mut picky = Raw::connect(&b, &b.issue("server-y", &["picky"])); + let only = sync_page(&mut picky, None); + assert!(!only.more); + assert_eq!(only.topics, ["b*"]); + assert_eq!(triples(&only.heads), every[1000..1000 + PAGE]); + // One more "b" (made while it runs): two pages, the second just it. + add_pairs(&database, "bz", 1); + let first = sync_page(&mut picky, None); + assert!(first.more); + assert_eq!(first.heads.len(), PAGE); + let second = sync_page(&mut picky, first.heads.last().map(Pair::from)); + assert!(!second.more); + assert_eq!( + triples(&second.heads), + [("bz000001".into(), "far".into(), 1)] + ); + + // A pattern to ask after is malformed: the connection is dropped. + let pattern = Pair { + topic: "b*".into(), + node: "far".into(), + }; + picky.send(SyncStateRequest { + after: Some(pattern), + }); + assert_eq!(picky.receive(), None); +} + +/// The servers' log, every test's (tracing's subscriber is global): from +/// the first call on. +fn log() -> String { + static LOG: Mutex = Mutex::new(String::new()); + struct Writer; + impl Write for Writer { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + let mut log = LOG.lock().unwrap_or_else(PoisonError::into_inner); + log.push_str(&String::from_utf8_lossy(bytes)); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + static START: Once = Once::new(); + START.call_once(|| { + let _ = tracing_subscriber::fmt() + .with_writer(|| Writer) + .with_ansi(false) + .try_init(); + }); + LOG.lock().unwrap_or_else(PoisonError::into_inner).clone() +} + +/// What a peer doesn't take of what it may be sent is warned about once, +/// again when it changes, and not sent. +#[test] +fn replication_not_taken_is_warned() { + log(); + // b takes only "logs" from its peers. + let b = Running::start_with( + "not-taken-b", + "\n[replication]\naccept_from = [\"127.0.0.1\"]\n", + ); + let config = b.folder.join("server.toml"); + let b = b.restart_after(|| { + let text = std::fs::read_to_string(&config).unwrap(); + let picky = text.replacen("accept_topics = [\"*\"]", "accept_topics = [\"logs\"]", 1); + assert_ne!(text, picky); + std::fs::write(&config, picky).unwrap(); + }); + let a = b.peer( + "not-taken-a", + "server-a", + &format!( + "\n[replication]\npush_to = [\"{}\"]\nsync_interval = \"1s\"\n", + b.address + ), + ); + let mut kitchen = a.connect(&a.issue("kitchen", &["sensor"])).unwrap(); + kitchen.push("logs", "{}").unwrap(); + kitchen.push("sensors", "{}").unwrap(); + + let mut on_b = b.connect(&b.issue("watcher", &["reader"])).unwrap(); + let mut on_b_has = |topic: &str| { + on_b.get_messages(topic, "kitchen", Some(0), 10) + .map(|answer| answer.messages.len()) + .unwrap_or(0) + }; + wait_for("logs on b", || on_b_has("logs") == 1); + let warnings = |names: &str| { + let line = format!("({}): doesn't take {names}, which", b.address); + log() + .lines() + .filter(|logged| logged.contains(&line)) + .count() + }; + wait_for("the warning", || warnings("sensors:kitchen") == 1); + // Checked in again and again (every second): not warned again. + std::thread::sleep(Duration::from_millis(3500)); + assert_eq!(warnings("sensors:kitchen"), 1, "{}", log()); + assert_eq!(on_b_has("sensors"), 0); + + // Another pair it doesn't take: warned again, both named. + let mut garage = a.connect(&a.issue("garage", &["sensor"])).unwrap(); + garage.push("sensors", "{}").unwrap(); + wait_for("the new warning", || { + warnings("sensors:garage, sensors:kitchen") == 1 + }); + assert_eq!(warnings("sensors:kitchen"), 1); + assert!(!log().contains(&format!("({}): doesn't take logs", b.address))); +} + +#[test] +fn replication_across_pages() { + // b with a page and more of pairs before "logs", and kitchen's last id + // in "logs" 5 (its messages gone): that head is on the second page. + let b = Running::start_with( + "across-pages-b", + "\n[replication]\naccept_from = [\"127.0.0.1\"]\n", + ); + let database = b.folder.join("bakashrot.sqlite"); + let b = b.restart_after(|| { + add_pairs(&database, "a", MAX_HEADS_PER_PACKET + 1000); + let raw = rusqlite::Connection::open(&database).unwrap(); + raw.execute( + "INSERT INTO streams (topic, node, last_id) VALUES ('logs', 'kitchen', 5)", + [], + ) + .unwrap(); + }); + let a = b.peer( + "across-pages-a", + "server-a", + &format!( + "\n[replication]\npush_to = [\"{}\"]\nsync_interval = \"1s\"\n\ + retry_delay = \"1s\"\n", + b.address + ), + ); + let mut on_a = a.connect(&a.issue("kitchen", &["sensor"])).unwrap(); + let mut on_b = b.connect(&b.issue("watcher", &["reader"])).unwrap(); + let ids = |client: &mut Client| { + client + .get_messages("logs", "kitchen", Some(0), 10) + .map(|messages| messages.messages.iter().map(|m| m.id).collect::>()) + .unwrap_or_default() + }; + // a sends only what's after b's 5: the second page was read. (Without + // it, a would take b to be at 0 and send all 6.) + for n in 1..=6 { + on_a.push("logs", &format!("{{\"n\":{n}}}")).unwrap(); + } + wait_for("#6 on b", || ids(&mut on_b) == [6]); + on_a.push("logs", "{\"n\":7}").unwrap(); + wait_for("#7 on b", || ids(&mut on_b) == [6, 7]); + // Check-ins after that send nothing more. + std::thread::sleep(Duration::from_millis(2500)); + assert_eq!(ids(&mut on_b), [6, 7]); +} + #[test] fn replication_edges() { // The test plays the peer, over a raw connection. @@ -1549,14 +1972,20 @@ fn replication_edges() { assert_eq!(got.messages[0].data, "m1"); // (`old` had a message, past its age.) assert_eq!( - reader.list_names(NameKind::Topic).unwrap().names, + reader + .list_names(NameKind::Topic, None, None) + .unwrap() + .names, ["elsewhere", "logs", "old"] ); let mut logs_only = running .connect(&running.issue("lounge", &["logs"])) .unwrap(); assert_eq!( - logs_only.list_names(NameKind::Topic).unwrap().names, + logs_only + .list_names(NameKind::Topic, None, None) + .unwrap() + .names, ["logs"] ); assert_eq!( diff --git a/crates/bakashrot-storage/src/batch.rs b/crates/bakashrot-storage/src/batch.rs index 73d5e10..db10981 100644 --- a/crates/bakashrot-storage/src/batch.rs +++ b/crates/bakashrot-storage/src/batch.rs @@ -26,6 +26,12 @@ impl Writer { /// rolled back otherwise. Each operation of a [`Batch`] is all or /// nothing on its own, so `write` may go on after one fails: many /// pushes in one batch are a group commit, one disk flush for all. + /// + /// Unless SQLite rolled the whole transaction back by itself (it may, + /// on a full disk, an I/O error, out of memory): then every operation + /// after is refused ([`Error::RolledBack`], they'd be written outside + /// the transaction, one at a time), and so is the batch: nothing in it + /// was stored. pub fn batch(&mut self, write: impl FnOnce(&mut Batch<'_>) -> Result) -> Result { let mut batch = Batch { transaction: self @@ -33,6 +39,7 @@ impl Writer { .transaction_with_behavior(TransactionBehavior::Immediate)?, }; let value = write(&mut batch)?; + batch.check_open()?; batch.transaction.commit()?; Ok(value) } @@ -52,9 +59,24 @@ impl Batch<'_> { /// which it returns. Without a savepoint, the hot path: a push that /// fails leaves at most its topic and node's (empty) stream. pub fn push(&mut self, topic: &str, node: &str, pushed_at: u64, data: &str) -> Result { + self.check_open()?; Ok(insert_pushed(&self.transaction, topic, node, pushed_at, data)?.0) } + /// Whether SQLite rolled the transaction back by itself: nothing more + /// may run in it, every operation is refused ([`Error::RolledBack`]). + fn is_rolled_back(&self) -> bool { + self.transaction.is_autocommit() + } + + /// [`Error::RolledBack`] once rolled back. + fn check_open(&self) -> Result<()> { + match self.is_rolled_back() { + false => Ok(()), + true => Err(Error::RolledBack), + } + } + /// Stores a pushed message with its attachment, an upload all of whose /// parts came ([`Batch::write_part`] said so) and whose SHA-256 the /// caller checked: the attachment is then `ready`. @@ -302,6 +324,9 @@ impl Batch<'_> { /// Runs one operation all or nothing (a savepoint), so the batch can go /// on after it fails. fn atomic(&mut self, operation: impl FnOnce(&Connection) -> Result) -> Result { + // Outside a transaction, a savepoint would start one of its own, + // committed when released. + self.check_open()?; let savepoint = self.transaction.savepoint()?; let value = operation(&savepoint)?; savepoint.commit()?; @@ -421,3 +446,60 @@ pub(crate) fn clean_up(db: &Connection) -> Result<()> { } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + /// SQLite may roll a whole transaction back by itself (a full disk, an + /// I/O error): what came after ran outside it, each committed alone, + /// while the batch failed and every write was answered as failed. + #[test] + fn nothing_runs_once_sqlite_rolled_back() { + let connection = Connection::open_in_memory().unwrap(); + connection + .execute_batch(include_str!("schema_v9.sql")) + .unwrap(); + let mut writer = Writer::new(connection); + let outcome = writer.batch(|batch| { + assert_eq!(batch.push("logs", "kitchen", 1, "a")?, 1); + assert!(!batch.is_rolled_back()); + // What SQLite does on its own, sometimes, on those errors. + batch.transaction.execute_batch("ROLLBACK")?; + assert!(batch.is_rolled_back()); + let refused = |result: Result<_>| matches!(result, Err(Error::RolledBack)); + assert!(refused(batch.push("logs", "kitchen", 2, "b"))); + assert!(refused(batch.push("other", "garage", 3, "c"))); + assert!(refused(batch.start_upload(5, &[0; 32]).map(|_| 0))); + assert!(refused(batch.delete_before("logs", 10, 10).map(|_| 0))); + assert!(refused(batch.purge_attachments(10).map(|_| 0))); + Ok(()) + }); + assert!(matches!(outcome, Err(Error::RolledBack)), "{outcome:?}"); + let count = |writer: &Writer, table: &str| -> i64 { + writer + .connection + .query_row(&format!("SELECT count(*) FROM {table}"), [], |row| { + row.get(0) + }) + .unwrap() + }; + // Nothing stored: neither before the rollback nor after it. + assert_eq!( + ( + count(&writer, "data"), + count(&writer, "streams"), + count(&writer, "attachments") + ), + (0, 0, 0) + ); + // The next batch goes on as usual. + assert_eq!( + writer + .batch(|batch| batch.push("logs", "kitchen", 4, "d")) + .unwrap(), + 1 + ); + assert_eq!(count(&writer, "data"), 1); + } +} diff --git a/crates/bakashrot-storage/src/database.rs b/crates/bakashrot-storage/src/database.rs index 6336f8a..3dbe433 100644 --- a/crates/bakashrot-storage/src/database.rs +++ b/crates/bakashrot-storage/src/database.rs @@ -4,7 +4,7 @@ use crate::{Error, QueryRunner, Reader, Result, SCHEMA_VERSION, Writer}; use bakashrot_config::Synchronous; use rusqlite::hooks::{AuthAction, AuthContext, Authorization}; -use rusqlite::{Connection, OptionalExtension, TransactionBehavior}; +use rusqlite::{Connection, OpenFlags, OptionalExtension, TransactionBehavior}; use std::path::{Path, PathBuf}; use std::time::Duration; @@ -129,19 +129,26 @@ impl Database { Ok(Reader::new(self.connect()?)) } - /// A connection for clients' queries: read-only (`query_only`), and - /// every PRAGMA refused from then on (SQLite's authorizer). Some take - /// effect when they're prepared, before a statement can be refused - /// for what it is: `PRAGMA query_only = 0` turned `query_only` off - /// for the connection's next queries. + /// A connection for clients' queries: the file opened read-only + /// (`SQLITE_OPEN_READONLY`: the file handle can't write), `query_only`, + /// and every PRAGMA refused from then on (SQLite's authorizer). Some + /// take effect when they're prepared, before a statement can be + /// refused for what it is: `PRAGMA query_only = 0` turned + /// `query_only` off for the connection's next queries. The database is + /// in WAL mode already (the writer made it so), which a read-only + /// connection can't change and doesn't need to. pub fn query_runner(&self) -> Result { - let mut connection = self.connect()?; + let flags = OpenFlags::SQLITE_OPEN_READ_ONLY + | OpenFlags::SQLITE_OPEN_URI + | OpenFlags::SQLITE_OPEN_NO_MUTEX; + let mut connection = Connection::open_with_flags(&self.path, flags)?; + connection.busy_timeout(BUSY_TIMEOUT)?; connection.pragma_update(None, "query_only", true)?; connection.authorizer(Some(|context: AuthContext<'_>| match context.action { AuthAction::Pragma { .. } => Authorization::Deny, _ => Authorization::Allow, }))?; - Ok(QueryRunner::new(connection)) + QueryRunner::new(connection) } /// A connection with this database's settings: WAL, `synchronous`, the diff --git a/crates/bakashrot-storage/src/lib.rs b/crates/bakashrot-storage/src/lib.rs index 298af4f..0e96193 100644 --- a/crates/bakashrot-storage/src/lib.rs +++ b/crates/bakashrot-storage/src/lib.rs @@ -22,7 +22,7 @@ mod reader; pub use batch::{Batch, Writer}; pub use database::{Checkpointer, Database, WRITER_CHECKPOINT_PAGES}; -pub use query::{MAX_QUERY_BYTES, MAX_QUERY_ROWS, QueryRunner}; +pub use query::{MAX_QUERY_BYTES, MAX_QUERY_ROWS, QueryRunner, Stop}; pub use reader::{Attachment, MESSAGES_BYTES, Reader}; use bakashrot_proto::limits::{MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID}; @@ -55,18 +55,28 @@ pub enum Error { TooBig(String), /// A client's query that failed or isn't read-only: `QueryFailed`. Query(String), + /// A client's query stopped past its time limit: `QueryTimedOut`. + QueryTimedOut(String), + /// SQLite rolled the batch's transaction back by itself (disk full, + /// an I/O error...): nothing in it is stored, and nothing more runs in + /// it (it would be written outside the transaction): `ServerError`. + RolledBack, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::Sqlite(error) => write!(f, "database: {error}"), + Error::RolledBack => f.write_str( + "database: the transaction was rolled back after a failure, nothing in it stored", + ), Error::Unusable(what) | Error::Invalid(what) | Error::NotFound(what) | Error::UnknownName(what) | Error::TooBig(what) - | Error::Query(what) => f.write_str(what), + | Error::Query(what) + | Error::QueryTimedOut(what) => f.write_str(what), } } } diff --git a/crates/bakashrot-storage/src/query.rs b/crates/bakashrot-storage/src/query.rs index eccdb7e..70d7c1c 100644 --- a/crates/bakashrot-storage/src/query.rs +++ b/crates/bakashrot-storage/src/query.rs @@ -1,19 +1,28 @@ //! Clients' read-only SQL (`Query`). //! -//! Read-only three ways: the connection has `query_only` on (SQLite -//! refuses any write), the statement must be one SQLite says only reads +//! Read-only four ways: the file is opened read-only (the handle itself +//! can't write), the connection has `query_only` on (SQLite refuses any +//! write), the statement must be one SQLite says only reads //! (`sqlite3_stmt_readonly`), and only one statement runs (more is an //! error, not ignored). PRAGMAs are refused as they're prepared //! (`Database::query_runner`'s authorizer): some would change the //! connection, `query_only` included, before the statement is looked //! at. The result is JSON, every value a string or null: //! `{"columns":[...],"rows":[[...],...]}`. +//! +//! A query can be stopped while it runs ([`QueryRunner::run_limited`]): +//! past a time limit, or from another thread ([`Stop`]: its client left). +//! SQLite looks every few thousand steps (its progress handler) and ends +//! the statement there. use crate::{Error, Result}; use bakashrot_proto::limits::MAX_MESSAGE_SIZE; use rusqlite::Connection; use rusqlite::types::ValueRef; use serde_json::Value; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; /// The most rows a query returns, as before. pub const MAX_QUERY_ROWS: usize = 10_000; @@ -21,22 +30,111 @@ pub const MAX_QUERY_ROWS: usize = 10_000; /// The biggest result, in bytes of JSON: what a packet carries. pub const MAX_QUERY_BYTES: usize = MAX_MESSAGE_SIZE; +/// How many of SQLite's steps between two looks at the time limit and the +/// [`Stop`]: about a tenth of a millisecond. +const STEPS_BETWEEN_LOOKS: i32 = 10_000; + +/// Stops a query run with [`QueryRunner::run_limited`], from any thread: +/// within a few steps, refused then ([`Error::Query`], "stopped while it +/// ran"). Clones stop the same query. +#[derive(Debug, Clone, Default)] +pub struct Stop(Arc); + +impl Stop { + /// Not stopped yet. + pub fn new() -> Stop { + Stop::default() + } + + /// Stops the query now, or as soon as it starts. + pub fn stop(&self) { + self.0.store(true, Ordering::Relaxed); + } + + /// Whether [`Stop::stop`] was called. + pub fn is_stopped(&self) -> bool { + self.0.load(Ordering::Relaxed) + } +} + +/// What the progress handler looks at during a query. +#[derive(Debug, Default)] +struct Watch { + /// The deadline and the limit it came from: none past `Instant`'s end. + limit: Option<(Instant, Duration)>, + stop: Stop, + /// Why it was interrupted, once it was: the refusal. + interrupted: Option, +} + +impl Watch { + /// Whether to interrupt the query now, and why. + fn look(&mut self) -> bool { + if self.interrupted.is_some() { + return true; + } + let why = if self.stop.is_stopped() { + Error::Query("stopped while it ran".to_owned()) + } else { + match self.limit { + Some((deadline, limit)) if Instant::now() >= deadline => Error::QueryTimedOut( + format!("stopped after {limit:?}, the server's time limit: narrow the query"), + ), + _ => return false, + } + }; + self.interrupted = Some(why); + true + } +} + /// A read-only connection for clients' queries. #[derive(Debug)] pub struct QueryRunner { connection: Connection, + watch: Arc>, +} + +fn lock(watch: &Mutex) -> std::sync::MutexGuard<'_, Watch> { + watch.lock().unwrap_or_else(PoisonError::into_inner) } impl QueryRunner { - pub(crate) fn new(connection: Connection) -> QueryRunner { - QueryRunner { connection } + pub(crate) fn new(mut connection: Connection) -> Result { + let watch = Arc::new(Mutex::new(Watch::default())); + let looking = watch.clone(); + connection.progress_handler(STEPS_BETWEEN_LOOKS, Some(move || lock(&looking).look()))?; + Ok(QueryRunner { connection, watch }) } /// Runs one read-only statement: its result as JSON. Refused /// ([`Error::Query`]) if it isn't one, or fails (SQLite's message, a /// failing row included: never a partial result); [`Error::TooBig`] - /// past [`MAX_QUERY_ROWS`] or [`MAX_QUERY_BYTES`]. + /// past [`MAX_QUERY_ROWS`] or [`MAX_QUERY_BYTES`]. No time limit. pub fn run(&self, sql: &str) -> Result { + self.run_limited(sql, Duration::MAX, &Stop::new()) + } + + /// [`QueryRunner::run`], stopped past `time_limit` + /// ([`Error::QueryTimedOut`]) or by `stop` ([`Error::Query`]). + pub fn run_limited(&self, sql: &str, time_limit: Duration, stop: &Stop) -> Result { + *lock(&self.watch) = Watch { + limit: Instant::now() + .checked_add(time_limit) + .map(|deadline| (deadline, time_limit)), + stop: stop.clone(), + interrupted: None, + }; + let result = self.query(sql); + let interrupted = std::mem::take(&mut *lock(&self.watch)).interrupted; + match (result, interrupted) { + // Interrupted, whatever SQLite made of it. + (Err(_), Some(why)) => Err(why), + (result, _) => result, + } + } + + fn query(&self, sql: &str) -> Result { let failed = |error: rusqlite::Error| Error::Query(explain(error.to_string())); let mut statement = self.connection.prepare(sql).map_err(failed)?; if !statement.readonly() || statement.column_count() == 0 { @@ -96,3 +194,33 @@ fn text(value: ValueRef<'_>) -> Value { ValueRef::Blob(bytes) => Value::String(bytes.iter().map(|b| format!("{b:02x}")).collect()), } } + +#[cfg(test)] +mod tests { + use crate::Database; + use bakashrot_config::Synchronous; + use rusqlite::MAIN_DB; + use std::path::PathBuf; + + /// The fifth guard, which the others hide from a test of what's + /// refused: SQLite says the file itself is read-only on it. + #[test] + fn the_file_is_opened_read_only() { + let folder = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/storage-unit"); + std::fs::create_dir_all(&folder).unwrap(); + let path = folder.join(format!("query-{}.sqlite", std::process::id())); + let database = Database::open(&path, Synchronous::Normal).unwrap(); + // The server's writer is always open: the WAL's files are there. + let writer = database.writer().unwrap(); + let runner = database.query_runner().unwrap(); + assert!(runner.connection.is_readonly(MAIN_DB).unwrap()); + assert_eq!( + runner.run("SELECT 1 AS one").unwrap(), + r#"{"columns":["one"],"rows":[["1"]]}"# + ); + drop((runner, writer, database)); + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); + } + } +} diff --git a/crates/bakashrot-storage/src/reader.rs b/crates/bakashrot-storage/src/reader.rs index 1f921be..acc5bdc 100644 --- a/crates/bakashrot-storage/src/reader.rs +++ b/crates/bakashrot-storage/src/reader.rs @@ -6,10 +6,10 @@ use crate::{ }; use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID}; use bakashrot_proto::packets::{ - Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, ReplicatedMessage, + Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, Pair, ReplicatedMessage, StoredAttachment, }; -use rusqlite::{Connection, OptionalExtension, Row}; +use rusqlite::{Connection, OptionalExtension, Row, params}; /// About how many bytes of messages one answer carries: past it, the rest /// is left for the next request (`more`). A bigger message goes alone. @@ -152,11 +152,6 @@ impl Reader { self.strings("SELECT DISTINCT topic FROM streams ORDER BY topic") } - /// Every node with messages (or that had some), in order. - pub fn nodes(&self) -> Result> { - self.strings("SELECT DISTINCT node FROM streams ORDER BY node") - } - /// Whether `node` has messages in any topic (or had some). fn has_node(&self, node: &str) -> Result { self.connection @@ -165,11 +160,25 @@ impl Reader { .map_err(Error::from) } - /// Every topic and node's last id: what `SyncState` compares. + /// Every topic and node's last id, in the order of their names + /// (without case). pub fn heads(&self) -> Result> { + self.heads_after(None, usize::MAX) + } + + /// Topics and nodes' last ids, what `SyncState` compares: `limit` at + /// most, in the order of their names (without case), those after the + /// pair `after` (from the first without). + pub fn heads_after(&self, after: Option<&Pair>, limit: usize) -> Result> { + // No name is empty: ("", "") comes before every pair. + let (topic, node) = after.map_or(("", ""), |pair| (&pair.topic, &pair.node)); + let limit = i64::try_from(limit).unwrap_or(i64::MAX); self.connection - .prepare_cached("SELECT topic, node, last_id FROM streams ORDER BY topic, node")? - .query_map([], |row| { + .prepare_cached( + "SELECT topic, node, last_id FROM streams WHERE (topic, node) > (?1, ?2) \ + ORDER BY topic, node LIMIT ?3", + )? + .query_map(params![topic, node, limit], |row| { Ok(Head { topic: row.get(0)?, node: row.get(1)?, diff --git a/crates/bakashrot-storage/tests/storage.rs b/crates/bakashrot-storage/tests/storage.rs index cd4c06e..d254bab 100644 --- a/crates/bakashrot-storage/tests/storage.rs +++ b/crates/bakashrot-storage/tests/storage.rs @@ -3,10 +3,11 @@ use bakashrot_config::Synchronous; use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID}; -use bakashrot_proto::packets::{Attachment as Sent, ReplicatedMessage}; -use bakashrot_storage::{AttachmentState, Database, Error, MAX_QUERY_ROWS, MAX_STREAMS}; +use bakashrot_proto::packets::{Attachment as Sent, Pair, ReplicatedMessage}; +use bakashrot_storage::{AttachmentState, Database, Error, MAX_QUERY_ROWS, MAX_STREAMS, Stop}; use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; const PART: usize = ATTACHMENT_PART_SIZE as usize; @@ -159,7 +160,6 @@ fn pushing_and_reading() { // Names, heads. assert_eq!(reader.topics().unwrap(), ["logs", "sensors"]); - assert_eq!(reader.nodes().unwrap(), ["garage", "kitchen"]); let heads: Vec<_> = reader .heads() .unwrap() @@ -174,6 +174,35 @@ fn pushing_and_reading() { ("sensors".into(), "kitchen".into(), 1) ] ); + // In pages: after a pair (its names without case), so many at most. + let page = |after: Option<(&str, &str)>, limit| -> Vec<_> { + let after = after.map(|(topic, node)| Pair { + topic: topic.into(), + node: node.into(), + }); + reader + .heads_after(after.as_ref(), limit) + .unwrap() + .into_iter() + .map(|h| (h.topic, h.node)) + .collect() + }; + assert_eq!( + page(None, 2), + [ + ("logs".into(), "garage".into()), + ("logs".into(), "kitchen".into()) + ] + ); + assert_eq!( + page(Some(("LOGS", "Kitchen")), 2), + [("sensors".into(), "kitchen".into())] + ); + assert_eq!( + page(Some(("logs", "h")), 1), + [("logs".into(), "kitchen".into())] + ); + assert!(page(Some(("sensors", "kitchen")), 2).is_empty()); assert_eq!(reader.last_id("logs", "kitchen").unwrap(), 3); assert_eq!(reader.last_id("nope", "kitchen").unwrap(), 0); } @@ -687,6 +716,28 @@ fn queries() { json("SELECT count(*) FROM messages")["rows"], serde_json::json!([["3"]]) ); + // SQLite without what nothing here uses (LIBSQLITE3_FLAGS in + // .cargo/config.toml): not built in, nor loadable. + for option in [ + "ENABLE_FTS3", + "ENABLE_FTS5", + "ENABLE_RTREE", + "ENABLE_DBSTAT_VTAB", + "ENABLE_STAT4", + "SOUNDEX", + "ENABLE_LOAD_EXTENSION", + "ENABLE_COLUMN_METADATA", + ] { + assert_eq!( + json(&format!("SELECT sqlite_compileoption_used('{option}')"))["rows"], + serde_json::json!([["0"]]), + "{option}" + ); + } + assert!(matches!( + runner.run("SELECT * FROM dbstat"), + Err(Error::Query(_)) + )); // A failing row fails it all, with SQLite's message. match runner.run("SELECT message_data ->> '$.t' FROM messages") { Err(Error::Query(why)) => assert!(why.contains("malformed JSON"), "{why}"), @@ -708,6 +759,58 @@ fn queries() { ); } +#[test] +fn queries_are_stopped() { + let (database, _) = open("stopped-queries"); + let _writer = database.writer().unwrap(); + let runner = database.query_runner().unwrap(); + let forever = + "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n"; + let refused = |result: bakashrot_storage::Result| match result { + Err(Error::Query(why)) => why, + other => panic!("{other:?}"), + }; + + // Past its time limit. + let started = Instant::now(); + let why = match runner.run_limited(forever, Duration::from_millis(200), &Stop::new()) { + Err(Error::QueryTimedOut(why)) => why, + other => panic!("{other:?}"), + }; + let took = started.elapsed(); + assert!(why.contains("200ms, the server's time limit"), "{why}"); + assert!( + took >= Duration::from_millis(200) && took < Duration::from_secs(5), + "{took:?}" + ); + + // From another thread, long before its time limit. + let stop = Stop::new(); + let stopping = stop.clone(); + let started = Instant::now(); + let thread = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(100)); + stopping.stop(); + }); + let why = refused(runner.run_limited(forever, Duration::from_secs(3600), &stop)); + thread.join().unwrap(); + assert_eq!(why, "stopped while it ran"); + assert!(started.elapsed() < Duration::from_secs(5)); + // Stopped before it starts: at its first look. + refused(runner.run_limited(forever, Duration::from_secs(3600), &stop)); + + // The next queries aren't: the connection is as before. + let short = "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 100000) SELECT count(*) FROM n"; + let counted = r#"{"columns":["count(*)"],"rows":[["100000"]]}"#; + assert_eq!( + runner + .run_limited(short, Duration::from_secs(60), &Stop::new()) + .unwrap(), + counted + ); + assert_eq!(runner.run(short).unwrap(), counted); +} + #[test] fn the_view_reads_by_key_range() { let (database, path) = open("plans"); diff --git a/crates/bakashrot-tools/Cargo.toml b/crates/bakashrot-tools/Cargo.toml index c74036f..772bf1f 100644 --- a/crates/bakashrot-tools/Cargo.toml +++ b/crates/bakashrot-tools/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "bakashrot-tools" -description = "BakaShrot's command-line tools: bakashrot pushes and reads messages, bakashrot-cert issues certificates and revokes them." +description = "BakaShrot's command-line tool: bakashrot pushes and reads messages, bakashrot cert issues certificates and revokes them." version.workspace = true edition.workspace = true rust-version.workspace = true @@ -9,17 +9,21 @@ authors.workspace = true repository.workspace = true publish.workspace = true -# No API to document, and its name is the DLL's library's (cargo doc would -# collide). +# One program, the certificates' commands in it (`bakashrot cert`): aws-lc, +# the C runtime and clap once, not in two programs. No API to document, and +# its name is the DLL's library's (cargo doc would collide). Released with +# the `release-tools` profile (../../Cargo.toml). [[bin]] name = "bakashrot" +path = "src/main.rs" doc = false [dependencies] bakashrot-client = { path = "../bakashrot-client" } bakashrot-pki = { path = "../bakashrot-pki" } bakashrot-proto = { path = "../bakashrot-proto" } -clap = { version = "4", features = ["derive"] } +# Without colours and "did you mean" suggestions: 40 KB less. +clap = { version = "4", default-features = false, features = ["std", "derive", "help", "usage", "error-context"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" time = "0.3.55" diff --git a/crates/bakashrot-tools/src/bin/bakashrot-cert.rs b/crates/bakashrot-tools/src/cert.rs similarity index 91% rename from crates/bakashrot-tools/src/bin/bakashrot-cert.rs rename to crates/bakashrot-tools/src/cert.rs index 8505920..0fa1fcd 100644 --- a/crates/bakashrot-tools/src/bin/bakashrot-cert.rs +++ b/crates/bakashrot-tools/src/cert.rs @@ -1,27 +1,16 @@ -//! `bakashrot-cert`: makes a CA, issues certificates, revokes them, shows -//! them. Every file is PEM; keys are written once, never over an existing -//! file. See `docs/certificates.md`. +//! `bakashrot cert`: makes a CA, issues certificates, revokes them, shows +//! them, with no server. Every file is PEM; keys are written once, never +//! over an existing file. See `docs/certificates.md`. use bakashrot_pki::{CA_DAYS, CERTIFICATE_DAYS, Ca, Identity, Revocations, Usage, summarize}; -use clap::{Parser, Subcommand}; +use clap::Subcommand; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; -use std::process::ExitCode; - -#[derive(Parser)] -#[command( - name = "bakashrot-cert", - version, - about = "Issues and revokes BakaShrot's certificates" -)] -struct Cli { - #[command(subcommand)] - command: Command, -} +// `bakashrot cert`'s commands (its help is `Command::Cert`'s, in main.rs). #[derive(Subcommand)] -enum Command { +pub enum Command { /// Makes a new CA: ca.crt and ca.key in --out. Keep ca.key off the /// servers: whoever has it can make any identity. Ca { @@ -85,17 +74,8 @@ enum Command { }, } -fn main() -> ExitCode { - match run(Cli::parse().command) { - Ok(()) => ExitCode::SUCCESS, - Err(error) => { - eprintln!("bakashrot-cert: {error}"); - ExitCode::FAILURE - } - } -} - -fn run(command: Command) -> Result<(), String> { +/// Runs one of `bakashrot cert`'s commands. +pub fn run(command: Command) -> Result<(), String> { match command { Command::Ca { name, days, out } => { let ca = Ca::create(&name, days).map_err(|e| e.to_string())?; diff --git a/crates/bakashrot-tools/src/bin/bakashrot.rs b/crates/bakashrot-tools/src/main.rs similarity index 89% rename from crates/bakashrot-tools/src/bin/bakashrot.rs rename to crates/bakashrot-tools/src/main.rs index 3e64ab9..7d19d1b 100644 --- a/crates/bakashrot-tools/src/bin/bakashrot.rs +++ b/crates/bakashrot-tools/src/main.rs @@ -1,6 +1,9 @@ //! `bakashrot`: pushes messages, reads them and their attachments, runs //! queries and lists names from the command line, connecting with a -//! `client.toml`; see `docs/client.md`, "The tools". +//! `client.toml`; see `docs/client.md`, "The tool". `bakashrot cert` +//! issues the certificates (`cert.rs`, `docs/certificates.md`). + +mod cert; use bakashrot_client::{Client, Error, Settings}; use bakashrot_proto::error::{code_name, is_refusal_code}; @@ -18,12 +21,12 @@ use std::time::Duration; #[command( name = "bakashrot", version, - about = "Pushes and reads BakaShrot's messages", + about = "Pushes and reads BakaShrot's messages, issues its certificates", after_help = "Exits with 0 on success, 1 on a failure, 2 on bad arguments." )] struct Cli { /// The client's settings: the server, the CA's certificate, this - /// client's certificate and key, the CRL. + /// client's certificate and key, the CRL (cert doesn't use them). #[arg(short, long, global = true, default_value = "client.toml")] config: PathBuf, #[command(subcommand)] @@ -102,14 +105,30 @@ enum Command { }, /// Lists the topics this client may use and the nodes of those it may /// read; every one if its roles have list_topics / list_nodes, or query. + /// --topics and --nodes keep the topics and nodes of the topic and node + /// pairs they match: `list topics --nodes kitchen` the topics kitchen + /// pushed to, `list nodes --topics 'sensors.*'` the nodes that pushed + /// to those. List { /// What to list. #[arg(value_enum, default_value_t = What::All)] what: What, + /// Only of the topics with this name or matching this pattern. + #[arg(long)] + topics: Option, + /// Only of the nodes with this name or matching this pattern. + #[arg(long)] + nodes: Option, /// Prints JSON, a line per list: {"kind":...,"names":[...],"truncated":...}. #[arg(long)] json: bool, }, + /// Makes a CA, issues certificates, revokes them, shows them; no + /// server needed (run it where the CA's key is). + Cert { + #[command(subcommand)] + command: cert::Command, + }, } /// Where `messages` starts. @@ -159,6 +178,7 @@ fn main() -> ExitCode { fn run(config: &Path, command: Command) -> Result<(), String> { match command { + Command::Cert { command } => cert::run(command)?, Command::Push { topic, message, @@ -246,7 +266,10 @@ fn run(config: &Path, command: Command) -> Result<(), String> { break; } if !batch.more { - std::thread::sleep(Duration::from_millis(interval)); + // Pinging meanwhile: `--interval` goes up to 1 h. + client + .wait(Duration::from_millis(interval)) + .map_err(failed)?; } } } @@ -254,7 +277,12 @@ fn run(config: &Path, command: Command) -> Result<(), String> { let sql = input(&sql)?; println!("{}", connect(config)?.query(&sql).map_err(failed)?); } - Command::List { what, json } => { + Command::List { + what, + topics, + nodes, + json, + } => { let mut client = connect(config)?; let kinds = [ (NameKind::Topic, "topic", "Topics"), @@ -267,7 +295,9 @@ fn run(config: &Path, command: Command) -> Result<(), String> { ) { continue; } - let list = client.list_names(kind).map_err(failed)?; + let list = client + .list_names(kind, topics.as_deref(), nodes.as_deref()) + .map_err(failed)?; if json { let json = serde_json::json!({ "kind": name, diff --git a/crates/bakashrot-tools/tests/bakashrot.rs b/crates/bakashrot-tools/tests/bakashrot.rs index c1b61f6..9490aeb 100644 --- a/crates/bakashrot-tools/tests/bakashrot.rs +++ b/crates/bakashrot-tools/tests/bakashrot.rs @@ -463,6 +463,24 @@ fn queries_and_lists() { json.ok().out, "{\"kind\":\"node\",\"names\":[\"kitchen\"],\"truncated\":false}\n" ); + // Filtered: the topics a node pushed to, the nodes of some topics. + assert_eq!( + server + .tool("kitchen", &["list", "topics", "--nodes", "Kitchen"]) + .ok() + .out, + "Topics (1):\n logs\n" + ); + assert_eq!( + server + .tool("kitchen", &["list", "--topics", "l*", "--nodes", "nobody"]) + .ok() + .out, + "Topics (0):\nNodes (0):\n" + ); + server + .tool("kitchen", &["list", "nodes", "--topics", "a b"]) + .fails(1, "isn't a topic name or pattern"); server .tool("kitchen", &["list", "everything"]) .fails(2, "everything"); diff --git a/crates/bakashrot-tools/tests/cert.rs b/crates/bakashrot-tools/tests/cert.rs index 116cf95..4fa5ec8 100644 --- a/crates/bakashrot-tools/tests/cert.rs +++ b/crates/bakashrot-tools/tests/cert.rs @@ -1,4 +1,4 @@ -//! `bakashrot-cert` end to end, in a folder of the build's. +//! `bakashrot cert` end to end, in a folder of the build's. use bakashrot_pki::{Revocations, summarize}; use std::fs; @@ -12,9 +12,11 @@ fn folder(name: &str) -> PathBuf { folder } -/// Runs the tool in `folder`: whether it succeeded, and what it printed. +/// Runs `bakashrot cert` in `folder`: whether it succeeded, and what it +/// printed. fn cert(folder: &Path, args: &[&str]) -> (bool, String) { - let output = Command::new(env!("CARGO_BIN_EXE_bakashrot-cert")) + let output = Command::new(env!("CARGO_BIN_EXE_bakashrot")) + .arg("cert") .args(args) .current_dir(folder) .output() diff --git a/docker/Dockerfile b/docker/Dockerfile index e888ee0..19d5702 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,5 +1,6 @@ -# The BakaShrot server's image: bakashrot-server, with the bakashrot and -# bakashrot-cert tools beside it. Built from the repository's root: +# The BakaShrot server's image: bakashrot-server, with the bakashrot tool +# beside it (bakashrot cert for the certificates). Built from the +# repository's root: # docker build -f docker/Dockerfile -t bakashrot-server . # CI builds it for amd64 and arm64 on a version tag, checks it # (docker/test.sh) and pushes it to ghcr.io/aziascreations/bakashrot-server @@ -12,7 +13,7 @@ # from outside the container # database = "/var/lib/bakashrot/bakashrot.sqlite" # and the certificates relative to it (ca = "ca.crt", ...). The server runs -# as uid 10001, which must be able to read its key (bakashrot-cert writes +# as uid 10001, which must be able to read its key (bakashrot cert writes # keys readable by their owner only): chown 10001:10001 config/server-1.key # # docker run -d --name bakashrot -p 7000:7000 \ @@ -20,7 +21,7 @@ # ghcr.io/aziascreations/bakashrot-server # # Or docker/compose.yml. `docker stop` stops it cleanly (SIGTERM). -# The tools: docker run --rm bakashrot-cert ... (or bakashrot ...). +# The tool: docker run --rm bakashrot cert ... (or bakashrot push ...). # --- Build --------------------------------------------------------------------- @@ -30,11 +31,13 @@ FROM rust:1-slim-trixie AS build WORKDIR /src # Only what the programs are built from (Dockerfile.dockerignore). COPY . . -# The toolchain rust-toolchain.toml pins, then the release build. +# The toolchain rust-toolchain.toml pins, then the release build, the tool +# with its own profile (release-tools, Cargo.toml). RUN rustup toolchain install \ - && cargo build --release --locked -p bakashrot-server -p bakashrot-tools \ + && cargo build --release --locked -p bakashrot-server \ + && cargo build --profile release-tools --locked -p bakashrot-tools \ && mkdir /out \ - && cp target/release/bakashrot-server target/release/bakashrot target/release/bakashrot-cert /out/ + && cp target/release/bakashrot-server target/release-tools/bakashrot /out/ # --- Runtime ------------------------------------------------------------------- diff --git a/docker/test.sh b/docker/test.sh index f8f5661..24555c1 100755 --- a/docker/test.sh +++ b/docker/test.sh @@ -1,6 +1,6 @@ #!/bin/sh # Smoke-tests a server image, as CI does before pushing it: certificates by -# its bakashrot-cert, its server started with them, its bakashrot pushing +# its bakashrot cert, its server started with them, its bakashrot pushing # and reading back over a Docker network, then `docker stop`, which must # end it cleanly (exit code 0, "stopped"). # Usage: docker/test.sh @@ -27,9 +27,9 @@ tool() { } docker network create "$name" >/dev/null -tool bakashrot-cert ca --name "Image test CA" -tool bakashrot-cert issue --name server-1 --server -tool bakashrot-cert issue --name tester --role tester +tool bakashrot cert ca --name "Image test CA" +tool bakashrot cert issue --name server-1 --server +tool bakashrot cert issue --name tester --role tester cat >"$work/server.toml" </native/`: .NET Core and .NET take the machine's (or +`dotnet publish -r`'s). .NET Framework ignores `runtimes/`: the package's +`build/net35/NibblePoker.BakaShrot.Client.targets` copies `win-x64`'s next +to the app, `win-arm64`'s when `PlatformTarget` is `ARM64` +(`BakaShrotRuntime` to choose). CI packs it after the releases, from +their libraries, and keeps it as the run's `bakashrot-nuget` artifact. + +```csharp +using (Client client = new Client("10.0.0.2", 7000, "ca.crt", "kitchen.crt", "kitchen.key", null)) +{ + client.Connect(); + long id = client.Push("sensors", "{\"t\":21}"); + foreach (Message message in client.IterMessages("sensors", client.Node, 0)) + Console.WriteLine(message.Id + " " + message.Data); +} +``` + +`new Client(host, port, ca, certificate, key, crl)` (PEM text or paths, +`crl` null for none), `Connect()`, `Node`, `Connected`, `Push(topic, +data[, byte[]])`, `PushFile(topic, data, path)`, `Latest()` (null if +none), `GetMessages()` (a `MessagesPage`), `IterMessages()`, `Follow()` +(pinging every minute while it waits longer), `Ping()` (`KeepAliveMs`), +`AnswerTimeoutMs` (`DefaultAnswerTimeoutMs` until set), +`GetAttachment()` (bytes), `SaveAttachment()` (a file), `ListTopics()` / +`ListNodes()` / `Query()` (the library's JSON, as a string: parsing it +is the app's; `ListTopics(topic, node)` / `ListNodes(topic, node)` +filter the lists as Python's do, null for any), `EnumerateTopics()` / +`EnumerateNodes()` (the same, filtered the same, as an +`IEnumerable`) and `EnumerateQuery()` (`QueryRow`s: `Values`, +null for NULL, by index or column name, `Columns`), over the library's +enumerations, no JSON: each `foreach` asks again, the enumeration closed +when it ends (`Close()` ends it too, `ConnectionLostException`), +`Close()` / `Dispose()`. The same exceptions as Python's: +`RefusedException`, `ConnectionLostException`, `AuthException`, +`BakaShrotException`, each with its `ErrorCode`. Strings go as UTF-16 (the +`W` exports); one with a NUL is refused (`InvalidArgument`) rather than +cut. Each `Client` has its own client in the DLL, its calls serialized: +several at once, from any threads. + +The library is found the usual DllImport way: next to the app, then the +PATH (`LD_LIBRARY_PATH` on Linux). It's 64-bit: the app must run as a +64-bit process (no "Prefer 32-bit" on .NET Framework). + ## PureBasic `bindings/purebasic/BakaShrot_Client_Prototypes.pbi` (with `BakaShrot_ErrorCodes.pbi`): `BakaShrot_LoadClient("bakashrot.dll")`, then -the `W` exports without their suffix, `BakaShrot_*String()` helpers for the -getters. Run directly, it's an example: `ClientExample +the `W` exports without their suffix, the client first, and +`BakaShrot_*String(Client)` helpers for the getters. Run directly, it's an example: `ClientExample `, pushing a message and one -with an attachment, reading both back (run by hand against a server; -not in CI, which has no PureBasic). +with an attachment, reading both back, then a second client at the same +time (run by hand against a server; not in CI, which has no PureBasic). -## The tools +## The tool -`bakashrot`, one program to push, read, query and list (`bakashrot-cert`, -for the CA, is apart: `certificates.md`). Each command connects with -`-c ` (`client.toml` by default), does one thing and exits: 0, 1 on a -failure (why on stderr: `Refused by the server (NotAllowed): ...`, -`Failed to connect to ...`), 2 on bad arguments. `--help` on each. +`bakashrot`, one program to push, read, query and list, and to make the +certificates (`bakashrot cert`, no server needed: `certificates.md`). +Each other command connects with `-c ` (`client.toml` by default), +does one thing and exits: 0, 1 on a failure (why on stderr: `Refused by +the server (NotAllowed): ...`, `Failed to connect to ...`), 2 on bad +arguments. `--help` on each. ```text bakashrot push logs '{"t":21}' Pushed as message #42 @@ -129,12 +261,14 @@ bakashrot messages logs kitchen -f --after latest --time bakashrot query "SELECT topic, count(*) FROM messages GROUP BY topic" bakashrot list Topics (2): ... Nodes (1): ... bakashrot list nodes --json {"kind":"node","names":["kitchen"],"truncated":false} +bakashrot list topics --nodes kitchen Topics (1): the topics kitchen pushed to +bakashrot list nodes --topics 'sensors.*' Nodes (2): those that pushed to sensors.* ``` - **`messages`:** the first 100 by default (`--limit 0` for all), `--after ` or `latest`; data as stored, a line break in it spanning lines; - `--follow` checks every `--interval` ms (500) until stopped or the - connection fails (exit 1); `--time` adds the push time between the id and + `--follow` checks every `--interval` ms (500, up to an hour, pinging + every minute meanwhile) until stopped or the connection fails (exit 1); `--time` adds the push time between the id and the data. - **Attachments:** `push -a `; `attachment` replaces the file, leaves none if it fails; `latest` says a message's (", not on this @@ -149,14 +283,52 @@ bakashrot list nodes --json {"kind":"node","names":["kitchen" ## Tests +`crates/bakashrot-client/tests/failures.rs`, against a fake server (TLS +with a test CA, then scripted answers): a late answer never taken for +the next request's, a wrong, malformed or cut answer, a part of the +wrong size, a refusal among the parts, a source failing mid-upload, a +connection the server closed (each: closed, `NotConnected` after, +nothing more sent); a refusal and an argument refused before sending +keeping it; a longer timeout waiting for a slow answer; `is_open()` +leaving it blocking, noticing a close_notify with the socket still open, +closing on data sent unasked or a broken TLS stream, and staying open +past a key update (the next request under the new keys). Each closing +path broken on purpose once: the tests caught it (`is_open()` five ways, +2026-11-20, the old socket peek among them). + `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, unaligned), selecting messages, attachments (from a file and memory, saved and loaded, the buffer, refused ones), every refusal and the 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. +- `exports.rs`, `answer_timeouts`: the answer timeout refused at 0 or + less, kept across connections; a query past it `ConnectionLost`. +- `codes.rs`: Python's, C#'s and PureBasic's error codes are the + protocol's (`error.rs`), every one by the same number and name; the + values Python and C# copy (the answer timeout, the keepalive, + `MAX_GET_MESSAGES`) are the Rust side's. +- `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 + `. Passed 2026-11-17 + with PureBasic 5.73 LTS and 6.41 (C backend), x64. 2026-11-20, both + again: the answer timeout exports and `QueryTimedOut` (11) through + the DLL against a server with `query_time_limit = "1s"`. +- C#, by hand (not in `test.ps1`): `cargo build`, then `dotnet test + bindings/csharp/NibblePoker.BakaShrot.Client.Tests` (NUnit). Its `[SetUpFixture]` + makes the certificates with `target/debug`'s `bakashrot cert` + (`BAKASHROT_BIN` for another folder), starts `bakashrot-server` on a free + port in `target/csharp-tests/`, copies the library next to the tests. + On `net48` (the `net35` build) and `net8.0` (`netstandard2.0`), on Linux + `net8.0` only. Passed 2026-11-18 on both, and on `net11.0` + (`-p:TargetFrameworks=net11.0`); 2026-11-20 on both again + (`AnswerTimeouts`). - `header.rs`: `bindings/c/bakashrot.h` matches the exports (rewritten when it doesn't: check it in). diff --git a/docs/config.md b/docs/config.md index e60a65b..06cc9a6 100644 --- a/docs/config.md +++ b/docs/config.md @@ -49,7 +49,7 @@ that browses a server: reading a topic is still `read_topics`. `query` gives both, it reads everything anyway. No `AllowRead` / `AllowWrite`: a list that's empty allows nothing. No -default topic: a push always names its topic (protocol 7 has none). +default topic: a push always names its topic (protocol 8 has none). **The roles are the only lists of topics** (decided 2026-11-16): no `[server] topics`, no `[replication] replicated_topics`, both refused as @@ -89,10 +89,32 @@ peers' `send_topics`. `[roles."site.reader"]`. Unquoted, TOML reads dots as tables: refused, `[retention]` says to quote. - **Durations:** numbers with a unit (`s m h d w`), added up: `"30s"`, - `"1d12h"`. Ages in `[retention]` can also be `"forever"`. + `"1d12h"`. Ages in `[retention]` can also be `"forever"`, and are 100 + years (`"36500d"`) at most (2026-11-19): longer ones once overflowed + when turned into milliseconds, a huge age wrapping around to almost + nothing. - **Sizes:** bytes, or `"500M"` with `K M G T` (1024-based), up to 1T. - **Paths:** relative ones are from the config file's folder. +## Database connections + +Reads and queries each have a pool of SQLite connections: one is opened +when none is idle, then kept for the next request. +`[server] idle_database_connections` (8 by default, 0 to 512) is how many +idle ones each pool keeps; more are closed as they're put back, and an +idle one is closed after a minute unused (looked at every 10 s). 0 opens +one per request. + +## Query time limit + +`[server] query_time_limit` (20 s by default) is how long a client's +query may run. Past it, SQLite stops it (it looks every 10,000 steps, a +fraction of a millisecond) and the client is refused with `QueryTimedOut` (11): +"stopped after 20s, the server's time limit". Keep it under the clients' +answer timeout (30 s by default; `BakaShrot_SetAnswerTimeout()`), or they +give up first. A client that gives up closes its connection, and the +server stops its query then too (`protocol.md`, "Rules"). + ## Retention A topic takes its name's line, else the first pattern matching it in the diff --git a/docs/known-issues.md b/docs/known-issues.md index a935dbf..174b6c0 100644 --- a/docs/known-issues.md +++ b/docs/known-issues.md @@ -42,9 +42,8 @@ network**, not exposed to the internet. So: server then needs every node's public key). - **Private keys sit in PEM files**, readable by whoever can read them: on trusted machines, file permissions are enough. -- **One connection per process in the DLL** (`revamp.md`, - "Open questions"): a handle-based API for several. Polling rather than - pushed subscriptions; nothing reconnects by itself, on purpose. +- **Polling rather than pushed subscriptions;** nothing reconnects by + itself, on purpose. - **At least once:** a push whose answer was lost (the server stopped between committing and answering) is stored twice if retried. A client that minds reads the latest message before retrying. @@ -62,13 +61,6 @@ network**, not exposed to the internet. So: From a read of the source on 2026-11-15: no test shows any of these yet. Reproduce one before fixing it, and move it up (or drop it) once known. -- **`sync_interval` over 5 min.** The server dialed closes the idle link - (`IDLE_TIMEOUT`), so every check-in fails once ("closed the link", - warned), then the link is dialed again after `retry_delay`. Nothing - in the config caps `sync_interval`. Left as it is (the owner, - 2026-11-16): replicating every 5 min or more isn't a real use, the - example config says to keep it under. Fix if needed: cap it under the - idle timeout, or have an idle link ask its `SyncState` more often. - **Resuming a big replicated attachment.** Before answering `Continue`, the receiver reads back and hashes every part it already has (`accept_from.rs`, `replicate_attachment`, `hash_parts`), while the @@ -80,11 +72,6 @@ Reproduce one before fixing it, and move it up (or drop it) once known. the example config says so by `max_attachment_size` (1 GiB by default). Fix if needed: a wait scaled to the parts already received, or the hash's state kept with the attachment. -- **`SyncState` in one packet.** Every head the peer may - send goes in one frame of 16 MiB at most: with very many topic and - node pairs (hundreds of thousands) it doesn't fit, the packet can't - be sent and replication stops. Fix: heads in several packets, or only - those that changed. - **Peers with several roles.** `SyncState` lists the union of its roles' `accept_topics` and the union of their `accept_nodes` (`Permissions::accepted`), while what's taken is each role on its diff --git a/docs/lab.md b/docs/lab.md index 4bf2d91..705fc5e 100644 --- a/docs/lab.md +++ b/docs/lab.md @@ -10,7 +10,7 @@ example configs. | Machine | What runs there | Files it gets | |---|---|---| -| admin (any) | `bakashrot-cert` | `ca.key` stays here, never copied | +| admin (any) | `bakashrot cert` | `ca.key` stays here, never copied | | server-1 | `bakashrot-server` | `ca.crt`, `server-1.crt`, `server-1.key`, `server.toml` | | server-2 | `bakashrot-server` | `ca.crt`, `server-2.crt`, `server-2.key`, `server.toml` | | kitchen | `bakashrot` (pushes to server-1) | `ca.crt`, `kitchen.crt`, `kitchen.key`, `client.toml` | @@ -23,12 +23,12 @@ their hostnames or IPs. The clients can be on the servers' machines. ## 1. The certificates (admin) ``` -bakashrot-cert ca --name "Lab CA" -bakashrot-cert issue --name server-1 --role peer --server -bakashrot-cert issue --name server-2 --role peer --server -bakashrot-cert issue --name kitchen --role sensor -bakashrot-cert issue --name dashboard --role dashboard -bakashrot-cert issue --name lab-py --role sensor --role dashboard +bakashrot cert ca --name "Lab CA" +bakashrot cert issue --name server-1 --role peer --server +bakashrot cert issue --name server-2 --role peer --server +bakashrot cert issue --name kitchen --role sensor +bakashrot cert issue --name dashboard --role dashboard +bakashrot cert issue --name lab-py --role sensor --role dashboard ``` A certificate is its name (the node) and its roles; the servers' configs @@ -154,7 +154,7 @@ Failed to connect to server-1.lab:7000 (NotAllowed): none of visitor's roles (gu takes them; it logs once that server-2 refused), start server-2: within about 10 s every one is on dashboard, in order. -**Revoking.** On admin, `bakashrot-cert revoke dashboard.crt` writes +**Revoking.** On admin, `bakashrot cert revoke dashboard.crt` writes `ca.crl`; copy it next to each server's `server.toml` (the `crl` above). Within 5 s they reload it (`INFO ca.crl: reloaded, 1 revoked`), and the certificate is refused, at its next connection or request: @@ -163,7 +163,7 @@ certificate is refused, at its next connection or request: Failed to connect to server-2.lab:7000 (AuthRejected): the server refused this client's certificate (CertificateRevoked) ``` -**Python.** `pip install bakashrot-0.3.0-py3-none-.whl` (from the +**Python.** `pip install bakashrot-0.4.0-py3-none-.whl` (from the release's `python/`), then, next to lab-py's `client.toml` (it may push and read: `sensor` and `dashboard`): diff --git a/docs/protocol.md b/docs/protocol.md index b336e65..5376cea 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -1,4 +1,4 @@ -# Protocol 7 +# Protocol 8 What goes over a connection between a client and a server, or two servers. The code is `crates/bakashrot-proto`; this describes it. @@ -20,8 +20,11 @@ connecting, pushes and messages (`server.md`). expected), no host names or IPs. Revoked certificates are in the CA's CRL: servers check it, and so do clients given it (servers dialing their peers too). -- **ALPN `bakashrot`** (`limits::ALPN`): both ends offer it, what isn't - BakaShrot doesn't get past the TLS handshake. It isn't versioned. +- **ALPN `bakashrot`** (`limits::ALPN`): both ends offer it and check it + was agreed on, what isn't BakaShrot doesn't get past TLS. rustls only + refuses a client offering other protocols, so the server closes one + offering none right after the handshake, before the versions + (2026-11-19). It isn't versioned. - **The versions, first:** right after TLS, each end sends its protocol version, 4 bytes little-endian (`frame::write_version()`), and reads the other's (`frame::check_version()`). Different versions: both ends @@ -36,6 +39,11 @@ connecting, pushes and messages (`server.md`). or over `MAX_PACKET_SIZE` (16 MiB), aborts the connection as soon as it arrived. The blocking client reads and writes them with `frame::read()` / `write()`, the async server with `frame::codec()` (`tokio-util`). + The limit applies to authenticated links only, as the owner asked + (2026-11-08, then 4 KB before authenticating): TLS authenticates both + ends before any frame, so nothing unauthenticated reaches one (rustls + bounds the handshake itself). Kept rather than lifted (2026-11-19): a + buggy peer announcing gigabytes would make the other end hold them. ## Packets @@ -83,8 +91,9 @@ format, its values are checked all the same.) ### Types Direction: **C** client, **S** server, **P** peer (a server linked to -another, as its client). Ids are protocol 7's own (6 can't connect); a new -packet takes the next one, none is ever reused. +another, as its client). Ids are protocol 7's own (6 can't connect; 8 +added `ListNames`' filters and `SyncState`'s pages); a new packet takes +the next one, none is ever reused. | Id | Packet | Dir | Fields | Answered by | |---|---|---|---|---| @@ -98,14 +107,16 @@ packet takes the next one, none is ever reused. | 8 | GetAttachment | C→S | `topic`, `node`, `message_id`, `from_part` | Attachment then its parts / RequestRefused | | 9 | Attachment | S→C | `size`, `sha256` | | | 10 | AttachmentPart | C→S, S→C, P→S | `data` bin, 1 B to 1 MiB | | -| 11 | ListNames | C→S | `kind` (1 topics, 2 nodes) | NamesList | +| 11 | ListNames | C→S | `kind` (1 topics, 2 nodes), `topics`, `nodes`: each a name or a pattern, or nil for any (those of the topic/node pairs they match) | NamesList | | 12 | NamesList | S→C | `kind`, `truncated` bool, `[name...]` (65536 at most) | | | 13 | Query | C→S | `sql` str | QueryResult / RequestRefused | | 14 | QueryResult | S→C | `json` str: `{"columns":[...],"rows":[[...],...]}` | | -| 15 | SyncStateRequest | P→S | none | SyncState / RequestRefused | -| 16 | SyncState | S→P | `[topic...]`, `[node...]` (names and patterns it takes from P), `[[topic, node, last_id]...]`, `[[topic, node, message_id, next_part]...]` (attachments it lacks, 256 at most) | | +| 15 | SyncStateRequest | P→S | `after`: `[topic, node]`, the last head of the previous page, or nil for the first | SyncState / RequestRefused | +| 16 | SyncState | S→P | `more` bool, `[topic...]`, `[node...]` (names and patterns it takes from P), `[[topic, node, last_id]...]` (in the order of their names, 32768 at most), `[[topic, node, message_id, next_part]...]` (attachments it lacks, 256 at most); the lists and attachments in the first page only | | | 17 | ReplicateMessages | P→S | `topic`, `node`, `[[id, pushed_at, data, [size, sha256] or nil]...]` (1-10000, ids strictly increasing) | MessagePushed (the last id) / RequestRefused | | 18 | ReplicateAttachment | P→S | `topic`, `node`, `message_id`, `from_part` | Continue, then its parts, then MessagePushed / RequestRefused | +| 19 | Ping | C→S, P→S | none: keeps an idle connection open | Pong | +| 20 | Pong | S→C, S→P | none | | ## Flows @@ -117,11 +128,13 @@ Reading C: GetMessages(after: id) S: Messages, `more` if other the latest C: GetMessages(after: nil, 1) S: Messages (empty if none) An attachment C: GetAttachment(from_part) S: Attachment, then AttachmentPart x the rest / RequestRefused (NotFound, NotReady) -Replicating P: SyncStateRequest S: SyncState +Replicating P: SyncStateRequest S: SyncState, `more` if others follow + P: SyncStateRequest(after) x pages S: SyncState P: ReplicateMessages x the batches S: MessagePushed each / RequestRefused P: ReplicateAttachment x missing S: Continue / RequestRefused (NotReady: another peer sending it) P: AttachmentPart x from next_part S: MessagePushed / RequestRefused +Keeping alive C: Ping (every minute while idle) S: Pong ``` - **Parts are streamed:** no request or answer per part, TCP paces them. @@ -132,15 +145,30 @@ Replicating P: SyncStateRequest S: SyncState them failed, then refuses: the client never has to read while sending. - **A server failing while it sends parts** closes the connection; the client asks again `from_part` the next one it needs. -- **Replication:** `SyncState` is all a check-in needs. The peer compares - it with what it has, by name, sends the messages the server lacks in +- **Replication:** `SyncState` is all a check-in needs. Its heads come + in pages of `MAX_HEADS_PER_PACKET` (32768): the biggest first page, + every list full and every name 64 characters, is about 13.3 MB, in a + 16 MiB frame (`the_biggest_sync_state_fits`). The peer asks for the + next `after` the last head while `more`, then compares them all with + what it has, by name, sends the messages the server lacks in batches of up to `batch_size` messages and about 1 MiB (a bigger message alone), then the attachments it listed. ## Rules - **One request at a time:** a client sends one, waits for its answer (the - parts of an attachment being part of its request or answer). + parts of an attachment being part of its request or answer). While a + `Query` runs, anything from the client (its closing, having given up + waiting) stops the query and closes the connection (2026-11-20); the + server's own limit stops it past `query_time_limit` (`QueryTimedOut`). +- **Silence:** the server closes a connection with no request for + `IDLE_TIMEOUT_SECS` (5 min). An end waiting longer between requests + sends a `Ping` every `KEEPALIVE_SECS` (1 min) meanwhile (added + 2026-11-19, protocol 8 not released yet): the tool's and the bindings' + follows and the replication links do it themselves; the DLL has no + thread of its own, so an app idle that long calls `BakaShrot_Ping()`. + A `Ping` needs no permission; a revoked certificate's is dropped like + any request. - **Refuse or abort:** valid but not allowed or not found (permissions, unknown names, over a limit, a failed query) is a `RequestRefused` with a code, the connection stays. Malformed or out of order (a bad frame, a diff --git a/docs/server.md b/docs/server.md index 24dd8fa..678f206 100644 --- a/docs/server.md +++ b/docs/server.md @@ -7,7 +7,7 @@ the wire: `protocol.md`. **Status:** steps 5, 6, 9, 10, 11 and 12: connecting, pushes and their attachments, messages, attachments, names, queries, retention, -replication, stopping cleanly. Every request of protocol 7 is answered. +replication, stopping cleanly. Every request of protocol 8 is answered. ## Running @@ -50,12 +50,13 @@ Restart=on-failure `docker/Dockerfile` (its comments have the details), the image `ghcr.io/aziascreations/bakashrot-server` (amd64 and arm64, pushed by CI -on a version tag): the server, with `bakashrot` and `bakashrot-cert` -beside it, on `debian:trixie-slim`, as uid 10001. +on a version tag): the server, with the `bakashrot` tool beside it +(`bakashrot cert` for the certificates), on `debian:trixie-slim`, as +uid 10001. - **The config** in `/etc/bakashrot`, read-only: `server.toml`, the certificates, the server's key (readable by uid 10001: `chown 10001` - it, `bakashrot-cert` writes keys for their owner only). `listen = + it, `bakashrot cert` writes keys for their owner only). `listen = "0.0.0.0:7000"`: 127.0.0.1 isn't reachable from outside. - **The database** in `/var/lib/bakashrot`, a volume: `database = "/var/lib/bakashrot/bakashrot.sqlite"`. @@ -64,7 +65,8 @@ beside it, on `debian:trixie-slim`, as uid 10001. 7000:7000 -v ./config:/etc/bakashrot:ro -v bakashrot-data:/var/lib/bakashrot `. `docker stop` is SIGTERM: a clean stop. The logs: `docker logs`. -- **The tools:** `docker run --rm bakashrot-cert ...`. +- **The tool:** `docker run --rm bakashrot cert ...` (or + `bakashrot push ...`). - **Checked** by `docker/test.sh ` (CI runs it on both before pushing): certificates by the image's tool, its server, a push read back over a Docker network, `docker stop` ending it cleanly. @@ -75,7 +77,7 @@ beside it, on `debian:trixie-slim`, as uid 10001. |---|---|---| | Connections | tokio, a task each | TLS (`tokio-rustls`, `bakashrot-pki`'s settings), the versions, the identity, then requests one at a time | | Writes | one writer thread | a queue of every write (pushes, uploads and their parts, replicated messages and parts, retention's deletes); the thread writes whatever is queued in one transaction (group commit, 1000 at most): the busier, the bigger the groups | -| Reads, queries | tokio's blocking threads | a pool of read connections and one of query connections (`query_only`), reused | +| Reads, queries | tokio's blocking threads | a pool of read connections and one of query connections (the file opened read-only, `query_only`), reused | | WAL checkpoints | one thread, every second | its own connection, off the writer's way (`storage.md`) | | The CRL file | a task, every 5 s | reloaded when its time or size changes; one that isn't the CA's is refused, the previous one stays; no file: nothing revoked, warned | | Retention | a task, at start then every `retention_interval` (1 min) | below | @@ -116,18 +118,27 @@ otherwise: 1. `SyncStateRequest`: the other server answers what it takes from this one (topics and nodes, patterns included), its last id in each topic - and node, and the attachments it lacks (256 at most). + and node, and the attachments it lacks (256 at most). The last ids + come in pages of 32768, each asked after the last of the previous + one, until none follow. 2. **The messages:** for each topic and node here that it takes and that its roles here may be sent (`send_topics`, `send_nodes`), and where it's behind, the messages after its last id, `batch_size` (1000) at a time and about 1 MiB at most (a bigger one alone), each batch answered before the next. A refusal - leaves that topic and node for the next check-in. + leaves that topic and node for the next check-in. Those its roles + here may be sent but it doesn't take (not in its roles' `accept_*` + there) are skipped and warned about (2026-11-21), the first ten + named: once per link, again only when they change, and "takes + everything" once none are left. Not at every check-in: it would spam. 3. **The attachments it lacks:** those this server has ready, from the part it needs. One it says doesn't match its SHA-256 is read back here: damaged (a disk, a bug), this server's copy is dropped and asked for again from its own peers (`replicating`, not served meanwhile), - instead of sent again at every check-in. + instead of sent again at every check-in. Damaged means read whole and + not matching, or a part missing; a read-back that fails otherwise (the + database busy, a connection not opened) says nothing, so the copy is + kept and warned about (2026-11-19): it may be the only one there is. **Receiving** (`accept_from.rs`): replication requests are answered only if the connection comes from `accept_from` (a hostname looked up at its @@ -155,7 +166,8 @@ the same ids with different messages, undetected. ## A connection 1. **TLS:** the client's certificate must be the CA's, valid, not revoked, - with an identity (`certificates.md`). A refused one gets TLS's alert, + with an identity (`certificates.md`), and ALPN `bakashrot` agreed on + (a client offering none is closed at once). A refused one gets TLS's alert, then a gentle close: the server shuts down and reads until the client closes (1 s at most). Closing at once reset the connection (the client's version bytes unread), which could beat the alert to the @@ -174,9 +186,10 @@ the same ids with different messages, undetected. | Timeout | | |---|---| | TLS, versions, welcome | 10 s (the server); the client's connect too | -| Silence between requests | 5 min, then the server closes | +| Silence between requests | 5 min, then the server closes (a `Ping` is a request: links and follows send one every minute while they wait) | | A packet sent (an answer, an attachment's part, to a peer too) | 30 s (the server), then it closes: a client that stopped reading doesn't hold a connection | -| An answer | 30 s (the client) | +| An answer | 30 s (the client; `set_answer_timeout()`, `BakaShrot_SetAnswerTimeout()`), then it closes: the server stops the query it was running | +| A query | 20 s (`[server] query_time_limit`), then SQLite stops it: `QueryTimedOut` | | An attachment's next part | 30 s (the server), then it closes | ## Requests so far @@ -211,10 +224,23 @@ the same ids with different messages, undetected. replicated), those the roles may push to or read (every one with `list_topics` or `query`); nodes are those with messages in the topics the roles may read (every one with `list_nodes` or `query`). `truncated` past 65,536. + The filters (`topics`, `nodes`: a name or a pattern each) keep the + topics or nodes of the topic and node pairs they match, out of + `reader.heads()`: the topics a node pushed to, the nodes that pushed to + a topic (a pair counts once it had messages, retention's deletions + included). A pair's topic must be one the roles may see when the + answer is topics or `topics` filters it; its node, when the answer is + nodes or `nodes` filters it (`connection.rs`, `list_names`). So a + node filter doesn't tell a client which nodes pushed to a topic it may + only push to. - **`Query`:** the roles must allow it (`NotAllowed`); read-only SQL, refused with SQLite's message (`QueryFailed`, with a hint to add `is_json = 1` on "malformed JSON"), over 10,000 rows or 16 MB (`TooBig`), never a partial result (`storage.md`, "The query surface"). + Stopped past `query_time_limit` (`QueryTimedOut`, "stopped after 20s, + the server's time limit"), or when the client closes meanwhile (it + gave up): its thread isn't left running. `Server::queries_running()` + says how many run. - **Sizes:** frames up to 16 MB (`MAX_PACKET_SIZE`), a bigger one drops the connection; messages up to `MAX_MESSAGE_SIZE` (16 MB less 4 KB), the server refusing bigger ones (`TooBig`); the client refuses messages and @@ -224,8 +250,8 @@ the same ids with different messages, undetected. `Client::connect(address, settings)` (`host:port`, the CA's certificate, the client's certificate and key, the CRL if any), then `push(topic, -data)`, `get_messages(topic, node, after, limit)`, `list_names(kind)`, -`query(sql)`. Blocking, no runtime. The DLL and the bindings over it: +data)`, `get_messages(topic, node, after, limit)`, `list_names(kind, +topics, nodes)`, `query(sql)`. Blocking, no runtime. The DLL and the bindings over it: `client.md`. Attachments: `push_with_attachment(topic, data, source)`, the source any @@ -330,7 +356,7 @@ each: isn't one line of JSON; - big messages: five of 600 KB and one of the largest size, one per answer, read back whole; one byte over refused; a query result over 16 MB refused; -- names: topics by role, nodes; +- names: topics by role, nodes, filtered by names and patterns; - attachments: 100 KB, 5 MB + 123 bytes, exactly 2 MB, 1 byte, 1 MB, read back and saved; the messages saying theirs; none, or no such message, refused leaving no file; another reader, one not allowed; over the server's limit, 0 for @@ -341,10 +367,16 @@ each: part on, something else than a part (closed, dropped); - queries: not allowed, results, a non-JSON row refused with the hint, errors, writes and two statements refused; + one past `query_time_limit` refused, the connection kept; one whose + client gave up first stopped (`queries_are_stopped`); - refusals keeping the connection (not allowed, unknown topic, a bad name the client catches); - certificates refused (no known role, with why; another CA's client; a - client trusting another CA; nothing listening); + client trusting another CA; a client offering no ALPN; nothing + listening); +- pings (answered with no permission needed, a `Pong` sent to the server + closing it, a revoked certificate's ping dropped); a server keeping no + idle database connection still serving reads and queries; - revoked certificates (an open connection dropped at its next request, a new one refused, others going on, a bad CRL refused); - six connections pushing at once (one id stream per node, none lost or @@ -366,6 +398,11 @@ each: first part going on from the second (the first read back for the SHA-256), one not matching refused and asked for from the start, a certificate whose roles take nothing refused; +- replication not taken (the server's log captured): a topic the peer + doesn't take warned about once over several check-ins and not sent, + warned again, both named, when another node pushes to it + (`replication_not_taken_is_warned`; `push_to.rs`'s + `heads_sent_and_not_taken` for what's sent and what's named); - two peers, one attachment (two raw connections): the second refused while the first sends it (names in any case), the first finishing it; one gone partway, the other going on from there; one whole but never diff --git a/docs/storage.md b/docs/storage.md index a49702a..84830db 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -73,6 +73,17 @@ operation of a `Batch` is all or nothing on its own (a savepoint), so a batch goes on after one fails: the server queues pushes and stores them together, one disk flush for all. +Except when SQLite rolls the whole transaction back by itself, which it +may on a full disk, an I/O error or out of memory. +What came after then ran outside any transaction, each operation +committed alone, while the batch failed and every write in it was +answered as failed: a retried push stored twice. Since 2026-11-19 every +operation after is refused (`Error::RolledBack`) and so is the batch: +nothing in it is stored, every write answered `ServerError` +(`nothing_runs_once_sqlite_rolled_back` in `batch.rs`, a `ROLLBACK` +standing in for SQLite's). The server's writer stops running the group +there. + | Operation | What | |---|---| | `push(topic, node, pushed_at, data)` | the next id of its stream, which it returns; the stream is made if new | @@ -97,8 +108,8 @@ read while the writer writes. Answers are the protocol's own types: | Reader | Gives | How | |---|---|---| | `messages(topic, node, after, limit)` | `Messages`: after an id in order, or the last ones; about 1 MiB at most (a bigger message alone), `more` if others follow | a range of keys | -| `topics()`, `nodes()` | the names with messages | `streams` | -| `heads()`, `last_id(topic, node)` | each stream's last id: `SyncState` | `streams` | +| `topics()` | the topics with messages | `streams` | +| `heads()`, `heads_after(after, limit)`, `last_id(topic, node)` | each stream's last id, all or a page after a pair (names without case): `SyncState` | `streams` (its `(topic, node)` index) | | `to_replicate(topic, node, after, limit)` | messages after an id as replication sends them (attachments' SHA-256s), about 1 MiB at most | a range of keys | | `missing_attachments(limit)` | replicated attachments not all here, from which part | `attachments` (index on states) | | `attachment(topic, node, id)`, `read_part(id, part)` | an attachment, its parts | the message's key; a part's key | @@ -133,9 +144,11 @@ afterwards, `purge_attachments(max_parts)` a batch at a time. ## The query surface -Clients' `Query` runs on `Database::query_runner()`, read-only three ways: -the connection is `query_only`, the statement must be one SQLite says only -reads, and one statement only (more is refused, not ignored). PRAGMAs are +Clients' `Query` runs on `Database::query_runner()`, read-only four ways: +the file is opened read-only (`SQLITE_OPEN_READONLY`, 2026-11-19: the +handle itself can't write), the connection is `query_only`, the statement +must be one SQLite says only reads, and one statement only (more is +refused, not ignored). PRAGMAs are refused as they're prepared ("not authorized", SQLite's authorizer), the `pragma_*` table functions too: some take effect at that point, and `PRAGMA query_only = 0`, though refused, turned `query_only` off for the @@ -159,6 +172,9 @@ SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen' SELECT message_data ->> '$.temp' FROM messages WHERE topic = 'sensors' AND is_json = 1 ``` +SQLite's functions are there, JSON's included; not `soundex()` nor the +`dbstat` table (left out of the build, "The file"). + - **By topic, or topic and node:** ranges of the table, read in order (a test checks the plans). - **Filters on `pushed_at` or `message_id`** read the streams they're in, @@ -182,7 +198,11 @@ SELECT message_data ->> '$.temp' FROM messages WHERE topic = 'sensors' AND is_js foreign keys: one writer keeps the tables consistent, `CHECK`s keep the values valid. - SQLite is compiled in (`rusqlite`'s `bundled`): the same version - everywhere, no system library. + everywhere, no system library. Without full-text search (FTS3, FTS5), + R-Tree, `dbstat`, STAT4, `soundex()`, extension loading and column + metadata, which libsqlite3-sys turns on and nothing here uses: 310 KB + less in the server (`LIBSQLITE3_FLAGS` in `../.cargo/config.toml`; a + test checks they're out). JSON is SQLite's own, always there. ## Measured @@ -251,7 +271,5 @@ big), the view's plans, and readers with two writers at once. In - **A time index**, if time queries over big streams get slow: a v10 migration adding an index on `(stream_id, pushed_at)` and joining the view on it too (measured above: twice the write cost). -- **Interrupting long queries** (a time limit): the server's, with - SQLite's interrupt. - **Attachments as files** next to the database instead of in it, if their size calls for it. diff --git a/guides/1-certificates.md b/guides/1-certificates.md index c7f902f..5734165 100644 --- a/guides/1-certificates.md +++ b/guides/1-certificates.md @@ -2,13 +2,14 @@ [Index](readme.md) · Next: [Server](2-server.md) -More options: `bakashrot-cert.exe --help`. +Made by `bakashrot.exe`'s `cert` commands, with no server needed. +More options: `bakashrot.exe cert --help`. ## The root certificate ```shell -bakashrot-cert.exe ca --name bakashrot-test +bakashrot.exe cert ca --name bakashrot-test ``` Resulting files: @@ -19,7 +20,7 @@ Resulting files: ## A server certificate ```shell -bakashrot-cert.exe issue --server --name server-lan1 +bakashrot.exe cert issue --server --name server-lan1 Wrote .\server-lan1.crt Wrote .\server-lan1.key ``` @@ -31,11 +32,11 @@ See [???](). ## Node certificates ```shell -bakashrot-cert.exe issue --name node-sensor --role sensor +bakashrot.exe cert issue --name node-sensor --role sensor Wrote .\node-sensor.crt Wrote .\node-sensor.key -bakashrot-cert.exe issue --name node-viewer --role viewer +bakashrot.exe cert issue --name node-viewer --role viewer Wrote .\node-viewer.crt Wrote .\node-viewer.key ``` @@ -48,7 +49,7 @@ Wrote .\node-viewer.key ## Checking one ```shell -bakashrot-cert.exe show node-sensor.crt +bakashrot.exe cert show node-sensor.crt node-sensor.crt name: node-sensor roles: sensor @@ -62,7 +63,7 @@ node-sensor.crt ## Revoking one ```shell -bakashrot-cert.exe revoke node-sensor.crt +bakashrot.exe cert revoke node-sensor.crt ``` * Writes `ca.crl` (every certificate revoked so far). diff --git a/guides/2-server.md b/guides/2-server.md index 1792845..57d5a9b 100644 --- a/guides/2-server.md +++ b/guides/2-server.md @@ -115,7 +115,7 @@ accept_nodes = ["*"] # Accepts every foreign node's messages (Default) > list_topics = true > list_nodes = true > ``` -> Its certificate: `bakashrot-cert.exe issue --name node-admin --role admin` +> Its certificate: `bakashrot.exe cert issue --name node-admin --role admin` ### Retention diff --git a/guides/5-reading.md b/guides/5-reading.md index cb3b5f8..21b4dab 100644 --- a/guides/5-reading.md +++ b/guides/5-reading.md @@ -51,6 +51,21 @@ E:\BakaShrot>bakashrot -c viewer.toml query "SELECT node, message_id, message_da ``` +## Names + +The topics a node pushed to, the nodes that pushed to some topics (a name +or a pattern): +```shell +E:\BakaShrot>bakashrot -c viewer.toml list topics --nodes node-sensor +Topics (1): + sensors + +E:\BakaShrot>bakashrot -c viewer.toml list nodes --topics "sens*" +Nodes (1): + node-sensor +``` + + ## Refused ```shell diff --git a/guides/readme.md b/guides/readme.md index aeb2e39..54933ca 100644 --- a/guides/readme.md +++ b/guides/readme.md @@ -15,12 +15,12 @@ Who gets which files: | Machine | Files | |---------|---------------------------------------------------------------------------------------| -| admin | `bakashrot-cert.exe`, `ca.crt`, `ca.key` (never copied) | +| admin | `bakashrot.exe` (its `cert` commands), `ca.crt`, `ca.key` (never copied) | | server | `bakashrot-server.exe`, `ca.crt`, `server-lan1.crt`, `server-lan1.key`, `server.toml` | | sensor | `bakashrot.exe`, `ca.crt`, `node-sensor.crt`, `node-sensor.key`, `client.toml` | | viewer | `bakashrot.exe`, `ca.crt`, `node-viewer.crt`, `node-viewer.key`, `viewer.toml` | More: -* `bakashrot --help`, `bakashrot-cert --help`. +* `bakashrot --help`, `bakashrot cert --help`. * Two replicating servers, Python, Docker: `docs/lab.md`. * Every setting: `docs/config.md`. diff --git a/readme.md b/readme.md index 55cfe7d..7138398 100644 --- a/readme.md +++ b/readme.md @@ -21,6 +21,7 @@ It also allows to sleep easy knowing each client is strongly authenticated by us * A C library (`bakashrot.dll`, `libbakashrot.so`), with a C header and PureBasic prototypes * A CLI tool to push, read, query and list * A Python module over the library, without dependencies, as a wheel with the library in it + * A C# client over the library, one file without dependencies, for .NET Framework 2.0 and 3.x up to the latest .NET ## Limitations diff --git a/release.ps1 b/release.ps1 index 2320146..0596df0 100644 --- a/release.ps1 +++ b/release.ps1 @@ -1,12 +1,14 @@ # A release for this platform, built, packaged and smoke-tested, into # target\dist\ (release.py, Python 3.11+, does it all). -# Usage: powershell -ExecutionPolicy Bypass -File release.ps1 [-SkipTest] -param([switch]$SkipTest) +# Usage: powershell -ExecutionPolicy Bypass -File release.ps1 [-SkipTest] [-HybridCrt] +# (-HybridCrt: the UCRT from Windows, see release.py's --hybrid-crt) +param([switch]$SkipTest, [switch]$HybridCrt) $ErrorActionPreference = "Stop" # The py launcher if it's there, python otherwise. $python = if (Get-Command py -ErrorAction SilentlyContinue) { @("py", "-3") } else { @("python") } $arguments = @(Join-Path $PSScriptRoot "release.py") if ($SkipTest) { $arguments += "--skip-test" } +if ($HybridCrt) { $arguments += "--hybrid-crt" } & $python[0] @($python | Select-Object -Skip 1) @arguments exit $LASTEXITCODE diff --git a/release.py b/release.py index eebb536..c243f1b 100644 --- a/release.py +++ b/release.py @@ -1,33 +1,38 @@ """Builds a BakaShrot release for this machine's platform (Windows or Linux, x64 or ARM64), checks it works, and archives it: - python release.py [--skip-test] + python release.py [--skip-test] [--hybrid-crt] Into target/dist/: bakashrot--/ the release: - bakashrot-server, bakashrot, bakashrot-cert the programs + bakashrot-server, bakashrot the programs bakashrot.dll / libbakashrot.so the client library (C) include/bakashrot.h its C header purebasic/*.pbi its PureBasic prototypes python/bakashrot.py the Python client, over it python/bakashrot--*.whl the same with the library in it + csharp/BakaShrot.cs the C# client, over it server.example.toml, client.example.toml the configs, documented docs/ docs/ README.txt what's where, how to start LICENSE.txt, THIRD-PARTY.txt BakaShrot's (CC0), its dependencies' bakashrot--.zip (Windows) or .tar.gz (Linux) -No keys or certificates in it: bakashrot-cert makes them. +No keys or certificates in it: bakashrot cert makes them. The check (unless --skip-test), in the release folder's _test/ (exes run from temp folders get blocked by antivirus here), deleted after unless -it failed: a CA and certificates by bakashrot-cert, the +it failed: a CA and certificates by bakashrot cert, the server started on a free port with a throwaway database, then the tool pushing (and an attachment of 3 MB), reading back, listing, querying; Python through the library, then the wheel installed by pip and used with no path given; then the server stopped as a service manager would (SIGTERM, or Ctrl+Break on Windows), which must end cleanly. +--hybrid-crt, on Windows: the C runtime's UCRT from Windows (10 and up) +instead of linked in, about 180 KB less per program, still no Visual C++ +redistributable (.cargo/hybrid-crt.toml); README.txt says which. + The version is the workspace's (Cargo.toml), which bakashrot.py's __version__ must match. Needs Python 3.11+ (tomllib) and cargo (rustup). """ @@ -49,16 +54,17 @@ HERE = os.path.dirname(os.path.abspath(__file__)) WINDOWS = sys.platform == "win32" EXE = ".exe" if WINDOWS else "" LIBRARY = "bakashrot.dll" if WINDOWS else "libbakashrot.so" -PROGRAMS = ["bakashrot-server", "bakashrot", "bakashrot-cert"] -CRATES = ["bakashrot-server", "bakashrot-tools", "bakashrot-capi"] +# Each built with its profile (Cargo.toml), into target//. +PROGRAMS = {"bakashrot-server": "release", "bakashrot": "release-tools"} +CRATES = {"bakashrot-server": "release", "bakashrot-capi": "release", "bakashrot-tools": "release-tools"} CLIENT_EXAMPLE = """\ # What the bakashrot tool and Python's Client.from_file() read, to connect # to a server. Paths are relative to this file's folder. See # docs/client.md. server = "10.0.0.2:7000" # host:port, [an IPv6 address]:port -ca = "ca.crt" # the CA's certificate (bakashrot-cert ca) -certificate = "kitchen.crt" # this node's (bakashrot-cert issue --name kitchen ...) +ca = "ca.crt" # the CA's certificate (bakashrot cert ca) +certificate = "kitchen.crt" # this node's (bakashrot cert issue --name kitchen ...) key = "kitchen.key" # crl = "ca.crl" # optional: certificates the CA revoked """ @@ -162,13 +168,17 @@ def third_party(): return "\n".join(lines) + "\n" -def readme(version, name): +def readme(version, name, hybrid): built = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") rustc = run(["rustc", "--version"]).strip() + crt = "" + if WINDOWS: + crt = ("\nThe C runtime: Windows' UCRT (Windows 10 and up), VCRuntime linked in." + if hybrid else "\nThe C runtime: linked in, nothing to install.") return f"""\ BakaShrot {version} ({name}) -Built {built}, commit {commit()}, {rustc}. +Built {built}, commit {commit()}, {rustc}.{crt} Licenses: BakaShrot is CC0 (LICENSE.txt); the crates built into it are listed in THIRD-PARTY.txt with their licenses. @@ -177,11 +187,11 @@ from clients with certificates of your own CA, store them in SQLite, and replicate them between servers. docs/ has the details (config.md, certificates.md, server.md, client.md, protocol.md). -Certificates (bakashrot-cert{EXE}; docs/certificates.md): - bakashrot-cert ca --name "Home CA" ca.crt, ca.key (keep ca.key safe) - bakashrot-cert issue --name server-1 --server a server's - bakashrot-cert issue --name kitchen --role sensor a client's: its node, its roles - bakashrot-cert revoke kitchen.crt ca.crl +Certificates (bakashrot{EXE} cert, no server needed; docs/certificates.md): + bakashrot cert ca --name "Home CA" ca.crt, ca.key (keep ca.key safe) + bakashrot cert issue --name server-1 --server a server's + bakashrot cert issue --name kitchen --role sensor a client's: its node, its roles + bakashrot cert revoke kitchen.crt ca.crl The server (bakashrot-server{EXE} server.toml; docs/config.md, server.md): server.example.toml has every setting. It logs to the console @@ -199,42 +209,51 @@ docs/client.md), --help on each command: The client library ({LIBRARY}): the BakaShrot_* exports, include/bakashrot.h for C, purebasic/ for PureBasic, python/bakashrot.py for Python (no -dependencies; it looks for the library next to itself or in BAKASHROT_DLL). +dependencies; it looks for the library next to itself or in BAKASHROT_DLL), +csharp/BakaShrot.cs for C# (.NET Framework 2.0 and up, .NET Core and .NET; +the library next to the app, which runs 64-bit). Or: pip install python/bakashrot-*.whl, the library inside. -Compatibility: protocol 7. Servers and clients must come from the same +Compatibility: protocol 8. Servers and clients must come from the same release: another version's connection is refused. Nothing from the old (PureBasic) BakaShrot is read: not its configs, keys or databases. """ -def build(): - print("Building") - command = ["cargo", "build", "--release", "--locked"] - for crate in CRATES: - command += ["-p", crate] - run(command) - return os.path.join(HERE, "target", "release") +def build(hybrid): + """Each profile's crates at once; the folder of a profile's output.""" + print("Building" + (" (the hybrid C runtime)" if hybrid else "")) + for profile in sorted(set(CRATES.values())): + command = ["cargo", "build", "--profile", profile, "--locked"] + if hybrid: + command += ["--config", os.path.join(".cargo", "hybrid-crt.toml")] + for crate, its in CRATES.items(): + if its == profile: + command += ["-p", crate] + run(command) + return lambda profile: os.path.join(HERE, "target", profile) -def package(built, version, name, out): +def package(built, version, name, out, hybrid): print(f"Packaging {out}") - for program in PROGRAMS: - shutil.copy2(os.path.join(built, program + EXE), out) - shutil.copy2(os.path.join(built, LIBRARY), out) + for program, profile in PROGRAMS.items(): + shutil.copy2(os.path.join(built(profile), program + EXE), out) + shutil.copy2(os.path.join(built(CRATES["bakashrot-capi"]), LIBRARY), out) bindings = os.path.join(HERE, "bindings") os.makedirs(os.path.join(out, "include")) shutil.copy2(os.path.join(bindings, "c", "bakashrot.h"), os.path.join(out, "include")) shutil.copytree(os.path.join(bindings, "purebasic"), os.path.join(out, "purebasic")) os.makedirs(os.path.join(out, "python")) shutil.copy2(os.path.join(bindings, "python", "bakashrot.py"), os.path.join(out, "python")) + os.makedirs(os.path.join(out, "csharp")) + shutil.copy2(os.path.join(bindings, "csharp", "NibblePoker.BakaShrot.Client", "BakaShrot.cs"), os.path.join(out, "csharp")) shutil.copytree(os.path.join(HERE, "docs"), os.path.join(out, "docs")) shutil.copy2(os.path.join(HERE, "crates", "bakashrot-config", "example.toml"), os.path.join(out, "server.example.toml")) write(os.path.join(out, "client.example.toml"), CLIENT_EXAMPLE) shutil.copy2(os.path.join(HERE, "LICENSE"), os.path.join(out, "LICENSE.txt")) write(os.path.join(out, "THIRD-PARTY.txt"), third_party()) - write(os.path.join(out, "README.txt"), readme(version, name)) + write(os.path.join(out, "README.txt"), readme(version, name, hybrid)) wheel = run([sys.executable, "-B", os.path.join(bindings, "python", "make_wheel.py"), os.path.join(out, LIBRARY), os.path.join(out, "python"), os.path.join(out, "LICENSE.txt"), os.path.join(out, "THIRD-PARTY.txt")]).strip() @@ -264,9 +283,9 @@ def smoke_test(out, wheel): if not re.search(pattern, got, re.MULTILINE): fail(f"{what}: unexpected output:\n{got}") - tool("bakashrot-cert", "ca", "--name", "Release test CA") - tool("bakashrot-cert", "issue", "--name", "server-1", "--server") - tool("bakashrot-cert", "issue", "--name", "tester", "--role", "tester") + tool("bakashrot", "cert", "ca", "--name", "Release test CA") + tool("bakashrot", "cert", "issue", "--name", "server-1", "--server") + tool("bakashrot", "cert", "issue", "--name", "tester", "--role", "tester") port = free_port() write(os.path.join(test, "server.toml"), f"""\ [server] @@ -328,7 +347,7 @@ key = "tester.key" expect("query", tool("bakashrot", "query", "SELECT message_data ->> '$.value' AS v FROM messages WHERE topic = 'releasetest' AND message_id = 1"), r'"rows":\[\["42"\]\]') - print(" The tools: pushed, an attachment too, read back, listed, queried: OK") + print(" The tool: certificates made, pushed, an attachment too, read back, listed, queried: OK") script = ("import sys; sys.path.insert(0, sys.argv[1]); import bakashrot\n" "with bakashrot.Client.from_file('client.toml', sys.argv[2]) as c:\n" @@ -382,7 +401,7 @@ def archive(out): def main(): args = set(sys.argv[1:]) - if args - {"--skip-test"}: + if args - {"--skip-test", "--hybrid-crt"}: sys.exit(__doc__) # rustup's folder isn't on every shell's PATH. os.environ["PATH"] = os.path.join(os.path.expanduser("~"), ".cargo", "bin") + os.pathsep + os.environ["PATH"] @@ -398,7 +417,8 @@ def main(): os.remove(old) os.makedirs(out) print(f"BakaShrot {release} for {name}, into {out}") - wheel = package(build(), release, name, out) + hybrid = "--hybrid-crt" in args + wheel = package(build(hybrid), release, name, out, hybrid) if "--skip-test" not in args: shutil.rmtree(smoke_test(out, wheel)) print(f"Archive: {archive(out)}") diff --git a/revamp.md b/revamp.md index 5499739..f50f91d 100644 --- a/revamp.md +++ b/revamp.md @@ -2,10 +2,10 @@ Started 2026-11-13: what it should change, what's decided, what's still open, and the plan. Every step of the plan is done (the workspace, -`bakashrot-proto`, `bakashrot-pki` and `bakashrot-cert`, +`bakashrot-proto`, `bakashrot-pki` and the certificate tool, `bakashrot-config`, `bakashrot-storage`, `bakashrot-server` and `bakashrot-client` answering every request, attachments included, the C -DLL with its C, PureBasic and Python bindings, the `bakashrot` tool, +DLL with its C, PureBasic, Python and C# bindings, the `bakashrot` tool, retention, replication, operations and releases, then the finish: one test runner, CI, Docker, `bench.ps1`), see "Plan". @@ -30,7 +30,12 @@ test runner, CI, Docker, `bench.ps1`), see "Plan". unloaded (`BakaShrot_UnloadClient()`) and Windows' loader lock is never in the way; - the C runtime linked statically on Windows (`+crt-static`), built - against an old glibc on Linux (manylinux); + against an old glibc on Linux (manylinux); a switch for the hybrid + one, not the default (2026-11-17): `build.ps1` / `release.ps1 + -HybridCrt`, `.cargo/hybrid-crt.toml`, the UCRT from Windows (10 + and up), VCRuntime still linked in, about 180 KB less per program, + still nothing to install (fully dynamic: 21 KB less again, but + `vcruntime140.dll`, the redistributable's); - `W` exports take UTF-16 everywhere (PureBasic's strings; `wchar_t` is 32 bits on Linux); - the toolchain pinned (`rust-toolchain.toml`), a C header generated @@ -112,7 +117,7 @@ Also decided (2026-11-13): config (warned in its log: a CRL deleted by mistake) and `client.toml` (the tool, Python's `from_file()`). A path given to the DLL's `SetCrl` or Python's `Client(crl=...)` is asked for - explicitly: missing, it's a `FileError`. `bakashrot-cert revoke` + explicitly: missing, it's a `FileError`. `bakashrot cert revoke` needs no file to start from (it writes the first one). A file that's there but can't be read or isn't the CA's is refused; - clients check it too when given one (`client_config()` takes the @@ -120,7 +125,7 @@ Also decided (2026-11-13): block each other whichever end dials; - revoked by certificate, not by name: each certificate has its own key and serial number, so two servers of the same name each have theirs, - revoked one at a time (`bakashrot-cert issue --file`). + revoked one at a time (`bakashrot cert issue --file`). - **The server's config is TOML** (2026-11-13), `docs/config.md`: - `[server]`, `[retention]`, `[replication]`, `[roles.]`; unknown keys refused; names only (no ids, pins or ranges); @@ -152,6 +157,121 @@ Also decided (2026-11-13): both): the topics it may push to or read, the nodes of the topics it may read (every node until then). Names only, reading is still `read_topics`. + - **Filtered lists** (2026-11-19, protocol 8): `ListNames` takes + `topics` and `nodes`, a name or a pattern each (nil for any), and + answers the topics or nodes of the topic and node pairs they match: + the topics a node pushed to, the nodes that pushed to a topic. Out + of the pairs the database has (`reader.heads()`), so replicated + messages count, and so do pairs whose messages retention deleted: + no new storage query. The same permissions as the lists, applied to + what the answer reveals: a pair's topic must be one the roles may + see when the answer is topics or `topics` filters it, its node when + the answer is nodes or `nodes` filters it. Without filters, the + lists as they were. In the DLL one export, `BakaShrot_ListNames` + (`kind`, `topics`, `nodes`); `ListTopics` and `ListNodes` went with + the enumerations (`ListNames(1 or 2, null, null)`). + - **The DLL's lists without JSON** (2026-11-19): the JSON getters are + `GetNamesListAsJson` and `GetQueryResultAsJson`; beside them, + enumerations like Win32's `FindFirstFile` / `FindNextFile` / + `FindClose`: `EnumerateNames` / `EnumerateQuery` keep a whole answer, + `NextName` / `NextQueryRow` move to the next item (before the first + at first), getters read it, `CloseEnum` closes it. They don't outlive + their client (`FreeClient` closes them); their handles are numbered + with the clients'. The query result is parsed in the DLL, the + protocol unchanged. Python keeps the JSON; C# has both (`List...()` + / `Query()` the JSON, `Enumerate...()` an `IEnumerable` over the + enumerations, `QueryRow`s for a query). + - **Queries stay** (2026-11-19): removing them (the `query` permission, + the packets, the runner, every binding) was done and undone the same + day, the owner's second thoughts; a filtered "field equals value" + request instead was weighed and not wanted. A fifth guard against + writes, asked by the owner: the query connection opens the file + read-only (`SQLITE_OPEN_READONLY`), beside `query_only`, the + read-only statement check, one statement only and no PRAGMAs. + - **The 16 MiB frame limit stays** (2026-11-19): it was the limit once + authenticated (2026-11-08, 4 KB before); since TLS authenticates + both ends before any frame, it's the only one left. Not lifted: a + buggy peer announcing gigabytes would make the other end hold them. + - **`SyncState` in pages** (2026-11-19, protocol 8, asked by the owner + for the worst case): `SyncStateRequest` takes `after` (the last head + received, a `Pair`), `SyncState` has `more` and 32768 heads at most + (`MAX_HEADS_PER_PACKET`), the lists and missing attachments in the + first page only. The biggest first page (every list full, every name + 64 characters) is about 13.3 MB, tested. A cursor by names, like + `GetMessages`' `after`, rather than several answers to one request + (one request, one answer) or ids (each server's own). The receiver + reads its heads in pages too (`heads_after`, on the `(topic, node)` + index); the sender gathers every page before comparing. + - **Fixes from a read of the code** (2026-11-19, asked by the owner): + - **ALPN required by the server too:** rustls only refuses a client + offering other protocols; one offering none is now closed right + after TLS, before the versions. + - **Retention ages, 100 years at most** (`MAX_RETENTION_AGE`, + `"36500d"`): turning a huge one into milliseconds wrapped around + (`"18446744073709552s"` was 384 ms). The cutoff is computed in one + place (`Retention::cutoff`), saturating. + - **`Ping` / `Pong`** (19, 20; protocol 8, not released yet): the + server closes a connection silent for 5 min + (`IDLE_TIMEOUT_SECS`). A ping every minute (`KEEPALIVE_SECS`) keeps + one open: the tool's `--follow`, Python's `follow()`, C#'s + `Follow()` and the replication links send it while waiting longer + (so `sync_interval` over 5 min works now). The DLL has no thread of + its own, so it can't on its own: `BakaShrot_Ping()` for apps, with + `ping()` / `Ping()` in Python and C#. Preferred to a longer idle + timeout (connections of dead clients would linger) or to + reconnecting by itself (nothing does, on purpose). + - **`[server] idle_database_connections`** (8 by default, 0-512): the + idle read and query connections each pool keeps (they were all + kept, as many as ever ran at once); one idle for a minute is + closed (a thread looks every 10 s). + - **An attachment dropped as damaged only when it is:** a peer + refusing it (`DataMismatch`) has the sender read its own copy + back; read whole and not matching, or a part missing, it's + dropped and asked for again as before. A read-back that failed + otherwise (a busy database, a connection not opened) dropped it + too, the only copy if this server was its origin: now it's kept + and warned about (`push_to.rs`, `judge`). + - **The Rust client closes a connection left out of step** + (`client.md`, "The Rust client"): an I/O error, a timeout, an + answer that isn't the request's, parts cut short or interrupted, a + source failing mid-upload. Requests after fail with `NotConnected` + without reading: a late answer was read as the next request's (a + push returning the previous one's id). `set_answer_timeout()` / + `answer_timeout()` (30 s by default); `is_open()` always blocking + again. The DLL already dropped its client on those. + - **Nothing written outside a transaction SQLite rolled back:** on a + full disk, an I/O error or out of memory, SQLite may roll a whole + batch back by itself; the writes after it then committed one at a + time while all were answered `ServerError` (retried, stored twice). + Every `Batch` operation after is refused now (`Error::RolledBack`), + the batch fails, nothing in it stored; the group's later writes are + refused too. + - **Long queries stopped** (2026-11-20): `[server] query_time_limit` + (20 s by default, under the clients' 30 s answer timeout) stops a + query through SQLite's progress handler (a look every 10,000 steps) + and refuses it with a code of its own, `QueryTimedOut` (11), so apps + tell it from SQL that fails (`QueryFailed`). A client closing while its query + runs (having given up) stops it too: the connection's task watches + it meanwhile, and dropping the query stops it, so no thread keeps + running one nobody waits for. The answer timeout reaches the DLL + (`BakaShrot_SetAnswerTimeout()` / `GetAnswerTimeout()`, kept across + connections), Python (`answer_timeout`) and C# (`AnswerTimeoutMs`). + - **`is_open()` reads through TLS** (2026-11-20): it peeked at the + socket, so a server's close_notify (bytes waiting) looked open + until the next request failed. It reads what's waiting into rustls + now, without blocking: TLS's own records (tickets, key updates) + keep it open, close_notify or the socket's end say closed, data + sent unasked or a broken TLS stream close it (out of step). + `&mut self` now; the DLL's `IsConnected` unchanged. + - **Names not taken by a peer warned about** (2026-11-21, old open + item): what a link's roles here may send but the peer doesn't + take is skipped as before, and logged to the console (a warning, + the first ten "topic:node" named) once per link, again only when + that changes; not at every check-in. + - **A NUL refused by Python** (2026-11-21, old item 23): every + string going to the DLL as a C string (a message, a name, SQL, a + path) with a NUL is refused (`INVALID_ARGUMENT`) rather than cut + there, as C# already did. - **Schema v9, not compatible with v8** (2026-11-13): old databases aren't opened, their data isn't carried over (the real-life tests start empty). `docs/storage.md`: @@ -184,13 +304,14 @@ Also decided (2026-11-13): - **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 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.ini`: Python's `Client.from_file()`, the tools at step 8. - **The tools** (2026-11-14), `docs/client.md`, "The tools": one `bakashrot` program with subcommands (`push`, `latest`, `messages`, `query`, `list`) over `bakashrot-client`, `bakashrot-cert` kept apart - (the CA's key); `-c/--config`, `client.toml` by default; the old tools' + (the CA's key; folded in as `bakashrot cert` on 2026-11-17, below); `-c/--config`, `client.toml` by default; the old tools' output; messages and SQL inline, `@file` or `-` (standard input); exit codes 0, 1, and 2 for bad arguments. - **Attachments** (2026-11-14), `docs/server.md` and `client.md`: @@ -241,7 +362,9 @@ Also decided (2026-11-13): - **the Python wheel has the library in it**, for a simple install; - **version 0.2.0**; **0.3.0** on 2026-11-16 (the identity OID under NibblePoker's PEN, the roles as the only lists of topics, - `list_topics` / `list_nodes`). + `list_topics` / `list_nodes`); **0.4.0** on 2026-11-19 (protocol 8: + filtered lists, `SyncState` in pages; the DLL's enumerations; the C# + binding). - **The PureBasic version removed** (2026-11-15): `OldSource/` deleted, kept in git history (up to `68966a8`). What of its notes and designs still holds went to `docs/known-issues.md`; the rest was already @@ -270,6 +393,36 @@ Also decided (2026-11-13): manual runs only, a read-only token but where images are pushed (after they're built and checked), no token left on disk by checkout, actions pinned to commits, `--locked` builds. +- **One tool, smaller** (2026-11-17), `docs/certificates.md`, "The + tool", and `docs/storage.md`, "The file": `bakashrot-cert` folded + into `bakashrot` as `bakashrot cert` (`ca`, `issue`, `revoke`, `show`, + the same options): aws-lc, the C runtime and clap once, 2.53 MB + instead of 2.85 + 1.73 MB on Windows. + The tool is built with its own profile, `release-tools` (`panic = + "abort"`, about 15% smaller); the DLL keeps `unwind` (it catches + panics), the server too (a panic loses one connection, not all). + clap without colours and "did you mean" suggestions (40 KB). SQLite + without what libsqlite3-sys turns on and nothing uses (FTS3, FTS5, + R-Tree, `dbstat`, STAT4, `soundex()`, extension loading, column + metadata; `LIBSQLITE3_FLAGS` in `.cargo/config.toml`): the server 4.68 + to 4.37 MB. Weighed and left: UPX (antivirus), the C runtime as a DLL + (Decided 2), a nightly `build-std` or `trim-paths`, `opt-level = "z"` + (5% for slower code), SQLite's `OMIT_*` options (7 KB), a TLS setup + naming P-384 only (25 KB: aws-lc links its other algorithms anyway). + **aws-lc kept** (the owner, 2026-11-17), the others measured with the + same TLS setup: Graviola (rustls-graviola 0.4.0, X25519MLKEM768 too) + 490 KB bigger, its P-256 and P-384 tables in it, and very new; ring + 410 KB smaller per program but without ML-KEM, which protects what's + recorded today from a quantum computer later; RustCrypto's provider + not for production. Worth another look if rustls-graviola lets a + 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 @@ -283,24 +436,17 @@ Also decided (2026-11-13): ## Open questions -- **A handle-based DLL API** (several connections per process, old open item - 10): later maybe, the owner's call (one connection per process for now). +None right now. ## The old open items The PureBasic version's, still not fixed: -- **Gaps in a topic and node's ids** aren't detected on replication (6), - and **`SyncState` is one packet** (9): `docs/known-issues.md`. +- **Gaps in a topic and node's ids** aren't detected on replication (6): + `docs/known-issues.md`. (**`SyncState` in one packet**, 9, fixed + 2026-11-19: its pages.) - **Peers are trusted with what they replicate** (12), unless messages get signed by their node: `docs/known-issues.md`. -- **Names left out of replication aren't warned about:** a topic or - node one side doesn't take is skipped silently. Warn once per peer - and name, again only when that changes (a log line at every check-in - would spam). -- **A NUL cuts a message from Python** (23): `push()` passes it to - `PushMessageToA` as a C string, `"a\x00b"` is stored as `a`. Refuse - it in `push()`, or pass a length. ## Plan @@ -338,6 +484,11 @@ by hand. | 11 | Replication | Peer links, sync state, batches by name, wildcards, attachments, skipping on arrival | Three servers end to end, a restart; the corrupted-attachment fix | Decided 2026-11-14 | Done 2026-11-14 | | 12 | Operations | Signals and a clean stop, logs, release, wheel | Runs unattended, stops cleanly, the release's smoke test | Decided 2026-11-14 | Done 2026-11-14 | | 13 | Finish | One test runner (the Rust tests, decided 2026-11-15), end-to-end tests in CI, the bench, Docker | Push speed with 4 servers replicating (`docs/server.md`, "Measured") | | Done 2026-11-16 (`bench.ps1`) | +| 14 | C# binding | `bindings/csharp`: `Client` over the `W` exports, C# 2 and .NET 2.0's library only (net35, netstandard2.0); the NuGet package `NibblePoker.BakaShrot.Client` with the four platforms' libraries, packed by CI after the releases (an artifact) | Its NUnit tests pass on net48 and net8.0 (by hand, not in `test.ps1`); the package loads the library on net8.0 and net48 | Asked by the owner 2026-11-18 (the name too) | Done 2026-11-18 | +| 15 | Filtered lists | `ListNames`' `topics` and `nodes` filters (protocol 8): server, client, `BakaShrot_ListNames` (`A`/`W`), Python, C#, PureBasic, `bakashrot list --topics/--nodes` | `end_to_end.rs` `names` (patterns, case, permissions), `exports.rs`, `check_bakashrot.py`, the NUnit tests | Decided 2026-11-19 | Done 2026-11-19 | +| 16 | The DLL's enumerations | `GetNamesListAsJson`, `GetQueryResultAsJson`; `EnumerateNames` / `EnumerateQuery`, `Next...`, their getters, `CloseEnum` (`enumerations.rs`); `ListTopics` / `ListNodes` dropped; PureBasic's example on them; C#'s `EnumerateTopics` / `EnumerateNodes` / `EnumerateQuery` (`IEnumerable`, asked at each `foreach`) | `exports.rs` `enumerations` (names, query rows and nulls, several at once, bad and closed handles, freed with the client); the NUnit `Enumerations` test | Decided 2026-11-19 | Done 2026-11-19 | +| 17 | `SyncState` in pages | `SyncStateRequest.after`, `SyncState.more`, `MAX_HEADS_PER_PACKET` (protocol 8); `heads_after` in storage; both ends of replication | `packets.rs` `the_biggest_sync_state_fits` and the page rules; `storage.rs` heads in pages; `end_to_end.rs` `sync_state_in_pages` (full and partial pages, the lists in the first only, a cursor in another case or not stored, pairs a peer doesn't take skipped, exactly a page, a pattern refused) and `replication_across_pages` (only what's after a head of the second page sent); each part broken on purpose once, every test caught it | Decided 2026-11-19 | Done 2026-11-19 | +| 18 | Fixes from a read of the code | The server requiring ALPN; retention ages capped at 100 years; `Ping` / `Pong` (protocol 8) with `BakaShrot_Ping`, Python's and C#'s `ping`, pings in the follows and the replication links; `idle_database_connections` and idle connections closed; a damaged copy told from a failed read-back; the Rust client closing a connection left out of step, `set_answer_timeout`; nothing written once SQLite rolled a batch back; `query_time_limit`, queries stopped when their client leaves, `BakaShrot_SetAnswerTimeout`; names a peer doesn't take warned about; a NUL refused by Python | `end_to_end.rs` `certificates_refused` (no ALPN: closed), `pings`, `no_idle_database_connections`; `config.rs` the cap, `retention_cutoff`, the key; the server's `pools_keep_few_and_close_the_idle` and `only_a_copy_read_whole_or_missing_a_part_is_damaged` (with `replication` for the damaged copy still dropped); the client's `failures.rs` (a fake server: late, wrong, cut answers and parts) and `revoked_certificates_are_dropped`; storage's `nothing_runs_once_sqlite_rolled_back` and `queries_are_stopped`; `end_to_end.rs` `queries_are_stopped` and `replication_not_taken_is_warned`, `heads_sent_and_not_taken`; `exports.rs` `answer_timeouts`, `codes.rs` (the bindings' codes and copied values), the NUnit `AnswerTimeouts`, PureBasic 5.73 and 6.41 by hand; `packets.rs` samples and bytes; `exports.rs`, `check_bakashrot.py`, the NUnit `Closing` | Decided 2026-11-19 | Done 2026-11-21 | Each step ends with its tests passing and its docs updated (the crate's docs, `docs/`, this file's status), then a commit when the owner