diff --git a/Cargo.lock b/Cargo.lock index 9af9ae3..c881eb2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -79,7 +79,7 @@ dependencies = [ [[package]] name = "bakashrot-capi" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bakashrot-client", "bakashrot-config", @@ -93,7 +93,7 @@ dependencies = [ [[package]] name = "bakashrot-client" -version = "0.3.0" +version = "0.4.0" dependencies = [ "aws-lc-rs", "bakashrot-pki", @@ -103,7 +103,7 @@ dependencies = [ [[package]] name = "bakashrot-config" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bakashrot-proto", "indexmap", @@ -113,7 +113,7 @@ dependencies = [ [[package]] name = "bakashrot-pki" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bakashrot-proto", "rcgen", @@ -125,7 +125,7 @@ dependencies = [ [[package]] name = "bakashrot-proto" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bytes", "rmp-serde", @@ -136,7 +136,7 @@ dependencies = [ [[package]] name = "bakashrot-server" -version = "0.3.0" +version = "0.4.0" dependencies = [ "aws-lc-rs", "bakashrot-client", @@ -156,7 +156,7 @@ dependencies = [ [[package]] name = "bakashrot-storage" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bakashrot-config", "bakashrot-proto", @@ -166,7 +166,7 @@ dependencies = [ [[package]] name = "bakashrot-tools" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bakashrot-client", "bakashrot-config", diff --git a/Cargo.toml b/Cargo.toml index b349298..92bf1f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.3.0" +version = "0.4.0" edition = "2024" rust-version = "1.100" license = "CC0-1.0" diff --git a/bindings/c/bakashrot.h b/bindings/c/bakashrot.h index 4aa2759..cb09c88 100644 --- a/bindings/c/bakashrot.h +++ b/bindings/c/bakashrot.h @@ -24,7 +24,7 @@ int64_t BakaShrot_CreateClient(void); /** * Frees a client and closes its connection (once a call on it in another - * thread ends): 1, or 0 if it wasn't one. + * thread ends), its enumerations closed too: 1, or 0 if it wasn't one. */ ptrdiff_t BakaShrot_FreeClient(int64_t client); @@ -245,34 +245,43 @@ ptrdiff_t BakaShrot_GetMessageNodeA(int64_t client, char *buffer, ptrdiff_t size ptrdiff_t BakaShrot_GetMessageNodeW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** - * Lists the topics with messages that this client may push to or read - * (every one if its roles have `list_topics` or `query`): how many, -1 on - * failure. Then `BakaShrot_GetNamesList()`. + * Lists topics (`kind` 1) or nodes (`kind` 2): the topics with messages + * that this client may push to or read (every one if its roles have + * `list_topics` or `query`), the nodes with messages in the topics it may + * read (every one with `list_nodes` or `query`). Only those of the topic + * and node pairs that `topics` and `nodes` match: each a name or a + * pattern (`sensors.*`), null for any. Every topic: 1, null, null; the + * topics a node pushed to: 1, null, the node; the nodes that pushed to a + * topic: 2, the topic, null. How many, -1 on failure. Then + * `BakaShrot_GetNamesListAsJson()`, or `BakaShrot_EnumerateNames()` + * instead. */ -int32_t BakaShrot_ListTopics(int64_t client); +int32_t BakaShrot_ListNamesA(int64_t client, int32_t kind, const char *topics, const char *nodes); /** - * Lists the nodes with messages in the topics this client may read (every - * one if its roles have `list_nodes` or `query`): how many, -1 on failure. Then - * `BakaShrot_GetNamesList()`. + * The same as `BakaShrot_ListNamesA`, in UTF-16. */ -int32_t BakaShrot_ListNodes(int64_t client); +int32_t BakaShrot_ListNamesW(int64_t client, + int32_t kind, + const uint16_t *topics, + const uint16_t *nodes); /** * The last list, as JSON: * `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated` * if some didn't fit. */ -ptrdiff_t BakaShrot_GetNamesListA(int64_t client, 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(int64_t client, uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetNamesListAsJsonW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * Runs read-only SQL on the server (one SELECT or WITH), if this client - * may query. Then `BakaShrot_GetQueryResult()`. + * may query. Then `BakaShrot_GetQueryResultAsJson()`, or + * `BakaShrot_EnumerateQuery()` instead. */ ptrdiff_t BakaShrot_QueryA(int64_t client, const char *sql); @@ -285,12 +294,12 @@ ptrdiff_t BakaShrot_QueryW(int64_t client, const uint16_t *sql); * The last query's result, as JSON: * `{"columns":[...],"rows":[[...],...]}`, every value a string or null. */ -ptrdiff_t BakaShrot_GetQueryResultA(int64_t client, 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(int64_t client, 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 @@ -383,6 +392,126 @@ int64_t BakaShrot_GetAttachmentData(int64_t client, void *buffer, int64_t buffer */ ptrdiff_t BakaShrot_FreeAttachmentData(int64_t client); +/** + * Closes an enumeration: 1, or 0 if it wasn't one. + */ +ptrdiff_t BakaShrot_CloseEnum(int64_t enumeration); + +/** + * Lists names as `BakaShrot_ListNames()` does (the same arguments), into + * an enumeration: its handle, 0 on failure (`BakaShrot_GetLastError(client)`). + * Then `BakaShrot_NextName()` and `BakaShrot_GetEnumName()`, and + * `BakaShrot_CloseEnum()`. Closed with its client by + * `BakaShrot_FreeClient()`. + */ +int64_t BakaShrot_EnumerateNamesA(int64_t client, + int32_t kind, + const char *topics, + const char *nodes); + +/** + * The same as `BakaShrot_EnumerateNamesA`, in UTF-16. + */ +int64_t BakaShrot_EnumerateNamesW(int64_t client, + int32_t kind, + const uint16_t *topics, + const uint16_t *nodes); + +/** + * Moves to the next name (the first, the first time): 1, 0 if there are + * no more, -1 if it isn't a names enumeration. + */ +ptrdiff_t BakaShrot_NextName(int64_t enumeration); + +/** + * The current name: the bytes it needs, 0 if there's none (before the + * first, past the last) or it isn't a names enumeration. + */ +ptrdiff_t BakaShrot_GetEnumNameA(int64_t enumeration, char *buffer, ptrdiff_t size); + +/** + * The same as `BakaShrot_GetEnumNameA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetEnumNameW(int64_t enumeration, uint16_t *buffer, ptrdiff_t size); + +/** + * How many names, -1 if it isn't a names enumeration. + */ +int32_t BakaShrot_GetNameCount(int64_t enumeration); + +/** + * Whether some names didn't fit in the server's answer: 1 or 0, -1 if it + * isn't a names enumeration. + */ +ptrdiff_t BakaShrot_IsNamesListTruncated(int64_t enumeration); + +/** + * Runs a query as `BakaShrot_Query()` does, into an enumeration: its + * handle, 0 on failure (`BakaShrot_GetLastError(client)`). Then + * `BakaShrot_GetQueryColumnCount()` and `GetQueryColumnName()`, + * `BakaShrot_NextQueryRow()` and `GetQueryValue()` / `IsQueryValueNull()`, + * and `BakaShrot_CloseEnum()`. Closed with its client by + * `BakaShrot_FreeClient()`. + */ +int64_t BakaShrot_EnumerateQueryA(int64_t client, const char *sql); + +/** + * The same as `BakaShrot_EnumerateQueryA`, in UTF-16. + */ +int64_t BakaShrot_EnumerateQueryW(int64_t client, const uint16_t *sql); + +/** + * How many columns, -1 if it isn't a query enumeration. + */ +int32_t BakaShrot_GetQueryColumnCount(int64_t enumeration); + +/** + * A column's name (`index` 0 to the count - 1): the bytes it needs, 0 if + * there's no such column or it isn't a query enumeration. + */ +ptrdiff_t BakaShrot_GetQueryColumnNameA(int64_t enumeration, + int32_t index, + char *buffer, + ptrdiff_t size); + +/** + * The same as `BakaShrot_GetQueryColumnNameA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetQueryColumnNameW(int64_t enumeration, + int32_t index, + uint16_t *buffer, + ptrdiff_t size); + +/** + * Moves to the next row (the first, the first time): 1, 0 if there are + * no more, -1 if it isn't a query enumeration. + */ +ptrdiff_t BakaShrot_NextQueryRow(int64_t enumeration); + +/** + * The current row's value in a column (`index` 0 to the count - 1): the + * bytes it needs, 0 if it's null (`BakaShrot_IsQueryValueNull()`), there's + * no current row or such column, or it isn't a query enumeration. + */ +ptrdiff_t BakaShrot_GetQueryValueA(int64_t enumeration, + int32_t index, + char *buffer, + ptrdiff_t size); + +/** + * The same as `BakaShrot_GetQueryValueA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetQueryValueW(int64_t enumeration, + int32_t index, + uint16_t *buffer, + ptrdiff_t size); + +/** + * Whether the current row's value in a column is null: 1 or 0, -1 if + * there's no current row or such column, or it isn't a query enumeration. + */ +ptrdiff_t BakaShrot_IsQueryValueNull(int64_t enumeration, int32_t index); + #ifdef __cplusplus } // extern "C" #endif // __cplusplus diff --git a/bindings/csharp/NibblePoker.BakaShrot.Client.Tests/ClientTests.cs b/bindings/csharp/NibblePoker.BakaShrot.Client.Tests/ClientTests.cs index bb9c9c7..2c59cc0 100644 --- a/bindings/csharp/NibblePoker.BakaShrot.Client.Tests/ClientTests.cs +++ b/bindings/csharp/NibblePoker.BakaShrot.Client.Tests/ClientTests.cs @@ -145,6 +145,54 @@ namespace NibblePoker.BakaShrot.Tests kitchen.Push("listed", "x"); Assert.That(kitchen.ListTopics(), Does.StartWith("{\"kind\":\"topic\"").And.Contain("\"listed\"")); Assert.That(kitchen.ListNodes(), Does.StartWith("{\"kind\":\"node\"").And.Contain("\"kitchen\"")); + + // Filtered: the topics a node pushed to, the nodes of a topic. + Assert.That(kitchen.ListTopics(null, "KITCHEN"), Does.Contain("\"listed\"")); + Assert.That(kitchen.ListNodes("list?d", null), Is.EqualTo("{\"kind\":\"node\",\"names\":[\"kitchen\"],\"truncated\":false}")); + Assert.That(kitchen.ListTopics(null, "nobody"), Is.EqualTo("{\"kind\":\"topic\",\"names\":[],\"truncated\":false}")); + BakaShrotException invalid = Assert.Catch(() => kitchen.ListNodes("a b", null))!; + Assert.That(invalid.Code, Is.EqualTo(ErrorCode.InvalidArgument)); + } + + [Test] + public void Enumerations() + { + using Client kitchen = Server.Connect("kitchen"); + kitchen.Push("enumerated", "x"); + kitchen.Push("enumerated", "y"); + Assert.That(kitchen.EnumerateTopics(), Does.Contain("enumerated")); + Assert.That(kitchen.EnumerateTopics(null, "KITCHEN"), Does.Contain("enumerated")); + Assert.That(kitchen.EnumerateNodes("enumer*", null), Is.EqualTo(new[] { "kitchen" })); + Assert.That(kitchen.EnumerateNodes("nothing", null), Is.Empty); + + // Rows: by index or column, NULL as null; asked again each time. + IEnumerable rows = kitchen.EnumerateQuery( + "SELECT message_data AS data, NULL AS missing, '' AS empty FROM messages WHERE topic = 'enumerated' ORDER BY message_id"); + for (int pass = 0; pass < 2; pass++) + { + List got = new List(rows); + Assert.That(got.Count, Is.EqualTo(2)); + Assert.That(got[0].Columns, Is.EqualTo(new[] { "data", "missing", "empty" })); + Assert.That(got[0]["data"], Is.EqualTo("x")); + Assert.That(got[1][0], Is.EqualTo("y")); + Assert.That(got[1]["missing"], Is.Null); + Assert.That(got[1]["empty"], Is.EqualTo("")); + Assert.Throws(() => { string _ = got[0]["nope"]; }); + } + Assert.That(kitchen.EnumerateQuery("SELECT 1 AS a WHERE 0"), Is.Empty); + + // Failures when the foreach starts; closing the client ends one. + IEnumerable bad = kitchen.EnumerateNodes("a b", null); + Assert.That(Assert.Catch(() => bad.GetEnumerator().MoveNext())!.Code, + Is.EqualTo(ErrorCode.InvalidArgument)); + Assert.That(Assert.Throws(() => new List(kitchen.EnumerateQuery("SELECT nope")))!.Code, + Is.EqualTo(ErrorCode.QueryFailed)); + using (IEnumerator topics = kitchen.EnumerateTopics().GetEnumerator()) + { + Assert.That(topics.MoveNext(), Is.True); + kitchen.Close(); + Assert.Throws(() => topics.MoveNext()); + } } [Test] diff --git a/bindings/csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs b/bindings/csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs index 4768a8f..0e861b2 100644 --- a/bindings/csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs +++ b/bindings/csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs @@ -99,6 +99,38 @@ namespace NibblePoker.BakaShrot } } + /// A row of EnumerateQuery(): its values (null for NULL), by + /// index or column name. + public sealed class QueryRow + { + /// The query's columns, the same array for every row. + public readonly string[] Columns; + public readonly string[] Values; + + internal QueryRow(string[] columns, string[] values) + { + Columns = columns; + Values = values; + } + + public string this[int column] + { + get { return Values[column]; } + } + + /// The first column with that name (as the query wrote it). + public string this[string column] + { + get + { + int index = Array.IndexOf(Columns, column); + if (index < 0) + throw new ArgumentException("No column " + column, "column"); + return Values[index]; + } + } + } + public sealed class Client : IDisposable { public readonly string Host, Ca, Certificate, Key, Crl; @@ -293,17 +325,32 @@ namespace NibblePoker.BakaShrot /// The topics with messages that this client may push to or /// read, as JSON: {"kind":"topic","truncated":false,"names":[...]}. public string ListTopics() + { + return ListTopics(null, null); + } + + /// ListTopics(), only those of the topic and node pairs that + /// topic and node match, each a name or a pattern ("sensors.*"), null + /// for any: ListTopics(null, "kitchen") is the topics kitchen pushed to. + public string ListTopics(string topic, string node) { lock (sync) - return Names(Native.BakaShrot_ListTopics(Handle()), "List topics"); + return Names(Native.BakaShrot_ListNamesW(Handle(), 1, Text(topic), Text(node)), "List topics"); } /// The nodes with messages in the topics this client may /// read, as ListTopics() says them. public string ListNodes() + { + return ListNodes(null, null); + } + + /// ListNodes(), filtered as ListTopics(topic, node) is: + /// ListNodes("logs", null) is the nodes that pushed to logs. + public string ListNodes(string topic, string node) { lock (sync) - return Names(Native.BakaShrot_ListNodes(Handle()), "List nodes"); + return Names(Native.BakaShrot_ListNamesW(Handle(), 2, Text(topic), Text(node)), "List nodes"); } /// Runs one read-only SELECT or WITH: the server's JSON, @@ -313,12 +360,98 @@ namespace NibblePoker.BakaShrot lock (sync) { Check(Native.BakaShrot_QueryW(Handle(), Text(sql)), "Query"); - return GetString(Native.BakaShrot_GetQueryResultW); + return GetString(Native.BakaShrot_GetQueryResultAsJsonW); + } + } + + /// The topics ListTopics() lists, one at a time, without + /// JSON. Asked once a foreach starts (each one asks again), closed + /// when it ends. + public IEnumerable EnumerateTopics() + { + return EnumerateNames(1, null, null); + } + + /// The topics ListTopics(topic, node) lists, as EnumerateTopics() gives them. + public IEnumerable EnumerateTopics(string topic, string node) + { + return EnumerateNames(1, topic, node); + } + + /// The nodes ListNodes() lists, as EnumerateTopics() gives them. + public IEnumerable EnumerateNodes() + { + return EnumerateNames(2, null, null); + } + + /// The nodes ListNodes(topic, node) lists, as EnumerateTopics() gives them. + public IEnumerable EnumerateNodes(string topic, string node) + { + return EnumerateNames(2, topic, node); + } + + /// Query(sql)'s rows, one at a time, without JSON. Asked + /// once a foreach starts (each one asks again), closed when it ends. + public IEnumerable EnumerateQuery(string sql) + { + long enumeration; + lock (sync) + enumeration = Opened(Native.BakaShrot_EnumerateQueryW(Handle(), Text(sql)), "Query"); + try + { + string[] columns = new string[Native.BakaShrot_GetQueryColumnCount(enumeration)]; + for (int column = 0; column < columns.Length; column++) + columns[column] = GetString(enumeration, ColumnGetter(Native.BakaShrot_GetQueryColumnNameW, column)); + while (Next(Native.BakaShrot_NextQueryRow(enumeration))) + { + string[] values = new string[columns.Length]; + for (int column = 0; column < values.Length; column++) + if (Native.BakaShrot_IsQueryValueNull(enumeration, column) == IntPtr.Zero) + values[column] = GetString(enumeration, ColumnGetter(Native.BakaShrot_GetQueryValueW, column)); + yield return new QueryRow(columns, values); + } + } + finally + { + Native.BakaShrot_CloseEnum(enumeration); } } // --- Inside --------------------------------------------------------- + private IEnumerable EnumerateNames(int kind, string topic, string node) + { + long enumeration; + lock (sync) + enumeration = Opened(Native.BakaShrot_EnumerateNamesW(Handle(), kind, Text(topic), Text(node)), + kind == 1 ? "List topics" : "List nodes"); + try + { + while (Next(Native.BakaShrot_NextName(enumeration))) + yield return GetString(enumeration, Native.BakaShrot_GetEnumNameW); + } + finally + { + Native.BakaShrot_CloseEnum(enumeration); + } + } + + // An enumeration's handle, 0 on failure. + private long Opened(long enumeration, string what) + { + if (enumeration == 0) + throw Failed(what, false); + return enumeration; + } + + // A Next...(): 1 an item, 0 no more, -1 closed (with its client, by Close()). + private static bool Next(IntPtr result) + { + if (result.ToInt64() < 0) + throw new ConnectionLostException("The client was closed while enumerating", ErrorCode.NotConnected); + return result != IntPtr.Zero; + } + private long Handle() { if (handle == 0) @@ -343,7 +476,7 @@ namespace NibblePoker.BakaShrot { if (count < 0) throw Failed(what, false); - return GetString(Native.BakaShrot_GetNamesListW); + return GetString(Native.BakaShrot_GetNamesListAsJsonW); } // Strings go as UTF-16: one with a NUL would be cut there. @@ -354,19 +487,32 @@ namespace NibblePoker.BakaShrot return value; } - private delegate IntPtr Getter(long client, byte[] buffer, IntPtr size); + private delegate IntPtr Getter(long handle, byte[] buffer, IntPtr size); + private delegate IntPtr IndexGetter(long handle, int index, 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(); + 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(handle, buffer, new IntPtr(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) @@ -430,11 +576,20 @@ namespace NibblePoker.BakaShrot [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 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_GetQueryResultW(long client, byte[] buffer, IntPtr size); + [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); diff --git a/bindings/csharp/NibblePoker.BakaShrot.Client/NibblePoker.BakaShrot.Client.csproj b/bindings/csharp/NibblePoker.BakaShrot.Client/NibblePoker.BakaShrot.Client.csproj index 8b7139e..574c68b 100644 --- a/bindings/csharp/NibblePoker.BakaShrot.Client/NibblePoker.BakaShrot.Client.csproj +++ b/bindings/csharp/NibblePoker.BakaShrot.Client/NibblePoker.BakaShrot.Client.csproj @@ -15,7 +15,7 @@ holding win-x64/, win-arm64/, linux-x64/, linux-arm64/, each with that release's library and THIRD-PARTY.txt (.github/workflows/ci.yml). --> - 0.3.0 + 0.4.0 Herwin Bozet (NibblePoker) BakaShrot's client: a message store with replication. Over the client library, its Windows and Linux x64 and ARM64 builds included; .NET Framework 2.0 and up, .NET Core, .NET. CC0-1.0 diff --git a/bindings/purebasic/BakaShrot_Client_Prototypes.pbi b/bindings/purebasic/BakaShrot_Client_Prototypes.pbi index 1528e25..823601c 100644 --- a/bindings/purebasic/BakaShrot_Client_Prototypes.pbi +++ b/bindings/purebasic/BakaShrot_Client_Prototypes.pbi @@ -1,7 +1,7 @@ ;{- Code Header ; ==- Basic Info -================================ ; Name: BakaShrot_Client_Prototypes.pbi -; Version: 0.0.1 +; Version: 0.4.0 ; Author: Herwin Bozet (NibblePoker) ; ; ==- Compatibility -============================= @@ -40,7 +40,12 @@ ; about each are in BakaShrot_ErrorCodes.pbi, next to this file (included ; below), BakaShrot_ErrorName() names them; ; BakaShrot_GetRefusalReasonString(Client) says why in words. -; _GetNamesList() is {"kind":"topic","names":[...],"truncated":false}. +; _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" @@ -71,11 +76,23 @@ PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype(Client.q) PrototypeC.i BakaShrot_GetMessageData_Prototype(Client.q, *Buffer, BufferSize.i) PrototypeC.i BakaShrot_GetMessageTopic_Prototype(Client.q, *Buffer, BufferSize.i) PrototypeC.i BakaShrot_GetMessageNode_Prototype(Client.q, *Buffer, BufferSize.i) -PrototypeC.l BakaShrot_ListTopics_Prototype(Client.q) -PrototypeC.l BakaShrot_ListNodes_Prototype(Client.q) -PrototypeC.i BakaShrot_GetNamesList_Prototype(Client.q, *Buffer, BufferSize.i) +; Kind 1 topics, 2 nodes; Topics and Nodes a name or a pattern, "" for any. +PrototypeC.l BakaShrot_ListNames_Prototype(Client.q, Kind.l, Topics.p-unicode, Nodes.p-unicode) +PrototypeC.i BakaShrot_GetNamesListAsJson_Prototype(Client.q, *Buffer, BufferSize.i) PrototypeC.i BakaShrot_Query_Prototype(Client.q, Sql.p-unicode) -PrototypeC.i BakaShrot_GetQueryResult_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.i BakaShrot_GetQueryResultAsJson_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.q BakaShrot_EnumerateNames_Prototype(Client.q, Kind.l, Topics.p-unicode, Nodes.p-unicode) +PrototypeC.i BakaShrot_NextName_Prototype(Enum.q) +PrototypeC.i BakaShrot_GetEnumName_Prototype(Enum.q, *Buffer, BufferSize.i) +PrototypeC.l BakaShrot_GetNameCount_Prototype(Enum.q) +PrototypeC.i BakaShrot_IsNamesListTruncated_Prototype(Enum.q) +PrototypeC.q BakaShrot_EnumerateQuery_Prototype(Client.q, Sql.p-unicode) +PrototypeC.l BakaShrot_GetQueryColumnCount_Prototype(Enum.q) +PrototypeC.i BakaShrot_GetQueryColumnName_Prototype(Enum.q, Index.l, *Buffer, BufferSize.i) +PrototypeC.i BakaShrot_NextQueryRow_Prototype(Enum.q) +PrototypeC.i BakaShrot_GetQueryValue_Prototype(Enum.q, Index.l, *Buffer, BufferSize.i) +PrototypeC.i BakaShrot_IsQueryValueNull_Prototype(Enum.q, Index.l) +PrototypeC.i BakaShrot_CloseEnum_Prototype(Enum.q) PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode) PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode, *Data, Size.q) PrototypeC.q BakaShrot_SaveAttachment_Prototype(Client.q, Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode) @@ -109,11 +126,22 @@ Global BakaShrot_IsMessageAttachmentReady.BakaShrot_IsMessageAttachmentReady_Pro Global BakaShrot_GetMessageData.BakaShrot_GetMessageData_Prototype Global BakaShrot_GetMessageTopic.BakaShrot_GetMessageTopic_Prototype Global BakaShrot_GetMessageNode.BakaShrot_GetMessageNode_Prototype -Global BakaShrot_ListTopics.BakaShrot_ListTopics_Prototype -Global BakaShrot_ListNodes.BakaShrot_ListNodes_Prototype -Global BakaShrot_GetNamesList.BakaShrot_GetNamesList_Prototype +Global BakaShrot_ListNames.BakaShrot_ListNames_Prototype +Global BakaShrot_GetNamesListAsJson.BakaShrot_GetNamesListAsJson_Prototype Global BakaShrot_Query.BakaShrot_Query_Prototype -Global BakaShrot_GetQueryResult.BakaShrot_GetQueryResult_Prototype +Global BakaShrot_GetQueryResultAsJson.BakaShrot_GetQueryResultAsJson_Prototype +Global BakaShrot_EnumerateNames.BakaShrot_EnumerateNames_Prototype +Global BakaShrot_NextName.BakaShrot_NextName_Prototype +Global BakaShrot_GetEnumName.BakaShrot_GetEnumName_Prototype +Global BakaShrot_GetNameCount.BakaShrot_GetNameCount_Prototype +Global BakaShrot_IsNamesListTruncated.BakaShrot_IsNamesListTruncated_Prototype +Global BakaShrot_EnumerateQuery.BakaShrot_EnumerateQuery_Prototype +Global BakaShrot_GetQueryColumnCount.BakaShrot_GetQueryColumnCount_Prototype +Global BakaShrot_GetQueryColumnName.BakaShrot_GetQueryColumnName_Prototype +Global BakaShrot_NextQueryRow.BakaShrot_NextQueryRow_Prototype +Global BakaShrot_GetQueryValue.BakaShrot_GetQueryValue_Prototype +Global BakaShrot_IsQueryValueNull.BakaShrot_IsQueryValueNull_Prototype +Global BakaShrot_CloseEnum.BakaShrot_CloseEnum_Prototype Global BakaShrot_PushMessageWithFile.BakaShrot_PushMessageWithFile_Prototype Global BakaShrot_PushMessageWithData.BakaShrot_PushMessageWithData_Prototype Global BakaShrot_SaveAttachment.BakaShrot_SaveAttachment_Prototype @@ -185,11 +213,22 @@ Procedure.i BakaShrot_LoadClient(DllPath.s) BakaShrot_GetMessageData = BakaShrot_ClientFunction("BakaShrot_GetMessageDataW") BakaShrot_GetMessageTopic = BakaShrot_ClientFunction("BakaShrot_GetMessageTopicW") BakaShrot_GetMessageNode = BakaShrot_ClientFunction("BakaShrot_GetMessageNodeW") - BakaShrot_ListTopics = BakaShrot_ClientFunction("BakaShrot_ListTopics") - BakaShrot_ListNodes = BakaShrot_ClientFunction("BakaShrot_ListNodes") - BakaShrot_GetNamesList = BakaShrot_ClientFunction("BakaShrot_GetNamesListW") + BakaShrot_ListNames = BakaShrot_ClientFunction("BakaShrot_ListNamesW") + BakaShrot_GetNamesListAsJson = BakaShrot_ClientFunction("BakaShrot_GetNamesListAsJsonW") 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_PushMessageWithData = BakaShrot_ClientFunction("BakaShrot_PushMessageWithDataW") BakaShrot_SaveAttachment = BakaShrot_ClientFunction("BakaShrot_SaveAttachmentW") @@ -226,6 +265,26 @@ Procedure.s BakaShrot_GetString(Client.q, Getter.BakaShrot_StringGetter_Prototyp ProcedureReturn Text EndProcedure +; The same for a getter of a column (Getter(Enum, Index, *Buffer, BufferSize)). +PrototypeC.i BakaShrot_ColumnGetter_Prototype(Enum.q, Index.l, *Buffer, BufferSize.i) +Procedure.s BakaShrot_GetColumnString(Enum.q, Index.l, Getter.BakaShrot_ColumnGetter_Prototype) + Protected *Buffer, BufferSize.i, Text.s + + BufferSize = Getter(Enum, Index, 0, 0) + If BufferSize <= 0 + ProcedureReturn "" + EndIf + *Buffer = AllocateMemory(BufferSize) + If Not *Buffer + ProcedureReturn "" + EndIf + Getter(Enum, Index, *Buffer, BufferSize) + Text = PeekS(*Buffer, -1, #PB_Unicode) + FreeMemory(*Buffer) + + ProcedureReturn Text +EndProcedure + ; The string getters, as strings. Procedure.s BakaShrot_GetRefusalReasonString(Client.q) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetRefusalReason) @@ -247,12 +306,24 @@ Procedure.s BakaShrot_GetMessageNodeString(Client.q) ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageNode) EndProcedure -Procedure.s BakaShrot_GetNamesListString(Client.q) - ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetNamesList) +Procedure.s BakaShrot_GetNamesListAsJsonString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetNamesListAsJson) EndProcedure -Procedure.s BakaShrot_GetQueryResultString(Client.q) - ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetQueryResult) +Procedure.s BakaShrot_GetQueryResultAsJsonString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetQueryResultAsJson) +EndProcedure + +Procedure.s BakaShrot_GetEnumNameString(Enum.q) + ProcedureReturn BakaShrot_GetString(Enum, BakaShrot_GetEnumName) +EndProcedure + +Procedure.s BakaShrot_GetQueryColumnNameString(Enum.q, Index.l) + ProcedureReturn BakaShrot_GetColumnString(Enum, Index, BakaShrot_GetQueryColumnName) +EndProcedure + +Procedure.s BakaShrot_GetQueryValueString(Enum.q, Index.l) + ProcedureReturn BakaShrot_GetColumnString(Enum, Index, BakaShrot_GetQueryValue) EndProcedure @@ -264,7 +335,7 @@ EndProcedure ; connected at the same time reads it too. CompilerIf #PB_Compiler_IsMainFile - Define Client.q, Second.q, Id.q, Size.q, *Attachment, *Copy + Define Client.q, Second.q, Enum.q, Id.q, Size.q, *Attachment, *Copy ; Prints why a client's last call failed, then ends. Procedure Failed(Client.q, What.s) @@ -321,8 +392,16 @@ CompilerIf #PB_Compiler_IsMainFile EndIf FreeMemory(*Attachment) : FreeMemory(*Copy) - If BakaShrot_ListTopics(Client) < 0 : Failed(Client, "Listing") : EndIf - PrintN("Topics: " + BakaShrot_GetNamesListString(Client)) + If BakaShrot_ListNames(Client, 1, "", "") < 0 : Failed(Client, "Listing") : EndIf + PrintN("Topics: " + BakaShrot_GetNamesListAsJsonString(Client)) + ; The topics this client's node pushed to ("" for any topic), one at a time. + Enum = BakaShrot_EnumerateNames(Client, 1, "", BakaShrot_GetNodeString(Client)) + If Not Enum : Failed(Client, "Listing") : EndIf + PrintN("Topics it pushed to (" + Str(BakaShrot_GetNameCount(Enum)) + "):") + While BakaShrot_NextName(Enum) = 1 + PrintN(" " + BakaShrot_GetEnumNameString(Enum)) + Wend + BakaShrot_CloseEnum(Enum) If BakaShrot_PushMessageTo(Client, "nothing", "{}") < 0 PrintN("A push to a topic it may not push to: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client)) + ", " + BakaShrot_GetRefusalReasonString(Client)) diff --git a/bindings/purebasic/BakaShrot_ErrorCodes.pbi b/bindings/purebasic/BakaShrot_ErrorCodes.pbi index 2c164fb..5e48324 100644 --- a/bindings/purebasic/BakaShrot_ErrorCodes.pbi +++ b/bindings/purebasic/BakaShrot_ErrorCodes.pbi @@ -1,7 +1,7 @@ ;{- Code Header ; ==- Basic Info -================================ ; Name: BakaShrot_ErrorCodes.pbi -; Version: 0.0.1 +; Version: 0.4.0 ; Author: Herwin Bozet (NibblePoker) ; ; ==- Compatibility -============================= @@ -16,7 +16,7 @@ ; BakaShrot error codes ; ; What BakaShrot_GetLastError() returns after a failed call of the client DLL -; (bakashrot.dll), and the code a server sends with each refusal (protocol 7, +; (bakashrot.dll), and the code a server sends with each refusal (protocol 8, ; crates/bakashrot-proto/src/error.rs). ; The Python client has them in bakashrot.ErrorCode. Shipped next to ; BakaShrot_Client_Prototypes.pbi, which includes it. diff --git a/bindings/python/bakashrot.py b/bindings/python/bakashrot.py index f65d6f9..4739ebb 100644 --- a/bindings/python/bakashrot.py +++ b/bindings/python/bakashrot.py @@ -58,7 +58,7 @@ from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Any, Iterator, Optional, Union -__version__ = "0.3.0" +__version__ = "0.4.0" __all__ = [ "Client", "Message", "MessagesPage", "NamesList", @@ -264,11 +264,10 @@ class _Dll: "BakaShrot_GetMessageTopicA": (I, [H, S, I]), "BakaShrot_GetMessageNodeA": (I, [H, S, I]), "BakaShrot_GetMessageDataA": (I, [H, S, I]), - "BakaShrot_ListTopics": (L, [H]), - "BakaShrot_ListNodes": (L, [H]), - "BakaShrot_GetNamesListA": (I, [H, S, I]), + "BakaShrot_ListNamesA": (L, [H, L, P, P]), + "BakaShrot_GetNamesListAsJsonA": (I, [H, S, I]), "BakaShrot_QueryA": (I, [H, P]), - "BakaShrot_GetQueryResultA": (I, [H, S, I]), + "BakaShrot_GetQueryResultAsJsonA": (I, [H, S, I]), "BakaShrot_PushMessageWithFileA": (Q, [H, P, P, P]), "BakaShrot_PushMessageWithDataA": (Q, [H, P, P, P, Q]), "BakaShrot_SaveAttachmentA": (Q, [H, P, P, Q, P]), @@ -556,20 +555,25 @@ class Client: if not page.more: time.sleep(interval) - def list_topics(self) -> NamesList: - """The topics with messages that the client may push to or read (every one with list_topics or query).""" - return self._list(self._dll.ListTopics, "List topics") + def list_topics(self, topic: Optional[str] = None, node: Optional[str] = None) -> NamesList: + """The topics with messages that the client may push to or read (every one with list_topics or query). + topic and node, each a name or a pattern ("sensors.*"), keep those of the topic/node pairs they + match: list_topics(node="kitchen") is the topics kitchen pushed to.""" + return self._list(1, topic, node, "List topics") - def list_nodes(self) -> NamesList: - """The nodes with messages in the topics the client may read (every one with list_nodes or query).""" - return self._list(self._dll.ListNodes, "List nodes") + def list_nodes(self, topic: Optional[str] = None, node: Optional[str] = None) -> NamesList: + """The nodes with messages in the topics the client may read (every one with list_nodes or query). + topic and node as list_topics() takes them: list_nodes(topic="logs") is the nodes that pushed to logs.""" + return self._list(2, topic, node, "List nodes") - def _list(self, function, what: str) -> NamesList: + def _list(self, kind: int, topic: Optional[str], node: Optional[str], what: str) -> NamesList: + topic = None if topic is None else _name(topic) + node = None if node is None else _name(node) with self._lock: self._check_connected() - if function(self._handle) < 0: + if self._dll.ListNamesA(self._handle, kind, topic, node) < 0: raise self._failed(what) - parsed = json.loads(self._dll.string(self._dll.GetNamesListA, self._handle)) + parsed = json.loads(self._dll.string(self._dll.GetNamesListAsJsonA, self._handle)) return NamesList(parsed["kind"], parsed["names"], bool(parsed["truncated"])) def query_raw(self, sql: str) -> str: @@ -583,7 +587,7 @@ class Client: self._check_connected() if not self._dll.QueryA(self._handle, sql.encode("utf-8")): raise self._failed("Query") - return self._dll.string(self._dll.GetQueryResultA, self._handle) + return self._dll.string(self._dll.GetQueryResultAsJsonA, self._handle) def query(self, sql: str) -> list: """query_raw(), as a list of dicts, one per row, by column name.""" diff --git a/bindings/python/check_bakashrot.py b/bindings/python/check_bakashrot.py index 144f896..5a1756f 100644 --- a/bindings/python/check_bakashrot.py +++ b/bindings/python/check_bakashrot.py @@ -152,6 +152,14 @@ with kitchen: check("list_topics()", topics.kind == "topic" and topics.names == ["logs", "secret"] and not topics.truncated, topics) nodes = kitchen.list_nodes() check("list_nodes()", nodes.kind == "node" and nodes.names == ["kitchen"], nodes) + topics = kitchen.list_topics(node="KITCHEN") + check("list_topics(node=...): the topics it pushed to", topics.names == ["logs", "secret"], topics) + nodes = kitchen.list_nodes(topic="s*") + check("list_nodes(topic=pattern): the nodes that pushed to those", nodes.names == ["kitchen"], nodes) + check("list_topics(node=...) of a node without messages: none", kitchen.list_topics(node="nobody").names == []) + ok, detail = raises(lambda: kitchen.list_nodes(topic="a b"), BakaShrotError, "isn't a topic name or pattern", + ErrorCode.INVALID_ARGUMENT) + check("list_nodes(topic=...) neither a name nor a pattern: INVALID_ARGUMENT", ok, detail) # --- follow() ------------------------------------------------------------ followed = [] diff --git a/crates/bakashrot-capi/src/enumerations.rs b/crates/bakashrot-capi/src/enumerations.rs new file mode 100644 index 0000000..bba5f99 --- /dev/null +++ b/crates/bakashrot-capi/src/enumerations.rs @@ -0,0 +1,365 @@ +//! Enumerations: a list of names or a query's rows, kept whole, read an +//! item at a time like Win32's `FindFirstFile` / `FindNextFile` / +//! `FindClose`. `Next...()` first (an enumeration starts before its first +//! item), then the getters; `BakaShrot_CloseEnum()` once done, or +//! `BakaShrot_FreeClient()` closes its client's. + +use super::{ + Error, HANDLES, Result, State, Text, Utf8, Utf16, bool_result, call, fetch_names, fetch_query, + invalid, lock, text, +}; +use bakashrot_proto::ErrorCode; +use std::ffi::c_char; +use std::panic::{AssertUnwindSafe, catch_unwind}; + +/// An answer of a client, kept whole. +pub(crate) struct Enumeration { + pub(crate) client: i64, + items: Items, +} + +enum Items { + Names { + names: Cursor, + truncated: bool, + }, + Query { + columns: Vec, + rows: Cursor>>, + }, +} + +/// Items and where it's at: 0 before the first, `n` on the `n`th, the +/// count + 1 past the last. +struct Cursor { + items: Vec, + position: usize, +} + +impl Cursor { + fn new(items: Vec) -> Cursor { + Cursor { items, position: 0 } + } + + /// Moves to the next item: whether there was one. + fn advance(&mut self) -> bool { + self.position = (self.position + 1).min(self.items.len() + 1); + self.position <= self.items.len() + } + + fn current(&self) -> Option<&T> { + self.items.get(self.position.checked_sub(1)?) + } +} + +/// Runs `fetch` on a client, keeps what it gives as an enumeration of that +/// client: its handle, 0 if it failed (the client's last error says why). +fn enumerate(client: i64, fetch: impl FnOnce(&mut State) -> Result) -> i64 { + call(client, 0, |state| { + let items = fetch(state)?; + let handles = &mut *lock(&HANDLES); + // Freed by another thread during the call: its enumerations went. + if !handles.clients.contains_key(&client) { + return Err(invalid(format!("client {client} freed during the call"))); + } + let handle = handles.take(); + handles + .enumerations + .insert(handle, Enumeration { client, items }); + Ok(handle) + }) +} + +/// Reads an enumeration: `default` for a bad handle, or `read` giving +/// `None` (one of the other kind, no current item, no such column). +fn read(handle: i64, default: R, read: impl FnOnce(&mut Items) -> Option) -> R { + catch_unwind(AssertUnwindSafe(|| { + let handles = &mut *lock(&HANDLES); + read(&mut handles.enumerations.get_mut(&handle)?.items) + })) + .ok() + .flatten() + .unwrap_or(default) +} + +/// A column index, as arguments. +fn column(index: i32) -> Option { + usize::try_from(index).ok() +} + +/// Closes an enumeration: 1, or 0 if it wasn't one. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_CloseEnum(enumeration: i64) -> isize { + let closed = catch_unwind(|| lock(&HANDLES).enumerations.remove(&enumeration).is_some()); + bool_result(closed.unwrap_or(false)) +} + +// --- Names ------------------------------------------------------------------- + +unsafe fn enumerate_names( + client: i64, + kind: i32, + topics: *const T::Unit, + nodes: *const T::Unit, +) -> i64 { + enumerate(client, |state| { + let list = unsafe { fetch_names::(state, kind, topics, nodes)? }; + Ok(Items::Names { + names: Cursor::new(list.names), + truncated: list.truncated, + }) + }) +} + +/// Lists names as `BakaShrot_ListNames()` does (the same arguments), into +/// an enumeration: its handle, 0 on failure (`BakaShrot_GetLastError(client)`). +/// Then `BakaShrot_NextName()` and `BakaShrot_GetEnumName()`, and +/// `BakaShrot_CloseEnum()`. Closed with its client by +/// `BakaShrot_FreeClient()`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_EnumerateNamesA( + client: i64, + kind: i32, + topics: *const c_char, + nodes: *const c_char, +) -> i64 { + unsafe { enumerate_names::(client, kind, topics.cast(), nodes.cast()) } +} + +/// The same as `BakaShrot_EnumerateNamesA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_EnumerateNamesW( + client: i64, + kind: i32, + topics: *const u16, + nodes: *const u16, +) -> i64 { + unsafe { enumerate_names::(client, kind, topics, nodes) } +} + +/// Moves to the next name (the first, the first time): 1, 0 if there are +/// no more, -1 if it isn't a names enumeration. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_NextName(enumeration: i64) -> isize { + read(enumeration, -1, |items| match items { + Items::Names { names, .. } => Some(bool_result(names.advance())), + Items::Query { .. } => None, + }) +} + +unsafe fn enum_name(enumeration: i64, buffer: *mut T::Unit, size: isize) -> isize { + read(enumeration, 0, |items| match items { + Items::Names { names, .. } => names + .current() + .map(|name| unsafe { text::copy::(name, buffer, size) }), + Items::Query { .. } => None, + }) +} + +/// The current name: the bytes it needs, 0 if there's none (before the +/// first, past the last) or it isn't a names enumeration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetEnumNameA( + enumeration: i64, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { enum_name::(enumeration, buffer.cast(), size) } +} + +/// The same as `BakaShrot_GetEnumNameA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetEnumNameW( + enumeration: i64, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { enum_name::(enumeration, buffer, size) } +} + +/// How many names, -1 if it isn't a names enumeration. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_GetNameCount(enumeration: i64) -> i32 { + read(enumeration, -1, |items| match items { + Items::Names { names, .. } => Some(names.items.len() as i32), + Items::Query { .. } => None, + }) +} + +/// Whether some names didn't fit in the server's answer: 1 or 0, -1 if it +/// isn't a names enumeration. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_IsNamesListTruncated(enumeration: i64) -> isize { + read(enumeration, -1, |items| match items { + Items::Names { truncated, .. } => Some(bool_result(*truncated)), + Items::Query { .. } => None, + }) +} + +// --- Queries ----------------------------------------------------------------- + +/// The server's `{"columns":[...],"rows":[[...],...]}`, each value a +/// string or null. +fn parse_query(json: &str) -> Option { + let value: serde_json::Value = serde_json::from_str(json).ok()?; + let columns = value + .get("columns")? + .as_array()? + .iter() + .map(|column| column.as_str().map(str::to_owned)) + .collect::>>()?; + let rows = value + .get("rows")? + .as_array()? + .iter() + .map(|row| { + row.as_array()? + .iter() + .map(|value| match value { + serde_json::Value::Null => Some(None), + serde_json::Value::String(text) => Some(Some(text.clone())), + _ => None, + }) + .collect::>>() + }) + .collect::>>()?; + Some(Items::Query { + columns, + rows: Cursor::new(rows), + }) +} + +unsafe fn enumerate_query(client: i64, sql: *const T::Unit) -> i64 { + enumerate(client, |state| { + let json = unsafe { fetch_query::(state, sql)? }; + parse_query(&json) + .ok_or_else(|| Error::new(ErrorCode::Internal, "the server's query result isn't one")) + }) +} + +/// Runs a query as `BakaShrot_Query()` does, into an enumeration: its +/// handle, 0 on failure (`BakaShrot_GetLastError(client)`). Then +/// `BakaShrot_GetQueryColumnCount()` and `GetQueryColumnName()`, +/// `BakaShrot_NextQueryRow()` and `GetQueryValue()` / `IsQueryValueNull()`, +/// and `BakaShrot_CloseEnum()`. Closed with its client by +/// `BakaShrot_FreeClient()`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_EnumerateQueryA(client: i64, sql: *const c_char) -> i64 { + unsafe { enumerate_query::(client, sql.cast()) } +} + +/// The same as `BakaShrot_EnumerateQueryA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_EnumerateQueryW(client: i64, sql: *const u16) -> i64 { + unsafe { enumerate_query::(client, sql) } +} + +/// How many columns, -1 if it isn't a query enumeration. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_GetQueryColumnCount(enumeration: i64) -> i32 { + read(enumeration, -1, |items| match items { + Items::Query { columns, .. } => Some(columns.len() as i32), + Items::Names { .. } => None, + }) +} + +unsafe fn column_name( + enumeration: i64, + index: i32, + buffer: *mut T::Unit, + size: isize, +) -> isize { + read(enumeration, 0, |items| match items { + Items::Query { columns, .. } => columns + .get(column(index)?) + .map(|name| unsafe { text::copy::(name, buffer, size) }), + Items::Names { .. } => None, + }) +} + +/// A column's name (`index` 0 to the count - 1): the bytes it needs, 0 if +/// there's no such column or it isn't a query enumeration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetQueryColumnNameA( + enumeration: i64, + index: i32, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { column_name::(enumeration, index, buffer.cast(), size) } +} + +/// The same as `BakaShrot_GetQueryColumnNameA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetQueryColumnNameW( + enumeration: i64, + index: i32, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { column_name::(enumeration, index, buffer, size) } +} + +/// Moves to the next row (the first, the first time): 1, 0 if there are +/// no more, -1 if it isn't a query enumeration. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_NextQueryRow(enumeration: i64) -> isize { + read(enumeration, -1, |items| match items { + Items::Query { rows, .. } => Some(bool_result(rows.advance())), + Items::Names { .. } => None, + }) +} + +/// The current row's value in a column: `None` without a row or column. +fn value(items: &Items, index: i32) -> Option<&Option> { + match items { + Items::Query { rows, .. } => rows.current()?.get(column(index)?), + Items::Names { .. } => None, + } +} + +unsafe fn query_value( + enumeration: i64, + index: i32, + buffer: *mut T::Unit, + size: isize, +) -> isize { + read(enumeration, 0, |items| { + value(items, index)? + .as_deref() + .map(|text| unsafe { text::copy::(text, buffer, size) }) + }) +} + +/// The current row's value in a column (`index` 0 to the count - 1): the +/// bytes it needs, 0 if it's null (`BakaShrot_IsQueryValueNull()`), there's +/// no current row or such column, or it isn't a query enumeration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetQueryValueA( + enumeration: i64, + index: i32, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { query_value::(enumeration, index, buffer.cast(), size) } +} + +/// The same as `BakaShrot_GetQueryValueA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetQueryValueW( + enumeration: i64, + index: i32, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { query_value::(enumeration, index, buffer, size) } +} + +/// Whether the current row's value in a column is null: 1 or 0, -1 if +/// there's no current row or such column, or it isn't a query enumeration. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_IsQueryValueNull(enumeration: i64, index: i32) -> isize { + read(enumeration, -1, |items| { + value(items, index).map(|value| bool_result(value.is_none())) + }) +} diff --git a/crates/bakashrot-capi/src/lib.rs b/crates/bakashrot-capi/src/lib.rs index 0a18668..3b797cc 100644 --- a/crates/bakashrot-capi/src/lib.rs +++ b/crates/bakashrot-capi/src/lib.rs @@ -9,6 +9,11 @@ //! first argument of every other export. Each has its own connection, //! answers and errors; different clients can be used from different //! threads at once. +//! - **Enumerations** (`BakaShrot_EnumerateNames()`, `EnumerateQuery()`): +//! an answer kept whole, read with `Next...()` (before the first item +//! at first) and its getters, closed with `BakaShrot_CloseEnum()` or +//! with their client by `BakaShrot_FreeClient()`. Their handles are +//! numbered with the clients', so one is never the other's. //! - **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or //! UTF-16 (`uint16_t*`, `wchar_t*` on Windows), null-terminated. //! - **Strings out** are copied into the caller's buffer of `BufferSize` @@ -27,11 +32,13 @@ #![allow(unsafe_code, non_snake_case, clippy::missing_safety_doc)] +mod enumerations; +pub use enumerations::*; mod text; use bakashrot_client::{Client, Error, Settings}; use bakashrot_proto::ErrorCode; -use bakashrot_proto::packets::{MessageEntry, NameKind}; +use bakashrot_proto::packets::{MessageEntry, NameKind, NamesList}; use std::collections::BTreeMap; use std::ffi::{c_char, c_void}; use std::fs::File; @@ -43,9 +50,28 @@ use text::{Text, Utf8, Utf16}; type Result = std::result::Result; -/// The next handle, and the clients by handle. A call holds its client's +/// The clients and enumerations by handle. A call holds its client's /// `Arc`, so a client freed during a call goes when the call ends. -static CLIENTS: Mutex<(i64, BTreeMap)> = Mutex::new((1, BTreeMap::new())); +static HANDLES: Mutex = Mutex::new(Handles { + next: 1, + clients: BTreeMap::new(), + enumerations: BTreeMap::new(), +}); + +struct Handles { + /// The next handle, of a client or an enumeration: never reused. + next: i64, + clients: BTreeMap, + /// Freed with their client. Only ever copied from, under this lock. + enumerations: BTreeMap, +} + +impl Handles { + fn take(&mut self) -> i64 { + self.next += 1; + self.next - 1 + } +} type Shared = Arc>; @@ -66,7 +92,7 @@ struct State { messages: Vec, selected: usize, more: bool, - /// The last `ListTopics` / `ListNodes`, as JSON. + /// The last `ListNames`, as JSON. names: String, /// The last `Query`'s result. query: String, @@ -135,7 +161,7 @@ fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { } fn find(client: i64) -> Option { - lock(&CLIENTS).1.get(&client).cloned() + lock(&HANDLES).clients.get(&client).cloned() } /// Runs a call that can fail on a client: its last error reset, then set @@ -186,8 +212,22 @@ fn invalid(why: impl Into) -> Error { Error::new(ErrorCode::InvalidArgument, why) } -fn required(value: Option, what: &str) -> Result { - value.ok_or_else(|| invalid(format!("no {what} (a null pointer)"))) +/// A string argument that must be there: `InvalidArgument` for a null +/// pointer. +unsafe fn required(pointer: *const T::Unit, what: &str) -> Result { + unsafe { text::read::(pointer, what)? } + .ok_or_else(|| invalid(format!("no {what} (a null pointer)"))) +} + +/// Settings change only before connecting. +fn not_connected(state: &State) -> Result<()> { + match state.client { + Some(_) => Err(Error::new( + ErrorCode::AlreadyConnected, + "already connected: disconnect first", + )), + None => Ok(()), + } } fn bool_result(ok: bool) -> isize { @@ -200,19 +240,27 @@ fn bool_result(ok: bool) -> isize { #[unsafe(no_mangle)] pub extern "C" fn BakaShrot_CreateClient() -> i64 { let made = catch_unwind(|| { - let (next, clients) = &mut *lock(&CLIENTS); - clients.insert(*next, Arc::new(Mutex::new(State::new()))); - *next += 1; - *next - 1 + let handles = &mut *lock(&HANDLES); + let client = handles.take(); + handles + .clients + .insert(client, Arc::new(Mutex::new(State::new()))); + client }); made.unwrap_or(0) } /// Frees a client and closes its connection (once a call on it in another -/// thread ends): 1, or 0 if it wasn't one. +/// thread ends), its enumerations closed too: 1, or 0 if it wasn't one. #[unsafe(no_mangle)] pub extern "C" fn BakaShrot_FreeClient(client: i64) -> isize { - let freed = catch_unwind(|| lock(&CLIENTS).1.remove(&client).is_some()); + let freed = catch_unwind(|| { + let handles = &mut *lock(&HANDLES); + handles + .enumerations + .retain(|_, enumeration| enumeration.client != client); + handles.clients.remove(&client).is_some() + }); bool_result(freed.unwrap_or(false)) } @@ -289,12 +337,7 @@ unsafe fn set( slot: fn(&mut State) -> &mut Option, ) -> isize { call(client, 0, |state| { - if state.client.is_some() { - return Err(Error::new( - ErrorCode::AlreadyConnected, - "already connected: disconnect first", - )); - } + not_connected(state)?; let value = unsafe { text::read::(value, what)? }; *slot(state) = pem_or_file(value, what, optional)?; Ok(1) @@ -391,13 +434,8 @@ pub unsafe extern "C" fn BakaShrot_SetCrlW(client: i64, crl: *const u16) -> isiz unsafe fn connect(client: i64, host: *const T::Unit, port: i32) -> isize { call(client, 0, |state| { - if state.client.is_some() { - return Err(Error::new( - ErrorCode::AlreadyConnected, - "already connected: disconnect first", - )); - } - let host = required(unsafe { text::read::(host, "host")? }, "host")?; + not_connected(state)?; + let host = unsafe { required::(host, "host")? }; let port = u16::try_from(port) .ok() .filter(|port| *port != 0) @@ -466,6 +504,10 @@ pub extern "C" fn BakaShrot_Disconnect(client: i64) -> isize { }) } +fn node(state: &State) -> &str { + state.client.as_ref().map_or("", Client::node) +} + /// The node this client is, as the server said when connecting: its /// certificate's name. Empty when not connected. #[unsafe(no_mangle)] @@ -474,21 +516,13 @@ pub unsafe extern "C" fn BakaShrot_GetNodeA( buffer: *mut c_char, size: isize, ) -> isize { - unsafe { - get_text::(client, buffer.cast(), size, |state| { - state.client.as_ref().map_or("", Client::node) - }) - } + unsafe { get_text::(client, buffer.cast(), size, node) } } /// The same as `BakaShrot_GetNodeA`, in UTF-16. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_GetNodeW(client: i64, buffer: *mut u16, size: isize) -> isize { - unsafe { - get_text::(client, buffer, size, |state| { - state.client.as_ref().map_or("", Client::node) - }) - } + unsafe { get_text::(client, buffer, size, node) } } // --- Pushing ----------------------------------------------------------------- @@ -499,7 +533,7 @@ unsafe fn topic_and_data( topic: *const T::Unit, data: *const T::Unit, ) -> Result<(String, String)> { - let topic = required(unsafe { text::read::(topic, "topic")? }, "topic")?; + let topic = unsafe { required::(topic, "topic")? }; let data = unsafe { text::read::(data, "the message")? }.unwrap_or_default(); Ok((topic, data)) } @@ -541,8 +575,8 @@ unsafe fn topic_and_node( topic: *const T::Unit, node: *const T::Unit, ) -> Result<(String, String)> { - let topic = required(unsafe { text::read::(topic, "topic")? }, "topic")?; - let node = required(unsafe { text::read::(node, "node")? }, "node")?; + let topic = unsafe { required::(topic, "topic")? }; + let node = unsafe { required::(node, "node")? }; Ok((topic, node)) } @@ -772,11 +806,35 @@ pub unsafe extern "C" fn BakaShrot_GetMessageNodeW( // --- Names ------------------------------------------------------------------- -fn list(client: i64, kind: NameKind) -> i32 { +/// Asks for a list of names: `kind` 1 topics, 2 nodes, as on the wire; +/// the filters null for any. +unsafe fn fetch_names( + state: &mut State, + kind: i32, + topics: *const T::Unit, + nodes: *const T::Unit, +) -> Result { + let kind = u8::try_from(kind) + .ok() + .and_then(|kind| NameKind::try_from(kind).ok()) + .ok_or_else(|| invalid(format!("a kind of {kind}: 1 (topics) or 2 (nodes)")))?; + let topics = unsafe { text::read::(topics, "topics")? }; + let nodes = unsafe { text::read::(nodes, "nodes")? }; + state + .client()? + .list_names(kind, topics.as_deref(), nodes.as_deref()) +} + +unsafe fn list( + client: i64, + kind: i32, + topics: *const T::Unit, + nodes: *const T::Unit, +) -> i32 { call(client, -1, |state| { state.names.clear(); - let list = state.client()?.list_names(kind)?; - let kind = match kind { + let list = unsafe { fetch_names::(state, kind, topics, nodes)? }; + let kind = match list.kind { NameKind::Topic => "topic", NameKind::Node => "node", }; @@ -791,27 +849,42 @@ fn list(client: i64, kind: NameKind) -> i32 { }) } -/// Lists the topics with messages that this client may push to or read -/// (every one if its roles have `list_topics` or `query`): how many, -1 on -/// failure. Then `BakaShrot_GetNamesList()`. +/// Lists topics (`kind` 1) or nodes (`kind` 2): the topics with messages +/// that this client may push to or read (every one if its roles have +/// `list_topics` or `query`), the nodes with messages in the topics it may +/// read (every one with `list_nodes` or `query`). Only those of the topic +/// and node pairs that `topics` and `nodes` match: each a name or a +/// pattern (`sensors.*`), null for any. Every topic: 1, null, null; the +/// topics a node pushed to: 1, null, the node; the nodes that pushed to a +/// topic: 2, the topic, null. How many, -1 on failure. Then +/// `BakaShrot_GetNamesListAsJson()`, or `BakaShrot_EnumerateNames()` +/// instead. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_ListTopics(client: i64) -> i32 { - list(client, NameKind::Topic) +pub unsafe extern "C" fn BakaShrot_ListNamesA( + client: i64, + kind: i32, + topics: *const c_char, + nodes: *const c_char, +) -> i32 { + unsafe { list::(client, kind, topics.cast(), nodes.cast()) } } -/// Lists the nodes with messages in the topics this client may read (every -/// one if its roles have `list_nodes` or `query`): how many, -1 on failure. Then -/// `BakaShrot_GetNamesList()`. +/// The same as `BakaShrot_ListNamesA`, in UTF-16. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_ListNodes(client: i64) -> i32 { - list(client, NameKind::Node) +pub unsafe extern "C" fn BakaShrot_ListNamesW( + client: i64, + kind: i32, + topics: *const u16, + nodes: *const u16, +) -> i32 { + unsafe { list::(client, kind, topics, nodes) } } /// The last list, as JSON: /// `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated` /// if some didn't fit. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetNamesListA( +pub unsafe extern "C" fn BakaShrot_GetNamesListAsJsonA( client: i64, buffer: *mut c_char, size: isize, @@ -819,9 +892,9 @@ pub unsafe extern "C" fn BakaShrot_GetNamesListA( unsafe { get_text::(client, buffer.cast(), size, |state| &state.names) } } -/// The same as `BakaShrot_GetNamesListA`, in UTF-16. +/// The same as `BakaShrot_GetNamesListAsJsonA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetNamesListW( +pub unsafe extern "C" fn BakaShrot_GetNamesListAsJsonW( client: i64, buffer: *mut u16, size: isize, @@ -831,17 +904,23 @@ pub unsafe extern "C" fn BakaShrot_GetNamesListW( // --- Queries ----------------------------------------------------------------- +/// Runs a query: the server's JSON. +unsafe fn fetch_query(state: &mut State, sql: *const T::Unit) -> Result { + let sql = unsafe { required::(sql, "query")? }; + state.client()?.query(&sql) +} + unsafe fn query(client: i64, sql: *const T::Unit) -> isize { call(client, 0, |state| { state.query.clear(); - let sql = required(unsafe { text::read::(sql, "query")? }, "query")?; - state.query = state.client()?.query(&sql)?; + state.query = unsafe { fetch_query::(state, sql)? }; Ok(1) }) } /// Runs read-only SQL on the server (one SELECT or WITH), if this client -/// may query. Then `BakaShrot_GetQueryResult()`. +/// may query. Then `BakaShrot_GetQueryResultAsJson()`, or +/// `BakaShrot_EnumerateQuery()` instead. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_QueryA(client: i64, sql: *const c_char) -> isize { unsafe { query::(client, sql.cast()) } @@ -856,7 +935,7 @@ pub unsafe extern "C" fn BakaShrot_QueryW(client: i64, sql: *const u16) -> isize /// The last query's result, as JSON: /// `{"columns":[...],"rows":[[...],...]}`, every value a string or null. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetQueryResultA( +pub unsafe extern "C" fn BakaShrot_GetQueryResultAsJsonA( client: i64, buffer: *mut c_char, size: isize, @@ -864,9 +943,9 @@ pub unsafe extern "C" fn BakaShrot_GetQueryResultA( unsafe { get_text::(client, buffer.cast(), size, |state| &state.query) } } -/// The same as `BakaShrot_GetQueryResultA`, in UTF-16. +/// The same as `BakaShrot_GetQueryResultAsJsonA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetQueryResultW( +pub unsafe extern "C" fn BakaShrot_GetQueryResultAsJsonW( client: i64, buffer: *mut u16, size: isize, @@ -889,7 +968,7 @@ unsafe fn push_with_file( ) -> i64 { call(client, -1, |state| { let (topic, data) = unsafe { topic_and_data::(topic, data)? }; - let path = required(unsafe { text::read::(path, "the file")? }, "file")?; + let path = unsafe { required::(path, "file")? }; let mut file = File::open(&path) .map_err(|error| Error::new(ErrorCode::FileError, format!("{path}: {error}")))?; let id = state @@ -983,7 +1062,7 @@ unsafe fn save( ) -> i64 { call(client, -1, |state| { let (topic, node) = unsafe { topic_and_node::(topic, node)? }; - let path = required(unsafe { text::read::(path, "the file")? }, "file")?; + let path = unsafe { required::(path, "file")? }; let size = state .client()? diff --git a/crates/bakashrot-capi/tests/exports.rs b/crates/bakashrot-capi/tests/exports.rs index 9615ae6..d78dd59 100644 --- a/crates/bakashrot-capi/tests/exports.rs +++ b/crates/bakashrot-capi/tests/exports.rs @@ -242,23 +242,45 @@ fn exports() { // Names, queries. // Topics: those with messages (nothing in `secret` yet). - assert_eq!(BakaShrot_ListTopics(client), 1); + let null = std::ptr::null(); + assert_eq!(BakaShrot_ListNamesW(client, 1, null, null), 1); assert_eq!( - get_w(client, BakaShrot_GetNamesListW), + get_w(client, BakaShrot_GetNamesListAsJsonW), r#"{"kind":"topic","names":["logs"],"truncated":false}"# ); - assert_eq!(BakaShrot_ListNodes(client), 1); + assert_eq!(BakaShrot_ListNamesW(client, 2, null, null), 1); + // Filtered: the topics a node pushed to, the nodes of a topic. + assert_eq!( + BakaShrot_ListNamesW(client, 1, null, w("KITCHEN").as_ptr()), + 1 + ); + assert_eq!( + 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_GetQueryResultW), + get_w(client, BakaShrot_GetQueryResultAsJsonW), r#"{"columns":["n"],"rows":[["3"]]}"# ); assert_eq!(BakaShrot_QueryW(client, w("SELECT nope").as_ptr()), 0); assert_eq!(error(client).0, code(ErrorCode::QueryFailed)); - assert_eq!(get_w(client, BakaShrot_GetQueryResultW), ""); + assert_eq!(get_w(client, BakaShrot_GetQueryResultAsJsonW), ""); // Attachments: from a file or memory, saved or loaded back. let (logs, kitchen) = (w("logs"), w("kitchen")); @@ -564,3 +586,120 @@ fn clients() { assert!(reads >= 1); assert_eq!(failed, code(ErrorCode::InvalidArgument)); } + +/// An enumeration's string at an index: asks for the size, then copies. +fn get_at( + enumeration: i64, + index: i32, + getter: unsafe extern "C" fn(i64, i32, *mut u16, isize) -> isize, +) -> String { + let size = unsafe { getter(enumeration, index, std::ptr::null_mut(), 0) }; + if size == 0 { + return String::new(); + } + let mut buffer = vec![0u16; size as usize / 2]; + unsafe { getter(enumeration, index, buffer.as_mut_ptr(), size) }; + String::from_utf16(&buffer[..buffer.len() - 1]).unwrap() +} + +/// Every name of an enumeration, `NextName` until it says no more. +fn names_of(enumeration: i64) -> Vec { + let mut names = Vec::new(); + while BakaShrot_NextName(enumeration) == 1 { + names.push(get_w(enumeration, BakaShrot_GetEnumNameW)); + } + names +} + +#[test] +fn enumerations() { + let running = common::Running::start("enumerations"); + running.issue("kitchen", &["home"]); + let client = connected(&running, "kitchen"); + let null = std::ptr::null(); + unsafe { + for (topic, data) in [("logs", "{}"), ("secret", "{}"), ("logs", "{}")] { + assert!(BakaShrot_PushMessageToW(client, w(topic).as_ptr(), w(data).as_ptr()) > 0); + } + + // Names: before the first at first, then each, then no more. + let topics = BakaShrot_EnumerateNamesW(client, 1, null, w("kitchen").as_ptr()); + assert!(topics > client, "numbered with the clients"); + assert_eq!(BakaShrot_GetNameCount(topics), 2); + assert_eq!(BakaShrot_IsNamesListTruncated(topics), 0); + assert_eq!( + get_w(topics, BakaShrot_GetEnumNameW), + "", + "before the first" + ); + assert_eq!(names_of(topics), ["logs", "secret"]); + assert_eq!(BakaShrot_NextName(topics), 0, "still none"); + assert_eq!(get_w(topics, BakaShrot_GetEnumNameW), ""); + // Several at once, each its own; the client's calls don't change them. + let nodes = BakaShrot_EnumerateNamesA(client, 2, a("s*").as_ptr(), null.cast()); + let none = BakaShrot_EnumerateNamesW(client, 2, w("nothing").as_ptr(), null); + assert_eq!(BakaShrot_ListNamesW(client, 1, null, null), 2); + assert_eq!(names_of(nodes), ["kitchen"]); + assert_eq!(BakaShrot_GetNameCount(none), 0); + assert_eq!(BakaShrot_NextName(none), 0); + // A failure: 0, the client's error. + assert_eq!(BakaShrot_EnumerateNamesW(client, 3, null, null), 0); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); + + // Queries: columns, rows, nulls. + let sql = w( + "SELECT topic, CASE WHEN message_id = 1 THEN NULL ELSE message_id END AS id \ + FROM messages ORDER BY topic, message_id", + ); + let query = BakaShrot_EnumerateQueryW(client, sql.as_ptr()); + assert!(query > 0, "{:?}", error(client)); + assert_eq!(BakaShrot_GetQueryColumnCount(query), 2); + assert_eq!(get_at(query, 0, BakaShrot_GetQueryColumnNameW), "topic"); + assert_eq!(get_at(query, 1, BakaShrot_GetQueryColumnNameW), "id"); + assert_eq!(get_at(query, 2, BakaShrot_GetQueryColumnNameW), ""); + assert_eq!(BakaShrot_IsQueryValueNull(query, 0), -1, "no row yet"); + let mut rows = Vec::new(); + while BakaShrot_NextQueryRow(query) == 1 { + let id = match BakaShrot_IsQueryValueNull(query, 1) { + 1 => None, + 0 => Some(get_at(query, 1, BakaShrot_GetQueryValueW)), + other => panic!("{other}"), + }; + rows.push((get_at(query, 0, BakaShrot_GetQueryValueW), id)); + } + let row = |topic: &str, id: Option<&str>| (topic.to_owned(), id.map(str::to_owned)); + assert_eq!( + rows, + [ + row("logs", None), + row("logs", Some("2")), + row("secret", None) + ] + ); + assert_eq!(BakaShrot_IsQueryValueNull(query, 0), -1, "past the last"); + assert_eq!( + BakaShrot_EnumerateQueryW(client, w("SELECT nope").as_ptr()), + 0 + ); + assert_eq!(error(client).0, code(ErrorCode::QueryFailed)); + + // Of the other kind, a client's, made up: refused, never a crash. + assert_eq!(BakaShrot_NextName(query), -1); + assert_eq!(BakaShrot_NextQueryRow(nodes), -1); + assert_eq!(BakaShrot_GetQueryColumnCount(nodes), -1); + assert_eq!(BakaShrot_NextName(client), -1); + assert_eq!(BakaShrot_NextName(99_999), -1); + assert_eq!(get_w(99_999, BakaShrot_GetEnumNameW), ""); + assert_eq!(BakaShrot_CloseEnum(client), 0, "a client isn't one"); + assert_eq!(BakaShrot_FreeClient(topics), 0, "nor the other way"); + + // Closed: refused after. Its client freed: all of its closed. + assert_eq!(BakaShrot_CloseEnum(topics), 1); + assert_eq!(BakaShrot_CloseEnum(topics), 0); + assert_eq!(BakaShrot_GetNameCount(topics), -1); + assert_eq!(BakaShrot_FreeClient(client), 1); + for enumeration in [nodes, none, query] { + assert_eq!(BakaShrot_CloseEnum(enumeration), 0, "{enumeration}"); + } + } +} diff --git a/crates/bakashrot-client/src/lib.rs b/crates/bakashrot-client/src/lib.rs index f570947..cfe5fd8 100644 --- a/crates/bakashrot-client/src/lib.rs +++ b/crates/bakashrot-client/src/lib.rs @@ -24,7 +24,7 @@ use bakashrot_proto::limits::{ ALPN, ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGE_SIZE, MAX_MESSAGES_PER_PACKET, MAX_PACKET_SIZE, }; -use bakashrot_proto::names::is_valid_name; +use bakashrot_proto::names::{is_valid_name, is_valid_name_or_pattern}; use bakashrot_proto::packets::{ Attachment, AttachmentPart, GetAttachment, GetMessages, ListNames, Messages, NameKind, NamesList, PushMessage, Query, @@ -245,12 +245,9 @@ impl Client { sha256.update(&buffer[..read]); size += read as u64; } - if !(1..=MAX_ATTACHMENT_SIZE).contains(&size) { - return Err(Error::new( - ErrorCode::InvalidArgument, - format!("an attachment of {size} bytes: 1 to {MAX_ATTACHMENT_SIZE}"), - )); - } + require((1..=MAX_ATTACHMENT_SIZE).contains(&size), || { + format!("an attachment of {size} bytes: 1 to {MAX_ATTACHMENT_SIZE}") + })?; source.rewind().map_err(file_error)?; let mut digest = [0; 32]; digest.copy_from_slice(sha256.finish().as_ref()); @@ -297,12 +294,9 @@ impl Client { ) -> Result { check_name(topic, "topic")?; check_name(node, "node")?; - if !(1..=MAX_MESSAGE_ID).contains(&message_id) { - return Err(Error::new( - ErrorCode::InvalidArgument, - format!("message {message_id}: 1 to {MAX_MESSAGE_ID}"), - )); - } + require((1..=MAX_MESSAGE_ID).contains(&message_id), || { + format!("message {message_id}: 1 to {MAX_MESSAGE_ID}") + })?; let get = GetAttachment { topic: topic.to_owned(), node: node.to_owned(), @@ -389,18 +383,12 @@ impl Client { ) -> Result { check_name(topic, "topic")?; check_name(node, "node")?; - if !(1..=MAX_MESSAGES_PER_PACKET).contains(&limit) { - return Err(Error::new( - ErrorCode::InvalidArgument, - format!("a limit of {limit}: 1 to {MAX_MESSAGES_PER_PACKET}"), - )); - } - if after.is_some_and(|after| after > MAX_MESSAGE_ID) { - return Err(Error::new( - ErrorCode::InvalidArgument, - format!("after {}: {MAX_MESSAGE_ID} at most", after.unwrap_or(0)), - )); - } + require((1..=MAX_MESSAGES_PER_PACKET).contains(&limit), || { + format!("a limit of {limit}: 1 to {MAX_MESSAGES_PER_PACKET}") + })?; + require(after.is_none_or(|after| after <= MAX_MESSAGE_ID), || { + format!("after {}: {MAX_MESSAGE_ID} at most", after.unwrap_or(0)) + })?; let get = GetMessages { topic: topic.to_owned(), node: node.to_owned(), @@ -415,10 +403,29 @@ impl Client { /// The topics with messages that this client may push to or read, or /// the nodes with messages in the topics it may read; every one if its - /// roles have `list_topics` / `list_nodes`, or `query`. `truncated` if - /// some didn't fit. - pub fn list_names(&mut self, kind: NameKind) -> Result { - match self.request(ListNames { kind }.into())? { + /// roles have `list_topics` / `list_nodes`, or `query`. `topics` and + /// `nodes` (a name or a pattern, `None` for any) keep those of the + /// topic and node pairs they match: the topics a node pushed to, the + /// nodes that pushed to a topic. `truncated` if some didn't fit. + pub fn list_names( + &mut self, + kind: NameKind, + topics: Option<&str>, + nodes: Option<&str>, + ) -> Result { + for (filter, what) in [(topics, "topic"), (nodes, "node")] { + if let Some(filter) = filter { + require(is_valid_name_or_pattern(filter), || { + format!("'{filter}' isn't a {what} name or pattern") + })?; + } + } + let list = ListNames { + kind, + topics: topics.map(str::to_owned), + nodes: nodes.map(str::to_owned), + }; + match self.request(list.into())? { Packet::NamesList(names) => Ok(names), other => Err(unexpected(&other)), } @@ -511,26 +518,25 @@ fn lost(error: io::Error) -> Error { } } -fn check_name(name: &str, what: &str) -> Result<()> { - if is_valid_name(name) { - Ok(()) - } else { - Err(Error::new( - ErrorCode::InvalidArgument, - format!("'{name}' isn't a {what} name"), - )) +/// An argument checked before sending: `InvalidArgument`, saying `why`, +/// if it isn't `ok`. +fn require(ok: bool, why: impl FnOnce() -> String) -> Result<()> { + match ok { + true => Ok(()), + false => Err(Error::new(ErrorCode::InvalidArgument, why())), } } +fn check_name(name: &str, what: &str) -> Result<()> { + require(is_valid_name(name), || { + format!("'{name}' isn't a {what} name") + }) +} + fn check_size(text: &str, what: &str) -> Result<()> { - if text.len() <= MAX_MESSAGE_SIZE { - Ok(()) - } else { - Err(Error::new( - ErrorCode::InvalidArgument, - format!("{what} of {} bytes: {MAX_MESSAGE_SIZE} at most", text.len()), - )) - } + require(text.len() <= MAX_MESSAGE_SIZE, || { + format!("{what} of {} bytes: {MAX_MESSAGE_SIZE} at most", text.len()) + }) } fn file_error(error: io::Error) -> Error { diff --git a/crates/bakashrot-config/src/roles.rs b/crates/bakashrot-config/src/roles.rs index 7ae812f..88dce97 100644 --- a/crates/bakashrot-config/src/roles.rs +++ b/crates/bakashrot-config/src/roles.rs @@ -1,7 +1,7 @@ //! Roles, and what a certificate's roles allow together. use crate::values::check_names; -use bakashrot_proto::names::{names_equal, pattern_matches}; +use bakashrot_proto::names::{name_matches, names_equal}; use serde::Deserialize; /// Topic or node names and patterns (`sensors.*`, `*` for all), none twice. @@ -27,9 +27,7 @@ impl NameList { /// Whether `name` is in it: one of its names, or matched by one of its /// patterns (without case). pub fn matches(&self, name: &str) -> bool { - self.0 - .iter() - .any(|entry| names_equal(entry, name) || pattern_matches(entry, name)) + self.0.iter().any(|entry| name_matches(entry, name)) } /// Whether it has nothing: matches nothing. @@ -117,15 +115,24 @@ impl Permissions { self.roles.iter().any(|role| role.query) } - /// Whether listing topics answers every one: `list_topics`, or - /// `query` (which reads them all anyway). - pub fn lists_every_topic(&self) -> bool { - self.roles.iter().any(|role| role.list_topics || role.query) + /// Whether listing names may show `topic`: one it may push to or + /// read, any with `list_topics` or `query` (which reads them all + /// anyway). + pub fn may_list_topic(&self, topic: &str) -> bool { + self.roles.iter().any(|role| { + role.list_topics + || role.query + || role.push_topics.matches(topic) + || role.read_topics.matches(topic) + }) } - /// Whether listing nodes answers every one: `list_nodes`, or `query`. - pub fn lists_every_node(&self) -> bool { - self.roles.iter().any(|role| role.list_nodes || role.query) + /// Whether listing names may show the nodes with messages in `topic`: + /// one it may read, any with `list_nodes` or `query`. + pub fn may_list_nodes_of(&self, topic: &str) -> bool { + self.roles + .iter() + .any(|role| role.list_nodes || role.query || role.read_topics.matches(topic)) } /// Whether `node`'s messages in `topic` are sent to it. diff --git a/crates/bakashrot-config/tests/config.rs b/crates/bakashrot-config/tests/config.rs index 2bed107..6a50bab 100644 --- a/crates/bakashrot-config/tests/config.rs +++ b/crates/bakashrot-config/tests/config.rs @@ -164,19 +164,23 @@ accept_nodes = ["garage"] assert!(both.can_read("Logs")); assert!(!both.can_read("sensors.garage")); assert!(!both.can_query()); - assert!(!both.lists_every_topic() && !both.lists_every_node()); + // Listing: the topics it may push to or read, the nodes of those it reads. + assert!(both.may_list_topic("sensors.garage") && both.may_list_topic("logs")); + assert!(!both.may_list_topic("other")); + assert!(both.may_list_nodes_of("logs") && !both.may_list_nodes_of("sensors.garage")); let admin = config.permissions(&["admin"]).unwrap(); assert!(admin.can_query()); - // A query reads them all anyway. - assert!(admin.lists_every_topic() && admin.lists_every_node()); + // A query reads them all anyway; reading messages is still read_topics. + assert!(admin.may_list_topic("other") && admin.may_list_nodes_of("other")); + assert!(!admin.can_read("logs")); let listing = Config::parse(&with( "[roles.a]\nlist_topics = true\n[roles.b]\nlist_nodes = true\n", )) .unwrap(); let a = listing.permissions(&["a"]).unwrap(); - assert!(a.lists_every_topic() && !a.lists_every_node() && !a.can_query()); + assert!(a.may_list_topic("other") && !a.may_list_nodes_of("other") && !a.can_query()); let b = listing.permissions(&["b", "a"]).unwrap(); - assert!(b.lists_every_topic() && b.lists_every_node()); + assert!(b.may_list_topic("other") && b.may_list_nodes_of("other")); // Replication: each role's topics with that role's nodes, not mixed. let peer = config.permissions(&["peer", "backup"]).unwrap(); @@ -338,6 +342,10 @@ fn refusals() { &with("[roles.r]\naccept_nodes = [\"x\", \"X\"]\n"), "'X' is given twice", ), + ( + &with("[roles.r]\nlist_topics = 1\n"), + "invalid type: integer", + ), (&with("[roles.r]\nquery = 1\n"), "invalid type: integer"), (&with("[roles.site.reader]\n"), "unknown field `reader`"), ]; diff --git a/crates/bakashrot-proto/src/frame.rs b/crates/bakashrot-proto/src/frame.rs index 9ffdbe0..ecb9c3e 100644 --- a/crates/bakashrot-proto/src/frame.rs +++ b/crates/bakashrot-proto/src/frame.rs @@ -169,11 +169,11 @@ mod tests { fn versions() { let mut stream = Vec::new(); write_version(&mut stream).unwrap(); - assert_eq!(stream, [7, 0, 0, 0]); + assert_eq!(stream, [8, 0, 0, 0]); let bytes = read_version(&mut &stream[..]).unwrap(); assert_eq!(check_version(bytes), Ok(())); - assert_eq!(check_version([6, 0, 0, 0]), Err(6)); - assert_eq!(check_version([8, 0, 0, 0]), Err(8)); + assert_eq!(check_version([7, 0, 0, 0]), Err(7)); + assert_eq!(check_version([9, 0, 0, 0]), Err(9)); assert!(read_version(&mut &[7u8, 0][..]).is_err()); } diff --git a/crates/bakashrot-proto/src/lib.rs b/crates/bakashrot-proto/src/lib.rs index 8159e8a..32e3bda 100644 --- a/crates/bakashrot-proto/src/lib.rs +++ b/crates/bakashrot-proto/src/lib.rs @@ -1,4 +1,4 @@ -//! BakaShrot's protocol, version 7: what the server, the clients and the +//! BakaShrot's protocol, version 8: what the server, the clients and the //! tools share, and nothing else. //! //! No I/O of its own beyond reading and writing frames on a stream it's diff --git a/crates/bakashrot-proto/src/limits.rs b/crates/bakashrot-proto/src/limits.rs index 487b118..202824a 100644 --- a/crates/bakashrot-proto/src/limits.rs +++ b/crates/bakashrot-proto/src/limits.rs @@ -5,7 +5,7 @@ /// The protocol's version. Both ends must have the same: they tell each /// other first thing (`frame::write_version()`), and abandon the /// connection if it differs. -pub const PROTOCOL_VERSION: u32 = 7; +pub const PROTOCOL_VERSION: u32 = 8; /// The ALPN protocol name both ends offer during the TLS handshake: what /// isn't BakaShrot doesn't get past it. Not versioned: the version is diff --git a/crates/bakashrot-proto/src/names.rs b/crates/bakashrot-proto/src/names.rs index f86d120..b3831f4 100644 --- a/crates/bakashrot-proto/src/names.rs +++ b/crates/bakashrot-proto/src/names.rs @@ -45,6 +45,12 @@ pub fn is_valid_name_or_pattern(text: &str) -> bool { is_valid_name(text) || is_valid_pattern(text) } +/// Whether `name` is `filter` (a name) or matches it (a pattern), without +/// case: what a list of names and patterns holds, one entry. +pub fn name_matches(filter: &str, name: &str) -> bool { + names_equal(filter, name) || pattern_matches(filter, name) +} + /// Whether the name `name` matches `pattern` (without case). Anything that /// isn't a valid name never matches. pub fn pattern_matches(pattern: &str, name: &str) -> bool { @@ -144,4 +150,12 @@ mod tests { ); } } + + #[test] + fn filters() { + assert!(name_matches("Logs", "logs")); + assert!(name_matches("sensors.*", "Sensors.kitchen")); + assert!(!name_matches("logs", "logs-1")); + assert!(!name_matches("sensors.*", "sensor.x")); + } } diff --git a/crates/bakashrot-proto/src/packets/messages.rs b/crates/bakashrot-proto/src/packets/messages.rs index d958d24..c6c94f7 100644 --- a/crates/bakashrot-proto/src/packets/messages.rs +++ b/crates/bakashrot-proto/src/packets/messages.rs @@ -201,16 +201,36 @@ impl TryFrom for NameKind { } } -/// Every topic or node the client may see. +/// The topics or nodes the client may see, of the topic and node pairs +/// with messages that the filters match: the topics a node pushed to, the +/// nodes that pushed to a topic. /// -/// `[11, [kind]]` +/// `[11, [kind, topics, nodes]]` #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListNames { /// Topics or nodes. pub kind: NameKind, + /// Only the pairs whose topic is this name or matches this pattern; + /// nil for any. + pub topics: Option, + /// Only the pairs whose node is this name or matches this pattern; + /// nil for any. + pub nodes: Option, } -impl Check for ListNames {} +impl Check for ListNames { + fn check(&self) -> Result<(), DecodeError> { + for (filter, field) in [ + (&self.topics, "ListNames.topics"), + (&self.nodes, "ListNames.nodes"), + ] { + if let Some(filter) = filter { + rules::name_or_pattern(filter, field)?; + } + } + Ok(()) + } +} /// Topics or nodes. /// diff --git a/crates/bakashrot-proto/src/packets/mod.rs b/crates/bakashrot-proto/src/packets/mod.rs index bb7763e..f4abc57 100644 --- a/crates/bakashrot-proto/src/packets/mod.rs +++ b/crates/bakashrot-proto/src/packets/mod.rs @@ -1,4 +1,4 @@ -//! Every packet of protocol 7. +//! Every packet of protocol 8. //! //! A packet is a MessagePack array of two: its type, then its fields as an //! array, `[type, [field, field, ...]]`. Structs inside are arrays of their @@ -298,6 +298,15 @@ pub(crate) mod rules { require(names::is_valid_name(value), field, "must be a name") } + /// A topic or node name, or a pattern. + pub fn name_or_pattern(value: &str, field: &'static str) -> Result<(), DecodeError> { + require( + names::is_valid_name_or_pattern(value), + field, + "must be a name or a pattern", + ) + } + /// A message id: 1 and up. pub fn message_id(value: u64, field: &'static str) -> Result<(), DecodeError> { range(value, 1, MAX_MESSAGE_ID, field) diff --git a/crates/bakashrot-proto/src/packets/replication.rs b/crates/bakashrot-proto/src/packets/replication.rs index f407436..7278d2a 100644 --- a/crates/bakashrot-proto/src/packets/replication.rs +++ b/crates/bakashrot-proto/src/packets/replication.rs @@ -9,7 +9,6 @@ use crate::limits::{ MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_MISSING_ATTACHMENTS, MAX_NAMES_LIST_ENTRIES, }; -use crate::names; use serde::{Deserialize, Serialize}; /// What the server takes from this peer, how far it is, and the @@ -75,11 +74,7 @@ impl Check for SyncState { ] { rules::most(list.len(), MAX_NAMES_LIST_ENTRIES, field)?; for item in list { - rules::require( - names::is_valid_name_or_pattern(item), - field, - "must be a name or a pattern", - )?; + rules::name_or_pattern(item, field)?; } } for head in &self.heads { diff --git a/crates/bakashrot-proto/tests/packets.rs b/crates/bakashrot-proto/tests/packets.rs index fcd5459..1df6a9e 100644 --- a/crates/bakashrot-proto/tests/packets.rs +++ b/crates/bakashrot-proto/tests/packets.rs @@ -98,6 +98,14 @@ fn samples() -> Vec { AttachmentPart { data: vec![1] }.into(), ListNames { kind: NameKind::Topic, + topics: None, + nodes: None, + } + .into(), + ListNames { + kind: NameKind::Node, + topics: Some("sensors.*".into()), + nodes: Some("kitchen".into()), } .into(), NamesList { @@ -297,8 +305,18 @@ fn shapes() { PacketType::Messages, (1u8, Vec::::new()) ))); - assert!(malformed(&raw(PacketType::ListNames, (3u8,))), "kind 3"); - assert!(malformed(&raw(PacketType::ListNames, (0u8,))), "kind 0"); + assert!( + malformed(&raw(PacketType::ListNames, (3u8, (), ()))), + "kind 3" + ); + assert!( + malformed(&raw(PacketType::ListNames, (0u8, (), ()))), + "kind 0" + ); + assert!( + malformed(&raw(PacketType::ListNames, (1u8,))), + "protocol 7's, no filters" + ); assert!( malformed(&raw( PacketType::Attachment, @@ -365,6 +383,19 @@ fn ranges() { assert!(Packet::decode(&get(Some(MAX_MESSAGE_ID), 1)).is_ok()); assert!(invalid(&get(Some(MAX_MESSAGE_ID + 1), 1))); + let list = |topics: Option<&str>, nodes: Option<&str>| { + ListNames { + kind: NameKind::Node, + topics: topics.map(Into::into), + nodes: nodes.map(Into::into), + } + .encode() + }; + assert!(Packet::decode(&list(Some("sensors.*"), Some("kitchen"))).is_ok()); + assert!(invalid(&list(Some("a b"), None))); + assert!(invalid(&list(None, Some("")))); + assert!(invalid(&list(None, Some("12")))); + let times = |pushed_at| { Messages { more: false, diff --git a/crates/bakashrot-server/src/connection.rs b/crates/bakashrot-server/src/connection.rs index af67693..fed766c 100644 --- a/crates/bakashrot-server/src/connection.rs +++ b/crates/bakashrot-server/src/connection.rs @@ -7,7 +7,7 @@ use aws_lc_rs::digest; use bakashrot_config::Permissions; use bakashrot_pki::Identity; use bakashrot_proto::limits::{MAX_MESSAGE_SIZE, MAX_NAMES_LIST_ENTRIES, MAX_PACKET_SIZE}; -use bakashrot_proto::names::names_equal; +use bakashrot_proto::names::{name_matches, names_equal}; use bakashrot_proto::packets::{ Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed, Messages, NameKind, NamesList, PushMessage, Query, QueryResult, RequestRefused, Welcome, @@ -476,38 +476,50 @@ async fn get_messages(shared: &Arc, peer: &Peer, get: GetMessages) -> Pa } } -/// Topics: those with messages (pushed here or replicated) that it may -/// push to or read; every one with `list_topics` or `query`. Nodes: those -/// with messages in the topics it may read; every one with `list_nodes` -/// or `query`. +/// The topics or nodes of the topic and node pairs with messages (pushed +/// here or replicated, or that had some) that the filters match, among +/// those it may see. A pair's topic must be one it may see when the answer +/// is topics or `topics` filters them: one it may push to or read, any +/// with `list_topics` or `query`. Its node, when the answer is nodes or +/// `nodes` filters them: one in a topic it may read, any with +/// `list_nodes` or `query`. Without filters: the topics it may see, the +/// nodes it may. async fn list_names(shared: &Arc, peer: &Peer, list: ListNames) -> Packet { - let permissions = &peer.permissions; - let found = match list.kind { - NameKind::Topic => shared - .read(|reader| reader.topics()) - .await - .map(|mut topics| { - if !permissions.lists_every_topic() { - topics - .retain(|topic| permissions.can_push(topic) || permissions.can_read(topic)); - } - topics - }), - NameKind::Node if permissions.lists_every_node() => { - shared.read(|reader| reader.nodes()).await - } - NameKind::Node => shared.read(|reader| reader.heads()).await.map(|heads| { - let mut nodes: Vec = heads + let permissions = peer.permissions.clone(); + let kind = list.kind; + // A pass over every pair: on the read's thread, off the async ones. + let found = shared + .read(move |reader| { + let matches = |filter: &Option, name: &str| { + filter + .as_deref() + .is_none_or(|filter| name_matches(filter, name)) + }; + let check_topic = kind == NameKind::Topic || list.topics.is_some(); + let check_node = kind == NameKind::Node || list.nodes.is_some(); + let mut names: Vec = reader + .heads()? .into_iter() - .filter(|head| permissions.can_read(&head.topic)) - .map(|head| head.node) + .filter(|head| { + matches(&list.topics, &head.topic) + && matches(&list.nodes, &head.node) + && (!check_topic || permissions.may_list_topic(&head.topic)) + && (!check_node || permissions.may_list_nodes_of(&head.topic)) + }) + .map(|head| match kind { + NameKind::Topic => head.topic, + NameKind::Node => head.node, + }) .collect(); - // As `reader.nodes()` answers them: in order, none twice. - nodes.sort_by_cached_key(|node| node.to_ascii_lowercase()); - nodes.dedup_by(|a, b| names_equal(a, b)); - nodes - }), - }; + // In order, none twice (names are without case). + names.sort_unstable_by(|a, b| { + let a = a.bytes().map(|c| c.to_ascii_lowercase()); + a.cmp(b.bytes().map(|c| c.to_ascii_lowercase())) + }); + names.dedup_by(|a, b| names_equal(a, b)); + Ok(names) + }) + .await; let mut names = match found { Ok(names) => names, Err(refused) => return refused.into(), @@ -515,7 +527,7 @@ async fn list_names(shared: &Arc, peer: &Peer, list: ListNames) -> Packe let truncated = names.len() > MAX_NAMES_LIST_ENTRIES; names.truncate(MAX_NAMES_LIST_ENTRIES); NamesList { - kind: list.kind, + kind, truncated, names, } diff --git a/crates/bakashrot-server/tests/end_to_end.rs b/crates/bakashrot-server/tests/end_to_end.rs index b89046c..a0e25ea 100644 --- a/crates/bakashrot-server/tests/end_to_end.rs +++ b/crates/bakashrot-server/tests/end_to_end.rs @@ -596,12 +596,13 @@ fn names() { .connect(&running.issue("analyst-1", &["analyst"])) .unwrap(); - let names = |client: &mut Client, kind| { - let list = client.list_names(kind).unwrap(); + let filtered = |client: &mut Client, kind, topics, nodes| { + let list = client.list_names(kind, topics, nodes).unwrap(); assert_eq!(list.kind, kind); assert!(!list.truncated); list.names }; + let names = |client: &mut Client, kind| filtered(client, kind, None, None); // Topics: those it may push to or read; every one for a query role. assert_eq!(names(&mut sensor, NameKind::Topic), ["logs", "sensors"]); assert_eq!(names(&mut screen, NameKind::Topic), ["logs"]); @@ -624,6 +625,55 @@ fn names() { ), ErrorCode::NotAllowed.code() ); + + // Filtered: the topics a node pushed to, the nodes that pushed to a + // topic; names (without case) or patterns. + sensor.push("sensors", "{}").unwrap(); + let (topic, node) = (NameKind::Topic, NameKind::Node); + let every = &mut analyst; + assert_eq!( + filtered(every, topic, None, Some("kitchen")), + ["logs", "sensors"] + ); + assert_eq!( + filtered(every, topic, None, Some("KITCHEN")), + ["logs", "sensors"] + ); + assert_eq!(filtered(every, topic, None, Some("g*")), ["sensors"]); + assert!(filtered(every, topic, None, Some("nobody")).is_empty()); + assert_eq!( + filtered(every, node, Some("sensors"), None), + ["garage", "kitchen"] + ); + assert_eq!(filtered(every, node, Some("l?gs"), None), ["kitchen"]); + assert_eq!(filtered(every, node, Some("*"), Some("k*")), ["kitchen"]); + assert_eq!( + filtered(every, topic, Some("s*"), Some("kitchen")), + ["sensors"] + ); + // Only what it may see: the nodes of the topics it may read... + assert_eq!( + filtered(&mut screen, topic, None, Some("kitchen")), + ["logs"] + ); + assert!(filtered(&mut screen, topic, None, Some("garage")).is_empty()); + assert_eq!(filtered(&mut screen, node, Some("*"), None), ["kitchen"]); + // ...not of those it may only push to, the topics of those it may. + assert!(filtered(&mut sensor, topic, None, Some("garage")).is_empty()); + assert_eq!(filtered(&mut sensor, topic, Some("s*"), None), ["sensors"]); + assert_eq!( + filtered(&mut explorer, topic, None, Some("garage")), + ["sensors"] + ); + assert_eq!( + filtered(&mut explorer, node, Some("logs"), None), + ["kitchen"] + ); + // Neither a name nor a pattern: refused before it's sent. + let error = analyst + .list_names(NameKind::Node, Some("a b"), None) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::InvalidArgument.code(), "{error}"); } /// Queries: allowed or not, results, refusals. @@ -1549,14 +1599,20 @@ fn replication_edges() { assert_eq!(got.messages[0].data, "m1"); // (`old` had a message, past its age.) assert_eq!( - reader.list_names(NameKind::Topic).unwrap().names, + reader + .list_names(NameKind::Topic, None, None) + .unwrap() + .names, ["elsewhere", "logs", "old"] ); let mut logs_only = running .connect(&running.issue("lounge", &["logs"])) .unwrap(); assert_eq!( - logs_only.list_names(NameKind::Topic).unwrap().names, + logs_only + .list_names(NameKind::Topic, None, None) + .unwrap() + .names, ["logs"] ); assert_eq!( diff --git a/crates/bakashrot-storage/src/database.rs b/crates/bakashrot-storage/src/database.rs index 6336f8a..678640d 100644 --- a/crates/bakashrot-storage/src/database.rs +++ b/crates/bakashrot-storage/src/database.rs @@ -4,7 +4,7 @@ use crate::{Error, QueryRunner, Reader, Result, SCHEMA_VERSION, Writer}; use bakashrot_config::Synchronous; use rusqlite::hooks::{AuthAction, AuthContext, Authorization}; -use rusqlite::{Connection, OptionalExtension, TransactionBehavior}; +use rusqlite::{Connection, OpenFlags, OptionalExtension, TransactionBehavior}; use std::path::{Path, PathBuf}; use std::time::Duration; @@ -129,13 +129,20 @@ impl Database { Ok(Reader::new(self.connect()?)) } - /// A connection for clients' queries: read-only (`query_only`), and - /// every PRAGMA refused from then on (SQLite's authorizer). Some take - /// effect when they're prepared, before a statement can be refused - /// for what it is: `PRAGMA query_only = 0` turned `query_only` off - /// for the connection's next queries. + /// A connection for clients' queries: the file opened read-only + /// (`SQLITE_OPEN_READONLY`: the file handle can't write), `query_only`, + /// and every PRAGMA refused from then on (SQLite's authorizer). Some + /// take effect when they're prepared, before a statement can be + /// refused for what it is: `PRAGMA query_only = 0` turned + /// `query_only` off for the connection's next queries. The database is + /// in WAL mode already (the writer made it so), which a read-only + /// connection can't change and doesn't need to. pub fn query_runner(&self) -> Result { - let mut connection = self.connect()?; + let flags = OpenFlags::SQLITE_OPEN_READ_ONLY + | OpenFlags::SQLITE_OPEN_URI + | OpenFlags::SQLITE_OPEN_NO_MUTEX; + let mut connection = Connection::open_with_flags(&self.path, flags)?; + connection.busy_timeout(BUSY_TIMEOUT)?; connection.pragma_update(None, "query_only", true)?; connection.authorizer(Some(|context: AuthContext<'_>| match context.action { AuthAction::Pragma { .. } => Authorization::Deny, diff --git a/crates/bakashrot-storage/src/query.rs b/crates/bakashrot-storage/src/query.rs index eccdb7e..9bac0e3 100644 --- a/crates/bakashrot-storage/src/query.rs +++ b/crates/bakashrot-storage/src/query.rs @@ -1,7 +1,8 @@ //! Clients' read-only SQL (`Query`). //! -//! Read-only three ways: the connection has `query_only` on (SQLite -//! refuses any write), the statement must be one SQLite says only reads +//! Read-only four ways: the file is opened read-only (the handle itself +//! can't write), the connection has `query_only` on (SQLite refuses any +//! write), the statement must be one SQLite says only reads //! (`sqlite3_stmt_readonly`), and only one statement runs (more is an //! error, not ignored). PRAGMAs are refused as they're prepared //! (`Database::query_runner`'s authorizer): some would change the @@ -96,3 +97,33 @@ fn text(value: ValueRef<'_>) -> Value { ValueRef::Blob(bytes) => Value::String(bytes.iter().map(|b| format!("{b:02x}")).collect()), } } + +#[cfg(test)] +mod tests { + use crate::Database; + use bakashrot_config::Synchronous; + use rusqlite::MAIN_DB; + use std::path::PathBuf; + + /// The fifth guard, which the others hide from a test of what's + /// refused: SQLite says the file itself is read-only on it. + #[test] + fn the_file_is_opened_read_only() { + let folder = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/storage-unit"); + std::fs::create_dir_all(&folder).unwrap(); + let path = folder.join(format!("query-{}.sqlite", std::process::id())); + let database = Database::open(&path, Synchronous::Normal).unwrap(); + // The server's writer is always open: the WAL's files are there. + let writer = database.writer().unwrap(); + let runner = database.query_runner().unwrap(); + assert!(runner.connection.is_readonly(MAIN_DB).unwrap()); + assert_eq!( + runner.run("SELECT 1 AS one").unwrap(), + r#"{"columns":["one"],"rows":[["1"]]}"# + ); + drop((runner, writer, database)); + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); + } + } +} diff --git a/crates/bakashrot-storage/src/reader.rs b/crates/bakashrot-storage/src/reader.rs index 1f921be..79bdad0 100644 --- a/crates/bakashrot-storage/src/reader.rs +++ b/crates/bakashrot-storage/src/reader.rs @@ -152,11 +152,6 @@ impl Reader { self.strings("SELECT DISTINCT topic FROM streams ORDER BY topic") } - /// Every node with messages (or that had some), in order. - pub fn nodes(&self) -> Result> { - self.strings("SELECT DISTINCT node FROM streams ORDER BY node") - } - /// Whether `node` has messages in any topic (or had some). fn has_node(&self, node: &str) -> Result { self.connection diff --git a/crates/bakashrot-storage/tests/storage.rs b/crates/bakashrot-storage/tests/storage.rs index 2838c60..261ba1b 100644 --- a/crates/bakashrot-storage/tests/storage.rs +++ b/crates/bakashrot-storage/tests/storage.rs @@ -159,7 +159,6 @@ fn pushing_and_reading() { // Names, heads. assert_eq!(reader.topics().unwrap(), ["logs", "sensors"]); - assert_eq!(reader.nodes().unwrap(), ["garage", "kitchen"]); let heads: Vec<_> = reader .heads() .unwrap() diff --git a/crates/bakashrot-tools/src/main.rs b/crates/bakashrot-tools/src/main.rs index a582d47..891c154 100644 --- a/crates/bakashrot-tools/src/main.rs +++ b/crates/bakashrot-tools/src/main.rs @@ -105,10 +105,20 @@ enum Command { }, /// Lists the topics this client may use and the nodes of those it may /// read; every one if its roles have list_topics / list_nodes, or query. + /// --topics and --nodes keep the topics and nodes of the topic and node + /// pairs they match: `list topics --nodes kitchen` the topics kitchen + /// pushed to, `list nodes --topics 'sensors.*'` the nodes that pushed + /// to those. List { /// What to list. #[arg(value_enum, default_value_t = What::All)] what: What, + /// Only of the topics with this name or matching this pattern. + #[arg(long)] + topics: Option, + /// Only of the nodes with this name or matching this pattern. + #[arg(long)] + nodes: Option, /// Prints JSON, a line per list: {"kind":...,"names":[...],"truncated":...}. #[arg(long)] json: bool, @@ -264,7 +274,12 @@ fn run(config: &Path, command: Command) -> Result<(), String> { let sql = input(&sql)?; println!("{}", connect(config)?.query(&sql).map_err(failed)?); } - Command::List { what, json } => { + Command::List { + what, + topics, + nodes, + json, + } => { let mut client = connect(config)?; let kinds = [ (NameKind::Topic, "topic", "Topics"), @@ -277,7 +292,9 @@ fn run(config: &Path, command: Command) -> Result<(), String> { ) { continue; } - let list = client.list_names(kind).map_err(failed)?; + let list = client + .list_names(kind, topics.as_deref(), nodes.as_deref()) + .map_err(failed)?; if json { let json = serde_json::json!({ "kind": name, diff --git a/crates/bakashrot-tools/tests/bakashrot.rs b/crates/bakashrot-tools/tests/bakashrot.rs index c1b61f6..9490aeb 100644 --- a/crates/bakashrot-tools/tests/bakashrot.rs +++ b/crates/bakashrot-tools/tests/bakashrot.rs @@ -463,6 +463,24 @@ fn queries_and_lists() { json.ok().out, "{\"kind\":\"node\",\"names\":[\"kitchen\"],\"truncated\":false}\n" ); + // Filtered: the topics a node pushed to, the nodes of some topics. + assert_eq!( + server + .tool("kitchen", &["list", "topics", "--nodes", "Kitchen"]) + .ok() + .out, + "Topics (1):\n logs\n" + ); + assert_eq!( + server + .tool("kitchen", &["list", "--topics", "l*", "--nodes", "nobody"]) + .ok() + .out, + "Topics (0):\nNodes (0):\n" + ); + server + .tool("kitchen", &["list", "nodes", "--topics", "a b"]) + .fails(1, "isn't a topic name or pattern"); server .tool("kitchen", &["list", "everything"]) .fails(2, "everything"); diff --git a/docs/client.md b/docs/client.md index 6d3c48f..ad7138f 100644 --- a/docs/client.md +++ b/docs/client.md @@ -67,11 +67,12 @@ Its conventions: on the other; the C runtime linked statically on Windows (the release DLL imports system DLLs only). -Every export but `CreateClient` takes the handle first (left out below). +Every export but `CreateClient` takes the handle first (left out below): +a client's, or an enumeration's for the enumeration getters. | Exports | What | |---|---| -| `CreateClient()`, `FreeClient` | a new client's handle (0 if it failed); freed, 1 | +| `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` | | `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 | @@ -80,8 +81,11 @@ Every export but `CreateClient` takes the handle first (left out below). | `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` | | `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}` | -| `Query(Sql)`, then `GetQueryResult` (`A`/`W`) | `{"columns":[...],"rows":[[...],...]}` | +| `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)` (`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`) | | `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 | @@ -89,6 +93,27 @@ Every export but `CreateClient` takes the handle first (left out below). 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 `bindings/python/bakashrot.py`: `Client(server, ca, @@ -98,7 +123,9 @@ on 3.8), `client.node` once connected, `push(data, topic, attachment=None)` (the topic required; the attachment bytes or a path), `latest()`, `get_messages()`, `iter_messages()`, `follow()`, `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()`. Each `Client` has its own client in the DLL: several can be connected at once, from any threads. Errors: `RefusedError`, `ConnectionLostError`, `AuthError` (a certificate @@ -140,8 +167,15 @@ using (Client client = new Client("10.0.0.2", 7000, "ca.crt", "kitchen.crt", "ki 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: +`ListNodes()` / `Query()` (the library's JSON, as a string: parsing it +is the app's; `ListTopics(topic, node)` / `ListNodes(topic, node)` +filter the lists as Python's do, null for any), `EnumerateTopics()` / +`EnumerateNodes()` (the same, filtered the same, as an +`IEnumerable`) and `EnumerateQuery()` (`QueryRow`s: `Values`, +null for NULL, by index or column name, `Columns`), over the library's +enumerations, no JSON: each `foreach` asks again, the enumeration closed +when it ends (`Close()` ends it too, `ConnectionLostException`), +`Close()` / `Dispose()`. The same exceptions as Python's: `RefusedException`, `ConnectionLostException`, `AuthException`, `BakaShrotException`, each with its `ErrorCode`. Strings go as UTF-16 (the `W` exports); one with a NUL is refused (`InvalidArgument`) rather than @@ -184,6 +218,8 @@ bakashrot messages logs kitchen -f --after latest --time bakashrot query "SELECT topic, count(*) FROM messages GROUP BY topic" bakashrot list Topics (2): ... Nodes (1): ... bakashrot list nodes --json {"kind":"node","names":["kitchen"],"truncated":false} +bakashrot list topics --nodes kitchen Topics (1): the topics kitchen pushed to +bakashrot list nodes --topics 'sensors.*' Nodes (2): those that pushed to sensors.* ``` - **`messages`:** the first 100 by default (`--limit 0` for all), `--after diff --git a/docs/config.md b/docs/config.md index e60a65b..b673522 100644 --- a/docs/config.md +++ b/docs/config.md @@ -49,7 +49,7 @@ that browses a server: reading a topic is still `read_topics`. `query` gives both, it reads everything anyway. No `AllowRead` / `AllowWrite`: a list that's empty allows nothing. No -default topic: a push always names its topic (protocol 7 has none). +default topic: a push always names its topic (protocol 8 has none). **The roles are the only lists of topics** (decided 2026-11-16): no `[server] topics`, no `[replication] replicated_topics`, both refused as diff --git a/docs/lab.md b/docs/lab.md index 40609b9..705fc5e 100644 --- a/docs/lab.md +++ b/docs/lab.md @@ -163,7 +163,7 @@ certificate is refused, at its next connection or request: Failed to connect to server-2.lab:7000 (AuthRejected): the server refused this client's certificate (CertificateRevoked) ``` -**Python.** `pip install bakashrot-0.3.0-py3-none-.whl` (from the +**Python.** `pip install bakashrot-0.4.0-py3-none-.whl` (from the release's `python/`), then, next to lab-py's `client.toml` (it may push and read: `sensor` and `dashboard`): diff --git a/docs/protocol.md b/docs/protocol.md index b336e65..6ae3bb3 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -1,4 +1,4 @@ -# Protocol 7 +# Protocol 8 What goes over a connection between a client and a server, or two servers. The code is `crates/bakashrot-proto`; this describes it. @@ -83,8 +83,9 @@ format, its values are checked all the same.) ### Types Direction: **C** client, **S** server, **P** peer (a server linked to -another, as its client). Ids are protocol 7's own (6 can't connect); a new -packet takes the next one, none is ever reused. +another, as its client). Ids are protocol 7's own (6 can't connect; 8 +added `ListNames`' filters); a new packet takes the next one, none is +ever reused. | Id | Packet | Dir | Fields | Answered by | |---|---|---|---|---| @@ -98,7 +99,7 @@ packet takes the next one, none is ever reused. | 8 | GetAttachment | C→S | `topic`, `node`, `message_id`, `from_part` | Attachment then its parts / RequestRefused | | 9 | Attachment | S→C | `size`, `sha256` | | | 10 | AttachmentPart | C→S, S→C, P→S | `data` bin, 1 B to 1 MiB | | -| 11 | ListNames | C→S | `kind` (1 topics, 2 nodes) | NamesList | +| 11 | ListNames | C→S | `kind` (1 topics, 2 nodes), `topics`, `nodes`: each a name or a pattern, or nil for any (those of the topic/node pairs they match) | NamesList | | 12 | NamesList | S→C | `kind`, `truncated` bool, `[name...]` (65536 at most) | | | 13 | Query | C→S | `sql` str | QueryResult / RequestRefused | | 14 | QueryResult | S→C | `json` str: `{"columns":[...],"rows":[[...],...]}` | | diff --git a/docs/server.md b/docs/server.md index fc2bc9f..7922376 100644 --- a/docs/server.md +++ b/docs/server.md @@ -7,7 +7,7 @@ the wire: `protocol.md`. **Status:** steps 5, 6, 9, 10, 11 and 12: connecting, pushes and their attachments, messages, attachments, names, queries, retention, -replication, stopping cleanly. Every request of protocol 7 is answered. +replication, stopping cleanly. Every request of protocol 8 is answered. ## Running @@ -77,7 +77,7 @@ uid 10001. |---|---|---| | Connections | tokio, a task each | TLS (`tokio-rustls`, `bakashrot-pki`'s settings), the versions, the identity, then requests one at a time | | Writes | one writer thread | a queue of every write (pushes, uploads and their parts, replicated messages and parts, retention's deletes); the thread writes whatever is queued in one transaction (group commit, 1000 at most): the busier, the bigger the groups | -| Reads, queries | tokio's blocking threads | a pool of read connections and one of query connections (`query_only`), reused | +| Reads, queries | tokio's blocking threads | a pool of read connections and one of query connections (the file opened read-only, `query_only`), reused | | WAL checkpoints | one thread, every second | its own connection, off the writer's way (`storage.md`) | | The CRL file | a task, every 5 s | reloaded when its time or size changes; one that isn't the CA's is refused, the previous one stays; no file: nothing revoked, warned | | Retention | a task, at start then every `retention_interval` (1 min) | below | @@ -213,6 +213,15 @@ the same ids with different messages, undetected. replicated), those the roles may push to or read (every one with `list_topics` or `query`); nodes are those with messages in the topics the roles may read (every one with `list_nodes` or `query`). `truncated` past 65,536. + The filters (`topics`, `nodes`: a name or a pattern each) keep the + topics or nodes of the topic and node pairs they match, out of + `reader.heads()`: the topics a node pushed to, the nodes that pushed to + a topic (a pair counts once it had messages, retention's deletions + included). A pair's topic must be one the roles may see when the + answer is topics or `topics` filters it; its node, when the answer is + nodes or `nodes` filters it (`connection.rs`, `list_names`). So a + node filter doesn't tell a client which nodes pushed to a topic it may + only push to. - **`Query`:** the roles must allow it (`NotAllowed`); read-only SQL, refused with SQLite's message (`QueryFailed`, with a hint to add `is_json = 1` on "malformed JSON"), over 10,000 rows or 16 MB @@ -226,8 +235,8 @@ the same ids with different messages, undetected. `Client::connect(address, settings)` (`host:port`, the CA's certificate, the client's certificate and key, the CRL if any), then `push(topic, -data)`, `get_messages(topic, node, after, limit)`, `list_names(kind)`, -`query(sql)`. Blocking, no runtime. The DLL and the bindings over it: +data)`, `get_messages(topic, node, after, limit)`, `list_names(kind, +topics, nodes)`, `query(sql)`. Blocking, no runtime. The DLL and the bindings over it: `client.md`. Attachments: `push_with_attachment(topic, data, source)`, the source any @@ -332,7 +341,7 @@ each: isn't one line of JSON; - big messages: five of 600 KB and one of the largest size, one per answer, read back whole; one byte over refused; a query result over 16 MB refused; -- names: topics by role, nodes; +- names: topics by role, nodes, filtered by names and patterns; - attachments: 100 KB, 5 MB + 123 bytes, exactly 2 MB, 1 byte, 1 MB, read back and saved; the messages saying theirs; none, or no such message, refused leaving no file; another reader, one not allowed; over the server's limit, 0 for diff --git a/docs/storage.md b/docs/storage.md index 512cd16..966edfa 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -133,9 +133,11 @@ afterwards, `purge_attachments(max_parts)` a batch at a time. ## The query surface -Clients' `Query` runs on `Database::query_runner()`, read-only three ways: -the connection is `query_only`, the statement must be one SQLite says only -reads, and one statement only (more is refused, not ignored). PRAGMAs are +Clients' `Query` runs on `Database::query_runner()`, read-only four ways: +the file is opened read-only (`SQLITE_OPEN_READONLY`, 2026-11-19: the +handle itself can't write), the connection is `query_only`, the statement +must be one SQLite says only reads, and one statement only (more is +refused, not ignored). PRAGMAs are refused as they're prepared ("not authorized", SQLite's authorizer), the `pragma_*` table functions too: some take effect at that point, and `PRAGMA query_only = 0`, though refused, turned `query_only` off for the diff --git a/guides/5-reading.md b/guides/5-reading.md index cb3b5f8..21b4dab 100644 --- a/guides/5-reading.md +++ b/guides/5-reading.md @@ -51,6 +51,21 @@ E:\BakaShrot>bakashrot -c viewer.toml query "SELECT node, message_id, message_da ``` +## Names + +The topics a node pushed to, the nodes that pushed to some topics (a name +or a pattern): +```shell +E:\BakaShrot>bakashrot -c viewer.toml list topics --nodes node-sensor +Topics (1): + sensors + +E:\BakaShrot>bakashrot -c viewer.toml list nodes --topics "sens*" +Nodes (1): + node-sensor +``` + + ## Refused ```shell diff --git a/release.py b/release.py index cd73311..c243f1b 100644 --- a/release.py +++ b/release.py @@ -214,7 +214,7 @@ csharp/BakaShrot.cs for C# (.NET Framework 2.0 and up, .NET Core and .NET; the library next to the app, which runs 64-bit). Or: pip install python/bakashrot-*.whl, the library inside. -Compatibility: protocol 7. Servers and clients must come from the same +Compatibility: protocol 8. Servers and clients must come from the same release: another version's connection is refused. Nothing from the old (PureBasic) BakaShrot is read: not its configs, keys or databases. """ diff --git a/revamp.md b/revamp.md index 173c79e..3aaa6e9 100644 --- a/revamp.md +++ b/revamp.md @@ -157,6 +157,37 @@ Also decided (2026-11-13): both): the topics it may push to or read, the nodes of the topics it may read (every node until then). Names only, reading is still `read_topics`. + - **Filtered lists** (2026-11-19, protocol 8): `ListNames` takes + `topics` and `nodes`, a name or a pattern each (nil for any), and + answers the topics or nodes of the topic and node pairs they match: + the topics a node pushed to, the nodes that pushed to a topic. Out + of the pairs the database has (`reader.heads()`), so replicated + messages count, and so do pairs whose messages retention deleted: + no new storage query. The same permissions as the lists, applied to + what the answer reveals: a pair's topic must be one the roles may + see when the answer is topics or `topics` filters it, its node when + the answer is nodes or `nodes` filters it. Without filters, the + lists as they were. In the DLL one export, `BakaShrot_ListNames` + (`kind`, `topics`, `nodes`); `ListTopics` and `ListNodes` went with + the enumerations (`ListNames(1 or 2, null, null)`). + - **The DLL's lists without JSON** (2026-11-19): the JSON getters are + `GetNamesListAsJson` and `GetQueryResultAsJson`; beside them, + enumerations like Win32's `FindFirstFile` / `FindNextFile` / + `FindClose`: `EnumerateNames` / `EnumerateQuery` keep a whole answer, + `NextName` / `NextQueryRow` move to the next item (before the first + at first), getters read it, `CloseEnum` closes it. They don't outlive + their client (`FreeClient` closes them); their handles are numbered + with the clients'. The query result is parsed in the DLL, the + protocol unchanged. Python keeps the JSON; C# has both (`List...()` + / `Query()` the JSON, `Enumerate...()` an `IEnumerable` over the + enumerations, `QueryRow`s for a query). + - **Queries stay** (2026-11-19): removing them (the `query` permission, + the packets, the runner, every binding) was done and undone the same + day, the owner's second thoughts; a filtered "field equals value" + request instead was weighed and not wanted. A fifth guard against + writes, asked by the owner: the query connection opens the file + read-only (`SQLITE_OPEN_READONLY`), beside `query_only`, the + read-only statement check, one statement only and no PRAGMAs. - **Schema v9, not compatible with v8** (2026-11-13): old databases aren't opened, their data isn't carried over (the real-life tests start empty). `docs/storage.md`: @@ -247,7 +278,8 @@ Also decided (2026-11-13): - **the Python wheel has the library in it**, for a simple install; - **version 0.2.0**; **0.3.0** on 2026-11-16 (the identity OID under NibblePoker's PEN, the roles as the only lists of topics, - `list_topics` / `list_nodes`). + `list_topics` / `list_nodes`); **0.4.0** on 2026-11-19 (protocol 8: + filtered lists; the DLL's enumerations; the C# binding). - **The PureBasic version removed** (2026-11-15): `OldSource/` deleted, kept in git history (up to `68966a8`). What of its notes and designs still holds went to `docs/known-issues.md`; the rest was already @@ -374,6 +406,8 @@ by hand. | 12 | Operations | Signals and a clean stop, logs, release, wheel | Runs unattended, stops cleanly, the release's smoke test | Decided 2026-11-14 | Done 2026-11-14 | | 13 | Finish | One test runner (the Rust tests, decided 2026-11-15), end-to-end tests in CI, the bench, Docker | Push speed with 4 servers replicating (`docs/server.md`, "Measured") | | Done 2026-11-16 (`bench.ps1`) | | 14 | C# binding | `bindings/csharp`: `Client` over the `W` exports, C# 2 and .NET 2.0's library only (net35, netstandard2.0); the NuGet package `NibblePoker.BakaShrot.Client` with the four platforms' libraries, packed by CI after the releases (an artifact) | Its NUnit tests pass on net48 and net8.0 (by hand, not in `test.ps1`); the package loads the library on net8.0 and net48 | Asked by the owner 2026-11-18 (the name too) | Done 2026-11-18 | +| 15 | Filtered lists | `ListNames`' `topics` and `nodes` filters (protocol 8): server, client, `BakaShrot_ListNames` (`A`/`W`), Python, C#, PureBasic, `bakashrot list --topics/--nodes` | `end_to_end.rs` `names` (patterns, case, permissions), `exports.rs`, `check_bakashrot.py`, the NUnit tests | Decided 2026-11-19 | Done 2026-11-19 | +| 16 | The DLL's enumerations | `GetNamesListAsJson`, `GetQueryResultAsJson`; `EnumerateNames` / `EnumerateQuery`, `Next...`, their getters, `CloseEnum` (`enumerations.rs`); `ListTopics` / `ListNodes` dropped; PureBasic's example on them; C#'s `EnumerateTopics` / `EnumerateNodes` / `EnumerateQuery` (`IEnumerable`, asked at each `foreach`) | `exports.rs` `enumerations` (names, query rows and nulls, several at once, bad and closed handles, freed with the client); the NUnit `Enumerations` test | Decided 2026-11-19 | Done 2026-11-19 | 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