openmeteo-rs 1.0.0

Rust client for the Open-Meteo weather API.
Documentation
//! Previous model runs endpoint builder.

use reqwest::Url;

use super::url::{
    QueryParam, build_endpoint_url, push_api_param, push_api_values, push_display_param,
    push_float_param,
};
use super::validation::{validate_at_most, validate_coordinates, validate_optional_solar_angle};
use crate::response::decode_forecast_json;
use crate::units::{
    CellSelection, PrecipitationUnit, TemperatureUnit, TimeFormat, Timezone, WindSpeedUnit,
};
use crate::variables::{HourlyVar, WeatherModel};
use crate::{Client, Error, PreviousRunsResponse, Result};

const MAX_FORECAST_DAYS: u8 = 16;
const MAX_PAST_DAYS: u8 = 92;

/// Builder for the previous model runs `/v1/forecast` endpoint.
#[derive(Debug)]
#[must_use = "previous-runs builders do nothing until `.send().await` is called"]
pub struct PreviousRunsBuilder<'a> {
    client: &'a Client,
    latitude: f64,
    longitude: f64,
    hourly: Vec<HourlyVar>,
    temperature_unit: Option<TemperatureUnit>,
    wind_speed_unit: Option<WindSpeedUnit>,
    precipitation_unit: Option<PrecipitationUnit>,
    timeformat: Option<TimeFormat>,
    timezone: Option<Timezone>,
    past_days: Option<u8>,
    forecast_days: Option<u8>,
    models: Vec<WeatherModel>,
    cell_selection: Option<CellSelection>,
    elevation: Option<f64>,
    tilt: Option<f32>,
    azimuth: Option<f32>,
}

impl<'a> PreviousRunsBuilder<'a> {
    pub(crate) fn new(client: &'a Client, latitude: f64, longitude: f64) -> Self {
        Self {
            client,
            latitude,
            longitude,
            hourly: Vec::new(),
            temperature_unit: None,
            wind_speed_unit: None,
            precipitation_unit: None,
            timeformat: None,
            timezone: None,
            past_days: None,
            forecast_days: None,
            models: Vec::new(),
            cell_selection: None,
            elevation: None,
            tilt: None,
            azimuth: None,
        }
    }

    /// Adds hourly previous-run variables to the request.
    ///
    /// Repeated calls accumulate variables rather than replacing the previous
    /// set.
    pub fn hourly<I>(mut self, variables: I) -> Self
    where
        I: IntoIterator<Item = HourlyVar>,
    {
        self.hourly.extend(variables);
        self
    }

    /// Sets the temperature unit.
    pub fn temperature_unit(mut self, unit: TemperatureUnit) -> Self {
        self.temperature_unit = Some(unit);
        self
    }

    /// Sets the wind-speed unit.
    pub fn wind_speed_unit(mut self, unit: WindSpeedUnit) -> Self {
        self.wind_speed_unit = Some(unit);
        self
    }

    /// Sets the precipitation unit.
    pub fn precipitation_unit(mut self, unit: PrecipitationUnit) -> Self {
        self.precipitation_unit = Some(unit);
        self
    }

    /// Sets the response timestamp format.
    pub fn timeformat(mut self, format: TimeFormat) -> Self {
        self.timeformat = Some(format);
        self
    }

    /// Sets the response timezone.
    pub fn timezone(mut self, timezone: Timezone) -> Self {
        self.timezone = Some(timezone);
        self
    }

    /// Requests forecasts from previous model-run days.
    pub fn past_days(mut self, days: u8) -> Self {
        self.past_days = Some(days);
        self
    }

    /// Requests the forecast horizon in days for each previous run.
    pub fn forecast_days(mut self, days: u8) -> Self {
        self.forecast_days = Some(days);
        self
    }

    /// Pins one or more forecast models.
    pub fn models<I>(mut self, models: I) -> Self
    where
        I: IntoIterator<Item = WeatherModel>,
    {
        self.models.extend(models);
        self
    }

    /// Sets grid-cell selection near coastlines.
    pub fn cell_selection(mut self, selection: CellSelection) -> Self {
        self.cell_selection = Some(selection);
        self
    }

    /// Overrides the automatically detected elevation.
    pub fn elevation(mut self, meters: f64) -> Self {
        self.elevation = Some(meters);
        self
    }

    /// Sets the panel tilt for `global_tilted_irradiance` variables.
    pub fn tilt(mut self, degrees: f32) -> Self {
        self.tilt = Some(degrees);
        self
    }

    /// Sets the panel azimuth for `global_tilted_irradiance` variables.
    pub fn azimuth(mut self, degrees: f32) -> Self {
        self.azimuth = Some(degrees);
        self
    }

