# Story 4.12: Alerting Interface (Core No-op + Extras Providers)

## Status: Planned

## Priority: Medium

## Estimated Effort: Medium (2-3 days)

## Dependencies

- **Depends on:** Story 4.10 (Pluggable Audit Storage Interface) - Alerting integrates with audit trails

## Epic / Series

Part of Epic 4: Enterprise Compliance & Observability / Series 4.x

---

## Context / Background

SRE/ops engineers need a core alerting interface with a no-op dispatcher and pluggable providers in extras. This enables routing compliance and error alerts to channels like email, Slack, PagerDuty without coupling core to vendors.

**Current state:** The `AuditTrail._send_compliance_alert()` method is a stub (`pass`). Alert *detection* logic exists (checking `real_time_alerts`, `alert_on_critical_errors`, etc.) but alert *delivery* does nothing. Users must subclass `AuditTrail` and override `_send_compliance_alert()` to implement alerting. This story provides a proper pluggable interface.

---

## User Story

**As an** SRE/ops engineer  
**I want** a core alerting interface with a no-op dispatcher and pluggable providers in extras  
**So that** we can route compliance and error alerts to channels like email, Slack, PagerDuty without coupling core to vendors

---

## Scope (In / Out)

### In Scope

- Define `AlertDispatcher` Protocol with async `send_alert()` method
- Provide `NoopAlertDispatcher` in core
- Configure `AuditTrail` with optional dispatcher
- Document provider guidance for extras (Slack, PagerDuty, Opsgenie, webhooks)
- Retry/backoff expectations documented

### Out of Scope

- Implementing actual alert providers (extras/plugins)
- Real-time alerting infrastructure
- Alert routing logic beyond basic dispatch

---

## Acceptance Criteria

### AC1: Core Protocol

- [ ] Define `AlertDispatcher` Protocol:
  ```python
  class AlertDispatcher(Protocol):
      async def send_alert(
          self,
          event: AuditEvent,
          *,
          severity: str,
          channel: str | None = None
      ) -> None: ...
  ```
- [ ] Protocol is documented and type-checkable

### AC2: No-op Implementation

- [ ] Provide `NoopAlertDispatcher` in core
- [ ] No-op dispatcher implements protocol
- [ ] No-op is the default when no dispatcher provided

### AC3: AuditTrail Integration

- [ ] `AuditTrail` can be configured with optional dispatcher
- [ ] `AuditTrail` uses dispatcher when compliance alert conditions are met
- [ ] No change in behavior when no dispatcher provided
- [ ] Backward compatible

### AC4: Provider Documentation

- [ ] Document provider guidance for extras:
  - [ ] Slack provider example
  - [ ] PagerDuty provider example
  - [ ] Opsgenie provider example
  - [ ] Webhook provider example
- [ ] Document retry/backoff expectations
- [ ] Provide example implementations

---

## Technical Design / Implementation Notes

### Protocol Definition

Location: `src/fapilog/core/alerting.py` (new file)

```python
from typing import Protocol
from .audit import AuditEvent

class AlertDispatcher(Protocol):
    """Protocol for alert dispatching."""
    
    async def send_alert(
        self,
        event: AuditEvent,
        *,
        severity: str,
        channel: str | None = None
    ) -> None:
        """Send an alert for the given audit event."""
        ...
```

### No-op Implementation

```python
class NoopAlertDispatcher:
    """No-op alert dispatcher that does nothing."""
    
    async def send_alert(
        self,
        event: AuditEvent,
        *,
        severity: str,
        channel: str | None = None
    ) -> None:
        """No-op implementation."""
        pass
```

### AuditTrail Integration

Modify `AuditTrail.__init__`:
```python
def __init__(
    self,
    policy: Optional[CompliancePolicy] = None,
    storage_path: Optional[Path] = None,
    alert_dispatcher: Optional[AlertDispatcher] = None,
) -> None:
    self._alert_dispatcher = alert_dispatcher or NoopAlertDispatcher()
```

---

## Tasks

### Phase 1: Core Protocol
- [ ] Create `src/fapilog/core/alerting.py`
- [ ] Define `AlertDispatcher` Protocol
- [ ] Implement `NoopAlertDispatcher`
- [ ] Add type hints and documentation

### Phase 2: AuditTrail Integration
- [ ] Update `AuditTrail` to accept optional dispatcher
- [ ] Integrate dispatcher in `_send_compliance_alert()`
- [ ] Ensure backward compatibility
- [ ] Add tests

### Phase 3: Documentation
- [ ] Document protocol usage
- [ ] Document provider guidance
- [ ] Provide example implementations
- [ ] Document retry/backoff patterns

---

## Tests

### Unit Tests

- [ ] Test `NoopAlertDispatcher` implements protocol
- [ ] Test `AuditTrail` with no dispatcher (backward compatible)
- [ ] Test `AuditTrail` with dispatcher (alerts sent)
- [ ] Test error handling in dispatcher calls

### Integration Tests

- [ ] Test audit trail with mock dispatcher
- [ ] Verify alerts are sent when conditions met

---

## Documentation Updates

- [ ] Document `AlertDispatcher` Protocol
- [ ] Document provider implementation guide
- [ ] Document retry/backoff expectations
- [ ] Add examples for common providers

---

## Definition of Done

Story is complete when ALL of the following are true:

### Code Complete
- [ ] All acceptance criteria met and verified
- [ ] All tasks completed
- [ ] Code follows project style guide
- [ ] No linting errors or warnings
- [ ] Type checking passes (mypy strict)

### Quality Assurance
- [ ] Unit tests: >90% coverage of new code
- [ ] Integration tests: all scenarios passing
- [ ] Regression tests: no existing functionality broken
- [ ] Performance tests: no regression vs baseline
- [ ] Manual testing completed (if applicable)

### Documentation
- [ ] User-facing docs updated
- [ ] API reference updated (if applicable)
- [ ] Code examples added/updated
- [ ] CHANGELOG.md updated
- [ ] Inline code documentation complete

### Review & Release
- [ ] Code review approved
- [ ] Documentation reviewed for clarity
- [ ] CI/CD pipeline passing
- [ ] Ready for merge to main branch

### Backwards Compatibility
- [ ] No breaking changes OR breaking changes documented with migration guide
- [ ] Existing tests still pass
- [ ] Deprecation warnings added (if applicable)

---

## Risks / Rollback / Monitoring

### Risks

- **Risk:** Protocol too restrictive for some providers
  - **Mitigation:** Keep protocol minimal, allow provider-specific extensions

- **Risk:** Breaking changes to AuditTrail
  - **Mitigation:** Make dispatcher optional, default to no-op

### Rollback Plan

- Remove dispatcher parameter from AuditTrail
- Keep protocol for future use
- No breaking changes if rolled back

---

## Related Documents

- [Story 4.10: Pluggable Audit Storage Interface](./4.10.pluggable-audit-storage.md)
- [Audit Trail Documentation](../api-reference/audit-trail.md)

---

## Change Log

| Date       | Change                    | Author |
| ---------- | ------------------------- | ------ |
| 2025-01-10 | Initial story creation    | System |
