# rez3x/bsdy_api architecture

> Architecture diagram of the GitHub repository rez3x/bsdy_api, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-03). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/rez3x/bsdy_api
- Repository: https://github.com/rez3x/bsdy_api

## Overview

1. **Overall shape**
BSDY API is a Rust 2021 backend built on Axum, organized as a layered service. The top-level HTTP router exposes several feature-specific route groups, each backed by a service layer that talks to MySQL/MariaDB, encryption utilities, and external providers like Google OAuth, Gemini, and Brevo SMTP.

2. **Startup and runtime composition**
`main.rs` is the composition root. It loads config, initializes the database pool and migrations, builds shared application state, starts the background scheduler, then serves the Axum router with graceful shutdown. This is the main boundary where infrastructure is assembled before request handling begins.

3. **Shared application state**
`state.rs` holds the cross-cutting runtime dependencies: database pool, config, crypto engine, Gemini client, email client, and shared HTTP client. Handlers and services receive this state rather than constructing dependencies themselves, so the runtime graph is centralized and explicit.

4. **HTTP routing layer**
`src/routes/` defines the public API surface by domain: auth, onboarding, mood, analytics, reports, notes, chats, content, logs, health, docs, and dev. `routes/mod.rs` assembles these into the full router, including static file serving for uploaded content. The router is the boundary between HTTP concerns and business logic.

5. **Middleware and request gating**
`src/middleware/` contains the non-business request guards. `api_key.rs` enforces the external-mode `X-API-Key` requirement, while `auth.rs` implements a tiered extractor model: `AuthUser`, `VerifiedUser`, `FullUser`, and `AdminUser`. `activity_log.rs` provides helpers for writing auth, activity, and admin audit events. These middleware layers are a major architectural boundary because they determine which routes are reachable and under what user state.

6. **Authentication and authorization flow**
Authentication is built around Google OAuth 2.0 plus JWT session tokens. The auth service exchanges the OAuth code, issues JWTs, and manages email verification and profile updates. Authorization is not a single boolean check; it is staged by user state: valid token, verified email, onboarding completion, then optional admin role. That staged model controls access to most of the API.

7. **Domain services**
The `src/services/` layer contains the core business logic, separated by capability: auth, onboarding, mood tracking, analytics generation, report generation, notes, chat, content management, and scheduling. Services orchestrate database operations, encryption/decryption, AI calls, and email delivery. The routes stay thin and delegate nearly all workflow logic to these service modules.

8. **Data model and persistence**
`src/models/` defines the persistent and transfer objects for users, mental-health records, chats, notes, content, and logs. The database schema is created through SQL migrations in `migrations/`, with separate migrations for the initial schema, admin content, and admin action logs. The system is centered on SQLx with MariaDB/MySQL, so persistence is strongly typed and migration-driven.

9. **Encryption boundary**
`crypto.rs` implements at-rest protection using AES-256-GCM with per-user key derivation via HKDF-SHA256. The master key comes from environment config, and each user has a salt stored in the database. Sensitive fields such as baseline assessments, mood details, notes, chat messages, analytics, and reports are encrypted before persistence and decrypted when read back.

10. **External integrations**
There are three major third-party integrations:
- **Google OAuth** for user sign-in
- **Gemini API** for AI chat, analytics, reports, and agentic tool execution
- **Brevo SMTP** for verification and report emails  
These are encapsulated in dedicated service modules, which keeps the rest of the app insulated from provider-specific APIs.

11. **Chat and agentic tool execution**
Chat is more than message storage: `chat_service` and `agent_service` support conversational AI, including an agentic mode that can invoke tools against internal data and services. Tool calls can read mood/baseline/notes/analytics/reports, generate new summaries or reports, and create/update/delete notes. This is a key orchestration boundary where AI output drives internal DB and service actions.

12. **Background scheduling**
`scheduler_service.rs` starts cron-driven jobs at boot for recurring weekly, monthly, and yearly reports. The scheduler depends on the same shared services as the request path, so automated generation uses the same persistence, crypto, AI, and email pipelines as synchronous API calls.

13. **Public docs and operational surfaces**
The `/docs/*` routes expose password-protected interactive documentation, playground tooling, and a browser-based test runner. `/health` provides dependency checks for DB and external services, while `/uploads/*` serves uploaded content images. These are operational/support surfaces rather than core domain endpoints, but they are part of the deployed API footprint.

14. **Observability and auditability**
The app uses structured logging via tracing, plus distinct database-backed log types for authentication, activity, and admin actions. Logging is tied to role and feature boundaries, which makes it possible to reconstruct user/admin behavior independently from request logs.

15. **Testing strategy**
The `tests/` directory mirrors the architecture: config/crypto, database, auth/chat, Gemini, email, services, routes, and error/model behavior. Tests are split between pure unit tests and integration tests that require MariaDB or live external services, reflecting the same boundary lines as the production system.

