Share address and TLS types across backend configurations

This commit is contained in:
2026-11-30 18:39:52 +08:00
parent 69513d9ffb
commit 8707eb87b6
6 changed files with 119 additions and 56 deletions
+4
View File
@@ -4,6 +4,8 @@
`resources` 存放按名称索引的资源,`bindings` 把用途绑定到资源名。目录增删改查使用同一套接口。资源枚举将具体校验和解析交给对应的后端模块。 `resources` 存放按名称索引的资源,`bindings` 把用途绑定到资源名。目录增删改查使用同一套接口。资源枚举将具体校验和解析交给对应的后端模块。
`transport.rs` 提供共享的 `Address` 和 `Tls`。SQL 通过 `tls` 字段配置 TLS,S3 从 endpoint 的协议得到 TLS 策略。省略 S3 endpoint 时使用默认 HTTPS 地址。
## 模块依赖 ## 模块依赖
箭头从使用方指向定义类型或提供功能的模块。图中省略 `mod` 声明和 `pub use` 导出。旧配置结构在 `format.rs` 转成统一目录。 箭头从使用方指向定义类型或提供功能的模块。图中省略 `mod` 声明和 `pub use` 导出。旧配置结构在 `format.rs` 转成统一目录。
@@ -22,6 +24,8 @@ flowchart LR
res --> err res --> err
sql -->|SqlDriver| drv sql -->|SqlDriver| drv
obj -->|ObjectStoreDriver| drv obj -->|ObjectStoreDriver| drv
sql -->|Address 和 Tls| net["transport.rs"]
obj -->|Address 和 Tls| net
sql --> err sql --> err
obj --> err obj --> err
+3 -1
View File
@@ -7,6 +7,7 @@ mod format;
mod object_storage; mod object_storage;
mod resource; mod resource;
mod sql; mod sql;
mod transport;
use std::collections::BTreeMap; use std::collections::BTreeMap;
@@ -19,7 +20,8 @@ pub use object_storage::ObjectStorage;
pub use resource::{ResolvedResource, Resource, ResourceRef}; pub use resource::{ResolvedResource, Resource, ResourceRef};
/// Compatibility name for the SQL cluster configuration. /// Compatibility name for the SQL cluster configuration.
pub use sql::SqlCluster as Cluster; pub use sql::SqlCluster as Cluster;
pub use sql::{Address, ResolvedSql, SqlCluster, Tls}; pub use sql::{ResolvedSql, SqlCluster};
pub use transport::{Address, Tls};
pub const DOCUMENTS: &str = "documents"; pub const DOCUMENTS: &str = "documents";
+29 -14
View File
@@ -1,7 +1,11 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use url::Url; use url::Url;
use crate::{ConfigError, driver::ObjectStoreDriver}; use crate::{
ConfigError,
driver::ObjectStoreDriver,
transport::{Address, Tls},
};
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
@@ -9,7 +13,7 @@ pub struct ObjectStorage {
pub driver: ObjectStoreDriver, pub driver: ObjectStoreDriver,
pub bucket: String, pub bucket: String,
pub region: String, pub region: String,
pub endpoint: Option<String>, pub endpoint: Option<Address>,
} }
impl ObjectStorage { impl ObjectStorage {
@@ -17,18 +21,29 @@ impl ObjectStorage {
if self.bucket.trim().is_empty() || self.region.trim().is_empty() { if self.bucket.trim().is_empty() || self.region.trim().is_empty() {
return Err(ConfigError::ObjectStorage); return Err(ConfigError::ObjectStorage);
} }
if let Some(endpoint) = &self.endpoint { self.tls()?;
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(self.clone()) Ok(self.clone())
} }
/// The TLS policy implied by this endpoint. The default S3 endpoint uses HTTPS.
pub fn tls(&self) -> Result<Tls, ConfigError> {
let Some(endpoint) = &self.endpoint else {
return Ok(Tls::VerifyFull);
};
let url =
Url::parse(endpoint.connection_string()).map_err(|_| ConfigError::ObjectStorage)?;
if 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);
}
match url.scheme() {
"https" => Ok(Tls::VerifyFull),
"http" => Ok(Tls::Disabled),
_ => Err(ConfigError::ObjectStorage),
}
}
} }
+8 -41
View File
@@ -1,46 +1,13 @@
use std::{fmt, path::Path}; use std::path::Path;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use url::Url; use url::Url;
use crate::{ConfigError, driver::SqlDriver}; use crate::{
ConfigError,
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)] driver::SqlDriver,
#[serde(rename_all = "snake_case")] transport::{Address, Tls},
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. /// A SQL target with a primary connection and optional read replicas.
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
@@ -153,7 +120,7 @@ fn resolve_address(
Tls::Disabled => tls_disabled, Tls::Disabled => tls_disabled,
}; };
url.query_pairs_mut().append_pair(tls_key, tls_mode); url.query_pairs_mut().append_pair(tls_key, tls_mode);
Ok(Address(url.into())) Ok(Address::from(String::from(url)))
} }
fn sqlite_url(path: &str, read_only: bool) -> Result<Address, ConfigError> { fn sqlite_url(path: &str, read_only: bool) -> Result<Address, ConfigError> {
@@ -167,5 +134,5 @@ fn sqlite_url(path: &str, read_only: bool) -> Result<Address, ConfigError> {
.strip_prefix("file:") .strip_prefix("file:")
.ok_or(ConfigError::SqlitePath)?; .ok_or(ConfigError::SqlitePath)?;
let mode = if read_only { "ro" } else { "rwc" }; let mode = if read_only { "ro" } else { "rwc" };
Ok(Address(format!("sqlite:{file}?mode={mode}"))) Ok(Address::from(format!("sqlite:{file}?mode={mode}")))
} }
+43
View File
@@ -0,0 +1,43 @@
//! Address and TLS settings shared by backend configurations.
use std::fmt;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Tls {
#[default]
VerifyFull,
Disabled,
}
/// A backend connection string, endpoint URL, or local path.
/// 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
}
}
@@ -229,3 +229,35 @@ fn missing_binding_target_is_rejected_for_any_role() {
if role == "attachments" && target == "missing") if role == "attachments" && target == "missing")
); );
} }
#[test]
fn s3_uses_shared_address_and_endpoint_tls() {
use clusters::{ConfigFormat, ObjectStorage};
let config = DeploymentConfig::parse(
include_str!("../../../deploy/kubernetes/multi-storage.yaml"),
ConfigFormat::Yaml,
)
.unwrap();
let Some(Resource::ObjectStore(store)) = config.resource("attachment-store") else {
panic!("expected object storage configuration");
};
assert_eq!(store.tls().unwrap(), Tls::VerifyFull);
for (url, expected) in [
("https://objects.example.test", Tls::VerifyFull),
("http://objects.example.test", Tls::Disabled),
] {
let store = ObjectStorage {
endpoint: Some(url.into()),
..store.clone()
};
assert_eq!(store.endpoint.as_ref().unwrap().connection_string(), url);
assert_eq!(store.tls().unwrap(), expected);
}
let store = ObjectStorage {
endpoint: Some("https://user@objects.example.test".into()),
..store.clone()
};
assert!(matches!(store.tls(), Err(ConfigError::ObjectStorage)));
}