# k6 load tests (PBPS MIS API)

Measure API latency on **local** vs **production** and compare before/after optimizations.

## Prerequisites

- [k6](https://grafana.com/docs/k6/latest/set-up/install-k6/) installed
- A valid JWT (`ACCESS_TOKEN`) for a user with project access
- `PROJECT_ID` for that project

## Get a token

1. Open **https://mis.icosconsult.com** and sign in (complete 2FA if prompted).
2. DevTools → **Application** → **Local Storage** → select the site.
3. Copy **`pbps.accessToken`** (long `eyJ...` string).
4. Optional: copy **`project.id`** from the **`pbps.auth`** JSON blob for `PROJECT_ID`.

Token expires when `JWT_ACCESS_EXPIRES` lapses (default 1 day). Refresh from the browser if k6 returns 401.

**PowerShell (login API):**

```powershell
curl.exe -s -X POST "https://misapi.icosconsult.com/api/auth/login" `
  -H "Content-Type: application/json" `
  -d "{\"email\":\"you@example.com\",\"password\":\"your-password\"}"
```

Use `accessToken` from the JSON response.

## Environment variables

| Variable | Example | Required |
|----------|---------|----------|
| `API_BASE_URL` | `https://mis.example.com` or `http://localhost:3001` | Yes |
| `PROJECT_ID` | `1` | Yes |
| `ACCESS_TOKEN` | `eyJ...` | Yes |

## Quick setup (Windows)

```powershell
cd loadtest/k6
copy .env.example .env.local
# Edit .env.local: set ACCESS_TOKEN and PROJECT_ID
.\run.ps1 smoke
```

## Run

From repo root (`apps/mis`):

```bash
# Quick smoke (1 user, health + trainings + trainees)
k6 run -e API_BASE_URL=http://localhost:3001 -e PROJECT_ID=1 -e ACCESS_TOKEN=your_token loadtest/k6/smoke.js

# Trainings list ramp
k6 run -e API_BASE_URL=https://your-server -e PROJECT_ID=1 -e ACCESS_TOKEN=your_token loadtest/k6/trainings-list.js

# Paginated trainees
k6 run -e API_BASE_URL=https://your-server -e PROJECT_ID=1 -e ACCESS_TOKEN=your_token loadtest/k6/trainees-list.js

# Dashboard open (single bundled `/dashboard` endpoint)
k6 run -e API_BASE_URL=https://your-server -e PROJECT_ID=1 -e ACCESS_TOKEN=your_token loadtest/k6/dashboard-burst.js
```

## Interpreting results

- **Local fast, server slow with empty DB** → usually **network** (browser ↔ server), reverse proxy, TLS, or Node not in production mode — not “weak hardware.”
- **`http_req_waiting` high, `http_req_connecting` high** → distance to server or proxy timeouts.
- **Only some endpoints slow** → check that endpoint’s SQL (k6 tags help).

Target after optimizations (same-region server): trainings list **p95 &lt; 500ms**, trainees page **p95 &lt; 1s** with small data.
