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
This commit is contained in:
feco
2026-11-15 10:25:35 +00:00
co-authored by Claude Opus 5.5
parent 0b5416df45
commit 3a84110565
148 changed files with 95803 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "db"
description = "PostgreSQL schema (migrations) and shared data access for the Sorsfonalak services"
edition.workspace = true
version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
base64.workspace = true
rand.workspace = true
serde.workspace = true
sha2.workspace = true
sqlx.workspace = true
time.workspace = true
uuid.workspace = true
+212
View File
@@ -0,0 +1,212 @@
-- Users, login, birth charts, synastries, text analyses, credits, sharing.
-- Identifiers are UUIDv7 generated by the application (time-ordered).
-- --- users and login ----------------------------------------------------------
CREATE TABLE users (
id uuid PRIMARY KEY,
-- Always stored lower-case; unique.
email text NOT NULL,
email_verified_at timestamptz,
display_name text,
-- UI and analysis language (BCP 47 primary tag, e.g. 'hu', 'en').
locale text NOT NULL DEFAULT 'hu',
roles text[] NOT NULL DEFAULT ARRAY['user']::text[],
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
last_login_at timestamptz,
CONSTRAINT users_email_lower CHECK (email = lower(email)),
CONSTRAINT users_roles_valid CHECK (cardinality(roles) > 0 AND roles <@ ARRAY['admin', 'creator', 'user']::text[])
);
CREATE UNIQUE INDEX users_email_key ON users (email);
-- One row per login method of a user. 'password' keeps the Argon2id hash;
-- external providers keep their stable subject id (Google 'sub').
CREATE TABLE auth_identities (
id uuid PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
provider text NOT NULL CHECK (provider IN ('password', 'google', 'facebook', 'apple')),
subject text NOT NULL,
password_hash text,
-- E-mail reported by the provider when the identity was linked.
email text,
created_at timestamptz NOT NULL DEFAULT now(),
last_used_at timestamptz,
UNIQUE (provider, subject),
UNIQUE (user_id, provider),
CONSTRAINT auth_identities_password CHECK ((provider = 'password') = (password_hash IS NOT NULL))
);
-- Opaque session tokens; only their SHA-256 hash is stored.
CREATE TABLE sessions (
id uuid PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
token_hash bytea NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL,
user_agent text
);
CREATE INDEX sessions_user_idx ON sessions (user_id);
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
-- One-time tokens sent by e-mail (verification, password reset).
CREATE TABLE auth_tokens (
id uuid PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
purpose text NOT NULL CHECK (purpose IN ('verify_email', 'reset_password')),
token_hash bytea NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL,
used_at timestamptz
);
CREATE INDEX auth_tokens_user_idx ON auth_tokens (user_id, purpose);
-- --- charts and synastries -------------------------------------------------------
-- A calculated natal chart. `birth_data` is the request sent to the
-- horoscope service, `result` its full response.
CREATE TABLE charts (
id uuid PRIMARY KEY,
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
label text NOT NULL,
-- The owner's own chart (at most one per user).
is_primary boolean NOT NULL DEFAULT false,
birth_data jsonb NOT NULL,
result jsonb NOT NULL,
-- Hash of the resolved birth moment, place and options: same hash, same chart.
chart_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX charts_one_primary ON charts (owner_id) WHERE is_primary;
CREATE INDEX charts_owner_idx ON charts (owner_id, created_at DESC);
-- Comparison of two charts. Visible to `owner_id` and to the owners of both
-- charts (an accepted invitation links two users this way).
CREATE TABLE synastries (
id uuid PRIMARY KEY,
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
chart1_id uuid NOT NULL REFERENCES charts (id) ON DELETE CASCADE,
chart2_id uuid NOT NULL REFERENCES charts (id) ON DELETE CASCADE,
-- Synastry part of the horoscope service response (without the two charts).
result jsonb NOT NULL,
synastry_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT synastries_distinct CHECK (chart1_id <> chart2_id),
UNIQUE (chart1_id, chart2_id)
);
CREATE INDEX synastries_chart2_idx ON synastries (chart2_id);
CREATE INDEX synastries_owner_idx ON synastries (owner_id, created_at DESC);
-- "How compatible are we?" invitation link.
CREATE TABLE synastry_invites (
id uuid PRIMARY KEY,
inviter_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
inviter_chart_id uuid NOT NULL REFERENCES charts (id) ON DELETE CASCADE,
token_hash bytea NOT NULL UNIQUE,
message text,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL,
accepted_at timestamptz,
accepted_by uuid REFERENCES users (id) ON DELETE SET NULL,
synastry_id uuid REFERENCES synastries (id) ON DELETE SET NULL
);
CREATE INDEX synastry_invites_inviter_idx ON synastry_invites (inviter_id, created_at DESC);
-- --- text analyses (LLM) ---------------------------------------------------------
CREATE TABLE analyses (
id uuid PRIMARY KEY,
kind text NOT NULL CHECK (kind IN ('natal', 'synastry')),
chart_id uuid REFERENCES charts (id) ON DELETE CASCADE,
synastry_id uuid REFERENCES synastries (id) ON DELETE CASCADE,
requested_by uuid REFERENCES users (id) ON DELETE SET NULL,
language text NOT NULL,
model text NOT NULL,
prompt_version text NOT NULL,
-- sha256(kind | chart/synastry hash | prompt version | model | language):
-- a finished analysis with the same key is reused instead of a new LLM call.
cache_key text NOT NULL,
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'running', 'done', 'failed')),
-- Structured result: {"summary", "strengths": [], "challenges": [], "body"}.
content jsonb,
error text,
input_tokens integer,
output_tokens integer,
credits_charged integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
started_at timestamptz,
completed_at timestamptz,
CONSTRAINT analyses_target CHECK (
(kind = 'natal' AND chart_id IS NOT NULL AND synastry_id IS NULL)
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL)
),
CONSTRAINT analyses_done_has_content CHECK (status <> 'done' OR content IS NOT NULL)
);
CREATE INDEX analyses_chart_idx ON analyses (chart_id, created_at DESC) WHERE chart_id IS NOT NULL;
CREATE INDEX analyses_synastry_idx ON analyses (synastry_id, created_at DESC) WHERE synastry_id IS NOT NULL;
CREATE INDEX analyses_cache_idx ON analyses (cache_key) WHERE status = 'done';
-- Work queue of the worker (SELECT ... FOR UPDATE SKIP LOCKED).
CREATE INDEX analyses_pending_idx ON analyses (created_at) WHERE status = 'pending';
-- --- credits -----------------------------------------------------------------------
-- Append-only ledger; the balance is SUM(delta).
CREATE TABLE credit_ledger (
id uuid PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
delta integer NOT NULL CHECK (delta <> 0),
reason text NOT NULL CHECK (reason IN ('monthly_grant', 'analysis', 'chat', 'refund', 'admin_adjust', 'purchase')),
-- 'YYYY-MM' of a monthly grant.
period text,
analysis_id uuid REFERENCES analyses (id) ON DELETE SET NULL,
note text,
created_by uuid REFERENCES users (id) ON DELETE SET NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT credit_ledger_grant_period CHECK ((reason = 'monthly_grant') = (period IS NOT NULL))
);
CREATE UNIQUE INDEX credit_ledger_monthly_grant_once ON credit_ledger (user_id, period) WHERE reason = 'monthly_grant';
CREATE INDEX credit_ledger_user_idx ON credit_ledger (user_id, created_at DESC);
-- --- public sharing -----------------------------------------------------------------
-- A public link (and OG card) to a chart, synastry or analysis.
CREATE TABLE shares (
id uuid PRIMARY KEY,
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
-- Unguessable public identifier used in the URL.
slug text NOT NULL UNIQUE,
kind text NOT NULL CHECK (kind IN ('chart', 'synastry', 'analysis')),
chart_id uuid REFERENCES charts (id) ON DELETE CASCADE,
synastry_id uuid REFERENCES synastries (id) ON DELETE CASCADE,
analysis_id uuid REFERENCES analyses (id) ON DELETE CASCADE,
title text,
-- Birth date, time and place are hidden unless the owner allows them.
show_birth_data boolean NOT NULL DEFAULT false,
view_count bigint NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
revoked_at timestamptz,
CONSTRAINT shares_target CHECK (
(kind = 'chart' AND chart_id IS NOT NULL AND synastry_id IS NULL AND analysis_id IS NULL)
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL AND analysis_id IS NULL)
OR (kind = 'analysis' AND analysis_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL)
)
);
CREATE INDEX shares_owner_idx ON shares (owner_id, created_at DESC);
-- --- outgoing e-mail -----------------------------------------------------------------
-- Written by the backend, sent by the worker.
CREATE TABLE email_outbox (
id uuid PRIMARY KEY,
user_id uuid REFERENCES users (id) ON DELETE CASCADE,
to_email text NOT NULL,
template text NOT NULL,
locale text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
sent_at timestamptz,
attempts integer NOT NULL DEFAULT 0,
last_error text
);
CREATE INDEX email_outbox_unsent_idx ON email_outbox (created_at) WHERE sent_at IS NULL;
+126
View File
@@ -0,0 +1,126 @@
//! Database schema and the data access shared by several services
//! (sessions are validated by the backend and later by the chat engine).
use std::time::Duration;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use sqlx::postgres::{PgPool, PgPoolOptions};
use time::OffsetDateTime;
use uuid::Uuid;
pub use sqlx;
/// All schema migrations, embedded at compile time.
pub static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("./migrations");
pub async fn connect(url: &str) -> Result<PgPool, sqlx::Error> {
PgPoolOptions::new().max_connections(20).acquire_timeout(Duration::from_secs(5)).connect(url).await
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Role {
Admin,
/// May write articles (phase 2).
Creator,
User,
}
impl Role {
pub const ALL: [Role; 3] = [Role::Admin, Role::Creator, Role::User];
pub fn as_str(self) -> &'static str {
match self {
Role::Admin => "admin",
Role::Creator => "creator",
Role::User => "user",
}
}
pub fn parse(s: &str) -> Option<Role> {
Role::ALL.into_iter().find(|r| r.as_str() == s)
}
}
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct User {
pub id: Uuid,
pub email: String,
pub email_verified_at: Option<OffsetDateTime>,
pub display_name: Option<String>,
pub locale: String,
pub roles: Vec<String>,
pub created_at: OffsetDateTime,
pub last_login_at: Option<OffsetDateTime>,
}
impl User {
pub fn has_role(&self, role: Role) -> bool {
self.roles.iter().any(|r| r == role.as_str())
}
pub fn role_list(&self) -> Vec<Role> {
self.roles.iter().filter_map(|r| Role::parse(r)).collect()
}
}
/// Columns selected into [`User`].
pub const USER_COLUMNS: &str = "id, email, email_verified_at, display_name, locale, roles, created_at, last_login_at";
/// A new random secret token (256 bits, URL-safe base64).
pub fn new_token() -> String {
random_token(32)
}
/// `bytes` random bytes as URL-safe base64.
pub fn random_token(bytes: usize) -> String {
let mut buf = vec![0u8; bytes];
rand::rng().fill_bytes(&mut buf);
URL_SAFE_NO_PAD.encode(buf)
}
/// Stored form of a secret token.
pub fn token_hash(token: &str) -> Vec<u8> {
Sha256::digest(token.as_bytes()).to_vec()
}
/// The session id and user of a valid (unexpired) session token.
pub async fn user_by_session(pool: &PgPool, token: &str) -> Result<Option<(Uuid, User)>, sqlx::Error> {
#[derive(sqlx::FromRow)]
struct Row {
session_id: Uuid,
#[sqlx(flatten)]
user: User,
}
let row: Option<Row> = sqlx::query_as(
"SELECT s.id AS session_id, u.id, u.email, u.email_verified_at, u.display_name, u.locale, u.roles, \
u.created_at, u.last_login_at \
FROM sessions s JOIN users u ON u.id = s.user_id \
WHERE s.token_hash = $1 AND s.expires_at > now()",
)
.bind(token_hash(token))
.fetch_optional(pool)
.await?;
Ok(row.map(|r| (r.session_id, r.user)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tokens_are_random_and_hashed() {
let a = new_token();
let b = new_token();
assert_ne!(a, b);
assert_eq!(a.len(), 43);
assert_eq!(token_hash(&a), token_hash(&a));
assert_ne!(token_hash(&a), token_hash(&b));
assert_eq!(Role::parse("creator"), Some(Role::Creator));
assert_eq!(Role::parse("root"), None);
}
}