Skip to main content

Circuit Breaker inteligente com Machine Learning adaptativo

Project description

🛡️ Lógica dos Desvios

Circuit Breaker inteligente com Machine Learning adaptativo para Python

PyPI version Python 3.7+ License: MIT


📋 Índice


🎯 Sobre

Lógica dos Desvios é uma biblioteca Python que implementa o padrão Circuit Breaker com capacidades de Machine Learning para adaptação automática de parâmetros.

Diferente dos circuit breakers tradicionais com threshold e timeout fixos, este sistema aprende com o histórico de operações e ajusta dinamicamente seus parâmetros para maximizar a resiliência.

Por que usar?

  • Adaptativo: Ajusta threshold (2-10) e timeout (5-300s) automaticamente
  • Inteligente: Usa ML para predizer falhas e tempos de recuperação
  • Resiliente: Recuperação gradual baseada em sucessos consecutivos
  • Observável: Análise de padrões históricos e tendências
  • Alertas: Sistema de notificações por severidade (CRITICAL/SEVERE/WARNING)
  • Persistente: Estado e histórico salvos em disco
  • Bilíngue: Suporta nomes em inglês e português

✨ Características

Circuit Breaker Tradicional

  • Estados: CLOSED, OPEN, HALF_OPEN
  • Proteção contra falhas em cascata
  • Timeout configurável
  • Persistência de estado

+ Machine Learning

  • Análise de padrões históricos
  • Predição de probabilidade de falha
  • Predição de tempo de recuperação
  • Detecção de tendências (melhorando/degradando/estável)
  • Análise de padrões horários

+ Adaptação Inteligente

  • Threshold dinâmico: Ajusta entre 2-10 baseado em taxa de falha
  • Timeout dinâmico: Ajusta entre 5-300s baseado em predições
  • Recuperação gradual: Aumenta threshold após 5 sucessos consecutivos
  • Limites de segurança: Nunca permite valores inseguros
  • Backoff exponencial: Em situações de instabilidade severa

📦 Instalação

pip install logica-desvios

Requisitos

  • Python >= 3.7
  • pandas >= 1.0.0
  • numpy >= 1.18.0

🚀 Uso Rápido

Exemplo Básico

from logica_desvios import AdaptiveCircuitBreakerAgent

# 1. Cria o agente
agent = AdaptiveCircuitBreakerAgent(
    name="meu_servico",
    initial_failure_threshold=3,
    initial_reset_timeout=60
)

# 2. Inicia aprendizado adaptativo (opcional mas recomendado)
agent.start_adaptive_learning()

# 3. Protege sua função
@agent.protect
def chamar_api_externa():
    # Sua operação que pode falhar
    response = requests.get("https://api.example.com/data")
    return response.json()

# 4. Usa normalmente
try:
    dados = chamar_api_externa()
    print(f"Sucesso: {dados}")
except CircuitBreakerOpenException:
    print("Serviço temporariamente indisponível")
except Exception as e:
    print(f"Erro: {e}")

# 5. Para o aprendizado quando terminar
agent.stop_adaptive_learning()

Exemplo em Português

from logica_desvios import AgenteInteligente, CircuitBreakerAbertoException

agente = AgenteInteligente(name="backup_system")
agente.start_adaptive_learning()

@agente.protect
def fazer_backup(arquivo):
    # Lógica de backup
    return salvar_arquivo(arquivo)

try:
    fazer_backup("database.sql")
except CircuitBreakerAbertoException:
    print("Sistema de backup temporariamente desabilitado")

📚 Exemplos

Caso 1: API Externa Instável

from logica_desvios import AdaptiveCircuitBreakerAgent
import requests

agent = AdaptiveCircuitBreakerAgent(name="api_weather")
agent.start_adaptive_learning()

@agent.protect
def buscar_previsao(cidade):
    response = requests.get(f"https://api.weather.com/{cidade}", timeout=5)
    return response.json()

# Sistema aprende e adapta automaticamente
for cidade in ["sao-paulo", "rio", "brasilia"]:
    try:
        previsao = buscar_previsao(cidade)
        print(f"{cidade}: {previsao['temp']}°C")
    except Exception as e:
        print(f"{cidade}: Falha - {e}")

Caso 2: Backup Automático Resiliente

from logica_desvios import AdaptiveCircuitBreakerAgent

backup_agent = AdaptiveCircuitBreakerAgent(
    name="backup_system",
    initial_failure_threshold=2,
    initial_reset_timeout=30
)

@backup_agent.protect
def backup_database(db_name):
    # Comando de backup
    os.system(f"pg_dump {db_name} > backup_{db_name}.sql")
    return True

# Executa backups diários
for db in ["users", "orders", "products"]:
    try:
        backup_database(db)
        print(f"✅ Backup de {db} concluído")
    except Exception as e:
        print(f"❌ Backup de {db} falhou: {e}")
        # Sistema automaticamente ajusta estratégia

Caso 3: Múltiplos Microserviços

from logica_desvios import AdaptiveCircuitBreakerAgent

# Um agente para cada serviço
auth_agent = AdaptiveCircuitBreakerAgent(name="auth_service")
payment_agent = AdaptiveCircuitBreakerAgent(name="payment_service")
email_agent = AdaptiveCircuitBreakerAgent(name="email_service")

@auth_agent.protect
def autenticar(user): ...

