Skip to content

Nexus Package

nexus

Nexus — F1 data service.

Provides FastF1/Ergast data fetching, database CRUD, authentication, and user prediction management.

config

Nexus service configuration.

All settings are loaded from environment variables with sensible defaults. Variables are prefixed with F1BOARD_NEXUS_ for service-specific values.

db

Database layer for the Nexus service.

auth

User authentication database queries.

get_user_id_by_username async
get_user_id_by_username(db: AsyncSession, username: str) -> str | None

Return a user's ID for the given username, or None.

create_user async
create_user(db: AsyncSession, username: str, password_hash: str) -> Mapping[str, Any] | None

Insert a new user and return the created row.

get_user_for_login async
get_user_for_login(db: AsyncSession, username: str) -> Mapping[str, Any] | None

Fetch a user row including password hash for login verification.

get_user_by_id async
get_user_by_id(db: AsyncSession, user_id: str) -> Mapping[str, Any] | None

Fetch a user by their UUID.

update_user_profile async
update_user_profile(db: AsyncSession, user_id: str, favorite_team: str | None, email: str | None, notifications_enabled: bool) -> Mapping[str, Any] | None

Update a user's profile fields and return the updated row.

connection

Async database engine and session management for Nexus.

get_db async
get_db()

Yield an async database session for dependency injection.

init_db async
init_db()

Create all tables defined in the ORM metadata and apply migrations.

close_db async
close_db()

Dispose of the database engine and release connections.

crud

CRUD helpers for the Nexus service database.

Every public function accepts an AsyncSession as its first argument.

get_driver async
get_driver(db: AsyncSession, driver_id: str) -> models.Driver | None

Fetch a driver by their string identifier.

get_driver_by_id async
get_driver_by_id(db: AsyncSession, id: int) -> models.Driver | None

Fetch a driver by primary key.

get_all_drivers async
get_all_drivers(db: AsyncSession) -> list[models.Driver]

Return all drivers.

get_drivers_by_season async
get_drivers_by_season(db: AsyncSession, season: int) -> list[models.Driver]

Return drivers active in a specific season.

create_driver async
create_driver(db: AsyncSession, driver: DriverCreate) -> models.Driver

Insert a new driver row.

get_or_create_driver async
get_or_create_driver(db: AsyncSession, driver: DriverCreate) -> models.Driver

Return an existing driver or create a new one.

If the driver already exists but has a missing nationality, update it from the incoming data.

get_constructor async
get_constructor(db: AsyncSession, constructor_id: str) -> models.Constructor | None

Fetch a constructor by its string identifier.

create_constructor async
create_constructor(db: AsyncSession, constructor: ConstructorCreate) -> models.Constructor

Insert a new constructor row.

get_or_create_constructor async
get_or_create_constructor(db: AsyncSession, constructor: ConstructorCreate) -> models.Constructor

Return an existing constructor or create a new one.

get_race async
get_race(db: AsyncSession, season: int, round: int) -> models.Race | None

Fetch a race by season and round number.

get_all_races async
get_all_races(db: AsyncSession) -> list[models.Race]

Return all races ordered by season and round.

create_race async
create_race(db: AsyncSession, race: RaceCreate) -> models.Race

Insert a new race row.

get_or_create_race async
get_or_create_race(db: AsyncSession, race: RaceCreate) -> models.Race

Return an existing race or create a new one.

create_race_result async
create_race_result(db: AsyncSession, result: RaceResultCreate) -> models.RaceResult

Insert a new race result row.

get_race_results async
get_race_results(db: AsyncSession, race_id: int) -> list[models.RaceResult]

Return all results for a race, eager-loading driver and constructor.

get_driver_results async
get_driver_results(db: AsyncSession, driver_id: int) -> list[models.RaceResult]

Return all race results for a specific driver.

get_all_results async
get_all_results(db: AsyncSession) -> list[models.RaceResult]

Return every race result with related race, driver, and constructor.

get_stats async
get_stats(db: AsyncSession) -> dict

Return aggregate statistics (driver/race/result counts, seasons).

fastf1_cache

Database caching for FastF1 data to improve performance.

FastF1DbCache

Cache FastF1 data in PostgreSQL.

get_race_winner async staticmethod
get_race_winner(year: int, round_num: int) -> dict | None

