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
View File
@@ -68,6 +68,9 @@ async fn main() -> anyhow::Result<()> {
horoscope_api = %config.horoscope_api_url,
"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 listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
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}")))
}
enum Target {
pub(super) enum Target {
Natal { chart_id: Uuid, hash: String },
Summary { chart_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,
/// 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.
async fn queue(
pub(super) async fn queue(
state: &AppState,
user: Uuid,
target: &Target,
+1 -1
View File
@@ -35,7 +35,7 @@ pub struct ChartRow {
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";
impl ChartRow {
+22 -9
View File
@@ -19,6 +19,7 @@ use uuid::Uuid;
use super::charts::{ChartRow, find_chart, owned_chart};
use super::{Body, IdPath, St};
use crate::AppState;
use crate::auth::AuthUser;
use crate::error::{ApiError, ApiResult};
use crate::views::{rfc3339, sha256_hex};
@@ -224,15 +225,7 @@ pub async fn create(
));
}
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 forecast_hash = forecast_hash(&chart.chart_hash, year, &location_key, &result);
let (result, forecast_hash) = calculate(&state, &chart, year, location.as_ref(), &location_key).await?;
let row: ForecastRow = sqlx::query_as(&format!(
"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) \
@@ -253,6 +246,26 @@ pub async fn create(
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
/// 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 {
+3
View File
@@ -14,9 +14,12 @@ mod forecasts;
mod invitations;
mod payments;
mod prompts;
mod recalculate;
mod shares;
mod synastries;
pub use recalculate::run as recalculate;
use std::sync::Arc;
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)
}
/// 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
/// it does not exist yet (in either order). `bool` = newly created.
pub async fn compute_synastry(
@@ -130,14 +147,7 @@ pub async fn compute_synastry(
return Ok((row, false));
}
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"]);
let (result, hash) = calculate(state, chart1, chart2).await?;
let inserted: Option<SynastryRow> = sqlx::query_as(&format!(
"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 {
router: Router,
pool: PgPool,
state: Arc<AppState>,
}
struct Response {
@@ -141,7 +142,8 @@ impl TestApp {
let fake = fake_services().await;
let mut config = Config::for_tests(String::new(), fake.clone(), format!("{fake}/jwks"));
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 {
@@ -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();
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],
"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"],
"calendar": ["gregorian", "julian"],
},