9 Commits

39 changed files with 2694 additions and 1508 deletions
Generated
+924 -526
View File
File diff suppressed because it is too large Load Diff
+12 -3
View File
@@ -9,14 +9,23 @@ rust-version = "1.91"
[workspace.dependencies]
clusters = { path = "crates/clusters" }
db = { path = "crates/db" }
documents = { path = "crates/documents" }
deadpool-postgres = "0.14.1"
mysql_async = { version = "0.36.1", default-features = false, features = ["minimal-rust", "ring", "rustls-tls", "tls12"] }
rusqlite = { version = "0.32.1", features = ["bundled"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
rustls-pemfile = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.8.6", default-features = false, features = ["any", "runtime-tokio", "tls-rustls-ring-webpki"] }
serde-saphyr = { version = "2.2", default-features = false, features = ["deserialize", "serialize"] }
toml = "0.9"
tempfile = "3"
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
tokio-postgres = "0.7.18"
tokio-postgres-rustls = { version = "0.13", default-features = false }
tokio-rusqlite = "0.6"
url = "2"
webpki-roots = "1"
[package]
name = "bedrock"
@@ -25,6 +34,6 @@ edition.workspace = true
rust-version.workspace = true
[dependencies]
clusters.workspace = true
db.workspace = true
serde_json.workspace = true
tokio.workspace = true
+5 -18
View File
@@ -4,32 +4,19 @@ Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has i
## Storage boundaries
`db` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `db` connection module selects the SQL driver and read endpoints. The backend modules share the connection pools and transaction implementation in `common.rs`.
`db` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `db` connection module selects the SQL driver and read endpoints. The backend modules share document types, validation, and encoding in `common.rs`.
Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock currently supports selecting a configured SQL cluster and using its read replicas. Workspace sharding, S3 object storage, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake)
Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock supports named SQL roles and read replicas. The catalog can describe S3 buckets. Object I/O, workspace routing, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake)
## Database configuration
Set `BEDROCK_DB_CONFIG` to the path of a private JSON deployment configuration to select a different cluster. For example:
Set `BEDROCK_DB_CONFIG` to a private YAML deployment configuration. See the [multi-storage example](deploy/multi-storage.yaml). TOML and existing JSON files also load through the same configuration model.
```json
{
"deployment": "production",
"cluster": "east",
"clusters": {
"east": {
"driver": "postgres",
"primary": "postgres://bedrock@primary.example.net/bedrock",
"replicas": ["postgres://bedrock_reader@replica.example.net/bedrock"],
"max_connections": 5
}
}
}
```
`clusters` lists SQL connection targets, and `sql` binds roles such as `documents` to those targets. The legacy `cluster` field selects the `documents` role. `object_storage` describes named object stores. The executable logs the configuration version and initializes every configured SQL role at startup.
The database must already exist for PostgreSQL and MySQL. Bedrock creates its own tables and deployment row on a writable startup. Network endpoints use TLS with certificate and hostname verification by default. For a private test database without TLS, set the cluster's `tls` to `"disabled"`. A top-level `"read_only": true` opens an existing deployment without initializing it. A SQLite deployment can set `sqlite_path` to use another file.
Applications connect with `db::connect`. A write batch commits at one new revision if its expected deployment revision still matches. Reads can target the primary or prefer replicas. Use an explicit revision to require that snapshot and fall back when replicas have fallen behind. A tombstone removes a document from subsequent snapshots while preserving earlier revisions. JSON null remains a stored value.
Applications use `db::connect` for the documents role or `db::connect_sql` for an explicitly resolved SQL role. A write batch commits at one new revision if its expected deployment revision still matches. Reads can target the primary or prefer replicas. Use an explicit revision to require that snapshot and fall back when replicas have fallen behind. A tombstone removes a document from subsequent snapshots while preserving earlier revisions. JSON null remains a stored value.
For MySQL, use `Connection::mysql_writer` to acquire, renew or release a writer lease. An active lease blocks ordinary writes. Use `commit_with_lease` while holding it. `delete_deployment` requires an active lease, deletes that deployment's documents and permanently retires its ID in the database.
+23 -1
View File
@@ -2,4 +2,26 @@
`ci/check-sql.sh` runs storage checks against SQLite and temporary PostgreSQL and MySQL containers. Run it from the workspace root on an approved remote runner. It removes its test containers and network on exit.
![Bedrock deployment and manual SQL verification flow](../deploy/bedrock-deployment.svg)
## Automatic deployment
```mermaid
flowchart TD
M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"]
W --> B["build-release.sh 编译发布版"]
B -->|Bedrock 二进制和 Git SHA| R["release.sh 暂存待发布版本"]
R --> P["render-postgres.py 生成私有 bedrock.yaml"]
E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P
P -->|配置就绪| I["临时容器运行 Bedrock,由 Bedrock 初始化 PostgreSQL"]
I -->|成功| S["保存版本并原子切换 current"]
P -->|失败| F["清理暂存目录,保留现有 current"]
I -->|失败| F
```
## Manual SQL checks
```mermaid
flowchart TD
H["在远程 runner 手动运行"] --> C["ci/check-sql.sh 创建临时网络和数据库容器"]
C --> T["测试 SQLite、PostgreSQL 和 MySQL"]
T -->|退出时| U["清理测试容器和临时网络"]
```
+3
View File
@@ -6,5 +6,8 @@ rust-version.workspace = true
[dependencies]
serde.workspace = true
serde_json.workspace = true
serde-saphyr.workspace = true
toml.workspace = true
thiserror.workspace = true
url.workspace = true
+30
View File
@@ -0,0 +1,30 @@
# clusters
`clusters` 负责读取和校验 Bedrock 的部署配置,并解析出各用途的连接参数。
## 模块依赖
箭头从使用方指向定义类型或提供功能的模块。图中省略 `mod` 声明和 `pub use` 导出。
`driver.rs` 集中定义驱动类型,供 SQL 和对象存储配置模块使用。
`sql.rs` 定义 `SqlCluster`,描述 SQL 主库和可选读副本。`catalog.rs` 的 `Resource` 统一表示 SQL 和对象存储资源。
```mermaid
flowchart LR
lib["lib.rs"] -->|解析 SQL 配置| sql["sql.rs"]
lib -->|校验对象存储配置| obj["object_storage.rs"]
sql -->|ConfigError| lib
obj -->|ConfigError| lib
sql -->|SqlDriver| drv["driver.rs"]
obj -->|ObjectStoreDriver| drv
cat["catalog.rs"] -->|为 DeploymentConfig 实现 CRUD| lib
cat -->|统一表示驱动类别| drv
cat -->|编辑 SQL 资源| sql
cat -->|编辑对象存储资源| obj
fmt["format.rs"] -->|读取和输出 DeploymentConfig| lib
fmt -->|导入时调用 insert_resource| cat
```
+88
View File
@@ -0,0 +1,88 @@
use serde::{Deserialize, Serialize};
use crate::{ConfigError, DeploymentConfig, Driver, ObjectStorage, SqlCluster, validate_name};
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Resource {
Sql(SqlCluster),
ObjectStore(ObjectStorage),
}
#[derive(Clone, Copy, Debug)]
pub enum ResourceRef<'a> {
Sql(&'a SqlCluster),
ObjectStore(&'a ObjectStorage),
}
impl ResourceRef<'_> {
pub fn driver(self) -> Driver {
match self {
Self::Sql(cluster) => Driver::Sql(cluster.driver),
Self::ObjectStore(store) => Driver::ObjectStore(store.driver),
}
}
}
impl DeploymentConfig {
pub fn resource(&self, name: &str) -> Option<ResourceRef<'_>> {
self.clusters
.get(name)
.map(ResourceRef::Sql)
.or_else(|| self.object_storage.get(name).map(ResourceRef::ObjectStore))
}
pub fn resources(&self) -> impl Iterator<Item = (&str, ResourceRef<'_>)> {
self.clusters
.iter()
.map(|(name, value)| (name.as_str(), ResourceRef::Sql(value)))
.chain(
self.object_storage
.iter()
.map(|(name, value)| (name.as_str(), ResourceRef::ObjectStore(value))),
)
}
pub fn insert_resource(&mut self, name: String, resource: Resource) -> Result<(), ConfigError> {
if self.resource(&name).is_some() {
return Err(ConfigError::DuplicateResource);
}
self.store_resource(name, resource)
}
pub fn update_resource(&mut self, name: &str, resource: Resource) -> Result<(), ConfigError> {
match (self.resource(name), &resource) {
(None, _) => return Err(ConfigError::MissingResource),
(Some(ResourceRef::Sql(_)), Resource::Sql(_))
| (Some(ResourceRef::ObjectStore(_)), Resource::ObjectStore(_)) => {}
_ => return Err(ConfigError::ResourceCategory),
}
self.store_resource(name.to_owned(), resource)
}
pub fn remove_resource(&mut self, name: &str) -> Result<Resource, ConfigError> {
if self.cluster.as_deref() == Some(name) || self.sql.values().any(|target| target == name) {
return Err(ConfigError::ResourceInUse);
}
self.clusters
.remove(name)
.map(Resource::Sql)
.or_else(|| self.object_storage.remove(name).map(Resource::ObjectStore))
.ok_or(ConfigError::MissingResource)
}
fn store_resource(&mut self, name: String, resource: Resource) -> Result<(), ConfigError> {
validate_name(&name, "resource")?;
match resource {
Resource::Sql(cluster) => {
cluster.resolve(&self.deployment, Some(&name), self.read_only)?;
self.clusters.insert(name, cluster);
}
Resource::ObjectStore(store) => {
store.validate()?;
self.object_storage.insert(name, store);
}
}
Ok(())
}
}
+64
View File
@@ -0,0 +1,64 @@
//! Driver definitions shared by the backend configuration modules.
use serde::{Deserialize, Serialize};
/// Common backend type for catalog lookups in Rust.
///
/// Serialized configuration uses category-specific driver types in its fields.
/// Deriving Serde traits on this enum would also require them on every wrapped type.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Driver {
Sql(SqlDriver),
ObjectStore(ObjectStoreDriver),
// Reserved categories gain Serde traits when their configuration fields are added.
Cache(CacheDriver),
Search(SearchDriver),
EventStream(EventStreamDriver),
BatchCompute(BatchComputeDriver),
OnlineService(OnlineServiceKind),
}
/// The driver in SQL cluster configuration. Serde uses snake_case names such as `postgres`.
/// `SqlDriver::default()` selects `Sqlite`.
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum SqlDriver {
#[default]
Sqlite,
Postgres,
Mysql,
}
/// The driver in object storage configuration. Serde reads and writes `S3` as `s3`.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ObjectStoreDriver {
S3,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CacheDriver {
Redis,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SearchDriver {
OpenSearch,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EventStreamDriver {
Kafka,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BatchComputeDriver {
Spark,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OnlineServiceKind {
Recommendation,
Retrieval,
Ranking,
}
+127
View File
@@ -0,0 +1,127 @@
use std::{collections::BTreeMap, path::Path};
use serde::Deserialize;
use serde::de::DeserializeOwned;
use thiserror::Error;
use crate::{ConfigError, DeploymentConfig, Resource};
#[derive(Clone, Copy, Debug)]
pub enum ConfigFormat {
Yaml,
Toml,
/// Compatibility with previously published deployment files.
Json,
}
#[derive(Clone, Copy, Debug)]
pub enum ImportFormat {
Catalog(ConfigFormat),
/// The bedrock_resources output of terraform output -json.
TerraformOutputs,
/// A ConfigMap carrying a catalog in data["bedrock-resources.yaml"].
KubernetesConfigMap,
}
#[derive(Debug, Error)]
pub enum FormatError {
#[error("configuration filename must end in .yaml, .yml, .toml or .json")]
FileExtension,
#[error("could not read the deployment configuration: {0}")]
Io(#[from] std::io::Error),
// Parser errors may quote connection strings or credentials.
#[error("invalid {0} configuration document")]
Parse(&'static str),
#[error("could not serialize the deployment configuration as YAML")]
Serialize,
#[error("import does not contain a Bedrock resource catalog")]
MissingCatalog,
#[error("publishable deployment configuration requires a valid catalog: {0}")]
Config(#[from] ConfigError),
}
impl ConfigFormat {
fn parse<T: DeserializeOwned>(self, input: &str) -> Result<T, FormatError> {
match self {
Self::Yaml => serde_saphyr::from_str(input).map_err(|_| FormatError::Parse("YAML")),
Self::Toml => toml::from_str(input).map_err(|_| FormatError::Parse("TOML")),
Self::Json => serde_json::from_str(input).map_err(|_| FormatError::Parse("JSON")),
}
}
}
impl DeploymentConfig {
pub fn parse(input: &str, format: ConfigFormat) -> Result<Self, FormatError> {
format.parse(input)
}
pub fn load(path: impl AsRef<Path>) -> Result<Self, FormatError> {
let path = path.as_ref();
let format = match path.extension().and_then(|value| value.to_str()) {
Some("yaml" | "yml") => ConfigFormat::Yaml,
Some("toml") => ConfigFormat::Toml,
Some("json") => ConfigFormat::Json,
_ => return Err(FormatError::FileExtension),
};
Self::parse(&std::fs::read_to_string(path)?, format)
}
/// Serializes the configuration, including any credentials in connection strings.
pub fn to_yaml(&self) -> Result<String, FormatError> {
self.resolve()?;
serde_saphyr::to_string(self).map_err(|_| FormatError::Serialize)
}
/// Imports an inventory atomically. Deployment roles are assigned separately.
pub fn import_resources(
&mut self,
input: &str,
format: ImportFormat,
) -> Result<(), FormatError> {
let resources: BTreeMap<String, Resource> = match format {
ImportFormat::Catalog(format) => format.parse(input)?,
ImportFormat::TerraformOutputs => {
let exports: TerraformOutputs = ConfigFormat::Json.parse(input)?;
exports
.bedrock_resources
.ok_or(FormatError::MissingCatalog)?
.value
}
ImportFormat::KubernetesConfigMap => {
let manifest: ConfigMap = ConfigFormat::Yaml.parse(input)?;
if manifest.kind != "ConfigMap" || manifest.api_version != "v1" {
return Err(FormatError::MissingCatalog);
}
let catalog = manifest
.data
.get("bedrock-resources.yaml")
.ok_or(FormatError::MissingCatalog)?;
ConfigFormat::Yaml.parse(catalog)?
}
};
let mut candidate = self.clone();
for (name, resource) in resources {
candidate.insert_resource(name, resource)?;
}
*self = candidate;
Ok(())
}
}
#[derive(Deserialize)]
struct TerraformOutputs {
bedrock_resources: Option<TerraformOutput>,
}
#[derive(Deserialize)]
struct TerraformOutput {
value: BTreeMap<String, Resource>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ConfigMap {
api_version: String,
kind: String,
data: BTreeMap<String, String>,
}
+105 -160
View File
@@ -1,78 +1,38 @@
use std::{collections::BTreeMap, fmt, path::Path};
//! Runtime configuration and named backend resources for Bedrock.
use serde::Deserialize;
mod catalog;
mod driver;
mod format;
mod object_storage;
mod sql;
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use url::Url;
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Driver {
#[default]
Sqlite,
Postgres,
Mysql,
}
pub use catalog::{Resource, ResourceRef};
pub use driver::*;
pub use format::{ConfigFormat, FormatError, ImportFormat};
pub use object_storage::ObjectStorage;
/// Compatibility name for the SQL cluster configuration.
pub use sql::SqlCluster as Cluster;
pub use sql::{Address, ResolvedSql, SqlCluster, Tls};
#[derive(Clone, Copy, Debug, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Tls {
#[default]
VerifyFull,
Disabled,
}
pub const DOCUMENTS: &str = "documents";
/// A database address may contain credentials.
#[derive(Clone, Deserialize)]
#[serde(transparent)]
pub struct Address(String);
impl From<&str> for Address {
fn from(value: &str) -> Self {
Self(value.to_owned())
}
}
impl From<String> for Address {
fn from(value: String) -> Self {
Self(value)
}
}
impl fmt::Debug for Address {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("Address([redacted])")
}
}
impl Address {
pub fn connection_string(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Cluster {
pub driver: Driver,
pub primary: Address,
#[serde(default)]
pub replicas: Vec<Address>,
#[serde(default)]
pub tls: Tls,
#[serde(default = "default_pool_size")]
pub max_connections: u32,
}
const fn default_pool_size() -> u32 {
5
}
#[derive(Clone, Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct DeploymentConfig {
pub deployment: String,
pub config_version: String,
/// Legacy shorthand for sql.documents.
pub cluster: Option<String>,
pub clusters: BTreeMap<String, Cluster>,
/// Named SQL targets that can be bound to entries in `sql`.
pub clusters: BTreeMap<String, SqlCluster>,
/// SQL role to named cluster.
pub sql: BTreeMap<String, String>,
pub object_storage: BTreeMap<String, ObjectStorage>,
pub read_only: bool,
pub sqlite_path: Address,
}
@@ -81,23 +41,30 @@ impl Default for DeploymentConfig {
fn default() -> Self {
Self {
deployment: "default".into(),
config_version: "local".into(),
cluster: None,
clusters: BTreeMap::new(),
sql: BTreeMap::new(),
object_storage: BTreeMap::new(),
read_only: false,
sqlite_path: "bedrock.sqlite3".into(),
}
}
}
#[derive(Debug)]
/// A validated startup snapshot. The version identifies the configuration release.
#[derive(Clone, Debug)]
pub struct ResolvedDeployment {
pub deployment: String,
pub cluster: Option<String>,
pub driver: Driver,
pub primary: Address,
pub replicas: Vec<Address>,
pub read_only: bool,
pub max_connections: u32,
pub config_version: String,
pub sql: BTreeMap<String, ResolvedSql>,
pub object_storage: BTreeMap<String, ObjectStorage>,
}
impl ResolvedDeployment {
pub fn documents(&self) -> Option<&ResolvedSql> {
self.sql.get(DOCUMENTS)
}
}
#[derive(Debug, Error)]
@@ -108,6 +75,18 @@ pub enum ConfigError {
UnknownCluster,
#[error("a cluster must be selected when clusters are configured")]
ClusterRequired,
#[error("legacy cluster and sql.documents refer to different resources")]
ConflictingDocuments,
#[error("invalid object storage configuration")]
ObjectStorage,
#[error("resource already exists")]
DuplicateResource,
#[error("resource does not exist")]
MissingResource,
#[error("resource is referenced by a SQL binding")]
ResourceInUse,
#[error("a resource update must preserve its category")]
ResourceCategory,
#[error("the database pool size must be greater than zero")]
PoolSize,
#[error("SQLite does not support a replica list")]
@@ -121,46 +100,68 @@ pub enum ConfigError {
impl DeploymentConfig {
pub fn resolve(&self) -> Result<ResolvedDeployment, ConfigError> {
validate_name(&self.deployment, "deployment")?;
let local = Cluster {
driver: Driver::Sqlite,
primary: self.sqlite_path.clone(),
replicas: vec![],
tls: Tls::Disabled,
max_connections: 1,
};
let cluster = match &self.cluster {
Some(name) => {
validate_name(name, "cluster")?;
self.clusters.get(name).ok_or(ConfigError::UnknownCluster)?
validate_name(&self.config_version, "config version")?;
let mut targets = BTreeMap::new();
for (name, cluster) in &self.clusters {
validate_name(name, "cluster")?;
targets.insert(
name.as_str(),
cluster.resolve(&self.deployment, Some(name), self.read_only)?,
);
}
for (name, store) in &self.object_storage {
validate_name(name, "object store")?;
if self.clusters.contains_key(name) {
return Err(ConfigError::DuplicateResource);
}
None if self.clusters.is_empty() => &local,
None => return Err(ConfigError::ClusterRequired),
};
if cluster.max_connections == 0 {
return Err(ConfigError::PoolSize);
store.validate()?;
}
if cluster.driver == Driver::Sqlite && !cluster.replicas.is_empty() {
return Err(ConfigError::SqliteReplicas);
let mut sql = BTreeMap::new();
for (role, target) in &self.sql {
validate_name(role, "SQL role")?;
validate_name(target, "cluster")?;
let settings = targets
.get(target.as_str())
.ok_or(ConfigError::UnknownCluster)?;
sql.insert(role.clone(), settings.clone());
}
if let Some(name) = &self.cluster {
validate_name(name, "cluster")?;
if self.sql.get(DOCUMENTS).is_some_and(|target| target != name) {
return Err(ConfigError::ConflictingDocuments);
}
let settings = targets
.get(name.as_str())
.ok_or(ConfigError::UnknownCluster)?;
sql.insert(DOCUMENTS.into(), settings.clone());
}
if sql.is_empty() {
if !targets.is_empty() {
return Err(ConfigError::ClusterRequired);
}
let local = SqlCluster {
driver: SqlDriver::Sqlite,
primary: self.sqlite_path.clone(),
replicas: vec![],
tls: Tls::Disabled,
max_connections: 1,
};
sql.insert(
DOCUMENTS.into(),
local.resolve(&self.deployment, None, self.read_only)?,
);
}
let primary = resolve_address(cluster, &cluster.primary, self.read_only)?;
let replicas = cluster
.replicas
.iter()
.map(|address| resolve_address(cluster, address, true))
.collect::<Result<_, _>>()?;
Ok(ResolvedDeployment {
deployment: self.deployment.clone(),
cluster: self.cluster.clone(),
driver: cluster.driver,
primary,
replicas,
read_only: self.read_only,
max_connections: cluster.max_connections,
config_version: self.config_version.clone(),
sql,
object_storage: self.object_storage.clone(),
})
}
}
fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> {
pub(crate) fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> {
if value.is_empty()
|| value.len() > 128
|| !value
@@ -171,59 +172,3 @@ fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> {
}
Ok(())
}
fn resolve_address(
cluster: &Cluster,
address: &Address,
read_only: bool,
) -> Result<Address, ConfigError> {
let address = address.connection_string();
let (driver, tls_key, tls_enabled, tls_disabled) = match cluster.driver {
Driver::Sqlite => return sqlite_url(address, read_only),
Driver::Postgres => ("postgres", "sslmode", "verify-full", "disable"),
Driver::Mysql => ("mysql", "ssl-mode", "VERIFY_IDENTITY", "DISABLED"),
};
let mut url = Url::parse(address).map_err(|_| ConfigError::Url(driver))?;
let compatible = url.scheme() == driver || driver == "postgres" && url.scheme() == "postgresql";
if !compatible
|| url.host_str().is_none()
|| url.username().is_empty()
|| url.path().trim_matches('/').is_empty()
|| url.fragment().is_some()
|| url.query_pairs().any(|(key, _)| {
matches!(
key.as_ref(),
"sslmode"
| "ssl-mode"
| "host"
| "hostaddr"
| "port"
| "socket"
| "dbname"
| "options"
)
})
{
return Err(ConfigError::Url(driver));
}
let tls_mode = match cluster.tls {
Tls::VerifyFull => tls_enabled,
Tls::Disabled => tls_disabled,
};
url.query_pairs_mut().append_pair(tls_key, tls_mode);
Ok(Address(url.into()))
}
fn sqlite_url(path: &str, read_only: bool) -> Result<Address, ConfigError> {
if path.is_empty() || path == ":memory:" || path.contains('\0') {
return Err(ConfigError::SqlitePath);
}
let absolute = std::path::absolute(Path::new(path)).map_err(|_| ConfigError::SqlitePath)?;
let file = Url::from_file_path(absolute).map_err(|_| ConfigError::SqlitePath)?;
let file = file
.as_str()
.strip_prefix("file:")
.ok_or(ConfigError::SqlitePath)?;
let mode = if read_only { "ro" } else { "rwc" };
Ok(Address(format!("sqlite:{file}?mode={mode}")))
}
+34
View File
@@ -0,0 +1,34 @@
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{ConfigError, driver::ObjectStoreDriver};
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ObjectStorage {
pub driver: ObjectStoreDriver,
pub bucket: String,
pub region: String,
pub endpoint: Option<String>,
}
impl ObjectStorage {
pub(crate) fn validate(&self) -> Result<(), ConfigError> {
if self.bucket.trim().is_empty() || self.region.trim().is_empty() {
return Err(ConfigError::ObjectStorage);
}
if let Some(endpoint) = &self.endpoint {
let url = Url::parse(endpoint).map_err(|_| ConfigError::ObjectStorage)?;
if !matches!(url.scheme(), "http" | "https")
|| url.host_str().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| url.query().is_some()
|| url.fragment().is_some()
{
return Err(ConfigError::ObjectStorage);
}
}
Ok(())
}
}
+161
View File
@@ -0,0 +1,161 @@
use std::{fmt, path::Path};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{ConfigError, driver::SqlDriver};
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Tls {
#[default]
VerifyFull,
Disabled,
}
/// A database address. Debug output includes the full value, which may contain credentials.
#[derive(Clone, Deserialize, Serialize)]
#[serde(transparent)]
pub struct Address(String);
impl From<&str> for Address {
fn from(value: &str) -> Self {
Self(value.to_owned())
}
}
impl From<String> for Address {
fn from(value: String) -> Self {
Self(value)
}
}
impl fmt::Debug for Address {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, formatter)
}
}
impl Address {
pub fn connection_string(&self) -> &str {
&self.0
}
}
/// A SQL target with a primary connection and optional read replicas.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SqlCluster {
pub driver: SqlDriver,
pub primary: Address,
#[serde(default)]
pub replicas: Vec<Address>,
#[serde(default)]
pub tls: Tls,
#[serde(default = "default_pool_size")]
pub max_connections: u32,
}
const DEFAULT_POOL_SIZE: u32 = 5;
fn default_pool_size() -> u32 {
DEFAULT_POOL_SIZE
}
#[derive(Clone, Debug)]
pub struct ResolvedSql {
pub deployment: String,
pub cluster: Option<String>,
pub driver: SqlDriver,
pub primary: Address,
pub replicas: Vec<Address>,
pub read_only: bool,
pub max_connections: u32,
}
impl SqlCluster {
pub(crate) fn resolve(
&self,
deployment: &str,
name: Option<&str>,
read_only: bool,
) -> Result<ResolvedSql, ConfigError> {
if self.max_connections == 0 {
return Err(ConfigError::PoolSize);
}
if self.driver == SqlDriver::Sqlite && !self.replicas.is_empty() {
return Err(ConfigError::SqliteReplicas);
}
let primary = resolve_address(self, &self.primary, read_only)?;
let replicas = self
.replicas
.iter()
.map(|address| resolve_address(self, address, true))
.collect::<Result<_, _>>()?;
Ok(ResolvedSql {
deployment: deployment.into(),
cluster: name.map(str::to_owned),
driver: self.driver,
primary,
replicas,
read_only,
max_connections: self.max_connections,
})
}
}
fn resolve_address(
cluster: &SqlCluster,
address: &Address,
read_only: bool,
) -> Result<Address, ConfigError> {
let address = address.connection_string();
let (driver, tls_key, tls_enabled, tls_disabled) = match cluster.driver {
SqlDriver::Sqlite => return sqlite_url(address, read_only),
SqlDriver::Postgres => ("postgres", "sslmode", "verify-full", "disable"),
SqlDriver::Mysql => ("mysql", "ssl-mode", "VERIFY_IDENTITY", "DISABLED"),
};
let mut url = Url::parse(address).map_err(|_| ConfigError::Url(driver))?;
let compatible = url.scheme() == driver || driver == "postgres" && url.scheme() == "postgresql";
if !compatible
|| url.host_str().is_none()
|| url.username().is_empty()
|| url.path().trim_matches('/').is_empty()
|| url.fragment().is_some()
|| url.query_pairs().any(|(key, _)| {
matches!(
key.as_ref(),
"sslmode"
| "ssl-mode"
| "host"
| "hostaddr"
| "port"
| "socket"
| "dbname"
| "options"
)
})
{
return Err(ConfigError::Url(driver));
}
let tls_mode = match cluster.tls {
Tls::VerifyFull => tls_enabled,
Tls::Disabled => tls_disabled,
};
url.query_pairs_mut().append_pair(tls_key, tls_mode);
Ok(Address(url.into()))
}
fn sqlite_url(path: &str, read_only: bool) -> Result<Address, ConfigError> {
if path.is_empty() || path == ":memory:" || path.contains('\0') {
return Err(ConfigError::SqlitePath);
}
let absolute = std::path::absolute(Path::new(path)).map_err(|_| ConfigError::SqlitePath)?;
let file = Url::from_file_path(absolute).map_err(|_| ConfigError::SqlitePath)?;
let file = file
.as_str()
.strip_prefix("file:")
.ok_or(ConfigError::SqlitePath)?;
let mode = if read_only { "ro" } else { "rwc" };
Ok(Address(format!("sqlite:{file}?mode={mode}")))
}
+90 -6
View File
@@ -1,15 +1,21 @@
use std::collections::BTreeMap;
use clusters::{Cluster, ConfigError, DeploymentConfig, Driver, Tls};
use clusters::{Address, ConfigError, DeploymentConfig, SqlCluster, SqlDriver, Tls};
#[test]
fn named_cluster_requires_matching_addresses_and_redacts_credentials() {
fn address_debug_formats_the_inner_string() {
let value = "bedrock.sqlite3";
assert_eq!(format!("{:?}", Address::from(value)), format!("{value:?}"));
}
#[test]
fn named_cluster_requires_matching_addresses() {
let mut config = DeploymentConfig {
cluster: Some("regional".into()),
clusters: BTreeMap::from([(
"regional".into(),
Cluster {
driver: Driver::Postgres,
SqlCluster {
driver: SqlDriver::Postgres,
primary: "postgres://user:secret@primary/bedrock".into(),
replicas: vec!["postgresql://reader:secret@replica/bedrock".into()],
tls: Tls::VerifyFull,
@@ -19,6 +25,7 @@ fn named_cluster_requires_matching_addresses_and_redacts_credentials() {
..DeploymentConfig::default()
};
let resolved = config.resolve().unwrap();
let resolved = resolved.documents().unwrap();
assert!(
resolved
.primary
@@ -30,8 +37,6 @@ fn named_cluster_requires_matching_addresses_and_redacts_credentials() {
.connection_string()
.ends_with("sslmode=verify-full")
);
assert!(!format!("{resolved:?}").contains("secret"));
config.clusters.get_mut("regional").unwrap().replicas[0] =
"mysql://user:secret@replica/bedrock".into();
assert!(matches!(
@@ -39,3 +44,82 @@ fn named_cluster_requires_matching_addresses_and_redacts_credentials() {
Err(ConfigError::Url("postgres"))
));
}
#[test]
fn resolves_named_connections_and_round_trips_yaml() {
use clusters::ConfigFormat;
let config = DeploymentConfig::parse(
include_str!("../../../deploy/multi-storage.yaml"),
ConfigFormat::Yaml,
)
.unwrap();
let snapshot = config.resolve().unwrap();
assert_eq!(snapshot.config_version, "example-1");
assert_eq!(snapshot.documents().unwrap().driver, SqlDriver::Postgres);
assert_eq!(snapshot.sql["legacy"].driver, SqlDriver::Mysql);
assert_eq!(
snapshot.object_storage["attachments"].bucket,
"bedrock-attachments"
);
assert_eq!(snapshot.documents().unwrap().max_connections, 5);
let serialized = config.to_yaml().unwrap();
let roundtrip = DeploymentConfig::parse(&serialized, ConfigFormat::Yaml)
.unwrap()
.resolve()
.unwrap();
assert_eq!(roundtrip.sql["legacy"].driver, SqlDriver::Mysql);
}
#[test]
fn imports_catalog_atomically_and_preserves_role_references() {
use clusters::{ConfigFormat, Driver, ImportFormat, ObjectStoreDriver, Resource};
let mut config =
DeploymentConfig::parse("config_version = 'test'", ConfigFormat::Toml).unwrap();
config
.import_resources(
include_str!("../../../deploy/kubernetes-catalog.yaml"),
ImportFormat::KubernetesConfigMap,
)
.unwrap();
config.sql.insert("documents".into(), "pg-main".into());
let before = config.resource("attachments").unwrap().driver();
assert_eq!(before, Driver::ObjectStore(ObjectStoreDriver::S3));
assert!(matches!(
config.remove_resource("pg-main"),
Err(ConfigError::ResourceInUse)
));
let inventory = r#"{
"bedrock_resources": {
"value": {
"another-bucket": {"kind":"object_store","driver":"s3","bucket":"other","region":"us-east-1"},
"attachments": {"kind":"object_store","driver":"s3","bucket":"duplicate","region":"us-east-1"}
}
}
}"#;
assert!(
config
.import_resources(inventory, ImportFormat::TerraformOutputs)
.is_err()
);
assert!(config.resource("another-bucket").is_none());
let Resource::ObjectStore(mut updated) = config.remove_resource("attachments").unwrap() else {
panic!("expected S3 configuration");
};
updated.bucket = "updated".into();
config
.insert_resource("attachments".into(), Resource::ObjectStore(updated.clone()))
.unwrap();
updated.bucket = "replaced".into();
config
.update_resource("attachments", Resource::ObjectStore(updated))
.unwrap();
assert_eq!(
config.resolve().unwrap().object_storage["attachments"].bucket,
"replaced"
);
}
+11 -2
View File
@@ -6,10 +6,19 @@ rust-version.workspace = true
[dependencies]
clusters.workspace = true
documents.workspace = true
deadpool-postgres.workspace = true
mysql_async.workspace = true
rusqlite.workspace = true
rustls.workspace = true
rustls-pemfile.workspace = true
serde_json.workspace = true
sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] }
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
+95 -314
View File
@@ -1,22 +1,29 @@
//! Shared SQL connection pools, documents, snapshots and write transactions.
//! Driver-independent documents, revisions, validation and encoding.
use std::{borrow::Cow, collections::HashSet, fmt::Write, time::Duration};
use std::{collections::HashSet, time::Duration};
use serde_json::Value;
use sqlx::{AnyConnection, AnyPool, Row, any::AnyPoolOptions};
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("SQL operation failed: {0}")]
Sql(#[from] sqlx::Error),
#[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")]
@@ -30,8 +37,6 @@ pub enum Error {
},
#[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,
}
@@ -40,18 +45,17 @@ impl Error {
pub fn retry_on_primary(&self) -> bool {
match self {
Self::Connection | Self::MissingDeployment | Self::Behind { .. } => true,
Self::Sql(error) => match error {
sqlx::Error::Io(_)
| sqlx::Error::Tls(_)
| sqlx::Error::PoolTimedOut
| sqlx::Error::PoolClosed
| sqlx::Error::WorkerCrashed => true,
sqlx::Error::Database(db) => db.code().is_some_and(|code| {
code.starts_with("08")
|| matches!(code.as_ref(), "57P01" | "57P03" | "42P01" | "1146")
}),
_ => false,
},
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,
}
}
@@ -77,272 +81,75 @@ pub struct Mutation {
pub value: Option<Value>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Dialect {
Sqlite,
Postgres,
Mysql,
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>>,
}
/// Opened SQL reader. Its pool is private so callers cannot bypass the read API.
#[derive(Clone)]
pub struct Reader {
pool: AnyPool,
dialect: Dialect,
deployment: Vec<u8>,
}
#[derive(Clone)]
pub struct Store {
reader: Reader,
}
/// Returns a lazily connected pool. The writer initializes schema before use.
#[doc(hidden)]
pub fn pool(dialect: Dialect, url: &str, connections: u32, read_only: bool) -> Result<AnyPool> {
if connections == 0 {
return Err(Error::Invalid("database pool size"));
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"));
}
sqlx::any::install_default_drivers();
let mut options = AnyPoolOptions::new()
.max_connections(connections)
.acquire_timeout(Duration::from_secs(5));
let read_only_statement = match dialect {
Dialect::Sqlite => "PRAGMA query_only = ON",
Dialect::Postgres => "SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY",
Dialect::Mysql => "SET SESSION TRANSACTION READ ONLY",
};
if read_only {
options = options.after_connect(move |connection, _| {
Box::pin(async move {
sqlx::query(read_only_statement).execute(connection).await?;
Ok(())
})
});
}
options.connect_lazy(url).map_err(|_| Error::Connection)
}
impl Reader {
#[doc(hidden)]
pub fn new(pool: AnyPool, dialect: Dialect, deployment: &str) -> Result<Self> {
validate_id(deployment)?;
Ok(Self {
pool,
dialect,
deployment: deployment.as_bytes().to_vec(),
})
}
pub async fn revision(&self) -> Result<Revision> {
let statement = statement(
self.dialect,
"SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0",
);
sqlx::query_scalar(&statement)
.bind(self.deployment.as_slice())
.fetch_optional(&self.pool)
.await
.map_err(connection_error)?
.ok_or(Error::MissingDeployment)
}
/// Fetch at the latest revision or at an exact, previously committed snapshot.
pub async fn get(&self, collection: &str, id: &str, at: Option<Revision>) -> Result<Snapshot> {
validate_id(collection)?;
validate_id(id)?;
if at.is_some_and(|at| at < 0) {
return Err(Error::Invalid("snapshot revision"));
}
// A single statement keeps the revision and document on the same database snapshot.
let statement = statement(
self.dialect,
"
SELECT d.revision AS available, v.revision AS document_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",
);
let row = sqlx::query(&statement)
.bind(collection.as_bytes())
.bind(id.as_bytes())
.bind(at)
.bind(self.deployment.as_slice())
.fetch_optional(&self.pool)
.await
.map_err(connection_error)?
.ok_or(Error::MissingDeployment)?;
let available = row.try_get("available")?;
let revision = at.unwrap_or(available);
if revision > available {
return Err(Error::Behind {
requested: revision,
available,
});
}
let document_revision: Option<Revision> = row.try_get("document_revision")?;
let payload: Option<Vec<u8>> = row.try_get("payload")?;
let document = match (document_revision, payload) {
(Some(revision), Some(payload)) => Some(Document {
revision,
value: serde_json::from_slice(&payload)?,
}),
_ => None,
};
Ok(Snapshot { revision, document })
}
}
impl Store {
#[doc(hidden)]
pub async fn initialize(
pool: AnyPool,
dialect: Dialect,
deployment: &str,
schema: &[&str],
insert_deployment: &str,
) -> Result<Self> {
let reader = Reader::new(pool, dialect, deployment)?;
if dialect == Dialect::Postgres {
// PostgreSQL catalog inserts can race even with IF NOT EXISTS.
let mut transaction = reader.pool.begin().await.map_err(connection_error)?;
sqlx::query("SELECT pg_advisory_xact_lock(1694199371)")
.execute(&mut *transaction)
.await?;
initialize_schema(
&mut transaction,
schema,
insert_deployment,
&reader.deployment,
)
.await?;
transaction.commit().await?;
} else {
let mut connection = reader.pool.acquire().await.map_err(connection_error)?;
initialize_schema(
&mut connection,
schema,
insert_deployment,
&reader.deployment,
)
.await?;
}
reader.revision().await?;
Ok(Self { reader })
}
pub fn reader(&self) -> Reader {
self.reader.clone()
}
pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result<Revision> {
self.commit_with_fence(expected, mutations, None).await
}
#[doc(hidden)]
pub async fn commit_with_fence(
&self,
expected: Revision,
mutations: &[Mutation],
fence: Option<i64>,
) -> Result<Revision> {
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::new();
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"));
}
let payload = mutation
.value
.as_ref()
.map(serde_json::to_vec)
.transpose()?;
rows.push((
mutation.collection.as_bytes(),
mutation.id.as_bytes(),
payload,
));
}
let store = &self.reader;
let mut transaction = store.pool.begin().await.map_err(connection_error)?;
let mut advance = "UPDATE bedrock_deployments SET revision = ? WHERE deployment = ? AND revision = ? AND retired = 0".to_owned();
if store.dialect == Dialect::Mysql {
lock_mysql_deployment(&mut transaction, &store.deployment).await?;
if fence.is_some() {
advance.push_str(" AND lease_epoch = ? AND lease_until > ");
} else {
advance.push_str(" AND lease_until <= ");
}
advance.push_str(MYSQL_NOW);
} else if fence.is_some() {
return Err(Error::Invalid("lease on a database without lease support"));
}
let advance = statement(store.dialect, &advance);
let mut query = sqlx::query(&advance)
.bind(revision)
.bind(store.deployment.as_slice())
.bind(expected);
if let Some(fence) = fence {
query = query.bind(fence);
}
if query.execute(&mut *transaction).await?.rows_affected() != 1 {
return Err(Error::WriteConflict);
}
let insert = statement(
store.dialect,
"
INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload)
VALUES (?, ?, ?, ?, ?)",
);
for (collection, id, payload) in rows {
sqlx::query(&insert)
.bind(store.deployment.as_slice())
.bind(collection)
.bind(id)
.bind(revision)
.bind(payload)
.execute(&mut *transaction)
.await?;
}
transaction.commit().await?;
Ok(revision)
}
}
/// MySQL server time in milliseconds, shared by lease management and fenced writes.
#[doc(hidden)]
pub const MYSQL_NOW: &str = "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS SIGNED)";
/// Lock before reading the database clock. MySQL timestamps are fixed at statement start.
#[doc(hidden)]
pub async fn lock_mysql_deployment(
connection: &mut AnyConnection,
deployment: &[u8],
) -> Result<()> {
sqlx::query_scalar::<_, Revision>(
"SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0 FOR UPDATE",
)
.bind(deployment)
.fetch_optional(connection)
.await?
.ok_or(Error::MissingDeployment)?;
Ok(())
}
fn validate_id(value: &str) -> Result<()> {
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)",
@@ -351,38 +158,12 @@ fn validate_id(value: &str) -> Result<()> {
Ok(())
}
async fn initialize_schema(
connection: &mut AnyConnection,
schema: &[&str],
insert_deployment: &str,
deployment: &[u8],
) -> Result<()> {
for ddl in schema {
sqlx::query(ddl).execute(&mut *connection).await?;
}
sqlx::query(insert_deployment)
.bind(deployment)
.execute(connection)
.await?;
Ok(())
}
fn statement(dialect: Dialect, sql: &str) -> Cow<'_, str> {
if dialect != Dialect::Postgres {
return Cow::Borrowed(sql);
}
let mut parts = sql.split('?');
let mut translated = parts.next().unwrap_or_default().to_owned();
for (index, part) in parts.enumerate() {
let _ = write!(translated, "${}", index + 1);
translated.push_str(part);
}
Cow::Owned(translated)
}
fn connection_error(error: sqlx::Error) -> Error {
match error {
sqlx::Error::Configuration(_) => Error::Connection,
other => Error::Sql(other),
}
}
// 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";
+84 -22
View File
@@ -2,19 +2,22 @@
use std::sync::atomic::{AtomicUsize, Ordering};
use clusters::{Address, ConfigError, DeploymentConfig, Driver, ResolvedDeployment};
use clusters::{Address, ConfigError, DeploymentConfig, ResolvedSql, SqlDriver as Driver};
use thiserror::Error;
use crate::{
common::{Error as StorageError, Mutation, Reader, Revision, Snapshot, Store},
mysql::{self, MySql},
postgres, sqlite,
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(transparent)]
Storage(#[from] StorageError),
}
@@ -29,14 +32,69 @@ pub enum ReadPreference {
PreferReplica,
}
enum Writer {
Sql(Store),
MySql(MySql),
/// 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<Writer>,
writer: Option<Store>,
primary: Reader,
replicas: Vec<Reader>,
next_replica: AtomicUsize,
@@ -44,6 +102,10 @@ pub struct Connection {
pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> {
let config = config.resolve()?;
connect_sql(config.documents().ok_or(ConnectError::MissingDocuments)?).await
}
pub async fn connect_sql(config: &ResolvedSql) -> Result<Connection, ConnectError> {
let writer = if config.read_only {
None
} else {
@@ -51,16 +113,15 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
let name = &config.deployment;
let max = config.max_connections;
Some(match config.driver {
Driver::Sqlite => Writer::Sql(sqlite::connect(url, name).await?),
Driver::Postgres => Writer::Sql(postgres::connect(url, name, max).await?),
Driver::Mysql => Writer::MySql(MySql::connect(url, name, max).await?),
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(Writer::Sql(store)) => store.reader(),
Some(Writer::MySql(store)) => store.reader(),
Some(store) => store.reader(),
None => {
let reader = reader(&config, &config.primary)?;
let reader = reader(config, &config.primary)?;
reader.revision().await?;
reader
}
@@ -68,7 +129,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
let replicas = config
.replicas
.iter()
.map(|address| reader(&config, address))
.map(|address| reader(config, address))
.collect::<Result<_, _>>()?;
Ok(Connection {
driver: config.driver,
@@ -79,13 +140,15 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
})
}
fn reader(config: &ResolvedDeployment, address: &Address) -> Result<Reader, StorageError> {
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),
Driver::Postgres => postgres::reader(url, name, config.max_connections),
Driver::Mysql => mysql::reader(url, name, config.max_connections),
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),
}
}
@@ -129,15 +192,14 @@ impl Connection {
changes: &[Mutation],
) -> Result<Revision, StorageError> {
match &self.writer {
Some(Writer::Sql(store)) => store.commit(expected, changes).await,
Some(Writer::MySql(store)) => store.commit(expected, changes).await,
Some(store) => store.commit(expected, changes).await,
None => Err(StorageError::ReadOnly),
}
}
pub fn mysql_writer(&self) -> Option<&MySql> {
match &self.writer {
Some(Writer::MySql(store)) => Some(store),
Some(Store::Mysql(store)) => Some(store),
_ => None,
}
}
-68
View File
@@ -1,68 +0,0 @@
//! Maps workspace documents onto the versioned SQL store.
//!
//! Within a deployment, the workspace selects a reserved collection prefix plus its ID.
//! The document ID becomes the row key in that collection, and the body is JSON.
use ::documents::{Document, DocumentKey};
use crate::{Connection, Mutation, ReadPreference, Result, Revision, StorageError};
// This collection namespace belongs to the workspace-document adapter.
const 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,
}
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 collection = collection(&document.key);
let id = document.key.document.as_str();
let snapshot = self
.get(&collection, id, None, ReadPreference::Primary)
.await?;
if snapshot.document.is_some() {
return Err(StorageError::DocumentAlreadyExists);
}
self.commit(
snapshot.revision,
&[Mutation {
collection,
id: id.to_owned(),
value: Some(document.body),
}],
)
.await
}
/// Reads the latest state of a workspace document from the primary.
pub async fn get_document(&self, key: &DocumentKey) -> Result<Option<StoredDocument>> {
let snapshot = self
.get(
&collection(key),
key.document.as_str(),
None,
ReadPreference::Primary,
)
.await?;
Ok(snapshot.document.map(|stored| StoredDocument {
document: Document {
key: key.clone(),
body: stored.value,
},
revision: stored.revision,
}))
}
}
fn collection(key: &DocumentKey) -> String {
format!("{COLLECTION_PREFIX}{}", key.workspace.as_str())
}
+9 -10
View File
@@ -2,18 +2,17 @@
mod common;
mod connection;
mod documents;
pub mod mysql;
pub mod postgres;
pub mod sqlite;
pub use self::documents::StoredDocument;
pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls};
pub use connection::{ConnectError, Connection, ReadPreference, connect};
pub use mysql::{Lease, MySql};
pub use common::Error as StorageError;
pub use common::{
Dialect, Document, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Snapshot, Store,
lock_mysql_deployment, pool,
pub use clusters::SqlDriver as Dialect;
pub use clusters::{
Address, Cluster, ConfigError, DeploymentConfig, 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_sql,
};
pub use mysql::{Lease, MySql};
+276 -75
View File
@@ -1,12 +1,19 @@
//! MySQL storage, writer leases and deployment cleanup.
use std::{sync::Arc, time::Duration};
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::{
Dialect, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Store, lock_mysql_deployment,
pool,
CONNECT_TIMEOUT, Error, GET_DOCUMENT, Mutation, Result, Revision, Snapshot, encode_batch,
snapshot, validate_id, validate_read,
};
use sqlx::AnyPool;
const MYSQL_NOW: &str = "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS SIGNED)";
const SCHEMA: &[&str] = &[
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
@@ -29,12 +36,68 @@ const SCHEMA: &[&str] = &[
#[derive(Clone)]
pub struct MySql {
store: Store,
pool: AnyPool,
deployment: Vec<u8>,
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 {
@@ -50,31 +113,34 @@ impl Lease {
impl MySql {
pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result<Self> {
let pool = pool(Dialect::Mysql, url, max_connections, false)?;
let store = Store::initialize(
pool.clone(),
Dialect::Mysql,
deployment,
SCHEMA,
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
ON DUPLICATE KEY UPDATE revision = revision",
)
.await?;
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 {
store,
pool,
deployment: deployment.as_bytes().to_vec(),
reader,
identity: Arc::new(()),
})
}
pub fn reader(&self) -> Reader {
self.store.reader()
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.store.commit(expected, mutations).await
self.commit_with_fence(expected, mutations, None).await
}
pub async fn commit_with_lease(
@@ -83,12 +149,44 @@ impl MySql {
expected: Revision,
mutations: &[Mutation],
) -> Result<Revision> {
let epoch = self.epoch(lease)?;
self.store
.commit_with_fence(expected, mutations, Some(epoch))
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)?;
@@ -98,21 +196,21 @@ impl MySql {
SET lease_epoch = lease_epoch + 1, lease_until = {MYSQL_NOW} + ?
WHERE deployment = ? AND retired = 0 AND lease_until <= {MYSQL_NOW}"
);
let mut transaction = self.pool.begin().await?;
lock_mysql_deployment(&mut transaction, &self.deployment).await?;
let changed = sqlx::query(&update)
.bind(ttl)
.bind(self.deployment.as_slice())
.execute(&mut *transaction)
.await?;
if changed.rows_affected() != 1 {
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 =
sqlx::query_scalar("SELECT lease_epoch FROM bedrock_deployments WHERE deployment = ?")
.bind(self.deployment.as_slice())
.fetch_one(&mut *transaction)
.await?;
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,
@@ -130,15 +228,14 @@ impl MySql {
SET lease_until = GREATEST(lease_until + 1, {MYSQL_NOW} + ?)
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
);
let mut transaction = self.pool.begin().await?;
lock_mysql_deployment(&mut transaction, &self.deployment).await?;
let changed = sqlx::query(&update)
.bind(ttl)
.bind(self.deployment.as_slice())
.bind(epoch)
.execute(&mut *transaction)
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 changed.rows_affected() != 1 {
if transaction.affected_rows() != 1 {
return Err(Error::LeaseLost);
}
transaction.commit().await?;
@@ -147,16 +244,15 @@ impl MySql {
pub async fn release_lease(&self, lease: &Lease) -> Result<bool> {
let epoch = self.epoch(lease)?;
let changed = sqlx::query(
"
UPDATE bedrock_deployments SET lease_until = 0
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > 0",
)
.bind(self.deployment.as_slice())
.bind(epoch)
.execute(&self.pool)
.await?;
Ok(changed.rows_affected() == 1)
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.
@@ -168,22 +264,23 @@ impl MySql {
UPDATE bedrock_deployments SET retired = 1, lease_until = 0
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
);
let mut transaction = self.pool.begin().await?;
lock_mysql_deployment(&mut transaction, &self.deployment).await?;
let changed = sqlx::query(&update)
.bind(self.deployment.as_slice())
.bind(epoch)
.execute(&mut *transaction)
.await?;
if changed.rows_affected() != 1 {
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);
}
let removed = sqlx::query("DELETE FROM bedrock_documents WHERE deployment = ?")
.bind(self.deployment.as_slice())
.execute(&mut *transaction)
transaction
.exec_drop(
"DELETE FROM bedrock_documents WHERE deployment = ?",
(deployment,),
)
.await?;
let removed = transaction.affected_rows();
transaction.commit().await?;
Ok(removed.rows_affected())
Ok(removed)
}
fn epoch(&self, lease: &Lease) -> Result<i64> {
@@ -194,12 +291,116 @@ impl MySql {
}
}
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<Reader> {
Reader::new(
pool(Dialect::Mysql, url, max_connections, true)?,
Dialect::Mysql,
deployment,
)
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> {
+251 -18
View File
@@ -1,6 +1,17 @@
//! PostgreSQL connection pools and the Bedrock document layout.
use crate::common::{Dialect, Reader, Result, Store, pool};
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 (
@@ -18,23 +29,245 @@ const SCHEMA: &[&str] = &[
)",
];
pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result<Store> {
let pool = pool(Dialect::Postgres, url, max_connections, false)?;
Store::initialize(
pool,
Dialect::Postgres,
deployment,
SCHEMA,
"INSERT INTO bedrock_deployments (deployment) VALUES ($1)
ON CONFLICT (deployment) DO NOTHING",
)
.await
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]>,
}
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<Reader> {
Reader::new(
pool(Dialect::Postgres, url, max_connections, true)?,
Dialect::Postgres,
deployment,
)
#[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),
}
}
+183 -18
View File
@@ -1,6 +1,15 @@
//! File-backed Bedrock storage for self-hosted deployments.
use crate::common::{Dialect, Reader, Result, Store, pool};
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 (
@@ -19,23 +28,179 @@ const SCHEMA: &[&str] = &[
)",
];
pub async fn connect(url: &str, deployment: &str) -> Result<Store> {
let pool = pool(Dialect::Sqlite, url, 1, false)?;
Store::initialize(
pool,
Dialect::Sqlite,
deployment,
SCHEMA,
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
ON CONFLICT (deployment) DO NOTHING",
)
.await
#[derive(Clone)]
pub struct SqliteReader {
inner: Arc<Endpoint>,
}
pub fn reader(url: &str, deployment: &str) -> Result<Reader> {
Reader::new(
pool(Dialect::Sqlite, url, 1, true)?,
Dialect::Sqlite,
deployment,
)
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
}
}
+15 -2
View File
@@ -1,7 +1,7 @@
use std::{collections::BTreeMap, env, time::Duration};
use db::{
Cluster, Connection, DeploymentConfig, Driver, Mutation, ReadPreference, StorageError, Tls,
Connection, DeploymentConfig, Driver, Mutation, ReadPreference, SqlCluster, StorageError, Tls,
connect,
};
use serde_json::json;
@@ -20,7 +20,7 @@ fn sql_config(driver: Driver, url: &str, deployment: &str) -> DeploymentConfig {
cluster: Some("test".into()),
clusters: BTreeMap::from([(
"test".into(),
Cluster {
SqlCluster {
driver,
primary: url.into(),
replicas: vec![],
@@ -136,6 +136,19 @@ async fn sqlite_persists_across_reopening_and_enforces_read_only() {
));
}
#[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 config = DeploymentConfig {
read_only: true,
sqlite_path: filename.to_str().unwrap().into(),
..DeploymentConfig::default()
};
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 {
-56
View File
@@ -1,56 +0,0 @@
use db::{DeploymentConfig, StorageError, connect};
use documents::{Document, DocumentId, DocumentKey, WorkspaceId};
use serde_json::json;
fn document(workspace: &str, body: serde_json::Value) -> Document {
Document {
key: DocumentKey {
workspace: WorkspaceId::new(workspace).unwrap(),
document: DocumentId::new("same-id").unwrap(),
},
body,
}
}
#[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 = DeploymentConfig {
sqlite_path: path.to_str().unwrap().into(),
..DeploymentConfig::default()
};
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)
));
}
-9
View File
@@ -1,9 +0,0 @@
[package]
name = "documents"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[dependencies]
serde_json.workspace = true
thiserror.workspace = true
-36
View File
@@ -1,36 +0,0 @@
use serde_json::Value;
use super::{
id::{IdError, validate_id},
workspace::WorkspaceId,
};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DocumentId(String);
impl DocumentId {
pub const MAX_BYTES: usize = 128;
pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
let value = value.into();
validate_id(&value, Self::MAX_BYTES, IdError::Document)?;
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
/// A document ID identifies a document within its workspace.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DocumentKey {
pub workspace: WorkspaceId,
pub document: DocumentId,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Document {
pub key: DocumentKey,
pub body: Value,
}
-20
View File
@@ -1,20 +0,0 @@
use thiserror::Error;
#[derive(Debug, Error, PartialEq, Eq)]
pub enum IdError {
#[error("a workspace ID must contain 1–96 bytes and no NUL")]
Workspace,
#[error("a document ID must contain 1–128 bytes and no NUL")]
Document,
#[error("a user ID must contain 1–128 bytes and no NUL")]
User,
#[error("an organization ID must contain 1–128 bytes and no NUL")]
Organization,
}
pub(super) fn validate_id(value: &str, max_bytes: usize, error: IdError) -> Result<(), IdError> {
if value.is_empty() || value.len() > max_bytes || value.contains('\0') {
return Err(error);
}
Ok(())
}
-13
View File
@@ -1,13 +0,0 @@
//! Logical models for documents, workspaces, users, and organizations.
mod document;
mod id;
mod organization;
mod user;
mod workspace;
pub use document::{Document, DocumentId, DocumentKey};
pub use id::IdError;
pub use organization::{Organization, OrganizationId, OrganizationMembership, OrganizationRole};
pub use user::{User, UserId};
pub use workspace::{Workspace, WorkspaceId};
-42
View File
@@ -1,42 +0,0 @@
use super::{
id::{IdError, validate_id},
user::UserId,
};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct OrganizationId(String);
impl OrganizationId {
pub const MAX_BYTES: usize = 128;
pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
let value = value.into();
validate_id(&value, Self::MAX_BYTES, IdError::Organization)?;
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Organization {
pub id: OrganizationId,
pub name: String,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OrganizationRole {
Owner,
Admin,
Member,
}
/// Links a user to an organization with a role in that organization.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OrganizationMembership {
pub organization_id: OrganizationId,
pub user_id: UserId,
pub role: OrganizationRole,
}
-24
View File
@@ -1,24 +0,0 @@
use super::id::{IdError, validate_id};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct UserId(String);
impl UserId {
pub const MAX_BYTES: usize = 128;
pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
let value = value.into();
validate_id(&value, Self::MAX_BYTES, IdError::User)?;
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct User {
pub id: UserId,
pub display_name: String,
}
-29
View File
@@ -1,29 +0,0 @@
use super::{
id::{IdError, validate_id},
organization::OrganizationId,
};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct WorkspaceId(String);
impl WorkspaceId {
pub const MAX_BYTES: usize = 96;
pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
let value = value.into();
validate_id(&value, Self::MAX_BYTES, IdError::Workspace)?;
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
/// A workspace belongs to one organization and contains documents.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Workspace {
pub id: WorkspaceId,
pub organization_id: OrganizationId,
pub name: String,
}
+31 -6
View File
@@ -1,12 +1,15 @@
# Deployment configuration
Deployments pass the path of a JSON configuration file to the Bedrock executable using `BEDROCK_DB_CONFIG`. The Rust libraries accept structured configuration.
Bedrock reads a YAML deployment file from `BEDROCK_DB_CONFIG`. See [local SQLite](sqlite.yaml) and [multiple SQL roles with S3 settings](multi-storage.yaml). The loader also accepts TOML and existing JSON files.
- **SQLite** uses `deploy/sqlite.json` as a template. Set `sqlite_path` to a persistent, writable volume path.
- **PostgreSQL** injects the Gitea Actions variable values `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE` and `BEDROCK_PG_USER`, and the secret `BEDROCK_PG_PASSWORD`, into the deployment step. Run `python3 deploy/render-postgres.py /path/to/private/bedrock.json --deployment production`. The renderer writes a private file and does not print its contents. Mount that file for the Bedrock service and set `BEDROCK_DB_CONFIG` to the mounted path. The configured database must already exist and the server must present a trusted certificate matching the database address.
- **MySQL** accepts the same cluster shape described in the [storage configuration](../README.md) with `"driver": "mysql"` and a `mysql://` endpoint.
- **SQLite** uses a persistent, writable path for `sqlite_path`.
- **PostgreSQL on the existing host** uses Gitea Actions variables `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE`, `BEDROCK_PG_USER` and secret `BEDROCK_PG_PASSWORD`. The release invokes `python3 deploy/render-postgres.py /path/to/private/bedrock.yaml --deployment production --config-version RELEASE_ID`. The renderer writes a private file. The database must already exist and present a trusted certificate for the selected endpoint.
- **Kubernetes** deploys each database and its Service separately. An in-cluster address can use the Service DNS name, such as `pg-main:5432` in the same namespace. Render the final YAML with deployment credentials, store it in a Secret, mount it into the Bedrock workload and set `BEDROCK_DB_CONFIG` to the mounted file. The [catalog ConfigMap example](kubernetes-catalog.yaml) shows how to package a catalog for the library import API without credentials. Declare the resource kind and driver in the catalog and bind its role in the deployment file. A Service name, port, or Kubernetes object kind alone does not describe the backend or its purpose.
- **Terraform or cloud inventory** can export the chosen endpoints. Map those results into the Bedrock resource schema before importing. `ImportFormat::TerraformOutputs` reads a named `bedrock_resources` output from `terraform output -json`. Generic catalogs use names as keys and the same `kind` fields shown in the Kubernetes example. Role bindings are assigned in the deployment configuration.
Keep `BEDROCK_S3_SECRET_KEY`, `BEDROCK_S3_ENDPOINT`, and `BEDROCK_S3_ACCESS_KEY` scoped to the deployment that consumes object storage. S3 integration is pending. The PostgreSQL renderer and `db` use only SQL configuration.
Publish the same versioned configuration to every instance in a deployment. Use a new configuration version and restart instances to apply changes. Rollouts can temporarily contain two versions. The catalog APIs edit an in-process draft. Publish the validated YAML through the deployment system to apply it across instances.
S3 entries describe endpoints and buckets. Keep access credentials in the deployment's secret store for the eventual object storage client.
Pull requests currently run without an automatic storage check. The optional `ci/check-sql.sh` script uses isolated database containers and generated fixture credentials when run on an approved remote runner.
@@ -14,4 +17,26 @@ Pull requests currently run without an automatic storage check. The optional `ci
Gitea builds a release on `ces-control` when a commit lands on `main`. The deploy step renders the private PostgreSQL configuration and runs the current one-shot Rust storage initializer on the existing `endoleap-dev_default` network. It publishes releases under `/opt/endoleap-infra/bedrock-rust/releases` and switches `/opt/endoleap-infra/bedrock-rust/current` after successful initialization. The Go service retains its own containers and routes.
![Bedrock deployment and manual SQL verification flow](./bedrock-deployment.svg)
### Automatic deployment
```mermaid
flowchart TD
M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"]
W --> B["build-release.sh 编译发布版"]
B -->|Bedrock 二进制和 Git SHA| R["release.sh 暂存待发布版本"]
R --> P["render-postgres.py 生成私有 bedrock.yaml"]
E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P
P -->|配置就绪| I["临时容器运行 Bedrock,由 Bedrock 初始化 PostgreSQL"]
I -->|成功| S["保存版本并原子切换 current"]
P -->|失败| F["清理暂存目录,保留现有 current"]
I -->|失败| F
```
### Manual SQL checks
```mermaid
flowchart TD
H["在远程 runner 手动运行"] --> C["ci/check-sql.sh 创建临时网络和数据库容器"]
C --> T["测试 SQLite、PostgreSQL 和 MySQL"]
T -->|退出时| U["清理测试容器和临时网络"]
```
+1 -1
View File
@@ -65,7 +65,7 @@
<text x="584" y="481" class="detail">和密码 Secret</text>
<rect x="84" y="497" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
<text x="104" y="526" class="code">render-postgres.py</text>
<text x="104" y="547" class="detail">由 release.sh 调用,生成权限为 0600 的 bedrock.json。</text>
<text x="104" y="547" class="detail">由 release.sh 调用,生成权限为 0600 的 bedrock.yaml。</text>
<rect x="84" y="580" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
<text x="104" y="609" class="headline">release.sh 启动临时容器</text>
<text x="104" y="630" class="detail">挂载二进制和配置,运行 Rust bedrock。</text>

Before

Width:  |  Height:  |  Size: 7.4 KiB

After

Width:  |  Height:  |  Size: 7.4 KiB

+16
View File
@@ -0,0 +1,16 @@
# Resource catalog for ImportFormat::KubernetesConfigMap.
apiVersion: v1
kind: ConfigMap
metadata:
name: bedrock-resources
data:
bedrock-resources.yaml: |
pg-main:
kind: sql
driver: postgres
primary: postgres://bedrock@pg-main:5432/bedrock
attachments:
kind: object_store
driver: s3
bucket: bedrock-attachments
region: us-east-1
+18
View File
@@ -0,0 +1,18 @@
# Illustrative service names. Inject deployment credentials before publishing.
deployment: production
config_version: example-1
clusters:
pg-main:
driver: postgres
primary: postgres://bedrock@pg-main:5432/bedrock
mysql-legacy:
driver: mysql
primary: mysql://bedrock@mysql-legacy:3306/legacy
sql:
documents: pg-main
legacy: mysql-legacy
object_storage:
attachments:
driver: s3
bucket: bedrock-attachments
region: us-east-1
+4 -3
View File
@@ -21,16 +21,17 @@ stage=$(mktemp -d "$root/releases/.staging.XXXXXXXX")
cleanup() { rm -rf -- "$stage"; }
trap cleanup EXIT
install -m 755 "$binary" "$stage/bedrock"
python3 "$(dirname "$0")/render-postgres.py" "$stage/bedrock.json" --deployment production
release="$revision.${stage##*.}"
python3 "$(dirname "$0")/render-postgres.py" "$stage/bedrock.yaml" \
--deployment production --config-version "$release"
# The current binary is a one-shot storage initializer. It publishes no ports.
docker run --rm --network "$network" \
--user "$(id -u):$(id -g)" --read-only --cap-drop ALL --security-opt no-new-privileges \
--mount "type=bind,source=$stage,target=/release,readonly" \
-e BEDROCK_DB_CONFIG=/release/bedrock.json \
-e BEDROCK_DB_CONFIG=/release/bedrock.yaml \
debian:bookworm-slim /release/bedrock
release="$revision.${stage##*.}"
# Keep the final release private; only switch current after initialization succeeds.
python3 - "$stage" "$root" "$release" <<'PY'
import os
+15 -12
View File
@@ -45,26 +45,29 @@ def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("output", type=Path)
parser.add_argument("--deployment", default="default")
parser.add_argument("--config-version", default="local")
options = parser.parse_args()
if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.deployment):
parser.error("invalid deployment name")
config = {
"deployment": options.deployment,
"cluster": "postgres",
"clusters": {
"postgres": {
"driver": "postgres",
"primary": database_url(),
}
},
}
if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.config_version):
parser.error("invalid config version")
# JSON quoting is valid for scalars in YAML and handles special characters.
config = (
f"deployment: {json.dumps(options.deployment)}\n"
f"config_version: {json.dumps(options.config_version)}\n"
"sql:\n"
" documents: postgres\n"
"clusters:\n"
" postgres:\n"
" driver: postgres\n"
f" primary: {json.dumps(database_url())}\n"
)
# Write with owner-only permissions, then replace the destination atomically.
file = tempfile.NamedTemporaryFile(mode="w", dir=options.output.parent, delete=False)
try:
with file:
json.dump(config, file, indent=2)
file.write("\n")
file.write(config)
os.replace(file.name, options.output)
finally:
Path(file.name).unlink(missing_ok=True)
-4
View File
@@ -1,4 +0,0 @@
{
"deployment": "default",
"sqlite_path": "bedrock.sqlite3"
}
+3
View File
@@ -0,0 +1,3 @@
deployment: default
config_version: local
sqlite_path: bedrock.sqlite3
+16 -10
View File
@@ -1,19 +1,25 @@
use std::{env, error::Error, fs};
use std::{env, error::Error};
use db::{DeploymentConfig, connect};
use clusters::DeploymentConfig;
use db::connect_sql;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let config = match env::var_os("BEDROCK_DB_CONFIG") {
Some(path) => serde_json::from_slice::<DeploymentConfig>(&fs::read(path)?)?,
Some(path) => DeploymentConfig::load(path)?,
None => DeploymentConfig::default(),
};
let db = connect(&config).await?;
println!(
"Bedrock storage ready ({:?}, revision {}, read-only: {})",
db.driver(),
db.revision().await?,
db.is_read_only()
);
let resolved = config.resolve()?;
for (role, settings) in &resolved.sql {
let connection = connect_sql(settings).await?;
println!(
"Bedrock storage ready (config {}, role {}, {:?}, revision {}, read-only: {})",
resolved.config_version,
role,
connection.driver(),
connection.revision().await?,
connection.is_read_only(),
);
}
Ok(())
}