mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Added filtered name lists and the DLL's enumerations, Opened the query connection read-only, Bumped to 0.4.0
- Protocol 8: ListTopics / ListNodes became one ListNames [kind, topics, nodes], each filter a name or a pattern: the topics a node pushed to, the nodes that pushed to a topic, wildcards included. No storage change; the permissions are the lists' (may_list_topic, may_list_nodes_of) - The DLL: the JSON getters are suffixed AsJson (GetNamesListAsJson, GetQueryResultAsJson); ListNamesA/W replaces ListTopics / ListNodes. Beside them, Win32-like enumerations: EnumerateNames / EnumerateQuery, NextName / NextQueryRow (before the first item at first), getters, CloseEnum (enumerations.rs). They don't outlive their client: FreeClient closes them - C#: EnumerateTopics / EnumerateNodes / EnumerateQuery as IEnumerable (QueryRow for a query), fetched at each foreach, closed in finally - Queries: the connection opens the file read-only (SQLITE_OPEN_READ_ONLY), a fifth guard beside query_only, the read-only statement check, one statement only and the PRAGMA-denying authorizer; a unit test checks the handle is read-only - Python, PureBasic, the tool, docs, guides and revamp.md (step 16) updated; versions 0.4.0 everywhere Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,365 @@
|
||||
//! Enumerations: a list of names or a query's rows, kept whole, read an
|
||||
//! item at a time like Win32's `FindFirstFile` / `FindNextFile` /
|
||||
//! `FindClose`. `Next...()` first (an enumeration starts before its first
|
||||
//! item), then the getters; `BakaShrot_CloseEnum()` once done, or
|
||||
//! `BakaShrot_FreeClient()` closes its client's.
|
||||
|
||||
use super::{
|
||||
Error, HANDLES, Result, State, Text, Utf8, Utf16, bool_result, call, fetch_names, fetch_query,
|
||||
invalid, lock, text,
|
||||
};
|
||||
use bakashrot_proto::ErrorCode;
|
||||
use std::ffi::c_char;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
|
||||
/// An answer of a client, kept whole.
|
||||
pub(crate) struct Enumeration {
|
||||
pub(crate) client: i64,
|
||||
items: Items,
|
||||
}
|
||||
|
||||
enum Items {
|
||||
Names {
|
||||
names: Cursor<String>,
|
||||
truncated: bool,
|
||||
},
|
||||
Query {
|
||||
columns: Vec<String>,
|
||||
rows: Cursor<Vec<Option<String>>>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Items and where it's at: 0 before the first, `n` on the `n`th, the
|
||||
/// count + 1 past the last.
|
||||
struct Cursor<T> {
|
||||
items: Vec<T>,
|
||||
position: usize,
|
||||
}
|
||||
|
||||
impl<T> Cursor<T> {
|
||||
fn new(items: Vec<T>) -> Cursor<T> {
|
||||
Cursor { items, position: 0 }
|
||||
}
|
||||
|
||||
/// Moves to the next item: whether there was one.
|
||||
fn advance(&mut self) -> bool {
|
||||
self.position = (self.position + 1).min(self.items.len() + 1);
|
||||
self.position <= self.items.len()
|
||||
}
|
||||
|
||||
fn current(&self) -> Option<&T> {
|
||||
self.items.get(self.position.checked_sub(1)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `fetch` on a client, keeps what it gives as an enumeration of that
|
||||
/// client: its handle, 0 if it failed (the client's last error says why).
|
||||
fn enumerate(client: i64, fetch: impl FnOnce(&mut State) -> Result<Items>) -> i64 {
|
||||
call(client, 0, |state| {
|
||||
let items = fetch(state)?;
|
||||
let handles = &mut *lock(&HANDLES);
|
||||
// Freed by another thread during the call: its enumerations went.
|
||||
if !handles.clients.contains_key(&client) {
|
||||
return Err(invalid(format!("client {client} freed during the call")));
|
||||
}
|
||||
let handle = handles.take();
|
||||
handles
|
||||
.enumerations
|
||||
.insert(handle, Enumeration { client, items });
|
||||
Ok(handle)
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads an enumeration: `default` for a bad handle, or `read` giving
|
||||
/// `None` (one of the other kind, no current item, no such column).
|
||||
fn read<R>(handle: i64, default: R, read: impl FnOnce(&mut Items) -> Option<R>) -> R {
|
||||
catch_unwind(AssertUnwindSafe(|| {
|
||||
let handles = &mut *lock(&HANDLES);
|
||||
read(&mut handles.enumerations.get_mut(&handle)?.items)
|
||||
}))
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or(default)
|
||||
}
|
||||
|
||||
/// A column index, as arguments.
|
||||
fn column(index: i32) -> Option<usize> {
|
||||
usize::try_from(index).ok()
|
||||
}
|
||||
|
||||
/// Closes an enumeration: 1, or 0 if it wasn't one.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_CloseEnum(enumeration: i64) -> isize {
|
||||
let closed = catch_unwind(|| lock(&HANDLES).enumerations.remove(&enumeration).is_some());
|
||||
bool_result(closed.unwrap_or(false))
|
||||
}
|
||||
|
||||
// --- Names -------------------------------------------------------------------
|
||||
|
||||
unsafe fn enumerate_names<T: Text>(
|
||||
client: i64,
|
||||
kind: i32,
|
||||
topics: *const T::Unit,
|
||||
nodes: *const T::Unit,
|
||||
) -> i64 {
|
||||
enumerate(client, |state| {
|
||||
let list = unsafe { fetch_names::<T>(state, kind, topics, nodes)? };
|
||||
Ok(Items::Names {
|
||||
names: Cursor::new(list.names),
|
||||
truncated: list.truncated,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Lists names as `BakaShrot_ListNames()` does (the same arguments), into
|
||||
/// an enumeration: its handle, 0 on failure (`BakaShrot_GetLastError(client)`).
|
||||
/// Then `BakaShrot_NextName()` and `BakaShrot_GetEnumName()`, and
|
||||
/// `BakaShrot_CloseEnum()`. Closed with its client by
|
||||
/// `BakaShrot_FreeClient()`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_EnumerateNamesA(
|
||||
client: i64,
|
||||
kind: i32,
|
||||
topics: *const c_char,
|
||||
nodes: *const c_char,
|
||||
) -> i64 {
|
||||
unsafe { enumerate_names::<Utf8>(client, kind, topics.cast(), nodes.cast()) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_EnumerateNamesA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_EnumerateNamesW(
|
||||
client: i64,
|
||||
kind: i32,
|
||||
topics: *const u16,
|
||||
nodes: *const u16,
|
||||
) -> i64 {
|
||||
unsafe { enumerate_names::<Utf16>(client, kind, topics, nodes) }
|
||||
}
|
||||
|
||||
/// Moves to the next name (the first, the first time): 1, 0 if there are
|
||||
/// no more, -1 if it isn't a names enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_NextName(enumeration: i64) -> isize {
|
||||
read(enumeration, -1, |items| match items {
|
||||
Items::Names { names, .. } => Some(bool_result(names.advance())),
|
||||
Items::Query { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn enum_name<T: Text>(enumeration: i64, buffer: *mut T::Unit, size: isize) -> isize {
|
||||
read(enumeration, 0, |items| match items {
|
||||
Items::Names { names, .. } => names
|
||||
.current()
|
||||
.map(|name| unsafe { text::copy::<T>(name, buffer, size) }),
|
||||
Items::Query { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The current name: the bytes it needs, 0 if there's none (before the
|
||||
/// first, past the last) or it isn't a names enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetEnumNameA(
|
||||
enumeration: i64,
|
||||
buffer: *mut c_char,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
unsafe { enum_name::<Utf8>(enumeration, buffer.cast(), size) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetEnumNameA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetEnumNameW(
|
||||
enumeration: i64,
|
||||
buffer: *mut u16,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
unsafe { enum_name::<Utf16>(enumeration, buffer, size) }
|
||||
}
|
||||
|
||||
/// How many names, -1 if it isn't a names enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_GetNameCount(enumeration: i64) -> i32 {
|
||||
read(enumeration, -1, |items| match items {
|
||||
Items::Names { names, .. } => Some(names.items.len() as i32),
|
||||
Items::Query { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether some names didn't fit in the server's answer: 1 or 0, -1 if it
|
||||
/// isn't a names enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_IsNamesListTruncated(enumeration: i64) -> isize {
|
||||
read(enumeration, -1, |items| match items {
|
||||
Items::Names { truncated, .. } => Some(bool_result(*truncated)),
|
||||
Items::Query { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
// --- Queries -----------------------------------------------------------------
|
||||
|
||||
/// The server's `{"columns":[...],"rows":[[...],...]}`, each value a
|
||||
/// string or null.
|
||||
fn parse_query(json: &str) -> Option<Items> {
|
||||
let value: serde_json::Value = serde_json::from_str(json).ok()?;
|
||||
let columns = value
|
||||
.get("columns")?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.map(|column| column.as_str().map(str::to_owned))
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
let rows = value
|
||||
.get("rows")?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.map(|row| {
|
||||
row.as_array()?
|
||||
.iter()
|
||||
.map(|value| match value {
|
||||
serde_json::Value::Null => Some(None),
|
||||
serde_json::Value::String(text) => Some(Some(text.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
Some(Items::Query {
|
||||
columns,
|
||||
rows: Cursor::new(rows),
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn enumerate_query<T: Text>(client: i64, sql: *const T::Unit) -> i64 {
|
||||
enumerate(client, |state| {
|
||||
let json = unsafe { fetch_query::<T>(state, sql)? };
|
||||
parse_query(&json)
|
||||
.ok_or_else(|| Error::new(ErrorCode::Internal, "the server's query result isn't one"))
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs a query as `BakaShrot_Query()` does, into an enumeration: its
|
||||
/// handle, 0 on failure (`BakaShrot_GetLastError(client)`). Then
|
||||
/// `BakaShrot_GetQueryColumnCount()` and `GetQueryColumnName()`,
|
||||
/// `BakaShrot_NextQueryRow()` and `GetQueryValue()` / `IsQueryValueNull()`,
|
||||
/// and `BakaShrot_CloseEnum()`. Closed with its client by
|
||||
/// `BakaShrot_FreeClient()`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_EnumerateQueryA(client: i64, sql: *const c_char) -> i64 {
|
||||
unsafe { enumerate_query::<Utf8>(client, sql.cast()) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_EnumerateQueryA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_EnumerateQueryW(client: i64, sql: *const u16) -> i64 {
|
||||
unsafe { enumerate_query::<Utf16>(client, sql) }
|
||||
}
|
||||
|
||||
/// How many columns, -1 if it isn't a query enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_GetQueryColumnCount(enumeration: i64) -> i32 {
|
||||
read(enumeration, -1, |items| match items {
|
||||
Items::Query { columns, .. } => Some(columns.len() as i32),
|
||||
Items::Names { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn column_name<T: Text>(
|
||||
enumeration: i64,
|
||||
index: i32,
|
||||
buffer: *mut T::Unit,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
read(enumeration, 0, |items| match items {
|
||||
Items::Query { columns, .. } => columns
|
||||
.get(column(index)?)
|
||||
.map(|name| unsafe { text::copy::<T>(name, buffer, size) }),
|
||||
Items::Names { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A column's name (`index` 0 to the count - 1): the bytes it needs, 0 if
|
||||
/// there's no such column or it isn't a query enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetQueryColumnNameA(
|
||||
enumeration: i64,
|
||||
index: i32,
|
||||
buffer: *mut c_char,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
unsafe { column_name::<Utf8>(enumeration, index, buffer.cast(), size) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetQueryColumnNameA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetQueryColumnNameW(
|
||||
enumeration: i64,
|
||||
index: i32,
|
||||
buffer: *mut u16,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
unsafe { column_name::<Utf16>(enumeration, index, buffer, size) }
|
||||
}
|
||||
|
||||
/// Moves to the next row (the first, the first time): 1, 0 if there are
|
||||
/// no more, -1 if it isn't a query enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_NextQueryRow(enumeration: i64) -> isize {
|
||||
read(enumeration, -1, |items| match items {
|
||||
Items::Query { rows, .. } => Some(bool_result(rows.advance())),
|
||||
Items::Names { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The current row's value in a column: `None` without a row or column.
|
||||
fn value(items: &Items, index: i32) -> Option<&Option<String>> {
|
||||
match items {
|
||||
Items::Query { rows, .. } => rows.current()?.get(column(index)?),
|
||||
Items::Names { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn query_value<T: Text>(
|
||||
enumeration: i64,
|
||||
index: i32,
|
||||
buffer: *mut T::Unit,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
read(enumeration, 0, |items| {
|
||||
value(items, index)?
|
||||
.as_deref()
|
||||
.map(|text| unsafe { text::copy::<T>(text, buffer, size) })
|
||||
})
|
||||
}
|
||||
|
||||
/// The current row's value in a column (`index` 0 to the count - 1): the
|
||||
/// bytes it needs, 0 if it's null (`BakaShrot_IsQueryValueNull()`), there's
|
||||
/// no current row or such column, or it isn't a query enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetQueryValueA(
|
||||
enumeration: i64,
|
||||
index: i32,
|
||||
buffer: *mut c_char,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
unsafe { query_value::<Utf8>(enumeration, index, buffer.cast(), size) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetQueryValueA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetQueryValueW(
|
||||
enumeration: i64,
|
||||
index: i32,
|
||||
buffer: *mut u16,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
unsafe { query_value::<Utf16>(enumeration, index, buffer, size) }
|
||||
}
|
||||
|
||||
/// Whether the current row's value in a column is null: 1 or 0, -1 if
|
||||
/// there's no current row or such column, or it isn't a query enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_IsQueryValueNull(enumeration: i64, index: i32) -> isize {
|
||||
read(enumeration, -1, |items| {
|
||||
value(items, index).map(|value| bool_result(value.is_none()))
|
||||
})
|
||||
}
|
||||
@@ -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<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// 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<i64, Shared>)> = Mutex::new((1, BTreeMap::new()));
|
||||
static HANDLES: Mutex<Handles> = 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<i64, Shared>,
|
||||
/// Freed with their client. Only ever copied from, under this lock.
|
||||
enumerations: BTreeMap<i64, enumerations::Enumeration>,
|
||||
}
|
||||
|
||||
impl Handles {
|
||||
fn take(&mut self) -> i64 {
|
||||
self.next += 1;
|
||||
self.next - 1
|
||||
}
|
||||
}
|
||||
|
||||
type Shared = Arc<Mutex<State>>;
|
||||
|
||||
@@ -66,7 +92,7 @@ struct State {
|
||||
messages: Vec<MessageEntry>,
|
||||
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<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
}
|
||||
|
||||
fn find(client: i64) -> Option<Shared> {
|
||||
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<String>) -> Error {
|
||||
Error::new(ErrorCode::InvalidArgument, why)
|
||||
}
|
||||
|
||||
fn required(value: Option<String>, what: &str) -> Result<String> {
|
||||
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<T: Text>(pointer: *const T::Unit, what: &str) -> Result<String> {
|
||||
unsafe { text::read::<T>(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<T: Text>(
|
||||
slot: fn(&mut State) -> &mut Option<String>,
|
||||
) -> 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::<T>(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<T: Text>(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::<T>(host, "host")? }, "host")?;
|
||||
not_connected(state)?;
|
||||
let host = unsafe { required::<T>(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::<Utf8>(client, buffer.cast(), size, |state| {
|
||||
state.client.as_ref().map_or("", Client::node)
|
||||
})
|
||||
}
|
||||
unsafe { get_text::<Utf8>(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::<Utf16>(client, buffer, size, |state| {
|
||||
state.client.as_ref().map_or("", Client::node)
|
||||
})
|
||||
}
|
||||
unsafe { get_text::<Utf16>(client, buffer, size, node) }
|
||||
}
|
||||
|
||||
// --- Pushing -----------------------------------------------------------------
|
||||
@@ -499,7 +533,7 @@ unsafe fn topic_and_data<T: Text>(
|
||||
topic: *const T::Unit,
|
||||
data: *const T::Unit,
|
||||
) -> Result<(String, String)> {
|
||||
let topic = required(unsafe { text::read::<T>(topic, "topic")? }, "topic")?;
|
||||
let topic = unsafe { required::<T>(topic, "topic")? };
|
||||
let data = unsafe { text::read::<T>(data, "the message")? }.unwrap_or_default();
|
||||
Ok((topic, data))
|
||||
}
|
||||
@@ -541,8 +575,8 @@ unsafe fn topic_and_node<T: Text>(
|
||||
topic: *const T::Unit,
|
||||
node: *const T::Unit,
|
||||
) -> Result<(String, String)> {
|
||||
let topic = required(unsafe { text::read::<T>(topic, "topic")? }, "topic")?;
|
||||
let node = required(unsafe { text::read::<T>(node, "node")? }, "node")?;
|
||||
let topic = unsafe { required::<T>(topic, "topic")? };
|
||||
let node = unsafe { required::<T>(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<T: Text>(
|
||||
state: &mut State,
|
||||
kind: i32,
|
||||
topics: *const T::Unit,
|
||||
nodes: *const T::Unit,
|
||||
) -> Result<NamesList> {
|
||||
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::<T>(topics, "topics")? };
|
||||
let nodes = unsafe { text::read::<T>(nodes, "nodes")? };
|
||||
state
|
||||
.client()?
|
||||
.list_names(kind, topics.as_deref(), nodes.as_deref())
|
||||
}
|
||||
|
||||
unsafe fn list<T: Text>(
|
||||
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::<T>(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::<Utf8>(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::<Utf16>(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::<Utf8>(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<T: Text>(state: &mut State, sql: *const T::Unit) -> Result<String> {
|
||||
let sql = unsafe { required::<T>(sql, "query")? };
|
||||
state.client()?.query(&sql)
|
||||
}
|
||||
|
||||
unsafe fn query<T: Text>(client: i64, sql: *const T::Unit) -> isize {
|
||||
call(client, 0, |state| {
|
||||
state.query.clear();
|
||||
let sql = required(unsafe { text::read::<T>(sql, "query")? }, "query")?;
|
||||
state.query = state.client()?.query(&sql)?;
|
||||
state.query = unsafe { fetch_query::<T>(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::<Utf8>(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::<Utf8>(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<T: Text>(
|
||||
) -> i64 {
|
||||
call(client, -1, |state| {
|
||||
let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? };
|
||||
let path = required(unsafe { text::read::<T>(path, "the file")? }, "file")?;
|
||||
let path = unsafe { required::<T>(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<T: Text>(
|
||||
) -> i64 {
|
||||
call(client, -1, |state| {
|
||||
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
|
||||
let path = required(unsafe { text::read::<T>(path, "the file")? }, "file")?;
|
||||
let path = unsafe { required::<T>(path, "file")? };
|
||||
let size =
|
||||
state
|
||||
.client()?
|
||||
|
||||
@@ -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<String> {
|
||||
let mut names = Vec::new();
|
||||
while BakaShrot_NextName(enumeration) == 1 {
|
||||
names.push(get_w(enumeration, BakaShrot_GetEnumNameW));
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enumerations() {
|
||||
let running = common::Running::start("enumerations");
|
||||
running.issue("kitchen", &["home"]);
|
||||
let client = connected(&running, "kitchen");
|
||||
let null = std::ptr::null();
|
||||
unsafe {
|
||||
for (topic, data) in [("logs", "{}"), ("secret", "{}"), ("logs", "{}")] {
|
||||
assert!(BakaShrot_PushMessageToW(client, w(topic).as_ptr(), w(data).as_ptr()) > 0);
|
||||
}
|
||||
|
||||
// Names: before the first at first, then each, then no more.
|
||||
let topics = BakaShrot_EnumerateNamesW(client, 1, null, w("kitchen").as_ptr());
|
||||
assert!(topics > client, "numbered with the clients");
|
||||
assert_eq!(BakaShrot_GetNameCount(topics), 2);
|
||||
assert_eq!(BakaShrot_IsNamesListTruncated(topics), 0);
|
||||
assert_eq!(
|
||||
get_w(topics, BakaShrot_GetEnumNameW),
|
||||
"",
|
||||
"before the first"
|
||||
);
|
||||
assert_eq!(names_of(topics), ["logs", "secret"]);
|
||||
assert_eq!(BakaShrot_NextName(topics), 0, "still none");
|
||||
assert_eq!(get_w(topics, BakaShrot_GetEnumNameW), "");
|
||||
// Several at once, each its own; the client's calls don't change them.
|
||||
let nodes = BakaShrot_EnumerateNamesA(client, 2, a("s*").as_ptr(), null.cast());
|
||||
let none = BakaShrot_EnumerateNamesW(client, 2, w("nothing").as_ptr(), null);
|
||||
assert_eq!(BakaShrot_ListNamesW(client, 1, null, null), 2);
|
||||
assert_eq!(names_of(nodes), ["kitchen"]);
|
||||
assert_eq!(BakaShrot_GetNameCount(none), 0);
|
||||
assert_eq!(BakaShrot_NextName(none), 0);
|
||||
// A failure: 0, the client's error.
|
||||
assert_eq!(BakaShrot_EnumerateNamesW(client, 3, null, null), 0);
|
||||
assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
|
||||
|
||||
// Queries: columns, rows, nulls.
|
||||
let sql = w(
|
||||
"SELECT topic, CASE WHEN message_id = 1 THEN NULL ELSE message_id END AS id \
|
||||
FROM messages ORDER BY topic, message_id",
|
||||
);
|
||||
let query = BakaShrot_EnumerateQueryW(client, sql.as_ptr());
|
||||
assert!(query > 0, "{:?}", error(client));
|
||||
assert_eq!(BakaShrot_GetQueryColumnCount(query), 2);
|
||||
assert_eq!(get_at(query, 0, BakaShrot_GetQueryColumnNameW), "topic");
|
||||
assert_eq!(get_at(query, 1, BakaShrot_GetQueryColumnNameW), "id");
|
||||
assert_eq!(get_at(query, 2, BakaShrot_GetQueryColumnNameW), "");
|
||||
assert_eq!(BakaShrot_IsQueryValueNull(query, 0), -1, "no row yet");
|
||||
let mut rows = Vec::new();
|
||||
while BakaShrot_NextQueryRow(query) == 1 {
|
||||
let id = match BakaShrot_IsQueryValueNull(query, 1) {
|
||||
1 => None,
|
||||
0 => Some(get_at(query, 1, BakaShrot_GetQueryValueW)),
|
||||
other => panic!("{other}"),
|
||||
};
|
||||
rows.push((get_at(query, 0, BakaShrot_GetQueryValueW), id));
|
||||
}
|
||||
let row = |topic: &str, id: Option<&str>| (topic.to_owned(), id.map(str::to_owned));
|
||||
assert_eq!(
|
||||
rows,
|
||||
[
|
||||
row("logs", None),
|
||||
row("logs", Some("2")),
|
||||
row("secret", None)
|
||||
]
|
||||
);
|
||||
assert_eq!(BakaShrot_IsQueryValueNull(query, 0), -1, "past the last");
|
||||
assert_eq!(
|
||||
BakaShrot_EnumerateQueryW(client, w("SELECT nope").as_ptr()),
|
||||
0
|
||||
);
|
||||
assert_eq!(error(client).0, code(ErrorCode::QueryFailed));
|
||||
|
||||
// Of the other kind, a client's, made up: refused, never a crash.
|
||||
assert_eq!(BakaShrot_NextName(query), -1);
|
||||
assert_eq!(BakaShrot_NextQueryRow(nodes), -1);
|
||||
assert_eq!(BakaShrot_GetQueryColumnCount(nodes), -1);
|
||||
assert_eq!(BakaShrot_NextName(client), -1);
|
||||
assert_eq!(BakaShrot_NextName(99_999), -1);
|
||||
assert_eq!(get_w(99_999, BakaShrot_GetEnumNameW), "");
|
||||
assert_eq!(BakaShrot_CloseEnum(client), 0, "a client isn't one");
|
||||
assert_eq!(BakaShrot_FreeClient(topics), 0, "nor the other way");
|
||||
|
||||
// Closed: refused after. Its client freed: all of its closed.
|
||||
assert_eq!(BakaShrot_CloseEnum(topics), 1);
|
||||
assert_eq!(BakaShrot_CloseEnum(topics), 0);
|
||||
assert_eq!(BakaShrot_GetNameCount(topics), -1);
|
||||
assert_eq!(BakaShrot_FreeClient(client), 1);
|
||||
for enumeration in [nodes, none, query] {
|
||||
assert_eq!(BakaShrot_CloseEnum(enumeration), 0, "{enumeration}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user