Rename the db crate to database
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "database"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
clusters.workspace = true
|
||||
deadpool-postgres.workspace = true
|
||||
documents.workspace = true
|
||||
mysql_async.workspace = true
|
||||
rusqlite.workspace = true
|
||||
rustls.workspace = true
|
||||
rustls-pemfile.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio = { workspace = true, features = ["sync", "time"] }
|
||||
tokio-postgres.workspace = true
|
||||
tokio-postgres-rustls.workspace = true
|
||||
tokio-rusqlite.workspace = true
|
||||
url.workspace = true
|
||||
webpki-roots.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
tokio.workspace = true
|
||||
@@ -0,0 +1,171 @@
|
||||
//! 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";
|
||||
@@ -0,0 +1,217 @@
|
||||
//! Deployment bootstrap and read routing.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use clusters::{
|
||||
Address, ConfigError, DOCUMENTS, DeploymentConfig, ResolvedDeployment, ResolvedSql,
|
||||
SqlDriver as Driver,
|
||||
};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
common::{Error as StorageError, Mutation, Revision, Snapshot},
|
||||
mysql::{self, MySql, MySqlReader},
|
||||
postgres::{self, Postgres, PostgresReader},
|
||||
sqlite::{self, Sqlite, SqliteReader},
|
||||
};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ConnectError {
|
||||
#[error(transparent)]
|
||||
Config(#[from] ConfigError),
|
||||
#[error("the documents SQL role is not configured")]
|
||||
MissingDocuments,
|
||||
#[error("the documents role must reference a SQL resource")]
|
||||
InvalidDocuments,
|
||||
#[error(transparent)]
|
||||
Storage(#[from] StorageError),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ReadPreference {
|
||||
/// Read from the primary endpoint.
|
||||
#[default]
|
||||
Primary,
|
||||
/// Try configured replicas in round-robin order, then fall back to the primary.
|
||||
/// Without an explicit snapshot revision a replica may return stale data.
|
||||
PreferReplica,
|
||||
}
|
||||
|
||||
/// A reader backed by the configured database. It exposes no raw SQL connection.
|
||||
#[derive(Clone)]
|
||||
pub enum Reader {
|
||||
Sqlite(SqliteReader),
|
||||
Postgres(PostgresReader),
|
||||
Mysql(MySqlReader),
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
pub async fn revision(&self) -> Result<Revision, StorageError> {
|
||||
match self {
|
||||
Self::Sqlite(reader) => reader.revision().await,
|
||||
Self::Postgres(reader) => reader.revision().await,
|
||||
Self::Mysql(reader) => reader.revision().await,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get(
|
||||
&self,
|
||||
collection: &str,
|
||||
id: &str,
|
||||
at: Option<Revision>,
|
||||
) -> Result<Snapshot, StorageError> {
|
||||
match self {
|
||||
Self::Sqlite(reader) => reader.get(collection, id, at).await,
|
||||
Self::Postgres(reader) => reader.get(collection, id, at).await,
|
||||
Self::Mysql(reader) => reader.get(collection, id, at).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum Store {
|
||||
Sqlite(Sqlite),
|
||||
Postgres(Postgres),
|
||||
Mysql(MySql),
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn reader(&self) -> Reader {
|
||||
match self {
|
||||
Self::Sqlite(store) => Reader::Sqlite(store.reader()),
|
||||
Self::Postgres(store) => Reader::Postgres(store.reader()),
|
||||
Self::Mysql(store) => Reader::Mysql(store.reader()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn commit(
|
||||
&self,
|
||||
expected: Revision,
|
||||
changes: &[Mutation],
|
||||
) -> Result<Revision, StorageError> {
|
||||
match self {
|
||||
Self::Sqlite(store) => store.commit(expected, changes).await,
|
||||
Self::Postgres(store) => store.commit(expected, changes).await,
|
||||
Self::Mysql(store) => store.commit(expected, changes).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Connection {
|
||||
driver: Driver,
|
||||
writer: Option<Store>,
|
||||
primary: Reader,
|
||||
replicas: Vec<Reader>,
|
||||
next_replica: AtomicUsize,
|
||||
}
|
||||
|
||||
pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> {
|
||||
connect_resolved(&config.resolve()?).await
|
||||
}
|
||||
|
||||
pub async fn connect_resolved(config: &ResolvedDeployment) -> Result<Connection, ConnectError> {
|
||||
let resource = config
|
||||
.binding(DOCUMENTS)
|
||||
.ok_or(ConnectError::MissingDocuments)?;
|
||||
connect_sql(resource.as_sql().ok_or(ConnectError::InvalidDocuments)?).await
|
||||
}
|
||||
|
||||
pub async fn connect_sql(config: &ResolvedSql) -> Result<Connection, ConnectError> {
|
||||
let writer = if config.read_only {
|
||||
None
|
||||
} else {
|
||||
let url = config.primary.connection_string();
|
||||
let name = &config.deployment;
|
||||
let max = config.max_connections;
|
||||
Some(match config.driver {
|
||||
Driver::Sqlite => Store::Sqlite(sqlite::connect(url, name).await?),
|
||||
Driver::Postgres => Store::Postgres(postgres::connect(url, name, max).await?),
|
||||
Driver::Mysql => Store::Mysql(MySql::connect(url, name, max).await?),
|
||||
})
|
||||
};
|
||||
let primary = match &writer {
|
||||
Some(store) => store.reader(),
|
||||
None => {
|
||||
let reader = reader(config, &config.primary)?;
|
||||
reader.revision().await?;
|
||||
reader
|
||||
}
|
||||
};
|
||||
let replicas = config
|
||||
.replicas
|
||||
.iter()
|
||||
.map(|address| reader(config, address))
|
||||
.collect::<Result<_, _>>()?;
|
||||
Ok(Connection {
|
||||
driver: config.driver,
|
||||
writer,
|
||||
primary,
|
||||
replicas,
|
||||
next_replica: AtomicUsize::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
fn reader(config: &ResolvedSql, address: &Address) -> Result<Reader, StorageError> {
|
||||
let url = address.connection_string();
|
||||
let name = &config.deployment;
|
||||
match config.driver {
|
||||
Driver::Sqlite => sqlite::reader(url, name).map(Reader::Sqlite),
|
||||
Driver::Postgres => {
|
||||
postgres::reader(url, name, config.max_connections).map(Reader::Postgres)
|
||||
}
|
||||
Driver::Mysql => mysql::reader(url, name, config.max_connections).map(Reader::Mysql),
|
||||
}
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
pub fn driver(&self) -> Driver {
|
||||
self.driver
|
||||
}
|
||||
|
||||
pub fn is_read_only(&self) -> bool {
|
||||
self.writer.is_none()
|
||||
}
|
||||
|
||||
pub async fn revision(&self) -> Result<Revision, StorageError> {
|
||||
self.primary.revision().await
|
||||
}
|
||||
|
||||
pub async fn get(
|
||||
&self,
|
||||
collection: &str,
|
||||
id: &str,
|
||||
at: Option<Revision>,
|
||||
preference: ReadPreference,
|
||||
) -> Result<Snapshot, StorageError> {
|
||||
if preference == ReadPreference::PreferReplica && !self.replicas.is_empty() {
|
||||
let count = self.replicas.len();
|
||||
let start = self.next_replica.fetch_add(1, Ordering::Relaxed) % count;
|
||||
for replica in self.replicas.iter().cycle().skip(start).take(count) {
|
||||
match replica.get(collection, id, at).await {
|
||||
Ok(snapshot) => return Ok(snapshot),
|
||||
Err(error) if error.retry_on_primary() => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
self.primary.get(collection, id, at).await
|
||||
}
|
||||
|
||||
pub async fn commit(
|
||||
&self,
|
||||
expected: Revision,
|
||||
changes: &[Mutation],
|
||||
) -> Result<Revision, StorageError> {
|
||||
match &self.writer {
|
||||
Some(store) => store.commit(expected, changes).await,
|
||||
None => Err(StorageError::ReadOnly),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mysql_writer(&self) -> Option<&MySql> {
|
||||
match &self.writer {
|
||||
Some(Store::Mysql(store)) => Some(store),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Maps workspace documents onto the versioned SQL store.
|
||||
//!
|
||||
//! Within a deployment, the workspace selects a collection and the document ID selects
|
||||
//! a row. The v2 JSON payload stores the parent, position, and typed content.
|
||||
|
||||
use ::documents::{Document, DocumentContent, DocumentId, DocumentKey};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Connection, Mutation, ReadPreference, Result, Revision, StorageError};
|
||||
|
||||
const COLLECTION_PREFIX: &str = "bedrock:workspace-documents:v2:";
|
||||
const LEGACY_COLLECTION_PREFIX: &str = "bedrock:workspace-documents:v1:";
|
||||
|
||||
/// A logical document and the deployment revision at which it was last written.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct StoredDocument {
|
||||
pub document: Document,
|
||||
pub revision: Revision,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct DocumentPayload {
|
||||
parent_id: Option<String>,
|
||||
position: u64,
|
||||
content: DocumentContent,
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
/// Creates a document using the primary snapshot and its expected revision.
|
||||
pub async fn create_document(&self, document: Document) -> Result<Revision> {
|
||||
if self.is_read_only() {
|
||||
return Err(StorageError::ReadOnly);
|
||||
}
|
||||
let (revision, existing) = self.lookup_document(&document.key, None).await?;
|
||||
if existing.is_some() {
|
||||
return Err(StorageError::DocumentAlreadyExists);
|
||||
}
|
||||
|
||||
if let Some(parent) = &document.parent_id {
|
||||
let parent_key = DocumentKey {
|
||||
workspace: document.key.workspace.clone(),
|
||||
document: parent.clone(),
|
||||
};
|
||||
let (_, stored) = self.lookup_document(&parent_key, Some(revision)).await?;
|
||||
if stored.is_none() {
|
||||
return Err(StorageError::Invalid("document parent"));
|
||||
}
|
||||
}
|
||||
|
||||
let value = serde_json::to_value(DocumentPayload {
|
||||
parent_id: document.parent_id.map(|id| id.as_str().to_owned()),
|
||||
position: document.position,
|
||||
content: document.content,
|
||||
})?;
|
||||
self.commit(
|
||||
revision,
|
||||
&[Mutation {
|
||||
collection: collection(COLLECTION_PREFIX, &document.key),
|
||||
id: document.key.document.as_str().to_owned(),
|
||||
value: Some(value),
|
||||
}],
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Reads the latest state of a workspace document from the primary.
|
||||
pub async fn get_document(&self, key: &DocumentKey) -> Result<Option<StoredDocument>> {
|
||||
let (_, document) = self.lookup_document(key, None).await?;
|
||||
Ok(document)
|
||||
}
|
||||
|
||||
async fn lookup_document(
|
||||
&self,
|
||||
key: &DocumentKey,
|
||||
at: Option<Revision>,
|
||||
) -> Result<(Revision, Option<StoredDocument>)> {
|
||||
let id = key.document.as_str();
|
||||
let snapshot = self
|
||||
.get(
|
||||
&collection(COLLECTION_PREFIX, key),
|
||||
id,
|
||||
at,
|
||||
ReadPreference::Primary,
|
||||
)
|
||||
.await?;
|
||||
let revision = snapshot.revision;
|
||||
if let Some(stored) = snapshot.document {
|
||||
let payload: DocumentPayload = serde_json::from_value(stored.value)?;
|
||||
let parent_id = payload
|
||||
.parent_id
|
||||
.map(DocumentId::new)
|
||||
.transpose()
|
||||
.map_err(|_| StorageError::Invalid("stored document parent ID"))?;
|
||||
return Ok((
|
||||
revision,
|
||||
Some(StoredDocument {
|
||||
document: Document {
|
||||
key: key.clone(),
|
||||
parent_id,
|
||||
position: payload.position,
|
||||
content: payload.content,
|
||||
},
|
||||
revision: stored.revision,
|
||||
}),
|
||||
));
|
||||
}
|
||||
|
||||
// Use the same snapshot when looking up a document saved with the original encoding.
|
||||
let legacy = self
|
||||
.get(
|
||||
&collection(LEGACY_COLLECTION_PREFIX, key),
|
||||
id,
|
||||
Some(revision),
|
||||
ReadPreference::Primary,
|
||||
)
|
||||
.await?;
|
||||
Ok((
|
||||
revision,
|
||||
legacy.document.map(|stored| StoredDocument {
|
||||
document: Document::new(key.clone(), DocumentContent::Json(stored.value)),
|
||||
revision: stored.revision,
|
||||
}),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn collection(prefix: &str, key: &DocumentKey) -> String {
|
||||
format!("{prefix}{}", key.workspace.as_str())
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Bedrock's transactional document storage for SQL databases.
|
||||
|
||||
mod common;
|
||||
mod connection;
|
||||
mod documents;
|
||||
pub mod mysql;
|
||||
pub mod postgres;
|
||||
pub mod sqlite;
|
||||
|
||||
pub use self::documents::StoredDocument;
|
||||
pub use clusters::SqlDriver as Dialect;
|
||||
pub use clusters::{
|
||||
Address, Cluster, ConfigError, DeploymentConfig, Resource, SqlCluster, SqlDriver as Driver, Tls,
|
||||
};
|
||||
pub use common::Error as StorageError;
|
||||
pub use common::{Document, Error, Mutation, Result, Revision, Snapshot};
|
||||
pub use connection::{
|
||||
ConnectError, Connection, ReadPreference, Reader, Store, connect, connect_resolved, connect_sql,
|
||||
};
|
||||
pub use mysql::{Lease, MySql};
|
||||
@@ -0,0 +1,412 @@
|
||||
//! MySQL storage, writer leases and deployment cleanup.
|
||||
|
||||
use std::{fmt::Write, path::PathBuf, sync::Arc, time::Duration};
|
||||
|
||||
use mysql_async::{
|
||||
ClientIdentity, Conn, Opts, OptsBuilder, Pool, PoolConstraints, PoolOpts, Row, SslOpts, TxOpts,
|
||||
from_row_opt, prelude::Queryable,
|
||||
};
|
||||
use url::Url;
|
||||
|
||||
use crate::common::{
|
||||
CONNECT_TIMEOUT, Error, GET_DOCUMENT, Mutation, Result, Revision, Snapshot, encode_batch,
|
||||
snapshot, validate_id, validate_read,
|
||||
};
|
||||
|
||||
const MYSQL_NOW: &str = "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS SIGNED)";
|
||||
|
||||
const SCHEMA: &[&str] = &[
|
||||
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
|
||||
deployment VARBINARY(128) PRIMARY KEY,
|
||||
revision BIGINT NOT NULL DEFAULT 0,
|
||||
retired BIGINT NOT NULL DEFAULT 0,
|
||||
lease_epoch BIGINT NOT NULL DEFAULT 0,
|
||||
lease_until BIGINT NOT NULL DEFAULT 0
|
||||
) ENGINE=InnoDB",
|
||||
"CREATE TABLE IF NOT EXISTS bedrock_documents (
|
||||
deployment VARBINARY(128) NOT NULL,
|
||||
collection VARBINARY(128) NOT NULL,
|
||||
document_id VARBINARY(128) NOT NULL,
|
||||
revision BIGINT NOT NULL,
|
||||
payload LONGBLOB,
|
||||
PRIMARY KEY (deployment, collection, document_id, revision),
|
||||
FOREIGN KEY (deployment) REFERENCES bedrock_deployments(deployment)
|
||||
) ENGINE=InnoDB",
|
||||
];
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct MySql {
|
||||
reader: MySqlReader,
|
||||
identity: Arc<()>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct MySqlReader {
|
||||
pool: Pool,
|
||||
deployment: Arc<[u8]>,
|
||||
}
|
||||
|
||||
impl MySqlReader {
|
||||
fn new(url: &str, deployment: &str, max_connections: u32, read_only: bool) -> Result<Self> {
|
||||
validate_id(deployment)?;
|
||||
Ok(Self {
|
||||
pool: Pool::new(connection_options(url, max_connections, read_only)?),
|
||||
deployment: Arc::from(deployment.as_bytes()),
|
||||
})
|
||||
}
|
||||
|
||||
async fn connection(&self) -> Result<Conn> {
|
||||
tokio::time::timeout(CONNECT_TIMEOUT, self.pool.get_conn())
|
||||
.await
|
||||
.map_err(|_| Error::Connection)?
|
||||
.map_err(|_| Error::Connection)
|
||||
}
|
||||
|
||||
pub async fn revision(&self) -> Result<Revision> {
|
||||
let row: Row = self
|
||||
.connection()
|
||||
.await?
|
||||
.exec_first(
|
||||
"SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0",
|
||||
(self.deployment.as_ref(),),
|
||||
)
|
||||
.await?
|
||||
.ok_or(Error::MissingDeployment)?;
|
||||
from_row_opt(row).map_err(|_| Error::InvalidRow)
|
||||
}
|
||||
|
||||
pub async fn get(&self, collection: &str, id: &str, at: Option<Revision>) -> Result<Snapshot> {
|
||||
validate_read(collection, id, at)?;
|
||||
let row: Option<Row> = self
|
||||
.connection()
|
||||
.await?
|
||||
.exec_first(
|
||||
GET_DOCUMENT,
|
||||
(
|
||||
collection.as_bytes(),
|
||||
id.as_bytes(),
|
||||
at,
|
||||
self.deployment.as_ref(),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
let row = row
|
||||
.map(from_row_opt)
|
||||
.transpose()
|
||||
.map_err(|_| Error::InvalidRow)?;
|
||||
snapshot(row, at)
|
||||
}
|
||||
}
|
||||
|
||||
/// The monotonically increasing epoch fences off holders whose lease expired.
|
||||
#[derive(Debug)]
|
||||
pub struct Lease {
|
||||
epoch: i64,
|
||||
issuer: Arc<()>,
|
||||
}
|
||||
|
||||
impl Lease {
|
||||
pub fn epoch(&self) -> i64 {
|
||||
self.epoch
|
||||
}
|
||||
}
|
||||
|
||||
impl MySql {
|
||||
pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result<Self> {
|
||||
let reader = MySqlReader::new(url, deployment, max_connections, false)?;
|
||||
{
|
||||
let mut connection = reader.connection().await?;
|
||||
for ddl in SCHEMA {
|
||||
connection.query_drop(*ddl).await?;
|
||||
}
|
||||
connection
|
||||
.exec_drop(
|
||||
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
|
||||
ON DUPLICATE KEY UPDATE revision = revision",
|
||||
(reader.deployment.as_ref(),),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
reader.revision().await?;
|
||||
Ok(Self {
|
||||
reader,
|
||||
identity: Arc::new(()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn reader(&self) -> MySqlReader {
|
||||
self.reader.clone()
|
||||
}
|
||||
|
||||
/// An ordinary write is allowed while no lease is active.
|
||||
pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result<Revision> {
|
||||
self.commit_with_fence(expected, mutations, None).await
|
||||
}
|
||||
|
||||
pub async fn commit_with_lease(
|
||||
&self,
|
||||
lease: &Lease,
|
||||
expected: Revision,
|
||||
mutations: &[Mutation],
|
||||
) -> Result<Revision> {
|
||||
self.commit_with_fence(expected, mutations, Some(self.epoch(lease)?))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn commit_with_fence(
|
||||
&self,
|
||||
expected: Revision,
|
||||
mutations: &[Mutation],
|
||||
fence: Option<i64>,
|
||||
) -> Result<Revision> {
|
||||
let (revision, rows) = encode_batch(expected, mutations)?;
|
||||
let deployment = self.reader.deployment.as_ref();
|
||||
let mut connection = self.reader.connection().await?;
|
||||
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
|
||||
lock_deployment(&mut transaction, deployment).await?;
|
||||
transaction
|
||||
.exec_drop(
|
||||
format!(
|
||||
"UPDATE bedrock_deployments SET revision = ?
|
||||
WHERE deployment = ? AND revision = ? AND retired = 0
|
||||
AND ((? IS NULL AND lease_until <= {MYSQL_NOW})
|
||||
OR (lease_epoch = ? AND lease_until > {MYSQL_NOW}))"
|
||||
),
|
||||
(revision, deployment, expected, fence, fence),
|
||||
)
|
||||
.await?;
|
||||
if transaction.affected_rows() != 1 {
|
||||
return Err(Error::WriteConflict);
|
||||
}
|
||||
transaction.exec_batch(
|
||||
"INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload)
|
||||
VALUES (?, ?, ?, ?, ?)",
|
||||
rows.into_iter().map(|row| (deployment, row.collection, row.id, revision, row.payload)),
|
||||
).await?;
|
||||
transaction.commit().await?;
|
||||
Ok(revision)
|
||||
}
|
||||
|
||||
/// Acquires an expired or unheld lease using the database clock.
|
||||
pub async fn acquire_lease(&self, ttl: Duration) -> Result<Option<Lease>> {
|
||||
let ttl = lease_millis(ttl)?;
|
||||
let update = format!(
|
||||
"
|
||||
UPDATE bedrock_deployments
|
||||
SET lease_epoch = lease_epoch + 1, lease_until = {MYSQL_NOW} + ?
|
||||
WHERE deployment = ? AND retired = 0 AND lease_until <= {MYSQL_NOW}"
|
||||
);
|
||||
let deployment = self.reader.deployment.as_ref();
|
||||
let mut connection = self.reader.connection().await?;
|
||||
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
|
||||
lock_deployment(&mut transaction, deployment).await?;
|
||||
transaction.exec_drop(update, (ttl, deployment)).await?;
|
||||
if transaction.affected_rows() != 1 {
|
||||
return Ok(None);
|
||||
}
|
||||
let epoch: i64 = transaction
|
||||
.exec_first(
|
||||
"SELECT lease_epoch FROM bedrock_deployments WHERE deployment = ?",
|
||||
(deployment,),
|
||||
)
|
||||
.await?
|
||||
.ok_or(Error::MissingDeployment)?;
|
||||
transaction.commit().await?;
|
||||
Ok(Some(Lease {
|
||||
epoch,
|
||||
issuer: self.identity.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Extends an active lease from the current database time without shortening it.
|
||||
pub async fn renew_lease(&self, lease: &Lease, ttl: Duration) -> Result<()> {
|
||||
let epoch = self.epoch(lease)?;
|
||||
let ttl = lease_millis(ttl)?;
|
||||
let update = format!(
|
||||
"
|
||||
UPDATE bedrock_deployments
|
||||
SET lease_until = GREATEST(lease_until + 1, {MYSQL_NOW} + ?)
|
||||
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
|
||||
);
|
||||
let deployment = self.reader.deployment.as_ref();
|
||||
let mut connection = self.reader.connection().await?;
|
||||
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
|
||||
lock_deployment(&mut transaction, deployment).await?;
|
||||
transaction
|
||||
.exec_drop(update, (ttl, deployment, epoch))
|
||||
.await?;
|
||||
if transaction.affected_rows() != 1 {
|
||||
return Err(Error::LeaseLost);
|
||||
}
|
||||
transaction.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn release_lease(&self, lease: &Lease) -> Result<bool> {
|
||||
let epoch = self.epoch(lease)?;
|
||||
let mut connection = self.reader.connection().await?;
|
||||
connection
|
||||
.exec_drop(
|
||||
"UPDATE bedrock_deployments SET lease_until = 0
|
||||
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > 0",
|
||||
(self.reader.deployment.as_ref(), epoch),
|
||||
)
|
||||
.await?;
|
||||
Ok(connection.affected_rows() == 1)
|
||||
}
|
||||
|
||||
/// Removes only this deployment's documents and retires its identity in one transaction.
|
||||
/// The retained deployment row prevents a restart from recreating the deleted deployment.
|
||||
pub async fn delete_deployment(&self, lease: &Lease) -> Result<u64> {
|
||||
let epoch = self.epoch(lease)?;
|
||||
let update = format!(
|
||||
"
|
||||
UPDATE bedrock_deployments SET retired = 1, lease_until = 0
|
||||
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
|
||||
);
|
||||
let deployment = self.reader.deployment.as_ref();
|
||||
let mut connection = self.reader.connection().await?;
|
||||
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
|
||||
lock_deployment(&mut transaction, deployment).await?;
|
||||
transaction.exec_drop(update, (deployment, epoch)).await?;
|
||||
if transaction.affected_rows() != 1 {
|
||||
return Err(Error::LeaseLost);
|
||||
}
|
||||
transaction
|
||||
.exec_drop(
|
||||
"DELETE FROM bedrock_documents WHERE deployment = ?",
|
||||
(deployment,),
|
||||
)
|
||||
.await?;
|
||||
let removed = transaction.affected_rows();
|
||||
transaction.commit().await?;
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
fn epoch(&self, lease: &Lease) -> Result<i64> {
|
||||
if !Arc::ptr_eq(&self.identity, &lease.issuer) {
|
||||
return Err(Error::LeaseLost);
|
||||
}
|
||||
Ok(lease.epoch)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<MySqlReader> {
|
||||
MySqlReader::new(url, deployment, max_connections, true)
|
||||
}
|
||||
|
||||
// MySQL evaluates the clock at statement start. Take the lock before checking the lease.
|
||||
async fn lock_deployment(
|
||||
transaction: &mut mysql_async::Transaction<'_>,
|
||||
deployment: &[u8],
|
||||
) -> Result<()> {
|
||||
let revision: Option<Revision> = transaction.exec_first(
|
||||
"SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0 FOR UPDATE",
|
||||
(deployment,),
|
||||
).await?;
|
||||
revision.ok_or(Error::MissingDeployment)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn connection_options(address: &str, max_connections: u32, read_only: bool) -> Result<Opts> {
|
||||
if max_connections == 0 {
|
||||
return Err(Error::Invalid("database pool size"));
|
||||
}
|
||||
let mut url = Url::parse(address).map_err(|_| Error::Connection)?;
|
||||
let mut tls = true;
|
||||
let (mut ca, mut cert, mut key) = (None, None, None);
|
||||
let (mut charset, mut collation, mut timezone, mut cache_size) = (None, None, None, None);
|
||||
for (name, value) in url.query_pairs() {
|
||||
match name.as_ref() {
|
||||
"sslmode" | "ssl-mode" => {
|
||||
tls = match value.as_ref() {
|
||||
"DISABLED" => false,
|
||||
"VERIFY_IDENTITY" => true,
|
||||
_ => return Err(Error::Connection),
|
||||
}
|
||||
}
|
||||
"sslca" | "ssl-ca" => ca = Some(PathBuf::from(value.as_ref())),
|
||||
"sslcert" | "ssl-cert" => cert = Some(PathBuf::from(value.as_ref())),
|
||||
"sslkey" | "ssl-key" => key = Some(PathBuf::from(value.as_ref())),
|
||||
"charset" => charset = Some(mysql_identifier(&value)?),
|
||||
"collation" => collation = Some(mysql_identifier(&value)?),
|
||||
"timezone" | "time-zone" => timezone = Some(value.into_owned()),
|
||||
"statement-cache-capacity" => {
|
||||
cache_size = Some(value.parse::<usize>().map_err(|_| Error::Connection)?)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
url.set_query(None);
|
||||
let mut setup = Vec::new();
|
||||
if charset.is_some() || collation.is_some() {
|
||||
let charset = charset.as_deref().unwrap_or("utf8mb4");
|
||||
let names = match collation {
|
||||
Some(collation) => format!("SET NAMES {charset} COLLATE {collation}"),
|
||||
None => format!("SET NAMES {charset}"),
|
||||
};
|
||||
setup.push(names);
|
||||
}
|
||||
if let Some(timezone) = timezone {
|
||||
// A hex literal preserves the configured value without interpolating SQL syntax.
|
||||
let mut encoded = String::new();
|
||||
for byte in timezone.as_bytes() {
|
||||
write!(encoded, "{byte:02x}").expect("writing to a string cannot fail");
|
||||
}
|
||||
setup.push(format!("SET time_zone = X'{encoded}'"));
|
||||
}
|
||||
if read_only {
|
||||
setup.push("SET SESSION TRANSACTION READ ONLY".into());
|
||||
}
|
||||
let constraints =
|
||||
PoolConstraints::new(max_connections.min(8) as usize, max_connections as usize)
|
||||
.ok_or(Error::Invalid("database pool size"))?;
|
||||
let opts = Opts::from_url(url.as_str()).map_err(|_| Error::Connection)?;
|
||||
let mut builder = OptsBuilder::from_opts(opts)
|
||||
.prefer_socket(false)
|
||||
.pool_opts(
|
||||
PoolOpts::new()
|
||||
.with_constraints(constraints)
|
||||
.with_reset_connection(false),
|
||||
)
|
||||
.setup(setup);
|
||||
if let Some(cache_size) = cache_size {
|
||||
builder = builder.stmt_cache_size(cache_size);
|
||||
}
|
||||
if tls {
|
||||
let mut ssl = SslOpts::default();
|
||||
if let Some(ca) = ca {
|
||||
ssl = ssl
|
||||
.with_disable_built_in_roots(true)
|
||||
.with_root_certs(vec![ca.into()]);
|
||||
}
|
||||
match (cert, key) {
|
||||
(Some(cert), Some(key)) => {
|
||||
ssl = ssl.with_client_identity(Some(ClientIdentity::new(cert.into(), key.into())))
|
||||
}
|
||||
(None, None) => {}
|
||||
_ => return Err(Error::Connection),
|
||||
}
|
||||
builder = builder.ssl_opts(Some(ssl));
|
||||
}
|
||||
Ok(builder.into())
|
||||
}
|
||||
|
||||
fn mysql_identifier(value: &str) -> Result<String> {
|
||||
if value.is_empty()
|
||||
|| !value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
|
||||
{
|
||||
return Err(Error::Connection);
|
||||
}
|
||||
Ok(format!("`{value}`"))
|
||||
}
|
||||
|
||||
fn lease_millis(ttl: Duration) -> Result<i64> {
|
||||
let millis = ttl.as_millis();
|
||||
if millis == 0 || millis >= i64::MAX as u128 / 2 {
|
||||
return Err(Error::Invalid("lease duration"));
|
||||
}
|
||||
Ok(millis as i64)
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
//! PostgreSQL connection pools and the Bedrock document layout.
|
||||
|
||||
use std::{fs::File, io::BufReader, path::PathBuf, sync::Arc};
|
||||
|
||||
use deadpool_postgres::{Manager, Pool, Runtime};
|
||||
use rustls::{ClientConfig, RootCertStore};
|
||||
use tokio_postgres::{Config, config::SslMode};
|
||||
use tokio_postgres_rustls::MakeRustlsConnect;
|
||||
use url::Url;
|
||||
|
||||
use crate::common::{
|
||||
CONNECT_TIMEOUT, Error, Mutation, Result, Revision, Snapshot, encode_batch, snapshot,
|
||||
validate_id, validate_read,
|
||||
};
|
||||
|
||||
const SCHEMA: &[&str] = &[
|
||||
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
|
||||
deployment BYTEA PRIMARY KEY,
|
||||
revision BIGINT NOT NULL DEFAULT 0,
|
||||
retired BIGINT NOT NULL DEFAULT 0
|
||||
)",
|
||||
"CREATE TABLE IF NOT EXISTS bedrock_documents (
|
||||
deployment BYTEA NOT NULL REFERENCES bedrock_deployments(deployment),
|
||||
collection BYTEA NOT NULL,
|
||||
document_id BYTEA NOT NULL,
|
||||
revision BIGINT NOT NULL,
|
||||
payload BYTEA,
|
||||
PRIMARY KEY (deployment, collection, document_id, revision)
|
||||
)",
|
||||
];
|
||||
|
||||
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 = $1 AND v.document_id = $2
|
||||
AND v.revision <= COALESCE($3, d.revision)
|
||||
WHERE d.deployment = $4 AND d.retired = 0
|
||||
ORDER BY v.revision DESC LIMIT 1";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PostgresReader {
|
||||
pool: Pool,
|
||||
deployment: Arc<[u8]>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Postgres {
|
||||
reader: PostgresReader,
|
||||
}
|
||||
|
||||
pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result<Postgres> {
|
||||
let reader = PostgresReader::new(url, deployment, max_connections, false)?;
|
||||
{
|
||||
let mut client = reader.client().await?;
|
||||
let transaction = client.transaction().await?;
|
||||
// PostgreSQL catalog inserts can race even with IF NOT EXISTS.
|
||||
transaction
|
||||
.batch_execute("SELECT pg_advisory_xact_lock(1694199371)")
|
||||
.await?;
|
||||
for ddl in SCHEMA {
|
||||
transaction.batch_execute(ddl).await?;
|
||||
}
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO bedrock_deployments (deployment) VALUES ($1)
|
||||
ON CONFLICT (deployment) DO NOTHING",
|
||||
&[&reader.deployment.as_ref()],
|
||||
)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
}
|
||||
reader.revision().await?;
|
||||
Ok(Postgres { reader })
|
||||
}
|
||||
|
||||
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<PostgresReader> {
|
||||
PostgresReader::new(url, deployment, max_connections, true)
|
||||
}
|
||||
|
||||
impl PostgresReader {
|
||||
fn new(url: &str, deployment: &str, max_connections: u32, read_only: bool) -> Result<Self> {
|
||||
validate_id(deployment)?;
|
||||
if max_connections == 0 {
|
||||
return Err(Error::Invalid("database pool size"));
|
||||
}
|
||||
let (config, tls) = connection_options(url, read_only)?;
|
||||
let manager = Manager::new(config, tls);
|
||||
let pool = Pool::builder(manager)
|
||||
.max_size(max_connections as usize)
|
||||
.runtime(Runtime::Tokio1)
|
||||
.wait_timeout(Some(CONNECT_TIMEOUT))
|
||||
.create_timeout(Some(CONNECT_TIMEOUT))
|
||||
.build()
|
||||
.map_err(|_| Error::Connection)?;
|
||||
Ok(Self {
|
||||
pool,
|
||||
deployment: Arc::from(deployment.as_bytes()),
|
||||
})
|
||||
}
|
||||
|
||||
async fn client(&self) -> Result<deadpool_postgres::Client> {
|
||||
self.pool.get().await.map_err(|_| Error::Connection)
|
||||
}
|
||||
|
||||
pub async fn revision(&self) -> Result<Revision> {
|
||||
let client = self.client().await?;
|
||||
let query = client
|
||||
.prepare_cached(
|
||||
"SELECT revision FROM bedrock_deployments WHERE deployment = $1 AND retired = 0",
|
||||
)
|
||||
.await?;
|
||||
let row = client
|
||||
.query_opt(&query, &[&self.deployment.as_ref()])
|
||||
.await?
|
||||
.ok_or(Error::MissingDeployment)?;
|
||||
Ok(row.try_get(0)?)
|
||||
}
|
||||
|
||||
pub async fn get(&self, collection: &str, id: &str, at: Option<Revision>) -> Result<Snapshot> {
|
||||
validate_read(collection, id, at)?;
|
||||
let client = self.client().await?;
|
||||
let query = client.prepare_cached(GET_DOCUMENT).await?;
|
||||
let row = client
|
||||
.query_opt(
|
||||
&query,
|
||||
&[
|
||||
&collection.as_bytes(),
|
||||
&id.as_bytes(),
|
||||
&at,
|
||||
&self.deployment.as_ref(),
|
||||
],
|
||||
)
|
||||
.await?
|
||||
.map(|row| -> Result<_> { Ok((row.try_get(0)?, row.try_get(1)?, row.try_get(2)?)) })
|
||||
.transpose()?;
|
||||
snapshot(row, at)
|
||||
}
|
||||
}
|
||||
|
||||
impl Postgres {
|
||||
pub fn reader(&self) -> PostgresReader {
|
||||
self.reader.clone()
|
||||
}
|
||||
|
||||
pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result<Revision> {
|
||||
let (revision, rows) = encode_batch(expected, mutations)?;
|
||||
let deployment = self.reader.deployment.as_ref();
|
||||
let mut client = self.reader.client().await?;
|
||||
let transaction = client.transaction().await?;
|
||||
let advance = transaction
|
||||
.prepare_cached(
|
||||
"UPDATE bedrock_deployments SET revision = $1
|
||||
WHERE deployment = $2 AND revision = $3 AND retired = 0",
|
||||
)
|
||||
.await?;
|
||||
if transaction
|
||||
.execute(&advance, &[&revision, &deployment, &expected])
|
||||
.await?
|
||||
!= 1
|
||||
{
|
||||
return Err(Error::WriteConflict);
|
||||
}
|
||||
let insert = transaction.prepare_cached(
|
||||
"INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload)
|
||||
VALUES ($1, $2, $3, $4, $5)",
|
||||
).await?;
|
||||
for row in rows {
|
||||
transaction
|
||||
.execute(
|
||||
&insert,
|
||||
&[
|
||||
&deployment,
|
||||
&row.collection,
|
||||
&row.id,
|
||||
&revision,
|
||||
&row.payload,
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
transaction.commit().await?;
|
||||
Ok(revision)
|
||||
}
|
||||
}
|
||||
|
||||
fn connection_options(address: &str, read_only: bool) -> Result<(Config, MakeRustlsConnect)> {
|
||||
let mut url = Url::parse(address).map_err(|_| Error::Connection)?;
|
||||
let mut mode = SslMode::Require;
|
||||
let (mut ca, mut cert, mut key) = (None, None, None);
|
||||
let mut parameters = Vec::new();
|
||||
for (name, value) in url.query_pairs() {
|
||||
match name.as_ref() {
|
||||
"sslmode" | "ssl-mode" => {
|
||||
mode = match value.as_ref() {
|
||||
"disable" => SslMode::Disable,
|
||||
// The rustls connector verifies both the certificate chain and hostname.
|
||||
"verify-full" | "require" => SslMode::Require,
|
||||
_ => return Err(Error::Connection),
|
||||
};
|
||||
}
|
||||
"sslrootcert" | "ssl-root-cert" | "ssl-ca" => ca = Some(PathBuf::from(value.as_ref())),
|
||||
"sslcert" | "ssl-cert" => cert = Some(PathBuf::from(value.as_ref())),
|
||||
"sslkey" | "ssl-key" => key = Some(PathBuf::from(value.as_ref())),
|
||||
"application_name" | "user" | "password" => {
|
||||
parameters.push((name.into_owned(), value.into_owned()))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
url.set_query(None);
|
||||
if !parameters.is_empty() {
|
||||
url.query_pairs_mut().extend_pairs(parameters);
|
||||
}
|
||||
let mut config: Config = url.as_str().parse().map_err(|_| Error::Connection)?;
|
||||
config.ssl_mode(mode).connect_timeout(CONNECT_TIMEOUT);
|
||||
if read_only {
|
||||
config.options("-c default_transaction_read_only=on");
|
||||
}
|
||||
let tls = tls_config(mode, ca, cert, key)?;
|
||||
Ok((config, MakeRustlsConnect::new(tls)))
|
||||
}
|
||||
|
||||
fn tls_config(
|
||||
mode: SslMode,
|
||||
ca: Option<PathBuf>,
|
||||
cert: Option<PathBuf>,
|
||||
key: Option<PathBuf>,
|
||||
) -> Result<ClientConfig> {
|
||||
let open = |path| {
|
||||
File::open(path)
|
||||
.map(BufReader::new)
|
||||
.map_err(|_| Error::Connection)
|
||||
};
|
||||
let mut roots = RootCertStore::empty();
|
||||
if mode != SslMode::Disable {
|
||||
if let Some(path) = ca {
|
||||
let mut file = open(path)?;
|
||||
let mut count = 0;
|
||||
for cert in rustls_pemfile::certs(&mut file) {
|
||||
roots
|
||||
.add(cert.map_err(|_| Error::Connection)?)
|
||||
.map_err(|_| Error::Connection)?;
|
||||
count += 1;
|
||||
}
|
||||
if count == 0 {
|
||||
return Err(Error::Connection);
|
||||
}
|
||||
} else {
|
||||
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
||||
}
|
||||
}
|
||||
let builder =
|
||||
ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|_| Error::Connection)?
|
||||
.with_root_certificates(roots);
|
||||
match (mode, cert, key) {
|
||||
(SslMode::Disable, _, _) | (_, None, None) => Ok(builder.with_no_client_auth()),
|
||||
(_, Some(cert), Some(key)) => {
|
||||
let chain = rustls_pemfile::certs(&mut open(cert)?)
|
||||
.collect::<std::io::Result<Vec<_>>>()
|
||||
.map_err(|_| Error::Connection)?;
|
||||
let key = rustls_pemfile::private_key(&mut open(key)?)
|
||||
.map_err(|_| Error::Connection)?
|
||||
.ok_or(Error::Connection)?;
|
||||
builder
|
||||
.with_client_auth_cert(chain, key)
|
||||
.map_err(|_| Error::Connection)
|
||||
}
|
||||
_ => Err(Error::Connection),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
//! File-backed Bedrock storage for self-hosted deployments.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use rusqlite::{OpenFlags, OptionalExtension, TransactionBehavior, params};
|
||||
use tokio::sync::OnceCell;
|
||||
use tokio_rusqlite::Connection;
|
||||
|
||||
use crate::common::{
|
||||
CONNECT_TIMEOUT, Error, GET_DOCUMENT, Mutation, Result, Revision, Snapshot, encode_batch,
|
||||
snapshot, validate_id, validate_read,
|
||||
};
|
||||
|
||||
const SCHEMA: &[&str] = &[
|
||||
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
|
||||
deployment BLOB PRIMARY KEY NOT NULL,
|
||||
revision INTEGER NOT NULL DEFAULT 0,
|
||||
retired INTEGER NOT NULL DEFAULT 0
|
||||
)",
|
||||
"CREATE TABLE IF NOT EXISTS bedrock_documents (
|
||||
deployment BLOB NOT NULL,
|
||||
collection BLOB NOT NULL,
|
||||
document_id BLOB NOT NULL,
|
||||
revision INTEGER NOT NULL,
|
||||
payload BLOB,
|
||||
PRIMARY KEY (deployment, collection, document_id, revision),
|
||||
FOREIGN KEY (deployment) REFERENCES bedrock_deployments(deployment)
|
||||
)",
|
||||
];
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SqliteReader {
|
||||
inner: Arc<Endpoint>,
|
||||
}
|
||||
|
||||
struct Endpoint {
|
||||
uri: String,
|
||||
flags: OpenFlags,
|
||||
deployment: Vec<u8>,
|
||||
connection: OnceCell<Connection>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Sqlite {
|
||||
reader: SqliteReader,
|
||||
}
|
||||
|
||||
pub async fn connect(url: &str, deployment: &str) -> Result<Sqlite> {
|
||||
let reader = SqliteReader::new(url, deployment, false)?;
|
||||
let deployment = reader.inner.deployment.clone();
|
||||
reader
|
||||
.call(move |connection| {
|
||||
let transaction =
|
||||
connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
for ddl in SCHEMA {
|
||||
transaction.execute_batch(ddl)?;
|
||||
}
|
||||
transaction.execute(
|
||||
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
|
||||
ON CONFLICT (deployment) DO NOTHING",
|
||||
[deployment],
|
||||
)?;
|
||||
transaction.commit()?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
reader.revision().await?;
|
||||
Ok(Sqlite { reader })
|
||||
}
|
||||
|
||||
pub fn reader(url: &str, deployment: &str) -> Result<SqliteReader> {
|
||||
SqliteReader::new(url, deployment, true)
|
||||
}
|
||||
|
||||
impl SqliteReader {
|
||||
fn new(url: &str, deployment: &str, read_only: bool) -> Result<Self> {
|
||||
validate_id(deployment)?;
|
||||
let address = url.strip_prefix("sqlite:").ok_or(Error::Connection)?;
|
||||
let address = address.strip_prefix("//").unwrap_or(address);
|
||||
let mut flags = OpenFlags::SQLITE_OPEN_URI | OpenFlags::SQLITE_OPEN_NO_MUTEX;
|
||||
let uri = if read_only {
|
||||
flags |= OpenFlags::SQLITE_OPEN_READ_ONLY;
|
||||
let (path, query) = address.split_once('?').unwrap_or((address, ""));
|
||||
let options =
|
||||
url::form_urlencoded::parse(query.as_bytes()).filter(|(key, _)| key != "mode");
|
||||
let query = url::form_urlencoded::Serializer::new(String::new())
|
||||
.extend_pairs(options)
|
||||
.append_pair("mode", "ro")
|
||||
.finish();
|
||||
format!("file:{path}?{query}")
|
||||
} else {
|
||||
flags |= OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE;
|
||||
if address == ":memory:" {
|
||||
address.to_owned()
|
||||
} else {
|
||||
format!("file:{address}")
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
inner: Arc::new(Endpoint {
|
||||
uri,
|
||||
flags,
|
||||
deployment: deployment.as_bytes().to_vec(),
|
||||
connection: OnceCell::new(),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
async fn call<T: Send + 'static>(
|
||||
&self,
|
||||
operation: impl FnOnce(&mut rusqlite::Connection) -> Result<T> + Send + 'static,
|
||||
) -> Result<T> {
|
||||
let connection = self
|
||||
.inner
|
||||
.connection
|
||||
.get_or_try_init(|| async {
|
||||
let connection = Connection::open_with_flags(&self.inner.uri, self.inner.flags)
|
||||
.await
|
||||
.map_err(|_| Error::Connection)?;
|
||||
connection
|
||||
.call(|connection| {
|
||||
connection.busy_timeout(CONNECT_TIMEOUT)?;
|
||||
connection.pragma_update(None, "foreign_keys", "ON")?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|_| Error::Connection)?;
|
||||
Ok::<_, Error>(connection)
|
||||
})
|
||||
.await?;
|
||||
connection
|
||||
.call(move |connection| Ok(operation(connection)))
|
||||
.await
|
||||
.map_err(|_| Error::Connection)?
|
||||
}
|
||||
|
||||
pub async fn revision(&self) -> Result<Revision> {
|
||||
let deployment = self.inner.deployment.clone();
|
||||
self.call(move |connection| {
|
||||
connection
|
||||
.prepare_cached(
|
||||
"SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0",
|
||||
)?
|
||||
.query_row([deployment], |row| row.get(0))
|
||||
.optional()?
|
||||
.ok_or(Error::MissingDeployment)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get(&self, collection: &str, id: &str, at: Option<Revision>) -> Result<Snapshot> {
|
||||
validate_read(collection, id, at)?;
|
||||
let collection = collection.as_bytes().to_vec();
|
||||
let id = id.as_bytes().to_vec();
|
||||
let deployment = self.inner.deployment.clone();
|
||||
let row = self
|
||||
.call(move |connection| {
|
||||
Ok(connection
|
||||
.prepare_cached(GET_DOCUMENT)?
|
||||
.query_row(params![collection, id, at, deployment], |row| {
|
||||
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
|
||||
})
|
||||
.optional()?)
|
||||
})
|
||||
.await?;
|
||||
snapshot(row, at)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sqlite {
|
||||
pub fn reader(&self) -> SqliteReader {
|
||||
self.reader.clone()
|
||||
}
|
||||
|
||||
pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result<Revision> {
|
||||
let (revision, rows) = encode_batch(expected, mutations)?;
|
||||
let rows: Vec<_> = rows
|
||||
.into_iter()
|
||||
.map(|row| (row.collection.to_vec(), row.id.to_vec(), row.payload))
|
||||
.collect();
|
||||
let deployment = self.reader.inner.deployment.clone();
|
||||
self.reader
|
||||
.call(move |connection| {
|
||||
let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let advanced = transaction.prepare_cached(
|
||||
"UPDATE bedrock_deployments SET revision = ?
|
||||
WHERE deployment = ? AND revision = ? AND retired = 0",
|
||||
)?.execute(params![revision, deployment, expected])?;
|
||||
if advanced != 1 {
|
||||
return Err(Error::WriteConflict);
|
||||
}
|
||||
{
|
||||
let mut insert = transaction.prepare_cached(
|
||||
"INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload)
|
||||
VALUES (?, ?, ?, ?, ?)",
|
||||
)?;
|
||||
for (collection, id, payload) in rows {
|
||||
insert.execute(params![deployment, collection, id, revision, payload])?;
|
||||
}
|
||||
}
|
||||
transaction.commit()?;
|
||||
Ok(revision)
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
use std::{collections::BTreeMap, env, time::Duration};
|
||||
|
||||
use database::{
|
||||
Connection, DeploymentConfig, Driver, Mutation, ReadPreference, Resource, SqlCluster,
|
||||
StorageError, Tls, connect,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
fn change(id: &str, text: &str) -> Mutation {
|
||||
Mutation {
|
||||
collection: "notes".into(),
|
||||
id: id.into(),
|
||||
value: Some(json!({ "text": text })),
|
||||
}
|
||||
}
|
||||
|
||||
fn sql_config(driver: Driver, url: &str, deployment: &str) -> DeploymentConfig {
|
||||
DeploymentConfig {
|
||||
deployment: deployment.into(),
|
||||
bindings: BTreeMap::from([("documents".into(), "test".into())]),
|
||||
resources: BTreeMap::from([(
|
||||
"test".into(),
|
||||
Resource::Sql(SqlCluster {
|
||||
driver,
|
||||
primary: url.into(),
|
||||
replicas: vec![],
|
||||
tls: Tls::Disabled,
|
||||
max_connections: 4,
|
||||
}),
|
||||
)]),
|
||||
..DeploymentConfig::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn test_url(variable: &str) -> Option<String> {
|
||||
match env::var(variable) {
|
||||
Ok(url) => Some(url),
|
||||
Err(_) if env::var_os("BEDROCK_REQUIRE_SQL_TESTS").is_some() => {
|
||||
panic!("{variable} is required for the remote storage checks")
|
||||
}
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_document_contract(db: &Connection) {
|
||||
assert_eq!(db.revision().await.unwrap(), 0);
|
||||
let original = change("doc", "first");
|
||||
assert_eq!(db.commit(0, &[original]).await.unwrap(), 1);
|
||||
|
||||
let duplicate = [
|
||||
change("other", "never written"),
|
||||
change("other", "duplicate"),
|
||||
];
|
||||
assert!(matches!(
|
||||
db.commit(1, &duplicate).await,
|
||||
Err(StorageError::Invalid(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
db.commit(0, &[change("other", "stale")]).await,
|
||||
Err(StorageError::WriteConflict)
|
||||
));
|
||||
|
||||
let second = [change("doc", "second")];
|
||||
let alternative = [change("doc", "alternative")];
|
||||
let (one, two) = tokio::join!(db.commit(1, &second), db.commit(1, &alternative));
|
||||
assert!(matches!(
|
||||
(&one, &two),
|
||||
(Ok(2), Err(StorageError::WriteConflict)) | (Err(StorageError::WriteConflict), Ok(2))
|
||||
));
|
||||
|
||||
let old = db
|
||||
.get("notes", "doc", Some(1), ReadPreference::Primary)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(old.document.unwrap().value, json!({ "text": "first" }));
|
||||
assert!(matches!(
|
||||
db.get("notes", "doc", Some(3), ReadPreference::Primary)
|
||||
.await,
|
||||
Err(StorageError::Behind {
|
||||
requested: 3,
|
||||
available: 2
|
||||
})
|
||||
));
|
||||
assert!(
|
||||
db.get("notes", "other", None, ReadPreference::Primary)
|
||||
.await
|
||||
.unwrap()
|
||||
.document
|
||||
.is_none()
|
||||
);
|
||||
|
||||
let tombstone = Mutation {
|
||||
collection: "notes".into(),
|
||||
id: "doc".into(),
|
||||
value: None,
|
||||
};
|
||||
let null_document = Mutation {
|
||||
collection: "notes".into(),
|
||||
id: "null".into(),
|
||||
value: Some(json!(null)),
|
||||
};
|
||||
assert_eq!(db.commit(2, &[tombstone, null_document]).await.unwrap(), 3);
|
||||
assert!(
|
||||
db.get("notes", "doc", None, ReadPreference::Primary)
|
||||
.await
|
||||
.unwrap()
|
||||
.document
|
||||
.is_none()
|
||||
);
|
||||
let null_document = db
|
||||
.get("notes", "null", None, ReadPreference::Primary)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(null_document.document.unwrap().value, json!(null));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlite_persists_across_reopening_and_enforces_read_only() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let filename = folder.path().join("bedrock +?#%.sqlite");
|
||||
let mut config = sql_config(Driver::Sqlite, filename.to_str().unwrap(), "default");
|
||||
let db = connect(&config).await.unwrap();
|
||||
assert_eq!(db.driver(), Driver::Sqlite);
|
||||
check_document_contract(&db).await;
|
||||
drop(db);
|
||||
config.read_only = true;
|
||||
let db = connect(&config).await.unwrap();
|
||||
assert_eq!(db.revision().await.unwrap(), 3);
|
||||
assert!(db.is_read_only());
|
||||
assert!(matches!(
|
||||
db.commit(3, &[change("doc", "invalid")]).await,
|
||||
Err(StorageError::ReadOnly)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlite_read_only_startup_does_not_create_a_database() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let filename = folder.path().join("missing.sqlite");
|
||||
let mut config = sql_config(Driver::Sqlite, filename.to_str().unwrap(), "default");
|
||||
config.read_only = true;
|
||||
assert!(connect(&config).await.is_err());
|
||||
assert!(!filename.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn postgres_reads_replicas_and_falls_back_when_behind() {
|
||||
let Some(url) = test_url("BEDROCK_TEST_POSTGRES") else {
|
||||
return;
|
||||
};
|
||||
let replica_url = test_url("BEDROCK_TEST_POSTGRES_REPLICA").unwrap();
|
||||
let mut config = sql_config(Driver::Postgres, &url, "pg_contract");
|
||||
let Some(Resource::Sql(cluster)) = config.resources.get_mut("test") else {
|
||||
panic!("expected a SQL resource");
|
||||
};
|
||||
cluster.replicas.push(replica_url.clone().into());
|
||||
let replica = connect(&sql_config(Driver::Postgres, &replica_url, "pg_contract"))
|
||||
.await
|
||||
.unwrap();
|
||||
let (db, concurrent) = tokio::join!(connect(&config), connect(&config));
|
||||
let db = db.unwrap();
|
||||
assert_eq!(concurrent.unwrap().revision().await.unwrap(), 0);
|
||||
check_document_contract(&db).await;
|
||||
replica
|
||||
.commit(0, &[change("doc", "replica")])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let stale = db
|
||||
.get("notes", "doc", None, ReadPreference::PreferReplica)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(stale.revision, 1);
|
||||
assert_eq!(stale.document.unwrap().value, json!({ "text": "replica" }));
|
||||
let fresh = db
|
||||
.get("notes", "null", Some(3), ReadPreference::PreferReplica)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(fresh.revision, 3);
|
||||
assert_eq!(fresh.document.unwrap().value, json!(null));
|
||||
|
||||
config.read_only = true;
|
||||
let db = connect(&config).await.unwrap();
|
||||
assert!(db.is_read_only());
|
||||
assert_eq!(db.revision().await.unwrap(), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mysql_fences_writers_and_cleans_only_one_deployment() {
|
||||
let Some(url) = test_url("BEDROCK_TEST_MYSQL") else {
|
||||
return;
|
||||
};
|
||||
let config = sql_config(Driver::Mysql, &url, "mysql_contract");
|
||||
let db = connect(&config).await.unwrap();
|
||||
check_document_contract(&db).await;
|
||||
let other = connect(&sql_config(Driver::Mysql, &url, "mysql_other"))
|
||||
.await
|
||||
.unwrap();
|
||||
other.commit(0, &[change("doc", "keep")]).await.unwrap();
|
||||
|
||||
let mysql = db.mysql_writer().unwrap();
|
||||
let lease = mysql
|
||||
.acquire_lease(Duration::from_secs(30))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(
|
||||
mysql
|
||||
.acquire_lease(Duration::from_secs(30))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert!(matches!(
|
||||
db.commit(3, &[change("doc", "blocked")]).await,
|
||||
Err(StorageError::WriteConflict)
|
||||
));
|
||||
assert!(matches!(
|
||||
other
|
||||
.mysql_writer()
|
||||
.unwrap()
|
||||
.delete_deployment(&lease)
|
||||
.await,
|
||||
Err(StorageError::LeaseLost)
|
||||
));
|
||||
mysql
|
||||
.renew_lease(&lease, Duration::from_secs(30))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
mysql
|
||||
.commit_with_lease(&lease, 3, &[change("doc", "leased")])
|
||||
.await
|
||||
.unwrap(),
|
||||
4
|
||||
);
|
||||
assert!(mysql.release_lease(&lease).await.unwrap());
|
||||
let next = mysql
|
||||
.acquire_lease(Duration::from_secs(30))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(next.epoch() > lease.epoch());
|
||||
assert!(matches!(
|
||||
mysql
|
||||
.commit_with_lease(&lease, 4, &[change("doc", "stale")])
|
||||
.await,
|
||||
Err(StorageError::WriteConflict)
|
||||
));
|
||||
assert!(mysql.delete_deployment(&next).await.unwrap() > 0);
|
||||
assert!(matches!(
|
||||
db.revision().await,
|
||||
Err(StorageError::MissingDeployment)
|
||||
));
|
||||
assert!(connect(&config).await.is_err());
|
||||
assert_eq!(
|
||||
other
|
||||
.get("notes", "doc", None, ReadPreference::Primary)
|
||||
.await
|
||||
.unwrap()
|
||||
.document
|
||||
.unwrap()
|
||||
.value,
|
||||
json!({ "text": "keep" })
|
||||
);
|
||||
let mut other_config = sql_config(Driver::Mysql, &url, "mysql_other");
|
||||
other_config.read_only = true;
|
||||
assert_eq!(
|
||||
connect(&other_config)
|
||||
.await
|
||||
.unwrap()
|
||||
.revision()
|
||||
.await
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
|
||||
use database::{
|
||||
DeploymentConfig, Driver, Mutation, Resource, SqlCluster, StorageError, Tls, connect,
|
||||
};
|
||||
use documents::{
|
||||
Contextualize, Document, DocumentContent, DocumentId, DocumentKey, DocumentTree, WorkspaceId,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
fn document(workspace: &str, body: serde_json::Value) -> Document {
|
||||
Document::new(
|
||||
DocumentKey {
|
||||
workspace: WorkspaceId::new(workspace).unwrap(),
|
||||
document: DocumentId::new("same-id").unwrap(),
|
||||
},
|
||||
DocumentContent::Json(body),
|
||||
)
|
||||
}
|
||||
|
||||
fn sqlite_config(path: &Path) -> DeploymentConfig {
|
||||
DeploymentConfig {
|
||||
resources: BTreeMap::from([(
|
||||
"local".into(),
|
||||
Resource::Sql(SqlCluster {
|
||||
driver: Driver::Sqlite,
|
||||
primary: path.to_str().unwrap().into(),
|
||||
replicas: vec![],
|
||||
tls: Tls::Disabled,
|
||||
max_connections: 1,
|
||||
}),
|
||||
)]),
|
||||
bindings: BTreeMap::from([("documents".into(), "local".into())]),
|
||||
..DeploymentConfig::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn workspace_documents_keep_their_identity_and_contents_after_reopen() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let path = folder.path().join("documents.sqlite3");
|
||||
let mut config = sqlite_config(&path);
|
||||
let connection = connect(&config).await.unwrap();
|
||||
let first = document(
|
||||
&"w".repeat(WorkspaceId::MAX_BYTES),
|
||||
json!({"title": "notes"}),
|
||||
);
|
||||
let second = document("other-workspace", json!(null));
|
||||
|
||||
assert!(connection.get_document(&first.key).await.unwrap().is_none());
|
||||
let first_revision = connection.create_document(first.clone()).await.unwrap();
|
||||
let second_revision = connection.create_document(second.clone()).await.unwrap();
|
||||
assert!(second_revision > first_revision);
|
||||
assert!(matches!(
|
||||
connection
|
||||
.create_document(document(first.key.workspace.as_str(), json!("overwrite")))
|
||||
.await,
|
||||
Err(StorageError::DocumentAlreadyExists)
|
||||
));
|
||||
drop(connection);
|
||||
|
||||
config.read_only = true;
|
||||
let connection = connect(&config).await.unwrap();
|
||||
let read = connection.get_document(&first.key).await.unwrap().unwrap();
|
||||
assert_eq!(read.document, first);
|
||||
assert_eq!(read.revision, first_revision);
|
||||
let read = connection.get_document(&second.key).await.unwrap().unwrap();
|
||||
assert_eq!(read.document, second);
|
||||
assert_eq!(read.revision, second_revision);
|
||||
assert!(matches!(
|
||||
connection
|
||||
.create_document(document("third-workspace", json!(null)))
|
||||
.await,
|
||||
Err(StorageError::ReadOnly)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn persists_typed_nodes_and_reads_the_original_json_encoding() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let path = folder.path().join("documents.sqlite3");
|
||||
let connection = connect(&sqlite_config(&path)).await.unwrap();
|
||||
|
||||
let page = Document::new(
|
||||
document("team", json!(null)).key,
|
||||
DocumentContent::Page {
|
||||
title: "Planning".into(),
|
||||
},
|
||||
);
|
||||
let mut todo = page.clone();
|
||||
todo.key.document = DocumentId::new("todo").unwrap();
|
||||
todo.parent_id = Some(page.key.document.clone());
|
||||
todo.position = 2;
|
||||
todo.content = DocumentContent::Todo {
|
||||
text: "Review".into(),
|
||||
checked: true,
|
||||
};
|
||||
|
||||
assert!(matches!(
|
||||
connection.create_document(todo.clone()).await,
|
||||
Err(StorageError::Invalid("document parent"))
|
||||
));
|
||||
connection.create_document(page.clone()).await.unwrap();
|
||||
connection.create_document(todo.clone()).await.unwrap();
|
||||
let read = connection.get_document(&todo.key).await.unwrap().unwrap();
|
||||
assert_eq!(read.document, todo);
|
||||
let tree = DocumentTree::new(page, [read.document]).unwrap();
|
||||
assert_eq!(tree.render_context(), "# Planning\n- [x] Review");
|
||||
|
||||
let legacy = document("legacy", json!({"previous": "body"}));
|
||||
connection
|
||||
.commit(
|
||||
connection.revision().await.unwrap(),
|
||||
&[Mutation {
|
||||
collection: "bedrock:workspace-documents:v1:legacy".into(),
|
||||
id: legacy.key.document.as_str().into(),
|
||||
value: Some(json!({"previous": "body"})),
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
connection
|
||||
.get_document(&legacy.key)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.document,
|
||||
legacy
|
||||
);
|
||||
assert!(matches!(
|
||||
connection.create_document(legacy).await,
|
||||
Err(StorageError::DocumentAlreadyExists)
|
||||
));
|
||||
}
|
||||
Reference in New Issue
Block a user