Какие Quality Gates используешь?
Комментарии (1)
Ответ сгенерирован нейросетью и может содержать ошибки
Quality Gates в production-среде
Quality Gates — это набор метрик и проверок, которые должны пройти перед деплоем. Это страховка, которая предотвращает попадание плохого кода в production.
1. Code Quality Gate (SonarQube / Sonar Cloud)
Это основной инструмент для контроля качества.
Метрики:
QualityGates:
- Coverage >= 80%
- Duplicated Lines Density < 3%
- Issues: A (максимум A rating)
- Security Hotspots: All reviewed
- Technical Debt < 5 дней
- Code Smells < 50 на 10k строк
Как интегрировать:
# .github/workflows/sonar.yml
name: SonarCloud
on:
push:
branches: [main]
pull_request:
jobs:
sonarcloud:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: SonarCloud Scan
uses: SonarSource/sonarcloud-github-action@master
with:
args: >
-Dsonar.projectKey=prepbro
-Dsonar.organization=my-org
-Dsonar.qualitygate.wait=true
Правило: PR мержится только если Quality Gate PASSED
2. Test Coverage Gate
Минимальное покрытие тестами.
# package.json
{
"scripts": {
"test": "jest --coverage",
"test:check-coverage": "jest --coverage --passWithNoTests && nyc check-coverage"
}
}
# .nycrc.json
{
"lines": 80,
"statements": 80,
"functions": 80,
"branches": 75,
"report-dir": "./coverage",
"reporter": ["text", "lcov", "html"]
}
Проверка:
# На локальной машине
npm run test:check-coverage
# На CI/CD
if [ $(coverage) -lt 80 ]; then exit 1; fi
3. Linting & Code Style
Синтаксис и стиль кода.
# .eslintrc.json
{
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended"
],
"rules": {
"no-console": "warn",
"no-debugger": "error",
"@typescript-eslint/no-any": "error",
"@typescript-eslint/no-explicit-any": "error"
}
}
# .prettierrc
{
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100
}
CI/CD проверка:
#!/bin/bash
npm run lint || exit 1 # Fail if lint errors
npm run format:check || exit 1 # Fail if formatting mismatch
4. Security Scanning
Поиск уязвимостей и секретов.
# package.json
{
"scripts": {
"audit": "npm audit --audit-level=moderate",
"snyk": "snyk test --severity-threshold=high"
}
}
# .github/workflows/security.yml
name: Security
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: npm audit
run: npm audit --audit-level=moderate
- name: Snyk scan
run: npx snyk test --severity-threshold=high
- name: SAST scan
uses: securego/gosec@master
5. Type Safety Gate
TypeScript strict mode.
# tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"noImplicitThis": true,
"alwaysStrict": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
}
}
# CI/CD
npx tsc --noEmit || exit 1
6. Performance Gate
Проверка производительности API.
# loadtest.js
const autocannon = require('autocannon');
async function runLoadTest() {
const result = await autocannon({
url: 'http://localhost:3000',
connections: 100,
duration: 30,
requests: [
{ method: 'GET', path: '/api/health' },
{ method: 'POST', path: '/api/users', body: { name: 'test' } },
],
thresholds: {
p99: 100, // 99th percentile < 100ms
p95: 50, // 95th percentile < 50ms
},
});
if (result.errors > 0) {
console.error('Performance test failed');
process.exit(1);
}
}
runLoadTest();
7. Build Gate
Проверка, что приложение собирается без ошибок.
# CI/CD
npm run build || exit 1
8. Database Migration Gate
Проверка миграций.
# На staging перед production
./scripts/test-migrations.sh
# Скрипт проверяет:
# 1. Все миграции применяются
# 2. Все миграции откатываются
# 3. Все миграции применяются снова (без ошибок)
9. API Contract Testing
Проверка API схемы (OpenAPI / GraphQL).
# openapi.yaml
openapi: 3.0.0
info:
title: My API
version: 1.0.0
paths:
/api/users:
get:
responses:
'200':
content:
application/json:
schema:
type: object
properties:
users:
type: array
# CI/CD: проверяем, что API соответствует spec
npx dredd openapi.yaml http://localhost:3000
Полный CI/CD pipeline с Quality Gates
# .github/workflows/quality-gates.yml
name: Quality Gates
on:
push:
branches: [main, develop]
pull_request:
branches: [main, develop]
jobs:
quality:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:15
env:
POSTGRES_PASSWORD: postgres
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v3
# 1. Lint & Format
- name: Lint
run: npm run lint -- --max-warnings 0
# 2. Type check
- name: TypeScript
run: npx tsc --noEmit
# 3. Tests + Coverage
- name: Tests
run: npm run test -- --coverage
# 4. Coverage Gate
- name: Check coverage
run: npx nyc check-coverage
# 5. Build
- name: Build
run: npm run build
# 6. Security audit
- name: npm audit
run: npm audit --audit-level=moderate
- name: Snyk
run: npx snyk test --severity-threshold=high
# 7. SonarCloud
- name: SonarCloud
uses: SonarSource/sonarcloud-github-action@master
with:
args: -Dsonar.qualitygate.wait=true
# 8. Database migrations test
- name: Test migrations
run: |
npm run db:migrate
npm run db:rollback
npm run db:migrate
# 9. Performance
- name: Load test
run: npm run test:load
# 10. API Contract
- name: API Contract test
run: npm run test:api-contract
# Если все gates passed, мержим
merge-check:
needs: quality
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- name: All checks passed
run: echo "Ready to merge"
Мой стек Quality Gates
Используемые инструменты:
| Gate | Tool | Threshold |
|---|---|---|
| Coverage | Jest | 80%+ |
| Lint | ESLint | 0 errors |
| Types | TypeScript | strict mode |
| Code Quality | SonarQube | A grade |
| Security | Snyk + npm audit | No high |
| Build | TypeScript | No errors |
| Performance | Autocannon | p99 < 100ms |
| DB Migrations | Custom script | All pass |
| API Contract | Dredd | 100% |
Правило: PR мержится ТОЛЬКО если ВСЕ gates прошли успешно.
Мягкие gates (warnings)
Warnings: # не блокируют merge, но видны в PR
- TODO comments count < 5
- Console.log в production < 10
- Large PR (> 500 строк) требует 2 approvals
Quality Gates — это не бюрократия, это инвестиция в стабильность production'а.