veza/AUDIT_EXHAUSTIF_2025_01_27.md

43 KiB
Raw Blame History

🔍 AUDIT EXHAUSTIF — PROJET VEZA

Date : 2025-01-27
Auditeur : Audit technique senior (sécurité + architecture + performance)
Repository : /home/senke/Documents/veza
Objectif : Cartographier l'état actuel du projet et proposer un plan de remédiation réaliste


📋 TABLE DES MATIÈRES

  1. Vue d'ensemble du projet
  2. Cartographie détaillée du code
  3. État fonctionnel : ce qui marche / est partiel / est cassĂ©
  4. Sécurité : failles et surfaces d'attaque
  5. Performance & architecture technique
  6. Guide d'utilisation du projet (mode actuel réel)
  7. Axes d'amélioration (sécurité, qualité, features)
  8. SynthĂšse finale

1. VUE D'ENSEMBLE DU PROJET

1.1 Résumé exécutif

Veza est une plateforme audio collaborative en développement, organisée en monorepo avec une architecture micro-services. Le projet vise à fournir un service de streaming audio avec fonctionnalités collaboratives (chat, playlists partagées, transcodage).

État global : "PoC prometteur mais fragile"

Le projet présente :

  • ✅ Backend Go : Fonctionnel et relativement stable (92% coverage selon l'audit de stabilitĂ©)
  • ⚠ Chat Server (Rust) : Compile avec warnings, mais prĂ©sente des problĂšmes de race conditions et de gestion d'erreurs
  • ⚠ Stream Server (Rust) : Compile avec de nombreux warnings, code partiellement implĂ©mentĂ©
  • ❌ Frontend React : Erreurs TypeScript bloquantes (42% Ă©chec de tests selon les rĂšgles)

Points positifs :

  • Architecture claire (monorepo bien structurĂ©)
  • Documentation prĂ©sente (docs/, veza-docs/)
  • SystĂšme de migrations DB cohĂ©rent
  • Authentification JWT implĂ©mentĂ©e
  • Tests prĂ©sents (mĂȘme si partiellement fonctionnels)

Points fragiles :

  • IncohĂ©rences entre services (pas de transaction distribuĂ©e)
  • Code mort / partiellement implĂ©mentĂ© (notamment dans stream-server)
  • Erreurs TypeScript non rĂ©solues dans le frontend
  • Gestion d'erreurs incomplĂšte dans plusieurs composants
  • Race conditions identifiĂ©es dans le chat server

Utilisabilité actuelle :

  • Backend Go : Utilisable avec prĂ©cautions (nĂ©cessite PostgreSQL, Redis, variables d'env)
  • Chat Server : Utilisable en dev, mais nĂ©cessite attention aux race conditions
  • Stream Server : Partiellement fonctionnel, code expĂ©rimental prĂ©sent
  • Frontend : Non utilisable sans corrections TypeScript

1.2 Stack technique identifiée

Langages principaux

  • Backend : Go 1.23.8
  • Chat Server : Rust (Ă©dition 2021)
  • Stream Server : Rust (Ă©dition 2021)
  • Frontend : TypeScript/React (Vite)
  • Scripts : Bash, Python (outils)

Frameworks et bibliothÚques clés

Backend Go :

  • gin-gonic/gin : Framework HTTP
  • gorm.io/gorm : ORM
  • golang-jwt/jwt/v5 : JWT
  • go.uber.org/zap : Logging
  • github.com/redis/go-redis/v9 : Client Redis
  • github.com/rabbitmq/amqp091-go : RabbitMQ

Chat Server (Rust) :

  • axum : Framework web async
  • tokio : Runtime async
  • sqlx : SQL async
  • jsonwebtoken : JWT
  • lapin : RabbitMQ client
  • tracing : Logging structurĂ©

Stream Server (Rust) :

  • axum : Framework web
  • tokio : Runtime async
  • sqlx : SQL async
  • symphonia, hound, minimp3 : Traitement audio
  • m3u8-rs : HLS streaming
  • tracing : Logging

Frontend :

  • react 18.2.0
  • vite 7.1.5
  • typescript 5.3.3
  • tailwindcss 4.0.0
  • zustand : State management
  • @tanstack/react-query : Data fetching
  • playwright : E2E tests

Bases de données et systÚmes de stockage

  • PostgreSQL 15 : Base principale (backend, chat, stream)
  • Redis 7 : Cache et sessions
  • RabbitMQ 3.12 : Event bus inter-services

Services externes / API

  • Sentry : Monitoring d'erreurs (configurĂ© mais optionnel)
  • Prometheus : MĂ©triques (exposĂ©es via /metrics)

Organisation du repo

Monorepo avec structure claire :

veza/
├── apps/web/              # Frontend React
├── veza-backend-api/      # Backend Go
├── veza-chat-server/      # Chat Server Rust
├── veza-stream-server/    # Stream Server Rust
├── veza-desktop/          # Wrapper Electron
├── veza-common/           # Code partagĂ© Rust
├── veza-rust-common/      # Utilitaires Rust
├── docs/                  # Documentation
├── scripts/               # Scripts de dĂ©ploiement/test
├── docker/                # Config Docker
└── migrations/            # Migrations globales

2. CARTOGRAPHIE DÉTAILLÉE DU CODE

2.1 Structure du repository

veza-backend-api/ (Go)

  • RĂŽle : API REST principale, gestion utilisateurs, playlists, tracks, analytics
  • Langage : Go 1.23.8
  • Niveau de maturitĂ© : ✅ Stable (92% coverage, migrations structurĂ©es)
  • Structure :
    • cmd/api/main.go : Point d'entrĂ©e principal
    • internal/handlers/ : Handlers HTTP
    • internal/services/ : Logique mĂ©tier
    • internal/models/ : ModĂšles GORM
    • internal/middleware/ : Middleware (auth, RBAC, metrics)
    • internal/database/ : Gestion DB et migrations
    • migrations/ : Migrations SQL (12 fichiers)

veza-chat-server/ (Rust)

  • RĂŽle : Serveur WebSocket pour chat en temps rĂ©el
  • Langage : Rust (Ă©dition 2021)
  • Niveau de maturitĂ© : ⚠ Partiel (compile mais warnings, race conditions)
  • Structure :
    • src/main.rs : Point d'entrĂ©e
    • src/websocket/ : Gestion WebSocket
    • src/repository/ : AccĂšs DB
    • src/security/ : Permissions, CSRF
    • src/typing_indicator.rs : Indicateurs de frappe
    • migrations/ : Migrations SQL (11 fichiers)

veza-stream-server/ (Rust)

  • RĂŽle : Streaming audio (HLS, WebSocket), transcodage
  • Langage : Rust (Ă©dition 2021)
  • Niveau de maturitĂ© : ⚠ Partiel / ExpĂ©rimental (compile avec warnings, code mort)
  • Structure :
    • src/main.rs : Point d'entrĂ©e
    • src/core/ : Traitement audio, encoding, sync
    • src/codecs/ : Codecs audio (MP3, AAC, FLAC, Opus)
    • src/streaming/ : HLS, WebSocket transport
    • src/routes/ : Routes HTTP
    • migrations/ : Migrations SQL (2 fichiers)

apps/web/ (React/TypeScript)

  • RĂŽle : Interface utilisateur web
  • Langage : TypeScript/React
  • Niveau de maturitĂ© : ❌ CassĂ© (erreurs TypeScript bloquantes)
  • Structure :
    • src/app/ : Point d'entrĂ©e React
    • src/features/ : Features par domaine (auth, player, chat, etc.)
    • src/components/ : Composants rĂ©utilisables
    • src/services/ : Clients API
    • e2e/ : Tests Playwright

scripts/ (Bash)

  • RĂŽle : Automatisation (dĂ©ploiement, tests, migrations)
  • Fichiers clĂ©s :
    • start-veza.sh : DĂ©marrage complet
    • migrate-db.sh : Migrations DB
    • run-tests.sh : Tests
    • lab/ : Scripts pour environnement lab

docs/ (Markdown)

  • RĂŽle : Documentation technique
  • Fichiers clĂ©s :
    • AUDIT_STABILITY.md : Audit de stabilitĂ© existant
    • DB_MIGRATIONS_STRATEGY_FINAL.md : StratĂ©gie migrations
    • TODO_TRIAGE_VEZA.md : TĂąches en cours

2.2 Points d'entrée

Backend Go

Fichier principal : veza-backend-api/cmd/api/main.go

Commande de lancement :

cd veza-backend-api
go run ./cmd/api

Dépendances :

  • PostgreSQL (via DATABASE_URL)
  • Redis (via REDIS_URL)
  • Variables d'environnement :
    • JWT_SECRET (requis)
    • DB_PASSWORD (requis)
    • APP_PORT (dĂ©faut: 8080)
    • APP_ENV (dĂ©faut: development)

Port : 8080 (configurable)

Chat Server (Rust)

Fichier principal : veza-chat-server/src/main.rs

Commande de lancement :

cd veza-chat-server
cargo run --release

Dépendances :

  • PostgreSQL (via DATABASE_URL)
  • Redis (optionnel, via REDIS_URL)
  • RabbitMQ (optionnel, via RABBITMQ_URL)
  • Variables d'environnement :
    • JWT_SECRET (requis, min 32 caractĂšres)
    • CHAT_SERVER_PORT (dĂ©faut: 8081)

Port : 8081 (configurable)

Stream Server (Rust)

Fichier principal : veza-stream-server/src/main.rs

Commande de lancement :

cd veza-stream-server
cargo run --release

Dépendances :

  • PostgreSQL (via DATABASE_URL)
  • Redis (via REDIS_URL)
  • Variables d'environnement :
    • JWT_SECRET (requis)
    • STREAM_PORT (dĂ©faut: 8082)
    • SECRET_KEY (requis, 32 bytes)

Port : 8082 (configurable)

Frontend React

Fichier principal : apps/web/src/main.tsx

Commande de lancement :

cd apps/web
npm install
npm run dev

Dépendances :

  • Node.js 18+
  • Variables d'environnement :
    • VITE_API_URL (dĂ©faut: http://localhost:8080/api)
    • VITE_WS_URL (dĂ©faut: ws://localhost:8081/ws)
    • VITE_STREAM_URL (dĂ©faut: ws://localhost:8082/stream)

Port : 5173 (Vite dev server)

Docker Compose (tous services)

Fichier : docker-compose.yml

Commande de lancement :

docker-compose up -d

Services :

  • postgres : PostgreSQL 15
  • redis : Redis 7
  • rabbitmq : RabbitMQ 3.12
  • backend-api : Backend Go
  • chat-server : Chat Server Rust
  • stream-server : Stream Server Rust
  • frontend : Frontend React (Nginx)
  • haproxy : Reverse proxy

2.3 Tests & qualité

Backend Go

Types de tests : Unitaires, intégration, transactions

Commande :

cd veza-backend-api
go test ./... -v

RĂ©sultat : ✅ Fonctionnel (92% coverage selon AUDIT_STABILITY.md)

Linters : Pas de linter configuré explicitement (gofmt standard)

Chat Server (Rust)

Types de tests : Unitaires (certains marqués #[ignore] car nécessitent DB)

Commande :

cd veza-chat-server
cargo test

RĂ©sultat : ⚠ Partiel (tests nĂ©cessitant DB ignorĂ©s)

Linters : cargo clippy (non exécuté dans l'audit)

Stream Server (Rust)

Types de tests : Unitaires (peu présents)

Commande :

cd veza-stream-server
cargo test

RĂ©sultat : ⚠ Partiel (peu de tests)

Linters : cargo clippy (non exécuté dans l'audit)

Frontend React

Types de tests : Unitaires (Vitest), E2E (Playwright)

Commande :

cd apps/web
npm test              # Unitaires
npm run test:e2e      # E2E

RĂ©sultat : ❌ CassĂ© (42% Ă©chec selon rĂšgles, erreurs TypeScript)

Linters : ESLint configuré (npm run lint)

CI/CD

Fichiers : .github/workflows/

  • backend-ci.yml : Tests Go
  • chat-ci.yml : Tests Rust (chat)
  • stream-ci.yml : Tests Rust (stream)
  • frontend-ci.yml : Tests React
  • ci.yml : Pipeline global

Status : Configuré mais non validé dans cet audit


3. ÉTAT FONCTIONNEL

3.1 Tableau de synthĂšse

Composant / Module Rîle Langage / Tech État Commentaire technique Commande(s)
Backend API API REST principale Go 1.23 / Gin ✅ Fonctionnel, 92% coverage. Gestion JSON robuste. go run ./cmd/api
Chat Server WebSocket chat Rust / Axum ⚠ Compile mais race conditions (TypingIndicatorManager). Warnings. cargo run --release
Stream Server Streaming audio Rust / Axum ⚠ Compile avec warnings. Code mort prĂ©sent. FFmpeg monitoring fragile. cargo run --release
Frontend Web Interface utilisateur React / Vite ❌ Erreurs TypeScript bloquantes. Imports manquants. npm run dev (ne dĂ©marre pas proprement)
Database Migrations SchĂ©ma DB SQL ✅ Migrations structurĂ©es (12 backend, 11 chat, 2 stream). UUID-first. scripts/migrate-db.sh
Docker Compose Orchestration Docker ✅ Configuration complĂšte. Health checks prĂ©sents. docker-compose up
Authentication JWT + Sessions Go/Rust ✅ JWT HS256, refresh tokens, sessions validĂ©es. IntĂ©grĂ©
RBAC Permissions Go ✅ Service PermissionService, middleware RequirePermission. IntĂ©grĂ©
Event Bus Communication inter-services RabbitMQ ⚠ ImplĂ©mentĂ© mais optionnel (mode dĂ©gradĂ© si absent). Via RabbitMQ
Health Checks Monitoring HTTP ✅ /health (stateless), /status (avec DB check). IntĂ©grĂ©

3.2 Détail par composant

3.2.1 Backend Go (veza-backend-api)

Description : API REST pour gestion utilisateurs, playlists, tracks, analytics, chat (legacy).

Implémentation actuelle :

  • Fichiers clĂ©s :

    • cmd/api/main.go : Point d'entrĂ©e avec graceful shutdown
    • internal/api/router.go : Configuration routes
    • internal/handlers/ : Handlers HTTP (auth, social, playlists, etc.)
    • internal/services/ : Services mĂ©tier (auth, playlist, RBAC, etc.)
    • internal/middleware/auth.go : Middleware JWT + sessions
    • internal/middleware/rbac_auth_middleware.go : RBAC
    • internal/database/database.go : Gestion DB + migrations
  • Endpoints importants :

    • POST /api/v1/auth/login : Authentification
    • POST /api/v1/auth/register : Inscription
    • GET /api/v1/playlists : Liste playlists
    • GET /api/v1/tracks : Liste tracks
    • GET /health : Health check
    • GET /status : Status avec DB check
  • Couverture de tests : 92% (selon AUDIT_STABILITY.md)

État rĂ©el :

  • ✅ Marche bien : Compilation OK, dĂ©marrage OK, endpoints principaux fonctionnels
  • ⚠ Points de fragilitĂ© :
    • Erreurs silencieuses dans certains handlers (rĂ©solu partiellement avec BindAndValidateJSON)
    • Absence de transactions dans certaines opĂ©rations multi-Ă©tapes
    • Race condition dans workers retries
    • Timing attack potentiel sur password reset

Points de fragilité :

  • HypothĂšses implicites : DB toujours disponible (pas de circuit breaker)
  • Gestion d'erreur : Certaines erreurs DB non wrappĂ©es avec contexte
  • Couplage : DĂ©pendance forte Ă  PostgreSQL (pas de fallback)
  • Legacy : Code chat legacy prĂ©sent (internal/api/ vs internal/handlers/)

3.2.2 Chat Server (veza-chat-server)

Description : Serveur WebSocket pour chat en temps réel avec gestion des conversations, typing indicators, read receipts.

Implémentation actuelle :

  • Fichiers clĂ©s :

    • src/main.rs : Point d'entrĂ©e avec Axum
    • src/websocket/handler.rs : Handler WebSocket
    • src/repository/message_store.rs : Repository messages
    • src/typing_indicator.rs : Gestion typing indicators
    • src/read_receipts.rs : Read receipts
    • src/security/permission.rs : VĂ©rifications permissions
  • Endpoints :

    • GET /ws : WebSocket upgrade
    • GET /api/messages/:conversation_id : RĂ©cupĂ©ration messages
    • POST /api/messages : Envoi message
    • GET /health : Health check

État rĂ©el :

  • ⚠ Marche mais avec limitations :
    • Compile avec warnings (unused imports, variables)
    • Race condition dans TypingIndicatorManager (RwLock vs Mutex)
    • Race conditions dans DeliveredStatusManager et ReadReceiptManager
    • Pas de panic boundary dans handle_socket
    • Tasks orphelins possibles (monitoring typing indicators)
    • Pas de heartbeat timeout pour dĂ©tecter connexions zombies

Points de fragilité :

  • Race conditions : TypingIndicatorManager, DeliveredStatusManager, ReadReceiptManager
  • Gestion d'erreur : 31 fichiers avec unwrap() ou expect() (panics possibles)
  • Tasks : Pas de mĂ©canisme de shutdown propre pour certaines tasks
  • Permissions : Risque de bypass si PermissionService Ă©choue (fail-secure non garanti)

3.2.3 Stream Server (veza-stream-server)

Description : Serveur de streaming audio avec transcodage (HLS, WebSocket), gestion des segments, synchronisation multi-clients.

Implémentation actuelle :

  • Fichiers clĂ©s :
    • src/main.rs : Point d'entrĂ©e
    • src/core/processing/processor.rs : Traitement audio
    • src/core/processing/segment_tracker.rs : Suivi segments
    • src/core/processing/ffmpeg_monitor.rs : Monitoring FFmpeg
    • src/streaming/hls.rs : HLS streaming
    • src/streaming/websocket.rs : WebSocket transport
    • src/routes/encoding.rs : Routes transcodage

État rĂ©el :

  • ⚠ Partiellement fonctionnel :
    • Compile avec de nombreux warnings (unused imports, variables, champs)
    • Code mort prĂ©sent (champs non lus, mĂ©thodes non utilisĂ©es)
    • Tasks non cancellĂ©es proprement en cas d'erreur (abort() brutal)
    • Erreurs FFmpeg non propagĂ©es correctement (loggĂ©es mais job continue)
    • DB pas toujours sync en cas de crash (segments non persistĂ©s)
    • Corruption d'Ă©tat concurrent possible dans SegmentTracker
    • Regex non robustes dans FFmpegMonitor (pas de fallback)

Points de fragilité :

  • Code mort : Nombreux champs/mĂ©thodes non utilisĂ©s (refactoring nĂ©cessaire)
  • Gestion d'erreur : Erreurs FFmpeg loggĂ©es mais non fatales
  • Concurrence : SegmentTracker peut avoir des problĂšmes d'ordre
  • Monitoring : FFmpegMonitor fragile (regex, IO errors incomplĂštes)

3.2.4 Frontend React (apps/web)

Description : Interface utilisateur web pour la plateforme Veza (player audio, chat, playlists, recherche).

Implémentation actuelle :

  • Fichiers clĂ©s :
    • src/app/App.tsx : Point d'entrĂ©e React
    • src/features/player/ : Player audio
    • src/features/chat/ : Chat
    • src/features/auth/ : Authentification
    • src/services/api.ts : Client API

État rĂ©el :

  • ❌ CassĂ© :
    • Erreurs TypeScript bloquantes (50+ erreurs)
    • Imports manquants (@/hooks/use-toast, @/components/ui/scroll-area, etc.)
    • PropriĂ©tĂ©s manquantes sur types (Track.url, Track.cover_url)
    • Tests Ă©chouent (42% selon rĂšgles)

Points de fragilité :

  • TypeScript : Types incomplets, imports manquants
  • Paths aliases : Configuration @/ peut ĂȘtre incorrecte
  • Tests : Échecs nombreux

4. SÉCURITÉ

4.1 Vue d'ensemble sécurité

Authentification

  • ✅ JWT : ImplĂ©mentĂ© (HS256) dans backend Go et services Rust
  • ✅ Sessions : Validation cĂŽtĂ© serveur (backend Go)
  • ✅ Refresh tokens : ImplĂ©mentĂ©s avec version checking
  • ✅ Token revocation : Blacklist Redis partielle

Autorisation / RĂŽles

  • ✅ RBAC : ImplĂ©mentĂ© (PermissionService, middleware RequirePermission)
  • ✅ RĂŽles : Admin, Moderator, User, Premium, Artist, Guest
  • ✅ Permissions : Granulaires (StreamAudio, UploadAudio, ManageUsers, etc.)

Gestion des mots de passe

  • ✅ Hashing : bcrypt (cost 12) dans backend Go
  • ✅ Validation : Force minimale (8 caractĂšres)
  • ✅ Password reset : ProtĂ©gĂ© contre Ă©numĂ©ration (toujours retourne succĂšs)

Utilisation de secrets

  • ✅ Stockage : Variables d'environnement (.env non commitĂ©)
  • ⚠ Gestion : Pas de gestionnaire de secrets centralisĂ© (Vault, etc.)
  • ✅ Masquage : Secrets masquĂ©s dans les logs (MaskSecret)

Niveau général : "Minimalement acceptable pour un labo / dev"

4.2 Failles et mauvaises pratiques

P0 – Critique (doit ĂȘtre corrigĂ© avant dĂ©ploiement)

  1. Backend Go : Erreurs JSON non traitées silencieusement

    • Localisation : RĂ©solu partiellement (BindAndValidateJSON créé)
    • Description : Certains handlers dans internal/api/ n'utilisent pas encore BindAndValidateJSON
    • Impact : Erreurs JSON peuvent passer silencieusement
    • Piste de correction : Refactoriser tous les handlers pour utiliser BindAndValidateJSON
  2. Backend Go : Absence de transactions dans opérations critiques

    • Localisation : internal/core/marketplace/service.go:134-136 et autres services
    • Description : OpĂ©rations multi-Ă©tapes non transactionnelles
    • Impact : IncohĂ©rence DB en cas d'erreur partielle
    • Piste de correction : Wrapper opĂ©rations multi-Ă©tapes dans transactions
  3. Chat Server : Race condition dans TypingIndicatorManager

    • Localisation : src/typing_indicator.rs:34-48
    • Description : RwLock peut causer des inversions de timestamps
    • Impact : Broadcasts dans le mauvais ordre
    • Piste de correction : Utiliser Mutex ou canal sĂ©rialisĂ©
  4. Chat Server : Panics possibles (31 fichiers avec unwrap())

    • Localisation : 31 fichiers identifiĂ©s
    • Description : unwrap() et expect() peuvent causer des panics
    • Impact : Crash du serveur
    • Piste de correction : Remplacer par ? ou gestion d'erreur explicite
  5. Stream Server : Tasks non cancellées proprement

    • Localisation : src/core/processing/processor.rs:168-169
    • Description : abort() tue brutalement les tasks
    • Impact : Transactions DB non commitĂ©es, handles orphelins
    • Piste de correction : Utiliser CancellationToken, attendre fin des tasks
  6. Global : Pas de transaction distribuée

    • Localisation : Tous les services
    • Description : Pas de garantie de cohĂ©rence inter-services
    • Impact : DonnĂ©es incohĂ©rentes entre services
    • Piste de correction : Pattern Saga ou Event Sourcing
  7. Global : Manque de tests unitaires critiques

    • Localisation : Tous les services
    • Description : Beaucoup de tests #[ignore] ou absents
    • Impact : Pas de validation automatique
    • Piste de correction : Utiliser mocks ou containers Docker pour tests
  8. Global : Jobs/messages/segments peuvent ĂȘtre incohĂ©rents

    • Localisation : Tous les services
    • Description : Pas de cleanup des donnĂ©es orphelines
    • Impact : DB contient des donnĂ©es incohĂ©rentes
    • Piste de correction : Jobs de cleanup pĂ©riodiques

P1 – Important

  1. Backend Go : Erreurs silencieuses, validation input incomplĂšte

    • Localisation : internal/handlers/
    • Description : Certains handlers retournent erreurs gĂ©nĂ©riques
    • Impact : Debugging difficile
    • Piste de correction : Utiliser systĂ©matiquement RespondWithAppError
  2. Backend Go : Race condition dans workers retries

    • Localisation : internal/workers/job_worker.go:127-135
    • Description : Retries peut ĂȘtre incrĂ©mentĂ© plusieurs fois
    • Impact : Jobs retry plus que maxRetries
    • Piste de correction : Mutex ou atomic operations
  3. Backend Go : Timing attack password reset

    • Localisation : internal/services/password_reset_service.go:70-125
    • Description : Temps de traitement diffĂšre selon existence email
    • Impact : DĂ©tection d'emails existants via timing
    • Piste de correction : DĂ©lai artificiel pour Ă©galiser temps
  4. Chat Server : Race conditions dans DeliveredStatusManager/ReadReceiptManager

    • Localisation : src/delivered_status.rs, src/read_receipts.rs
    • Description : Updates DB peuvent se chevaucher
    • Impact : Statuts incohĂ©rents
    • Piste de correction : Queue sĂ©rialisĂ©e ou transaction DB
  5. Chat Server : Pas de panic boundary dans WebSocket handler

    • Localisation : src/websocket/handler.rs:77-163
    • Description : Panic peut faire crasher la task Tokio
    • Impact : Client malveillant peut faire crasher le serveur
    • Piste de correction : Wrapper dans std::panic::catch_unwind
  6. Chat Server : Tasks orphelins, pas de heartbeat timeout

    • Localisation : src/typing_indicator.rs, src/websocket/handler.rs
    • Description : Tasks continuent aprĂšs arrĂȘt, pas de dĂ©tection connexions zombies
    • Impact : Fuites ressources
    • Piste de correction : CancellationToken, heartbeat ping/pong
  7. Stream Server : Erreurs FFmpeg non propagées, DB pas toujours sync

    • Localisation : src/core/processing/processor.rs:154-156, src/core/processing/processor.rs:238-243
    • Description : Erreurs loggĂ©es mais non fatales, segments non persistĂ©s en cas de crash
    • Impact : Jobs se terminent en "succĂšs" alors que FFmpeg a Ă©chouĂ©, incohĂ©rence DB
    • Piste de correction : DĂ©tecter erreurs fatales, persister immĂ©diatement chaque segment
  8. Stream Server : Corruption d'état concurrent dans SegmentTracker

    • Localisation : src/core/processing/segment_tracker.rs:59-78
    • Description : Ordre d'insertion peut varier
    • Impact : Segments persistĂ©s dans le mauvais ordre
    • Piste de correction : Canal sĂ©rialisĂ© ou mutex global
  9. Stream Server : Regex non robustes, IO errors incomplĂštes

    • Localisation : src/core/processing/ffmpeg_monitor.rs:22-24, src/core/processing/ffmpeg_monitor.rs:90-94
    • Description : Regex peut ne plus matcher, IO errors non propagĂ©es
    • Impact : Segments non dĂ©tectĂ©s, monitoring s'arrĂȘte silencieusement
    • Piste de correction : Fallback dĂ©tection segments, logger et propager erreurs
  10. Global : Pas de validation croisée IDs, pas de tests de charge

    • Localisation : Communication inter-services
    • Description : Chat server accepte conversation_id sans vĂ©rification, pas de tests charge
    • Impact : Messages pour conversations inexistantes, problĂšmes performance non dĂ©tectĂ©s
    • Piste de correction : Validation croisĂ©e via API, tests k6/locust
  11. Global : Fuites goroutine/task, pas de correlation-id

    • Localisation : internal/jobs/cleanup_sessions.go:33-45, veza-chat-server/src/optimized_persistence.rs:264-285
    • Description : Goroutines/tasks sans mĂ©canisme shutdown, pas de tracing distribuĂ©
    • Impact : Fuites ressources, debugging difficile
    • Piste de correction : context.Context avec cancellation, OpenTelemetry

P2 – AmĂ©lioration

  1. Backend Go : Pas de circuit breaker health check

    • Localisation : Health checks
    • Description : Pas de circuit breaker pour Ă©viter surcharger DB
    • Impact : Health checks continuent Ă  tenter connexions si DB down
    • Piste de correction : ImplĂ©menter circuit breaker
  2. Backend Go : Queue in-memory sans persistance

    • Localisation : internal/workers/job_worker.go
    • Description : Queue en mĂ©moire, jobs perdus en cas de crash
    • Impact : Perte de jobs non traitĂ©s
    • Piste de correction : Queue persistante (Redis, RabbitMQ)
  3. Global : Logs non structurés, pas de vérification d'intégrité

    • Localisation : Quelques handlers
    • Description : Certains logs utilisent fmt.Printf, pas de job vĂ©rification intĂ©gritĂ©
    • Impact : Logs non queryables, incohĂ©rences non dĂ©tectĂ©es
    • Piste de correction : Standardiser sur tracing/zap, job vĂ©rification quotidien

4.3 Gestion des données & vie privée

Type de données manipulées

  • Emails, identifiants utilisateurs
  • Messages de chat
  • MĂ©tadonnĂ©es audio (tracks, playlists)
  • Logs d'accĂšs

Points sensibles

  • ⚠ DonnĂ©es personnelles dans logs : Emails, user IDs peuvent apparaĂźtre dans logs (vĂ©rifier masquage)
  • ✅ Masquage secrets : MaskSecret implĂ©mentĂ© pour secrets
  • ⚠ Export / stockage : Pas de contrĂŽle d'accĂšs explicite sur exports de donnĂ©es

5. PERFORMANCE & ARCHITECTURE TECHNIQUE

5.1 Architecture globale

Style général : Micro-services avec monorepo

  • Backend Go : Monolithe modulaire (handlers, services, models)
  • Chat Server : Service indĂ©pendant (WebSocket)
  • Stream Server : Service indĂ©pendant (streaming audio)
  • Frontend : Application React monolithique

Couplage entre modules :

  • Fort : Backend ↔ Chat (validation conversation_id), Backend ↔ Stream (jobs transcodage)
  • Faible : Services Rust indĂ©pendants (communication via RabbitMQ optionnel)

Zones problématiques :

  • Pas de transaction distribuĂ©e (incohĂ©rence possible)
  • Validation croisĂ©e IDs manquante (chat accepte conversation_id sans vĂ©rification backend)

Patterns utilisés :

  • Backend Go : MVC-ish (handlers → services → models)
  • Chat/Stream Rust : Hexagonal-ish (repository pattern, services)

5.2 Points de performance

RequĂȘtes DB non indexĂ©es / rĂ©pĂ©titives

  • Localisation : À vĂ©rifier dans les migrations
  • Description : Indexes prĂ©sents dans migrations SQL, mais certains peuvent manquer
  • Impact : RequĂȘtes lentes sur grandes tables
  • Piste d'amĂ©lioration : Audit indexes, ajouter indexes manquants

Boucles ou traitements synchrones

  • Localisation : veza-chat-server/src/typing_indicator.rs (monitoring task)
  • Description : Task de monitoring avec interval 500ms
  • Impact : CPU usage si nombreuses conversations
  • Piste d'amĂ©lioration : Optimiser algorithme, rĂ©duire frĂ©quence si possible

I/O bloquantes

  • Localisation : veza-stream-server/src/core/processing/ffmpeg_monitor.rs
  • Description : Lecture stderr FFmpeg peut bloquer
  • Impact : Latence traitement audio
  • Piste d'amĂ©lioration : Async I/O, buffering

Absence de pagination / limitation

  • Localisation : veza-chat-server/src/main.rs:389 (get_messages avec limit 50 max)
  • Description : Pagination prĂ©sente mais limitĂ©e Ă  100
  • Impact : OK pour chat, mais vĂ©rifier autres endpoints
  • Piste d'amĂ©lioration : VĂ©rifier pagination sur tous endpoints listes

Cache

  • Localisation : Redis utilisĂ© pour sessions, mais cache mĂ©tier limitĂ©
  • Description : Pas de cache systĂ©matique pour donnĂ©es frĂ©quemment accĂ©dĂ©es
  • Impact : RequĂȘtes DB rĂ©pĂ©titives
  • Piste d'amĂ©lioration : Cache Redis pour playlists, tracks populaires

6. GUIDE D'UTILISATION

6.1 Prérequis

Services nécessaires

  • PostgreSQL 15 : Base de donnĂ©es principale
  • Redis 7 : Cache et sessions
  • RabbitMQ 3.12 : Event bus (optionnel, mode dĂ©gradĂ© si absent)

Variables d'environnement

Backend Go (.env dans veza-backend-api/) :

DATABASE_URL=postgresql://veza:password@localhost:5432/veza_db?sslmode=disable
REDIS_URL=redis://localhost:6379
JWT_SECRET=your-super-secret-jwt-key-min-32-chars
APP_PORT=8080
APP_ENV=development

Chat Server (.env dans veza-chat-server/) :

DATABASE_URL=postgresql://veza:password@localhost:5432/veza_db?sslmode=disable
REDIS_URL=redis://localhost:6379
JWT_SECRET=your-super-secret-jwt-key-min-32-chars
CHAT_SERVER_PORT=8081

Stream Server (.env dans veza-stream-server/) :

DATABASE_URL=postgresql://veza:password@localhost:5432/veza_db?sslmode=disable
REDIS_URL=redis://localhost:6379
JWT_SECRET=your-super-secret-jwt-key
SECRET_KEY=your-32-byte-secret-key
STREAM_PORT=8082

Frontend (.env dans apps/web/) :

VITE_API_URL=http://localhost:8080/api
VITE_WS_URL=ws://localhost:8081/ws
VITE_STREAM_URL=ws://localhost:8082/stream

Commandes d'installation

Backend Go :

cd veza-backend-api
go mod download

Chat Server (Rust) :

cd veza-chat-server
cargo build --release

Stream Server (Rust) :

cd veza-stream-server
cargo build --release

Frontend :

cd apps/web
npm install

6.2 Lancement des composants

Option 1 : Docker Compose (recommandé)

docker-compose up -d
  • DĂ©marre tous les services (PostgreSQL, Redis, RabbitMQ, Backend, Chat, Stream, Frontend, HAProxy)
  • Health checks automatiques
  • Ports : 80 (HAProxy), 8080 (Backend), 8081 (Chat), 8082 (Stream), 8085 (Frontend)

Option 2 : Manuel (développement)

1. Démarrer infrastructure :

# Via Makefile
make infra-up

# Ou manuellement
docker-compose up -d postgres redis rabbitmq

2. Appliquer migrations :

# Via Makefile
make migrate-all

# Ou manuellement
cd veza-backend-api
go run ./cmd/migrate_tool
cd ../veza-chat-server
sqlx migrate run
cd ../veza-stream-server
sqlx migrate run

3. Démarrer services :

# Backend
cd veza-backend-api
go run ./cmd/api

# Chat Server (terminal 2)
cd veza-chat-server
cargo run --release

# Stream Server (terminal 3)
cd veza-stream-server
cargo run --release

# Frontend (terminal 4)
cd apps/web
npm run dev

ProblĂšmes potentiels et workarounds

  1. PostgreSQL non accessible :

    • VĂ©rifier DATABASE_URL
    • VĂ©rifier que PostgreSQL est dĂ©marrĂ© : pg_isready -U veza -d veza_db
  2. Redis non accessible :

    • VĂ©rifier REDIS_URL
    • Tester : redis-cli ping
  3. Frontend erreurs TypeScript :

    • ⚠ ProblĂšme connu : Erreurs TypeScript bloquantes
    • Workaround : npm run dev peut fonctionner malgrĂ© erreurs (Vite ignore certaines erreurs)
  4. Stream Server compilation :

    • ⚠ NĂ©cessite PostgreSQL accessible pour sqlx::query! macros
    • Solution : GĂ©nĂ©rer sqlx-data.json avec cargo sqlx prepare

6.3 Tests

Backend Go

cd veza-backend-api
go test ./... -v

RĂ©sultat attendu : ✅ Tests passent (92% coverage)

Chat Server

cd veza-chat-server
cargo test

RĂ©sultat attendu : ⚠ Certains tests #[ignore] (nĂ©cessitent DB)

Stream Server

cd veza-stream-server
cargo test

RĂ©sultat attendu : ⚠ Peu de tests prĂ©sents

Frontend

cd apps/web
npm test              # Unitaires
npm run test:e2e      # E2E

RĂ©sultat attendu : ❌ Erreurs TypeScript, tests Ă©chouent

Recommandation minimale

Avant un commit / release :

  1. ✅ Backend Go : go test ./...
  2. ⚠ Chat Server : cargo test (vĂ©rifier tests non ignorĂ©s)
  3. ⚠ Stream Server : cargo test (vĂ©rifier tests prĂ©sents)
  4. ❌ Frontend : Corriger erreurs TypeScript avant commit

7. AXES D'AMÉLIORATION

7.1 Plan de remédiation priorisé

P0 – Urgent / bloquant

  1. Corriger erreurs TypeScript frontend

    • RĂ©sumĂ© : RĂ©soudre 50+ erreurs TypeScript bloquantes
    • Pourquoi : Frontend non utilisable
    • OĂč : apps/web/src/
    • ComplexitĂ© : Moyenne (corrections types, imports, paths aliases)
    • Estimation : 4-6h
  2. Implémenter transactions dans opérations critiques backend

    • RĂ©sumĂ© : Wrapper opĂ©rations multi-Ă©tapes dans transactions
    • Pourquoi : Éviter incohĂ©rences DB
    • OĂč : veza-backend-api/internal/services/, internal/core/
    • ComplexitĂ© : Moyenne (identifier opĂ©rations, wrapper)
    • Estimation : 6-8h
  3. Corriger race conditions chat server

    • RĂ©sumĂ© : Remplacer RwLock par Mutex dans TypingIndicatorManager, sĂ©rialiser updates dans DeliveredStatusManager/ReadReceiptManager
    • Pourquoi : Éviter incohĂ©rences donnĂ©es
    • OĂč : veza-chat-server/src/typing_indicator.rs, src/delivered_status.rs, src/read_receipts.rs
    • ComplexitĂ© : Faible-Moyenne (changements ciblĂ©s)
    • Estimation : 4-6h
  4. Remplacer unwrap() par gestion d'erreur explicite

    • RĂ©sumĂ© : Remplacer tous les unwrap()/expect() par ? ou gestion explicite
    • Pourquoi : Éviter panics
    • OĂč : 31 fichiers identifiĂ©s dans chat server
    • ComplexitĂ© : Faible (mĂ©canique)
    • Estimation : 4-6h
  5. Corriger gestion tasks stream server

    • RĂ©sumĂ© : Utiliser CancellationToken au lieu de abort(), attendre fin tasks
    • Pourquoi : Éviter transactions DB non commitĂ©es
    • OĂč : veza-stream-server/src/core/processing/processor.rs
    • ComplexitĂ© : Moyenne (refactoring shutdown)
    • Estimation : 4-6h
  6. Implémenter cleanup jobs données orphelines

    • RĂ©sumĂ© : Jobs pĂ©riodiques pour supprimer donnĂ©es incohĂ©rentes
    • Pourquoi : Maintenir cohĂ©rence DB
    • OĂč : Nouveaux workers dans chaque service
    • ComplexitĂ© : Moyenne (identifier donnĂ©es orphelines, implĂ©menter cleanup)
    • Estimation : 6-8h

P1 – Important / à planifier à court terme

  1. Refactoriser handlers backend pour utiliser BindAndValidateJSON

    • RĂ©sumĂ© : Migrer handlers dans internal/api/ vers BindAndValidateJSON
    • Pourquoi : Uniformiser gestion erreurs JSON
    • OĂč : veza-backend-api/internal/api/
    • ComplexitĂ© : Faible (mĂ©canique)
    • Estimation : 2-4h
  2. Ajouter panic boundary WebSocket handler

    • RĂ©sumĂ© : Wrapper handle_incoming_message dans catch_unwind
    • Pourquoi : Éviter crash serveur si panic
    • OĂč : veza-chat-server/src/websocket/handler.rs
    • ComplexitĂ© : Faible
    • Estimation : 1-2h
  3. Implémenter heartbeat timeout WebSocket

    • RĂ©sumĂ© : Ping/pong avec timeout pour dĂ©tecter connexions zombies
    • Pourquoi : LibĂ©rer ressources
    • OĂč : veza-chat-server/src/websocket/handler.rs
    • ComplexitĂ© : Moyenne
    • Estimation : 3-4h
  4. Corriger gestion erreurs FFmpeg stream server

    • RĂ©sumĂ© : DĂ©tecter erreurs fatales, arrĂȘter traitement immĂ©diatement
    • Pourquoi : Éviter jobs "succĂšs" alors que FFmpeg a Ă©chouĂ©
    • OĂč : veza-stream-server/src/core/processing/processor.rs, src/core/processing/ffmpeg_monitor.rs
    • ComplexitĂ© : Moyenne
    • Estimation : 4-6h
  5. Implémenter validation croisée IDs inter-services

    • RĂ©sumĂ© : Chat server vĂ©rifie conversation_id via API backend
    • Pourquoi : Éviter messages pour conversations inexistantes
    • OĂč : veza-chat-server/src/websocket/handler.rs
    • ComplexitĂ© : Moyenne (appel API, cache)
    • Estimation : 4-6h
  6. Ajouter correlation-id / tracing distribué

    • RĂ©sumĂ© : ImplĂ©menter OpenTelemetry ou systĂšme de tracing
    • Pourquoi : Faciliter debugging en production
    • OĂč : Tous les services
    • ComplexitĂ© : ÉlevĂ©e (infrastructure)
    • Estimation : 8-12h
  7. Nettoyer code mort stream server

    • RĂ©sumĂ© : Supprimer champs/mĂ©thodes non utilisĂ©s
    • Pourquoi : RĂ©duire complexitĂ©, amĂ©liorer maintenabilitĂ©
    • OĂč : veza-stream-server/src/
    • ComplexitĂ© : Faible (mĂ©canique)
    • Estimation : 2-4h

P2 – AmĂ©lioration continue

  1. Implémenter circuit breaker health checks

    • RĂ©sumĂ© : Circuit breaker pour Ă©viter surcharger DB
    • Pourquoi : AmĂ©liorer rĂ©silience
    • OĂč : veza-backend-api/internal/handlers/health.go
    • ComplexitĂ© : Moyenne
    • Estimation : 4-6h
  2. Migrer queue in-memory vers queue persistante

    • RĂ©sumĂ© : Utiliser Redis ou RabbitMQ pour jobs
    • Pourquoi : Éviter perte jobs en cas de crash
    • OĂč : veza-backend-api/internal/workers/job_worker.go
    • ComplexitĂ© : ÉlevĂ©e (refactoring)
    • Estimation : 8-12h
  3. Standardiser logs (tracing/zap)

    • RĂ©sumĂ© : Remplacer fmt.Printf par tracing/zap
    • Pourquoi : Logs queryables
    • OĂč : Quelques handlers
    • ComplexitĂ© : Faible
    • Estimation : 2-4h
  4. Implémenter job vérification intégrité DB

    • RĂ©sumĂ© : Job quotidien vĂ©rifiant cohĂ©rence fichiers/DB
    • Pourquoi : DĂ©tecter incohĂ©rences
    • OĂč : Nouveau worker
    • ComplexitĂ© : Moyenne
    • Estimation : 4-6h
  5. Ajouter tests de charge

    • RĂ©sumĂ© : Tests k6 ou locust pour valider performance
    • Pourquoi : DĂ©tecter problĂšmes performance
    • OĂč : Nouveau dossier tests/load/
    • ComplexitĂ© : Moyenne
    • Estimation : 6-8h

7.2 Nouveaux features (optionnels, mais intelligents)

  1. Health check dashboard

    • ProblĂšme actuel : Health checks dispersĂ©s (/health, /status)
    • Impact : Centraliser monitoring santĂ© services
    • ImplĂ©mentation : Endpoint /health/all agrĂ©geant health checks de tous services
    • ComplexitĂ© : Faible-Moyenne
  2. Rate limiting global

    • ProblĂšme actuel : Pas de rate limiting systĂ©matique
    • Impact : Protection contre abus, DDoS
    • ImplĂ©mentation : Middleware rate limiting (Redis-based) dans backend, chat, stream
    • ComplexitĂ© : Moyenne
  3. Metrics dashboard (Prometheus + Grafana)

    • ProblĂšme actuel : MĂ©triques exposĂ©es mais pas de dashboard
    • Impact : Visualisation mĂ©triques, alerting
    • ImplĂ©mentation : Grafana avec datasource Prometheus
    • ComplexitĂ© : Faible (infrastructure)
  4. API documentation interactive (Swagger/OpenAPI)

    • ProblĂšme actuel : Documentation API limitĂ©e
    • Impact : Faciliter intĂ©gration, tests
    • ImplĂ©mentation : Swagger dĂ©jĂ  configurĂ© dans backend Go, complĂ©ter annotations
    • ComplexitĂ© : Faible
  5. Webhook notifications

    • ProblĂšme actuel : Pas de notifications externes
    • Impact : IntĂ©grations tierces
    • ImplĂ©mentation : SystĂšme webhooks pour Ă©vĂ©nements (nouveau track, nouveau message, etc.)
    • ComplexitĂ© : ÉlevĂ©e

8. SYNTHÈSE FINALE

Dans quel état réel est le projet aujourd'hui ?

"PoC prometteur mais fragile"

Le projet Veza présente une architecture solide avec des services bien séparés (Backend Go, Chat Rust, Stream Rust, Frontend React). Le backend Go est fonctionnel et relativement stable (92% coverage), mais les autres composants présentent des fragilités importantes :

  • Chat Server : Compile mais race conditions et panics possibles
  • Stream Server : Code partiellement implĂ©mentĂ©, gestion d'erreurs incomplĂšte
  • Frontend : Erreurs TypeScript bloquantes, non utilisable sans corrections

Le projet est utilisable en développement avec précautions, mais nécessite des corrections critiques avant un déploiement en production.

Qu'est-ce qui fonctionne le mieux ?

  1. Backend Go : Architecture claire, tests présents, migrations structurées, authentification JWT robuste, RBAC implémenté
  2. Docker Compose : Configuration complÚte avec health checks, facile à démarrer
  3. Migrations DB : SystÚme cohérent, UUID-first, bien documenté
  4. Documentation : Présente et structurée (docs/, veza-docs/)

Qu'est-ce qui est le plus dangereux / fragile ?

  1. Frontend TypeScript : 50+ erreurs bloquantes, non utilisable
  2. Race conditions chat server : TypingIndicatorManager, DeliveredStatusManager, ReadReceiptManager
  3. Panics Rust : 31 fichiers avec unwrap()/expect() dans chat server
  4. Incohérences DB : Pas de transactions distribuées, données orphelines possibles
  5. Gestion d'erreurs stream server : Erreurs FFmpeg non propagées, tasks non cancellées proprement

Quelles 3 actions prioritaires maximisent le rapport effort / bénéfice ?

  1. Corriger erreurs TypeScript frontend (P0, 4-6h)

    • BĂ©nĂ©fice : Frontend utilisable
    • Effort : Moyen (corrections mĂ©caniques)
    • Impact : ImmĂ©diat (frontend fonctionnel)
  2. Corriger race conditions chat server (P0, 4-6h)

    • BĂ©nĂ©fice : StabilitĂ© chat, cohĂ©rence donnĂ©es
    • Effort : Faible-Moyen (changements ciblĂ©s)
    • Impact : Critique (Ă©vite bugs production)
  3. Remplacer unwrap() par gestion d'erreur explicite (P0, 4-6h)

    • BĂ©nĂ©fice : Évite panics, stabilitĂ© serveurs Rust
    • Effort : Faible (mĂ©canique)
    • Impact : Critique (Ă©vite crashes)

Total estimation P0 critiques : 12-18h de travail ciblé pour rendre le projet significativement plus stable.


Fin du rapport d'audit