Get cached race winner from database.

save_race_winner async staticmethod
save_race_winner(year: int, round_num: int, winner_data: dict) -> None

Save race winner to database cache.

get_race_results async staticmethod
get_race_results(year: int, round_num: int) -> list[dict] | None

Get cached race results from database.

save_race_results async staticmethod
save_race_results(year: int, round_num: int, results: list[dict]) -> None

Save race results to database cache.

get_standings async staticmethod
get_standings(year: int, cache_type: str) -> dict | None

Get cached standings from database (driver or constructor).

save_standings async staticmethod
save_standings(year: int, cache_type: str, completed_rounds: int, standings_data: list[dict]) -> None

Save standings to database cache.

predictions

User prediction CRUD and scoring logic.

Handles creating, updating, scoring, and deleting user podium predictions.

upsert_prediction async
upsert_prediction(db: AsyncSession, user_id: str, race_id: int, p1_driver_id: int, p2_driver_id: int, p3_driver_id: int) -> models.UserPrediction

Create or update a user's podium prediction for a race.

get_user_predictions async
get_user_predictions(db: AsyncSession, user_id: str) -> list[models.UserPrediction]

Return all predictions for a user, ordered newest first.

get_prediction_score async
get_prediction_score(db: AsyncSession, prediction_id: int) -> int | None

Return the score for a single prediction, syncing if needed.

delete_prediction_for_user_race async
delete_prediction_for_user_race(db: AsyncSession, user_id: str, race_id: int) -> bool

Delete a user's prediction for a race (only if not locked).

get_race_predictions async
get_race_predictions(db: AsyncSession, race_id: int) -> list[dict]

Return all user predictions for a specific race with usernames.

get_leaderboard_progression async
get_leaderboard_progression(db: AsyncSession) -> list[dict]

Build per-round cumulative points progression for each user.

get_leaderboard_rows async
get_leaderboard_rows(db: AsyncSession) -> list[dict]

Build a season leaderboard ranked by total prediction score.

main

FastAPI application entry point for the Nexus data service.

Registers routers, configures CORS, and manages the application lifespan.

preload_fastf1_cache async

preload_fastf1_cache()

Preload FastF1 data in background to warm the cache without blocking startup.

lifespan async

lifespan(app: FastAPI)

Initialise the database on startup and clean up on shutdown.

root async

root()

Return service metadata.

models

ORM models and Pydantic schemas for the Nexus service.

database

SQLAlchemy ORM models for Nexus-specific tables.

User

Bases: Base

Application user with authentication credentials.

UserPrediction

Bases: Base

A user's podium prediction for a race.

NotificationDispatch

Bases: Base

Tracks reminder/result emails that have been sent to a user for a race.

schemas

Pydantic schemas for request/response validation in the Nexus service.

DriverBase

Bases: BaseModel

Shared driver fields.

ConstructorBase

Bases: BaseModel

Shared constructor fields.

RaceBase

Bases: BaseModel

Shared race fields.

RaceResultBase

Bases: BaseModel

Shared race-result fields.

HealthResponse

Bases: BaseModel

Health-check response schema.

StatsResponse

Bases: BaseModel

Aggregate database statistics.

SyncRequest

Bases: BaseModel

Data sync request specifying season range.

SyncResponse

Bases: BaseModel

Data sync result summary.

DriverSyncResponse

Bases: BaseModel

Driver sync result summary.

AuthRequest

Bases: BaseModel

Login or registration request.

AuthUser

Bases: BaseModel

Authenticated user profile returned to the frontend.

ProfileUpdate

Bases: BaseModel

Request body for updating user profile settings.

AuthResponse

Bases: BaseModel

Authentication response with user info and JWT.

PredictionCreate

Bases: BaseModel

Request body for creating a podium prediction.

PredictionResponse

Bases: BaseModel

Full prediction response with driver names and optional score.

LeaderboardEntry

Bases: BaseModel

A single row on the season leaderboard.

RacePredictionEntry

Bases: BaseModel

A single user's prediction for a race, shown to other players.

LeaderboardProgressionPoint

Bases: BaseModel

A single round data point in a user's leaderboard progression.

LeaderboardProgressionEntry

Bases: BaseModel

