Skip to content

Commit

Permalink
don't use async-trait for context
Browse files Browse the repository at this point in the history
  • Loading branch information
syphar authored and GuillaumeGomez committed Jan 2, 2025
1 parent 0b3bab3 commit 144032c
Show file tree
Hide file tree
Showing 9 changed files with 29 additions and 33 deletions.
2 changes: 0 additions & 2 deletions src/bin/cratesfyi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use std::str::FromStr;
use std::sync::Arc;

use anyhow::{anyhow, Context as _, Error, Result};
use axum::async_trait;
use clap::{Parser, Subcommand, ValueEnum};
use docs_rs::cdn::CdnBackend;
use docs_rs::db::{self, add_path_into_database, CrateId, Overrides, Pool};
Expand Down Expand Up @@ -877,7 +876,6 @@ macro_rules! lazy {
}
}

#[async_trait]
impl Context for BinContext {
lazy! {
fn build_queue(self) -> BuildQueue = {
Expand Down
4 changes: 2 additions & 2 deletions src/build_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -608,9 +608,9 @@ impl BuildQueue {
/// Builds the top package from the queue. Returns whether there was a package in the queue.
///
/// Note that this will return `Ok(true)` even if the package failed to build.
pub(crate) fn build_next_queue_package(
pub(crate) fn build_next_queue_package<C: Context>(
&self,
context: &dyn Context,
context: &C,
builder: &mut RustwideBuilder,
) -> Result<bool> {
let mut processed = false;
Expand Down
12 changes: 5 additions & 7 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,18 @@ use crate::{
AsyncBuildQueue, AsyncStorage, BuildQueue, Config, Index, InstanceMetrics, RegistryApi,
ServiceMetrics, Storage,
};
use axum::async_trait;
use std::sync::Arc;
use std::{future::Future, sync::Arc};
use tokio::runtime::Runtime;

#[async_trait]
pub trait Context {
fn config(&self) -> Result<Arc<Config>>;
async fn async_build_queue(&self) -> Result<Arc<AsyncBuildQueue>>;
fn async_build_queue(&self) -> impl Future<Output = Result<Arc<AsyncBuildQueue>>> + Send;
fn build_queue(&self) -> Result<Arc<BuildQueue>>;
fn storage(&self) -> Result<Arc<Storage>>;
async fn async_storage(&self) -> Result<Arc<AsyncStorage>>;
async fn cdn(&self) -> Result<Arc<CdnBackend>>;
fn async_storage(&self) -> impl Future<Output = Result<Arc<AsyncStorage>>> + Send;
fn cdn(&self) -> impl Future<Output = Result<Arc<CdnBackend>>> + Send;
fn pool(&self) -> Result<Pool>;
async fn async_pool(&self) -> Result<Pool>;
fn async_pool(&self) -> impl Future<Output = Result<Pool>> + Send;
fn service_metrics(&self) -> Result<Arc<ServiceMetrics>>;
fn instance_metrics(&self) -> Result<Arc<InstanceMetrics>>;
fn index(&self) -> Result<Arc<Index>>;
Expand Down
8 changes: 4 additions & 4 deletions src/docbuilder/rustwide_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ async fn get_configured_toolchain(conn: &mut sqlx::PgConnection) -> Result<Toolc
}
}

fn build_workspace(context: &dyn Context) -> Result<Workspace> {
fn build_workspace<C: Context>(context: &C) -> Result<Workspace> {
let config = context.config()?;

let mut builder = WorkspaceBuilder::new(&config.rustwide_workspace, USER_AGENT)
Expand Down Expand Up @@ -99,7 +99,7 @@ pub struct RustwideBuilder {
}

impl RustwideBuilder {
pub fn init(context: &dyn Context) -> Result<Self> {
pub fn init<C: Context>(context: &C) -> Result<Self> {
let config = context.config()?;
let pool = context.pool()?;
let runtime = context.runtime()?;
Expand All @@ -123,9 +123,9 @@ impl RustwideBuilder {
})
}

pub fn reinitialize_workspace_if_interval_passed(
pub fn reinitialize_workspace_if_interval_passed<C: Context>(
&mut self,
context: &dyn Context,
context: &C,
) -> Result<()> {
let interval = context.config()?.build_workspace_reinitialization_interval;
if self.workspace_initialize_time.elapsed() >= interval {
Expand Down
3 changes: 1 addition & 2 deletions src/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::{
};
use anyhow::Context as _;
use axum::body::Bytes;
use axum::{async_trait, body::Body, http::Request, response::Response as AxumResponse, Router};
use axum::{body::Body, http::Request, response::Response as AxumResponse, Router};
use fn_error_context::context;
use futures_util::{stream::TryStreamExt, FutureExt};
use http_body_util::BodyExt; // for `collect`
Expand Down Expand Up @@ -621,7 +621,6 @@ impl TestEnvironment {
}
}

#[async_trait]
impl Context for TestEnvironment {
fn config(&self) -> Result<Arc<Config>> {
Ok(TestEnvironment::config(self))
Expand Down
5 changes: 3 additions & 2 deletions src/utils/consistency/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const BUILD_PRIORITY: i32 = 15;
///
/// Even when activities fail, the command can just be re-run. While the diff calculation will
/// be repeated, we won't re-execute fixing activities.
pub fn run_check(ctx: &dyn Context, dry_run: bool) -> Result<()> {
pub fn run_check<C: Context>(ctx: &C, dry_run: bool) -> Result<()> {
let index = ctx.index()?;

info!("Loading data from database...");
Expand Down Expand Up @@ -79,9 +79,10 @@ struct HandleResult {
yanks_corrected: u32,
}

fn handle_diff<'a, I>(ctx: &dyn Context, iter: I, dry_run: bool) -> Result<HandleResult>
fn handle_diff<'a, I, C>(ctx: &C, iter: I, dry_run: bool) -> Result<HandleResult>
where
I: Iterator<Item = &'a diff::Difference>,
C: Context,
{
let mut result = HandleResult::default();

Expand Down
8 changes: 4 additions & 4 deletions src/utils/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub async fn watch_registry(
}
}

fn start_registry_watcher(context: &dyn Context) -> Result<(), Error> {
fn start_registry_watcher<C: Context>(context: &C) -> Result<(), Error> {
let build_queue = context.runtime()?.block_on(context.async_build_queue())?;
let config = context.config()?;
let index = context.index()?;
Expand All @@ -69,7 +69,7 @@ fn start_registry_watcher(context: &dyn Context) -> Result<(), Error> {
Ok(())
}

pub fn start_background_repository_stats_updater(context: &dyn Context) -> Result<(), Error> {
pub fn start_background_repository_stats_updater<C: Context>(context: &C) -> Result<(), Error> {
// This call will still skip github repositories updates and continue if no token is provided
// (gitlab doesn't require to have a token). The only time this can return an error is when
// creating a pool or if config fails, which shouldn't happen here because this is run right at
Expand All @@ -91,7 +91,7 @@ pub fn start_background_repository_stats_updater(context: &dyn Context) -> Resul
Ok(())
}

pub fn start_background_queue_rebuild(context: &dyn Context) -> Result<(), Error> {
pub fn start_background_queue_rebuild<C: Context>(context: &C) -> Result<(), Error> {
let runtime = context.runtime()?;
let pool = context.pool()?;
let config = context.config()?;
Expand Down Expand Up @@ -120,7 +120,7 @@ pub fn start_background_queue_rebuild(context: &dyn Context) -> Result<(), Error
Ok(())
}

pub fn start_background_cdn_invalidator(context: &dyn Context) -> Result<(), Error> {
pub fn start_background_cdn_invalidator<C: Context>(context: &C) -> Result<(), Error> {
let metrics = context.instance_metrics()?;
let config = context.config()?;
let pool = context.pool()?;
Expand Down
4 changes: 2 additions & 2 deletions src/utils/queue_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use std::time::Duration;
use std::{fs, io, path::Path, thread};
use tracing::{debug, error, warn};

pub fn queue_builder(
context: &dyn Context,
pub fn queue_builder<C: Context>(
context: &C,
mut builder: RustwideBuilder,
build_queue: Arc<BuildQueue>,
config: Arc<Config>,
Expand Down
16 changes: 8 additions & 8 deletions src/web/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,9 +399,9 @@ async fn set_sentry_transaction_name_from_axum_route(
next.run(request).await
}

async fn apply_middleware(
async fn apply_middleware<C: Context>(
router: AxumRouter,
context: &dyn Context,
context: &C,
template_data: Option<Arc<TemplateData>>,
) -> Result<AxumRouter> {
let config = context.config()?;
Expand Down Expand Up @@ -441,20 +441,20 @@ async fn apply_middleware(
))
}

pub(crate) async fn build_axum_app(
context: &dyn Context,
pub(crate) async fn build_axum_app<C: Context>(
context: &C,
template_data: Arc<TemplateData>,
) -> Result<AxumRouter, Error> {
apply_middleware(routes::build_axum_routes(), context, Some(template_data)).await
}

pub(crate) async fn build_metrics_axum_app(context: &dyn Context) -> Result<AxumRouter, Error> {
pub(crate) async fn build_metrics_axum_app<C: Context>(context: &C) -> Result<AxumRouter, Error> {
apply_middleware(routes::build_metric_routes(), context, None).await
}

pub fn start_background_metrics_webserver(
pub fn start_background_metrics_webserver<C: Context>(
addr: Option<SocketAddr>,
context: &dyn Context,
context: &C,
) -> Result<(), Error> {
let axum_addr: SocketAddr = addr.unwrap_or(DEFAULT_BIND);

Expand Down Expand Up @@ -492,7 +492,7 @@ pub fn start_background_metrics_webserver(
}

#[instrument(skip_all)]
pub fn start_web_server(addr: Option<SocketAddr>, context: &dyn Context) -> Result<(), Error> {
pub fn start_web_server<C: Context>(addr: Option<SocketAddr>, context: &C) -> Result<(), Error> {
let template_data = Arc::new(TemplateData::new(context.config()?.render_threads)?);

let axum_addr = addr.unwrap_or(DEFAULT_BIND);
Expand Down

0 comments on commit 144032c

Please sign in to comment.