How rez3x/jw_api works
1. Overall shape
- This is a single Rust monolith built with Axum 0.7. It exposes a REST API for civic reporting, department workflows, chat/AI assistance, and admin operations.
- The code is organized in a classic request pipeline: routes → services → database/external systems, with shared cross-cutting concerns in middleware.
2. Entrypoint and application wiring
- src/main.rs is the runtime entrypoint. It wires together CORS, shutdown behavior, the HTTP router, and shared application state.
- src/lib.rs exposes the reusable modules, which is useful because the integration tests exercise the app as a library rather than only via the binary.
3. Shared state and configuration
- src/state.rs holds the app-wide dependencies used by handlers and services, likely including the SQLx pool, config, and clients for external services.
- src/config.rs centralizes environment loading for database, JWT, OAuth, Gemini, SMTP, encryption, app mode, and upload limits. This config is a key boundary because it drives both security and runtime behavior.
4. Persistence layer
- src/db.rs manages the MariaDB connection pool and runs migrations from migrations/001_initial_schema.sql at startup.
- The data model is relational and SQL-first. The models/ directory contains row/DTO types for users, posts, comments, votes, chats, and logs, reflecting the primary database entities.
5. HTTP layer and domain routing
- src/routes/ groups handlers by domain: auth, users, posts, comments, votes, departments, chats, analytics, logs, health, and dev tooling.
- This routing structure matches the product areas in the README and is the main surface for external clients. Most endpoints are CRUD or workflow operations around reports and moderation.
6. Business logic layer
- src/services/ contains the domain logic that sits between HTTP handlers and storage/integrations.
- Notable service boundaries:
- auth_service: Google OAuth, JWT issuance, verification email flow.
- post_service, comment_service, vote_service, user_service: core civic-content workflows.
- department_service: government queue/status/response workflows.
- analytics_service: aggregate reporting and trends.
- chat_service plus agent_service: AI chat orchestration and tool-calling behavior.
- email_service, media_service, gemini_service: external integrations and file handling.
7. Authentication and authorization pipeline
- src/middleware/auth.rs implements layered identity extraction, progressing from general authenticated users to more specific role-checked variants such as verified users, government users, and dev users.
- src/middleware/api_key.rs adds an external-mode gate, which suggests the API can be locked behind an API key in certain deployments.
- Authorization is therefore enforced both structurally in middleware and semantically in the route/service layer, especially for gov-only and dev-only endpoints.
8. Audit and activity logging
- src/middleware/activity_log.rs records authenticated activity, feeding the log models and /api/logs/* endpoints.
- This creates an operational/audit boundary separate from the main business data, which matters for understanding admin observability and traceability of user actions.
9. AI and chat subsystem
- Chat is a distinct subsystem with two modes: general conversation and agentic tool-using chat.
- Messages are encrypted at rest using src/crypto.rs with AES-256-GCM + HKDF, and chat data is decrypted only when read back through chat endpoints.
- The chat stack depends on gemini_service for model calls and agent_service for role-aware tool access to platform data such as posts, stats, and department queues.
10. External integrations
- Google OAuth 2.0 is used for sign-in, and JWT is used for session/auth propagation after callback.
- Brevo SMTP via email_service handles verification and other outbound mail.
- Gemini API powers AI classification and chat responses.
- Uploaded media is stored on the local filesystem and exposed under /uploads/*, so file storage is part of the runtime architecture rather than an external object store.
11. Role-based domain segmentation
- The application distinguishes several actor classes: basic, department-specific government roles, city_major_gov, and dev.
- This role model directly shapes the route surface: public/community features, government dashboard actions, and developer admin/log access are separate bounded areas.
12. Data flow patterns
- Typical request flow is: client request → auth/API-key middleware → route handler → service logic → MariaDB and/or external service → response.
- Special flows include:
- OAuth callback returns JWT and onboarding state.
- Post/comment/vote actions persist relational updates and often feed analytics/logging.
- Chat message submission stores encrypted message content, calls Gemini, then stores the AI response.
- Media uploads are multipart HTTP requests that end in filesystem writes plus DB metadata updates.
13. Testing boundary
- tests/ includes unit-style tests for config, crypto, errors, models, database behavior, and service logic, plus integration tests for routes and live external dependencies.
- The test layout mirrors the architecture: it validates the service boundaries, authentication behavior, and end-to-end route contracts rather than only isolated functions.
14. What to draw in an architecture diagram
- The central node should be the Rust/Axum API server.
- Surround it with MariaDB, local uploads storage, Google OAuth, Brevo SMTP, and Gemini API.
- Inside the server, show distinct bands for middleware, routes, services, models, and shared state/config/crypto/db.
- Emphasize that chat encryption, role-based authorization, and department workflows are key differentiators of this backend, not just generic CRUD endpoints.
Main entry points: mod.rs Router · db.rs Database · chat_service.rs Chat service · main.rs API server
Components 28
Core runtime
Rust/Axum application wiring, shared state, middleware, persistence, and models.
- API server · Runtime entrypoint that builds the router, state, CORS, and shutdown behavior.
src/main.rs - Library API · Reusable module exports used by the binary and tests.
src/lib.rs - App state · Global dependencies shared across handlers and services.
src/state.rs - Config · Environment-driven settings for auth, mail, Gemini, uploads, and runtime mode.
src/config.rs - Database · MariaDB pool and startup migrations.
src/db.rs - Crypto · AES-256-GCM + HKDF for encrypted chat payloads.
src/crypto.rs - Auth middleware · Authenticated, verified, government, and dev role extraction/guarding.
src/middleware/auth.rs - API key gate · External-mode access control for deployments that require an API key.
src/middleware/api_key.rs - Activity log · Records authenticated activity for auditing and log endpoints.
src/middleware/activity_log.rs - Data models · Relational entities for users, posts, comments, votes, chats, and logs.
src/models/mod.rs
HTTP surface
Route modules organized by domain.
- Router · Top-level HTTP route assembly and domain mounting.
src/routes/mod.rs - Auth routes · Sign-in, callback, verification, and session endpoints.
src/routes/auth.rs - Content routes · Posts, comments, votes, and user-centric civic content endpoints.
src/routes/post.rs - Dept routes · Government workflow and queue/status endpoints.
src/routes/department.rs - Chat routes · General chat and agentic AI conversation endpoints.
src/routes/chat.rs - Admin routes · Analytics, logs, health, and development endpoints.
src/routes/analytics.rs
Domain services
Business logic and integration orchestration.
- Auth service · OAuth sign-in, JWT issuance, and verification email workflows.
src/services/auth_service.rs - Content service · Posts, comments, votes, and user workflow logic.
src/services/post_service.rs - Dept service · Department queues, statuses, and response handling.
src/services/department_service.rs - Chat service · Chat orchestration, message persistence, and response handling.
src/services/chat_service.rs - Agent service · Role-aware tool access for agentic chat over platform data.
src/services/agent_service.rs - Integrations · Email, Gemini, and media/file handling services.
src/services/email_service.rs - Analytics service · Reporting and trend aggregation over civic activity.
src/services/analytics_service.rs
External systems
Databases and third-party/runtime dependencies.
- MariaDB · Primary SQL persistence backend.
- Google OAuth · External sign-in identity provider.
- Brevo SMTP · Outbound email delivery for verification and notifications.
- Gemini API · Model calls for chat responses and classification.
- Uploads · Local file storage exposed for uploaded media.
Connections 41
- API server → Library API: uses · Binary builds on shared crate modules.
- API server → App state: initializes · Creates app-wide shared state.
- API server → Router: mounts · Installs the HTTP router.
- API server → Database: starts · Opens the database pool and runs migrations.
- App state → Config: loads · State is configured from environment-driven settings.
- App state → Database: contains · Shares the SQL pool with handlers and services.
- App state → Crypto: contains · Shares encryption helpers for chat data.
- Router → Auth middleware: guards · Routes are protected by role-aware identity checks.
- Router → API key gate: optionally gates · Deployment-specific API key enforcement.
- Router → Activity log: records · Activity logging wraps authenticated requests.
- Router → Auth routes: mounts · Auth endpoint group.
- Router → Content routes: mounts · Public civic content endpoints.
- Router → Dept routes: mounts · Government workflow endpoints.
- Router → Chat routes: mounts · Chat endpoints.
- Router → Admin routes: mounts · Analytics, logs, health, and dev endpoints.
- Auth routes → Auth service: calls · Delegates identity and session logic.
- Content routes → Content service: calls · Delegates content CRUD and voting workflows.
- Dept routes → Dept service: calls · Delegates government queue/workflow logic.
- Chat routes → Chat service: calls · Handles general chat workflows.
- Chat routes → Agent service: calls · Handles agentic tool-using chat.
- Admin routes → Analytics service: calls · Serves reporting and trend data.
- Admin routes → Activity log: reads · Log endpoints surface audit data.
- Auth service → Google OAuth: uses · Google sign-in callback flow.
- Auth service → Brevo SMTP: uses · Sends verification and outbound email.
- Auth service → Database: persists · Stores user/auth records.
- Content service → Database: persists · Stores posts, comments, votes, and user state.
- Dept service → Database: persists · Stores department workflow updates.
- Chat service → Database: persists · Stores encrypted chat records.
- Chat service → Crypto: encrypts · Encrypts/decrypts chat messages at rest.
- Chat service → Gemini API: uses · Calls the model for AI responses.
- Agent service → Gemini API: uses · Uses model calls for agentic behavior.
- Agent service → Database: reads · Tool access to platform data.
- Integrations → Brevo SMTP: uses · Mail delivery integration.
- Integrations → Gemini API: uses · Gemini adapter for AI features.
- Integrations → Uploads: writes · Handles uploaded media on the local filesystem.
- Analytics service → Database: reads · Aggregates activity and trend data.
- Database → MariaDB: connects to · Primary relational backend.
- Content service → Data models: uses · Works with row and DTO types.
- Dept service → Data models: uses · Uses workflow-related entities.
- Chat service → Data models: uses · Uses chat message and conversation models.
- Analytics service → Data models: uses · Uses log and content models for aggregation.