Skip to content

Instantly share code, notes, and snippets.

@SyNeto
Created November 22, 2025 18:22
Show Gist options
  • Select an option

  • Save SyNeto/acdcb92615fa64b95412bb8683b672d5 to your computer and use it in GitHub Desktop.

Select an option

Save SyNeto/acdcb92615fa64b95412bb8683b672d5 to your computer and use it in GitHub Desktop.
Splenda Infrastructure: Local Deployment Monitoring Options

Opciones de Monitoreo Local para Despliegues de Infraestructura

Contexto

Para el proyecto Splenda CMS, tenemos workflows de CI/CD que despliegan ambientes ephemeral y staging. Actualmente monitoreamos desde GitHub web o usando gh run list. Aquí están las opciones para mejorar el monitoreo local.


Opción 1: GitHub CLI con watch (Más simple)

Ventajas: Zero setup, usa herramientas existentes
Desventajas: Interfaz básica, sin notificaciones

Comandos útiles:

# Monitorear runs en tiempo real (actualiza cada 5 segundos)
watch -n 5 'gh run list --limit 5'

# Ver logs de un run específico en tiempo real
gh run watch <run-id>

# Ver logs del último run
gh run view --log

# Monitorear runs filtrados por workflow
gh run list --workflow=ephemeral-deploy.yml --limit 3

# Ver estado de un PR específico
gh pr checks 45

Ejemplo de uso:

# Terminal 1: Monitorear infrastructure deploys
cd ~/Projects/splenda/infraestructure
watch -n 5 'gh run list --limit 5 --json status,conclusion,name,createdAt | jq -r ".[] | \"\(.status) | \(.conclusion // \"running\") | \(.name)\""'

# Terminal 2: Monitorear CMS triggers
cd ~/Projects/splenda/cms
watch -n 5 'gh run list --workflow=deploy-trigger.yml --limit 3'

Opción 2: Script personalizado con notificaciones (Recomendado)

Ventajas: Notificaciones del sistema, logs en tiempo real, información contextual
Desventajas: Requiere desarrollo inicial

Características:

  • ✅ Monitorea múltiples repos simultáneamente
  • ✅ Notificaciones macOS cuando termina un deploy
  • ✅ Muestra URL del ambiente cuando está listo
  • ✅ Colorea output según status (verde=success, rojo=failure)
  • ✅ Opción de seguir logs en vivo del último deployment

Estructura propuesta:

~/bin/splenda-monitor

Script básico:

#!/bin/bash
# ~/bin/splenda-monitor

INFRA_REPO="CoreMemorySquad/cms_infrastructure"
CMS_REPO="CoreMemorySquad/splenda_cms"

function notify() {
  osascript -e "display notification \"$2\" with title \"$1\""
}

function check_deployments() {
  # Último deployment en infrastructure
  INFRA_RUN=$(gh run list -R $INFRA_REPO --limit 1 --json status,conclusion,name,url --jq '.[0]')
  
  # Extraer info
  STATUS=$(echo $INFRA_RUN | jq -r '.status')
  CONCLUSION=$(echo $INFRA_RUN | jq -r '.conclusion // "running"')
  NAME=$(echo $INFRA_RUN | jq -r '.name')
  URL=$(echo $INFRA_RUN | jq -r '.url')
  
  # Mostrar en terminal con colores
  if [ "$STATUS" = "completed" ]; then
    if [ "$CONCLUSION" = "success" ]; then
      echo -e "\033[0;32m✅ $NAME - SUCCESS\033[0m"
      notify "Deployment Success" "$NAME completed successfully"
    else
      echo -e "\033[0;31m❌ $NAME - FAILED\033[0m"
      notify "Deployment Failed" "$NAME failed. Check logs."
    fi
  else
    echo -e "\033[0;33m⏳ $NAME - RUNNING\033[0m"
  fi
  
  echo "   $URL"
}

