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
+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);