A user's cumulative points progression across the season.

routers

FastAPI routers for the Nexus service.

auth

Authentication endpoints (register, login, profile).

register async
register(request: AuthRequest, db: AsyncSession = Depends(get_db))

Register a new user account.

login async
login(request: AuthRequest, db: AsyncSession = Depends(get_db))

Authenticate a user and return a JWT.

me async
me(token: str = Depends(get_bearer_token), db: AsyncSession = Depends(get_db))

Return the authenticated user's profile.

update_user_profile async
update_user_profile(body: ProfileUpdate, token: str = Depends(get_bearer_token), db: AsyncSession = Depends(get_db))

Update the authenticated user's profile settings.

calendar

Calendar and standings endpoints backed by FastF1.

get_calendar async
get_calendar(year: int = Query(default=None))

Return the race calendar for a given year.

get_driver_standings async
get_driver_standings(year: int = Query(default=None))

Return current driver championship standings.

get_constructor_standings async
get_constructor_standings(year: int = Query(default=None))

Return current constructor championship standings.

health

Health endpoint for the Nexus data service.

health_check async
health_check(db: AsyncSession = Depends(get_db))

Return service health including database connectivity.

predictions

User and AI prediction endpoints.

Handles submitting, retrieving, scoring, and deleting user podium predictions as well as fetching AI-generated predictions from the ML service.

submit_prediction async
submit_prediction(request: PredictionCreate, current_user: AuthUser = Depends(_require_current_user), db: AsyncSession = Depends(get_db))

Submit or update a podium prediction for the authenticated user.

get_predictions_for_user async
get_predictions_for_user(user_id: str, current_user: AuthUser = Depends(_require_current_user), db: AsyncSession = Depends(get_db))

List all predictions for the authenticated user.

get_prediction_leaderboard async
get_prediction_leaderboard(db: AsyncSession = Depends(get_db))

Return the season prediction leaderboard.

get_leaderboard_points_progression async
get_leaderboard_points_progression(db: AsyncSession = Depends(get_db))

Return per-round cumulative points progression for all players.

get_all_predictions_for_race async
get_all_predictions_for_race(race_id: int, db: AsyncSession = Depends(get_db))

Return all user predictions for a given race.

clear_prediction_for_race async
clear_prediction_for_race(race_id: int, current_user: AuthUser = Depends(_require_current_user), db: AsyncSession = Depends(get_db))

Delete the authenticated user's prediction for a race.

get_ai_prediction_for_current_race async
get_ai_prediction_for_current_race(_: AuthUser = Depends(_require_current_user), db: AsyncSession = Depends(get_db))

Return the AI prediction for the next upcoming race.

get_single_prediction_score async
get_single_prediction_score(prediction_id: int, db: AsyncSession = Depends(get_db))

Return the score for a single prediction.

stats

Stats, data sync, and resource listing endpoints.

get_stats async
get_stats(db: AsyncSession = Depends(get_db))

Return aggregate database statistics.

sync_f1_data async
sync_f1_data(request: SyncRequest, db: AsyncSession = Depends(get_db))

Sync F1 race data from FastF1 for a range of seasons.

sync_drivers async
sync_drivers(year: int, db: AsyncSession = Depends(get_db))

Sync drivers and constructors for a single season from FastF1.

sync_season async
sync_season(year: int, db: AsyncSession = Depends(get_db))

Sync a single season's data.

backfill_nationalities async
backfill_nationalities(db: AsyncSession = Depends(get_db))

Repopulate missing driver nationalities.

For drivers whose nationality is empty or looks like a 3-letter country code, this endpoint converts them to proper nationality strings and, for any still missing, attempts to fetch the data from the Jolpica API by re-syncing the seasons in which the driver has race results.

get_drivers async
get_drivers(db: AsyncSession = Depends(get_db), season: int | None = None)

List drivers, optionally filtered to a specific season.

get_races async
get_races(db: AsyncSession = Depends(get_db))

List all known races.

get_race async
get_race(season: int, round: int, db: AsyncSession = Depends(get_db))

Fetch a single race by season and round.

get_race_results async
get_race_results(season: int, round: int, db: AsyncSession = Depends(get_db))

Return finishing results for a specific race.

services

