Luca Sacchi Ricciardi baef924cfd fix: resolve ES modules compatibility in E2E test files
- Replace __dirname with import.meta.url pattern for ES modules compatibility
- Add fileURLToPath imports to all E2E test files
- Fix duplicate require statements in setup-verification.spec.ts
- Update playwright.config.ts to use relative path instead of __dirname

This fixes the 'ReferenceError: __dirname is not defined in ES module scope' error
when running Playwright tests in the ES modules environment.
2026-04-07 16:18:31 +02:00

mockupAWS - Backend Profiler & Cost Estimator

Versione: 0.3.0 (Completata)
Stato: Database, Backend & Frontend Implementation Complete

Panoramica

mockupAWS è una piattaforma di simulazione locale (homelab) progettata per profilare il traffico e calcolare i driver di costo dei servizi AWS (SQS, Lambda, Bedrock/LLM) prima del deploy in produzione.

A differenza dei semplici calcolatori di costo online, mockupAWS permette di:

  • Creare scenari di simulazione isolati e tracciabili
  • Inviare log reali tramite HTTP API (compatibile Logstash)
  • Storicizzare tutte le metriche in database PostgreSQL
  • Calcolare costi usando prezzi AWS reali aggiornabili
  • Generare report PDF/CSV professionali
  • Confrontare scenari per decisioni data-driven
  • Rilevare PII nei log prima dell'invio al cloud

Caratteristiche Principali

🎯 Gestione Scenari

  • Crea scenari di simulazione con nome, descrizione e tag
  • Isola completamente i dati tra scenari diversi
  • Stati dello scenario: draftrunningcompletedarchived
  • Confronta scenari side-by-side con indicatori di delta costi

💰 Calcolo Costi AWS Reale

  • Tabella prezzi AWS configurabile per regione
  • Calcolo accurato basato su:
    • SQS: $0.40 per milione richieste (blocchi 64KB)
    • Lambda: $0.20 per milione richieste + $0.0000166667 per GB-second
    • Bedrock: Prezzi per token input/output (variano per modello)
  • Supporto multi-regione (us-east-1, eu-west-1, ecc.)

📊 Interfaccia Web

  • Dashboard responsive con grafici in tempo reale
  • Dark/Light mode
  • Form guidato per creazione scenari
  • Vista dettaglio con metriche, costi, logs e PII detection
  • Export report PDF/CSV

🔒 Sicurezza

  • Rilevamento automatico email (PII) nei log
  • Hashing dei messaggi per privacy
  • Deduplicazione automatica per simulazione batching ottimizzato
  • Autenticazione JWT/API Keys (in sviluppo)

Architettura