    /// Sends the request and decodes the JSON previous-runs response.
    pub async fn send(self) -> Result<PreviousRunsResponse> {
        let url = self.build_url()?;
        let body = self.client.execute(self.client.http.get(url)).await?;
        decode_forecast_json(&body)
    }

    pub(crate) fn build_url(&self) -> Result<Url> {
        self.validate()?;

        let mut params: Vec<QueryParam> = vec![
            ("latitude", self.latitude.to_string()),
            ("longitude", self.longitude.to_string()),
        ];
        push_api_values(&mut params, "hourly", &self.hourly);
        push_api_param(
            &mut params,
            "temperature_unit",
            self.temperature_unit.as_ref(),
        );
        push_api_param(
            &mut params,
            "wind_speed_unit",
            self.wind_speed_unit.as_ref(),
        );
        push_api_param(
            &mut params,
            "precipitation_unit",
            self.precipitation_unit.as_ref(),
        );
        push_api_param(&mut params, "timeformat", self.timeformat.as_ref());
        push_api_param(&mut params, "timezone", self.timezone.as_ref());
        push_display_param(&mut params, "past_days", self.past_days);
        push_display_param(&mut params, "forecast_days", self.forecast_days);
        push_api_values(&mut params, "models", &self.models);
        push_api_param(&mut params, "cell_selection", self.cell_selection.as_ref());
        push_float_param(&mut params, "elevation", self.elevation);
        push_float_param(&mut params, "tilt", self.tilt.map(Into::into));
        push_float_param(&mut params, "azimuth", self.azimuth.map(Into::into));

        build_endpoint_url(
            &self.client.previous_runs_base,
            "previous_runs_base_url",
            "v1/forecast",
            self.client.api_key.as_deref(),
            params,
        )
    }

    fn validate(&self) -> Result<()> {
        validate_coordinates(self.latitude, self.longitude)?;
        if self.hourly.is_empty() {
            return Err(Error::InvalidParam {
                field: "variables",
                reason: "set at least one hourly variable".into(),
            });
        }
        validate_at_most("past_days", self.past_days, MAX_PAST_DAYS)?;
        validate_at_most("forecast_days", self.forecast_days, MAX_FORECAST_DAYS)?;
        validate_optional_solar_angle("tilt", self.tilt, 0.0..=90.0)?;
        validate_optional_solar_angle("azimuth", self.azimuth, -180.0..=180.0)?;

        for var in &self.hourly {
            var.validate_weather_request()?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{HourlyVar, TemperatureUnit, Timezone, WeatherModel};

    #[test]
    fn build_previous_runs_url_with_hourly_variables() {
        let client = Client::builder()
            .previous_runs_base_url("https://example.com/previous?token=abc")
            .unwrap()
            .build()
            .unwrap();

        let url = client
            .previous_runs(47.3769, 8.5417)
            .hourly([
                HourlyVar::Temperature2m,
                HourlyVar::other("temperature_2m_previous_day1"),
            ])
            .timezone(Timezone::Iana("Europe/Zurich".to_owned()))
            .temperature_unit(TemperatureUnit::Fahrenheit)
            .past_days(1)
            .forecast_days(2)
            .models([WeatherModel::EcmwfIfs025])
            .build_url()
            .unwrap();

        assert_eq!(
            url.as_str(),
            "https://example.com/previous/v1/forecast?token=abc&latitude=47.3769&longitude=8.5417&hourly=temperature_2m%2Ctemperature_2m_previous_day1&temperature_unit=fahrenheit&timezone=Europe%2FZurich&past_days=1&forecast_days=2&models=ecmwf_ifs025"
        );
    }

    #[test]
    fn build_previous_runs_url_with_api_key_on_public_base() {
        let client = Client::builder()
            .previous_runs_base_url("https://example.com")
            .unwrap()
            .api_key("secret")
            .build()
            .unwrap();

        let url = client
            .previous_runs(47.3769, 8.5417)
            .hourly([HourlyVar::Temperature2m])
            .build_url()
            .unwrap();

        assert_eq!(
            url.as_str(),
            "https://example.com/v1/forecast?latitude=47.3769&longitude=8.5417&hourly=temperature_2m&apikey=secret"
        );
    }

    #[test]
    fn rejects_empty_previous_runs_variable_set() {
        let client = Client::new();
        let err = client
            .previous_runs(47.3769, 8.5417)
            .build_url()
            .unwrap_err();

        assert!(matches!(
            err,
            Error::InvalidParam {
                field: "variables",
                ..
            }
        ));
    }

    #[test]
    fn rejects_out_of_range_previous_runs_windows() {
        let client = Client::new();
        let err = client
            .previous_runs(47.3769, 8.5417)
            .hourly([HourlyVar::Temperature2m])
            .forecast_days(17)
            .build_url()
            .unwrap_err();

        assert!(matches!(
            err,
            Error::InvalidParam {
                field: "forecast_days",
                ..
            }
        ));
    }
}