Business-logic services for the Nexus service.

auth

Authentication business logic.

Orchestrates user registration, login, and profile operations between the database layer and the HTTP layer.

register_user async
register_user(db: AsyncSession, request: AuthRequest) -> AuthResponse

Register a new user, returning an AuthResponse with JWT.

login_user async
login_user(db: AsyncSession, request: AuthRequest) -> AuthResponse

Authenticate a user and return an AuthResponse with JWT.

get_current_user async
get_current_user(db: AsyncSession, token: str) -> AuthUser

Decode a JWT and return the corresponding AuthUser.

update_profile async
update_profile(db: AsyncSession, token: str, profile: ProfileUpdate) -> AuthUser

Update the authenticated user's profile.

f1_data

Ergast F1 API client for fetching and syncing historical data.

ErgastService

HTTP client for the Ergast F1 REST API.

close async
close() -> None

Close the underlying HTTP client.

fetch_season_races async
fetch_season_races(season: int) -> list[dict[str, Any]]

Fetch the race schedule for a season from Ergast.

fetch_race_results async
fetch_race_results(season: int, round: int) -> dict[str, Any] | None

Fetch detailed results for a specific race.

sync_season async
sync_season(db: AsyncSession, season: int) -> tuple[int, int]

Sync a full season (races, drivers, constructors, results) to the DB.

fetch_season_constructors async
fetch_season_constructors(season: int) -> list[dict[str, Any]]

Fetch the constructor list for a season.

fetch_constructor_drivers async
fetch_constructor_drivers(season: int, constructor_id: str) -> list[dict[str, Any]]

Fetch drivers for a specific constructor in a season.

fetch_season_drivers async
fetch_season_drivers(season: int) -> list[dict[str, Any]]

Fetch all drivers for a season with their constructor info.

Returns a list of dicts with keys: driverId, code, givenName, familyName, permanentNumber, nationality, constructorId, constructorName, constructorNationality.

sync_seasons async
sync_seasons(db: AsyncSession, start: int, end: int) -> tuple[int, int]

Sync a range of seasons to the database.

fastf1_data

FastF1Service
sync_season_drivers async
sync_season_drivers(db: AsyncSession, year: int) -> dict

Sync drivers and constructors for year into the DB.

Fetches driver data from the Jolpica (Ergast) API with constructor assignments. This works reliably even before the season starts.

The caller is responsible for committing the transaction.

sync_drivers_to_db async
sync_drivers_to_db(year: int) -> dict

Fetch drivers for a season from Jolpica API and persist to the DB.

Self-contained entry-point that manages its own DB session.

fastf1_sync

Sync FastF1 data to the database for ML training.

sync_season_to_db async
sync_season_to_db(db: AsyncSession, year: int) -> dict

Sync all completed races for a season to the database.

sync_all_seasons async
sync_all_seasons(db: AsyncSession, start_year: int, end_year: int) -> dict

Sync multiple seasons to the database.

notifications

Notification scheduler for race reminders and results emails.

NotificationService

Periodic worker that sends race reminder and result emails.

start
start() -> None

Start scheduler loop if notifications are configured.

stop async
stop() -> None

Stop scheduler loop.

utils

Utility helpers for the Nexus service.

auth

Password hashing and JWT token management.

hash_password
hash_password(password: str) -> str

Hash a password using PBKDF2-SHA256.

verify_password
verify_password(password: str, stored_hash: str) -> bool

Verify a password against a stored hash (supports PBKDF2 and bcrypt).

create_access_token
create_access_token(user_id: str, username: str) -> str

Create a signed JWT access token.

decode_access_token
decode_access_token(token: str) -> dict[str, Any]

Decode and validate a JWT access token.

get_bearer_token
get_bearer_token(authorization: str | None = Header(default=None)) -> str

Extract the bearer token from the Authorization header.

nationality

Country code to nationality mapping for F1 drivers and constructors.

country_code_to_nationality
country_code_to_nationality(code: str | None) -> str

Convert a country code to a nationality string.

Returns the nationality string if found, otherwise returns the original code stripped of whitespace, or an empty string.

simple_cache

Simple in-memory TTL cache.

SimpleTTLCache

Thread-unsafe in-memory cache with per-key time-to-live.

get
get(key: str) -> Any | None

