Skip to content

Logiflow-Gavilanes-ECI/logiflow

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

251 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

LogiFlow

LogiFlow β€” Backend Monorepo

Real-time dynamic fleet routing platform Β· cloud-native Β· 9 microservices Β· 245 story points

Live Demo API Docs Architecture PDF IEEE Article

CI Deploy Coverage Tests Uptime License


What is this?

LogiFlow is a distributed cloud-native platform that solves the Vehicle Routing Problem (VRP) in under 4 seconds when traffic events disrupt the day. Dispatchers see vehicles on a live map; drivers receive optimized routes on their Android app the instant a route closes or a new order arrives.

Built by four engineering students across 10 sprints with 245 story points delivered. Currently running on Azure with full Terraform-managed infrastructure.

Key metrics (production)

Metric Value
Latency P95 (50 users) 2.81 s
Throughput sostenible 20.98 TPS
Infrastructure uptime 99.79 %
End-to-end test coverage 83.36 %
Total story points 245
Sprints delivered 10
Microservices 9
LOC to migrate to another cloud 0

End-to-End Flow

flowchart LR
    A([🌐 Traffic Event<br/>External webhook]) --> B[πŸ”§ n8n<br/>Automation]
    B -->|HTTPS + JWT| C[πŸšͺ Gateway<br/>NestJS]
    C -->|gRPC| D[βš™οΈ Optimizer<br/>Node.js]
    D -->|HTTP| E[🧭 VROOM<br/>VRP Engine]
    D -.->|optional<br/>HTTP POST| F[πŸ€– AI Predictor<br/>Python/Flask]
    D -->|SET key| G[(πŸ’Ύ Redis<br/>route:vehicle:*)]
    C -->|pub/sub| H[πŸ“‘ Realtime<br/>Socket.io]
    H -->|WSS| I([πŸ‘¨β€πŸ’Ό Dispatcher<br/>Web Admin])
    H -->|WSS| J([πŸš› Driver<br/>Mobile App])
    C -->|FCM| K([πŸ”” Push<br/>Notification])
    K --> J

    style A fill:#FF6B35,color:#fff
    style C fill:#E0234E,color:#fff
    style D fill:#1F3060,color:#fff
    style E fill:#00E5FF,color:#000
    style F fill:#3776AB,color:#fff
    style G fill:#DC382D,color:#fff
    style H fill:#010101,color:#fff
    style I fill:#22C55E,color:#fff
    style J fill:#22C55E,color:#fff
Loading
From traffic event detection to route delivered to the driver, in under 4 seconds.
πŸ“ Click for full architectural diagrams (Context, Components, Deployment, Sequence, ER, Class, Activity)

🎯 Context Diagram (C4 Level 1)

Context Diagram

🧩 Components Diagram (C4 Level 2–3)

Components Diagram

☁️ Deployment Diagram

Deployment Diagram

πŸ”„ Sequence Diagram β€” Reoptimization flow

Sequence Diagram

πŸ—ƒοΈ Entity-Relationship Diagram

ER Diagram

πŸ“¦ Class Diagram

Class Diagram

⚑ Activity Diagram

Activity Diagram


Navigation

πŸ—οΈ Services
9 microservices, ports & roles
πŸš€ Quick Start
Run the stack in 3 commands
πŸ”§ Environment
All env vars documented
πŸ€– CI/CD
Pipelines and deployment
πŸ“š Documentation
PDFs, slides, runbooks

Services Overview

Service Tech Port Role
πŸšͺ gateway NestJS 11 Β· Prisma 7 Β· PostgreSQL 3002 REST API Β· Google OAuth Β· JWT Β· webhooks Β· FCM
πŸ“‘ realtime Node.js Β· Socket.io 4 Β· Redis Adapter 3001 WebSocket server Β· live fleet tracking
βš™οΈ optimizer Node.js Β· gRPC Β· VROOM Β· Redis 50051 VRP route optimization (gRPC)
πŸ€– ai-predictor Python 3.12 Β· Flask 3.1 Β· gunicorn 5001 Traffic-aware travel time adjustments
🧭 vroom C++ VRP engine 3000 Internal · called by optimizer
πŸ—„οΈ postgres PostgreSQL 16 5432 Users Β· vehicles Β· stops Β· routes
πŸ’Ύ redis Redis 7 6379 Pub/sub Β· Socket.io adapter Β· route cache
πŸ”§ n8n n8n 1.66.0 5678 Workflow automation Β· webhook ingest
πŸ”” openclaw OpenClaw 2026.5.12 Β· Claude Sonnet 4 18789 AI-powered multi-channel notifications
πŸšͺ Gateway β€” REST API Β· Auth Β· Orchestration

