4

I need to implement a circuit breaker pattern in my app so I tried doing it with PyBreaker. The app runs all properly but I don't know how can I test it and see if the breaker is working well. This is my CircuitBreakerListener class:

import pybreaker
import logging

class CircuitBreakerListener(pybreaker.CircuitBreakerListener):

    def failure(self, cb, exc):
        logging.info("CRITICAL {0}: The last request caused a system error".format(cb))

    def state_change(self, cb, old_state, new_state):
        logging.info("Circuit Breaker {0}: The {1} state changed to {2} state".format(cb, old_state, new_state))

and my function call:

from starlette.responses import JSONResponse

def circuitbreaker_call(circuitbreaker, data):
    if circuitbreaker.current_state == 'open':
        data = JSONResponse(status_code=404, content={"Error": "Oops, something went wrong. Try again in 10 seconds"})
    print(circuitbreaker.current_state)
    return data

As far as I read, the breaker should change its status when an Exception occurs. This is what I did in order to throw an Exception:

db_breaker = pybreaker.CircuitBreaker(fail_max=1, reset_timeout=5, listeners=[CircuitBreakerListener()])

@db_breaker
def get_projects(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.Project).offset(skip).limit(limit).all() == 'a'

and my endpoint:

@app.get("/projects", response_model=List[schemas.Project])
def get_projects(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    return circuitbreaker_call(db_breaker, crud.get_projects(db, skip=skip, limit=limit))

but instead of getting 404 code with "Oops, something went wrong" message, I just get 500 Internal Server error in my console and nothing really changes on the /projects endpoint. Is there a way to trigger the circuit breaker and test it to see if it actually works?

anthino12
  • 770
  • 1
  • 6
  • 29

0 Answers0