Files
Bedrock/crates/database/src/common.rs
T

172 lines
5.3 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Driver-independent documents, revisions, validation and encoding.
use std::{collections::HashSet, time::Duration};
use serde_json::Value;
use thiserror::Error;
pub type Revision = i64;
pub type Result<T> = std::result::Result<T, Error>;
pub(crate) const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Debug, Error)]
pub enum Error {
#[error("invalid {0}")]
Invalid(&'static str),
#[error("the database connection failed")]
Connection,
#[error("SQLite operation failed: {0}")]
Sqlite(#[from] rusqlite::Error),
#[error("PostgreSQL operation failed: {0}")]
Postgres(#[from] tokio_postgres::Error),
#[error("MySQL operation failed: {0}")]
Mysql(#[from] mysql_async::Error),
#[error("invalid database row")]
InvalidRow,
#[error("document encoding failed: {0}")]
Encoding(#[from] serde_json::Error),
#[error("the connection is read-only")]
ReadOnly,
#[error("the deployment is missing or retired")]
MissingDeployment,
#[error("database is at revision {available}, requested revision {requested}")]
Behind {
requested: Revision,
available: Revision,
},
#[error("the write conflicts with the current revision or lease")]
WriteConflict,
#[error("the workspace document already exists")]
DocumentAlreadyExists,
#[error("lease is missing, expired, or belongs to another store")]
LeaseLost,
}
impl Error {
pub fn retry_on_primary(&self) -> bool {
match self {
Self::Connection | Self::MissingDeployment | Self::Behind { .. } => true,
Self::Postgres(error) => {
error.is_closed()
|| error.code().is_some_and(|code| {
code.code().starts_with("08")
|| matches!(code.code(), "57P01" | "57P03" | "42P01")
})
}
Self::Mysql(mysql_async::Error::Server(error)) => {
error.state.starts_with("08") || error.code == 1146
}
Self::Mysql(error) => error.is_fatal(),
_ => false,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Document {
pub revision: Revision,
pub value: Value,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Snapshot {
pub revision: Revision,
pub document: Option<Document>,
}
#[derive(Clone, Debug)]
pub struct Mutation {
pub collection: String,
pub id: String,
/// None writes a tombstone. Some(Value::Null) stores a JSON null.
pub value: Option<Value>,
}
pub(crate) type EncodedSnapshot = (Revision, Option<Revision>, Option<Vec<u8>>);
pub(crate) struct EncodedMutation<'a> {
pub collection: &'a [u8],
pub id: &'a [u8],
pub payload: Option<Vec<u8>>,
}
pub(crate) fn validate_read(collection: &str, id: &str, at: Option<Revision>) -> Result<()> {
validate_id(collection)?;
validate_id(id)?;
if at.is_some_and(|revision| revision < 0) {
return Err(Error::Invalid("snapshot revision"));
}
Ok(())
}
pub(crate) fn snapshot(row: Option<EncodedSnapshot>, at: Option<Revision>) -> Result<Snapshot> {
let (available, document_revision, payload) = row.ok_or(Error::MissingDeployment)?;
let revision = at.unwrap_or(available);
if revision > available {
return Err(Error::Behind {
requested: revision,
available,
});
}
let document = match (document_revision, payload) {
(Some(revision), Some(payload)) => Some(Document {
revision,
value: serde_json::from_slice(&payload)?,
}),
_ => None,
};
Ok(Snapshot { revision, document })
}
pub(crate) fn encode_batch(
expected: Revision,
mutations: &[Mutation],
) -> Result<(Revision, Vec<EncodedMutation<'_>>)> {
let revision = expected
.checked_add(1)
.filter(|_| expected >= 0)
.ok_or(Error::Invalid("expected revision"))?;
if mutations.is_empty() {
return Err(Error::Invalid("empty write batch"));
}
let mut seen = HashSet::with_capacity(mutations.len());
let mut rows = Vec::with_capacity(mutations.len());
for mutation in mutations {
validate_id(&mutation.collection)?;
validate_id(&mutation.id)?;
if !seen.insert((&mutation.collection, &mutation.id)) {
return Err(Error::Invalid("duplicate document in write batch"));
}
rows.push(EncodedMutation {
collection: mutation.collection.as_bytes(),
id: mutation.id.as_bytes(),
payload: mutation
.value
.as_ref()
.map(serde_json::to_vec)
.transpose()?,
});
}
Ok((revision, rows))
}
pub(crate) fn validate_id(value: &str) -> Result<()> {
if value.is_empty() || value.len() > 128 || value.contains('\0') {
return Err(Error::Invalid(
"identifier (expected 1–128 bytes without NUL)",
));
}
Ok(())
}
// A single statement observes the revision and the document at the same point in time.
pub(crate) const GET_DOCUMENT: &str = "
SELECT d.revision, v.revision, v.payload
FROM bedrock_deployments d
LEFT JOIN bedrock_documents v
ON v.deployment = d.deployment AND v.collection = ? AND v.document_id = ?
AND v.revision <= COALESCE(?, d.revision)
WHERE d.deployment = ? AND d.retired = 0
ORDER BY v.revision DESC LIMIT 1";