NestJS REST API and single public entry point for all clients.

Responsibilities

  • Google OAuth 2.0 β€” sole authentication method (no email/password in production)
  • JWT access tokens (1h) + rotated refresh tokens (7-day TTL, stored as SHA-256 hash)
  • Role-based access: admin (dispatchers) and conductor (drivers)
  • Receives traffic webhooks, calls the optimizer over gRPC, broadcasts results via Socket.io, sends FCM push notifications
  • Vehicle and stop CRUD (admin only)

Notable endpoints

Method Path Auth Description
GET /api/v1/health Public Health check
GET /api/v1/auth/google Public Initiate Google OAuth (?app=admin|mobile|web)
GET /api/v1/auth/google/callback Public OAuth redirect handler
POST /api/v1/auth/google/token Public Exchange Google ID token (mobile)
POST /api/v1/auth/refresh Public Rotate refresh token
POST /api/v1/webhook JWT (admin) Receive traffic event, trigger optimization
GET/POST/PATCH/DELETE /api/v1/vehicles JWT Fleet management
GET/POST/PATCH/DELETE /api/v1/stops JWT Stop management
POST /api/v1/notifications/register-device JWT (conductor) Register FCM device token
GET /api/v1/docs Public Swagger UI
βš™οΈ Optimizer β€” gRPC VRP solver with AI travel-time adjustment

gRPC server that takes a Vehicle Routing Problem (VRP) payload, optionally adjusts travel times with the AI Predictor, calls VROOM, and persists route summaries to Redis.

Environment flags

Variable Dev default Description
MATRIX_SOURCE request request = use matrix from payload; google = call Google Routes API
GOOGLE_ROUTES_ALLOW_CALLS false Gate for live Google Routes API calls
GOOGLE_ROUTES_MOCK true Return mock matrix instead of real API
AI_PREDICTOR_ENABLED false Toggle AI travel-time adjustments
REDIS_ROUTE_TTL_SECONDS 3600 Route cache TTL in Redis

Prometheus metrics (port 9090 in production)

optimize_requests_total Β· optimize_duration_ms Β· vroom_failures_total Β· ai_predictor_failures_total Β· ai_breaker_state_changes Β· redis_failures_total Β· matrix_source_total

AI circuit breaker (opossum): 50% error threshold Β· 30s reset Β· min 5 volume.

πŸ“‘ Realtime β€” Socket.io server with Redis pub/sub

Socket.io server with Redis pub/sub adapter for multi-instance support.

Rooms

Room Clients Events received
fleet Web admin dashboard All fleet events
vehicle:<id> Driver mobile app route:update for that vehicle

Events emitted

Event Payload Direction
vehicle:position { vehicleId, lat, lng, speed } Realtime β†’ clients
route:update { vehicleId, stops[], polyline[], estimatedTime, totalDistance, eventType } Gateway β†’ realtime β†’ clients
vehicle:offline { vehicleId } Realtime β†’ clients
vehicle:online { vehicleId } Realtime β†’ clients
vehicle:status { vehicleId, status } Driver β†’ realtime β†’ fleet room
πŸ€– AI Predictor β€” BogotΓ‘ traffic congestion model

Flask service that applies traffic multipliers to a duration matrix based on time-of-day and road corridor.

Modeled corridors (BogotΓ‘)

Corridor Peak hours Multiplier
autopista_norte 07–09, 17–19 1.8Γ—
calle_80 07–09 1.6Γ—
carrera_7 12–14, 17–19 1.5Γ—

Weekends: no adjustment (1.0Γ—). Skips silently when AI_PREDICTOR_ENABLED=false.

πŸ”§ n8n + πŸ”” OpenClaw β€” Automation and multi-channel alerts

n8n auto-imports and activates workflow logiflow-traffic-event-trigger on startup. The workflow accepts a public webhook at POST /webhook/logiflow/traffic-event, authenticates with the gateway, and forwards the normalized payload to POST /api/v1/webhook.

OpenClaw runs a logiflow-notify skill that dispatches AI-generated alerts (Claude Sonnet 4) across 5 channels simultaneously:

Channel Required env var(s)
πŸ’¬ Telegram TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID
🟣 Discord DISCORD_WEBHOOK_URL
πŸ’Ό Slack SLACK_WEBHOOK_URL
πŸ“§ Email SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_TO
πŸ”₯ Firebase Push LOGIFLOW_GATEWAY_URL, LOGIFLOW_GATEWAY_TOKEN

