|
| 1 | +use anyhow::Context; |
| 2 | +use reqwest::{IntoUrl, Url}; |
| 3 | +use slog::{Logger, o}; |
| 4 | + |
| 5 | +use mithril_common::StdResult; |
| 6 | + |
| 7 | +use crate::client::AggregatorClient; |
| 8 | + |
| 9 | +/// A builder of [AggregatorClient] |
| 10 | +pub struct AggregatorClientBuilder { |
| 11 | + aggregator_url_result: reqwest::Result<Url>, |
| 12 | + logger: Option<Logger>, |
| 13 | +} |
| 14 | + |
| 15 | +impl AggregatorClientBuilder { |
| 16 | + /// Constructs a new `AggregatorClientBuilder`. |
| 17 | + // |
| 18 | + // This is the same as `AggregatorClient::builder()`. |
| 19 | + pub fn new<U: IntoUrl>(aggregator_url: U) -> Self { |
| 20 | + Self { |
| 21 | + aggregator_url_result: aggregator_url.into_url(), |
| 22 | + logger: None, |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + /// Set the [Logger] to use. |
| 27 | + pub fn with_logger(mut self, logger: Logger) -> Self { |
| 28 | + self.logger = Some(logger); |
| 29 | + self |
| 30 | + } |
| 31 | + |
| 32 | + /// Returns an [AggregatorClient] based on the builder configuration |
| 33 | + pub fn build(self) -> StdResult<AggregatorClient> { |
| 34 | + let aggregator_endpoint = |
| 35 | + enforce_trailing_slash(self.aggregator_url_result.with_context( |
| 36 | + || "Invalid aggregator endpoint, it must be a correctly formed url", |
| 37 | + )?); |
| 38 | + let logger = self.logger.unwrap_or_else(|| Logger::root(slog::Discard, o!())); |
| 39 | + |
| 40 | + Ok(AggregatorClient { |
| 41 | + aggregator_endpoint, |
| 42 | + client: reqwest::Client::new(), |
| 43 | + logger, |
| 44 | + }) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +fn enforce_trailing_slash(url: Url) -> Url { |
| 49 | + // Trailing slash is significant because url::join |
| 50 | + // (https://docs.rs/url/latest/url/struct.Url.html#method.join) will remove |
| 51 | + // the 'path' part of the url if it doesn't end with a trailing slash. |
| 52 | + if url.as_str().ends_with('/') { |
| 53 | + url |
| 54 | + } else { |
| 55 | + let mut url = url.clone(); |
| 56 | + url.set_path(&format!("{}/", url.path())); |
| 57 | + url |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +#[cfg(test)] |
| 62 | +mod tests { |
| 63 | + use super::*; |
| 64 | + |
| 65 | + #[test] |
| 66 | + fn enforce_trailing_slash_for_aggregator_url() { |
| 67 | + let url_without_trailing_slash = Url::parse("http://localhost:8080").unwrap(); |
| 68 | + let url_with_trailing_slash = Url::parse("http://localhost:8080/").unwrap(); |
| 69 | + |
| 70 | + assert_eq!( |
| 71 | + url_with_trailing_slash, |
| 72 | + enforce_trailing_slash(url_without_trailing_slash.clone()) |
| 73 | + ); |
| 74 | + assert_eq!( |
| 75 | + url_with_trailing_slash, |
| 76 | + enforce_trailing_slash(url_with_trailing_slash.clone()) |
| 77 | + ); |
| 78 | + } |
| 79 | +} |
0 commit comments