Skip to content

Commit

Permalink
Merge pull request #15 from DioCrafts/feature/frontend-helm-chart
Browse files Browse the repository at this point in the history
fix frontend
  • Loading branch information
DioCrafts authored Nov 18, 2024
2 parents 15fcd94 + 2afc0d6 commit 0962046
Show file tree
Hide file tree
Showing 13 changed files with 165 additions and 26 deletions.
16 changes: 16 additions & 0 deletions api-gateway/backend/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions api-gateway/backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ path = "src/main.rs"
[dependencies]
# Actix dependencies for web server and web GUI
actix-web = "4.9.0"
actix-cors = "0.7.0"
actix-rt = "2.10.0"
actix-files = "0.6.6"
actix-service = "2.0.2"
Expand Down
11 changes: 11 additions & 0 deletions api-gateway/backend/src/rest/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,14 @@ pub async fn delete_backend(path: web::Path<u32>) -> impl Responder {
println!("Deleting backend with ID: {}", id);
HttpResponse::Ok().json(json!({ "message": "Backend deleted", "id": id }))
}

/// Handler for `GET /api/alerts`
///
/// Returns a list of alerts (mocked example data for now).
pub async fn get_alerts() -> impl Responder {
let alerts = json!([
{ "id": 1, "message": "High latency detected" },
{ "id": 2, "message": "Backend unreachable" }
]);
HttpResponse::Ok().json(alerts)
}
12 changes: 10 additions & 2 deletions api-gateway/backend/src/rest/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//! This module handles all REST endpoints for the backend, exposing data
//! for the frontend and other clients.
use actix_cors::Cors;
use actix_web::{App, HttpServer};
use crate::rest::routes::configure_routes;

