Create mock backend to simulate AI responses for UI development: Backend Implementation: - tools/fake-backend/server.js: Express server with CORS - POST /api/analyze: Accepts log, returns mock AI analysis with 1.5s delay - GET /health: Health check endpoint - Pattern matching for different log types (PostgreSQL, Nginx, Node.js, Disk) - Error handling: 400 for empty payload, 500 for server errors - Mock responses for common errors (OOM, 502, connection refused, disk full) Container Setup: - Dockerfile: Node.js 20 Alpine container - docker-compose.yml: Added fake-backend service on port 3000 - Health checks for both frontend and backend services - Environment variable VITE_API_URL for frontend Frontend Integration: - InteractiveDemo.tsx: Replaced static data with real fetch() calls - API_URL configurable via env var (default: http://localhost:3000) - Error handling with user-friendly messages - Shows backend URL in demo section - Maintains loading states and UI feedback Documentation: - docs/tools_fake_backend.md: Complete usage guide - README.md: Updated with tools/fake-backend structure and usage Development Workflow: 1. docker compose up -d (starts both frontend and backend) 2. Frontend calls http://fake-backend:3000/api/analyze 3. Backend returns realistic mock responses 4. No OpenRouter API costs during development Safety First: - No real API calls during development - Isolated mock logic in dedicated tool - Easy switch to real backend by changing URL - CORS enabled only for development Refs: Sprint 4 preparation, API development workflow
193 lines
3.9 KiB
Markdown
193 lines
3.9 KiB
Markdown
# Fake Backend Tool
|
|
|
|
> **Strumento di sviluppo per simulare risposte API AI**
|
|
>
|
|
> Scopo: Permettere lo sviluppo e il testing del frontend senza dipendere dal backend reale o dalle API di OpenRouter.
|
|
|
|
---
|
|
|
|
## 📋 Descrizione
|
|
|
|
Il `fake-backend` è un server Node.js/Express che simula le risposte dell'API di LogWhisperer AI. È progettato per:
|
|
|
|
- **Sviluppo UI**: Testare l'interfaccia utente con risposte realistiche
|
|
- **Demo offline**: Mostrare il prodotto senza connessione internet
|
|
- **Testing**: Validare il flusso frontend senza costi API
|
|
- **Onboarding**: Permettere ai nuovi sviluppatori di lavorare subito
|
|
|
|
---
|
|
|
|
## 🚀 Endpoint API
|
|
|
|
### POST /api/analyze
|
|
|
|
Analizza un log e restituisce una risposta AI simulata.
|
|
|
|
**Request:**
|
|
```http
|
|
POST http://localhost:3000/api/analyze
|
|
Content-Type: application/json
|
|
|
|
{
|
|
"log": "FATAL: database system is out of memory"
|
|
}
|
|
```
|
|
|
|
**Response (dopo 1.5s delay):**
|
|
```json
|
|
{
|
|
"success": true,
|
|
"analysis": {
|
|
"title": "PostgreSQL Out of Memory",
|
|
"description": "Il database ha esaurito la memoria disponibile...",
|
|
"command": "ps aux | grep postgres | head -5 && free -h",
|
|
"isSafe": true,
|
|
"note": "Verifica processi Postgres e memoria disponibile."
|
|
},
|
|
"timestamp": "2026-04-03T10:30:00.000Z"
|
|
}
|
|
```
|
|
|
|
**Errori gestiti:**
|
|
- `400 Bad Request`: Payload vuoto o malformato
|
|
- `500 Internal Error`: Errore server generico
|
|
|
|
---
|
|
|
|
## 🛠️ Setup
|
|
|
|
### Prerequisiti
|
|
- Node.js 18+
|
|
- npm 9+
|
|
|
|
### Installazione
|
|
|
|
```bash
|
|
# Entra nella directory
|
|
cd tools/fake-backend
|
|
|
|
# Installa dipendenze
|
|
npm install
|
|
|
|
# Avvia il server
|
|
node server.js
|
|
```
|
|
|
|
Il server sarà disponibile su `http://localhost:3000`
|
|
|
|
---
|
|
|
|
## 🐳 Docker
|
|
|
|
Per avviare il fake backend con Docker:
|
|
|
|
```bash
|
|
# Dalla root del progetto
|
|
docker compose up fake-backend -d
|
|
```
|
|
|
|
Il servizio sarà esposto sulla porta 3000.
|
|
|
|
---
|
|
|
|
## 🔧 Configurazione
|
|
|
|
Variabili ambiente (opzionali):
|
|
|
|
```bash
|
|
PORT=3000 # Porta server (default: 3000)
|
|
DELAY_MS=1500 # Delay simulazione AI (default: 1500ms)
|
|
```
|
|
|
|
---
|
|
|
|
## 📁 Struttura
|
|
|
|
```
|
|
tools/fake-backend/
|
|
├── server.js # Server Express principale
|
|
├── package.json # Dipendenze npm
|
|
├── Dockerfile # Containerizzazione
|
|
└── README.md # Questo file
|
|
```
|
|
|
|
---
|
|
|
|
## 🔒 Sicurezza
|
|
|
|
⚠️ **ATTENZIONE**: Questo è uno strumento di sviluppo. NON usarlo in produzione:
|
|
- Nessuna autenticazione implementata
|
|
- Risposte statiche predefinite
|
|
- Nessuna validazione input avanzata
|
|
- CORS abilitato per tutte le origini
|
|
|
|
---
|
|
|
|
## 🧪 Test Manuale
|
|
|
|
```bash
|
|
# Test endpoint analyze
|
|
curl -X POST http://localhost:3000/api/analyze \
|
|
-H "Content-Type: application/json" \
|
|
-d '{"log": "Error: Connection refused"}'
|
|
```
|
|
|
|
---
|
|
|
|
## 📝 Note per Sviluppatori
|
|
|
|
### Aggiungere nuove risposte mock
|
|
|
|
Modifica l'oggetto `MOCK_RESPONSES` in `server.js`:
|
|
|
|
```javascript
|
|
const MOCK_RESPONSES = {
|
|
'errore-specifico': {
|
|
title: 'Titolo Problema',
|
|
description: 'Descrizione...',
|
|
command: 'comando-da-eseguire',
|
|
isSafe: true,
|
|
note: 'Nota aggiuntiva'
|
|
}
|
|
};
|
|
```
|
|
|
|
### Pattern matching
|
|
|
|
Il server cerca keyword nel log e restituisce la risposta appropriata:
|
|
- "memory" / "oom" → PostgreSQL OOM
|
|
- "connection refused" / "502" → Nginx/Connection error
|
|
- Default → Risposta generica
|
|
|
|
---
|
|
|
|
## 🤝 Integrazione Frontend
|
|
|
|
Per usare il fake backend dal frontend React:
|
|
|
|
```typescript
|
|
const analyzeLog = async (log: string) => {
|
|
const response = await fetch('http://localhost:3000/api/analyze', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ log })
|
|
});
|
|
return response.json();
|
|
};
|
|
```
|
|
|
|
---
|
|
|
|
## 🔄 Passaggio a Backend Reale
|
|
|
|
Quando il backend reale è pronto:
|
|
|
|
1. Aggiorna l'URL in `InteractiveDemo.tsx`
|
|
2. Aggiungi autenticazione (JWT/API Key)
|
|
3. Rimuovi CORS permissivo
|
|
4. Implementa rate limiting
|
|
|
|
---
|
|
|
|
*Strumento creato seguendo il principio "Safety First" del Metodo Sacchi*
|