use reqwest::Url;
use time::{Date, PrimitiveDateTime};
use super::url::{
QueryParam, build_endpoint_url, push_api_param, push_api_values, push_display_param,
};
use super::validation::{
format_hour, is_non_zero_u8, is_non_zero_u16, validate_at_most, validate_coordinates,
validate_fixed_range_windows,
};
use crate::response::decode_forecast_json;
use crate::units::{CellSelection, LengthUnit, TimeFormat, Timezone, WindSpeedUnit};
use crate::variables::{
MarineCurrentVar, MarineDailyVar, MarineHourlyVar, MarineMinutely15Var, MarineModel,
};
use crate::{Client, Error, MarineResponse, Result};
const MAX_FORECAST_DAYS: u8 = 8;
const MAX_PAST_DAYS: u8 = 92;
const MAX_FORECAST_HOURS: u16 = 8 * 24;
const MAX_FORECAST_MINUTELY_15: u16 = 8 * 24 * 4;
#[derive(Debug)]
#[must_use = "marine builders do nothing until `.send().await` is called"]
pub struct MarineBuilder<'a> {
client: &'a Client,
latitude: f64,
longitude: f64,
hourly: Vec<MarineHourlyVar>,
minutely_15: Vec<MarineMinutely15Var>,
daily: Vec<MarineDailyVar>,
current: Vec<MarineCurrentVar>,
length_unit: Option<LengthUnit>,
wind_speed_unit: Option<WindSpeedUnit>,
timeformat: Option<TimeFormat>,
timezone: Option<Timezone>,
past_days: Option<u8>,
forecast_days: Option<u8>,
past_hours: Option<u16>,
forecast_hours: Option<u16>,
past_minutely_15: Option<u16>,
forecast_minutely_15: Option<u16>,
date_range: Option<(Date, Date)>,
hour_range: Option<(PrimitiveDateTime, PrimitiveDateTime)>,
models: Vec<MarineModel>,
cell_selection: Option<CellSelection>,
}
impl<'a> MarineBuilder<'a> {
pub(crate) fn new(client: &'a Client, latitude: f64, longitude: f64) -> Self {
Self {
client,
latitude,
longitude,
hourly: Vec::new(),
minutely_15: Vec::new(),
daily: Vec::new(),
current: Vec::new(),
length_unit: None,
wind_speed_unit: None,
timeformat: None,
timezone: None,
past_days: None,
forecast_days: None,
past_hours: None,
forecast_hours: None,
past_minutely_15: None,
forecast_minutely_15: None,
date_range: None,
hour_range: None,
models: Vec::new(),
cell_selection: None,
}
}
pub fn hourly<I>(mut self, variables: I) -> Self
where
I: IntoIterator<Item = MarineHourlyVar>,
{
self.hourly.extend(variables);
self
}
pub fn minutely_15<I>(mut self, variables: I) -> Self
where
I: IntoIterator<Item = MarineMinutely15Var>,
{
self.minutely_15.extend(variables);
self
}
pub fn daily<I>(mut self, variables: I) -> Self
where
I: IntoIterator<Item = MarineDailyVar>,
{
self.daily.extend(variables);
self
}
pub fn current<I>(mut self, variables: I) -> Self
where
I: IntoIterator<Item = MarineCurrentVar>,
{
self.current.extend(variables);
self
}
pub fn length_unit(mut self, unit: LengthUnit) -> Self {
self.length_unit = Some(unit);
self
}
pub fn wind_speed_unit(mut self, unit: WindSpeedUnit) -> Self {
self.wind_speed_unit = Some(unit);
self
}
pub fn timeformat(mut self, format: TimeFormat) -> Self {
self.timeformat = Some(format);
self
}
pub fn timezone(mut self, timezone: Timezone) -> Self {
self.timezone = Some(timezone);
self
}
pub fn past_days(mut self, days: u8) -> Self {
self.past_days = Some(days);
self
}
pub fn forecast_days(mut self, days: u8) -> Self {
self.forecast_days = Some(days);
self
}
pub fn past_hours(mut self, hours: u16) -> Self {
self.past_hours = Some(hours);
self
}
pub fn forecast_hours(mut self, hours: u16) -> Self {
self.forecast_hours = Some(hours);
self
}
pub fn past_minutely_15(mut self, intervals: u16) -> Self {
self.past_minutely_15 = Some(intervals);
self
}
pub fn forecast_minutely_15(mut self, intervals: u16) -> Self {
self.forecast_minutely_15 = Some(intervals);
self
}
pub fn date_range(mut self, start: Date, end: Date) -> Self {
self.date_range = Some((start, end));
self
}
pub fn hour_range(mut self, start: PrimitiveDateTime, end: PrimitiveDateTime) -> Self {
self.hour_range = Some((start, end));
self
}
pub fn models<I>(mut self, models: I) -> Self
where
I: IntoIterator<Item = MarineModel>,
{
self.models.extend(models);
self
}
pub fn cell_selection(mut self, selection: CellSelection) -> Self {
self.cell_selection = Some(selection);
self
}
pub async fn send(self) -> Result<MarineResponse> {
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_values(&mut params, "minutely_15", &self.minutely_15);
push_api_values(&mut params, "daily", &self.daily);
push_api_values(&mut params, "current", &self.current);
push_api_param(&mut params, "length_unit", self.length_unit.as_ref());
push_api_param(
&mut params,
"wind_speed_unit",
self.wind_speed_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.filter(|days| *days > 0),
);
push_display_param(&mut params, "forecast_days", self.forecast_days);
push_display_param(
&mut params,
"past_hours",
self.past_hours.filter(|hours| *hours > 0),
);
push_display_param(
&mut params,
"forecast_hours",
self.forecast_hours.filter(|hours| *hours > 0),
);
push_display_param(
&mut params,
"past_minutely_15",
self.past_minutely_15.filter(|intervals| *intervals > 0),
);
push_display_param(
&mut params,
"forecast_minutely_15",
self.forecast_minutely_15.filter(|intervals| *intervals > 0),
);
if let Some((start, end)) = self.date_range {
params.push(("start_date", start.to_string()));
params.push(("end_date", end.to_string()));
}
if let Some((start, end)) = self.hour_range {
params.push(("start_hour", format_hour(start)?));
params.push(("end_hour", format_hour(end)?));
}
push_api_values(&mut params, "models", &self.models);
push_api_param(&mut params, "cell_selection", self.cell_selection.as_ref());
build_endpoint_url(
&self.client.marine_base,
"marine_base_url",
"v1/marine",
self.client.api_key.as_deref(),
params,
)
}
fn validate(&self) -> Result<()> {
validate_coordinates(self.latitude, self.longitude)?;
if self.hourly.is_empty()
&& self.minutely_15.is_empty()
&& self.daily.is_empty()
&& self.current.is_empty()
{
return Err(Error::InvalidParam {
field: "variables",
reason: "set at least one hourly, minutely_15, daily, or current 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_at_most("forecast_hours", self.forecast_hours, MAX_FORECAST_HOURS)?;
validate_at_most(
"forecast_minutely_15",
self.forecast_minutely_15,
MAX_FORECAST_MINUTELY_15,
)?;
validate_fixed_range_windows(
self.date_range,
self.hour_range,
&[
("past_days", is_non_zero_u8(self.past_days)),
("forecast_days", self.forecast_days.is_some()),
("past_hours", is_non_zero_u16(self.past_hours)),
("forecast_hours", is_non_zero_u16(self.forecast_hours)),
("past_minutely_15", is_non_zero_u16(self.past_minutely_15)),
(
"forecast_minutely_15",
is_non_zero_u16(self.forecast_minutely_15),
),
],
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
LengthUnit, MarineCurrentVar, MarineDailyVar, MarineHourlyVar, MarineMinutely15Var,
MarineModel, Timezone, WindSpeedUnit,
};
use time::macros::{date, datetime};
#[test]
fn build_marine_url_with_all_groups() {
let client = Client::builder()
.marine_base_url("https://example.com/marine?token=abc")
.unwrap()
.build()
.unwrap();
let url = client
.marine(47.0, -8.0)
.hourly([
MarineHourlyVar::WaveHeight,
MarineHourlyVar::OceanCurrentVelocity,
])
.minutely_15([MarineMinutely15Var::SeaLevelHeightMsl])
.daily([MarineDailyVar::WaveHeightMax])
.current([MarineCurrentVar::WaveHeight])
.timezone(Timezone::Iana("Europe/Lisbon".to_owned()))
.length_unit(LengthUnit::Imperial)
.wind_speed_unit(WindSpeedUnit::Kn)
.forecast_days(1)
.models([MarineModel::GfsWave016])
.build_url()
.unwrap();
assert_eq!(
url.as_str(),
"https://example.com/marine/v1/marine?token=abc&latitude=47&longitude=-8&hourly=wave_height%2Cocean_current_velocity&minutely_15=sea_level_height_msl&daily=wave_height_max¤t=wave_height&length_unit=imperial&wind_speed_unit=kn&timezone=Europe%2FLisbon&forecast_days=1&models=ncep_gfswave016"
);
}
#[test]
fn build_marine_url_with_date_and_hour_ranges() {
let client = Client::builder()
.marine_base_url("https://example.com")
.unwrap()
.build()
.unwrap();
let date_url = client
.marine(47.0, -8.0)
.hourly([MarineHourlyVar::WaveHeight])
.date_range(date!(2026 - 04 - 29), date!(2026 - 04 - 30))
.build_url()
.unwrap();
assert_eq!(
date_url.as_str(),
"https://example.com/v1/marine?latitude=47&longitude=-8&hourly=wave_height&start_date=2026-04-29&end_date=2026-04-30"
);
let hour_url = client
.marine(47.0, -8.0)
.hourly([MarineHourlyVar::WaveHeight])
.hour_range(datetime!(2026-04-29 06:00), datetime!(2026-04-29 18:00))
.build_url()
.unwrap();
assert_eq!(
hour_url.as_str(),
"https://example.com/v1/marine?latitude=47&longitude=-8&hourly=wave_height&start_hour=2026-04-29T06%3A00&end_hour=2026-04-29T18%3A00"
);
}
#[test]
fn build_marine_url_with_api_key_on_public_base() {
let client = Client::builder()
.marine_base_url("https://example.com")
.unwrap()
.api_key("secret")
.build()
.unwrap();
let url = client
.marine(47.0, -8.0)
.hourly([MarineHourlyVar::WaveHeight])
.build_url()
.unwrap();
assert_eq!(
url.as_str(),
"https://example.com/v1/marine?latitude=47&longitude=-8&hourly=wave_height&apikey=secret"
);
}
#[test]
fn rejects_empty_marine_variable_set() {
let client = Client::new();
let err = client.marine(47.0, -8.0).build_url().unwrap_err();
assert!(matches!(
err,
Error::InvalidParam {
field: "variables",
..
}
));
}
#[test]
fn rejects_out_of_range_marine_windows() {
let client = Client::new();
let err = client
.marine(47.0, -8.0)
.hourly([MarineHourlyVar::WaveHeight])
.forecast_days(9)
.build_url()
.unwrap_err();
assert!(matches!(
err,
Error::InvalidParam {
field: "forecast_days",
..
}
));
let err = client
.marine(47.0, -8.0)
.hourly([MarineHourlyVar::WaveHeight])
.forecast_hours(193)
.build_url()
.unwrap_err();
assert!(matches!(
err,
Error::InvalidParam {
field: "forecast_hours",
..
}
));
}
#[test]
fn rejects_marine_date_range_with_relative_window() {
let client = Client::new();
let err = client
.marine(47.0, -8.0)
.hourly([MarineHourlyVar::WaveHeight])
.date_range(date!(2026 - 04 - 29), date!(2026 - 04 - 30))
.forecast_days(1)
.build_url()
.unwrap_err();
assert!(matches!(
err,
Error::MutuallyExclusive {
first: "date_range",
second: "forecast_days"
}
));
}
}