Each channel skips silently when its env var is not set.


Quick Start

Prerequisites

  • Docker 24+ and Docker Compose v2
  • Free ports: 3000, 3001, 3002, 5001, 5432, 6379, 50051

Run the full stack

git clone https://github.com/Logiflow-Gavilanes-ECI/logiflow.git
cd logiflow
cp .env.example .env
docker compose up -d --build
docker compose ps

The gateway runs Prisma migrations and seeds the database on first boot.

πŸ”‘ Seed credentials (development only)

Email Password Role Vehicle
admin@logiflow.app Admin2026! admin β€”
conductor@logiflow.app Driver2026! conductor v-001
conductor2@logiflow.app Driver2026! conductor v-002

Optional β€” automation profile

docker compose --profile automation up -d

Adds n8n (:5678) and OpenClaw (:18789) to the running stack.

Verify

curl http://localhost:3002/api/v1/health
# β†’ {"status":"ok"}

Full API docs: http://localhost:3002/api/v1/docs


Environment Variables

πŸšͺ Gateway (services/gateway)
Variable Required Default Description
PORT No 3002 HTTP port
DATABASE_URL Yes β€” PostgreSQL connection string
JWT_SECRET Yes β€” JWT signing secret
JWT_EXPIRES_IN No 1h Access token TTL
REFRESH_TOKEN_TTL_MINUTES No 10080 Refresh token TTL (7 days)
GRPC_OPTIMIZER_HOST Yes β€” Optimizer hostname
GRPC_OPTIMIZER_PORT No 50051 Optimizer gRPC port
SOCKETIO_SERVER_HOST Yes β€” Realtime hostname
SOCKETIO_SERVER_PORT No 3001 Realtime port
CORS_ORIGINS No * Comma-separated allowed origins
GOOGLE_CLIENT_ID No* β€” Google OAuth client ID
GOOGLE_CLIENT_SECRET No* β€” Google OAuth client secret
GOOGLE_CALLBACK_URL No http://localhost:3002/api/v1/auth/google/callback OAuth redirect URI
GOOGLE_REDIRECT_FRONTEND No http://localhost:4200 Web app redirect after OAuth
GOOGLE_REDIRECT_FRONTEND_ADMIN No β€” Admin app redirect after OAuth
GOOGLE_REDIRECT_FRONTEND_MOBILE No http://localhost:8100 Mobile app redirect after OAuth
GOOGLE_ADMIN_EMAILS No β€” Comma-separated emails auto-assigned admin role
FIREBASE_PROJECT_ID No* β€” Firebase project ID (FCM push)
FIREBASE_CLIENT_EMAIL No* β€” Firebase service account email
FIREBASE_PRIVATE_KEY No* β€” Firebase private key (newlines as \n)

*Required only when the relevant feature is used. Gateway starts normally without them; Google OAuth returns 501, FCM push is skipped silently.

βš™οΈ Optimizer (services/optimizer)
Variable Default Description
GRPC_PORT 50051 gRPC listen port
VROOM_URL β€” VROOM HTTP endpoint
REDIS_URL β€” Redis connection URL
MATRIX_SOURCE request request or google
GOOGLE_ROUTES_ENABLED false Enable Google Routes integration
GOOGLE_ROUTES_ALLOW_CALLS false Allow live API calls
GOOGLE_ROUTES_MOCK true Use mock matrix response
AI_PREDICTOR_ENABLED false Enable AI travel-time adjustment
AI_PREDICTOR_URL β€” AI Predictor endpoint
AI_PREDICTOR_TIMEOUT_MS 3000 Per-request timeout
AI_BREAKER_ERROR_PCT 50 Circuit breaker error % threshold
AI_BREAKER_RESET_MS 30000 Circuit breaker reset timeout
AI_BREAKER_VOLUME 5 Minimum call volume for breaker
REDIS_ROUTE_TTL_SECONDS 3600 Route cache TTL
METRICS_PORT β€” Prometheus metrics port (prod: 9090)
SHUTDOWN_DEADLINE_MS 25000 Graceful shutdown deadline
πŸ”§ Automation (n8n / OpenClaw)
Variable Description
WEBHOOK_TARGET Gateway webhook URL
GATEWAY_AUTH_EMAIL Gateway admin login email
GATEWAY_AUTH_PASSWORD Gateway admin login password
GOOGLE_MAPS_API_KEY Google Maps API key for route display
ANTHROPIC_API_KEY Anthropic API key (OpenClaw AI)
TELEGRAM_BOT_TOKEN Telegram bot token
TELEGRAM_CHAT_ID Telegram target chat ID
DISCORD_WEBHOOK_URL Discord incoming webhook URL
SLACK_WEBHOOK_URL Slack incoming webhook URL
SMTP_HOST / SMTP_PORT / SMTP_USER / SMTP_PASS Email SMTP config
SMTP_FROM Sender address (LogiFlow Alerts <alerts@logiflow.app>)
SMTP_TO Recipient address
OPENCLAW_WEBHOOK_URL OpenClaw skill endpoint