Main entry points: [`src/routes/mod.rs`](https://github.com/rez3x/bsdy_api/blob/main/src/routes/mod.rs) (Router), [`src/db.rs`](https://github.com/rez3x/bsdy_api/blob/main/src/db.rs) (Database), [`src/services/report_service.rs`](https://github.com/rez3x/bsdy_api/blob/main/src/services/report_service.rs) (Reports), [`src/main.rs`](https://github.com/rez3x/bsdy_api/blob/main/src/main.rs) (Main)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_grp_runtime["Runtime"]
  node_main["Main<br/>composition root<br/>[main.rs]"]
  node_config["Config<br/>[config.rs]"]
  node_state["State<br/>shared deps<br/>[state.rs]"]
end

subgraph group_grp_http["HTTP API"]
  node_router["Router<br/>[mod.rs]"]
  node_middleware_auth["Auth guard<br/>request auth<br/>[auth.rs]"]
  node_middleware_key["API key<br/>external gate<br/>[api_key.rs]"]
  node_middleware_log["Audit log<br/>request logging<br/>[activity_log.rs]"]
  node_auth_routes["Auth routes<br/>route group<br/>[auth.rs]"]
  node_onboarding_routes["Onboarding<br/>route group<br/>[onboarding.rs]"]
  node_core_routes["Core routes<br/>route group<br/>[mood.rs]"]
  node_content_routes["Content<br/>route group<br/>[content.rs]"]
  node_ops_routes["Ops routes<br/>route group<br/>[health.rs]"]
end

subgraph group_grp_domain["Domain"]
  node_auth_service["Auth svc<br/>identity workflow<br/>[auth_service.rs]"]
  node_chat_service["Chat svc<br/>conversation workflow<br/>[chat_service.rs]"]
  node_agent_service["Agent svc<br/>tool orchestration<br/>[agent_service.rs]"]
  node_report_service["Reports<br/>report workflow<br/>[report_service.rs]"]
  node_scheduler_service["Scheduler<br/>background jobs"]
end

subgraph group_grp_data["Data"]
  node_db[("Database<br/>sqlx pool<br/>[db.rs]")]
  node_crypto{{"Crypto<br/>aes-gcm<br/>[crypto.rs]"}}
  node_models["Models<br/>domain records<br/>[mod.rs]"]
  node_migrations["Migrations<br/>schema sql"]
end

subgraph group_grp_external["External"]
  node_email_service["Email svc<br/>smtp delivery<br/>[email_service.rs]"]
  node_gemini_service["Gemini svc<br/>ai provider<br/>[gemini_service.rs]"]
end

node_main -->|"loads"| node_config
node_main -->|"builds"| node_state
node_main -->|"initializes"| node_db
node_main -->|"starts"| node_scheduler_service
node_main -->|"serves"| node_router
node_router -->|"uses"| node_middleware_auth
node_router -->|"uses"| node_middleware_key
node_router -->|"uses"| node_middleware_log
node_router -->|"mounts"| node_auth_routes
node_router -->|"mounts"| node_onboarding_routes
node_router -->|"mounts"| node_core_routes
node_router -->|"mounts"| node_content_routes
node_router -->|"mounts"| node_ops_routes
node_auth_routes -->|"delegates"| node_auth_service
node_onboarding_routes -->|"reads"| node_state
node_core_routes -->|"delegates"| node_chat_service
node_core_routes -->|"delegates"| node_report_service
node_core_routes -->|"delegates"| node_agent_service
node_content_routes -->|"reads"| node_state
node_ops_routes -->|"checks"| node_db
node_auth_service -->|"reads/writes"| node_db
node_auth_service -->|"uses"| node_crypto
node_auth_service -->|"uses"| node_email_service
node_auth_service -->|"uses"| node_gemini_service
node_chat_service -->|"reads/writes"| node_db
node_chat_service -->|"uses"| node_crypto
node_chat_service -->|"uses"| node_gemini_service
node_agent_service -->|"orchestrates"| node_chat_service
node_agent_service -->|"orchestrates"| node_report_service
node_agent_service -->|"reads/writes"| node_db
node_report_service -->|"reads/writes"| node_db
node_report_service -->|"uses"| node_crypto
node_report_service -->|"uses"| node_gemini_service
node_report_service -->|"uses"| node_email_service
node_scheduler_service -->|"triggers"| node_report_service
node_models -->|"maps"| node_db
node_migrations -->|"creates schema"| node_db

click node_main "https://github.com/rez3x/bsdy_api/blob/main/src/main.rs"
click node_config "https://github.com/rez3x/bsdy_api/blob/main/src/config.rs"
click node_state "https://github.com/rez3x/bsdy_api/blob/main/src/state.rs"
click node_router "https://github.com/rez3x/bsdy_api/blob/main/src/routes/mod.rs"
click node_middleware_auth "https://github.com/rez3x/bsdy_api/blob/main/src/middleware/auth.rs"
click node_middleware_key "https://github.com/rez3x/bsdy_api/blob/main/src/middleware/api_key.rs"
click node_middleware_log "https://github.com/rez3x/bsdy_api/blob/main/src/middleware/activity_log.rs"
click node_auth_routes "https://github.com/rez3x/bsdy_api/blob/main/src/routes/auth.rs"
click node_onboarding_routes "https://github.com/rez3x/bsdy_api/blob/main/src/routes/onboarding.rs"
click node_core_routes "https://github.com/rez3x/bsdy_api/blob/main/src/routes/mood.rs"
click node_content_routes "https://github.com/rez3x/bsdy_api/blob/main/src/routes/content.rs"
click node_ops_routes "https://github.com/rez3x/bsdy_api/blob/main/src/routes/health.rs"
click node_auth_service "https://github.com/rez3x/bsdy_api/blob/main/src/services/auth_service.rs"
click node_chat_service "https://github.com/rez3x/bsdy_api/blob/main/src/services/chat_service.rs"
click node_agent_service "https://github.com/rez3x/bsdy_api/blob/main/src/services/agent_service.rs"
click node_report_service "https://github.com/rez3x/bsdy_api/blob/main/src/services/report_service.rs"
click node_scheduler_service "https://github.com/rez3x/bsdy_api/blob/main/src/services/scheduler_service.rs"
click node_db "https://github.com/rez3x/bsdy_api/blob/main/src/db.rs"
click node_crypto "https://github.com/rez3x/bsdy_api/blob/main/src/crypto.rs"
click node_models "https://github.com/rez3x/bsdy_api/blob/main/src/models/mod.rs"
click node_migrations "https://github.com/rez3x/bsdy_api/blob/main/migrations/001_initial_schema.sql"
click node_email_service "https://github.com/rez3x/bsdy_api/blob/main/src/services/email_service.rs"
click node_gemini_service "https://github.com/rez3x/bsdy_api/blob/main/src/services/gemini_service.rs"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_main,node_config,node_state toneBlue
class node_router,node_middleware_auth,node_middleware_key,node_middleware_log,node_auth_routes,node_onboarding_routes,node_core_routes,node_content_routes,node_ops_routes toneAmber
class node_auth_service,node_chat_service,node_agent_service,node_report_service,node_scheduler_service toneMint
class node_db,node_crypto,node_models,node_migrations toneRose
class node_email_service,node_gemini_service toneIndigo
```

## Components

### Runtime

Bootstrapping, config, and shared application state

- [Main](https://github.com/rez3x/bsdy_api/blob/main/src/main.rs): composition root · Loads config, builds state, starts scheduler, and serves Axum · `src/main.rs`
- [Config](https://github.com/rez3x/bsdy_api/blob/main/src/config.rs): runtime config · Environment-driven application settings · `src/config.rs`
- [State](https://github.com/rez3x/bsdy_api/blob/main/src/state.rs): shared deps · Central runtime state passed to handlers and services · `src/state.rs`

### HTTP API

Router, middleware, and route groups

- [Router](https://github.com/rez3x/bsdy_api/blob/main/src/routes/mod.rs): api router · Assembles the public HTTP surface and static uploads · `src/routes/mod.rs`
- [Auth guard](https://github.com/rez3x/bsdy_api/blob/main/src/middleware/auth.rs): request auth · Tiered user extractors and authorization gating · `src/middleware/auth.rs`
- [API key](https://github.com/rez3x/bsdy_api/blob/main/src/middleware/api_key.rs): external gate · Enforces external-mode API key access · `src/middleware/api_key.rs`
- [Audit log](https://github.com/rez3x/bsdy_api/blob/main/src/middleware/activity_log.rs): request logging · Helpers for auth, activity, and admin audit events · `src/middleware/activity_log.rs`
- [Auth routes](https://github.com/rez3x/bsdy_api/blob/main/src/routes/auth.rs): route group · Login, tokens, verification, and profile flows · `src/routes/auth.rs`
- [Onboarding](https://github.com/rez3x/bsdy_api/blob/main/src/routes/onboarding.rs): route group · User setup and completion endpoints · `src/routes/onboarding.rs`
- [Core routes](https://github.com/rez3x/bsdy_api/blob/main/src/routes/mood.rs): route group · Mood, notes, chats, analytics, and reports endpoints · `src/routes/mood.rs`
- [Content](https://github.com/rez3x/bsdy_api/blob/main/src/routes/content.rs): route group · Content and uploaded asset endpoints · `src/routes/content.rs`
- [Ops routes](https://github.com/rez3x/bsdy_api/blob/main/src/routes/health.rs): route group · Health, docs, dev, and log endpoints · `src/routes/health.rs`

### Domain

Business services and supporting execution flows

- [Auth svc](https://github.com/rez3x/bsdy_api/blob/main/src/services/auth_service.rs): identity workflow · OAuth exchange, JWTs, verification, and profile updates · `src/services/auth_service.rs`
- [Chat svc](https://github.com/rez3x/bsdy_api/blob/main/src/services/chat_service.rs): conversation workflow · Chat storage, retrieval, and AI-assisted responses · `src/services/chat_service.rs`
- [Agent svc](https://github.com/rez3x/bsdy_api/blob/main/src/services/agent_service.rs): tool orchestration · Agentic tool execution over internal data and actions · `src/services/agent_service.rs`
- [Reports](https://github.com/rez3x/bsdy_api/blob/main/src/services/report_service.rs): report workflow · Generates scheduled and on-demand reports · `src/services/report_service.rs`
- [Scheduler](https://github.com/rez3x/bsdy_api/blob/main/src/services/scheduler_service.rs): background jobs · Starts recurring report jobs at boot · `src/services/scheduler_service.rs`

### Data

Models, database, migrations, and cryptography

- [Database](https://github.com/rez3x/bsdy_api/blob/main/src/db.rs): sqlx pool · MySQL/MariaDB access and migrations boundary · `src/db.rs`
- [Crypto](https://github.com/rez3x/bsdy_api/blob/main/src/crypto.rs): aes-gcm · Per-user encryption and decryption for sensitive fields · `src/crypto.rs`
- [Models](https://github.com/rez3x/bsdy_api/blob/main/src/models/mod.rs): domain records · Persistent user, mood, chat, note, content, and log types · `src/models/mod.rs`
- [Migrations](https://github.com/rez3x/bsdy_api/blob/main/migrations/001_initial_schema.sql): schema sql · SQL schema and admin feature migrations · `migrations/001_initial_schema.sql`

### External

Third-party providers and outbound integrations

- [Email svc](https://github.com/rez3x/bsdy_api/blob/main/src/services/email_service.rs): smtp delivery · Verification and report email delivery · `src/services/email_service.rs`
- [Gemini svc](https://github.com/rez3x/bsdy_api/blob/main/src/services/gemini_service.rs): ai provider · LLM-backed chat, analytics, reports, and tools · `src/services/gemini_service.rs`

## Connections

- Main → Config: loads · Reads runtime configuration at startup
- Main → State: builds · Constructs shared application state
- Main → Database: initializes · Creates pool and runs migrations
- Main → Scheduler: starts · Launches recurring background jobs
- Main → Router: serves · Mounts HTTP router for requests
- Router → Auth guard: uses · Applies staged auth extraction
- Router → API key: uses · Protects external-mode routes
- Router → Audit log: uses · Writes request and audit events
- Router → Auth routes: mounts · Exposes authentication endpoints
- Router → Onboarding: mounts · Exposes onboarding endpoints
- Router → Core routes: mounts · Exposes core user workflows
- Router → Content: mounts · Exposes content and uploads
- Router → Ops routes: mounts · Exposes health, docs, dev, and logs
- Auth routes → Auth svc: delegates · Handles login and account management through service layer
- Onboarding → State: reads · Uses shared dependencies for setup flow
- Core routes → Chat svc: delegates · Routes chat operations to service logic
- Core routes → Reports: delegates · Routes report generation to service logic
- Core routes → Agent svc: delegates · Routes agentic tool execution through orchestration layer
- Content → State: reads · Uses shared state for file/content operations
- Ops routes → Database: checks · Health and diagnostics inspect dependency status
- Auth svc → Database: reads/writes · Persists users, tokens, and verification state
- Auth svc → Crypto: uses · Encrypts sensitive user data
- Auth svc → Email svc: uses · Sends verification emails
- Auth svc → Gemini svc: uses · Shares state with AI-backed flows where needed
- Chat svc → Database: reads/writes · Stores and retrieves chat data
- Chat svc → Crypto: uses · Encrypts message content
- Chat svc → Gemini svc: uses · Generates AI responses
- Agent svc → Chat svc: orchestrates · Reuses chat workflows for conversational actions
- Agent svc → Reports: orchestrates · Can generate reports from tool calls
- Agent svc → Database: reads/writes · Executes tool actions over persisted data
- Reports → Database: reads/writes · Reads inputs and stores generated reports
- Reports → Crypto: uses · Encrypts report content
- Reports → Gemini svc: uses · Generates summaries and reports
- Reports → Email svc: uses · Delivers report emails
- Scheduler → Reports: triggers · Runs weekly, monthly, and yearly jobs
- Models → Database: maps · Defines persisted domain records
- Migrations → Database: creates schema · Defines database structure and admin tables