┌─────────────────┐     ┌──────────────────┐     ┌─────────────────┐
│   Logstash      │     │   React Web UI   │     │   API Clients   │
│   (o Client)    │     │   (Dashboard)    │     │   (CI/CD)       │
└────────┬────────┘     └────────┬─────────┘     └────────┬────────┘
         │                       │                        │
         │ HTTP POST             │ HTTPS                  │ API Key
         │ /ingest               │ /api/v1/*              │ /api/v1/*
         ▼                       ▼                        ▼
┌────────────────────────────────────────────────────────────────────┐
│                    API LAYER (FastAPI + Uvicorn)                   │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌───────────┐ │
│  │ /scenarios  │  │ /ingest     │  │ /reports    │  │ /pricing  │ │
│  │ /metrics    │  │ (scenario)  │  │ generate    │  │ (admin)   │ │
│  └─────────────┘  └─────────────┘  └─────────────┘  └───────────┘ │
└────────────────────────────────────────────────────────────────────┘
         │
         ▼
┌────────────────────────────────────────────────────────────────────┐
│              DATABASE LAYER (PostgreSQL 15+)                       │
│  ┌──────────────┐ ┌──────────────┐ ┌──────────────┐               │
│  │  scenarios   │ │scenario_logs │ │ aws_pricing  │               │
│  │  scenario_   │ │  reports     │ │              │               │
│  │  metrics     │ │              │ │              │               │
│  └──────────────┘ └──────────────┘ └──────────────┘               │
└────────────────────────────────────────────────────────────────────┘

Stack Tecnologico

Backend

  • FastAPI (≥0.110) - Framework web async ad alte prestazioni
  • PostgreSQL (≥15) - Database relazionale con supporto JSON
  • SQLAlchemy (≥2.0) - ORM moderno con supporto async/await
  • Alembic - Migrazioni database versionate
  • Pydantic (≥2.7) - Validazione dati e serializzazione
  • tiktoken - Tokenizer ufficiale OpenAI per calcolo costi LLM
  • python-jose - JWT handling (preparato per v1.0.0)

Frontend

  • React (≥18) - UI library con hooks e functional components
  • Vite (≥5.0) - Build tool ultra-veloce con HMR
  • TypeScript (≥5.0) - Type safety e developer experience
  • Tailwind CSS (≥3.4) - Utility-first CSS framework
  • shadcn/ui - Componenti UI accessibili e personalizzabili
  • TanStack Query (React Query) - Data fetching e caching
  • Axios - HTTP client con interceptors
  • React Router - Client-side routing
  • Lucide React - Icone moderne e consistenti

DevOps

  • Docker & Docker Compose - Containerizzazione
  • Nginx - Reverse proxy (pronto per produzione)
  • uv - Package manager Python veloce e moderno
  • Ruff - Linter e formatter Python
  • ESLint & Prettier - Code quality frontend

Requisiti

  • Docker & Docker Compose
  • Python 3.11+ (se sviluppo locale)
  • Node.js 20+ (se sviluppo frontend)
  • ~2GB RAM disponibili

Installazione e Avvio

Prerequisiti

  • Docker & Docker Compose
  • Python 3.11+ (per sviluppo locale)
  • Node.js 20+ (per sviluppo frontend)
  • PostgreSQL 15+ (se non usi Docker)

Metodo 1: Docker Compose (Consigliato)

# Clona il repository
git clone <repository-url>
cd mockupAWS

# Avvia tutti i servizi (API + Database + Frontend)
docker-compose up --build

# L'applicazione sarà disponibile su:
# - Web UI: http://localhost:5173  (Vite dev server)
# - API: http://localhost:8000
# - API Docs: http://localhost:8000/docs
# - Database: localhost:5432

Metodo 2: Sviluppo Locale

Step 1: Database

# Usa Docker solo per PostgreSQL
docker-compose up -d postgres
# oppure configura PostgreSQL localmente

Step 2: Backend

# Installa dipendenze Python
uv sync

# Esegui migrazioni database
uv run alembic upgrade head

# Avvia server API
uv run uvicorn src.main:app --reload --host 0.0.0.0 --port 8000

Step 3: Frontend (in un altro terminale)

cd frontend

# Installa dipendenze
npm install

# Avvia server sviluppo
npm run dev

# L'app sarà disponibile su http://localhost:5173

Configurazione Ambiente

Crea un file .env nella root del progetto:

# Database
DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/mockupaws

# API
API_V1_STR=/api/v1
PROJECT_NAME=mockupAWS

# Frontend (se necessario)
VITE_API_URL=http://localhost:8000

Utilizzo

1. Creare uno Scenario

Via Web UI:

  1. Apri http://localhost:3000
  2. Clicca "Nuovo Scenario"
  3. Inserisci nome, descrizione, seleziona regione AWS
  4. Clicca "Crea e Avvia"

Via API:

curl -X POST http://localhost:8000/api/v1/scenarios \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Produzione Q2",
    "description": "Simulazione traffico produzione",
    "region": "us-east-1",
    "tags": ["production"]
  }'
# Response: { "id": "uuid-scenario-123", ... }

2. Inviare Log allo Scenario

# Usa lo scenario ID ricevuto
curl -X POST http://localhost:8000/ingest \
  -H "Content-Type: application/json" \
  -H "X-Scenario-ID: uuid-scenario-123" \
  -d '{"message": "Error: connection timeout", "source": "api"}'

Oppure configura Logstash:

output {
  http {
    url => "http://localhost:8000/ingest"
    headers => ["X-Scenario-ID", "uuid-scenario-123"]
    content_type => "application/json"
    format => "json"
  }
}

3. Monitorare in Tempo Reale

  • Apri la Web UI http://localhost:3000
  • Seleziona il tuo scenario
  • Osserva metriche in tempo reale:
    • Richieste totali
    • Costo stimato cumulativo
    • Blocchi SQS fatturabili
    • Token LLM contati
    • Violazioni PII rilevate

4. Generare Report

Via Web UI:

  1. Vai al tab "Report" dello scenario
  2. Seleziona formato (PDF o CSV)
  3. Clicca "Genera Report"
  4. Scarica il file

Via API:

curl -X POST http://localhost:8000/api/v1/scenarios/uuid-scenario-123/reports \
  -H "Content-Type: application/json" \
  -d '{"format": "pdf", "include_logs": false}'

5. Confrontare Scenari

Nella Web UI:

  1. Dalla lista scenari, seleziona 2+ scenari con i checkbox
  2. Clicca "Confronta Selezionati"
  3. Visualizza comparazione costi e metriche

Struttura del Progetto

mockupAWS/
├── src/                          # Backend FastAPI
│   ├── main.py                   # Entry point applicazione
│   ├── api/
│   │   ├── deps.py              # Dependencies (DB session, auth)
│   │   └── v1/                  # API v1 endpoints
│   │       ├── scenarios.py     # CRUD scenari
│   │       ├── ingest.py        # Ingestione log
│   │       └── metrics.py       # Metriche e costi
│   ├── core/
│   │   ├── config.py            # Configurazione app
│   │   ├── database.py          # SQLAlchemy setup
│   │   └── exceptions.py        # Gestione errori
│   ├── models/                  # SQLAlchemy models
│   │   ├── scenario.py
│   │   ├── scenario_log.py
│   │   ├── scenario_metric.py
│   │   ├── aws_pricing.py
│   │   └── report.py
│   ├── schemas/                 # Pydantic schemas
│   ├── repositories/            # Repository pattern
│   └── services/                # Business logic
│       ├── pii_detector.py
│       ├── cost_calculator.py
│       └── ingest_service.py
├── frontend/                     # Frontend React
│   ├── src/
│   │   ├── App.tsx              # Root component
│   │   ├── components/
│   │   │   ├── layout/          # Header, Sidebar, Layout
│   │   │   └── ui/              # shadcn components
│   │   ├── hooks/               # React Query hooks
│   │   ├── lib/
│   │   │   ├── api.ts           # Axios client
│   │   │   └── utils.ts         # Utility functions
│   │   ├── pages/               # Page components
│   │   │   ├── Dashboard.tsx
│   │   │   ├── ScenarioDetail.tsx
│   │   │   └── ScenarioEdit.tsx
│   │   └── types/
│   │       └── api.ts           # TypeScript types
│   ├── package.json
│   └── vite.config.ts
├── alembic/                      # Database migrations
│   └── versions/                 # Migration files
├── export/                       # Documentazione progetto
│   ├── prd.md                   # Product Requirements
│   ├── architecture.md          # Architettura sistema
│   ├── kanban.md                # Task breakdown
│   └── progress.md              # Progress tracking
├── docker-compose.yml            # Docker orchestration
├── pyproject.toml               # Python dependencies
└── README.md                    # Questo file

Principi di Design

🔐 Safety First

Validazione rigorosa dei payload e rilevamento PII prima di qualsiasi elaborazione.

🔄 Little Often

Processamento a piccoli batch per simulare l'ottimizzazione Lambda e minimizzare costi.

✓ Double Check

Ogni calcolo (token count, billing blocks, costi) è verificato. Target: >95% accuratezza vs AWS reale.

Sviluppo

Flusso di Lavoro (TDD)

  1. Spec-Driven: Definisci input/output prima di implementare
  2. Test First: Scrivi test che falliscono (Red)
  3. Implementa: Codice minimo per far passare test (Green)
  4. Refactor: Migliora codice mantenendo test passanti

Convenzioni Git

  • Conventional Commits: feat:, fix:, test:, docs:, chore:
  • Commit atomici
  • Esempio: feat: add scenario cost calculation with AWS pricing

Comandi Utili

# Test
uv run pytest                    # Tutti i test
uv run pytest -v                 # Verbose
uv run pytest --cov=src          # Con coverage

# Database
uv run alembic revision --autogenerate -m "description"
uv run alembic upgrade head
uv run alembic downgrade -1

# Formattazione
uv run ruff check src/
uv run ruff format src/

# Frontend
cd frontend
npm run lint
npm run build

Roadmap

v0.2.0 Completata

  • API ingestion base
  • Calcolo metriche (SQS, Lambda, Bedrock)
  • Database PostgreSQL con SQLAlchemy 2.0 async
  • Tabelle scenari e persistenza
  • Tabella prezzi AWS (seed dati per us-east-1, eu-west-1)
  • Migrazioni Alembic (6 migrations)
  • Repository pattern + Services layer
  • PII detection e cost calculation

v0.3.0 Completata

  • Frontend React 18 con Vite
  • Dashboard responsive con Tailwind CSS
  • Form creazione/modifica scenari
  • Lista scenari con paginazione
  • Pagina dettaglio scenario
  • Integrazione API con Axios + React Query
  • Componenti UI shadcn/ui

v0.4.0 (Prossima Release)

  • Generazione report PDF/CSV
  • Confronto scenari
  • Grafici interattivi con Recharts
  • Dark/Light mode toggle

v1.0.0

  • Autenticazione JWT e autorizzazione
  • API Keys management
  • Backup automatico database
  • Documentazione API completa (OpenAPI)
  • Testing E2E

Contributi

Contributi sono benvenuti! Per favore:

  1. Fork il repository
  2. Crea un branch feature (git checkout -b feature/amazing-feature)
  3. Commit le modifiche (git commit -m 'feat: add amazing feature')
  4. Push al branch (git push origin feature/amazing-feature)
  5. Apri una Pull Request

Licenza

Distribuito sotto licenza MIT. Vedi LICENSE per dettagli.


MockupAWS - Parte del progetto LogWhispererAI
Stima i costi AWS prima di spenderli davvero

Description
Ambiente di test per il backend di LogWhispererAI. Riceve i dati da Logstash, simula l'ingestion e l'elaborazione AWS calcolando metriche, payload e costi operativi in locale.
Readme MIT 5.2 MiB
Languages
TypeScript 62.8%
Python 34.1%
CSS 1.9%
JavaScript 0.7%
Mako 0.2%
Other 0.3%