//! `POST /v1/natal`: birth data -> place -> time zone -> UTC -> chart. use astro_engine::time::{is_valid_julian_date, jd_from_unix_seconds, julian_to_gregorian}; use astro_engine::{ChartInput, ChartOptions, GeoPosition, NatalChart, calculate_chart}; use geo_tz::tz::parse_offset; use geo_tz::{AmbiguityPolicy, Country, GeoError, LocalizedTime, Place, PlaceMatch, ZoneChoice, ZoneSource}; use jiff::civil::{Date, DateTime, Time}; use jiff::tz::Offset; use serde::{Deserialize, Serialize}; use crate::AppState; use crate::error::ApiError; /// Coordinates farther than this from every known place of the given country /// are probably a mistake (wrong country or swapped latitude/longitude). const FAR_FROM_COUNTRY_KM: f64 = 150.0; #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Calendar { #[default] Gregorian, /// Julian calendar date (e.g. Russia before 1918); converted to Gregorian. Julian, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct NatalRequest { /// Optional label, echoed back. #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option, /// Local birth date, `YYYY-MM-DD`. pub date: String, /// Local birth time, `HH:MM` or `HH:MM:SS`; omit if unknown. #[serde(default, skip_serializing_if = "Option::is_none")] pub time: Option, #[serde(default)] pub calendar: Calendar, /// Country of birth: ISO 3166-1 alpha-2/alpha-3 code or English name. pub country: String, /// Place name (any language, accents optional). #[serde(default, skip_serializing_if = "Option::is_none")] pub place: Option, /// First-level region (county/state) to disambiguate `place`. #[serde(default, skip_serializing_if = "Option::is_none")] pub region: Option, /// Exact GeoNames id (e.g. from `GET /v1/places`); takes precedence over `place`. #[serde(default, skip_serializing_if = "Option::is_none")] pub geonames_id: Option, /// Coordinates override the place's coordinates; required without a place. #[serde(default, skip_serializing_if = "Option::is_none")] pub latitude: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub longitude: Option, /// Meters; used only for topocentric positions. #[serde(default, skip_serializing_if = "Option::is_none")] pub elevation: Option, /// IANA time zone override (e.g. `Europe/Budapest`). #[serde(default, skip_serializing_if = "Option::is_none")] pub timezone: Option, /// Fixed UTC offset override (e.g. `+02:00`) when the historical record /// says so; disables time zone rules. #[serde(default, skip_serializing_if = "Option::is_none")] pub utc_offset: Option, /// Handling of local times that occurred twice or not at all due to DST. #[serde(default)] pub ambiguous_time: AmbiguityPolicy, #[serde(default)] pub options: ChartOptions, } #[derive(Debug, Serialize)] pub struct LocationInfo { pub country: Country, #[serde(skip_serializing_if = "Option::is_none")] pub place: Option, pub latitude: f64, pub longitude: f64, pub elevation: f64, /// `place` or `coordinates`: where latitude/longitude come from. pub coordinates_source: &'static str, /// Nearest known populated place when only coordinates were given. #[serde(skip_serializing_if = "Option::is_none")] pub nearest_place: Option, /// Other places matching the name (when `place` was ambiguous). #[serde(skip_serializing_if = "Vec::is_empty")] pub alternatives: Vec, } #[derive(Debug, Serialize)] pub struct NearestPlace { #[serde(flatten)] pub place: Place, pub distance_km: f64, } #[derive(Debug, Serialize)] pub struct TimeInfo { pub calendar: Calendar, /// Date as given in the request. pub date_as_given: String, /// Gregorian date used for the calculation. pub date: String, pub time_known: bool, #[serde(flatten)] pub localized: LocalizedTime, pub zone_source: Option, /// Local mean time at the birth longitude (UT + longitude/15). pub local_mean_time: String, #[serde(skip_serializing_if = "Vec::is_empty")] pub notes: Vec, } #[derive(Debug, Serialize)] pub struct DataSources { pub ephemeris: astro_engine::EphemerisInfo, pub tzdb_version: String, pub geonames_downloaded: Option, pub geonames_attribution: &'static str, } #[derive(Debug, Serialize)] pub struct Meta { pub service: &'static str, pub version: &'static str, pub data_sources: DataSources, } /// One person's chart with the resolved place and time. #[derive(Debug, Serialize)] pub struct NatalResult { pub input: NatalRequest, pub location: LocationInfo, pub time: TimeInfo, #[serde(flatten)] pub chart: NatalChart, pub warnings: Vec, } #[derive(Debug, Serialize)] pub struct NatalResponse { #[serde(flatten)] pub result: NatalResult, pub meta: Meta, } pub fn meta(state: &AppState) -> Meta { Meta { service: env!("CARGO_PKG_NAME"), version: env!("CARGO_PKG_VERSION"), data_sources: DataSources { ephemeris: state.engine.info(), tzdb_version: state.atlas.zones.version.clone(), geonames_downloaded: state.atlas.places.downloaded.clone(), geonames_attribution: "Place data from GeoNames (https://www.geonames.org), CC BY 4.0", }, } } fn bad(msg: impl Into) -> ApiError { ApiError::BadRequest(msg.into()) } fn parse_date(text: &str, calendar: Calendar) -> Result { let parts: Vec<&str> = text.trim().split('-').collect(); let [y, m, d] = parts.as_slice() else { return Err(bad(format!("date must be YYYY-MM-DD, got '{text}'"))); }; let (Ok(y), Ok(m), Ok(d)) = (y.parse::(), m.parse::(), d.parse::()) else { return Err(bad(format!("date must be YYYY-MM-DD, got '{text}'"))); }; if !(1000..=2999).contains(&y) { return Err(bad("year must be between 1000 and 2999")); } let (y, m, d) = match calendar { Calendar::Gregorian => (y, m, d), Calendar::Julian => { if !is_valid_julian_date(y, m, d) { return Err(bad(format!("'{text}' is not a valid Julian calendar date"))); } julian_to_gregorian(y, m, d) } }; Date::new(y as i16, m as i8, d as i8).map_err(|_| bad(format!("'{text}' is not a valid date"))) } fn parse_time(text: &str) -> Result { let err = || bad(format!("time must be HH:MM or HH:MM:SS, got '{text}'")); let nums: Vec = text.trim().split(':').map(|p| p.parse::().map_err(|_| err())).collect::>()?; let (h, m, s) = match nums.as_slice() { [h, m] => (*h, *m, 0), [h, m, s] => (*h, *m, *s), _ => return Err(err()), }; Time::new(h, m, s, 0).map_err(|_| err()) } fn validate_coordinates(lat: f64, lon: f64) -> Result<(), ApiError> { if !(-90.0..=90.0).contains(&lat) || !lat.is_finite() { return Err(bad(format!("latitude must be between -90 and 90, got {lat}"))); } if !(-180.0..=180.0).contains(&lon) || !lon.is_finite() { return Err(bad(format!("longitude must be between -180 and 180, got {lon}"))); } Ok(()) } /// Finds the birth place: GeoNames id > place name; returns the best match and /// the remaining candidates. fn resolve_place( state: &AppState, req: &NatalRequest, country: &Country, warnings: &mut Vec, ) -> Result<(Option, Vec), ApiError> { if let Some(id) = req.geonames_id { let place = state.atlas.places.by_id(id)?; if place.country_code != country.iso2 { return Err(GeoError::PlaceCountryMismatch { id, place: place.name.clone(), actual: place.country_code.clone(), expected: country.iso2.clone(), } .into()); } return Ok((Some(place.clone()), Vec::new())); } let Some(query) = req.place.as_deref().filter(|q| !q.trim().is_empty()) else { return Ok((None, Vec::new())); }; let mut matches = state.atlas.places.search(country, query, req.region.as_deref(), 6); if matches.is_empty() { if req.latitude.is_some() && req.longitude.is_some() { warnings .push(format!("Place '{query}' was not found in {}; the given coordinates are used.", country.name)); return Ok((None, Vec::new())); } // Suggest places from the whole country with a prefix of the query. let prefix: String = query.chars().take(4).collect(); let suggestions = state.atlas.places.search(country, &prefix, None, 5); return Err(ApiError::PlaceNotFound { query: query.into(), country: country.name.clone(), suggestions }); } let best = matches.remove(0); if !matches.is_empty() { warnings.push(format!( "'{query}' matches {} places in {}; the most likely one was used ({}{}). \ Pass geonames_id or region to choose another (see location.alternatives).", matches.len() + 1, country.name, best.place.name, best.place.region.as_deref().map(|r| format!(", {r}")).unwrap_or_default(), )); } Ok((Some(best.place), matches)) } pub fn calculate(state: &AppState, req: NatalRequest) -> Result { let mut warnings = Vec::new(); let mut notes = Vec::new(); // --- date and time ------------------------------------------------------- let date = parse_date(&req.date, req.calendar)?; let time_known = req.time.as_deref().is_some_and(|t| !t.trim().is_empty()); let time = match req.time.as_deref().filter(|t| !t.trim().is_empty()) { Some(t) => parse_time(t)?, None => Time::constant(12, 0, 0, 0), }; let local = DateTime::from_parts(date, time); if req.calendar == Calendar::Julian { notes.push(format!("Julian calendar date {} converted to Gregorian {date}.", req.date.trim())); } let orb_multiplier = req.options.orb_multiplier; if !(orb_multiplier > 0.0 && orb_multiplier <= 3.0) { return Err(bad("options.orb_multiplier must be greater than 0 and at most 3")); } // --- place ---------------------------------------------------------------- let country = state.atlas.places.country(&req.country)?.clone(); let (place, alternatives) = resolve_place(state, &req, &country, &mut warnings)?; let (latitude, longitude, coordinates_source) = match (req.latitude, req.longitude, &place) { (Some(lat), Some(lon), _) => (lat, lon, "coordinates"), (None, None, Some(p)) => (p.latitude, p.longitude, "place"), (Some(_), None, _) | (None, Some(_), _) => { return Err(bad("latitude and longitude must be given together")); } (None, None, None) => return Err(bad("either place, geonames_id or latitude+longitude is required")), }; validate_coordinates(latitude, longitude)?; let elevation = req.elevation.or(place.as_ref().and_then(|p| p.elevation.map(f64::from))).unwrap_or(0.0); let nearest_place = if place.is_none() { state.atlas.places.nearest(&country.iso2, latitude, longitude, |_| true).map(|(p, d)| { if d > FAR_FROM_COUNTRY_KM { warnings.push(format!( "The coordinates are {d:.0} km from the nearest known place in {} ({}); check the country and \ the coordinates (latitude/longitude swapped?).", country.name, p.name )); } NearestPlace { place: p.clone(), distance_km: (d * 10.0).round() / 10.0 } }) } else { None }; // --- time zone ------------------------------------------------------------ if req.utc_offset.is_some() && req.timezone.is_some() { return Err(bad("give either timezone or utc_offset, not both")); } let (mut localized, zone_source) = match req.utc_offset.as_deref() { Some(text) => { let seconds = parse_offset(text).ok_or_else(|| bad(format!("invalid utc_offset '{text}'")))?; notes .push("A fixed UTC offset from the request was used; time zone and DST rules were not applied.".into()); (state.atlas.zones.localize_fixed(local, seconds)?, None) } None => { let ZoneChoice { zone, source } = state.atlas.choose_zone(&country, req.timezone.as_deref(), place.as_ref(), (latitude, longitude))?; if source == ZoneSource::Request && !state.atlas.zones.zones_of(&country.iso2).iter().any(|z| z.name == zone) { warnings.push(format!("Time zone {zone} is not one of the zones of {}.", country.name)); } (state.atlas.zones.localize(&zone, local, req.ambiguous_time)?, Some(source)) } }; if let Some(t) = &localized.transition { warnings.push(format!( "The local time falls into a DST {} ({} -> {}); resolved with '{}'.", match t.kind { geo_tz::TransitionKind::Gap => "gap (non-existent hour)", geo_tz::TransitionKind::Fold => "fold (repeated hour)", }, t.offset_before, t.offset_after, serde_json::to_value(t.resolved_with).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(), )); } if localized.abbreviation == "LMT" && localized.zone.is_some() { // Before standard time, clocks (and birth records) showed the local // mean time of the place itself; tzdb only knows the LMT of the zone's // reference city (e.g. Budapest for all of Hungary). let zone_lmt = localized.utc_offset.clone(); let place_offset = (longitude * 240.0).round() as i32; let zone = localized.zone.take(); localized = state.atlas.zones.localize_fixed(local, place_offset)?; localized.zone = zone; localized.abbreviation = "LMT".into(); notes.push(format!( "No standard time was in use yet: local mean time of the birthplace (longitude {longitude:.4}°, \ UTC{}) was used instead of the zone's reference-city LMT (UTC{zone_lmt}).", localized.utc_offset )); } if date.year() < 1970 && localized.zone.is_some() { notes.push( "Time zone history before 1970 comes from the IANA tzdb backzone data; verify unusual local practices \ (e.g. wartime or regional deviations) against birth records and use utc_offset if they differ." .into(), ); } // --- chart ---------------------------------------------------------------- let ts = localized.timestamp; let jd_ut = jd_from_unix_seconds(ts.as_second() as f64 + ts.subsec_nanosecond() as f64 * 1e-9); let observer = GeoPosition { latitude, longitude, elevation }; let input = ChartInput { jd_ut, observer, time_known, options: req.options }; let mut chart = calculate_chart(state.engine.as_ref(), &input).map_err(|e| ApiError::Calculation(e.to_string()))?; warnings.append(&mut chart.warnings); if let Some((from, to)) = state.engine.info().precise_years && !(from..=to).contains(&(date.year() as i32)) { warnings.push(format!("The date is outside the {from}-{to} range of the installed ephemeris files.")); } let lmt_seconds = ts.as_second() + (longitude * 240.0).round() as i64; let local_mean_time = Offset::UTC .to_datetime(jiff::Timestamp::from_second(lmt_seconds).map_err(|e| ApiError::Internal(e.to_string()))?) .time() .to_string(); Ok(NatalResult { time: TimeInfo { calendar: req.calendar, date_as_given: req.date.trim().to_string(), date: date.to_string(), time_known, localized, zone_source, local_mean_time, notes, }, location: LocationInfo { country, place, latitude, longitude, elevation, coordinates_source, nearest_place, alternatives, }, chart, warnings, input: req, }) } #[cfg(test)] mod tests { use super::*; #[test] fn dates() { assert_eq!(parse_date("1985-07-14", Calendar::Gregorian).unwrap().to_string(), "1985-07-14"); assert_eq!(parse_date("1917-10-25", Calendar::Julian).unwrap().to_string(), "1917-11-07"); assert!(parse_date("1985-02-30", Calendar::Gregorian).is_err()); assert!(parse_date("1900-02-29", Calendar::Gregorian).is_err()); assert!(parse_date("1900-02-29", Calendar::Julian).is_ok()); assert!(parse_date("14.07.1985", Calendar::Gregorian).is_err()); assert!(parse_date("0999-01-01", Calendar::Gregorian).is_err()); } #[test] fn times() { assert_eq!(parse_time("14:30").unwrap().to_string(), "14:30:00"); assert_eq!(parse_time("07:05:09").unwrap().to_string(), "07:05:09"); assert!(parse_time("24:00").is_err()); assert!(parse_time("14").is_err()); } }