AlgoViz

Chain of responsibility

medium 45 min

A request travels past several handlers until one takes it, or until one stops it.

Watch lesson4:36

Failures and tracing

A handler that throws, hangs or lies, and how to see it.

The point: pass, refuse, done and broken are four different answers. A chain that mixes them will one day let a request through because a check crashed.

Four answers

Say what you mean

AnswerMeaningThe chain
PASSnot mine, or fine for measks the next
DONEI resolved itstops, result
REFUSEI know that it must not go onstops, reason
exceptionI could not decidedepends: fail closed or fail open
Python
from dataclasses import dataclassfrom enum import Enumimport timeclass Kind(Enum):    PASS = 1    DONE = 2    REFUSE = 3@dataclass(frozen=True)class Outcome:    kind: Kind    detail: str = ""@dataclass(frozen=True)class Link:    name: str    run: object    critical: bool          # True: if it breaks, refuseclass Chain:    def __init__(self, links, clock=time.monotonic):        self._links, self._clock = tuple(links), clock    def handle(self, request):        trail = []        for link in self._links:            start = self._clock()            try:                out = link.run(request)            except Exception as e:                out = Outcome(Kind.REFUSE if link.critical else Kind.PASS, f"broke: {type(e).__name__}")            trail.append((link.name, out.kind.name, out.detail, round(self._clock() - start, 3)))            if out.kind is not Kind.PASS:                return out, trail        return Outcome(Kind.REFUSE, "nobody handled it"), traildef permission(r): return Outcome(Kind.PASS if r["role"] == "admin" else Kind.REFUSE, r["role"])def fraud(r): raise TimeoutError("no answer")def coupon(r): raise KeyError("coupon")def accept(r): return Outcome(Kind.DONE, "order 7")for critical in (True, False):    chain = Chain([Link("permission", permission, True), Link("coupon", coupon, False),                   Link("fraud", fraud, critical), Link("accept", accept, True)])    out, trail = chain.handle({"role": "admin"})    print("fraud critical =", critical, "->", out.kind.name, out.detail)    for row in trail:        print("   ", row)
Run it. The fraud service is down. Each handler says in advance what its own failure means.
Edit and run it in your browser

The fraud check does not answer. What happens to the order?

BreaksCatch the error and go on
How
except: pass in the chain.
Limit
The protection is off exactly when somebody attacks it. Nobody notices.
Choose when
Never for protection.
WorksFail the whole request
How
The exception travels up.
Limit
A broken coupon service stops all sales.
Choose when
When every link is essential.
StrongDecide per link, with a time limit
How
Security links fail closed, comfort links fail open. Each remote call has a budget, and broken links are counted.
Limit
Somebody must decide for every link, and review it.
Choose when
Chains with remote calls.

Budget

Time adds up

Deadline of a chain

5 remote links⋅2 s=10 s worst case5 \text{ remote links} \cdot 2\,\text{s} = 10\,\text{s worst case}
Assumed: each link waits up to 2 seconds. A caller who gives up after 3 seconds never sees the answer. Give the whole chain one deadline and hand each link what is left of it.

A deadline that travels

A cap per link and one deadline for all. Stock is not asked, because the order is already refused.

Effects

A refusal after an effect

A link that reserves stock and a later link that refuses leave a reservation behind. Put links with effects last. If that is impossible, give them an undo and run the undos in reverse order. That is a macro of commands, not a chain trick.

Show it

SignalFinds
Trail per request: name, answer, timewhy this one request ended here
Count of takers per handlerhandlers that never take anything: dead or shadowed
Count at the catch-allmissing rules
Broken count per linka protection that fails open every day
The order, logged at starta wiring change nobody reviewed