Flow Event Discovery - Documentazione Tecnica del Codice (Estesa)

Perimetro e obiettivo

Documento tecnico completo al 10 marzo 2026: struttura del monorepo, porte, modelli dati, flussi, configurazioni e comandi operativi.

Mappa servizi, porte ed entrypoint

  • API Gateway | backend/api-gateway/src/server.js | porta 3000 | proxy verso user (3001), event (3002), social (3003), notification (default 3004), realtime (3005, ws), AI 8001/8002.
  • User Service | backend/user-service/src/server.js | porta 3001 | Mongo flow_db, Redis db0 | emette JWT e gestisce identita/profili.
  • Event Service | backend/event-service/src/app.js | porta 3002 | Mongo flow_events, Redis db1 | eventi, venue, categorie, search, analytics.
  • Social Service | backend/social-service/src/app.js | porta attesa 3003 | Mongo + Redis db0/?, gruppi/connessioni/post.
  • Notification Service | backend/notification-service/server.js | porta di default 3003 (gateway preconfigurato 3004: allineare PORT o NOTIFICATION_SERVICE_URL) | Mongo + Redis (Bull) | email/SMS/push.
  • Realtime Service | backend/realtime-service/server.js | porta 3005 | Socket.IO + Mongo flow_realtime + Redis opzionale.
  • Recommendation Engine | ai-services/recommendation-engine/main.py | 8001 | FastAPI placeholder.
  • Matchmaking Service | ai-services/matchmaking-service/main.py | 8002 | FastAPI placeholder.
  • Admin Portal | admin-portal (Next.js) | dev porta 3000 | Supabase auth.
  • Mobile | mobile (Flutter) | usa API Gateway + Socket.IO.

Flussi architetturali principali

  1. Auth: il client chiama /api/auth sul user-service (via gateway). Il token JWT viene poi verificato dal gateway e propagato ai servizi. Refresh token gestito da user-service.
  2. Creazione evento: richiesta a /api/v1/events validazioni salvataggio Mongo cache Redis eventuale email/notification analytics incrementate.
  3. Interazione social: gruppi/post/connessioni su social-service; cache Redis per feed; controlli privacy e membership.
  4. Realtime: gateway proxy /socket.io verso realtime-service; socketAuth valida JWT, trackConnection registra metriche; eventi di messaggistica, stanze, presence, typing.
  5. Notifiche: /api/notifications validazione user-preferences enqueue Bull (Redis) adattatori canale (FCM, email, SMS, web-push, in-app) log esito.
  6. Raccomandazioni/matchmaking: endpoint FastAPI placeholder (da implementare) esposti come /api/recommendations e /api/matchmaking.

Dettaglio microservizi backend

API Gateway

  • Sicurezza: Helmet con CSP/HSTS, rateLimit + slowDown, CORS whitelisted, compression, cookie parser.
  • Auth: middleware verifyToken su rotte protette; aggiunge x-user-id e x-user-role ai proxy; correlation-id per tracing.
  • Proxy: http-proxy-middleware con retry e gestione errori 503; websocket proxy su /socket.io.
  • Doc: Swagger opzionale /api-docs.

User Service

  • Middleware: helmet, cors, mongoSanitize, filtro XSS manuale, HPP, rate limit + slow down, compression, request logger morgan.
  • Rotte: /api/auth (signup, login, refresh, password reset, email verification), /api/users (CRUD, ruoli, disattivazione), /api/profile (bio/avatar/location), /api/preferences (notifiche, interessi), /health, /api-docs.
  • Modello User (Mongo): email, username, password hash, firstName/lastName, DOB con validazione eta, gender, phone, location (coords 2dsphere), loginAttempts/lockUntil, passwordChangedAt, passwordResetToken/Expires, emailVerificationToken/Expires, flags isVerified/isActive, preference ref, sessioni via Redis.
  • Modelli Profile/Preferences: avatar con varianti, bio, social links, interessi/tag, impostazioni notifiche, lingua, tema, filtri contenuto.
  • Token: JWT access/refresh, reset/verify token hashed; bcrypt rounds configurabili; 2FA opzionale via feature flag.
  • Cache: TTL separati per profilo, sessione, preferenze (config.cache.*).

Event Service

  • Middleware: helmet, cors, mongoSanitize, xss-clean, hpp, rate limit, compression, request timing logger.
  • Rotte: /api/v1/events, /api/v1/categories, /api/v1/venues, /api/v1/search/events, analytics (dashboard, venue), cache admin (/api/v1/cache/clear|stats), health.
  • Modello Event: title/slug, descrizioni short/full, category/subcategory ref, organizer + coOrganizers, schedule (start/end/timezone, recurrence), location (venue ref, indirizzo, coords), media, ticketing (types, price, currency, capacity, waitlist), attendees + statuses, social (likes/comments/save), analytics (views/unique/purchases/cancellations), visibility (public/private/unlisted), status (draft/published/cancelled), moderation flags.
  • Modelli Category/Venue: categorizzazione, slug univoci, venue con capacity, geo index, owner.
  • Servizi: cacheService (pattern delete), searchService (testo + filtri), analyticsService (dashboard organizer), emailService (invia conferme/reminder), notificationService (hookabile).

