Add horoscope-api, synastry, and backend services

- horoscope-api: Swiss Ephemeris natal charts, timezone/place resolution,
  POST /v1/natal and POST /v1/synastry
- backend: users with roles, email/password and Google login, saved charts,
  synastries and invites, analyses with credit ledger, public shares, admin
- shared crates: astro-engine, db (migrations), horoscope-client, service-kit
- docker-compose with postgres, legacy Java project for reference

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-15 10:25:35 +00:00
co-authored by Claude Opus 5.5
parent 0b5416df45
commit 3a84110565
148 changed files with 95803 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "horoscope-api"
description = "HTTP API that calculates natal charts from birth data"
edition.workspace = true
version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
astro-engine.workspace = true
geo-tz.workspace = true
service-kit.workspace = true
anyhow.workspace = true
axum.workspace = true
jiff.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
tokio.workspace = true
tower-http.workspace = true
tracing.workspace = true
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
http-body-util = "0.1"
+51
View File
@@ -0,0 +1,51 @@
# syntax=docker/dockerfile:1
#
# Build from the repository root:
# docker build -f services/horoscope-api/Dockerfile -t sorsfonalak/horoscope-api .
#
# All external data (Swiss Ephemeris, IANA tzdb with backzone, GeoNames) is
# downloaded at build time; the running container needs no network access.
ARG RUST_VERSION=1.99
# --- 1. external data and C sources -------------------------------------------
FROM alpine:3.22 AS deps
RUN apk add --no-cache curl build-base gawk unzip
ARG SWISSEPH_VERSION=v2.10.3bfinal
ARG SWISSEPH_EPHE_FILES="sepl_18.se1 semo_18.se1 seas_18.se1"
ARG TZDB_VERSION=2026f
ARG GEONAMES_CITIES=cities500
ARG GEONAMES_FULL_COUNTRIES=HU
COPY scripts/fetch-deps.sh /fetch-deps.sh
RUN SWISSEPH_VERSION="$SWISSEPH_VERSION" SWISSEPH_EPHE_FILES="$SWISSEPH_EPHE_FILES" \
TZDB_VERSION="$TZDB_VERSION" GEONAMES_CITIES="$GEONAMES_CITIES" \
GEONAMES_FULL_COUNTRIES="$GEONAMES_FULL_COUNTRIES" \
sh /fetch-deps.sh /out
# --- 2. static (musl) build ----------------------------------------------------
FROM rust:${RUST_VERSION}-alpine AS build
RUN apk add --no-cache musl-dev
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY crates crates
COPY services services
COPY --from=deps /out/vendor vendor
RUN --mount=type=cache,target=/usr/local/cargo/registry \
--mount=type=cache,target=/app/target \
cargo build --release --locked -p horoscope-api \
&& cp target/release/horoscope-api /horoscope-api
# --- 3. runtime: binary + data only --------------------------------------------
FROM scratch
COPY --from=build /horoscope-api /horoscope-api
COPY --from=deps /out/data /data
COPY --from=deps /out/vendor/swisseph/LICENSE /licenses/swisseph-LICENSE
ENV ASTRO_DATA_DIR=/data \
BIND_ADDR=0.0.0.0:8080 \
LOG_FORMAT=json \
RUST_LOG=info
USER 65532:65532
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD ["/horoscope-api", "healthcheck"]
ENTRYPOINT ["/horoscope-api"]
+98
View File
@@ -0,0 +1,98 @@
use axum::Json;
use axum::extract::rejection::{JsonRejection, QueryRejection};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use geo_tz::{GeoError, PlaceMatch};
use serde::Serialize;
#[derive(Debug, thiserror::Error)]
pub enum ApiError {
#[error("{0}")]
BadRequest(String),
#[error(transparent)]
Geo(#[from] GeoError),
#[error("place not found: '{query}' in {country}")]
PlaceNotFound { query: String, country: String, suggestions: Vec<PlaceMatch> },
#[error("calculation failed: {0}")]
Calculation(String),
#[error("internal error: {0}")]
Internal(String),
/// An error in one person's data of a multi-person request.
#[error("{person}: {source}")]
Person { person: &'static str, source: Box<ApiError> },
}
#[derive(Serialize)]
struct ErrorBody<'a> {
error: ErrorDetail<'a>,
}
#[derive(Serialize)]
struct ErrorDetail<'a> {
code: &'a str,
message: String,
/// Which person of a multi-person request the error refers to.
#[serde(skip_serializing_if = "Option::is_none")]
person: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
suggestions: Option<&'a [PlaceMatch]>,
}
impl ApiError {
pub fn for_person(self, person: &'static str) -> Self {
ApiError::Person { person, source: Box::new(self) }
}
fn status_and_code(&self) -> (StatusCode, &'static str) {
match self {
ApiError::Person { source, .. } => source.status_and_code(),
ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, "bad_request"),
ApiError::PlaceNotFound { .. } => (StatusCode::NOT_FOUND, "place_not_found"),
ApiError::Calculation(_) => (StatusCode::UNPROCESSABLE_ENTITY, "calculation_failed"),
ApiError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"),
ApiError::Geo(e) => match e {
GeoError::UnknownCountry(_) => (StatusCode::BAD_REQUEST, "unknown_country"),
GeoError::UnknownTimeZone(_) => (StatusCode::BAD_REQUEST, "unknown_time_zone"),
GeoError::UnknownPlaceId(_) => (StatusCode::NOT_FOUND, "unknown_place_id"),
GeoError::PlaceCountryMismatch { .. } => (StatusCode::BAD_REQUEST, "place_country_mismatch"),
GeoError::PlaceNotFound { .. } => (StatusCode::NOT_FOUND, "place_not_found"),
GeoError::AmbiguousTime { .. } => (StatusCode::UNPROCESSABLE_ENTITY, "ambiguous_local_time"),
GeoError::NonexistentTime { .. } => (StatusCode::UNPROCESSABLE_ENTITY, "nonexistent_local_time"),
GeoError::InvalidDateTime(_) => (StatusCode::BAD_REQUEST, "invalid_date_time"),
GeoError::NoTimeZone(_) => (StatusCode::UNPROCESSABLE_ENTITY, "no_time_zone"),
GeoError::Data { .. } => (StatusCode::INTERNAL_SERVER_ERROR, "data_error"),
},
}
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let (status, code) = self.status_and_code();
if status.is_server_error() {
tracing::error!(error = %self, "request failed");
}
let (person, inner) = match &self {
ApiError::Person { person, source } => (Some(*person), source.as_ref()),
other => (None, other),
};
let suggestions = match inner {
ApiError::PlaceNotFound { suggestions, .. } if !suggestions.is_empty() => Some(suggestions.as_slice()),
_ => None,
};
let body = ErrorBody { error: ErrorDetail { code, message: self.to_string(), person, suggestions } };
(status, Json(body)).into_response()
}
}
impl From<JsonRejection> for ApiError {
fn from(rejection: JsonRejection) -> Self {
ApiError::BadRequest(rejection.body_text())
}
}
impl From<QueryRejection> for ApiError {
fn from(rejection: QueryRejection) -> Self {
ApiError::BadRequest(rejection.body_text())
}
}
+63
View File
@@ -0,0 +1,63 @@
//! Natal chart and synastry HTTP API.
//!
//! Configuration (environment):
//! * `ASTRO_DATA_DIR` directory with `ephe/`, `zoneinfo/`, `geonames/` (default `./data`)
//! * `BIND_ADDR` listen address (default `0.0.0.0:8080`)
//! * `CORS_ALLOWED_ORIGINS` `*` (default) or a comma-separated list of origins
//! * `LOG_FORMAT` `text` (default) or `json`; `RUST_LOG` sets the level
//!
//! `horoscope-api healthcheck` performs a local health check (for Docker).
mod error;
mod natal;
mod routes;
mod synastry;
#[cfg(test)]
mod tests;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;
use anyhow::Context;
use astro_engine::Ephemeris;
use astro_engine::swiss::SwissEphemeris;
use geo_tz::Atlas;
pub struct AppState {
pub engine: Arc<dyn Ephemeris>,
pub atlas: Atlas,
}
const DEFAULT_BIND_ADDR: &str = "0.0.0.0:8080";
fn load_state() -> anyhow::Result<AppState> {
let data_dir = PathBuf::from(std::env::var("ASTRO_DATA_DIR").unwrap_or_else(|_| "data".into()));
let started = Instant::now();
let engine = SwissEphemeris::new(data_dir.join("ephe"))
.with_context(|| format!("loading ephemeris from {}", data_dir.join("ephe").display()))?;
let atlas = Atlas::load(&data_dir).with_context(|| format!("loading data from {}", data_dir.display()))?;
tracing::info!(
places = atlas.places.len(),
tzdb = %atlas.zones.version,
ephemeris = %engine.info().version,
elapsed_ms = started.elapsed().as_millis() as u64,
"data loaded"
);
Ok(AppState { engine: Arc::new(engine), atlas })
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let addr = service_kit::bind_addr(DEFAULT_BIND_ADDR)?;
if std::env::args().nth(1).as_deref() == Some("healthcheck") {
return service_kit::healthcheck(addr);
}
service_kit::init_logging();
let state = Arc::new(tokio::task::spawn_blocking(load_state).await??);
let app = routes::router(state);
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
tracing::info!(%addr, "listening");
axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?;
Ok(())
}
+435
View File
@@ -0,0 +1,435 @@
//! `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<String>,
/// 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<String>,
#[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<String>,
/// First-level region (county/state) to disambiguate `place`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub region: Option<String>,
/// 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<u64>,
/// Coordinates override the place's coordinates; required without a place.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub latitude: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub longitude: Option<f64>,
/// Meters; used only for topocentric positions.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub elevation: Option<f64>,
/// IANA time zone override (e.g. `Europe/Budapest`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timezone: Option<String>,
/// 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<String>,
/// 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<Place>,
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<NearestPlace>,
/// Other places matching the name (when `place` was ambiguous).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub alternatives: Vec<PlaceMatch>,
}
#[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<ZoneSource>,
/// 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<String>,
}
#[derive(Debug, Serialize)]
pub struct DataSources {
pub ephemeris: astro_engine::EphemerisInfo,
pub tzdb_version: String,
pub geonames_downloaded: Option<String>,
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<String>,
}
#[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<String>) -> ApiError {
ApiError::BadRequest(msg.into())
}
fn parse_date(text: &str, calendar: Calendar) -> Result<Date, ApiError> {
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::<i32>(), m.parse::<u32>(), d.parse::<u32>()) 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<Time, ApiError> {
let err = || bad(format!("time must be HH:MM or HH:MM:SS, got '{text}'"));
let nums: Vec<i8> = text.trim().split(':').map(|p| p.parse::<i8>().map_err(|_| err())).collect::<Result<_, _>>()?;
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<String>,
) -> Result<(Option<Place>, Vec<PlaceMatch>), 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<NatalResult, ApiError> {
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());
}
}
+156
View File
@@ -0,0 +1,156 @@
use std::sync::Arc;
use astro_engine::{AspectSet, Ayanamsa, HouseSystem, LilithType, NodeType, ZodiacType};
use axum::extract::rejection::{JsonRejection, QueryRejection};
use axum::extract::{Query, State};
use axum::http::{HeaderValue, Method};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tower_http::cors::{AllowOrigin, Any, CorsLayer};
use tower_http::trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer};
use tracing::Level;
use crate::AppState;
use crate::error::ApiError;
use crate::natal::{self, NatalRequest, NatalResponse};
use crate::synastry::{self, SynastryRequest, SynastryResponse};
type AppResult<T> = Result<Json<T>, ApiError>;
pub fn router(state: Arc<AppState>) -> Router {
Router::new()
.route("/healthz", get(health))
.route("/v1/info", get(info))
.route("/v1/countries", get(countries))
.route("/v1/places", get(places))
.route("/v1/timezones", get(timezones))
.route("/v1/natal", post(natal_chart))
.route("/v1/synastry", post(synastry_chart))
.layer(cors())
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(Level::INFO))
.on_response(DefaultOnResponse::new().level(Level::INFO)),
)
.with_state(state)
}
fn cors() -> CorsLayer {
let origins = std::env::var("CORS_ALLOWED_ORIGINS").unwrap_or_else(|_| "*".into());
let allow = if origins.trim() == "*" {
AllowOrigin::any()
} else {
AllowOrigin::list(origins.split(',').filter_map(|o| HeaderValue::from_str(o.trim()).ok()))
};
CorsLayer::new().allow_origin(allow).allow_methods([Method::GET, Method::POST]).allow_headers(Any)
}
async fn health() -> Json<Value> {
Json(json!({ "status": "ok" }))
}
async fn info(State(state): State<Arc<AppState>>) -> Json<Value> {
Json(json!({
"meta": natal::meta(&state),
"places_loaded": state.atlas.places.len(),
"options": {
"house_system": HouseSystem::ALL,
"zodiac": [ZodiacType::Tropical, ZodiacType::Sidereal],
"ayanamsa": [
Ayanamsa::Lahiri, Ayanamsa::FaganBradley, Ayanamsa::Raman, Ayanamsa::Krishnamurti,
Ayanamsa::DeLuce, Ayanamsa::Yukteshwar, Ayanamsa::TrueCitra, Ayanamsa::GalacticCenter0Sag,
],
"node_type": [NodeType::True, NodeType::Mean],
"lilith_type": [LilithType::Mean, LilithType::True],
"aspect_set": [AspectSet::Major, AspectSet::Extended],
"ambiguous_time": ["reject", "earlier", "later"],
"calendar": ["gregorian", "julian"],
},
"defaults": astro_engine::ChartOptions::default(),
}))
}
#[derive(Serialize)]
struct CountryEntry<'a> {
#[serde(flatten)]
country: &'a geo_tz::Country,
timezones: Vec<&'a str>,
}
async fn countries(State(state): State<Arc<AppState>>) -> Json<Value> {
let list: Vec<CountryEntry> = state
.atlas
.places
.countries()
.iter()
.map(|c| CountryEntry {
country: c,
timezones: state.atlas.zones.zones_of(&c.iso2).iter().map(|z| z.name.as_str()).collect(),
})
.collect();
Json(json!({ "countries": list }))
}
#[derive(Deserialize)]
struct PlacesQuery {
country: String,
q: String,
region: Option<String>,
limit: Option<usize>,
}
async fn places(
State(state): State<Arc<AppState>>,
query: Result<Query<PlacesQuery>, QueryRejection>,
) -> AppResult<Value> {
let Query(q) = query?;
let country = state.atlas.places.country(&q.country)?;
let limit = q.limit.unwrap_or(10).clamp(1, 50);
let matches = state.atlas.places.search(country, &q.q, q.region.as_deref(), limit);
Ok(Json(json!({ "country": country, "query": q.q, "places": matches })))
}
#[derive(Deserialize)]
struct TimezonesQuery {
country: String,
}
async fn timezones(
State(state): State<Arc<AppState>>,
query: Result<Query<TimezonesQuery>, QueryRejection>,
) -> AppResult<Value> {
let Query(q) = query?;
let country = state.atlas.places.country(&q.country)?;
Ok(Json(json!({
"country": country,
"tzdb_version": state.atlas.zones.version,
"timezones": state.atlas.zones.zones_of(&country.iso2),
})))
}
async fn natal_chart(
State(state): State<Arc<AppState>>,
body: Result<Json<NatalRequest>, JsonRejection>,
) -> AppResult<NatalResponse> {
let Json(request) = body?;
// The ephemeris engine serializes access internally; keep it off the async workers.
let response = tokio::task::spawn_blocking(move || {
natal::calculate(&state, request).map(|result| NatalResponse { result, meta: natal::meta(&state) })
})
.await
.map_err(|e| ApiError::Internal(e.to_string()))??;
Ok(Json(response))
}
async fn synastry_chart(
State(state): State<Arc<AppState>>,
body: Result<Json<SynastryRequest>, JsonRejection>,
) -> AppResult<SynastryResponse> {
let Json(request) = body?;
let response = tokio::task::spawn_blocking(move || synastry::calculate(&state, request))
.await
.map_err(|e| ApiError::Internal(e.to_string()))??;
Ok(Json(response))
}
+58
View File
@@ -0,0 +1,58 @@
//! `POST /v1/synastry`: two sets of birth data -> two natal charts ->
//! inter-chart aspects, house overlays and the composite chart.
use astro_engine::{ChartOptions, Synastry, calculate_synastry};
use serde::{Deserialize, Serialize};
use crate::AppState;
use crate::error::ApiError;
use crate::natal::{self, Meta, NatalRequest, NatalResult};
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SynastryRequest {
pub person1: NatalRequest,
pub person2: NatalRequest,
/// Calculation options for both charts (per-person `options` are not allowed).
#[serde(default)]
pub options: ChartOptions,
}
#[derive(Debug, Serialize)]
pub struct SynastryResponse {
pub person1: NatalResult,
pub person2: NatalResult,
#[serde(flatten)]
pub synastry: Synastry,
pub meta: Meta,
}
fn person_chart(
state: &AppState,
label: &'static str,
mut req: NatalRequest,
options: ChartOptions,
) -> Result<NatalResult, ApiError> {
if req.options != ChartOptions::default() {
return Err(
ApiError::BadRequest("options must be given at the top level, not per person".into()).for_person(label)
);
}
req.options = options;
natal::calculate(state, req).map_err(|e| e.for_person(label))
}
pub fn calculate(state: &AppState, req: SynastryRequest) -> Result<SynastryResponse, ApiError> {
let person1 = person_chart(state, "person1", req.person1, req.options)?;
let person2 = person_chart(state, "person2", req.person2, req.options)?;
let mut synastry = calculate_synastry(&person1.chart, &person2.chart, &req.options);
for (label, p) in [("person1", &person1), ("person2", &person2)] {
if !p.time.time_known {
synastry.warnings.push(format!(
"Birth time of {label} is unknown: its angles are left out of the inter-chart aspects, there are no \
house overlays into its chart, and the composite has no angles or houses."
));
}
}
Ok(SynastryResponse { person1, person2, synastry, meta: natal::meta(state) })
}
+275
View File
@@ -0,0 +1,275 @@
//! End-to-end tests of the HTTP API against the real data directory.
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use astro_engine::swiss::SwissEphemeris;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use geo_tz::Atlas;
use http_body_util::BodyExt;
use serde_json::{Value, json};
use tower::ServiceExt;
use crate::{AppState, routes};
fn state() -> Arc<AppState> {
static STATE: OnceLock<Arc<AppState>> = OnceLock::new();
STATE
.get_or_init(|| {
let data = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../data");
Arc::new(AppState {
engine: Arc::new(SwissEphemeris::new(data.join("ephe")).expect("ephemeris")),
atlas: Atlas::load(&data).expect("atlas"),
})
})
.clone()
}
async fn call(method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
let mut req = Request::builder().method(method).uri(uri);
let body = match body {
Some(v) => {
req = req.header("content-type", "application/json");
Body::from(v.to_string())
}
None => Body::empty(),
};
let resp = routes::router(state()).oneshot(req.body(body).unwrap()).await.unwrap();
let status = resp.status();
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
(status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
}
async fn natal(body: Value) -> (StatusCode, Value) {
call("POST", "/v1/natal", Some(body)).await
}
#[tokio::test]
async fn budapest_1985_full_chart() {
let (status, d) = natal(json!({"date": "1985-07-14", "time": "14:30", "country": "HU", "place": "Budapest"})).await;
assert_eq!(status, StatusCode::OK, "{d}");
assert_eq!(d["time"]["utc"], "1985-07-14T12:30:00Z");
assert_eq!(d["time"]["dst"], true);
assert_eq!(d["time"]["abbreviation"], "CEST");
assert_eq!(d["points"][0]["id"], "sun");
assert_eq!(d["points"][0]["sign"], "cancer");
assert_eq!(d["angles"]["ascendant"]["sign"], "scorpio");
assert_eq!(d["houses"]["cusps"].as_array().unwrap().len(), 12);
assert!(d["aspects"].as_array().unwrap().len() > 10);
assert_eq!(d["summary"]["sect"], "day");
assert_eq!(d["warnings"], json!([]));
assert_eq!(d["meta"]["data_sources"]["tzdb_version"], "2026f");
}
#[tokio::test]
async fn place_lmt_before_standard_time() {
// Debrecen 1880: Hungary had no standard time; Debrecen's own mean time
// (21.6273° E -> +01:26:31) applies, not Budapest's (+01:16:20).
let (status, d) = natal(json!({"date": "1880-03-01", "time": "12:00", "country": "HU", "place": "Debrecen"})).await;
assert_eq!(status, StatusCode::OK, "{d}");
let offset = d["time"]["utc_offset"].as_str().unwrap();
assert!(offset.starts_with("+01:26:"), "{offset}");
assert_eq!(d["time"]["abbreviation"], "LMT");
assert_eq!(d["time"]["zone"], "Europe/Budapest");
}
#[tokio::test]
async fn ambiguous_and_nonexistent_local_times() {
let (status, d) = natal(json!({"date": "2023-10-29", "time": "02:30", "country": "HU", "place": "Szeged"})).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(d["error"]["code"], "ambiguous_local_time");
let (status, d) = natal(json!({
"date": "2023-10-29", "time": "02:30", "country": "HU", "place": "Szeged", "ambiguous_time": "later"
}))
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(d["time"]["utc_offset"], "+01:00");
assert_eq!(d["time"]["transition"]["kind"], "fold");
let (status, d) = natal(json!({"date": "2023-03-26", "time": "02:30", "country": "HU", "place": "Szeged"})).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(d["error"]["code"], "nonexistent_local_time");
}
#[tokio::test]
async fn coordinates_only_in_multi_zone_country() {
let (status, d) =
natal(json!({"date": "1990-01-15", "time": "08:00", "country": "US", "latitude": 39.74, "longitude": -104.99}))
.await;
assert_eq!(status, StatusCode::OK, "{d}");
assert_eq!(d["time"]["zone"], "America/Denver");
assert_eq!(d["time"]["zone_source"], "nearest_place");
assert_eq!(d["location"]["coordinates_source"], "coordinates");
assert!(d["location"]["nearest_place"]["name"].is_string());
}
#[tokio::test]
async fn unknown_time_and_julian_calendar() {
let (status, d) = natal(json!({"date": "1950-03-01", "country": "HU", "place": "Iborfia"})).await;
assert_eq!(status, StatusCode::OK, "{d}");
assert_eq!(d["time"]["time_known"], false);
assert!(d["houses"].is_null() && d["angles"].is_null() && d["lots"].is_null());
let (status, d) = natal(json!({
"date": "1917-10-25", "time": "10:00", "calendar": "julian", "country": "RU", "place": "Moscow"
}))
.await;
assert_eq!(status, StatusCode::OK, "{d}");
assert_eq!(d["time"]["date"], "1917-11-07");
}
#[tokio::test]
async fn validation_errors() {
let cases = [
(json!({"date": "1985-07-14", "country": "HU"}), StatusCode::BAD_REQUEST, "bad_request"),
(json!({"date": "1985-13-01", "country": "HU", "place": "Szeged"}), StatusCode::BAD_REQUEST, "bad_request"),
(json!({"date": "1985-07-14", "country": "XX", "place": "Szeged"}), StatusCode::BAD_REQUEST, "unknown_country"),
(
json!({"date": "1985-07-14", "country": "HU", "place": "Nincsilyenhely"}),
StatusCode::NOT_FOUND,
"place_not_found",
),
(
json!({"date": "1985-07-14", "country": "HU", "latitude": 95.0, "longitude": 19.0}),
StatusCode::BAD_REQUEST,
"bad_request",
),
(
json!({"date": "1985-07-14", "country": "HU", "place": "Szeged", "timezone": "Mars/Base"}),
StatusCode::BAD_REQUEST,
"unknown_time_zone",
),
(
json!({"date": "1985-07-14", "country": "HU", "geonames_id": 683506}),
StatusCode::BAD_REQUEST,
"place_country_mismatch",
),
(
json!({"date": "1985-07-14", "country": "HU", "place": "Szeged", "foo": 1}),
StatusCode::BAD_REQUEST,
"bad_request",
),
(
json!({"date": "1985-07-14", "country": "HU", "place": "Szeged", "options": {"house_system": "nope"}}),
StatusCode::BAD_REQUEST,
"bad_request",
),
];
for (body, status, code) in cases {
let (s, d) = natal(body.clone()).await;
assert_eq!((s, d["error"]["code"].as_str().unwrap_or_default()), (status, code), "{body} -> {d}");
}
}
#[tokio::test]
async fn lookup_endpoints() {
let (status, d) = call("GET", "/v1/places?country=HU&q=szentgyorgy&limit=3", None).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(d["places"].as_array().unwrap().len(), 3);
let (status, d) = call("GET", "/v1/timezones?country=US", None).await;
assert_eq!(status, StatusCode::OK);
assert!(d["timezones"].as_array().unwrap().len() > 20);
let (status, d) = call("GET", "/v1/info", None).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(d["options"]["house_system"][0], "placidus");
let (status, _) = call("GET", "/healthz", None).await;
assert_eq!(status, StatusCode::OK);
let (status, d) = call("GET", "/v1/places?country=HU", None).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{d}");
}
#[tokio::test]
async fn synastry_two_known_times() {
let (status, d) = call(
"POST",
"/v1/synastry",
Some(json!({
"person1": {"name": "A", "date": "1985-07-14", "time": "14:30", "country": "HU", "place": "Budapest"},
"person2": {"name": "B", "date": "1987-02-03", "time": "06:10", "country": "HU", "place": "Szeged"},
"options": {"aspect_set": "extended"}
})),
)
.await;
assert_eq!(status, StatusCode::OK, "{d}");
assert_eq!(d["person1"]["input"]["name"], "A");
assert_eq!(d["person2"]["time"]["abbreviation"], "CET");
assert_eq!(d["person2"]["settings"]["aspect_set"], "extended");
let aspects = d["aspects"].as_array().unwrap();
assert!(aspects.len() > 10);
assert!(aspects.windows(2).all(|w| w[0]["orb"].as_f64() <= w[1]["orb"].as_f64()));
assert!(aspects.iter().any(|a| a["person1"] == "ascendant" || a["person2"] == "ascendant"));
assert_eq!(d["summary"]["aspect_count"], aspects.len());
// Person 1's Sun (Cancer) in person 2's houses, and the reverse direction.
let overlays = d["house_overlays"]["person1_in_person2"].as_array().unwrap();
let sun = overlays.iter().find(|o| o["point"] == "sun").unwrap();
assert_eq!(sun["sign"], "cancer");
assert!((1..=12).contains(&sun["house"].as_u64().unwrap()));
assert!(d["house_overlays"]["person2_in_person1"].as_array().unwrap().len() >= 18);
let comp = &d["composite"];
assert_eq!(comp["houses"]["cusps"].as_array().unwrap().len(), 12);
assert_eq!(comp["angles"]["ascendant"]["longitude"], comp["houses"]["cusps"][0]["longitude"]);
let sun1 = d["person1"]["points"][0]["longitude"].as_f64().unwrap();
let sun2 = d["person2"]["points"][0]["longitude"].as_f64().unwrap();
let mid = comp["points"][0]["longitude"].as_f64().unwrap();
assert!((astro_engine::synastry::midpoint(sun1, sun2) - mid).abs() < 1e-9);
assert!(d["meta"]["data_sources"]["tzdb_version"].is_string());
assert!(d.get("warnings").is_none(), "{}", d["warnings"]);
}
#[tokio::test]
async fn synastry_unknown_time_and_errors() {
let (status, d) = call(
"POST",
"/v1/synastry",
Some(json!({
"person1": {"date": "1985-07-14", "time": "14:30", "country": "HU", "place": "Budapest"},
"person2": {"date": "1990-03-01", "country": "HU", "place": "Pécs"}
})),
)
.await;
assert_eq!(status, StatusCode::OK, "{d}");
assert!(d["house_overlays"]["person1_in_person2"].is_null());
assert!(d["house_overlays"]["person2_in_person1"].is_array());
assert!(d["composite"]["houses"].is_null() && d["composite"]["angles"].is_null());
assert!(d["aspects"].as_array().unwrap().iter().all(|a| a["person2"] != "ascendant"));
assert!(d["warnings"][0].as_str().unwrap().contains("person2"));
let (status, d) = call(
"POST",
"/v1/synastry",
Some(json!({
"person1": {"date": "1985-07-14", "time": "14:30", "country": "HU", "place": "Budapest"},
"person2": {"date": "1990-03-01", "country": "HU", "place": "Nincsilyenhely"}
})),
)
.await;
assert_eq!(status, StatusCode::NOT_FOUND);
assert_eq!(d["error"]["code"], "place_not_found");
assert_eq!(d["error"]["person"], "person2");
assert!(d["error"]["message"].as_str().unwrap().starts_with("person2: "));
let (status, d) = call(
"POST",
"/v1/synastry",
Some(json!({
"person1": {"date": "1985-07-14", "country": "HU", "place": "Budapest",
"options": {"house_system": "koch"}},
"person2": {"date": "1990-03-01", "country": "HU", "place": "Pécs"}
})),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(d["error"]["person"], "person1");
let (status, _) = call("POST", "/v1/synastry", Some(json!({"person1": {"date": "1985-07-14"}}))).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
}