How rez3x/bsdy_api works
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: mod.rs Router · db.rs Database · report_service.rs Reports · main.rs Main
Components 23
Runtime
Bootstrapping, config, and shared application state
HTTP API
Router, middleware, and route groups
- Router · Assembles the public HTTP surface and static uploads
src/routes/mod.rs - Auth guard · Tiered user extractors and authorization gating
src/middleware/auth.rs - API key · Enforces external-mode API key access
src/middleware/api_key.rs - Audit log · Helpers for auth, activity, and admin audit events
src/middleware/activity_log.rs - Auth routes · Login, tokens, verification, and profile flows
src/routes/auth.rs - Onboarding · User setup and completion endpoints
src/routes/onboarding.rs - Core routes · Mood, notes, chats, analytics, and reports endpoints
src/routes/mood.rs - Content · Content and uploaded asset endpoints
src/routes/content.rs - Ops routes · Health, docs, dev, and log endpoints
src/routes/health.rs
Domain
Business services and supporting execution flows
- Auth svc · OAuth exchange, JWTs, verification, and profile updates
src/services/auth_service.rs - Chat svc · Chat storage, retrieval, and AI-assisted responses
src/services/chat_service.rs - Agent svc · Agentic tool execution over internal data and actions
src/services/agent_service.rs - Reports · Generates scheduled and on-demand reports
src/services/report_service.rs - Scheduler · Starts recurring report jobs at boot
src/services/scheduler_service.rs
Data
Models, database, migrations, and cryptography
- Database · MySQL/MariaDB access and migrations boundary
src/db.rs - Crypto · Per-user encryption and decryption for sensitive fields
src/crypto.rs - Models · Persistent user, mood, chat, note, content, and log types
src/models/mod.rs - Migrations · SQL schema and admin feature migrations
migrations/001_initial_schema.sql
External
Third-party providers and outbound integrations
- Email svc · Verification and report email delivery
src/services/email_service.rs - Gemini svc · LLM-backed chat, analytics, reports, and tools
src/services/gemini_service.rs
Connections 37
- 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