refactor: adapters configured from config crate

This commit is contained in:
2026-10-25 21:07:19 +01:00
parent 1f724bb064
commit 04f9c13625
45 changed files with 277 additions and 177 deletions

View File

@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
[dependencies]
config = { workspace = true }
k-ap = { version = "0.5.0", registry = "gitea" }
domain = { workspace = true }
axum = { workspace = true }

View File

@@ -68,6 +68,7 @@ pub struct ActivityPubDeps {
pub follow_query: std::sync::Arc<dyn domain::ports::FollowQuery>,
pub instance: domain::value_objects::InstanceIdentity,
pub allow_registration: bool,
pub federation: config::FederationConfig,
pub event_publisher: std::sync::Arc<dyn domain::ports::EventPublisher>,
}
@@ -92,6 +93,7 @@ pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
follow_query: _,
instance,
allow_registration,
federation,
event_publisher,
} = deps;
let review_handler = std::sync::Arc::new(ReviewObjectHandler {
@@ -118,9 +120,7 @@ pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
goal: goal_handler,
});
let federation_debug = std::env::var("FEDERATION_DEBUG")
.map(|v| v == "true" || v == "1")
.unwrap_or(false);
let federation_debug = federation.debug;
if federation_debug {
tracing::warn!(

View File

@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
[dependencies]
config = { workspace = true }
async-trait = { workspace = true }
domain = { workspace = true }
anyhow = { workspace = true }

View File

@@ -22,19 +22,17 @@ pub struct AuthConfig {
}
impl AuthConfig {
pub fn from_env() -> anyhow::Result<Self> {
let secret = std::env::var("JWT_SECRET")
.map_err(|_| anyhow::anyhow!("JWT_SECRET env var is required"))?;
pub fn from_config(config: &config::AuthConfig) -> anyhow::Result<Self> {
let secret = config
.jwt_secret
.clone()
.ok_or_else(|| anyhow::anyhow!("JWT_SECRET env var is required"))?;
if secret.is_empty() {
anyhow::bail!("JWT_SECRET must not be empty");
}
let ttl_seconds = std::env::var("JWT_TTL_SECONDS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(900u64);
Ok(Self {
secret,
ttl_seconds,
ttl_seconds: config.jwt_ttl_seconds,
})
}
}
@@ -107,11 +105,13 @@ impl PasswordHasher for Argon2PasswordHasher {
}
}
pub fn create() -> anyhow::Result<(
pub fn create(
config: &config::AuthConfig,
) -> anyhow::Result<(
std::sync::Arc<dyn domain::ports::AuthService>,
std::sync::Arc<dyn domain::ports::PasswordHasher>,
)> {
let config = AuthConfig::from_env()?;
let config = AuthConfig::from_config(config)?;
Ok((
std::sync::Arc::new(JwtAuthService::new(config)),
std::sync::Arc::new(Argon2PasswordHasher),

View File

@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
[dependencies]
config = { workspace = true }
domain = { workspace = true }
async-trait = { workspace = true }
tokio = { workspace = true }

View File

@@ -16,12 +16,10 @@ pub struct EventPublisherConfig {
}
impl EventPublisherConfig {
pub fn from_env() -> Self {
let channel_buffer = std::env::var("EVENT_CHANNEL_BUFFER")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(128);
Self { channel_buffer }
pub fn from_config(config: &config::EventsConfig) -> Self {
Self {
channel_buffer: config.channel_buffer,
}
}
}

View File

@@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2021"
[dependencies]
config = { workspace = true }
domain = { workspace = true }
async-trait = { workspace = true }
anyhow = { workspace = true }

View File

@@ -18,11 +18,8 @@ pub struct ConversionConfig {
}
impl ConversionConfig {
pub fn from_env() -> anyhow::Result<Option<Self>> {
Self::from_vars(
std::env::var("IMAGE_CONVERSION_ENABLED").ok().as_deref(),
std::env::var("IMAGE_CONVERSION_FORMAT").ok().as_deref(),
)
pub fn from_config(config: &::config::ImageConversionConfig) -> anyhow::Result<Option<Self>> {
Self::from_vars(config.enabled.then_some("true"), config.format.as_deref())
}
fn from_vars(enabled: Option<&str>, format: Option<&str>) -> anyhow::Result<Option<Self>> {

View File

@@ -14,12 +14,13 @@ use std::sync::Arc;
type ConversionPair = (Arc<dyn EventHandler>, Arc<dyn PeriodicJob>);
pub fn build(
config: &::config::ImageConversionConfig,
object_storage: Arc<dyn ObjectStorage>,
image_ref_command: Arc<dyn ImageRefCommand>,
image_ref_query: Arc<dyn ImageRefQuery>,
event_publisher: Arc<dyn EventPublisher>,
) -> anyhow::Result<Option<ConversionPair>> {
let config = match ConversionConfig::from_env()? {
let config = match ConversionConfig::from_config(config)? {
Some(c) => c,
None => return Ok(None),
};

View File

@@ -43,3 +43,15 @@ fn avif_extension() {
fn webp_extension() {
assert_eq!(Format::Webp.extension(), ".webp");
}
#[test]
fn from_config_follows_section() {
let disabled = ::config::ImageConversionConfig::default();
assert!(ConversionConfig::from_config(&disabled).unwrap().is_none());
let enabled = ::config::ImageConversionConfig {
enabled: true,
format: Some("webp".into()),
};
let cfg = ConversionConfig::from_config(&enabled).unwrap().unwrap();
assert_eq!(cfg.format, Format::Webp);
}

View File

@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
[dependencies]
config = { workspace = true }
anyhow = { workspace = true }
async-trait = { workspace = true }
reqwest = { workspace = true }

View File

@@ -68,12 +68,16 @@ impl MetadataClient for MetadataClientImpl {
}
}
pub fn create() -> anyhow::Result<std::sync::Arc<dyn domain::ports::MetadataClient>> {
pub fn create(
config: &config::MetadataConfig,
) -> anyhow::Result<std::sync::Arc<dyn domain::ports::MetadataClient>> {
use anyhow::Context;
if let Ok(key) = std::env::var("TMDB_API_KEY") {
if let Some(key) = config.tmdb_api_key.clone() {
Ok(std::sync::Arc::new(MetadataClientImpl::new_tmdb(key)))
} else {
let key = std::env::var("OMDB_API_KEY")
let key = config
.omdb_api_key
.clone()
.context("either TMDB_API_KEY or OMDB_API_KEY must be set")?;
Ok(std::sync::Arc::new(MetadataClientImpl::new_omdb(key)))
}

View File

@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
[dependencies]
config = { workspace = true }
async-nats = "0.48.0"
domain = { workspace = true }

View File

@@ -14,13 +14,13 @@ pub struct NatsConfig {
}
impl NatsConfig {
pub fn from_env() -> anyhow::Result<Self> {
pub fn from_config(config: &::config::NatsConfig) -> anyhow::Result<Self> {
Self::from_vars(
std::env::var("NATS_URL").ok().as_deref(),
std::env::var("NATS_MODE").ok().as_deref(),
std::env::var("NATS_SUBJECT_PREFIX").ok().as_deref(),
std::env::var("NATS_STREAM_NAME").ok().as_deref(),
std::env::var("NATS_CONSUMER_NAME").ok().as_deref(),
config.url.as_deref(),
Some(&config.mode),
Some(&config.subject_prefix),
Some(&config.stream_name),
Some(&config.consumer_name),
)
}

View File

@@ -28,3 +28,20 @@ fn invalid_mode_errors() {
NatsConfig::from_vars(Some("nats://test:4222"), Some("kafka"), None, None, None).is_err()
);
}
#[test]
fn from_config_requires_url() {
assert!(NatsConfig::from_config(&::config::NatsConfig::default()).is_err());
}
#[test]
fn from_config_uses_section_values() {
let section = ::config::NatsConfig {
url: Some("nats://test:4222".into()),
mode: "core".into(),
..Default::default()
};
let cfg = NatsConfig::from_config(&section).unwrap();
assert_eq!(cfg.url, "nats://test:4222");
assert_eq!(cfg.mode, NatsMode::Core);
}

View File

@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
[dependencies]
config = { workspace = true }
domain = { workspace = true }
anyhow = { workspace = true }
async-trait = { workspace = true }

View File

@@ -5,21 +5,25 @@ use std::sync::Arc;
pub struct StorageConfig(Arc<dyn ObjectStore>);
impl StorageConfig {
pub fn from_env() -> anyhow::Result<Self> {
let backend = std::env::var("IMAGE_STORAGE_BACKEND").unwrap_or_else(|_| "local".into());
let store: Arc<dyn ObjectStore> = match backend.as_str() {
pub fn from_config(config: &::config::StorageConfig) -> anyhow::Result<Self> {
let store: Arc<dyn ObjectStore> = match config.backend.as_str() {
"s3" => build_s3_store(
&std::env::var("MINIO_ENDPOINT").context("MINIO_ENDPOINT required")?,
&std::env::var("MINIO_ACCESS_KEY_ID").context("MINIO_ACCESS_KEY_ID required")?,
&std::env::var("MINIO_SECRET_ACCESS_KEY")
config
.endpoint
.as_deref()
.context("MINIO_ENDPOINT required")?,
config
.access_key_id
.as_deref()
.context("MINIO_ACCESS_KEY_ID required")?,
config
.secret_access_key
.as_deref()
.context("MINIO_SECRET_ACCESS_KEY required")?,
&std::env::var("MINIO_BUCKET").context("MINIO_BUCKET required")?,
&std::env::var("MINIO_REGION").unwrap_or_else(|_| "minio".to_string()),
)?,
"local" => build_local_store(
&std::env::var("IMAGE_STORAGE_PATH").unwrap_or_else(|_| "./images".into()),
config.bucket.as_deref().context("MINIO_BUCKET required")?,
&config.region,
)?,
"local" => build_local_store(&config.path)?,
other => {
anyhow::bail!("Unknown IMAGE_STORAGE_BACKEND: {other:?}. Valid values: s3, local")
}

View File

@@ -127,9 +127,9 @@ impl EventHandler for ImageCleanupHandler {
}
}
pub fn create() -> anyhow::Result<Arc<dyn ObjectStorage>> {
pub fn create(config: &::config::StorageConfig) -> anyhow::Result<Arc<dyn ObjectStorage>> {
Ok(Arc::new(ObjectStorageAdapter::from_config(
StorageConfig::from_env()?,
StorageConfig::from_config(config)?,
)))
}

View File

@@ -15,3 +15,22 @@ fn local_store_succeeds_if_dir_already_exists() {
let result = build_local_store(dir.to_str().unwrap());
assert!(result.is_ok());
}
#[test]
fn s3_backend_requires_endpoint() {
let section = ::config::StorageConfig {
backend: "s3".into(),
..Default::default()
};
let err = StorageConfig::from_config(&section).err().unwrap();
assert!(err.to_string().contains("MINIO_ENDPOINT required"));
}
#[test]
fn unknown_backend_is_error() {
let section = ::config::StorageConfig {
backend: "ftp".into(),
..Default::default()
};
assert!(StorageConfig::from_config(&section).is_err());
}

View File

@@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2021"
[dependencies]
config = { workspace = true }
domain = { workspace = true }
async-trait = { workspace = true }
reqwest = { workspace = true }

View File

@@ -3,11 +3,9 @@ pub struct PosterFetcherConfig {
}
impl PosterFetcherConfig {
pub fn from_env() -> Self {
let timeout_seconds = std::env::var("POSTER_FETCH_TIMEOUT_SECONDS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(30);
Self { timeout_seconds }
pub fn from_config(config: &::config::MetadataConfig) -> Self {
Self {
timeout_seconds: config.poster_fetch_timeout_seconds,
}
}
}

View File

@@ -59,14 +59,18 @@ impl ImageFetcher for ReqwestPosterFetcher {
}
}
pub fn create() -> anyhow::Result<std::sync::Arc<dyn domain::ports::PosterFetcherClient>> {
pub fn create(
config: &::config::MetadataConfig,
) -> anyhow::Result<std::sync::Arc<dyn domain::ports::PosterFetcherClient>> {
Ok(std::sync::Arc::new(ReqwestPosterFetcher::new(
PosterFetcherConfig::from_env(),
PosterFetcherConfig::from_config(config),
)?))
}
pub fn create_image_fetcher() -> anyhow::Result<std::sync::Arc<dyn domain::ports::ImageFetcher>> {
pub fn create_image_fetcher(
config: &::config::MetadataConfig,
) -> anyhow::Result<std::sync::Arc<dyn domain::ports::ImageFetcher>> {
Ok(std::sync::Arc::new(ReqwestPosterFetcher::new(
PosterFetcherConfig::from_env(),
PosterFetcherConfig::from_config(config),
)?))
}

View File

@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
[dependencies]
config = { workspace = true }
sqlx = { workspace = true, features = ["macros", "chrono"] }
domain = { workspace = true }

View File

@@ -22,20 +22,11 @@ pub struct DbEventQueueConfig {
}
impl DbEventQueueConfig {
pub fn from_env() -> Self {
pub fn from_config(config: &config::EventsConfig) -> Self {
Self {
poll_interval_ms: std::env::var("EVENT_QUEUE_POLL_INTERVAL_MS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(500),
batch_size: std::env::var("EVENT_QUEUE_BATCH_SIZE")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10),
max_attempts: std::env::var("EVENT_QUEUE_MAX_ATTEMPTS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(5),
poll_interval_ms: config.queue_poll_interval_ms,
batch_size: config.queue_batch_size,
max_attempts: config.queue_max_attempts,
}
}
}
@@ -54,15 +45,19 @@ impl SqliteEventQueue {
})
}
pub async fn create_publisher(pool: SqlitePool) -> anyhow::Result<Arc<dyn EventPublisher>> {
let q = Self::create(pool, DbEventQueueConfig::from_env()).await?;
pub async fn create_publisher(
pool: SqlitePool,
config: &config::EventsConfig,
) -> anyhow::Result<Arc<dyn EventPublisher>> {
let q = Self::create(pool, DbEventQueueConfig::from_config(config)).await?;
Ok(Arc::new(q))
}
pub async fn create_channel(
pool: SqlitePool,
config: &config::EventsConfig,
) -> anyhow::Result<(Arc<dyn EventPublisher>, Arc<dyn EventConsumer>)> {
let q = Self::create(pool, DbEventQueueConfig::from_env()).await?;
let q = Self::create(pool, DbEventQueueConfig::from_config(config)).await?;
Ok((Arc::new(q.clone()), Arc::new(q)))
}
}

View File

@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
[dependencies]
config = { workspace = true }
domain = { workspace = true }
reqwest = { workspace = true }
serde = { workspace = true }

View File

@@ -7,9 +7,11 @@ pub struct TmdbEnrichmentClient {
}
impl TmdbEnrichmentClient {
pub fn from_env() -> Result<Self, DomainError> {
let api_key = std::env::var("TMDB_API_KEY")
.map_err(|_| DomainError::InfrastructureError("TMDB_API_KEY is not set".into()))?;
pub fn from_config(config: &config::MetadataConfig) -> Result<Self, DomainError> {
let api_key = config
.tmdb_api_key
.clone()
.ok_or_else(|| DomainError::InfrastructureError("TMDB_API_KEY is not set".into()))?;
Ok(Self {
api_key,
http: reqwest::Client::new(),