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

Moved the PureBasic version to OldSource/, Started the Rust rewrite in Source/

The rewrite's plan and decisions are in revamp.md. Steps 0 to 10 are done:
the workspace and checks, bakashrot-proto, bakashrot-pki and
bakashrot-cert, bakashrot-config, bakashrot-storage (schema v9), the
server and the client library (every request but replication's,
attachments and retention included), the C DLL with its C, PureBasic and
Python bindings, and the bakashrot tool. Step 11 (replication) is next.

OldSource/ is the old implementation, kept building and passing as the
reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVTGs2SsufaH6zquzcb
This commit is contained in:
2026-11-14 12:47:40 +01:00
parent d0048b17c8
commit e044fcf359
225 changed files with 21849 additions and 123 deletions
@@ -0,0 +1,28 @@
[package]
name = "bakashrot-storage"
description = "BakaShrot's database: SQLite, schema v9, messages by stream, attachments, read-only queries."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
# The limits (message ids, attachment parts).
bakashrot-proto = { path = "../bakashrot-proto" }
# Synchronous, as the config says it.
bakashrot-config = { path = "../bakashrot-config" }
# SQLite itself compiled in (`bundled`): the same version everywhere, with
# its JSON functions, no system library to install. `fallible_uint`: u64
# in and out, an error past i64::MAX instead of a wrap.
rusqlite = { version = "0.42.0", features = ["bundled", "fallible_uint"] }
# Query results as JSON.
serde_json = "1.0.154"
[lints]
workspace = true
[dev-dependencies]
serde_json = "1.0.154"
@@ -0,0 +1,394 @@
//! Writing: the writer's connection, and what a batch (one transaction)
//! does.
use crate::{
AttachmentState, Error, MAX_STREAMS, Result, find_stream, message_key, part_key, part_keys,
stream_keys,
};
use bakashrot_proto::limits::{
ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, attachment_part_len,
};
use bakashrot_proto::packets::ReplicatedMessage;
use rusqlite::{Connection, OptionalExtension, Transaction, TransactionBehavior};
/// The connection that writes (one per database).
#[derive(Debug)]
pub struct Writer {
connection: Connection,
}
impl Writer {
pub(crate) fn new(connection: Connection) -> Writer {
Writer { connection }
}
/// Runs `write` in one transaction, committed if it returns `Ok`,
/// rolled back otherwise. Each operation of a [`Batch`] is all or
/// nothing on its own, so `write` may go on after one fails: many
/// pushes in one batch are a group commit, one disk flush for all.
pub fn batch<T>(&mut self, write: impl FnOnce(&mut Batch<'_>) -> Result<T>) -> Result<T> {
let mut batch = Batch {
transaction: self
.connection
.transaction_with_behavior(TransactionBehavior::Immediate)?,
};
let value = write(&mut batch)?;
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
/// checked (`bakashrot_proto`'s decoding). Attachment ids are this
/// database's own, from [`Batch::start_upload`] or
/// [`Reader::attachment`](crate::Reader::attachment).
#[derive(Debug)]
pub struct Batch<'c> {
transaction: Transaction<'c>,
}
impl Batch<'_> {
/// Stores a pushed message: the next id of its topic and node (from 1),
/// which it returns. Without a savepoint, the hot path: a push that
/// fails leaves at most its topic and node's (empty) stream.
pub fn push(&mut self, topic: &str, node: &str, pushed_at: u64, data: &str) -> Result<u64> {
Ok(insert_pushed(&self.transaction, topic, node, pushed_at, data)?.0)
}
/// Stores a pushed message with its attachment, an upload all of whose
/// parts came ([`Batch::write_part`] said so) and whose SHA-256 the
/// caller checked: the attachment is then `ready`.
pub fn push_with_attachment(
&mut self,
upload: i64,
topic: &str,
node: &str,
pushed_at: u64,
data: &str,
) -> Result<u64> {
self.atomic(|db| {
let (state, size, received) = attachment(db, upload)?;
if state != AttachmentState::Uploading || received != size {
return Err(Error::Invalid(format!(
"attachment {upload} isn't a complete upload"
)));
}
let (id, key) = insert_pushed(db, topic, node, pushed_at, data)?;
set_attachment(db, upload, "message_key = ?2, state = 'ready'", key)?;
Ok(id)
})
}
/// Starts an upload: an attachment pushed with its message, whose parts
/// come next. Returns its id.
pub fn start_upload(&mut self, size: u64, sha256: &[u8; 32]) -> Result<i64> {
if !(1..=MAX_ATTACHMENT_SIZE).contains(&size) {
return Err(Error::TooBig(format!(
"an attachment of {size} bytes: 1 to {MAX_ATTACHMENT_SIZE}"
)));
}
self.atomic(|db| {
db.execute(
"INSERT INTO attachments (size, sha256, state) VALUES (?1, ?2, 'uploading')",
(size, sha256),
)?;
Ok(db.last_insert_rowid())
})
}
/// Stores the next part of an upload or of a replicated attachment: in
/// order, each of its exact size (`attachment_part_len`). Returns
/// whether that was the last one.
pub fn write_part(&mut self, attachment_id: i64, part: u64, data: &[u8]) -> Result<bool> {
self.atomic(|db| {
let (state, size, received) = attachment(db, attachment_id)?;
if state != AttachmentState::Uploading && state != AttachmentState::Replicating {
return Err(Error::Invalid(format!(
"attachment {attachment_id} is {state}, it takes no parts"
)));
}
// Every part but the last is whole: what came is whole parts.
let next = received / ATTACHMENT_PART_SIZE;
if received == size || part != next {
return Err(Error::Invalid(format!(
"part {part} of attachment {attachment_id}: part {next} is next"
)));
}
let expected = attachment_part_len(size, part);
if data.len() as u64 != expected {
return Err(Error::Invalid(format!(
"part {part} of attachment {attachment_id}: {} bytes, {expected} expected",
data.len()
)));
}
db.prepare_cached("INSERT INTO attachment_parts (key, part_data) VALUES (?1, ?2)")?
.execute((part_key(attachment_id, part), data))?;
set_attachment(db, attachment_id, "received = received + ?2", expected)?;
Ok(received + expected == size)
})
}
/// Drops an upload that won't be pushed: cut short, or not matching its
/// SHA-256.
pub fn cancel_upload(&mut self, upload: i64) -> Result<()> {
self.atomic(|db| {
if attachment(db, upload)?.0 != AttachmentState::Uploading {
return Err(Error::Invalid(format!(
"attachment {upload} isn't an upload"
)));
}
delete_attachment(db, upload)
})
}
/// Stores messages a peer sent for `topic` and `node`, with their own
/// ids, in order; ones already here are kept as they are. Their
/// attachments are noted, to be asked for (`replicating`), or never if
/// bigger than `max_attachment_size` (`too_big`). Returns the topic and
/// node's last id.
pub fn replicate(
&mut self,
topic: &str,
node: &str,
messages: &[ReplicatedMessage],
max_attachment_size: u64,
) -> Result<u64> {
self.atomic(|db| {
let (stream, mut last_id) = stream(db, topic, node)?;
let mut insert = db.prepare_cached(
"INSERT OR IGNORE INTO data (key, pushed_at, message_data) VALUES (?1, ?2, ?3)",
)?;
let mut attach = db.prepare_cached(
"INSERT INTO attachments (message_key, size, sha256, state) VALUES (?1, ?2, ?3, ?4)",
)?;
for message in messages {
if !(1..=MAX_MESSAGE_ID).contains(&message.id) {
return Err(Error::Invalid(format!("message id {}", message.id)));
}
let key = message_key(stream, message.id);
let stored = insert.execute((key, message.pushed_at, &message.data))? == 1;
if let (true, Some(attachment)) = (stored, &message.attachment) {
let state = if attachment.size > max_attachment_size {
AttachmentState::TooBig
} else {
AttachmentState::Replicating
};
attach.execute((key, attachment.size, &attachment.sha256, state))?;
}
// What the trigger keeps: one ignored was here, below it.
last_id = last_id.max(message.id);
}
Ok(last_id)
})
}
/// A replicated attachment all of whose parts came: `matches` its
/// SHA-256 (the caller checked), it's `ready`; otherwise its parts are
/// dropped and it's asked for again from the start.
pub fn finish_replicated(&mut self, attachment_id: i64, matches: bool) -> Result<()> {
self.atomic(|db| {
let (state, size, received) = attachment(db, attachment_id)?;
if state != AttachmentState::Replicating || received != size {
return Err(Error::Invalid(format!(
"attachment {attachment_id} isn't a complete replicated one"
)));
}
if matches {
set_attachment(db, attachment_id, "state = ?2", AttachmentState::Ready)
} else {
delete_parts(db, attachment_id, None)?;
set_attachment(db, attachment_id, "received = ?2", 0)
}
})
}
/// Retention: deletes `topic`'s messages pushed before `cutoff` (ms),
/// `limit` at most (call again while it returns `limit`). Each stream
/// is read from its oldest message and stops at the first one it keeps:
/// only what's deleted is read. So messages go in id order: one stamped
/// earlier than the one before it (a clock set back) waits for it.
pub fn delete_before(&mut self, topic: &str, cutoff: u64, limit: usize) -> Result<usize> {
self.atomic(|db| {
let streams: Vec<i64> = db
.prepare_cached("SELECT stream_id FROM streams WHERE topic = ?1")?
.query_map([topic], |row| row.get(0))?
.collect::<rusqlite::Result<_>>()?;
let mut oldest = db.prepare_cached(
"SELECT key, pushed_at FROM data WHERE key BETWEEN ?1 AND ?2 ORDER BY key",
)?;
let mut deleted = 0;
for stream in streams {
let (first, last) = stream_keys(stream);
let mut up_to = None;
let mut rows = oldest.query((first, last))?;
while deleted < limit {
let Some(row) = rows.next()? else { break };
if row.get::<_, u64>(1)? >= cutoff {
break;
}
up_to = Some(row.get::<_, i64>(0)?);
deleted += 1;
}
drop(rows);
if let Some(up_to) = up_to {
db.execute(
"DELETE FROM data WHERE key BETWEEN ?1 AND ?2",
(first, up_to),
)?;
}
if deleted == limit {
break;
}
}
Ok(deleted)
})
}
/// Deletes the parts of attachments whose message was deleted,
/// `max_parts` at most (call again while it returns `max_parts`), and
/// their rows once they have none left.
pub fn purge_attachments(&mut self, max_parts: usize) -> Result<usize> {
self.atomic(|db| {
let deleting: Vec<i64> = db
.prepare_cached(
"SELECT attachment_id FROM attachments WHERE state = 'deleting' \
ORDER BY attachment_id",
)?
.query_map([], |row| row.get(0))?
.collect::<rusqlite::Result<_>>()?;
let mut purged = 0;
for attachment_id in deleting {
purged += delete_parts(db, attachment_id, Some(max_parts - purged))?;
if purged == max_parts {
break;
}
db.execute(
"DELETE FROM attachments WHERE attachment_id = ?1",
[attachment_id],
)?;
}
Ok(purged)
})
}
/// Runs one operation all or nothing (a savepoint), so the batch can go
/// on after it fails.
fn atomic<T>(&mut self, operation: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
let savepoint = self.transaction.savepoint()?;
let value = operation(&savepoint)?;
savepoint.commit()?;
Ok(value)
}
}
/// A topic and node's stream, made if new: its id and last id.
fn stream(db: &Connection, topic: &str, node: &str) -> Result<(i64, u64)> {
if let Some(found) = find_stream(db, topic, node)? {
return Ok(found);
}
let next: i64 = db.query_row(
"SELECT coalesce(max(stream_id), 0) + 1 FROM streams",
[],
|row| row.get(0),
)?;
if next > MAX_STREAMS {
return Err(Error::TooBig(format!(
"{topic}/{node}: this database has {MAX_STREAMS} topic and node pairs already"
)));
}
db.execute(
"INSERT INTO streams (stream_id, topic, node) VALUES (?1, ?2, ?3)",
(next, topic, node),
)?;
Ok((next, 0))
}
/// Inserts a pushed message with the next id of its stream: the id and the
/// message's key.
fn insert_pushed(
db: &Connection,
topic: &str,
node: &str,
pushed_at: u64,
data: &str,
) -> Result<(u64, i64)> {
let (stream, last_id) = stream(db, topic, node)?;
let id = last_id + 1;
if id > MAX_MESSAGE_ID {
return Err(Error::TooBig(format!("{topic}/{node}: no message id left")));
}
let key = message_key(stream, id);
db.prepare_cached("INSERT INTO data (key, pushed_at, message_data) VALUES (?1, ?2, ?3)")?
.execute((key, pushed_at, data))?;
Ok((id, key))
}
/// An attachment's state, size and bytes received.
fn attachment(db: &Connection, attachment_id: i64) -> Result<(AttachmentState, u64, u64)> {
db.prepare_cached("SELECT state, size, received FROM attachments WHERE attachment_id = ?1")?
.query_row([attachment_id], |row| {
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
})
.optional()?
.ok_or_else(|| Error::NotFound(format!("no attachment {attachment_id}")))
}
/// `UPDATE attachments SET <set>` of one, `?2` being `value`.
fn set_attachment(
db: &Connection,
attachment_id: i64,
set: &str,
value: impl rusqlite::ToSql,
) -> Result<()> {
db.prepare_cached(&format!(
"UPDATE attachments SET {set} WHERE attachment_id = ?1"
))?
.execute((attachment_id, value))?;
Ok(())
}
/// Deletes an attachment's parts, `limit` at most: how many.
fn delete_parts(db: &Connection, attachment_id: i64, limit: Option<usize>) -> Result<usize> {
let (first, last) = part_keys(attachment_id);
let limit = limit.map_or(-1, |limit| limit as i64);
Ok(db
.prepare_cached(
"DELETE FROM attachment_parts WHERE key IN \
(SELECT key FROM attachment_parts WHERE key BETWEEN ?1 AND ?2 LIMIT ?3)",
)?
.execute((first, last, limit))?)
}
/// Deletes an attachment and its parts.
fn delete_attachment(db: &Connection, attachment_id: i64) -> Result<()> {
delete_parts(db, attachment_id, None)?;
db.execute(
"DELETE FROM attachments WHERE attachment_id = ?1",
[attachment_id],
)?;
Ok(())
}
/// Deletes every upload: at start, none of them can be pushed any more.
pub(crate) fn delete_uploads(db: &Connection) -> Result<()> {
let uploads: Vec<i64> = db
.prepare("SELECT attachment_id FROM attachments WHERE state = 'uploading'")?
.query_map([], |row| row.get(0))?
.collect::<rusqlite::Result<_>>()?;
for upload in uploads {
delete_attachment(db, upload)?;
}
Ok(())
}
@@ -0,0 +1,194 @@
//! Opening a database: making a new one, or checking and migrating one,
//! and the connections to it.
use crate::{Error, QueryRunner, Reader, Result, SCHEMA_VERSION, Writer};
use bakashrot_config::Synchronous;
use rusqlite::{Connection, OptionalExtension, TransactionBehavior};
use std::path::{Path, PathBuf};
use std::time::Duration;
/// `PRAGMA application_id` of a BakaShrot database: "BSHT".
const APPLICATION_ID: i64 = 0x4253_4854;
/// The schema, made in one go.
const SCHEMA: &str = include_str!("schema_v9.sql");
/// Migrations from v9 on: the version each makes, and its SQL. Applied in
/// order from the database's version, each in one transaction with
/// `schema_version` set. None yet.
const MIGRATIONS: &[(i64, &str)] = &[];
/// How long a connection waits for another's lock before failing.
const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
/// The WAL's size, in pages, past which the writer checkpoints it itself
/// (SQLite's default is 1000): a backstop when the [`Checkpointer`] can't
/// keep up.
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`).
#[derive(Debug)]
pub struct Checkpointer {
connection: Connection,
}
impl Checkpointer {
/// Copies what it can without waiting for anyone (`PASSIVE`).
pub fn checkpoint(&self) -> Result<()> {
self.connection
.query_row("PRAGMA wal_checkpoint(PASSIVE)", [], |_| Ok(()))?;
Ok(())
}
}
/// A database, opened and checked once: hands out connections to it.
#[derive(Debug, Clone)]
pub struct Database {
path: PathBuf,
synchronous: Synchronous,
}
impl Database {
/// Opens the database at `path`: makes it if there's none (or it's an
/// empty file), migrates an older one, refuses one that isn't a
/// BakaShrot database of a version this one reads. Then deletes the
/// uploads left over (their pushes never finished).
pub fn open(path: &Path, synchronous: Synchronous) -> Result<Database> {
let database = Database {
path: path.to_owned(),
synchronous,
};
let mut connection = database.connect()?;
let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
let application_id: i64 =
transaction.query_row("PRAGMA application_id", [], |row| row.get(0))?;
let tables: i64 =
transaction.query_row("SELECT count(*) FROM sqlite_schema", [], |row| row.get(0))?;
if application_id == 0 && tables == 0 {
transaction.execute_batch(SCHEMA)?;
transaction.execute(
"INSERT INTO metadata (name, value) VALUES ('created_by', ?1)",
[concat!("bakashrot-storage ", env!("CARGO_PKG_VERSION"))],
)?;
} else if application_id != APPLICATION_ID {
return Err(Error::Unusable(unusable(&transaction, path)?));
}
let mut version = schema_version(&transaction)?;
if version > SCHEMA_VERSION {
return Err(Error::Unusable(format!(
"{}: schema v{version}, made by a newer version (this one reads v{SCHEMA_VERSION})",
path.display()
)));
}
for (made, sql) in MIGRATIONS {
if *made == version + 1 {
transaction.execute_batch(sql)?;
transaction.execute(
"UPDATE metadata SET value = ?1 WHERE name = 'schema_version'",
[made],
)?;
version = *made;
}
}
if version != SCHEMA_VERSION {
return Err(Error::Unusable(format!(
"{}: schema v{version}, which this version can't migrate",
path.display()
)));
}
crate::batch::delete_uploads(&transaction)?;
transaction.commit()?;
Ok(database)
}
/// The connection that writes. Only one at a time should: a second
/// waits for the first's transactions (up to 5 s, then fails). It only
/// checkpoints the WAL itself past [`WRITER_CHECKPOINT_PAGES`]: a
/// [`Checkpointer`] keeps that off its way.
pub fn writer(&self) -> Result<Writer> {
let connection = self.connect()?;
connection.pragma_update(None, "wal_autocheckpoint", WRITER_CHECKPOINT_PAGES)?;
Ok(Writer::new(connection))
}
/// A connection that copies the WAL into the database, off the
/// writer's way: call [`Checkpointer::checkpoint`] every second or so.
pub fn checkpointer(&self) -> Result<Checkpointer> {
Ok(Checkpointer {
connection: self.connect()?,
})
}
/// A connection that reads, as many as needed.
pub fn reader(&self) -> Result<Reader> {
Ok(Reader::new(self.connect()?))
}
/// A connection for clients' queries: read-only (`query_only`).
pub fn query_runner(&self) -> Result<QueryRunner> {
let connection = self.connect()?;
connection.pragma_update(None, "query_only", true)?;
Ok(QueryRunner::new(connection))
}
/// A connection with this database's settings: WAL, `synchronous`, the
/// busy timeout.
fn connect(&self) -> Result<Connection> {
let connection = Connection::open(&self.path)?;
connection.busy_timeout(BUSY_TIMEOUT)?;
let mode: String =
connection.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?;
if !mode.eq_ignore_ascii_case("wal") {
return Err(Error::Unusable(format!(
"{}: can't be put in WAL mode (it's in {mode})",
self.path.display()
)));
}
let synchronous = match self.synchronous {
Synchronous::Full => "FULL",
Synchronous::Normal => "NORMAL",
};
connection.pragma_update(None, "synchronous", synchronous)?;
Ok(connection)
}
}
/// `metadata`'s `schema_version`.
fn schema_version(connection: &Connection) -> Result<i64> {
let has_metadata: bool = connection.query_row(
"SELECT count(*) > 0 FROM sqlite_schema WHERE type = 'table' AND name = 'metadata'",
[],
|row| row.get(0),
)?;
let version = if has_metadata {
connection
.query_row(
"SELECT value FROM metadata WHERE name = 'schema_version'",
[],
|row| row.get(0),
)
.optional()?
} else {
None
};
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())
})
}
+265
View File
@@ -0,0 +1,265 @@
//! BakaShrot's database: SQLite, schema v9 (`schema_v9.sql`).
//!
//! - [`Database`]: opens one (creating it, or checking it's a v9 one),
//! 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.
//! - [`Reader`]: as many as needed, reading while the writer writes (WAL).
//! - [`QueryRunner`]: clients' read-only SQL, on a read-only connection.
//!
//! **Everything is by name:** topics, nodes, message ids, times, as on the
//! wire. Streams (one node's messages in one topic) and the packed keys
//! that store them stay inside this crate: `Source/docs/storage.md`.
//!
//! **Blocking:** SQLite is. The server runs these on threads of their own
//! (the writer on one, readers on a pool), not on its async tasks.
mod batch;
mod database;
mod query;
mod reader;
pub use batch::{Batch, Writer};
pub use database::{Checkpointer, Database, WRITER_CHECKPOINT_PAGES};
pub use query::{MAX_QUERY_BYTES, MAX_QUERY_ROWS, QueryRunner};
pub use reader::{Attachment, MESSAGES_BYTES, Reader};
use bakashrot_proto::limits::{MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID};
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use rusqlite::{Connection, OptionalExtension};
use std::fmt;
/// The schema version this crate makes and reads.
pub const SCHEMA_VERSION: i64 = 9;
/// The most streams (topic and node pairs) a database holds: 2^20 - 1.
pub const MAX_STREAMS: i64 = (1 << STREAM_BITS) - 1;
/// What went wrong. The server answers each with its own refusal code.
#[derive(Debug)]
pub enum Error {
/// SQLite failed (the disk, a lock held too long...): `ServerError`.
Sqlite(rusqlite::Error),
/// A database this version doesn't open: another program's, the old
/// server's, a newer schema's. Said at start.
Unusable(String),
/// A request that doesn't fit what's stored: a part out of order or of
/// the wrong size, an attachment in the wrong state: `InvalidRequest`.
Invalid(String),
/// No such attachment: `NotFound`.
NotFound(String),
/// A node without any message, in any topic: `UnknownName`.
UnknownName(String),
/// Over a limit: streams, message ids, a query's result: `TooBig`.
TooBig(String),
/// A client's query that failed or isn't read-only: `QueryFailed`.
Query(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Sqlite(error) => write!(f, "database: {error}"),
Error::Unusable(what)
| Error::Invalid(what)
| Error::NotFound(what)
| Error::UnknownName(what)
| Error::TooBig(what)
| Error::Query(what) => f.write_str(what),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Sqlite(error) => Some(error),
_ => None,
}
}
}
impl From<rusqlite::Error> for Error {
fn from(error: rusqlite::Error) -> Self {
Error::Sqlite(error)
}
}
/// A result of this crate.
pub type Result<T> = std::result::Result<T, Error>;
/// Where an attachment is at (`Source/docs/storage.md`, "Attachments").
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttachmentState {
/// Pushed, its parts coming, no message yet.
Uploading,
/// Its message came from a peer, its parts come after.
Replicating,
/// All here, checked.
Ready,
/// Bigger than this server keeps: never asked for.
TooBig,
/// Its message was deleted, its parts go in the background.
Deleting,
}
impl AttachmentState {
const ALL: [AttachmentState; 5] = [
AttachmentState::Uploading,
AttachmentState::Replicating,
AttachmentState::Ready,
AttachmentState::TooBig,
AttachmentState::Deleting,
];
/// As the database writes it.
pub fn as_str(self) -> &'static str {
match self {
AttachmentState::Uploading => "uploading",
AttachmentState::Replicating => "replicating",
AttachmentState::Ready => "ready",
AttachmentState::TooBig => "too_big",
AttachmentState::Deleting => "deleting",
}
}
}
impl fmt::Display for AttachmentState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl ToSql for AttachmentState {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(self.as_str().into())
}
}
impl FromSql for AttachmentState {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
let text = value.as_str()?;
Self::ALL
.into_iter()
.find(|state| state.as_str() == text)
.ok_or(FromSqlError::InvalidType)
}
}
/// A topic and node's stream, if it has one: its id and last id.
fn find_stream(db: &Connection, topic: &str, node: &str) -> rusqlite::Result<Option<(i64, u64)>> {
db.prepare_cached("SELECT stream_id, last_id FROM streams WHERE topic = ?1 AND node = ?2")?
.query_row((topic, node), |row| Ok((row.get(0)?, row.get(1)?)))
.optional()
}
// The packed keys (storage.md, "Keys"). Only these know the layout (and
// the schema's generated columns, which a test checks against them).
/// Bits of a message id in `data.key`, below the stream's.
const ID_BITS: u32 = 43;
/// Bits of a stream id above them: 43 + 20 = 63, a positive i64.
const STREAM_BITS: u32 = 20;
/// Bits of a part's index in `attachment_parts.key`.
const PART_BITS: u32 = 20;
const ID_MASK: i64 = (1 << ID_BITS) - 1;
const _: () = assert!(MAX_MESSAGE_ID == ID_MASK as u64, "ids fill their bits");
const _: () = assert!(MAX_ATTACHMENT_PARTS == 1 << PART_BITS, "parts fill theirs");
/// `data.key` of a stream's message.
fn message_key(stream: i64, id: u64) -> i64 {
(stream << ID_BITS) | id as i64
}
/// The message id in a `data.key`.
fn message_id(key: i64) -> u64 {
(key & ID_MASK) as u64
}
/// The first and last `data.key` a stream can have.
fn stream_keys(stream: i64) -> (i64, i64) {
(message_key(stream, 1), message_key(stream, MAX_MESSAGE_ID))
}
/// `attachment_parts.key` of an attachment's part.
fn part_key(attachment: i64, part: u64) -> i64 {
(attachment << PART_BITS) | part as i64
}
/// The first and last `attachment_parts.key` an attachment can have.
fn part_keys(attachment: i64) -> (i64, i64) {
(
part_key(attachment, 0),
part_key(attachment, MAX_ATTACHMENT_PARTS - 1),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keys() {
let key = message_key(MAX_STREAMS, MAX_MESSAGE_ID);
assert_eq!(key, i64::MAX);
assert_eq!(message_id(key), MAX_MESSAGE_ID);
assert_eq!(key >> ID_BITS, MAX_STREAMS);
assert_eq!(message_id(message_key(5, 42)), 42);
let (first, last) = stream_keys(2);
assert!(stream_keys(1).1 < first && last < stream_keys(3).0);
let (first, last) = part_keys(7);
assert_eq!(last - first + 1, MAX_ATTACHMENT_PARTS as i64);
assert!(part_keys(6).1 < first);
}
#[test]
fn the_schema_unpacks_keys_the_same() {
let db = Connection::open_in_memory().unwrap();
db.execute_batch(include_str!("schema_v9.sql")).unwrap();
db.execute(
"INSERT INTO streams (stream_id, topic, node) VALUES (?1, 't', 'n')",
[MAX_STREAMS],
)
.unwrap();
for (stream, id) in [(1, 1), (MAX_STREAMS, MAX_MESSAGE_ID), (77, 123_456_789)] {
let key = message_key(stream, id);
db.execute(
"INSERT INTO data (key, pushed_at, message_data) VALUES (?1, 1, '')",
[key],
)
.unwrap();
let (sql_stream, sql_id): (i64, u64) = db
.query_row(
"SELECT stream_id, message_id FROM data WHERE key = ?1",
[key],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.unwrap();
assert_eq!((sql_stream, sql_id), (stream, id));
}
// The trigger reads the same id.
let last: u64 = db
.query_row(
"SELECT last_id FROM streams WHERE stream_id = ?1",
[MAX_STREAMS],
|r| r.get(0),
)
.unwrap();
assert_eq!(last, MAX_MESSAGE_ID);
}
#[test]
fn states_round_trip() {
let db = Connection::open_in_memory().unwrap();
for state in AttachmentState::ALL {
let back: AttachmentState = db.query_row("SELECT ?1", [state], |r| r.get(0)).unwrap();
assert_eq!(back, state);
}
let wrong: rusqlite::Result<AttachmentState> =
db.query_row("SELECT 'lost'", [], |r| r.get(0));
assert!(wrong.is_err());
}
}
@@ -0,0 +1,95 @@
//! Clients' read-only SQL (`Query`), as the old server ran it.
//!
//! Read-only three ways: 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). The result is JSON, every value a string or null
//! (as in protocol 6): `{"columns":[...],"rows":[[...],...]}`.
use crate::{Error, Result};
use bakashrot_proto::limits::MAX_MESSAGE_SIZE;
use rusqlite::Connection;
use rusqlite::types::ValueRef;
use serde_json::Value;
/// The most rows a query returns, as before.
pub const MAX_QUERY_ROWS: usize = 10_000;
/// The biggest result, in bytes of JSON: what a packet carries.
pub const MAX_QUERY_BYTES: usize = MAX_MESSAGE_SIZE;
/// A read-only connection for clients' queries.
#[derive(Debug)]
pub struct QueryRunner {
connection: Connection,
}
impl QueryRunner {
pub(crate) fn new(connection: Connection) -> QueryRunner {
QueryRunner { connection }
}
/// Runs one read-only statement: its result as JSON. Refused
/// ([`Error::Query`]) if it isn't one, or fails (SQLite's message, a
/// failing row included: never a partial result); [`Error::TooBig`]
/// past [`MAX_QUERY_ROWS`] or [`MAX_QUERY_BYTES`].
pub fn run(&self, sql: &str) -> Result<String> {
let failed = |error: rusqlite::Error| Error::Query(explain(error.to_string()));
let mut statement = self.connection.prepare(sql).map_err(failed)?;
if !statement.readonly() || statement.column_count() == 0 {
return Err(Error::Query("only queries that read are allowed".into()));
}
let columns: Vec<String> = statement.column_names().map(str::to_owned).collect();
let width = columns.len();
let mut rows: Vec<Vec<Value>> = Vec::new();
let mut bytes = 0;
let mut results = statement.query([]).map_err(failed)?;
while let Some(row) = results.next().map_err(failed)? {
if rows.len() == MAX_QUERY_ROWS {
return Err(Error::TooBig(format!(
"more than {MAX_QUERY_ROWS} rows: narrow the query (LIMIT)"
)));
}
let mut values = Vec::with_capacity(width);
for column in 0..width {
let value = text(row.get_ref(column).map_err(failed)?);
// Its JSON's size, about: quotes, escapes aside.
bytes += value.as_str().map_or(5, |text| text.len() + 3);
values.push(value);
}
if bytes > MAX_QUERY_BYTES {
return Err(Error::TooBig(format!(
"a result over {MAX_QUERY_BYTES} bytes: narrow the query"
)));
}
rows.push(values);
}
let json = serde_json::json!({ "columns": columns, "rows": rows }).to_string();
if json.len() > MAX_QUERY_BYTES {
return Err(Error::TooBig(format!(
"a result over {MAX_QUERY_BYTES} bytes: narrow the query"
)));
}
Ok(json)
}
}
/// SQLite's error, with a hint where the old server gave one.
fn explain(why: String) -> String {
if why.contains("malformed JSON") {
format!("{why} (a row isn't JSON: add is_json = 1 to the WHERE)")
} else {
why
}
}
/// A value as text, or null: numbers as SQLite writes them, blobs in hex.
fn text(value: ValueRef<'_>) -> Value {
match value {
ValueRef::Null => Value::Null,
ValueRef::Integer(number) => Value::String(number.to_string()),
ValueRef::Real(number) => Value::String(format!("{number:?}")),
ValueRef::Text(text) => Value::String(String::from_utf8_lossy(text).into_owned()),
ValueRef::Blob(bytes) => Value::String(bytes.iter().map(|b| format!("{b:02x}")).collect()),
}
}
@@ -0,0 +1,225 @@
//! Reading: messages, names, what replication compares, attachments.
//! Answers are the protocol's own types where it has them.
use crate::{
AttachmentState, Error, Result, find_stream, message_id, message_key, part_key, stream_keys,
};
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID};
use bakashrot_proto::packets::{Head, MessageEntry, Messages, MissingAttachment, StoredAttachment};
use rusqlite::{Connection, OptionalExtension, Row};
/// About how many bytes of messages one answer carries: past it, the rest
/// is left for the next request (`more`). A bigger message goes alone.
pub const MESSAGES_BYTES: usize = 1024 * 1024;
/// A stream's messages after a key, in order (`?1` that key, `?2` the
/// stream's last possible one), with their attachments.
const AFTER: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.state \
FROM data d LEFT JOIN attachments a ON a.message_key = d.key \
WHERE d.key > ?1 AND d.key <= ?2 ORDER BY d.key LIMIT ?3";
/// A stream's last messages, newest first (`?1`, `?2`: its key range).
const LATEST: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.state \
FROM data d LEFT JOIN attachments a ON a.message_key = d.key \
WHERE d.key >= ?1 AND d.key <= ?2 ORDER BY d.key DESC LIMIT ?3";
/// A connection that reads.
#[derive(Debug)]
pub struct Reader {
connection: Connection,
}
/// A message's attachment, as stored.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attachment {
/// Its id in this database, for [`Reader::read_part`] and the writer.
pub id: i64,
/// Its size.
pub size: u64,
/// Its SHA-256.
pub sha256: [u8; 32],
/// The bytes of it here so far.
pub received: u64,
/// Where it's at.
pub state: AttachmentState,
}
impl Reader {
pub(crate) fn new(connection: Connection) -> Reader {
Reader { connection }
}
/// A topic and node's messages: `after` an id (0 for the first ones),
/// in order, or the last ones (`None`); `limit` at most, about
/// [`MESSAGES_BYTES`] at most. `more` if others follow (asking `after`
/// the last one gets them). None for a topic and node without any,
/// [`Error::UnknownName`] for a node without any in every topic.
pub fn messages(
&self,
topic: &str,
node: &str,
after: Option<u64>,
limit: u32,
) -> Result<Messages> {
let mut answer = Messages {
more: false,
messages: Vec::new(),
};
let Some((stream, _)) = find_stream(&self.connection, topic, node)? else {
return match self.has_node(node)? {
true => Ok(answer),
false => Err(Error::UnknownName(format!("unknown node '{node}'"))),
};
};
let (first, last) = stream_keys(stream);
let (sql, from) = match after {
Some(after) => (AFTER, message_key(stream, after.min(MAX_MESSAGE_ID))),
None => (LATEST, first),
};
let mut statement = self.connection.prepare_cached(sql)?;
// One more than asked: whether more follow.
let mut rows = statement.query((from, last, i64::from(limit) + 1))?;
let mut bytes = 0;
while let Some(row) = rows.next()? {
let message = entry(row)?;
let full = answer.messages.len() == limit as usize
|| (!answer.messages.is_empty() && bytes + message.data.len() > MESSAGES_BYTES);
if full {
answer.more = after.is_some();
break;
}
bytes += message.data.len();
answer.messages.push(message);
}
if after.is_none() {
answer.messages.reverse();
}
Ok(answer)
}
/// Every topic with messages (or that had some), in order.
pub fn topics(&self) -> Result<Vec<String>> {
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<Vec<String>> {
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<bool> {
self.connection
.prepare_cached("SELECT EXISTS (SELECT 1 FROM streams WHERE node = ?1)")?
.query_row([node], |row| row.get(0))
.map_err(Error::from)
}
/// Every topic and node's last id: what `SyncState` compares.
pub fn heads(&self) -> Result<Vec<Head>> {
self.connection
.prepare_cached("SELECT topic, node, last_id FROM streams ORDER BY topic, node")?
.query_map([], |row| {
Ok(Head {
topic: row.get(0)?,
node: row.get(1)?,
last_id: row.get(2)?,
})
})?
.collect::<rusqlite::Result<_>>()
.map_err(Error::from)
}
/// A topic and node's last id: 0 if it has none.
pub fn last_id(&self, topic: &str, node: &str) -> Result<u64> {
Ok(find_stream(&self.connection, topic, node)?.map_or(0, |(_, last_id)| last_id))
}
/// The replicated attachments not all here yet, oldest first, `limit`
/// at most: what `SyncState` asks for, and from which part.
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 \
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| {
Ok(MissingAttachment {
topic: row.get(0)?,
node: row.get(1)?,
message_id: row.get(2)?,
next_part: row.get::<_, u64>(3)? / ATTACHMENT_PART_SIZE,
})
})?
.collect::<rusqlite::Result<_>>()
.map_err(Error::from)
}
/// A message's attachment, if it has one (none once the message was
/// deleted).
pub fn attachment(
&self,
topic: &str,
node: &str,
message_id: u64,
) -> Result<Option<Attachment>> {
let Some((stream, _)) = find_stream(&self.connection, topic, node)? else {
return Ok(None);
};
self.connection
.prepare_cached(
"SELECT attachment_id, size, sha256, received, state FROM attachments \
WHERE message_key = ?1 AND state <> 'deleting'",
)?
.query_row(
[message_key(stream, message_id.min(MAX_MESSAGE_ID))],
|row| {
Ok(Attachment {
id: row.get(0)?,
size: row.get(1)?,
sha256: row.get(2)?,
received: row.get(3)?,
state: row.get(4)?,
})
},
)
.optional()
.map_err(Error::from)
}
/// One part of an attachment, if it's here.
pub fn read_part(&self, attachment_id: i64, part: u64) -> Result<Vec<u8>> {
self.connection
.prepare_cached("SELECT part_data FROM attachment_parts WHERE key = ?1")?
.query_row([part_key(attachment_id, part)], |row| row.get(0))
.optional()?
.ok_or_else(|| Error::NotFound(format!("part {part} of attachment {attachment_id}")))
}
fn strings(&self, sql: &str) -> Result<Vec<String>> {
self.connection
.prepare_cached(sql)?
.query_map([], |row| row.get(0))?
.collect::<rusqlite::Result<_>>()
.map_err(Error::from)
}
}
/// A row of `messages()`'s query, as the protocol carries it.
fn entry(row: &Row<'_>) -> rusqlite::Result<MessageEntry> {
let attachment = match row.get::<_, Option<u64>>(3)? {
Some(size) => Some(StoredAttachment {
size,
ready: row.get::<_, AttachmentState>(4)? == AttachmentState::Ready,
}),
None => None,
};
Ok(MessageEntry {
id: message_id(row.get(0)?),
pushed_at: row.get(1)?,
data: row.get(2)?,
attachment,
})
}
@@ -0,0 +1,146 @@
-- BakaShrot's database, schema v9. Read Source/docs/storage.md first: the
-- 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).
-- Every connection then sets journal_mode = WAL, synchronous (the
-- config's) and busy_timeout. No foreign keys: one writer keeps the tables
-- consistent, the CHECKs keep the values valid.
--
-- Packed keys (storage.md, "Keys"):
-- data.key = stream_id << 43 | message_id
-- attachment_parts.key = attachment_id << 20 | part
-- 8796093022207 below is 2^43 - 1, a message id's mask.
PRAGMA application_id = 1112754260; -- 'BSHT': a BakaShrot database
-- About the database itself. schema_version drives migrations: a database
-- without it, or of a version the server doesn't know, is refused; an older
-- one is migrated a version at a time, each step in one transaction that
-- also sets schema_version.
CREATE TABLE metadata (
name TEXT PRIMARY KEY,
value ANY NOT NULL
) WITHOUT ROWID;
INSERT INTO metadata (name, value) VALUES
('schema_version', 9),
('created_at', CAST(strftime('%s', 'now') AS INTEGER) * 1000);
-- Database::open adds ('created_by', 'bakashrot-storage <version>').
-- A stream: one node's messages in one topic. Message ids count per
-- stream, replication compares streams' last ids, GetMessages reads one.
-- Topics and nodes are only names here: a topic's streams are its rows.
-- last_id is the highest id the stream ever had: deleting messages
-- (retention) leaves it, so ids never go back. Kept by trg_data_last_id.
CREATE TABLE streams (
stream_id INTEGER PRIMARY KEY CHECK (stream_id BETWEEN 1 AND 1048575),
topic TEXT NOT NULL COLLATE NOCASE CHECK (length(topic) BETWEEN 1 AND 64),
node TEXT NOT NULL COLLATE NOCASE CHECK (length(node) BETWEEN 1 AND 64),
last_id INTEGER NOT NULL DEFAULT 0,
UNIQUE (topic, node)
);
-- The messages, in ONE b-tree ordered by (stream, message id): key packs
-- both. A stream's messages sit together, a range of them is a range of
-- keys; no other index to write at every push. stream_id, message_id and
-- is_json are computed when read, never stored. pushed_at: ms since
-- 1970-01-01 UTC, stamped by the server it was pushed to, kept by
-- replication.
CREATE TABLE data (
key INTEGER PRIMARY KEY,
pushed_at INTEGER NOT NULL,
message_data TEXT NOT NULL,
stream_id INTEGER GENERATED ALWAYS AS (key >> 43) VIRTUAL,
message_id INTEGER GENERATED ALWAYS AS (key & 8796093022207) VIRTUAL,
is_json INTEGER GENERATED ALWAYS AS (json_valid(message_data)) VIRTUAL,
CHECK (key & 8796093022207 >= 1)
);
-- A message's attachment (one at most), or one being pushed (no message
-- yet). The states (storage.md, "Attachments"):
-- uploading pushed, its parts coming; message_key is NULL until all
-- came and the message is stored with it, in one
-- transaction. Cut short: deleted, and at every start.
-- replicating its message came from a peer, its parts come after
-- (asked from part received / 1 MiB on).
-- ready all here, its SHA-256 checked.
-- too_big bigger than max_attachment_size: its message is kept,
-- its parts never asked for.
-- deleting its message was deleted: its parts go in the background,
-- then the row.
CREATE TABLE attachments (
attachment_id INTEGER PRIMARY KEY,
message_key INTEGER, -- data.key of its message, NULL while uploading
size INTEGER NOT NULL CHECK (size BETWEEN 1 AND 1099511627776),
sha256 BLOB NOT NULL CHECK (length(sha256) = 32),
received INTEGER NOT NULL DEFAULT 0 CHECK (received BETWEEN 0 AND size),
state TEXT NOT NULL
CHECK (state IN ('uploading', 'replicating', 'ready', 'too_big', 'deleting')),
CHECK ((message_key IS NULL) = (state = 'uploading'))
);
-- A message's attachment, by its message.
CREATE UNIQUE INDEX attachments_message ON attachments (message_key)
WHERE message_key IS NOT NULL;
-- What's left to do: uploads to clean up, parts to ask for, parts to delete.
CREATE INDEX attachments_state ON attachments (state) WHERE state <> 'ready';
-- Its parts, 1 MiB each (ATTACHMENT_PART_SIZE), the last one what's left,
-- in ONE b-tree: key packs the attachment and the part (2^20 parts of
-- 1 MiB is exactly the 1 TiB limit). An attachment's parts are a range of
-- keys, in order.
CREATE TABLE attachment_parts (
key INTEGER PRIMARY KEY,
part_data BLOB NOT NULL
);
-- A stored message moves its stream's last_id (pushes and replication
-- alike).
CREATE TRIGGER trg_data_last_id AFTER INSERT ON data BEGIN
UPDATE streams SET last_id = max(last_id, NEW.key & 8796093022207)
WHERE stream_id = NEW.key >> 43;
END;
-- A deleted message's attachment goes too, in the background.
CREATE TRIGGER trg_data_attachment AFTER DELETE ON data BEGIN
UPDATE attachments SET state = 'deleting' WHERE message_key = OLD.key;
END;
-- What queries read (Query, read-only): the messages by name, no keys.
-- Joined by key range: a topic's or a node's messages are ranges of the
-- table, read in order (storage.md, "The query surface").
-- SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen'
CREATE VIEW messages AS
SELECT s.topic,
s.node,
d.message_id,
d.message_data,
d.is_json,
d.pushed_at,
strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc,
a.size AS attachment_size,
a.state AS attachment_state
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
-- for all, in its one row, open browse_messages. Never written by the
-- server.
CREATE TABLE browse (
id INTEGER PRIMARY KEY CHECK (id = 1),
topic TEXT COLLATE NOCASE,
node TEXT COLLATE NOCASE
);
CREATE VIEW browse_messages AS
SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json,
m.attachment_size, m.topic
FROM browse b
JOIN messages m ON m.topic = b.topic
WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node)
ORDER BY m.pushed_at DESC, m.node, m.message_id DESC;
@@ -0,0 +1,848 @@
//! The storage, end to end on database files: every request's SQL, the
//! limits, refused databases, and readers and writers at once.
use bakashrot_config::Synchronous;
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID};
use bakashrot_proto::packets::{Attachment as Sent, ReplicatedMessage};
use bakashrot_storage::{AttachmentState, Database, Error, MAX_QUERY_ROWS, MAX_STREAMS};
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
const PART: usize = ATTACHMENT_PART_SIZE as usize;
/// A fresh database file of its own (in target/, not the temp folder).
fn path(name: &str) -> PathBuf {
static COUNT: AtomicUsize = AtomicUsize::new(0);
let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!(
"storage-{}-{}-{name}",
std::process::id(),
COUNT.fetch_add(1, Ordering::Relaxed)
));
let _ = std::fs::remove_dir_all(&folder);
std::fs::create_dir_all(&folder).unwrap();
folder.join("bakashrot.sqlite")
}
fn open(name: &str) -> (Database, PathBuf) {
let path = path(name);
(Database::open(&path, Synchronous::Normal).unwrap(), path)
}
fn ids(messages: &bakashrot_proto::packets::Messages) -> Vec<u64> {
messages.messages.iter().map(|m| m.id).collect()
}
fn replicated(id: u64, pushed_at: u64, attachment: Option<(u64, [u8; 32])>) -> ReplicatedMessage {
ReplicatedMessage {
id,
pushed_at,
data: format!("r{id}"),
attachment: attachment.map(|(size, sha256)| Sent { size, sha256 }),
}
}
#[test]
fn opening() {
let (database, path) = open("opening");
let raw = rusqlite::Connection::open(&path).unwrap();
let meta = |name: &str| -> String {
raw.query_row(
"SELECT CAST(value AS TEXT) FROM metadata WHERE name = ?1",
[name],
|r| r.get(0),
)
.unwrap()
};
assert_eq!(meta("schema_version"), "9");
assert!(meta("created_by").starts_with("bakashrot-storage "));
assert!(meta("created_at").parse::<u64>().unwrap() > 1_700_000_000_000);
let mode: String = raw
.query_row("PRAGMA journal_mode", [], |r| r.get(0))
.unwrap();
assert_eq!(mode, "wal");
drop(database);
// Opened again as it is.
Database::open(&path, Synchronous::Full).unwrap();
// An empty file is made a database.
let empty = self::path("empty");
std::fs::write(&empty, b"").unwrap();
Database::open(&empty, Synchronous::Full).unwrap();
}
#[test]
fn refused_databases() {
let refused = |setup: &str, expected: &str| {
let path = path("refused");
rusqlite::Connection::open(&path)
.unwrap()
.execute_batch(setup)
.unwrap();
match Database::open(&path, Synchronous::Full) {
Err(Error::Unusable(why)) => assert!(why.contains(expected), "{why}"),
other => panic!("{setup}: {other:?}"),
}
};
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",
);
// A newer version's.
let (database, path) = open("newer");
drop(database);
rusqlite::Connection::open(&path)
.unwrap()
.execute(
"UPDATE metadata SET value = 10 WHERE name = 'schema_version'",
[],
)
.unwrap();
match Database::open(&path, Synchronous::Full) {
Err(Error::Unusable(why)) => assert!(why.contains("schema v10, made by a newer"), "{why}"),
other => panic!("{other:?}"),
}
}
#[test]
fn pushing_and_reading() {
let (database, _) = open("push");
let mut writer = database.writer().unwrap();
let reader = database.reader().unwrap();
// A group commit: ids per topic and node, names without case.
let ids_pushed = writer
.batch(|batch| {
Ok(vec![
batch.push("logs", "kitchen", 1000, "{\"t\":1}")?,
batch.push("logs", "kitchen", 1001, "not json")?,
batch.push("LOGS", "Kitchen", 1002, "{}")?,
batch.push("logs", "garage", 1003, "{}")?,
batch.push("sensors", "kitchen", 1004, "{}")?,
])
})
.unwrap();
assert_eq!(ids_pushed, [1, 2, 3, 1, 1]);
let all = reader.messages("logs", "kitchen", Some(0), 100).unwrap();
assert_eq!(ids(&all), [1, 2, 3]);
assert!(!all.more);
assert_eq!(all.messages[1].data, "not json");
assert_eq!(all.messages[0].pushed_at, 1000);
assert!(all.messages[0].attachment.is_none());
// after, limit, more; the latest ones, in order.
let some = reader.messages("logs", "kitchen", Some(1), 1).unwrap();
assert_eq!((ids(&some), some.more), (vec![2], true));
let latest = reader.messages("Logs", "KITCHEN", None, 2).unwrap();
assert_eq!((ids(&latest), latest.more), (vec![2, 3], false));
assert!(
reader
.messages("logs", "kitchen", Some(3), 10)
.unwrap()
.messages
.is_empty()
);
// A node without any message, in any topic: unknown.
assert!(matches!(
reader.messages("logs", "nobody", None, 10),
Err(Error::UnknownName(_))
));
assert!(
reader
.messages("logs", "kitchen", Some(MAX_MESSAGE_ID), 10)
.unwrap()
.messages
.is_empty()
);
// Names, heads.
assert_eq!(reader.topics().unwrap(), ["logs", "sensors"]);
assert_eq!(reader.nodes().unwrap(), ["garage", "kitchen"]);
let heads: Vec<_> = reader
.heads()
.unwrap()
.into_iter()
.map(|h| (h.topic, h.node, h.last_id))
.collect();
assert_eq!(
heads,
[
("logs".into(), "garage".into(), 1),
("logs".into(), "kitchen".into(), 3),
("sensors".into(), "kitchen".into(), 1)
]
);
assert_eq!(reader.last_id("logs", "kitchen").unwrap(), 3);
assert_eq!(reader.last_id("nope", "kitchen").unwrap(), 0);
}
#[test]
fn answers_stop_at_about_a_megabyte() {
let (database, _) = open("bytes");
let mut writer = database.writer().unwrap();
let big = "x".repeat(400 * 1024);
writer
.batch(|batch| {
for _ in 0..5 {
batch.push("logs", "kitchen", 1, &big)?;
}
batch.push("logs", "kitchen", 1, &"y".repeat(3 * 1024 * 1024))?;
Ok(())
})
.unwrap();
let reader = database.reader().unwrap();
let first = reader.messages("logs", "kitchen", Some(0), 100).unwrap();
assert_eq!((ids(&first), first.more), (vec![1, 2], true));
let next = reader.messages("logs", "kitchen", Some(4), 100).unwrap();
assert_eq!((ids(&next), next.more), (vec![5], true));
// A bigger message goes alone.
let alone = reader.messages("logs", "kitchen", Some(5), 100).unwrap();
assert_eq!((ids(&alone), alone.more), (vec![6], false));
}
#[test]
fn uploads() {
let (database, path) = open("uploads");
let mut writer = database.writer().unwrap();
let size = (2 * PART + 10) as u64;
let sha = [7; 32];
let upload = writer.batch(|b| b.start_upload(size, &sha)).unwrap();
let part = |n: usize| vec![n as u8; if n == 2 { 10 } else { PART }];
// Only in order, each its size.
assert!(matches!(
writer.batch(|b| b.write_part(upload, 1, &part(1))),
Err(Error::Invalid(_))
));
assert!(matches!(
writer.batch(|b| b.write_part(upload, 0, &[0; 10])),
Err(Error::Invalid(_))
));
assert!(!writer.batch(|b| b.write_part(upload, 0, &part(0))).unwrap());
assert!(!writer.batch(|b| b.write_part(upload, 1, &part(1))).unwrap());
// Not complete: no push with it, and the batch goes on after.
let pushed = writer
.batch(|b| {
assert!(matches!(
b.push_with_attachment(upload, "logs", "kitchen", 1, "{}"),
Err(Error::Invalid(_))
));
b.push("logs", "kitchen", 1, "without")
})
.unwrap();
assert_eq!(pushed, 1);
assert!(writer.batch(|b| b.write_part(upload, 2, &part(2))).unwrap());
assert!(matches!(
writer.batch(|b| b.write_part(upload, 3, &[1])),
Err(Error::Invalid(_))
));
let id = writer
.batch(|b| b.push_with_attachment(upload, "logs", "kitchen", 2, "with"))
.unwrap();
assert_eq!(id, 2);
let reader = database.reader().unwrap();
let message = &reader
.messages("logs", "kitchen", Some(1), 1)
.unwrap()
.messages[0];
let stored = message.attachment.as_ref().unwrap();
assert_eq!((stored.size, stored.ready), (size, true));
let attachment = reader.attachment("logs", "kitchen", 2).unwrap().unwrap();
assert_eq!(
(attachment.state, attachment.sha256, attachment.received),
(AttachmentState::Ready, sha, size)
);
assert_eq!(reader.read_part(attachment.id, 1).unwrap(), part(1));
assert_eq!(reader.read_part(attachment.id, 2).unwrap(), part(2));
assert!(matches!(
reader.read_part(attachment.id, 3),
Err(Error::NotFound(_))
));
assert!(reader.attachment("logs", "kitchen", 1).unwrap().is_none());
// Cancelled, or left over at a restart: gone with their parts.
let cancelled = writer.batch(|b| b.start_upload(5, &sha)).unwrap();
writer
.batch(|b| b.write_part(cancelled, 0, &[1; 5]))
.unwrap();
writer.batch(|b| b.cancel_upload(cancelled)).unwrap();
assert!(matches!(
writer.batch(|b| b.cancel_upload(cancelled)),
Err(Error::NotFound(_))
));
let left = writer.batch(|b| b.start_upload(5, &sha)).unwrap();
writer.batch(|b| b.write_part(left, 0, &[1; 5])).unwrap();
drop((writer, reader, database));
Database::open(&path, Synchronous::Normal).unwrap();
let raw = rusqlite::Connection::open(&path).unwrap();
let count = |sql: &str| raw.query_row(sql, [], |r| r.get::<_, i64>(0)).unwrap();
assert_eq!(count("SELECT count(*) FROM attachments"), 1);
assert_eq!(count("SELECT count(*) FROM attachment_parts"), 3);
// Sizes.
let database = Database::open(&path, Synchronous::Normal).unwrap();
let mut writer = database.writer().unwrap();
assert!(matches!(
writer.batch(|b| b.start_upload(0, &sha)),
Err(Error::TooBig(_))
));
assert!(matches!(
writer.batch(|b| b.start_upload((1 << 40) + 1, &sha)),
Err(Error::TooBig(_))
));
}
#[test]
fn replication() {
let (database, _) = open("replication");
let mut writer = database.writer().unwrap();
let reader = database.reader().unwrap();
let sha = [3; 32];
let last = writer
.batch(|b| {
b.replicate(
"logs",
"kitchen",
&[
replicated(5, 100, None),
replicated(9, 200, Some((PART as u64 + 1, sha))),
replicated(12, 300, Some((50, sha))),
],
1000,
)
})
.unwrap();
assert_eq!(last, 12);
// Ones already here are kept as they are; the head never goes back.
let again = writer
.batch(|b| {
b.replicate(
"logs",
"kitchen",
&[ReplicatedMessage {
data: "other".into(),
..replicated(5, 1, None)
}],
1000,
)
})
.unwrap();
assert_eq!(again, 12);
let stored = reader.messages("logs", "kitchen", Some(0), 10).unwrap();
assert_eq!(ids(&stored), [5, 9, 12]);
assert_eq!(stored.messages[0].data, "r5");
// A push goes on after the replicated ids.
assert_eq!(
writer
.batch(|b| b.push("logs", "kitchen", 400, "{}"))
.unwrap(),
13
);
// Attachments: too big here, or to ask for.
let big = reader.attachment("logs", "kitchen", 9).unwrap().unwrap();
assert_eq!(big.state, AttachmentState::TooBig);
assert!(!stored.messages[1].attachment.as_ref().unwrap().ready);
let missing = reader.missing_attachments(256).unwrap();
assert_eq!(missing.len(), 1);
assert_eq!((missing[0].message_id, missing[0].next_part), (12, 0));
// Its parts; a mismatch starts it over; a match makes it ready.
let small = reader.attachment("logs", "kitchen", 12).unwrap().unwrap();
assert!(
writer
.batch(|b| b.write_part(small.id, 0, &[1; 50]))
.unwrap()
);
writer
.batch(|b| b.finish_replicated(small.id, false))
.unwrap();
assert_eq!(
reader
.attachment("logs", "kitchen", 12)
.unwrap()
.unwrap()
.received,
0
);
assert_eq!(reader.missing_attachments(256).unwrap()[0].next_part, 0);
assert!(
writer
.batch(|b| b.write_part(small.id, 0, &[2; 50]))
.unwrap()
);
writer
.batch(|b| b.finish_replicated(small.id, true))
.unwrap();
assert_eq!(
reader
.attachment("logs", "kitchen", 12)
.unwrap()
.unwrap()
.state,
AttachmentState::Ready
);
assert!(reader.missing_attachments(256).unwrap().is_empty());
assert!(matches!(
writer.batch(|b| b.finish_replicated(small.id, true)),
Err(Error::Invalid(_))
));
assert!(matches!(
writer.batch(|b| b.write_part(big.id, 0, &[0; PART])),
Err(Error::Invalid(_))
));
// A resumed one: next_part follows what came.
writer
.batch(|b| {
b.replicate(
"logs",
"garage",
&[replicated(1, 1, Some((2 * PART as u64, sha)))],
u64::MAX,
)
})
.unwrap();
let resumed = reader.attachment("logs", "garage", 1).unwrap().unwrap();
writer
.batch(|b| b.write_part(resumed.id, 0, &[0; PART]))
.unwrap();
let missing = reader.missing_attachments(256).unwrap();
assert_eq!(
(missing[0].node.as_str(), missing[0].next_part),
("garage", 1)
);
// Ids out of range.
assert!(matches!(
writer.batch(|b| b.replicate("logs", "kitchen", &[replicated(0, 1, None)], 0)),
Err(Error::Invalid(_))
));
}
#[test]
fn retention() {
let (database, _) = open("retention");
let mut writer = database.writer().unwrap();
let reader = database.reader().unwrap();
writer
.batch(|b| {
for at in 1..=10 {
b.push("logs", "kitchen", at * 100, "{}")?;
b.push("logs", "garage", at * 100 + 50, "{}")?;
b.push("sensors", "kitchen", at * 100, "{}")?;
}
Ok(())
})
.unwrap();
// An attachment on an old message.
let upload = writer
.batch(|b| b.start_upload(3 * PART as u64, &[1; 32]))
.unwrap();
for part in 0..3 {
writer
.batch(|b| b.write_part(upload, part, &[0; PART]))
.unwrap();
}
writer
.batch(|b| b.push_with_attachment(upload, "logs", "kitchen", 120, "{}"))
.unwrap();
// Before 500: kitchen 1-4 and 11 (pushed at 120, after 4: in id order, it
// waits for 5-10), garage 1-4. A limit, then the rest.
assert_eq!(
writer.batch(|b| b.delete_before("logs", 500, 5)).unwrap(),
5
);
assert_eq!(
writer.batch(|b| b.delete_before("logs", 500, 100)).unwrap(),
3
);
assert_eq!(
writer.batch(|b| b.delete_before("logs", 500, 100)).unwrap(),
0
);
assert_eq!(
ids(&reader.messages("logs", "kitchen", Some(0), 100).unwrap()),
[5, 6, 7, 8, 9, 10, 11]
);
assert_eq!(
ids(&reader.messages("logs", "garage", Some(0), 100).unwrap()).len(),
6
);
assert_eq!(
ids(&reader.messages("sensors", "kitchen", Some(0), 100).unwrap()).len(),
10
);
// Everything: the heads stay, ids go on.
assert_eq!(
writer
.batch(|b| b.delete_before("logs", u64::MAX, 1000))
.unwrap(),
13
);
assert_eq!(reader.last_id("logs", "kitchen").unwrap(), 11);
assert_eq!(
writer
.batch(|b| b.push("logs", "kitchen", 2000, "{}"))
.unwrap(),
12
);
// The attachment's parts go in batches, then its row.
assert_eq!(reader.attachment("logs", "kitchen", 11).unwrap(), None);
assert_eq!(writer.batch(|b| b.purge_attachments(2)).unwrap(), 2);
assert_eq!(writer.batch(|b| b.purge_attachments(2)).unwrap(), 1);
assert_eq!(writer.batch(|b| b.purge_attachments(2)).unwrap(), 0);
assert!(matches!(
reader.read_part(upload, 2),
Err(Error::NotFound(_))
));
}
#[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");
let mut writer = database.writer().unwrap();
writer
.batch(|b| b.push("logs", "kitchen", 1, "{}"))
.unwrap();
let raw = rusqlite::Connection::open(&path).unwrap();
// A topic and node with no id left.
raw.execute("UPDATE streams SET last_id = ?1", [MAX_MESSAGE_ID as i64])
.unwrap();
assert!(matches!(
writer.batch(|b| b.push("logs", "kitchen", 1, "{}")),
Err(Error::TooBig(_))
));
// No stream left.
raw.execute(
"INSERT INTO streams (stream_id, topic, node) VALUES (?1, 'x', 'y')",
[MAX_STREAMS],
)
.unwrap();
assert!(matches!(
writer.batch(|b| b.push("new", "kitchen", 1, "{}")),
Err(Error::TooBig(_))
));
// The highest key there is.
raw.execute(
"UPDATE streams SET last_id = ?1 - 1 WHERE topic = 'x'",
[MAX_MESSAGE_ID as i64],
)
.unwrap();
assert_eq!(
writer.batch(|b| b.push("x", "y", 1, "last")).unwrap(),
MAX_MESSAGE_ID
);
let reader = database.reader().unwrap();
let last = reader.messages("x", "y", None, 1).unwrap();
assert_eq!(
(last.messages[0].id, last.messages[0].data.as_str()),
(MAX_MESSAGE_ID, "last")
);
}
#[test]
fn queries() {
let (database, _) = open("queries");
let mut writer = database.writer().unwrap();
writer
.batch(|b| {
b.push("logs", "kitchen", 1_700_000_000_000, "{\"t\": 21.5}")?;
b.push("logs", "kitchen", 1_700_000_000_001, "not json")?;
b.push("logs", "garage", 1_700_000_000_002, "{\"t\": 3}")
})
.unwrap();
let runner = database.query_runner().unwrap();
let json = |sql: &str| -> serde_json::Value {
serde_json::from_str(&runner.run(sql).unwrap()).unwrap()
};
let result = json(
"SELECT topic, node, message_id, is_json, pushed_utc, message_data ->> '$.t' AS t, \
attachment_size FROM messages WHERE topic = 'logs' AND node = 'kitchen' AND is_json = 1",
);
assert_eq!(
result,
serde_json::json!({
"columns": ["topic", "node", "message_id", "is_json", "pushed_utc", "t", "attachment_size"],
"rows": [["logs", "kitchen", "1", "1", "2023-11-14T22:13:20.000Z", "21.5", null]]
})
);
assert_eq!(
json("SELECT x'00ff', 1.0, NULL")["rows"],
serde_json::json!([["00ff", "1.0", null]])
);
assert_eq!(
json("SELECT count(*) FROM messages")["rows"],
serde_json::json!([["3"]])
);
// Refused: writes, whatever their form, more than one statement, no rows to give.
for sql in [
"DELETE FROM data",
"WITH x AS (SELECT 1) DELETE FROM data",
"INSERT INTO browse VALUES (1, 'logs', NULL)",
"PRAGMA query_only = 0",
"SELECT 1; DELETE FROM data",
"CREATE TABLE t (x)",
"ATTACH 'other.sqlite' AS other",
"SELEKT 1",
] {
assert!(matches!(runner.run(sql), Err(Error::Query(_))), "{sql}");
}
// A failing row fails it all, with SQLite's message.
match runner.run("SELECT message_data ->> '$.t' FROM messages") {
Err(Error::Query(why)) => assert!(why.contains("malformed JSON"), "{why}"),
other => panic!("{other:?}"),
}
// Too big.
let rows = format!(
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i <= {MAX_QUERY_ROWS}) SELECT i FROM n"
);
assert!(matches!(runner.run(&rows), Err(Error::TooBig(_))));
assert!(matches!(
runner.run("WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 20) SELECT zeroblob(1000000) FROM n"),
Err(Error::TooBig(_))
));
// Still nothing written.
assert_eq!(
json("SELECT count(*) FROM data")["rows"],
serde_json::json!([["3"]])
);
}
#[test]
fn the_view_reads_by_key_range() {
let (database, path) = open("plans");
drop(database);
let raw = rusqlite::Connection::open(&path).unwrap();
for sql in [
"SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen'",
"SELECT * FROM messages WHERE topic = 'logs' AND pushed_at > 5",
"SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id DESC LIMIT 5",
] {
let plan: Vec<String> = raw
.prepare(&format!("EXPLAIN QUERY PLAN {sql}"))
.unwrap()
.query_map([], |r| r.get(3))
.unwrap()
.collect::<Result<_, _>>()
.unwrap();
let plan = plan.join(" | ");
assert!(
plan.contains("INTEGER PRIMARY KEY (rowid>? AND rowid<?)"),
"{sql}: {plan}"
);
assert!(!plan.contains("SCAN d"), "{sql}: {plan}");
}
}
#[test]
fn readers_while_writing() {
let (database, _) = open("concurrent");
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let readers: Vec<_> = (0..3)
.map(|_| {
let database = database.clone();
let stop = stop.clone();
std::thread::spawn(move || {
let reader = database.reader().unwrap();
let mut seen = 0;
let mut reads = 0;
while !stop.load(Ordering::Relaxed) {
let latest = match reader.messages("logs", "kitchen", None, 10) {
// Not pushed to yet.
Err(Error::UnknownName(_)) => continue,
latest => latest.unwrap(),
};
let ids = ids(&latest);
assert!(ids.windows(2).all(|w| w[1] == w[0] + 1), "{ids:?}");
let last = ids.last().copied().unwrap_or(0);
assert!(last >= seen, "went back: {last} < {seen}");
seen = last;
reads += 1;
}
reads
})
})
.collect();
// Two writers at once: the second waits for the first's transactions.
let writers: Vec<_> = ["kitchen", "garage"]
.into_iter()
.map(|node| {
let database = database.clone();
std::thread::spawn(move || {
let mut writer = database.writer().unwrap();
for batch in 0..100 {
writer
.batch(|b| {
for i in 0..20 {
b.push("logs", node, batch * 20 + i, "{}")?;
}
Ok(())
})
.unwrap();
}
})
})
.collect();
for writer in writers {
writer.join().unwrap();
}
stop.store(true, Ordering::Relaxed);
for reader in readers {
assert!(reader.join().unwrap() > 0);
}
let reader = database.reader().unwrap();
assert_eq!(reader.last_id("logs", "kitchen").unwrap(), 2000);
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
/// 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
/// default: `PUSHES=1000000 SYNC=normal cargo test --release -p
/// bakashrot-storage -- --ignored --nocapture`.
#[test]
#[ignore]
fn compare_with_old() {
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());
let synchronous = if sync == "full" {
Synchronous::Full
} else {
Synchronous::Normal
};
let path = path("compare");
let database = Database::open(&path, synchronous).unwrap();
let mut writer = database.writer().unwrap();
let prefix = r#"{"kind":"temp","value":21.37,"ts":1700000000,"pad":""#;
let json = format!("{prefix}{}\"}}", "x".repeat(200 - prefix.len() - 2));
assert_eq!(json.len(), 200);
let topics: Vec<String> = (0..100).map(|t| format!("topic{t}")).collect();
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.
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let checkpoints = {
let checkpointer = database.checkpointer().unwrap();
let stop = stop.clone();
std::thread::spawn(move || {
while !stop.load(Ordering::Relaxed) {
std::thread::sleep(std::time::Duration::from_secs(1));
checkpointer.checkpoint().unwrap();
}
})
};
let mut state: u64 = 1;
let start = Instant::now();
for batch in 0..count / 100 {
writer
.batch(|b| {
for i in 0..100 {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
let x = (state >> 33) & 0x7FFF_FFFF;
let at = 1_700_000_000_000 + (batch * 100 + i) * 10;
b.push(
&topics[(x % 100) as usize],
&nodes[(x / 100 % 5) as usize],
at,
&json,
)?;
}
Ok(())
})
.unwrap();
}
let pushing = start.elapsed().as_secs_f64();
stop.store(true, Ordering::Relaxed);
checkpoints.join().unwrap();
let reader = database.reader().unwrap();
let pick = |i: usize| (&topics[i * 37 % 100], &nodes[i * 3 % 5]);
let middle: Vec<u64> = (0..500)
.map(|i| reader.last_id(pick(i).0, pick(i).1).unwrap() / 2)
.collect();
let start = Instant::now();
for i in 0..2000 {
reader.messages(pick(i).0, pick(i).1, None, 1).unwrap();
}
let latest = start.elapsed().as_secs_f64() * 1000.0 / 2000.0;
let start = Instant::now();
let mut read = 0;
for (i, after) in middle.iter().enumerate() {
read += reader
.messages(pick(i).0, pick(i).1, Some(*after), 1000)
.unwrap()
.messages
.len();
}
let after = start.elapsed().as_secs_f64() * 1000.0 / 500.0;
rusqlite::Connection::open(&path)
.unwrap()
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
.unwrap();
let size = std::fs::metadata(&path).unwrap().len();
let start = Instant::now();
let cutoff = 1_700_000_000_000 + count / 10 * 10;
let deleted = writer
.batch(|b| b.delete_before("topic0", cutoff, 100_000_000))
.unwrap();
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",
count as f64 / pushing,
size as f64 / 1e6
);
}