# rez3x/jw_api architecture

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

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

## Overview

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: [`src/routes/mod.rs`](https://github.com/rez3x/jw_api/blob/main/src/routes/mod.rs) (Router), [`src/db.rs`](https://github.com/rez3x/jw_api/blob/main/src/db.rs) (Database), [`src/services/chat_service.rs`](https://github.com/rez3x/jw_api/blob/main/src/services/chat_service.rs) (Chat service), [`src/main.rs`](https://github.com/rez3x/jw_api/blob/main/src/main.rs) (API server)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_core["Core runtime"]
  node_main["API server<br/>axum binary<br/>[main.rs]"]
  node_lib["Library API<br/>crate module<br/>[lib.rs]"]
  node_state["App state<br/>shared deps<br/>[state.rs]"]
  node_config["Config<br/>[config.rs]"]
  node_db[("Database<br/>sqlx pool<br/>[db.rs]")]
  node_crypto{{"Crypto<br/>encryption<br/>[crypto.rs]"}}
  node_middleware_auth["Auth middleware<br/>identity gate<br/>[auth.rs]"]
  node_middleware_api["API key gate<br/>deployment gate<br/>[api_key.rs]"]
  node_middleware_log["Activity log<br/>audit middleware<br/>[activity_log.rs]"]
  node_models["Data models<br/>row/DTO models<br/>[mod.rs]"]
end

subgraph group_api["HTTP surface"]
  node_routes_mod["Router<br/>route wiring<br/>[mod.rs]"]
  node_routes_auth["Auth routes<br/>http routes<br/>[auth.rs]"]
  node_routes_content["Content routes<br/>http routes<br/>[post.rs]"]
  node_routes_department["Dept routes<br/>http routes<br/>[department.rs]"]
  node_routes_chat["Chat routes<br/>http routes<br/>[chat.rs]"]
  node_routes_admin["Admin routes<br/>http routes<br/>[analytics.rs]"]
end

subgraph group_logic["Domain services"]
  node_svc_auth["Auth service<br/>identity logic<br/>[auth_service.rs]"]
  node_svc_content["Content service<br/>civic workflows<br/>[post_service.rs]"]
  node_svc_department["Dept service<br/>gov workflows"]
  node_svc_chat["Chat service<br/>ai chat<br/>[chat_service.rs]"]
  node_svc_agent["Agent service<br/>tool calling<br/>[agent_service.rs]"]
  node_svc_integrations["Integrations<br/>external adapters<br/>[email_service.rs]"]
  node_svc_analytics["Analytics service<br/>aggregation"]
end

subgraph group_ext["External systems"]
  node_mariadb[("MariaDB<br/>relational store")]
  node_oauth["Google OAuth<br/>oauth provider"]
  node_smtp["Brevo SMTP<br/>mail service"]
  node_gemini["Gemini API<br/>llm api"]
  node_uploads[("Uploads<br/>filesystem")]
end

node_main -->|"uses"| node_lib
node_main -->|"initializes"| node_state
node_main -->|"mounts"| node_routes_mod
node_main -->|"starts"| node_db
node_state -->|"loads"| node_config
node_state -->|"contains"| node_db
node_state -->|"contains"| node_crypto
node_routes_mod -->|"guards"| node_middleware_auth
node_routes_mod -->|"optionally gates"| node_middleware_api
node_routes_mod -->|"records"| node_middleware_log
node_routes_mod -->|"mounts"| node_routes_auth
node_routes_mod -->|"mounts"| node_routes_content
node_routes_mod -->|"mounts"| node_routes_department
node_routes_mod -->|"mounts"| node_routes_chat
node_routes_mod -->|"mounts"| node_routes_admin
node_routes_auth -->|"calls"| node_svc_auth
node_routes_content -->|"calls"| node_svc_content
node_routes_department -->|"calls"| node_svc_department
node_routes_chat -->|"calls"| node_svc_chat
node_routes_chat -->|"calls"| node_svc_agent
node_routes_admin -->|"calls"| node_svc_analytics
node_routes_admin -->|"reads"| node_middleware_log
node_svc_auth -->|"uses"| node_oauth
node_svc_auth -->|"uses"| node_smtp
node_svc_auth -->|"persists"| node_db
node_svc_content -->|"persists"| node_db
node_svc_department -->|"persists"| node_db
node_svc_chat -->|"persists"| node_db
node_svc_chat -->|"encrypts"| node_crypto
node_svc_chat -->|"uses"| node_gemini
node_svc_agent -->|"uses"| node_gemini
node_svc_agent -->|"reads"| node_db
node_svc_integrations -->|"uses"| node_smtp
node_svc_integrations -->|"uses"| node_gemini
node_svc_integrations -->|"writes"| node_uploads
node_svc_analytics -->|"reads"| node_db
node_db -->|"connects to"| node_mariadb
node_svc_content -->|"uses"| node_models
node_svc_department -->|"uses"| node_models
node_svc_chat -->|"uses"| node_models
node_svc_analytics -->|"uses"| node_models

click node_main "https://github.com/rez3x/jw_api/blob/main/src/main.rs"
click node_lib "https://github.com/rez3x/jw_api/blob/main/src/lib.rs"
click node_state "https://github.com/rez3x/jw_api/blob/main/src/state.rs"
click node_config "https://github.com/rez3x/jw_api/blob/main/src/config.rs"
click node_db "https://github.com/rez3x/jw_api/blob/main/src/db.rs"
click node_crypto "https://github.com/rez3x/jw_api/blob/main/src/crypto.rs"
click node_middleware_auth "https://github.com/rez3x/jw_api/blob/main/src/middleware/auth.rs"
click node_middleware_api "https://github.com/rez3x/jw_api/blob/main/src/middleware/api_key.rs"
click node_middleware_log "https://github.com/rez3x/jw_api/blob/main/src/middleware/activity_log.rs"
click node_models "https://github.com/rez3x/jw_api/blob/main/src/models/mod.rs"
click node_routes_mod "https://github.com/rez3x/jw_api/blob/main/src/routes/mod.rs"
click node_routes_auth "https://github.com/rez3x/jw_api/blob/main/src/routes/auth.rs"
click node_routes_content "https://github.com/rez3x/jw_api/blob/main/src/routes/post.rs"
click node_routes_department "https://github.com/rez3x/jw_api/blob/main/src/routes/department.rs"
click node_routes_chat "https://github.com/rez3x/jw_api/blob/main/src/routes/chat.rs"
click node_routes_admin "https://github.com/rez3x/jw_api/blob/main/src/routes/analytics.rs"
click node_svc_auth "https://github.com/rez3x/jw_api/blob/main/src/services/auth_service.rs"
click node_svc_content "https://github.com/rez3x/jw_api/blob/main/src/services/post_service.rs"
click node_svc_department "https://github.com/rez3x/jw_api/blob/main/src/services/department_service.rs"
click node_svc_chat "https://github.com/rez3x/jw_api/blob/main/src/services/chat_service.rs"
click node_svc_agent "https://github.com/rez3x/jw_api/blob/main/src/services/agent_service.rs"
click node_svc_integrations "https://github.com/rez3x/jw_api/blob/main/src/services/email_service.rs"
click node_svc_analytics "https://github.com/rez3x/jw_api/blob/main/src/services/analytics_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_lib,node_state,node_config,node_db,node_crypto,node_middleware_auth,node_middleware_api,node_middleware_log,node_models toneBlue
class node_routes_mod,node_routes_auth,node_routes_content,node_routes_department,node_routes_chat,node_routes_admin toneAmber
class node_svc_auth,node_svc_content,node_svc_department,node_svc_chat,node_svc_agent,node_svc_integrations,node_svc_analytics toneMint
class node_mariadb,node_oauth,node_smtp,node_gemini,node_uploads toneRose
```

## Components

### Core runtime

Rust/Axum application wiring, shared state, middleware, persistence, and models.

- [API server](https://github.com/rez3x/jw_api/blob/main/src/main.rs): axum binary · Runtime entrypoint that builds the router, state, CORS, and shutdown behavior. · `src/main.rs`
- [Library API](https://github.com/rez3x/jw_api/blob/main/src/lib.rs): crate module · Reusable module exports used by the binary and tests. · `src/lib.rs`
- [App state](https://github.com/rez3x/jw_api/blob/main/src/state.rs): shared deps · Global dependencies shared across handlers and services. · `src/state.rs`
- [Config](https://github.com/rez3x/jw_api/blob/main/src/config.rs): env config · Environment-driven settings for auth, mail, Gemini, uploads, and runtime mode. · `src/config.rs`
- [Database](https://github.com/rez3x/jw_api/blob/main/src/db.rs): sqlx pool · MariaDB pool and startup migrations. · `src/db.rs`
- [Crypto](https://github.com/rez3x/jw_api/blob/main/src/crypto.rs): encryption · AES-256-GCM + HKDF for encrypted chat payloads. · `src/crypto.rs`
- [Auth middleware](https://github.com/rez3x/jw_api/blob/main/src/middleware/auth.rs): identity gate · Authenticated, verified, government, and dev role extraction/guarding. · `src/middleware/auth.rs`
- [API key gate](https://github.com/rez3x/jw_api/blob/main/src/middleware/api_key.rs): deployment gate · External-mode access control for deployments that require an API key. · `src/middleware/api_key.rs`
- [Activity log](https://github.com/rez3x/jw_api/blob/main/src/middleware/activity_log.rs): audit middleware · Records authenticated activity for auditing and log endpoints. · `src/middleware/activity_log.rs`
- [Data models](https://github.com/rez3x/jw_api/blob/main/src/models/mod.rs): row/DTO models · Relational entities for users, posts, comments, votes, chats, and logs. · `src/models/mod.rs`

### HTTP surface

Route modules organized by domain.

- [Router](https://github.com/rez3x/jw_api/blob/main/src/routes/mod.rs): route wiring · Top-level HTTP route assembly and domain mounting. · `src/routes/mod.rs`
- [Auth routes](https://github.com/rez3x/jw_api/blob/main/src/routes/auth.rs): http routes · Sign-in, callback, verification, and session endpoints. · `src/routes/auth.rs`
- [Content routes](https://github.com/rez3x/jw_api/blob/main/src/routes/post.rs): http routes · Posts, comments, votes, and user-centric civic content endpoints. · `src/routes/post.rs`
- [Dept routes](https://github.com/rez3x/jw_api/blob/main/src/routes/department.rs): http routes · Government workflow and queue/status endpoints. · `src/routes/department.rs`
- [Chat routes](https://github.com/rez3x/jw_api/blob/main/src/routes/chat.rs): http routes · General chat and agentic AI conversation endpoints. · `src/routes/chat.rs`
- [Admin routes](https://github.com/rez3x/jw_api/blob/main/src/routes/analytics.rs): http routes · Analytics, logs, health, and development endpoints. · `src/routes/analytics.rs`

### Domain services

Business logic and integration orchestration.

- [Auth service](https://github.com/rez3x/jw_api/blob/main/src/services/auth_service.rs): identity logic · OAuth sign-in, JWT issuance, and verification email workflows. · `src/services/auth_service.rs`
- [Content service](https://github.com/rez3x/jw_api/blob/main/src/services/post_service.rs): civic workflows · Posts, comments, votes, and user workflow logic. · `src/services/post_service.rs`
- [Dept service](https://github.com/rez3x/jw_api/blob/main/src/services/department_service.rs): gov workflows · Department queues, statuses, and response handling. · `src/services/department_service.rs`
- [Chat service](https://github.com/rez3x/jw_api/blob/main/src/services/chat_service.rs): ai chat · Chat orchestration, message persistence, and response handling. · `src/services/chat_service.rs`
- [Agent service](https://github.com/rez3x/jw_api/blob/main/src/services/agent_service.rs): tool calling · Role-aware tool access for agentic chat over platform data. · `src/services/agent_service.rs`
- [Integrations](https://github.com/rez3x/jw_api/blob/main/src/services/email_service.rs): external adapters · Email, Gemini, and media/file handling services. · `src/services/email_service.rs`
- [Analytics service](https://github.com/rez3x/jw_api/blob/main/src/services/analytics_service.rs): aggregation · Reporting and trend aggregation over civic activity. · `src/services/analytics_service.rs`

### External systems

Databases and third-party/runtime dependencies.

- **MariaDB**: relational store · Primary SQL persistence backend.
- **Google OAuth**: oauth provider · External sign-in identity provider.
- **Brevo SMTP**: mail service · Outbound email delivery for verification and notifications.
- **Gemini API**: llm api · Model calls for chat responses and classification.
- **Uploads**: filesystem · Local file storage exposed for uploaded media.

## Connections

- 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.
