# Sentry Integration

This document describes the Sentry integration for the AI Feedback FastAPI service, which provides error tracking, performance monitoring, and application insights.

## Overview

Sentry is integrated to provide:
- **Error Tracking**: Automatic capture of exceptions and errors
- **Performance Monitoring**: Request timing and transaction tracking
- **Request Context**: Detailed information about HTTP requests
- **User Context**: Ability to associate errors with specific users
- **Release Tracking**: Version-based error grouping

## Configuration

### Environment Variables

Add the following environment variables to your `.env` file:

```bash
# Sentry Configuration
SENTRY_DSN=your_sentry_dsn_here
SENTRY_ENVIRONMENT=development
SENTRY_ENABLE_DEBUG=false
```

### Configuration Options

- **SENTRY_DSN**: Your Sentry project DSN (required for Sentry to work)
- **SENTRY_ENVIRONMENT**: Environment name (e.g., development, staging, production)
- **SENTRY_TRACES_SAMPLE_RATE**: Percentage of transactions to sample (0.0 to 1.0)
- **SENTRY_PROFILES_SAMPLE_RATE**: Percentage of profiles to sample (0.0 to 1.0)
- **SENTRY_ENABLE_DEBUG**: Enable Sentry debug mode (default: false)

## Features

### Automatic Error Capture

All unhandled exceptions are automatically captured and sent to Sentry:

```python
# Exceptions are automatically captured in the global exception handler
@app.exception_handler(Exception)
async def global_exception_handler(_request: Request, exc: Exception):
    # SentryService.capture_exception(exc) is called automatically
    pass
```

### Performance Monitoring

The Sentry middleware automatically tracks:
- Request duration
- HTTP method and path
- Response status codes
- Client IP and user agent
- Request headers (excluding sensitive ones)

### Manual Error Reporting

You can manually capture errors and messages:

```python
from app.services.sentry_service import SentryService

# Capture an exception
try:
    # Some risky operation
    pass
except Exception as e:
    SentryService.capture_exception(e)

# Capture a message
SentryService.capture_message("User completed action", "info")

# Set user context
SentryService.set_user_context("user123", "user@example.com", role="admin")

# Set custom tags
SentryService.set_tag("feature", "video_analysis")

# Set context data
SentryService.set_context("job_details", {"job_id": "123", "status": "processing"})
```

## Integration Points

### FastAPI Integration

Sentry is integrated with FastAPI through:
- **FastApiIntegration**: Captures FastAPI-specific errors and context
- **AsyncioIntegration**: Captures async/await related errors
- **SqlalchemyIntegration**: Captures database-related errors
- **RedisIntegration**: Captures Redis-related errors
- **HttpxIntegration**: Captures HTTP client errors

### Middleware

The `SentryMiddleware` provides:
- Request timing
- Transaction context
- Performance metrics
- Slow request logging (>5 seconds)

### Database Integration

Database errors are automatically captured through the SQLAlchemy integration.

## Best Practices

### Error Filtering

The integration includes automatic filtering for:
- Connection errors (can be noisy in production)
- Timeout errors (often expected in certain scenarios)

### Sensitive Data Protection

The middleware automatically excludes sensitive headers:
- Authorization
- Cookie
- X-API-Key

### Performance Impact

- **Traces Sample Rate**: Start with 0.1 (10%) in production
- **Profiles Sample Rate**: Start with 0.1 (10%) in production
- Adjust based on your Sentry plan and performance requirements

## Monitoring and Alerts

### Error Alerts

Configure Sentry alerts for:
- High error rates
- New error types
- Performance degradation
- Specific error patterns

### Performance Alerts

Monitor:
- Response time percentiles
- Error rates by endpoint
- Database query performance
- External API call performance

## Troubleshooting

### Common Issues

1. **Sentry not capturing errors**: Check `SENTRY_DSN` is set correctly
2. **High volume of events**: Reduce sample rates
3. **Missing context**: Ensure middleware is added before other middleware

### Debug Mode

Enable debug mode to see Sentry initialization details:

```bash
SENTRY_ENABLE_DEBUG=true
```

### Testing

Run the Sentry tests to verify integration:

```bash
pytest tests/test_sentry.py -v
```

## Production Considerations

### Environment Configuration

- Use different DSNs for different environments
- Set appropriate sample rates for production
- Configure alerts and notifications

### Performance Monitoring

- Monitor Sentry's own performance impact
- Adjust sample rates based on traffic volume
- Use Sentry's performance insights to optimize your application

### Security

- Never commit DSNs to version control
- Use environment variables or secrets management
- Review Sentry data for sensitive information

## Support

For Sentry-specific issues:
- Check [Sentry documentation](https://docs.sentry.io/)
- Review Sentry project settings
- Check Sentry quotas and limits

For integration issues:
- Review application logs
- Check Sentry dashboard for events
- Verify configuration values
