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

Merge pull request #5 from aziascreations/dev-improvements

Various improvements
This commit is contained in:
2026-11-22 20:43:35 +01:00
committed by GitHub
77 changed files with 6931 additions and 1320 deletions
+5
View File
@@ -9,3 +9,8 @@ rustflags = ["-C", "target-feature=+crt-static"]
# 2026-11-14 (../revamp.md, "Randomness from the OS"; ../docs/certificates.md). # 2026-11-14 (../revamp.md, "Randomness from the OS"; ../docs/certificates.md).
[env] [env]
AWS_LC_SYS_NO_JITTER_ENTROPY = "1" 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"
+9
View File
@@ -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"]
+61 -1
View File
@@ -1,6 +1,7 @@
# On a version tag, or run by hand: the same checks as test.ps1 (Windows # 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 # 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 # arm64, checked (docker/test.sh), pushed to ghcr.io on a tag only. Gitea
# Actions runs this file too. # Actions runs this file too.
# #
@@ -112,6 +113,65 @@ jobs:
target/dist/*.tar.gz target/dist/*.tar.gz
if-no-files-found: error if-no-files-found: error
nuget:
# The C# client's NuGet package (docs/client.md, "C#"): the four
# releases' libraries in runtimes/<rid>/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: docker:
# The server's image, each architecture built on its own kind of # The server's image, each architecture built on its own kind of
# machine (no emulation), checked, then pushed as <version>-<arch> on a # machine (no emulation), checked, then pushed as <version>-<arch> on a
+4
View File
@@ -14,6 +14,10 @@
# Python # Python
__pycache__/ __pycache__/
# C#
bindings/csharp/*/bin/
bindings/csharp/*/obj/
# Rust # Rust
target/ target/
Generated
+8 -84
View File
@@ -2,56 +2,12 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 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]] [[package]]
name = "anstyle" name = "anstyle"
version = "1.0.14" version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" 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]] [[package]]
name = "asn1-rs" name = "asn1-rs"
version = "0.7.2" version = "0.7.2"
@@ -123,7 +79,7 @@ dependencies = [
[[package]] [[package]]
name = "bakashrot-capi" name = "bakashrot-capi"
version = "0.3.0" version = "0.4.0"
dependencies = [ dependencies = [
"bakashrot-client", "bakashrot-client",
"bakashrot-config", "bakashrot-config",
@@ -137,7 +93,7 @@ dependencies = [
[[package]] [[package]]
name = "bakashrot-client" name = "bakashrot-client"
version = "0.3.0" version = "0.4.0"
dependencies = [ dependencies = [
"aws-lc-rs", "aws-lc-rs",
"bakashrot-pki", "bakashrot-pki",
@@ -147,7 +103,7 @@ dependencies = [
[[package]] [[package]]
name = "bakashrot-config" name = "bakashrot-config"
version = "0.3.0" version = "0.4.0"
dependencies = [ dependencies = [
"bakashrot-proto", "bakashrot-proto",
"indexmap", "indexmap",
@@ -157,7 +113,7 @@ dependencies = [
[[package]] [[package]]
name = "bakashrot-pki" name = "bakashrot-pki"
version = "0.3.0" version = "0.4.0"
dependencies = [ dependencies = [
"bakashrot-proto", "bakashrot-proto",
"rcgen", "rcgen",
@@ -169,7 +125,7 @@ dependencies = [
[[package]] [[package]]
name = "bakashrot-proto" name = "bakashrot-proto"
version = "0.3.0" version = "0.4.0"
dependencies = [ dependencies = [
"bytes", "bytes",
"rmp-serde", "rmp-serde",
@@ -180,7 +136,7 @@ dependencies = [
[[package]] [[package]]
name = "bakashrot-server" name = "bakashrot-server"
version = "0.3.0" version = "0.4.0"
dependencies = [ dependencies = [
"aws-lc-rs", "aws-lc-rs",
"bakashrot-client", "bakashrot-client",
@@ -200,7 +156,7 @@ dependencies = [
[[package]] [[package]]
name = "bakashrot-storage" name = "bakashrot-storage"
version = "0.3.0" version = "0.4.0"
dependencies = [ dependencies = [
"bakashrot-config", "bakashrot-config",
"bakashrot-proto", "bakashrot-proto",
@@ -210,7 +166,7 @@ dependencies = [
[[package]] [[package]]
name = "bakashrot-tools" name = "bakashrot-tools"
version = "0.3.0" version = "0.4.0"
dependencies = [ dependencies = [
"bakashrot-client", "bakashrot-client",
"bakashrot-config", "bakashrot-config",
@@ -304,10 +260,8 @@ version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
dependencies = [ dependencies = [
"anstream",
"anstyle", "anstyle",
"clap_lex", "clap_lex",
"strsim",
] ]
[[package]] [[package]]
@@ -337,12 +291,6 @@ dependencies = [
"cc", "cc",
] ]
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]] [[package]]
name = "data-encoding" name = "data-encoding"
version = "2.11.1" version = "2.11.1"
@@ -526,12 +474,6 @@ dependencies = [
"serde_core", "serde_core",
] ]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.19" version = "1.0.19"
@@ -674,12 +616,6 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]] [[package]]
name = "pem" name = "pem"
version = "4.0.0" version = "4.0.0"
@@ -973,12 +909,6 @@ dependencies = [
"rsqlite-vfs", "rsqlite-vfs",
] ]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]] [[package]]
name = "subtle" name = "subtle"
version = "2.6.1" version = "2.6.1"
@@ -1265,12 +1195,6 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]] [[package]]
name = "vcpkg" name = "vcpkg"
version = "0.2.15" version = "0.2.15"
+11 -2
View File
@@ -6,7 +6,7 @@ resolver = "3"
members = ["crates/*"] members = ["crates/*"]
[workspace.package] [workspace.package]
version = "0.3.0" version = "0.4.0"
edition = "2024" edition = "2024"
rust-version = "1.100" rust-version = "1.100"
license = "CC0-1.0" license = "CC0-1.0"
@@ -34,5 +34,14 @@ lto = true
codegen-units = 1 codegen-units = 1
strip = true strip = true
# Kept on purpose: the C DLL catches panics at every export (catch_unwind), # 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" 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"
+254 -70
View File
@@ -18,67 +18,79 @@ extern "C" {
#endif // __cplusplus #endif // __cplusplus
/** /**
* Why the last call failed: a protocol error code (1-99 a server's * Makes a client: its handle (1 and up, never reused), 0 if it failed.
* refusal, the connection still open; 100 and up the client's own), 0 if
* it succeeded. Getters don't change it.
*/ */
int32_t BakaShrot_GetLastError(void); int64_t BakaShrot_CreateClient(void);
/** /**
* Why the last call failed, in words: the server's reason for a refusal, * Frees a client and closes its connection (once a call on it in another
* the client's otherwise. Empty if it succeeded. * thread ends), 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. * The same as `BakaShrot_GetRefusalReasonA`, in UTF-16.
*/ */
ptrdiff_t BakaShrot_GetRefusalReasonW(uint16_t *buffer, ptrdiff_t size); ptrdiff_t BakaShrot_GetRefusalReasonW(int64_t client, uint16_t *buffer, ptrdiff_t size);
/** /**
* Sets the CA's certificate, which the server's must be issued by: PEM * Sets the CA's certificate, which the server's must be issued by: PEM
* text, or the path of a file holding it. Before connecting. * text, or the path of a file holding it. Before connecting.
*/ */
ptrdiff_t BakaShrot_SetCaCertificateA(const char *certificate); ptrdiff_t BakaShrot_SetCaCertificateA(int64_t client, const char *certificate);
/** /**
* The same as `BakaShrot_SetCaCertificateA`, in UTF-16. * The same as `BakaShrot_SetCaCertificateA`, in UTF-16.
*/ */
ptrdiff_t BakaShrot_SetCaCertificateW(const uint16_t *certificate); ptrdiff_t BakaShrot_SetCaCertificateW(int64_t client, const uint16_t *certificate);
/** /**
* Sets this client's certificate, which says its node and its roles: PEM * Sets the client's certificate, which says its node and its roles: PEM
* text, or the path of a file holding it. Before connecting. * text, or the path of a file holding it. Before connecting.
*/ */
ptrdiff_t BakaShrot_SetCertificateA(const char *certificate); ptrdiff_t BakaShrot_SetCertificateA(int64_t client, const char *certificate);
/** /**
* The same as `BakaShrot_SetCertificateA`, in UTF-16. * The same as `BakaShrot_SetCertificateA`, in UTF-16.
*/ */
ptrdiff_t BakaShrot_SetCertificateW(const uint16_t *certificate); ptrdiff_t BakaShrot_SetCertificateW(int64_t client, const uint16_t *certificate);
/** /**
* Sets this client's private key, its certificate's: PEM text, or the path * Sets the client's private key, its certificate's: PEM text, or the path
* of a file holding it. Before connecting. * of a file holding it. Before connecting.
*/ */
ptrdiff_t BakaShrot_SetPrivateKeyA(const char *key); ptrdiff_t BakaShrot_SetPrivateKeyA(int64_t client, const char *key);
/** /**
* The same as `BakaShrot_SetPrivateKeyA`, in UTF-16. * The same as `BakaShrot_SetPrivateKeyA`, in UTF-16.
*/ */
ptrdiff_t BakaShrot_SetPrivateKeyW(const uint16_t *key); ptrdiff_t BakaShrot_SetPrivateKeyW(int64_t client, const uint16_t *key);
/** /**
* Sets the CA's CRL, optional: servers it revokes are refused. PEM text, * Sets the CA's CRL, optional: servers it revokes are refused. PEM text,
* or the path of a file holding it (one that isn't there is a * or the path of a file holding it (one that isn't there is a
* `FileError`); null or empty for none. Before connecting. * `FileError`); null or empty for none. Before connecting.
*/ */
ptrdiff_t BakaShrot_SetCrlA(const char *crl); ptrdiff_t BakaShrot_SetCrlA(int64_t client, const char *crl);
/** /**
* The same as `BakaShrot_SetCrlA`, in UTF-16. * The same as `BakaShrot_SetCrlA`, in UTF-16.
*/ */
ptrdiff_t BakaShrot_SetCrlW(const uint16_t *crl); ptrdiff_t BakaShrot_SetCrlW(int64_t client, const uint16_t *crl);
/** /**
* Connects to the server at `host` (a name or an address) and `port`: * Connects to the server at `host` (a name or an address) and `port`:
@@ -87,57 +99,81 @@ ptrdiff_t BakaShrot_SetCrlW(const uint16_t *crl);
* the server refused the certificate, `ServerNotVerified` this client * the server refused the certificate, `ServerNotVerified` this client
* refused the server's, `NotAllowed` none of its roles is the server's). * refused the server's, `NotAllowed` none of its roles is the server's).
*/ */
ptrdiff_t BakaShrot_ConnectA(const char *host, int32_t port); ptrdiff_t BakaShrot_ConnectA(int64_t client, const char *host, int32_t port);
/** /**
* The same as `BakaShrot_ConnectA`, in UTF-16. * The same as `BakaShrot_ConnectA`, in UTF-16.
*/ */
ptrdiff_t BakaShrot_ConnectW(const uint16_t *host, int32_t port); ptrdiff_t BakaShrot_ConnectW(int64_t client, const uint16_t *host, int32_t port);
/** /**
* 1 while connected: notices when the server closed the connection * 1 while connected: notices when the server closed the connection
* (forgotten then: connect again). * (forgotten then: connect again).
*/ */
ptrdiff_t BakaShrot_IsConnected(void); ptrdiff_t BakaShrot_IsConnected(int64_t client);
/** /**
* Closes the connection: 0 if there was none. The settings stay. * Closes the connection: 0 if there was none. The settings stay.
*/ */
ptrdiff_t BakaShrot_Disconnect(void); ptrdiff_t BakaShrot_Disconnect(int64_t client);
/**
* 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 * The node this client is, as the server said when connecting: its
* certificate's name. Empty when not connected. * certificate's name. Empty when not connected.
*/ */
ptrdiff_t BakaShrot_GetNodeA(char *buffer, ptrdiff_t size); ptrdiff_t BakaShrot_GetNodeA(int64_t client, char *buffer, ptrdiff_t size);
/** /**
* The same as `BakaShrot_GetNodeA`, in UTF-16. * The same as `BakaShrot_GetNodeA`, in UTF-16.
*/ */
ptrdiff_t BakaShrot_GetNodeW(uint16_t *buffer, ptrdiff_t size); ptrdiff_t BakaShrot_GetNodeW(int64_t client, uint16_t *buffer, ptrdiff_t size);
/** /**
* Pushes a message (JSON or not) to `topic`, as this client's node: its * Pushes a message (JSON or not) to `topic`, as this client's node: its
* id (1 and up), -1 on failure. A push whose answer was lost * id (1 and up), -1 on failure. A push whose answer was lost
* (`ConnectionLost`) may have been stored all the same. * (`ConnectionLost`) may have been stored all the same.
*/ */
int64_t BakaShrot_PushMessageToA(const char *topic, const char *data); int64_t BakaShrot_PushMessageToA(int64_t client, const char *topic, const char *data);
/** /**
* The same as `BakaShrot_PushMessageToA`, in UTF-16. * The same as `BakaShrot_PushMessageToA`, in UTF-16.
*/ */
int64_t BakaShrot_PushMessageToW(const uint16_t *topic, const uint16_t *data); int64_t BakaShrot_PushMessageToW(int64_t client, const uint16_t *topic, const uint16_t *data);
/** /**
* Gets the latest message of `topic` and `node`, then read with the * Gets the latest message of `topic` and `node`, then read with the
* `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet. * `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet.
*/ */
ptrdiff_t BakaShrot_GetLatestMessageOfA(const char *topic, const char *node); ptrdiff_t BakaShrot_GetLatestMessageOfA(int64_t client, const char *topic, const char *node);
/** /**
* The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16. * The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16.
*/ */
ptrdiff_t BakaShrot_GetLatestMessageOfW(const uint16_t *topic, const uint16_t *node); ptrdiff_t BakaShrot_GetLatestMessageOfW(int64_t client,
const uint16_t *topic,
const uint16_t *node);
/** /**
* Gets the messages of `topic` and `node` after id `after` (0 for the * Gets the messages of `topic` and `node` after id `after` (0 for the
@@ -146,12 +182,17 @@ ptrdiff_t BakaShrot_GetLatestMessageOfW(const uint16_t *topic, const uint16_t *n
* first is selected; `BakaShrot_SelectMessage()` selects the others, * first is selected; `BakaShrot_SelectMessage()` selects the others,
* `BakaShrot_HasMoreMessages()` says whether more follow the last one. * `BakaShrot_HasMoreMessages()` says whether more follow the last one.
*/ */
int32_t BakaShrot_GetMessagesA(const char *topic, const char *node, int64_t after, int32_t limit); int32_t BakaShrot_GetMessagesA(int64_t client,
const char *topic,
const char *node,
int64_t after,
int32_t limit);
/** /**
* The same as `BakaShrot_GetMessagesA`, in UTF-16. * The same as `BakaShrot_GetMessagesA`, in UTF-16.
*/ */
int32_t BakaShrot_GetMessagesW(const uint16_t *topic, int32_t BakaShrot_GetMessagesW(int64_t client,
const uint16_t *topic,
const uint16_t *node, const uint16_t *node,
int64_t after, int64_t after,
int32_t limit); int32_t limit);
@@ -159,119 +200,128 @@ int32_t BakaShrot_GetMessagesW(const uint16_t *topic,
/** /**
* How many messages the last `GetMessages` or `GetLatestMessageOf` got. * How many messages the last `GetMessages` or `GetLatestMessageOf` got.
*/ */
int32_t BakaShrot_GetMessageCount(void); int32_t BakaShrot_GetMessageCount(int64_t client);
/** /**
* Selects the message at `index` (0 to the count - 1) for the getters: 0 * Selects the message at `index` (0 to the count - 1) for the getters: 0
* if there's none there (`InvalidArgument`), the selection unchanged. * if there's none there (`InvalidArgument`), the selection unchanged.
*/ */
ptrdiff_t BakaShrot_SelectMessage(int32_t index); ptrdiff_t BakaShrot_SelectMessage(int64_t client, int32_t index);
/** /**
* 1 if more messages follow the last one the last `GetMessages` got: ask * 1 if more messages follow the last one the last `GetMessages` got: ask
* again after its id. * again after its id.
*/ */
ptrdiff_t BakaShrot_HasMoreMessages(void); ptrdiff_t BakaShrot_HasMoreMessages(int64_t client);
/** /**
* The selected message's id, 0 if none. * The selected message's id, 0 if none.
*/ */
int64_t BakaShrot_GetMessageId(void); int64_t BakaShrot_GetMessageId(int64_t client);
/** /**
* When the selected message was pushed, by the server it was pushed to: * When the selected message was pushed, by the server it was pushed to:
* milliseconds since 1970-01-01 UTC, 0 if none. * milliseconds since 1970-01-01 UTC, 0 if none.
*/ */
int64_t BakaShrot_GetMessagePushedAt(void); int64_t BakaShrot_GetMessagePushedAt(int64_t client);
/** /**
* The selected message's attachment's size, 0 without one. * The selected message's attachment's size, 0 without one.
*/ */
int64_t BakaShrot_GetMessageAttachmentSize(void); int64_t BakaShrot_GetMessageAttachmentSize(int64_t client);
/** /**
* 1 if the selected message's attachment is all on this server (a * 1 if the selected message's attachment is all on this server (a
* replicated one may still be on its way). * replicated one may still be on its way).
*/ */
ptrdiff_t BakaShrot_IsMessageAttachmentReady(void); ptrdiff_t BakaShrot_IsMessageAttachmentReady(int64_t client);
/** /**
* The selected message's data, as pushed (JSON or not). * The selected message's data, as pushed (JSON or not).
*/ */
ptrdiff_t BakaShrot_GetMessageDataA(char *buffer, ptrdiff_t size); ptrdiff_t BakaShrot_GetMessageDataA(int64_t client, char *buffer, ptrdiff_t size);
/** /**
* The same as `BakaShrot_GetMessageDataA`, in UTF-16. * The same as `BakaShrot_GetMessageDataA`, in UTF-16.
*/ */
ptrdiff_t BakaShrot_GetMessageDataW(uint16_t *buffer, ptrdiff_t size); ptrdiff_t BakaShrot_GetMessageDataW(int64_t client, uint16_t *buffer, ptrdiff_t size);
/** /**
* The topic the last `GetMessages` or `GetLatestMessageOf` asked for. * The topic the last `GetMessages` or `GetLatestMessageOf` asked for.
*/ */
ptrdiff_t BakaShrot_GetMessageTopicA(char *buffer, ptrdiff_t size); ptrdiff_t BakaShrot_GetMessageTopicA(int64_t client, char *buffer, ptrdiff_t size);
/** /**
* The same as `BakaShrot_GetMessageTopicA`, in UTF-16. * The same as `BakaShrot_GetMessageTopicA`, in UTF-16.
*/ */
ptrdiff_t BakaShrot_GetMessageTopicW(uint16_t *buffer, ptrdiff_t size); ptrdiff_t BakaShrot_GetMessageTopicW(int64_t client, uint16_t *buffer, ptrdiff_t size);
/** /**
* The node the last `GetMessages` or `GetLatestMessageOf` asked for. * The node the last `GetMessages` or `GetLatestMessageOf` asked for.
*/ */
ptrdiff_t BakaShrot_GetMessageNodeA(char *buffer, ptrdiff_t size); ptrdiff_t BakaShrot_GetMessageNodeA(int64_t client, char *buffer, ptrdiff_t size);
/** /**
* The same as `BakaShrot_GetMessageNodeA`, in UTF-16. * The same as `BakaShrot_GetMessageNodeA`, in UTF-16.
*/ */
ptrdiff_t BakaShrot_GetMessageNodeW(uint16_t *buffer, ptrdiff_t size); ptrdiff_t BakaShrot_GetMessageNodeW(int64_t client, uint16_t *buffer, ptrdiff_t size);
/** /**
* Lists the topics with messages that this client may push to or read * Lists topics (`kind` 1) or nodes (`kind` 2): the topics with messages
* (every one if its roles have `list_topics` or `query`): how many, -1 on * that this client may push to or read (every one if its roles have
* failure. Then `BakaShrot_GetNamesList()`. * `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 * The same as `BakaShrot_ListNamesA`, in UTF-16.
* one if its roles have `list_nodes` or `query`): how many, -1 on failure. Then
* `BakaShrot_GetNamesList()`.
*/ */
int32_t BakaShrot_ListNodes(void); int32_t BakaShrot_ListNamesW(int64_t client,
int32_t kind,
const uint16_t *topics,
const uint16_t *nodes);
/** /**
* The last list, as JSON: * The last list, as JSON:
* `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated` * `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated`
* if some didn't fit. * if some didn't fit.
*/ */
ptrdiff_t BakaShrot_GetNamesListA(char *buffer, ptrdiff_t size); ptrdiff_t BakaShrot_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 * 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. * The same as `BakaShrot_QueryA`, in UTF-16.
*/ */
ptrdiff_t BakaShrot_QueryW(const uint16_t *sql); ptrdiff_t BakaShrot_QueryW(int64_t client, const uint16_t *sql);
/** /**
* The last query's result, as JSON: * The last query's result, as JSON:
* `{"columns":[...],"rows":[[...],...]}`, every value a string or null. * `{"columns":[...],"rows":[[...],...]}`, every value a string or null.
*/ */
ptrdiff_t BakaShrot_GetQueryResultA(char *buffer, ptrdiff_t size); ptrdiff_t BakaShrot_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 * 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 * read twice (its SHA-256 first): one changed in between is refused
* (`DataMismatch`). * (`DataMismatch`).
*/ */
int64_t BakaShrot_PushMessageWithFileA(const char *topic, const char *data, const char *file_path); int64_t BakaShrot_PushMessageWithFileA(int64_t client,
const char *topic,
const char *data,
const char *file_path);
/** /**
* The same as `BakaShrot_PushMessageWithFileA`, in UTF-16. * The same as `BakaShrot_PushMessageWithFileA`, in UTF-16.
*/ */
int64_t BakaShrot_PushMessageWithFileW(const uint16_t *topic, int64_t BakaShrot_PushMessageWithFileW(int64_t client,
const uint16_t *topic,
const uint16_t *data, const uint16_t *data,
const uint16_t *file_path); const uint16_t *file_path);
@@ -293,7 +347,8 @@ int64_t BakaShrot_PushMessageWithFileW(const uint16_t *topic,
* Pushes a message with the `Size` bytes at `Data` as its attachment, as * Pushes a message with the `Size` bytes at `Data` as its attachment, as
* `BakaShrot_PushMessageWithFileA` does. * `BakaShrot_PushMessageWithFileA` does.
*/ */
int64_t BakaShrot_PushMessageWithDataA(const char *topic, int64_t BakaShrot_PushMessageWithDataA(int64_t client,
const char *topic,
const char *data, const char *data,
const void *attachment, const void *attachment,
int64_t size); int64_t size);
@@ -301,7 +356,8 @@ int64_t BakaShrot_PushMessageWithDataA(const char *topic,
/** /**
* The same as `BakaShrot_PushMessageWithDataA`, in UTF-16. * The same as `BakaShrot_PushMessageWithDataA`, in UTF-16.
*/ */
int64_t BakaShrot_PushMessageWithDataW(const uint16_t *topic, int64_t BakaShrot_PushMessageWithDataW(int64_t client,
const uint16_t *topic,
const uint16_t *data, const uint16_t *data,
const void *attachment, const void *attachment,
int64_t size); int64_t size);
@@ -313,7 +369,8 @@ int64_t BakaShrot_PushMessageWithDataW(const uint16_t *topic,
* `NotReady` if it isn't on this server yet, `AttachmentMismatch`). A * `NotReady` if it isn't on this server yet, `AttachmentMismatch`). A
* failed one leaves no file. * failed one leaves no file.
*/ */
int64_t BakaShrot_SaveAttachmentA(const char *topic, int64_t BakaShrot_SaveAttachmentA(int64_t client,
const char *topic,
const char *node, const char *node,
int64_t message_id, int64_t message_id,
const char *file_path); const char *file_path);
@@ -321,7 +378,8 @@ int64_t BakaShrot_SaveAttachmentA(const char *topic,
/** /**
* The same as `BakaShrot_SaveAttachmentA`, in UTF-16. * The same as `BakaShrot_SaveAttachmentA`, in UTF-16.
*/ */
int64_t BakaShrot_SaveAttachmentW(const uint16_t *topic, int64_t BakaShrot_SaveAttachmentW(int64_t client,
const uint16_t *topic,
const uint16_t *node, const uint16_t *node,
int64_t message_id, int64_t message_id,
const uint16_t *file_path); const uint16_t *file_path);
@@ -331,24 +389,150 @@ int64_t BakaShrot_SaveAttachmentW(const uint16_t *topic,
* memory, checked with its SHA-256 (`BakaShrot_SaveAttachmentA` for big * memory, checked with its SHA-256 (`BakaShrot_SaveAttachmentA` for big
* ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`. * ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`.
*/ */
int64_t BakaShrot_LoadAttachmentA(const char *topic, const char *node, int64_t message_id); int64_t BakaShrot_LoadAttachmentA(int64_t client,
const char *topic,
const char *node,
int64_t message_id);
/** /**
* The same as `BakaShrot_LoadAttachmentA`, in UTF-16. * The same as `BakaShrot_LoadAttachmentA`, in UTF-16.
*/ */
int64_t BakaShrot_LoadAttachmentW(const uint16_t *topic, const uint16_t *node, int64_t message_id); int64_t BakaShrot_LoadAttachmentW(int64_t client,
const uint16_t *topic,
const uint16_t *node,
int64_t message_id);
/** /**
* Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if * Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if
* `BufferSize` is enough: returns its size (0 if none), copies nothing if * `BufferSize` is enough: returns its size (0 if none), copies nothing if
* it doesn't fit (a null `Buffer` asks for the size). * it doesn't fit (a null `Buffer` asks for the size).
*/ */
int64_t BakaShrot_GetAttachmentData(void *buffer, int64_t buffer_size); int64_t BakaShrot_GetAttachmentData(int64_t client, void *buffer, int64_t buffer_size);
/** /**
* Frees what `BakaShrot_LoadAttachment()` read: 1. * Frees what `BakaShrot_LoadAttachment()` read: 1.
*/ */
ptrdiff_t BakaShrot_FreeAttachmentData(void); ptrdiff_t BakaShrot_FreeAttachmentData(int64_t client);
/**
* 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 #ifdef __cplusplus
} // extern "C" } // extern "C"
@@ -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<long> 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<Message> 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<RefusedException>(() => 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<BakaShrotException>(() => 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<BakaShrotException>(() => kitchen.Push("refusals", "a\0b"))!;
Assert.That(error.Code, Is.EqualTo(ErrorCode.InvalidArgument), "a NUL would cut the message");
error = Assert.Throws<BakaShrotException>(() => kitchen.GetMessages("refusals", "kitchen", 0, 0))!;
Assert.That(error.Code, Is.EqualTo(ErrorCode.InvalidArgument), "limit 0");
error = Assert.Throws<BakaShrotException>(() => 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<RefusedException>(() => lounge.Push("logs", "x"))!;
Assert.That(refused.Code, Is.EqualTo(ErrorCode.NotAllowed));
refused = Assert.Throws<RefusedException>(() => lounge.GetMessages("refusals", "kitchen", 0, 1000))!;
Assert.That(refused.Code, Is.EqualTo(ErrorCode.NotAllowed));
refused = Assert.Throws<RefusedException>(() => 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<RefusedException>(() => 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<BakaShrotException>(() => 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<QueryRow> 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<QueryRow> got = new List<QueryRow>(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<ArgumentException>(() => { 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<string> bad = kitchen.EnumerateNodes("a b", null);
Assert.That(Assert.Catch<BakaShrotException>(() => bad.GetEnumerator().MoveNext())!.Code,
Is.EqualTo(ErrorCode.InvalidArgument));
Assert.That(Assert.Throws<RefusedException>(() => new List<QueryRow>(kitchen.EnumerateQuery("SELECT nope")))!.Code,
Is.EqualTo(ErrorCode.QueryFailed));
using (IEnumerator<string> topics = kitchen.EnumerateTopics().GetEnumerator())
{
Assert.That(topics.MoveNext(), Is.True);
kitchen.Close();
Assert.Throws<ConnectionLostException>(() => 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<RefusedException>(() => kitchen.GetAttachment("files", "kitchen", plainId))!;
Assert.That(refused.Code, Is.EqualTo(ErrorCode.NotFound));
string none = Server.In("none.bin");
refused = Assert.Throws<RefusedException>(() => 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<BakaShrotException>(() => kitchen.Push("files", "x", new byte[0]))!;
Assert.That(error.Code, Is.EqualTo(ErrorCode.InvalidArgument));
error = Assert.Throws<BakaShrotException>(() => 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<Message> follow = kitchen.Follow("follow", "kitchen");
List<Message> followed = new List<Message>();
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<long> 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<long>[] pushed = { new List<long>(), new List<long>() };
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<ConnectionLostException>(() => kitchen.Push("logs", "x"))!;
Assert.That(lost.Code, Is.EqualTo(ErrorCode.NotConnected));
lost = Assert.Throws<ConnectionLostException>(() => 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<BakaShrotException>(() => 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<ConnectionLostException>(() => 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<ConnectionLostException>(() => 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<ConnectionLostException>(() =>
new Client("127.0.0.1", 1, ca, certificate, key, null).Connect())!;
Assert.That(lost.Code, Is.EqualTo(ErrorCode.ConnectFailed));
AuthException auth = Assert.Throws<AuthException>(() => Server.Connect("guest"))!;
Assert.That(auth.Code, Is.EqualTo(ErrorCode.NotAllowed));
BakaShrotException error = Assert.Throws<BakaShrotException>(() =>
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<BakaShrotException>(() =>
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");
}
}
}
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- net48: the net35 build, on .NET Framework. net8.0: the netstandard2.0 one. -->
<PropertyGroup>
<TargetFrameworks Condition="'$(OS)' == 'Windows_NT'">net48;net8.0</TargetFrameworks>
<TargetFramework Condition="'$(OS)' != 'Windows_NT'">net8.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="NUnit" Version="3.14.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\NibblePoker.BakaShrot.Client\NibblePoker.BakaShrot.Client.csproj" />
</ItemGroup>
</Project>
@@ -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
{
/// <summary>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).</summary>
[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;
}
}
}
@@ -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
{
/// <summary>crates/bakashrot-proto/src/error.rs: 1-99 refused by the
/// server, 100 and up the client's own.</summary>
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;
}
}
/// <summary>The server refused (codes 1-99), the connection still open:
/// Message is its reason.</summary>
public class RefusedException : BakaShrotException
{
public RefusedException(string reason, ErrorCode code) : base(reason, code) { }
}
/// <summary>Not connected, unreachable, or the connection broke:
/// Connect() again. A push whose answer was lost may be stored.</summary>
public class ConnectionLostException : BakaShrotException
{
public ConnectionLostException(string message, ErrorCode code) : base(message, code) { }
}
/// <summary>Connecting refused for good: a certificate either way, no
/// role allowed, another protocol version.</summary>
public class AuthException : BakaShrotException
{
public AuthException(string message, ErrorCode code) : base(message, code) { }
}
/// <summary>A stored message, its data as pushed (JSON or not).</summary>
public sealed class Message
{
public long Id;
public string Topic, Node, Data;
/// <summary>Milliseconds since 1970-01-01 UTC, by the server it was pushed to.</summary>
public long PushedAt;
/// <summary>0 without an attachment.</summary>
public long AttachmentSize;
/// <summary>All of the attachment is on this server.</summary>
public bool AttachmentReady;
public DateTime Pushed
{
get { return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(PushedAt); }
}
}
/// <summary>One answer of GetMessages(): More if more follow LastId.</summary>
public sealed class MessagesPage
{
public List<Message> Messages = new List<Message>();
public bool More;
/// <summary>The last message's id, 0 if none.</summary>
public long LastId
{
get { return Messages.Count == 0 ? 0 : Messages[Messages.Count - 1].Id; }
}
}
/// <summary>A row of EnumerateQuery(): its values (null for NULL), by
/// index or column name.</summary>
public sealed class QueryRow
{
/// <summary>The query's columns, the same array for every row.</summary>
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]; }
}
/// <summary>The first column with that name (as the query wrote it).</summary>
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()
/// <summary>host: a name or an address. The certificates and the CRL
/// (null for none): PEM text or a file's path.</summary>
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;
}
/// <summary>The node the server says this client is, once connected.</summary>
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;
}
}
/// <summary>Disconnects and frees its client in the library; Connect() reconnects.</summary>
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);
}
/// <summary>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.</summary>
public void Ping()
{
lock (sync)
Check(Native.BakaShrot_Ping(Handle()), "Ping");
}
/// <summary>How often to Ping() while waiting between requests, in ms.</summary>
public const int KeepAliveMs = 60000;
/// <summary>AnswerTimeoutMs until changed.</summary>
public const int DefaultAnswerTimeoutMs = 30000;
/// <summary>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.</summary>
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;
}
}
}
/// <summary>Pushes data (JSON or not) to topic, as this client's node: its id.</summary>
public long Push(string topic, string data)
{
lock (sync)
return Id(Native.BakaShrot_PushMessageToW(Handle(), Text(topic), Text(data ?? "")), "Push");
}
/// <summary>With an attachment (1 byte and up): the message is stored once all of it came.</summary>
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");
}
/// <summary>With the file at path as its attachment, read a part at a time.</summary>
public long PushFile(string topic, string data, string path)
{
lock (sync)
return Id(Native.BakaShrot_PushMessageWithFileW(Handle(), Text(topic), Text(data ?? ""), Text(path)), "Push");
}
/// <summary>The latest message of topic and node, null if none yet.</summary>
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;
}
}
/// <summary>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.</summary>
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;
}
}
/// <summary>Every message of topic and node after id after, until there are no more.</summary>
public IEnumerable<Message> 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);
}
/// <summary>The messages pushed from now on, as Follow(topic, node, after, 500) does.</summary>
public IEnumerable<Message> Follow(string topic, string node)
{
Message latest = Latest(topic, node);
return Follow(topic, node, latest == null ? 0 : latest.Id, 500);
}
/// <summary>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.</summary>
public IEnumerable<Message> 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);
}
}
/// <summary>A message's attachment, in memory (SaveAttachment() for
/// big ones), checked with its SHA-256.</summary>
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);
}
}
}
/// <summary>Saves a message's attachment as the file at path
/// (replaced), checked with its SHA-256: its size. A failed one
/// leaves no file.</summary>
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");
}
/// <summary>The topics with messages that this client may push to or
/// read, as JSON: {"kind":"topic","truncated":false,"names":[...]}.</summary>
public string ListTopics()
{
return ListTopics(null, null);
}
/// <summary>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.</summary>
public string ListTopics(string topic, string node)
{
lock (sync)
return Names(Native.BakaShrot_ListNamesW(Handle(), 1, Text(topic), Text(node)), "List topics");
}
/// <summary>The nodes with messages in the topics this client may
/// read, as ListTopics() says them.</summary>
public string ListNodes()
{
return ListNodes(null, null);
}
/// <summary>ListNodes(), filtered as ListTopics(topic, node) is:
/// ListNodes("logs", null) is the nodes that pushed to logs.</summary>
public string ListNodes(string topic, string node)
{
lock (sync)
return Names(Native.BakaShrot_ListNamesW(Handle(), 2, Text(topic), Text(node)), "List nodes");
}
/// <summary>Runs one read-only SELECT or WITH: the server's JSON,
/// {"columns":[...],"rows":[[...],...]}.</summary>
public string Query(string sql)
{
lock (sync)
{
Check(Native.BakaShrot_QueryW(Handle(), Text(sql)), "Query");
return GetString(Native.BakaShrot_GetQueryResultAsJsonW);
}
}
/// <summary>The topics ListTopics() lists, one at a time, without
/// JSON. Asked once a foreach starts (each one asks again), closed
/// when it ends.</summary>
public IEnumerable<string> EnumerateTopics()
{
return EnumerateNames(1, null, null);
}
/// <summary>The topics ListTopics(topic, node) lists, as EnumerateTopics() gives them.</summary>
public IEnumerable<string> EnumerateTopics(string topic, string node)
{
return EnumerateNames(1, topic, node);
}
/// <summary>The nodes ListNodes() lists, as EnumerateTopics() gives them.</summary>
public IEnumerable<string> EnumerateNodes()
{
return EnumerateNames(2, null, null);
}
/// <summary>The nodes ListNodes(topic, node) lists, as EnumerateTopics() gives them.</summary>
public IEnumerable<string> EnumerateNodes(string topic, string node)
{
return EnumerateNames(2, topic, node);
}
/// <summary>Query(sql)'s rows, one at a time, without JSON. Asked
/// once a foreach starts (each one asks again), closed when it ends.</summary>
public IEnumerable<QueryRow> 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<string> 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);
}
}
@@ -0,0 +1,42 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- net35: .NET Framework 2.0 and 3.x (it uses only mscorlib), 4.x too.
netstandard2.0: .NET Core 2.0 and up, .NET 5 and up.
Not BakaShrot.dll: that's the native library's name on Windows. -->
<PropertyGroup>
<TargetFrameworks>net35;netstandard2.0</TargetFrameworks>
<LangVersion>ISO-2</LangVersion>
<RootNamespace>NibblePoker.BakaShrot</RootNamespace>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<!-- The package. CI packs it with the version and the native libraries:
dotnet pack -p:Version=<version> -p:NativeDir=<folder>/, the folder
holding win-x64/, win-arm64/, linux-x64/, linux-arm64/, each with
that release's library and THIRD-PARTY.txt (.github/workflows/ci.yml). -->
<PropertyGroup>
<Version>0.4.0</Version>
<Authors>Herwin Bozet (NibblePoker)</Authors>
<Description>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.</Description>
<PackageLicenseExpression>CC0-1.0</PackageLicenseExpression>
<PackageProjectUrl>https://github.com/aziascreations/BakaShrot</PackageProjectUrl>
<RepositoryUrl>https://github.com/aziascreations/BakaShrot</RepositoryUrl>
<PackageTags>bakashrot;messages;replication;sqlite</PackageTags>
</PropertyGroup>
<ItemGroup Condition="'$(NativeDir)' != ''">
<!-- .NET Core and .NET pick theirs from runtimes/<rid>/native/. -->
<None Include="$(NativeDir)win-x64/bakashrot.dll" Pack="true" PackagePath="runtimes/win-x64/native/" />
<None Include="$(NativeDir)win-arm64/bakashrot.dll" Pack="true" PackagePath="runtimes/win-arm64/native/" />
<None Include="$(NativeDir)linux-x64/libbakashrot.so" Pack="true" PackagePath="runtimes/linux-x64/native/" />
<None Include="$(NativeDir)linux-arm64/libbakashrot.so" Pack="true" PackagePath="runtimes/linux-arm64/native/" />
<!-- The crates built into each. -->
<None Include="$(NativeDir)win-x64/THIRD-PARTY.txt" Pack="true" PackagePath="licenses/win-x64/" />
<None Include="$(NativeDir)win-arm64/THIRD-PARTY.txt" Pack="true" PackagePath="licenses/win-arm64/" />
<None Include="$(NativeDir)linux-x64/THIRD-PARTY.txt" Pack="true" PackagePath="licenses/linux-x64/" />
<None Include="$(NativeDir)linux-arm64/THIRD-PARTY.txt" Pack="true" PackagePath="licenses/linux-arm64/" />
<!-- .NET Framework doesn't: this copies it next to the app. -->
<None Include="NibblePoker.BakaShrot.Client.targets" Pack="true" PackagePath="build/net35/" />
</ItemGroup>
</Project>
@@ -0,0 +1,13 @@
<Project>
<!-- .NET Framework apps (packages.config or PackageReference): the native
library next to the app, as .NET Framework ignores runtimes/. It's
64-bit: ARM64's when the app is built for ARM64, x64's otherwise. -->
<PropertyGroup>
<BakaShrotRuntime Condition="'$(BakaShrotRuntime)' == '' And '$(PlatformTarget)' == 'ARM64'">win-arm64</BakaShrotRuntime>
<BakaShrotRuntime Condition="'$(BakaShrotRuntime)' == ''">win-x64</BakaShrotRuntime>
</PropertyGroup>
<ItemGroup>
<None Include="$(MSBuildThisFileDirectory)../../runtimes/$(BakaShrotRuntime)/native/bakashrot.dll"
Link="bakashrot.dll" CopyToOutputDirectory="PreserveNewest" Visible="false" />
</ItemGroup>
</Project>
@@ -1,12 +1,13 @@
;{- Code Header ;{- Code Header
; ==- Basic Info -================================ ; ==- Basic Info -================================
; Name: BakaShrot_Client_Prototypes.pbi ; Name: BakaShrot_Client_Prototypes.pbi
; Version: 0.0.1 ; Version: 0.4.0
; Author: Herwin Bozet (NibblePoker) ; Author: Herwin Bozet (NibblePoker)
; ;
; ==- Compatibility -============================= ; ==- Compatibility -=============================
; Tested compiler versions: ; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64) ; * PureBasic 5.73 LTS (Windows x64)
; * PureBasic 6.41 (Windows x64)
; ;
; ==- Links -===================================== ; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot ; GitHub: https://github.com/aziascreations/BakaShrot
@@ -18,65 +19,94 @@
; Include this in an app to use bakashrot.dll (libbakashrot.so on Linux): ; Include this in an app to use bakashrot.dll (libbakashrot.so on Linux):
; XIncludeFile "BakaShrot_Client_Prototypes.pbi" ; XIncludeFile "BakaShrot_Client_Prototypes.pbi"
; If BakaShrot_LoadClient("bakashrot.dll") ; If BakaShrot_LoadClient("bakashrot.dll")
; BakaShrot_SetCaCertificate("ca.crt") ; a file, or PEM text ; Client = BakaShrot_CreateClient()
; BakaShrot_SetCertificate("kitchen.crt") ; BakaShrot_SetCaCertificate(Client, "ca.crt") ; a file, or PEM text
; BakaShrot_SetPrivateKey("kitchen.key") ; BakaShrot_SetCertificate(Client, "kitchen.crt")
; If BakaShrot_Connect("10.0.0.2", 7000) ; BakaShrot_SetPrivateKey(Client, "kitchen.key")
; BakaShrot_PushMessageTo("logs", ~"{\"temp\": 21}") ; If BakaShrot_Connect(Client, "10.0.0.2", 7000)
; BakaShrot_PushMessageTo(Client, "logs", ~"{\"temp\": 21}")
; ... ; ...
; EndIf ; EndIf
; BakaShrot_FreeClient(Client)
; BakaShrot_UnloadClient() ; BakaShrot_UnloadClient()
; EndIf ; EndIf
; ;
; Every function but BakaShrot_CreateClient() takes the client first (a
; quad). Make as many as needed: each has its own connection and errors.
;
; docs/client.md has what each function does (and ; docs/client.md has what each function does (and
; bindings/c/bakashrot.h, generated from the DLL). The string ; bindings/c/bakashrot.h, generated from the DLL). The string
; functions are mapped to the DLL's W (UTF-16) variants. After a failed ; functions are mapped to the DLL's W (UTF-16) variants. After a failed
; call, BakaShrot_GetLastError() tells why: the codes and what to do about ; call, BakaShrot_GetLastError(Client) tells why: the codes and what to do
; each are in BakaShrot_ErrorCodes.pbi, next to this file (included below), ; about each are in BakaShrot_ErrorCodes.pbi, next to this file (included
; BakaShrot_ErrorName() names them; BakaShrot_GetRefusalReasonString() says ; below), BakaShrot_ErrorName() names them;
; why in words. _GetNamesList() is ; BakaShrot_GetRefusalReasonString(Client) says why in words.
; {"kind":"topic","names":[...],"truncated":false}. ; _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" XIncludeFile "BakaShrot_ErrorCodes.pbi"
PrototypeC.l BakaShrot_GetLastError_Prototype() PrototypeC.q BakaShrot_CreateClient_Prototype()
PrototypeC.i BakaShrot_GetRefusalReason_Prototype(*Buffer, BufferSize.i) PrototypeC.i BakaShrot_FreeClient_Prototype(Client.q)
PrototypeC.i BakaShrot_SetCaCertificate_Prototype(Certificate.p-unicode) PrototypeC.l BakaShrot_GetLastError_Prototype(Client.q)
PrototypeC.i BakaShrot_SetCertificate_Prototype(Certificate.p-unicode) PrototypeC.i BakaShrot_GetRefusalReason_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.i BakaShrot_SetPrivateKey_Prototype(PrivateKey.p-unicode) PrototypeC.i BakaShrot_SetCaCertificate_Prototype(Client.q, Certificate.p-unicode)
PrototypeC.i BakaShrot_SetCrl_Prototype(Crl.p-unicode) PrototypeC.i BakaShrot_SetCertificate_Prototype(Client.q, Certificate.p-unicode)
PrototypeC.i BakaShrot_Connect_Prototype(Host.p-unicode, Port.l) PrototypeC.i BakaShrot_SetPrivateKey_Prototype(Client.q, PrivateKey.p-unicode)
PrototypeC.i BakaShrot_IsConnected_Prototype() PrototypeC.i BakaShrot_SetCrl_Prototype(Client.q, Crl.p-unicode)
PrototypeC.i BakaShrot_Disconnect_Prototype() PrototypeC.i BakaShrot_Connect_Prototype(Client.q, Host.p-unicode, Port.l)
PrototypeC.i BakaShrot_GetNode_Prototype(*Buffer, BufferSize.i) PrototypeC.i BakaShrot_IsConnected_Prototype(Client.q)
PrototypeC.q BakaShrot_PushMessageTo_Prototype(Topic.p-unicode, JsonData.p-unicode) PrototypeC.i BakaShrot_Disconnect_Prototype(Client.q)
PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Topic.p-unicode, Node.p-unicode) PrototypeC.i BakaShrot_Ping_Prototype(Client.q)
PrototypeC.l BakaShrot_GetMessages_Prototype(Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l) PrototypeC.i BakaShrot_SetAnswerTimeout_Prototype(Client.q, Milliseconds.q)
PrototypeC.l BakaShrot_GetMessageCount_Prototype() PrototypeC.q BakaShrot_GetAnswerTimeout_Prototype(Client.q)
PrototypeC.i BakaShrot_SelectMessage_Prototype(Index.l) PrototypeC.i BakaShrot_GetNode_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.i BakaShrot_HasMoreMessages_Prototype() PrototypeC.q BakaShrot_PushMessageTo_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode)
PrototypeC.q BakaShrot_GetMessageId_Prototype() PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Client.q, Topic.p-unicode, Node.p-unicode)
PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype() PrototypeC.l BakaShrot_GetMessages_Prototype(Client.q, Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l)
PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype() PrototypeC.l BakaShrot_GetMessageCount_Prototype(Client.q)
PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype() PrototypeC.i BakaShrot_SelectMessage_Prototype(Client.q, Index.l)
PrototypeC.i BakaShrot_GetMessageData_Prototype(*Buffer, BufferSize.i) PrototypeC.i BakaShrot_HasMoreMessages_Prototype(Client.q)
PrototypeC.i BakaShrot_GetMessageTopic_Prototype(*Buffer, BufferSize.i) PrototypeC.q BakaShrot_GetMessageId_Prototype(Client.q)
PrototypeC.i BakaShrot_GetMessageNode_Prototype(*Buffer, BufferSize.i) PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype(Client.q)
PrototypeC.l BakaShrot_ListTopics_Prototype() PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype(Client.q)
PrototypeC.l BakaShrot_ListNodes_Prototype() PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype(Client.q)
PrototypeC.i BakaShrot_GetNamesList_Prototype(*Buffer, BufferSize.i) PrototypeC.i BakaShrot_GetMessageData_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.i BakaShrot_Query_Prototype(Sql.p-unicode) PrototypeC.i BakaShrot_GetMessageTopic_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.i BakaShrot_GetQueryResult_Prototype(*Buffer, BufferSize.i) PrototypeC.i BakaShrot_GetMessageNode_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode) ; Kind 1 topics, 2 nodes; Topics and Nodes a name or a pattern, "" for any.
PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Topic.p-unicode, JsonData.p-unicode, *Data, Size.q) PrototypeC.l BakaShrot_ListNames_Prototype(Client.q, Kind.l, Topics.p-unicode, Nodes.p-unicode)
PrototypeC.q BakaShrot_SaveAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode) PrototypeC.i BakaShrot_GetNamesListAsJson_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.q BakaShrot_LoadAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q) PrototypeC.i BakaShrot_Query_Prototype(Client.q, Sql.p-unicode)
PrototypeC.q BakaShrot_GetAttachmentData_Prototype(*Buffer, BufferSize.q) PrototypeC.i BakaShrot_GetQueryResultAsJson_Prototype(Client.q, *Buffer, BufferSize.i)
PrototypeC.i BakaShrot_FreeAttachmentData_Prototype() 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_GetLastError.BakaShrot_GetLastError_Prototype
Global BakaShrot_GetRefusalReason.BakaShrot_GetRefusalReason_Prototype Global BakaShrot_GetRefusalReason.BakaShrot_GetRefusalReason_Prototype
Global BakaShrot_SetCaCertificate.BakaShrot_SetCaCertificate_Prototype Global BakaShrot_SetCaCertificate.BakaShrot_SetCaCertificate_Prototype
@@ -86,6 +116,9 @@ Global BakaShrot_SetCrl.BakaShrot_SetCrl_Prototype
Global BakaShrot_Connect.BakaShrot_Connect_Prototype Global BakaShrot_Connect.BakaShrot_Connect_Prototype
Global BakaShrot_IsConnected.BakaShrot_IsConnected_Prototype Global BakaShrot_IsConnected.BakaShrot_IsConnected_Prototype
Global BakaShrot_Disconnect.BakaShrot_Disconnect_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_GetNode.BakaShrot_GetNode_Prototype
Global BakaShrot_PushMessageTo.BakaShrot_PushMessageTo_Prototype Global BakaShrot_PushMessageTo.BakaShrot_PushMessageTo_Prototype
Global BakaShrot_GetLatestMessageOf.BakaShrot_GetLatestMessageOf_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_GetMessageData.BakaShrot_GetMessageData_Prototype
Global BakaShrot_GetMessageTopic.BakaShrot_GetMessageTopic_Prototype Global BakaShrot_GetMessageTopic.BakaShrot_GetMessageTopic_Prototype
Global BakaShrot_GetMessageNode.BakaShrot_GetMessageNode_Prototype Global BakaShrot_GetMessageNode.BakaShrot_GetMessageNode_Prototype
Global BakaShrot_ListTopics.BakaShrot_ListTopics_Prototype Global BakaShrot_ListNames.BakaShrot_ListNames_Prototype
Global BakaShrot_ListNodes.BakaShrot_ListNodes_Prototype Global BakaShrot_GetNamesListAsJson.BakaShrot_GetNamesListAsJson_Prototype
Global BakaShrot_GetNamesList.BakaShrot_GetNamesList_Prototype
Global BakaShrot_Query.BakaShrot_Query_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_PushMessageWithFile.BakaShrot_PushMessageWithFile_Prototype
Global BakaShrot_PushMessageWithData.BakaShrot_PushMessageWithData_Prototype Global BakaShrot_PushMessageWithData.BakaShrot_PushMessageWithData_Prototype
Global BakaShrot_SaveAttachment.BakaShrot_SaveAttachment_Prototype Global BakaShrot_SaveAttachment.BakaShrot_SaveAttachment_Prototype
@@ -151,6 +195,8 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
BakaShrot_ClientMissing = "" BakaShrot_ClientMissing = ""
; PureBasic strings are UTF-16, so the W variants are used. ; PureBasic strings are UTF-16, so the W variants are used.
BakaShrot_CreateClient = BakaShrot_ClientFunction("BakaShrot_CreateClient")
BakaShrot_FreeClient = BakaShrot_ClientFunction("BakaShrot_FreeClient")
BakaShrot_GetLastError = BakaShrot_ClientFunction("BakaShrot_GetLastError") BakaShrot_GetLastError = BakaShrot_ClientFunction("BakaShrot_GetLastError")
BakaShrot_GetRefusalReason = BakaShrot_ClientFunction("BakaShrot_GetRefusalReasonW") BakaShrot_GetRefusalReason = BakaShrot_ClientFunction("BakaShrot_GetRefusalReasonW")
BakaShrot_SetCaCertificate = BakaShrot_ClientFunction("BakaShrot_SetCaCertificateW") BakaShrot_SetCaCertificate = BakaShrot_ClientFunction("BakaShrot_SetCaCertificateW")
@@ -160,6 +206,9 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
BakaShrot_Connect = BakaShrot_ClientFunction("BakaShrot_ConnectW") BakaShrot_Connect = BakaShrot_ClientFunction("BakaShrot_ConnectW")
BakaShrot_IsConnected = BakaShrot_ClientFunction("BakaShrot_IsConnected") BakaShrot_IsConnected = BakaShrot_ClientFunction("BakaShrot_IsConnected")
BakaShrot_Disconnect = BakaShrot_ClientFunction("BakaShrot_Disconnect") 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_GetNode = BakaShrot_ClientFunction("BakaShrot_GetNodeW")
BakaShrot_PushMessageTo = BakaShrot_ClientFunction("BakaShrot_PushMessageToW") BakaShrot_PushMessageTo = BakaShrot_ClientFunction("BakaShrot_PushMessageToW")
BakaShrot_GetLatestMessageOf = BakaShrot_ClientFunction("BakaShrot_GetLatestMessageOfW") BakaShrot_GetLatestMessageOf = BakaShrot_ClientFunction("BakaShrot_GetLatestMessageOfW")
@@ -174,11 +223,22 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
BakaShrot_GetMessageData = BakaShrot_ClientFunction("BakaShrot_GetMessageDataW") BakaShrot_GetMessageData = BakaShrot_ClientFunction("BakaShrot_GetMessageDataW")
BakaShrot_GetMessageTopic = BakaShrot_ClientFunction("BakaShrot_GetMessageTopicW") BakaShrot_GetMessageTopic = BakaShrot_ClientFunction("BakaShrot_GetMessageTopicW")
BakaShrot_GetMessageNode = BakaShrot_ClientFunction("BakaShrot_GetMessageNodeW") BakaShrot_GetMessageNode = BakaShrot_ClientFunction("BakaShrot_GetMessageNodeW")
BakaShrot_ListTopics = BakaShrot_ClientFunction("BakaShrot_ListTopics") BakaShrot_ListNames = BakaShrot_ClientFunction("BakaShrot_ListNamesW")
BakaShrot_ListNodes = BakaShrot_ClientFunction("BakaShrot_ListNodes") BakaShrot_GetNamesListAsJson = BakaShrot_ClientFunction("BakaShrot_GetNamesListAsJsonW")
BakaShrot_GetNamesList = BakaShrot_ClientFunction("BakaShrot_GetNamesListW")
BakaShrot_Query = BakaShrot_ClientFunction("BakaShrot_QueryW") BakaShrot_Query = BakaShrot_ClientFunction("BakaShrot_QueryW")
BakaShrot_GetQueryResult = BakaShrot_ClientFunction("BakaShrot_GetQueryResultW") 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_PushMessageWithFile = BakaShrot_ClientFunction("BakaShrot_PushMessageWithFileW")
BakaShrot_PushMessageWithData = BakaShrot_ClientFunction("BakaShrot_PushMessageWithDataW") BakaShrot_PushMessageWithData = BakaShrot_ClientFunction("BakaShrot_PushMessageWithDataW")
BakaShrot_SaveAttachment = BakaShrot_ClientFunction("BakaShrot_SaveAttachmentW") BakaShrot_SaveAttachment = BakaShrot_ClientFunction("BakaShrot_SaveAttachmentW")
@@ -194,18 +254,41 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
EndProcedure EndProcedure
; Calls a string getter of the DLL (Getter(*Buffer, BufferSize)) and ; Calls a client's string getter (Getter(Client, *Buffer, BufferSize)) and
; returns the string: asks for the size, then copies. ; returns the string: asks for the size, then copies.
PrototypeC.i BakaShrot_StringGetter_Prototype(*Buffer, BufferSize.i) PrototypeC.i BakaShrot_StringGetter_Prototype(Client.q, *Buffer, BufferSize.i)
Procedure.s BakaShrot_GetString(Getter.BakaShrot_StringGetter_Prototype) Procedure.s BakaShrot_GetString(Client.q, Getter.BakaShrot_StringGetter_Prototype)
Protected *Buffer, BufferSize.i, Text.s Protected *Buffer, BufferSize.i, Text.s
BufferSize = Getter(0, 0) BufferSize = Getter(Client, 0, 0)
If BufferSize <= 0
ProcedureReturn ""
EndIf
*Buffer = AllocateMemory(BufferSize) *Buffer = AllocateMemory(BufferSize)
If Not *Buffer If Not *Buffer
ProcedureReturn "" ProcedureReturn ""
EndIf EndIf
Getter(*Buffer, BufferSize) Getter(Client, *Buffer, BufferSize)
Text = PeekS(*Buffer, -1, #PB_Unicode)
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) Text = PeekS(*Buffer, -1, #PB_Unicode)
FreeMemory(*Buffer) FreeMemory(*Buffer)
@@ -213,32 +296,44 @@ Procedure.s BakaShrot_GetString(Getter.BakaShrot_StringGetter_Prototype)
EndProcedure EndProcedure
; The string getters, as strings. ; The string getters, as strings.
Procedure.s BakaShrot_GetRefusalReasonString() Procedure.s BakaShrot_GetRefusalReasonString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetRefusalReason) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetRefusalReason)
EndProcedure EndProcedure
Procedure.s BakaShrot_GetNodeString() Procedure.s BakaShrot_GetNodeString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetNode) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetNode)
EndProcedure EndProcedure
Procedure.s BakaShrot_GetMessageDataString() Procedure.s BakaShrot_GetMessageDataString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageData) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageData)
EndProcedure EndProcedure
Procedure.s BakaShrot_GetMessageTopicString() Procedure.s BakaShrot_GetMessageTopicString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageTopic) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageTopic)
EndProcedure EndProcedure
Procedure.s BakaShrot_GetMessageNodeString() Procedure.s BakaShrot_GetMessageNodeString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageNode) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageNode)
EndProcedure EndProcedure
Procedure.s BakaShrot_GetNamesListString() Procedure.s BakaShrot_GetNamesListAsJsonString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetNamesList) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetNamesListAsJson)
EndProcedure EndProcedure
Procedure.s BakaShrot_GetQueryResultString() Procedure.s BakaShrot_GetQueryResultAsJsonString(Client.q)
ProcedureReturn BakaShrot_GetString(BakaShrot_GetQueryResult) 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 EndProcedure
@@ -246,18 +341,29 @@ EndProcedure
; IDE), not when it's included by an app. ; IDE), not when it's included by an app.
; ClientExample <DllPath> <CaFile> <CertificateFile> <KeyFile> <Host> <Port> ; ClientExample <DllPath> <CaFile> <CertificateFile> <KeyFile> <Host> <Port>
; Pushes a message to "logs", reads it back, pushes one with an ; Pushes a message to "logs", reads it back, pushes one with an
; attachment and reads that back, lists the topics. ; attachment and reads that back, lists the topics; then a second client
; connected at the same time reads it too.
CompilerIf #PB_Compiler_IsMainFile CompilerIf #PB_Compiler_IsMainFile
Define Id.q, Size.q, *Attachment, *Copy Define Client.q, Second.q, Enum.q, Id.q, Size.q, *Attachment, *Copy
; Prints why the last call failed, then ends. ; Prints why a client's last call failed, then ends.
Procedure Failed(What.s) Procedure Failed(Client.q, What.s)
PrintN(What + " failed: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString()) PrintN(What + " failed: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client)) + ", " + BakaShrot_GetRefusalReasonString(Client))
BakaShrot_UnloadClient() BakaShrot_UnloadClient()
End 1 End 1
EndProcedure EndProcedure
; A new client, connected with the certificates given.
Procedure.q Connected(What.s)
Protected Client.q = BakaShrot_CreateClient()
If Not BakaShrot_SetCaCertificate(Client, ProgramParameter(1)) : Failed(Client, What + ": setting the CA's certificate") : EndIf
If Not BakaShrot_SetCertificate(Client, ProgramParameter(2)) : Failed(Client, What + ": setting the certificate") : EndIf
If Not BakaShrot_SetPrivateKey(Client, ProgramParameter(3)) : Failed(Client, What + ": setting the private key") : EndIf
If Not BakaShrot_Connect(Client, ProgramParameter(4), Val(ProgramParameter(5))) : Failed(Client, What + ": connecting") : EndIf
ProcedureReturn Client
EndProcedure
OpenConsole() OpenConsole()
If CountProgramParameters() < 6 If CountProgramParameters() < 6
PrintN("Usage: ClientExample <DllPath> <CaFile> <CertificateFile> <KeyFile> <Host> <Port>") PrintN("Usage: ClientExample <DllPath> <CaFile> <CertificateFile> <KeyFile> <Host> <Port>")
@@ -269,28 +375,25 @@ CompilerIf #PB_Compiler_IsMainFile
End 1 End 1
EndIf EndIf
If Not BakaShrot_SetCaCertificate(ProgramParameter(1)) : Failed("Setting the CA's certificate") : EndIf Client = Connected("The client")
If Not BakaShrot_SetCertificate(ProgramParameter(2)) : Failed("Setting the certificate") : EndIf PrintN("Client #" + Str(Client) + " connected as " + BakaShrot_GetNodeString(Client))
If Not BakaShrot_SetPrivateKey(ProgramParameter(3)) : Failed("Setting the private key") : EndIf
If Not BakaShrot_Connect(ProgramParameter(4), Val(ProgramParameter(5))) : Failed("Connecting") : EndIf
PrintN("Connected as " + BakaShrot_GetNodeString())
Id = BakaShrot_PushMessageTo("logs", ~"{\"from\": \"PureBasic\", \"text\": \"hello\"}") Id = BakaShrot_PushMessageTo(Client, "logs", ~"{\"from\": \"PureBasic\", \"text\": \"hello\"}")
If Id < 1 : Failed("Pushing") : EndIf If Id < 1 : Failed(Client, "Pushing") : EndIf
PrintN("Pushed #" + Str(Id)) PrintN("Pushed #" + Str(Id))
If Not BakaShrot_GetLatestMessageOf("logs", BakaShrot_GetNodeString()) : Failed("Reading") : EndIf If Not BakaShrot_GetLatestMessageOf(Client, "logs", BakaShrot_GetNodeString(Client)) : Failed(Client, "Reading") : EndIf
PrintN("Latest: #" + Str(BakaShrot_GetMessageId()) + " " + BakaShrot_GetMessageDataString()) PrintN("Latest: #" + Str(BakaShrot_GetMessageId(Client)) + " " + BakaShrot_GetMessageDataString(Client))
*Attachment = AllocateMemory(3000) *Attachment = AllocateMemory(3000)
FillMemory(*Attachment, 3000, 42, #PB_Byte) FillMemory(*Attachment, 3000, 42, #PB_Byte)
Id = BakaShrot_PushMessageWithData("logs", ~"{\"photo\": 1}", *Attachment, 3000) Id = BakaShrot_PushMessageWithData(Client, "logs", ~"{\"photo\": 1}", *Attachment, 3000)
If Id < 1 : Failed("Pushing an attachment") : EndIf If Id < 1 : Failed(Client, "Pushing an attachment") : EndIf
Size = BakaShrot_LoadAttachment("logs", BakaShrot_GetNodeString(), Id) Size = BakaShrot_LoadAttachment(Client, "logs", BakaShrot_GetNodeString(Client), Id)
If Size < 0 : Failed("Reading the attachment") : EndIf If Size < 0 : Failed(Client, "Reading the attachment") : EndIf
*Copy = AllocateMemory(Size) *Copy = AllocateMemory(Size)
BakaShrot_GetAttachmentData(*Copy, Size) BakaShrot_GetAttachmentData(Client, *Copy, Size)
BakaShrot_FreeAttachmentData() BakaShrot_FreeAttachmentData(Client)
If CompareMemory(*Attachment, *Copy, 3000) If CompareMemory(*Attachment, *Copy, 3000)
PrintN("Pushed #" + Str(Id) + " with " + Str(Size) + " bytes, read back the same") PrintN("Pushed #" + Str(Id) + " with " + Str(Size) + " bytes, read back the same")
Else Else
@@ -299,15 +402,36 @@ CompilerIf #PB_Compiler_IsMainFile
EndIf EndIf
FreeMemory(*Attachment) : FreeMemory(*Copy) FreeMemory(*Attachment) : FreeMemory(*Copy)
If BakaShrot_ListTopics() < 0 : Failed("Listing") : EndIf If BakaShrot_ListNames(Client, 1, "", "") < 0 : Failed(Client, "Listing") : EndIf
PrintN("Topics: " + BakaShrot_GetNamesListString()) 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 If BakaShrot_PushMessageTo(Client, "nothing", "{}") < 0
PrintN("A push to a topic it may not push to: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString()) PrintN("A push to a topic it may not push to: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client)) + ", " + BakaShrot_GetRefusalReasonString(Client))
EndIf EndIf
BakaShrot_Disconnect() ; A second client, connected at the same time.
PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected())) Second = Connected("The second client")
If Not BakaShrot_GetLatestMessageOf(Second, "logs", BakaShrot_GetNodeString(Second)) : Failed(Second, "The second client reading") : EndIf
PrintN("Second client #" + Str(Second) + ", both connected (" + Str(BakaShrot_IsConnected(Client)) + Str(BakaShrot_IsConnected(Second)) + "), its latest: #" + Str(BakaShrot_GetMessageId(Second)))
; Its errors are its own: the first client's last call succeeds, its fails.
BakaShrot_GetLatestMessageOf(Client, "logs", BakaShrot_GetNodeString(Client))
If BakaShrot_PushMessageTo(Second, "nothing", "{}") < 0
PrintN("Its own error: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Second)) + ", the first client's: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client)))
EndIf
BakaShrot_FreeClient(Second)
PrintN("Freed, IsConnected: " + Str(BakaShrot_IsConnected(Second)) + ", its error now: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Second)))
BakaShrot_Disconnect(Client)
PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected(Client)))
BakaShrot_FreeClient(Client)
BakaShrot_UnloadClient() BakaShrot_UnloadClient()
End 0 End 0
+9 -3
View File
@@ -1,12 +1,13 @@
;{- Code Header ;{- Code Header
; ==- Basic Info -================================ ; ==- Basic Info -================================
; Name: BakaShrot_ErrorCodes.pbi ; Name: BakaShrot_ErrorCodes.pbi
; Version: 0.0.1 ; Version: 0.4.0
; Author: Herwin Bozet (NibblePoker) ; Author: Herwin Bozet (NibblePoker)
; ;
; ==- Compatibility -============================= ; ==- Compatibility -=============================
; Tested compiler versions: ; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64) ; * PureBasic 5.73 LTS (Windows x64)
; * PureBasic 6.41 (Windows x64)
; ;
; ==- Links -===================================== ; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot ; GitHub: https://github.com/aziascreations/BakaShrot
@@ -16,7 +17,7 @@
; BakaShrot error codes ; BakaShrot error codes
; ;
; What BakaShrot_GetLastError() returns after a failed call of the client DLL ; 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). ; crates/bakashrot-proto/src/error.rs).
; The Python client has them in bakashrot.ErrorCode. Shipped next to ; The Python client has them in bakashrot.ErrorCode. Shipped next to
; BakaShrot_Client_Prototypes.pbi, which includes it. ; BakaShrot_Client_Prototypes.pbi, which includes it.
@@ -30,7 +31,8 @@
; reconnect, then retry: NotConnected, ConnectFailed, ConnectionLost, ; reconnect, then retry: NotConnected, ConnectFailed, ConnectionLost,
; ProtocolError (the connection is closed) ; ProtocolError (the connection is closed)
; retry later: NotReady (an attachment still on its way), ; 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 ; fix the certificates or
; the server's config: AuthRejected, ServerNotVerified, NotAllowed, ; the server's config: AuthRejected, ServerNotVerified, NotAllowed,
; UnknownName, VersionMismatch ; UnknownName, VersionMismatch
@@ -67,6 +69,9 @@
#BakaShrot_Refused_QueryFailed = 9 #BakaShrot_Refused_QueryFailed = 9
; The server couldn't store or read something: its database failed. ; The server couldn't store or read something: its database failed.
#BakaShrot_Refused_ServerError = 10 #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. ; The highest a refusal can have, anything above is the client's own.
#BakaShrot_Refused_Max = 99 #BakaShrot_Refused_Max = 99
@@ -119,6 +124,7 @@ Procedure.s BakaShrot_ErrorName(Code.l)
Case #BakaShrot_Refused_DataMismatch : ProcedureReturn "DataMismatch" Case #BakaShrot_Refused_DataMismatch : ProcedureReturn "DataMismatch"
Case #BakaShrot_Refused_QueryFailed : ProcedureReturn "QueryFailed" Case #BakaShrot_Refused_QueryFailed : ProcedureReturn "QueryFailed"
Case #BakaShrot_Refused_ServerError : ProcedureReturn "ServerError" Case #BakaShrot_Refused_ServerError : ProcedureReturn "ServerError"
Case #BakaShrot_Refused_QueryTimedOut : ProcedureReturn "QueryTimedOut"
Case #BakaShrot_Error_NotConnected : ProcedureReturn "NotConnected" Case #BakaShrot_Error_NotConnected : ProcedureReturn "NotConnected"
Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "ConnectFailed" Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "ConnectFailed"
Case #BakaShrot_Error_AuthRejected : ProcedureReturn "AuthRejected" Case #BakaShrot_Error_AuthRejected : ProcedureReturn "AuthRejected"
+178 -96
View File
@@ -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()) print(message.id, message.json())
Who the client is comes from its certificate, issued by the CA the server 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 do. client.toml says where the server is and where the certificates are
(docs/client.md): (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 A push whose answer was lost (ConnectionLostError) may have been stored all
the same: pushed again, it's stored twice. Delivery is at least once. the same: pushed again, it's stored twice. Delivery is at least once.
The DLL holds a single connection per process: only one Client may be Each Client has its own client in the DLL, so several can be connected at
connected at a time. Calls are serialized with a lock, so a Client can be once, from different threads. A Client's own calls are serialized with a
shared between threads, one request at a time. lock: one can be shared between threads, one request at a time.
The DLL is looked for, in order: the dll_path given, the BAKASHROT_DLL The DLL is looked for, in order: the dll_path given, the BAKASHROT_DLL
environment variable, next to this file, then in the current directory. environment variable, next to this file, then in the current directory.
@@ -58,17 +58,22 @@ from dataclasses import dataclass, field
from datetime import datetime, timezone from datetime import datetime, timezone
from typing import Any, Iterator, Optional, Union from typing import Any, Iterator, Optional, Union
__version__ = "0.3.0" __version__ = "0.4.0"
__all__ = [ __all__ = [
"Client", "Message", "MessagesPage", "NamesList", "Client", "Message", "MessagesPage", "NamesList",
"BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode", "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. # The protocol's: crates/bakashrot-proto/src/limits.rs.
MAX_GET_MESSAGES = 10000 MAX_GET_MESSAGES = 10000
MAX_MESSAGE_SIZE = 16 * 1024 * 1024 - 4096 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" 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 DATA_MISMATCH = 8 # an upload that doesn't match its SHA-256
QUERY_FAILED = 9 # the SQL failed QUERY_FAILED = 9 # the SQL failed
SERVER_ERROR = 10 # the server's database failed: retry later 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. # The client's own.
NOT_CONNECTED = 100 # never connected, or closed or lost before NOT_CONNECTED = 100 # never connected, or closed or lost before
CONNECT_FAILED = 101 # nothing answers at that host and port 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 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: def _name(value: str) -> bytes:
if not isinstance(value, str): if not isinstance(value, str):
raise TypeError(f"a topic or node is a name, not {value!r}") 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: def _find_dll(dll_path: Optional[str]) -> str:
@@ -237,41 +251,46 @@ class _Dll:
self.path = path self.path = path
I, L, Q, P, S = ctypes.c_ssize_t, ctypes.c_int32, ctypes.c_int64, ctypes.c_char_p, ctypes.c_void_p I, L, Q, P, S = ctypes.c_ssize_t, ctypes.c_int32, ctypes.c_int64, ctypes.c_char_p, ctypes.c_void_p
H = Q # a client's handle
signatures = { signatures = {
"BakaShrot_GetLastError": (L, []), "BakaShrot_CreateClient": (Q, []),
"BakaShrot_GetRefusalReasonA": (I, [S, I]), "BakaShrot_FreeClient": (I, [H]),
"BakaShrot_SetCaCertificateA": (I, [P]), "BakaShrot_GetLastError": (L, [H]),
"BakaShrot_SetCertificateA": (I, [P]), "BakaShrot_GetRefusalReasonA": (I, [H, S, I]),
"BakaShrot_SetPrivateKeyA": (I, [P]), "BakaShrot_SetCaCertificateA": (I, [H, P]),
"BakaShrot_SetCrlA": (I, [P]), "BakaShrot_SetCertificateA": (I, [H, P]),
"BakaShrot_ConnectA": (I, [P, L]), "BakaShrot_SetPrivateKeyA": (I, [H, P]),
"BakaShrot_IsConnected": (I, []), "BakaShrot_SetCrlA": (I, [H, P]),
"BakaShrot_Disconnect": (I, []), "BakaShrot_ConnectA": (I, [H, P, L]),
"BakaShrot_GetNodeA": (I, [S, I]), "BakaShrot_IsConnected": (I, [H]),
"BakaShrot_PushMessageToA": (Q, [P, P]), "BakaShrot_Disconnect": (I, [H]),
"BakaShrot_GetLatestMessageOfA": (I, [P, P]), "BakaShrot_Ping": (I, [H]),
"BakaShrot_GetMessagesA": (L, [P, P, Q, L]), "BakaShrot_SetAnswerTimeout": (I, [H, Q]),
"BakaShrot_GetMessageCount": (L, []), "BakaShrot_GetAnswerTimeout": (Q, [H]),
"BakaShrot_SelectMessage": (I, [L]), "BakaShrot_GetNodeA": (I, [H, S, I]),
"BakaShrot_HasMoreMessages": (I, []), "BakaShrot_PushMessageToA": (Q, [H, P, P]),
"BakaShrot_GetMessageId": (Q, []), "BakaShrot_GetLatestMessageOfA": (I, [H, P, P]),
"BakaShrot_GetMessagePushedAt": (Q, []), "BakaShrot_GetMessagesA": (L, [H, P, P, Q, L]),
"BakaShrot_GetMessageAttachmentSize": (Q, []), "BakaShrot_GetMessageCount": (L, [H]),
"BakaShrot_IsMessageAttachmentReady": (I, []), "BakaShrot_SelectMessage": (I, [H, L]),
"BakaShrot_GetMessageTopicA": (I, [S, I]), "BakaShrot_HasMoreMessages": (I, [H]),
"BakaShrot_GetMessageNodeA": (I, [S, I]), "BakaShrot_GetMessageId": (Q, [H]),
"BakaShrot_GetMessageDataA": (I, [S, I]), "BakaShrot_GetMessagePushedAt": (Q, [H]),
"BakaShrot_ListTopics": (L, []), "BakaShrot_GetMessageAttachmentSize": (Q, [H]),
"BakaShrot_ListNodes": (L, []), "BakaShrot_IsMessageAttachmentReady": (I, [H]),
"BakaShrot_GetNamesListA": (I, [S, I]), "BakaShrot_GetMessageTopicA": (I, [H, S, I]),
"BakaShrot_QueryA": (I, [P]), "BakaShrot_GetMessageNodeA": (I, [H, S, I]),
"BakaShrot_GetQueryResultA": (I, [S, I]), "BakaShrot_GetMessageDataA": (I, [H, S, I]),
"BakaShrot_PushMessageWithFileA": (Q, [P, P, P]), "BakaShrot_ListNamesA": (L, [H, L, P, P]),
"BakaShrot_PushMessageWithDataA": (Q, [P, P, P, Q]), "BakaShrot_GetNamesListAsJsonA": (I, [H, S, I]),
"BakaShrot_SaveAttachmentA": (Q, [P, P, Q, P]), "BakaShrot_QueryA": (I, [H, P]),
"BakaShrot_LoadAttachmentA": (Q, [P, P, Q]), "BakaShrot_GetQueryResultAsJsonA": (I, [H, S, I]),
"BakaShrot_GetAttachmentData": (Q, [S, Q]), "BakaShrot_PushMessageWithFileA": (Q, [H, P, P, P]),
"BakaShrot_FreeAttachmentData": (I, []), "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(): for name, (restype, argtypes) in signatures.items():
try: try:
@@ -280,15 +299,16 @@ class _Dll:
raise BakaShrotError(f"{path} has no {name}, is it an older build?", ErrorCode.INTERNAL) from error raise BakaShrotError(f"{path} has no {name}, is it an older build?", ErrorCode.INTERNAL) from error
function.restype = restype function.restype = restype
function.argtypes = argtypes function.argtypes = argtypes
# BakaShrot_PushMessageToA as PushMessageToA.
setattr(self, name[len("BakaShrot_"):], function) setattr(self, name[len("BakaShrot_"):], function)
def string(self, getter) -> str: def string(self, getter, handle: int) -> str:
"""Calls a string getter: asks for the size, then copies (UTF-8).""" """Calls a client's string getter: asks for the size, then copies (UTF-8)."""
size = getter(None, 0) size = getter(handle, None, 0)
if size <= 1: if size <= 1:
return "" return ""
buffer = ctypes.create_string_buffer(size) buffer = ctypes.create_string_buffer(size)
getter(buffer, size) getter(handle, buffer, size)
return buffer.raw[: size - 1].decode("utf-8") return buffer.raw[: size - 1].decode("utf-8")
@@ -309,8 +329,6 @@ class Client:
its private key, the CA's CRL (servers it revokes are refused). its private key, the CA's CRL (servers it revokes are refused).
""" """
_connected_client: Optional["Client"] = None
def __init__(self, server: str, ca: str, certificate: str, key: str, crl: Optional[str] = None, def __init__(self, server: str, ca: str, certificate: str, key: str, crl: Optional[str] = None,
dll_path: Optional[str] = None): dll_path: Optional[str] = None):
self._dll = _Dll.get(dll_path) self._dll = _Dll.get(dll_path)
@@ -321,6 +339,9 @@ class Client:
self.key = os.fspath(key) self.key = os.fspath(key)
self.crl = os.fspath(crl) if crl else None self.crl = os.fspath(crl) if crl else None
self.node = "" self.node = ""
self._answer_timeout = ANSWER_TIMEOUT_SECONDS
# Its client in the DLL, from connect() to close().
self._handle: Optional[int] = None
@classmethod @classmethod
def from_file(cls, path: Union[str, os.PathLike], dll_path: Optional[str] = None) -> "Client": def from_file(cls, path: Union[str, os.PathLike], dll_path: Optional[str] = None) -> "Client":
@@ -360,34 +381,69 @@ class Client:
def connect(self) -> "Client": def connect(self) -> "Client":
"""Connects. Raises ConnectionLostError when the server can't be """Connects. Raises ConnectionLostError when the server can't be
reached (CONNECT_FAILED), AuthError when a certificate is refused, reached (CONNECT_FAILED), AuthError when a certificate is refused,
BakaShrotError on a bad setting (INVALID_ARGUMENT, FILE_ERROR) or BakaShrotError on a bad setting (INVALID_ARGUMENT, FILE_ERROR)."""
another Client holding the DLL's connection (ALREADY_CONNECTED)."""
with self._lock: with self._lock:
owner = Client._connected_client
if owner is not None and owner is not self and owner.connected:
raise BakaShrotError("The DLL holds one connection, another Client is connected", ErrorCode.ALREADY_CONNECTED)
if self.connected: if self.connected:
return self return self
dll = self._dll dll = self._dll
if self._handle is None:
handle = dll.CreateClient()
if handle < 1:
raise BakaShrotError("The DLL made no client", ErrorCode.INTERNAL)
self._handle = handle
handle = self._handle
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), for setter, value in ((dll.SetCaCertificateA, self.ca), (dll.SetCertificateA, self.certificate),
(dll.SetPrivateKeyA, self.key), (dll.SetCrlA, self.crl or "")): (dll.SetPrivateKeyA, self.key), (dll.SetCrlA, self.crl or "")):
if not setter(value.encode("utf-8")): if not setter(handle, _text(value)):
raise self._failed("Certificates") 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) raise self._failed(f"Connect to {self.host}:{self.port}", connecting=True)
self.node = dll.string(dll.GetNodeA) self.node = dll.string(dll.GetNodeA, handle)
Client._connected_client = self
return self return self
def close(self) -> None: def close(self) -> None:
"""Disconnects, and frees its client in the DLL. connect() again
reconnects."""
with self._lock: with self._lock:
if Client._connected_client is self: if self._handle is not None:
self._dll.Disconnect() self._dll.FreeClient(self._handle)
Client._connected_client = None self._handle = None
def __del__(self):
try:
self.close()
except Exception: # noqa: BLE001 - the interpreter may be shutting down
pass
@property
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 @property
def connected(self) -> bool: def connected(self) -> bool:
return Client._connected_client is self and bool(self._dll.IsConnected()) handle = self._handle
return handle is not None and bool(self._dll.IsConnected(handle))
def __enter__(self) -> "Client": def __enter__(self) -> "Client":
return self.connect() return self.connect()
@@ -401,15 +457,13 @@ class Client:
def _failed(self, what: str, connecting: bool = False) -> BakaShrotError: def _failed(self, what: str, connecting: bool = False) -> BakaShrotError:
"""The error for a failed call, by the DLL's BakaShrot_GetLastError().""" """The error for a failed call, by the DLL's BakaShrot_GetLastError()."""
code = _error_code(self._dll.GetLastError()) code = _error_code(self._dll.GetLastError(self._handle))
reason = self._dll.string(self._dll.GetRefusalReasonA) reason = self._dll.string(self._dll.GetRefusalReasonA, self._handle)
if connecting and code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED, if connecting and code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED,
ErrorCode.NOT_ALLOWED, ErrorCode.VERSION_MISMATCH): ErrorCode.NOT_ALLOWED, ErrorCode.VERSION_MISMATCH):
return AuthError(f"{what}: {reason}", code) return AuthError(f"{what}: {reason}", code)
if isinstance(code, int) and 1 <= int(code) <= 99: if isinstance(code, int) and 1 <= int(code) <= 99:
return RefusedError(reason, code) return RefusedError(reason, code)
if not self._dll.IsConnected() and Client._connected_client is self:
Client._connected_client = None
name = code.name if isinstance(code, ErrorCode) else str(code) name = code.name if isinstance(code, ErrorCode) else str(code)
message = f"{what} ({name}): {reason or 'failed'}" message = f"{what} ({name}): {reason or 'failed'}"
if code in (ErrorCode.NOT_CONNECTED, ErrorCode.CONNECT_FAILED, ErrorCode.CONNECTION_LOST, ErrorCode.PROTOCOL_ERROR): if code in (ErrorCode.NOT_CONNECTED, ErrorCode.CONNECT_FAILED, ErrorCode.CONNECTION_LOST, ErrorCode.PROTOCOL_ERROR):
@@ -418,6 +472,27 @@ class Client:
# --- Requests ---------------------------------------------------------- # --- 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, def push(self, data: Any, topic: str,
attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int: attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int:
"""Pushes a message into topic, under the client's node. data is """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.""" message is only stored once all of it came."""
if not isinstance(data, str): if not isinstance(data, str):
data = json.dumps(data, separators=(",", ":"), ensure_ascii=False) data = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
encoded = data.encode("utf-8") encoded = _text(data)
if len(encoded) > MAX_MESSAGE_SIZE: 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) raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}", ErrorCode.INVALID_ARGUMENT)
with self._lock: with self._lock:
self._check_connected() self._check_connected()
if attachment is None: if attachment is None:
message_id = self._dll.PushMessageToA(_name(topic), encoded) message_id = self._dll.PushMessageToA(self._handle, _name(topic), encoded)
elif isinstance(attachment, (bytes, bytearray, memoryview)): elif isinstance(attachment, (bytes, bytearray, memoryview)):
raw = bytes(attachment) raw = bytes(attachment)
message_id = self._dll.PushMessageWithDataA(_name(topic), encoded, raw, len(raw)) message_id = self._dll.PushMessageWithDataA(self._handle, _name(topic), encoded, raw, len(raw))
else: else:
path = os.fspath(attachment).encode("utf-8") path = _text(os.fspath(attachment))
message_id = self._dll.PushMessageWithFileA(_name(topic), encoded, path) message_id = self._dll.PushMessageWithFileA(self._handle, _name(topic), encoded, path)
if message_id < 1: if message_id < 1:
raise self._failed("Push") raise self._failed("Push")
return message_id return message_id
@@ -452,15 +527,15 @@ class Client:
(NOT_FOUND) or it isn't on this server yet (NOT_READY).""" (NOT_FOUND) or it isn't on this server yet (NOT_READY)."""
with self._lock: with self._lock:
self._check_connected() self._check_connected()
size = self._dll.LoadAttachmentA(_name(topic), _name(node), int(message_id)) size = self._dll.LoadAttachmentA(self._handle, _name(topic), _name(node), int(message_id))
if size < 0: if size < 0:
raise self._failed("Attachment") raise self._failed("Attachment")
try: try:
buffer = ctypes.create_string_buffer(size) buffer = ctypes.create_string_buffer(size)
self._dll.GetAttachmentData(buffer, size) self._dll.GetAttachmentData(self._handle, buffer, size)
return buffer.raw[:size] return buffer.raw[:size]
finally: finally:
self._dll.FreeAttachmentData() self._dll.FreeAttachmentData(self._handle)
def save_attachment(self, topic: str, node: str, message_id: int, path: Union[str, os.PathLike]) -> int: def save_attachment(self, topic: str, node: str, message_id: int, path: Union[str, os.PathLike]) -> int:
"""Saves the attachment of a message as path (replaced), a part at a """Saves the attachment of a message as path (replaced), a part at a
@@ -468,23 +543,24 @@ class Client:
leaves no file.""" leaves no file."""
with self._lock: with self._lock:
self._check_connected() self._check_connected()
size = self._dll.SaveAttachmentA(_name(topic), _name(node), int(message_id), size = self._dll.SaveAttachmentA(self._handle, _name(topic), _name(node), int(message_id),
os.fspath(path).encode("utf-8")) _text(os.fspath(path)))
if size < 0: if size < 0:
raise self._failed("Attachment") raise self._failed("Attachment")
return size return size
def _current(self) -> Message: def _current(self) -> Message:
dll = self._dll dll, handle = self._dll, self._handle
return Message(dll.GetMessageId(), dll.string(dll.GetMessageTopicA), dll.string(dll.GetMessageNodeA), return Message(dll.GetMessageId(handle), dll.string(dll.GetMessageTopicA, handle),
dll.string(dll.GetMessageDataA), dll.GetMessagePushedAt(), dll.GetMessageAttachmentSize(), dll.string(dll.GetMessageNodeA, handle), dll.string(dll.GetMessageDataA, handle),
bool(dll.IsMessageAttachmentReady())) dll.GetMessagePushedAt(handle), dll.GetMessageAttachmentSize(handle),
bool(dll.IsMessageAttachmentReady(handle)))
def latest(self, topic: str, node: str) -> Optional[Message]: def latest(self, topic: str, node: str) -> Optional[Message]:
"""The latest message of topic/node, None if there's none yet.""" """The latest message of topic/node, None if there's none yet."""
with self._lock: with self._lock:
self._check_connected() self._check_connected()
if not self._dll.GetLatestMessageOfA(_name(topic), _name(node)): if not self._dll.GetLatestMessageOfA(self._handle, _name(topic), _name(node)):
error = self._failed("Latest message") error = self._failed("Latest message")
if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND: if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND:
return None return None
@@ -503,14 +579,14 @@ class Client:
with self._lock: with self._lock:
self._check_connected() self._check_connected()
dll = self._dll dll = self._dll
count = dll.GetMessagesA(_name(topic), _name(node), after, limit) count = dll.GetMessagesA(self._handle, _name(topic), _name(node), after, limit)
if count < 0: if count < 0:
raise self._failed("Get messages") raise self._failed("Get messages")
messages = [] messages = []
for index in range(count): for index in range(count):
dll.SelectMessage(index) dll.SelectMessage(self._handle, index)
messages.append(self._current()) messages.append(self._current())
return MessagesPage(messages, bool(dll.HasMoreMessages())) return MessagesPage(messages, bool(dll.HasMoreMessages(self._handle)))
def iter_messages(self, topic: str, node: str, after: int = 0, batch: int = 1000) -> Iterator[Message]: def iter_messages(self, topic: str, node: str, after: int = 0, batch: int = 1000) -> Iterator[Message]:
"""Every message of topic/node after `after`, asking for batch at a """Every message of topic/node after `after`, asking for batch at a
@@ -526,8 +602,9 @@ class Client:
def follow(self, topic: str, node: str, after: Union[int, str] = "latest", def follow(self, topic: str, node: str, after: Union[int, str] = "latest",
interval: float = 0.5, batch: int = 1000) -> Iterator[Message]: interval: float = 0.5, batch: int = 1000) -> Iterator[Message]:
"""Every message of topic/node after `after`, then new ones as they """Every message of topic/node after `after`, then new ones as they
come, checking every `interval` seconds once caught up. Forever: come, checking every `interval` seconds once caught up (pinging
stop iterating to stop. after="latest" starts with the next new one. 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 Raises ConnectionLostError if the connection fails: nothing
reconnects by itself, connect() again and follow from the last id.""" reconnects by itself, connect() again and follow from the last id."""
if after == "latest": if after == "latest":
@@ -541,22 +618,27 @@ class Client:
if page.messages: if page.messages:
after = page.last_id after = page.last_id
if not page.more: if not page.more:
time.sleep(interval) self._wait(interval)
def list_topics(self) -> NamesList: 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).""" """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") 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: 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).""" """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") 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: with self._lock:
self._check_connected() self._check_connected()
if function() < 0: if self._dll.ListNamesA(self._handle, kind, topic, node) < 0:
raise self._failed(what) raise self._failed(what)
parsed = json.loads(self._dll.string(self._dll.GetNamesListA)) parsed = json.loads(self._dll.string(self._dll.GetNamesListAsJsonA, self._handle))
return NamesList(parsed["kind"], parsed["names"], bool(parsed["truncated"])) return NamesList(parsed["kind"], parsed["names"], bool(parsed["truncated"]))
def query_raw(self, sql: str) -> str: def query_raw(self, sql: str) -> str:
@@ -568,9 +650,9 @@ class Client:
query is refused: RefusedError "malformed JSON".""" query is refused: RefusedError "malformed JSON"."""
with self._lock: with self._lock:
self._check_connected() self._check_connected()
if not self._dll.QueryA(sql.encode("utf-8")): if not self._dll.QueryA(self._handle, _text(sql)):
raise self._failed("Query") 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: def query(self, sql: str) -> list:
"""query_raw(), as a list of dicts, one per row, by column name.""" """query_raw(), as a list of dicts, one per row, by column name."""
+64 -3
View File
@@ -16,7 +16,7 @@ import threading
import time import time
import bakashrot 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] dll_path, folder = sys.argv[1:3]
fails = 0 fails = 0
@@ -138,15 +138,32 @@ with kitchen:
ok, detail = raises(lambda: kitchen.push("x" * (bakashrot.MAX_MESSAGE_SIZE + 1), "logs"), BakaShrotError, "too big", ok, detail = raises(lambda: kitchen.push("x" * (bakashrot.MAX_MESSAGE_SIZE + 1), "logs"), BakaShrotError, "too big",
ErrorCode.INVALID_ARGUMENT) ErrorCode.INVALID_ARGUMENT)
check("A message over the limit: refused before sending", ok, detail) 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") secret_id = kitchen.push({"s": 1}, "secret")
check("Push to another allowed topic", secret_id == 1, secret_id) check("Push to another allowed topic", secret_id == 1, secret_id)
ok, detail = raises(lambda: lounge.connect(), BakaShrotError, "one connection", ErrorCode.ALREADY_CONNECTED) with lounge:
check("A second Client can't connect while one is", ok and not lounge.connected, detail) page = lounge.get_messages("logs", "kitchen", after=0, limit=2)
check("A second Client connected at the same time: both work",
lounge.connected and lounge.node == "lounge" and [m.id for m in page] == [1, 2]
and kitchen.connected and kitchen.latest("secret", "kitchen").id == secret_id,
f"{lounge.node}, {[m.id for m in page]}")
check("Closing one leaves the other connected", kitchen.connected and not lounge.connected)
topics = kitchen.list_topics() topics = kitchen.list_topics()
check("list_topics()", topics.kind == "topic" and topics.names == ["logs", "secret"] and not topics.truncated, topics) check("list_topics()", topics.kind == "topic" and topics.names == ["logs", "secret"] and not topics.truncated, topics)
nodes = kitchen.list_nodes() nodes = kitchen.list_nodes()
check("list_nodes()", nodes.kind == "node" and nodes.names == ["kitchen"], 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() ------------------------------------------------------------ # --- follow() ------------------------------------------------------------
followed = [] followed = []
@@ -210,10 +227,54 @@ with kitchen:
"missing.bin", ErrorCode.FILE_ERROR) "missing.bin", ErrorCode.FILE_ERROR)
check("A missing file: refused before sending", ok, detail) check("A missing file: refused before sending", ok, detail)
check("Still connected", kitchen.connected) check("Still connected", kitchen.connected)
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) check("close(): disconnected", not kitchen.connected)
ok, detail = raises(lambda: kitchen.push("x", "logs"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED) ok, detail = raises(lambda: kitchen.push("x", "logs"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED)
check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail) check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail)
ok, detail = raises(kitchen.ping, ConnectionLostError, code=ErrorCode.NOT_CONNECTED)
check("ping() once closed: ConnectionLostError, NOT_CONNECTED", ok, detail)
# --- Connecting: unreachable, refused, PEM text ---------------------------------- # --- Connecting: unreachable, refused, PEM text ----------------------------------
with open(kitchen.ca) as ca, open(kitchen.certificate) as certificate, open(kitchen.key) as key: with open(kitchen.ca) as ca, open(kitchen.certificate) as certificate, open(kitchen.key) as key:
+13 -4
View File
@@ -1,7 +1,12 @@
# Builds everything (the server, the tools, the client library), release # Builds everything (the server, the tool, the client library), release
# mode, into target\release\. # mode, into target\release\: the tool with its own profile (release-tools,
# Usage: powershell -ExecutionPolicy Bypass -File build.ps1 # 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" $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). # rustup's folder isn't always on the PATH (it isn't in every shell here).
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) { if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
@@ -10,8 +15,12 @@ if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
Push-Location $PSScriptRoot Push-Location $PSScriptRoot
try { try {
cargo build --workspace --release --locked cargo build --workspace --exclude bakashrot-tools --release --locked @crt
if ($LASTEXITCODE -ne 0) { "FAILED: cargo build"; exit 1 } 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 { } finally {
Pop-Location Pop-Location
} }
+14 -10
View File
@@ -8,13 +8,13 @@ From the repository's root, on Windows (`powershell -ExecutionPolicy Bypass -Fil
| Script | What it does | | 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 | | `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) | | `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` | | `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`). the benchmarks are ignored tests (`cargo test --release -- --ignored`).
Generated keys and certificates never go in git. Generated keys and certificates never go in git.
@@ -23,7 +23,7 @@ Generated keys and certificates never go in git.
A Cargo workspace: 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) rust-toolchain.toml the pinned toolchain (1.100.0)
build.ps1, test.ps1, release.ps1, clean.ps1, bench.ps1 build.ps1, test.ps1, release.ps1, clean.ps1, bench.ps1
release.py a release for this platform: build, package, smoke test 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-server/ the server: TLS, identities, requests, the writer thread (and its program)
bakashrot-client/ the client library, Rust API, blocking bakashrot-client/ the client library, Rust API, blocking
bakashrot-capi/ the C DLL over bakashrot-client: the BakaShrot_* exports (bakashrot.dll) 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/ bindings/
c/ bakashrot.h, generated from bakashrot-capi c/ bakashrot.h, generated from bakashrot-capi
purebasic/ the prototypes and error codes purebasic/ the prototypes and error codes
python/ bakashrot.py over the DLL, check_bakashrot.py, make_wheel.py 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 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 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 ## Releases
`python release.py` (or `release.ps1`) on Windows or Linux, x64 or ARM64, builds that platform's release into `python release.py` (or `release.ps1`) on Windows or Linux, x64 or ARM64, builds that platform's release into
`target/dist/bakashrot-<version>-<platform>/` and its archive (`.zip`, `.tar.gz`): `target/dist/bakashrot-<version>-<platform>/` and its archive (`.zip`, `.tar.gz`):
the server, `bakashrot`, `bakashrot-cert`, the client library with its C header and PureBasic prototypes, 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`), the example configs, `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`). `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, 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 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 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/<rid>/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. 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. The version is the workspace's (`Cargo.toml`), and `bindings/python/bakashrot.py`'s `__version__` must be the same.
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "bakashrot-capi" name = "bakashrot-capi"
description = "BakaShrot's C DLL: the BakaShrot_* exports over bakashrot-client, one connection per process." description = "BakaShrot's C DLL: the BakaShrot_* exports over bakashrot-client, as many clients as needed."
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
+365
View File
@@ -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<String>,
truncated: bool,
},
Query {
columns: Vec<String>,
rows: Cursor<Vec<Option<String>>>,
},
}
/// Items and where it's at: 0 before the first, `n` on the `n`th, the
/// count + 1 past the last.
struct Cursor<T> {
items: Vec<T>,
position: usize,
}
impl<T> Cursor<T> {
fn new(items: Vec<T>) -> Cursor<T> {
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<Items>) -> 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<R>(handle: i64, default: R, read: impl FnOnce(&mut Items) -> Option<R>) -> 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> {
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<T: Text>(
client: i64,
kind: i32,
topics: *const T::Unit,
nodes: *const T::Unit,
) -> i64 {
enumerate(client, |state| {
let list = unsafe { fetch_names::<T>(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::<Utf8>(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::<Utf16>(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<T: Text>(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::<T>(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::<Utf8>(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::<Utf16>(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<Items> {
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::<Option<Vec<_>>>()?;
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::<Option<Vec<_>>>()
})
.collect::<Option<Vec<_>>>()?;
Some(Items::Query {
columns,
rows: Cursor::new(rows),
})
}
unsafe fn enumerate_query<T: Text>(client: i64, sql: *const T::Unit) -> i64 {
enumerate(client, |state| {
let json = unsafe { fetch_query::<T>(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::<Utf8>(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::<Utf16>(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<T: Text>(
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::<T>(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::<Utf8>(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::<Utf16>(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<String>> {
match items {
Items::Query { rows, .. } => rows.current()?.get(column(index)?),
Items::Names { .. } => None,
}
}
unsafe fn query_value<T: Text>(
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::<T>(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::<Utf8>(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::<Utf16>(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()))
})
}
File diff suppressed because it is too large Load Diff
+133
View File
@@ -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<u32, String> {
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<Item = &'a str>) -> BTreeMap<u32, String> {
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::<u32>() 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<Item = &'a str> {
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}");
}
}
+534 -127
View File
@@ -1,6 +1,7 @@
//! The exports called as C would, against a server: the `W` ones (what //! The exports called as C would, against a server. `exports`: one client,
//! PureBasic uses; Python's check covers the `A` ones), the buffers, the //! the `W` exports (what PureBasic uses; Python's check covers the `A`
//! errors. One test: the DLL holds one connection per process. //! ones), the buffers, the errors. `clients`: several clients at once, bad
//! handles, threads.
#![allow(unsafe_code)] #![allow(unsafe_code)]
@@ -9,6 +10,8 @@ mod common;
use bakashrot::*; use bakashrot::*;
use bakashrot_proto::ErrorCode; use bakashrot_proto::ErrorCode;
use std::ffi::{CString, c_char}; use std::ffi::{CString, c_char};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
fn w(text: &str) -> Vec<u16> { fn w(text: &str) -> Vec<u16> {
text.encode_utf16().chain([0]).collect() text.encode_utf16().chain([0]).collect()
@@ -19,25 +22,28 @@ fn a(text: &str) -> CString {
} }
/// A `W` getter's string: asks for the size, then copies. /// A `W` getter's string: asks for the size, then copies.
fn get_w(getter: unsafe extern "C" fn(*mut u16, isize) -> isize) -> String { fn get_w(client: i64, getter: unsafe extern "C" fn(i64, *mut u16, isize) -> isize) -> String {
let size = unsafe { getter(std::ptr::null_mut(), 0) }; let size = unsafe { getter(client, std::ptr::null_mut(), 0) };
if size == 0 {
return String::new();
}
let mut buffer = vec![0u16; size as usize / 2]; let mut buffer = vec![0u16; size as usize / 2];
unsafe { getter(buffer.as_mut_ptr(), size) }; unsafe { getter(client, buffer.as_mut_ptr(), size) };
String::from_utf16(&buffer[..buffer.len() - 1]).unwrap() String::from_utf16(&buffer[..buffer.len() - 1]).unwrap()
} }
fn get_a(getter: unsafe extern "C" fn(*mut c_char, isize) -> isize) -> String { fn get_a(client: i64, getter: unsafe extern "C" fn(i64, *mut c_char, isize) -> isize) -> String {
let size = unsafe { getter(std::ptr::null_mut(), 0) }; let size = unsafe { getter(client, std::ptr::null_mut(), 0) };
let mut buffer = vec![0u8; size as usize]; let mut buffer = vec![0u8; size as usize];
unsafe { getter(buffer.as_mut_ptr().cast(), size) }; unsafe { getter(client, buffer.as_mut_ptr().cast(), size) };
String::from_utf8(buffer[..buffer.len() - 1].to_vec()).unwrap() String::from_utf8(buffer[..buffer.len() - 1].to_vec()).unwrap()
} }
/// The last error's code and reason. /// The client's last error: its code and reason.
fn error() -> (u32, String) { fn error(client: i64) -> (u32, String) {
( (
BakaShrot_GetLastError() as u32, BakaShrot_GetLastError(client) as u32,
get_w(BakaShrot_GetRefusalReasonW), get_w(client, BakaShrot_GetRefusalReasonW),
) )
} }
@@ -54,172 +60,227 @@ fn exports() {
let pem = |name: &str| std::fs::read_to_string(running.folder.join(name)).unwrap(); let pem = |name: &str| std::fs::read_to_string(running.folder.join(name)).unwrap();
let localhost = w("127.0.0.1"); let localhost = w("127.0.0.1");
let port = i32::from(running.port); let port = i32::from(running.port);
let client = BakaShrot_CreateClient();
assert!(client >= 1);
unsafe { unsafe {
// Nothing set, not connected. // Nothing set, not connected.
assert_eq!( assert_eq!(
BakaShrot_PushMessageToW(w("logs").as_ptr(), w("{}").as_ptr()), BakaShrot_PushMessageToW(client, w("logs").as_ptr(), w("{}").as_ptr()),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::NotConnected)); assert_eq!(error(client).0, code(ErrorCode::NotConnected));
assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0); assert_eq!(BakaShrot_ConnectW(client, localhost.as_ptr(), port), 0);
let (failed, why) = error(); let (failed, why) = error(client);
assert_eq!(failed, code(ErrorCode::InvalidArgument)); assert_eq!(failed, code(ErrorCode::InvalidArgument));
assert!(why.contains("BakaShrot_SetCaCertificate"), "{why}"); assert!(why.contains("BakaShrot_SetCaCertificate"), "{why}");
// Files or PEM text; a missing file, an empty setting. // Files or PEM text; a missing file, an empty setting.
assert_eq!( assert_eq!(
BakaShrot_SetCaCertificateW(w(&file("missing.crt")).as_ptr()), BakaShrot_SetCaCertificateW(client, w(&file("missing.crt")).as_ptr()),
0 0
); );
assert_eq!(error().0, code(ErrorCode::FileError)); assert_eq!(error(client).0, code(ErrorCode::FileError));
assert_eq!(BakaShrot_SetCertificateW(std::ptr::null()), 0); assert_eq!(BakaShrot_SetCertificateW(client, std::ptr::null()), 0);
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 1);
assert_eq!(BakaShrot_GetLastError(), 0);
assert_eq!( assert_eq!(
BakaShrot_SetCertificateW(w(&pem("kitchen.crt")).as_ptr()), BakaShrot_SetCaCertificateW(client, w(&file("ca.crt")).as_ptr()),
1
);
assert_eq!(BakaShrot_GetLastError(client), 0);
assert_eq!(
BakaShrot_SetCertificateW(client, w(&pem("kitchen.crt")).as_ptr()),
1 1
); );
assert_eq!( assert_eq!(
BakaShrot_SetPrivateKeyA(a(&file("kitchen.key")).as_ptr()), BakaShrot_SetPrivateKeyA(client, a(&file("kitchen.key")).as_ptr()),
1 1
); );
// A CRL file asked for is needed (client.toml's may be missing). // A CRL file asked for is needed (client.toml's may be missing).
assert_eq!(BakaShrot_SetCrlW(w(&file("missing.crl")).as_ptr()), 0); assert_eq!(
assert_eq!(error().0, code(ErrorCode::FileError)); BakaShrot_SetCrlW(client, w(&file("missing.crl")).as_ptr()),
assert_eq!(BakaShrot_SetCrlW(std::ptr::null()), 1); 0
assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), 0), 0); );
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::FileError));
assert_eq!(BakaShrot_SetCrlW(client, std::ptr::null()), 1);
assert_eq!(BakaShrot_ConnectW(client, localhost.as_ptr(), 0), 0);
assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
assert_eq!( assert_eq!(
BakaShrot_ConnectW(localhost.as_ptr(), port), BakaShrot_ConnectW(client, localhost.as_ptr(), port),
1, 1,
"{:?}", "{:?}",
error() error(client)
); );
assert_eq!(BakaShrot_IsConnected(), 1); assert_eq!(BakaShrot_IsConnected(client), 1);
assert_eq!(get_w(BakaShrot_GetNodeW), "kitchen"); assert_eq!(get_w(client, BakaShrot_GetNodeW), "kitchen");
assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0); assert_eq!(BakaShrot_ConnectW(client, localhost.as_ptr(), port), 0);
assert_eq!(error().0, code(ErrorCode::AlreadyConnected)); assert_eq!(error(client).0, code(ErrorCode::AlreadyConnected));
assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 0); assert_eq!(
assert_eq!(error().0, code(ErrorCode::AlreadyConnected)); BakaShrot_SetCaCertificateW(client, w(&file("ca.crt")).as_ptr()),
0
);
assert_eq!(error(client).0, code(ErrorCode::AlreadyConnected));
// Pushes: UTF-16, a null message is an empty one. // Pushes: UTF-16, a null message is an empty one.
assert_eq!( assert_eq!(
BakaShrot_PushMessageToW(w("logs").as_ptr(), w(r#"{"i":1}"#).as_ptr()), BakaShrot_PushMessageToW(client, w("logs").as_ptr(), w(r#"{"i":1}"#).as_ptr()),
1 1
); );
assert_eq!( assert_eq!(
BakaShrot_PushMessageToW(w("logs").as_ptr(), w("héllo 🌍").as_ptr()), BakaShrot_PushMessageToW(client, w("logs").as_ptr(), w("héllo 🌍").as_ptr()),
2 2
); );
assert_eq!( assert_eq!(
BakaShrot_PushMessageToW(w("logs").as_ptr(), std::ptr::null()), BakaShrot_PushMessageToW(client, w("logs").as_ptr(), std::ptr::null()),
3 3
); );
assert_eq!( assert_eq!(
BakaShrot_PushMessageToW(std::ptr::null(), w("{}").as_ptr()), BakaShrot_PushMessageToW(client, std::ptr::null(), w("{}").as_ptr()),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
assert_eq!( assert_eq!(
BakaShrot_PushMessageToW(w("nothing").as_ptr(), w("{}").as_ptr()), BakaShrot_PushMessageToW(client, w("nothing").as_ptr(), w("{}").as_ptr()),
-1 -1
); );
let (failed, why) = error(); let (failed, why) = error(client);
assert_eq!(failed, code(ErrorCode::NotAllowed)); assert_eq!(failed, code(ErrorCode::NotAllowed));
assert!(why.contains("may not push to 'nothing'"), "{why}"); assert!(why.contains("may not push to 'nothing'"), "{why}");
// The latest; none yet in another topic. // The latest; none yet in another topic.
assert_eq!( assert_eq!(
BakaShrot_GetLatestMessageOfW(w("logs").as_ptr(), w("kitchen").as_ptr()), BakaShrot_GetLatestMessageOfW(client, w("logs").as_ptr(), w("kitchen").as_ptr()),
1 1
); );
assert_eq!( assert_eq!(
(BakaShrot_GetMessageCount(), BakaShrot_GetMessageId()), (
BakaShrot_GetMessageCount(client),
BakaShrot_GetMessageId(client)
),
(1, 3) (1, 3)
); );
assert_eq!(get_w(BakaShrot_GetMessageDataW), ""); assert_eq!(get_w(client, BakaShrot_GetMessageDataW), "");
assert!(BakaShrot_GetMessagePushedAt() > 1_700_000_000_000); assert!(BakaShrot_GetMessagePushedAt(client) > 1_700_000_000_000);
assert_eq!(BakaShrot_GetMessageAttachmentSize(), 0); assert_eq!(BakaShrot_GetMessageAttachmentSize(client), 0);
assert_eq!(BakaShrot_IsMessageAttachmentReady(), 0); assert_eq!(BakaShrot_IsMessageAttachmentReady(client), 0);
assert_eq!( assert_eq!(
BakaShrot_GetLatestMessageOfW(w("secret").as_ptr(), w("kitchen").as_ptr()), BakaShrot_GetLatestMessageOfW(client, w("secret").as_ptr(), w("kitchen").as_ptr()),
0 0
); );
assert_eq!(error().0, code(ErrorCode::NotFound)); assert_eq!(error(client).0, code(ErrorCode::NotFound));
assert_eq!(BakaShrot_GetMessageCount(), 0); assert_eq!(BakaShrot_GetMessageCount(client), 0);
// A run of messages, selected one by one. // A run of messages, selected one by one.
assert_eq!( assert_eq!(
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 2), BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 2),
2 2
); );
assert_eq!(BakaShrot_HasMoreMessages(), 1); assert_eq!(BakaShrot_HasMoreMessages(client), 1);
assert_eq!(get_w(BakaShrot_GetMessageTopicW), "logs"); assert_eq!(get_w(client, BakaShrot_GetMessageTopicW), "logs");
assert_eq!(get_w(BakaShrot_GetMessageNodeW), "kitchen"); assert_eq!(get_w(client, BakaShrot_GetMessageNodeW), "kitchen");
assert_eq!(BakaShrot_GetMessageId(), 1); assert_eq!(BakaShrot_GetMessageId(client), 1);
assert_eq!(BakaShrot_SelectMessage(1), 1); assert_eq!(BakaShrot_SelectMessage(client, 1), 1);
assert_eq!(get_w(BakaShrot_GetMessageDataW), "héllo 🌍"); assert_eq!(get_w(client, BakaShrot_GetMessageDataW), "héllo 🌍");
assert_eq!(get_a(BakaShrot_GetMessageDataA), "héllo 🌍"); assert_eq!(get_a(client, BakaShrot_GetMessageDataA), "héllo 🌍");
assert_eq!(BakaShrot_SelectMessage(2), 0); assert_eq!(BakaShrot_SelectMessage(client, 2), 0);
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
assert_eq!(BakaShrot_GetMessageId(), 2, "the selection stays"); assert_eq!(BakaShrot_GetMessageId(client), 2, "the selection stays");
assert_eq!( assert_eq!(
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 3, 10), BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("kitchen").as_ptr(), 3, 10),
0 0
); );
assert_eq!(BakaShrot_HasMoreMessages(), 0); assert_eq!(BakaShrot_HasMoreMessages(client), 0);
assert_eq!(BakaShrot_GetMessageId(), 0); assert_eq!(BakaShrot_GetMessageId(client), 0);
for (after, limit) in [(-1, 10), (0, 0), (0, 10_001)] { for (after, limit) in [(-1, 10), (0, 0), (0, 10_001)] {
assert_eq!( assert_eq!(
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), after, limit), BakaShrot_GetMessagesW(
client,
w("logs").as_ptr(),
w("kitchen").as_ptr(),
after,
limit
),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
} }
assert_eq!( assert_eq!(
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("nobody").as_ptr(), 0, 10), BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("nobody").as_ptr(), 0, 10),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::UnknownName)); assert_eq!(error(client).0, code(ErrorCode::UnknownName));
assert_eq!(BakaShrot_IsConnected(), 1, "a refusal keeps the connection"); assert_eq!(
BakaShrot_IsConnected(client),
1,
"a refusal keeps the connection"
);
// The buffers: the size needed, nothing copied if it doesn't fit. // The buffers: the size needed, nothing copied if it doesn't fit.
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 1); BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 1);
assert_eq!(BakaShrot_GetMessageDataW(std::ptr::null_mut(), 0), 16); assert_eq!(
assert_eq!(BakaShrot_GetMessageDataA(std::ptr::null_mut(), 0), 8); BakaShrot_GetMessageDataW(client, std::ptr::null_mut(), 0),
16
);
assert_eq!(
BakaShrot_GetMessageDataA(client, std::ptr::null_mut(), 0),
8
);
let mut small = [7u16; 7]; let mut small = [7u16; 7];
assert_eq!(BakaShrot_GetMessageDataW(small.as_mut_ptr(), 14), 16); assert_eq!(
BakaShrot_GetMessageDataW(client, small.as_mut_ptr(), 14),
16
);
assert_eq!(small, [7; 7]); assert_eq!(small, [7; 7]);
// Unaligned: a byte buffer. // Unaligned: a byte buffer.
let mut bytes = [0u8; 17]; let mut bytes = [0u8; 17];
assert_eq!( assert_eq!(
BakaShrot_GetMessageDataW(bytes[1..].as_mut_ptr().cast(), 16), BakaShrot_GetMessageDataW(client, bytes[1..].as_mut_ptr().cast(), 16),
16 16
); );
assert_eq!(bytes[1..3], [b'{', 0]); assert_eq!(bytes[1..3], [b'{', 0]);
// Names, queries. // Names, queries.
// Topics: those with messages (nothing in `secret` yet). // Topics: those with messages (nothing in `secret` yet).
assert_eq!(BakaShrot_ListTopics(), 1); let null = std::ptr::null();
assert_eq!(BakaShrot_ListNamesW(client, 1, null, null), 1);
assert_eq!( assert_eq!(
get_w(BakaShrot_GetNamesListW), get_w(client, BakaShrot_GetNamesListAsJsonW),
r#"{"kind":"topic","names":["logs"],"truncated":false}"# 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!( assert_eq!(
BakaShrot_QueryW(w("SELECT COUNT(*) AS n FROM data").as_ptr()), BakaShrot_ListNamesW(client, 1, null, w("KITCHEN").as_ptr()),
1 1
); );
assert_eq!( 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"]]}"# r#"{"columns":["n"],"rows":[["3"]]}"#
); );
assert_eq!(BakaShrot_QueryW(w("SELECT nope").as_ptr()), 0); assert_eq!(BakaShrot_QueryW(client, w("SELECT nope").as_ptr()), 0);
assert_eq!(error().0, code(ErrorCode::QueryFailed)); assert_eq!(error(client).0, code(ErrorCode::QueryFailed));
assert_eq!(get_w(BakaShrot_GetQueryResultW), ""); assert_eq!(get_w(client, BakaShrot_GetQueryResultAsJsonW), "");
// Attachments: from a file or memory, saved or loaded back. // Attachments: from a file or memory, saved or loaded back.
let (logs, kitchen) = (w("logs"), w("kitchen")); let (logs, kitchen) = (w("logs"), w("kitchen"));
@@ -227,34 +288,36 @@ fn exports() {
std::fs::write(running.folder.join("photo.bin"), &photo).unwrap(); std::fs::write(running.folder.join("photo.bin"), &photo).unwrap();
let photo_file = w(&file("photo.bin")); let photo_file = w(&file("photo.bin"));
let pushed = BakaShrot_PushMessageWithFileW( let pushed = BakaShrot_PushMessageWithFileW(
client,
logs.as_ptr(), logs.as_ptr(),
w(r#"{"photo":1}"#).as_ptr(), w(r#"{"photo":1}"#).as_ptr(),
photo_file.as_ptr(), photo_file.as_ptr(),
); );
assert_eq!(pushed, 4, "{:?}", error()); assert_eq!(pushed, 4, "{:?}", error(client));
let tiny = b"tiny"; let tiny = b"tiny";
let pushed = BakaShrot_PushMessageWithDataW( let pushed = BakaShrot_PushMessageWithDataW(
client,
logs.as_ptr(), logs.as_ptr(),
std::ptr::null(), std::ptr::null(),
tiny.as_ptr().cast(), tiny.as_ptr().cast(),
4, 4,
); );
assert_eq!(pushed, 5, "{:?}", error()); assert_eq!(pushed, 5, "{:?}", error(client));
assert_eq!( assert_eq!(
BakaShrot_GetLatestMessageOfW(logs.as_ptr(), kitchen.as_ptr()), BakaShrot_GetLatestMessageOfW(client, logs.as_ptr(), kitchen.as_ptr()),
1 1
); );
assert_eq!( assert_eq!(
( (
BakaShrot_GetMessageId(), BakaShrot_GetMessageId(client),
BakaShrot_GetMessageAttachmentSize(), BakaShrot_GetMessageAttachmentSize(client),
BakaShrot_IsMessageAttachmentReady() BakaShrot_IsMessageAttachmentReady(client)
), ),
(5, 4, 1) (5, 4, 1)
); );
let saved = w(&file("saved.bin")); let saved = w(&file("saved.bin"));
assert_eq!( assert_eq!(
BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 4, saved.as_ptr()), BakaShrot_SaveAttachmentW(client, logs.as_ptr(), kitchen.as_ptr(), 4, saved.as_ptr()),
1_500_000 1_500_000
); );
assert_eq!( assert_eq!(
@@ -262,84 +325,428 @@ fn exports() {
photo photo
); );
assert_eq!( assert_eq!(
BakaShrot_LoadAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 5), BakaShrot_LoadAttachmentW(client, logs.as_ptr(), kitchen.as_ptr(), 5),
4
);
assert_eq!(
BakaShrot_GetAttachmentData(client, std::ptr::null_mut(), 0),
4 4
); );
assert_eq!(BakaShrot_GetAttachmentData(std::ptr::null_mut(), 0), 4);
let mut small = [9u8; 3]; let mut small = [9u8; 3];
assert_eq!(BakaShrot_GetAttachmentData(small.as_mut_ptr().cast(), 3), 4); assert_eq!(
BakaShrot_GetAttachmentData(client, small.as_mut_ptr().cast(), 3),
4
);
assert_eq!(small, [9; 3], "nothing copied if it doesn't fit"); assert_eq!(small, [9; 3], "nothing copied if it doesn't fit");
let mut data = [0u8; 4]; let mut data = [0u8; 4];
assert_eq!(BakaShrot_GetAttachmentData(data.as_mut_ptr().cast(), 4), 4);
assert_eq!(&data, tiny);
assert_eq!(BakaShrot_FreeAttachmentData(), 1);
assert_eq!(BakaShrot_GetAttachmentData(std::ptr::null_mut(), 0), 0);
assert_eq!( assert_eq!(
BakaShrot_LoadAttachmentA(a("logs").as_ptr(), a("kitchen").as_ptr(), 4), BakaShrot_GetAttachmentData(client, data.as_mut_ptr().cast(), 4),
4
);
assert_eq!(&data, tiny);
assert_eq!(BakaShrot_FreeAttachmentData(client), 1);
assert_eq!(
BakaShrot_GetAttachmentData(client, std::ptr::null_mut(), 0),
0
);
assert_eq!(
BakaShrot_LoadAttachmentA(client, a("logs").as_ptr(), a("kitchen").as_ptr(), 4),
1_500_000 1_500_000
); );
BakaShrot_FreeAttachmentData(); BakaShrot_FreeAttachmentData(client);
// Refused, or the client's own failures: -1, no file. // Refused, or the client's own failures: -1, no file.
let none = w(&file("none.bin")); let none = w(&file("none.bin"));
assert_eq!( assert_eq!(
BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 1, none.as_ptr()), BakaShrot_SaveAttachmentW(client, logs.as_ptr(), kitchen.as_ptr(), 1, none.as_ptr()),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::NotFound)); assert_eq!(error(client).0, code(ErrorCode::NotFound));
assert!(!running.folder.join("none.bin").exists()); assert!(!running.folder.join("none.bin").exists());
assert_eq!( assert_eq!(
BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), -1, none.as_ptr()), BakaShrot_SaveAttachmentW(client, logs.as_ptr(), kitchen.as_ptr(), -1, none.as_ptr()),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
let missing = w(&file("missing.bin")); let missing = w(&file("missing.bin"));
assert_eq!( assert_eq!(
BakaShrot_PushMessageWithFileW(logs.as_ptr(), std::ptr::null(), missing.as_ptr()), BakaShrot_PushMessageWithFileW(
client,
logs.as_ptr(),
std::ptr::null(),
missing.as_ptr()
),
-1 -1
); );
assert_eq!(error().0, code(ErrorCode::FileError)); assert_eq!(error(client).0, code(ErrorCode::FileError));
for (pointer, size) in [(std::ptr::null(), 4), (tiny.as_ptr(), 0)] { for (pointer, size) in [(std::ptr::null(), 4), (tiny.as_ptr(), 0)] {
let pushed = BakaShrot_PushMessageWithDataW( let pushed = BakaShrot_PushMessageWithDataW(
client,
logs.as_ptr(), logs.as_ptr(),
std::ptr::null(), std::ptr::null(),
pointer.cast(), pointer.cast(),
size, size,
); );
assert_eq!(pushed, -1); assert_eq!(pushed, -1);
assert_eq!(error().0, code(ErrorCode::InvalidArgument)); assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
} }
assert_eq!(BakaShrot_IsConnected(), 1); assert_eq!(BakaShrot_IsConnected(client), 1);
// 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. // Closed: requests refused, the settings kept.
assert_eq!(BakaShrot_Disconnect(), 1); assert_eq!(BakaShrot_Disconnect(client), 1);
assert_eq!(BakaShrot_Disconnect(), 0); assert_eq!(BakaShrot_Disconnect(client), 0);
assert_eq!(BakaShrot_IsConnected(), 0); assert_eq!(BakaShrot_IsConnected(client), 0);
assert_eq!(get_w(BakaShrot_GetNodeW), ""); assert_eq!(BakaShrot_Ping(client), 0);
assert_eq!(BakaShrot_QueryW(w("SELECT 1").as_ptr()), 0); assert_eq!(error(client).0, code(ErrorCode::NotConnected));
assert_eq!(error().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. // Another identity, by the A exports: not allowed to query.
assert_eq!( assert_eq!(
BakaShrot_SetCertificateA(a(&file("lounge.crt")).as_ptr()), BakaShrot_SetCertificateA(client, a(&file("lounge.crt")).as_ptr()),
1 1
); );
assert_eq!(BakaShrot_SetPrivateKeyA(a(&pem("lounge.key")).as_ptr()), 1);
assert_eq!( assert_eq!(
BakaShrot_ConnectA(a("localhost").as_ptr(), port), BakaShrot_SetPrivateKeyA(client, a(&pem("lounge.key")).as_ptr()),
1
);
assert_eq!(
BakaShrot_ConnectA(client, a("localhost").as_ptr(), port),
1, 1,
"{:?}", "{:?}",
error() error(client)
); );
assert_eq!(get_a(BakaShrot_GetNodeA), "lounge"); assert_eq!(get_a(client, BakaShrot_GetNodeA), "lounge");
assert_eq!(BakaShrot_QueryA(a("SELECT 1").as_ptr()), 0); assert_eq!(BakaShrot_QueryA(client, a("SELECT 1").as_ptr()), 0);
let (failed, why) = error(); let (failed, why) = error(client);
assert_eq!(failed, code(ErrorCode::NotAllowed)); assert_eq!(failed, code(ErrorCode::NotAllowed));
assert_eq!(get_a(BakaShrot_GetRefusalReasonA), why); assert_eq!(get_a(client, BakaShrot_GetRefusalReasonA), why);
BakaShrot_Disconnect(); BakaShrot_Disconnect(client);
// Nothing listening there. // Nothing listening there.
assert_eq!(BakaShrot_ConnectA(a("127.0.0.1").as_ptr(), 1), 0); assert_eq!(BakaShrot_ConnectA(client, a("127.0.0.1").as_ptr(), 1), 0);
assert_eq!(error().0, code(ErrorCode::ConnectFailed)); assert_eq!(error(client).0, code(ErrorCode::ConnectFailed));
}
assert_eq!(BakaShrot_FreeClient(client), 1);
}
/// 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<i64> = (0..50)
.map(|i| unsafe {
let data = w(&format!(r#"{{"t":{i}}}"#));
BakaShrot_PushMessageToW(client, w("logs").as_ptr(), data.as_ptr())
})
.collect();
assert_eq!(BakaShrot_FreeClient(client), 1);
ids
})
})
.collect();
let mut ids: Vec<i64> = threads
.into_iter()
.flat_map(|thread| thread.join().unwrap())
.collect();
ids.sort_unstable();
assert_eq!(ids, (4..=203).collect::<Vec<i64>>());
// A client freed while another thread uses it: that thread's calls
// fail from then on, nothing crashes.
let client = connected(&running, "kitchen");
let started = Arc::new(AtomicBool::new(false));
let reader = {
let started = started.clone();
std::thread::spawn(move || {
let mut reads = 0;
loop {
let count = unsafe {
BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 50)
};
started.store(true, Ordering::SeqCst);
if count < 0 {
return (reads, error(client).0);
}
reads += 1;
}
})
};
while !started.load(Ordering::SeqCst) {
std::thread::yield_now();
}
assert_eq!(BakaShrot_FreeClient(client), 1);
let (reads, failed) = reader.join().unwrap();
assert!(reads >= 1);
assert_eq!(failed, code(ErrorCode::InvalidArgument));
}
/// 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<String> {
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}");
}
} }
} }
+293 -131
View File
@@ -17,17 +17,24 @@
//! ALPN `bakashrot`, both ends' protocol versions, then the server's //! ALPN `bakashrot`, both ends' protocol versions, then the server's
//! `Welcome` (`docs/protocol.md`). Errors carry the protocol's codes //! `Welcome` (`docs/protocol.md`). Errors carry the protocol's codes
//! (`bakashrot_proto::ErrorCode`): a server's refusal keeps its own. //! (`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 aws_lc_rs::digest;
use bakashrot_pki::{Revocations, tls}; use bakashrot_pki::{Revocations, tls};
use bakashrot_proto::limits::{ use bakashrot_proto::limits::{
ALPN, ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGE_SIZE, ALPN, ATTACHMENT_PART_SIZE, KEEPALIVE_SECS, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID,
MAX_MESSAGES_PER_PACKET, MAX_PACKET_SIZE, 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::{ use bakashrot_proto::packets::{
Attachment, AttachmentPart, GetAttachment, GetMessages, ListNames, Messages, NameKind, Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed,
NamesList, PushMessage, Query, Messages, NameKind, NamesList, Ping, Pong, PushMessage, Query, QueryResult, Welcome,
}; };
use bakashrot_proto::{ErrorCode, Packet, frame}; use bakashrot_proto::{ErrorCode, Packet, frame};
use rustls::{ClientConnection, StreamOwned}; use rustls::{ClientConnection, StreamOwned};
@@ -97,11 +104,26 @@ impl std::error::Error for Error {}
/// A result of this crate. /// A result of this crate.
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
/// 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. /// A connection to a server.
pub struct Client { pub struct Client {
stream: StreamOwned<ClientConnection, TcpStream>, stream: StreamOwned<ClientConnection, TcpStream>,
server: String, server: String,
node: 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 { impl fmt::Debug for Client {
@@ -166,20 +188,38 @@ impl Client {
stream, stream,
server: String::new(), server: String::new(),
node: String::new(), node: String::new(),
answer_timeout: CONNECT_TIMEOUT,
closed: false,
}; };
match client.answer()? { let welcome: Welcome = client.answer()?;
Packet::Welcome(welcome) => { (client.server, client.node) = (welcome.server, welcome.node);
client.server = welcome.server; client.set_answer_timeout(ANSWER_TIMEOUT)?;
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)?;
Ok(client) 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. /// The server's name.
pub fn server(&self) -> &str { pub fn server(&self) -> &str {
&self.server &self.server
@@ -191,17 +231,90 @@ impl Client {
} }
/// Whether the connection still looks open: the server hasn't closed /// Whether the connection still looks open: the server hasn't closed
/// it (after its idle timeout, say). Only a request tells for sure. /// it (after its idle timeout, say, or with TLS's close_notify). Only a
pub fn is_open(&self) -> bool { /// request tells for sure.
let tcp = &self.stream.sock; ///
if tcp.set_nonblocking(true).is_err() { /// 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; return false;
} }
let open = match tcp.peek(&mut [0]) { if self.stream.sock.set_nonblocking(true).is_err() {
Ok(read) => read > 0, return false;
Err(error) => error.kind() == io::ErrorKind::WouldBlock, }
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,
}; };
open && tcp.set_nonblocking(false).is_ok() 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. /// Pushes a message to `topic`, as this client's node: its id.
@@ -213,10 +326,8 @@ impl Client {
data: data.to_owned(), data: data.to_owned(),
attachment: None, attachment: None,
}; };
match self.request(push.into())? { let pushed: MessagePushed = self.request(push.into())?;
Packet::MessagePushed(pushed) => Ok(pushed.message_id), Ok(pushed.message_id)
other => Err(unexpected(&other)),
}
} }
/// Pushes a message with an attachment read from `source` (a `File`, a /// Pushes a message with an attachment read from `source` (a `File`, a
@@ -245,12 +356,9 @@ impl Client {
sha256.update(&buffer[..read]); sha256.update(&buffer[..read]);
size += read as u64; size += read as u64;
} }
if !(1..=MAX_ATTACHMENT_SIZE).contains(&size) { require((1..=MAX_ATTACHMENT_SIZE).contains(&size), || {
return Err(Error::new( format!("an attachment of {size} bytes: 1 to {MAX_ATTACHMENT_SIZE}")
ErrorCode::InvalidArgument, })?;
format!("an attachment of {size} bytes: 1 to {MAX_ATTACHMENT_SIZE}"),
));
}
source.rewind().map_err(file_error)?; source.rewind().map_err(file_error)?;
let mut digest = [0; 32]; let mut digest = [0; 32];
digest.copy_from_slice(sha256.finish().as_ref()); digest.copy_from_slice(sha256.finish().as_ref());
@@ -263,26 +371,20 @@ impl Client {
data: data.to_owned(), data: data.to_owned(),
attachment: Some(attachment.clone()), attachment: Some(attachment.clone()),
}; };
match self.request(push.into())? { let Continue {} = self.request(push.into())?;
Packet::Continue(_) => {}
other => return Err(unexpected(&other)),
}
for part in 0..attachment.part_count() { for part in 0..attachment.part_count() {
let part = &mut buffer[..attachment.part_len(part) as usize]; let part = &mut buffer[..attachment.part_len(part) as usize];
if let Err(error) = source.read_exact(part) { if let Err(error) = source.read_exact(part) {
self.close(); // The server waits for parts that won't come.
return Err(file_error(error)); return Err(self.out_of_step(file_error(error)));
} }
let packet = Packet::from(AttachmentPart { self.send(&Packet::from(AttachmentPart {
data: part.to_vec(), 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 /// Writes a message's attachment into `out`, a part at a time, checked
@@ -297,41 +399,31 @@ impl Client {
) -> Result<u64> { ) -> Result<u64> {
check_name(topic, "topic")?; check_name(topic, "topic")?;
check_name(node, "node")?; check_name(node, "node")?;
if !(1..=MAX_MESSAGE_ID).contains(&message_id) { require((1..=MAX_MESSAGE_ID).contains(&message_id), || {
return Err(Error::new( format!("message {message_id}: 1 to {MAX_MESSAGE_ID}")
ErrorCode::InvalidArgument, })?;
format!("message {message_id}: 1 to {MAX_MESSAGE_ID}"),
));
}
let get = GetAttachment { let get = GetAttachment {
topic: topic.to_owned(), topic: topic.to_owned(),
node: node.to_owned(), node: node.to_owned(),
message_id, message_id,
from_part: 0, from_part: 0,
}; };
let attachment = match self.request(get.into())? { let attachment: Attachment = self.request(get.into())?;
Packet::Attachment(attachment) => attachment,
other => return Err(unexpected(&other)),
};
let mut sha256 = digest::Context::new(&digest::SHA256); let mut sha256 = digest::Context::new(&digest::SHA256);
// A failing `out`: the parts are still all read, the connection // A failing `out`: the parts are still all read, the connection
// stays usable. // stays usable.
let mut failed = None; let mut failed = None;
for part in 0..attachment.part_count() { for part in 0..attachment.part_count() {
let data = match self.answer()? { // Parts come without a request each: anything else, a refusal
Packet::AttachmentPart(part) => part.data, // too, leaves the rest of them unread.
other => { let read: Result<AttachmentPart> = self.answer();
self.close(); let data = read.map_err(|error| self.out_of_step(error))?.data;
return Err(unexpected(&other));
}
};
let expected = attachment.part_len(part); let expected = attachment.part_len(part);
if data.len() as u64 != expected { if data.len() as u64 != expected {
self.close(); return Err(self.out_of_step(Error::new(
return Err(Error::new(
ErrorCode::ProtocolError, ErrorCode::ProtocolError,
format!("part {part}: {} bytes, {expected} expected", data.len()), format!("part {part}: {} bytes, {expected} expected", data.len()),
)); )));
} }
sha256.update(&data); sha256.update(&data);
if failed.is_none() { if failed.is_none() {
@@ -389,40 +481,47 @@ impl Client {
) -> Result<Messages> { ) -> Result<Messages> {
check_name(topic, "topic")?; check_name(topic, "topic")?;
check_name(node, "node")?; check_name(node, "node")?;
if !(1..=MAX_MESSAGES_PER_PACKET).contains(&limit) { require((1..=MAX_MESSAGES_PER_PACKET).contains(&limit), || {
return Err(Error::new( format!("a limit of {limit}: 1 to {MAX_MESSAGES_PER_PACKET}")
ErrorCode::InvalidArgument, })?;
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))
} })?;
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)),
));
}
let get = GetMessages { let get = GetMessages {
topic: topic.to_owned(), topic: topic.to_owned(),
node: node.to_owned(), node: node.to_owned(),
after, after,
limit, limit,
}; };
match self.request(get.into())? { self.request(get.into())
Packet::Messages(messages) => Ok(messages),
other => Err(unexpected(&other)),
}
} }
/// The topics with messages that this client may push to or read, or /// 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 /// the nodes with messages in the topics it may read; every one if its
/// roles have `list_topics` / `list_nodes`, or `query`. `truncated` if /// roles have `list_topics` / `list_nodes`, or `query`. `topics` and
/// some didn't fit. /// `nodes` (a name or a pattern, `None` for any) keep those of the
pub fn list_names(&mut self, kind: NameKind) -> Result<NamesList> { /// topic and node pairs they match: the topics a node pushed to, the
match self.request(ListNames { kind }.into())? { /// nodes that pushed to a topic. `truncated` if some didn't fit.
Packet::NamesList(names) => Ok(names), pub fn list_names(
other => Err(unexpected(&other)), &mut self,
kind: NameKind,
topics: Option<&str>,
nodes: Option<&str>,
) -> Result<NamesList> {
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 /// Runs read-only SQL: `{"columns":[...],"rows":[[...],...]}`, every
/// value a string or null (`docs/storage.md`, "The query surface"). /// value a string or null (`docs/storage.md`, "The query surface").
@@ -431,42 +530,113 @@ impl Client {
let query = Query { let query = Query {
sql: sql.to_owned(), sql: sql.to_owned(),
}; };
match self.request(query.into())? { let result: QueryResult = self.request(query.into())?;
Packet::QueryResult(result) => Ok(result.json), Ok(result.json)
other => Err(unexpected(&other)),
}
} }
/// Closes the connection: it's out of step (a part not sent, or not /// Closes the connection for good: every request fails then
/// as expected). Every request fails then (`ConnectionLost`). /// (`NotConnected`).
fn close(&mut self) { fn close(&mut self) {
self.closed = true;
let _ = self.stream.sock.shutdown(Shutdown::Both); let _ = self.stream.sock.shutdown(Shutdown::Both);
} }
/// Sends a request, reads its answer. /// `NotConnected` once closed.
fn request(&mut self, packet: Packet) -> Result<Packet> { fn check_open(&self) -> Result<()> {
frame::write(&mut self.stream, &packet.encode()).map_err(lost)?; match self.closed {
self.stream.flush().map_err(lost)?; 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<T: TryFrom<Packet, Error = Packet>>(&mut self, packet: Packet) -> Result<T> {
self.send(&packet)?;
self.flush()?;
self.answer() self.answer()
} }
/// Reads the server's next packet: a refusal is an error. /// Reads the server's next packet, a `T`: a refusal is an error (the
fn answer(&mut self) -> Result<Packet> { /// connection kept), any other packet closes it (`ProtocolError`, the
let bytes = frame::read(&mut self.stream, MAX_PACKET_SIZE) /// answer isn't the request's), as anything else wrong does.
.map_err(lost)? fn answer<T: TryFrom<Packet, Error = Packet>>(&mut self) -> Result<T> {
.ok_or_else(|| { let packet = self.receive()?;
Error::new( 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<Packet> {
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, ErrorCode::ConnectionLost,
"the server closed the connection", "the server closed the connection",
) )));
})?; }
Err(error) => return Err(self.io_failed(error)),
};
match Packet::decode(&bytes) { match Packet::decode(&bytes) {
Ok(Packet::RequestRefused(refused)) => Err(Error { Ok(Packet::RequestRefused(refused)) => Err(Error {
code: refused.code, code: refused.code,
message: refused.reason, message: refused.reason,
}), }),
Ok(packet) => Ok(packet), 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<()> { /// An argument checked before sending: `InvalidArgument`, saying `why`,
if is_valid_name(name) { /// if it isn't `ok`.
Ok(()) fn require(ok: bool, why: impl FnOnce() -> String) -> Result<()> {
} else { match ok {
Err(Error::new( true => Ok(()),
ErrorCode::InvalidArgument, false => Err(Error::new(ErrorCode::InvalidArgument, why())),
format!("'{name}' isn't a {what} name"),
))
} }
} }
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<()> { fn check_size(text: &str, what: &str) -> Result<()> {
if text.len() <= MAX_MESSAGE_SIZE { require(text.len() <= MAX_MESSAGE_SIZE, || {
Ok(()) format!("{what} of {} bytes: {MAX_MESSAGE_SIZE} at most", text.len())
} else { })
Err(Error::new(
ErrorCode::InvalidArgument,
format!("{what} of {} bytes: {MAX_MESSAGE_SIZE} at most", text.len()),
))
}
} }
fn file_error(error: io::Error) -> Error { fn file_error(error: io::Error) -> Error {
Error::new(ErrorCode::FileError, format!("the attachment: {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()),
)
}
+498
View File
@@ -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<ServerConnection, TcpStream>;
/// 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<Packet> {
let bytes = frame::read(stream, MAX_PACKET_SIZE).ok()??;
Some(Packet::decode(&bytes).unwrap())
}
fn answer(stream: &mut Stream, packet: impl Into<Packet>) {
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<impl std::fmt::Debug, bakashrot_client::Error>,
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<Vec<u8>>,
rewinds: usize,
}
impl Read for FailingSecondTime {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
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<u64> {
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();
}
+7 -4
View File
@@ -11,7 +11,7 @@
[server] [server]
listen = "0.0.0.0:7000" # required: address and port 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. # for its peers, is its certificate's name.
ca = "ca.crt" ca = "ca.crt"
certificate = "server-1.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). # 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 max_attachment_size = "1G" # bytes, or K M G T (1024-based); 0: none
retention_interval = "1m" # how often old messages are deleted 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 # 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 # pushed: 100 years ("36500d") at most, or "forever". A topic takes its
# it, else "*"'s; without any, it's kept forever. # name's line, else the first pattern matching it, else "*"'s; without
# any, it's kept forever.
[retention] [retention]
logs = "30d" logs = "30d"
"sensors.*" = "12h" "sensors.*" = "12h"
@@ -47,7 +50,7 @@ logs = "30d"
push_to = [] # dialed and sent to: ["10.0.0.2:7000", "server-2.lan:7000"] 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 ["*"] accept_from = [] # taken from: ["10.0.0.2", "server-2.lan"], or ["*"]
retry_delay = "10s" 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 batch_size = 1000 # messages per packet, 1-10000
# What certificates with a role may do. A certificate gets everything its # What certificates with a role may do. A certificate gets everything its
+40
View File
@@ -29,6 +29,11 @@ use std::path::{Path, PathBuf};
use std::time::Duration; use std::time::Duration;
use values::{DURATION_HELP, NAME_HELP, parse_age}; 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. /// What's wrong with a config, in words: where (the file, the line) and why.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error(String); pub struct Error(String);
@@ -95,6 +100,22 @@ pub struct Server {
deserialize_with = "values::duration" deserialize_with = "values::duration"
)] )]
pub retention_interval: 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 /// How hard the database makes sure a push is on disk before answering it
@@ -165,6 +186,11 @@ impl TryFrom<IndexMap<String, toml::Value>> for Retention {
let age = age.ok_or_else(|| { let age = age.ok_or_else(|| {
format!("{key} = {value} isn't an age: {DURATION_HELP}, or \"forever\"") 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)); lines.push((key, age));
} }
Ok(Retention { lines }) Ok(Retention { lines })
@@ -185,6 +211,14 @@ impl Retention {
.or_else(|| self.lines.iter().find(|(key, _)| key == "*")) .or_else(|| self.lines.iter().find(|(key, _)| key == "*"))
.and_then(|(_, age)| *age) .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<u64> {
let age = self.age(topic)?;
Some(now.saturating_sub(u64::try_from(age.as_millis()).unwrap_or(u64::MAX)))
}
} }
/// `[replication]`. /// `[replication]`.
@@ -238,6 +272,12 @@ mod defaults {
pub(crate) fn retention_interval() -> Duration { pub(crate) fn retention_interval() -> Duration {
Duration::from_secs(60) 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. /// `[roles.*]`: each section's name is its role's, none twice.
+18 -11
View File
@@ -1,7 +1,7 @@
//! Roles, and what a certificate's roles allow together. //! Roles, and what a certificate's roles allow together.
use crate::values::check_names; use crate::values::check_names;
use bakashrot_proto::names::{names_equal, pattern_matches}; use bakashrot_proto::names::{name_matches, names_equal};
use serde::Deserialize; use serde::Deserialize;
/// Topic or node names and patterns (`sensors.*`, `*` for all), none twice. /// 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 /// Whether `name` is in it: one of its names, or matched by one of its
/// patterns (without case). /// patterns (without case).
pub fn matches(&self, name: &str) -> bool { pub fn matches(&self, name: &str) -> bool {
self.0 self.0.iter().any(|entry| name_matches(entry, name))
.iter()
.any(|entry| names_equal(entry, name) || pattern_matches(entry, name))
} }
/// Whether it has nothing: matches nothing. /// Whether it has nothing: matches nothing.
@@ -117,15 +115,24 @@ impl Permissions {
self.roles.iter().any(|role| role.query) self.roles.iter().any(|role| role.query)
} }
/// Whether listing topics answers every one: `list_topics`, or /// Whether listing names may show `topic`: one it may push to or
/// `query` (which reads them all anyway). /// read, any with `list_topics` or `query` (which reads them all
pub fn lists_every_topic(&self) -> bool { /// anyway).
self.roles.iter().any(|role| role.list_topics || role.query) 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`. /// Whether listing names may show the nodes with messages in `topic`:
pub fn lists_every_node(&self) -> bool { /// one it may read, any with `list_nodes` or `query`.
self.roles.iter().any(|role| role.list_nodes || role.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. /// Whether `node`'s messages in `topic` are sent to it.
+15
View File
@@ -184,6 +184,21 @@ pub(crate) fn batch_size<'de, D: Deserializer<'de>>(reader: D) -> Result<u32, D:
Ok(size) Ok(size)
} }
/// The most idle database connections a server keeps per pool.
pub(crate) const MAX_IDLE_CONNECTIONS: u32 = 512;
/// How many idle database connections to keep, 0 to
/// `MAX_IDLE_CONNECTIONS`.
pub(crate) fn idle_connections<'de, D: Deserializer<'de>>(reader: D) -> Result<usize, D::Error> {
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. /// Checks a list of names or patterns, none twice.
pub(crate) fn check_names(list: &[String]) -> Result<(), String> { pub(crate) fn check_names(list: &[String]) -> Result<(), String> {
for (at, entry) in list.iter().enumerate() { for (at, entry) in list.iter().enumerate() {
+59 -5
View File
@@ -59,6 +59,8 @@ fn defaults() {
assert_eq!(server.synchronous, Synchronous::Full); assert_eq!(server.synchronous, Synchronous::Full);
assert_eq!(server.max_attachment_size, 1 << 30); assert_eq!(server.max_attachment_size, 1 << 30);
assert_eq!(server.retention_interval, Duration::from_secs(60)); 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.retention.age("logs"), None);
assert_eq!(config.replication.retry_delay, Duration::from_secs(10)); assert_eq!(config.replication.retry_delay, Duration::from_secs(10));
assert_eq!(config.replication.sync_interval, Duration::from_secs(5)); assert_eq!(config.replication.sync_interval, Duration::from_secs(5));
@@ -75,6 +77,8 @@ database = "data/messages.sqlite"
synchronous = "NORMAL" synchronous = "NORMAL"
max_attachment_size = 0 max_attachment_size = 0
retention_interval = "1h30m" retention_interval = "1h30m"
idle_database_connections = 0
query_time_limit = "2m"
[replication] [replication]
push_to = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"] 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.synchronous, Synchronous::Normal);
assert_eq!(config.server.max_attachment_size, 0); assert_eq!(config.server.max_attachment_size, 0);
assert_eq!(config.server.retention_interval, Duration::from_secs(5400)); 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.push_to.len(), 3);
assert_eq!(config.replication.accept_from[2], "fd00::4"); assert_eq!(config.replication.accept_from[2], "fd00::4");
assert_eq!(config.replication.retry_delay, Duration::from_secs(60)); assert_eq!(config.replication.retry_delay, Duration::from_secs(60));
@@ -122,6 +128,24 @@ logs = "30d"
assert_eq!(age("other"), days(365)); 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] #[test]
fn permissions() { fn permissions() {
let config = Config::parse(&with( let config = Config::parse(&with(
@@ -164,19 +188,23 @@ accept_nodes = ["garage"]
assert!(both.can_read("Logs")); assert!(both.can_read("Logs"));
assert!(!both.can_read("sensors.garage")); assert!(!both.can_read("sensors.garage"));
assert!(!both.can_query()); 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(); let admin = config.permissions(&["admin"]).unwrap();
assert!(admin.can_query()); assert!(admin.can_query());
// A query reads them all anyway. // A query reads them all anyway; reading messages is still read_topics.
assert!(admin.lists_every_topic() && admin.lists_every_node()); assert!(admin.may_list_topic("other") && admin.may_list_nodes_of("other"));
assert!(!admin.can_read("logs"));
let listing = Config::parse(&with( let listing = Config::parse(&with(
"[roles.a]\nlist_topics = true\n[roles.b]\nlist_nodes = true\n", "[roles.a]\nlist_topics = true\n[roles.b]\nlist_nodes = true\n",
)) ))
.unwrap(); .unwrap();
let a = listing.permissions(&["a"]).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(); 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. // Replication: each role's topics with that role's nodes, not mixed.
let peer = config.permissions(&["peer", "backup"]).unwrap(); let peer = config.permissions(&["peer", "backup"]).unwrap();
@@ -273,6 +301,18 @@ fn refusals() {
&with("retention_interval = \"0s\"\n"), &with("retention_interval = \"0s\"\n"),
"'0s' isn't a duration", "'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] // [retention]
( (
&with("[retention]\nlogs = \"30\"\n"), &with("[retention]\nlogs = \"30\"\n"),
@@ -291,6 +331,16 @@ fn refusals() {
&with("[retention]\nsensors.kitchen = \"1d\"\n"), &with("[retention]\nsensors.kitchen = \"1d\"\n"),
"quote names with dots", "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] // [replication]
( (
&with("[replication]\npush_to = [\"10.0.0.2\"]\n"), &with("[replication]\npush_to = [\"10.0.0.2\"]\n"),
@@ -338,6 +388,10 @@ fn refusals() {
&with("[roles.r]\naccept_nodes = [\"x\", \"X\"]\n"), &with("[roles.r]\naccept_nodes = [\"x\", \"X\"]\n"),
"'X' is given twice", "'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.r]\nquery = 1\n"), "invalid type: integer"),
(&with("[roles.site.reader]\n"), "unknown field `reader`"), (&with("[roles.site.reader]\n"), "unknown field `reader`"),
]; ];
+4 -1
View File
@@ -6,7 +6,8 @@
//! What to do about each: //! What to do about each:
//! - reconnect, then retry: `NotConnected`, `ConnectFailed`, //! - reconnect, then retry: `NotConnected`, `ConnectFailed`,
//! `ConnectionLost`, `ProtocolError` (the connection is closed); //! `ConnectionLost`, `ProtocolError` (the connection is closed);
//! - retry later: `NotReady`, `ServerError`; //! - retry later: `NotReady`, `ServerError`, `QueryTimedOut` (or narrow
//! the query);
//! - fix the configuration: `AuthRejected`, `ServerNotVerified`, //! - fix the configuration: `AuthRejected`, `ServerNotVerified`,
//! `NotAllowed`, `UnknownName`; //! `NotAllowed`, `UnknownName`;
//! - update one end: `VersionMismatch`; //! - update one end: `VersionMismatch`;
@@ -74,6 +75,7 @@ error_codes! {
DataMismatch = 8, "An uploaded attachment that doesn't match its SHA-256: dropped."; 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)."; 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."; 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. // The client's own.
NotConnected = 100, "Not connected: never, or the connection was closed or lost before."; NotConnected = 100, "Not connected: never, or the connection was closed or lost before.";
@@ -140,6 +142,7 @@ mod tests {
(8, "DataMismatch"), (8, "DataMismatch"),
(9, "QueryFailed"), (9, "QueryFailed"),
(10, "ServerError"), (10, "ServerError"),
(11, "QueryTimedOut"),
(100, "NotConnected"), (100, "NotConnected"),
(101, "ConnectFailed"), (101, "ConnectFailed"),
(102, "AuthRejected"), (102, "AuthRejected"),
+3 -3
View File
@@ -169,11 +169,11 @@ mod tests {
fn versions() { fn versions() {
let mut stream = Vec::new(); let mut stream = Vec::new();
write_version(&mut stream).unwrap(); 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(); let bytes = read_version(&mut &stream[..]).unwrap();
assert_eq!(check_version(bytes), Ok(())); assert_eq!(check_version(bytes), Ok(()));
assert_eq!(check_version([6, 0, 0, 0]), Err(6)); assert_eq!(check_version([7, 0, 0, 0]), Err(7));
assert_eq!(check_version([8, 0, 0, 0]), Err(8)); assert_eq!(check_version([9, 0, 0, 0]), Err(9));
assert!(read_version(&mut &[7u8, 0][..]).is_err()); assert!(read_version(&mut &[7u8, 0][..]).is_err());
} }
+1 -1
View File
@@ -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. //! tools share, and nothing else.
//! //!
//! No I/O of its own beyond reading and writing frames on a stream it's //! No I/O of its own beyond reading and writing frames on a stream it's
+15 -1
View File
@@ -5,13 +5,22 @@
/// The protocol's version. Both ends must have the same: they tell each /// The protocol's version. Both ends must have the same: they tell each
/// other first thing (`frame::write_version()`), and abandon the /// other first thing (`frame::write_version()`), and abandon the
/// connection if it differs. /// 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 /// 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 /// isn't BakaShrot doesn't get past it. Not versioned: the version is
/// checked once connected, so a mismatch is told as such. /// checked once connected, so a mismatch is told as such.
pub const ALPN: &[u8] = b"bakashrot"; 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). /// The biggest packet on the wire, in bytes (a frame's size field).
pub const MAX_PACKET_SIZE: usize = 16 * 1024 * 1024; 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. /// The most attachments a `SyncState` lists as missing at once.
pub const MAX_MISSING_ATTACHMENTS: usize = 256; 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. /// Attachments go in parts of this many bytes, the last one what's left.
pub const ATTACHMENT_PART_SIZE: u64 = 1024 * 1024; pub const ATTACHMENT_PART_SIZE: u64 = 1024 * 1024;
+14
View File
@@ -45,6 +45,12 @@ pub fn is_valid_name_or_pattern(text: &str) -> bool {
is_valid_name(text) || is_valid_pattern(text) 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 /// Whether the name `name` matches `pattern` (without case). Anything that
/// isn't a valid name never matches. /// isn't a valid name never matches.
pub fn pattern_matches(pattern: &str, name: &str) -> bool { 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"));
}
} }
+23 -3
View File
@@ -201,16 +201,36 @@ impl TryFrom<u8> 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)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListNames { pub struct ListNames {
/// Topics or nodes. /// Topics or nodes.
pub kind: NameKind, pub kind: NameKind,
/// Only the pairs whose topic is this name or matches this pattern;
/// nil for any.
pub topics: Option<String>,
/// Only the pairs whose node is this name or matches this pattern;
/// nil for any.
pub nodes: Option<String>,
} }
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. /// Topics or nodes.
/// ///
+28 -4
View File
@@ -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 //! 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 //! array, `[type, [field, field, ...]]`. Structs inside are arrays of their
@@ -33,10 +33,10 @@ pub use messages::{
PushMessage, Query, QueryResult, StoredAttachment, PushMessage, Query, QueryResult, StoredAttachment,
}; };
pub use replication::{ pub use replication::{
Head, MissingAttachment, ReplicateAttachment, ReplicateMessages, ReplicatedMessage, SyncState, Head, MissingAttachment, Pair, ReplicateAttachment, ReplicateMessages, ReplicatedMessage,
SyncStateRequest, 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::de::{self, DeserializeOwned, IgnoredAny, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::{Deserialize, Deserializer, Serialize, Serializer};
@@ -144,6 +144,17 @@ macro_rules! packets {
Packet::$name(body) Packet::$name(body)
} }
} }
/// The body of a packet of this type, or the packet back.
impl TryFrom<Packet> 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 { impl Packet {
@@ -244,6 +255,10 @@ packets! {
ReplicateMessages = 17, ReplicateMessages = 17,
/// P→S: an attachment the server is missing, its parts after it (`Continue`, then `MessagePushed` / `RequestRefused`). /// P→S: an attachment the server is missing, its parts after it (`Continue`, then `MessagePushed` / `RequestRefused`).
ReplicateAttachment = 18, 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 { impl Packet {
@@ -298,6 +313,15 @@ pub(crate) mod rules {
require(names::is_valid_name(value), field, "must be a name") 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. /// A message id: 1 and up.
pub fn message_id(value: u64, field: &'static str) -> Result<(), DecodeError> { pub fn message_id(value: u64, field: &'static str) -> Result<(), DecodeError> {
range(value, 1, MAX_MESSAGE_ID, field) range(value, 1, MAX_MESSAGE_ID, field)
@@ -6,20 +6,43 @@
use super::rules; use super::rules;
use super::{Attachment, Check, DecodeError}; use super::{Attachment, Check, DecodeError};
use crate::limits::{ use crate::limits::{
MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_MISSING_ATTACHMENTS, MAX_ATTACHMENT_PARTS, MAX_HEADS_PER_PACKET, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET,
MAX_NAMES_LIST_ENTRIES, MAX_MISSING_ATTACHMENTS, MAX_NAMES_LIST_ENTRIES,
}; };
use crate::names;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// What the server takes from this peer, how far it is, and the /// 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)] #[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<Pair>,
}
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. /// How far the server is in a topic/node pair.
/// ///
@@ -34,6 +57,16 @@ pub struct Head {
pub last_id: u64, 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. /// An attachment the server lacks, and where to go on from.
/// ///
/// `[topic, node, message_id, next_part]` /// `[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 /// 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)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncState { 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 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<String>, pub topics: Vec<String>,
/// The nodes it takes from this peer, the same way. /// The nodes it takes from this peer, the same way.
pub nodes: Vec<String>, pub nodes: Vec<String>,
/// 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<Head>, pub heads: Vec<Head>,
/// The attachments it lacks among those, `MAX_MISSING_ATTACHMENTS` at /// The attachments it lacks among those, `MAX_MISSING_ATTACHMENTS` at
/// most. /// most. Empty after the first page.
pub missing: Vec<MissingAttachment>, pub missing: Vec<MissingAttachment>,
} }
impl Check for SyncState { impl Check for SyncState {
fn check(&self) -> Result<(), DecodeError> { 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 [ for (list, field) in [
(&self.topics, "SyncState.topics"), (&self.topics, "SyncState.topics"),
(&self.nodes, "SyncState.nodes"), (&self.nodes, "SyncState.nodes"),
] { ] {
rules::most(list.len(), MAX_NAMES_LIST_ENTRIES, field)?; rules::most(list.len(), MAX_NAMES_LIST_ENTRIES, field)?;
for item in list { for item in list {
rules::require( rules::name_or_pattern(item, field)?;
names::is_valid_name_or_pattern(item),
field,
"must be a name or a pattern",
)?;
} }
} }
for head in &self.heads { for head in &self.heads {
@@ -74,3 +74,21 @@ impl Check for RequestRefused {
pub struct Continue {} pub struct Continue {}
impl Check for 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 {}
+119 -6
View File
@@ -2,8 +2,9 @@
//! refuses, and that no input makes it panic. //! refuses, and that no input makes it panic.
use bakashrot_proto::limits::{ use bakashrot_proto::limits::{
ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_PARTS, MAX_ATTACHMENT_SIZE, MAX_HEADS_PER_PACKET,
MAX_TIMESTAMP, 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::packets::*;
use bakashrot_proto::{Body, DecodeError, ErrorCode, Packet, PacketType}; use bakashrot_proto::{Body, DecodeError, ErrorCode, Packet, PacketType};
@@ -35,6 +36,8 @@ fn samples() -> Vec<Packet> {
.into(), .into(),
RequestRefused::new(ErrorCode::UnknownName, "Unknown topic 'nope'").into(), RequestRefused::new(ErrorCode::UnknownName, "Unknown topic 'nope'").into(),
Continue {}.into(), Continue {}.into(),
Ping {}.into(),
Pong {}.into(),
PushMessage { PushMessage {
topic: "logs".into(), topic: "logs".into(),
data: "é€ \u{1F600} {\"a\":[1,2]}".into(), data: "é€ \u{1F600} {\"a\":[1,2]}".into(),
@@ -98,6 +101,14 @@ fn samples() -> Vec<Packet> {
AttachmentPart { data: vec![1] }.into(), AttachmentPart { data: vec![1] }.into(),
ListNames { ListNames {
kind: NameKind::Topic, kind: NameKind::Topic,
topics: None,
nodes: None,
}
.into(),
ListNames {
kind: NameKind::Node,
topics: Some("sensors.*".into()),
nodes: Some("kitchen".into()),
} }
.into(), .into(),
NamesList { NamesList {
@@ -114,8 +125,16 @@ fn samples() -> Vec<Packet> {
json: r#"{"columns":["a"],"rows":[[1],[null]]}"#.into(), json: r#"{"columns":["a"],"rows":[[1],[null]]}"#.into(),
} }
.into(), .into(),
SyncStateRequest {}.into(), SyncStateRequest { after: None }.into(),
SyncStateRequest {
after: Some(Pair {
topic: "logs".into(),
node: "kitchen".into(),
}),
}
.into(),
SyncState { SyncState {
more: true,
topics: vec!["logs".into(), "sensors.*".into()], topics: vec!["logs".into(), "sensors.*".into()],
nodes: vec!["*".into()], nodes: vec!["*".into()],
heads: vec![ heads: vec![
@@ -237,6 +256,8 @@ fn golden_bytes() {
] ]
); );
assert_eq!(Continue {}.encode(), [0x92, 0x03, 0x90]); assert_eq!(Continue {}.encode(), [0x92, 0x03, 0x90]);
assert_eq!(Ping {}.encode(), [0x92, 0x13, 0x90]);
assert_eq!(Pong {}.encode(), [0x92, 0x14, 0x90]);
assert_eq!( assert_eq!(
MessagePushed { message_id: 300 }.encode(), MessagePushed { message_id: 300 }.encode(),
[0x92, 0x05, 0x91, 0xcd, 0x01, 0x2c] [0x92, 0x05, 0x91, 0xcd, 0x01, 0x2c]
@@ -290,6 +311,7 @@ fn shapes() {
assert!(malformed(&raw(PacketType::MessagePushed, ((),)))); assert!(malformed(&raw(PacketType::MessagePushed, ((),))));
assert!(malformed(&raw(PacketType::MessagePushed, (1u64, 2u64)))); assert!(malformed(&raw(PacketType::MessagePushed, (1u64, 2u64))));
assert!(malformed(&raw(PacketType::Continue, (1u64,)))); assert!(malformed(&raw(PacketType::Continue, (1u64,))));
assert!(malformed(&raw(PacketType::Ping, (1u64,))));
// The wrong types. // The wrong types.
assert!(malformed(&raw(PacketType::MessagePushed, ("1",)))); assert!(malformed(&raw(PacketType::MessagePushed, ("1",))));
assert!(malformed(&raw(PacketType::MessagePushed, (-1i64,)))); assert!(malformed(&raw(PacketType::MessagePushed, (-1i64,))));
@@ -297,8 +319,18 @@ fn shapes() {
PacketType::Messages, PacketType::Messages,
(1u8, Vec::<u8>::new()) (1u8, Vec::<u8>::new())
))); )));
assert!(malformed(&raw(PacketType::ListNames, (3u8,))), "kind 3"); assert!(
assert!(malformed(&raw(PacketType::ListNames, (0u8,))), "kind 0"); 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!( assert!(
malformed(&raw( malformed(&raw(
PacketType::Attachment, PacketType::Attachment,
@@ -365,6 +397,19 @@ fn ranges() {
assert!(Packet::decode(&get(Some(MAX_MESSAGE_ID), 1)).is_ok()); assert!(Packet::decode(&get(Some(MAX_MESSAGE_ID), 1)).is_ok());
assert!(invalid(&get(Some(MAX_MESSAGE_ID + 1), 1))); 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| { let times = |pushed_at| {
Messages { Messages {
more: false, more: false,
@@ -448,7 +493,26 @@ fn too_many_items() {
}; };
assert!(invalid(&too_many.encode())); 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 { let missing = SyncState {
more: false,
topics: vec![], topics: vec![],
nodes: vec![], nodes: vec![],
heads: vec![], heads: vec![],
@@ -501,6 +565,7 @@ fn names_everywhere() {
let state = |topic: &str| { let state = |topic: &str| {
SyncState { SyncState {
more: false,
topics: vec![topic.into()], topics: vec![topic.into()],
nodes: vec![], nodes: vec![],
heads: vec![], heads: vec![],
@@ -512,6 +577,20 @@ fn names_everywhere() {
assert!(Packet::decode(&state("logs")).is_ok()); assert!(Packet::decode(&state("logs")).is_ok());
assert!(invalid(&state("12"))); assert!(invalid(&state("12")));
assert!(invalid(&state("a b*"))); 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 { let welcome = Welcome {
server: "s".into(), server: "s".into(),
@@ -520,6 +599,40 @@ fn names_everywhere() {
assert!(invalid(&welcome.encode())); 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. /// xorshift64*, enough to make bytes that look like anything.
struct Random(u64); struct Random(u64);
@@ -541,7 +654,7 @@ fn nothing_makes_it_panic() {
let mut bytes: Vec<u8> = (0..len).map(|_| random.next() as u8).collect(); let mut bytes: Vec<u8> = (0..len).map(|_| random.next() as u8).collect();
if round % 2 == 0 && bytes.len() > 2 { if round % 2 == 0 && bytes.len() > 2 {
bytes[0] = 0x92; 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); bytes[2] = 0x90 | (bytes[2] & 0x0f);
} }
let _ = Packet::decode(&bytes); let _ = Packet::decode(&bytes);
+51 -17
View File
@@ -5,9 +5,12 @@
use crate::connection::{Frames, Peer, receive_parts, refused, send}; use crate::connection::{Frames, Peer, receive_parts, refused, send};
use crate::writer::Write; use crate::writer::Write;
use crate::{Shared, now}; 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::{ 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_proto::{ErrorCode, Packet};
use bakashrot_storage::AttachmentState; 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 /// What it takes from this peer, how far it is in those, and the
/// attachments it lacks among them. /// attachments it lacks among them: a page of it, the lists in the first.
pub(crate) async fn sync_state(shared: &Arc<Shared>, peer: &mut Peer) -> Packet { pub(crate) async fn sync_state(
shared: &Arc<Shared>,
peer: &mut Peer,
request: SyncStateRequest,
) -> Packet {
if let Err(refusal) = check_address(shared, peer).await { if let Err(refusal) = check_address(shared, peer).await {
return refusal; return refusal;
} }
let (topics, nodes) = peer.permissions.accepted(); let first = request.after.is_none();
let found = shared let mut after = request.after;
.read(|reader| { let (mut heads, mut more) = (Vec::new(), false);
Ok(( // Read in pages too, those it doesn't take from this peer skipped:
reader.heads()?, // until the page is full and one more is found, or none is left.
reader.missing_attachments(MAX_MISSING_ATTACHMENTS)?, 'pages: loop {
)) let from = after.take();
}) let read = shared
.read(move |reader| reader.heads_after(from.as_ref(), MAX_HEADS_PER_PACKET))
.await; .await;
let (mut heads, mut missing) = match found { let read: Vec<Head> = match read {
Ok(found) => found, 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(), 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)); missing.retain(|missing| peer.permissions.accepts(&missing.topic, &missing.node));
}
SyncState { SyncState {
more,
topics, topics,
nodes, nodes,
heads, heads,
@@ -163,8 +197,8 @@ pub(crate) async fn replicate_messages(
let skip_before = shared let skip_before = shared
.config .config
.retention .retention
.age(&batch.topic) .cutoff(&batch.topic, now())
.map_or(0, |age| now().saturating_sub(age.as_millis() as u64)); .unwrap_or(0);
let write = Write::Replicate { let write = Write::Replicate {
topic: batch.topic, topic: batch.topic,
node: batch.node, node: batch.node,
+79 -42
View File
@@ -6,11 +6,13 @@ use crate::{Shared, accept_from, now};
use aws_lc_rs::digest; use aws_lc_rs::digest;
use bakashrot_config::Permissions; use bakashrot_config::Permissions;
use bakashrot_pki::Identity; use bakashrot_pki::Identity;
use bakashrot_proto::limits::{MAX_MESSAGE_SIZE, MAX_NAMES_LIST_ENTRIES, MAX_PACKET_SIZE}; use bakashrot_proto::limits::{
use bakashrot_proto::names::names_equal; 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::{ use bakashrot_proto::packets::{
Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed, 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_proto::{ErrorCode, Packet, frame};
use bakashrot_storage::AttachmentState; use bakashrot_storage::AttachmentState;
@@ -29,8 +31,9 @@ use tracing::{debug, info};
/// How long TLS and the versions may take. /// How long TLS and the versions may take.
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10); const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
/// How long a connection may stay silent between requests. /// How long a connection may stay silent between requests (a `Ping`
const IDLE_TIMEOUT: Duration = Duration::from_secs(300); /// counts).
const IDLE_TIMEOUT: Duration = Duration::from_secs(IDLE_TIMEOUT_SECS);
/// How long an attachment's next part may take to come. /// How long an attachment's next part may take to come.
const PART_TIMEOUT: Duration = Duration::from_secs(30); const PART_TIMEOUT: Duration = Duration::from_secs(30);
@@ -106,8 +109,13 @@ async fn serve(shared: &Arc<Shared>, tcp: TcpStream, address: IpAddr) -> Result<
} }
Packet::GetMessages(get) => get_messages(shared, &peer, get).await, Packet::GetMessages(get) => get_messages(shared, &peer, get).await,
Packet::ListNames(list) => list_names(shared, &peer, list).await, Packet::ListNames(list) => list_names(shared, &peer, list).await,
Packet::Query(query) => self::query(shared, &peer, query).await, Packet::Query(query) => self::query(shared, &peer, &mut frames, query)
Packet::SyncStateRequest(_) => accept_from::sync_state(shared, &mut peer).await, .await
.map_err(failed)?,
Packet::Ping(_) => Pong {}.into(),
Packet::SyncStateRequest(request) => {
accept_from::sync_state(shared, &mut peer, request).await
}
Packet::ReplicateMessages(batch) => { Packet::ReplicateMessages(batch) => {
accept_from::replicate_messages(shared, &mut peer, batch).await accept_from::replicate_messages(shared, &mut peer, batch).await
} }
@@ -158,6 +166,12 @@ async fn open(
return Err(format!("TLS: {error}")); 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 stream
.write_all(&frame::version_bytes()) .write_all(&frame::version_bytes())
@@ -476,38 +490,50 @@ async fn get_messages(shared: &Arc<Shared>, peer: &Peer, get: GetMessages) -> Pa
} }
} }
/// Topics: those with messages (pushed here or replicated) that it may /// The topics or nodes of the topic and node pairs with messages (pushed
/// push to or read; every one with `list_topics` or `query`. Nodes: those /// here or replicated, or that had some) that the filters match, among
/// with messages in the topics it may read; every one with `list_nodes` /// those it may see. A pair's topic must be one it may see when the answer
/// or `query`. /// 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<Shared>, peer: &Peer, list: ListNames) -> Packet { async fn list_names(shared: &Arc<Shared>, peer: &Peer, list: ListNames) -> Packet {
let permissions = &peer.permissions; let permissions = peer.permissions.clone();
let found = match list.kind { let kind = list.kind;
NameKind::Topic => shared // A pass over every pair: on the read's thread, off the async ones.
.read(|reader| reader.topics()) let found = shared
.await .read(move |reader| {
.map(|mut topics| { let matches = |filter: &Option<String>, name: &str| {
if !permissions.lists_every_topic() { filter
topics .as_deref()
.retain(|topic| permissions.can_push(topic) || permissions.can_read(topic)); .is_none_or(|filter| name_matches(filter, name))
}
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<String> = heads
.into_iter()
.filter(|head| permissions.can_read(&head.topic))
.map(|head| 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
}),
}; };
let check_topic = kind == NameKind::Topic || list.topics.is_some();
let check_node = kind == NameKind::Node || list.nodes.is_some();
let mut names: Vec<String> = reader
.heads()?
.into_iter()
.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();
// 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 { let mut names = match found {
Ok(names) => names, Ok(names) => names,
Err(refused) => return refused.into(), Err(refused) => return refused.into(),
@@ -515,23 +541,34 @@ async fn list_names(shared: &Arc<Shared>, peer: &Peer, list: ListNames) -> Packe
let truncated = names.len() > MAX_NAMES_LIST_ENTRIES; let truncated = names.len() > MAX_NAMES_LIST_ENTRIES;
names.truncate(MAX_NAMES_LIST_ENTRIES); names.truncate(MAX_NAMES_LIST_ENTRIES);
NamesList { NamesList {
kind: list.kind, kind,
truncated, truncated,
names, names,
} }
.into() .into()
} }
async fn query(shared: &Arc<Shared>, 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<Shared>,
peer: &Peer,
frames: &mut Frames,
query: Query,
) -> Result<Packet, String> {
if !peer.permissions.can_query() { if !peer.permissions.can_query() {
return refused( return Ok(refused(
ErrorCode::NotAllowed, ErrorCode::NotAllowed,
format!("{} may not run queries", peer.node), format!("{} may not run queries", peer.node),
); ));
} }
match shared.query(query.sql).await { tokio::select! {
answer = shared.query(query.sql) => Ok(match answer {
Ok(json) => QueryResult { json }.into(), Ok(json) => QueryResult { json }.into(),
Err(refused) => refused.into(), Err(refused) => refused.into(),
}),
// Dropping the query stops it.
_ = frames.next() => Err("left while its query ran: stopped".into()),
} }
} }
+164 -21
View File
@@ -27,12 +27,13 @@ use bakashrot_config::Config;
use bakashrot_pki::{Revocations, SharedRevocations, summarize, tls}; use bakashrot_pki::{Revocations, SharedRevocations, summarize, tls};
use bakashrot_proto::ErrorCode; use bakashrot_proto::ErrorCode;
use bakashrot_proto::packets::RequestRefused; use bakashrot_proto::packets::RequestRefused;
use bakashrot_storage::{Database, QueryRunner, Reader}; use bakashrot_storage::{Database, QueryRunner, Reader, Stop};
use std::collections::HashSet; use std::collections::HashSet;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::Path; use std::path::Path;
use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH}; use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::net::TcpListener; use tokio::net::TcpListener;
use tokio_rustls::{TlsAcceptor, TlsConnector}; use tokio_rustls::{TlsAcceptor, TlsConnector};
use tracing::{info, warn}; use tracing::{info, warn};
@@ -44,6 +45,12 @@ const CRL_POLL: Duration = Duration::from_secs(5);
/// How often the WAL is checkpointed. /// How often the WAL is checkpointed.
const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(1); 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. /// A server, ready to take connections.
#[derive(Clone)] #[derive(Clone)]
pub struct Server { pub struct Server {
@@ -64,9 +71,11 @@ struct Shared {
database: Database, database: Database,
pushes: Pushes, pushes: Pushes,
/// Read connections not in use. /// Read connections not in use.
readers: Mutex<Vec<Reader>>, readers: Pool<Reader>,
/// Query connections not in use. /// Query connections not in use.
queries: Mutex<Vec<QueryRunner>>, queries: Pool<QueryRunner>,
/// Clients' queries running now.
queries_running: AtomicUsize,
/// The replicated attachments being received (topic, node, message /// The replicated attachments being received (topic, node, message
/// id): one peer at a time each (`accept_from.rs`). /// id): one peer at a time each (`accept_from.rs`).
receiving: Mutex<HashSet<(String, String, u64)>>, receiving: Mutex<HashSet<(String, String, u64)>>,
@@ -101,8 +110,7 @@ impl Server {
let pushes = Pushes::start(database.writer().map_err(|error| error.to_string())?) let pushes = Pushes::start(database.writer().map_err(|error| error.to_string())?)
.map_err(|error| format!("the writer's thread: {error}"))?; .map_err(|error| format!("the writer's thread: {error}"))?;
start_checkpoints(&database)?; start_checkpoints(&database)?;
Ok(Server { let shared = Arc::new(Shared {
shared: Arc::new(Shared {
name, name,
acceptor: TlsAcceptor::from(tls), acceptor: TlsAcceptor::from(tls),
connector: TlsConnector::from(dialing), connector: TlsConnector::from(dialing),
@@ -110,12 +118,14 @@ impl Server {
ca, ca,
database, database,
pushes, pushes,
readers: Mutex::new(Vec::new()), readers: Pool::new(),
queries: Mutex::new(Vec::new()), queries: Pool::new(),
queries_running: AtomicUsize::new(0),
receiving: Mutex::new(HashSet::new()), receiving: Mutex::new(HashSet::new()),
config, config,
}), });
}) start_pool_sweeps(&shared)?;
Ok(Server { shared })
} }
/// The server's name: its certificate's. /// The server's name: its certificate's.
@@ -179,6 +189,13 @@ impl Server {
self.shared.pushes.stop().await; 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. /// Reloads the CRL file now: how many certificates it revokes.
pub fn reload_revocations(&self) -> Result<usize, String> { pub fn reload_revocations(&self) -> Result<usize, String> {
let shared = &self.shared; let shared = &self.shared;
@@ -220,35 +237,42 @@ impl Shared {
Ok(sha256) 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<Self>, sql: String) -> Result<String, RequestRefused> { async fn query(self: &Arc<Self>, sql: String) -> Result<String, RequestRefused> {
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( self.pooled(
|shared| &shared.queries, |shared| &shared.queries,
Database::query_runner, 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 .await
} }
/// Runs `work` on an idle connection of `pool`, or a new one, then /// 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<C: Send + 'static, T: Send + 'static>( async fn pooled<C: Send + 'static, T: Send + 'static>(
self: &Arc<Self>, self: &Arc<Self>,
pool: fn(&Shared) -> &Mutex<Vec<C>>, pool: fn(&Shared) -> &Pool<C>,
open: fn(&Database) -> bakashrot_storage::Result<C>, open: fn(&Database) -> bakashrot_storage::Result<C>,
work: impl FnOnce(&C) -> bakashrot_storage::Result<T> + Send + 'static, work: impl FnOnce(&C) -> bakashrot_storage::Result<T> + Send + 'static,
) -> Result<T, RequestRefused> { ) -> Result<T, RequestRefused> {
let shared = self.clone(); let shared = self.clone();
tokio::task::spawn_blocking(move || { tokio::task::spawn_blocking(move || {
let idle = pool(&shared).lock().ok().and_then(|mut idle| idle.pop()); let connection = match pool(&shared).take() {
let connection = match idle {
Some(connection) => connection, Some(connection) => connection,
None => open(&shared.database).map_err(refusal)?, None => open(&shared.database).map_err(refusal)?,
}; };
let value = work(&connection).map_err(refusal); let value = work(&connection).map_err(refusal);
if let Ok(mut idle) = pool(&shared).lock() { let max = shared.config.server.idle_database_connections;
idle.push(connection); pool(&shared).put_back(connection, max, Instant::now());
}
value value
}) })
.await .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<C> {
idle: Mutex<Vec<(C, Instant)>>,
}
impl<C> Pool<C> {
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<C> {
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<Shared>) -> 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 /// 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 /// own, so the writer doesn't do it in the middle of a commit (2.5 times
/// the pushes: `docs/storage.md`, "The benchmark"). /// the pushes: `docs/storage.md`, "The benchmark").
@@ -284,7 +405,8 @@ fn refusal(error: bakashrot_storage::Error) -> RequestRefused {
Error::UnknownName(_) => ErrorCode::UnknownName, Error::UnknownName(_) => ErrorCode::UnknownName,
Error::TooBig(_) => ErrorCode::TooBig, Error::TooBig(_) => ErrorCode::TooBig,
Error::Query(_) => ErrorCode::QueryFailed, Error::Query(_) => ErrorCode::QueryFailed,
Error::Sqlite(_) | Error::Unusable(_) => { Error::QueryTimedOut(_) => ErrorCode::QueryTimedOut,
Error::Sqlite(_) | Error::Unusable(_) | Error::RolledBack => {
warn!("the database: {error}"); warn!("the database: {error}");
return server_error("the database failed"); return server_error("the database failed");
} }
@@ -339,6 +461,27 @@ fn stamp(path: &Path) -> Option<(SystemTime, u64)> {
mod tests { mod tests {
use super::*; 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] #[test]
fn a_clock_before_1970_is_refused() { fn a_clock_before_1970_is_refused() {
assert!(check_clock(UNIX_EPOCH).is_ok()); assert!(check_clock(UNIX_EPOCH).is_ok());
+246 -40
View File
@@ -5,22 +5,26 @@
//! attachments it lacks; again at once if it sent any (it keeps up under //! 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' //! load), after `sync_interval` otherwise. Only what the other server's roles'
//! `send_*` allow. `accept_from.rs` is the other end. //! `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::Shared;
use crate::connection::SEND_TIMEOUT; use crate::connection::SEND_TIMEOUT;
use crate::writer::Write; use crate::writer::Write;
use bakashrot_config::Permissions; use bakashrot_config::Permissions;
use bakashrot_pki::tls; use bakashrot_pki::tls;
use bakashrot_proto::limits::{ALPN, MAX_PACKET_SIZE}; use bakashrot_proto::limits::{ALPN, KEEPALIVE_SECS, MAX_PACKET_SIZE};
use bakashrot_proto::names::{names_equal, pattern_matches}; use bakashrot_proto::names::name_matches;
use bakashrot_proto::packets::{ use bakashrot_proto::packets::{
Attachment, AttachmentPart, MissingAttachment, ReplicateAttachment, ReplicateMessages, Attachment, AttachmentPart, Head, MissingAttachment, Pair, Ping, ReplicateAttachment,
SyncState, SyncStateRequest, ReplicateMessages, RequestRefused, SyncState, SyncStateRequest,
}; };
use bakashrot_proto::{ErrorCode, Packet, frame}; use bakashrot_proto::{ErrorCode, Packet, frame};
use bakashrot_storage::AttachmentState; use bakashrot_storage::AttachmentState;
use futures_util::{SinkExt, StreamExt}; use futures_util::{SinkExt, StreamExt};
use std::collections::HashMap; use std::collections::{BTreeSet, HashMap};
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -48,20 +52,33 @@ pub(crate) async fn run(shared: Arc<Shared>) {
} }
/// Links to `address`, checks in until the link fails, then again after /// 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<Shared>, address: String) { async fn keep_linked(shared: Arc<Shared>, address: String) {
let replication = &shared.config.replication; let replication = &shared.config.replication;
let mut last_failure = String::new(); let mut last_failure = String::new();
let mut not_taken = BTreeSet::new();
loop { loop {
let failure = match Link::open(&shared, &address).await { let failure = match Link::open(&shared, &address).await {
Ok(mut link) => { Ok(mut link) => {
info!("{address}: linked to {}", link.name); info!("{address}: linked to {}", link.name);
last_failure.clear(); last_failure.clear();
loop { loop {
match link.check_in(&shared).await { let checked = match link.check_in(&shared).await {
Ok(true) => {} Ok(sent) => {
Ok(false) => sleep(replication.sync_interval).await, if link.not_taken != not_taken {
Err(why) => break format!("{} ({address}): {why}", link.name), not_taken = link.not_taken.clone();
log_not_taken(&format!("{} ({address})", link.name), &not_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, permissions: Permissions,
/// Whether this check-in sent something it took. /// Whether this check-in sent something it took.
sent: bool, sent: bool,
/// What it may be sent but doesn't take, as of this check-in:
/// "topic:node".
not_taken: BTreeSet<String>,
} }
impl Link { impl Link {
@@ -127,6 +147,7 @@ impl Link {
name: identity.name, name: identity.name,
permissions, permissions,
sent: false, sent: false,
not_taken: BTreeSet::new(),
}; };
match link.receive().await? { match link.receive().await? {
Packet::Welcome(_) => Ok(link), Packet::Welcome(_) => Ok(link),
@@ -139,28 +160,21 @@ impl Link {
/// Whether it sent something it took. /// Whether it sent something it took.
async fn check_in(&mut self, shared: &Arc<Shared>) -> Result<bool, String> { async fn check_in(&mut self, shared: &Arc<Shared>) -> Result<bool, String> {
self.sent = false; self.sent = false;
let state = match self.ask(SyncStateRequest {}.into()).await? { let (state, theirs) = self.sync_state().await?;
Packet::SyncState(state) => state,
Packet::RequestRefused(refused) => return Err(format!("refused: {}", refused.reason)),
other => return Err(unexpected(&other)),
};
let heads = shared let heads = shared
.read(|reader| reader.heads()) .read(|reader| reader.heads())
.await .await
.map_err(|refused| refused.reason)?; .map_err(|refused| refused.reason)?;
let theirs: HashMap<(String, String), u64> = state let (to_send, not_taken) = sort_heads(&self.permissions, &state, heads);
.heads self.not_taken = not_taken;
.iter() for head in to_send {
.map(|head| (key(&head.topic, &head.node), head.last_id)) let after = theirs
.collect(); .get(&key(&head.topic, &head.node))
for head in heads { .copied()
let (topic, node) = (head.topic, head.node); .unwrap_or(0);
if !self.sends(&state, &topic, &node) {
continue;
}
let after = theirs.get(&key(&topic, &node)).copied().unwrap_or(0);
if after < head.last_id { 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 { for missing in state.missing {
@@ -171,16 +185,34 @@ impl Link {
Ok(self.sent) Ok(self.sent)
} }
/// Whether it takes `node`'s messages in `topic` (its `SyncState`) and /// Its `SyncState`, every page: the first (the lists), and the last
/// may be sent them (its roles here). /// id of each topic and node.
fn sends(&self, state: &SyncState, topic: &str, node: &str) -> bool { async fn sync_state(&mut self) -> Result<(SyncState, HashMap<(String, String), u64>), String> {
let listed = |list: &[String], name: &str| { let mut first = self.sync_page(None).await?;
list.iter() let (mut heads, mut more) = (std::mem::take(&mut first.heads), first.more);
.any(|entry| names_equal(entry, name) || pattern_matches(entry, name)) 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));
}; };
listed(&state.topics, topic) let page = self.sync_page(Some(after)).await?;
&& listed(&state.nodes, node) (heads, more) = (page.heads, page.more);
&& self.permissions.sends(topic, node) }
}
/// A page of its `SyncState`, after the pair `after`.
async fn sync_page(&mut self, after: Option<Pair>) -> Result<SyncState, String> {
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 /// A topic and node's messages after `after`, in batches. A refusal
@@ -292,6 +324,24 @@ impl Link {
Ok(()) 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<Packet, String> { async fn ask(&mut self, packet: Packet) -> Result<Packet, String> {
self.send(packet).await?; self.send(packet).await?;
self.receive().await self.receive().await
@@ -326,12 +376,21 @@ async fn check_own_copy(
attachment: &Attachment, attachment: &Attachment,
message: &str, message: &str,
) { ) {
let read = shared.hash_parts(attachment_id, 0..attachment.part_count()); let read = shared
if let Ok(sha256) = read.await .hash_parts(attachment_id, 0..attachment.part_count())
&& sha256.finish().as_ref() == attachment.sha256 .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; return;
} }
}
let damaged = Write::Damaged { let damaged = Write::Damaged {
attachment: attachment_id as u64, 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<bool, RequestRefused>) -> 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<Head>,
) -> (Vec<Head>, BTreeSet<String>) {
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<String>) {
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>) -> 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. /// A topic and node, to compare without case.
fn key(topic: &str, node: &str) -> (String, String) { fn key(topic: &str, node: &str) -> (String, String) {
(topic.to_ascii_lowercase(), node.to_ascii_lowercase()) (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 { fn unexpected(packet: &Packet) -> String {
format!("answered {}", packet.packet_type().name()) 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::<Vec<_>>(),
["logs:garage", "secret:kitchen"]
);
let names: BTreeSet<String> = (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());
}
}
+1 -2
View File
@@ -31,10 +31,9 @@ pub(crate) async fn run(shared: &Arc<Shared>) {
async fn once(shared: &Arc<Shared>) -> Result<(), RequestRefused> { async fn once(shared: &Arc<Shared>) -> Result<(), RequestRefused> {
let now = crate::now(); let now = crate::now();
for topic in shared.read(|reader| reader.topics()).await? { 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; continue;
}; };
let cutoff = now.saturating_sub(age.as_millis() as u64);
let deleted = repeat(shared, MESSAGES_PER_WRITE, |limit| Write::DeleteBefore { let deleted = repeat(shared, MESSAGES_PER_WRITE, |limit| Write::DeleteBefore {
topic: topic.clone(), topic: topic.clone(),
cutoff, cutoff,
+2
View File
@@ -195,6 +195,8 @@ fn write(writer: &mut Writer, group: Vec<(Write, oneshot::Sender<Outcome>)>) {
} }
let mut outcomes = Vec::with_capacity(group.len()); let mut outcomes = Vec::with_capacity(group.len());
let committed = writer.batch(|batch| { 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 { for (write, _) in &group {
outcomes.push(write.run(batch).map_err(refusal)); outcomes.push(write.run(batch).map_err(refusal));
} }
+452 -23
View File
@@ -6,11 +6,13 @@
use bakashrot_client::{Client, Settings}; use bakashrot_client::{Client, Settings};
use bakashrot_config::Config; use bakashrot_config::Config;
use bakashrot_pki::{Ca, Identity, Issued, Revocations, Usage, summarize, tls}; 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::{ use bakashrot_proto::packets::{
Attachment, AttachmentPart, GetAttachment, MessagePushed, Messages, NameKind, PushMessage, Attachment, AttachmentPart, GetAttachment, Head, MessagePushed, Messages, NameKind, Pair, Ping,
ReplicateAttachment, ReplicateMessages, ReplicatedMessage, StoredAttachment, SyncState, Pong, PushMessage, ReplicateAttachment, ReplicateMessages, ReplicatedMessage, StoredAttachment,
SyncStateRequest, SyncState, SyncStateRequest,
}; };
use bakashrot_proto::{ErrorCode, Packet, frame}; use bakashrot_proto::{ErrorCode, Packet, frame};
use bakashrot_server::Server; use bakashrot_server::Server;
@@ -18,8 +20,9 @@ use std::io::{Cursor, Read, Seek, SeekFrom, Write};
use std::net::TcpStream; use std::net::TcpStream;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, Once, PoisonError};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use tokio_rustls::rustls::{ClientConnection, StreamOwned}; use tokio_rustls::rustls::{ClientConfig, ClientConnection, StreamOwned};
const CONFIG: &str = r#" const CONFIG: &str = r#"
[server] [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] #[test]
fn refusals_keep_the_connection() { fn refusals_keep_the_connection() {
let running = Running::start("refusals"); let running = Running::start("refusals");
@@ -298,6 +398,20 @@ fn certificates_refused() {
.unwrap_err(); .unwrap_err();
assert_eq!(error.code(), ErrorCode::ServerNotVerified.code(), "{error}"); 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. // Nothing listening.
let error = Client::connect( let error = Client::connect(
"127.0.0.1:1", "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. // Its open connection goes at its next request, a new one is refused.
let error = connected.push("logs", "{}").unwrap_err(); let error = connected.push("logs", "{}").unwrap_err();
assert_eq!(error.code(), ErrorCode::ConnectionLost.code(), "{error}"); 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(); let error = running.connect(&kitchen).unwrap_err();
assert_eq!(error.code(), ErrorCode::AuthRejected.code(), "{error}"); assert_eq!(error.code(), ErrorCode::AuthRejected.code(), "{error}");
// Others go on. // Others go on.
@@ -596,12 +714,13 @@ fn names() {
.connect(&running.issue("analyst-1", &["analyst"])) .connect(&running.issue("analyst-1", &["analyst"]))
.unwrap(); .unwrap();
let names = |client: &mut Client, kind| { let filtered = |client: &mut Client, kind, topics, nodes| {
let list = client.list_names(kind).unwrap(); let list = client.list_names(kind, topics, nodes).unwrap();
assert_eq!(list.kind, kind); assert_eq!(list.kind, kind);
assert!(!list.truncated); assert!(!list.truncated);
list.names 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. // 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 sensor, NameKind::Topic), ["logs", "sensors"]);
assert_eq!(names(&mut screen, NameKind::Topic), ["logs"]); assert_eq!(names(&mut screen, NameKind::Topic), ["logs"]);
@@ -624,6 +743,55 @@ fn names() {
), ),
ErrorCode::NotAllowed.code() 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. /// Queries: allowed or not, results, refusals.
@@ -872,17 +1040,7 @@ struct Raw(StreamOwned<ClientConnection, TcpStream>);
impl Raw { impl Raw {
fn connect(running: &Running, issued: &Issued) -> Raw { fn connect(running: &Running, issued: &Issued) -> Raw {
let config = tls::client_config( let mut raw = Raw::open(running, issued, |_| {});
&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));
frame::write_version(&mut raw.0).unwrap(); frame::write_version(&mut raw.0).unwrap();
raw.0.flush().unwrap(); raw.0.flush().unwrap();
frame::read_version(&mut raw.0).unwrap(); frame::read_version(&mut raw.0).unwrap();
@@ -890,6 +1048,24 @@ impl Raw {
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<Packet>) { fn send(&mut self, packet: impl Into<Packet>) {
frame::write(&mut self.0, &packet.into().encode()).unwrap(); frame::write(&mut self.0, &packet.into().encode()).unwrap();
self.0.flush().unwrap(); self.0.flush().unwrap();
@@ -980,7 +1156,7 @@ fn attachment_edges() {
.unwrap_err(); .unwrap_err();
assert_eq!(error.code(), ErrorCode::FileError.code(), "{error}"); assert_eq!(error.code(), ErrorCode::FileError.code(), "{error}");
let error = kitchen.push("logs", "{}").unwrap_err(); 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(); let started = Instant::now();
while uploads(&mut analyst) != none_left { while uploads(&mut analyst) != none_left {
assert!( 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 { 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<Pair>) -> SyncState {
raw.send(SyncStateRequest { after });
match raw.receive() { match raw.receive() {
Some(Packet::SyncState(state)) => state, Some(Packet::SyncState(state)) => state,
other => panic!("expected a SyncState, got {other:?}"), 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<String> = Mutex::new(String::new());
struct Writer;
impl Write for Writer {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
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::<Vec<_>>())
.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] #[test]
fn replication_edges() { fn replication_edges() {
// The test plays the peer, over a raw connection. // The test plays the peer, over a raw connection.
@@ -1549,14 +1972,20 @@ fn replication_edges() {
assert_eq!(got.messages[0].data, "m1"); assert_eq!(got.messages[0].data, "m1");
// (`old` had a message, past its age.) // (`old` had a message, past its age.)
assert_eq!( assert_eq!(
reader.list_names(NameKind::Topic).unwrap().names, reader
.list_names(NameKind::Topic, None, None)
.unwrap()
.names,
["elsewhere", "logs", "old"] ["elsewhere", "logs", "old"]
); );
let mut logs_only = running let mut logs_only = running
.connect(&running.issue("lounge", &["logs"])) .connect(&running.issue("lounge", &["logs"]))
.unwrap(); .unwrap();
assert_eq!( assert_eq!(
logs_only.list_names(NameKind::Topic).unwrap().names, logs_only
.list_names(NameKind::Topic, None, None)
.unwrap()
.names,
["logs"] ["logs"]
); );
assert_eq!( assert_eq!(
+82
View File
@@ -26,6 +26,12 @@ impl Writer {
/// rolled back otherwise. Each operation of a [`Batch`] is all or /// rolled back otherwise. Each operation of a [`Batch`] is all or
/// nothing on its own, so `write` may go on after one fails: many /// 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. /// 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<T>(&mut self, write: impl FnOnce(&mut Batch<'_>) -> Result<T>) -> Result<T> { pub fn batch<T>(&mut self, write: impl FnOnce(&mut Batch<'_>) -> Result<T>) -> Result<T> {
let mut batch = Batch { let mut batch = Batch {
transaction: self transaction: self
@@ -33,6 +39,7 @@ impl Writer {
.transaction_with_behavior(TransactionBehavior::Immediate)?, .transaction_with_behavior(TransactionBehavior::Immediate)?,
}; };
let value = write(&mut batch)?; let value = write(&mut batch)?;
batch.check_open()?;
batch.transaction.commit()?; batch.transaction.commit()?;
Ok(value) Ok(value)
} }
@@ -52,9 +59,24 @@ impl Batch<'_> {
/// which it returns. Without a savepoint, the hot path: a push that /// which it returns. Without a savepoint, the hot path: a push that
/// fails leaves at most its topic and node's (empty) stream. /// 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<u64> { pub fn push(&mut self, topic: &str, node: &str, pushed_at: u64, data: &str) -> Result<u64> {
self.check_open()?;
Ok(insert_pushed(&self.transaction, topic, node, pushed_at, data)?.0) 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 /// Stores a pushed message with its attachment, an upload all of whose
/// parts came ([`Batch::write_part`] said so) and whose SHA-256 the /// parts came ([`Batch::write_part`] said so) and whose SHA-256 the
/// caller checked: the attachment is then `ready`. /// 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 /// Runs one operation all or nothing (a savepoint), so the batch can go
/// on after it fails. /// on after it fails.
fn atomic<T>(&mut self, operation: impl FnOnce(&Connection) -> Result<T>) -> Result<T> { fn atomic<T>(&mut self, operation: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
// Outside a transaction, a savepoint would start one of its own,
// committed when released.
self.check_open()?;
let savepoint = self.transaction.savepoint()?; let savepoint = self.transaction.savepoint()?;
let value = operation(&savepoint)?; let value = operation(&savepoint)?;
savepoint.commit()?; savepoint.commit()?;
@@ -421,3 +446,60 @@ pub(crate) fn clean_up(db: &Connection) -> Result<()> {
} }
Ok(()) 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);
}
}
+15 -8
View File
@@ -4,7 +4,7 @@
use crate::{Error, QueryRunner, Reader, Result, SCHEMA_VERSION, Writer}; use crate::{Error, QueryRunner, Reader, Result, SCHEMA_VERSION, Writer};
use bakashrot_config::Synchronous; use bakashrot_config::Synchronous;
use rusqlite::hooks::{AuthAction, AuthContext, Authorization}; use rusqlite::hooks::{AuthAction, AuthContext, Authorization};
use rusqlite::{Connection, OptionalExtension, TransactionBehavior}; use rusqlite::{Connection, OpenFlags, OptionalExtension, TransactionBehavior};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::time::Duration; use std::time::Duration;
@@ -129,19 +129,26 @@ impl Database {
Ok(Reader::new(self.connect()?)) Ok(Reader::new(self.connect()?))
} }
/// A connection for clients' queries: read-only (`query_only`), and /// A connection for clients' queries: the file opened read-only
/// every PRAGMA refused from then on (SQLite's authorizer). Some take /// (`SQLITE_OPEN_READONLY`: the file handle can't write), `query_only`,
/// effect when they're prepared, before a statement can be refused /// and every PRAGMA refused from then on (SQLite's authorizer). Some
/// for what it is: `PRAGMA query_only = 0` turned `query_only` off /// take effect when they're prepared, before a statement can be
/// for the connection's next queries. /// 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<QueryRunner> { pub fn query_runner(&self) -> Result<QueryRunner> {
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.pragma_update(None, "query_only", true)?;
connection.authorizer(Some(|context: AuthContext<'_>| match context.action { connection.authorizer(Some(|context: AuthContext<'_>| match context.action {
AuthAction::Pragma { .. } => Authorization::Deny, AuthAction::Pragma { .. } => Authorization::Deny,
_ => Authorization::Allow, _ => Authorization::Allow,
}))?; }))?;
Ok(QueryRunner::new(connection)) QueryRunner::new(connection)
} }
/// A connection with this database's settings: WAL, `synchronous`, the /// A connection with this database's settings: WAL, `synchronous`, the
+12 -2
View File
@@ -22,7 +22,7 @@ mod reader;
pub use batch::{Batch, Writer}; pub use batch::{Batch, Writer};
pub use database::{Checkpointer, Database, WRITER_CHECKPOINT_PAGES}; 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}; pub use reader::{Attachment, MESSAGES_BYTES, Reader};
use bakashrot_proto::limits::{MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID}; use bakashrot_proto::limits::{MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID};
@@ -55,18 +55,28 @@ pub enum Error {
TooBig(String), TooBig(String),
/// A client's query that failed or isn't read-only: `QueryFailed`. /// A client's query that failed or isn't read-only: `QueryFailed`.
Query(String), 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 { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Error::Sqlite(error) => write!(f, "database: {error}"), 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::Unusable(what)
| Error::Invalid(what) | Error::Invalid(what)
| Error::NotFound(what) | Error::NotFound(what)
| Error::UnknownName(what) | Error::UnknownName(what)
| Error::TooBig(what) | Error::TooBig(what)
| Error::Query(what) => f.write_str(what), | Error::Query(what)
| Error::QueryTimedOut(what) => f.write_str(what),
} }
} }
} }
+133 -5
View File
@@ -1,19 +1,28 @@
//! Clients' read-only SQL (`Query`). //! Clients' read-only SQL (`Query`).
//! //!
//! Read-only three ways: the connection has `query_only` on (SQLite //! Read-only four ways: the file is opened read-only (the handle itself
//! refuses any write), the statement must be one SQLite says only reads //! 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 //! (`sqlite3_stmt_readonly`), and only one statement runs (more is an
//! error, not ignored). PRAGMAs are refused as they're prepared //! error, not ignored). PRAGMAs are refused as they're prepared
//! (`Database::query_runner`'s authorizer): some would change the //! (`Database::query_runner`'s authorizer): some would change the
//! connection, `query_only` included, before the statement is looked //! connection, `query_only` included, before the statement is looked
//! at. The result is JSON, every value a string or null: //! at. The result is JSON, every value a string or null:
//! `{"columns":[...],"rows":[[...],...]}`. //! `{"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 crate::{Error, Result};
use bakashrot_proto::limits::MAX_MESSAGE_SIZE; use bakashrot_proto::limits::MAX_MESSAGE_SIZE;
use rusqlite::Connection; use rusqlite::Connection;
use rusqlite::types::ValueRef; use rusqlite::types::ValueRef;
use serde_json::Value; 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. /// The most rows a query returns, as before.
pub const MAX_QUERY_ROWS: usize = 10_000; 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. /// The biggest result, in bytes of JSON: what a packet carries.
pub const MAX_QUERY_BYTES: usize = MAX_MESSAGE_SIZE; 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<AtomicBool>);
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<Error>,
}
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. /// A read-only connection for clients' queries.
#[derive(Debug)] #[derive(Debug)]
pub struct QueryRunner { pub struct QueryRunner {
connection: Connection, connection: Connection,
watch: Arc<Mutex<Watch>>,
}
fn lock(watch: &Mutex<Watch>) -> std::sync::MutexGuard<'_, Watch> {
watch.lock().unwrap_or_else(PoisonError::into_inner)
} }
impl QueryRunner { impl QueryRunner {
pub(crate) fn new(connection: Connection) -> QueryRunner { pub(crate) fn new(mut connection: Connection) -> Result<QueryRunner> {
QueryRunner { connection } 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 /// Runs one read-only statement: its result as JSON. Refused
/// ([`Error::Query`]) if it isn't one, or fails (SQLite's message, a /// ([`Error::Query`]) if it isn't one, or fails (SQLite's message, a
/// failing row included: never a partial result); [`Error::TooBig`] /// 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<String> { pub fn run(&self, sql: &str) -> Result<String> {
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<String> {
*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<String> {
let failed = |error: rusqlite::Error| Error::Query(explain(error.to_string())); let failed = |error: rusqlite::Error| Error::Query(explain(error.to_string()));
let mut statement = self.connection.prepare(sql).map_err(failed)?; let mut statement = self.connection.prepare(sql).map_err(failed)?;
if !statement.readonly() || statement.column_count() == 0 { 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()), 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()));
}
}
}
+19 -10
View File
@@ -6,10 +6,10 @@ use crate::{
}; };
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID}; use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID};
use bakashrot_proto::packets::{ use bakashrot_proto::packets::{
Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, ReplicatedMessage, Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, Pair, ReplicatedMessage,
StoredAttachment, 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 /// 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. /// 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") 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<Vec<String>> {
self.strings("SELECT DISTINCT node FROM streams ORDER BY node")
}
/// Whether `node` has messages in any topic (or had some). /// Whether `node` has messages in any topic (or had some).
fn has_node(&self, node: &str) -> Result<bool> { fn has_node(&self, node: &str) -> Result<bool> {
self.connection self.connection
@@ -165,11 +160,25 @@ impl Reader {
.map_err(Error::from) .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<Vec<Head>> { pub fn heads(&self) -> Result<Vec<Head>> {
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<Vec<Head>> {
// 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 self.connection
.prepare_cached("SELECT topic, node, last_id FROM streams ORDER BY topic, node")? .prepare_cached(
.query_map([], |row| { "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 { Ok(Head {
topic: row.get(0)?, topic: row.get(0)?,
node: row.get(1)?, node: row.get(1)?,
+106 -3
View File
@@ -3,10 +3,11 @@
use bakashrot_config::Synchronous; use bakashrot_config::Synchronous;
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID}; use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID};
use bakashrot_proto::packets::{Attachment as Sent, ReplicatedMessage}; use bakashrot_proto::packets::{Attachment as Sent, Pair, ReplicatedMessage};
use bakashrot_storage::{AttachmentState, Database, Error, MAX_QUERY_ROWS, MAX_STREAMS}; use bakashrot_storage::{AttachmentState, Database, Error, MAX_QUERY_ROWS, MAX_STREAMS, Stop};
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
const PART: usize = ATTACHMENT_PART_SIZE as usize; const PART: usize = ATTACHMENT_PART_SIZE as usize;
@@ -159,7 +160,6 @@ fn pushing_and_reading() {
// Names, heads. // Names, heads.
assert_eq!(reader.topics().unwrap(), ["logs", "sensors"]); assert_eq!(reader.topics().unwrap(), ["logs", "sensors"]);
assert_eq!(reader.nodes().unwrap(), ["garage", "kitchen"]);
let heads: Vec<_> = reader let heads: Vec<_> = reader
.heads() .heads()
.unwrap() .unwrap()
@@ -174,6 +174,35 @@ fn pushing_and_reading() {
("sensors".into(), "kitchen".into(), 1) ("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("logs", "kitchen").unwrap(), 3);
assert_eq!(reader.last_id("nope", "kitchen").unwrap(), 0); assert_eq!(reader.last_id("nope", "kitchen").unwrap(), 0);
} }
@@ -687,6 +716,28 @@ fn queries() {
json("SELECT count(*) FROM messages")["rows"], json("SELECT count(*) FROM messages")["rows"],
serde_json::json!([["3"]]) 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. // A failing row fails it all, with SQLite's message.
match runner.run("SELECT message_data ->> '$.t' FROM messages") { match runner.run("SELECT message_data ->> '$.t' FROM messages") {
Err(Error::Query(why)) => assert!(why.contains("malformed JSON"), "{why}"), 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<String>| 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] #[test]
fn the_view_reads_by_key_range() { fn the_view_reads_by_key_range() {
let (database, path) = open("plans"); let (database, path) = open("plans");
+8 -4
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "bakashrot-tools" 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 version.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -9,17 +9,21 @@ authors.workspace = true
repository.workspace = true repository.workspace = true
publish.workspace = true publish.workspace = true
# No API to document, and its name is the DLL's library's (cargo doc would # One program, the certificates' commands in it (`bakashrot cert`): aws-lc,
# collide). # 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]] [[bin]]
name = "bakashrot" name = "bakashrot"
path = "src/main.rs"
doc = false doc = false
[dependencies] [dependencies]
bakashrot-client = { path = "../bakashrot-client" } bakashrot-client = { path = "../bakashrot-client" }
bakashrot-pki = { path = "../bakashrot-pki" } bakashrot-pki = { path = "../bakashrot-pki" }
bakashrot-proto = { path = "../bakashrot-proto" } 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 = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154" serde_json = "1.0.154"
time = "0.3.55" time = "0.3.55"
@@ -1,27 +1,16 @@
//! `bakashrot-cert`: makes a CA, issues certificates, revokes them, shows //! `bakashrot cert`: makes a CA, issues certificates, revokes them, shows
//! them. Every file is PEM; keys are written once, never over an existing //! them, with no server. Every file is PEM; keys are written once, never
//! file. See `docs/certificates.md`. //! over an existing file. See `docs/certificates.md`.
use bakashrot_pki::{CA_DAYS, CERTIFICATE_DAYS, Ca, Identity, Revocations, Usage, summarize}; use bakashrot_pki::{CA_DAYS, CERTIFICATE_DAYS, Ca, Identity, Revocations, Usage, summarize};
use clap::{Parser, Subcommand}; use clap::Subcommand;
use std::fs; use std::fs;
use std::io::Write; use std::io::Write;
use std::path::{Path, PathBuf}; 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)] #[derive(Subcommand)]
enum Command { pub enum Command {
/// Makes a new CA: ca.crt and ca.key in --out. Keep ca.key off the /// Makes a new CA: ca.crt and ca.key in --out. Keep ca.key off the
/// servers: whoever has it can make any identity. /// servers: whoever has it can make any identity.
Ca { Ca {
@@ -85,17 +74,8 @@ enum Command {
}, },
} }
fn main() -> ExitCode { /// Runs one of `bakashrot cert`'s commands.
match run(Cli::parse().command) { pub fn run(command: Command) -> Result<(), String> {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("bakashrot-cert: {error}");
ExitCode::FAILURE
}
}
}
fn run(command: Command) -> Result<(), String> {
match command { match command {
Command::Ca { name, days, out } => { Command::Ca { name, days, out } => {
let ca = Ca::create(&name, days).map_err(|e| e.to_string())?; let ca = Ca::create(&name, days).map_err(|e| e.to_string())?;
@@ -1,6 +1,9 @@
//! `bakashrot`: pushes messages, reads them and their attachments, runs //! `bakashrot`: pushes messages, reads them and their attachments, runs
//! queries and lists names from the command line, connecting with a //! 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_client::{Client, Error, Settings};
use bakashrot_proto::error::{code_name, is_refusal_code}; use bakashrot_proto::error::{code_name, is_refusal_code};
@@ -18,12 +21,12 @@ use std::time::Duration;
#[command( #[command(
name = "bakashrot", name = "bakashrot",
version, 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." after_help = "Exits with 0 on success, 1 on a failure, 2 on bad arguments."
)] )]
struct Cli { struct Cli {
/// The client's settings: the server, the CA's certificate, this /// 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")] #[arg(short, long, global = true, default_value = "client.toml")]
config: PathBuf, config: PathBuf,
#[command(subcommand)] #[command(subcommand)]
@@ -102,14 +105,30 @@ enum Command {
}, },
/// Lists the topics this client may use and the nodes of those it may /// 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. /// 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 { List {
/// What to list. /// What to list.
#[arg(value_enum, default_value_t = What::All)] #[arg(value_enum, default_value_t = What::All)]
what: What, what: What,
/// Only of the topics with this name or matching this pattern.
#[arg(long)]
topics: Option<String>,
/// Only of the nodes with this name or matching this pattern.
#[arg(long)]
nodes: Option<String>,
/// Prints JSON, a line per list: {"kind":...,"names":[...],"truncated":...}. /// Prints JSON, a line per list: {"kind":...,"names":[...],"truncated":...}.
#[arg(long)] #[arg(long)]
json: bool, 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. /// Where `messages` starts.
@@ -159,6 +178,7 @@ fn main() -> ExitCode {
fn run(config: &Path, command: Command) -> Result<(), String> { fn run(config: &Path, command: Command) -> Result<(), String> {
match command { match command {
Command::Cert { command } => cert::run(command)?,
Command::Push { Command::Push {
topic, topic,
message, message,
@@ -246,7 +266,10 @@ fn run(config: &Path, command: Command) -> Result<(), String> {
break; break;
} }
if !batch.more { 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)?; let sql = input(&sql)?;
println!("{}", connect(config)?.query(&sql).map_err(failed)?); println!("{}", connect(config)?.query(&sql).map_err(failed)?);
} }
Command::List { what, json } => { Command::List {
what,
topics,
nodes,
json,
} => {
let mut client = connect(config)?; let mut client = connect(config)?;
let kinds = [ let kinds = [
(NameKind::Topic, "topic", "Topics"), (NameKind::Topic, "topic", "Topics"),
@@ -267,7 +295,9 @@ fn run(config: &Path, command: Command) -> Result<(), String> {
) { ) {
continue; 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 { if json {
let json = serde_json::json!({ let json = serde_json::json!({
"kind": name, "kind": name,
+18
View File
@@ -463,6 +463,24 @@ fn queries_and_lists() {
json.ok().out, json.ok().out,
"{\"kind\":\"node\",\"names\":[\"kitchen\"],\"truncated\":false}\n" "{\"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 server
.tool("kitchen", &["list", "everything"]) .tool("kitchen", &["list", "everything"])
.fails(2, "everything"); .fails(2, "everything");
+5 -3
View File
@@ -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 bakashrot_pki::{Revocations, summarize};
use std::fs; use std::fs;
@@ -12,9 +12,11 @@ fn folder(name: &str) -> PathBuf {
folder 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) { 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) .args(args)
.current_dir(folder) .current_dir(folder)
.output() .output()
+10 -7
View File
@@ -1,5 +1,6 @@
# The BakaShrot server's image: bakashrot-server, with the bakashrot and # The BakaShrot server's image: bakashrot-server, with the bakashrot tool
# bakashrot-cert tools beside it. Built from the repository's root: # beside it (bakashrot cert for the certificates). Built from the
# repository's root:
# docker build -f docker/Dockerfile -t bakashrot-server . # docker build -f docker/Dockerfile -t bakashrot-server .
# CI builds it for amd64 and arm64 on a version tag, checks it # 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 # (docker/test.sh) and pushes it to ghcr.io/aziascreations/bakashrot-server
@@ -12,7 +13,7 @@
# from outside the container # from outside the container
# database = "/var/lib/bakashrot/bakashrot.sqlite" # database = "/var/lib/bakashrot/bakashrot.sqlite"
# and the certificates relative to it (ca = "ca.crt", ...). The server runs # 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 # keys readable by their owner only): chown 10001:10001 config/server-1.key
# #
# docker run -d --name bakashrot -p 7000:7000 \ # docker run -d --name bakashrot -p 7000:7000 \
@@ -20,7 +21,7 @@
# ghcr.io/aziascreations/bakashrot-server # ghcr.io/aziascreations/bakashrot-server
# #
# Or docker/compose.yml. `docker stop` stops it cleanly (SIGTERM). # Or docker/compose.yml. `docker stop` stops it cleanly (SIGTERM).
# The tools: docker run --rm <image> bakashrot-cert ... (or bakashrot ...). # The tool: docker run --rm <image> bakashrot cert ... (or bakashrot push ...).
# --- Build --------------------------------------------------------------------- # --- Build ---------------------------------------------------------------------
@@ -30,11 +31,13 @@ FROM rust:1-slim-trixie AS build
WORKDIR /src WORKDIR /src
# Only what the programs are built from (Dockerfile.dockerignore). # Only what the programs are built from (Dockerfile.dockerignore).
COPY . . 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 \ 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 \ && 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 ------------------------------------------------------------------- # --- Runtime -------------------------------------------------------------------
+4 -4
View File
@@ -1,6 +1,6 @@
#!/bin/sh #!/bin/sh
# Smoke-tests a server image, as CI does before pushing it: certificates by # 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 # and reading back over a Docker network, then `docker stop`, which must
# end it cleanly (exit code 0, "stopped"). # end it cleanly (exit code 0, "stopped").
# Usage: docker/test.sh <image> # Usage: docker/test.sh <image>
@@ -27,9 +27,9 @@ tool() {
} }
docker network create "$name" >/dev/null docker network create "$name" >/dev/null
tool bakashrot-cert ca --name "Image test CA" tool bakashrot cert ca --name "Image test CA"
tool bakashrot-cert issue --name server-1 --server tool bakashrot cert issue --name server-1 --server
tool bakashrot-cert issue --name tester --role tester tool bakashrot cert issue --name tester --role tester
cat >"$work/server.toml" <<EOF cat >"$work/server.toml" <<EOF
[server] [server]
listen = "0.0.0.0:7000" listen = "0.0.0.0:7000"
+7 -7
View File
@@ -2,7 +2,7 @@
Who connects to whom, and how it's checked. The code is Who connects to whom, and how it's checked. The code is
`crates/bakashrot-pki` (the library) and `crates/bakashrot-tools` `crates/bakashrot-pki` (the library) and `crates/bakashrot-tools`
(`bakashrot-cert`, the tool). Decided in `../revamp.md`, "Decided". (`bakashrot cert`, the tool's commands). Decided in `../revamp.md`, "Decided".
## The idea ## The idea
@@ -68,7 +68,7 @@ connected, `peer_identity()` gives the other end's `Identity`.
## Revocation ## Revocation
- `bakashrot-cert revoke` writes `ca.crl`, signed by the CA, with every - `bakashrot cert revoke` writes `ca.crl`, signed by the CA, with every
certificate revoked before (written aside, then moved in place). certificate revoked before (written aside, then moved in place).
- A server reads it into `Revocations`, which its TLS setup shares - A server reads it into `Revocations`, which its TLS setup shares
(`SharedRevocations`): replacing what's inside takes effect for the next (`SharedRevocations`): replacing what's inside takes effect for the next
@@ -95,11 +95,11 @@ connected, `peer_identity()` gives the other end's `Identity`.
## The tool ## The tool
``` ```
bakashrot-cert ca --name "Home CA" ca.crt, ca.key bakashrot cert ca --name "Home CA" ca.crt, ca.key
bakashrot-cert issue --name kitchen --role sensor kitchen.crt, kitchen.key bakashrot cert issue --name kitchen --role sensor kitchen.crt, kitchen.key
bakashrot-cert issue --name server-1 --role peer --server bakashrot cert issue --name server-1 --role peer --server
bakashrot-cert revoke kitchen.crt ca.crl bakashrot cert revoke kitchen.crt ca.crl
bakashrot-cert show kitchen.crt bakashrot cert show kitchen.crt
``` ```
`--ca` (the folder of `ca.crt` / `ca.key`, `.` by default), `--out` (where `--ca` (the folder of `ca.crt` / `ca.key`, `.` by default), `--out` (where
+198 -26
View File
@@ -5,29 +5,64 @@ What apps connect with, in layers:
| Layer | Where | For | | Layer | Where | For |
|---|---|---| |---|---|---|
| `bakashrot-client` | `crates/bakashrot-client` | Rust: blocking, one connection per `Client` | | `bakashrot-client` | `crates/bakashrot-client` | Rust: blocking, one connection per `Client` |
| The DLL | `crates/bakashrot-capi`: `bakashrot.dll`, `libbakashrot.so` | C and anything that loads a DLL: the `BakaShrot_*` exports, one connection per process | | The DLL | `crates/bakashrot-capi`: `bakashrot.dll`, `libbakashrot.so` | C and anything that loads a DLL: the `BakaShrot_*` exports, as many clients as needed |
| C header | `bindings/c/bakashrot.h` | generated from the DLL (cbindgen) | | C header | `bindings/c/bakashrot.h` | generated from the DLL (cbindgen) |
| PureBasic | `bindings/purebasic/` | the prototypes and the error codes | | PureBasic | `bindings/purebasic/` | the prototypes and the error codes |
| Python | `bindings/python/bakashrot.py` | `Client` over the DLL (ctypes), standard library only | | Python | `bindings/python/bakashrot.py` | `Client` over the DLL (ctypes), standard library only |
| The tools | `crates/bakashrot-tools`: `bakashrot` | the command line, over `bakashrot-client` | | C# | `bindings/csharp/NibblePoker.BakaShrot.Client/` | `Client` over the DLL (P/Invoke), .NET Framework 2.0 and up, .NET Core, .NET; a NuGet package with every platform's library |
| The tool | `crates/bakashrot-tools`: `bakashrot` | the command line, over `bakashrot-client`; `bakashrot cert`, the certificates |
Decided in `../revamp.md`, "Decided" (2026-11-13). What goes over the Decided in `../revamp.md`, "Decided" (2026-11-13). What goes over the
wire: `protocol.md`; the server's side: `server.md`. wire: `protocol.md`; the server's side: `server.md`.
**Status:** steps 7 to 9: connecting, pushes, messages, attachments, **Status:** steps 7 to 9: connecting, pushes, messages, attachments,
names, queries. names, queries, several clients.
## The Rust client
`bakashrot_client::Client`, blocking, one request at a time. A refusal
(1-99), or an argument refused before anything is sent
(`InvalidArgument`), keeps the connection. **Anything that leaves it out
of step closes it** (2026-11-19): an I/O error, no answer within
`answer_timeout()` (`ConnectionLost`), an answer that isn't the
request's or doesn't decode (`ProtocolError`), an attachment's parts cut
short or of the wrong size, a refusal among them, a source failing
mid-upload (`FileError`). Every request after fails with `NotConnected`
without reading anything: before, the socket stayed open, and a late
answer could be read as the next request's (a push returning the
previous push's id). `is_closed()` says so. The DLL forgets its client
whenever it's closed so (it did on `ConnectionLost` and `ProtocolError`
already; now on a file failing mid-upload too), so connecting again
works; Python and C# go through it.
- `set_answer_timeout()`: how long an answer, or sending a packet, may
take: 30 s (`ANSWER_TIMEOUT`) until changed, more than 0. Longer for a
slow query, say (the server's own limit, `query_time_limit`, is 20 s
by default: `config.md`). Giving up closes the connection, and the
server stops the query it was running then.
- `is_open()` (`&mut self`): false once closed. It reads what's waiting
without blocking, through TLS, then always makes the socket blocking
again (it was left non-blocking when it found the connection gone).
What TLS sends for itself (session tickets, key updates) leaves it
open; the socket's end or TLS's close_notify says the server closed it
(the next request fails with `ConnectionLost`); data sent unasked or a
broken TLS stream leave it out of step, so it's closed (`NotConnected`
after).
- `ping()`: keeps an idle connection open (`protocol.md`, "Rules").
`wait()` sleeps, pinging every `KEEPALIVE_SECS` meanwhile (the
tool's `--follow` uses it).
## Who connects: certificates ## Who connects: certificates
A client is its certificate, issued by the CA the servers trust A client is its certificate, issued by the CA the servers trust
(`certificates.md`, `bakashrot-cert issue`): its name is its node, its (`certificates.md`, `bakashrot cert issue`): its name is its node, its
roles say what it may do on each server (`config.md`). It needs the CA's roles say what it may do on each server (`config.md`). It needs the CA's
certificate (to check the server's), its own certificate and key, and the certificate (to check the server's), its own certificate and key, and the
CA's CRL if there is one (servers it revokes are refused). CA's CRL if there is one (servers it revokes are refused).
### `client.toml` ### `client.toml`
What Python's `Client.from_file()` and the tools read. Paths are relative What Python's `Client.from_file()` and the tool read. Paths are relative
to the file's folder. to the file's folder.
```toml ```toml
@@ -42,8 +77,11 @@ crl = "ca.crl" # optional; a file not there yet: none
Its conventions: Its conventions:
- **One connection per process.** Calls from several threads wait for each - **Clients.** `BakaShrot_CreateClient()` makes one and returns its
other. handle, the first argument of every other export;
`BakaShrot_FreeClient(Client)` frees it. Each client has its own
connection, answers and errors, and different clients can be used from
different threads at once. A bad handle fails with `InvalidArgument`.
- **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or UTF-16 - **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or UTF-16
(`uint16_t*`, `wchar_t*` on Windows; PureBasic uses these), (`uint16_t*`, `wchar_t*` on Windows; PureBasic uses these),
null-terminated. A null string is an empty one where that means null-terminated. A null string is an empty one where that means
@@ -63,25 +101,55 @@ Its conventions:
on the other; the C runtime linked statically on Windows (the release on the other; the C runtime linked statically on Windows (the release
DLL imports system DLLs only). DLL imports system DLLs only).
Every export but `CreateClient` takes the handle first (left out below):
a client's, or an enumeration's for the enumeration getters.
| Exports | What | | Exports | What |
|---|---| |---|---|
| `CreateClient()`, `FreeClient` | a new client's handle (0 if it failed); freed (its enumerations closed), 1 |
| `SetCaCertificate`, `SetCertificate`, `SetPrivateKey`, `SetCrl` (`A`/`W`) | PEM text (starting with `-----BEGIN`), or the path of a file holding it; `SetCrl` null or empty for none. Before connecting (`AlreadyConnected`); a file that can't be read is `FileError` | | `SetCaCertificate`, `SetCertificate`, `SetPrivateKey`, `SetCrl` (`A`/`W`) | PEM text (starting with `-----BEGIN`), or the path of a file holding it; `SetCrl` null or empty for none. Before connecting (`AlreadyConnected`); a file that can't be read is `FileError` |
| `Connect(Host, Port)` (`A`/`W`) | TLS with those; refused: `AuthRejected` (the server refused the certificate), `ServerNotVerified` (this client refused the server's), `NotAllowed` (none of its roles is the server's), `VersionMismatch` | | `Connect(Host, Port)` (`A`/`W`) | TLS with those; refused: `AuthRejected` (the server refused the certificate), `ServerNotVerified` (this client refused the server's), `NotAllowed` (none of its roles is the server's), `VersionMismatch` |
| `IsConnected`, `Disconnect` | `IsConnected` notices a connection the server closed | | `IsConnected`, `Disconnect` | `IsConnected` notices a connection the server closed |
| `Ping` | 1, or 0 if the connection is gone: keeps it open. The server closes one silent for 5 min; the DLL has no thread of its own, so an app idle longer calls it every minute or so |
| `SetAnswerTimeout(Milliseconds)`, `GetAnswerTimeout` | how long an answer may take: 30000 until changed, more than 0 (`InvalidArgument`). Kept across connections, and applied to the current one too (unlike the other settings). Past it, `ConnectionLost`, the connection closed and the server's query stopped |
| `GetNode` (`A`/`W`) | the node the server says this client is | | `GetNode` (`A`/`W`) | the node the server says this client is |
| `PushMessageTo(Topic, Data)` (`A`/`W`) | the id, -1 on failure | | `PushMessageTo(Topic, Data)` (`A`/`W`) | the id, -1 on failure |
| `GetLatestMessageOf(Topic, Node)` (`A`/`W`) | 1, or 0 with `NotFound` when there's none yet | | `GetLatestMessageOf(Topic, Node)` (`A`/`W`) | 1, or 0 with `NotFound` when there's none yet |
| `GetMessages(Topic, Node, After, Limit)` (`A`/`W`) | how many (0 isn't a failure), -1 on failure; then `GetMessageCount`, `SelectMessage(Index)`, `HasMoreMessages` | | `GetMessages(Topic, Node, After, Limit)` (`A`/`W`) | how many (0 isn't a failure), -1 on failure; then `GetMessageCount`, `SelectMessage(Index)`, `HasMoreMessages` |
| `GetMessageId`, `GetMessagePushedAt`, `GetMessageAttachmentSize`, `IsMessageAttachmentReady`, `GetMessageData`/`Topic`/`Node` (`A`/`W`) | the selected message; topic and node as asked | | `GetMessageId`, `GetMessagePushedAt`, `GetMessageAttachmentSize`, `IsMessageAttachmentReady`, `GetMessageData`/`Topic`/`Node` (`A`/`W`) | the selected message; topic and node as asked |
| `ListTopics`, `ListNodes`, then `GetNamesList` (`A`/`W`) | how many; `{"kind":"topic","names":[...],"truncated":false}` | | `ListNames(Kind, Topics, Nodes)` (`A`/`W`), then `GetNamesListAsJson` (`A`/`W`) | how many; `{"kind":"topic","names":[...],"truncated":false}`. 1 topics, 2 nodes, of the topic/node pairs `Topics` and `Nodes` match (a name or a pattern each, null for any): `(1, null, null)` every topic it may see, `(1, null, "kitchen")` the topics kitchen pushed to, `(2, "sensors.*", null)` the nodes that pushed to those |
| `Query(Sql)`, then `GetQueryResult` (`A`/`W`) | `{"columns":[...],"rows":[[...],...]}` | | `Query(Sql)` (`A`/`W`), then `GetQueryResultAsJson` (`A`/`W`) | `{"columns":[...],"rows":[[...],...]}` |
| `EnumerateNames(Kind, Topics, Nodes)` (`A`/`W`), then `NextName`, `GetEnumName` (`A`/`W`), `GetNameCount`, `IsNamesListTruncated` | the same list without JSON: an enumeration's handle (0 on failure, the client's error); see below |
| `EnumerateQuery(Sql)` (`A`/`W`), then `GetQueryColumnCount`, `GetQueryColumnName(Index)` (`A`/`W`), `NextQueryRow`, `GetQueryValue(Index)` (`A`/`W`), `IsQueryValueNull(Index)` | the same result without JSON, a row at a time; see below |
| `CloseEnum` | an enumeration closed: 1, 0 if it wasn't one |
| `PushMessageWithFile(Topic, Data, FilePath)`, `PushMessageWithData(Topic, Data, *Data, Size)` (`A`/`W`) | the id, -1 on failure; the attachment 1 byte and up, as much as the server takes (`TooBig`); a file read twice (its SHA-256 first), one changed in between refused (`DataMismatch`) | | `PushMessageWithFile(Topic, Data, FilePath)`, `PushMessageWithData(Topic, Data, *Data, Size)` (`A`/`W`) | the id, -1 on failure; the attachment 1 byte and up, as much as the server takes (`TooBig`); a file read twice (its SHA-256 first), one changed in between refused (`DataMismatch`) |
| `SaveAttachment(Topic, Node, MessageId, FilePath)` (`A`/`W`) | its size, -1 on failure (`NotFound`, `NotReady`, `AttachmentMismatch`); a failed one leaves no file | | `SaveAttachment(Topic, Node, MessageId, FilePath)` (`A`/`W`) | its size, -1 on failure (`NotFound`, `NotReady`, `AttachmentMismatch`); a failed one leaves no file |
| `LoadAttachment(Topic, Node, MessageId)` (`A`/`W`), then `GetAttachmentData(*Buffer, Size)`, `FreeAttachmentData()` | into memory, for small ones; the getter returns the size, copies nothing if it doesn't fit | | `LoadAttachment(Topic, Node, MessageId)` (`A`/`W`), then `GetAttachmentData(*Buffer, Size)`, `FreeAttachmentData()` | into memory, for small ones; the getter returns the size, copies nothing if it doesn't fit |
| `GetLastError`, `GetRefusalReason` (`A`/`W`) | why the last call failed | | `GetLastError`, `GetRefusalReason` (`A`/`W`) | why the client's last call failed |
The header has each one's comment. Every name starts with `BakaShrot_`. The header has each one's comment. Every name starts with `BakaShrot_`.
**Enumerations**, like Win32's `FindFirstFile` / `FindNextFile` /
`FindClose`: `EnumerateNames()` or `EnumerateQuery()` asks the server
once and keeps the whole answer; `NextName()` / `NextQueryRow()` move to
the next item (1, 0 once there are no more, -1 for a handle that isn't
one of that kind), the getters read it. An enumeration starts before its
first item, so `while (BakaShrot_NextName(e) == 1)` reads them all, none
for an empty list. Several can be open at once, even on one client; the
client's later calls don't change them. They don't outlive their client:
`FreeClient()` closes them, their handles refused after. Otherwise
`CloseEnum()` once done. Their handles are numbered with the clients',
never reused: one is never the other's. A value's getter returns 0 for a
null, `IsQueryValueNull()` tells it from an empty string.
```c
int64_t e = BakaShrot_EnumerateNamesW(client, 1, NULL, L"kitchen");
while (BakaShrot_NextName(e) == 1) {
BakaShrot_GetEnumNameW(e, name, sizeof name); /* a topic kitchen pushed to */
}
BakaShrot_CloseEnum(e);
```
## Python ## Python
`bindings/python/bakashrot.py`: `Client(server, ca, `bindings/python/bakashrot.py`: `Client(server, ca,
@@ -89,32 +157,96 @@ certificate, key, crl=None)` (PEM text or paths) or
`Client.from_file("client.toml")` (Python 3.11+, `tomllib`; the rest runs `Client.from_file("client.toml")` (Python 3.11+, `tomllib`; the rest runs
on 3.8), `client.node` once connected, `push(data, topic, on 3.8), `client.node` once connected, `push(data, topic,
attachment=None)` (the topic required; the attachment bytes or a path), attachment=None)` (the topic required; the attachment bytes or a path),
`latest()`, `get_messages()`, `iter_messages()`, `follow()`, `latest()`, `get_messages()`, `iter_messages()`, `follow()` (pinging
every minute while it waits longer), `ping()` (`KEEPALIVE_SECONDS`),
`answer_timeout` (seconds, `ANSWER_TIMEOUT_SECONDS` until set; before
connecting or while connected),
`get_attachment()` (bytes), `save_attachment()` (a file), `get_attachment()` (bytes), `save_attachment()` (a file),
`list_topics()` / `list_nodes()` (names), `query()` / `query_raw()`. `list_topics()` / `list_nodes()` (names; `topic=` and `node=`, a name or
a pattern each, filter them: `list_topics(node="kitchen")` the topics
kitchen pushed to), `query()` / `query_raw()`.
Strings go to the DLL as UTF-8 C strings: one with a NUL (a message, a
name, SQL, a path) is refused (`INVALID_ARGUMENT`) rather than cut there.
Each `Client` has its own client in the DLL: several can be connected at
once, from any threads.
Errors: `RefusedError`, `ConnectionLostError`, `AuthError` (a certificate Errors: `RefusedError`, `ConnectionLostError`, `AuthError` (a certificate
refused, either way, or no role allowed), `BakaShrotError`. The DLL is refused, either way, or no role allowed), `BakaShrotError`. The DLL is
looked for next to the module, or `BAKASHROT_DLL`. The release has a looked for next to the module, or `BAKASHROT_DLL`. The release has a
wheel with the library in it (`pip install bakashrot-*.whl`, nothing else: wheel with the library in it (`pip install bakashrot-*.whl`, nothing else:
`bindings/python/make_wheel.py`, `../README.md`, "Releases"). `bindings/python/make_wheel.py`, `../README.md`, "Releases").
## C#
The NuGet package `NibblePoker.BakaShrot.Client` (namespace
`NibblePoker.BakaShrot`), or `bindings/csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs`,
one file to copy into a project. C# 2 and .NET 2.0's class library only:
built for `net35` (it references `mscorlib` 2.0 only, so .NET Framework
2.0 and 3.x load it, 4.x too) and `netstandard2.0` (.NET Core 2.0 and up,
.NET 5 and up). The assembly is `NibblePoker.BakaShrot.Client.dll`, not
`BakaShrot.dll`, which is the library's name on Windows.
The package has the library for Windows and Linux, x64 and ARM64, in
`runtimes/<rid>/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<string>`) 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 ## PureBasic
`bindings/purebasic/BakaShrot_Client_Prototypes.pbi` (with `bindings/purebasic/BakaShrot_Client_Prototypes.pbi` (with
`BakaShrot_ErrorCodes.pbi`): `BakaShrot_LoadClient("bakashrot.dll")`, then `BakaShrot_ErrorCodes.pbi`): `BakaShrot_LoadClient("bakashrot.dll")`, then
the `W` exports without their suffix, `BakaShrot_*String()` helpers for the the `W` exports without their suffix, the client first, and
getters. Run directly, it's an example: `ClientExample <DllPath> <CaFile> `BakaShrot_*String(Client)` helpers for the getters. Run directly, it's an example: `ClientExample <DllPath> <CaFile>
<CertificateFile> <KeyFile> <Host> <Port>`, pushing a message and one <CertificateFile> <KeyFile> <Host> <Port>`, pushing a message and one
with an attachment, reading both back (run by hand against a server; with an attachment, reading both back, then a second client at the same
not in CI, which has no PureBasic). time (run by hand against a server; not in CI, which has no PureBasic).
## The tools ## The tool
`bakashrot`, one program to push, read, query and list (`bakashrot-cert`, `bakashrot`, one program to push, read, query and list, and to make the
for the CA, is apart: `certificates.md`). Each command connects with certificates (`bakashrot cert`, no server needed: `certificates.md`).
`-c <file>` (`client.toml` by default), does one thing and exits: 0, 1 on a Each other command connects with `-c <file>` (`client.toml` by default),
failure (why on stderr: `Refused by the server (NotAllowed): ...`, does one thing and exits: 0, 1 on a failure (why on stderr: `Refused by
`Failed to connect to ...`), 2 on bad arguments. `--help` on each. the server (NotAllowed): ...`, `Failed to connect to ...`), 2 on bad
arguments. `--help` on each.
```text ```text
bakashrot push logs '{"t":21}' Pushed as message #42 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 query "SELECT topic, count(*) FROM messages GROUP BY topic"
bakashrot list Topics (2): ... Nodes (1): ... bakashrot list Topics (2): ... Nodes (1): ...
bakashrot list nodes --json {"kind":"node","names":["kitchen"],"truncated":false} 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 - **`messages`:** the first 100 by default (`--limit 0` for all), `--after
<id>` or `latest`; data as stored, a line break in it spanning lines; <id>` or `latest`; data as stored, a line break in it spanning lines;
`--follow` checks every `--interval` ms (500) until stopped or the `--follow` checks every `--interval` ms (500, up to an hour, pinging
connection fails (exit 1); `--time` adds the push time between the id and every minute meanwhile) until stopped or the connection fails (exit 1); `--time` adds the push time between the id and
the data. the data.
- **Attachments:** `push -a <file>`; `attachment` replaces the file, - **Attachments:** `push -a <file>`; `attachment` replaces the file,
leaves none if it fails; `latest` says a message's (", not on this 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 ## 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: `crates/bakashrot-capi/tests/`, each against a server on a free port:
- `exports.rs`: the exports as C calls them: certificates from files and - `exports.rs`, `exports`: the exports as C calls them, on one client: certificates from files and
PEM, the `W` strings (and some `A`), the buffers (the size, too small, PEM, the `W` strings (and some `A`), the buffers (the size, too small,
unaligned), selecting messages, attachments (from a file and memory, unaligned), selecting messages, attachments (from a file and memory,
saved and loaded, the buffer, refused ones), every refusal and the saved and loaded, the buffer, refused ones), every refusal and the
client's own errors, closing, another identity. client's own errors, closing, another identity.
- `python.rs`: runs `bindings/python/check_bakashrot.py` on the DLL; skipped, saying so, without Python 3.11+. - `exports.rs`, `clients`: two clients at once, each with its own answers
and errors; bad and freed handles; 4 threads on 4 clients; a client
freed while another thread uses it.
- `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 <DllPath>
<CaFile> <CertificateFile> <KeyFile> <Host> <Port>`. 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 - `header.rs`: `bindings/c/bakashrot.h` matches the exports (rewritten
when it doesn't: check it in). when it doesn't: check it in).
+24 -2
View File
@@ -49,7 +49,7 @@ that browses a server: reading a topic is still `read_topics`. `query`
gives both, it reads everything anyway. gives both, it reads everything anyway.
No `AllowRead` / `AllowWrite`: a list that's empty allows nothing. No 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 **The roles are the only lists of topics** (decided 2026-11-16): no
`[server] topics`, no `[replication] replicated_topics`, both refused as `[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, `[roles."site.reader"]`. Unquoted, TOML reads dots as tables: refused,
`[retention]` says to quote. `[retention]` says to quote.
- **Durations:** numbers with a unit (`s m h d w`), added up: `"30s"`, - **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. - **Sizes:** bytes, or `"500M"` with `K M G T` (1024-based), up to 1T.
- **Paths:** relative ones are from the config file's folder. - **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 ## Retention
A topic takes its name's line, else the first pattern matching it in the A topic takes its name's line, else the first pattern matching it in the
+2 -15
View File
@@ -42,9 +42,8 @@ network**, not exposed to the internet. So:
server then needs every node's public key). server then needs every node's public key).
- **Private keys sit in PEM files**, readable by whoever can read them: on - **Private keys sit in PEM files**, readable by whoever can read them: on
trusted machines, file permissions are enough. trusted machines, file permissions are enough.
- **One connection per process in the DLL** (`revamp.md`, - **Polling rather than pushed subscriptions;** nothing reconnects by
"Open questions"): a handle-based API for several. Polling rather than itself, on purpose.
pushed subscriptions; nothing reconnects by itself, on purpose.
- **At least once:** a push whose answer was lost (the server stopped - **At least once:** a push whose answer was lost (the server stopped
between committing and answering) is stored twice if retried. A client between committing and answering) is stored twice if retried. A client
that minds reads the latest message before retrying. that minds reads the latest message before retrying.
@@ -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. 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. 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`, - **Resuming a big replicated attachment.** Before answering `Continue`,
the receiver reads back and hashes every part it already has the receiver reads back and hashes every part it already has
(`accept_from.rs`, `replicate_attachment`, `hash_parts`), while the (`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 the example config says so by `max_attachment_size` (1 GiB by
default). Fix if needed: a wait scaled to the parts already received, default). Fix if needed: a wait scaled to the parts already received,
or the hash's state kept with the attachment. 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 - **Peers with several roles.** `SyncState` lists the union of its
roles' `accept_topics` and the union of their `accept_nodes` roles' `accept_topics` and the union of their `accept_nodes`
(`Permissions::accepted`), while what's taken is each role on its (`Permissions::accepted`), while what's taken is each role on its
+9 -9
View File
@@ -10,7 +10,7 @@ example configs.
| Machine | What runs there | Files it gets | | 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-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` | | 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` | | 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) ## 1. The certificates (admin)
``` ```
bakashrot-cert ca --name "Lab CA" bakashrot cert ca --name "Lab CA"
bakashrot-cert issue --name server-1 --role peer --server bakashrot cert issue --name server-1 --role peer --server
bakashrot-cert issue --name server-2 --role peer --server bakashrot cert issue --name server-2 --role peer --server
bakashrot-cert issue --name kitchen --role sensor bakashrot cert issue --name kitchen --role sensor
bakashrot-cert issue --name dashboard --role dashboard bakashrot cert issue --name dashboard --role dashboard
bakashrot-cert issue --name lab-py --role sensor --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 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 takes them; it logs once that server-2 refused), start server-2: within
about 10 s every one is on dashboard, in order. 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). `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 Within 5 s they reload it (`INFO ca.crl: reloaded, 1 revoked`), and the
certificate is refused, at its next connection or request: 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) 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-<platform>.whl` (from the **Python.** `pip install bakashrot-0.4.0-py3-none-<platform>.whl` (from the
release's `python/`), then, next to lab-py's `client.toml` (it may push and release's `python/`), then, next to lab-py's `client.toml` (it may push and
read: `sensor` and `dashboard`): read: `sensor` and `dashboard`):
+40 -12
View File
@@ -1,4 +1,4 @@
# Protocol 7 # Protocol 8
What goes over a connection between a client and a server, or two servers. What goes over a connection between a client and a server, or two servers.
The code is `crates/bakashrot-proto`; this describes it. 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 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 CRL: servers check it, and so do clients given it (servers dialing their
peers too). peers too).
- **ALPN `bakashrot`** (`limits::ALPN`): both ends offer it, what isn't - **ALPN `bakashrot`** (`limits::ALPN`): both ends offer it and check it
BakaShrot doesn't get past the TLS handshake. It isn't versioned. 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 - **The versions, first:** right after TLS, each end sends its protocol
version, 4 bytes little-endian (`frame::write_version()`), and reads the version, 4 bytes little-endian (`frame::write_version()`), and reads the
other's (`frame::check_version()`). Different versions: both ends 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 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()` arrived. The blocking client reads and writes them with `frame::read()`
/ `write()`, the async server with `frame::codec()` (`tokio-util`). / `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 ## Packets
@@ -83,8 +91,9 @@ format, its values are checked all the same.)
### Types ### Types
Direction: **C** client, **S** server, **P** peer (a server linked to 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 another, as its client). Ids are protocol 7's own (6 can't connect; 8
packet takes the next one, none is ever reused. added `ListNames`' filters and `SyncState`'s pages); a new packet takes
the next one, none is ever reused.
| Id | Packet | Dir | Fields | Answered by | | 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 | | 8 | GetAttachment | C→S | `topic`, `node`, `message_id`, `from_part` | Attachment then its parts / RequestRefused |
| 9 | Attachment | S→C | `size`, `sha256` | | | 9 | Attachment | S→C | `size`, `sha256` | |
| 10 | AttachmentPart | C→S, S→C, P→S | `data` bin, 1 B to 1 MiB | | | 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) | | | 12 | NamesList | S→C | `kind`, `truncated` bool, `[name...]` (65536 at most) | |
| 13 | Query | C→S | `sql` str | QueryResult / RequestRefused | | 13 | Query | C→S | `sql` str | QueryResult / RequestRefused |
| 14 | QueryResult | S→C | `json` str: `{"columns":[...],"rows":[[...],...]}` | | | 14 | QueryResult | S→C | `json` str: `{"columns":[...],"rows":[[...],...]}` | |
| 15 | SyncStateRequest | P→S | none | SyncState / RequestRefused | | 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 | `[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) | | | 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 | | 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 | | 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 ## 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) 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 An attachment C: GetAttachment(from_part) S: Attachment, then AttachmentPart x the rest
/ RequestRefused (NotFound, NotReady) / 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: ReplicateMessages x the batches S: MessagePushed each / RequestRefused
P: ReplicateAttachment x missing S: Continue / RequestRefused P: ReplicateAttachment x missing S: Continue / RequestRefused
(NotReady: another peer sending it) (NotReady: another peer sending it)
P: AttachmentPart x from next_part S: MessagePushed / RequestRefused 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. - **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. them failed, then refuses: the client never has to read while sending.
- **A server failing while it sends parts** closes the connection; the - **A server failing while it sends parts** closes the connection; the
client asks again `from_part` the next one it needs. client asks again `from_part` the next one it needs.
- **Replication:** `SyncState` is all a check-in needs. The peer compares - **Replication:** `SyncState` is all a check-in needs. Its heads come
it with what it has, by name, sends the messages the server lacks in 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 batches of up to `batch_size` messages and about 1 MiB (a bigger
message alone), then the attachments it listed. message alone), then the attachments it listed.
## Rules ## Rules
- **One request at a time:** a client sends one, waits for its answer (the - **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, - **Refuse or abort:** valid but not allowed or not found (permissions,
unknown names, over a limit, a failed query) is a `RequestRefused` with a 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 code, the connection stays. Malformed or out of order (a bad frame, a
+53 -16
View File
@@ -7,7 +7,7 @@ the wire: `protocol.md`.
**Status:** steps 5, 6, 9, 10, 11 and 12: connecting, pushes and their **Status:** steps 5, 6, 9, 10, 11 and 12: connecting, pushes and their
attachments, messages, attachments, names, queries, retention, 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 ## Running
@@ -50,12 +50,13 @@ Restart=on-failure
`docker/Dockerfile` (its comments have the details), the image `docker/Dockerfile` (its comments have the details), the image
`ghcr.io/aziascreations/bakashrot-server` (amd64 and arm64, pushed by CI `ghcr.io/aziascreations/bakashrot-server` (amd64 and arm64, pushed by CI
on a version tag): the server, with `bakashrot` and `bakashrot-cert` on a version tag): the server, with the `bakashrot` tool beside it
beside it, on `debian:trixie-slim`, as uid 10001. (`bakashrot cert` for the certificates), on `debian:trixie-slim`, as
uid 10001.
- **The config** in `/etc/bakashrot`, read-only: `server.toml`, the - **The config** in `/etc/bakashrot`, read-only: `server.toml`, the
certificates, the server's key (readable by uid 10001: `chown 10001` 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. "0.0.0.0:7000"`: 127.0.0.1 isn't reachable from outside.
- **The database** in `/var/lib/bakashrot`, a volume: `database = - **The database** in `/var/lib/bakashrot`, a volume: `database =
"/var/lib/bakashrot/bakashrot.sqlite"`. "/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 7000:7000 -v ./config:/etc/bakashrot:ro -v
bakashrot-data:/var/lib/bakashrot <image>`. `docker stop` is SIGTERM: bakashrot-data:/var/lib/bakashrot <image>`. `docker stop` is SIGTERM:
a clean stop. The logs: `docker logs`. a clean stop. The logs: `docker logs`.
- **The tools:** `docker run --rm <image> bakashrot-cert ...`. - **The tool:** `docker run --rm <image> bakashrot cert ...` (or
`bakashrot push ...`).
- **Checked** by `docker/test.sh <image>` (CI runs it on both before - **Checked** by `docker/test.sh <image>` (CI runs it on both before
pushing): certificates by the image's tool, its server, a push read pushing): certificates by the image's tool, its server, a push read
back over a Docker network, `docker stop` ending it cleanly. 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 | | 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 | | 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`) | | 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 | | 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 | | 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 1. `SyncStateRequest`: the other server answers what it takes from this
one (topics and nodes, patterns included), its last id in each topic 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 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 its roles here may be sent (`send_topics`, `send_nodes`), and where
it's behind, the messages after its it's behind, the messages after its
last id, `batch_size` (1000) at a time and about 1 MiB at most (a 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 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 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 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 here: damaged (a disk, a bug), this server's copy is dropped and asked
for again from its own peers (`replicating`, not served meanwhile), 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 **Receiving** (`accept_from.rs`): replication requests are answered only
if the connection comes from `accept_from` (a hostname looked up at its 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 ## A connection
1. **TLS:** the client's certificate must be the CA's, valid, not revoked, 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 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 closes (1 s at most). Closing at once reset the connection (the
client's version bytes unread), which could beat the alert to 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 | | | Timeout | |
|---|---| |---|---|
| TLS, versions, welcome | 10 s (the server); the client's connect too | | 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 | | 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 | | An attachment's next part | 30 s (the server), then it closes |
## Requests so far ## 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 replicated), those the roles may push to or read (every one with
`list_topics` or `query`); nodes are those with messages in the `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. 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, - **`Query`:** the roles must allow it (`NotAllowed`); read-only SQL,
refused with SQLite's message (`QueryFailed`, with a hint to add refused with SQLite's message (`QueryFailed`, with a hint to add
`is_json = 1` on "malformed JSON"), over 10,000 rows or 16 MB `is_json = 1` on "malformed JSON"), over 10,000 rows or 16 MB
(`TooBig`), never a partial result (`storage.md`, "The query surface"). (`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 - **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 connection; messages up to `MAX_MESSAGE_SIZE` (16 MB less 4 KB), the
server refusing bigger ones (`TooBig`); the client refuses messages and 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, `Client::connect(address, settings)` (`host:port`, the CA's certificate,
the client's certificate and key, the CRL if any), then `push(topic, the client's certificate and key, the CRL if any), then `push(topic,
data)`, `get_messages(topic, node, after, limit)`, `list_names(kind)`, data)`, `get_messages(topic, node, after, limit)`, `list_names(kind,
`query(sql)`. Blocking, no runtime. The DLL and the bindings over it: topics, nodes)`, `query(sql)`. Blocking, no runtime. The DLL and the bindings over it:
`client.md`. `client.md`.
Attachments: `push_with_attachment(topic, data, source)`, the source any Attachments: `push_with_attachment(topic, data, source)`, the source any
@@ -330,7 +356,7 @@ each:
isn't one line of JSON; 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 - 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; 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 - 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 messages saying theirs; none, or no such message, refused leaving no
file; another reader, one not allowed; over the server's limit, 0 for 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); part on, something else than a part (closed, dropped);
- queries: not allowed, results, a non-JSON row - queries: not allowed, results, a non-JSON row
refused with the hint, errors, writes and two statements refused; 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 - refusals keeping the connection (not allowed, unknown topic, a bad name
the client catches); the client catches);
- certificates refused (no known role, with why; another CA's client; a - 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 - revoked certificates (an open connection dropped at its next request, a
new one refused, others going on, a bad CRL refused); new one refused, others going on, a bad CRL refused);
- six connections pushing at once (one id stream per node, none lost or - 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 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 SHA-256), one not matching refused and asked for from the start, a
certificate whose roles take nothing refused; 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 - two peers, one attachment (two raw connections): the second refused
while the first sends it (names in any case), the first finishing it; 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 one gone partway, the other going on from there; one whole but never
+26 -8
View File
@@ -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 batch goes on after one fails: the server queues pushes and stores them
together, one disk flush for all. 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 | | Operation | What |
|---|---| |---|---|
| `push(topic, node, pushed_at, data)` | the next id of its stream, which it returns; the stream is made if new | | `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 | | 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 | | `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` | | `topics()` | the topics with messages | `streams` |
| `heads()`, `last_id(topic, node)` | each stream's last id: `SyncState` | `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 | | `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) | | `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 | | `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 ## The query surface
Clients' `Query` runs on `Database::query_runner()`, read-only three ways: Clients' `Query` runs on `Database::query_runner()`, read-only four ways:
the connection is `query_only`, the statement must be one SQLite says only the file is opened read-only (`SQLITE_OPEN_READONLY`, 2026-11-19: the
reads, and one statement only (more is refused, not ignored). PRAGMAs are 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 refused as they're prepared ("not authorized", SQLite's authorizer), the
`pragma_*` table functions too: some take effect at that point, and `pragma_*` table functions too: some take effect at that point, and
`PRAGMA query_only = 0`, though refused, turned `query_only` off for the `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 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 - **By topic, or topic and node:** ranges of the table, read in order (a
test checks the plans). test checks the plans).
- **Filters on `pushed_at` or `message_id`** read the streams they're in, - **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 foreign keys: one writer keeps the tables consistent, `CHECK`s keep the
values valid. values valid.
- SQLite is compiled in (`rusqlite`'s `bundled`): the same version - 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 ## 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 - **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 migration adding an index on `(stream_id, pushed_at)` and joining the
view on it too (measured above: twice the write cost). 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 - **Attachments as files** next to the database instead of in it, if their
size calls for it. size calls for it.
+8 -7
View File
@@ -2,13 +2,14 @@
[Index](readme.md) · Next: [Server](2-server.md) [Index](readme.md) · Next: [Server](2-server.md)
More options: `bakashrot-cert.exe <command> --help`. Made by `bakashrot.exe`'s `cert` commands, with no server needed.
More options: `bakashrot.exe cert <command> --help`.
## The root certificate ## The root certificate
```shell ```shell
bakashrot-cert.exe ca --name bakashrot-test bakashrot.exe cert ca --name bakashrot-test
``` ```
Resulting files: Resulting files:
@@ -19,7 +20,7 @@ Resulting files:
## A server certificate ## A server certificate
```shell ```shell
bakashrot-cert.exe issue --server --name server-lan1 bakashrot.exe cert issue --server --name server-lan1
Wrote .\server-lan1.crt Wrote .\server-lan1.crt
Wrote .\server-lan1.key Wrote .\server-lan1.key
``` ```
@@ -31,11 +32,11 @@ See [???]().
## Node certificates ## Node certificates
```shell ```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.crt
Wrote .\node-sensor.key 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.crt
Wrote .\node-viewer.key Wrote .\node-viewer.key
``` ```
@@ -48,7 +49,7 @@ Wrote .\node-viewer.key
## Checking one ## Checking one
```shell ```shell
bakashrot-cert.exe show node-sensor.crt bakashrot.exe cert show node-sensor.crt
node-sensor.crt node-sensor.crt
name: node-sensor name: node-sensor
roles: sensor roles: sensor
@@ -62,7 +63,7 @@ node-sensor.crt
## Revoking one ## Revoking one
```shell ```shell
bakashrot-cert.exe revoke node-sensor.crt bakashrot.exe cert revoke node-sensor.crt
``` ```
* Writes `ca.crl` (every certificate revoked so far). * Writes `ca.crl` (every certificate revoked so far).
+1 -1
View File
@@ -115,7 +115,7 @@ accept_nodes = ["*"] # Accepts every foreign node's messages (Default)
> list_topics = true > list_topics = true
> list_nodes = 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 ### Retention
+15
View File
@@ -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 ## Refused
```shell ```shell
+2 -2
View File
@@ -15,12 +15,12 @@ Who gets which files:
| Machine | 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` | | 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` | | 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` | | viewer | `bakashrot.exe`, `ca.crt`, `node-viewer.crt`, `node-viewer.key`, `viewer.toml` |
More: More:
* `bakashrot <command> --help`, `bakashrot-cert <command> --help`. * `bakashrot <command> --help`, `bakashrot cert <command> --help`.
* Two replicating servers, Python, Docker: `docs/lab.md`. * Two replicating servers, Python, Docker: `docs/lab.md`.
* Every setting: `docs/config.md`. * Every setting: `docs/config.md`.
+1
View File
@@ -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 C library (`bakashrot.dll`, `libbakashrot.so`), with a C header and PureBasic prototypes
* A CLI tool to push, read, query and list * 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 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 ## Limitations
+4 -2
View File
@@ -1,12 +1,14 @@
# A release for this platform, built, packaged and smoke-tested, into # A release for this platform, built, packaged and smoke-tested, into
# target\dist\ (release.py, Python 3.11+, does it all). # target\dist\ (release.py, Python 3.11+, does it all).
# Usage: powershell -ExecutionPolicy Bypass -File release.ps1 [-SkipTest] # Usage: powershell -ExecutionPolicy Bypass -File release.ps1 [-SkipTest] [-HybridCrt]
param([switch]$SkipTest) # (-HybridCrt: the UCRT from Windows, see release.py's --hybrid-crt)
param([switch]$SkipTest, [switch]$HybridCrt)
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Stop"
# The py launcher if it's there, python otherwise. # The py launcher if it's there, python otherwise.
$python = if (Get-Command py -ErrorAction SilentlyContinue) { @("py", "-3") } else { @("python") } $python = if (Get-Command py -ErrorAction SilentlyContinue) { @("py", "-3") } else { @("python") }
$arguments = @(Join-Path $PSScriptRoot "release.py") $arguments = @(Join-Path $PSScriptRoot "release.py")
if ($SkipTest) { $arguments += "--skip-test" } if ($SkipTest) { $arguments += "--skip-test" }
if ($HybridCrt) { $arguments += "--hybrid-crt" }
& $python[0] @($python | Select-Object -Skip 1) @arguments & $python[0] @($python | Select-Object -Skip 1) @arguments
exit $LASTEXITCODE exit $LASTEXITCODE
+53 -33
View File
@@ -1,33 +1,38 @@
"""Builds a BakaShrot release for this machine's platform (Windows or """Builds a BakaShrot release for this machine's platform (Windows or
Linux, x64 or ARM64), checks it works, and archives it: 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/: Into target/dist/:
bakashrot-<version>-<platform>/ the release: bakashrot-<version>-<platform>/ the release:
bakashrot-server, bakashrot, bakashrot-cert the programs bakashrot-server, bakashrot the programs
bakashrot.dll / libbakashrot.so the client library (C) bakashrot.dll / libbakashrot.so the client library (C)
include/bakashrot.h its C header include/bakashrot.h its C header
purebasic/*.pbi its PureBasic prototypes purebasic/*.pbi its PureBasic prototypes
python/bakashrot.py the Python client, over it python/bakashrot.py the Python client, over it
python/bakashrot-<version>-*.whl the same with the library in it python/bakashrot-<version>-*.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 server.example.toml, client.example.toml the configs, documented
docs/ docs/ docs/ docs/
README.txt what's where, how to start README.txt what's where, how to start
LICENSE.txt, THIRD-PARTY.txt BakaShrot's (CC0), its dependencies' LICENSE.txt, THIRD-PARTY.txt BakaShrot's (CC0), its dependencies'
bakashrot-<version>-<platform>.zip (Windows) or .tar.gz (Linux) bakashrot-<version>-<platform>.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 The check (unless --skip-test), in the release folder's _test/ (exes run
from temp folders get blocked by antivirus here), deleted after unless 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 server started on a free port with a throwaway database, then the tool
pushing (and an attachment of 3 MB), reading back, listing, querying; pushing (and an attachment of 3 MB), reading back, listing, querying;
Python through the library, then the wheel installed by pip and used with 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 no path given; then the server stopped as a service manager would
(SIGTERM, or Ctrl+Break on Windows), which must end cleanly. (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 The version is the workspace's (Cargo.toml), which bakashrot.py's
__version__ must match. Needs Python 3.11+ (tomllib) and cargo (rustup). __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" WINDOWS = sys.platform == "win32"
EXE = ".exe" if WINDOWS else "" EXE = ".exe" if WINDOWS else ""
LIBRARY = "bakashrot.dll" if WINDOWS else "libbakashrot.so" LIBRARY = "bakashrot.dll" if WINDOWS else "libbakashrot.so"
PROGRAMS = ["bakashrot-server", "bakashrot", "bakashrot-cert"] # Each built with its profile (Cargo.toml), into target/<profile>/.
CRATES = ["bakashrot-server", "bakashrot-tools", "bakashrot-capi"] PROGRAMS = {"bakashrot-server": "release", "bakashrot": "release-tools"}
CRATES = {"bakashrot-server": "release", "bakashrot-capi": "release", "bakashrot-tools": "release-tools"}
CLIENT_EXAMPLE = """\ CLIENT_EXAMPLE = """\
# What the bakashrot tool and Python's Client.from_file() read, to connect # 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 # to a server. Paths are relative to this file's folder. See
# docs/client.md. # docs/client.md.
server = "10.0.0.2:7000" # host:port, [an IPv6 address]:port server = "10.0.0.2:7000" # host:port, [an IPv6 address]:port
ca = "ca.crt" # the CA's certificate (bakashrot-cert ca) ca = "ca.crt" # the CA's certificate (bakashrot cert ca)
certificate = "kitchen.crt" # this node's (bakashrot-cert issue --name kitchen ...) certificate = "kitchen.crt" # this node's (bakashrot cert issue --name kitchen ...)
key = "kitchen.key" key = "kitchen.key"
# crl = "ca.crl" # optional: certificates the CA revoked # crl = "ca.crl" # optional: certificates the CA revoked
""" """
@@ -162,13 +168,17 @@ def third_party():
return "\n".join(lines) + "\n" 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") built = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
rustc = run(["rustc", "--version"]).strip() 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"""\ return f"""\
BakaShrot {version} ({name}) 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 Licenses: BakaShrot is CC0 (LICENSE.txt); the crates built into it are
listed in THIRD-PARTY.txt with their licenses. 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, replicate them between servers. docs/ has the details (config.md,
certificates.md, server.md, client.md, protocol.md). certificates.md, server.md, client.md, protocol.md).
Certificates (bakashrot-cert{EXE}; docs/certificates.md): 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 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 server-1 --server a server's
bakashrot-cert issue --name kitchen --role sensor a client's: its node, its roles bakashrot cert issue --name kitchen --role sensor a client's: its node, its roles
bakashrot-cert revoke kitchen.crt ca.crl bakashrot cert revoke kitchen.crt ca.crl
The server (bakashrot-server{EXE} server.toml; docs/config.md, server.md): The server (bakashrot-server{EXE} server.toml; docs/config.md, server.md):
server.example.toml has every setting. It logs to the console 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 The client library ({LIBRARY}): the BakaShrot_* exports, include/bakashrot.h
for C, purebasic/ for PureBasic, python/bakashrot.py for Python (no 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. 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 release: another version's connection is refused. Nothing from the old
(PureBasic) BakaShrot is read: not its configs, keys or databases. (PureBasic) BakaShrot is read: not its configs, keys or databases.
""" """
def build(): def build(hybrid):
print("Building") """Each profile's crates at once; the folder of a profile's output."""
command = ["cargo", "build", "--release", "--locked"] print("Building" + (" (the hybrid C runtime)" if hybrid else ""))
for crate in CRATES: 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] command += ["-p", crate]
run(command) run(command)
return os.path.join(HERE, "target", "release") 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}") print(f"Packaging {out}")
for program in PROGRAMS: for program, profile in PROGRAMS.items():
shutil.copy2(os.path.join(built, program + EXE), out) shutil.copy2(os.path.join(built(profile), program + EXE), out)
shutil.copy2(os.path.join(built, LIBRARY), out) shutil.copy2(os.path.join(built(CRATES["bakashrot-capi"]), LIBRARY), out)
bindings = os.path.join(HERE, "bindings") bindings = os.path.join(HERE, "bindings")
os.makedirs(os.path.join(out, "include")) os.makedirs(os.path.join(out, "include"))
shutil.copy2(os.path.join(bindings, "c", "bakashrot.h"), 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")) shutil.copytree(os.path.join(bindings, "purebasic"), os.path.join(out, "purebasic"))
os.makedirs(os.path.join(out, "python")) os.makedirs(os.path.join(out, "python"))
shutil.copy2(os.path.join(bindings, "python", "bakashrot.py"), 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.copytree(os.path.join(HERE, "docs"), os.path.join(out, "docs"))
shutil.copy2(os.path.join(HERE, "crates", "bakashrot-config", "example.toml"), shutil.copy2(os.path.join(HERE, "crates", "bakashrot-config", "example.toml"),
os.path.join(out, "server.example.toml")) os.path.join(out, "server.example.toml"))
write(os.path.join(out, "client.example.toml"), CLIENT_EXAMPLE) write(os.path.join(out, "client.example.toml"), CLIENT_EXAMPLE)
shutil.copy2(os.path.join(HERE, "LICENSE"), os.path.join(out, "LICENSE.txt")) 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, "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"), 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, LIBRARY), os.path.join(out, "python"),
os.path.join(out, "LICENSE.txt"), os.path.join(out, "THIRD-PARTY.txt")]).strip() 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): if not re.search(pattern, got, re.MULTILINE):
fail(f"{what}: unexpected output:\n{got}") fail(f"{what}: unexpected output:\n{got}")
tool("bakashrot-cert", "ca", "--name", "Release test CA") tool("bakashrot", "cert", "ca", "--name", "Release test CA")
tool("bakashrot-cert", "issue", "--name", "server-1", "--server") tool("bakashrot", "cert", "issue", "--name", "server-1", "--server")
tool("bakashrot-cert", "issue", "--name", "tester", "--role", "tester") tool("bakashrot", "cert", "issue", "--name", "tester", "--role", "tester")
port = free_port() port = free_port()
write(os.path.join(test, "server.toml"), f"""\ write(os.path.join(test, "server.toml"), f"""\
[server] [server]
@@ -328,7 +347,7 @@ key = "tester.key"
expect("query", tool("bakashrot", "query", expect("query", tool("bakashrot", "query",
"SELECT message_data ->> '$.value' AS v FROM messages WHERE topic = 'releasetest' AND message_id = 1"), "SELECT message_data ->> '$.value' AS v FROM messages WHERE topic = 'releasetest' AND message_id = 1"),
r'"rows":\[\["42"\]\]') 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" 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" "with bakashrot.Client.from_file('client.toml', sys.argv[2]) as c:\n"
@@ -382,7 +401,7 @@ def archive(out):
def main(): def main():
args = set(sys.argv[1:]) args = set(sys.argv[1:])
if args - {"--skip-test"}: if args - {"--skip-test", "--hybrid-crt"}:
sys.exit(__doc__) sys.exit(__doc__)
# rustup's folder isn't on every shell's PATH. # 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"] 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.remove(old)
os.makedirs(out) os.makedirs(out)
print(f"BakaShrot {release} for {name}, into {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: if "--skip-test" not in args:
shutil.rmtree(smoke_test(out, wheel)) shutil.rmtree(smoke_test(out, wheel))
print(f"Archive: {archive(out)}") print(f"Archive: {archive(out)}")
+170 -19
View File
@@ -2,10 +2,10 @@
Started 2026-11-13: what it should change, what's decided, what's still 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, 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-config`, `bakashrot-storage`, `bakashrot-server` and
`bakashrot-client` answering every request, attachments included, the C `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 retention, replication, operations and releases, then the finish: one
test runner, CI, Docker, `bench.ps1`), see "Plan". 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 unloaded (`BakaShrot_UnloadClient()`) and Windows' loader lock is
never in the way; never in the way;
- the C runtime linked statically on Windows (`+crt-static`), built - 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 - `W` exports take UTF-16 everywhere (PureBasic's strings; `wchar_t` is
32 bits on Linux); 32 bits on Linux);
- the toolchain pinned (`rust-toolchain.toml`), a C header generated - 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 config (warned in its log: a CRL deleted by mistake) and
`client.toml` (the tool, Python's `from_file()`). A path given `client.toml` (the tool, Python's `from_file()`). A path given
to the DLL's `SetCrl` or Python's `Client(crl=...)` is asked for 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 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; 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 - 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; block each other whichever end dials;
- revoked by certificate, not by name: each certificate has its own key - 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, 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`: - **The server's config is TOML** (2026-11-13), `docs/config.md`:
- `[server]`, `[retention]`, `[replication]`, `[roles.<name>]`; unknown - `[server]`, `[retention]`, `[replication]`, `[roles.<name>]`; unknown
keys refused; names only (no ids, pins or ranges); 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 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 it may read (every node until then). Names only, reading is still
`read_topics`. `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 - **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). opened, their data isn't carried over (the real-life tests start empty).
`docs/storage.md`: `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 - **the old exports that don't fit any more are dropped**, not kept
failing: the keys and node setters, the id-based ones, the default failing: the keys and node setters, the id-based ones, the default
topic's `PushMessage()`; topic's `PushMessage()`;
- **one connection per process**, as before (handles maybe later); - **one connection per process**, as before (replaced by handles
2026-11-17, below);
- **`client.toml`** (server, ca, certificate, key, crl) replaces - **`client.toml`** (server, ca, certificate, key, crl) replaces
`client.ini`: Python's `Client.from_file()`, the tools at step 8. `client.ini`: Python's `Client.from_file()`, the tools at step 8.
- **The tools** (2026-11-14), `docs/client.md`, "The tools": one - **The tools** (2026-11-14), `docs/client.md`, "The tools": one
`bakashrot` program with subcommands (`push`, `latest`, `messages`, `bakashrot` program with subcommands (`push`, `latest`, `messages`,
`query`, `list`) over `bakashrot-client`, `bakashrot-cert` kept apart `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 output; messages and SQL inline, `@file` or `-` (standard input); exit
codes 0, 1, and 2 for bad arguments. codes 0, 1, and 2 for bad arguments.
- **Attachments** (2026-11-14), `docs/server.md` and `client.md`: - **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; - **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 - **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, 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, - **The PureBasic version removed** (2026-11-15): `OldSource/` deleted,
kept in git history (up to `68966a8`). What of its notes and designs 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 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 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 they're built and checked), no token left on disk by checkout, actions
pinned to commits, `--locked` builds. 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 ## Proposed, to confirm
@@ -283,24 +436,17 @@ Also decided (2026-11-13):
## Open questions ## Open questions
- **A handle-based DLL API** (several connections per process, old open item None right now.
10): later maybe, the owner's call (one connection per process for now).
## The old open items ## The old open items
The PureBasic version's, still not fixed: The PureBasic version's, still not fixed:
- **Gaps in a topic and node's ids** aren't detected on replication (6), - **Gaps in a topic and node's ids** aren't detected on replication (6):
and **`SyncState` is one packet** (9): `docs/known-issues.md`. `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 - **Peers are trusted with what they replicate** (12), unless messages
get signed by their node: `docs/known-issues.md`. 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 ## 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 | | 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 | | 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`) | | 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 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 docs, `docs/`, this file's status), then a commit when the owner