sentry-for-modal 0.1.0
A Sentry integration package for Modal applications with automatic error handling and lifecycle management
License: MIT
Requires Python: >=3.8
Keywords: error-handling, logging, modal, monitoring, sentry

# Sentry for Modal

A comprehensive Sentry integration package for Modal applications with automatic error handling, lifecycle management, and enhanced monitoring capabilities.

## Features

- 🚀 **Automatic Modal Integration**: Seamlessly integrates with Modal's lifecycle methods
- 🛡️ **Comprehensive Error Handling**: Automatic error capture and reporting to Sentry
- 📊 **Enhanced Context**: Rich context data including function arguments, system info, and custom tags
- 🔄 **Lifecycle Management**: Automatic breadcrumb tracking for container startup/shutdown
- 🎯 **Method Decorators**: Easy-to-use decorators for error handling and Modal method wrapping
- 🔒 **Data Sanitization**: Automatic removal of sensitive information from error reports
- ⚡ **Async Support**: Full support for both synchronous and asynchronous Modal methods

## Installation

```bash
pip install sentry-for-modal
```

## Quick Start

```python
import modal
from sentry_for_modal import Sentry

class MyModalApp(Sentry):
    # Configure Sentry settings
    SENTRY_DSN = "your-sentry-dsn"
    SENTRY_ENVIRONMENT = "production"
    SENTRY_DEBUG = True

    async def modal_run(self, input_data: str):
        # Your Modal method implementation
        result = self.process_data(input_data)
        return result

# Create and run your Modal app
app = MyModalApp()
```

## Configuration

### Environment Variables

The package supports configuration via environment variables:

```bash
export SENTRY_DSN="your-sentry-dsn"
export SENTRY_ENVIRONMENT="production"
export SENTRY_TRACES_SAMPLE_RATE="0.1"
export SENTRY_PROFILES_SAMPLE_RATE="0.1"
export SENTRY_RELEASE="v1.0.0"
```

### Class-Level Configuration

You can also configure Sentry settings at the class level:

```python
class MyApp(Sentry):
    SENTRY_DSN = "your-sentry-dsn"
    SENTRY_ENVIRONMENT = "production"
    SENTRY_TRACES_SAMPLE_RATE = 0.1
    SENTRY_PROFILES_SAMPLE_RATE = 0.1
    SENTRY_RELEASE = "v1.0.0"
    SENTRY_DEBUG = True
    SENTRY_TAGS = {"service": "my-modal-app"}
    SENTRY_CONTEXT = {"team": "backend"}
```

## Usage

### Basic Modal App

```python
from sentry_for_modal import Sentry
import modal

class DataProcessor(Sentry):
    SENTRY_DSN = "your-sentry-dsn"

    async def modal_process_data(self, data: dict):
        # This method is automatically wrapped with error handling
        result = self.transform_data(data)
        return result

    def transform_data(self, data: dict):
        # This will also be protected by error handling
        return {k.upper(): v for k, v in data.items()}
```

### Custom Error Handling

```python
class CustomApp(Sentry):
    SENTRY_DSN = "your-sentry-dsn"

    def handle_error(self, error: Exception, method_name: str, *args, **kwargs):
        # Custom error handling logic
        print(f"Custom error handling for {method_name}: {error}")

        # Call parent error handler for Sentry reporting
        super().handle_error(error, method_name, *args, **kwargs)

        # Return a fallback value
        return {"error": str(error), "status": "failed"}
```

### Manual Breadcrumbs

```python
class AppWithBreadcrumbs(Sentry):
    SENTRY_DSN = "your-sentry-dsn"

    async def modal_complex_operation(self, data: dict):
        # Add custom breadcrumbs
        self._add_breadcrumb(
            message="Starting complex operation",
            category="business",
            level="info",
            data={"input_size": len(data)}
        )

        # Your operation logic here
        result = self.process(data)

        self._add_breadcrumb(
            message="Complex operation completed",
            category="business",
            level="info",
            data={"output_size": len(result)}
        )

        return result
```

## API Reference

### Sentry Class

The main base class that provides Sentry integration for Modal applications.

#### Class Attributes

- `SENTRY_DSN`: Sentry DSN string
- `SENTRY_ENVIRONMENT`: Environment name (e.g., "production", "staging")
- `SENTRY_TRACES_SAMPLE_RATE`: Sampling rate for performance traces (0.0 to 1.0)
- `SENTRY_PROFILES_SAMPLE_RATE`: Sampling rate for performance profiles (0.0 to 1.0)
- `SENTRY_RELEASE`: Release version string
- `SENTRY_DEBUG`: Enable debug logging
- `SENTRY_DISABLED`: Disable Sentry reporting
- `SENTRY_TAGS`: Default tags to apply to all events
- `SENTRY_CONTEXT`: Default context to apply to all events

#### Methods

- `handle_error(error, method_name, *args, **kwargs)`: Enhanced error handler
- `_add_breadcrumb(message, category, level, data)`: Add breadcrumb to Sentry
- `_initialize_sentry()`: Initialize Sentry SDK
- `_sanitize_data(data, max_depth, max_length)`: Sanitize data for Sentry

### Decorators

#### `@error_handler`

A decorator that wraps methods with error handling:

```python
from sentry_for_modal import error_handler

class MyClass:
    @error_handler
    def risky_method(self, data):
        # This method is automatically wrapped with error handling
        return process_data(data)
```

#### `@modal_method_with_error_handling`

A decorator that combines `@modal.method()` with error handling:

```python
from sentry_for_modal import modal_method_with_error_handling
import modal

class MyModalApp:
    @modal_method_with_error_handling
    async def modal_run(self, data):
        # This method is both a Modal method and has error handling
        return process_data(data)
```

## Error Reporting

The package automatically captures and reports the following information to Sentry:

- **Exception details**: Type, message, and full traceback
- **Function context**: Method name, class name, module, and line number
- **Arguments**: Sanitized function arguments (sensitive data removed)
- **System context**: Platform, Python version, timestamp, and process ID
- **Custom tags**: Error type, method name, class name, and platform
- **Breadcrumbs**: Automatic lifecycle and custom breadcrumbs

## Data Sanitization

The package automatically sanitizes data before sending to Sentry:

- Removes sensitive keys (password, token, key, secret, auth, credential)
- Limits data depth and length to prevent oversized payloads
- Converts complex objects to string representations
- Preserves essential debugging information

## Development

### Setup

```bash
git clone https://github.com/lighthouse/sentry-for-modal.git
cd sentry-for-modal
pip install -e ".[dev]"
```

### Running Tests

```bash
pytest
```

### Code Formatting

```bash
black src/ tests/
isort src/ tests/
```

### Type Checking

```bash
mypy src/
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Ensure all tests pass
6. Submit a pull request

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Support

- Documentation: https://sentry-for-modal.readthedocs.io
- Issues: https://github.com/lighthouse/sentry-for-modal/issues
- Discussions: https://github.com/lighthouse/sentry-for-modal/discussions