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

Stopped long queries, Read is_open() through TLS, Simplified answers and paging

- [server] query_time_limit (20 s by default) stops a client's query
  through SQLite's progress handler: refused with QueryTimedOut (11). A
  client closing while its query runs stops it too.
- The answer timeout in the DLL (BakaShrot_SetAnswerTimeout /
  GetAnswerTimeout, kept across connections), Python (answer_timeout)
  and C# (AnswerTimeoutMs); QueryTimedOut in every binding.
- is_open() reads what's waiting through TLS: a close_notify says
  closed, TLS's own records keep it open, unasked data or a broken
  stream close it.
- The Rust client checks an answer's type in one place (TryFrom per
  packet); Client::wait() pings while waiting (the tool's --follow).
- Pair::from(&Head), heads_after taking a Pair; simpler SyncState
  paging on both ends; the writer's redundant rollback check dropped.
- codes.rs: the bindings' error codes and copied values match Rust's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 12:17:28 +01:00
parent a6ade535d0
commit 1bae8ee182
37 changed files with 1064 additions and 264 deletions
+45 -11
View File
@@ -36,7 +36,7 @@ mod enumerations;
pub use enumerations::*;
mod text;
use bakashrot_client::{Client, Error, Settings};
use bakashrot_client::{ANSWER_TIMEOUT, Client, Error, Settings};
use bakashrot_proto::ErrorCode;
use bakashrot_proto::packets::{MessageEntry, NameKind, NamesList};
use std::collections::BTreeMap;
@@ -46,6 +46,7 @@ use std::io::Cursor;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::path::Path;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use text::{Text, Utf8, Utf16};
type Result<T> = std::result::Result<T, Error>;
@@ -81,6 +82,8 @@ struct State {
certificate: Option<String>,
key: Option<String>,
crl: Option<String>,
/// Given to each connection, and to the current one when set.
answer_timeout: Duration,
client: Option<Client>,
/// The last call's error code, 0 if it succeeded.
last_error: u32,
@@ -107,6 +110,7 @@ impl State {
certificate: None,
key: None,
crl: None,
answer_timeout: ANSWER_TIMEOUT,
client: None,
last_error: 0,
reason: String::new(),
@@ -124,14 +128,10 @@ impl State {
fn fail(&mut self, error: Error) {
self.last_error = error.code();
self.reason = error.message().to_owned();
// The client closes its connection on those, and on others that
// leave it out of step (a file failing mid-upload): forgotten then,
// so connecting again works.
let closed = [ErrorCode::ConnectionLost, ErrorCode::ProtocolError]
.iter()
.any(|code| code.code() == error.code())
|| self.client.as_ref().is_some_and(Client::is_closed);
if closed {
// The client closes its connection on every failure that leaves it
// out of step (`ConnectionLost`, `ProtocolError`, a file failing
// mid-upload): forgotten then, so connecting again works.
if self.client.as_ref().is_some_and(Client::is_closed) {
self.client = None;
}
}
@@ -465,7 +465,8 @@ unsafe fn connect<T: Text>(client: i64, host: *const T::Unit, port: i32) -> isiz
true => format!("[{host}]:{port}"),
false => format!("{host}:{port}"),
};
let client = Client::connect(&address, &settings)?;
let mut client = Client::connect(&address, &settings)?;
client.set_answer_timeout(state.answer_timeout)?;
state.client = Some(client);
Ok(1)
})
@@ -492,7 +493,7 @@ pub unsafe extern "C" fn BakaShrot_ConnectW(client: i64, host: *const u16, port:
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_IsConnected(client: i64) -> isize {
get(client, 0, |state| {
let open = state.client.as_ref().is_some_and(Client::is_open);
let open = state.client.as_mut().is_some_and(Client::is_open);
if !open {
state.client = None;
}
@@ -520,6 +521,39 @@ pub extern "C" fn BakaShrot_Ping(client: i64) -> isize {
})
}
/// Sets how long an answer may take, in milliseconds (more than 0; 30000
/// until changed): longer for a slow query, say. Past it, the request
/// fails with `ConnectionLost`, the connection closed (the server then
/// stops the query it was running). Kept for the next connections, and
/// applied to the current one: 1, or 0 if refused.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_SetAnswerTimeout(client: i64, milliseconds: i64) -> isize {
call(client, 0, |state| {
let timeout = u64::try_from(milliseconds)
.ok()
.filter(|ms| *ms > 0)
.map(Duration::from_millis)
.ok_or_else(|| {
invalid(format!(
"an answer timeout of {milliseconds} ms: more than 0"
))
})?;
if let Some(connected) = state.client.as_mut() {
connected.set_answer_timeout(timeout)?;
}
state.answer_timeout = timeout;
Ok(1)
})
}
/// How long an answer may take, in milliseconds (`BakaShrot_SetAnswerTimeout()`).
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_GetAnswerTimeout(client: i64) -> i64 {
get(client, -1, |state| {
i64::try_from(state.answer_timeout.as_millis()).unwrap_or(i64::MAX)
})
}
fn node(state: &State) -> &str {
state.client.as_ref().map_or("", Client::node)
}
+133
View File
@@ -0,0 +1,133 @@
//! The bindings' error codes are the protocol's, every one, by the same
//! numbers: Python's `ErrorCode`, C#'s `ErrorCode`, PureBasic's constants.
//! And the values they copy are the Rust side's.
use bakashrot_client::ANSWER_TIMEOUT;
use bakashrot_proto::ErrorCode;
use bakashrot_proto::limits::{KEEPALIVE_SECS, MAX_MESSAGES_PER_PACKET};
use std::collections::BTreeMap;
use std::path::PathBuf;
fn binding(path: &str) -> String {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../bindings")
.join(path);
std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{}: {error}", path.display()))
}
/// The protocol's codes, by number: their names as `name` writes them.
fn expected(name: impl Fn(ErrorCode) -> String) -> BTreeMap<u32, String> {
ErrorCode::ALL
.iter()
.map(|&code| (code.code(), name(code)))
.collect()
}
/// `NotFound` as `NOT_FOUND`.
fn upper_snake(name: &str) -> String {
let mut snake = String::new();
for (at, c) in name.char_indices() {
if c.is_ascii_uppercase() && at > 0 {
snake.push('_');
}
snake.push(c.to_ascii_uppercase());
}
snake
}
/// `NAME = 12` in `text`, one per line or comma: the names and numbers.
fn assignments<'a>(text: impl Iterator<Item = &'a str>) -> BTreeMap<u32, String> {
let mut found = BTreeMap::new();
for item in text.flat_map(|line| line.split(',')) {
// Comments: PureBasic's `;`, Python's ` #` (PureBasic's constants
// start with `#`).
let item = item.split(';').next().unwrap_or("");
let item = item.split(" #").next().unwrap_or("").trim();
let Some((name, number)) = item.split_once('=') else {
continue;
};
let Ok(number) = number.trim().parse::<u32>() else {
continue;
};
let before = found.insert(number, name.trim().to_owned());
assert!(before.is_none(), "{number} twice: {before:?}, {name}");
}
found
}
/// The lines of `text` from the one starting with `start` to the next
/// starting with `end`.
fn section<'a>(text: &'a str, start: &str, end: &str) -> impl Iterator<Item = &'a str> {
text.lines()
.skip_while(move |line| !line.trim_start().starts_with(start))
.skip(1)
.take_while(move |line| !line.trim_start().starts_with(end))
}
/// The number `name` is set to in `text`: `NAME = 12`, a `;` after or not.
fn number(text: &str, name: &str) -> f64 {
let set = format!("{name} = ");
let line = text.lines().find(|line| line.contains(&set));
let line = line.unwrap_or_else(|| panic!("no {set}"));
let value = line.split(&set).nth(1).unwrap_or("");
let value = value.trim().trim_end_matches(';');
value.parse().unwrap_or_else(|_| panic!("{set}{value}"))
}
#[test]
fn copied_values() {
let python = binding("python/bakashrot.py");
let csharp = binding("csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs");
let answer = ANSWER_TIMEOUT.as_secs_f64();
let keepalive = KEEPALIVE_SECS as f64;
assert_eq!(number(&python, "ANSWER_TIMEOUT_SECONDS"), answer);
assert_eq!(number(&python, "KEEPALIVE_SECONDS"), keepalive);
assert_eq!(
number(&python, "MAX_GET_MESSAGES"),
f64::from(MAX_MESSAGES_PER_PACKET)
);
assert_eq!(number(&csharp, "DefaultAnswerTimeoutMs"), answer * 1000.0);
assert_eq!(number(&csharp, "KeepAliveMs"), keepalive * 1000.0);
}
#[test]
fn python() {
let text = binding("python/bakashrot.py");
let found = assignments(section(&text, "class ErrorCode", "@property"));
let mut expected = expected(|code| upper_snake(code.name()));
expected.insert(0, "NONE".into());
assert_eq!(found, expected);
}
#[test]
fn csharp() {
let text = binding("csharp/NibblePoker.BakaShrot.Client/BakaShrot.cs");
let found = assignments(section(&text, "public enum ErrorCode", "}"));
let mut expected = expected(|code| code.name().to_owned());
expected.insert(0, "None".into());
assert_eq!(found, expected);
}
#[test]
fn purebasic() {
let text = binding("purebasic/BakaShrot_ErrorCodes.pbi");
let constants = text
.lines()
.filter(|line| line.starts_with("#BakaShrot_") && !line.contains("_Max"));
let found = assignments(constants);
let mut expected = expected(|code| {
let kind = if code.is_refusal() {
"Refused"
} else {
"Error"
};
format!("#BakaShrot_{kind}_{}", code.name())
});
expected.insert(0, "#BakaShrot_Error_None".into());
assert_eq!(found, expected);
// Each named by BakaShrot_ErrorName().
for code in ErrorCode::ALL {
let case = format!("ProcedureReturn \"{}\"", code.name());
assert!(text.contains(&case), "BakaShrot_ErrorName() lacks {code}");
}
}
+41
View File
@@ -434,6 +434,45 @@ fn exports() {
assert_eq!(BakaShrot_FreeClient(client), 1);
}
/// The answer timeout: set before connecting or while connected, kept
/// across connections; past it, `ConnectionLost` and the connection closed.
#[test]
fn answer_timeouts() {
let running = common::Running::start("answer-timeouts");
running.issue("kitchen", &["home"]);
let client = BakaShrot_CreateClient();
assert_eq!(BakaShrot_GetAnswerTimeout(client), 30_000);
for refused in [0, -1, i64::MIN] {
assert_eq!(BakaShrot_SetAnswerTimeout(client, refused), 0);
assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
}
assert_eq!(BakaShrot_SetAnswerTimeout(client, 60_000), 1);
assert_eq!(BakaShrot_FreeClient(client), 1);
let client = connected(&running, "kitchen");
assert_eq!(BakaShrot_SetAnswerTimeout(client, 300), 1);
assert_eq!(BakaShrot_GetAnswerTimeout(client), 300);
let forever =
a("WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n");
let started = std::time::Instant::now();
unsafe {
assert_eq!(BakaShrot_QueryA(client, forever.as_ptr()), 0);
assert_eq!(error(client).0, code(ErrorCode::ConnectionLost));
assert!(started.elapsed() < std::time::Duration::from_secs(5));
assert_eq!(BakaShrot_IsConnected(client), 0);
// Connected again: the timeout kept.
let host = a("127.0.0.1");
assert_eq!(
BakaShrot_ConnectA(client, host.as_ptr(), i32::from(running.port)),
1
);
assert_eq!(BakaShrot_GetAnswerTimeout(client), 300);
assert_eq!(BakaShrot_QueryA(client, forever.as_ptr()), 0);
assert_eq!(error(client).0, code(ErrorCode::ConnectionLost));
}
assert_eq!(BakaShrot_FreeClient(client), 1);
}
/// A new client, connected as `name` (its certificate and key in files).
fn connected(running: &common::Running, name: &str) -> i64 {
let client = BakaShrot_CreateClient();
@@ -476,6 +515,8 @@ fn clients() {
assert!(why.contains("no client 99"), "{why}");
assert_eq!(BakaShrot_IsConnected(99), 0);
assert_eq!(BakaShrot_Ping(99), 0);
assert_eq!(BakaShrot_SetAnswerTimeout(99, 1000), 0);
assert_eq!(BakaShrot_GetAnswerTimeout(99), -1);
assert_eq!(BakaShrot_GetMessageId(-5), 0);
assert_eq!(get_w(99, BakaShrot_GetMessageDataW), "");
assert_eq!(BakaShrot_FreeClient(99), 0);