# Deployment Checklist

Complete checklist for deploying the Server Recommendation System to Cloudflare Workers.

---

## Pre-Deployment Checklist

### Development Environment ✅
- [x] Node.js 18+ installed
- [x] Dependencies installed (`npm install`)
- [x] TypeScript compilation passes (`npm run typecheck`)
- [x] Code structure verified

### Cloudflare Account 
- [ ] Cloudflare account created/logged in
- [ ] Wrangler CLI authenticated (`npx wrangler login`)

---

## Step-by-Step Deployment

### Step 1: Create D1 Database (2 minutes)

```bash
# Create database
npx wrangler d1 create server-recommend-db
```

**Expected Output:**
```
✅ Successfully created DB 'server-recommend-db'!

[[d1_databases]]
binding = "DB"
database_name = "server-recommend-db"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
```

**Action Required:**
- [ ] Copy the `database_id` value
- [ ] Open `wrangler.toml`
- [ ] Replace empty `database_id = ""` with your actual ID
- [ ] Save file

---

### Step 2: Create KV Namespace (1 minute)

```bash
# Create KV namespace
npx wrangler kv:namespace create CACHE
```

**Expected Output:**
```
🌀 Creating namespace with title "server-recommend-CACHE"
✨ Success!
Add the following to your configuration file:

[[kv_namespaces]]
binding = "CACHE"
id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Action Required:**
- [ ] Copy the `id` value
- [ ] Open `wrangler.toml`
- [ ] Replace empty `id = ""` with your actual ID
- [ ] Save file

**Verify wrangler.toml:**
```toml
[[d1_databases]]
binding = "DB"
database_name = "server-recommend-db"
database_id = "YOUR_ACTUAL_DATABASE_ID"  # ← Should be filled

[[kv_namespaces]]
binding = "CACHE"
id = "YOUR_ACTUAL_KV_ID"  # ← Should be filled
```

---

### Step 3: Initialize Database (2 minutes)

```bash
# Create tables and indexes
npx wrangler d1 execute server-recommend-db --file=schema.sql
```

**Expected Output:**
```
🌀 Mapping SQL input into an array of statements
🌀 Executing on server-recommend-db (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx):
🚣 Executed 7 commands in X.XXXs
```

**Checklist:**
- [ ] Command executed successfully
- [ ] No errors in output
- [ ] Tables created (providers, servers, server_regions)
- [ ] Indexes created

**Verify:**
```bash
# Check tables
npx wrangler d1 execute server-recommend-db --command "SELECT name FROM sqlite_master WHERE type='table'"
```

---

### Step 4: Seed Sample Data (1 minute)

```bash
# Insert sample server data
npx wrangler d1 execute server-recommend-db --file=seed.sql
```

**Expected Output:**
```
🌀 Mapping SQL input into an array of statements
🌀 Executing on server-recommend-db (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx):
🚣 Executed XX commands in X.XXXs
```

**Verify:**
```bash
# Check row counts
npx wrangler d1 execute server-recommend-db --command "SELECT COUNT(*) as count FROM servers"
```

**Expected:** `count = 13` (sample data includes 13 servers)

**Checklist:**
- [ ] Command executed successfully
- [ ] 4 providers inserted
- [ ] 13 servers inserted
- [ ] Regional data inserted

---

### Step 5: Local Testing (2 minutes)

```bash
# Start development server
npm run dev
```

**Expected Output:**
```
⛅️ wrangler 4.60.0
-------------------
⎔ Starting local server...
[wrangler:inf] Ready on http://localhost:8787
```

**In another terminal:**
```bash
# Run test suite
./test.sh
```

**Or manual tests:**
```bash
# Health check
curl http://localhost:8787/api/health

# List servers
curl http://localhost:8787/api/servers | jq .

# Get recommendation
curl -X POST http://localhost:8787/api/recommend \
  -H "Content-Type: application/json" \
  -d '{
    "cpu_cores": 2,
    "memory_gb": 4,
    "storage_gb": 80
  }' | jq .
```

**Checklist:**
- [ ] Health endpoint returns 200
- [ ] Servers endpoint returns data
- [ ] Recommend endpoint works
- [ ] AI generates recommendations
- [ ] Cache works (second request faster)
- [ ] No errors in console

---

### Step 6: Deploy to Production (1 minute)

```bash
# Deploy to Cloudflare Workers
npm run deploy
```

**Expected Output:**
```
⛅️ wrangler 4.60.0
-------------------
Total Upload: XX.XX KiB / gzip: XX.XX KiB
Uploaded server-recommend (X.XX sec)
Published server-recommend (X.XX sec)
  https://server-recommend.YOUR_SUBDOMAIN.workers.dev
Current Deployment ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```

**Action Required:**
- [ ] Copy the deployed worker URL
- [ ] Save it for testing

**Checklist:**
- [ ] Deployment successful
- [ ] Worker URL obtained
- [ ] No deployment errors

---

### Step 7: Production Testing (2 minutes)

**Replace with your actual worker URL:**
```bash
export WORKER_URL="https://server-recommend.YOUR_SUBDOMAIN.workers.dev"
```

**Run tests:**
```bash
# Test with your URL
./test.sh $WORKER_URL

# Or manual tests
curl $WORKER_URL/api/health