# Loop infinito con intervalo
while true; do
  clear
  echo "=== Splenda Infrastructure Monitor ==="
  echo "$(date '+%Y-%m-%d %H:%M:%S')"
  echo ""
  check_deployments
  echo ""
  echo "Press Ctrl+C to stop monitoring"
  sleep 10
done

Instalación:

chmod +x ~/bin/splenda-monitor
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc

Uso:

# Iniciar monitor
splenda-monitor

# En otra terminal, trabajar normalmente
cd ~/Projects/splenda/cms
# ... hacer cambios, commits, etc

Opción 3: TUI (Terminal UI) personalizado

Ventajas: Interfaz rica, interactiva, múltiples paneles
Desventajas: Mayor complejidad de desarrollo

Herramientas recomendadas:

  • Python + Rich: Para TUI moderno con tablas y paneles
  • Node.js + Blessed: Para dashboard interactivo

Características propuestas:

┌─────────────────────────────────────────────────────────┐
│ Splenda Infrastructure Monitor                         │
├─────────────────────────────────────────────────────────┤
│ Active Environments:                                    │
│  • pr-45 (ephemeral) - https://pr-45-testing.ernjv.me  │
│    Status: ✅ Running | Database: pr_45               │
│    Last deploy: 5 minutes ago                          │
│                                                         │
│ Recent Deployments:                                     │
│  ✅ Deploy Ephemeral - pr-45 (2 min ago)              │
│  ❌ Deploy Ephemeral - pr-44 (15 min ago)             │
│  ✅ Deploy Staging - main (1 hour ago)                │
│                                                         │
│ Actions: [D]eploy [R]efresh [L]ogs [Q]uit             │
└─────────────────────────────────────────────────────────┘

Implementación con Rich (Python):

#!/usr/bin/env python3
# ~/bin/splenda-tui

from rich.console import Console
from rich.table import Table
from rich.live import Live
import subprocess
import json
import time

def get_runs():
    result = subprocess.run(
        ['gh', 'run', 'list', '-R', 'CoreMemorySquad/cms_infrastructure', 
         '--limit', '5', '--json', 'status,conclusion,name,createdAt'],
        capture_output=True, text=True
    )
    return json.loads(result.stdout)

def create_table():
    table = Table(title="Splenda Deployments")
    table.add_column("Status", style="cyan")
    table.add_column("Name", style="magenta")
    table.add_column("Time", style="green")
    
    for run in get_runs():
        status = "✅" if run['conclusion'] == 'success' else "❌" if run['conclusion'] == 'failure' else "⏳"
        table.add_row(status, run['name'], run['createdAt'])
    
    return table

with Live(create_table(), refresh_per_second=0.2) as live:
    while True:
        time.sleep(5)
        live.update(create_table())

Opción 4: Dashboard web local

Ventajas: Visualización rica, accesible desde cualquier dispositivo en la red
Desventajas: Mayor complejidad, requiere servidor corriendo

Stack propuesto:

  • Backend: Express.js + Socket.io (real-time updates)
  • Frontend: React + Tailwind
  • API: GitHub API via Octokit

Características:

  • 📊 Métricas de deployments (success rate, tiempo promedio)
  • 🗺️ Vista de todos los ambientes activos en un mapa
  • 📝 Logs en tiempo real con syntax highlighting
  • 🔔 Notificaciones web push
  • 📱 Responsive para móvil

Estructura:

~/Projects/splenda/monitor-dashboard/
├── server/
│   ├── index.js          # Express server
│   ├── github-client.js  # GitHub API wrapper
│   └── socket-handler.js # WebSocket events
├── client/
│   ├── src/
│   │   ├── App.jsx
│   │   ├── components/
│   │   │   ├── DeploymentList.jsx
│   │   │   ├── EnvironmentCard.jsx
│   │   │   └── LogViewer.jsx
│   │   └── hooks/
│   │       └── useDeployments.js
│   └── package.json
└── package.json

Demo de inicio:

