# Performance Testing Scripts

Quick reference for performance testing and monitoring.

---

## Quick Start

### Test Current Server Performance
```bash
# Quick check (recommended)
curl -w "Time: %{time_total}s\n" -o /dev/null -s http://localhost:10000/

# Comprehensive test
python scripts/performance_test.py

# Shell script (Unix/Mac)
bash scripts/quick-perf-check.sh
```

---

## Available Scripts

### 1. `performance_test.py`
**Purpose:** Comprehensive Python-based performance testing

**Usage:**
```bash
python scripts/performance_test.py
```

**Features:**
- Tests multiple endpoints (pages + APIs)
- Statistical analysis (mean, median, std dev)
- Domain verification
- Performance recommendations
- JSON output support

**Output:**
- Response time statistics per endpoint
- Overall performance summary
- Recommendations for slow endpoints
- Pass/fail status

---

### 2. `quick-perf-check.sh`
**Purpose:** Fast performance spot-check

**Usage:**
```bash
# Default (localhost:10000)
bash scripts/quick-perf-check.sh

# Custom URL
bash scripts/quick-perf-check.sh https://workroot.in
```

**Features:**
- Quick response time checks
- Color-coded status indicators
- Minimal dependencies (just curl)
- Production-ready

---

### 3. `lighthouse_audit.py`
**Purpose:** Lighthouse performance audit

**Usage:**
```bash
python scripts/lighthouse_audit.py <url>

# Example
python scripts/lighthouse_audit.py http://localhost:10000
```

**Features:**
- Full Lighthouse audit
- Performance, accessibility, SEO scores
- Best practices analysis
- Detailed issue reporting

**Note:** May have encoding issues on Windows. Use WSL or fix Unicode output.

---

## Performance Targets

| Metric | Excellent | Good | Needs Work |
|--------|-----------|------|------------|
| **SSR Page Load** | < 200ms | < 500ms | > 500ms |
| **API Response** | < 100ms | < 200ms | > 200ms |
| **TTFB** | < 200ms | < 300ms | > 300ms |

---

## Core Web Vitals (Production)

| Metric | Good | Needs Improvement | Poor |
|--------|------|-------------------|------|
| **LCP** | < 2.5s | 2.5s - 4.0s | > 4.0s |
| **INP** | < 200ms | 200ms - 500ms | > 500ms |
| **CLS** | < 0.1 | 0.1 - 0.25 | > 0.25 |

---

## Manual Testing with curl

### Basic Response Time
```bash
curl -w "\nTime: %{time_total}s\n" -o /dev/null -s http://localhost:10000/
```

### Detailed Timing
```bash
curl -w "\n
Total Time: %{time_total}s
DNS Lookup: %{time_namelookup}s
TCP Connect: %{time_connect}s
TLS Handshake: %{time_appconnect}s
Time to First Byte: %{time_starttransfer}s
HTTP Code: %{http_code}
\n" -o /dev/null -s http://localhost:10000/
```

### Test Multiple Endpoints
```bash
for endpoint in / /contact /about /api/health.json; do
  echo "Testing $endpoint"
  curl -w "Time: %{time_total}s\n" -o /dev/null -s http://localhost:10000$endpoint
  echo ""
done
```

---

## CI/CD Integration

### GitHub Actions Example
```yaml
- name: Performance Test
  run: |
    npm run build
    npm run preview &
    sleep 5
    python scripts/performance_test.py
```

### Pre-deployment Check
```bash
# Build and test
npm run build
npm run preview &
sleep 5
python scripts/performance_test.py

# If all tests pass, deploy
if [ $? -eq 0 ]; then
  echo "Performance tests passed"
  # Deploy command here
else
  echo "Performance tests failed"
  exit 1
fi
```

---

## Troubleshooting

### Slow Response Times (> 500ms)

**Possible Causes:**
1. Development server (not optimized)
2. Cold start (first request)
3. Large bundle size
4. Unoptimized images
5. Missing caching

**Solutions:**
```bash
# 1. Build for production
npm run build

# 2. Analyze bundle
npm run build -- --analyze

# 3. Check bundle size
du -sh dist/

# 4. Test production build
npm run preview
```

### High Variance in Response Times

**Possible Causes:**
1. Network issues
2. System load
3. Garbage collection
4. Cache inconsistency

**Solutions:**
- Run multiple iterations (10+)
- Test during low system load
- Close other applications
- Clear caches between tests

---

## Monitoring in Production

### Recommended Tools
- **DataDog RUM:** Real User Monitoring
- **New Relic:** Application Performance Monitoring
- **Google Analytics:** Core Web Vitals
- **Sentry:** Performance tracking + errors

### Custom Performance Monitoring
```javascript
// Add to your app
if (typeof window !== 'undefined') {
  window.addEventListener('load', () => {
    const perfData = performance.getEntriesByType('navigation')[0];
    console.log('Page Load Time:', perfData.loadEventEnd - perfData.fetchStart, 'ms');
    console.log('DOM Interactive:', perfData.domInteractive - perfData.fetchStart, 'ms');
    console.log('TTFB:', perfData.responseStart - perfData.requestStart, 'ms');
  });
}
```

---

## Best Practices

1. **Test Regularly:** Run performance tests before each deployment
2. **Set Baselines:** Document baseline performance metrics
3. **Monitor Trends:** Track performance over time
4. **Test Production:** Dev server performance != production performance
5. **Real Users:** Use RUM to understand actual user experience
6. **Set Budgets:** Define performance budgets and enforce them

---

## Resources

- [Web.dev Performance](https://web.dev/performance/)
- [Lighthouse Scoring](https://web.dev/performance-scoring/)
- [Core Web Vitals](https://web.dev/vitals/)
- [Astro Performance](https://docs.astro.build/en/guides/performance/)

---

## Quick Reference

```bash
# Test homepage
curl -w "%{time_total}s\n" -o /dev/null -s http://localhost:10000/

# Comprehensive test
python scripts/performance_test.py

# Lighthouse audit
npx lighthouse http://localhost:10000 --view

# Bundle analysis
npm run build -- --analyze
```