Return cached value or None if expired/missing.

set
set(key: str, value: Any, ttl_seconds: int) -> None

Store a value with a TTL in seconds.

invalidate_prefix
invalidate_prefix(prefix: str) -> None

Remove all entries whose key starts with prefix.

clear
clear() -> None

Remove all cached entries.

Configuration

nexus.config

Nexus service configuration.

All settings are loaded from environment variables with sensible defaults. Variables are prefixed with F1BOARD_NEXUS_ for service-specific values.

Database

Connection

nexus.db.connection

Async database engine and session management for Nexus.

get_db async

get_db()

Yield an async database session for dependency injection.

init_db async

init_db()

Create all tables defined in the ORM metadata and apply migrations.

close_db async

close_db()

Dispose of the database engine and release connections.

CRUD

nexus.db.crud

CRUD helpers for the Nexus service database.

Every public function accepts an AsyncSession as its first argument.

get_driver async

get_driver(db: AsyncSession, driver_id: str) -> models.Driver | None

Fetch a driver by their string identifier.

get_driver_by_id async

get_driver_by_id(db: AsyncSession, id: int) -> models.Driver | None

Fetch a driver by primary key.

get_all_drivers async

get_all_drivers(db: AsyncSession) -> list[models.Driver]

Return all drivers.

get_drivers_by_season async

get_drivers_by_season(db: AsyncSession, season: int) -> list[models.Driver]

Return drivers active in a specific season.

create_driver async

create_driver(db: AsyncSession, driver: DriverCreate) -> models.Driver

Insert a new driver row.

get_or_create_driver async

get_or_create_driver(db: AsyncSession, driver: DriverCreate) -> models.Driver

Return an existing driver or create a new one.

If the driver already exists but has a missing nationality, update it from the incoming data.

get_constructor async

get_constructor(db: AsyncSession, constructor_id: str) -> models.Constructor | None

Fetch a constructor by its string identifier.

create_constructor async

create_constructor(db: AsyncSession, constructor: ConstructorCreate) -> models.Constructor

Insert a new constructor row.

get_or_create_constructor async

get_or_create_constructor(db: AsyncSession, constructor: ConstructorCreate) -> models.Constructor

Return an existing constructor or create a new one.

get_race async

get_race(db: AsyncSession, season: int, round: int) -> models.Race | None

Fetch a race by season and round number.

get_all_races async

get_all_races(db: AsyncSession) -> list[models.Race]

Return all races ordered by season and round.

create_race async

create_race(db: AsyncSession, race: RaceCreate) -> models.Race

Insert a new race row.

get_or_create_race async

get_or_create_race(db: AsyncSession, race: RaceCreate) -> models.Race

Return an existing race or create a new one.

create_race_result async

create_race_result(db: AsyncSession, result: RaceResultCreate) -> models.RaceResult

Insert a new race result row.

get_race_results async

get_race_results(db: AsyncSession, race_id: int) -> list[models.RaceResult]

Return all results for a race, eager-loading driver and constructor.

get_driver_results async

get_driver_results(db: AsyncSession, driver_id: int) -> list[models.RaceResult]

Return all race results for a specific driver.

get_all_results async

get_all_results(db: AsyncSession) -> list[models.RaceResult]

Return every race result with related race, driver, and constructor.

get_stats async

get_stats(db: AsyncSession) -> dict

Return aggregate statistics (driver/race/result counts, seasons).

Authentication Queries

nexus.db.auth

User authentication database queries.

get_user_id_by_username async

get_user_id_by_username(db: AsyncSession, username: str) -> str | None

Return a user's ID for the given username, or None.

create_user async

create_user(db: AsyncSession, username: str, password_hash: str) -> Mapping[str, Any] | None

Insert a new user and return the created row.

get_user_for_login async

get_user_for_login(db: AsyncSession, username: str) -> Mapping[str, Any] | None

Fetch a user row including password hash for login verification.

get_user_by_id async

get_user_by_id(db: AsyncSession, user_id: str) -> Mapping[str, Any] | None

Fetch a user by their UUID.

update_user_profile async

update_user_profile(db: AsyncSession, user_id: str, favorite_team: str | None, email: str | None, notifications_enabled: bool) -> Mapping[str, Any] | None

