# Features Configuration

Rustelo's modular feature system allows you to enable, disable, and configure individual features based on your application's needs. This chapter covers how to configure features, understand their dependencies, and optimize your application by selecting the right combination of features.

## Overview

Features in Rustelo are:

- **Modular**: Each feature can be enabled/disabled independently
- **Configurable**: Features have their own configuration settings
- **Environment-Aware**: Different settings for development, staging, and production
- **Dependency-Aware**: Features can depend on other features
- **Performance-Optimized**: Unused features don't impact performance

## Feature System Architecture

```
features/
├── auth/                   # Authentication & Authorization
│   ├── dev.toml           # Development settings
│   ├── prod.toml          # Production settings
│   └── example.toml       # Example configuration
├── content/               # Content Management
├── email/                 # Email System
├── metrics/              # Monitoring & Metrics
├── tls/                  # SSL/TLS Security
├── rbac/                 # Role-Based Access Control
└── cache/                # Caching System
```

## Core Features

### Authentication Feature

The authentication feature provides user authentication, session management, and security controls.

#### Configuration

```toml
[features]
auth = true

[auth.jwt]
secret = "${JWT_SECRET}"
expiration = 3600              # Token expiration in seconds
refresh_token_expiration = 604800  # Refresh token expiration (7 days)
algorithm = "HS256"            # JWT algorithm
issuer = "rustelo-app"         # JWT issuer
audience = "rustelo-users"     # JWT audience

[auth.password]
min_length = 8                 # Minimum password length
require_uppercase = true       # Require uppercase letters
require_lowercase = true       # Require lowercase letters
require_numbers = true         # Require numbers
require_special_chars = true   # Require special characters
max_age_days = 90             # Password expiration in days
history_count = 5             # Number of previous passwords to remember

[auth.security]
max_login_attempts = 5        # Maximum failed login attempts
lockout_duration = 900        # Account lockout duration in seconds
session_timeout = 1800        # Session timeout in seconds
require_email_verification = true  # Require email verification
password_reset_timeout = 3600 # Password reset token timeout

[auth.two_factor]
enabled = true                # Enable 2FA
backup_codes_count = 10       # Number of backup codes
totp_issuer = "Rustelo App"   # TOTP issuer name
totp_digits = 6               # TOTP code length
totp_period = 30              # TOTP time period in seconds

[auth.sessions]
cleanup_interval = 3600       # Session cleanup interval in seconds
max_concurrent_sessions = 3   # Maximum concurrent sessions per user
remember_me_duration = 2592000  # Remember me duration (30 days)
```

#### Environment-Specific Settings

**Development:**
```toml
[auth.password]
min_length = 6
require_uppercase = false
require_special_chars = false

[auth.security]
max_login_attempts = 10
require_email_verification = false
```

**Production:**
```toml
[auth.password]
min_length = 12
require_uppercase = true
require_special_chars = true

[auth.security]
max_login_attempts = 3
require_email_verification = true
```

### Content Management Feature

The content feature provides content creation, editing, and management capabilities.

#### Configuration

```toml
[features]
content = true

[content]
enabled = true
content_dir = "content"       # Content storage directory
cache_enabled = true          # Enable content caching
cache_ttl = 3600             # Cache TTL in seconds
max_file_size = 10485760     # Maximum file size (10MB)
allowed_file_types = [       # Allowed file extensions
    "md", "txt", "html", "css", "js", "json", "toml", "yaml"
]

[content.markdown]
enabled = true               # Enable Markdown processing
syntax_highlighting = true  # Enable code syntax highlighting
math_support = false        # Enable LaTeX math rendering
table_of_contents = true    # Generate table of contents
auto_links = true           # Automatically link URLs

[content.media]
enabled = true              # Enable media uploads
max_image_size = 5242880   # Maximum image size (5MB)
max_video_size = 52428800  # Maximum video size (50MB)
image_processing = true     # Enable image processing
thumbnail_generation = true # Generate thumbnails
allowed_image_types = ["jpg", "jpeg", "png", "gif", "webp"]
allowed_video_types = ["mp4", "webm", "ogg"]

[content.versioning]
enabled = false             # Enable content versioning
max_versions = 10          # Maximum versions to keep
auto_save_interval = 60    # Auto-save interval in seconds

[content.publishing]
draft_mode = true          # Enable draft mode
scheduled_publishing = true # Enable scheduled publishing
approval_workflow = false  # Require approval for publishing
```

