Chain of responsibility
medium 45 minA 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
| Answer | Meaning | The chain |
|---|---|---|
| PASS | not mine, or fine for me | asks the next |
| DONE | I resolved it | stops, result |
| REFUSE | I know that it must not go on | stops, reason |
| exception | I could not decide | depends: 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)The fraud check does not answer. What happens to the order?
BreaksCatch the error and go on
- How
except: passin 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
A deadline that travels
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
| Signal | Finds |
|---|---|
| Trail per request: name, answer, time | why this one request ended here |
| Count of takers per handler | handlers that never take anything: dead or shadowed |
| Count at the catch-all | missing rules |
| Broken count per link | a protection that fails open every day |
| The order, logged at start | a wiring change nobody reviewed |