Update a user's profile fields and return the updated row.

Predictions

nexus.db.predictions

User prediction CRUD and scoring logic.

Handles creating, updating, scoring, and deleting user podium predictions.

upsert_prediction async

upsert_prediction(db: AsyncSession, user_id: str, race_id: int, p1_driver_id: int, p2_driver_id: int, p3_driver_id: int) -> models.UserPrediction

Create or update a user's podium prediction for a race.

get_user_predictions async

get_user_predictions(db: AsyncSession, user_id: str) -> list[models.UserPrediction]

Return all predictions for a user, ordered newest first.

get_prediction_score async

get_prediction_score(db: AsyncSession, prediction_id: int) -> int | None

Return the score for a single prediction, syncing if needed.

delete_prediction_for_user_race async

delete_prediction_for_user_race(db: AsyncSession, user_id: str, race_id: int) -> bool

Delete a user's prediction for a race (only if not locked).

get_race_predictions async

get_race_predictions(db: AsyncSession, race_id: int) -> list[dict]

Return all user predictions for a specific race with usernames.

get_leaderboard_progression async

get_leaderboard_progression(db: AsyncSession) -> list[dict]

Build per-round cumulative points progression for each user.

get_leaderboard_rows async

get_leaderboard_rows(db: AsyncSession) -> list[dict]

Build a season leaderboard ranked by total prediction score.

FastF1 Cache

nexus.db.fastf1_cache

Database caching for FastF1 data to improve performance.

FastF1DbCache

Cache FastF1 data in PostgreSQL.

get_race_winner async staticmethod

get_race_winner(year: int, round_num: int) -> dict | None

Get cached race winner from database.

save_race_winner async staticmethod

save_race_winner(year: int, round_num: int, winner_data: dict) -> None

Save race winner to database cache.

get_race_results async staticmethod

get_race_results(year: int, round_num: int) -> list[dict] | None

Get cached race results from database.

save_race_results async staticmethod

save_race_results(year: int, round_num: int, results: list[dict]) -> None

Save race results to database cache.

get_standings async staticmethod

get_standings(year: int, cache_type: str) -> dict | None

Get cached standings from database (driver or constructor).

save_standings async staticmethod

save_standings(year: int, cache_type: str, completed_rounds: int, standings_data: list[dict]) -> None

Save standings to database cache.

Models

ORM Models

nexus.models.database

SQLAlchemy ORM models for Nexus-specific tables.

User

Bases: Base

Application user with authentication credentials.

UserPrediction

Bases: Base

A user's podium prediction for a race.

NotificationDispatch

Bases: Base

Tracks reminder/result emails that have been sent to a user for a race.

Schemas

nexus.models.schemas

Pydantic schemas for request/response validation in the Nexus service.

DriverBase

Bases: BaseModel

Shared driver fields.

ConstructorBase

Bases: BaseModel

Shared constructor fields.

RaceBase

Bases: BaseModel

Shared race fields.

RaceResultBase

Bases: BaseModel

Shared race-result fields.

HealthResponse

Bases: BaseModel

Health-check response schema.

StatsResponse

Bases: BaseModel

Aggregate database statistics.

SyncRequest

Bases: BaseModel

Data sync request specifying season range.

SyncResponse

Bases: BaseModel

Data sync result summary.

DriverSyncResponse

Bases: BaseModel

Driver sync result summary.

AuthRequest

Bases: BaseModel

Login or registration request.

AuthUser

Bases: BaseModel

Authenticated user profile returned to the frontend.

ProfileUpdate

Bases: BaseModel

Request body for updating user profile settings.

AuthResponse

Bases: BaseModel

Authentication response with user info and JWT.

PredictionCreate

Bases: BaseModel

Request body for creating a podium prediction.

PredictionResponse

Bases: BaseModel

Full prediction response with driver names and optional score.

LeaderboardEntry

Bases: BaseModel

A single row on the season leaderboard.

RacePredictionEntry

Bases: BaseModel

A single user's prediction for a race, shown to other players.

LeaderboardProgressionPoint

Bases: BaseModel

A single round data point in a user's leaderboard progression.

LeaderboardProgressionEntry

Bases: BaseModel

A user's cumulative points progression across the season.

Routers

Health

