Naar hoofdinhoud
🔒 Voorbeeldmodus. De eerste vijftien Foundations-lessen zijn gratis; deze is Pro. Start een 7-daagse trial om de editor, AI-hints en de rest van het curriculum te ontgrendelen. Kaart vereist, op elk moment opzegbaar in Dashboard.Start 7-daagse trial →
← CursussenSystem Design for Python JuniorsModule 1 · Basisprincipes van systeemontwerpOntwerpen voor falenpredict15 / 105
+100 XP
Opdracht
📝 **Taak:** Voorspel het 7-regelige spoor van statusreeksen dat door de stroomonderbreker wordt uitgezonden terwijl deze 2 successen, 3 mislukkingen, 1 kortsluiting en 1 herstelsonde doorloopt. 📋 Implementeer bovenstaande functie. Tests worden automatisch uitgevoerd. 💡 **Hint:** Herlees de theorie als je vastloopt.
Voorspel uitvoer

Lees de code zorgvuldig

class CircuitBreaker:
    def __init__(self, threshold=3):
        self.state = "CLOSED"
        self.failures = 0
        self.threshold = threshold

    def call(self, fn):
        # OPEN — short-circuit, never call the real fn.
        if self.state == "OPEN":
            return "fallback"
        try:
            result = fn()
        except Exception:
            self.failures += 1
            if self.failures >= self.threshold:
                self.state = "OPEN"
            return "fallback"
        # Success path — only reset failure count from HALF_OPEN.
        if self.state == "HALF_OPEN":
            self.state = "CLOSED"
            self.failures = 0
        return result

    def half_open(self):
        # An external timer in a real CB would do this. We trigger
        # it manually so the prediction stays deterministic.
        self.state = "HALF_OPEN"


def ok():    return "ok"
def boom():  raise RuntimeError("dep down")

cb = CircuitBreaker(threshold=3)

cb.call(ok);   print(cb.state)        # CLOSED, success — state unchanged
cb.call(ok);   print(cb.state)        # CLOSED
cb.call(boom); print(cb.state)        # 1 fail → CLOSED still (under threshold)
cb.call(boom); print(cb.state)        # 2 fails → CLOSED
cb.call(boom); print(cb.state)        # 3 fails → OPEN (just tripped)
cb.call(ok);   print(cb.state)        # OPEN — short-circuited, real fn skipped
cb.half_open()
cb.call(ok);   print(cb.state)        # HALF_OPEN probe success → CLOSED

# What does this print? Type your prediction.

Wat zal het programma uitprinten? Schrijf hier:

💬 Discussie

Wees de eerste — stel een vraag of deel een tip.
Log in om mee te doen aan de discussie. Lezen is gratis.
Discussie laden…