Backend and the workers also write their log as JSON into the logs volume, one file a day kept 30 days (LOG_DIR, LOG_NAME, LOG_KEEP_DAYS), so errors can be looked up after a container is replaced. The Docker health check (/healthz every 30 s) no longer goes into the request log of the backend and the horoscope API. The home, login and packages pages no longer compare the analyses to an experienced astrologer's depth; they say what the user gets: detailed, personal text in minutes, for a fraction of a personal consultation's price. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
171 lines
5.8 KiB
Rust
171 lines
5.8 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::forecast::{self, ForecastRequest, ForecastResponse};
|
|
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("/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))
|
|
.route("/v1/forecast", post(forecast_year))
|
|
.layer(cors())
|
|
.layer(
|
|
TraceLayer::new_for_http()
|
|
.make_span_with(DefaultMakeSpan::new().level(Level::INFO))
|
|
.on_response(DefaultOnResponse::new().level(Level::INFO)),
|
|
)
|
|
// After the layers: the Docker health check (every 30 s) stays out of the log.
|
|
.route("/healthz", get(health))
|
|
.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::Standard, 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))
|
|
}
|
|
|
|
async fn forecast_year(
|
|
State(state): State<Arc<AppState>>,
|
|
body: Result<Json<ForecastRequest>, JsonRejection>,
|
|
) -> AppResult<ForecastResponse> {
|
|
let Json(request) = body?;
|
|
let response = tokio::task::spawn_blocking(move || forecast::calculate(&state, request))
|
|
.await
|
|
.map_err(|e| ApiError::Internal(e.to_string()))??;
|
|
Ok(Json(response))
|
|
}
|