curl "$WORKER_URL/api/servers?minCpu=4"

curl -X POST $WORKER_URL/api/recommend \
  -H "Content-Type: application/json" \
  -d @test-request.json | jq .
```

**Checklist:**
- [ ] Health check works
- [ ] Server listing works
- [ ] Recommendations work
- [ ] Response times acceptable
- [ ] No 500 errors

---

### Step 8: Monitor Deployment (Ongoing)

```bash
# View real-time logs
npx wrangler tail
```

**Cloudflare Dashboard:**
1. Go to https://dash.cloudflare.com/
2. Navigate to Workers & Pages
3. Click on `server-recommend`
4. View metrics:
   - [ ] Request rate
   - [ ] Success rate
   - [ ] Errors
   - [ ] Invocation duration

---

## Post-Deployment Verification

### Functional Tests
- [ ] ✅ Health endpoint: `GET /api/health`
- [ ] ✅ Server list: `GET /api/servers`
- [ ] ✅ Server filtering: `GET /api/servers?minCpu=4&minMemory=8`
- [ ] ✅ Recommendations: `POST /api/recommend`
- [ ] ✅ Cache working (second request faster)
- [ ] ✅ CORS headers present
- [ ] ✅ Error handling works

### Performance Tests
- [ ] Cold start: < 100ms
- [ ] Cached response: < 100ms
- [ ] AI response: 2-5s (first request)
- [ ] Database query: < 50ms

### Security Tests
- [ ] Input validation working
- [ ] SQL injection protected
- [ ] Error messages safe
- [ ] CORS properly configured

---

## Troubleshooting

### Issue: "Database not found"
**Solution:**
1. Verify `database_id` in `wrangler.toml`
2. List databases: `npx wrangler d1 list`
3. Re-create if needed: `npx wrangler d1 create server-recommend-db`

### Issue: "KV namespace not found"
**Solution:**
1. Verify `id` in `wrangler.toml`
2. List namespaces: `npx wrangler kv:namespace list`
3. Re-create if needed: `npx wrangler kv:namespace create CACHE`

### Issue: "No servers found"
**Solution:**
1. Verify seed data: `npx wrangler d1 execute server-recommend-db --command "SELECT COUNT(*) FROM servers"`
2. Re-seed if needed: `npx wrangler d1 execute server-recommend-db --file=seed.sql`

### Issue: "Workers AI error"
**Solution:**
1. Workers AI is automatic, no configuration needed
2. Check quota in Cloudflare dashboard
3. Verify model name: `@cf/meta/llama-3.1-8b-instruct`

### Issue: "Deployment fails"
**Solution:**
1. Check `wrangler.toml` syntax
2. Verify all IDs filled
3. Run `npm run typecheck`
4. Check authentication: `npx wrangler whoami`

---

## Rollback Procedure

If deployment has issues:

```bash
# Rollback to previous deployment
npx wrangler rollback

# Or deploy specific version
npx wrangler rollback --deployment-id <DEPLOYMENT_ID>
```

---

## Success Criteria

Deployment is successful when:

✅ All 3 API endpoints return 200 status  
✅ AI recommendations generated correctly  
✅ Cache hit rate > 0% after multiple requests  
✅ No 500 errors in logs  
✅ Response times within targets  
✅ Database queries working  
✅ Sample data accessible  

---

## Next Steps After Deployment

### Immediate
1. [ ] Test all endpoints thoroughly
2. [ ] Monitor logs for errors
3. [ ] Verify cache working
4. [ ] Document worker URL

### Short Term (1 week)
1. [ ] Add production server data
2. [ ] Monitor usage and performance
3. [ ] Set up alerts for errors
4. [ ] Adjust cache TTL if needed

### Long Term (1 month)
1. [ ] Implement rate limiting
2. [ ] Add authentication
3. [ ] Set up custom domain
4. [ ] Enhance AI prompts
5. [ ] Add analytics
6. [ ] Create admin interface

---

## Resource Limits Checklist

### Free Tier (Daily Limits)
- [ ] Workers: < 100,000 requests/day
- [ ] Workers AI: < 10,000 neurons/day
- [ ] D1: < 5M reads/day, < 100K writes/day
- [ ] KV: < 100,000 reads/day, < 1,000 writes/day

### Monitoring Alerts
Set up alerts for:
- [ ] Request rate > 80% of limit
- [ ] Error rate > 1%
- [ ] Response time > 5s (95th percentile)
- [ ] AI quota > 80% usage

---

## Support Resources

- **Cloudflare Workers Docs:** https://developers.cloudflare.com/workers/
- **Workers AI Docs:** https://developers.cloudflare.com/workers-ai/
- **D1 Docs:** https://developers.cloudflare.com/d1/
- **Community Discord:** https://discord.gg/cloudflaredev
- **Status Page:** https://www.cloudflarestatus.com/

---

## Deployment Complete! 🎉

When all checkboxes are marked:
- ✅ Worker deployed successfully
- ✅ All endpoints tested
- ✅ Monitoring in place
- ✅ No errors detected

**Your Server Recommendation System is now LIVE!**

Worker URL: `https://server-recommend.YOUR_SUBDOMAIN.workers.dev`

Share this URL with users to start receiving recommendations!