Quality Attributes β€” Measured in Production

🎯 Performance

Concurrent users TPS P95 (ms) Error %
10 19.91 674 0.00
25 21.10 1,546 0.00
50 20.98 2,812 0.02
100 9.69* 5,245 51.82

*Effective TPS after failures Β· stability ceiling at 50 users (Azure D2s_v3 single VM)

⚑ Availability (Bass et al. β€” serial model)

A_cloud = 0.999 Γ— 0.9999 Γ— 0.999 = 99.79%
                ↓
        ~1.51 h/month downtime
        ~18.4 h/year downtime

A_total (cloud + custom software) β‰ˆ 96.83 %

Bottleneck: single VM. Architecture ready for Azure Load Balancer to reach 99.9 %.

πŸ›‘οΈ Security (3 STRIDE scenarios)

# Scenario Result
S1 JWT in WebSocket handshake 100% rejection in <5 ms
S2 Role-based authorization 0 cross-role accesses
S3 TLS + bcrypt + Refresh Token Rotation 0 plaintext in DB

πŸ§ͺ Maintainability

Repo Framework Coverage Tests
Backend Jest 83.36 % 70 βœ…
Frontend Karma 80.49 % 109 βœ…

Quality gate: 🟒 Verde in SonarCloud (both repos).


CI/CD

Continuous Integration

GitHub Actions runs on every push and pull request to main and develop. Four service jobs execute in parallel:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  automation β”‚   gateway   β”‚   realtime  β”‚  optimizer  β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
       β”‚             β”‚             β”‚             β”‚
       └──── npm ci ─┴──── npm run lint ─┴──── npm test (cov) ─┴── SonarCloud

Continuous Deployment

Merge to main β†’ CI green β†’ rsync to Azure VM β†’ docker compose up -d --build β†’ smoke test
  • Target VM: logiflow-api.eastus2.cloudapp.azure.com
  • Smoke test: polls GET /api/v1/health up to 8 times (15s intervals)
  • Required secrets: SSH_PRIVATE_KEY, SERVER_IP, SSH_USER

Infrastructure

The production environment runs on an Azure Virtual Machine behind Nginx with Let's Encrypt TLS, fully provisioned by Terraform.

