diff --git a/K6_README.md b/K6_README.md new file mode 100644 index 0000000..9da24e8 --- /dev/null +++ b/K6_README.md @@ -0,0 +1,404 @@ +# K6 Load Testing Documentation for GoodGo Platform + +Complete guide to understanding and implementing K6 load tests for the GoodGo Platform API. + +--- + +## ๐Ÿ“š Documentation Files + +This directory contains three comprehensive guides for K6 load testing: + +### 1. **K6_LOAD_TESTING_GUIDE.md** (Primary Reference) +Comprehensive exploration of the GoodGo Platform API structure for load testing. + +**Contents:** +- API module structure (auth, listings, payments, search) +- Detailed endpoint documentation with HTTP methods, rate limits, and auth requirements +- Complete DTO specifications with request/response body shapes +- Database and environment configuration reference +- Existing test setup (Playwright, Vitest, CI/CD) +- Architecture patterns (CQRS, DDD) +- File location quick reference +- K6 implementation recommendations + +**When to use:** Deep dives into specific endpoints, understanding authentication flows, checking environment variables + +### 2. **K6_ENDPOINTS_SUMMARY.md** (Quick Reference) +Condensed endpoint reference with data shapes for immediate lookup. + +**Contents:** +- All endpoints in table format (method, path, auth, rate limit) +- Authentication module (register, login, refresh, profile) +- Listings module (CRUD, moderation, media upload) +- Payments module (create, list, callbacks, refund) +- Search module (full-text, geo) +- Request/response body examples (JSON) +- K6 test scenarios (search, auth, listings, payments, webhooks) +- Rate limits summary +- Authentication flow examples (cookies vs tokens) + +**When to use:** Quick lookup of endpoint details, copy-paste example payloads, understanding rate limits + +### 3. **K6_QUICK_START.md** (Executable Examples) +Step-by-step guide with ready-to-run K6 scripts and setup instructions. + +**Contents:** +- Installation instructions (macOS, Linux, Docker) +- Environment setup (starting API, seeding database) +- Five runnable K6 scripts: + - Search load test (public, high volume) + - Auth load test (rate-limited registration) + - Listing creation (authenticated, quota-gated) + - Payment processing (authenticated) + - All scenarios combined +- CI integration with GitHub Actions +- Report generation options (JSON, Grafana Cloud, CSV) +- Common K6 checks and patterns +- Debugging and troubleshooting + +**When to use:** Getting started quickly, running tests immediately, setting up CI/CD + +--- + +## ๐Ÿš€ Quick Start (3 Minutes) + +### 1. Install K6 +```bash +brew install k6 # macOS +# or +apt-get install k6 # Linux +``` + +### 2. Start API & Database +```bash +pnpm install +pnpm db:generate +pnpm db:migrate:dev +pnpm db:seed +pnpm dev +``` + +### 3. Run a Load Test +```bash +# Copy this from K6_QUICK_START.md Step 3 +k6 run load-tests/search.k6.js +``` + +### 4. View Results +K6 prints a summary to console. For more detailed reports, see K6_QUICK_START.md section on report generation. + +--- + +## ๐Ÿ“Š Test Scenarios Implemented + +| Scenario | File | Focus | VUs | Duration | Key Endpoints | +|----------|------|-------|-----|----------|--------------| +| Search Load | `load-tests/search.k6.js` | Public search performance | 50 | 4m | `GET /search`, `GET /search/geo` | +| Authentication | `load-tests/auth.k6.js` | Auth throughput & rate limits | 10 | 2m | `POST /auth/register`, `POST /auth/login` | +| Listing Creation | `load-tests/listings.k6.js` | Authenticated listing CRUD | 5 | 2m | `POST /listings`, `GET /listings/:id` | +| Payments | `load-tests/payments.k6.js` | Payment initiation & status | 10 | 2m | `POST /payments`, `GET /payments/:id` | +| Combined | `load-tests/all-scenarios.k6.js` | Realistic mixed load | 50 | 5m | Multiple endpoints | + +--- + +## ๐Ÿ” Authentication Methods + +### Option 1: Cookie-Based (Recommended for Browser-Like Tests) +```javascript +const loginRes = http.post(`${BASE_URL}/auth/login`, { phone, password }); +// Cookies automatically managed by K6 +const profileRes = http.get(`${BASE_URL}/auth/profile`); +``` + +### Option 2: Bearer Token (Recommended for API-Only Tests) +```javascript +const loginRes = http.post(`${BASE_URL}/auth/login`, { phone, password }); +const { accessToken } = loginRes.json(); +const headers = { Authorization: `Bearer ${accessToken}` }; +const profileRes = http.get(`${BASE_URL}/auth/profile`, { headers }); +``` + +See K6_ENDPOINTS_SUMMARY.md for full examples. + +--- + +## ๐ŸŽฏ Key Endpoints by Priority + +### High Priority (Core Functionality) +| Endpoint | Priority | Why | +|----------|----------|-----| +| `GET /search` | โญโญโญ | Public, high-volume query | +| `GET /search/geo` | โญโญโญ | Geospatial, frequently used | +| `GET /listings` | โญโญโญ | Public search/filter | +| `GET /listings/:id` | โญโญโญ | Detail page load | +| `POST /auth/login` | โญโญ | User session creation | +| `POST /auth/register` | โญโญ | Rate-limited, important | + +### Medium Priority (Feature-Specific) +| Endpoint | Priority | Why | +|----------|----------|-----| +| `POST /listings` | โญโญ | Quota-gated, authenticated | +| `POST /payments` | โญโญ | External integrations | +| `GET /payments` | โญโญ | User transaction history | +| `POST /payments/callback/:provider` | โญโญ | Webhook handler, critical | + +### Low Priority (Admin/Specialized) +| Endpoint | Priority | Why | +|----------|----------|-----| +| `PATCH /listings/:id/moderate` | โญ | Admin-only | +| `GET /listings/pending` | โญ | Admin-only | +| `POST /search/reindex` | โญ | Admin-only, scheduled | + +--- + +## ๐Ÿ“ API Structure at a Glance + +``` +API Base: http://localhost:3001/api/v1 + +Modules: +โ”œโ”€โ”€ /auth # User authentication & profiles +โ”œโ”€โ”€ /listings # Property CRUD & moderation +โ”œโ”€โ”€ /search # Full-text & geo search +โ”œโ”€โ”€ /payments # Payment processing & webhooks +โ”œโ”€โ”€ /subscriptions # Plans & quotas (not focused for load tests) +โ”œโ”€โ”€ /admin # Admin operations (low priority for load tests) +โ””โ”€โ”€ /analytics # Market data (low priority for load tests) +``` + +--- + +## ๐Ÿ—„๏ธ Database Configuration + +### Local Development +```bash +DATABASE_URL=postgresql://goodgo:password@localhost:5432/goodgo +REDIS_URL=redis://localhost:6379 +TYPESENSE_HOST=localhost +TYPESENSE_PORT=8108 +``` + +### Test Environment (CI) +```bash +DATABASE_URL=postgresql://goodgo:goodgo_test_secret@localhost:5432/goodgo_test +REDIS_URL=redis://localhost:6379 +TYPESENSE_HOST=localhost +TYPESENSE_PORT=8108 +``` + +See K6_LOAD_TESTING_GUIDE.md for full environment variables. + +--- + +## โšก Rate Limits + +Respect these limits in your load tests: + +| Endpoint | Limit | Window | Action on Exceeded | +|----------|-------|--------|-------------------| +| `/auth/register` | 5 | per hour | Returns 429 | +| `/auth/login` | 5 | per hour | Returns 429 | +| `/auth/refresh` | 5 | per hour | Returns 429 | +| `/payments/callback/*` | 20 | per minute | Returns 429 | +| All others | None | N/A | Quota gates apply for writes | + +**K6 Handling:** +```javascript +check(res, { + 'status not rate limited': (r) => r.status !== 429, + 'status success or expected': (r) => [200, 201, 400, 404].includes(r.status), +}); +``` + +--- + +## ๐Ÿ—๏ธ Recommended Test Structure + +``` +load-tests/ +โ”œโ”€โ”€ search.k6.js # High-volume public search +โ”œโ”€โ”€ auth.k6.js # Authentication flow with rate limit handling +โ”œโ”€โ”€ listings.k6.js # Authenticated listing creation +โ”œโ”€โ”€ payments.k6.js # Payment processing +โ”œโ”€โ”€ all-scenarios.k6.js # Combined realistic mix +โ”œโ”€โ”€ helpers/ +โ”‚ โ”œโ”€โ”€ data-generators.js # Generate test data (users, listings) +โ”‚ โ”œโ”€โ”€ auth-flows.js # Reusable login/register functions +โ”‚ โ””โ”€โ”€ assertions.js # Custom check functions +โ””โ”€โ”€ config.js # Base URL, env, thresholds +``` + +Example helper structure provided in K6_QUICK_START.md. + +--- + +## ๐Ÿงช Integration with Existing Tests + +### Complement, Don't Replace + +K6 is for **load testing** (performance under concurrent load). +Existing tests serve different purposes: + +| Test Type | Tool | Purpose | When | +|-----------|------|---------|------| +| Unit Tests | Vitest | Verify function logic | During development | +| E2E Tests | Playwright | Verify user flows work | Before deployment | +| Load Tests | K6 | Verify performance at scale | Scheduled, on-demand | + +### Running All Tests + +```bash +# Unit tests (API only) +pnpm test + +# E2E tests (API + Web) +pnpm test:e2e + +# Load tests (new) +k6 run load-tests/search.k6.js + +# All in sequence +pnpm test && pnpm test:e2e && k6 run load-tests/all-scenarios.k6.js +``` + +--- + +## ๐Ÿ“ˆ CI/CD Integration + +### GitHub Actions Workflow + +Create `.github/workflows/load-test.yml` (template in K6_QUICK_START.md section ๐Ÿ”Ÿ): + +```bash +# Runs on schedule (daily at 2 AM) +# Or manually via workflow_dispatch +# Reports results as artifacts +``` + +### Manual Reporting + +```bash +# Export JSON +k6 run load-tests/search.k6.js --summary-export=results.json + +# View CSV (with extension) +k6 run load-tests/search.k6.js --out csv=results.csv + +# Upload to Grafana Cloud +K6_CLOUD_TOKEN=xxx k6 run load-tests/search.k6.js --out cloud +``` + +--- + +## ๐Ÿ”— Cross-Reference Guide + +### Looking for...? + +| Need | Find in | +|------|----------| +| All endpoint URLs & methods | K6_ENDPOINTS_SUMMARY.md | +| Request/response JSON shapes | K6_ENDPOINTS_SUMMARY.md (๐Ÿ“Š Key Data Shapes) | +| DTOs & validation rules | K6_LOAD_TESTING_GUIDE.md (Controllers & DTOs) | +| Rate limit specifics | K6_ENDPOINTS_SUMMARY.md (๐Ÿ“Œ Important Rate Limits) | +| Authentication flows | K6_ENDPOINTS_SUMMARY.md (๐Ÿ”— Authentication Flow for K6) | +| Database variables | K6_LOAD_TESTING_GUIDE.md (๐Ÿ—„๏ธ Database & Environment) | +| Ready-to-run scripts | K6_QUICK_START.md (Steps 3-8๏ธโƒฃ) | +| CI/CD setup | K6_QUICK_START.md (Step ๐Ÿ”Ÿ) | +| Troubleshooting | K6_QUICK_START.md (โœ… Troubleshooting) | +| Architecture details | K6_LOAD_TESTING_GUIDE.md (๐Ÿ“Š Architecture Patterns) | +| File locations | K6_LOAD_TESTING_GUIDE.md (๐Ÿ“ File Locations Quick Reference) | + +--- + +## ๐Ÿ› ๏ธ Common Tasks + +### Task: Load Test Search Endpoint +1. Read: K6_ENDPOINTS_SUMMARY.md (๐Ÿ” Search section) +2. Use: K6_QUICK_START.md (Step 3๏ธโƒฃ - Search Load Test) +3. Run: `k6 run load-tests/search.k6.js` + +### Task: Understand Payment Flow +1. Read: K6_LOAD_TESTING_GUIDE.md (๐Ÿ’ณ PAYMENTS MODULE) +2. Check: K6_ENDPOINTS_SUMMARY.md (๐Ÿ’ณ Payments section) +3. Use: K6_QUICK_START.md (Step 7๏ธโƒฃ - Payment Test) + +### Task: Add New Endpoint to Load Tests +1. Find endpoint in: K6_LOAD_TESTING_GUIDE.md or K6_ENDPOINTS_SUMMARY.md +2. Get data shape from: K6_ENDPOINTS_SUMMARY.md (๐Ÿ“Š Key Data Shapes) +3. Check auth from: K6_LOAD_TESTING_GUIDE.md (each module section) +4. Implement using examples in: K6_QUICK_START.md + +--- + +## โœ… Verification Checklist + +Before running load tests, verify: + +- [ ] API running: `pnpm dev` (port 3001) +- [ ] Database seeded: `pnpm db:seed` +- [ ] K6 installed: `k6 version` +- [ ] Can reach API: `curl http://localhost:3001/api/v1/docs` +- [ ] ENV variables set: `JWT_SECRET`, `CORS_ORIGINS`, etc. +- [ ] Load test file exists: `load-tests/*.k6.js` +- [ ] Test data available: Check seed in `prisma/seed.ts` + +--- + +## ๐Ÿ“ž Support & References + +### Internal Documentation +- **Full Architecture**: K6_LOAD_TESTING_GUIDE.md +- **Endpoint Reference**: K6_ENDPOINTS_SUMMARY.md +- **Getting Started**: K6_QUICK_START.md + +### External Resources +- **K6 Official Docs**: https://k6.io/docs +- **K6 API Reference**: https://k6.io/docs/javascript-api +- **K6 Community**: https://community.k6.io +- **K6 Examples**: https://github.com/grafana/k6-templates + +### Project Files +- **API Controllers**: `apps/api/src/modules/*/presentation/controllers/` +- **DTOs**: `apps/api/src/modules/*/presentation/dto/` +- **E2E Tests**: `e2e/api/` +- **Seed Data**: `prisma/seed.ts` + +--- + +## ๐ŸŽ“ Learning Path + +### Beginner (30 minutes) +1. Read K6_QUICK_START.md (Steps 1-4) +2. Install K6 +3. Run: `k6 run load-tests/search.k6.js` + +### Intermediate (1-2 hours) +1. Read K6_ENDPOINTS_SUMMARY.md +2. Understand auth flows +3. Run auth test: `k6 run load-tests/auth.k6.js` +4. Run listing test: `k6 run load-tests/listings.k6.js` + +### Advanced (2-4 hours) +1. Read K6_LOAD_TESTING_GUIDE.md completely +2. Review controller implementations in source +3. Create custom load test script +4. Set up CI/CD with GitHub Actions (K6_QUICK_START.md Step ๐Ÿ”Ÿ) +5. Generate and analyze reports + +--- + +## ๐Ÿ“ Notes + +- **No existing K6 setup** โ€” These docs provide complete guidance +- **Three complementary docs** โ€” Explore different docs for different needs +- **Executable examples** โ€” K6_QUICK_START.md scripts work as-is +- **Rate limits matter** โ€” Consider them in test design +- **Quota gates** โ€” Some operations (listings, payments) are gated by subscription +- **Test data** โ€” Use seed data or generate unique test users per VU +- **Production ready** โ€” Guides follow K6 best practices + +--- + +Generated: 2026-04-09 +Last Updated: K6_QUICK_START.md latest +