### Email System Feature

The email feature provides email sending, templating, and queue management.

#### Configuration

```toml
[features]
email = true

[email]
enabled = true
provider = "smtp"              # Email provider: smtp, sendgrid, console
from_email = "${FROM_EMAIL}"   # Default sender email
from_name = "${FROM_NAME}"     # Default sender name
reply_to = ""                  # Reply-to address
templates_dir = "templates/email"  # Email templates directory
queue_enabled = true           # Enable email queue
max_retries = 3               # Maximum retry attempts
retry_delay = 300             # Retry delay in seconds

[email.smtp]
host = "${SMTP_HOST}"         # SMTP server host
port = 587                    # SMTP server port
username = "${SMTP_USERNAME}" # SMTP username
password = "${SMTP_PASSWORD}" # SMTP password
use_tls = true               # Use TLS encryption
use_starttls = true          # Use STARTTLS
timeout = 30                 # Connection timeout in seconds

[email.sendgrid]
api_key = "${SENDGRID_API_KEY}"  # SendGrid API key
endpoint = "https://api.sendgrid.com/v3/mail/send"  # SendGrid endpoint

[email.templates]
cache_enabled = true         # Cache compiled templates
cache_ttl = 3600            # Template cache TTL
default_language = "en"     # Default template language
```

### Metrics & Monitoring Feature

The metrics feature provides application monitoring, performance tracking, and observability.

#### Configuration

```toml
[features]
metrics = true

[metrics]
enabled = true
endpoint = "/metrics"        # Metrics endpoint path
collect_interval = 15        # Collection interval in seconds
retention_days = 30         # Metrics retention period

[metrics.prometheus]
enabled = true              # Enable Prometheus metrics
namespace = "rustelo"       # Metrics namespace
subsystem = "app"          # Metrics subsystem
labels = { version = "1.0.0", environment = "production" }

[metrics.system]
enabled = true              # Collect system metrics
cpu_usage = true           # Monitor CPU usage
memory_usage = true        # Monitor memory usage
disk_usage = true          # Monitor disk usage
network_usage = true       # Monitor network usage

[metrics.application]
enabled = true             # Collect application metrics
request_metrics = true     # HTTP request metrics
database_metrics = true    # Database query metrics
cache_metrics = true       # Cache hit/miss metrics
error_metrics = true       # Error rate metrics

[metrics.custom]
enabled = true             # Enable custom metrics
business_metrics = true    # Business-specific metrics
user_metrics = true        # User activity metrics
```

### TLS/SSL Security Feature

The TLS feature provides SSL/TLS encryption, certificate management, and security headers.

#### Configuration

```toml
[features]
tls = true

[tls]
enabled = true
cert_file = "${TLS_CERT_FILE}"     # Certificate file path
key_file = "${TLS_KEY_FILE}"       # Private key file path
ca_file = "${TLS_CA_FILE}"         # CA certificate file path
protocols = ["TLSv1.2", "TLSv1.3"] # Supported TLS protocols
ciphers = [                        # Allowed cipher suites
    "TLS_AES_256_GCM_SHA384",
    "TLS_CHACHA20_POLY1305_SHA256",
    "TLS_AES_128_GCM_SHA256"
]

[tls.security]
force_https = true            # Force HTTPS redirects
hsts_enabled = true          # Enable HSTS
hsts_max_age = 31536000      # HSTS max age (1 year)
hsts_include_subdomains = true  # Include subdomains in HSTS
hsts_preload = true          # Enable HSTS preload

[tls.certificates]
auto_renewal = true          # Enable automatic certificate renewal
renewal_threshold = 2592000  # Renewal threshold (30 days)
acme_enabled = false         # Enable ACME/Let's Encrypt
acme_directory = "https://acme-v02.api.letsencrypt.org/directory"
```

