app backend prima
This commit is contained in:
420
ARCHITECTURE.md
Normal file
420
ARCHITECTURE.md
Normal file
@@ -0,0 +1,420 @@
|
||||
# Architettura Sistema Terrain Monitor
|
||||
|
||||
## Overview
|
||||
|
||||
Sistema distribuito per il monitoraggio di infrastrutture critiche (ponti, dighe, gallerie, frane) con notifiche push real-time su app mobile.
|
||||
|
||||
## Diagramma Architettura
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ SISTEMA CENTRALIZZATO │
|
||||
│ (Elaborazione dati sensori) │
|
||||
└────────────────────────────┬────────────────────────────────────────┘
|
||||
│
|
||||
│ Pubblica allarmi
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ MQTT Broker │
|
||||
│ (Mosquitto) │
|
||||
│ Port: 1883 │
|
||||
└────────┬────────┘
|
||||
│
|
||||
│ Topic: terrain/alarms/#
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────────────────┐
|
||||
│ BACKEND (FastAPI) │
|
||||
│ ┌──────────────────────────────────────────────────────────────┐ │
|
||||
│ │ MQTT Client │ │
|
||||
│ │ - Sottoscrive topic allarmi │ │
|
||||
│ │ - Valida payload JSON │ │
|
||||
│ └─────────────────────┬────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Alarm Handler │ │
|
||||
│ │ 1. Salva allarme in DB │ │
|
||||
│ │ 2. Recupera utenti cliente │ │
|
||||
│ │ 3. Filtra per FCM token │ │
|
||||
│ └─────────────────────┬────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Firebase Service │ │
|
||||
│ │ - Prepara notifica (titolo, body, data) │ │
|
||||
│ │ - Determina priorità (critical/warning/info) │ │
|
||||
│ │ - Invia multicast a tutti i dispositivi │ │
|
||||
│ └─────────────────────┬────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌─────────────────────┴────────────────────────────────────────┐ │
|
||||
│ │ REST API │ │
|
||||
│ │ - /auth/* : Autenticazione, FCM token registration │ │
|
||||
│ │ - /allarmi/* : Lista, dettagli, aggiornamento allarmi │ │
|
||||
│ └──────────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────────────────────────────────────────┐ │
|
||||
│ │ PostgreSQL Database │ │
|
||||
│ │ - clienti, siti, utenti, allarmi │ │
|
||||
│ └──────────────────────────────────────────────────────────────┘ │
|
||||
└────────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
│ Firebase Cloud Messaging (FCM)
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────────────────┐
|
||||
│ FIREBASE CLOUD MESSAGING │
|
||||
│ (Google Infrastructure) │
|
||||
└─────────────────────┬──────────────────────┬───────────────────────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
┌──────────────────┐ ┌──────────────────┐
|
||||
│ APP ANDROID │ │ APP iOS │
|
||||
│ │ │ │
|
||||
│ - Login │ │ - Login │
|
||||
│ - FCM Token │ │ - FCM Token │
|
||||
│ - Ricevi notif. │ │ - Ricevi notif. │
|
||||
│ - Lista allarmi │ │ - Lista allarmi │
|
||||
│ - Dettagli │ │ - Dettagli │
|
||||
└──────────────────┘ └──────────────────┘
|
||||
```
|
||||
|
||||
## Componenti Dettagliati
|
||||
|
||||
### 1. Sistema Centralizzato di Monitoraggio
|
||||
|
||||
**Responsabilità:**
|
||||
- Raccolta dati da centrali remote
|
||||
- Elaborazione e analisi dati
|
||||
- Rilevamento anomalie
|
||||
- Generazione allarmi
|
||||
|
||||
**Output:**
|
||||
- Messaggi JSON su MQTT quando rileva un allarme
|
||||
- Topic structure: `terrain/alarms/{sito_id}`
|
||||
|
||||
### 2. MQTT Broker (Mosquitto)
|
||||
|
||||
**Caratteristiche:**
|
||||
- Protocollo leggero per IoT
|
||||
- Publish/Subscribe pattern
|
||||
- QoS (Quality of Service) configurabile
|
||||
- Persistenza messaggi
|
||||
|
||||
**Configurazione:**
|
||||
- Port: 1883 (MQTT)
|
||||
- Port: 9001 (WebSocket - opzionale)
|
||||
|
||||
### 3. Backend FastAPI
|
||||
|
||||
#### 3.1 MQTT Client
|
||||
```python
|
||||
- Connessione persistente al broker
|
||||
- Auto-reconnect in caso di disconnessione
|
||||
- Parsing e validazione payload JSON
|
||||
- Handler per processare messaggi
|
||||
```
|
||||
|
||||
#### 3.2 Alarm Handler
|
||||
```python
|
||||
Flusso di processamento:
|
||||
1. Valida payload (sito_id obbligatorio)
|
||||
2. Verifica esistenza sito in DB
|
||||
3. Crea record Allarme
|
||||
4. Query utenti del cliente con FCM token attivo
|
||||
5. Delega a Firebase Service per invio
|
||||
```
|
||||
|
||||
#### 3.3 Firebase Service
|
||||
```python
|
||||
Funzionalità:
|
||||
- Singleton per riutilizzo connessione
|
||||
- send_notification() per singolo dispositivo
|
||||
- send_multicast() per batch invio
|
||||
- Gestione errori (token scaduti, etc.)
|
||||
- Configurazione priorità per piattaforma
|
||||
```
|
||||
|
||||
#### 3.4 REST API
|
||||
```
|
||||
Endpoints principali:
|
||||
|
||||
Authentication:
|
||||
POST /auth/token # OAuth2 login
|
||||
POST /auth/login # JSON login
|
||||
POST /auth/register-fcm-token # Registra device
|
||||
GET /auth/me # User info
|
||||
|
||||
Allarmi:
|
||||
GET /allarmi # Lista paginata
|
||||
GET /allarmi/{id} # Dettaglio
|
||||
PATCH /allarmi/{id} # Aggiorna stato
|
||||
GET /allarmi/sito/{sito_id} # Per sito
|
||||
```
|
||||
|
||||
#### 3.5 Database (PostgreSQL)
|
||||
|
||||
**Schema:**
|
||||
|
||||
```sql
|
||||
clienti
|
||||
├─ id (PK)
|
||||
├─ nome, email, telefono
|
||||
└─ attivo
|
||||
|
||||
siti
|
||||
├─ id (PK)
|
||||
├─ cliente_id (FK → clienti)
|
||||
├─ nome, tipo (enum)
|
||||
├─ lat, lng, altitudine
|
||||
└─ codice_identificativo
|
||||
|
||||
utenti
|
||||
├─ id (PK)
|
||||
├─ cliente_id (FK → clienti)
|
||||
├─ email (unique)
|
||||
├─ password_hash
|
||||
├─ fcm_token (per notifiche)
|
||||
└─ ruolo (enum: admin, operatore, viewer)
|
||||
|
||||
allarmi
|
||||
├─ id (PK)
|
||||
├─ sito_id (FK → siti)
|
||||
├─ tipo (enum: movimento_terreno, etc.)
|
||||
├─ severita (enum: critical, warning, info)
|
||||
├─ stato (enum: nuovo, risolto, etc.)
|
||||
├─ valore_rilevato, valore_soglia
|
||||
├─ dati_sensori (JSONB)
|
||||
└─ timestamp_rilevamento
|
||||
```
|
||||
|
||||
**Indici:**
|
||||
```sql
|
||||
- utenti.email (unique)
|
||||
- allarmi.sito_id + timestamp_rilevamento
|
||||
- allarmi.severita
|
||||
- allarmi.stato
|
||||
```
|
||||
|
||||
### 4. Firebase Cloud Messaging
|
||||
|
||||
**Vantaggi:**
|
||||
- ✓ Supporto nativo Android + iOS
|
||||
- ✓ Delivery garantito (anche app chiusa)
|
||||
- ✓ Priorità configurabile
|
||||
- ✓ Topic e targeting avanzato
|
||||
- ✓ Analytics integrato
|
||||
- ✓ Gratuito fino a volumi molto alti
|
||||
|
||||
**Formato Notifica:**
|
||||
```json
|
||||
{
|
||||
"notification": {
|
||||
"title": "CRITICAL: Ponte Morandi",
|
||||
"body": "Movimento terreno rilevato: 15.5mm"
|
||||
},
|
||||
"data": {
|
||||
"alarm_id": "456",
|
||||
"sito_id": "123",
|
||||
"tipo": "movimento_terreno",
|
||||
"severita": "critical"
|
||||
},
|
||||
"android": {
|
||||
"priority": "high",
|
||||
"notification": {
|
||||
"sound": "default",
|
||||
"priority": "max"
|
||||
}
|
||||
},
|
||||
"apns": {
|
||||
"payload": {
|
||||
"aps": {
|
||||
"sound": "default",
|
||||
"badge": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. App Mobile (Flutter/React Native)
|
||||
|
||||
**Funzionalità principali:**
|
||||
1. Login con JWT
|
||||
2. Registrazione FCM token al login
|
||||
3. Ricezione notifiche push in background
|
||||
4. Lista allarmi (filtri, paginazione)
|
||||
5. Dettaglio allarme con mappa
|
||||
6. Aggiornamento stato (risolto, in gestione)
|
||||
7. Visualizzazione dati sensori
|
||||
|
||||
**Tecnologie consigliate:**
|
||||
- **Flutter**: Singola codebase, performance native
|
||||
- **React Native**: Ecosystem JavaScript
|
||||
- **Firebase SDK**: Gestione notifiche
|
||||
- **HTTP Client**: Chiamate API REST
|
||||
|
||||
## Flusso Dati End-to-End
|
||||
|
||||
### Scenario: Allarme Movimento Terreno
|
||||
|
||||
```
|
||||
1. SENSORE
|
||||
↓ (dati grezzi via LoRa/4G)
|
||||
|
||||
2. CENTRALINA LOCALE
|
||||
↓ (aggregazione e validazione)
|
||||
|
||||
3. SISTEMA CENTRALIZZATO
|
||||
- Riceve dati ogni 5 minuti
|
||||
- Elabora: valore_attuale = 15.5mm
|
||||
- Confronta: soglia = 10.0mm
|
||||
- TRIGGER: 15.5 > 10.0 → ALLARME!
|
||||
↓ (pubblica MQTT)
|
||||
|
||||
4. MQTT BROKER
|
||||
- Topic: terrain/alarms/123
|
||||
- Payload JSON con dettagli
|
||||
↓ (forward a subscriber)
|
||||
|
||||
5. BACKEND MQTT CLIENT
|
||||
- Riceve messaggio
|
||||
- Valida JSON
|
||||
- Chiama alarm_handler
|
||||
↓
|
||||
|
||||
6. ALARM HANDLER
|
||||
- INSERT INTO allarmi (...)
|
||||
- SELECT utenti WHERE cliente_id = X AND fcm_token IS NOT NULL
|
||||
- Trova 3 utenti attivi
|
||||
↓
|
||||
|
||||
7. FIREBASE SERVICE
|
||||
- Prepara notifica multicast
|
||||
- Priorità: HIGH (severità = critical)
|
||||
- Invia a 3 FCM tokens
|
||||
↓
|
||||
|
||||
8. FIREBASE CLOUD MESSAGING
|
||||
- Delivery a Google/Apple servers
|
||||
- Push a dispositivi
|
||||
↓
|
||||
|
||||
9. APP MOBILE (3 dispositivi)
|
||||
- Riceve notifica
|
||||
- Mostra: "CRITICAL: Ponte Morandi"
|
||||
- Suono + vibrazione
|
||||
- Badge icon: 1 nuovo
|
||||
- Tap → apre dettaglio allarme
|
||||
↓
|
||||
|
||||
10. UTENTE
|
||||
- Visualizza dati completi
|
||||
- Vede mappa sito
|
||||
- Cambia stato → "in_gestione"
|
||||
- PATCH /allarmi/456 → aggiorna DB
|
||||
```
|
||||
|
||||
**Latenza totale:** < 2 secondi (dal publish MQTT alla notifica)
|
||||
|
||||
## Sicurezza
|
||||
|
||||
### Autenticazione
|
||||
- JWT tokens (HS256)
|
||||
- Password hashing (bcrypt)
|
||||
- Token expiration configurabile
|
||||
|
||||
### Autorizzazione
|
||||
- Multi-tenant: isolamento per cliente_id
|
||||
- Ruoli: admin, operatore, visualizzatore
|
||||
- Filter automatico query per cliente
|
||||
|
||||
### Network
|
||||
- HTTPS obbligatorio (produzione)
|
||||
- MQTT con TLS + credenziali
|
||||
- CORS configurato per domini specifici
|
||||
- Rate limiting (TODO)
|
||||
|
||||
### Database
|
||||
- Prepared statements (SQLAlchemy ORM)
|
||||
- No SQL injection possibile
|
||||
- Backup automatici
|
||||
- Encryption at rest (configurazione DB)
|
||||
|
||||
## Scalabilità
|
||||
|
||||
### Orizzontale
|
||||
- Backend stateless → multiple instances
|
||||
- Load balancer (nginx/HAProxy)
|
||||
- Database: read replicas per query
|
||||
|
||||
### Verticale
|
||||
- PostgreSQL: ottimizzazioni indici
|
||||
- MQTT: clustering (EMQX per produzione)
|
||||
- Firebase: gestisce automaticamente
|
||||
|
||||
### Performance Stimata
|
||||
- 1000 allarmi/minuto: OK con 1 istanza
|
||||
- 10000+ allarmi/minuto: 3-5 istanze + DB tuning
|
||||
- FCM: 1M+ notifiche/secondo (gestito da Google)
|
||||
|
||||
## Monitoring e Logging
|
||||
|
||||
### Logs
|
||||
- Application: Python logging module
|
||||
- MQTT: Mosquitto logs
|
||||
- Database: PostgreSQL logs
|
||||
- Aggregation: ELK Stack o CloudWatch
|
||||
|
||||
### Metriche
|
||||
- Allarmi ricevuti/inviati
|
||||
- Latenza MQTT → FCM
|
||||
- Success rate notifiche
|
||||
- Database query performance
|
||||
|
||||
### Alerting
|
||||
- Backend down → PagerDuty
|
||||
- MQTT disconnection → Email
|
||||
- Database errors → Slack
|
||||
- High latency → Grafana alerts
|
||||
|
||||
## Disaster Recovery
|
||||
|
||||
### Backup
|
||||
- Database: pg_dump giornaliero
|
||||
- Configurazione: Git repository
|
||||
- Logs: retention 30 giorni
|
||||
|
||||
### Fault Tolerance
|
||||
- MQTT: auto-reconnect + QoS 1
|
||||
- Database: replication master-slave
|
||||
- Backend: health check + auto-restart
|
||||
- FCM: retry automatico (gestito da SDK)
|
||||
|
||||
## Costi Stimati (Produzione)
|
||||
|
||||
### Infrastruttura
|
||||
- Backend: $50-100/mese (2 istanze AWS EC2 t3.medium)
|
||||
- Database: $100-200/mese (AWS RDS PostgreSQL)
|
||||
- MQTT: $50-100/mese (EMQX Cloud o self-hosted)
|
||||
- **Totale:** ~$200-400/mese
|
||||
|
||||
### Servizi Esterni
|
||||
- Firebase FCM: **GRATIS** (fino a milioni di notifiche/giorno)
|
||||
- Domain + SSL: $20/anno
|
||||
- Monitoring: $50/mese (Datadog/New Relic)
|
||||
|
||||
### Totale Stimato
|
||||
**$250-500/mese** per sistema completo in produzione
|
||||
|
||||
---
|
||||
|
||||
## Prossimi Miglioramenti
|
||||
|
||||
1. **WebSocket** per notifiche real-time su web dashboard
|
||||
2. **GraphQL** alternativa a REST API
|
||||
3. **Redis** per caching e rate limiting
|
||||
4. **Kubernetes** per orchestrazione container
|
||||
5. **TimescaleDB** per dati time-series sensori
|
||||
6. **Machine Learning** per predizione anomalie
|
||||
7. **Geofencing** per notifiche basate su posizione
|
||||
8. **Multi-language** support (i18n)
|
||||
Reference in New Issue
Block a user