# arjyun/ai-water-management architecture

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

- Interactive diagram: https://gitdiagram.com/arjyun/ai-water-management
- Repository: https://github.com/arjyun/ai-water-management

## Overview

WaterAI is a two-tier application with a React/Vite frontend and an Express/MySQL backend. The system is organized around a simulated “water-aware” workload management domain: users authenticate, view operational dashboards, manage workloads, inspect metrics/analytics, and see policy-driven optimization and alerting behavior based on water-usage estimates.

#### High-level architecture

The repository has three main layers:

1. **Frontend UI layer**
   - React single-page app built with Vite.
   - Handles login, navigation, role-aware page access, and data visualization.
   - Talks to the backend through a shared API client that attaches JWTs.

2. **Backend API layer**
   - Node.js + Express server.
   - Exposes feature-oriented REST routes for auth, workloads, metrics, analytics, optimization, policies, alerts, reports, and admin functions.
   - Enforces authentication and role-based authorization.
   - Applies domain logic such as workload state transitions and policy checks.

3. **Persistence layer**
   - MySQL database.
   - Schema is defined in SQL files under `database/` and `backend/`.
   - Seed script populates realistic simulated data for workloads and metrics.

#### Frontend subsystem

The frontend is centered in `frontend/src` and is split into:

- **Entry/runtime**
  - `main.jsx` and `App.jsx` bootstrap the app.
  - `App.css` and `index.css` define global presentation.

- **API boundary**
  - `src/api/client.js` is the single outbound HTTP client.
  - It likely centralizes the backend base URL and injects JWT auth headers for requests.
  - This is the main boundary between UI state and server state.

- **Auth state**
  - `src/context/AuthContext.jsx` manages session state on the client.
  - It is the frontend’s source of truth for logged-in user identity and role.

- **Reusable UI components**
  - `Navbar.jsx`, `StatCard.jsx`, and `Badges.jsx` are shared presentation components.
  - These appear to support the dashboard and page-level summaries.

- **Feature pages**
  - `Login.jsx`
  - `Dashboard.jsx`
  - `Workloads.jsx`
  - `Metrics.jsx`
  - `Analytics.jsx`
  - `Optimize.jsx`
  - `Policies.jsx`
  - `Alerts.jsx`
  - `Reports.jsx`
  - `Admin.jsx`

The page structure mirrors the backend route structure, which makes the architecture easy to map: each major business capability has a dedicated page and API route.

##### Frontend data flow
1. User logs in on `Login.jsx`.
2. Frontend stores auth/session state in `AuthContext`.
3. `api/client.js` sends authenticated API calls.
4. Pages fetch domain data from the backend and render summaries/charts/tables.
5. Role-based page access is enforced in the UI, matching backend authorization rules.

#### Backend subsystem

The backend is an Express application with a clear separation between infrastructure, middleware, route handlers, and domain utilities.

- **Entry point**
  - `server.js` starts the API server and wires the route modules together.

- **Database connection**
  - `config/db.js` defines the MySQL connection pool/configuration.
  - This is the backend’s persistence boundary.

- **Authentication and authorization**
  - `middleware/auth.js` verifies JWTs.
  - `middleware/role.js` enforces role-based access control.
  - The README shows four roles: Admin, DevOps Engineer, Sustainability Officer, and Viewer.

- **Route modules**
  - `routes/auth.js` handles login and auth-related operations.
  - `routes/workloads.js` manages workload lifecycle/state transitions.
  - `routes/metrics.js` exposes operational metrics.
  - `routes/analytics.js` provides aggregated analysis.
  - `routes/optimize.js` handles optimization actions or recommendations.
  - `routes/policies.js` exposes policy definitions and thresholds.
  - `routes/alerts.js` handles alert creation and retrieval.
  - `routes/reports.js` serves reporting endpoints.
  - `routes/admin.js` covers privileged administrative operations.

- **Domain utility**
  - `utils/waterCalculator.js` encapsulates water-usage estimation logic.
  - This is a key domain service because the system’s core business rule is based on simulated water usage per workload and region.

