Diagramas Entidad-Relación (ERD)
Todas las tablas residen en PostgreSQL 16, organizadas por dominio con roles de conexión separados (auth, core, realtime, games). No existen claves foráneas entre servicios distintos para permitir despliegue y escalado independientes.
0. Tabla inicial activa hoy en producción (core)
Sección titulada «0. Tabla inicial activa hoy en producción (core)»Actualmente api.42.salado.me ya ejecuta la migración 001_phrases.sql que alimenta GET /random y la landing de 42.salado.me:
erDiagram
PHRASES {
smallint id PK "1..42"
text code UK "slug unico (ej. up2u)"
text phrase "Frase real de 42"
text meaning "Explicacion en contexto"
timestamptz created_at
}1. ERD de Identidad y Seguridad (auth)
Sección titulada «1. ERD de Identidad y Seguridad (auth)»erDiagram
CAMPUSES ||--o{ USERS : "campus_id"
USERS ||--o{ SESSIONS : "user_id"
USERS ||--o{ MAGIC_LINKS : "user_id"
USERS ||--o{ SECURITY_EVENTS : "user_id"
USERS ||--o| TOTP_SECRETS : "user_id"
USERS ||--o{ RECOVERY_CODES : "user_id"
CAMPUSES {
int id PK "ID oficial Intra 42"
text name UK
text country
text timezone
}
USERS {
uuid id PK
text login UK
text email UK
text password_hash "Argon2id/bcrypt (nullable si OAuth)"
int intra_id UK "Nullable"
text role "CHECK: student|moderator|staff|admin|company"
int campus_id FK
timestamptz campus_verified_at
int failed_login_count "Default 0"
timestamptz locked_until
timestamptz suspended_at
timestamptz consent_accepted_at
timestamptz deleted_at "Soft-delete RGPD 30d"
timestamptz created_at
}
SESSIONS {
uuid id PK
uuid user_id FK
text refresh_hash UK "SHA-256 del token opaco"
timestamptz used_at "Deteccion de reutilizacion"
timestamptz expires_at
timestamptz created_at
}
TOTP_SECRETS {
uuid user_id PK,FK
bytea encrypted_secret "AES-256-GCM"
boolean enabled "Default false"
timestamptz verified_at
}
RECOVERY_CODES {
uuid id PK
uuid user_id FK
text code_hash
timestamptz used_at
}
MAGIC_LINKS {
uuid id PK
uuid user_id FK
text token_hash UK
text purpose "signup|login|email_change"
timestamptz expires_at
timestamptz consumed_at
}
SECURITY_EVENTS {
uuid id PK
uuid user_id FK
text kind "login_ok|login_fail|2fa_on|reuse_detected|..."
text ip_hash
text user_agent
timestamptz created_at
}2. ERD de Comunidad, Campus y Estudio (core)
Sección titulada «2. ERD de Comunidad, Campus y Estudio (core)»erDiagram
PROFILES ||--o{ FRIENDSHIPS : "user_a / user_b"
PROFILES ||--|| USER_PROGRESS : "user_id"
PROFILES ||--o{ XP_EVENTS : "user_id"
PROFILES ||--o{ API_KEYS : "user_id"
EVENTS ||--o{ EVENT_REGISTRATIONS : "event_id"
LEAGUES ||--o{ LEAGUE_MEMBERS : "league_id"
DECKS ||--o{ FLASHCARDS : "deck_id"
QUESTIONS ||--o{ ANSWERS : "question_id"
COMPANIES ||--o{ JOB_OFFERS : "company_id"
JOB_OFFERS ||--o{ JOB_APPLICATIONS : "offer_id"
PROFILES {
uuid user_id PK "Ref por valor a auth.users"
text login UK
text display_name
text bio
text avatar_key "Objeto S3"
int campus_id
timestamptz updated_at
}
FRIENDSHIPS {
uuid user_a PK "CHECK user_a < user_b"
uuid user_b PK
uuid requester_id
text status "pending|accepted"
timestamptz created_at
}
EVENTS {
uuid id PK
int campus_id
uuid author_id
text title
text description
text location
timestamptz starts_at
int capacity
text status "draft|pending|published"
timestamptz published_at
}
EVENT_REGISTRATIONS {
uuid event_id PK,FK
uuid user_id PK
text state "registered|waitlist|cancelled"
timestamptz created_at
}
LEAGUES {
uuid id PK
text slug UK
int campus_id
text name
text policy "open|request"
text status "draft|pending|published"
}
LEAGUE_MEMBERS {
uuid league_id PK,FK
uuid user_id PK
text role "owner|manager|member|pending"
timestamptz joined_at
}
DECKS {
uuid id PK
uuid owner_id
text title
boolean is_public
timestamptz created_at
}
FLASHCARDS {
uuid id PK
uuid deck_id FK
text front
text back
float ease_factor "Default 2.5"
int interval_days
timestamptz next_review_at
}
QUESTIONS {
uuid id PK
uuid author_id
text title
text body
uuid accepted_answer_id
timestamptz created_at
}
ANSWERS {
uuid id PK
uuid question_id FK
uuid author_id
text body
int votes
timestamptz created_at
}
USER_PROGRESS {
uuid user_id PK
int total_xp "Default 0"
int level "Calculado"
int streak_days
timestamptz updated_at
}
XP_EVENTS {
uuid id PK
uuid user_id FK
text idempotency_key UK
text source "match|daily|qa|flashcards"
int amount
timestamptz created_at
}
API_KEYS {
uuid id PK
uuid user_id FK
text name
text prefix UK
text secret_hash
timestamptz revoked_at
timestamptz last_used_at
}
COMPANIES {
uuid id PK
text name UK
text status "pending|approved|rejected"
timestamptz created_at
}
JOB_OFFERS {
uuid id PK
uuid company_id FK
text title
text contract
text remote_mode
text status "draft|published|closed"
}
JOB_APPLICATIONS {
uuid id PK
uuid offer_id FK
uuid candidate_id
text status "sent|viewed|shortlisted|rejected|withdrawn"
timestamptz created_at
}3. ERD de Mensajería y Tiempo Real (realtime)
Sección titulada «3. ERD de Mensajería y Tiempo Real (realtime)»erDiagram
CHANNELS ||--o{ CHANNEL_MESSAGES : "channel_id"
CHANNEL_MESSAGES ||--o{ CHANNEL_MESSAGES : "parent_id"
CHANNEL_MESSAGES ||--o{ MESSAGE_REACTIONS : "message_id"
CHANNELS {
uuid id PK
text slug UK
text scope "world|campus"
text kind "public|coalition|league|milestone|project"
int campus_id "Nullable"
timestamptz created_at
}
CHANNEL_MESSAGES {
uuid id PK
uuid channel_id FK
uuid author_id
uuid parent_id FK "Nullable (hilo)"
text body
timestamptz hidden_at "Moderacion"
timestamptz created_at
}
MESSAGE_REACTIONS {
uuid message_id PK,FK
uuid user_id PK
text emoji PK
}
DIRECT_MESSAGES {
uuid id PK
uuid pair_a "CHECK pair_a < pair_b"
uuid pair_b
uuid sender_id
text body
timestamptz read_at
timestamptz created_at
}
NOTIFICATIONS {
uuid id PK
uuid user_id
text kind "mention|dm|friend|match|tournament|mod"
jsonb payload
timestamptz read_at
timestamptz created_at
}
BLOCKS {
uuid blocker_id PK
uuid blocked_id PK
timestamptz created_at
}4. ERD de Arena, Partidas y Torneos (games)
Sección titulada «4. ERD de Arena, Partidas y Torneos (games)»erDiagram
MATCHES ||--|{ MATCH_PLAYERS : "match_id"
MATCHES ||--o| REPLAYS : "match_id"
MATCHES ||--o{ OUTBOX_EVENTS : "aggregate_id"
TOURNAMENTS ||--|{ TOURNAMENT_PLAYERS : "tournament_id"
TOURNAMENTS ||--|{ TOURNAMENT_MATCHES : "tournament_id"
TOURNAMENT_MATCHES }o--o| MATCHES : "match_id"
TOURNAMENTS ||--o| TOURNAMENT_CHAIN : "tournament_id"
MATCHES {
uuid id PK
text game "pong|checkers"
text mode "ai|local|friend|ranked|party|tournament"
text status "invited|accepted|live|finished|declined|expired|abandoned"
bigint seed
jsonb rules
timestamptz started_at
timestamptz finished_at
}
MATCH_PLAYERS {
uuid match_id PK,FK
uuid user_id PK
smallint slot "0..7"
int score "Default 0"
int elo_before
int elo_after
}
REPLAYS {
uuid match_id PK,FK
bigint seed
jsonb input_log
timestamptz created_at
}
RATINGS {
uuid user_id PK
text game PK
int elo "Default 1200"
int wins
int losses
timestamptz updated_at
}
TOURNAMENTS {
uuid id PK
uuid creator_id
text name
int max_players "4|8|16"
text status "registering|live|finished|cancelled"
timestamptz created_at
}
TOURNAMENT_PLAYERS {
uuid tournament_id PK,FK
uuid user_id PK
int seed_order
}
TOURNAMENT_MATCHES {
uuid id PK
uuid tournament_id FK
int round
int position
uuid player_a
uuid player_b
uuid winner_id
uuid match_id FK
timestamptz deadline_at
}
TOURNAMENT_CHAIN {
uuid tournament_id PK,FK
text network
text tx_hash
text merkle_root
text status "pending|confirmed|failed"
}
OUTBOX_EVENTS {
uuid id PK
uuid aggregate_id
text destination
jsonb payload
int attempts
timestamptz delivered_at
}Restricciones e índices críticos
Sección titulada «Restricciones e índices críticos»- Pares ordenados (
CHECK (user_a < user_b)): enfriendshipsydirect_messagesevita duplicar la misma relación como(A, B)y(B, A). - Idempotencia (
xp_events.idempotency_key UK): garantiza que si el worker del outbox reintenta enviar XP por timeout de red, el jugador nunca recibe el doble de puntos. - Consistencia de publicación (
CHECK ((status = 'published') = (published_at IS NOT NULL))): impide registros publicados sin fecha o borradores con fecha de publicación. - Compare-And-Swap en aceptación de partidas:
UPDATE matches SET status = 'accepted' WHERE id = $1 AND status = 'invited'evita carreras cuando dos jugadores pulsan a la vez.