# API Normalization - Audit

Comprehensive audit logging, metrics collection, and performance monitoring for API Normalization.

## Purpose

This submodule provides production-critical monitoring features for the API Normalization platform:

- **Audit Logging**: Immutable audit trail for compliance and security
- **Metrics Collection**: Real-time metrics for API operations
- **Performance Monitoring**: Track response times, memory usage, and system health
- **Alerting**: Automated alerts for performance threshold breaches

## Why Use This Module?

While the core API Normalization module handles API integration, this audit module provides essential production features:

### Compliance & Security
- Complete audit trail of all operations (schema imports, endpoint executions, config changes)
- Immutable logs (INSERT only, no UPDATE/DELETE)
- IP address and user agent tracking
- Multi-tenant support with tenant ID filtering

### Performance Monitoring
- Real-time performance tracking with session-based monitoring
- Memory usage and database query tracking
- Performance grading (A-F) for operations
- Automated optimization recommendations

### Production Visibility
- Metrics collection for trend analysis
- Performance alerts (warning/critical thresholds)
- System health monitoring
- Historical performance reports

## Installation

```bash
# Enable the module
drush en api_normalization_audit

# Database schema is installed automatically
```

## Usage

### Audit Logging

```php
// Get audit logger service
$audit_logger = \Drupal::service('api_normalization_audit.audit_logger');

// Log schema import
$audit_logger->logSchemaImport('my_schema', [
  'schema_name' => 'OpenWeather API',
  'endpoint_count' => 5,
]);

// Log endpoint execution
$audit_logger->logEndpointExecution(
  'weather_endpoint',
  200,
  45.2,
  ['provider' => 'openweathermap']
);

// Log provider failover
$audit_logger->logProviderSwitch(
  'primary_provider',
  'backup_provider',
  'Primary provider timeout',
  TRUE
);

// Query audit logs
$logs = $audit_logger->queryAuditLog([
  'action' => 'endpoint_executed',
  'date_from' => strtotime('-7 days'),
  'result' => 'success',
], 50);
```

### Performance Monitoring

```php
// Get performance monitor
$monitor = \Drupal::service('api_normalization_audit.performance_monitor');

// Start monitoring an operation
$session_id = $monitor->startMonitoring('api.normalize', [
  'endpoint' => '/api/weather',
  'provider' => 'openweathermap',
]);

// Record custom metrics
$monitor->recordMetric($session_id, 'cache_hit', TRUE);
$monitor->recordMetric($session_id, 'response_time', 45.2);

// Stop monitoring and get report
$report = $monitor->stopMonitoring($session_id);

// Report contains:
// - duration, memory_usage, query_count
// - performance_grade (A-F)
// - alerts (if thresholds exceeded)
// - recommendations for optimization
```

### Metrics Collection

```php
// Get metrics collector
$metrics = \Drupal::service('api_normalization_audit.metrics_collector');

// Get total requests (last 24 hours)
$total = $metrics->getTotalRequests('24 hours');

// Get error rate
$error_rate = $metrics->getErrorRate('24 hours', 'anthropic');

// Get average response time
$avg_time = $metrics->getAverageResponseTime('24 hours');

// Get daily metrics
$daily = $metrics->getDailyMetrics(7);
```

### Unified Performance Service

```php
// Get unified performance service
$perf = \Drupal::service('api_normalization_audit.performance');

// Start tracking with multi-tier caching
$session_id = $perf->startTracking('api.cache_operation', [
  'cache_key' => 'weather_data',
]);

// Use intelligent caching
$data = $perf->getCached('weather_key', function() {
  return expensive_api_call();
}, ['ttl' => 3600]);

// Monitor metrics
$perf->monitor($session_id, 'cache_hit', TRUE, ['type' => 'memory']);

// Check rate limiting
if (!$perf->checkRateLimit('user:123', 100, 3600)) {
  throw new TooManyRequestsException();
}

// End tracking and get comprehensive report
$report = $perf->endTracking($session_id);
```

## Database Schema

### Audit Log Table