##### Backend data flow
1. Client sends a request with a JWT.
2. `auth` middleware validates identity.
3. `role` middleware checks access to the specific route.
4. Route handler queries MySQL via the DB pool.
5. Domain logic, including water estimation and policy checks, is applied.
6. Response is returned to the frontend as JSON.

#### Core domain model

The project is built around a water-usage simulation for AI workloads.

The README describes the baseline as Google WUE figures by region. The system uses that baseline to estimate water consumption for different workload types and regions, then drives policy and alert behavior from those estimates.

Key domain concepts visible in the repo:

- **Workloads**
  - Have lifecycle states.
  - Progress through a state machine such as Submitted, Queued, Executing, Completed, Failed, PausedForOptimization, Deferred, and Aborted.
  - Can be retried or redirected based on state rules.

- **Policies**
  - Define region thresholds or limits.
  - Are checked when workloads enter execution.
  - Can cause a workload to be paused for optimization.

- **Alerts**
  - Created when estimated usage violates policy thresholds or other operational conditions.

- **Metrics and analytics**
  - Provide historical and aggregated views over workload/resource behavior.
  - Likely derive from stored workload activity and seeded historical data.

- **Reports**
  - Package the above data into report-oriented output for approved roles.

#### Important workflow boundary: workload state machine

The repository explicitly defines a workload lifecycle:

Submitted → Queued → Executing → Completed  
Executing can also lead to Failed, PausedForOptimization, or Deferred.

There are also retry and recovery behaviors:
- Failed workloads may retry while retry count is below 3.
- After too many retries, they become Aborted.
- PausedForOptimization and Deferred both can move back to Queued.

This state machine is a major architectural boundary because it is where operational control, policy enforcement, and alert generation intersect.

A key business rule occurs when a workload transitions to Executing:
- the system evaluates water policy thresholds;
- if estimated usage exceeds the region threshold, the workload is paused for optimization;
- an alert is created.

That means workload execution is not just a status change; it is also the trigger point for compliance and optimization logic.

#### Persistence and initialization

The database is set up separately from the app:

- `database/schema.sql` is the install-time schema source mentioned in the README.
- `backend/schema.sql` also exists, suggesting a backend-local schema copy or alternate version.
- `backend/seed.js` populates realistic demo data, including workload and metric history.

This means the app is designed for a local MySQL-backed demo environment with seeded data rather than an external managed database service.

#### Testing and quality boundaries

There are tests on both sides of the stack:

- **Backend**
  - `tests/unit/policies.test.js`
  - `tests/integration/workloads.test.js`

- **Frontend**
  - `src/tests/Dashboard.test.jsx`
  - Cypress end-to-end test at `cypress/e2e/workflow.cy.js`

This indicates the project validates:
- business rules in isolation,
- HTTP/API behavior for workload flows,
- and at least one end-to-end user workflow through the UI.

#### Role-based access model

The architecture is strongly role-driven. The README’s access matrix shows that the backend and frontend both care about role restrictions. The main roles are:

- Admin: full access
- DevOps Engineer: operational pages like workloads, metrics, optimize, reports
- Sustainability Officer: policies, reports, dashboard, metrics
- Viewer: limited to dashboard and some analytics visibility

This implies two enforcement layers:
- client-side navigation/page gating for user experience,
- server-side middleware enforcement for actual security.

#### How to draw the architecture

A useful diagram for this repository would show:

- A **browser/frontend boundary** containing:
  - auth context,
  - API client,
  - page components,
  - shared UI components.

- A **backend API boundary** containing:
  - Express server,
  - JWT auth middleware,
  - role middleware,
  - route modules,
  - water calculation utility.

- A **database boundary** containing:
  - MySQL schema,
  - seeded workload/metric data.

- A **domain flow** centered on workloads:
  - login → authenticated API calls → workload lifecycle → policy evaluation → alerts/optimization → metrics/analytics/reports.

The most important architectural idea is that the application is not just a dashboard; it is a policy-aware workload simulation system where workload execution, water-usage estimation, and compliance actions are tightly connected.

