refactor: move AppContext to presentation crate, structurally enforce boundary
All checks were successful
CI / Check / Test (push) Successful in 39m33s

This commit is contained in:
2026-06-11 23:18:28 +02:00
parent b5cc7f8371
commit 57520c00f3
51 changed files with 268 additions and 377 deletions

View File

@@ -7,8 +7,9 @@ use crate::{
auth::{
commands::RegisterCommand,
deps::{LoginDeps, RefreshDeps, RegisterDeps},
login, logout, refresh, register,
login, logout,
queries::LoginQuery,
refresh, register,
},
test_helpers::TestContextBuilder,
};
@@ -52,12 +53,9 @@ async fn logout_revokes_refresh_token() {
.await
.unwrap();
logout::execute(
b.refresh_session_repo.clone(),
&login_result.refresh_token,
)
.await
.unwrap();
logout::execute(b.refresh_session_repo.clone(), &login_result.refresh_token)
.await
.unwrap();
let refresh_deps = RefreshDeps {
refresh_session: b.refresh_session_repo.clone(),

View File

@@ -7,8 +7,9 @@ use crate::{
auth::{
commands::RegisterCommand,
deps::{LoginDeps, RefreshDeps, RegisterDeps},
login, refresh, register,
login,
queries::LoginQuery,
refresh, register,
},
test_helpers::TestContextBuilder,
};

View File

@@ -1,64 +0,0 @@
use std::sync::Arc;
use domain::ports::{
AuthService, DiaryExporter, DiaryRepository, DocumentParser, EventPublisher, GoalRepository,
ImportProfileRepository, ImportSessionRepository, MetadataClient, MovieProfileRepository,
MovieRepository, ObjectStorage, PasswordHasher, PersonCommand, PersonEnrichmentClient,
PersonQuery, PosterFetcherClient, RefreshSessionRepository, RemoteGoalRepository,
RemoteWatchlistRepository, ReviewRepository, SearchCommand, SearchPort, SocialQueryPort,
StatsRepository, UserProfileFieldsRepository, UserRepository, UserSettingsRepository,
WatchEventRepository, WatchlistRepository, WebhookTokenRepository, WrapUpRepository,
WrapUpStatsQuery,
};
use crate::config::AppConfig;
use crate::ports::ReviewLogger;
#[derive(Clone)]
pub struct Repositories {
pub movie: Arc<dyn MovieRepository>,
pub review: Arc<dyn ReviewRepository>,
pub diary: Arc<dyn DiaryRepository>,
pub stats: Arc<dyn StatsRepository>,
pub user: Arc<dyn UserRepository>,
pub import_session: Arc<dyn ImportSessionRepository>,
pub import_profile: Arc<dyn ImportProfileRepository>,
pub movie_profile: Arc<dyn MovieProfileRepository>,
pub watchlist: Arc<dyn WatchlistRepository>,
pub watch_event: Arc<dyn WatchEventRepository>,
pub webhook_token: Arc<dyn WebhookTokenRepository>,
pub person_command: Arc<dyn PersonCommand>,
pub person_query: Arc<dyn PersonQuery>,
pub search_port: Arc<dyn SearchPort>,
pub search_command: Arc<dyn SearchCommand>,
pub profile_fields: Arc<dyn UserProfileFieldsRepository>,
pub remote_watchlist: Arc<dyn RemoteWatchlistRepository>,
pub social_query: Arc<dyn SocialQueryPort>,
pub wrapup_stats: Arc<dyn WrapUpStatsQuery>,
pub wrapup_repo: Arc<dyn WrapUpRepository>,
pub goal: Arc<dyn GoalRepository>,
pub user_settings: Arc<dyn UserSettingsRepository>,
pub remote_goal: Arc<dyn RemoteGoalRepository>,
pub refresh_session: Arc<dyn RefreshSessionRepository>,
}
#[derive(Clone)]
pub struct Services {
pub auth: Arc<dyn AuthService>,
pub password_hasher: Arc<dyn PasswordHasher>,
pub metadata: Arc<dyn MetadataClient>,
pub poster_fetcher: Arc<dyn PosterFetcherClient>,
pub object_storage: Arc<dyn ObjectStorage>,
pub event_publisher: Arc<dyn EventPublisher>,
pub diary_exporter: Arc<dyn DiaryExporter>,
pub document_parser: Arc<dyn DocumentParser>,
pub review_logger: Arc<dyn ReviewLogger>,
pub person_enrichment: Option<Arc<dyn PersonEnrichmentClient>>,
}
#[derive(Clone)]
pub struct AppContext {
pub repos: Repositories,
pub services: Services,
pub config: AppConfig,
}

View File

@@ -16,5 +16,7 @@ pub async fn execute(
let entries = diary
.get_user_history(&UserId::from_uuid(query.user_id))
.await?;
diary_exporter.serialize_entries(&entries, query.format).await
diary_exporter
.serialize_entries(&entries, query.format)
.await
}

View File

@@ -12,9 +12,7 @@ use domain::{
};
use crate::{
diary::commands::DeleteReviewCommand,
diary::delete_review,
diary::deps::DeleteReviewDeps,
diary::commands::DeleteReviewCommand, diary::delete_review, diary::deps::DeleteReviewDeps,
};
fn make_movie() -> Movie {

View File

@@ -5,11 +5,8 @@ use domain::errors::DomainError;
use domain::testing::{FakeDiaryRepository, NoopSocialQueryPort};
use crate::{
config::AppConfig,
diary::deps::GetActivityFeedDeps,
diary::get_activity_feed,
diary::queries::GetActivityFeedQuery,
test_helpers::TestContextBuilder,
config::AppConfig, diary::deps::GetActivityFeedDeps, diary::get_activity_feed,
diary::queries::GetActivityFeedQuery, test_helpers::TestContextBuilder,
};
fn default_deps() -> GetActivityFeedDeps {

View File

@@ -10,8 +10,7 @@ use domain::{
};
use crate::{
diary::deps::GetMovieSocialPageDeps,
diary::get_movie_social_page,
diary::deps::GetMovieSocialPageDeps, diary::get_movie_social_page,
diary::queries::GetMovieSocialPageQuery,
};

View File

@@ -17,9 +17,7 @@ pub async fn execute(
) -> Result<GoalWithProgress, DomainError> {
let user_id = UserId::from_uuid(cmd.user_id);
let existing = goal
.find_by_user_and_year(&user_id, cmd.year)
.await?;
let existing = goal.find_by_user_and_year(&user_id, cmd.year).await?;
if existing.is_some() {
return Err(DomainError::ValidationError(
"Goal already exists for this year".into(),
@@ -34,9 +32,7 @@ pub async fn execute(
)?;
goal.save(&g).await?;
let current_count = goal
.count_reviews_in_year(&user_id, cmd.year)
.await?;
let current_count = goal.count_reviews_in_year(&user_id, cmd.year).await?;
event_publisher
.publish(&DomainEvent::GoalCreated {

View File

@@ -1,6 +1,8 @@
use std::sync::Arc;
use domain::{errors::DomainError, models::GoalWithProgress, ports::GoalRepository, value_objects::UserId};
use domain::{
errors::DomainError, models::GoalWithProgress, ports::GoalRepository, value_objects::UserId,
};
use super::queries::GetGoalQuery;
@@ -10,15 +12,11 @@ pub async fn execute(
) -> Result<Option<GoalWithProgress>, DomainError> {
let user_id = UserId::from_uuid(query.user_id);
let found = goal
.find_by_user_and_year(&user_id, query.year)
.await?;
let found = goal.find_by_user_and_year(&user_id, query.year).await?;
let Some(g) = found else { return Ok(None) };
let current_count = goal
.count_reviews_in_year(&user_id, query.year)
.await?;
let current_count = goal.count_reviews_in_year(&user_id, query.year).await?;
Ok(Some(GoalWithProgress {
goal: g,

View File

@@ -1,6 +1,8 @@
use std::sync::Arc;
use domain::{errors::DomainError, models::GoalWithProgress, ports::GoalRepository, value_objects::UserId};
use domain::{
errors::DomainError, models::GoalWithProgress, ports::GoalRepository, value_objects::UserId,
};
use super::queries::ListGoalsQuery;
@@ -13,9 +15,7 @@ pub async fn execute(
let mut result = Vec::with_capacity(goals.len());
for g in goals {
let current_count = goal
.count_reviews_in_year(&user_id, g.year())
.await?;
let current_count = goal.count_reviews_in_year(&user_id, g.year()).await?;
result.push(GoalWithProgress {
goal: g,
current_count,

View File

@@ -25,9 +25,7 @@ pub async fn execute(
g.update_target(cmd.target_count)?;
goal.update(&g).await?;
let current_count = goal
.count_reviews_in_year(&user_id, cmd.year)
.await?;
let current_count = goal.count_reviews_in_year(&user_id, cmd.year).await?;
event_publisher
.publish(&DomainEvent::GoalUpdated {

View File

@@ -22,9 +22,7 @@ pub async fn execute(
cmd: CreateImportSessionCommand,
) -> Result<CreateSessionResult, DomainError> {
let user_id = UserId::from_uuid(cmd.user_id);
import_session
.delete_expired_for_user(&user_id)
.await?;
import_session.delete_expired_for_user(&user_id).await?;
let parsed = document_parser
.parse(&cmd.bytes, cmd.format)

View File

@@ -1,6 +1,9 @@
use std::sync::Arc;
use domain::{errors::DomainError, models::ImportProfile, ports::ImportProfileRepository, value_objects::UserId};
use domain::{
errors::DomainError, models::ImportProfile, ports::ImportProfileRepository,
value_objects::UserId,
};
pub async fn execute(
import_profile: Arc<dyn ImportProfileRepository>,

View File

@@ -11,7 +11,9 @@ async fn returns_empty_when_no_profiles() {
let profiles = InMemoryImportProfileRepository::new();
let user_id = UserId::from_uuid(Uuid::new_v4());
let result = list_profiles::execute(Arc::clone(&profiles) as _, &user_id).await.unwrap();
let result = list_profiles::execute(Arc::clone(&profiles) as _, &user_id)
.await
.unwrap();
assert!(result.is_empty());
}

View File

@@ -1,6 +1,8 @@
use std::sync::Arc;
use domain::{errors::DomainError, models::WebhookToken, ports::WebhookTokenRepository, value_objects::UserId};
use domain::{
errors::DomainError, models::WebhookToken, ports::WebhookTokenRepository, value_objects::UserId,
};
use sha2::{Digest, Sha256};
use crate::integrations::commands::GenerateWebhookTokenCommand;

View File

@@ -1,6 +1,8 @@
use std::sync::Arc;
use domain::{errors::DomainError, models::WatchEvent, ports::WatchEventRepository, value_objects::UserId};
use domain::{
errors::DomainError, models::WatchEvent, ports::WatchEventRepository, value_objects::UserId,
};
use crate::integrations::queries::GetWatchQueueQuery;

View File

@@ -1,6 +1,8 @@
use std::sync::Arc;
use domain::{errors::DomainError, models::WebhookToken, ports::WebhookTokenRepository, value_objects::UserId};
use domain::{
errors::DomainError, models::WebhookToken, ports::WebhookTokenRepository, value_objects::UserId,
};
use crate::integrations::queries::GetWebhookTokensQuery;

View File

@@ -17,10 +17,7 @@ pub async fn execute(
.await?
.ok_or_else(|| DomainError::Unauthorized("invalid webhook token".into()))?;
let _ = deps
.webhook_token
.touch_last_used(webhook_token.id())
.await;
let _ = deps.webhook_token.touch_last_used(webhook_token.id()).await;
let parsed = match parser.parse_playback_event(&cmd.raw_payload)? {
Some(event) => event,

View File

@@ -2,7 +2,9 @@ use std::sync::Arc;
use domain::models::WatchEventSource;
use domain::ports::{EventPublisher, WatchEventRepository, WebhookTokenRepository};
use domain::testing::{InMemoryWebhookTokenRepository, InMemoryWatchEventRepository, NoopEventPublisher};
use domain::testing::{
InMemoryWatchEventRepository, InMemoryWebhookTokenRepository, NoopEventPublisher,
};
use uuid::Uuid;
use crate::integrations::commands::{GenerateWebhookTokenCommand, IngestWatchEventCommand};

View File

@@ -2,7 +2,10 @@ use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use domain::{errors::DomainError, ports::{ImportSessionRepository, PeriodicJob}};
use domain::{
errors::DomainError,
ports::{ImportSessionRepository, PeriodicJob},
};
pub struct ImportSessionCleanupJob {
import_session: Arc<dyn ImportSessionRepository>,

View File

@@ -2,7 +2,10 @@ use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use domain::{errors::DomainError, ports::{PeriodicJob, WatchEventRepository}};
use domain::{
errors::DomainError,
ports::{PeriodicJob, WatchEventRepository},
};
pub struct WatchEventCleanupJob {
watch_event: Arc<dyn WatchEventRepository>,

View File

@@ -114,10 +114,7 @@ impl PeriodicJob for WrapUpCleanupJob {
async fn run(&self) -> Result<(), DomainError> {
let cutoff = chrono::Utc::now().naive_utc() - chrono::Duration::days(7);
let n = self
.wrapup_repo
.delete_failed_older_than(cutoff)
.await?;
let n = self.wrapup_repo.delete_failed_older_than(cutoff).await?;
if n > 0 {
tracing::info!("wrapup cleanup: removed {n} failed records");
}

View File

@@ -1,5 +1,4 @@
pub mod config;
pub mod context;
pub mod jobs;
pub mod ports;
pub mod worker;

View File

@@ -30,11 +30,7 @@ pub async fn execute(deps: &SyncPosterDeps, cmd: SyncPosterCommand) -> Result<()
})?
.clone();
let poster_url = match deps
.metadata
.get_poster_url(&external_metadata_id)
.await
{
let poster_url = match deps.metadata.get_poster_url(&external_metadata_id).await {
Ok(Some(url)) => url,
Ok(None) => return Ok(()),
Err(e) => {
@@ -43,10 +39,7 @@ pub async fn execute(deps: &SyncPosterDeps, cmd: SyncPosterCommand) -> Result<()
}
};
let image_bytes = deps
.poster_fetcher
.fetch_poster_bytes(&poster_url)
.await?;
let image_bytes = deps.poster_fetcher.fetch_poster_bytes(&poster_url).await?;
let stored_path = deps
.object_storage

View File

@@ -6,7 +6,10 @@ use domain::{
errors::DomainError,
models::Movie,
ports::{MetadataClient, MovieRepository},
testing::{InMemoryMovieProfileRepository, InMemoryMovieRepository, NoopEventPublisher, NoopObjectStorage, FakeSearchCommand},
testing::{
FakeSearchCommand, InMemoryMovieProfileRepository, InMemoryMovieRepository,
NoopEventPublisher, NoopObjectStorage,
},
value_objects::{ExternalMetadataId, MovieTitle, PosterUrl, ReleaseYear},
};

View File

@@ -1,9 +1,9 @@
use std::sync::Arc;
use domain::{
errors::DomainError,
models::{SearchQuery, SearchResults},
ports::SearchPort,
};
use std::sync::Arc;
pub async fn execute(
search_port: Arc<dyn SearchPort>,

View File

@@ -1,8 +1,7 @@
use std::sync::Arc;
use domain::testing::{
InMemoryGoalRepository, InMemoryWrapUpRepository, InMemoryWrapUpStatsQuery,
NoopRemoteWatchlistRepository, NoopSocialQueryPort,
InMemoryGoalRepository, InMemoryWrapUpRepository, InMemoryWrapUpStatsQuery, NoopSocialQueryPort,
};
use domain::{
ports::{
@@ -29,12 +28,7 @@ use domain::{
use async_trait::async_trait;
use domain::errors::DomainError;
use crate::{
config::AppConfig,
context::{AppContext, Repositories, Services},
diary::commands::LogReviewCommand,
ports::ReviewLogger,
};
use crate::{config::AppConfig, diary::commands::LogReviewCommand, ports::ReviewLogger};
pub struct NoopReviewLogger;
@@ -263,48 +257,4 @@ impl TestContextBuilder {
self.config = config;
self
}
pub fn build(self) -> AppContext {
AppContext {
repos: Repositories {
movie: self.movie_repo,
review: self.review_repo,
diary: self.diary_repo,
stats: self.stats_repo,
user: self.user_repo,
import_session: self.import_session_repo,
import_profile: self.import_profile_repo,
movie_profile: self.movie_profile_repo,
watchlist: self.watchlist_repo,
watch_event: self.watch_event_repo,
webhook_token: self.webhook_token_repo,
profile_fields: self.profile_fields_repo,
person_command: self.person_command,
person_query: self.person_query,
search_port: self.search_port,
search_command: self.search_command,
remote_watchlist: Arc::new(NoopRemoteWatchlistRepository),
social_query: self.social_query,
wrapup_stats: self.wrapup_stats,
wrapup_repo: self.wrapup_repo,
goal: self.goal_repo,
user_settings: self.user_settings_repo,
remote_goal: Arc::new(domain::testing::NoopRemoteGoalRepository),
refresh_session: self.refresh_session_repo,
},
services: Services {
auth: self.auth_service,
password_hasher: self.password_hasher,
metadata: self.metadata_client,
poster_fetcher: self.poster_fetcher,
object_storage: self.object_storage,
event_publisher: self.event_publisher,
diary_exporter: self.diary_exporter,
document_parser: self.document_parser,
review_logger: self.review_logger,
person_enrichment: None,
},
config: self.config,
}
}
}

View File

@@ -1,6 +1,8 @@
use std::sync::Arc;
use domain::{errors::DomainError, models::UserSettings, ports::UserSettingsRepository, value_objects::UserId};
use domain::{
errors::DomainError, models::UserSettings, ports::UserSettingsRepository, value_objects::UserId,
};
pub async fn execute(
user_settings: Arc<dyn UserSettingsRepository>,

View File

@@ -1,7 +1,11 @@
use std::sync::Arc;
use crate::users::queries::GetUsersQuery;
use domain::{errors::DomainError, models::UserSummary, ports::{RemoteActorInfo, SocialQueryPort, UserRepository}};
use domain::{
errors::DomainError,
models::UserSummary,
ports::{RemoteActorInfo, SocialQueryPort, UserRepository},
};
pub struct UsersListData {
pub users: Vec<UserSummary>,

View File

@@ -7,7 +7,9 @@ async fn returns_default_settings() {
let b = TestContextBuilder::new();
let user_settings = b.user_settings_repo.clone();
let settings = get_settings::execute(user_settings, Uuid::nil()).await.unwrap();
let settings = get_settings::execute(user_settings, Uuid::nil())
.await
.unwrap();
assert!(!settings.federate_goals());
}

View File

@@ -8,7 +8,9 @@ async fn returns_empty_when_no_users() {
let user = b.user_repo.clone();
let social_query = b.social_query.clone();
let result = get_users::execute(user, social_query, GetUsersQuery).await.unwrap();
let result = get_users::execute(user, social_query, GetUsersQuery)
.await
.unwrap();
assert!(result.users.is_empty());
assert!(result.remote_actors.is_empty());

View File

@@ -11,8 +11,7 @@ use crate::{
#[tokio::test]
async fn updates_federate_goals() {
let settings_repo = InMemoryUserSettingsRepository::new();
let b = TestContextBuilder::new()
.with_user_settings(Arc::clone(&settings_repo) as _);
let b = TestContextBuilder::new().with_user_settings(Arc::clone(&settings_repo) as _);
let user_settings = b.user_settings_repo.clone();
let uid = Uuid::nil();

View File

@@ -2,7 +2,10 @@ use domain::{errors::DomainError, events::DomainEvent, value_objects::UserId};
use crate::users::{commands::UpdateProfileCommand, deps::UpdateProfileDeps};
pub async fn execute(deps: &UpdateProfileDeps, cmd: UpdateProfileCommand) -> Result<(), DomainError> {
pub async fn execute(
deps: &UpdateProfileDeps,
cmd: UpdateProfileCommand,
) -> Result<(), DomainError> {
let user_id = UserId::from_uuid(cmd.user_id);
let user = deps

View File

@@ -1,7 +1,11 @@
use std::sync::Arc;
use domain::{
errors::DomainError, events::DomainEvent, models::UserProfile, ports::{EventPublisher, UserProfileFieldsRepository}, value_objects::UserId,
errors::DomainError,
events::DomainEvent,
models::UserProfile,
ports::{EventPublisher, UserProfileFieldsRepository},
value_objects::UserId,
};
use crate::users::commands::UpdateProfileFieldsCommand;

View File

@@ -10,7 +10,10 @@ use crate::{
watchlist::{commands::AddToWatchlistCommand, deps::WatchlistAddDeps},
};
pub async fn execute(deps: &WatchlistAddDeps, cmd: AddToWatchlistCommand) -> Result<(), DomainError> {
pub async fn execute(
deps: &WatchlistAddDeps,
cmd: AddToWatchlistCommand,
) -> Result<(), DomainError> {
let user_id = UserId::from_uuid(cmd.user_id);
let movie = if let Some(id) = cmd.input.movie_id {

View File

@@ -37,9 +37,7 @@ pub async fn execute(
match compute::execute(deps.wrapup_stats.clone(), query).await {
Ok(report) => {
deps.wrapup_repo
.set_complete(&wrapup_id, &report)
.await?;
deps.wrapup_repo.set_complete(&wrapup_id, &report).await?;
deps.event_publisher
.publish(&DomainEvent::WrapUpCompleted { wrapup_id })