```
api_normalization_audit_log
├── id (serial)
├── action (varchar) - Action performed
├── actor_uid (int) - User ID
├── tenant_id (int) - Optional tenant ID
├── resource_type (varchar) - Resource type
├── resource_id (varchar) - Resource ID
├── changes (text) - JSON changes
├── context (text) - JSON context
├── timestamp (int) - Unix timestamp
├── ip_address (varchar) - IP address
├── user_agent (varchar) - User agent
└── result (varchar) - success/failure/warning/info
```

### Performance Metrics Table

```
api_normalization_performance_metrics
├── id (serial)
├── session_id (varchar) - Unique session ID
├── operation_id (varchar) - Operation identifier
├── endpoint (varchar) - API endpoint
├── user_id (int) - User ID
├── duration (float) - Operation duration
├── memory_usage (int) - Memory usage in bytes
├── query_count (int) - Database query count
├── performance_grade (varchar) - A-F grade
├── alert_count (int) - Number of alerts
├── created (int) - Unix timestamp
└── metrics_data (blob) - Serialized metrics
```

## Configuration

### Performance Thresholds

The module includes default alert thresholds:

- **Response Time**: Warning @ 1s, Critical @ 3s
- **Memory Usage**: Warning @ 128MB, Critical @ 256MB
- **Query Count**: Warning @ 50, Critical @ 100
- **Error Rate**: Warning @ 5%, Critical @ 10%

These can be customized via configuration:

```php
$config = \Drupal::configFactory()->getEditable('api_normalization_audit.settings');
$config->set('alert_thresholds.response_time.warning', 500);
$config->save();
```

## Features

### Audit Actions

- `schema_imported` - Schema import
- `schema_updated` - Schema update
- `schema_deleted` - Schema deletion
- `endpoint_executed` - Endpoint execution
- `endpoint_failed` - Endpoint failure
- `provider_detected` - Provider detection
- `provider_switched` - Provider switch
- `provider_failover` - Provider failover
- `api_key_created` - API key creation
- `api_key_revoked` - API key revocation
- `api_key_rotated` - API key rotation
- `config_changed` - Configuration change
- `rate_limit_exceeded` - Rate limit violation
- `security_violation` - Security violation
- `cache_cleared` - Cache clearing
- `maintenance_mode` - Maintenance mode change

### Performance Metrics

- **Real-time Metrics**: Active sessions, memory usage, system load
- **Historical Trends**: Response time trends, error rate trends
- **Cache Performance**: Hit/miss rates, cache efficiency
- **Query Analysis**: Slow query detection, optimization suggestions

### Security Features

- **Sensitive Data Filtering**: Automatic redaction of passwords, tokens, API keys
- **IP Tracking**: Record IP addresses for security audits
- **Immutable Logs**: Audit logs cannot be modified or deleted
- **Multi-tenant Support**: Isolate audit logs by tenant ID

## Requirements

- Drupal core ^10.3 || ^11
- api_normalization module (parent module)

## Drupal Best Practices

This module follows Drupal best practices:

- Uses Drupal's database API for all queries
- Leverages Drupal's cache system for performance
- Integrates with Drupal's logging system
- Uses dependency injection for all services
- Provides hook_schema() for database tables
- Includes proper install/uninstall hooks

## Performance Impact

Minimal performance impact:

- Audit logging is asynchronous (doesn't block operations)
- Metrics buffering reduces database writes
- Intelligent caching minimizes overhead
- Failed audit writes are logged but don't throw exceptions

## Use Cases

### Compliance Auditing

Track all API operations for compliance requirements (HIPAA, SOC 2, GDPR).

### Performance Optimization

Identify slow endpoints, high memory operations, and optimization opportunities.

### Security Monitoring

Track failed authentications, rate limit violations, and security events.

### Cost Tracking

Monitor API usage by provider for cost analysis and optimization.

### SLA Monitoring

Track response times and availability for SLA compliance.

## Support

For issues and feature requests, please use the API Normalization issue queue.

## License

GPL-2.0-or-later