Main entry points: [`backend/server.js`](https://github.com/arjyun/ai-water-management/blob/main/backend/server.js) (API server), [`frontend/src/App.jsx`](https://github.com/arjyun/ai-water-management/blob/main/frontend/src/App.jsx) (App), [`backend/routes/workloads.js`](https://github.com/arjyun/ai-water-management/blob/main/backend/routes/workloads.js) (Workloads), [`backend/config/db.js`](https://github.com/arjyun/ai-water-management/blob/main/backend/config/db.js) (DB config)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_frontend["Frontend"]
  node_frontend_boot["App shell<br/>react entry<br/>[main.jsx]"]
  node_frontend_app["App<br/>ui container<br/>[App.jsx]"]
  node_frontend_auth(("Auth state<br/>client session<br/>[AuthContext.jsx]"))
  node_frontend_api["API client<br/>http boundary<br/>[client.js]"]
  node_frontend_nav["Shared UI<br/>components<br/>[Navbar.jsx]"]
  node_frontend_login["Login<br/>page<br/>[Login.jsx]"]
  node_frontend_workflows["Ops pages<br/>[Workloads.jsx]"]
  node_frontend_dashboard["Dashboard<br/>page<br/>[Dashboard.jsx]"]
end

subgraph group_backend["Backend"]
  node_backend_server["API server<br/>express entry<br/>[server.js]"]
  node_backend_db[("DB config<br/>mysql pool<br/>[db.js]")]
  node_backend_authmw{{"JWT auth<br/>middleware<br/>[auth.js]"}}
  node_backend_rolemw{{"Role check<br/>middleware<br/>[role.js]"}}
  node_backend_workloads["Workloads<br/>route<br/>[workloads.js]"]
  node_backend_policies["Policies<br/>route<br/>[policies.js]"]
  node_backend_alerts["Alerts<br/>route<br/>[alerts.js]"]
  node_backend_metrics["Metrics<br/>route<br/>[metrics.js]"]
  node_backend_analytics["Analytics<br/>route<br/>[analytics.js]"]
  node_backend_optimize["Optimize<br/>route<br/>[optimize.js]"]
  node_backend_reports["Reports<br/>route<br/>[reports.js]"]
  node_backend_admin["Admin<br/>route<br/>[admin.js]"]
  node_backend_water{{"Water calc<br/>domain service<br/>[waterCalculator.js]"}}
end

subgraph group_data["Persistence"]
  node_data_schema[("Schema<br/>[schema.sql]")]
  node_data_seed["Seed data<br/>demo data<br/>[seed.js]"]
end

subgraph group_tests["Tests"]
  node_tests_ui["UI test<br/>frontend test<br/>[Dashboard.test.jsx]"]
  node_tests_api["Workload test<br/>integration test<br/>[workloads.test.js]"]
  node_tests_policy["Policy test<br/>unit test<br/>[policies.test.js]"]
  node_tests_e2e["E2E flow<br/>cypress test<br/>[workflow.cy.js]"]
end

node_frontend_boot -->|"mounts"| node_frontend_app
node_frontend_app -->|"reads session"| node_frontend_auth
node_frontend_app -->|"calls API"| node_frontend_api
node_frontend_app -->|"renders"| node_frontend_nav
node_frontend_app -->|"shows"| node_frontend_login
node_frontend_app -->|"shows"| node_frontend_dashboard
node_frontend_app -->|"shows"| node_frontend_workflows
node_frontend_workflows -->|"fetches"| node_frontend_api
node_frontend_login -->|"sets session"| node_frontend_auth
node_frontend_api -->|"requests"| node_backend_server
node_backend_server -->|"uses"| node_backend_authmw
node_backend_server -->|"uses"| node_backend_rolemw
node_backend_server -->|"mounts"| node_backend_workloads
node_backend_server -->|"mounts"| node_backend_policies
node_backend_server -->|"mounts"| node_backend_alerts
node_backend_server -->|"mounts"| node_backend_metrics
node_backend_server -->|"mounts"| node_backend_analytics
node_backend_server -->|"mounts"| node_backend_optimize
node_backend_server -->|"mounts"| node_backend_reports
node_backend_server -->|"mounts"| node_backend_admin
node_backend_workloads -->|"estimates"| node_backend_water
node_backend_workloads -->|"checks"| node_backend_policies
node_backend_workloads -->|"creates"| node_backend_alerts
node_backend_workloads -->|"queries"| node_backend_db
node_backend_metrics -->|"queries"| node_backend_db
node_backend_analytics -->|"aggregates"| node_backend_db
node_backend_optimize -->|"recommends"| node_backend_water
node_backend_reports -->|"reads"| node_backend_db
node_backend_admin -->|"administers"| node_backend_db
node_backend_db -->|"defined by"| node_data_schema
node_data_schema -->|"initialized by"| node_data_seed
node_tests_ui -.->|"covers"| node_frontend_dashboard
node_tests_api -.->|"covers"| node_backend_workloads
node_tests_policy -.->|"covers"| node_backend_policies
node_tests_e2e -.->|"covers"| node_frontend_app

click node_frontend_boot "https://github.com/arjyun/ai-water-management/blob/main/frontend/src/main.jsx"
click node_frontend_app "https://github.com/arjyun/ai-water-management/blob/main/frontend/src/App.jsx"
click node_frontend_auth "https://github.com/arjyun/ai-water-management/blob/main/frontend/src/context/AuthContext.jsx"
click node_frontend_api "https://github.com/arjyun/ai-water-management/blob/main/frontend/src/api/client.js"
click node_frontend_nav "https://github.com/arjyun/ai-water-management/blob/main/frontend/src/components/Navbar.jsx"
click node_frontend_login "https://github.com/arjyun/ai-water-management/blob/main/frontend/src/pages/Login.jsx"
click node_frontend_workflows "https://github.com/arjyun/ai-water-management/blob/main/frontend/src/pages/Workloads.jsx"
click node_frontend_dashboard "https://github.com/arjyun/ai-water-management/blob/main/frontend/src/pages/Dashboard.jsx"
click node_backend_server "https://github.com/arjyun/ai-water-management/blob/main/backend/server.js"
click node_backend_db "https://github.com/arjyun/ai-water-management/blob/main/backend/config/db.js"
click node_backend_authmw "https://github.com/arjyun/ai-water-management/blob/main/backend/middleware/auth.js"
click node_backend_rolemw "https://github.com/arjyun/ai-water-management/blob/main/backend/middleware/role.js"
click node_backend_workloads "https://github.com/arjyun/ai-water-management/blob/main/backend/routes/workloads.js"
click node_backend_policies "https://github.com/arjyun/ai-water-management/blob/main/backend/routes/policies.js"
click node_backend_alerts "https://github.com/arjyun/ai-water-management/blob/main/backend/routes/alerts.js"
click node_backend_metrics "https://github.com/arjyun/ai-water-management/blob/main/backend/routes/metrics.js"
click node_backend_analytics "https://github.com/arjyun/ai-water-management/blob/main/backend/routes/analytics.js"
click node_backend_optimize "https://github.com/arjyun/ai-water-management/blob/main/backend/routes/optimize.js"
click node_backend_reports "https://github.com/arjyun/ai-water-management/blob/main/backend/routes/reports.js"
click node_backend_admin "https://github.com/arjyun/ai-water-management/blob/main/backend/routes/admin.js"
click node_backend_water "https://github.com/arjyun/ai-water-management/blob/main/backend/utils/waterCalculator.js"
click node_data_schema "https://github.com/arjyun/ai-water-management/blob/main/database/schema.sql"
click node_data_seed "https://github.com/arjyun/ai-water-management/blob/main/backend/seed.js"
click node_tests_ui "https://github.com/arjyun/ai-water-management/blob/main/frontend/src/tests/Dashboard.test.jsx"
click node_tests_api "https://github.com/arjyun/ai-water-management/blob/main/backend/tests/integration/workloads.test.js"
click node_tests_policy "https://github.com/arjyun/ai-water-management/blob/main/backend/tests/unit/policies.test.js"
click node_tests_e2e "https://github.com/arjyun/ai-water-management/blob/main/frontend/cypress/e2e/workflow.cy.js"

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_frontend_boot,node_frontend_app,node_frontend_auth,node_frontend_api,node_frontend_nav,node_frontend_login,node_frontend_workflows,node_frontend_dashboard toneBlue
class node_backend_server,node_backend_db,node_backend_authmw,node_backend_rolemw,node_backend_workloads,node_backend_policies,node_backend_alerts,node_backend_metrics,node_backend_analytics,node_backend_optimize,node_backend_reports,node_backend_admin,node_backend_water toneAmber
class node_data_schema,node_data_seed toneMint
class node_tests_ui,node_tests_api,node_tests_policy,node_tests_e2e toneRose
```

## Components

### Frontend

React/Vite single-page UI and client state

- [App shell](https://github.com/arjyun/ai-water-management/blob/main/frontend/src/main.jsx): react entry · Bootstraps the Vite app and global styling · `frontend/src/main.jsx`
- [App](https://github.com/arjyun/ai-water-management/blob/main/frontend/src/App.jsx): ui container · Top-level routing and page composition · `frontend/src/App.jsx`
- [Auth state](https://github.com/arjyun/ai-water-management/blob/main/frontend/src/context/AuthContext.jsx): client session · Holds login identity and role state · `frontend/src/context/AuthContext.jsx`
- [API client](https://github.com/arjyun/ai-water-management/blob/main/frontend/src/api/client.js): http boundary · Shared authenticated client for backend requests · `frontend/src/api/client.js`
- [Shared UI](https://github.com/arjyun/ai-water-management/blob/main/frontend/src/components/Navbar.jsx): components · Reusable navigation and dashboard display widgets · `frontend/src/components/Navbar.jsx`
- [Login](https://github.com/arjyun/ai-water-management/blob/main/frontend/src/pages/Login.jsx): page · User authentication entry page · `frontend/src/pages/Login.jsx`
- [Ops pages](https://github.com/arjyun/ai-water-management/blob/main/frontend/src/pages/Workloads.jsx): pages · Workloads, metrics, analytics, optimize, policies, alerts, reports, admin · `frontend/src/pages/Workloads.jsx`
- [Dashboard](https://github.com/arjyun/ai-water-management/blob/main/frontend/src/pages/Dashboard.jsx): page · Operational summary and status overview · `frontend/src/pages/Dashboard.jsx`

### Backend

Express API, middleware, routes, and domain logic

- [API server](https://github.com/arjyun/ai-water-management/blob/main/backend/server.js): express entry · Starts the server and wires route modules · `backend/server.js`
- [DB config](https://github.com/arjyun/ai-water-management/blob/main/backend/config/db.js): mysql pool · MySQL connection boundary · `backend/config/db.js`
- [JWT auth](https://github.com/arjyun/ai-water-management/blob/main/backend/middleware/auth.js): middleware · Validates access tokens · `backend/middleware/auth.js`
- [Role check](https://github.com/arjyun/ai-water-management/blob/main/backend/middleware/role.js): middleware · Enforces role-based authorization · `backend/middleware/role.js`
- [Workloads](https://github.com/arjyun/ai-water-management/blob/main/backend/routes/workloads.js): route · Workload lifecycle and state transitions · `backend/routes/workloads.js`
- [Policies](https://github.com/arjyun/ai-water-management/blob/main/backend/routes/policies.js): route · Policy thresholds and enforcement rules · `backend/routes/policies.js`
- [Alerts](https://github.com/arjyun/ai-water-management/blob/main/backend/routes/alerts.js): route · Alert creation and retrieval · `backend/routes/alerts.js`
- [Metrics](https://github.com/arjyun/ai-water-management/blob/main/backend/routes/metrics.js): route · Operational metrics endpoints · `backend/routes/metrics.js`
- [Analytics](https://github.com/arjyun/ai-water-management/blob/main/backend/routes/analytics.js): route · Aggregated analysis endpoints · `backend/routes/analytics.js`
- [Optimize](https://github.com/arjyun/ai-water-management/blob/main/backend/routes/optimize.js): route · Optimization actions and recommendations · `backend/routes/optimize.js`
- [Reports](https://github.com/arjyun/ai-water-management/blob/main/backend/routes/reports.js): route · Reporting endpoints for approved roles · `backend/routes/reports.js`
- [Admin](https://github.com/arjyun/ai-water-management/blob/main/backend/routes/admin.js): route · Privileged administrative operations · `backend/routes/admin.js`
- [Water calc](https://github.com/arjyun/ai-water-management/blob/main/backend/utils/waterCalculator.js): domain service · Estimates water usage for workload and region · `backend/utils/waterCalculator.js`

### Persistence

MySQL schema and seeded demo data

- [Schema](https://github.com/arjyun/ai-water-management/blob/main/database/schema.sql): mysql schema · Primary database schema definition · `database/schema.sql`
- [Seed data](https://github.com/arjyun/ai-water-management/blob/main/backend/seed.js): demo data · Populates workloads and metric history · `backend/seed.js`

### Tests

Representative automated checks across UI and API

- [UI test](https://github.com/arjyun/ai-water-management/blob/main/frontend/src/tests/Dashboard.test.jsx): frontend test · Dashboard component coverage · `frontend/src/tests/Dashboard.test.jsx`
- [Workload test](https://github.com/arjyun/ai-water-management/blob/main/backend/tests/integration/workloads.test.js): integration test · Backend workload flow checks · `backend/tests/integration/workloads.test.js`
- [Policy test](https://github.com/arjyun/ai-water-management/blob/main/backend/tests/unit/policies.test.js): unit test · Policy rule validation · `backend/tests/unit/policies.test.js`
- [E2E flow](https://github.com/arjyun/ai-water-management/blob/main/frontend/cypress/e2e/workflow.cy.js): cypress test · End-to-end user workflow · `frontend/cypress/e2e/workflow.cy.js`

## Connections

- App shell → App: mounts · Bootstraps the application shell
- App → Auth state: reads session · Uses auth context for access and identity
- App → API client: calls API · All server requests flow through the shared client
- App → Shared UI: renders · Composes shared navigation and status widgets
- App → Login: shows · Routes unauthenticated users to login
- App → Dashboard: shows · Primary operational overview page
- App → Ops pages: shows · Operational feature pages
- Ops pages → API client: fetches · Pages request backend domain data
- Login → Auth state: sets session · Stores authenticated user state
- API client → API server: requests · Authenticated HTTP boundary to the API
- API server → JWT auth: uses · Validates JWTs before protected routes
- API server → Role check: uses · Applies role-based authorization
- API server → Workloads: mounts · Registers workload route module
- API server → Policies: mounts · Registers policy route module
- API server → Alerts: mounts · Registers alert route module
- API server → Metrics: mounts · Registers metrics route module
- API server → Analytics: mounts · Registers analytics route module
- API server → Optimize: mounts · Registers optimization route module
- API server → Reports: mounts · Registers reports route module
- API server → Admin: mounts · Registers admin route module
- Workloads → Water calc: estimates · Calculates water usage during execution transitions
- Workloads → Policies: checks · Applies policy thresholds to workload state
- Workloads → Alerts: creates · Violations trigger alert generation
- Workloads → DB config: queries · Persists and reads workload state
- Metrics → DB config: queries · Reads operational measurements
- Analytics → DB config: aggregates · Builds higher-level summaries from stored data
- Optimize → Water calc: recommends · Optimization logic uses usage estimates
- Reports → DB config: reads · Compiles report data from persistence
- Admin → DB config: administers · Performs privileged data operations
- DB config → Schema: defined by · Schema source for the MySQL database
- Schema → Seed data: initialized by · Seed script populates demo workload data
- UI test → Dashboard: covers · Exercises dashboard rendering and state
- Workload test → Workloads: covers · Validates workload API behavior
- Policy test → Policies: covers · Checks policy rule logic
- E2E flow → App: covers · Runs a user workflow through the UI