Internet
   β”‚ HTTPS
   β–Ό
 Nginx (TLS termination)
   β”œβ”€β”€ /api/*        β†’ gateway:3002
   β”œβ”€β”€ /socket.io/*  β†’ realtime:3001
   └── /webhook/*    β†’ n8n:5678
  • IaC: Terraform (infra/terraform/) β€” VM, network, DNS, docker-compose.prod.yml and nginx.conf generated from templates
  • Frontend static site: Azure Blob Storage Static Website ($web container)
  • Deploy script: infra/scripts/deploy.sh
  • Prod FQDN: logiflow-api.eastus2.cloudapp.azure.com
Production-only differences vs dev compose
  • Redis requires password auth (--requirepass)
  • Resource limits (CPU/memory) on all containers
  • JSON-file log rotation
  • Prometheus metrics endpoint on optimizer (:9090)
  • AI_PREDICTOR_ENABLED=true, GOOGLE_ROUTES_ALLOW_CALLS=true

API Reference

Full Swagger UI available at:

gRPC Contract

The optimizer exposes a single RPC defined in shared/proto/optimizer.proto:

service RouteOptimizer {
  rpc OptimizeRoutes(OptimizeRequest) returns (OptimizeResponse);
}

Key message fields:

Message Fields
OptimizeRequest vehicles[], jobs[], shipments[], matrix, options, departureTime, correlationId
OptimizeResponse routes[], code, summary, matrixSource, aiAdjusted, correlationId
Vehicle id (string, e.g. v-001), startCoord, capacity, profile
Job id, location, service, amount[], priority, timeWindows[]

Testing

# Per-service tests
cd services/gateway && npm test
cd services/optimizer && npm test
cd services/realtime && npm test
cd services/automation && npm test

# With coverage
npm test -- --coverage

# Gateway only β€” run in band (DB tests)
npm test -- --runInBand

Current status: 13 test suites Β· 70 tests passing Β· 83.36% statements coverage

The gateway uses a full Prisma mock (__mocks__/prisma-client.mock.ts) β€” no real DB required for unit tests.


Documentation

All Release 2 deliverables live under docs/:

πŸ“„ Deliverable Format Description
πŸ“˜ Architecture Document PDF (40 pages) Full LaTeX architecture deliverable. Methodology, quality attributes, UML diagrams, sprint logbook. Source: .tex
πŸ“° IEEE Article PDF (5 pages, IEEEtran) Conference-style article: abstract, methodology, architecture, technical achievements, results. Source: .tex
πŸ“Š Defense Slides PowerPoint 18 slides covering problem, architecture, live demo, quality attributes, Scrum recap
πŸ“‹ Backend Demo Runbook Markdown Step-by-step reproducible demo against the deployed VM
🎨 UML Diagrams 7 Γ— PNG (300 DPI) Context, Components, Classes, ER, Sequence, Deployment, Activity

Compile LaTeX docs locally

cd docs/
pdflatex LogiFlow-architecture.tex && pdflatex LogiFlow-architecture.tex   # 2 passes for ToC
pdflatex LogiFlow-article.tex && pdflatex LogiFlow-article.tex             # 2 passes for refs

Project Structure

logiflow/
β”œβ”€β”€ .github/workflows/       CI + deploy pipelines
β”œβ”€β”€ docs/
β”‚   β”œβ”€β”€ LogiFlow-architecture.{tex,pdf}    πŸ“˜ Architecture document
β”‚   β”œβ”€β”€ LogiFlow-article.{tex,pdf}         πŸ“° IEEE article
β”‚   β”œβ”€β”€ LogiFlow-presentation.pptx         πŸ“Š Defense slides
β”‚   β”œβ”€β”€ backend-demo-runbook.md            πŸ“‹ Demo runbook
β”‚   └── diagrams/                          🎨 7 UML PNGs
β”œβ”€β”€ infra/
β”‚   β”œβ”€β”€ nginx/               Nginx config template
β”‚   β”œβ”€β”€ scripts/             Deploy script
β”‚   └── terraform/           IaC (VM, DNS, TLS, compose generation)
β”œβ”€β”€ services/
β”‚   β”œβ”€β”€ ai-predictor/        πŸ€– Python Flask traffic predictor
β”‚   β”œβ”€β”€ automation/          πŸ”§ n8n workflows + πŸ”” OpenClaw AI alerts
β”‚   β”œβ”€β”€ gateway/             πŸšͺ NestJS REST API
β”‚   β”œβ”€β”€ optimizer/           βš™οΈ gRPC + VROOM wrapper
β”‚   └── realtime/            πŸ“‘ Socket.io server
β”œβ”€β”€ shared/
β”‚   └── proto/               optimizer.proto (gRPC contract)
β”œβ”€β”€ docker-compose.yml       Development stack
β”œβ”€β”€ docker-compose.prod.yml  Production stack
└── .env.example             All variables documented

Team β€” Los Gavilanes del CΓ³digo


Andersson David
SΓ‘nchez MΓ©ndez

πŸ”§ Automation Β· CI/CD
n8n Β· OpenClaw

Cristian Santiago
Pedraza RodrΓ­guez

βš™οΈ Optimization
VROOM Β· gRPC Β· AI Predictor

Elizabeth
Correa SuΓ‘rez

πŸ“‘ Realtime Β· Frontend
Socket.io Β· Redis Β· Angular

Juan SebastiΓ‘n
Ortega MuΓ±oz

πŸšͺ Gateway Β· Auth
NestJS Β· Prisma Β· OAuth
Arquitecturas de Software (ARSW) Β· Escuela Colombiana de Ingenieria Julio Garavito Β· Mayo 2026

License

MIT License

MIT Β© 2026 LogiFlow β€” Escuela Colombiana de Ingenieria Julio Garavito


Made with β˜• and a lot of docker compose up -d by Los Gavilanes del CΓ³digo

About

Monorepo for an AI-powered real-time fleet routing platform. Dynamically solves the Vehicle Routing Problem via NestJS, gRPC, WebSockets, n8n automation, and VROOM optimization for Colombian logistics at scale.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages