HardПрактика4 min

Модификации интеграции

Расширения интеграции CRC для 6 ролей: кэширование, synthetic monitoring, WAF, оптимизация задержки, аналитика и AI

Developer Mod: Playing the Hits

Задача

Реализовать API-версионирование и кэширование ответов. Добавить обратную совместимость при обновлении API.

Реализация

// Frontend: вызов конкретной версии API
const API_V1 = 'https://api.ivanpetrov.com/v1/count';
const API_V2 = 'https://api.ivanpetrov.com/v2/count';

// v1: простой счётчик
// GET /v1/count → {"count": 42}

// v2: расширенный ответ с метаданными
// GET /v2/count → {"count": 42, "lastUpdated": "...", "daily": 15}
# Lambda: маршрутизация по версии
def lambda_handler(event, context):
    path = event.get('rawPath', '')

    if path.startswith('/v1/'):
        return handle_v1(event)
    elif path.startswith('/v2/'):
        return handle_v2(event)
    else:
        return {'statusCode': 404, 'body': 'Not Found'}

def handle_v1(event):
    count = get_total_count()
    return response({'count': count})

def handle_v2(event):
    count = get_total_count()
    daily = get_daily_count()
    return response({
        'count': count,
        'daily': daily,
        'lastUpdated': datetime.now().isoformat()
    })

DevOps Mod: Browser Up

Задача

Настроить synthetic monitoring -- автоматическую проверку доступности сайта из разных регионов мира.

AWS CloudWatch Synthetics

# Создание canary (синтетического теста)
aws synthetics create-canary \
  --name crc-health-check \
  --artifact-s3-location "s3://crc-canary-artifacts/" \
  --execution-role-arn arn:aws:iam::123456789012:role/canary-role \
  --schedule '{"Expression": "rate(5 minutes)"}' \
  --runtime-version syn-python-selenium-3.0 \
  --code '{
    "Handler": "health_check.handler",
    "Script": "..."
  }'
# Canary script
from aws_synthetics.selenium import synthetics_webdriver as webdriver

def handler(event, context):
    browser = webdriver.Chrome()
    browser.get('https://resume.ivanpetrov.com')

    # Check page loads
    assert 'Иван Петров' in browser.title or browser.page_source

    # Check visitor counter
    counter = browser.find_element_by_id('visitor-count')
    assert counter.text.isdigit(), f"Counter not a number: {counter.text}"

    # Check API directly
    browser.get('https://api.ivanpetrov.com/count')
    assert '"count"' in browser.page_source

    return "All checks passed"

Security Mod: Wall of Fire

Задача

Настроить WAF с правилами защиты, geo-блокировкой и IP reputation list.

Расширенные правила WAF

# Geo-блокировка (пример: блокировка определённых стран)
aws wafv2 update-web-acl --rules '[
  {
    "Name": "GeoBlock",
    "Priority": 1,
    "Action": {"Block": {}},
    "Statement": {
      "GeoMatchStatement": {
        "CountryCodes": ["CN", "RU", "KP"]
      }
    }
  },
  {
    "Name": "IPReputation",
    "Priority": 2,
    "OverrideAction": {"None": {}},
    "Statement": {
      "ManagedRuleGroupStatement": {
        "VendorName": "AWS",
        "Name": "AWSManagedRulesAmazonIpReputationList"
      }
    }
  },
  {
    "Name": "RateLimit",
    "Priority": 3,
    "Action": {"Block": {}},
    "Statement": {
      "RateBasedStatement": {
        "Limit": 100,
        "AggregateKeyType": "IP"
      }
    }
  }
]'

Отчёт по безопасности

В рамках этого мода подготовьте документ с анализом: какие атаки возможны, какие правила WAF защищают от каждой, и каковы trade-offs (ложноположительные срабатывания, стоимость).

Architect Mod: Latency Whisperer

Задача

Оптимизировать задержку end-to-end: от клика пользователя до отображения результата.

Анализ задержки

