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

Fixed two peers sending the same attachment at once, Noted the stream limits, Removed the PureBasic-era leftovers

- An attachment is received from one peer at a time: the others are
  refused NotReady and ask again at their next sync; one cut short lets
  the next one take it over
- A 'replicating' row with all its bytes but never checked is asked
  again from part 0, and a peer asking from the wrong part resets it
- Noted the stream limit (1,048,575 topic/node pairs, 2^43-1 message ids
  each) in the example config and known-issues.md
- Removed NoDefaultTopic (code 6, retired), Writer::vacuum, the v8
  detection and the old ini key tests
- Cleared the PureBasic-era notes from the docs, revamp.md keeping only
  the old open items still unfixed; noted the GUI explorer (egui)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 17:23:33 +01:00
parent 764bc3652a
commit a5a2f65442
38 changed files with 436 additions and 907 deletions
-12
View File
@@ -36,18 +36,6 @@ impl Writer {
batch.transaction.commit()?;
Ok(value)
}
/// Gives the space of deleted messages back to the disk: rewrites the
/// database (`VACUUM`), then empties the WAL. SQLite reuses that space
/// by itself; this only shrinks the file. Slow on a big database, and
/// every other write waits meanwhile: the old server's `vacuum`
/// command.
pub fn vacuum(&mut self) -> Result<()> {
self.connection.execute_batch("VACUUM")?;
self.connection
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))?;
Ok(())
}
}
/// What's written in one transaction ([`Writer::batch`]). Names come
+5 -20
View File
@@ -28,8 +28,7 @@ const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
pub const WRITER_CHECKPOINT_PAGES: u32 = 10_000;
/// Copies the WAL into the database on a connection of its own, so the
/// writer doesn't do it in the middle of a commit (the old server's way:
/// `OldSource/Server/Storage/Writer.pbi`).
/// writer doesn't do it in the middle of a commit.
#[derive(Debug)]
pub struct Checkpointer {
connection: Connection,
@@ -74,7 +73,10 @@ impl Database {
[concat!("bakashrot-storage ", env!("CARGO_PKG_VERSION"))],
)?;
} else if application_id != APPLICATION_ID {
return Err(Error::Unusable(unusable(&transaction, path)?));
return Err(Error::Unusable(format!(
"{}: not a BakaShrot database",
path.display()
)));
}
let mut version = schema_version(&transaction)?;
if version > SCHEMA_VERSION {
@@ -184,20 +186,3 @@ fn schema_version(connection: &Connection) -> Result<i64> {
};
version.ok_or_else(|| Error::Unusable("a BakaShrot database without its schema version".into()))
}
/// Why a database that isn't ours can't be opened, in words.
fn unusable(connection: &Connection, path: &Path) -> Result<String> {
let old: bool = connection.query_row(
"SELECT count(*) > 0 FROM sqlite_schema WHERE type = 'table' AND name = 'node_heads'",
[],
|row| row.get(0),
)?;
Ok(if old {
format!(
"{}: made by the old server (schema v8), which this one doesn't read: start a new database",
path.display()
)
} else {
format!("{}: not a BakaShrot database", path.display())
})
}
+1 -2
View File
@@ -4,8 +4,7 @@
//! and hands out connections.
//! - [`Writer`]: the one connection that writes. Everything is written in
//! a [`Batch`], one transaction: pushes, replication, attachments,
//! retention. Many pushes in one batch is a group commit. And
//! [`Writer::vacuum`], to shrink the file.
//! retention. Many pushes in one batch is a group commit.
//! - [`Reader`]: as many as needed, reading while the writer writes (WAL).
//! - [`QueryRunner`]: clients' read-only SQL, on a read-only connection.
//!
+4 -4
View File
@@ -1,4 +1,4 @@
//! Clients' read-only SQL (`Query`), as the old server ran it.
//! 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
@@ -6,8 +6,8 @@
//! error, not ignored). PRAGMAs are refused as they're prepared
//! (`Database::query_runner`'s authorizer): some would change the
//! connection, `query_only` included, before the statement is looked
//! at. The result is JSON, every value a string or null
//! (as in protocol 6): `{"columns":[...],"rows":[[...],...]}`.
//! at. The result is JSON, every value a string or null:
//! `{"columns":[...],"rows":[[...],...]}`.
use crate::{Error, Result};
use bakashrot_proto::limits::MAX_MESSAGE_SIZE;
@@ -77,7 +77,7 @@ impl QueryRunner {
}
}
/// SQLite's error, with a hint where the old server gave one.
/// SQLite's error, with a hint where one helps.
fn explain(why: String) -> String {
if why.contains("malformed JSON") {
format!("{why} (a row isn't JSON: add is_json = 1 to the WHERE)")
+8 -2
View File
@@ -190,17 +190,23 @@ impl Reader {
pub fn missing_attachments(&self, limit: usize) -> Result<Vec<MissingAttachment>> {
self.connection
.prepare_cached(
"SELECT s.topic, s.node, d.message_id, a.received FROM attachments a \
"SELECT s.topic, s.node, d.message_id, a.received, a.size FROM attachments a \
JOIN data d ON d.key = a.message_key \
JOIN streams s ON s.stream_id = d.stream_id \
WHERE a.state = 'replicating' ORDER BY a.attachment_id LIMIT ?1",
)?
.query_map([limit as i64], |row| {
let (received, size): (u64, u64) = (row.get(3)?, row.get(4)?);
Ok(MissingAttachment {
topic: row.get(0)?,
node: row.get(1)?,
message_id: row.get(2)?,
next_part: row.get::<_, u64>(3)? / ATTACHMENT_PART_SIZE,
// Whole but not checked: it starts over from the first.
next_part: if received == size {
0
} else {
received / ATTACHMENT_PART_SIZE
},
})
})?
.collect::<rusqlite::Result<_>>()
+1 -3
View File
@@ -2,8 +2,6 @@
-- keys below are packed integers, on purpose, and only bakashrot-storage
-- packs and unpacks them.
--
-- Not compatible with v8 (OldSource/Server/Storage/db_schema_v8.dbml): a
-- database of the old server isn't opened, its data isn't carried over.
-- Needs SQLite 3.38+ (JSON functions, ->>), bundled with the crate.
--
-- Run once, in one transaction, on an empty database (Database::open).
@@ -128,7 +126,7 @@ FROM streams s
JOIN data d ON d.key BETWEEN (s.stream_id << 43) AND (s.stream_id << 43) + 8796093022207
LEFT JOIN attachments a ON a.message_key = d.key;
-- What to browse with a database tool (v8's): set topic, and node or NULL
-- What to browse with a database tool: set topic, and node or NULL
-- for all, in its one row, open browse_messages. Never written by the
-- server.
CREATE TABLE browse (
+5 -40
View File
@@ -84,10 +84,6 @@ fn refused_databases() {
}
};
refused("CREATE TABLE other (x);", "not a BakaShrot database");
refused(
"CREATE TABLE data (x); CREATE TABLE node_heads (y);",
"made by the old server (schema v8)",
);
refused(
"PRAGMA application_id = 1112754260; CREATE TABLE x (y);",
"without its schema version",
@@ -580,36 +576,6 @@ fn retention() {
));
}
#[test]
fn vacuum() {
let (database, path) = open("vacuum");
let mut writer = database.writer().unwrap();
let big = "x".repeat(10_000);
writer
.batch(|b| {
for _ in 0..1000 {
b.push("logs", "kitchen", 1, &big)?;
}
Ok(())
})
.unwrap();
writer.vacuum().unwrap();
let full = std::fs::metadata(&path).unwrap().len();
writer
.batch(|b| b.delete_before("logs", u64::MAX, 10_000))
.unwrap();
writer.vacuum().unwrap();
let emptied = std::fs::metadata(&path).unwrap().len();
assert!(emptied * 10 < full, "{full} -> {emptied}");
// Still the same database: ids go on.
assert_eq!(
writer
.batch(|b| b.push("logs", "kitchen", 2, "{}"))
.unwrap(),
1001
);
}
#[test]
fn limits() {
let (database, path) = open("limits");
@@ -829,8 +795,7 @@ fn readers_while_writing() {
assert_eq!(reader.last_id("logs", "garage").unwrap(), 2000);
}
/// The same workload as the old storage's benchmark
/// (`OldSource\Build\Bench\StorageBenchOld.exe`), to compare them: pushes
/// The storage alone, flat out (`docs/storage.md`, "The benchmark"): pushes
/// over 100 topics x 5 nodes (an LCG picks them), 100 per batch, 200-byte
/// JSON; 2000 latest-message reads, 500 reads of 1000 messages after the
/// middle id, the file's size, retention of 10% of one topic. Not run by
@@ -838,7 +803,7 @@ fn readers_while_writing() {
/// bakashrot-storage -- --ignored --nocapture`.
#[test]
#[ignore]
fn compare_with_old() {
fn storage_rate() {
use std::time::Instant;
let count: u64 = std::env::var("PUSHES").map_or(1_000_000, |n| n.parse().unwrap());
let sync = std::env::var("SYNC").unwrap_or_else(|_| "normal".into());
@@ -847,7 +812,7 @@ fn compare_with_old() {
} else {
Synchronous::Normal
};
let path = path("compare");
let path = path("rate");
let database = Database::open(&path, synchronous).unwrap();
let mut writer = database.writer().unwrap();
@@ -858,7 +823,7 @@ fn compare_with_old() {
let nodes: Vec<String> = (0..5).map(|n| format!("node{n}")).collect();
// Checkpoints every second on their own connection, as the server's
// (and the old server's) thread does.
// thread does.
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let checkpoints = {
let checkpointer = database.checkpointer().unwrap();
@@ -932,7 +897,7 @@ fn compare_with_old() {
let retention = start.elapsed().as_secs_f64() * 1000.0;
println!(
"new {sync}: {count} pushes in {pushing:.1} s = {:.0}/s | file {:.0} MB | latest {latest:.3} ms | 1000 after {after:.3} ms ({read} read) | retention {deleted} in {retention:.0} ms",
"{sync}: {count} pushes in {pushing:.1} s = {:.0}/s | file {:.0} MB | latest {latest:.3} ms | 1000 after {after:.3} ms ({read} read) | retention {deleted} in {retention:.0} ms",
count as f64 / pushing,
size as f64 / 1e6
);