cd ~/Projects/splenda/monitor-dashboard
npm start
# Abre http://localhost:3000

Opción 5: VSCode Extension

Ventajas: Integrado en el editor, no cambia workflow
Desventajas: Solo funciona en VSCode, desarrollo más complejo

Características:

  • 📍 Status bar item mostrando estado de último deploy
  • 🔔 Notifications cuando termina un deployment
  • 📂 Panel lateral con árbol de ambientes
  • ⚡ Comandos rápidos (Deploy, Destroy, Open URL)
  • 📝 Output channel con logs en tiempo real

Comandos propuestos:

  • Splenda: Deploy to Ephemeral
  • Splenda: Deploy to Staging
  • Splenda: Destroy Environment
  • Splenda: Open Environment URL
  • Splenda: View Deployment Logs

Configuración en settings.json:

{
  "splenda.autoRefresh": true,
  "splenda.refreshInterval": 30,
  "splenda.notifications": true,
  "splenda.repositories": {
    "infrastructure": "CoreMemorySquad/cms_infrastructure",
    "cms": "CoreMemorySquad/splenda_cms"
  }
}

Comparación de opciones

Opción Complejidad Setup Time Features Recomendado para
1. gh CLI + watch 🟢 Baja 0 min Básico Quick checks
2. Script + notifs 🟡 Media 15 min Bueno Día a día ⭐
3. TUI 🟡 Media 1-2 horas Excelente Power users
4. Web Dashboard 🔴 Alta 4-8 horas Premium Equipos grandes
5. VSCode Ext 🔴 Alta 8-16 horas Integrado VSCode users

Recomendación inicial: Opción 2 (Script con notificaciones)

Por qué:

  1. Rápido de implementar (~15 minutos)
  2. No invasivo - corre en background, notifica cuando necesitas
  3. Flexible - fácil de extender con más features
  4. Portable - shell script funciona en cualquier Mac/Linux

Roadmap sugerido:

  1. Hoy: Implementar script básico con notificaciones
  2. Semana 1: Agregar parsing de URLs de ambientes desde comentarios del PR
  3. Semana 2: Agregar seguimiento de múltiples PRs simultáneos
  4. Futuro: Evolucionar a TUI si se necesita más interactividad

Implementación completa del script recomendado

#!/bin/bash
# ~/bin/splenda-monitor
# Monitorea deployments de Splenda Infrastructure y envía notificaciones

set -euo pipefail

# Configuración
INFRA_REPO="CoreMemorySquad/cms_infrastructure"
CMS_REPO="CoreMemorySquad/splenda_cms"
CHECK_INTERVAL=15
STATE_FILE="/tmp/splenda-monitor-state.json"

# Colores
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Funciones de utilidad
function notify() {
  local title="$1"
  local message="$2"
  osascript -e "display notification \"$message\" with title \"$title\" sound name \"Glass\""
}

function log_info() {
  echo -e "${BLUE}${NC} $1"
}

function log_success() {
  echo -e "${GREEN}${NC} $1"
}

function log_error() {
  echo -e "${RED}${NC} $1"
}

function log_warning() {
  echo -e "${YELLOW}${NC} $1"
}

# Obtener último run de infrastructure
function get_latest_run() {
  gh run list -R "$INFRA_REPO" --limit 1 --json databaseId,status,conclusion,name,url,createdAt,updatedAt
}

# Extraer URL del ambiente desde comentarios del PR
function get_environment_url() {
  local pr_number="$1"
  local comment=$(gh pr view "$pr_number" -R "$CMS_REPO" --json comments --jq '.comments[-1].body' 2>/dev/null || echo "")
  
  # Buscar URL del ambiente en el comentario
  if echo "$comment" | grep -q "Environment Deployed"; then
    echo "$comment" | grep -oE 'https://[a-z0-9-]+\.testing\.ernjv\.me' | head -1
  else
    echo ""
  fi
}

