Quincunx in the default aspects, sign-based moon phases, backend recalculate command
CI / test (push) Successful in 55s
CI / build (push) Successful in 5m14s
CI / deploy (push) Skipped

- AspectSet::Standard (default): the major aspects and the quincunx; forecasts use it too
- Moon phase: new, quarter and full moon only within 12° and in the matching signs
- backend recalculate: recalculates stored charts, comparisons and forecasts,
  then queues every analysis again (nobody is charged)

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-18 12:18:39 +00:00
co-authored by Claude Opus 5.5
parent 62df5c2764
commit 23975a8369
15 changed files with 280 additions and 38 deletions
+3 -1
View File
@@ -112,7 +112,7 @@ Környezeti változók: `ASTRO_DATA_DIR` (alapérték: `data`), `BIND_ADDR` (`0.
| `ayanamsa` | **`lahiri`**, `fagan_bradley`, `raman`, `krishnamurti`, `de_luce`, `yukteshwar`, `true_citra`, `galactic_center0_sag` (csak sziderikus zodiákusnál) | | `ayanamsa` | **`lahiri`**, `fagan_bradley`, `raman`, `krishnamurti`, `de_luce`, `yukteshwar`, `true_citra`, `galactic_center0_sag` (csak sziderikus zodiákusnál) |
| `node_type` | **`true`**, `mean`: holdcsomópont | | `node_type` | **`true`**, `mean`: holdcsomópont |
| `lilith_type` | **`mean`**, `true`: Fekete Hold | | `lilith_type` | **`mean`**, `true`: Fekete Hold |
| `aspect_set` | **`major`** (együttállás, szextil, kvadrát, trigon, oppozíció), `extended` (+ félszextil, félkvadrát, kvintil, másfélkvadrát, bikvintil, kvinkunx) | | `aspect_set` | `major` (együttállás, szextil, kvadrát, trigon, oppozíció), **`standard`** (a fők + kvinkunx 150°), `extended` (+ félszextil, félkvadrát, kvintil, másfélkvadrát, bikvintil) |
| `orb_multiplier` | **`1.0`** (0 < x ≤ 3) | | `orb_multiplier` | **`1.0`** (0 < x ≤ 3) |
| `topocentric` | **`false`** | | `topocentric` | **`false`** |
| `include_asteroids` | **`true`** (Ceres, Pallas, Juno, Vesta) | | `include_asteroids` | **`true`** (Ceres, Pallas, Juno, Vesta) |
@@ -156,6 +156,8 @@ Környezeti változók: `ASTRO_DATA_DIR` (alapérték: `data`), `BIND_ADDR` (`0.
} }
``` ```
A holdfázis fő fázisai (újhold, első negyed, telihold, utolsó negyed) a pontos fényszögtől legfeljebb 12°-ig tartanak, és csak a megfelelő jegyek között: telihold csak szemben álló jegyekben (Kos–Mérleg, Bika–Skorpió …), újhold egy jegyben. Minden más helyzet sarló vagy domború hold.
Minden azonosító (bolygó, jegy, fényszög, fázis) angol `snake_case`; a magyar fordítás a frontend feladata. Minden azonosító (bolygó, jegy, fényszög, fázis) angol `snake_case`; a magyar fordítás a frontend feladata.
### `POST /v1/synastry`: kérés ### `POST /v1/synastry`: kérés
+3 -1
View File
@@ -168,7 +168,9 @@ Use the usual Hungarian astrological terms:
- signs: Kos, Bika, Ikrek, Rák, Oroszlán, Szűz, Mérleg, Skorpió, Nyilas, Bak, Vízöntő, Halak (\"a Nap a Rák jegyében\", \"Kos Aszcendens\"); - signs: Kos, Bika, Ikrek, Rák, Oroszlán, Szűz, Mérleg, Skorpió, Nyilas, Bak, Vízöntő, Halak (\"a Nap a Rák jegyében\", \"Kos Aszcendens\");
- planets and points: Nap, Hold, Merkúr, Vénusz, Mars, Jupiter, Szaturnusz, Uránusz, Neptunusz, Plútó, Chiron (Kiron), \ - planets and points: Nap, Hold, Merkúr, Vénusz, Mars, Jupiter, Szaturnusz, Uránusz, Neptunusz, Plútó, Chiron (Kiron), \
Észak-Holdcsomópont, Dél-Holdcsomópont, Lilith (Fekete Hold), Aszcendens, Descendens, Medium Coeli (MC), Imum Coeli (IC), Szerencsepont; Észak-Holdcsomópont, Dél-Holdcsomópont, Lilith (Fekete Hold), Aszcendens, Descendens, Medium Coeli (MC), Imum Coeli (IC), Szerencsepont;
- aspects: együttállás (konjunkció), szextil, kvadrát (négyzet), trigon, szembenállás (oppozíció); - aspects: együttállás (konjunkció), szextil, kvadrát (négyzet), trigon, kvinkunx (150°), szembenállás (oppozíció);
- Moon phases: újhold, növő sarló, első negyed, növő (domború) hold, telihold, fogyó (domború) hold, utolsó negyed, \
fogyó sarló; name the phase given in the data, never another one;
- elements and modalities: tűz, föld, levegő, víz (\"tűz elem\", \"a föld hiánya\"); kardinális, fix, változó; - elements and modalities: tűz, föld, levegő, víz (\"tűz elem\", \"a föld hiánya\"); kardinális, fix, változó;
Never leave English words (e.g. fire, earth, air, water) in the Hungarian text. Never leave English words (e.g. fire, earth, air, water) in the Hungarian text.
- other: \"a 3. házban\", \"a horoszkóp uralkodója\", retrográd, uralom (domicilium), száműzetés, exaltáció, esés, nappali/éjszakai horoszkóp."; - other: \"a 3. házban\", \"a horoszkóp uralkodója\", retrográd, uralom (domicilium), száműzetés, exaltáció, esés, nappali/éjszakai horoszkóp.";
+51 -9
View File
@@ -616,7 +616,7 @@ pub fn calculate_chart(engine: &dyn Ephemeris, input: &ChartInput) -> Result<Nat
let elongation = normalize(moon - sun); let elongation = normalize(moon - sun);
let moon_phase = MoonPhase { let moon_phase = MoonPhase {
elongation, elongation,
phase: phase_name(elongation), phase: phase_name(sun, moon),
illumination: engine.illumination(Body::Moon, jd)?, illumination: engine.illumination(Body::Moon, jd)?,
waxing: elongation < 180.0, waxing: elongation < 180.0,
}; };
@@ -720,10 +720,28 @@ fn above_horizon(lon: f64, ascendant: f64) -> bool {
angle::arc(ascendant, lon) >= 180.0 angle::arc(ascendant, lon) >= 180.0
} }
pub(crate) fn phase_name(elongation: f64) -> MoonPhaseName { /// At most this far from the exact new moon, quarter or full moon is the
/// Moon still in that phase, as astrologers read it.
const LUNATION_ORB: f64 = 12.0;
/// The Moon's phase from the longitudes of the Sun and the Moon. A main phase
/// (new, first quarter, full, last quarter) is the exact aspect of the lights
/// within [`LUNATION_ORB`] and in the matching signs: a full moon only between
/// opposite signs (Aries–Libra, Taurus–Scorpio, ...), a new moon in one sign.
/// Otherwise the Moon is crescent or gibbous, so a Moon 150° from the Sun (a
/// quincunx) or 30° past the opposition is not full.
pub(crate) fn phase_name(sun: f64, moon: f64) -> MoonPhaseName {
use MoonPhaseName::*; use MoonPhaseName::*;
[NewMoon, WaxingCrescent, FirstQuarter, WaxingGibbous, FullMoon, WaningGibbous, LastQuarter, WaningCrescent] let elongation = (moon - sun).rem_euclid(360.0);
[((elongation / 45.0).floor() as usize).min(7)] let signs_apart = (ZodiacSign::from_longitude(moon).index() + 12 - ZodiacSign::from_longitude(sun).index()) % 12;
let main = [NewMoon, FirstQuarter, FullMoon, LastQuarter];
for (k, phase) in main.into_iter().enumerate() {
let off = (elongation - 90.0 * k as f64 + 180.0).rem_euclid(360.0) - 180.0;
if off.abs() <= LUNATION_ORB && signs_apart == 3 * k {
return phase;
}
}
[WaxingCrescent, WaxingGibbous, WaningGibbous, WaningCrescent][((elongation / 90.0) as usize).min(3)]
} }
/// Points taking part in aspects as `(id, longitude, speed)`: everything but /// Points taking part in aspects as `(id, longitude, speed)`: everything but
@@ -744,8 +762,10 @@ pub(crate) fn aspect_points(points: &[Point], angles: Option<&Angles>) -> Vec<(P
pub(crate) fn aspect_kinds(set: AspectSet) -> Vec<AspectKind> { pub(crate) fn aspect_kinds(set: AspectSet) -> Vec<AspectKind> {
let mut kinds = AspectKind::MAJOR.to_vec(); let mut kinds = AspectKind::MAJOR.to_vec();
if set == AspectSet::Extended { match set {
kinds.extend(AspectKind::MINOR); AspectSet::Major => {}
AspectSet::Standard => kinds.push(AspectKind::Quincunx),
AspectSet::Extended => kinds.extend(AspectKind::MINOR),
} }
kinds kinds
} }
@@ -888,9 +908,31 @@ mod tests {
// Ascendant at 0° Aries: Cancer (90°) is below (IC side), Capricorn (270°) above. // Ascendant at 0° Aries: Cancer (90°) is below (IC side), Capricorn (270°) above.
assert!(!above_horizon(90.0, 0.0)); assert!(!above_horizon(90.0, 0.0));
assert!(above_horizon(270.0, 0.0)); assert!(above_horizon(270.0, 0.0));
assert_eq!(phase_name(0.0), MoonPhaseName::NewMoon); use MoonPhaseName::*;
assert_eq!(phase_name(185.0), MoonPhaseName::FullMoon); // (Sun, Moon) longitudes
assert_eq!(phase_name(359.9), MoonPhaseName::WaningCrescent); assert_eq!(phase_name(10.0, 10.0), NewMoon);
assert_eq!(phase_name(15.0, 5.0), NewMoon); // 10° before, both in Aries
assert_eq!(phase_name(3.0, 355.0), WaningCrescent); // 8° before, but Pisces–Aries
assert_eq!(phase_name(28.0, 359.0), WaningCrescent); // 29° before, and in Pisces
assert_eq!(phase_name(10.0, 195.0), FullMoon); // Aries–Libra, 5° past
assert_eq!(phase_name(2.0, 170.0), WaxingGibbous); // 12° before, but Aries–Virgo
assert_eq!(phase_name(25.0, 199.0), FullMoon); // 6° before, Aries–Libra
assert_eq!(phase_name(10.0, 203.0), WaningGibbous); // 13° past: beyond the orb
// a quincunx between the lights is not a full moon
assert_eq!(phase_name(10.0, 159.0), WaxingGibbous);
assert_eq!(phase_name(10.0, 221.1), WaningGibbous);
assert_eq!(phase_name(10.0, 100.0), FirstQuarter); // Aries–Cancer
assert_eq!(phase_name(10.0, 285.0), LastQuarter); // Aries–Capricorn
assert_eq!(phase_name(10.0, 340.0), WaningCrescent);
}
#[test]
fn the_default_aspects_include_the_quincunx() {
let pts = [(PointId::Sun, 10.0, 1.0), (PointId::Moon, 159.0, 13.0)]; // 149° apart
assert_eq!(AspectSet::default(), AspectSet::Standard);
let found = find_aspects(&pts, AspectSet::Standard, 1.0);
assert_eq!(found.iter().map(|a| a.aspect).collect::<Vec<_>>(), [AspectKind::Quincunx]);
assert!(find_aspects(&pts, AspectSet::Major, 1.0).is_empty());
} }
#[test] #[test]
+10 -3
View File
@@ -37,8 +37,15 @@ const NEAR_DAYS: f64 = 200.0;
const TRANSITING: [Body; 5] = [Body::Jupiter, Body::Saturn, Body::Uranus, Body::Neptune, Body::Pluto]; const TRANSITING: [Body; 5] = [Body::Jupiter, Body::Saturn, Body::Uranus, Body::Neptune, Body::Pluto];
const PROGRESSED: [Body; 5] = [Body::Sun, Body::Moon, Body::Mercury, Body::Venus, Body::Mars]; const PROGRESSED: [Body; 5] = [Body::Sun, Body::Moon, Body::Mercury, Body::Venus, Body::Mars];
const ASPECTS: [AspectKind; 5] = /// The aspects of the default chart (`AspectSet::Standard`): the major ones and the quincunx.
[AspectKind::Conjunction, AspectKind::Sextile, AspectKind::Square, AspectKind::Trine, AspectKind::Opposition]; const ASPECTS: [AspectKind; 6] = [
AspectKind::Conjunction,
AspectKind::Sextile,
AspectKind::Square,
AspectKind::Trine,
AspectKind::Quincunx,
AspectKind::Opposition,
];
type Result<T> = std::result::Result<T, EngineError>; type Result<T> = std::result::Result<T, EngineError>;
@@ -409,7 +416,7 @@ impl Year<'_> {
// The progressed lunation phase: the progressed Moon's distance from the progressed Sun. // The progressed lunation phase: the progressed Moon's distance from the progressed Sun.
let (sun, moon) = (&samples[0], &samples[1]); let (sun, moon) = (&samples[0], &samples[1]);
let phase_at = |i: usize| phase_name((moon.lon[i] - sun.lon[i]).rem_euclid(360.0)); let phase_at = |i: usize| phase_name(sun.lon[i], moon.lon[i]);
let lunar_phase = phase_at(0); let lunar_phase = phase_at(0);
let lunar_phase_change = if known { let lunar_phase_change = if known {
(1..moon.lon.len()) (1..moon.lon.len())
+3 -1
View File
@@ -96,8 +96,10 @@ pub enum Ayanamsa {
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub enum AspectSet { pub enum AspectSet {
/// Conjunction, sextile, square, trine, opposition. /// Conjunction, sextile, square, trine, opposition.
#[default]
Major, Major,
/// The major aspects plus the quincunx (150°), which most astrologers read.
#[default]
Standard,
/// Major aspects plus semisextile, semisquare, quintile, sesquiquadrate, biquintile, quincunx. /// Major aspects plus semisextile, semisquare, quintile, sesquiquadrate, biquintile, quincunx.
Extended, Extended,
} }
+1 -1
View File
@@ -7,7 +7,7 @@ Egy év születésnaptól születésnapig, több bevett előrejelző módszerbő
| Módszer | Mit ad | Hol számolódik | | Módszer | Mit ad | Hol számolódik |
|---|---|---| |---|---|---|
| **Szolár** (szoláris visszatérés) | Az a pillanat, amikor a Nap visszatér a születéskori hosszúságára; az erre a pillanatra és a születésnapi tartózkodási helyre felállított képlet „az év képlete”. | `astro_engine::forecast::solar_return`, a képlet a horoscope-api-ban | | **Szolár** (szoláris visszatérés) | Az a pillanat, amikor a Nap visszatér a születéskori hosszúságára; az erre a pillanatra és a születésnapi tartózkodási helyre felállított képlet „az év képlete”. | `astro_engine::forecast::solar_return`, a képlet a horoscope-api-ban |
| **Tranzitok** | A Jupiter, Szaturnusz, Uránusz, Neptunusz és Plútó fő fényszögei (együttállás, szextil, kvadrát, trigon, szembenállás) a tíz bolygóhoz, az Aszcendenshez és az MC-hez, 1° hatásfokkal: pontos dátumok (retrográd áthaladásokkal) és hatásidők. A lassú bolygók házai és házváltásai. | `forecast.rs`, `Year::transits` | | **Tranzitok** | A Jupiter, Szaturnusz, Uránusz, Neptunusz és Plútó fő fényszögei (együttállás, szextil, kvadrát, trigon, szembenállás) és a kvinkunx (150°) a tíz bolygóhoz, az Aszcendenshez és az MC-hez, 1° hatásfokkal: pontos dátumok (retrográd áthaladásokkal) és hatásidők. A lassú bolygók házai és házváltásai. | `forecast.rs`, `Year::transits` |
| **Szekunder direkció** | „Egy nap = egy év”: a progresszív Nap, Hold, Merkúr, Vénusz, Mars helye, jegy- és házváltásai, fényszögei a születési képlethez, a progresszív holdfázis. | `Year::progressions` | | **Szekunder direkció** | „Egy nap = egy év”: a progresszív Nap, Hold, Merkúr, Vénusz, Mars helye, jegy- és házváltásai, fényszögei a születési képlethez, a progresszív holdfázis. | `Year::progressions` |
| **Éves profekció** | Minden életév egy házat aktivál (egész jegyes házak az Aszcendenstől); a jegy hagyományos uralkodója „az év ura”. | `Year::profection` | | **Éves profekció** | Minden életév egy házat aktivál (egész jegyes házak az Aszcendenstől); a jegy hagyományos uralkodója „az év ura”. | `Year::profection` |
| **Fogyatkozások** | Az év nap- és holdfogyatkozásai (a félárnyékos holdfogyatkozás nélkül), a születési házuk, és ha 3°-on belül érintenek egy születési pontot. | Swiss Ephemeris `swe_sol_eclipse_when_glob`, `swe_lun_eclipse_when` | | **Fogyatkozások** | Az év nap- és holdfogyatkozásai (a félárnyékos holdfogyatkozás nélkül), a születési házuk, és ha 3°-on belül érintenek egy születési pontot. | Swiss Ephemeris `swe_sol_eclipse_when_glob`, `swe_lun_eclipse_when` |
+3
View File
@@ -68,6 +68,9 @@ async fn main() -> anyhow::Result<()> {
horoscope_api = %config.horoscope_api_url, horoscope_api = %config.horoscope_api_url,
"database ready" "database ready"
); );
if std::env::args().nth(1).as_deref() == Some("recalculate") {
return routes::recalculate(&AppState::new(pool, config)).await;
}
let app = routes::router(Arc::new(AppState::new(pool, config))); let app = routes::router(Arc::new(AppState::new(pool, config)));
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?; let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
tracing::info!(%addr, "listening"); tracing::info!(%addr, "listening");
+2 -2
View File
@@ -113,7 +113,7 @@ fn optional_body(body: &[u8]) -> Result<AnalysisRequest, ApiError> {
serde_json::from_slice(body).map_err(|e| ApiError::BadRequest(format!("invalid request body: {e}"))) serde_json::from_slice(body).map_err(|e| ApiError::BadRequest(format!("invalid request body: {e}")))
} }
enum Target { pub(super) enum Target {
Natal { chart_id: Uuid, hash: String }, Natal { chart_id: Uuid, hash: String },
Summary { chart_id: Uuid, hash: String }, Summary { chart_id: Uuid, hash: String },
Synastry { synastry_id: Uuid, hash: String }, Synastry { synastry_id: Uuid, hash: String },
@@ -143,7 +143,7 @@ async fn request(
/// Returns the existing analysis with the same cache key for this target, /// Returns the existing analysis with the same cache key for this target,
/// copies a finished one from another chart with the same data, or queues a /// copies a finished one from another chart with the same data, or queues a
/// new one (spending one `unit`, if given). 200, 201 and 202 respectively. /// new one (spending one `unit`, if given). 200, 201 and 202 respectively.
async fn queue( pub(super) async fn queue(
state: &AppState, state: &AppState,
user: Uuid, user: Uuid,
target: &Target, target: &Target,
+1 -1
View File
@@ -35,7 +35,7 @@ pub struct ChartRow {
pub updated_at: OffsetDateTime, pub updated_at: OffsetDateTime,
} }
const CHART_COLUMNS: &str = pub(super) const CHART_COLUMNS: &str =
"id, owner_id, label, is_primary, kind, birth_data, result, chart_hash, created_at, updated_at"; "id, owner_id, label, is_primary, kind, birth_data, result, chart_hash, created_at, updated_at";
impl ChartRow { impl ChartRow {
+22 -9
View File
@@ -19,6 +19,7 @@ use uuid::Uuid;
use super::charts::{ChartRow, find_chart, owned_chart}; use super::charts::{ChartRow, find_chart, owned_chart};
use super::{Body, IdPath, St}; use super::{Body, IdPath, St};
use crate::AppState;
use crate::auth::AuthUser; use crate::auth::AuthUser;
use crate::error::{ApiError, ApiResult}; use crate::error::{ApiError, ApiResult};
use crate::views::{rfc3339, sha256_hex}; use crate::views::{rfc3339, sha256_hex};
@@ -224,15 +225,7 @@ pub async fn create(
)); ));
} }
let mut request = json!({ "birth": chart.birth_data, "year": year }); let (result, forecast_hash) = calculate(&state, &chart, year, location.as_ref(), &location_key).await?;
if let Some(l) = &location {
request["location"] = l.clone();
}
let mut result = state.horoscope.forecast(&request).await?;
if let Some(obj) = result.as_object_mut() {
obj.remove("meta");
}
let forecast_hash = forecast_hash(&chart.chart_hash, year, &location_key, &result);
let row: ForecastRow = sqlx::query_as(&format!( let row: ForecastRow = sqlx::query_as(&format!(
"INSERT INTO forecasts (id, chart_id, chart_hash, year, location, location_key, result, forecast_hash, created_by) \ "INSERT INTO forecasts (id, chart_id, chart_hash, year, location, location_key, result, forecast_hash, created_by) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) \ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) \
@@ -253,6 +246,26 @@ pub async fn create(
Ok((StatusCode::CREATED, Json(row.view()))) Ok((StatusCode::CREATED, Json(row.view())))
} }
/// One year of a stored chart as stored: `(result, forecast_hash)`.
pub(super) async fn calculate(
state: &AppState,
chart: &ChartRow,
year: i32,
location: Option<&Value>,
location_key: &str,
) -> Result<(Value, String), ApiError> {
let mut request = json!({ "birth": chart.birth_data, "year": year });
if let Some(l) = location {
request["location"] = l.clone();
}
let mut result = state.horoscope.forecast(&request).await?;
if let Some(obj) = result.as_object_mut() {
obj.remove("meta");
}
let hash = forecast_hash(&chart.chart_hash, year, location_key, &result);
Ok((result, hash))
}
/// Identifies a forecast independently of how the place was entered: the /// Identifies a forecast independently of how the place was entered: the
/// chart, the year and the resolved place and time zone of the solar return. /// chart, the year and the resolved place and time zone of the solar return.
fn forecast_hash(chart_hash: &str, year: i32, location_key: &str, result: &Value) -> String { fn forecast_hash(chart_hash: &str, year: i32, location_key: &str, result: &Value) -> String {
+3
View File
@@ -14,9 +14,12 @@ mod forecasts;
mod invitations; mod invitations;
mod payments; mod payments;
mod prompts; mod prompts;
mod recalculate;
mod shares; mod shares;
mod synastries; mod synastries;
pub use recalculate::run as recalculate;
use std::sync::Arc; use std::sync::Arc;
use axum::extract::{Path, State}; use axum::extract::{Path, State};
+117
View File
@@ -0,0 +1,117 @@
//! `backend recalculate`: after a change in the calculation, recalculates
//! every stored chart, comparison and forecast with the horoscope service,
//! then deletes all analyses and queues them again: a short summary and a
//! detailed analysis for every chart, one analysis for every comparison and
//! every forecast. Nobody is charged; each analysis is requested in the name
//! of the owner, in the owner's language.
use anyhow::Context;
use serde_json::Value;
use sqlx::PgPool;
use uuid::Uuid;
use super::analyses::{Target, queue};
use super::charts::{CHART_COLUMNS, ChartRow};
use crate::AppState;
async fn all_charts(db: &PgPool) -> Result<Vec<ChartRow>, sqlx::Error> {
sqlx::query_as(&format!("SELECT {CHART_COLUMNS} FROM charts ORDER BY created_at")).fetch_all(db).await
}
async fn locale(db: &PgPool, user: Uuid) -> Result<String, sqlx::Error> {
sqlx::query_scalar("SELECT locale FROM users WHERE id = $1").bind(user).fetch_one(db).await
}
pub async fn run(state: &AppState) -> anyhow::Result<()> {
let db = &state.db;
let charts = all_charts(db).await?;
for chart in &charts {
let (_, result, hash) = super::charts::calculate(state, chart.birth_data.clone())
.await
.map_err(|e| anyhow::anyhow!("chart {}: {e:?}", chart.id))?;
sqlx::query("UPDATE charts SET result = $1, chart_hash = $2 WHERE id = $3")
.bind(&result)
.bind(&hash)
.bind(chart.id)
.execute(db)
.await?;
}
tracing::info!(count = charts.len(), "charts recalculated");
let charts = all_charts(db).await?;
let chart = |id: Uuid| charts.iter().find(|c| c.id == id).context("missing chart");
let synastries: Vec<(Uuid, Uuid, Uuid, Uuid)> =
sqlx::query_as("SELECT id, owner_id, chart1_id, chart2_id FROM synastries ORDER BY created_at")
.fetch_all(db)
.await?;
let mut synastry_hashes = Vec::new();
for &(id, owner, chart1, chart2) in &synastries {
let (result, hash) = super::synastries::calculate(state, chart(chart1)?, chart(chart2)?)
.await
.map_err(|e| anyhow::anyhow!("synastry {id}: {e:?}"))?;
sqlx::query("UPDATE synastries SET result = $1, synastry_hash = $2 WHERE id = $3")
.bind(&result)
.bind(&hash)
.bind(id)
.execute(db)
.await?;
synastry_hashes.push((id, owner, hash));
}
tracing::info!(count = synastries.len(), "comparisons recalculated");
let forecasts: Vec<(Uuid, Uuid, i32, Option<Value>, String)> =
sqlx::query_as("SELECT id, chart_id, year, location, location_key FROM forecasts ORDER BY created_at")
.fetch_all(db)
.await?;
let mut forecast_hashes = Vec::new();
for (id, chart_id, year, location, location_key) in &forecasts {
let c = chart(*chart_id)?;
let (result, hash) = super::forecasts::calculate(state, c, *year, location.as_ref(), location_key)
.await
.map_err(|e| anyhow::anyhow!("forecast {id}: {e:?}"))?;
let updated =
sqlx::query("UPDATE forecasts SET chart_hash = $1, result = $2, forecast_hash = $3 WHERE id = $4")
.bind(&c.chart_hash)
.bind(&result)
.bind(&hash)
.bind(id)
.execute(db)
.await;
match updated {
Ok(_) => forecast_hashes.push((*id, c.owner_id, hash)),
// The same year and place from an earlier version of the birth data: a duplicate now.
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => {
sqlx::query("DELETE FROM forecasts WHERE id = $1").bind(id).execute(db).await?;
tracing::warn!(%id, "duplicate forecast removed");
}
Err(e) => return Err(e.into()),
}
}
tracing::info!(count = forecast_hashes.len(), "forecasts recalculated");
let deleted = sqlx::query("DELETE FROM analyses").execute(db).await?.rows_affected();
let summary_model = &state.config.summary_model;
let analysis_model = &state.config.analysis_model;
let mut queued = 0;
for c in &charts {
let language = locale(db, c.owner_id).await?;
let summary = Target::Summary { chart_id: c.id, hash: c.chart_hash.clone() };
queue(state, c.owner_id, &summary, &language, summary_model, None).await?;
let natal = Target::Natal { chart_id: c.id, hash: c.chart_hash.clone() };
queue(state, c.owner_id, &natal, &language, analysis_model, None).await?;
queued += 2;
}
for (synastry_id, owner, hash) in synastry_hashes {
let target = Target::Synastry { synastry_id, hash };
queue(state, owner, &target, &locale(db, owner).await?, analysis_model, None).await?;
queued += 1;
}
for (forecast_id, owner, hash) in forecast_hashes {
let target = Target::Forecast { forecast_id, hash };
queue(state, owner, &target, &locale(db, owner).await?, analysis_model, None).await?;
queued += 1;
}
tracing::info!(deleted, queued, "analyses queued again");
Ok(())
}
+18 -8
View File
@@ -108,6 +108,23 @@ fn without(value: &Value, keys: &[&str]) -> Value {
Value::Object(map) Value::Object(map)
} }
/// The comparison of two stored charts as stored: `(result, synastry_hash)`.
pub(super) async fn calculate(
state: &AppState,
chart1: &ChartRow,
chart2: &ChartRow,
) -> Result<(Value, String), ApiError> {
let request = json!({
"person1": without(&chart1.birth_data, &["options"]),
"person2": without(&chart2.birth_data, &["options"]),
"options": chart1.birth_data.get("options").cloned().unwrap_or_else(|| json!({})),
});
let response = state.horoscope.synastry(&request).await?;
let result = without(&response, &["person1", "person2", "meta"]);
let hash = synastry_hash(&chart1.chart_hash, &chart2.chart_hash, &result["settings"]);
Ok((result, hash))
}
/// Returns the synastry of the two charts, calculating and storing it when /// Returns the synastry of the two charts, calculating and storing it when
/// it does not exist yet (in either order). `bool` = newly created. /// it does not exist yet (in either order). `bool` = newly created.
pub async fn compute_synastry( pub async fn compute_synastry(
@@ -130,14 +147,7 @@ pub async fn compute_synastry(
return Ok((row, false)); return Ok((row, false));
} }
let request = json!({ let (result, hash) = calculate(state, chart1, chart2).await?;
"person1": without(&chart1.birth_data, &["options"]),
"person2": without(&chart2.birth_data, &["options"]),
"options": chart1.birth_data.get("options").cloned().unwrap_or_else(|| json!({})),
});
let response = state.horoscope.synastry(&request).await?;
let result = without(&response, &["person1", "person2", "meta"]);
let hash = synastry_hash(&chart1.chart_hash, &chart2.chart_hash, &result["settings"]);
let inserted: Option<SynastryRow> = sqlx::query_as(&format!( let inserted: Option<SynastryRow> = sqlx::query_as(&format!(
"INSERT INTO synastries (id, owner_id, chart1_id, chart2_id, result, synastry_hash) \ "INSERT INTO synastries (id, owner_id, chart1_id, chart2_id, result, synastry_hash) \
+42 -1
View File
@@ -124,6 +124,7 @@ fn google_token(sub: &str, email: &str, audience: &str) -> String {
struct TestApp { struct TestApp {
router: Router, router: Router,
pool: PgPool, pool: PgPool,
state: Arc<AppState>,
} }
struct Response { struct Response {
@@ -141,7 +142,8 @@ impl TestApp {
let fake = fake_services().await; let fake = fake_services().await;
let mut config = Config::for_tests(String::new(), fake.clone(), format!("{fake}/jwks")); let mut config = Config::for_tests(String::new(), fake.clone(), format!("{fake}/jwks"));
change(&mut config); change(&mut config);
Self { router: routes::router(Arc::new(AppState::new(pool.clone(), config))), pool } let state = Arc::new(AppState::new(pool.clone(), config));
Self { router: routes::router(state.clone()), pool, state }
} }
async fn call(&self, method: &str, uri: &str, token: Option<&str>, body: Option<Value>) -> Response { async fn call(&self, method: &str, uri: &str, token: Option<&str>, body: Option<Value>) -> Response {
@@ -1419,3 +1421,42 @@ async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) {
let (n,): (i64,) = sqlx::query_as("SELECT count(*) FROM forecasts").fetch_one(&pool).await.unwrap(); let (n,): (i64,) = sqlx::query_as("SELECT count(*) FROM forecasts").fetch_one(&pool).await.unwrap();
assert_eq!(n, 0); assert_eq!(n, 0);
} }
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn recalculate_refreshes_calculations_and_queues_every_analysis_again(pool: PgPool) {
let app = TestApp::new(pool.clone()).await;
let anna = app.register("anna@example.com", "Anna").await;
let own = app.chart(&anna, "Saját", true, "1990-03-15").await;
let bela = app.chart(&anna, "Béla", false, "1985-08-02").await;
let syn = app.post("/v1/synastries", Some(&anna), json!({"chart1_id": own["id"], "chart2_id": bela["id"]})).await;
let own_id = own["id"].as_str().unwrap();
let forecast = app.post(&format!("/v1/charts/{own_id}/forecasts"), Some(&anna), json!({})).await;
assert_eq!(forecast.status, StatusCode::CREATED, "{}", forecast.body);
let before = app.get("/v1/me", Some(&anna)).await.body["analyses_left"].clone();
// stored with an older calculation
sqlx::query("UPDATE charts SET result = '{}', chart_hash = 'old'").execute(&pool).await.unwrap();
sqlx::query("UPDATE synastries SET result = '{}', synastry_hash = 'old'").execute(&pool).await.unwrap();
sqlx::query("UPDATE forecasts SET result = '{}', forecast_hash = 'old'").execute(&pool).await.unwrap();
routes::recalculate(&app.state).await.unwrap();
let (old,): (i64,) = sqlx::query_as(
"SELECT (SELECT count(*) FROM charts WHERE chart_hash = 'old' OR result = '{}') \
+ (SELECT count(*) FROM synastries WHERE synastry_hash = 'old' OR result = '{}') \
+ (SELECT count(*) FROM forecasts WHERE forecast_hash = 'old' OR result = '{}')",
)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(old, 0);
let rows: Vec<(String, String, i32)> =
sqlx::query_as("SELECT kind, status, credits_charged FROM analyses ORDER BY kind")
.fetch_all(&pool)
.await
.unwrap();
let kinds: Vec<&str> = rows.iter().map(|r| r.0.as_str()).collect();
assert_eq!(kinds, ["forecast", "natal", "natal", "summary", "summary", "synastry"]);
assert!(rows.iter().all(|r| r.1 == "pending" && r.2 == 0), "{rows:?}");
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["analyses_left"], before);
assert_eq!(syn.status, StatusCode::CREATED);
}
+1 -1
View File
@@ -66,7 +66,7 @@ async fn info(State(state): State<Arc<AppState>>) -> Json<Value> {
], ],
"node_type": [NodeType::True, NodeType::Mean], "node_type": [NodeType::True, NodeType::Mean],
"lilith_type": [LilithType::Mean, LilithType::True], "lilith_type": [LilithType::Mean, LilithType::True],
"aspect_set": [AspectSet::Major, AspectSet::Extended], "aspect_set": [AspectSet::Major, AspectSet::Standard, AspectSet::Extended],
"ambiguous_time": ["reject", "earlier", "later"], "ambiguous_time": ["reject", "earlier", "later"],
"calendar": ["gregorian", "julian"], "calendar": ["gregorian", "julian"],
}, },