### Role-Based Access Control (RBAC)

The RBAC feature provides fine-grained access control, permissions, and role management.

#### Configuration

```toml
[features]
rbac = true

[rbac]
enabled = true
default_role = "user"        # Default role for new users
admin_role = "admin"         # Administrator role name
super_admin_role = "super_admin"  # Super administrator role

[rbac.permissions]
hierarchical = true          # Enable hierarchical permissions
inheritance = true           # Enable permission inheritance
caching = true              # Cache permission checks
cache_ttl = 300             # Permission cache TTL

[rbac.roles]
dynamic_roles = true        # Enable dynamic role creation
role_templates = true       # Enable role templates
role_expiration = false     # Enable role expiration

[rbac.audit]
enabled = true              # Enable audit logging
log_level = "info"          # Audit log level
retention_days = 90         # Audit log retention period
```

### Caching System Feature

The caching feature provides multi-level caching for improved performance.

#### Configuration

```toml
[features]
cache = true

[cache]
enabled = true
default_ttl = 3600          # Default cache TTL in seconds
max_memory_size = 134217728 # Maximum memory cache size (128MB)
cleanup_interval = 300      # Cache cleanup interval in seconds

[cache.memory]
enabled = true              # Enable in-memory caching
max_entries = 10000         # Maximum cache entries
eviction_policy = "lru"     # Eviction policy: lru, lfu, random

[cache.redis]
enabled = false             # Enable Redis caching
url = "${REDIS_URL}"        # Redis connection URL
database = 0                # Redis database number
key_prefix = "rustelo:"     # Cache key prefix
compression = true          # Enable compression

[cache.file]
enabled = false             # Enable file-based caching
cache_dir = "cache"         # Cache directory
max_file_size = 1048576     # Maximum file size (1MB)
```

## Feature Dependencies

Some features depend on others. The system automatically handles these dependencies:

```toml
# Feature dependency matrix
[feature_dependencies]
rbac = ["auth"]              # RBAC requires authentication
content = ["auth"]           # Content management requires authentication
email = []                   # Email has no dependencies
metrics = []                 # Metrics has no dependencies
tls = []                     # TLS has no dependencies
cache = []                   # Cache has no dependencies
```

## Feature Flags

Feature flags allow runtime control of features:

```toml
[feature_flags]
auth_enabled = true
content_enabled = true
email_enabled = true
metrics_enabled = true
tls_enabled = true
rbac_enabled = false
cache_enabled = true

# Conditional features
[feature_flags.conditional]
oauth_enabled = false        # Enable OAuth (requires auth)
two_factor_enabled = true   # Enable 2FA (requires auth)
file_uploads_enabled = true # Enable file uploads (requires content)
```

## Environment-Specific Feature Configuration

### Development Environment

```toml
[features]
auth = true
content = true
email = true
metrics = true
tls = false
rbac = false
cache = true

[feature_flags]
debug_mode = true
mock_external_services = true
verbose_logging = true
```

### Production Environment

```toml
[features]
auth = true
content = true
email = true
metrics = true
tls = true
rbac = true
cache = true

[feature_flags]
debug_mode = false
mock_external_services = false
verbose_logging = false
performance_monitoring = true
```

## Performance Optimization

### Feature-Based Optimization

```toml
[optimization]
lazy_loading = true          # Lazy load features
compile_time_optimization = true  # Optimize at compile time
runtime_checks = false      # Disable runtime feature checks in production

[optimization.features]
auth = { priority = "high", preload = true }
content = { priority = "medium", preload = false }
email = { priority = "low", preload = false }
metrics = { priority = "low", preload = false }
```

### Resource Management

```toml
[resource_limits]
max_memory_per_feature = 67108864  # 64MB per feature
max_cpu_per_feature = 10           # 10% CPU per feature
max_connections_per_feature = 100  # 100 connections per feature
```

