Moon and retrograde calendars, "today in the sky" on the own chart
New public pages: /holdnaptar (new and full moons, quarters, eclipses and the Moon's sign changes, month by month, with the Moon of today) and /retrograd (the retrograde periods of Mercury to Pluto with their shadows, and which planets are retrograde now), each with a page per year around the current one. The own chart gets a "Ma az égen" card: the Moon's sign, phase and natal house, the tightest transits to the chart in fixed sentences, and the retrograde planets. No AI, nothing stored. The events come from astro-engine (sampling and bisection, checked against swetest and the 2026 eclipses) through horoscope-api GET /v1/sky and /v1/sky/events; the backend serves them at /v1/public/sky… and keeps them in memory (the sky now for five minutes, a year's events for good). Links in the mobile menu, the footer, the sitemap and the free tools on the home page; the desktop header is unchanged (it is full at 1280 px). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -12,6 +12,7 @@ mod error;
|
||||
mod forecast;
|
||||
mod natal;
|
||||
mod routes;
|
||||
mod sky;
|
||||
mod synastry;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::AppState;
|
||||
use crate::error::ApiError;
|
||||
use crate::forecast::{self, ForecastRequest, ForecastResponse};
|
||||
use crate::natal::{self, NatalRequest, NatalResponse};
|
||||
use crate::sky::{self, EventsQuery, EventsResponse, SkyQuery, SkyResponse};
|
||||
use crate::synastry::{self, SynastryRequest, SynastryResponse};
|
||||
|
||||
type AppResult<T> = Result<Json<T>, ApiError>;
|
||||
@@ -29,6 +30,8 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/natal", post(natal_chart))
|
||||
.route("/v1/synastry", post(synastry_chart))
|
||||
.route("/v1/forecast", post(forecast_year))
|
||||
.route("/v1/sky", get(sky_now))
|
||||
.route("/v1/sky/events", get(sky_events))
|
||||
.layer(cors())
|
||||
// The request log: masked paths, health checks only when they fail.
|
||||
.layer(TraceLayer::new_for_http().make_span_with(service_kit::RequestLog).on_response(service_kit::RequestLog))
|
||||
@@ -163,3 +166,25 @@ async fn forecast_year(
|
||||
.map_err(|e| ApiError::Internal(e.to_string()))??;
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
async fn sky_now(
|
||||
State(state): State<Arc<AppState>>,
|
||||
query: Result<Query<SkyQuery>, QueryRejection>,
|
||||
) -> AppResult<SkyResponse> {
|
||||
let Query(query) = query?;
|
||||
let response = tokio::task::spawn_blocking(move || sky::now(&state, query))
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(e.to_string()))??;
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
async fn sky_events(
|
||||
State(state): State<Arc<AppState>>,
|
||||
query: Result<Query<EventsQuery>, QueryRejection>,
|
||||
) -> AppResult<EventsResponse> {
|
||||
let Query(query) = query?;
|
||||
let response = tokio::task::spawn_blocking(move || sky::events(&state, query))
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(e.to_string()))??;
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
//! The sky by date, the same for everyone (tropical, geocentric):
|
||||
//!
|
||||
//! * `GET /v1/sky?at=&tz=`: the sky at a moment (default now): where the
|
||||
//! planets are, which are retrograde and their next station, the Moon's
|
||||
//! phase, when it changes sign, and the next main phases;
|
||||
//! * `GET /v1/sky/events?year=&tz=`: a calendar year's lunar phases (with the
|
||||
//! eclipses on them), the Moon's sign changes and the retrograde periods
|
||||
//! with their shadows.
|
||||
//!
|
||||
//! Local times are on the clock of `tz` (default Europe/Budapest).
|
||||
|
||||
use astro_engine::chart::{MoonPhaseName, ZodiacPosition};
|
||||
use astro_engine::sky::{
|
||||
LunationKind, RETROGRADING, Station, lunations, moon_ingresses, moon_now, next_station, retrograde_periods,
|
||||
};
|
||||
use astro_engine::{Body, EclipseKind, EclipseType, Frame, ZodiacSign};
|
||||
use geo_tz::tz::format_offset;
|
||||
use jiff::Timestamp;
|
||||
use jiff::tz::TimeZone;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::AppState;
|
||||
use crate::error::ApiError;
|
||||
|
||||
pub const DEFAULT_TZ: &str = "Europe/Budapest";
|
||||
/// The calendar years served.
|
||||
pub const YEARS: std::ops::RangeInclusive<i32> = 1900..=2100;
|
||||
/// Far enough ahead for every planet's next station (Mars may run direct for two years).
|
||||
const STATION_HORIZON_DAYS: f64 = 800.0;
|
||||
|
||||
const UNIX_EPOCH_JD: f64 = 2_440_587.5;
|
||||
|
||||
fn jd_of(ts: Timestamp) -> f64 {
|
||||
ts.as_second() as f64 / 86_400.0 + UNIX_EPOCH_JD
|
||||
}
|
||||
|
||||
fn timestamp_of(jd: f64) -> Result<Timestamp, ApiError> {
|
||||
Timestamp::from_second(((jd - UNIX_EPOCH_JD) * 86_400.0).round() as i64)
|
||||
.map_err(|e| ApiError::Internal(e.to_string()))
|
||||
}
|
||||
|
||||
fn calc(e: astro_engine::EngineError) -> ApiError {
|
||||
ApiError::Calculation(e.to_string())
|
||||
}
|
||||
|
||||
/// A moment in UTC and on the local clock (to the minute).
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct Moment {
|
||||
pub moment_utc: String,
|
||||
/// `YYYY-MM-DDTHH:MM`, rounded to the minute.
|
||||
pub local_time: String,
|
||||
}
|
||||
|
||||
fn moment(jd: f64, tz: &TimeZone) -> Result<Moment, ApiError> {
|
||||
let ts = timestamp_of(jd)?;
|
||||
let minute = Timestamp::from_second((ts.as_second() + 30).div_euclid(60) * 60)
|
||||
.map_err(|e| ApiError::Internal(e.to_string()))?;
|
||||
Ok(Moment { moment_utc: ts.to_string(), local_time: tz.to_datetime(minute).strftime("%Y-%m-%dT%H:%M").to_string() })
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct StationOut {
|
||||
#[serde(flatten)]
|
||||
pub moment: Moment,
|
||||
/// Turns retrograde (`true`) or direct here.
|
||||
pub retrograde: bool,
|
||||
pub position: ZodiacPosition,
|
||||
}
|
||||
|
||||
fn station(s: &Station, tz: &TimeZone) -> Result<StationOut, ApiError> {
|
||||
Ok(StationOut {
|
||||
moment: moment(s.jd_ut, tz)?,
|
||||
retrograde: s.retrograde,
|
||||
position: ZodiacPosition::new(s.longitude),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct EclipseOut {
|
||||
pub kind: EclipseKind,
|
||||
pub eclipse_type: EclipseType,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct LunationOut {
|
||||
pub kind: LunationKind,
|
||||
#[serde(flatten)]
|
||||
pub moment: Moment,
|
||||
/// Where the Moon is.
|
||||
pub position: ZodiacPosition,
|
||||
/// The eclipse at this new or full moon, if any.
|
||||
pub eclipse: Option<EclipseOut>,
|
||||
}
|
||||
|
||||
/// The lunations between two moments, with the eclipses on them.
|
||||
fn lunations_out(state: &AppState, from: f64, to: f64, tz: &TimeZone) -> Result<Vec<LunationOut>, ApiError> {
|
||||
let engine = state.engine.as_ref();
|
||||
let eclipses = engine.eclipses(from - 1.0, to + 1.0).map_err(calc)?;
|
||||
lunations(engine, from, to)
|
||||
.map_err(calc)?
|
||||
.into_iter()
|
||||
.map(|l| {
|
||||
let eclipse = eclipses
|
||||
.iter()
|
||||
.find(|e| {
|
||||
let on = match e.kind {
|
||||
EclipseKind::Solar => LunationKind::NewMoon,
|
||||
EclipseKind::Lunar => LunationKind::FullMoon,
|
||||
};
|
||||
on == l.kind && (e.jd_ut - l.jd_ut).abs() < 0.6
|
||||
})
|
||||
.map(|e| EclipseOut { kind: e.kind, eclipse_type: e.eclipse_type });
|
||||
Ok(LunationOut {
|
||||
kind: l.kind,
|
||||
moment: moment(l.jd_ut, tz)?,
|
||||
position: ZodiacPosition::new(l.moon_longitude),
|
||||
eclipse,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct IngressOut {
|
||||
#[serde(flatten)]
|
||||
pub moment: Moment,
|
||||
pub sign: ZodiacSign,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct PlanetNow {
|
||||
pub id: Body,
|
||||
pub position: ZodiacPosition,
|
||||
/// Degrees a day (negative: retrograde).
|
||||
pub speed: f64,
|
||||
pub retrograde: bool,
|
||||
/// The next station (the end of a retrograde period, or the start of the next one).
|
||||
pub next_station: Option<StationOut>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct MoonOut {
|
||||
pub position: ZodiacPosition,
|
||||
pub phase: MoonPhaseName,
|
||||
/// Illuminated fraction of the disc (0..1).
|
||||
pub illumination: f64,
|
||||
/// Moon minus Sun, degrees.
|
||||
pub elongation: f64,
|
||||
pub waxing: bool,
|
||||
/// When the Moon enters the next sign.
|
||||
pub sign_change: Option<IngressOut>,
|
||||
/// The next four main phases.
|
||||
pub next_phases: Vec<LunationOut>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SkyResponse {
|
||||
#[serde(flatten)]
|
||||
pub moment: Moment,
|
||||
pub timezone: String,
|
||||
pub utc_offset: String,
|
||||
pub planets: Vec<PlanetNow>,
|
||||
pub moon: MoonOut,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SkyQuery {
|
||||
/// RFC 3339; now when not given.
|
||||
pub at: Option<String>,
|
||||
pub tz: Option<String>,
|
||||
}
|
||||
|
||||
fn zone(state: &AppState, name: Option<&str>) -> Result<(String, TimeZone), ApiError> {
|
||||
let name = name.unwrap_or(DEFAULT_TZ);
|
||||
Ok((name.to_string(), state.atlas.zones.get(name)?))
|
||||
}
|
||||
|
||||
pub fn now(state: &AppState, query: SkyQuery) -> Result<SkyResponse, ApiError> {
|
||||
let (zone_name, tz) = zone(state, query.tz.as_deref())?;
|
||||
let ts = match query.at.as_deref() {
|
||||
Some(at) => at.parse::<Timestamp>().map_err(|_| ApiError::BadRequest("at must be an RFC 3339 time".into()))?,
|
||||
None => Timestamp::now(),
|
||||
};
|
||||
let jd = jd_of(ts);
|
||||
let year = tz.to_datetime(ts).year();
|
||||
if !YEARS.contains(&i32::from(year)) {
|
||||
return Err(ApiError::BadRequest(format!("at must be between {} and {}", YEARS.start(), YEARS.end())));
|
||||
}
|
||||
let engine = state.engine.as_ref();
|
||||
let planets = Body::PLANETS
|
||||
.iter()
|
||||
.map(|&body| {
|
||||
let s = engine.position(body, jd, &Frame::TROPICAL_GEOCENTRIC).map_err(calc)?;
|
||||
let next = if RETROGRADING.contains(&body) {
|
||||
next_station(engine, body, jd, STATION_HORIZON_DAYS).map_err(calc)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(PlanetNow {
|
||||
id: body,
|
||||
position: ZodiacPosition::new(s.longitude),
|
||||
speed: s.speed_longitude,
|
||||
retrograde: s.speed_longitude < 0.0,
|
||||
next_station: next.as_ref().map(|n| station(n, &tz)).transpose()?,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, ApiError>>()?;
|
||||
|
||||
let m = moon_now(engine, jd).map_err(calc)?;
|
||||
let sign_change = moon_ingresses(engine, jd, jd + 3.0)
|
||||
.map_err(calc)?
|
||||
.first()
|
||||
.map(|&(t, sign)| Ok::<_, ApiError>(IngressOut { moment: moment(t, &tz)?, sign }))
|
||||
.transpose()?;
|
||||
let mut next_phases = lunations_out(state, jd, jd + 31.0, &tz)?;
|
||||
next_phases.truncate(4);
|
||||
let moon = MoonOut {
|
||||
position: ZodiacPosition::new(m.longitude),
|
||||
phase: m.phase,
|
||||
illumination: m.illumination,
|
||||
elongation: m.elongation,
|
||||
waxing: m.elongation < 180.0,
|
||||
sign_change,
|
||||
next_phases,
|
||||
};
|
||||
Ok(SkyResponse {
|
||||
moment: moment(jd, &tz)?,
|
||||
timezone: zone_name,
|
||||
utc_offset: format_offset(tz.to_offset(ts)),
|
||||
planets,
|
||||
moon,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct RetrogradeOut {
|
||||
pub planet: Body,
|
||||
pub station_retrograde: StationOut,
|
||||
pub station_direct: StationOut,
|
||||
/// The planet first reaches the degree where it turns direct.
|
||||
pub shadow_start: Moment,
|
||||
/// The planet is back at the degree where it turned retrograde.
|
||||
pub shadow_end: Moment,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct EventsResponse {
|
||||
pub year: i32,
|
||||
pub timezone: String,
|
||||
pub lunations: Vec<LunationOut>,
|
||||
pub moon_ingresses: Vec<IngressOut>,
|
||||
/// The retrograde periods overlapping the year, by planet, then by time.
|
||||
pub retrogrades: Vec<RetrogradeOut>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct EventsQuery {
|
||||
pub year: i32,
|
||||
pub tz: Option<String>,
|
||||
}
|
||||
|
||||
pub fn events(state: &AppState, query: EventsQuery) -> Result<EventsResponse, ApiError> {
|
||||
if !YEARS.contains(&query.year) {
|
||||
return Err(ApiError::BadRequest(format!("year must be between {} and {}", YEARS.start(), YEARS.end())));
|
||||
}
|
||||
let (zone_name, tz) = zone(state, query.tz.as_deref())?;
|
||||
let start_of = |year: i32| -> Result<f64, ApiError> {
|
||||
let zoned =
|
||||
jiff::civil::date(year as i16, 1, 1).to_zoned(tz.clone()).map_err(|e| ApiError::Internal(e.to_string()))?;
|
||||
Ok(jd_of(zoned.timestamp()))
|
||||
};
|
||||
let (from, to) = (start_of(query.year)?, start_of(query.year + 1)?);
|
||||
let engine = state.engine.as_ref();
|
||||
|
||||
let lunations = lunations_out(state, from, to, &tz)?;
|
||||
let moon_ingresses = moon_ingresses(engine, from, to)
|
||||
.map_err(calc)?
|
||||
.into_iter()
|
||||
.map(|(t, sign)| Ok(IngressOut { moment: moment(t, &tz)?, sign }))
|
||||
.collect::<Result<Vec<_>, ApiError>>()?;
|
||||
let mut retrogrades = Vec::new();
|
||||
for body in RETROGRADING {
|
||||
for p in retrograde_periods(engine, body, from, to).map_err(calc)? {
|
||||
retrogrades.push(RetrogradeOut {
|
||||
planet: body,
|
||||
station_retrograde: station(&p.station_retrograde, &tz)?,
|
||||
station_direct: station(&p.station_direct, &tz)?,
|
||||
shadow_start: moment(p.shadow_start, &tz)?,
|
||||
shadow_end: moment(p.shadow_end, &tz)?,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(EventsResponse { year: query.year, timezone: zone_name, lunations, moon_ingresses, retrogrades })
|
||||
}
|
||||
@@ -318,3 +318,77 @@ async fn forecast_year_with_solar_return() {
|
||||
let (status, _) = call("POST", "/v1/forecast", Some(json!({"birth": birth, "year": 1985}))).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sky_at_a_moment() {
|
||||
// 2026-03-10 12:00 UTC: Mercury retrograde (26 Feb – 20 Mar), waning Moon.
|
||||
let (status, d) = call("GET", "/v1/sky?at=2026-03-10T12:00:00Z", None).await;
|
||||
assert_eq!(status, StatusCode::OK, "{d}");
|
||||
assert_eq!(d["timezone"], "Europe/Budapest");
|
||||
assert_eq!(d["utc_offset"], "+01:00");
|
||||
assert_eq!(d["local_time"], "2026-03-10T13:00");
|
||||
let planets = d["planets"].as_array().unwrap();
|
||||
assert_eq!(planets.len(), 10);
|
||||
let mercury = planets.iter().find(|p| p["id"] == "mercury").unwrap();
|
||||
assert_eq!(mercury["retrograde"], true);
|
||||
assert_eq!(mercury["position"]["sign"], "pisces");
|
||||
assert_eq!(mercury["next_station"]["retrograde"], false);
|
||||
assert!(mercury["next_station"]["local_time"].as_str().unwrap().starts_with("2026-03-2"), "{mercury}");
|
||||
let sun = planets.iter().find(|p| p["id"] == "sun").unwrap();
|
||||
assert_eq!(sun["retrograde"], false);
|
||||
assert!(sun["next_station"].is_null());
|
||||
let moon = &d["moon"];
|
||||
assert_eq!(moon["waxing"], false);
|
||||
assert!(moon["sign_change"]["local_time"].as_str().unwrap() > "2026-03-10T13:00");
|
||||
let phases = moon["next_phases"].as_array().unwrap();
|
||||
assert_eq!(phases.len(), 4);
|
||||
assert_eq!(phases[0]["kind"], "last_quarter");
|
||||
// The new moon of 19 March is not an eclipse; 3 March was (and is past).
|
||||
assert!(phases.iter().all(|p| p["eclipse"].is_null()), "{phases:?}");
|
||||
|
||||
let (status, _) = call("GET", "/v1/sky?at=tegnap", None).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
let (status, _) = call("GET", "/v1/sky?tz=Mars/Olympus", None).await;
|
||||
assert!(status.is_client_error(), "{status}");
|
||||
let (status, now) = call("GET", "/v1/sky", None).await;
|
||||
assert_eq!(status, StatusCode::OK, "{now}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sky_events_of_a_year() {
|
||||
let (status, d) = call("GET", "/v1/sky/events?year=2026", None).await;
|
||||
assert_eq!(status, StatusCode::OK, "{d}");
|
||||
assert_eq!(d["year"], 2026);
|
||||
let lunations = d["lunations"].as_array().unwrap();
|
||||
assert!(lunations.iter().all(|l| l["local_time"].as_str().unwrap().starts_with("2026-")));
|
||||
// The total lunar eclipse at the full moon of 3 March (12:38 in Budapest),
|
||||
// the total solar eclipse at the new moon of 12 August.
|
||||
let eclipse = |date: &str| {
|
||||
lunations.iter().find(|l| l["local_time"].as_str().unwrap().starts_with(date) && !l["eclipse"].is_null())
|
||||
};
|
||||
let march = eclipse("2026-03-03").expect("lunar eclipse");
|
||||
assert_eq!((march["kind"].as_str(), march["eclipse"]["kind"].as_str()), (Some("full_moon"), Some("lunar")));
|
||||
assert_eq!(march["eclipse"]["eclipse_type"], "total");
|
||||
assert_eq!(march["position"]["sign"], "virgo");
|
||||
let august = eclipse("2026-08-12").expect("solar eclipse");
|
||||
assert_eq!(august["eclipse"]["eclipse_type"], "total");
|
||||
assert_eq!(lunations.iter().filter(|l| !l["eclipse"].is_null()).count(), 4);
|
||||
|
||||
let ingresses = d["moon_ingresses"].as_array().unwrap();
|
||||
assert!((155..=170).contains(&ingresses.len()), "{}", ingresses.len());
|
||||
|
||||
let retro = d["retrogrades"].as_array().unwrap();
|
||||
let mercury: Vec<&Value> = retro.iter().filter(|r| r["planet"] == "mercury").collect();
|
||||
assert_eq!(mercury.len(), 3);
|
||||
assert!(mercury[0]["station_retrograde"]["local_time"].as_str().unwrap().starts_with("2026-02-26"));
|
||||
assert_eq!(mercury[0]["station_retrograde"]["retrograde"], true);
|
||||
assert!(mercury[0]["shadow_start"]["local_time"].as_str().unwrap() < "2026-02-26");
|
||||
// Every planet but the Sun and the Moon; Venus turns retrograde in October.
|
||||
assert!(retro.iter().any(|r| r["planet"] == "venus"));
|
||||
assert!(retro.iter().any(|r| r["planet"] == "pluto"));
|
||||
|
||||
for bad in ["/v1/sky/events?year=1800", "/v1/sky/events", "/v1/sky/events?year=2026&x=1"] {
|
||||
let (status, _) = call("GET", bad, None).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user