refactor: bootstrap crate, thin server/worker binaries
This commit is contained in:
49
crates/bootstrap/Cargo.toml
Normal file
49
crates/bootstrap/Cargo.toml
Normal file
@@ -0,0 +1,49 @@
|
||||
[package]
|
||||
name = "bootstrap"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
nats = ["dep:nats"]
|
||||
federation = [
|
||||
"application/federation",
|
||||
"presentation/federation",
|
||||
"dep:sqlite-federation",
|
||||
"dep:activitypub",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
config = { workspace = true }
|
||||
domain = { workspace = true }
|
||||
application = { workspace = true }
|
||||
presentation = { path = "../presentation", default-features = false }
|
||||
auth = { workspace = true }
|
||||
metadata = { workspace = true }
|
||||
poster-fetcher = { workspace = true }
|
||||
object-storage = { workspace = true }
|
||||
poster-sync = { workspace = true }
|
||||
tmdb-enrichment = { workspace = true }
|
||||
image-converter = { workspace = true }
|
||||
export = { workspace = true }
|
||||
importer = { workspace = true }
|
||||
rss = { workspace = true }
|
||||
jellyfin = { workspace = true }
|
||||
plex = { workspace = true }
|
||||
sqlite = { workspace = true }
|
||||
sqlx = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
async-trait = { workspace = true }
|
||||
axum = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
|
||||
nats = { workspace = true, optional = true }
|
||||
activitypub = { workspace = true, optional = true }
|
||||
sqlite-federation = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
chrono = { workspace = true }
|
||||
domain = { workspace = true, features = ["test-helpers"] }
|
||||
uuid = { workspace = true }
|
||||
398
crates/bootstrap/src/build.rs
Normal file
398
crates/bootstrap/src/build.rs
Normal file
@@ -0,0 +1,398 @@
|
||||
use application::auth::deps::{
|
||||
LoginDeps, LogoutDeps, RefreshDeps, RegisterAndLoginDeps, RegisterDeps,
|
||||
};
|
||||
use application::deps::{
|
||||
AuthGroup, Deps, DiaryGroup, GoalsGroup, ImportGroup, InsightsGroup, IntegrationsGroup,
|
||||
MoviesGroup, PersonGroup, SearchGroup, SocialGroup, UsersGroup, WatchlistGroup, WorkerDeps,
|
||||
WrapupGroup,
|
||||
};
|
||||
use application::diary::deps::{
|
||||
DeleteReviewDeps, EditReviewDeps, ExportDiaryDeps, GetActivityFeedDeps, GetDiaryDeps,
|
||||
GetMovieSocialPageDeps, GetReviewHistoryDeps, GetUserFeedDeps,
|
||||
};
|
||||
use application::goals::deps::{GoalCommandDeps, GoalQueryDeps};
|
||||
use application::import::deps::{
|
||||
ApplyMappingDeps, ApplyProfileAndMapDeps, ApplyProfileDeps, CreateSessionDeps,
|
||||
DeleteImportProfileDeps, ExecuteImportDeps, GetMappingStageDeps, GetPreviewStageDeps,
|
||||
GetSessionStateDeps, ListImportProfilesDeps, SaveProfileDeps,
|
||||
};
|
||||
use application::insights::deps::GetInsightsDeps;
|
||||
use application::integrations::deps::{
|
||||
ConfirmWatchEventsDeps, DismissWatchEventsDeps, GenerateWebhookTokenDeps, GetWatchQueueDeps,
|
||||
GetWebhookTokensDeps, IngestWatchEventDeps, RevokeWebhookTokenDeps,
|
||||
};
|
||||
use application::movies::deps::{
|
||||
EnrichMovieDeps, GetMovieProfileDeps, GetMoviesDeps, ReindexSearchDeps, SyncPosterDeps,
|
||||
};
|
||||
use application::movies::merge_duplicates::MergeDuplicatesDeps;
|
||||
use application::person::deps::{EnrichPersonDeps, GetPersonDeps};
|
||||
use application::search::deps::SearchDeps;
|
||||
use application::social::deps::{SocialCommandDeps, SocialQueryDeps};
|
||||
use application::users::deps::{
|
||||
AuthorizeAdminDeps, DeleteAccountDeps, GetCurrentProfileDeps, GetFederatedProfileDeps,
|
||||
GetFederatedProfileStatsDeps, GetLocalProfileDeps, GetPageViewerDeps, GetProfileSettingsDeps,
|
||||
GetSettingsDeps, GetUsersListDeps, ResolveUsernameDeps, UpdateProfileDeps,
|
||||
UpdateProfileFieldsDeps, UpdateSettingsDeps,
|
||||
};
|
||||
use application::watchlist::deps::{
|
||||
GetWatchlistDeps, GetWatchlistForOwnerDeps, IsOnWatchlistDeps, RemoveFromWatchlistDeps,
|
||||
WatchlistAddDeps,
|
||||
};
|
||||
use application::wrapup::deps::{
|
||||
DeleteWrapUpDeps, GenerateWrapUpDeps, GetReadyReportDeps, GetWrapUpDeps,
|
||||
HandleWrapUpRequestedDeps, ListWrapUpsDeps,
|
||||
};
|
||||
use domain::value_objects::InstanceIdentity;
|
||||
|
||||
use crate::{DatabaseOutput, Repositories};
|
||||
|
||||
/// The composition root's single assembly point: every one of the server-facing
|
||||
/// deps structs, built once from the already-constructed `Repositories` and
|
||||
/// `application::Services`. Only `Arc` clones happen here — no adapters are built.
|
||||
pub fn build_deps(
|
||||
repos: &Repositories,
|
||||
services: &application::Services,
|
||||
config: &application::config::AppConfig,
|
||||
instance: &InstanceIdentity,
|
||||
) -> Deps {
|
||||
Deps {
|
||||
auth: AuthGroup {
|
||||
login: LoginDeps {
|
||||
user: repos.user.clone(),
|
||||
password_hasher: services.password_hasher.clone(),
|
||||
auth: services.auth.clone(),
|
||||
refresh_session: repos.refresh_session.clone(),
|
||||
config: config.clone(),
|
||||
},
|
||||
register: RegisterDeps {
|
||||
user: repos.user.clone(),
|
||||
password_hasher: services.password_hasher.clone(),
|
||||
config: config.clone(),
|
||||
},
|
||||
refresh: RefreshDeps {
|
||||
refresh_session: repos.refresh_session.clone(),
|
||||
auth: services.auth.clone(),
|
||||
config: config.clone(),
|
||||
},
|
||||
register_and_login: RegisterAndLoginDeps {
|
||||
user: repos.user.clone(),
|
||||
password_hasher: services.password_hasher.clone(),
|
||||
auth: services.auth.clone(),
|
||||
refresh_session: repos.refresh_session.clone(),
|
||||
config: config.clone(),
|
||||
},
|
||||
logout: LogoutDeps {
|
||||
refresh_session: repos.refresh_session.clone(),
|
||||
},
|
||||
},
|
||||
diary: DiaryGroup {
|
||||
delete_review: DeleteReviewDeps {
|
||||
review: repos.review.clone(),
|
||||
diary: repos.diary.clone(),
|
||||
movie_command: repos.movie_command.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
},
|
||||
edit_review: EditReviewDeps {
|
||||
review: repos.review.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
},
|
||||
get_movie_social_page: GetMovieSocialPageDeps {
|
||||
movie_query: repos.movie_query.clone(),
|
||||
diary: repos.diary.clone(),
|
||||
movie_profile: repos.movie_profile.clone(),
|
||||
},
|
||||
get_activity_feed: GetActivityFeedDeps {
|
||||
diary: repos.diary.clone(),
|
||||
social_query: repos.follow_graph.clone(),
|
||||
config: config.clone(),
|
||||
},
|
||||
get_user_feed: GetUserFeedDeps {
|
||||
user: repos.user.clone(),
|
||||
diary: repos.diary.clone(),
|
||||
},
|
||||
get_diary: GetDiaryDeps {
|
||||
diary: repos.diary.clone(),
|
||||
},
|
||||
get_review_history: GetReviewHistoryDeps {
|
||||
diary: repos.diary.clone(),
|
||||
},
|
||||
export_diary: ExportDiaryDeps {
|
||||
diary: repos.diary.clone(),
|
||||
diary_exporter: services.diary_exporter.clone(),
|
||||
},
|
||||
},
|
||||
goals: GoalsGroup {
|
||||
command: GoalCommandDeps {
|
||||
goal_command: repos.goal_command.clone(),
|
||||
goal_query: repos.goal_query.clone(),
|
||||
stats: repos.stats.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
},
|
||||
query: GoalQueryDeps {
|
||||
goal_query: repos.goal_query.clone(),
|
||||
stats: repos.stats.clone(),
|
||||
},
|
||||
},
|
||||
import: ImportGroup {
|
||||
create_session: CreateSessionDeps {
|
||||
import_session: repos.import_session.clone(),
|
||||
document_parser: services.document_parser.clone(),
|
||||
},
|
||||
apply_mapping: ApplyMappingDeps {
|
||||
import_session: repos.import_session.clone(),
|
||||
document_parser: services.document_parser.clone(),
|
||||
movie_query: repos.movie_query.clone(),
|
||||
},
|
||||
apply_profile: ApplyProfileDeps {
|
||||
import_profile: repos.import_profile.clone(),
|
||||
import_session: repos.import_session.clone(),
|
||||
},
|
||||
execute_import: ExecuteImportDeps {
|
||||
import_session: repos.import_session.clone(),
|
||||
review_logger: services.review_logger.clone(),
|
||||
},
|
||||
save_profile: SaveProfileDeps {
|
||||
import_session: repos.import_session.clone(),
|
||||
import_profile: repos.import_profile.clone(),
|
||||
},
|
||||
get_mapping_stage: GetMappingStageDeps {
|
||||
import_session: repos.import_session.clone(),
|
||||
},
|
||||
get_preview_stage: GetPreviewStageDeps {
|
||||
import_session: repos.import_session.clone(),
|
||||
},
|
||||
get_session_state: GetSessionStateDeps {
|
||||
import_session: repos.import_session.clone(),
|
||||
},
|
||||
apply_profile_and_map: ApplyProfileAndMapDeps {
|
||||
import_profile: repos.import_profile.clone(),
|
||||
import_session: repos.import_session.clone(),
|
||||
document_parser: services.document_parser.clone(),
|
||||
movie_query: repos.movie_query.clone(),
|
||||
},
|
||||
delete_profile: DeleteImportProfileDeps {
|
||||
import_profile: repos.import_profile.clone(),
|
||||
},
|
||||
list_profiles: ListImportProfilesDeps {
|
||||
import_profile: repos.import_profile.clone(),
|
||||
},
|
||||
},
|
||||
insights: InsightsGroup {
|
||||
get: GetInsightsDeps {
|
||||
insights: repos.insights.clone(),
|
||||
},
|
||||
},
|
||||
integrations: IntegrationsGroup {
|
||||
ingest_watch_event: IngestWatchEventDeps {
|
||||
webhook_token: repos.webhook_token.clone(),
|
||||
watch_event_command: repos.watch_event_command.clone(),
|
||||
watch_event_query: repos.watch_event_query.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
},
|
||||
confirm_watch_events: ConfirmWatchEventsDeps {
|
||||
watch_event_command: repos.watch_event_command.clone(),
|
||||
watch_event_query: repos.watch_event_query.clone(),
|
||||
review_logger: services.review_logger.clone(),
|
||||
},
|
||||
dismiss_watch_events: DismissWatchEventsDeps {
|
||||
watch_event_command: repos.watch_event_command.clone(),
|
||||
watch_event_query: repos.watch_event_query.clone(),
|
||||
},
|
||||
generate_webhook_token: GenerateWebhookTokenDeps {
|
||||
webhook_token: repos.webhook_token.clone(),
|
||||
},
|
||||
get_watch_queue: GetWatchQueueDeps {
|
||||
watch_event_query: repos.watch_event_query.clone(),
|
||||
},
|
||||
get_webhook_tokens: GetWebhookTokensDeps {
|
||||
webhook_token: repos.webhook_token.clone(),
|
||||
},
|
||||
revoke_webhook_token: RevokeWebhookTokenDeps {
|
||||
webhook_token: repos.webhook_token.clone(),
|
||||
},
|
||||
jellyfin_parser: std::sync::Arc::new(jellyfin::JellyfinParser),
|
||||
plex_parser: std::sync::Arc::new(plex::PlexParser),
|
||||
},
|
||||
movies: MoviesGroup {
|
||||
sync_poster: SyncPosterDeps {
|
||||
movie_command: repos.movie_command.clone(),
|
||||
movie_query: repos.movie_query.clone(),
|
||||
movie_profile: repos.movie_profile.clone(),
|
||||
metadata: services.metadata.clone(),
|
||||
poster_fetcher: services.poster_fetcher.clone(),
|
||||
object_storage: services.object_storage.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
search_command: repos.search_command.clone(),
|
||||
},
|
||||
get_movie_profile: GetMovieProfileDeps {
|
||||
movie_profile: repos.movie_profile.clone(),
|
||||
},
|
||||
get_movies: GetMoviesDeps {
|
||||
movie: repos.movie_query.clone(),
|
||||
},
|
||||
},
|
||||
person: PersonGroup {
|
||||
get_person: GetPersonDeps {
|
||||
person_query: repos.person_query.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
},
|
||||
},
|
||||
search: SearchGroup {
|
||||
execute: SearchDeps {
|
||||
search_port: repos.search_port.clone(),
|
||||
},
|
||||
},
|
||||
social: SocialGroup {
|
||||
command: SocialCommandDeps {
|
||||
social_command: repos.social_command.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
},
|
||||
query: SocialQueryDeps {
|
||||
follow_graph: repos.follow_graph.clone(),
|
||||
block_query: repos.block_query.clone(),
|
||||
},
|
||||
},
|
||||
users: UsersGroup {
|
||||
get_local_profile: GetLocalProfileDeps {
|
||||
stats: repos.stats.clone(),
|
||||
diary: repos.diary.clone(),
|
||||
social_query: repos.follow_graph.clone(),
|
||||
user: repos.user.clone(),
|
||||
instance: instance.clone(),
|
||||
},
|
||||
get_federated_profile_stats: GetFederatedProfileStatsDeps {
|
||||
stats: repos.stats.clone(),
|
||||
diary: repos.diary.clone(),
|
||||
social_query: repos.follow_graph.clone(),
|
||||
},
|
||||
get_page_viewer: GetPageViewerDeps {
|
||||
user: repos.user.clone(),
|
||||
follow_graph: repos.follow_graph.clone(),
|
||||
},
|
||||
resolve_username: ResolveUsernameDeps {
|
||||
user: repos.user.clone(),
|
||||
},
|
||||
get_profile_settings: GetProfileSettingsDeps {
|
||||
user: repos.user.clone(),
|
||||
profile_fields: repos.profile_fields.clone(),
|
||||
instance: instance.clone(),
|
||||
},
|
||||
get_users_list: GetUsersListDeps {
|
||||
user: repos.user.clone(),
|
||||
federation_admin: repos.federation_admin.clone(),
|
||||
},
|
||||
update_profile: UpdateProfileDeps {
|
||||
user: repos.user.clone(),
|
||||
object_storage: services.object_storage.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
},
|
||||
delete_account: DeleteAccountDeps {
|
||||
user: repos.user.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
},
|
||||
get_current_profile: GetCurrentProfileDeps {
|
||||
user: repos.user.clone(),
|
||||
},
|
||||
update_profile_fields: UpdateProfileFieldsDeps {
|
||||
profile_fields: repos.profile_fields.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
},
|
||||
get_settings: GetSettingsDeps {
|
||||
user_settings: repos.user_settings.clone(),
|
||||
},
|
||||
update_settings: UpdateSettingsDeps {
|
||||
user_settings: repos.user_settings.clone(),
|
||||
},
|
||||
authorize_admin: AuthorizeAdminDeps {
|
||||
user: repos.user.clone(),
|
||||
},
|
||||
get_federated_profile: GetFederatedProfileDeps {
|
||||
federated_profile: repos.federated_profile.clone(),
|
||||
},
|
||||
},
|
||||
watchlist: WatchlistGroup {
|
||||
add: WatchlistAddDeps {
|
||||
movie_command: repos.movie_command.clone(),
|
||||
movie_query: repos.movie_query.clone(),
|
||||
metadata: services.metadata.clone(),
|
||||
watchlist: repos.watchlist.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
},
|
||||
get_watchlist_for_owner: GetWatchlistForOwnerDeps {
|
||||
user: repos.user.clone(),
|
||||
watchlist: repos.watchlist.clone(),
|
||||
remote_watchlist: repos.remote_watchlist.clone(),
|
||||
},
|
||||
get_watchlist: GetWatchlistDeps {
|
||||
watchlist: repos.watchlist.clone(),
|
||||
},
|
||||
is_on_watchlist: IsOnWatchlistDeps {
|
||||
watchlist: repos.watchlist.clone(),
|
||||
},
|
||||
remove_from_watchlist: RemoveFromWatchlistDeps {
|
||||
watchlist: repos.watchlist.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
},
|
||||
},
|
||||
wrapup: WrapupGroup {
|
||||
get_ready_report: GetReadyReportDeps {
|
||||
wrapup_repo: repos.wrapup_repo.clone(),
|
||||
},
|
||||
delete_wrapup: DeleteWrapUpDeps {
|
||||
wrapup_repo: repos.wrapup_repo.clone(),
|
||||
},
|
||||
generate: GenerateWrapUpDeps {
|
||||
wrapup_repo: repos.wrapup_repo.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
},
|
||||
get_wrapup: GetWrapUpDeps {
|
||||
wrapup_repo: repos.wrapup_repo.clone(),
|
||||
},
|
||||
list_wrapups: ListWrapUpsDeps {
|
||||
wrapup_repo: repos.wrapup_repo.clone(),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The worker binary's assembly point: the five deps structs that have no consumer
|
||||
/// the server binary can ever reach, built straight from `DatabaseOutput` — the
|
||||
/// worker cannot honestly construct a `Repositories` (it lacks the six
|
||||
/// federation-sourced ports) but every field this function reads is on
|
||||
/// `DatabaseOutput` — plus `application::WorkerServices`, the strict subset of
|
||||
/// ports the worker actually constructs.
|
||||
pub fn build_worker_deps(
|
||||
db: &DatabaseOutput,
|
||||
services: &application::WorkerServices,
|
||||
) -> WorkerDeps {
|
||||
WorkerDeps {
|
||||
enrich_movie: EnrichMovieDeps {
|
||||
movie_query: db.movie_query.clone(),
|
||||
movie_profile: db.movie_profile.clone(),
|
||||
person_command: db.person_command.clone(),
|
||||
search_command: db.search_command.clone(),
|
||||
},
|
||||
reindex_search: ReindexSearchDeps {
|
||||
movie_query: db.movie_query.clone(),
|
||||
movie_profile: db.movie_profile.clone(),
|
||||
search_command: db.search_command.clone(),
|
||||
person_command: db.person_command.clone(),
|
||||
person_query: db.person_query.clone(),
|
||||
},
|
||||
merge_duplicates: MergeDuplicatesDeps {
|
||||
movie_query: db.movie_query.clone(),
|
||||
deduplicator: db.deduplicator.clone(),
|
||||
object_storage: services.object_storage.clone(),
|
||||
},
|
||||
enrich_person: EnrichPersonDeps {
|
||||
person_query: db.person_query.clone(),
|
||||
person_enrichment: services.person_enrichment.clone(),
|
||||
person_command: db.person_command.clone(),
|
||||
},
|
||||
handle_requested: HandleWrapUpRequestedDeps {
|
||||
wrapup_repo: db.wrapup_repo.clone(),
|
||||
event_publisher: services.event_publisher.clone(),
|
||||
wrapup_stats: db.wrapup_stats.clone(),
|
||||
},
|
||||
}
|
||||
}
|
||||
165
crates/bootstrap/src/database.rs
Normal file
165
crates/bootstrap/src/database.rs
Normal file
@@ -0,0 +1,165 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Context;
|
||||
use domain::ports::{
|
||||
AuthService, ImageRefCommand, ImageRefQuery, LocalApContentQuery, MetadataClient,
|
||||
MovieDeduplicator, ObjectStorage, PasswordHasher, PosterFetcherClient,
|
||||
RefreshSessionRepository, UserProfileFieldsRepository, WatchEventCommand, WatchEventQuery,
|
||||
WebhookTokenRepository,
|
||||
};
|
||||
|
||||
pub enum DbPool {
|
||||
Sqlite(sqlx::SqlitePool),
|
||||
}
|
||||
|
||||
pub struct DatabaseOutput {
|
||||
pub movie_command: Arc<dyn domain::ports::MovieCommand>,
|
||||
pub movie_query: Arc<dyn domain::ports::MovieQuery>,
|
||||
pub review: Arc<dyn domain::ports::ReviewRepository>,
|
||||
pub diary: Arc<dyn domain::ports::DiaryQuery>,
|
||||
pub stats: Arc<dyn domain::ports::StatsRepository>,
|
||||
pub user: Arc<dyn domain::ports::UserRepository>,
|
||||
pub import_session: Arc<dyn domain::ports::ImportSessionRepository>,
|
||||
pub import_profile: Arc<dyn domain::ports::ImportProfileRepository>,
|
||||
pub movie_profile: Arc<dyn domain::ports::MovieProfileRepository>,
|
||||
pub watchlist: Arc<dyn domain::ports::WatchlistRepository>,
|
||||
pub watch_event_command: Arc<dyn WatchEventCommand>,
|
||||
pub watch_event_query: Arc<dyn WatchEventQuery>,
|
||||
pub webhook_token: Arc<dyn WebhookTokenRepository>,
|
||||
pub person_command: Arc<dyn domain::ports::PersonCommand>,
|
||||
pub person_query: Arc<dyn domain::ports::PersonQuery>,
|
||||
pub search_port: Arc<dyn domain::ports::SearchPort>,
|
||||
pub search_command: Arc<dyn domain::ports::SearchCommand>,
|
||||
pub profile_fields: Arc<dyn UserProfileFieldsRepository>,
|
||||
pub ap_content: Arc<dyn LocalApContentQuery>,
|
||||
pub wrapup_stats: Arc<dyn domain::ports::WrapUpStatsQuery>,
|
||||
pub wrapup_repo: Arc<dyn domain::ports::WrapUpRepository>,
|
||||
pub insights: Arc<dyn domain::ports::InsightsQuery>,
|
||||
pub goal_command: Arc<dyn domain::ports::GoalCommand>,
|
||||
pub goal_query: Arc<dyn domain::ports::GoalQuery>,
|
||||
pub user_settings: Arc<dyn domain::ports::UserSettingsRepository>,
|
||||
pub federation_settings: std::sync::Arc<dyn domain::ports::UserFederationSettingsQuery>,
|
||||
pub remote_goal: Arc<dyn domain::ports::RemoteGoalRepository>,
|
||||
pub refresh_session: Arc<dyn RefreshSessionRepository>,
|
||||
pub deduplicator: Arc<dyn MovieDeduplicator>,
|
||||
pub image_ref_command: Arc<dyn ImageRefCommand>,
|
||||
pub image_ref_query: Arc<dyn ImageRefQuery>,
|
||||
pub follow_command: Arc<dyn domain::ports::FollowCommand>,
|
||||
pub follow_query: Arc<dyn domain::ports::FollowQuery>,
|
||||
pub db_pool: DbPool,
|
||||
}
|
||||
|
||||
pub async fn build_database_adapters(
|
||||
url: &str,
|
||||
instance: &domain::value_objects::InstanceIdentity,
|
||||
) -> anyhow::Result<DatabaseOutput> {
|
||||
let w = sqlite::wire(url)
|
||||
.await
|
||||
.context("SQLite connection failed")?;
|
||||
assemble(w, instance)
|
||||
}
|
||||
|
||||
/// Like [`build_database_adapters`], on a pool the caller already connected
|
||||
/// (migrations still run). Lets tests drive the real wiring on an in-memory pool.
|
||||
pub async fn build_database_adapters_on(
|
||||
pool: sqlx::SqlitePool,
|
||||
instance: &domain::value_objects::InstanceIdentity,
|
||||
) -> anyhow::Result<DatabaseOutput> {
|
||||
let w = sqlite::wire_pool(pool)
|
||||
.await
|
||||
.context("SQLite wiring failed")?;
|
||||
assemble(w, instance)
|
||||
}
|
||||
|
||||
fn assemble(
|
||||
w: sqlite::SqliteWireOutput,
|
||||
instance: &domain::value_objects::InstanceIdentity,
|
||||
) -> anyhow::Result<DatabaseOutput> {
|
||||
let (image_ref_command, image_ref_query) = sqlite::create_image_ref(w.pool.clone());
|
||||
let (pc, pq) = sqlite::create_person_adapter(w.pool.clone());
|
||||
let (sc, sp) = sqlite::create_search_adapter(w.pool.clone());
|
||||
let pf = sqlite::create_profile_fields_repo(w.pool.clone());
|
||||
let we = Arc::new(sqlite::SqliteWatchEventRepository::new(w.pool.clone()));
|
||||
let wt: Arc<dyn WebhookTokenRepository> =
|
||||
Arc::new(sqlite::SqliteWebhookTokenRepository::new(w.pool.clone()));
|
||||
let social = Arc::new(sqlite::SqliteSocialRepository::new(
|
||||
w.pool.clone(),
|
||||
instance.clone(),
|
||||
));
|
||||
Ok(DatabaseOutput {
|
||||
movie_command: w.movie_command,
|
||||
movie_query: w.movie_query,
|
||||
review: w.review,
|
||||
diary: w.diary,
|
||||
stats: w.stats,
|
||||
user: w.user,
|
||||
import_session: w.import_session,
|
||||
import_profile: w.import_profile,
|
||||
movie_profile: w.movie_profile,
|
||||
watchlist: w.watchlist,
|
||||
watch_event_command: we.clone() as _,
|
||||
watch_event_query: we as _,
|
||||
webhook_token: wt,
|
||||
person_command: pc,
|
||||
person_query: pq,
|
||||
search_port: sp,
|
||||
search_command: sc,
|
||||
profile_fields: pf,
|
||||
ap_content: w.ap_content,
|
||||
wrapup_stats: w.wrapup_stats,
|
||||
wrapup_repo: w.wrapup_repo,
|
||||
insights: w.insights,
|
||||
goal_command: w.goal_command,
|
||||
goal_query: w.goal_query,
|
||||
user_settings: w.user_settings,
|
||||
federation_settings: w.federation_settings,
|
||||
remote_goal: w.remote_goal,
|
||||
refresh_session: Arc::new(sqlite::SqliteRefreshSessionAdapter::new(w.pool.clone())) as _,
|
||||
deduplicator: w.deduplicator,
|
||||
image_ref_command,
|
||||
image_ref_query,
|
||||
follow_command: Arc::clone(&social) as _,
|
||||
follow_query: social as _,
|
||||
db_pool: DbPool::Sqlite(w.pool),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_auth_adapters(
|
||||
config: &config::AuthConfig,
|
||||
) -> anyhow::Result<(Arc<dyn AuthService>, Arc<dyn PasswordHasher>)> {
|
||||
auth::create(config)
|
||||
}
|
||||
|
||||
pub fn build_metadata_client(
|
||||
config: &config::MetadataConfig,
|
||||
) -> anyhow::Result<Arc<dyn MetadataClient>> {
|
||||
metadata::create(config)
|
||||
}
|
||||
|
||||
pub fn build_poster_fetcher(
|
||||
config: &config::MetadataConfig,
|
||||
) -> anyhow::Result<Arc<dyn PosterFetcherClient>> {
|
||||
poster_fetcher::create(config)
|
||||
}
|
||||
|
||||
pub fn build_object_storage(
|
||||
config: &config::StorageConfig,
|
||||
) -> anyhow::Result<Arc<dyn ObjectStorage>> {
|
||||
object_storage::create(config)
|
||||
}
|
||||
|
||||
pub fn build_profile_fields_repo(
|
||||
pool: &DbPool,
|
||||
) -> anyhow::Result<Arc<dyn UserProfileFieldsRepository>> {
|
||||
match pool {
|
||||
DbPool::Sqlite(pool) => Ok(sqlite::create_profile_fields_repo(pool.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn warn_if_database_backend_set() {
|
||||
if let Ok(v) = std::env::var("DATABASE_BACKEND")
|
||||
&& v != "sqlite"
|
||||
{
|
||||
tracing::warn!("DATABASE_BACKEND is ignored; SQLite is the only backend");
|
||||
}
|
||||
}
|
||||
77
crates/bootstrap/src/event_bus.rs
Normal file
77
crates/bootstrap/src/event_bus.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(feature = "nats")]
|
||||
use anyhow::Context;
|
||||
use domain::ports::{EventConsumer, EventPublisher};
|
||||
|
||||
use crate::database::DbPool;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum EventBusBackend {
|
||||
Db,
|
||||
#[cfg(feature = "nats")]
|
||||
Nats,
|
||||
}
|
||||
|
||||
impl EventBusBackend {
|
||||
pub fn from_config(config: &config::EventsConfig) -> anyhow::Result<Self> {
|
||||
match config.bus_backend.as_str() {
|
||||
"db" => Ok(Self::Db),
|
||||
#[cfg(feature = "nats")]
|
||||
"nats" => Ok(Self::Nats),
|
||||
#[cfg(not(feature = "nats"))]
|
||||
"nats" => {
|
||||
anyhow::bail!("EVENT_BUS_BACKEND=nats requires the nats feature to be compiled in")
|
||||
}
|
||||
other => anyhow::bail!("unknown EVENT_BUS_BACKEND={other}, expected 'db' or 'nats'"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_publisher(
|
||||
db_pool: &DbPool,
|
||||
config: &config::AppConfig,
|
||||
) -> anyhow::Result<Arc<dyn EventPublisher>> {
|
||||
match EventBusBackend::from_config(&config.events)? {
|
||||
EventBusBackend::Db => {
|
||||
tracing::info!("event bus: DB queue");
|
||||
Ok(match db_pool {
|
||||
DbPool::Sqlite(pool) => {
|
||||
sqlite::SqliteEventQueue::create_publisher(pool.clone(), &config.events).await?
|
||||
}
|
||||
})
|
||||
}
|
||||
#[cfg(feature = "nats")]
|
||||
EventBusBackend::Nats => {
|
||||
let cfg = nats::NatsConfig::from_config(&config.nats)
|
||||
.context("EVENT_BUS_BACKEND=nats requires NATS_URL to be set")?;
|
||||
tracing::info!("event bus: NATS ({})", cfg.url);
|
||||
Ok(nats::create_publisher(cfg).await?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_channel(
|
||||
db_pool: &DbPool,
|
||||
config: &config::AppConfig,
|
||||
) -> anyhow::Result<(Arc<dyn EventPublisher>, Arc<dyn EventConsumer>)> {
|
||||
match EventBusBackend::from_config(&config.events)? {
|
||||
EventBusBackend::Db => {
|
||||
tracing::info!("event bus: DB queue");
|
||||
match db_pool {
|
||||
DbPool::Sqlite(pool) => Ok(sqlite::SqliteEventQueue::create_channel(
|
||||
pool.clone(),
|
||||
&config.events,
|
||||
)
|
||||
.await?),
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "nats")]
|
||||
EventBusBackend::Nats => {
|
||||
let cfg = nats::NatsConfig::from_config(&config.nats)
|
||||
.context("EVENT_BUS_BACKEND=nats requires NATS_URL to be set")?;
|
||||
tracing::info!("event bus: NATS ({})", cfg.url);
|
||||
Ok(nats::create_channel(cfg).await?)
|
||||
}
|
||||
}
|
||||
}
|
||||
170
crates/bootstrap/src/federation.rs
Normal file
170
crates/bootstrap/src/federation.rs
Normal file
@@ -0,0 +1,170 @@
|
||||
//! Social and federation wiring for the server and worker.
|
||||
//!
|
||||
//! Federation off still wires real local social behaviour (`LocalSocialService`):
|
||||
//! the follow graph and block queries must never silently report empty.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use domain::ports::{
|
||||
BlockQuery, EventPublisher, FederatedProfileQuery, FederationAdminQuery, FollowGraphQuery,
|
||||
RemoteWatchlistRepository, SocialCommand,
|
||||
};
|
||||
use domain::value_objects::InstanceIdentity;
|
||||
|
||||
use crate::database::DatabaseOutput;
|
||||
|
||||
pub struct ServerSocial {
|
||||
pub ap_router: axum::Router,
|
||||
#[cfg(feature = "federation")]
|
||||
pub ap_document: Arc<dyn domain::ports::ApDocumentPort>,
|
||||
#[cfg(feature = "federation")]
|
||||
pub ap_blocklist: Arc<dyn domain::ports::InstanceBlocklistPort>,
|
||||
pub social_command: Arc<dyn SocialCommand>,
|
||||
pub follow_graph: Arc<dyn FollowGraphQuery>,
|
||||
pub block_query: Arc<dyn BlockQuery>,
|
||||
pub remote_watchlist: Arc<dyn RemoteWatchlistRepository>,
|
||||
pub federation_admin: Arc<dyn FederationAdminQuery>,
|
||||
pub federated_profile: Option<Arc<dyn FederatedProfileQuery>>,
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "federation"))]
|
||||
pub async fn wire_server_social(
|
||||
db: &DatabaseOutput,
|
||||
instance: &InstanceIdentity,
|
||||
_config: &config::AppConfig,
|
||||
_event_publisher: &Arc<dyn EventPublisher>,
|
||||
) -> anyhow::Result<ServerSocial> {
|
||||
let local = Arc::new(application::social::local_service::LocalSocialService::new(
|
||||
Arc::clone(&db.user),
|
||||
Arc::clone(&db.follow_command),
|
||||
Arc::clone(&db.follow_query),
|
||||
instance.clone(),
|
||||
));
|
||||
Ok(ServerSocial {
|
||||
ap_router: axum::Router::new(),
|
||||
social_command: Arc::clone(&local) as Arc<dyn SocialCommand>,
|
||||
follow_graph: Arc::clone(&local) as Arc<dyn FollowGraphQuery>,
|
||||
block_query: local as Arc<dyn BlockQuery>,
|
||||
remote_watchlist: Arc::new(domain::ports::noop::NoopRemoteWatchlistRepository),
|
||||
// The empty list this noop returns is an invariant, not an approximation:
|
||||
// federation-off, `LocalSocialService::follow_resolved` hard-errors on any
|
||||
// non-Local target and block/unblock always error, so no remote follow can
|
||||
// ever be persisted through this wiring. (Stale rows from an instance
|
||||
// previously built federation-ON are the one exception — display staleness
|
||||
// only; see ADR-0009.)
|
||||
federation_admin: Arc::new(domain::ports::noop::NoopFederationAdminQuery),
|
||||
federated_profile: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(feature = "federation")]
|
||||
pub async fn wire_server_social(
|
||||
db: &DatabaseOutput,
|
||||
instance: &InstanceIdentity,
|
||||
config: &config::AppConfig,
|
||||
event_publisher: &Arc<dyn EventPublisher>,
|
||||
) -> anyhow::Result<ServerSocial> {
|
||||
let crate::database::DbPool::Sqlite(pool) = &db.db_pool;
|
||||
let fed_repos = sqlite_federation::wire(pool.clone(), instance.clone());
|
||||
|
||||
let ap = activitypub::wire(activitypub::ActivityPubDeps {
|
||||
activity_repo: fed_repos.activity,
|
||||
follow_repo: fed_repos.follow,
|
||||
actor_repo: fed_repos.actor,
|
||||
blocklist_repo: fed_repos.blocklist,
|
||||
review_store: fed_repos.review_store,
|
||||
remote_watchlist_repo: fed_repos.remote_watchlist.clone(),
|
||||
remote_goal_repo: Arc::clone(&db.remote_goal),
|
||||
local_ap_content: Arc::clone(&db.ap_content),
|
||||
movie_repo: Arc::clone(&db.movie_query),
|
||||
review_repo: Arc::clone(&db.review),
|
||||
diary_repo: Arc::clone(&db.diary),
|
||||
goal_repo: Arc::clone(&db.goal_query),
|
||||
stats_repo: Arc::clone(&db.stats),
|
||||
user_repo: Arc::clone(&db.user),
|
||||
federation_settings: Arc::clone(&db.federation_settings),
|
||||
follow_command: Arc::clone(&fed_repos.follow_command),
|
||||
follow_query: Arc::clone(&fed_repos.follow_query),
|
||||
instance: instance.clone(),
|
||||
allow_registration: config.server.allow_registration,
|
||||
federation: config.federation.clone(),
|
||||
event_publisher: Arc::clone(event_publisher),
|
||||
})
|
||||
.await?;
|
||||
|
||||
let local_social: Arc<dyn domain::ports::LocalSocial> =
|
||||
Arc::new(application::social::local_service::LocalSocialService::new(
|
||||
Arc::clone(&db.user),
|
||||
Arc::clone(&db.follow_command),
|
||||
Arc::clone(&db.follow_query),
|
||||
instance.clone(),
|
||||
));
|
||||
|
||||
let composite_social = Arc::new(activitypub::CompositeSocialAdapter::new(
|
||||
local_social,
|
||||
ap.service,
|
||||
Arc::clone(&db.user),
|
||||
instance.clone(),
|
||||
));
|
||||
|
||||
Ok(ServerSocial {
|
||||
ap_router: ap.router,
|
||||
ap_document: ap.document,
|
||||
ap_blocklist: ap.blocklist,
|
||||
social_command: composite_social.clone() as Arc<dyn SocialCommand>,
|
||||
follow_graph: composite_social.clone() as Arc<dyn FollowGraphQuery>,
|
||||
block_query: composite_social as Arc<dyn BlockQuery>,
|
||||
remote_watchlist: fed_repos.remote_watchlist,
|
||||
federation_admin: fed_repos.admin_query,
|
||||
federated_profile: Some(sqlite::create_federated_profile_query(
|
||||
pool.clone(),
|
||||
instance.clone(),
|
||||
)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The worker's federation event handlers: the ActivityPub delivery handler and
|
||||
/// the follow-accepted outbox backfill.
|
||||
#[cfg(feature = "federation")]
|
||||
pub async fn wire_worker_handlers(
|
||||
db: &DatabaseOutput,
|
||||
instance: &InstanceIdentity,
|
||||
config: &config::AppConfig,
|
||||
event_publisher: &Arc<dyn EventPublisher>,
|
||||
) -> anyhow::Result<Vec<Arc<dyn domain::ports::EventHandler>>> {
|
||||
let crate::database::DbPool::Sqlite(pool) = &db.db_pool;
|
||||
let fed_repos = sqlite_federation::wire(pool.clone(), instance.clone());
|
||||
|
||||
let ap_wire = activitypub::wire(activitypub::ActivityPubDeps {
|
||||
activity_repo: fed_repos.activity,
|
||||
follow_repo: fed_repos.follow,
|
||||
actor_repo: fed_repos.actor,
|
||||
blocklist_repo: fed_repos.blocklist,
|
||||
review_store: fed_repos.review_store,
|
||||
remote_watchlist_repo: fed_repos.remote_watchlist,
|
||||
remote_goal_repo: Arc::clone(&db.remote_goal),
|
||||
local_ap_content: Arc::clone(&db.ap_content),
|
||||
movie_repo: Arc::clone(&db.movie_query),
|
||||
review_repo: Arc::clone(&db.review),
|
||||
diary_repo: Arc::clone(&db.diary),
|
||||
goal_repo: Arc::clone(&db.goal_query),
|
||||
stats_repo: Arc::clone(&db.stats),
|
||||
user_repo: Arc::clone(&db.user),
|
||||
follow_command: fed_repos.follow_command,
|
||||
follow_query: fed_repos.follow_query,
|
||||
instance: instance.clone(),
|
||||
allow_registration: config.server.allow_registration,
|
||||
federation: config.federation.clone(),
|
||||
event_publisher: Arc::clone(event_publisher),
|
||||
federation_settings: Arc::clone(&db.federation_settings),
|
||||
})
|
||||
.await?;
|
||||
|
||||
tracing::info!("federation event handler registered");
|
||||
Ok(vec![
|
||||
ap_wire.event_handler,
|
||||
Arc::new(crate::follow_backfill_handler::FollowBackfillHandler {
|
||||
backfill: ap_wire.backfill,
|
||||
}),
|
||||
])
|
||||
}
|
||||
49
crates/bootstrap/src/follow_backfill_handler.rs
Normal file
49
crates/bootstrap/src/follow_backfill_handler.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
events::DomainEvent,
|
||||
ports::{ApBackfillPort, EventHandler},
|
||||
value_objects::SocialIdentity,
|
||||
};
|
||||
|
||||
pub struct FollowBackfillHandler {
|
||||
pub backfill: Arc<dyn ApBackfillPort>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl EventHandler for FollowBackfillHandler {
|
||||
async fn handle(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
||||
match event {
|
||||
DomainEvent::FollowAccepted {
|
||||
owner,
|
||||
requester: SocialIdentity::Remote { actor_url },
|
||||
} => {
|
||||
tracing::info!(actor = %actor_url, "follow accepted — looking up outbox for import");
|
||||
let following = self.backfill.get_following(owner.value()).await?;
|
||||
if let Some(actor) = following.iter().find(|a| a.url == *actor_url) {
|
||||
if let Some(outbox_url) = &actor.outbox_url {
|
||||
tracing::info!(outbox = %outbox_url, actor = %actor_url, "importing remote outbox");
|
||||
self.backfill
|
||||
.import_remote_outbox(outbox_url, actor_url)
|
||||
.await?;
|
||||
} else {
|
||||
tracing::warn!(actor = %actor_url, "no outbox URL for accepted follow — skipping import");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
DomainEvent::BackfillFollower {
|
||||
owner_user_id,
|
||||
follower_inbox_url,
|
||||
} => {
|
||||
tracing::info!(owner = %owner_user_id.value(), inbox = %follower_inbox_url, "backfilling local content to new follower");
|
||||
self.backfill
|
||||
.run_backfill_for_follower(owner_user_id.value(), follower_inbox_url.clone())
|
||||
.await
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
28
crates/bootstrap/src/lib.rs
Normal file
28
crates/bootstrap/src/lib.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
//! The composition root: the only crate that names concrete adapters.
|
||||
//!
|
||||
//! `server` and `worker` are thin binaries over [`build_server`] and
|
||||
//! [`build_worker`]; everything between configuration and a running service is
|
||||
//! assembled here (ADR-0005, ADR-0013).
|
||||
|
||||
pub mod build;
|
||||
pub mod database;
|
||||
mod event_bus;
|
||||
mod federation;
|
||||
#[cfg(feature = "federation")]
|
||||
mod follow_backfill_handler;
|
||||
pub mod repositories;
|
||||
mod server;
|
||||
mod tracing_setup;
|
||||
mod worker;
|
||||
|
||||
pub use build::{build_deps, build_worker_deps};
|
||||
pub use database::{DatabaseOutput, DbPool};
|
||||
pub use event_bus::EventBusBackend;
|
||||
pub use repositories::Repositories;
|
||||
pub use server::{ServerApp, build_server, build_server_on};
|
||||
pub use tracing_setup::init_tracing;
|
||||
pub use worker::{WorkerApp, build_worker};
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests/build.rs"]
|
||||
mod build_tests;
|
||||
47
crates/bootstrap/src/repositories.rs
Normal file
47
crates/bootstrap/src/repositories.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use domain::ports::{
|
||||
BlockQuery, DiaryQuery, FederatedProfileQuery, FederationAdminQuery, FollowGraphQuery,
|
||||
GoalCommand, GoalQuery, ImportProfileRepository, ImportSessionRepository, InsightsQuery,
|
||||
MovieCommand, MovieProfileRepository, MovieQuery, PersonCommand, PersonQuery,
|
||||
RefreshSessionRepository, RemoteGoalRepository, RemoteWatchlistRepository, ReviewRepository,
|
||||
SearchCommand, SearchPort, SocialCommand, StatsRepository, UserProfileFieldsRepository,
|
||||
UserRepository, UserSettingsRepository, WatchEventCommand, WatchEventQuery,
|
||||
WatchlistRepository, WebhookTokenRepository, WrapUpRepository, WrapUpStatsQuery,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Repositories {
|
||||
pub movie_command: Arc<dyn MovieCommand>,
|
||||
pub movie_query: Arc<dyn MovieQuery>,
|
||||
pub review: Arc<dyn ReviewRepository>,
|
||||
pub diary: Arc<dyn DiaryQuery>,
|
||||
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_command: Arc<dyn WatchEventCommand>,
|
||||
pub watch_event_query: Arc<dyn WatchEventQuery>,
|
||||
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_command: Arc<dyn SocialCommand>,
|
||||
pub follow_graph: Arc<dyn FollowGraphQuery>,
|
||||
pub block_query: Arc<dyn BlockQuery>,
|
||||
pub federation_admin: Arc<dyn FederationAdminQuery>,
|
||||
pub wrapup_stats: Arc<dyn WrapUpStatsQuery>,
|
||||
pub wrapup_repo: Arc<dyn WrapUpRepository>,
|
||||
pub insights: Arc<dyn InsightsQuery>,
|
||||
pub goal_command: Arc<dyn GoalCommand>,
|
||||
pub goal_query: Arc<dyn GoalQuery>,
|
||||
pub user_settings: Arc<dyn UserSettingsRepository>,
|
||||
pub remote_goal: Arc<dyn RemoteGoalRepository>,
|
||||
pub refresh_session: Arc<dyn RefreshSessionRepository>,
|
||||
pub federated_profile: Option<Arc<dyn FederatedProfileQuery>>,
|
||||
}
|
||||
147
crates/bootstrap/src/server.rs
Normal file
147
crates/bootstrap/src/server.rs
Normal file
@@ -0,0 +1,147 @@
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Context;
|
||||
use application::config::AppConfig as AppSettings;
|
||||
use domain::ports::{DiaryExporter, DocumentParser, EventPublisher};
|
||||
use domain::value_objects::InstanceIdentity;
|
||||
use export::ExportAdapter;
|
||||
use importer::ImporterDocumentParser;
|
||||
use presentation::context::AppContext;
|
||||
use presentation::{openapi, routes, state::AppState};
|
||||
use rss::RssAdapter;
|
||||
|
||||
use crate::database::{self, DatabaseOutput};
|
||||
use crate::{Repositories, event_bus, federation};
|
||||
|
||||
pub struct ServerApp {
|
||||
pub router: axum::Router,
|
||||
pub addr: SocketAddr,
|
||||
}
|
||||
|
||||
/// Wires the whole HTTP application from configuration.
|
||||
pub async fn build_server(config: &config::AppConfig) -> anyhow::Result<ServerApp> {
|
||||
database::warn_if_database_backend_set();
|
||||
let instance = InstanceIdentity::new(config.server.base_url.clone());
|
||||
let db = database::build_database_adapters(&config.database.url, &instance).await?;
|
||||
let router = assemble(config, db, instance)
|
||||
.await
|
||||
.context("Failed to wire dependencies")?;
|
||||
|
||||
// Resolved like `TcpListener::bind(&str)` would, so a hostname HOST keeps working.
|
||||
let bind = format!("{}:{}", config.server.host, config.server.port);
|
||||
let addr = tokio::net::lookup_host(&bind)
|
||||
.await
|
||||
.with_context(|| format!("Invalid HOST/PORT {bind}"))?
|
||||
.next()
|
||||
.with_context(|| format!("HOST/PORT {bind} resolved to no address"))?;
|
||||
Ok(ServerApp { router, addr })
|
||||
}
|
||||
|
||||
/// Builds the same router as [`build_server`] on a caller-provided pool.
|
||||
/// Migrations run on it exactly as they do for the normal path.
|
||||
pub async fn build_server_on(
|
||||
config: &config::AppConfig,
|
||||
pool: sqlx::SqlitePool,
|
||||
) -> anyhow::Result<axum::Router> {
|
||||
let instance = InstanceIdentity::new(config.server.base_url.clone());
|
||||
let db = database::build_database_adapters_on(pool, &instance).await?;
|
||||
assemble(config, db, instance).await
|
||||
}
|
||||
|
||||
async fn assemble(
|
||||
config: &config::AppConfig,
|
||||
db: DatabaseOutput,
|
||||
instance: InstanceIdentity,
|
||||
) -> anyhow::Result<axum::Router> {
|
||||
let app_config = AppSettings::from(config);
|
||||
|
||||
let (auth_service, password_hasher) = database::build_auth_adapters(&config.auth)?;
|
||||
let metadata_client = database::build_metadata_client(&config.metadata)?;
|
||||
let poster_fetcher = database::build_poster_fetcher(&config.metadata)?;
|
||||
let object_storage = database::build_object_storage(&config.storage)?;
|
||||
|
||||
let event_publisher: Arc<dyn EventPublisher> =
|
||||
event_bus::create_publisher(&db.db_pool, config).await?;
|
||||
|
||||
let social = federation::wire_server_social(&db, &instance, config, &event_publisher).await?;
|
||||
|
||||
let review_logger = Arc::new(application::diary::review_logger::DefaultReviewLogger::new(
|
||||
Arc::clone(&db.movie_command),
|
||||
Arc::clone(&db.movie_query),
|
||||
Arc::clone(&db.review),
|
||||
Arc::clone(&db.watchlist),
|
||||
Arc::clone(&metadata_client),
|
||||
Arc::clone(&event_publisher),
|
||||
));
|
||||
|
||||
let repos = Repositories {
|
||||
movie_command: db.movie_command,
|
||||
movie_query: db.movie_query,
|
||||
review: db.review,
|
||||
diary: db.diary,
|
||||
stats: db.stats,
|
||||
user: db.user,
|
||||
import_session: db.import_session,
|
||||
import_profile: db.import_profile,
|
||||
movie_profile: db.movie_profile,
|
||||
watchlist: db.watchlist,
|
||||
watch_event_command: db.watch_event_command,
|
||||
watch_event_query: db.watch_event_query,
|
||||
webhook_token: db.webhook_token,
|
||||
person_command: db.person_command,
|
||||
person_query: db.person_query,
|
||||
search_port: db.search_port,
|
||||
search_command: db.search_command,
|
||||
profile_fields: db.profile_fields,
|
||||
remote_watchlist: social.remote_watchlist,
|
||||
social_command: social.social_command,
|
||||
follow_graph: social.follow_graph,
|
||||
block_query: social.block_query,
|
||||
federation_admin: social.federation_admin,
|
||||
wrapup_stats: db.wrapup_stats,
|
||||
wrapup_repo: db.wrapup_repo,
|
||||
insights: db.insights,
|
||||
goal_command: db.goal_command,
|
||||
goal_query: db.goal_query,
|
||||
user_settings: db.user_settings,
|
||||
remote_goal: db.remote_goal,
|
||||
refresh_session: db.refresh_session,
|
||||
federated_profile: social.federated_profile,
|
||||
};
|
||||
|
||||
let services = application::Services {
|
||||
auth: auth_service,
|
||||
password_hasher,
|
||||
metadata: metadata_client,
|
||||
poster_fetcher,
|
||||
object_storage,
|
||||
event_publisher,
|
||||
diary_exporter: Arc::new(ExportAdapter) as Arc<dyn DiaryExporter>,
|
||||
document_parser: Arc::new(ImporterDocumentParser) as Arc<dyn DocumentParser>,
|
||||
review_logger,
|
||||
person_enrichment: None,
|
||||
};
|
||||
|
||||
let deps = Arc::new(crate::build_deps(&repos, &services, &app_config, &instance));
|
||||
|
||||
let app_ctx = AppContext {
|
||||
deps,
|
||||
services,
|
||||
config: app_config,
|
||||
instance,
|
||||
#[cfg(feature = "federation")]
|
||||
ap_document: social.ap_document,
|
||||
#[cfg(feature = "federation")]
|
||||
ap_blocklist: social.ap_blocklist,
|
||||
};
|
||||
|
||||
let state = AppState {
|
||||
app_ctx,
|
||||
rss_renderer: Arc::new(RssAdapter::new(config.server.base_url.clone())),
|
||||
};
|
||||
Ok(openapi::serve(routes::build_router(
|
||||
state,
|
||||
social.ap_router,
|
||||
)))
|
||||
}
|
||||
1079
crates/bootstrap/src/tests/build.rs
Normal file
1079
crates/bootstrap/src/tests/build.rs
Normal file
File diff suppressed because it is too large
Load Diff
25
crates/bootstrap/src/tracing_setup.rs
Normal file
25
crates/bootstrap/src/tracing_setup.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||
|
||||
/// Installs the global subscriber. `RUST_LOG` overrides `default_directives`.
|
||||
pub fn init_tracing(default_directives: &str) {
|
||||
tracing_subscriber::registry()
|
||||
.with(log_filter(default_directives))
|
||||
.with(tracing_subscriber::fmt::layer())
|
||||
.init();
|
||||
}
|
||||
|
||||
/// `RUST_LOG` names the crates to trace in detail; anything it doesn't name
|
||||
/// still reports warnings and errors. Without a baseline, a filter like
|
||||
/// `presentation=debug` silently drops adapter errors (e.g. the sqlx detail
|
||||
/// behind "Database operation failed").
|
||||
fn log_filter(default: &str) -> tracing_subscriber::EnvFilter {
|
||||
let directives = std::env::var("RUST_LOG").unwrap_or_else(|_| default.to_string());
|
||||
let has_baseline = directives
|
||||
.split(',')
|
||||
.any(|d| !d.trim().is_empty() && !d.contains('='));
|
||||
if has_baseline {
|
||||
tracing_subscriber::EnvFilter::new(directives)
|
||||
} else {
|
||||
tracing_subscriber::EnvFilter::new(format!("warn,{directives}"))
|
||||
}
|
||||
}
|
||||
231
crates/bootstrap/src/worker.rs
Normal file
231
crates/bootstrap/src/worker.rs
Normal file
@@ -0,0 +1,231 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use application::config::AppConfig as AppSettings;
|
||||
use application::{
|
||||
MovieDiscoveryIndexer, SearchCleanupHandler, SearchReindexHandler, worker::WorkerService,
|
||||
};
|
||||
use domain::ports::{EventHandler, MovieEnrichmentClient, PeriodicJob, PersonEnrichmentClient};
|
||||
use domain::value_objects::InstanceIdentity;
|
||||
|
||||
use crate::{database, event_bus};
|
||||
|
||||
pub struct WorkerApp {
|
||||
pub service: WorkerService,
|
||||
}
|
||||
|
||||
/// Wires the background worker: event handlers, periodic jobs (already
|
||||
/// spawned) and the consumer. Run it with `service.run(shutdown)`.
|
||||
pub async fn build_worker(config: &config::AppConfig) -> anyhow::Result<WorkerApp> {
|
||||
database::warn_if_database_backend_set();
|
||||
let app_config = AppSettings::from(config);
|
||||
let instance = InstanceIdentity::new(app_config.base_url.clone());
|
||||
|
||||
let metadata_client = metadata::create(&config.metadata)?;
|
||||
let poster_fetcher = poster_fetcher::create(&config.metadata)?;
|
||||
let object_storage = object_storage::create(&config.storage)?;
|
||||
|
||||
// TMDb client detection happens before `build_worker_deps` so the optional
|
||||
// person-enrichment port can be handed to `WorkerServices` up front.
|
||||
let tmdb_client = match tmdb_enrichment::TmdbEnrichmentClient::from_config(&config.metadata) {
|
||||
Ok(client) => {
|
||||
tracing::info!("TMDb enrichment enabled");
|
||||
Some(Arc::new(client))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("TMDb enrichment disabled: {e}");
|
||||
None
|
||||
}
|
||||
};
|
||||
let person_enrichment: Option<Arc<dyn PersonEnrichmentClient>> = tmdb_client
|
||||
.clone()
|
||||
.map(|c| c as Arc<dyn PersonEnrichmentClient>);
|
||||
|
||||
let db = database::build_database_adapters(&config.database.url, &instance).await?;
|
||||
let (event_publisher_arc, consumer_arc) =
|
||||
event_bus::create_channel(&db.db_pool, config).await?;
|
||||
|
||||
let worker_services = application::WorkerServices {
|
||||
object_storage: Arc::clone(&object_storage),
|
||||
event_publisher: Arc::clone(&event_publisher_arc),
|
||||
person_enrichment,
|
||||
};
|
||||
let worker_deps = crate::build_worker_deps(&db, &worker_services);
|
||||
|
||||
let image_ref_command = Arc::clone(&db.image_ref_command);
|
||||
let image_ref_query = Arc::clone(&db.image_ref_query);
|
||||
|
||||
#[cfg(feature = "federation")]
|
||||
let federation_handlers =
|
||||
crate::federation::wire_worker_handlers(&db, &instance, config, &event_publisher_arc)
|
||||
.await?;
|
||||
|
||||
let movie_command = db.movie_command;
|
||||
let movie_query = db.movie_query;
|
||||
let user = db.user;
|
||||
let import_session = db.import_session;
|
||||
let movie_profile = db.movie_profile;
|
||||
let watch_event_command = db.watch_event_command;
|
||||
let person_query = db.person_query;
|
||||
let search_command = db.search_command;
|
||||
let wrapup_repo = db.wrapup_repo;
|
||||
let refresh_session = db.refresh_session;
|
||||
|
||||
let event_publisher = event_publisher_arc;
|
||||
let metadata = metadata_client;
|
||||
|
||||
// ── Enrichment ────────────────────────────────────────────────────────────
|
||||
// Both the event handler and the staleness job are gated on TMDB_API_KEY.
|
||||
// Without a key, no MovieEnrichmentRequested events are produced or handled.
|
||||
|
||||
type EnrichmentParts = (
|
||||
Option<Arc<dyn EventHandler>>,
|
||||
Option<Arc<dyn EventHandler>>,
|
||||
Option<Arc<dyn PeriodicJob>>,
|
||||
);
|
||||
let (enrichment_handler, person_enrichment_handler, enrichment_job): EnrichmentParts =
|
||||
match tmdb_client {
|
||||
Some(client) => {
|
||||
let image_fetcher = poster_fetcher::create_image_fetcher(&config.metadata)?;
|
||||
let handler = Arc::new(application::movies::MovieEnrichmentHandler::new(
|
||||
Arc::clone(&client) as Arc<dyn MovieEnrichmentClient>,
|
||||
worker_deps.enrich_movie.movie_query.clone(),
|
||||
worker_deps.enrich_movie.movie_profile.clone(),
|
||||
worker_deps.enrich_movie.person_command.clone(),
|
||||
worker_deps.enrich_movie.search_command.clone(),
|
||||
Arc::clone(&object_storage),
|
||||
image_fetcher,
|
||||
)) as Arc<dyn EventHandler>;
|
||||
let person_handler = Arc::new(application::person::PersonEnrichmentHandler::new(
|
||||
worker_deps.enrich_person.person_query.clone(),
|
||||
worker_deps.enrich_person.person_enrichment.clone(),
|
||||
worker_deps.enrich_person.person_command.clone(),
|
||||
)) as Arc<dyn EventHandler>;
|
||||
let job = Arc::new(application::jobs::EnrichmentStalenessJob::new(
|
||||
Arc::clone(&movie_profile),
|
||||
Arc::clone(&event_publisher),
|
||||
)) as Arc<dyn PeriodicJob>;
|
||||
(Some(handler), Some(person_handler), Some(job))
|
||||
}
|
||||
None => (None, None, None),
|
||||
};
|
||||
|
||||
// ── Image conversion ──────────────────────────────────────────────────────
|
||||
|
||||
let conversion = image_converter::build(
|
||||
&config.image_conversion,
|
||||
Arc::clone(&object_storage),
|
||||
image_ref_command,
|
||||
image_ref_query,
|
||||
Arc::clone(&event_publisher),
|
||||
)?;
|
||||
|
||||
// ── Periodic jobs ─────────────────────────────────────────────────────────
|
||||
|
||||
let mut periodic_jobs: Vec<Arc<dyn PeriodicJob>> = vec![
|
||||
Arc::new(application::jobs::MovieDeduplicationJob::new(
|
||||
worker_deps.merge_duplicates.movie_query.clone(),
|
||||
worker_deps.merge_duplicates.deduplicator.clone(),
|
||||
worker_deps.merge_duplicates.object_storage.clone(),
|
||||
)),
|
||||
Arc::new(application::jobs::ImportSessionCleanupJob::new(
|
||||
import_session.clone(),
|
||||
)),
|
||||
Arc::new(application::jobs::WatchEventCleanupJob::new(
|
||||
watch_event_command.clone(),
|
||||
)),
|
||||
Arc::new(application::jobs::WrapUpAutoGenerateJob::new(
|
||||
Arc::clone(&user),
|
||||
Arc::clone(&wrapup_repo),
|
||||
Arc::clone(&event_publisher),
|
||||
)),
|
||||
Arc::new(application::jobs::WrapUpCleanupJob::new(Arc::clone(
|
||||
&wrapup_repo,
|
||||
))),
|
||||
Arc::new(application::jobs::RefreshSessionCleanupJob::new(
|
||||
Arc::clone(&refresh_session),
|
||||
)),
|
||||
];
|
||||
if let Some(job) = enrichment_job {
|
||||
periodic_jobs.push(job);
|
||||
}
|
||||
if let Some((_, ref conv_job)) = conversion {
|
||||
periodic_jobs.push(Arc::clone(conv_job));
|
||||
}
|
||||
|
||||
for job in periodic_jobs {
|
||||
tokio::spawn(async move {
|
||||
let mut tick = tokio::time::interval(job.interval());
|
||||
loop {
|
||||
tick.tick().await;
|
||||
if let Err(e) = job.run().await {
|
||||
tracing::error!("periodic job failed: {e}");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ── Event handlers ────────────────────────────────────────────────────────
|
||||
|
||||
let handlers: Vec<Arc<dyn EventHandler>> = {
|
||||
let poster = Arc::new(poster_sync::PosterSyncHandler::new(
|
||||
Arc::clone(&movie_command),
|
||||
Arc::clone(&movie_query),
|
||||
Arc::clone(&metadata),
|
||||
Arc::clone(&poster_fetcher),
|
||||
Arc::clone(&object_storage),
|
||||
Arc::clone(&event_publisher),
|
||||
3,
|
||||
)) as Arc<dyn EventHandler>;
|
||||
|
||||
let cleanup = Arc::new(object_storage::ImageCleanupHandler::new(Arc::clone(
|
||||
&object_storage,
|
||||
))) as Arc<dyn EventHandler>;
|
||||
|
||||
let search_cleanup = Arc::new(SearchCleanupHandler::new(
|
||||
Arc::clone(&search_command),
|
||||
Arc::clone(&person_query),
|
||||
)) as Arc<dyn EventHandler>;
|
||||
|
||||
let discovery_indexer = Arc::new(MovieDiscoveryIndexer::new(
|
||||
Arc::clone(&movie_query),
|
||||
Arc::clone(&search_command),
|
||||
)) as Arc<dyn EventHandler>;
|
||||
|
||||
let wrapup_handler = Arc::new(application::wrapup::event_handler::WrapUpEventHandler::new(
|
||||
worker_deps.handle_requested.wrapup_repo.clone(),
|
||||
worker_deps.handle_requested.event_publisher.clone(),
|
||||
worker_deps.handle_requested.wrapup_stats.clone(),
|
||||
)) as Arc<dyn EventHandler>;
|
||||
|
||||
let reindex_handler = Arc::new(SearchReindexHandler::new(worker_deps.reindex_search))
|
||||
as Arc<dyn EventHandler>;
|
||||
|
||||
let mut h = vec![
|
||||
poster,
|
||||
cleanup,
|
||||
search_cleanup,
|
||||
discovery_indexer,
|
||||
wrapup_handler,
|
||||
reindex_handler,
|
||||
];
|
||||
|
||||
#[cfg(feature = "federation")]
|
||||
h.extend(federation_handlers);
|
||||
|
||||
if let Some(e) = enrichment_handler {
|
||||
h.push(e);
|
||||
}
|
||||
if let Some(e) = person_enrichment_handler {
|
||||
h.push(e);
|
||||
}
|
||||
if let Some((ref conv_handler, _)) = conversion {
|
||||
h.push(Arc::clone(conv_handler));
|
||||
}
|
||||
|
||||
h
|
||||
};
|
||||
|
||||
Ok(WorkerApp {
|
||||
service: WorkerService::new(consumer_arc, handlers),
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user