# Estado previo
function load_state() {
  if [ -f "$STATE_FILE" ]; then
    cat "$STATE_FILE"
  else
    echo '{"last_run_id":"","last_status":""}'
  fi
}

function save_state() {
  echo "$1" > "$STATE_FILE"
}

# Monitor principal
function monitor() {
  local prev_state=$(load_state)
  local prev_run_id=$(echo "$prev_state" | jq -r '.last_run_id')
  
  while true; do
    clear
    echo -e "${BLUE}╔══════════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}${NC}  Splenda Infrastructure Monitor            ${BLUE}${NC}"
    echo -e "${BLUE}╚══════════════════════════════════════════════╝${NC}"
    echo ""
    echo "$(date '+%Y-%m-%d %H:%M:%S')"
    echo ""
    
    # Obtener último run
    local run_data=$(get_latest_run)
    local run_id=$(echo "$run_data" | jq -r '.[0].databaseId')
    local status=$(echo "$run_data" | jq -r '.[0].status')
    local conclusion=$(echo "$run_data" | jq -r '.[0].conclusion // "running"')
    local name=$(echo "$run_data" | jq -r '.[0].name')
    local url=$(echo "$run_data" | jq -r '.[0].url')
    local created_at=$(echo "$run_data" | jq -r '.[0].createdAt')
    
    # Mostrar estado actual
    echo "Latest Deployment:"
    echo "  Name: $name"
    echo "  ID: $run_id"
    
    if [ "$status" = "completed" ]; then
      if [ "$conclusion" = "success" ]; then
        log_success "Status: SUCCESS"
        
        # Notificar si es un nuevo deployment exitoso
        if [ "$run_id" != "$prev_run_id" ]; then
          notify "Deployment Success" "$name completed successfully"
          
          # Intentar obtener URL del ambiente
          if echo "$name" | grep -q "Ephemeral"; then
            pr_number=$(echo "$name" | grep -oE 'pr-[0-9]+' | grep -oE '[0-9]+' || echo "")
            if [ -n "$pr_number" ]; then
              env_url=$(get_environment_url "$pr_number")
              if [ -n "$env_url" ]; then
                log_info "Environment: $env_url"
                # Copiar URL al clipboard
                echo "$env_url" | pbcopy
                log_success "URL copied to clipboard!"
              fi
            fi
          fi
        fi
      else
        log_error "Status: FAILED"
        
        # Notificar si es un nuevo deployment fallido
        if [ "$run_id" != "$prev_run_id" ]; then
          notify "Deployment Failed" "$name - Check logs for details"
        fi
      fi
    else
      log_warning "Status: RUNNING"
    fi
    
    echo "  URL: $url"
    echo "  Created: $created_at"
    echo ""
    echo -e "${BLUE}════════════════════════════════════════════════${NC}"
    echo "Refreshing every ${CHECK_INTERVAL}s | Press Ctrl+C to stop"
    
    # Guardar estado
    save_state "{\"last_run_id\":\"$run_id\",\"last_status\":\"$conclusion\"}"
    
    sleep "$CHECK_INTERVAL"
  done
}

# Cleanup al salir
trap 'echo ""; log_info "Monitoring stopped"; exit 0' INT TERM

# Main
log_info "Starting Splenda Infrastructure Monitor..."
monitor

Instalación y uso:

# 1. Crear script
mkdir -p ~/bin
nano ~/bin/splenda-monitor
# (pegar el script)

# 2. Dar permisos
chmod +x ~/bin/splenda-monitor

# 3. Agregar a PATH si no está
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc

# 4. Ejecutar
splenda-monitor

Próximos pasos

  1. Probar script básico (Opción 2)
  2. Iterar según feedback
  3. Considerar TUI (Opción 3) si se necesita más interactividad
  4. Documentar en CLAUDE.md o ADR si se vuelve crítico para el workflow

Generado: 2025-11-22
Proyecto: Splenda CMS Infrastructure
Repositorio: CoreMemorySquad/cms_infrastructure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment