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

Moved the workspace to the root, Added the build scripts, ARM64 releases and the Docker image

Source/'s content is at the root now, Source/README.md merged into
readme.md. Scripts at the root: build.ps1, test.ps1 (was check.ps1),
release.ps1 (over release.py) and clean.ps1. Everything is LF except the
.ps1 files.

CI (.github/workflows/ci.yml) runs on a v* tag or by hand: the checks,
then a release for Windows x64 and ARM64 and Linux x64 and ARM64, each on
its own kind of runner, the archives kept as artifacts. release.py names
the platform from the Rust host, make_wheel.py tags the wheel from the
library's header.

docker/: the server's image (built from source, the tools beside it, uid
10001), compose.yml and test.sh. CI builds amd64 and arm64 natively,
checks them, and on a tag pushes them to ghcr.io with an index for
<version> and latest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 01:13:44 +01:00
parent 17ec69c03c
commit 5045019df4
93 changed files with 634 additions and 277 deletions
+435
View File
@@ -0,0 +1,435 @@
//! 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`). Ones pushed before
/// `skip_before` (ms, past their age here) aren't stored, but count as
/// received. Returns the topic and node's last id.
pub fn replicate(
&mut self,
topic: &str,
node: &str,
messages: &[ReplicatedMessage],
max_attachment_size: u64,
skip_before: 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)));
}
// What the trigger keeps: one ignored was here, below it.
last_id = last_id.max(message.id);
if message.pushed_at < skip_before {
continue;
}
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))?;
}
}
// The skipped ones move it too.
db.prepare_cached("UPDATE streams SET last_id = ?2 WHERE stream_id = ?1")?
.execute((stream, last_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)
}
})
}
/// A ready attachment found not to match its SHA-256 (a damaged
/// disk, a bug): its parts go, it's asked for again from its peers
/// (`replicating`), and not served meanwhile.
pub fn damaged(&mut self, attachment_id: i64) -> Result<()> {
self.atomic(|db| {
if attachment(db, attachment_id)?.0 != AttachmentState::Ready {
return Err(Error::Invalid(format!(
"attachment {attachment_id} isn't a ready one"
)));
}
delete_parts(db, attachment_id, None)?;
db.prepare_cached(
"UPDATE attachments SET state = 'replicating', received = 0 \
WHERE attachment_id = ?1",
)?
.execute([attachment_id])?;
Ok(())
})
}
/// 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(())
}
/// At start: deletes every upload (none of them can be pushed any more),
/// and starts over the replicated attachments all of whose parts came but
/// weren't checked (stopped in between).
pub(crate) fn clean_up(db: &Connection) -> Result<()> {
let unchecked: Vec<i64> = db
.prepare(
"SELECT attachment_id FROM attachments \
WHERE state = 'replicating' AND received = size",
)?
.query_map([], |row| row.get(0))?
.collect::<rusqlite::Result<_>>()?;
for attachment_id in unchecked {
delete_parts(db, attachment_id, None)?;
set_attachment(db, attachment_id, "received = ?2", 0)?;
}
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(())
}
+194
View File
@@ -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::clean_up(&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: `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 (`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());
}
}
+95
View File
@@ -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()),
}
}
+275
View File
@@ -0,0 +1,275 @@
//! 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::{
Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, ReplicatedMessage,
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 stream's messages after a key, as replication sends them.
const TO_REPLICATE: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.sha256 \
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 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)
}
/// A topic and node's messages after an id, as replication sends them:
/// `limit` at most, about [`MESSAGES_BYTES`] at most (a bigger one
/// alone). None once there are no more.
pub fn to_replicate(
&self,
topic: &str,
node: &str,
after: u64,
limit: u32,
) -> Result<Vec<ReplicatedMessage>> {
let mut messages = Vec::new();
let Some((stream, _)) = find_stream(&self.connection, topic, node)? else {
return Ok(messages);
};
let (_, last) = stream_keys(stream);
let mut statement = self.connection.prepare_cached(TO_REPLICATE)?;
let from = message_key(stream, after.min(MAX_MESSAGE_ID));
let mut rows = statement.query((from, last, i64::from(limit)))?;
let mut bytes = 0;
while let Some(row) = rows.next()? {
let data: String = row.get(2)?;
if !messages.is_empty() && bytes + data.len() > MESSAGES_BYTES {
break;
}
bytes += data.len();
let attachment = match row.get::<_, Option<u64>>(3)? {
Some(size) => Some(Sent {
size,
sha256: row.get(4)?,
}),
None => None,
};
messages.push(ReplicatedMessage {
id: message_id(row.get(0)?),
pushed_at: row.get(1)?,
data,
attachment,
});
}
Ok(messages)
}
/// 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,
})
}
+146
View File
@@ -0,0 +1,146 @@
-- BakaShrot's database, schema v9. Read 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;