From d4cfc90b06dd51590fcf4743534314a769cedffc Mon Sep 17 00:00:00 2001 From: Sean Ankenbruck Date: Sat, 21 Feb 2026 15:55:00 -0500 Subject: [PATCH 1/3] complete set of load tests added and validated --- src/Faro.Collector/Program.cs | 4 + tests/load/.gitignore | 11 + tests/load/QUICK_START.md | 197 +++++++++++++ tests/load/README.md | 437 +++++++++++++++++++++++++++++ tests/load/example-test-session.sh | 215 ++++++++++++++ tests/load/load-test.js | 265 +++++++++++++++++ tests/load/monitor-system.sh | 65 +++++ tests/load/run-load-test.sh | 238 ++++++++++++++++ tests/load/test-configs.yaml | 240 ++++++++++++++++ tests/load/verify-ingestion.sh | 129 +++++++++ 10 files changed, 1801 insertions(+) create mode 100644 tests/load/.gitignore create mode 100644 tests/load/QUICK_START.md create mode 100644 tests/load/README.md create mode 100755 tests/load/example-test-session.sh create mode 100644 tests/load/load-test.js create mode 100755 tests/load/monitor-system.sh create mode 100755 tests/load/run-load-test.sh create mode 100644 tests/load/test-configs.yaml create mode 100755 tests/load/verify-ingestion.sh diff --git a/src/Faro.Collector/Program.cs b/src/Faro.Collector/Program.cs index 54efbfa..bc8da54 100644 --- a/src/Faro.Collector/Program.cs +++ b/src/Faro.Collector/Program.cs @@ -1,6 +1,7 @@ using FluentValidation; using Faro.Collector.Services; using Faro.Shared.Validation; +using Faro.Storage; var builder = WebApplication.CreateBuilder(args); @@ -12,6 +13,9 @@ // Add validation builder.Services.AddValidatorsFromAssemblyContaining(); +// Add storage services +builder.Services.AddMetricsStorage(builder.Configuration); + // Add Kafka producer builder.Services.AddSingleton(); diff --git a/tests/load/.gitignore b/tests/load/.gitignore new file mode 100644 index 0000000..2cbc56b --- /dev/null +++ b/tests/load/.gitignore @@ -0,0 +1,11 @@ +# Load test results +results/ +*.json +*.log + +# k6 cloud results +k6-cloud-*.json + +# Temporary files +*.tmp +.DS_Store diff --git a/tests/load/QUICK_START.md b/tests/load/QUICK_START.md new file mode 100644 index 0000000..6c876f3 --- /dev/null +++ b/tests/load/QUICK_START.md @@ -0,0 +1,197 @@ +# Load Testing Quick Start + +## TL;DR - Run Your First Test in 60 Seconds + +```bash +# 1. Install k6 (macOS) +brew install k6 + +# 2. Start Faro services +cd /path/to/faro +docker-compose up -d + +# 3. Run smoke test +cd tests/load +./run-load-test.sh smoke + +# 4. Verify results +./verify-ingestion.sh +``` + +## Commands Cheat Sheet + +### Running Tests + +```bash +# Smoke test (30s) - Always run this first! +./run-load-test.sh smoke + +# Light load (5min, ~10k metrics/sec) +./run-load-test.sh light + +# Medium load (15min, ~100k metrics/sec) +./run-load-test.sh medium + +# Heavy load (30min, ~300k metrics/sec) +./run-load-test.sh heavy + +# Stress test (find breaking point) +./run-load-test.sh stress + +# Custom configuration +BASE_URL=http://staging:5000 BATCH_SIZE=500 ./run-load-test.sh medium +``` + +### Monitoring + +```bash +# Watch metrics count in real-time +watch -n 1 'curl -s "http://localhost:8123/?query=SELECT+count(*)+FROM+metrics"' + +# Monitor system resources +./monitor-system.sh + +# View Grafana dashboards +open http://localhost:3000 + +# View Kafka UI +open http://localhost:8080 +``` + +### Verification + +```bash +# Verify metrics reached ClickHouse +./verify-ingestion.sh + +# Check specific metrics +curl "http://localhost:8123/" --data "SELECT * FROM metrics LIMIT 10 FORMAT Pretty" + +# Check ingestion rate +curl "http://localhost:8123/" --data " +SELECT + toStartOfMinute(timestamp) as minute, + count() as metrics_count +FROM metrics +WHERE timestamp >= now() - INTERVAL 10 MINUTE +GROUP BY minute +ORDER BY minute DESC +FORMAT PrettyCompact +" +``` + +### Troubleshooting + +```bash +# Check if services are running +docker-compose ps + +# View collector logs +docker-compose logs collector --tail=50 -f + +# View consumer logs +docker-compose logs consumer --tail=50 -f + +# Check Kafka consumer lag +docker exec faro-kafka kafka-consumer-groups \ + --bootstrap-server localhost:9092 \ + --group faro-consumer-group \ + --describe + +# Restart services +docker-compose restart collector consumer +``` + +## Recommended Test Progression + +### First Time Users + +1. **Smoke test** (30s) - Verify everything works + ```bash + ./run-load-test.sh smoke + ``` + +2. **Verify ingestion** + ```bash + ./verify-ingestion.sh + ``` + +3. **Light test** (5min) - Build confidence + ```bash + ./run-load-test.sh light + ``` + +### Performance Validation + +4. **Medium test** (15min) - Realistic production load + ```bash + ./run-load-test.sh medium + ``` + +5. **Heavy test** (30min) - Peak load + ```bash + ./run-load-test.sh heavy + ``` + +### Finding Limits + +6. **Stress test** (14min) - Find breaking point + ```bash + ./run-load-test.sh stress + ``` + +## Expected Results + +| Test | Duration | VUs | Expected Throughput | P95 Latency | Failure Rate | +|------|----------|-----|---------------------|-------------|--------------| +| smoke | 30s | 10 | ~1k/sec | <500ms | <1% | +| light | 5m | 100 | ~10k/sec | <1s | <1% | +| medium | 15m | 1000 | ~100k/sec | <2s | <5% | +| heavy | 30m | 3000 | ~300k/sec | <5s | <10% | + +## Understanding k6 Output + +``` + ✓ status is 202 + ✓ response has received count + + checks.........................: 100.00% ✓ 5000 ✗ 0 + data_received..................: 1.2 MB 40 kB/s + data_sent......................: 15 MB 500 kB/s + http_req_blocked...............: avg=1.5ms p(95)=4.2ms + http_req_duration..............: avg=234ms p(95)=456ms ← Key metric + http_req_failed................: 0.00% ✓ 0 ✗ 5000 ← Key metric + http_reqs......................: 5000 166/s + metrics_sent...................: 500000 16666/s ← Actual throughput +``` + +**Key Metrics:** +- **http_req_failed**: Should be <5% for medium load +- **http_req_duration p95**: Should be <2s for medium load +- **metrics_sent**: Total metrics ingested + +## Common Issues + +### "Connection refused" +**Solution:** Start services with `docker-compose up -d` + +### "High failure rate" +**Solution:** Reduce load or increase batch size +```bash +BATCH_SIZE=500 ./run-load-test.sh light +``` + +### "Metrics not in ClickHouse" +**Solution:** Check consumer is running +```bash +docker-compose logs consumer +``` + +### "Out of memory" +**Solution:** Increase Docker memory limit or reduce VUs + +## Need Help? + +- See [README.md](README.md) for comprehensive documentation +- Run interactive session: `./example-test-session.sh` +- Check logs: `docker-compose logs collector consumer` diff --git a/tests/load/README.md b/tests/load/README.md new file mode 100644 index 0000000..a6b1100 --- /dev/null +++ b/tests/load/README.md @@ -0,0 +1,437 @@ +# Faro Load Testing Suite + +This directory contains comprehensive load tests for validating Faro's high-throughput metrics ingestion capabilities. + +## Overview + +The load testing suite uses [k6](https://k6.io/) to simulate realistic production workloads and validate the system's ability to handle 1M+ metrics per second. + +## Prerequisites + +### Install k6 + +**macOS:** +```bash +brew install k6 +``` + +**Linux (Debian/Ubuntu):** +```bash +sudo gpg -k +sudo gpg --no-default-keyring --keyring /usr/share/keyrings/k6-archive-keyring.gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys C5AD17C747E3415A3642D57D77C6C491D6AC1D69 +echo "deb [signed-by=/usr/share/keyrings/k6-archive-keyring.gpg] https://dl.k6.io/deb stable main" | sudo tee /etc/apt/sources.list.d/k6.list +sudo apt-get update +sudo apt-get install k6 +``` + +**Windows:** +```powershell +choco install k6 +``` + +Or download from: https://k6.io/docs/getting-started/installation/ + +### Start Faro Services + +Before running load tests, ensure all services are running: + +```bash +# From the project root +docker-compose up -d + +# Verify services are healthy +docker-compose ps +``` + +## Quick Start + +### Run a Smoke Test (30 seconds) + +```bash +cd tests/load +chmod +x run-load-test.sh +./run-load-test.sh smoke +``` + +### Run a Medium Load Test (15 minutes) + +```bash +./run-load-test.sh medium +``` + +## Test Profiles + +### 1. Smoke Test (`smoke`) +- **Duration:** 30 seconds +- **Load:** 10 VUs (Virtual Users) +- **Expected Throughput:** ~1,000 metrics/second +- **Purpose:** Basic functionality validation +- **Use Case:** Quick verification that the system works + +```bash +./run-load-test.sh smoke +``` + +### 2. Light Load (`light`) +- **Duration:** 5 minutes +- **Load:** 100 VUs +- **Expected Throughput:** ~10,000 metrics/second +- **Purpose:** Validate system under light production load +- **Use Case:** Development environment testing + +```bash +./run-load-test.sh light +``` + +### 3. Medium Load (`medium`) +- **Duration:** 15 minutes +- **Load:** 500-1000 VUs +- **Expected Throughput:** ~50,000-100,000 metrics/second +- **Purpose:** Validate system under typical production load +- **Use Case:** Staging environment performance testing + +```bash +./run-load-test.sh medium +``` + +### 4. Heavy Load (`heavy`) +- **Duration:** 30 minutes +- **Load:** 2000-3000 VUs +- **Expected Throughput:** ~200,000-300,000 metrics/second +- **Purpose:** Validate system under peak production load +- **Use Case:** Pre-production capacity planning + +```bash +./run-load-test.sh heavy +``` + +### 5. Stress Test (`stress`) +- **Duration:** 14 minutes +- **Load:** Up to 4000 VUs +- **Expected Throughput:** ~400,000+ metrics/second +- **Purpose:** Find the breaking point +- **Use Case:** Capacity planning and failure mode testing + +```bash +./run-load-test.sh stress +``` + +## Configuration + +### Environment Variables + +| Variable | Default | Description | +|----------|---------|-------------| +| `BASE_URL` | `http://localhost:5000` | Collector API endpoint | +| `BATCH_SIZE` | `100` | Number of metrics per batch request | +| `DELAY_MS` | `0.1` | Delay between requests (milliseconds) | +| `TEST_PROFILE` | `medium` | Test profile to run | + +### Custom Test Configuration + +```bash +# Test against a different endpoint +BASE_URL=http://staging.example.com:5000 ./run-load-test.sh medium + +# Use larger batches for more efficient ingestion +BATCH_SIZE=500 ./run-load-test.sh heavy + +# Adjust delay to control throughput +DELAY_MS=1 ./run-load-test.sh medium +``` + +## Monitoring During Tests + +### Real-Time Metrics + +#### Watch ClickHouse Metric Count +```bash +watch -n 1 'curl -s "http://localhost:8123/?query=SELECT+count(*)+FROM+metrics"' +``` + +#### Check Kafka Lag +```bash +# Open Kafka UI +open http://localhost:8080 +``` + +#### View Grafana Dashboards +```bash +# Open Grafana +open http://localhost:3000 +# Login: admin / admin +``` + +### k6 Metrics + +During the test, k6 outputs real-time metrics: + +- **http_req_duration:** Request latency (p95, p99) +- **http_req_failed:** Failed request rate +- **http_reqs:** Requests per second +- **metrics_sent:** Custom counter of metrics ingested +- **batch_duration:** Custom metric for batch processing time + +## Distributed Load Testing + +To achieve 1M+ metrics per second, you may need to run k6 from multiple machines: + +### Using k6 Cloud (Recommended for High Load) + +```bash +# Sign up at https://k6.io/cloud +k6 login cloud + +# Run distributed test +k6 cloud load-test.js \ + -e BASE_URL=http://your-collector:5000 \ + -e TEST_PROFILE=heavy +``` + +### Manual Distribution (Multiple k6 Instances) + +Run the same test from multiple machines simultaneously: + +```bash +# Machine 1 +BASE_URL=http://collector:5000 ./run-load-test.sh heavy & + +# Machine 2 +BASE_URL=http://collector:5000 ./run-load-test.sh heavy & + +# Machine 3 +BASE_URL=http://collector:5000 ./run-load-test.sh heavy & +``` + +Aggregate results manually or use a shared results database. + +## Understanding Results + +### Success Criteria + +#### Smoke Test +- ✅ `http_req_failed < 1%` +- ✅ `http_req_duration p95 < 500ms` + +#### Light Load +- ✅ `http_req_failed < 1%` +- ✅ `http_req_duration p95 < 1s` +- ✅ `http_req_duration p99 < 2s` + +#### Medium Load +- ✅ `http_req_failed < 5%` +- ✅ `http_req_duration p95 < 2s` +- ✅ `http_req_duration p99 < 5s` + +#### Heavy/Stress Load +- ✅ `http_req_failed < 10%` +- ✅ System remains stable (no crashes) +- ✅ Metrics eventually reach ClickHouse + +### Output Files + +After each test, results are saved to `./results/YYYYMMDD_HHMMSS/`: + +- **summary.json:** High-level test results and metrics +- **results.json:** Detailed per-request data +- **test.log:** Complete k6 output log + +### Interpreting Results + +```json +{ + "metrics": { + "http_req_duration": { + "avg": 234.5, + "p95": 450.2, + "p99": 890.1 + }, + "http_req_failed": { + "rate": 0.023 // 2.3% failure rate + }, + "metrics_sent": { + "count": 5000000 // Total metrics sent + } + } +} +``` + +**Key Indicators:** +- **Low failure rate (< 5%):** System is handling load well +- **P95 latency < 2s:** Collector is responsive under load +- **Increasing latency over time:** System may be saturating +- **High failure rate (> 10%):** System is overloaded + +## Validating ClickHouse Ingestion + +After the load test completes, verify metrics reached ClickHouse: + +```bash +# Check total count +curl "http://localhost:8123/?query=SELECT+count(*)+FROM+metrics" + +# Check recent metrics (last 5 minutes) +curl "http://localhost:8123/" --data "SELECT count(*) FROM metrics WHERE timestamp >= now() - INTERVAL 5 MINUTE" + +# Check metrics by service +curl "http://localhost:8123/" --data "SELECT service, count(*) FROM metrics GROUP BY service ORDER BY count() DESC" + +# Check ingestion rate over time +curl "http://localhost:8123/" --data " +SELECT + toStartOfMinute(timestamp) as minute, + count() as metrics_count +FROM metrics +WHERE timestamp >= now() - INTERVAL 1 HOUR +GROUP BY minute +ORDER BY minute DESC +LIMIT 10 +FORMAT PrettyCompact +" +``` + +## Troubleshooting + +### Issue: Connection Refused + +``` +Error: dial tcp 127.0.0.1:5000: connect: connection refused +``` + +**Solution:** Ensure the Collector is running: +```bash +docker-compose ps +docker-compose logs collector +``` + +### Issue: High Failure Rate + +If you see > 10% failures during medium/heavy tests: + +1. **Check Kafka lag:** Kafka may be backlogged + ```bash + docker-compose logs kafka | tail -50 + ``` + +2. **Check Collector logs:** + ```bash + docker-compose logs collector --tail=100 -f + ``` + +3. **Increase Collector resources:** + ```yaml + # In docker-compose.yml + collector: + deploy: + resources: + limits: + cpus: '4' + memory: 4G + ``` + +4. **Tune batch sizes:** + ```bash + # Larger batches = fewer requests + BATCH_SIZE=500 ./run-load-test.sh medium + ``` + +### Issue: ClickHouse Not Receiving Metrics + +If metrics are sent but don't appear in ClickHouse: + +1. **Check Consumer is running:** + ```bash + docker-compose ps consumer + docker-compose logs consumer --tail=50 + ``` + +2. **Check Kafka messages:** + - Open Kafka UI: http://localhost:8080 + - Check `faro-metrics` topic for messages + +3. **Check Consumer lag:** + ```bash + docker-compose exec kafka kafka-consumer-groups \ + --bootstrap-server localhost:9092 \ + --group faro-consumer-group \ + --describe + ``` + +### Issue: Out of Memory + +If k6 or the Collector runs out of memory: + +1. **Reduce VUs or batch size:** + ```bash + BATCH_SIZE=50 ./run-load-test.sh light + ``` + +2. **Increase Docker memory limits:** + ```bash + # Docker Desktop: Settings → Resources → Memory + ``` + +3. **Use distributed load testing** (see above) + +## Performance Tuning Tips + +### Collector Tuning + +Edit `src/Faro.Collector/appsettings.json`: + +```json +{ + "MetricsCollector": { + "FlushIntervalSeconds": 1, // Reduce for faster flushing + "BatchSize": 5000 // Increase for larger Kafka batches + }, + "Kafka": { + "ProducerConfig": { + "LingerMs": 10, // Reduce for lower latency + "BatchSize": 65536, // Increase for better compression + "CompressionType": "lz4" // lz4 is faster than snappy + } + } +} +``` + +### ClickHouse Tuning + +For high-throughput ingestion: + +```sql +-- Increase max insert threads +SET max_insert_threads = 8; + +-- Disable fsync for better performance (staging only!) +SET fsync_metadata = 0; +``` + +### Consumer Tuning + +Edit `src/Faro.Consumer/appsettings.json`: + +```json +{ + "Consumer": { + "BatchSize": 10000, // Larger batches to ClickHouse + "BatchTimeoutSeconds": 5, // Reduce for lower latency + "MaxRetries": 3 + } +} +``` + +## Contributing + +To add new test scenarios: + +1. Edit `load-test.js` and add a new profile to the `profiles` object +2. Update this README with the new profile description +3. Test your changes with `./run-load-test.sh your-profile` + +## References + +- [k6 Documentation](https://k6.io/docs/) +- [k6 Best Practices](https://k6.io/docs/testing-guides/test-types/) +- [ClickHouse Performance Tips](https://clickhouse.com/docs/en/operations/tips/) +- [Kafka Performance Tuning](https://kafka.apache.org/documentation/#producerconfigs) diff --git a/tests/load/example-test-session.sh b/tests/load/example-test-session.sh new file mode 100755 index 0000000..4d80929 --- /dev/null +++ b/tests/load/example-test-session.sh @@ -0,0 +1,215 @@ +#!/bin/bash + +####################################### +# Example Test Session +# +# This script demonstrates a complete load testing workflow +# with monitoring and validation +####################################### + +set -e + +# Colors +BLUE='\033[0;34m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +RED='\033[0;31m' +NC='\033[0m' + +print_header() { + echo "" + echo -e "${BLUE}========================================${NC}" + echo -e "${BLUE}$1${NC}" + echo -e "${BLUE}========================================${NC}" + echo "" +} + +print_step() { + echo -e "${GREEN}➜${NC} $1" +} + +print_info() { + echo -e "${YELLOW}ℹ${NC} $1" +} + +print_header "Faro Load Testing - Complete Workflow Example" + +echo "This script will guide you through a complete load testing session:" +echo "" +echo "1. Check prerequisites" +echo "2. Start monitoring (in background)" +echo "3. Get baseline metrics" +echo "4. Run load test" +echo "5. Verify ingestion" +echo "6. Generate report" +echo "" +echo -e "${YELLOW}Press Enter to continue, or Ctrl+C to cancel...${NC}" +read + +# Step 1: Check prerequisites +print_header "Step 1: Checking Prerequisites" + +print_step "Checking if k6 is installed..." +if command -v k6 &> /dev/null; then + echo -e "${GREEN}✓${NC} k6 is installed: $(k6 version)" +else + echo -e "${RED}✗${NC} k6 is not installed" + echo "" + echo "Install k6:" + echo " macOS: brew install k6" + echo " Linux: See https://k6.io/docs/getting-started/installation/" + exit 1 +fi + +print_step "Checking if Docker services are running..." +if docker ps | grep -q "faro-collector"; then + echo -e "${GREEN}✓${NC} Collector is running" +else + echo -e "${RED}✗${NC} Collector is not running" + echo "" + echo "Start services with: docker-compose up -d" + exit 1 +fi + +if docker ps | grep -q "faro-kafka"; then + echo -e "${GREEN}✓${NC} Kafka is running" +else + echo -e "${YELLOW}⚠${NC} Kafka is not running" +fi + +if docker ps | grep -q "faro-clickhouse"; then + echo -e "${GREEN}✓${NC} ClickHouse is running" +else + echo -e "${YELLOW}⚠${NC} ClickHouse is not running" +fi + +sleep 2 + +# Step 2: Start monitoring +print_header "Step 2: Starting Monitoring" + +print_info "You can monitor the test in real-time using these tools:" +echo "" +echo " Terminal 1: ./monitor-system.sh" +echo " Terminal 2: watch -n 1 'curl -s http://localhost:8123/?query=SELECT+count(*)+FROM+metrics'" +echo " Browser: http://localhost:3000 (Grafana)" +echo " Browser: http://localhost:8080 (Kafka UI)" +echo "" +print_info "These will run in the background during the test" +echo "" +echo -e "${YELLOW}Press Enter to continue...${NC}" +read + +# Step 3: Get baseline +print_header "Step 3: Getting Baseline Metrics" + +print_step "Querying current metric count..." +BASELINE=$(curl -s "http://localhost:8123/?query=SELECT+count(*)+FROM+metrics" 2>/dev/null || echo "0") +echo "Current metrics in ClickHouse: ${BASELINE}" +echo "" +sleep 2 + +# Step 4: Choose test profile +print_header "Step 4: Choosing Test Profile" + +echo "Select a test profile:" +echo "" +echo " 1. smoke - Quick 30s test (recommended first time)" +echo " 2. light - 5 minute test at 10k metrics/sec" +echo " 3. medium - 15 minute test at 50-100k metrics/sec" +echo "" +echo -n "Enter choice (1-3): " +read choice + +case $choice in + 1) + PROFILE="smoke" + ;; + 2) + PROFILE="light" + ;; + 3) + PROFILE="medium" + ;; + *) + echo "Invalid choice, defaulting to smoke" + PROFILE="smoke" + ;; +esac + +echo "" +print_info "Running ${PROFILE} test profile" +sleep 2 + +# Step 5: Run the test +print_header "Step 5: Running Load Test" + +print_step "Starting k6 load test..." +echo "" + +./run-load-test.sh ${PROFILE} + +TEST_EXIT_CODE=$? + +if [ $TEST_EXIT_CODE -ne 0 ]; then + echo "" + echo -e "${RED}✗${NC} Load test failed with exit code ${TEST_EXIT_CODE}" + echo "" + echo "Check the logs above for errors" + exit 1 +fi + +echo "" +print_step "Load test completed successfully!" +sleep 2 + +# Step 6: Verify ingestion +print_header "Step 6: Verifying Ingestion" + +print_info "Waiting 10 seconds for metrics to flow through the pipeline..." +sleep 10 + +print_step "Running verification script..." +echo "" + +./verify-ingestion.sh + +# Step 7: Calculate results +print_header "Step 7: Calculating Results" + +AFTER_COUNT=$(curl -s "http://localhost:8123/?query=SELECT+count(*)+FROM+metrics" 2>/dev/null || echo "0") +INGESTED=$((AFTER_COUNT - BASELINE)) + +echo "Baseline metrics: ${BASELINE}" +echo "Current metrics: ${AFTER_COUNT}" +echo "Metrics ingested: ${INGESTED}" +echo "" + +if [ $INGESTED -gt 0 ]; then + echo -e "${GREEN}✓${NC} Successfully ingested ${INGESTED} metrics!" +else + echo -e "${YELLOW}⚠${NC} No new metrics detected. Check the consumer logs:" + echo " docker-compose logs consumer --tail=50" +fi + +# Step 8: Next steps +print_header "Complete! Next Steps" + +echo "Your load test is complete. Here's what you can do next:" +echo "" +echo "1. View detailed results:" +echo " - Check ./results/ directory for k6 output" +echo "" +echo "2. View metrics in Grafana:" +echo " - Open http://localhost:3000 (admin/admin)" +echo " - Create a dashboard with ClickHouse datasource" +echo "" +echo "3. Query ClickHouse directly:" +echo " - Run: curl 'http://localhost:8123/' --data 'SELECT * FROM metrics LIMIT 10 FORMAT Pretty'" +echo "" +echo "4. Run more intensive tests:" +echo " - ./run-load-test.sh heavy" +echo " - ./run-load-test.sh stress" +echo "" +echo -e "${GREEN}Happy load testing!${NC}" +echo "" diff --git a/tests/load/load-test.js b/tests/load/load-test.js new file mode 100644 index 0000000..65e940a --- /dev/null +++ b/tests/load/load-test.js @@ -0,0 +1,265 @@ +/** + * Faro Load Test - High-Throughput Metrics Ingestion + * + * This test validates the system's ability to handle high-volume metric ingestion + * and verifies the claim of 1M+ metrics per second throughput. + * + * Test scenarios: + * 1. Warm-up: 10k metrics/sec for 30s + * 2. Ramp-up: Gradually increase to target load + * 3. Sustained: Hold at target load + * 4. Stress: Push beyond target to find breaking point + * 5. Cool-down: Gradual decrease + */ + +import http from 'k6/http'; +import { check, sleep } from 'k6'; +import { Rate, Trend, Counter } from 'k6/metrics'; + +// Custom metrics +const failureRate = new Rate('failed_requests'); +const metricsSent = new Counter('metrics_sent'); +const batchDuration = new Trend('batch_duration'); + +// Configuration +const BASE_URL = __ENV.BASE_URL || 'http://localhost:5000'; +const BATCH_SIZE = parseInt(__ENV.BATCH_SIZE || '100'); +const TEST_PROFILE = __ENV.TEST_PROFILE || 'medium'; + +// Test profiles with different load characteristics +const profiles = { + // Smoke test - basic functionality validation + smoke: { + stages: [ + { duration: '30s', target: 10 }, // 10 VUs = ~1k metrics/sec + ], + thresholds: { + http_req_failed: ['rate<0.01'], // Less than 1% errors + http_req_duration: ['p(95)<500'], // 95% of requests under 500ms + } + }, + + // Light load - 100k metrics/sec + light: { + stages: [ + { duration: '1m', target: 100 }, // Ramp-up to 100 VUs + { duration: '3m', target: 100 }, // Hold at 100 VUs (~10k metrics/sec) + { duration: '1m', target: 0 }, // Cool-down + ], + thresholds: { + http_req_failed: ['rate<0.01'], + http_req_duration: ['p(95)<1000'], + http_req_duration: ['p(99)<2000'], + } + }, + + // Medium load - 500k metrics/sec + medium: { + stages: [ + { duration: '30s', target: 100 }, // Warm-up + { duration: '2m', target: 500 }, // Ramp to 500 VUs (~50k metrics/sec) + { duration: '5m', target: 500 }, // Hold at 500 VUs + { duration: '2m', target: 1000 }, // Push to 1000 VUs (~100k metrics/sec) + { duration: '5m', target: 1000 }, // Hold at 1000 VUs + { duration: '1m', target: 0 }, // Cool-down + ], + thresholds: { + http_req_failed: ['rate<0.05'], // Less than 5% errors under load + http_req_duration: ['p(95)<2000'], // 95% under 2s + http_req_duration: ['p(99)<5000'], // 99% under 5s + } + }, + + // Heavy load - 1M+ metrics/sec (requires multiple load generators) + heavy: { + stages: [ + { duration: '1m', target: 500 }, // Warm-up + { duration: '3m', target: 2000 }, // Ramp to 2000 VUs + { duration: '10m', target: 2000 }, // Hold at 2000 VUs (~200k metrics/sec) + { duration: '3m', target: 3000 }, // Push to 3000 VUs + { duration: '10m', target: 3000 }, // Hold at 3000 VUs (~300k metrics/sec) + { duration: '2m', target: 0 }, // Cool-down + ], + thresholds: { + http_req_failed: ['rate<0.10'], // Less than 10% errors + http_req_duration: ['p(95)<5000'], // 95% under 5s + } + }, + + // Stress test - find the breaking point + stress: { + stages: [ + { duration: '1m', target: 500 }, // Warm-up + { duration: '2m', target: 1000 }, // + { duration: '2m', target: 2000 }, // + { duration: '2m', target: 4000 }, // Push hard + { duration: '5m', target: 4000 }, // Hold at breaking point + { duration: '2m', target: 0 }, // Cool-down + ], + thresholds: { + // More lenient thresholds for stress testing + http_req_failed: ['rate<0.20'], // Less than 20% errors + } + }, +}; + +// Apply the selected profile +export const options = profiles[TEST_PROFILE]; + +// Metric name pools for realistic variance +const metricNames = [ + 'cpu_usage', + 'memory_used', + 'disk_io_read', + 'disk_io_write', + 'network_bytes_in', + 'network_bytes_out', + 'api.request.duration', + 'api.request.count', + 'api.error.count', + 'db.query.duration', + 'db.connection.pool.size', + 'cache.hit.count', + 'cache.miss.count', + 'queue.depth', + 'worker.processing_time', +]; + +const environments = ['production', 'staging', 'development']; +const services = [ + 'api-gateway', + 'auth-service', + 'user-service', + 'order-service', + 'payment-service', + 'notification-service', + 'analytics-service', + 'search-service', +]; + +// Generate realistic host names +function generateHostname(service, replica) { + return `${service}-${replica}`; +} + +// Generate a random metric value based on metric type +function generateMetricValue(metricName) { + if (metricName.includes('cpu') || metricName.includes('memory')) { + return Math.random() * 100; // 0-100% + } else if (metricName.includes('duration') || metricName.includes('time')) { + return Math.random() * 1000; // 0-1000ms + } else if (metricName.includes('count')) { + return Math.floor(Math.random() * 100); + } else if (metricName.includes('bytes')) { + return Math.floor(Math.random() * 1000000); // 0-1MB + } + return Math.random() * 100; +} + +// Generate a batch of realistic metrics +function generateMetricBatch(size) { + const metrics = []; + const timestamp = new Date().toISOString(); + + for (let i = 0; i < size; i++) { + const service = services[Math.floor(Math.random() * services.length)]; + const metricName = metricNames[Math.floor(Math.random() * metricNames.length)]; + + metrics.push({ + metricName: metricName, + value: generateMetricValue(metricName), + timestamp: timestamp, + host: generateHostname(service, Math.floor(Math.random() * 10) + 1), + service: service, + environment: environments[Math.floor(Math.random() * environments.length)], + tags: { + region: `us-${['east', 'west', 'central'][Math.floor(Math.random() * 3)]}-1`, + availability_zone: `${['a', 'b', 'c'][Math.floor(Math.random() * 3)]}`, + version: `v${Math.floor(Math.random() * 5) + 1}.${Math.floor(Math.random() * 10)}`, + } + }); + } + + return { metrics }; +} + +// Main test function - executed by each virtual user +export default function () { + const batch = generateMetricBatch(BATCH_SIZE); + + const params = { + headers: { + 'Content-Type': 'application/json', + }, + tags: { + name: 'batch_metrics', + }, + }; + + const startTime = Date.now(); + const response = http.post( + `${BASE_URL}/api/metrics/batch`, + JSON.stringify(batch), + params + ); + const duration = Date.now() - startTime; + + // Record custom metrics + batchDuration.add(duration); + metricsSent.add(BATCH_SIZE); + + // Check response + const success = check(response, { + 'status is 202': (r) => r.status === 202, + 'response has received count': (r) => { + try { + const body = JSON.parse(r.body); + return body.received === BATCH_SIZE; + } catch (e) { + return false; + } + }, + }); + + failureRate.add(!success); + + // Add slight delay to avoid overwhelming the system + // This is configurable based on desired throughput + const delayMs = parseFloat(__ENV.DELAY_MS || '0.1'); + sleep(delayMs); +} + +// Setup function - runs once before test starts +export function setup() { + console.log('='.repeat(80)); + console.log('Faro Load Test Configuration'); + console.log('='.repeat(80)); + console.log(`Base URL: ${BASE_URL}`); + console.log(`Test Profile: ${TEST_PROFILE}`); + console.log(`Batch Size: ${BATCH_SIZE}`); + console.log(`Expected throughput: ~${BATCH_SIZE * 10} metrics/sec per 100 VUs`); + console.log('='.repeat(80)); + + // Verify collector is responsive + const healthCheck = http.get(`${BASE_URL}/health`); + if (healthCheck.status !== 200) { + console.error('WARNING: Collector health check failed. Service may not be ready.'); + } + + return { + startTime: new Date().toISOString(), + }; +} + +// Teardown function - runs once after test completes +export function teardown(data) { + console.log('='.repeat(80)); + console.log('Load Test Complete'); + console.log('='.repeat(80)); + console.log(`Start Time: ${data.startTime}`); + console.log(`End Time: ${new Date().toISOString()}`); + console.log('='.repeat(80)); + console.log('Check the results summary above for detailed metrics.'); + console.log('Review Grafana dashboards for system performance during the test.'); + console.log('='.repeat(80)); +} diff --git a/tests/load/monitor-system.sh b/tests/load/monitor-system.sh new file mode 100755 index 0000000..c5684b7 --- /dev/null +++ b/tests/load/monitor-system.sh @@ -0,0 +1,65 @@ +#!/bin/bash + +####################################### +# System Resource Monitor +# +# Monitors Docker containers and system resources during load test +####################################### + +# Colors +BLUE='\033[0;34m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +INTERVAL=${1:-5} # Default 5 seconds + +echo "" +echo -e "${BLUE}========================================${NC}" +echo -e "${BLUE}Faro System Resource Monitor${NC}" +echo -e "${BLUE}Refresh interval: ${INTERVAL}s${NC}" +echo -e "${BLUE}========================================${NC}" +echo "" +echo -e "${YELLOW}Press Ctrl+C to stop${NC}" +echo "" + +while true; do + clear + echo -e "${BLUE}=== System Resources $(date '+%Y-%m-%d %H:%M:%S') ===${NC}" + echo "" + + # Docker container stats + echo -e "${GREEN}Docker Container Stats:${NC}" + docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}\t{{.BlockIO}}" \ + faro-collector faro-consumer faro-kafka faro-clickhouse 2>/dev/null || echo "No containers running" + + echo "" + + # ClickHouse metrics count + echo -e "${GREEN}ClickHouse Metrics:${NC}" + METRICS_COUNT=$(curl -s "http://localhost:8123/?query=SELECT+count(*)+FROM+metrics" 2>/dev/null || echo "N/A") + echo "Total metrics: ${METRICS_COUNT}" + + # Recent ingestion rate + RECENT_1M=$(curl -s "http://localhost:8123/" --data "SELECT count(*) FROM metrics WHERE timestamp >= now() - INTERVAL 1 MINUTE" 2>/dev/null || echo "N/A") + echo "Last 1 minute: ${RECENT_1M}" + + if [ "$RECENT_1M" != "N/A" ] && [ "$RECENT_1M" -gt 0 ]; then + RATE=$((RECENT_1M / 60)) + echo -e "Ingestion rate: ~${RATE} metrics/sec" + fi + + echo "" + + # Kafka lag + echo -e "${GREEN}Kafka Consumer Lag:${NC}" + docker exec faro-kafka kafka-consumer-groups \ + --bootstrap-server localhost:9092 \ + --group faro-consumer-group \ + --describe 2>/dev/null | grep faro-metrics || echo "No consumer group found" + + echo "" + echo -e "${YELLOW}Refreshing in ${INTERVAL}s...${NC}" + + sleep $INTERVAL +done diff --git a/tests/load/run-load-test.sh b/tests/load/run-load-test.sh new file mode 100755 index 0000000..51a518e --- /dev/null +++ b/tests/load/run-load-test.sh @@ -0,0 +1,238 @@ +#!/bin/bash + +####################################### +# Faro Load Test Runner +# +# This script orchestrates load tests against the Faro metrics system +# and provides monitoring, reporting, and validation capabilities. +####################################### + +set -e + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Configuration +BASE_URL=${BASE_URL:-"http://localhost:5000"} +TEST_PROFILE=${1:-"smoke"} +BATCH_SIZE=${BATCH_SIZE:-100} +DELAY_MS=${DELAY_MS:-0.1} +OUTPUT_DIR="./results/$(date +%Y%m%d_%H%M%S)" + +# Print colored output +print_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +print_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +print_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +print_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +print_header() { + echo "" + echo -e "${BLUE}========================================${NC}" + echo -e "${BLUE}$1${NC}" + echo -e "${BLUE}========================================${NC}" + echo "" +} + +# Check if k6 is installed +check_k6() { + if ! command -v k6 &> /dev/null; then + print_error "k6 is not installed" + print_info "Install k6 from: https://k6.io/docs/getting-started/installation/" + print_info "On macOS: brew install k6" + print_info "On Linux: sudo gpg -k && sudo gpg --no-default-keyring --keyring /usr/share/keyrings/k6-archive-keyring.gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys C5AD17C747E3415A3642D57D77C6C491D6AC1D69 && echo \"deb [signed-by=/usr/share/keyrings/k6-archive-keyring.gpg] https://dl.k6.io/deb stable main\" | sudo tee /etc/apt/sources.list.d/k6.list && sudo apt-get update && sudo apt-get install k6" + exit 1 + fi + print_success "k6 is installed ($(k6 version))" +} + +# Check if services are running +check_services() { + print_info "Checking if Faro services are running..." + + # Check Collector + if curl -sf "${BASE_URL}/api/health" > /dev/null 2>&1; then + print_success "Collector is responding at ${BASE_URL}" + else + print_error "Collector is not responding at ${BASE_URL}" + print_info "Start services with: docker-compose up -d" + exit 1 + fi + + # Check ClickHouse + if curl -sf "http://localhost:8123/ping" > /dev/null 2>&1; then + print_success "ClickHouse is responding" + else + print_warning "ClickHouse may not be responding (this is optional for collector tests)" + fi + + # Check Kafka + if docker ps | grep -q "faro-kafka"; then + print_success "Kafka container is running" + else + print_warning "Kafka container is not running (this may cause issues)" + fi +} + +# Get baseline metrics from ClickHouse +get_baseline_metrics() { + print_info "Getting baseline metrics from ClickHouse..." + + BASELINE_COUNT=$(curl -s "http://localhost:8123/?query=SELECT+count(*)+FROM+metrics" 2>/dev/null || echo "0") + print_info "Current metric count in ClickHouse: ${BASELINE_COUNT}" + + return 0 +} + +# Run the load test +run_load_test() { + print_header "Starting Load Test: ${TEST_PROFILE}" + + mkdir -p "$OUTPUT_DIR" + + print_info "Test Configuration:" + print_info " Profile: ${TEST_PROFILE}" + print_info " Base URL: ${BASE_URL}" + print_info " Batch Size: ${BATCH_SIZE}" + print_info " Delay: ${DELAY_MS}ms" + print_info " Output Directory: ${OUTPUT_DIR}" + + # Run k6 with configuration + k6 run \ + --out json="${OUTPUT_DIR}/results.json" \ + --summary-export="${OUTPUT_DIR}/summary.json" \ + -e BASE_URL="${BASE_URL}" \ + -e TEST_PROFILE="${TEST_PROFILE}" \ + -e BATCH_SIZE="${BATCH_SIZE}" \ + -e DELAY_MS="${DELAY_MS}" \ + load-test.js | tee "${OUTPUT_DIR}/test.log" + + TEST_EXIT_CODE=${PIPESTATUS[0]} + + if [ $TEST_EXIT_CODE -eq 0 ]; then + print_success "Load test completed successfully" + else + print_error "Load test failed with exit code ${TEST_EXIT_CODE}" + fi + + return $TEST_EXIT_CODE +} + +# Generate HTML report +generate_report() { + print_info "Generating test report..." + + if [ -f "${OUTPUT_DIR}/summary.json" ]; then + cat "${OUTPUT_DIR}/summary.json" | python3 -m json.tool > "${OUTPUT_DIR}/summary_formatted.json" 2>/dev/null || true + print_success "Report saved to ${OUTPUT_DIR}" + fi +} + +# Validate results +validate_results() { + print_header "Validating Results" + + if [ ! -f "${OUTPUT_DIR}/summary.json" ]; then + print_error "Summary file not found" + return 1 + fi + + # Parse key metrics from summary + print_info "Extracting key performance indicators..." + + # This is a simple validation - you can enhance it + FAILURE_RATE=$(cat "${OUTPUT_DIR}/summary.json" | grep -o '"failed_requests":{"rate":[0-9.]*' | grep -o '[0-9.]*$' || echo "0") + + print_info "Request failure rate: ${FAILURE_RATE}" + + # Check if failure rate is acceptable + THRESHOLD=0.10 # 10% threshold + if (( $(echo "$FAILURE_RATE < $THRESHOLD" | bc -l 2>/dev/null || echo "1") )); then + print_success "Failure rate is within acceptable limits (<${THRESHOLD})" + else + print_warning "Failure rate exceeds threshold (>${THRESHOLD})" + fi +} + +# Monitor ClickHouse during test +monitor_clickhouse() { + print_info "You can monitor ClickHouse during the test with:" + print_info " watch -n 1 'curl -s \"http://localhost:8123/?query=SELECT+count(*)+FROM+metrics\"'" + print_info "" + print_info "Or use Grafana at http://localhost:3000 (admin/admin)" + print_info "Or use Kafka UI at http://localhost:8080" +} + +# Usage information +usage() { + echo "Usage: $0 [TEST_PROFILE]" + echo "" + echo "Test Profiles:" + echo " smoke - Quick smoke test (30s, 10 VUs, ~1k metrics/sec)" + echo " light - Light load (5min, 100 VUs, ~10k metrics/sec)" + echo " medium - Medium load (15min, 1000 VUs, ~100k metrics/sec) [DEFAULT]" + echo " heavy - Heavy load (30min, 3000 VUs, ~300k metrics/sec)" + echo " stress - Stress test (14min, 4000 VUs, find breaking point)" + echo "" + echo "Environment Variables:" + echo " BASE_URL - Collector URL (default: http://localhost:5000)" + echo " BATCH_SIZE - Metrics per batch (default: 100)" + echo " DELAY_MS - Delay between requests in ms (default: 0.1)" + echo "" + echo "Examples:" + echo " $0 smoke # Run smoke test" + echo " BASE_URL=http://prod:5000 $0 medium # Test against production" + echo " BATCH_SIZE=500 $0 heavy # Heavy test with larger batches" +} + +# Main execution +main() { + if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then + usage + exit 0 + fi + + print_header "Faro Load Test Runner" + + check_k6 + check_services + get_baseline_metrics + monitor_clickhouse + + echo "" + read -p "Press Enter to start the test, or Ctrl+C to cancel..." + echo "" + + run_load_test + TEST_RESULT=$? + + generate_report + validate_results + + print_header "Test Complete" + + print_info "Results saved to: ${OUTPUT_DIR}" + print_info "View detailed metrics in:" + print_info " - ${OUTPUT_DIR}/summary.json" + print_info " - ${OUTPUT_DIR}/results.json" + print_info " - ${OUTPUT_DIR}/test.log" + + exit $TEST_RESULT +} + +# Run main function +main "$@" diff --git a/tests/load/test-configs.yaml b/tests/load/test-configs.yaml new file mode 100644 index 0000000..85d4b84 --- /dev/null +++ b/tests/load/test-configs.yaml @@ -0,0 +1,240 @@ +# Faro Load Test Configurations +# +# This file documents recommended configurations for different +# deployment environments and testing scenarios. + +# Local Development (laptop/workstation) +local_dev: + description: "Testing on a local machine with Docker Desktop" + recommended_profile: "smoke" + max_profile: "light" + settings: + BASE_URL: "http://localhost:5000" + BATCH_SIZE: 100 + DELAY_MS: 0.5 + docker_resources: + collector_memory: "512M" + collector_cpus: "1" + consumer_memory: "512M" + consumer_cpus: "1" + clickhouse_memory: "2G" + clickhouse_cpus: "2" + kafka_memory: "1G" + kafka_cpus: "1" + notes: + - "Use smoke or light tests only" + - "Medium+ tests may overwhelm local system" + - "Monitor Docker Desktop memory usage" + +# Staging Environment (cloud VM) +staging: + description: "Testing on a staging server (4 CPU, 8GB RAM)" + recommended_profile: "medium" + max_profile: "heavy" + settings: + BASE_URL: "http://staging-collector:5000" + BATCH_SIZE: 200 + DELAY_MS: 0.1 + docker_resources: + collector_memory: "1G" + collector_cpus: "2" + consumer_memory: "1G" + consumer_cpus: "1" + clickhouse_memory: "4G" + clickhouse_cpus: "2" + kafka_memory: "2G" + kafka_cpus: "1" + notes: + - "Can handle medium and heavy profiles" + - "May need multiple k6 instances for heavy test" + - "Monitor disk I/O for ClickHouse" + +# Production Sizing (dedicated servers) +production: + description: "Production-grade deployment (8+ CPU, 32GB RAM)" + recommended_profile: "heavy" + max_profile: "stress" + settings: + BASE_URL: "http://prod-collector:5000" + BATCH_SIZE: 500 + DELAY_MS: 0.05 + docker_resources: + collector_memory: "4G" + collector_cpus: "4" + consumer_memory: "2G" + consumer_cpus: "2" + clickhouse_memory: "16G" + clickhouse_cpus: "4" + kafka_memory: "4G" + kafka_cpus: "2" + notes: + - "Can handle all test profiles" + - "Use distributed k6 for stress tests" + - "Monitor network bandwidth" + - "Enable ClickHouse replication for production" + +# Distributed Load Generation (1M+ metrics/sec) +distributed: + description: "Multiple k6 load generators for maximum throughput" + recommended_profile: "heavy" + max_profile: "stress" + settings: + BASE_URL: "http://load-balancer:5000" + BATCH_SIZE: 1000 + DELAY_MS: 0.01 + k6_instances: 5 + architecture: + - "5+ k6 instances (separate VMs/containers)" + - "Load balancer in front of collectors" + - "Multiple collector instances (3-5)" + - "Kafka cluster (3+ brokers)" + - "ClickHouse cluster (3+ nodes with replication)" + - "Multiple consumer instances (3-5)" + notes: + - "Required for validating 1M+ metrics/sec claim" + - "Each k6 instance can generate ~200k metrics/sec" + - "Monitor network bandwidth carefully" + - "Use k6 cloud for easier distributed testing" + +# Test Scenario Configurations +scenarios: + + # Quick validation (always run first) + smoke_test: + profile: "smoke" + duration: "30s" + target_throughput: "1,000 metrics/sec" + expected_metrics: "~30,000" + validation: + - "All services start successfully" + - "Metrics reach ClickHouse" + - "No errors in logs" + - "P95 latency < 500ms" + + # Sustained medium load + endurance_test: + profile: "medium" + duration: "15m" + target_throughput: "100,000 metrics/sec" + expected_metrics: "~90,000,000" + validation: + - "Failure rate < 5%" + - "P95 latency < 2s" + - "No memory leaks" + - "Consumer keeps up with Kafka" + + # Find breaking point + capacity_test: + profile: "stress" + duration: "14m" + target_throughput: "400,000+ metrics/sec" + validation: + - "Identify max sustainable throughput" + - "Document when system starts degrading" + - "Measure recovery time after load" + + # Realistic production simulation + production_simulation: + profile: "heavy" + duration: "1h" + target_throughput: "200,000 metrics/sec" + expected_metrics: "~720,000,000" + validation: + - "System remains stable for full hour" + - "Materialized views stay up-to-date" + - "Disk usage remains predictable" + - "No service restarts needed" + +# Performance Tuning Recommendations +tuning: + + # If you see high latency + high_latency: + symptoms: + - "P95 > 5s" + - "Increasing latency over time" + solutions: + - name: "Increase Collector flush frequency" + config: "MetricsCollector:FlushIntervalSeconds = 1" + - name: "Increase Kafka batch size" + config: "Kafka:ProducerConfig:BatchSize = 65536" + - name: "Add more collector instances" + method: "Scale horizontally" + - name: "Increase ClickHouse resources" + config: "More CPU/Memory for background merges" + + # If you see high failure rate + high_failures: + symptoms: + - "Failure rate > 10%" + - "Connection timeouts" + solutions: + - name: "Reduce load" + method: "Increase DELAY_MS or reduce VUs" + - name: "Increase batch sizes" + config: "BATCH_SIZE=500" + - name: "Check Kafka lag" + command: "docker exec faro-kafka kafka-consumer-groups --describe" + - name: "Scale consumers" + method: "Add more consumer instances" + + # If metrics don't reach ClickHouse + ingestion_issues: + symptoms: + - "k6 succeeds but ClickHouse count doesn't increase" + solutions: + - name: "Check consumer logs" + command: "docker-compose logs consumer" + - name: "Verify consumer is running" + command: "docker-compose ps consumer" + - name: "Check Kafka messages" + method: "Use Kafka UI at localhost:8080" + - name: "Verify ClickHouse is writable" + command: "curl 'http://localhost:8123/?query=INSERT+INTO+metrics+VALUES'" + + # If you run out of resources + resource_exhaustion: + symptoms: + - "Out of memory errors" + - "High CPU usage (>90%)" + - "Disk full" + solutions: + - name: "Increase Docker resources" + method: "Docker Desktop → Resources → Memory/CPU" + - name: "Enable ClickHouse TTL" + config: "Verify TTL is active in schema" + - name: "Reduce test intensity" + method: "Use lighter test profile" + - name: "Clean old data" + command: "curl 'http://localhost:8123/' --data 'OPTIMIZE TABLE metrics FINAL'" + +# Expected Performance Baselines +# Update these with your actual results! +baselines: + local_laptop: + hardware: "MacBook Pro M1, 16GB RAM" + smoke_test: + throughput: "TBD" + p95_latency: "TBD" + failure_rate: "TBD" + light_test: + throughput: "TBD" + p95_latency: "TBD" + failure_rate: "TBD" + + cloud_vm_small: + hardware: "AWS t3.xlarge (4 vCPU, 16GB RAM)" + medium_test: + throughput: "TBD" + p95_latency: "TBD" + failure_rate: "TBD" + + cloud_vm_large: + hardware: "AWS c5.4xlarge (16 vCPU, 32GB RAM)" + heavy_test: + throughput: "TBD" + p95_latency: "TBD" + failure_rate: "TBD" + stress_test: + max_throughput: "TBD" + breaking_point: "TBD" diff --git a/tests/load/verify-ingestion.sh b/tests/load/verify-ingestion.sh new file mode 100755 index 0000000..d421716 --- /dev/null +++ b/tests/load/verify-ingestion.sh @@ -0,0 +1,129 @@ +#!/bin/bash + +####################################### +# Verify Metrics Ingestion +# +# This script validates that metrics from the load test +# successfully made it through the entire pipeline to ClickHouse +####################################### + +set -e + +# Colors +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +CLICKHOUSE_URL=${CLICKHOUSE_URL:-"http://localhost:8123"} + +echo "" +echo -e "${BLUE}========================================${NC}" +echo -e "${BLUE}Faro Metrics Ingestion Verification${NC}" +echo -e "${BLUE}========================================${NC}" +echo "" + +# Check ClickHouse connectivity +echo -e "${BLUE}[1/7]${NC} Checking ClickHouse connectivity..." +if curl -sf "${CLICKHOUSE_URL}/ping" > /dev/null 2>&1; then + echo -e "${GREEN}✓${NC} ClickHouse is responding" +else + echo -e "${YELLOW}✗${NC} ClickHouse is not responding at ${CLICKHOUSE_URL}" + exit 1 +fi + +# Total metrics count +echo "" +echo -e "${BLUE}[2/7]${NC} Checking total metrics count..." +TOTAL_COUNT=$(curl -s "${CLICKHOUSE_URL}/?query=SELECT+count(*)+FROM+metrics" 2>/dev/null || echo "0") +echo -e "${GREEN}✓${NC} Total metrics in database: ${TOTAL_COUNT}" + +# Recent metrics (last 5 minutes) +echo "" +echo -e "${BLUE}[3/7]${NC} Checking recent metrics (last 5 minutes)..." +RECENT_COUNT=$(curl -s "${CLICKHOUSE_URL}/" --data "SELECT count(*) FROM metrics WHERE timestamp >= now() - INTERVAL 5 MINUTE" 2>/dev/null || echo "0") +echo -e "${GREEN}✓${NC} Metrics ingested in last 5 minutes: ${RECENT_COUNT}" + +if [ "$RECENT_COUNT" -gt 0 ]; then + echo -e "${GREEN}✓${NC} Recent ingestion is working!" +else + echo -e "${YELLOW}⚠${NC} No recent metrics found. Was a load test running?" +fi + +# Metrics by service +echo "" +echo -e "${BLUE}[4/7]${NC} Checking metrics distribution by service..." +curl -s "${CLICKHOUSE_URL}/" --data " +SELECT + service, + count() as metric_count, + min(timestamp) as earliest, + max(timestamp) as latest +FROM metrics +GROUP BY service +ORDER BY metric_count DESC +LIMIT 10 +FORMAT PrettyCompact +" 2>/dev/null + +# Metrics by name +echo "" +echo -e "${BLUE}[5/7]${NC} Checking metrics distribution by name..." +curl -s "${CLICKHOUSE_URL}/" --data " +SELECT + metric_name, + count() as metric_count +FROM metrics +GROUP BY metric_name +ORDER BY metric_count DESC +LIMIT 10 +FORMAT PrettyCompact +" 2>/dev/null + +# Ingestion rate over last hour +echo "" +echo -e "${BLUE}[6/7]${NC} Checking ingestion rate over last hour..." +curl -s "${CLICKHOUSE_URL}/" --data " +SELECT + toStartOfMinute(timestamp) as minute, + count() as metrics_per_minute, + round(count() / 60, 2) as metrics_per_second +FROM metrics +WHERE timestamp >= now() - INTERVAL 1 HOUR +GROUP BY minute +ORDER BY minute DESC +LIMIT 10 +FORMAT PrettyCompact +" 2>/dev/null + +# Check materialized views +echo "" +echo -e "${BLUE}[7/7]${NC} Checking materialized views..." + +METRICS_1M_COUNT=$(curl -s "${CLICKHOUSE_URL}/" --data "SELECT count(*) FROM metrics_1m" 2>/dev/null || echo "0") +echo -e "${GREEN}✓${NC} metrics_1m view: ${METRICS_1M_COUNT} rows" + +METRICS_1H_COUNT=$(curl -s "${CLICKHOUSE_URL}/" --data "SELECT count(*) FROM metrics_1h" 2>/dev/null || echo "0") +echo -e "${GREEN}✓${NC} metrics_1h view: ${METRICS_1H_COUNT} rows" + +# Summary +echo "" +echo -e "${BLUE}========================================${NC}" +echo -e "${BLUE}Summary${NC}" +echo -e "${BLUE}========================================${NC}" +echo "" +echo "Total Metrics: ${TOTAL_COUNT}" +echo "Recent (5m): ${RECENT_COUNT}" +echo "1-min aggregates: ${METRICS_1M_COUNT}" +echo "1-hour aggregates: ${METRICS_1H_COUNT}" +echo "" + +# Calculate throughput if we have recent data +if [ "$RECENT_COUNT" -gt 0 ]; then + THROUGHPUT=$((RECENT_COUNT / 300)) # 300 seconds = 5 minutes + echo -e "${GREEN}✓${NC} Average throughput (last 5m): ~${THROUGHPUT} metrics/second" +fi + +echo "" +echo -e "${GREEN}Verification complete!${NC}" +echo "" From bf04d59f3c4e0dcae2a7214556c5b04fefbca90b Mon Sep 17 00:00:00 2001 From: Sean Ankenbruck Date: Sat, 21 Feb 2026 16:08:32 -0500 Subject: [PATCH 2/3] improve test coverage for new components like kafka and storage --- .../AlertEvaluatorTests.cs | 250 ++++++++++++++ .../AlertingEngineWorkerTests.cs | 264 +++++++++++++++ .../HealthControllerTests.cs | 208 ++++++++++++ .../KafkaProducerServiceTests.cs | 194 +++++++++++ .../ClickHouseConnectionFactoryTests.cs | 317 ++++++++++++++++++ .../ServiceCollectionExtensionsTests.cs | 248 ++++++++++++++ 6 files changed, 1481 insertions(+) create mode 100644 tests/Faro.Collector.Tests/HealthControllerTests.cs create mode 100644 tests/Faro.Collector.Tests/KafkaProducerServiceTests.cs create mode 100644 tests/Faro.Storage.Tests/ClickHouseConnectionFactoryTests.cs create mode 100644 tests/Faro.Storage.Tests/ServiceCollectionExtensionsTests.cs diff --git a/tests/Faro.AlertingEngine.Tests/AlertEvaluatorTests.cs b/tests/Faro.AlertingEngine.Tests/AlertEvaluatorTests.cs index d55203f..c427460 100644 --- a/tests/Faro.AlertingEngine.Tests/AlertEvaluatorTests.cs +++ b/tests/Faro.AlertingEngine.Tests/AlertEvaluatorTests.cs @@ -82,4 +82,254 @@ public void AlertEvaluationResult_Success_ContainsValue() Assert.True(result.ConditionMet); Assert.Equal(AlertState.Firing, result.NewState); } + + [Theory] + [InlineData(ComparisonOperator.GreaterThan, 150.0, 100.0, true)] + [InlineData(ComparisonOperator.GreaterThan, 50.0, 100.0, false)] + [InlineData(ComparisonOperator.LessThan, 50.0, 100.0, true)] + [InlineData(ComparisonOperator.LessThan, 150.0, 100.0, false)] + [InlineData(ComparisonOperator.GreaterThanOrEqual, 100.0, 100.0, true)] + [InlineData(ComparisonOperator.GreaterThanOrEqual, 101.0, 100.0, true)] + [InlineData(ComparisonOperator.GreaterThanOrEqual, 99.0, 100.0, false)] + [InlineData(ComparisonOperator.LessThanOrEqual, 100.0, 100.0, true)] + [InlineData(ComparisonOperator.LessThanOrEqual, 99.0, 100.0, true)] + [InlineData(ComparisonOperator.LessThanOrEqual, 101.0, 100.0, false)] + [InlineData(ComparisonOperator.Equal, 100.0, 100.0, true)] + [InlineData(ComparisonOperator.Equal, 100.00001, 100.0, true)] + [InlineData(ComparisonOperator.Equal, 101.0, 100.0, false)] + [InlineData(ComparisonOperator.NotEqual, 101.0, 100.0, true)] + [InlineData(ComparisonOperator.NotEqual, 100.0, 100.0, false)] + public void AlertCondition_ComparisonOperators_EvaluateCorrectly( + ComparisonOperator op, double value, double threshold, bool expectedResult) + { + var condition = new AlertCondition + { + Operator = op, + Threshold = threshold + }; + + // This is testing the condition logic that would be used in evaluation + bool actualResult = op switch + { + ComparisonOperator.GreaterThan => value > threshold, + ComparisonOperator.LessThan => value < threshold, + ComparisonOperator.GreaterThanOrEqual => value >= threshold, + ComparisonOperator.LessThanOrEqual => value <= threshold, + ComparisonOperator.Equal => Math.Abs(value - threshold) < 0.0001, + ComparisonOperator.NotEqual => Math.Abs(value - threshold) >= 0.0001, + _ => false + }; + + Assert.Equal(expectedResult, actualResult); + } + + [Fact] + public void AlertRule_WithAllProperties_CreatesSuccessfully() + { + var rule = new AlertRule + { + Id = "test-rule", + Name = "High CPU Alert", + Description = "Alerts when CPU exceeds threshold", + Query = "SELECT avg(value) FROM metrics WHERE metric_name = 'cpu.usage'", + EvaluationInterval = TimeSpan.FromMinutes(1), + For = TimeSpan.FromMinutes(5), + Condition = new AlertCondition + { + Operator = ComparisonOperator.GreaterThan, + Threshold = 80.0 + }, + NotificationChannels = new List { "email", "webhook" }, + Labels = new Dictionary + { + ["severity"] = "critical", + ["team"] = "platform" + }, + Enabled = true + }; + + Assert.Equal("test-rule", rule.Id); + Assert.Equal("High CPU Alert", rule.Name); + Assert.Equal(TimeSpan.FromMinutes(1), rule.EvaluationInterval); + Assert.Equal(TimeSpan.FromMinutes(5), rule.For); + Assert.True(rule.Enabled); + Assert.Equal(2, rule.NotificationChannels.Count); + Assert.Equal(2, rule.Labels.Count); + } + + [Fact] + public void AlertInstance_InitialState_IsOK() + { + var instance = new AlertInstance + { + RuleId = "test-rule" + }; + + Assert.Equal(AlertState.OK, instance.State); + Assert.Null(instance.CurrentValue); + Assert.Null(instance.FirstFiredAt); + Assert.Equal(0, instance.ConsecutiveFailures); + } + + [Fact] + public void AlertInstance_StateTransitions_Tracked() + { + var instance = new AlertInstance + { + RuleId = "test-rule", + State = AlertState.OK + }; + + instance.State = AlertState.Pending; + Assert.Equal(AlertState.Pending, instance.State); + + instance.State = AlertState.Firing; + Assert.Equal(AlertState.Firing, instance.State); + + instance.State = AlertState.Resolved; + Assert.Equal(AlertState.Resolved, instance.State); + } + + [Fact] + public void AlertState_AllStatesExist() + { + var states = new[] + { + AlertState.OK, + AlertState.Pending, + AlertState.Firing, + AlertState.Resolved + }; + + Assert.Equal(4, states.Length); + Assert.Contains(AlertState.OK, states); + Assert.Contains(AlertState.Pending, states); + Assert.Contains(AlertState.Firing, states); + Assert.Contains(AlertState.Resolved, states); + } + + [Fact] + public void AlertCondition_SupportsAllOperators() + { + var operators = new[] + { + ComparisonOperator.GreaterThan, + ComparisonOperator.LessThan, + ComparisonOperator.GreaterThanOrEqual, + ComparisonOperator.LessThanOrEqual, + ComparisonOperator.Equal, + ComparisonOperator.NotEqual + }; + + foreach (var op in operators) + { + var condition = new AlertCondition + { + Operator = op, + Threshold = 100.0 + }; + + Assert.Equal(op, condition.Operator); + Assert.Equal(100.0, condition.Threshold); + } + } + + [Fact] + public void AlertEvaluationResult_WithError_HasNoValue() + { + var result = AlertEvaluationResult.Error("test-rule", "Database connection failed"); + + Assert.Equal("test-rule", result.RuleId); + Assert.NotNull(result.ErrorMessage); + Assert.Equal("Database connection failed", result.ErrorMessage); + Assert.Null(result.Value); + } + + [Fact] + public void AlertEvaluationResult_NoData_HasExpectedDefaults() + { + var result = AlertEvaluationResult.NoData("test-rule"); + + Assert.Equal("test-rule", result.RuleId); + Assert.Null(result.Value); + Assert.False(result.ConditionMet); + Assert.Equal(AlertState.OK, result.NewState); + Assert.Null(result.ErrorMessage); + Assert.NotEqual(default(DateTime), result.EvaluatedAt); + } + + [Fact] + public void AlertRule_DisabledRule_CanBeCreated() + { + var rule = new AlertRule + { + Id = "disabled-rule", + Name = "Disabled Rule", + Query = "SELECT 1", + Condition = new AlertCondition + { + Operator = ComparisonOperator.GreaterThan, + Threshold = 100.0 + }, + Enabled = false + }; + + Assert.False(rule.Enabled); + } + + [Theory] + [InlineData(1)] + [InlineData(30)] + [InlineData(60)] + [InlineData(300)] + public void AlertRule_SupportsVariousEvaluationIntervals(int seconds) + { + var rule = new AlertRule + { + Id = "test-rule", + Name = "Test Rule", + Query = "SELECT 1", + EvaluationInterval = TimeSpan.FromSeconds(seconds), + Condition = new AlertCondition + { + Operator = ComparisonOperator.GreaterThan, + Threshold = 100.0 + } + }; + + Assert.Equal(TimeSpan.FromSeconds(seconds), rule.EvaluationInterval); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(5)] + [InlineData(10)] + public void AlertInstance_TracksConsecutiveFailures(int failures) + { + var instance = new AlertInstance + { + RuleId = "test-rule", + ConsecutiveFailures = failures + }; + + Assert.Equal(failures, instance.ConsecutiveFailures); + } + + [Fact] + public void AlertInstance_AllTimestampsTracked() + { + var now = DateTime.UtcNow; + var instance = new AlertInstance + { + RuleId = "test-rule", + FirstFiredAt = now, + LastEvaluatedAt = now.AddMinutes(1), + LastNotifiedAt = now.AddMinutes(2) + }; + + Assert.Equal(now, instance.FirstFiredAt); + Assert.Equal(now.AddMinutes(1), instance.LastEvaluatedAt); + Assert.Equal(now.AddMinutes(2), instance.LastNotifiedAt); + } } diff --git a/tests/Faro.AlertingEngine.Tests/AlertingEngineWorkerTests.cs b/tests/Faro.AlertingEngine.Tests/AlertingEngineWorkerTests.cs index 30ab259..60aebc7 100644 --- a/tests/Faro.AlertingEngine.Tests/AlertingEngineWorkerTests.cs +++ b/tests/Faro.AlertingEngine.Tests/AlertingEngineWorkerTests.cs @@ -140,6 +140,270 @@ public void AlertRule_SupportsLabelsForSeverityMapping() Assert.Equal(2, rule.Labels.Count); } + [Fact] + public void AlertState_Transitions_FromOKToPending() + { + var previousState = AlertState.OK; + var newState = AlertState.Pending; + + var shouldNotify = ShouldNotify(previousState, newState); + + Assert.False(shouldNotify); + } + + [Fact] + public void AlertState_Transitions_FromPendingToFiring_ShouldNotify() + { + var previousState = AlertState.Pending; + var newState = AlertState.Firing; + + var shouldNotify = ShouldNotify(previousState, newState); + + Assert.True(shouldNotify); + } + + [Fact] + public void AlertState_Transitions_FromFiringToResolved_ShouldNotify() + { + var previousState = AlertState.Firing; + var newState = AlertState.Resolved; + + var shouldNotify = ShouldNotify(previousState, newState); + + Assert.True(shouldNotify); + } + + [Fact] + public void AlertState_Transitions_FromOKToFiring_ShouldNotify() + { + var previousState = AlertState.OK; + var newState = AlertState.Firing; + + var shouldNotify = ShouldNotify(previousState, newState); + + Assert.True(shouldNotify); + } + + [Fact] + public void AlertState_NoTransition_ShouldNotNotify() + { + var states = new[] { AlertState.OK, AlertState.Pending, AlertState.Firing, AlertState.Resolved }; + + foreach (var state in states) + { + var shouldNotify = ShouldNotify(state, state); + Assert.False(shouldNotify); + } + } + + [Theory] + [InlineData("critical", NotificationSeverity.Critical)] + [InlineData("warning", NotificationSeverity.Warning)] + [InlineData("info", NotificationSeverity.Info)] + public void DetermineSeverity_MapsLabelToSeverity(string label, NotificationSeverity expectedSeverity) + { + var labels = new Dictionary + { + ["severity"] = label + }; + + var severity = DetermineSeverity(labels); + + Assert.Equal(expectedSeverity, severity); + } + + [Fact] + public void DetermineSeverity_UnknownLabel_ReturnsWarning() + { + var labels = new Dictionary + { + ["severity"] = "unknown" + }; + + var severity = DetermineSeverity(labels); + + Assert.Equal(NotificationSeverity.Warning, severity); + } + + [Fact] + public void DetermineSeverity_NoSeverityLabel_ReturnsWarning() + { + var labels = new Dictionary + { + ["team"] = "platform" + }; + + var severity = DetermineSeverity(labels); + + Assert.Equal(NotificationSeverity.Warning, severity); + } + + [Fact] + public void DetermineSeverity_EmptyLabels_ReturnsWarning() + { + var labels = new Dictionary(); + + var severity = DetermineSeverity(labels); + + Assert.Equal(NotificationSeverity.Warning, severity); + } + + [Fact] + public void NotificationMessage_ContainsMetadata() + { + var message = new NotificationMessage + { + Title = "Test Alert", + Body = "Alert body", + Severity = NotificationSeverity.Critical, + Metadata = new Dictionary + { + ["rule_id"] = "test-rule", + ["state"] = "Firing" + } + }; + + Assert.NotNull(message.Metadata); + Assert.Equal(2, message.Metadata.Count); + Assert.Equal("test-rule", message.Metadata["rule_id"]); + Assert.Equal("Firing", message.Metadata["state"]); + } + + [Fact] + public void AlertRule_WithMultipleChannels_ConfiguredCorrectly() + { + var rule = CreateTestRule("test-rule"); + rule.NotificationChannels = new List { "email", "webhook", "pagerduty" }; + + Assert.Equal(3, rule.NotificationChannels.Count); + Assert.Contains("email", rule.NotificationChannels); + Assert.Contains("webhook", rule.NotificationChannels); + Assert.Contains("pagerduty", rule.NotificationChannels); + } + + [Fact] + public void AlertRule_DefaultEvaluationInterval_IsOneMinute() + { + var rule = new AlertRule + { + Id = "test", + Name = "Test" + }; + + Assert.Equal(TimeSpan.FromMinutes(1), rule.EvaluationInterval); + } + + [Fact] + public void AlertRule_DefaultForDuration_IsFiveMinutes() + { + var rule = new AlertRule + { + Id = "test", + Name = "Test" + }; + + Assert.Equal(TimeSpan.FromMinutes(5), rule.For); + } + + [Fact] + public void AlertRule_DefaultEnabled_IsTrue() + { + var rule = new AlertRule + { + Id = "test", + Name = "Test" + }; + + Assert.True(rule.Enabled); + } + + [Fact] + public void NotificationSeverity_AllLevelsExist() + { + var severities = new[] + { + NotificationSeverity.Info, + NotificationSeverity.Warning, + NotificationSeverity.Critical + }; + + Assert.Equal(3, severities.Length); + } + + [Fact] + public void AlertInstance_DefaultConsecutiveFailures_IsZero() + { + var instance = new AlertInstance + { + RuleId = "test-rule" + }; + + Assert.Equal(0, instance.ConsecutiveFailures); + } + + [Fact] + public void AlertInstance_DefaultState_IsOK() + { + var instance = new AlertInstance + { + RuleId = "test-rule" + }; + + Assert.Equal(AlertState.OK, instance.State); + } + + [Fact] + public void AlertCondition_WithThreshold_StoresCorrectly() + { + var condition = new AlertCondition + { + Operator = ComparisonOperator.GreaterThan, + Threshold = 85.5 + }; + + Assert.Equal(ComparisonOperator.GreaterThan, condition.Operator); + Assert.Equal(85.5, condition.Threshold); + } + + [Theory] + [InlineData(0.0)] + [InlineData(50.0)] + [InlineData(100.0)] + [InlineData(-50.0)] + public void AlertCondition_SupportsVariousThresholds(double threshold) + { + var condition = new AlertCondition + { + Operator = ComparisonOperator.GreaterThan, + Threshold = threshold + }; + + Assert.Equal(threshold, condition.Threshold); + } + + // Helper methods that match the Worker class logic + private bool ShouldNotify(AlertState previousState, AlertState newState) + { + return previousState != newState && + (newState == AlertState.Firing || newState == AlertState.Resolved); + } + + private NotificationSeverity DetermineSeverity(Dictionary labels) + { + if (labels.TryGetValue("severity", out var severity)) + { + return severity.ToLowerInvariant() switch + { + "critical" => NotificationSeverity.Critical, + "warning" => NotificationSeverity.Warning, + "info" => NotificationSeverity.Info, + _ => NotificationSeverity.Warning + }; + } + + return NotificationSeverity.Warning; + } + private AlertRule CreateTestRule(string id, bool enabled = true) { return new AlertRule diff --git a/tests/Faro.Collector.Tests/HealthControllerTests.cs b/tests/Faro.Collector.Tests/HealthControllerTests.cs new file mode 100644 index 0000000..5411aca --- /dev/null +++ b/tests/Faro.Collector.Tests/HealthControllerTests.cs @@ -0,0 +1,208 @@ +using Faro.Collector.Controllers; +using Faro.Storage; +using Microsoft.AspNetCore.Mvc; +using Moq; + +namespace Faro.Collector.Tests; + +public class HealthControllerTests +{ + private readonly Mock _mockRepository; + private readonly HealthController _controller; + + public HealthControllerTests() + { + _mockRepository = new Mock(); + _controller = new HealthController(_mockRepository.Object); + } + + [Fact] + public async Task Get_WhenHealthy_ReturnsOkWithHealthyStatus() + { + _mockRepository.Setup(r => r.HealthCheckAsync(It.IsAny())) + .ReturnsAsync(true); + + var result = await _controller.Get(); + + var okResult = Assert.IsType(result); + Assert.NotNull(okResult.Value); + + var responseType = okResult.Value!.GetType(); + var statusProperty = responseType.GetProperty("status"); + var timestampProperty = responseType.GetProperty("timestamp"); + + Assert.NotNull(statusProperty); + Assert.NotNull(timestampProperty); + + var statusValue = statusProperty.GetValue(okResult.Value) as string; + Assert.Equal("healthy", statusValue); + } + + [Fact] + public async Task Get_WhenUnhealthy_ReturnsServiceUnavailable() + { + _mockRepository.Setup(r => r.HealthCheckAsync(It.IsAny())) + .ReturnsAsync(false); + + var result = await _controller.Get(); + + var statusCodeResult = Assert.IsType(result); + Assert.Equal(503, statusCodeResult.StatusCode); + Assert.NotNull(statusCodeResult.Value); + + var responseType = statusCodeResult.Value!.GetType(); + var statusProperty = responseType.GetProperty("status"); + var timestampProperty = responseType.GetProperty("timestamp"); + + Assert.NotNull(statusProperty); + Assert.NotNull(timestampProperty); + + var statusValue = statusProperty.GetValue(statusCodeResult.Value) as string; + Assert.Equal("unhealthy", statusValue); + } + + [Fact] + public async Task Get_CallsRepositoryHealthCheck() + { + _mockRepository.Setup(r => r.HealthCheckAsync(It.IsAny())) + .ReturnsAsync(true); + + await _controller.Get(); + + _mockRepository.Verify( + r => r.HealthCheckAsync(It.IsAny()), + Times.Once); + } + + [Fact] + public async Task Get_WhenRepositoryThrows_PropagatesException() + { + _mockRepository.Setup(r => r.HealthCheckAsync(It.IsAny())) + .ThrowsAsync(new Exception("Database connection failed")); + + await Assert.ThrowsAsync(() => _controller.Get()); + } + + [Fact] + public async Task Get_ReturnsTimestamp() + { + _mockRepository.Setup(r => r.HealthCheckAsync(It.IsAny())) + .ReturnsAsync(true); + + var beforeCall = DateTime.UtcNow; + var result = await _controller.Get(); + var afterCall = DateTime.UtcNow; + + var okResult = Assert.IsType(result); + + var responseType = okResult.Value!.GetType(); + var timestampProperty = responseType.GetProperty("timestamp"); + Assert.NotNull(timestampProperty); + + var timestamp = (DateTime)timestampProperty.GetValue(okResult.Value)!; + Assert.InRange(timestamp, beforeCall.AddSeconds(-1), afterCall.AddSeconds(1)); + } + + [Fact] + public async Task Get_WithCancellationToken_PassesToRepository() + { + _mockRepository.Setup(r => r.HealthCheckAsync(It.IsAny())) + .ReturnsAsync(true); + + var result = await _controller.Get(); + + var okResult = Assert.IsType(result); + Assert.NotNull(okResult.Value); + } + + [Fact] + public async Task Get_MultipleCallsWhenHealthy_ConsistentlyReturnsOk() + { + _mockRepository.Setup(r => r.HealthCheckAsync(It.IsAny())) + .ReturnsAsync(true); + + for (int i = 0; i < 5; i++) + { + var result = await _controller.Get(); + Assert.IsType(result); + } + + _mockRepository.Verify( + r => r.HealthCheckAsync(It.IsAny()), + Times.Exactly(5)); + } + + [Fact] + public async Task Get_MultipleCallsWhenUnhealthy_ConsistentlyReturnsServiceUnavailable() + { + _mockRepository.Setup(r => r.HealthCheckAsync(It.IsAny())) + .ReturnsAsync(false); + + for (int i = 0; i < 3; i++) + { + var result = await _controller.Get(); + var statusCodeResult = Assert.IsType(result); + Assert.Equal(503, statusCodeResult.StatusCode); + } + } + + [Fact] + public async Task Get_StatusTransition_ReflectsRepositoryState() + { + // First call: healthy + _mockRepository.Setup(r => r.HealthCheckAsync(It.IsAny())) + .ReturnsAsync(true); + + var result1 = await _controller.Get(); + Assert.IsType(result1); + + // Second call: unhealthy + _mockRepository.Setup(r => r.HealthCheckAsync(It.IsAny())) + .ReturnsAsync(false); + + var result2 = await _controller.Get(); + var statusCodeResult = Assert.IsType(result2); + Assert.Equal(503, statusCodeResult.StatusCode); + + // Third call: healthy again + _mockRepository.Setup(r => r.HealthCheckAsync(It.IsAny())) + .ReturnsAsync(true); + + var result3 = await _controller.Get(); + Assert.IsType(result3); + } + + [Fact] + public async Task Get_ResponseIncludesCorrectStatusText() + { + _mockRepository.Setup(r => r.HealthCheckAsync(It.IsAny())) + .ReturnsAsync(true); + + var result = await _controller.Get(); + var okResult = Assert.IsType(result); + + var responseType = okResult.Value!.GetType(); + var statusProperty = responseType.GetProperty("status"); + Assert.NotNull(statusProperty); + + var statusValue = statusProperty.GetValue(okResult.Value) as string; + Assert.Equal("healthy", statusValue); + } + + [Fact] + public async Task Get_UnhealthyResponseIncludesCorrectStatusText() + { + _mockRepository.Setup(r => r.HealthCheckAsync(It.IsAny())) + .ReturnsAsync(false); + + var result = await _controller.Get(); + var statusCodeResult = Assert.IsType(result); + + var responseType = statusCodeResult.Value!.GetType(); + var statusProperty = responseType.GetProperty("status"); + Assert.NotNull(statusProperty); + + var statusValue = statusProperty.GetValue(statusCodeResult.Value) as string; + Assert.Equal("unhealthy", statusValue); + } +} diff --git a/tests/Faro.Collector.Tests/KafkaProducerServiceTests.cs b/tests/Faro.Collector.Tests/KafkaProducerServiceTests.cs new file mode 100644 index 0000000..a7dd964 --- /dev/null +++ b/tests/Faro.Collector.Tests/KafkaProducerServiceTests.cs @@ -0,0 +1,194 @@ +using Confluent.Kafka; +using Faro.Collector.Services; +using Faro.Shared.Models; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Moq; + +namespace Faro.Collector.Tests; + +public class KafkaProducerServiceTests +{ + private readonly Mock> _mockLogger; + private readonly IConfiguration _configuration; + + public KafkaProducerServiceTests() + { + _mockLogger = new Mock>(); + + var inMemorySettings = new Dictionary + { + ["Kafka:BootstrapServers"] = "localhost:9092", + ["Kafka:Topic"] = "test-metrics" + }; + + _configuration = new ConfigurationBuilder() + .AddInMemoryCollection(inMemorySettings!) + .Build(); + } + + [Fact] + public void Constructor_WithValidConfiguration_CreatesInstance() + { + var service = new KafkaProducerService(_configuration, _mockLogger.Object); + + Assert.NotNull(service); + } + + [Fact] + public void Constructor_WithoutTopic_UsesDefaultTopic() + { + var configWithoutTopic = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Kafka:BootstrapServers"] = "localhost:9092" + }!) + .Build(); + + var service = new KafkaProducerService(configWithoutTopic, _mockLogger.Object); + + Assert.NotNull(service); + _mockLogger.Verify( + x => x.Log( + LogLevel.Information, + It.IsAny(), + It.Is((v, t) => v.ToString()!.Contains("faro-metrics")), + null, + It.IsAny>()), + Times.Once); + } + + [Fact] + public void Constructor_LogsInitialization() + { + var service = new KafkaProducerService(_configuration, _mockLogger.Object); + + _mockLogger.Verify( + x => x.Log( + LogLevel.Information, + It.IsAny(), + It.Is((v, t) => v.ToString()!.Contains("Kafka producer initialized")), + null, + It.IsAny>()), + Times.Once); + } + + [Fact] + public void Dispose_CallsProducerFlushAndDispose() + { + var service = new KafkaProducerService(_configuration, _mockLogger.Object); + + // Should not throw + service.Dispose(); + } + + [Fact] + public void Constructor_ConfiguresProducerWithCorrectSettings() + { + var customConfig = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Kafka:BootstrapServers"] = "kafka.example.com:9093", + ["Kafka:Topic"] = "custom-topic" + }!) + .Build(); + + var service = new KafkaProducerService(customConfig, _mockLogger.Object); + + Assert.NotNull(service); + _mockLogger.Verify( + x => x.Log( + LogLevel.Information, + It.IsAny(), + It.Is((v, t) => v.ToString()!.Contains("custom-topic")), + null, + It.IsAny>()), + Times.Once); + } + + [Fact] + public void MetricPoint_SerializesToJson() + { + var metric = new MetricPoint + { + MetricName = "test.metric", + Value = 42.0, + Timestamp = DateTime.UtcNow, + Tags = new Dictionary + { + ["host"] = "test-host", + ["service"] = "test-service" + } + }; + + var json = System.Text.Json.JsonSerializer.Serialize(metric); + + Assert.Contains("test.metric", json); + Assert.Contains("42", json); + Assert.Contains("test-host", json); + } + + [Fact] + public void Configuration_SupportsCustomBootstrapServers() + { + var configs = new[] + { + "localhost:9092", + "kafka1:9092,kafka2:9092,kafka3:9092", + "broker.example.com:9093" + }; + + foreach (var bootstrapServers in configs) + { + var config = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Kafka:BootstrapServers"] = bootstrapServers + }!) + .Build(); + + var service = new KafkaProducerService(config, _mockLogger.Object); + Assert.NotNull(service); + } + } + + [Fact] + public void MetricPoint_WithEmptyTags_Serializes() + { + var metric = new MetricPoint + { + MetricName = "test.metric", + Value = 100.0, + Timestamp = DateTime.UtcNow, + Tags = new Dictionary() + }; + + var json = System.Text.Json.JsonSerializer.Serialize(metric); + + Assert.Contains("test.metric", json); + Assert.Contains("100", json); + } + + [Fact] + public void MetricPoint_WithManyTags_Serializes() + { + var tags = new Dictionary(); + for (int i = 0; i < 20; i++) + { + tags[$"tag{i}"] = $"value{i}"; + } + + var metric = new MetricPoint + { + MetricName = "test.metric", + Value = 42.0, + Timestamp = DateTime.UtcNow, + Tags = tags + }; + + var json = System.Text.Json.JsonSerializer.Serialize(metric); + + Assert.Contains("tag0", json); + Assert.Contains("tag19", json); + } +} diff --git a/tests/Faro.Storage.Tests/ClickHouseConnectionFactoryTests.cs b/tests/Faro.Storage.Tests/ClickHouseConnectionFactoryTests.cs new file mode 100644 index 0000000..b6a5895 --- /dev/null +++ b/tests/Faro.Storage.Tests/ClickHouseConnectionFactoryTests.cs @@ -0,0 +1,317 @@ +using Faro.Shared.Models; +using Faro.Storage; +using Faro.Storage.Configuration; +using Microsoft.Extensions.Options; + +namespace Faro.Storage.Tests; + +public class ClickHouseConnectionFactoryTests +{ + private readonly ClickHouseOptions _options; + private readonly IOptions _optionsWrapper; + + public ClickHouseConnectionFactoryTests() + { + _options = new ClickHouseOptions + { + Host = "localhost", + Port = 8123, + Database = "test_db", + Username = "test_user", + Password = "test_password" + }; + _optionsWrapper = Options.Create(_options); + } + + [Fact] + public void Constructor_WithValidOptions_CreatesInstance() + { + var factory = new ClickHouseConnectionFactory(_optionsWrapper); + + Assert.NotNull(factory); + } + + [Fact] + public void Constructor_WithCustomOptions_CreatesInstance() + { + var customOptions = Options.Create(new ClickHouseOptions + { + Host = "clickhouse.example.com", + Port = 9000, + Database = "metrics", + Username = "admin", + Password = "secure_pass" + }); + + var factory = new ClickHouseConnectionFactory(customOptions); + + Assert.NotNull(factory); + } + + [Theory] + [InlineData("localhost", 8123)] + [InlineData("192.168.1.100", 9000)] + [InlineData("clickhouse.local", 8123)] + public void Constructor_VariousHostsAndPorts_Accepted(string host, int port) + { + var options = Options.Create(new ClickHouseOptions + { + Host = host, + Port = port, + Database = "test", + Username = "user", + Password = "pass" + }); + + var factory = new ClickHouseConnectionFactory(options); + + Assert.NotNull(factory); + } + + [Fact] + public void ClickHouseOptions_ConnectionString_IsGenerated() + { + var options = new ClickHouseOptions + { + Host = "localhost", + Port = 8123, + Database = "metrics", + Username = "admin", + Password = "secret" + }; + + Assert.NotNull(options.ConnectionString); + Assert.Contains("localhost", options.ConnectionString); + Assert.Contains("8123", options.ConnectionString); + } + + [Fact] + public void ClickHouseOptions_ConnectionString_WithDifferentPorts() + { + var options8123 = new ClickHouseOptions + { + Host = "localhost", + Port = 8123, + Database = "test", + Username = "user", + Password = "pass" + }; + + var options9000 = new ClickHouseOptions + { + Host = "localhost", + Port = 9000, + Database = "test", + Username = "user", + Password = "pass" + }; + + Assert.Contains("8123", options8123.ConnectionString); + Assert.Contains("9000", options9000.ConnectionString); + } + + [Fact] + public void ClickHouseOptions_AllPropertiesSet() + { + var options = new ClickHouseOptions + { + Host = "db.example.com", + Port = 9000, + Database = "metrics_db", + Username = "writer", + Password = "pass123", + MaxRetries = 5 + }; + + Assert.Equal("db.example.com", options.Host); + Assert.Equal(9000, options.Port); + Assert.Equal("metrics_db", options.Database); + Assert.Equal("writer", options.Username); + Assert.Equal("pass123", options.Password); + Assert.Equal(5, options.MaxRetries); + } + + [Fact] + public void ClickHouseOptions_SectionName_IsCorrect() + { + Assert.Equal("ClickHouse", ClickHouseOptions.SectionName); + } + + [Fact] + public void ClickHouseOptions_DefaultMaxRetries() + { + var options = new ClickHouseOptions + { + Host = "localhost", + Port = 8123, + Database = "test", + Username = "user", + Password = "pass" + }; + + Assert.Equal(3, options.MaxRetries); + } + + [Theory] + [InlineData(1)] + [InlineData(3)] + [InlineData(5)] + [InlineData(10)] + public void ClickHouseOptions_CustomMaxRetries_Accepted(int maxRetries) + { + var options = new ClickHouseOptions + { + Host = "localhost", + Port = 8123, + Database = "test", + Username = "user", + Password = "pass", + MaxRetries = maxRetries + }; + + Assert.Equal(maxRetries, options.MaxRetries); + } + + [Fact] + public void ClickHouseOptions_EmptyPassword_Accepted() + { + var options = new ClickHouseOptions + { + Host = "localhost", + Port = 8123, + Database = "test", + Username = "default", + Password = "" + }; + + Assert.Empty(options.Password); + Assert.NotNull(options.ConnectionString); + } + + [Fact] + public void ClickHouseOptions_LongDatabaseName_Accepted() + { + var options = new ClickHouseOptions + { + Host = "localhost", + Port = 8123, + Database = "very_long_database_name_for_metrics_storage", + Username = "user", + Password = "pass" + }; + + Assert.Equal("very_long_database_name_for_metrics_storage", options.Database); + } + + [Fact] + public void ClickHouseOptions_SpecialCharactersInPassword_Accepted() + { + var options = new ClickHouseOptions + { + Host = "localhost", + Port = 8123, + Database = "test", + Username = "user", + Password = "p@ssw0rd!#$%" + }; + + Assert.Equal("p@ssw0rd!#$%", options.Password); + } + + [Fact] + public void MetricPoint_PreparedForBulkInsert() + { + var metric = new MetricPoint + { + MetricName = "test.metric", + Value = 42.0, + Timestamp = DateTime.UtcNow, + Tags = new Dictionary + { + ["host"] = "test-host", + ["service"] = "test-service", + ["environment"] = "production" + } + }; + + var row = new object[] + { + metric.Timestamp, + metric.MetricName, + metric.Value, + metric.Tags, + metric.Host, + metric.Service, + metric.Environment + }; + + Assert.Equal(7, row.Length); + Assert.Equal("test.metric", row[1]); + Assert.Equal(42.0, row[2]); + Assert.Equal("test-host", metric.Host); + Assert.Equal("test-service", metric.Service); + Assert.Equal("production", metric.Environment); + } + + [Fact] + public void MetricPoint_WithNullTags_HandledGracefully() + { + var metric = new MetricPoint + { + MetricName = "test.metric", + Value = 100.0, + Timestamp = DateTime.UtcNow, + Tags = new Dictionary() + }; + + Assert.NotNull(metric.Tags); + Assert.Empty(metric.Tags); + Assert.Empty(metric.Host); + Assert.Empty(metric.Service); + Assert.Empty(metric.Environment); + } + + [Fact] + public void MetricPoint_BulkInsertFormat_MatchesTableSchema() + { + var metrics = new List + { + new MetricPoint + { + MetricName = "cpu.usage", + Value = 75.5, + Timestamp = DateTime.UtcNow, + Tags = new Dictionary + { + ["host"] = "server1", + ["service"] = "api" + } + }, + new MetricPoint + { + MetricName = "memory.usage", + Value = 80.2, + Timestamp = DateTime.UtcNow, + Tags = new Dictionary + { + ["host"] = "server2", + ["service"] = "worker" + } + } + }; + + var rows = metrics.Select(m => new object[] + { + m.Timestamp, + m.MetricName, + m.Value, + m.Tags, + m.Host, + m.Service, + m.Environment + }).ToList(); + + Assert.Equal(2, rows.Count); + Assert.All(rows, row => Assert.Equal(7, row.Length)); + } +} diff --git a/tests/Faro.Storage.Tests/ServiceCollectionExtensionsTests.cs b/tests/Faro.Storage.Tests/ServiceCollectionExtensionsTests.cs new file mode 100644 index 0000000..4c142aa --- /dev/null +++ b/tests/Faro.Storage.Tests/ServiceCollectionExtensionsTests.cs @@ -0,0 +1,248 @@ +using Faro.Storage; +using Faro.Storage.Configuration; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +namespace Faro.Storage.Tests; + +public class ServiceCollectionExtensionsTests +{ + private readonly IConfiguration _configuration; + + public ServiceCollectionExtensionsTests() + { + var inMemorySettings = new Dictionary + { + ["ClickHouse:Host"] = "localhost", + ["ClickHouse:Port"] = "8123", + ["ClickHouse:Database"] = "test_db", + ["ClickHouse:Username"] = "test_user", + ["ClickHouse:Password"] = "test_password", + ["ClickHouse:MaxRetries"] = "3" + }; + + _configuration = new ConfigurationBuilder() + .AddInMemoryCollection(inMemorySettings!) + .Build(); + } + + [Fact] + public void AddMetricsStorage_RegistersClickHouseOptions() + { + var services = new ServiceCollection(); + + services.AddMetricsStorage(_configuration); + + var serviceProvider = services.BuildServiceProvider(); + var options = serviceProvider.GetService>(); + + Assert.NotNull(options); + Assert.NotNull(options.Value); + Assert.Equal("localhost", options.Value.Host); + Assert.Equal(8123, options.Value.Port); + Assert.Equal("test_db", options.Value.Database); + Assert.Equal("test_user", options.Value.Username); + Assert.Equal("test_password", options.Value.Password); + Assert.Equal(3, options.Value.MaxRetries); + } + + [Fact] + public void AddMetricsStorage_RegistersClickHouseConnectionFactory() + { + var services = new ServiceCollection(); + services.AddLogging(); + + services.AddMetricsStorage(_configuration); + + var serviceProvider = services.BuildServiceProvider(); + var factory = serviceProvider.GetService(); + + Assert.NotNull(factory); + Assert.IsType(factory); + } + + [Fact] + public void AddMetricsStorage_RegistersMetricsRepository() + { + var services = new ServiceCollection(); + services.AddLogging(); + + services.AddMetricsStorage(_configuration); + + var serviceProvider = services.BuildServiceProvider(); + var repository = serviceProvider.GetService(); + + Assert.NotNull(repository); + Assert.IsType(repository); + } + + [Fact] + public void AddMetricsStorage_AllServicesRegisteredAsSingleton() + { + var services = new ServiceCollection(); + services.AddLogging(); + + services.AddMetricsStorage(_configuration); + + var serviceProvider = services.BuildServiceProvider(); + + // Get instances multiple times + var factory1 = serviceProvider.GetService(); + var factory2 = serviceProvider.GetService(); + + var repo1 = serviceProvider.GetService(); + var repo2 = serviceProvider.GetService(); + + // Should be same instances (singleton) + Assert.Same(factory1, factory2); + Assert.Same(repo1, repo2); + } + + [Fact] + public void AddMetricsStorage_ReturnsServiceCollection() + { + var services = new ServiceCollection(); + + var result = services.AddMetricsStorage(_configuration); + + Assert.Same(services, result); + } + + [Fact] + public void AddMetricsStorage_CanChainWithOtherRegistrations() + { + var services = new ServiceCollection(); + + services + .AddMetricsStorage(_configuration) + .AddLogging(); + + var serviceProvider = services.BuildServiceProvider(); + + Assert.NotNull(serviceProvider.GetService()); + } + + [Fact] + public void AddMetricsStorage_WithDifferentConfiguration_UsesProvidedValues() + { + var customConfig = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["ClickHouse:Host"] = "custom.host.com", + ["ClickHouse:Port"] = "9000", + ["ClickHouse:Database"] = "custom_db", + ["ClickHouse:Username"] = "custom_user", + ["ClickHouse:Password"] = "custom_pass", + ["ClickHouse:MaxRetries"] = "5" + }!) + .Build(); + + var services = new ServiceCollection(); + services.AddMetricsStorage(customConfig); + + var serviceProvider = services.BuildServiceProvider(); + var options = serviceProvider.GetService>(); + + Assert.Equal("custom.host.com", options!.Value.Host); + Assert.Equal(9000, options.Value.Port); + Assert.Equal("custom_db", options.Value.Database); + Assert.Equal("custom_user", options.Value.Username); + Assert.Equal("custom_pass", options.Value.Password); + Assert.Equal(5, options.Value.MaxRetries); + } + + [Fact] + public void AddMetricsStorage_WithMissingConfiguration_UsesDefaults() + { + var emptyConfig = new ConfigurationBuilder().Build(); + + var services = new ServiceCollection(); + services.AddMetricsStorage(emptyConfig); + + var serviceProvider = services.BuildServiceProvider(); + var options = serviceProvider.GetService>(); + + Assert.NotNull(options); + // Default values from ClickHouseOptions + Assert.Equal(3, options.Value.MaxRetries); + } + + [Fact] + public void AddMetricsStorage_RegisteredServicesCanBeResolved() + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddMetricsStorage(_configuration); + + var serviceProvider = services.BuildServiceProvider(); + + // Should be able to resolve all registered types + var factory = serviceProvider.GetRequiredService(); + var repository = serviceProvider.GetRequiredService(); + var options = serviceProvider.GetRequiredService>(); + + Assert.NotNull(factory); + Assert.NotNull(repository); + Assert.NotNull(options); + } + + [Fact] + public void AddMetricsStorage_OptionsBindingWorks() + { + var services = new ServiceCollection(); + services.AddMetricsStorage(_configuration); + + var serviceProvider = services.BuildServiceProvider(); + var options = serviceProvider.GetRequiredService>(); + + // Verify that options are bound from configuration + Assert.NotNull(options.Value.ConnectionString); + Assert.Contains("localhost", options.Value.ConnectionString); + } + + [Fact] + public void AddMetricsStorage_MultipleCallsDoNotDuplicate() + { + var services = new ServiceCollection(); + services.AddLogging(); + + services.AddMetricsStorage(_configuration); + services.AddMetricsStorage(_configuration); + + var serviceProvider = services.BuildServiceProvider(); + + // Should still work without errors + var repository = serviceProvider.GetService(); + Assert.NotNull(repository); + } + + [Fact] + public void AddMetricsStorage_WorksInAspNetCoreScenario() + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddOptions(); + services.AddMetricsStorage(_configuration); + + var serviceProvider = services.BuildServiceProvider(); + + using var scope = serviceProvider.CreateScope(); + var repository = scope.ServiceProvider.GetRequiredService(); + + Assert.NotNull(repository); + } + + [Fact] + public void ClickHouseOptions_SectionName_MatchesConfiguration() + { + var services = new ServiceCollection(); + services.AddMetricsStorage(_configuration); + + var serviceProvider = services.BuildServiceProvider(); + var options = serviceProvider.GetRequiredService>(); + + // Verify configuration section name is correct + Assert.Equal("ClickHouse", ClickHouseOptions.SectionName); + } +} From b7c0f86ae37cf353111c9ea63bed4be55bf076d7 Mon Sep 17 00:00:00 2001 From: Sean Ankenbruck Date: Sat, 21 Feb 2026 16:29:19 -0500 Subject: [PATCH 3/3] fix code coverage reference --- .github/workflows/test-coverage.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test-coverage.yaml b/.github/workflows/test-coverage.yaml index 7dedf1a..e0883ba 100644 --- a/.github/workflows/test-coverage.yaml +++ b/.github/workflows/test-coverage.yaml @@ -44,6 +44,6 @@ jobs: uses: codecov/codecov-action@v4 with: token: ${{ secrets.CODECOV_TOKEN }} - directory: ./coverage + files: ./coverage/**/coverage.cobertura.xml fail_ci_if_error: true verbose: true \ No newline at end of file