## Feature Testing

### Test Configuration

```toml
[testing]
features_under_test = ["auth", "content"]
mock_dependencies = true
integration_tests = true
performance_tests = false

[testing.auth]
test_users = 1000
test_sessions = 100
test_roles = 10

[testing.content]
test_documents = 500
test_media_files = 100
test_versions = 5
```

## Creating Custom Features

### Feature Structure

```
features/my_feature/
├── dev.toml               # Development configuration
├── prod.toml              # Production configuration
├── example.toml           # Example configuration
└── README.md              # Feature documentation
```

### Example Custom Feature

```toml
# features/my_feature/dev.toml
[features]
my_feature = true

[my_feature]
enabled = true
debug_mode = true
api_endpoint = "http://localhost:8080"
timeout = 30
retry_count = 3

[my_feature.settings]
option1 = "value1"
option2 = 42
option3 = true
```

## Feature Management Commands

### Using Configuration Scripts

```bash
# List available features
./config/scripts/manage-config.sh list-features

# Enable a feature
./config/scripts/manage-config.sh enable-feature auth

# Disable a feature
./config/scripts/manage-config.sh disable-feature rbac

# Check feature dependencies
./config/scripts/manage-config.sh check-dependencies

# Validate feature configuration
./config/scripts/manage-config.sh validate-features
```

### Runtime Feature Management

```bash
# Check feature status
curl http://localhost:3030/admin/features

# Enable feature at runtime (if supported)
curl -X POST http://localhost:3030/admin/features/auth/enable

# Disable feature at runtime (if supported)
curl -X POST http://localhost:3030/admin/features/auth/disable
```

## Best Practices

### 1. Feature Selection

- **Start Small**: Begin with essential features only
- **Add Gradually**: Enable additional features as needed
- **Monitor Impact**: Watch performance metrics when adding features
- **Document Changes**: Keep track of feature changes and their impact

### 2. Configuration Management

- **Environment Consistency**: Use consistent feature sets across environments
- **Version Control**: Track feature configuration changes
- **Testing**: Test feature combinations thoroughly
- **Rollback Plan**: Have a plan for disabling problematic features

### 3. Performance Considerations

- **Resource Usage**: Monitor resource usage per feature
- **Startup Time**: Consider impact on application startup
- **Memory Usage**: Track memory consumption of enabled features
- **Database Impact**: Monitor database performance with features enabled

### 4. Security Considerations

- **Feature Isolation**: Ensure features don't interfere with each other
- **Access Control**: Implement proper access controls for feature management
- **Audit Logging**: Log feature changes and access
- **Security Testing**: Test security implications of feature combinations

## Troubleshooting

### Common Issues

1. **Feature Not Loading**
   ```bash
   # Check feature configuration
   ./config/scripts/manage-config.sh validate-features
   
   # Check feature dependencies
   ./config/scripts/manage-config.sh check-dependencies
   ```

2. **Performance Issues**
   ```bash
   # Monitor feature resource usage
   curl http://localhost:3030/metrics | grep feature_
   
   # Check feature startup time
   grep "feature.*initialized" logs/app.log
   ```

3. **Configuration Conflicts**
   ```bash
   # Compare feature configurations
   ./config/scripts/manage-config.sh diff-features dev prod
   ```

### Debug Mode

Enable debug mode for detailed feature information:

```bash
RUSTELO_DEBUG=true FEATURE_DEBUG=true ./rustelo-server
```

## Migration Guide

When updating feature configurations:

1. **Backup Current Configuration**
   ```bash
   ./config/scripts/manage-config.sh backup-features
   ```

2. **Test New Configuration**
   ```bash
   ./config/scripts/manage-config.sh test-features
   ```

3. **Gradual Rollout**
   - Update staging environment first
   - Monitor for issues
   - Update production environment

4. **Rollback if Needed**
   ```bash
   ./config/scripts/manage-config.sh restore-features backup-file
   ```

For detailed migration instructions, see the [Feature Migration Guide](../reference/feature-migration.md).