# 🚀 Microservices Deployment Fix Guide

## 🔍 Issues Identified

### 1. N8N Service Failure (Exit Code 1)
- **Root Cause**: Database schema conflicts and timing issues
- **Symptoms**: `pipeline_n8n` container exits with code 1

### 2. PostgreSQL Constraint Violations
- **Root Cause**: Duplicate type/table creation attempts
- **Error**: `duplicate key value violates unique constraint "pg_type_typname_nsp_index"`

## 🛠️ Solutions Implemented

### 1. Enhanced N8N Configuration
- Added dedicated `n8n` schema
- Improved health checks with longer start period
- Added restart policy and better logging
- Ensured proper dependency ordering

### 2. Database Schema Cleanup
- Created schema conflict resolution script
- Proper table ownership and permissions
- Separated n8n tables into dedicated schema

### 3. Deployment Orchestration
- Staged service startup to prevent race conditions
- Proper dependency management
- Volume cleanup for fresh starts

## 🚀 Deployment Steps

### Option 1: Automated Fix (Recommended)
```bash
cd /home/tech4biz/Desktop/Projectsnew/CODENUK1/codenuk-backend-live
./scripts/fix-deployment-issues.sh
```

### Option 2: Manual Step-by-Step

#### Step 1: Clean Environment
```bash
# Stop all services
docker-compose down --volumes --remove-orphans

# Clean Docker system
docker system prune -f
docker volume prune -f

# Remove problematic volumes
docker volume rm codenuk-backend-live_postgres_data 2>/dev/null || true
docker volume rm codenuk-backend-live_n8n_data 2>/dev/null || true
```

#### Step 2: Start Core Infrastructure
```bash
# Start databases first
docker-compose up -d postgres redis mongodb rabbitmq

# Wait for readiness
sleep 30
```

#### Step 3: Fix Database Schema
```bash
# Apply schema fixes
docker exec -i pipeline_postgres psql -U pipeline_admin -d dev_pipeline < databases/scripts/fix-schema-conflicts.sql
```

#### Step 4: Run Migrations
```bash
docker-compose up migrations
```

#### Step 5: Start Services in Stages
```bash
# Stage 1: Core services
docker-compose up -d n8n api-gateway requirement-processor

# Stage 2: Generation services  
docker-compose up -d tech-stack-selector architecture-designer code-generator

# Stage 3: User services
docker-compose up -d user-auth template-manager

# Stage 4: Additional services
docker-compose up -d ai-mockup-service git-integration web-dashboard
```

## 🏥 Health Verification

### Check Service Status
```bash
docker-compose ps
```

### Check N8N Specifically
```bash
# Check n8n logs
docker-compose logs n8n

# Test n8n endpoint
curl -f http://localhost:5678/healthz
```

### Check Database
```bash
# Connect to database
docker exec -it pipeline_postgres psql -U pipeline_admin -d dev_pipeline

# List schemas
\dn

# Check n8n tables
\dt n8n.*
```

## 🔧 Troubleshooting

### If N8N Still Fails
1. Check logs: `docker-compose logs n8n`
2. Verify database connection: `docker exec pipeline_postgres pg_isready`
3. Check n8n schema exists: `docker exec -it pipeline_postgres psql -U pipeline_admin -d dev_pipeline -c "\dn"`

### If Database Conflicts Persist
1. Run schema cleanup again: `docker exec -i pipeline_postgres psql -U pipeline_admin -d dev_pipeline < databases/scripts/fix-schema-conflicts.sql`
2. Check for remaining conflicts: `docker-compose logs postgres | grep ERROR`

### If Services Won't Start
1. Check dependencies: `docker-compose config --services`
2. Start services individually: `docker-compose up [service-name]`
3. Check resource usage: `docker stats`

## 📊 Expected Results

After successful deployment:
- ✅ All services should show "Up" status
- ✅ N8N accessible at http://localhost:5678
- ✅ No database constraint errors
- ✅ All health checks passing

## 🎯 Key Improvements Made

1. **N8N Configuration**:
   - Dedicated schema isolation
   - Better dependency management
   - Improved health checks
   - Restart policies

2. **Database Management**:
   - Schema conflict resolution
   - Proper table ownership
   - Clean migration process

3. **Deployment Process**:
   - Staged service startup
   - Volume cleanup
   - Dependency ordering

## 📞 Support

If issues persist:
1. Check service logs: `docker-compose logs [service-name]`
2. Verify network connectivity: `docker network ls`
3. Check resource usage: `docker system df`
4. Review configuration: `docker-compose config`

---
**Last Updated**: September 30, 2025  
**Build Number**: 24+ (Fixed)  
**Status**: ✅ Ready for Deployment
