use std::path::Path;
use crate::admin::{QueryAnalysis, QueryClass};
use crate::format::OutputFormat;
use super::errors::{err, Category, Result};
#[derive(Debug, Clone)]
pub struct EngineStartOptions {
pub data_path: std::path::PathBuf,
pub backups_allowed_path: std::path::PathBuf,
}
pub trait Engine: Send {
fn version(&mut self) -> Result<String>;
fn backup_format(&mut self) -> Result<u64>;
fn start(&mut self, options: EngineStartOptions) -> Result<()>;
fn create_database(&mut self, database: &str) -> Result<()>;
fn use_database(&mut self, database: &str) -> Result<()>;
fn analyze(&mut self, sql: &str, target_database: &str) -> Result<QueryAnalysis>;
fn query(&mut self, sql: &str, format: OutputFormat) -> Result<Vec<u8>>;
fn run(&mut self, sql: &str) -> Result<()>;
fn backup_database(&mut self, database: &str, file_path: &Path) -> Result<()>;
fn restore_database(&mut self, database: &str, file_path: &Path) -> Result<()>;
fn close(&mut self) -> Result<()>;
}
pub type EngineFactory = Box<dyn Fn() -> Result<Box<dyn Engine>> + Send + Sync>;
pub(crate) fn assert_query_allowed(analysis: &QueryAnalysis) -> Result<()> {
if analysis.class == QueryClass::Unknown {
return Err(err(
Category::ClassificationRefused,
"durable: core could not classify this statement; refusing rather than running \
something whose effect is unknown",
));
}
if analysis.statement_count != 1 {
return Err(err(
Category::ClassificationRefused,
format!(
"durable: query takes exactly one statement, core counted {}",
analysis.statement_count
),
));
}
if analysis.class != QueryClass::ReadOnly {
return Err(err(
Category::ClassificationRefused,
format!(
"durable: query accepts only READ_ONLY statements, core classified this as {}",
analysis.class
),
));
}
Ok(())
}
pub(crate) fn assert_execute_allowed(analysis: &QueryAnalysis, database: &str) -> Result<()> {
if analysis.class == QueryClass::Unknown {
return Err(err(
Category::ClassificationRefused,
"durable: core could not classify this statement; refusing rather than logging \
something whose effect is unknown",
));
}
if analysis.statement_count != 1 {
return Err(err(
Category::ClassificationRefused,
format!(
"durable: execute takes exactly one statement, core counted {}. A WAL record is \
one statement, so a batch has no replayable form in V1",
analysis.statement_count
),
));
}
if analysis.class != QueryClass::Mutating {
let mut message = format!(
"durable: execute accepts only MUTATING statements, core classified this as {}",
analysis.class
);
match analysis.class {
QueryClass::ReadOnly => {
message.push_str(". Use query(), which does not write the WAL");
}
QueryClass::MutatingGlobal => {
message.push_str(
". Global state lives outside every database, so a checkpoint cannot carry \
it and V1 refuses it",
);
}
QueryClass::Control => {
message.push_str(
". USE/SET/SYSTEM/BACKUP/RESTORE, and writes outside the engine, are managed \
by the durable object and cannot be issued through it",
);
}
_ => {}
}
return Err(err(Category::ClassificationRefused, message));
}
if analysis.changes_database_lifecycle {
return Err(err(
Category::ClassificationRefused,
format!(
"durable: execute cannot create, drop or rename a database; the object owns \
{database:?} and its lifecycle is not a logged mutation"
),
));
}
if !analysis.writes_only_target_database {
return Err(err(
Category::ClassificationRefused,
format!(
"durable: core could not prove every write lands in {database:?}. A write to \
another database, to system, to a table function or to a file is not captured \
by this object's checkpoint"
),
));
}
if analysis.has_secrets {
return Err(err(
Category::SecretRefused,
"durable: refusing to log a mutation that embeds a credential; the WAL outlives the \
statement, so the credential would outlive it too",
));
}
Ok(())
}
#[cfg(test)]
mod test {
use super::*;
fn analysis(class: QueryClass) -> QueryAnalysis {
QueryAnalysis {
class,
statement_count: 1,
has_secrets: false,
writes_only_target_database: true,
changes_database_lifecycle: false,
}
}
#[test]
fn the_query_gate_takes_one_read_only_statement_and_nothing_else() {
assert!(assert_query_allowed(&analysis(QueryClass::ReadOnly)).is_ok());
for class in [
QueryClass::Mutating,
QueryClass::MutatingGlobal,
QueryClass::Control,
QueryClass::Unknown,
] {
let error = assert_query_allowed(&analysis(class)).expect_err("not a read");
assert_eq!(error.category(), Category::ClassificationRefused, "{class}");
}
let mut batch = analysis(QueryClass::ReadOnly);
batch.statement_count = 2;
assert_eq!(
assert_query_allowed(&batch).unwrap_err().category(),
Category::ClassificationRefused
);
}
#[test]
fn the_execute_gate_takes_one_local_mutation_and_nothing_else() {
assert!(assert_execute_allowed(&analysis(QueryClass::Mutating), "mem").is_ok());
for class in [
QueryClass::ReadOnly,
QueryClass::MutatingGlobal,
QueryClass::Control,
QueryClass::Unknown,
] {
let error = assert_execute_allowed(&analysis(class), "mem").expect_err("not a write");
assert_eq!(error.category(), Category::ClassificationRefused, "{class}");
}
}
#[test]
fn a_write_the_checkpoint_would_not_carry_is_refused() {
let mut elsewhere = analysis(QueryClass::Mutating);
elsewhere.writes_only_target_database = false;
assert_eq!(
assert_execute_allowed(&elsewhere, "mem")
.unwrap_err()
.category(),
Category::ClassificationRefused
);
let mut lifecycle = analysis(QueryClass::Mutating);
lifecycle.changes_database_lifecycle = true;
assert_eq!(
assert_execute_allowed(&lifecycle, "mem")
.unwrap_err()
.category(),
Category::ClassificationRefused
);
}
#[test]
fn a_credential_bearing_mutation_is_refused_without_echoing_it() {
let mut secret = analysis(QueryClass::Mutating);
secret.has_secrets = true;
let error = assert_execute_allowed(&secret, "mem").expect_err("a credential in the WAL");
assert_eq!(error.category(), Category::SecretRefused);
assert!(
!error.to_string().to_lowercase().contains("password"),
"the refusal must not quote the statement: {error}"
);
}
#[test]
fn a_batch_is_refused_before_its_class_is_even_considered() {
let mut batch = analysis(QueryClass::Mutating);
batch.statement_count = 2;
let error = assert_execute_allowed(&batch, "mem").expect_err("a batch has no WAL record");
assert!(error.to_string().contains("one statement"), "{error}");
}
}