Social Service

  • Middleware: helmet, cors dinamico, mongoSanitize, xss-clean, hpp, compression, morgan, logger custom con durata richieste.
  • Rotte: groupRoutes (crea/aggiorna/joina/leave, inviti, ruoli), connectionRoutes (follow/friend request, accept/decline, blocco), postRoutes (post, commenti, like, feed, segnalazioni), health, cache clear.
  • Modelli chiave: Group (owner, members con ruoli, privacy, tag), Post (author, content, media, visibilita, likes/comments), Connection (from/to, stato, tipo follow/friend), Notification hooks verso notification-service.
  • Cache: Redis per feed/list; endpoint admin per clear pattern o flushall.

Notification Service

  • Stack: Express, Mongo, Redis (Bull queue), Firebase Admin, Nodemailer, Twilio, web-push, Handlebars templates.
  • Rotte: /api/notifications (crea/invia/schedula), /api/templates (CRUD, media upload), /api/user-preferences (per canale), /health.
  • Canali: email, SMS, push (FCM), web-push, in-app; feature flags ENABLE_* per canale.
  • Rate limiting: express-rate-limit + store Redis; request-size limit; sanitize input; content-type validator.
  • Code: Bull code in Redis, priorita e retry; workers definiti in services/*.js.
  • Logging: winston + daily rotate (cartella logs/), request-id su header.
  • Nota porta: config default PORT 3003, gateway default 3004 impostare PORT=3004 o NOTIFICATION_SERVICE_URL coerente.

Realtime Service

  • Stack: Express + Socket.IO, Mongo, Redis opzionale; CORS/helmet/compression/rate limit/mongoSanitize.
  • Eventi principali: MessageEvents (chat), RoomEvents (crea/unisci/lascia stanza), PresenceEvents (online/offline/typing), supporto per ack e broadcast.
  • Middleware: socketAuth (JWT), trackConnection (metriche), errorHandler; graceful shutdown chiude HTTP, Socket.IO, Mongo, Redis.
  • Health: endpoint health (express) + metriche base da logger.

AI Services

  • Recommendation Engine (8001) e Matchmaking (8002): FastAPI con root + health; logica da implementare (attualmente placeholder).

Admin Portal

  • Next.js 16 App Router + TypeScript + Tailwind; stato con TanStack Query; form con RHF + Zod; tabelle con TanStack Table; grafici Recharts/Chart.js.
  • Directory chiave: app/ (route), components/ (UI), contexts/ e providers/ (auth, theme), lib/ (api client), tests/ e tests/ (Vitest), email-templates/ (MJML/React?).
  • Auth/DB: Supabase; env richiesti NEXT_PUBLIC_SUPABASE_URL, NEXT_PUBLIC_SUPABASE_ANON_KEY; proxy di sviluppo in proxy.ts verso API gateway.
  • Test: npm run test (Vitest), npx playwright test (E2E).

Mobile

  • Flutter multi-piattaforma; comandi npm run dev:mobile, npm run build:mobile; usa API Gateway e Socket.IO per realtime (configurare endpoints/namespaces in lib/).

Modelli dati chiave (Mongo)

  • User: email, username, password hash, first/last name, DOB, gender, phone, location 2dsphere, ruoli, isVerified/isActive, loginAttempts/lockUntil, passwordChangedAt, passwordResetToken/Expires, emailVerificationToken/Expires, lastLogin.
  • Profile: bio, avatar variants, social links, interests/tags, visibility, language, timezone, badges/achievements.
  • Preferences: notification toggles per canale, categorie preferite, radius geolocalizzazione, safe content filter, language, privacy flags.
  • Event: titolo/slug, descrizioni, categoria/subcategoria, organizer/coOrganizers, schedule, venue/coords, media, ticketing (types, price, capacity, fees), attendees (status), waitlist, social likes/comments/saves, analytics (views/unique/purchases/cancellations), status/visibility, moderation.
  • Category/Venue: slug, nome, descrizione; venue con address, coords, capacity, owner.
  • Social: Group (owner, members, privacy, tags), Post (author, content, media, visibility, likes/comments), Connection (from/to, stato, tipo follow/friend), Notification (per azioni social).
  • Notification: Template (name, channel, subject/body, placeholders), NotificationJob (payload, channel, status, retry), UserPreference (channel flags).
  • Realtime: Room, Message, Presence documents (controllare src/models in realtime-service per dettagli quando popolati).

Configurazione ed env principali

  • Porte: API_GATEWAY_PORT=3000, USER_SERVICE_PORT=3001, EVENT_SERVICE_PORT=3002, SOCIAL_SERVICE_URL=http://localhost:3003, NOTIFICATION_SERVICE_URL=http://localhost:3004 (o PORT nel servizio), REALTIME_SERVICE_URL=http://localhost:3005, RECOMMENDATION_ENGINE_URL=http://localhost:8001, MATCHMAKING_SERVICE_URL=http://localhost:8002.
  • JWT: JWT_SECRET, JWT_ACCESS_EXPIRY, JWT_REFRESH_EXPIRY, JWT_ISSUER/AUDIENCE (gateway + user-service).
  • Mongo: MONGODB_URI (specifici per servizio: flow_db, flow_events, flow_realtime), opzioni pool/timeouts in config.*.js.
  • Redis: REDIS_HOST, REDIS_PORT, REDIS_PASSWORD, REDIS_DB (user-service usa db0, event-service db1, altri configurabili).
  • Email/Push/SMS: SENDGRID_API_KEY o provider, SENDGRID_FROM_EMAIL, TWILIO creds, FCM service account, WEB_PUSH keys.
  • File upload: MAX_FILE_SIZE (default 10MB), ALLOWED_MIME_TYPES, uploadPath per avatar/templates.
  • Feature flags: FEATURE_* in user-service (registration, emailVerification, 2FA, analytics), ENABLE_* nel notification-service per canali.
  • Swagger: SWAGGER_ENABLED=true/false (gateway, user-service).
  • Dev utility: SKIP_EXTERNALS=true (event/social) per saltare connessioni esterne in locale.

Comandi build/test/lint

  • Root: npm install; npm run install:backend; npm run install:ai (pip); npm run dev (gateway+backend+ai); npm run build; npm test; npm run docker:build && npm run docker:up.
  • backend/api-gateway: npm run dev | npm test | npm run lint | npm run format.
  • backend/user-service: npm run dev | npm test | npm run lint | npm run format; start richiede Mongo+Redis.
  • backend/event-service: npm run dev | npm test | npm run lint | npm run format; SKIP_EXTERNALS per test locali.
  • backend/social-service: npm run dev | npm test | npm run lint | npm run format.
  • backend/notification-service: npm run dev | npm test | npm run lint | npm run seed/migrate; dipendenze FCM/Twilio/SendGrid.
  • backend/realtime-service: npm run dev | npm test | npm run lint.
  • ai-services: python -m uvicorn main:app —reload —port 8001/8002; pytest per test; requirements.txt in radice ai-services/.
  • admin-portal: npm install; npm run dev; npm run test (Vitest); npx playwright test.
  • mobile: flutter run | flutter build apk/ios; flutter test; flutter analyze.

Osservabilita e sicurezza

  • Health: /health in ogni servizio; gateway inoltre espone /health; monitorare stati Mongo/Redis/email (event-service health integra checks se SKIP_EXTERNALS=false).
  • Logging: morgan combinato nei servizi HTTP; winston rotazione file in notification-service (logs/); correlation-id propagato dal gateway; request timing in event/social.
  • Rate limiting: gateway e user-service 100 req/15min (configurabile), speedLimiter su 50% della soglia; notification-service usa store Redis per rate limit.
  • Sicurezza: Helmet + CSP, HSTS (gateway/user), sanitize NoSQL/XSS, HPP, cookie secure in produzione, upload mime whitelist, session secret e bcrypt rounds configurabili.
  • Tracing: header x-correlation-id generato dal gateway, inoltrato ai servizi; logger usa questo id.

Deployment e container

  • Docker: docker-compose.yml standard, compose.dev/prod; servizi su porte host 3000-3005, 8001-8002; dipendenze Mongo/Redis definite in compose (controllare file).
  • Vercel: admin-portal predisposto per deploy su Vercel (vercel.json).
  • Supabase: richiede progetto e chiavi impostate; tenere sincronizzato schema in supabase/.

Rischi e TODO aperti

  • Servizi AI sono placeholder: implementare pipeline di raccomandazione e matchmaking, definire contratti API e integrazione col social/event data.
  • Mismatch porte notification-service (PORT 3003 vs gateway 3004): decidere porta definitiva e allineare env/compose.
  • Doppio set modelli Mongo/SQL nel user-service: definire strategia di migrazione o rimuovere duplicati.
  • Documentazione API incompleta: estendere Swagger per tutti i microservizi e per websocket events.
  • Testing: copertura non verificata; aggiungere integrazione automatizzata per health e rate limiting, e2e Playwright per admin portal.
  • Mobile: documentare configurazione endpoints e Socket.IO namespace per l’app Flutter.

Percorsi utili

  • API Gateway: backend/api-gateway/src/server.js, config/config.js, middleware/auth.js.
  • User: backend/user-service/src/server.js, config/config.js, models/User.js, routes/auth.js|users.js|profiles.js|preferences.js.
  • Eventi: backend/event-service/src/app.js, models/Event.js|Category.js|Venue.js, services/cacheService.js|analyticsService.js.
  • Social: backend/social-service/src/app.js, routes/groupRoutes.js|connectionRoutes.js|postRoutes.js, models directory.
  • Notifiche: backend/notification-service/server.js, src/routes, src/services (workers), src/config/index.js, logs/.
  • Realtime: backend/realtime-service/server.js, src/events, src/middleware/socketAuth.js, src/config/index.js.
  • Admin portal: admin-portal/app, admin-portal/proxy.ts, admin-portal/docs.
  • Supabase: supabase/ (schema/migrazioni).

Fine del documento.