mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Added a C# binding, packaged as NibblePoker.BakaShrot.Client on NuGet
- bindings/csharp/NibblePoker.BakaShrot.Client: P/Invoke over the DLL's UTF-16 exports, one Client per handle (namespace NibblePoker.BakaShrot). C# 2 and the .NET 2.0 BCL only: net35 (.NET Framework 2.0 and up) and netstandard2.0 (.NET Core 2.0 and up, .NET 5 and up) - No JSON or TOML parsing: ListTopics, ListNodes and Query return the raw JSON string for the caller to parse; settings go to the constructor - The package: the four native libraries under runtimes/<rid>/native/, their THIRD-PARTY.txt under licenses/<rid>/, and a build/net35 .targets copying the right one next to .NET Framework apps (which ignore runtimes/) - CI: a nuget job after the four release builds packs it with the release's version and libraries, checks the listing and keeps it as the bakashrot-nuget artifact - Tests: an NUnit project (net48 and net8.0) against a real server with certificates from `bakashrot cert`, 13 tests - release.py ships BakaShrot.cs in csharp/; docs/client.md, building.md, readme.md, revamp.md (step 14) updated Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
# On a version tag, or run by hand: the same checks as test.ps1 (Windows
|
||||
# and Linux), then a release for each platform (release.py), its archive
|
||||
# kept as the run's artifact, and the server's Docker image for amd64 and
|
||||
# kept as the run's artifact, the C# client's NuGet package with their four
|
||||
# libraries (an artifact too), and the server's Docker image for amd64 and
|
||||
# arm64, checked (docker/test.sh), pushed to ghcr.io on a tag only. Gitea
|
||||
# Actions runs this file too.
|
||||
#
|
||||
@@ -112,6 +113,65 @@ jobs:
|
||||
target/dist/*.tar.gz
|
||||
if-no-files-found: error
|
||||
|
||||
nuget:
|
||||
# The C# client's NuGet package (docs/client.md, "C#"): the four
|
||||
# releases' libraries in runtimes/<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:
|
||||
# The server's image, each architecture built on its own kind of
|
||||
# machine (no emulation), checked, then pushed as <version>-<arch> on a
|
||||
|
||||
@@ -14,6 +14,10 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
|
||||
# C#
|
||||
bindings/csharp/*/bin/
|
||||
bindings/csharp/*/obj/
|
||||
|
||||
# Rust
|
||||
target/
|
||||
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
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\""));
|
||||
}
|
||||
|
||||
[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.Close();
|
||||
Assert.That(kitchen.Connected, Is.False);
|
||||
ConnectionLostException lost = Assert.Throws<ConnectionLostException>(() => kitchen.Push("logs", "x"))!;
|
||||
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 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
@@ -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,445 @@
|
||||
// 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,
|
||||
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; }
|
||||
}
|
||||
}
|
||||
|
||||
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 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_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>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: 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)
|
||||
Thread.Sleep(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()
|
||||
{
|
||||
lock (sync)
|
||||
return Names(Native.BakaShrot_ListTopics(Handle()), "List topics");
|
||||
}
|
||||
|
||||
/// <summary>The nodes with messages in the topics this client may
|
||||
/// read, as ListTopics() says them.</summary>
|
||||
public string ListNodes()
|
||||
{
|
||||
lock (sync)
|
||||
return Names(Native.BakaShrot_ListNodes(Handle()), "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_GetQueryResultW);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Inside ---------------------------------------------------------
|
||||
|
||||
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_GetNamesListW);
|
||||
}
|
||||
|
||||
// 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 client, byte[] buffer, IntPtr size);
|
||||
|
||||
// A string getter: the size first (bytes, the terminator included), then the copy.
|
||||
private string GetString(Getter getter)
|
||||
{
|
||||
int size = getter(handle, null, IntPtr.Zero).ToInt32();
|
||||
if (size <= 2)
|
||||
return "";
|
||||
byte[] buffer = new byte[size];
|
||||
getter(handle, buffer, new IntPtr(size));
|
||||
return Encoding.Unicode.GetString(buffer, 0, size - 2);
|
||||
}
|
||||
|
||||
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_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)] internal static extern int BakaShrot_ListTopics(long client);
|
||||
[DllImport(Dll, ExactSpelling = true)] internal static extern int BakaShrot_ListNodes(long client);
|
||||
[DllImport(Dll, ExactSpelling = true)] internal static extern IntPtr BakaShrot_GetNamesListW(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_GetQueryResultW(long client, byte[] buffer, IntPtr size);
|
||||
[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.3.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>
|
||||
+5
-2
@@ -42,6 +42,7 @@ bindings/
|
||||
c/ bakashrot.h, generated from bakashrot-capi
|
||||
purebasic/ the prototypes and error codes
|
||||
python/ bakashrot.py over the DLL, check_bakashrot.py, make_wheel.py
|
||||
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
|
||||
@@ -55,7 +56,7 @@ on their own; `server` and `client` use them; the DLL and the tool only use `cli
|
||||
`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`):
|
||||
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`).
|
||||
|
||||
Then it checks it, in the folder's `_test/`: a CA and certificates, the server on a free port,
|
||||
@@ -65,7 +66,9 @@ which must end cleanly (`_test/` kept if not). `--skip-test` skips it.
|
||||
|
||||
CI ([.github/workflows/ci.yml](.github/workflows/ci.yml)) runs on a version tag (`v*`) or by hand: `test.ps1`'s checks
|
||||
on Windows and Linux, then a release on each of Windows x64 and ARM64, Linux x64 and ARM64, each on its own
|
||||
kind of machine (so its smoke test runs there), its archive kept as the run's artifact. The Linux ones build
|
||||
kind of machine (so its smoke test runs there), its archive kept as the run's artifact; then the C# client's
|
||||
NuGet package, `NibblePoker.BakaShrot.Client`, packed from the four releases' libraries
|
||||
(`runtimes/<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.
|
||||
The version is the workspace's (`Cargo.toml`), and `bindings/python/bakashrot.py`'s `__version__` must be the same.
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ What apps connect with, in layers:
|
||||
| C header | `bindings/c/bakashrot.h` | generated from the DLL (cbindgen) |
|
||||
| PureBasic | `bindings/purebasic/` | the prototypes and the error codes |
|
||||
| Python | `bindings/python/bakashrot.py` | `Client` over the DLL (ctypes), standard library only |
|
||||
| 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
|
||||
@@ -106,6 +107,51 @@ 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:
|
||||
`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()`,
|
||||
`GetAttachment()` (bytes), `SaveAttachment()` (a file), `ListTopics()` /
|
||||
`ListNodes()` / `Query()` (the library's JSON, as a string: parsing it is
|
||||
the app's), `Close()` / `Dispose()`. The same exceptions as Python's:
|
||||
`RefusedException`, `ConnectionLostException`, `AuthException`,
|
||||
`BakaShrotException`, each with its `ErrorCode`. Strings go as UTF-16 (the
|
||||
`W` exports); one with a NUL is refused (`InvalidArgument`) rather than
|
||||
cut. Each `Client` has its own client in the DLL, its calls serialized:
|
||||
several at once, from any threads.
|
||||
|
||||
The library is found the usual DllImport way: next to the app, then the
|
||||
PATH (`LD_LIBRARY_PATH` on Linux). It's 64-bit: the app must run as a
|
||||
64-bit process (no "Prefer 32-bit" on .NET Framework).
|
||||
|
||||
## PureBasic
|
||||
|
||||
`bindings/purebasic/BakaShrot_Client_Prototypes.pbi` (with
|
||||
@@ -174,6 +220,14 @@ bakashrot list nodes --json {"kind":"node","names":["kitchen"
|
||||
`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.
|
||||
- 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`).
|
||||
- `header.rs`: `bindings/c/bakashrot.h` matches the exports (rewritten
|
||||
when it doesn't: check it in).
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ It also allows to sleep easy knowing each client is strongly authenticated by us
|
||||
* A C library (`bakashrot.dll`, `libbakashrot.so`), with a C header and PureBasic prototypes
|
||||
* A CLI tool to push, read, query and list
|
||||
* A Python module over the library, without dependencies, as a wheel with the library in it
|
||||
* A C# client over the library, one file without dependencies, for .NET Framework 2.0 and 3.x up to the latest .NET
|
||||
|
||||
|
||||
## Limitations
|
||||
|
||||
+6
-1
@@ -11,6 +11,7 @@ Into target/dist/:
|
||||
purebasic/*.pbi its PureBasic prototypes
|
||||
python/bakashrot.py the Python client, over 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
|
||||
docs/ docs/
|
||||
README.txt what's where, how to start
|
||||
@@ -208,7 +209,9 @@ docs/client.md), --help on each command:
|
||||
|
||||
The client library ({LIBRARY}): the BakaShrot_* exports, include/bakashrot.h
|
||||
for C, purebasic/ for PureBasic, python/bakashrot.py for Python (no
|
||||
dependencies; it looks for the library next to itself or in BAKASHROT_DLL).
|
||||
dependencies; it looks for the library next to itself or in BAKASHROT_DLL),
|
||||
csharp/BakaShrot.cs for C# (.NET Framework 2.0 and up, .NET Core and .NET;
|
||||
the library next to the app, which runs 64-bit).
|
||||
Or: pip install python/bakashrot-*.whl, the library inside.
|
||||
|
||||
Compatibility: protocol 7. Servers and clients must come from the same
|
||||
@@ -242,6 +245,8 @@ def package(built, version, name, out, hybrid):
|
||||
shutil.copytree(os.path.join(bindings, "purebasic"), os.path.join(out, "purebasic"))
|
||||
os.makedirs(os.path.join(out, "python"))
|
||||
shutil.copy2(os.path.join(bindings, "python", "bakashrot.py"), os.path.join(out, "python"))
|
||||
os.makedirs(os.path.join(out, "csharp"))
|
||||
shutil.copy2(os.path.join(bindings, "csharp", "NibblePoker.BakaShrot.Client", "BakaShrot.cs"), os.path.join(out, "csharp"))
|
||||
shutil.copytree(os.path.join(HERE, "docs"), os.path.join(out, "docs"))
|
||||
shutil.copy2(os.path.join(HERE, "crates", "bakashrot-config", "example.toml"),
|
||||
os.path.join(out, "server.example.toml"))
|
||||
|
||||
@@ -5,7 +5,7 @@ open, and the plan. Every step of the plan is done (the workspace,
|
||||
`bakashrot-proto`, `bakashrot-pki` and the certificate tool,
|
||||
`bakashrot-config`, `bakashrot-storage`, `bakashrot-server` and
|
||||
`bakashrot-client` answering every request, attachments included, the C
|
||||
DLL with its C, PureBasic and Python bindings, the `bakashrot` tool,
|
||||
DLL with its C, PureBasic, Python and C# bindings, the `bakashrot` tool,
|
||||
retention, replication, operations and releases, then the finish: one
|
||||
test runner, CI, Docker, `bench.ps1`), see "Plan".
|
||||
|
||||
@@ -373,6 +373,7 @@ by hand.
|
||||
| 11 | Replication | Peer links, sync state, batches by name, wildcards, attachments, skipping on arrival | Three servers end to end, a restart; the corrupted-attachment fix | Decided 2026-11-14 | Done 2026-11-14 |
|
||||
| 12 | Operations | Signals and a clean stop, logs, release, wheel | Runs unattended, stops cleanly, the release's smoke test | Decided 2026-11-14 | Done 2026-11-14 |
|
||||
| 13 | Finish | One test runner (the Rust tests, decided 2026-11-15), end-to-end tests in CI, the bench, Docker | Push speed with 4 servers replicating (`docs/server.md`, "Measured") | | Done 2026-11-16 (`bench.ps1`) |
|
||||
| 14 | C# binding | `bindings/csharp`: `Client` over the `W` exports, C# 2 and .NET 2.0's library only (net35, netstandard2.0); the NuGet package `NibblePoker.BakaShrot.Client` with the four platforms' libraries, packed by CI after the releases (an artifact) | Its NUnit tests pass on net48 and net8.0 (by hand, not in `test.ps1`); the package loads the library on net8.0 and net48 | Asked by the owner 2026-11-18 (the name too) | Done 2026-11-18 |
|
||||
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user