nexus.routers.health

Health endpoint for the Nexus data service.

health_check async

health_check(db: AsyncSession = Depends(get_db))

Return service health including database connectivity.

Calendar

nexus.routers.calendar

Calendar and standings endpoints backed by FastF1.

get_calendar async

get_calendar(year: int = Query(default=None))

Return the race calendar for a given year.

get_driver_standings async

get_driver_standings(year: int = Query(default=None))

Return current driver championship standings.

get_constructor_standings async

get_constructor_standings(year: int = Query(default=None))

Return current constructor championship standings.

Stats

nexus.routers.stats

Stats, data sync, and resource listing endpoints.

get_stats async

get_stats(db: AsyncSession = Depends(get_db))

Return aggregate database statistics.

sync_f1_data async

sync_f1_data(request: SyncRequest, db: AsyncSession = Depends(get_db))

Sync F1 race data from FastF1 for a range of seasons.

sync_drivers async

sync_drivers(year: int, db: AsyncSession = Depends(get_db))

Sync drivers and constructors for a single season from FastF1.

sync_season async

sync_season(year: int, db: AsyncSession = Depends(get_db))

Sync a single season's data.

backfill_nationalities async

backfill_nationalities(db: AsyncSession = Depends(get_db))

Repopulate missing driver nationalities.

For drivers whose nationality is empty or looks like a 3-letter country code, this endpoint converts them to proper nationality strings and, for any still missing, attempts to fetch the data from the Jolpica API by re-syncing the seasons in which the driver has race results.

get_drivers async

get_drivers(db: AsyncSession = Depends(get_db), season: int | None = None)

List drivers, optionally filtered to a specific season.

get_races async

get_races(db: AsyncSession = Depends(get_db))

List all known races.

get_race async

get_race(season: int, round: int, db: AsyncSession = Depends(get_db))

Fetch a single race by season and round.

get_race_results async

get_race_results(season: int, round: int, db: AsyncSession = Depends(get_db))

Return finishing results for a specific race.

Authentication

nexus.routers.auth

Authentication endpoints (register, login, profile).

register async

register(request: AuthRequest, db: AsyncSession = Depends(get_db))

Register a new user account.

login async

login(request: AuthRequest, db: AsyncSession = Depends(get_db))

Authenticate a user and return a JWT.

me async

me(token: str = Depends(get_bearer_token), db: AsyncSession = Depends(get_db))

Return the authenticated user's profile.

update_user_profile async

update_user_profile(body: ProfileUpdate, token: str = Depends(get_bearer_token), db: AsyncSession = Depends(get_db))

Update the authenticated user's profile settings.

Predictions

nexus.routers.predictions

User and AI prediction endpoints.

Handles submitting, retrieving, scoring, and deleting user podium predictions as well as fetching AI-generated predictions from the ML service.

submit_prediction async

submit_prediction(request: PredictionCreate, current_user: AuthUser = Depends(_require_current_user), db: AsyncSession = Depends(get_db))

Submit or update a podium prediction for the authenticated user.

get_predictions_for_user async

get_predictions_for_user(user_id: str, current_user: AuthUser = Depends(_require_current_user), db: AsyncSession = Depends(get_db))

List all predictions for the authenticated user.

get_prediction_leaderboard async

get_prediction_leaderboard(db: AsyncSession = Depends(get_db))

Return the season prediction leaderboard.

get_leaderboard_points_progression async

get_leaderboard_points_progression(db: AsyncSession = Depends(get_db))

Return per-round cumulative points progression for all players.

get_all_predictions_for_race async

get_all_predictions_for_race(race_id: int, db: AsyncSession = Depends(get_db))

Return all user predictions for a given race.

clear_prediction_for_race async

clear_prediction_for_race(race_id: int, current_user: AuthUser = Depends(_require_current_user), db: AsyncSession = Depends(get_db))

Delete the authenticated user's prediction for a race.

get_ai_prediction_for_current_race async

get_ai_prediction_for_current_race(_: AuthUser = Depends(_require_current_user), db: AsyncSession = Depends(get_db))

Return the AI prediction for the next upcoming race.

get_single_prediction_score async

get_single_prediction_score(prediction_id: int, db: AsyncSession = Depends(get_db))