Expand All @@ -16,9 +17,16 @@ use crate::rest::routes::configure_routes;
pub async fn start_rest_server(port: u16) -> std::io::Result<()> {
println!("Starting REST server on port {}", port);

HttpServer::new(|| {
HttpServer::new(move || {
// Configura el middleware CORS dentro del closure
let cors = Cors::default()
.allow_any_origin() // Permite cualquier origen; cambia esto en producción
.allow_any_header()
.allow_any_method();

App::new()
.configure(configure_routes) // Register routes
.wrap(cors) // Aplica CORS al App
.configure(configure_routes) // Registra las rutas
})
.bind(("0.0.0.0", port))?
.run()
Expand Down
2 changes: 2 additions & 0 deletions api-gateway/backend/src/rest/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ pub fn configure_routes(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/api")
.route("/metrics", web::get().to(handlers::get_metrics)) // GET /api/metrics
.route("/alerts", web::get().to(handlers::get_alerts)) // GET /api/alerts
.route("/backends", web::get().to(handlers::get_backends)) // GET /api/backends
.route("/backends", web::post().to(handlers::add_backend)) // POST /api/backends
.route("/backends/{id}", web::delete().to(handlers::delete_backend)), // DELETE /api/backends/{id}
);
}

21 changes: 20 additions & 1 deletion api-gateway/frontend/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,13 +1,32 @@
# Etapa 1: Construcción de los archivos estáticos
FROM node:18-alpine AS builder

# Establece el directorio de trabajo
WORKDIR /app

# Copia los archivos necesarios para instalar las dependencias
COPY package.json package-lock.json ./

# Instala las dependencias del proyecto
RUN npm install

# Copia el código fuente al contenedor
COPY . .

# Construye los archivos estáticos con Vite
RUN npm run build

# Etapa 2: Servidor Nginx para los archivos estáticos
# Etapa 2: Servidor Nginx para servir los archivos estáticos
FROM nginx:stable-alpine

# Copia los archivos estáticos generados a la carpeta predeterminada de Nginx
COPY --from=builder /app/dist /usr/share/nginx/html

# Copia la configuración personalizada de Nginx (si existe)
COPY nginx.conf /etc/nginx/conf.d/default.conf

# Expone el puerto 80 para el tráfico HTTP
EXPOSE 80

# Inicia Nginx en modo foreground
CMD ["nginx", "-g", "daemon off;"]
20 changes: 20 additions & 0 deletions api-gateway/frontend/nginx.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
server {
listen 80;

# Sirve los archivos estáticos del frontend
location / {
root /usr/share/nginx/html; # Ruta donde están los archivos generados (dist/)
index index.html;
try_files $uri /index.html; # Asegura que las rutas SPA funcionen
}

# Proxy para las llamadas a la API
location /api/ {
proxy_pass http://flusso-api-gateway-api-gateway.default.svc.cluster.local:8081;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
37 changes: 28 additions & 9 deletions api-gateway/frontend/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,47 @@
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom';
import { AppBar, Toolbar, Button, Typography } from '@mui/material';
import Dashboard from './components/Dashboard';
import Gateways from './components/Gateways';
import Security from './components/Security';
import Observability from './components/Observability';
import Backends from './components/Backends';
import './App.css'; // Opcional: agrega estilos globales o themes

const App: React.FC = () => {
return (
<Router>
<div>
{/* Encabezado opcional: un Navbar o Sidebar */}
<header>
<h1>API Gateway GUI</h1>
</header>
{/* Navbar */}
<AppBar position="static">
<Toolbar>
<Typography variant="h6" sx={{ flexGrow: 1 }}>
API Gateway GUI
</Typography>
<Button color="inherit" component={Link} to="/">
Dashboard
</Button>
<Button color="inherit" component={Link} to="/backends">
Backends
</Button>
<Button color="inherit" component={Link} to="/gateways">
Gateways
</Button>
<Button color="inherit" component={Link} to="/observability">
Observability
</Button>
<Button color="inherit" component={Link} to="/security">
Security
</Button>
</Toolbar>
</AppBar>

{/* Definición de rutas */}
{/* Rutas */}
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/backends" element={<Backends />} />
<Route path="/gateways" element={<Gateways />} />
<Route path="/security" element={<Security />} />
<Route path="/observability" element={<Observability />} />
<Route path="/backends" element={<Backends />} />
<Route path="/security" element={<Security />} />
</Routes>
</div>
</Router>
Expand Down
4 changes: 1 addition & 3 deletions api-gateway/frontend/src/apiClient.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import axios from 'axios';

// Configura Axios para que apunte al API REST en Kubernetes
const apiClient = axios.create({
baseURL: 'http://flusso-api-gateway-api-gateway.default.svc.cluster.local:8081/api', // URL del API REST
baseURL: '/api', // Redirige automáticamente al backend usando el proxy de Vite
});

// Funciones para consumir la API REST
export const getMetrics = async () => {
const response = await apiClient.get('/metrics');
return response.data;
Expand Down
47 changes: 45 additions & 2 deletions api-gateway/frontend/src/components/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,30 @@ import {
LinearProgress
} from '@mui/material';
import { Line } from 'react-chartjs-2';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
import { getMetrics, getAlerts } from '../apiClient'; // Usa el cliente API

// Define interfaces for types
// Registrar componentes y escalas de Chart.js
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);

// Define interfaces para tipos
interface Metric {
name: string;
value: string | number;
Expand All @@ -39,6 +60,28 @@ const generateChartData = () => ({
],
});

// Opciones del gráfico
const chartOptions = {
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Traffic Over Time',
},
},
scales: {
x: {
type: 'category', // Escala categórica en el eje X
},
y: {
beginAtZero: true, // Empieza en 0 en el eje Y
},
},
};

const Dashboard: React.FC = () => {
const [metrics, setMetrics] = useState<Metric[]>([]);
const [alerts, setAlerts] = useState<Alert[]>([]);
Expand Down Expand Up @@ -145,7 +188,7 @@ const Dashboard: React.FC = () => {
<Typography variant="h5" gutterBottom>
Traffic Over Time
</Typography>
<Line data={generateChartData()} />
<Line data={generateChartData()} options={chartOptions} />
</CardContent>
</Card>
</Grid>
Expand Down
16 changes: 9 additions & 7 deletions api-gateway/frontend/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';


export default defineConfig({
root: './', // Adjust this path to point to where your `index.html` is located
root: './',
plugins: [react()],
server: {
host: true, // Permite conexiones externas
port: 5173, // Cambia si hay conflictos de puertos
open: true, // Abre el navegador automáticamente
host: true,
port: 8080,
open: true,
proxy: {
'/api': 'http://flusso-api-gateway-api-gateway.default.svc.cluster.local:8081', // Redirige las solicitudes al API REST en Kubernetes
'/api': {
target: 'http://flusso-api-gateway-api-gateway.default.svc.cluster.local:8081', // URL del backend interno
changeOrigin: true,
},
},
},
});
});
2 changes: 1 addition & 1 deletion helm/api-gateway/backend/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ replicaCount: 1

image:
repository: diocrafts/flusso-api-gateway
tag: v0.0.46
tag: v0.0.56
pullPolicy: IfNotPresent

serviceAccount:
Expand Down
2 changes: 1 addition & 1 deletion helm/api-gateway/frontend/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ replicaCount: 1

image:
repository: diocrafts/flusso-api-gateway-gui
tag: v0.0.50
tag: v0.0.64
pullPolicy: IfNotPresent

service:
Expand Down

0 comments on commit 0962046

Please sign in to comment.