Files
sorsfonalak/services/horoscope-api/src/routes.rs
T
fecoandClaude Opus 5.5 3a84110565 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
2026-11-15 10:25:35 +00:00

157 lines
5.2 KiB
Rust

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))
}