Текущая цепочка:
  Браузер → CloudFront (cache hit: 5ms, miss: 50ms)
  Браузер → API GW (10ms) → Lambda (cold: 500ms, warm: 5ms) → DynamoDB (5ms)

Оптимизации:
  1. CloudFront: cache HTML → снижает TTFB
  2. Lambda: arm64, 128MB → быстрый cold start
  3. DynamoDB: On-Demand → нет throttling
  4. API Gateway: HTTP API → меньше overhead
  5. Lambda SnapStart (Java) или Provisioned Concurrency → нет cold start

Multi-region deployment

# Для ультра-низкой задержки: Lambda@Edge или CloudFront Functions
# CloudFront Function для кэширования счётчика на edge

function handler(event) {
    var request = event.request;

    // Cache counter response for 60 seconds at edge
    if (request.uri === '/count') {
        var cachedCount = getCached('visitor-count');
        if (cachedCount) {
            return {
                statusCode: 200,
                body: JSON.stringify({count: cachedCount})
            };
        }
    }

    return request;
}

Data Engineer Mod: Analytics Tap-In

Задача

Подключить собственную аналитику (не Google Analytics) и визуализировать данные посещений.

Data Pipeline

Браузер → API Gateway → Lambda (tracker)
                            │
                            ├── DynamoDB (real-time counters)
                            │
                            └── Kinesis Firehose → S3 (data lake)
                                                    │
                                                    └── Athena (analytics)
                                                        │
                                                        └── QuickSight (dashboard)
# Lambda: dual-write for analytics
import boto3
import json

firehose = boto3.client('firehose')

def lambda_handler(event, context):
    # 1. Update counter (existing logic)
    count = increment_counter()

    # 2. Send to Firehose for analytics
    analytics_record = {
        'timestamp': datetime.now().isoformat(),
        'page': event.get('queryStringParameters', {}).get('page', '/'),
        'userAgent': event.get('headers', {}).get('user-agent', ''),
        'count': count
    }

    firehose.put_record(
        DeliveryStreamName='crc-analytics',
        Record={'Data': json.dumps(analytics_record) + '\n'}
    )

    return response({'count': count})

AI Engineer Mod: Smart Frontend

Задача

Реализовать streaming LLM-ответов в реальном времени и prompt engineering для чат-интерфейса.

Streaming через API Gateway + Lambda

# Lambda с streaming response (response streaming)
import json

def lambda_handler(event, context):
    question = json.loads(event.get('body', '{}')).get('question', '')

    # Stream response using Lambda response streaming
    def generate():
        yield '{"answer": "'

        for chunk in call_bedrock_stream(question):
            yield chunk

        yield '"}'

    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'application/json',
            'Transfer-Encoding': 'chunked'
        },
        'body': generate()
    }
// Frontend: streaming display
async function askAI(question) {
    const response = await fetch('https://api.ivanpetrov.com/ask', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({question})
    });

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    const output = document.getElementById('ai-response');
    output.textContent = '';

    while (true) {
        const {done, value} = await reader.read();
        if (done) break;
        output.textContent += decoder.decode(value);
    }
}

Сравнение модов интеграции

Мод Навык Сервисы Сложность
Playing the Hits API Design API Gateway Средняя
Browser Up Observability CloudWatch Synthetics Средняя
Wall of Fire Security WAF, Shield Высокая
Latency Whisperer Performance CloudFront, Lambda@Edge Высокая
Analytics Tap-In Data Engineering Kinesis, Athena Высокая
Smart Frontend AI/ML Bedrock, Streaming Высокая

Проверь себя

Зачем нужно API-версионирование в Developer Mod 'Playing the Hits'?

Зачем в Architect Mod 'Latency Whisperer' рассматривается Lambda@Edge?

Какой AWS-сервис используется для streaming LLM-ответов в AI Mod?

Что такое dual-write в Data Mod 'Analytics Tap-In'?

Что такое synthetic monitoring в DevOps Mod 'Browser Up'?