@payment_agent.protect
def processar_pagamento(valor): ...

@email_agent.protect
def enviar_confirmacao(email): ...

# Cada serviço tem seu próprio comportamento adaptativo

📖 Documentação

API Principal

AdaptiveCircuitBreakerAgent

agent = AdaptiveCircuitBreakerAgent(
    name: str,                          # Nome único do agente
    initial_failure_threshold: int = 3, # Falhas antes de abrir (será adaptado)
    initial_reset_timeout: int = 60,    # Segundos antes de testar (será adaptado)
    decision_interval_seconds: int = 15 # Intervalo de decisão ML
)

Métodos:

  • start_adaptive_learning(): Inicia loop de ML
  • stop_adaptive_learning(): Para loop de ML
  • protect(func): Decorador para proteger funções
  • get_stats(): Retorna estatísticas completas

Estados do Circuit Breaker

  • CLOSED (FECHADO): Operação normal, todas as requisições passam
  • OPEN (ABERTO): Bloqueando requisições (serviço falhou)
  • HALF_OPEN (MEIO_ABERTO): Testando recuperação

Exceções

  • CircuitBreakerOpenException: Levantada quando CB está OPEN

Aliases em Português

from logica_desvios import (
    AgenteInteligente,              # = AdaptiveCircuitBreakerAgent
    AgenteCircuitBreaker,           # = CircuitBreakerAgent
    AdaptadorML,                    # = MLAdapter
    TomadorDecisao,                 # = DecisionMaker
    CircuitBreakerAbertoException,  # = CircuitBreakerOpenException
    FECHADO, ABERTO, MEIO_ABERTO    # = CLOSED, OPEN, HALF_OPEN
)

🔧 Configuração Avançada

Ajuste Fino de Parâmetros

from logica_desvios import AdaptiveCircuitBreakerAgent

agent = AdaptiveCircuitBreakerAgent(
    name="api_critical",
    initial_failure_threshold=5,      # Mais tolerante
    initial_reset_timeout=120,        # Espera mais antes de testar
    decision_interval_seconds=10      # Decisões mais frequentes
)

Acessando Componentes Individuais

# Acessar o MLAdapter
ml_insights = agent.ml_adapter.analyze_patterns()
print(f"Taxa de falha: {ml_insights['failure_rate']}")

# Acessar o Circuit Breaker
cb_state = agent.circuit_breaker.get_state()
print(f"Estado: {cb_state}")

# Acessar estatísticas
stats = agent.get_stats()
print(f"Threshold atual: {stats['failure_threshold']}")

📊 Métricas e Monitoramento

stats = agent.get_stats()

print(f"""
Estado: {stats['state']}
Threshold: {stats['failure_threshold']}
Timeout: {stats['reset_timeout']}s
Taxa de falha: {stats['failure_rate']*100:.1f}%
Operações totais: {stats['total_operations']}
Sucessos: {stats['total_successes']}
Falhas: {stats['total_failures']}
""")

🤝 Contribuindo

Contribuições são bem-vindas! Por favor:

  1. Fork o projeto
  2. Crie uma branch para sua feature (git checkout -b feature/AmazingFeature)
  3. Commit suas mudanças (git commit -m 'Add some AmazingFeature')
  4. Push para a branch (git push origin feature/AmazingFeature)
  5. Abra um Pull Request

📝 Licença

Este projeto está licenciado sob a Licença MIT - veja o arquivo LICENSE para detalhes.


👤 Autor

Marcos Sea


🙏 Agradecimentos

  • Inspirado pelo padrão Circuit Breaker do livro "Release It!" de Michael T. Nygard
  • Baseado em conceitos de Machine Learning e sistemas adaptativos
  • Comunidade Python por ferramentas incríveis

📈 Roadmap

  • Suporte a Redis para estado compartilhado
  • Integração com Prometheus/Grafana
  • Dashboard web em tempo real
  • Modelos ML mais sofisticados (Random Forest, LSTM)
  • Suporte a múltiplos backends de persistência
  • Integração com sistemas de notificação (Slack, Telegram, Email)

⭐ Se este projeto foi útil, considere dar uma estrela no GitHub!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

logica_desvios-0.2.0.tar.gz (22.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

logica_desvios-0.2.0-py3-none-any.whl (17.5 kB view details)

Uploaded Python 3

File details

Details for the file logica_desvios-0.2.0.tar.gz.

File metadata

  • Download URL: logica_desvios-0.2.0.tar.gz
  • Upload date:
  • Size: 22.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for logica_desvios-0.2.0.tar.gz
Algorithm Hash digest
SHA256 15c733e98328a97fb9c41e7897201db62e1640a5e51c9b000066b7fc85c892f0
MD5 13e5856fec15a70af75d5be6a34238d0
BLAKE2b-256 ed6e856141608365141f2b791870c4009a77dbad60d7882a50e5fb21a25be840

See more details on using hashes here.

File details

Details for the file logica_desvios-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: logica_desvios-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 17.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for logica_desvios-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0be03679ff37d0980dbe4830cb637928cd9deedf8cd5e8753338b3534b291eb3
MD5 2f3b262f0f5a403a6cb2184f5b75cda9
BLAKE2b-256 fee393f90388af194c11e221ae7da6aca3d0ca0ffbc066c6003f2a85e887edf6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page