Return the score for a single prediction.

Services

Authentication

nexus.services.auth

Authentication business logic.

Orchestrates user registration, login, and profile operations between the database layer and the HTTP layer.

register_user async

register_user(db: AsyncSession, request: AuthRequest) -> AuthResponse

Register a new user, returning an AuthResponse with JWT.

login_user async

login_user(db: AsyncSession, request: AuthRequest) -> AuthResponse

Authenticate a user and return an AuthResponse with JWT.

get_current_user async

get_current_user(db: AsyncSession, token: str) -> AuthUser

Decode a JWT and return the corresponding AuthUser.

update_profile async

update_profile(db: AsyncSession, token: str, profile: ProfileUpdate) -> AuthUser

Update the authenticated user's profile.

Ergast API Client

nexus.services.f1_data

Ergast F1 API client for fetching and syncing historical data.

ErgastService

HTTP client for the Ergast F1 REST API.

close async

close() -> None

Close the underlying HTTP client.

fetch_season_races async

fetch_season_races(season: int) -> list[dict[str, Any]]

Fetch the race schedule for a season from Ergast.

fetch_race_results async

fetch_race_results(season: int, round: int) -> dict[str, Any] | None

Fetch detailed results for a specific race.

sync_season async

sync_season(db: AsyncSession, season: int) -> tuple[int, int]

Sync a full season (races, drivers, constructors, results) to the DB.

fetch_season_constructors async

fetch_season_constructors(season: int) -> list[dict[str, Any]]

Fetch the constructor list for a season.

fetch_constructor_drivers async

fetch_constructor_drivers(season: int, constructor_id: str) -> list[dict[str, Any]]

Fetch drivers for a specific constructor in a season.

fetch_season_drivers async

fetch_season_drivers(season: int) -> list[dict[str, Any]]

Fetch all drivers for a season with their constructor info.

Returns a list of dicts with keys: driverId, code, givenName, familyName, permanentNumber, nationality, constructorId, constructorName, constructorNationality.

sync_seasons async

sync_seasons(db: AsyncSession, start: int, end: int) -> tuple[int, int]

Sync a range of seasons to the database.

FastF1 Data

nexus.services.fastf1_data

FastF1Service

sync_season_drivers async

sync_season_drivers(db: AsyncSession, year: int) -> dict

Sync drivers and constructors for year into the DB.

Fetches driver data from the Jolpica (Ergast) API with constructor assignments. This works reliably even before the season starts.

The caller is responsible for committing the transaction.

sync_drivers_to_db async

sync_drivers_to_db(year: int) -> dict

Fetch drivers for a season from Jolpica API and persist to the DB.

Self-contained entry-point that manages its own DB session.

FastF1 Sync

nexus.services.fastf1_sync

Sync FastF1 data to the database for ML training.

sync_season_to_db async

sync_season_to_db(db: AsyncSession, year: int) -> dict

Sync all completed races for a season to the database.

sync_all_seasons async

sync_all_seasons(db: AsyncSession, start_year: int, end_year: int) -> dict

Sync multiple seasons to the database.

Utilities

Auth Helpers

nexus.utils.auth

Password hashing and JWT token management.

hash_password

hash_password(password: str) -> str

Hash a password using PBKDF2-SHA256.

verify_password

verify_password(password: str, stored_hash: str) -> bool

Verify a password against a stored hash (supports PBKDF2 and bcrypt).

create_access_token

create_access_token(user_id: str, username: str) -> str

Create a signed JWT access token.

decode_access_token

decode_access_token(token: str) -> dict[str, Any]

Decode and validate a JWT access token.

get_bearer_token

get_bearer_token(authorization: str | None = Header(default=None)) -> str

Extract the bearer token from the Authorization header.

Simple Cache

nexus.utils.simple_cache

Simple in-memory TTL cache.

SimpleTTLCache

Thread-unsafe in-memory cache with per-key time-to-live.

get

get(key: str) -> Any | None

Return cached value or None if expired/missing.

set

set(key: str, value: Any, ttl_seconds: int) -> None

Store a value with a TTL in seconds.

invalidate_prefix

invalidate_prefix(prefix: str) -> None

Remove all entries whose key starts with prefix.

clear

clear() -> None

Remove all cached entries.