Chain of responsibility
medium 45 minA request travels past several handlers until one takes it, or until one stops it.
Watch lesson4:36
Order and live changes
Declared order, checks at start, and swapping a chain under load.
The point: order is a requirement. Write it down, check it when the program starts, and change the chain only as a whole.
Failure walk
A password in the log
Two links, one wrong order
With 5 links there are 120 orders, with 8 there are 40,320. Nobody can review them. Each link should state what it needs, and a program should find an order or refuse to start.
Why a list needs rules
Python
from graphlib import TopologicalSorter, CycleErrorAFTER = { "errors": [], "rate_limit": ["errors"], "redact": ["errors"], "log": ["redact"], "auth": ["rate_limit", "log"], "roles": ["auth"],}def order(rules): known = set(rules) for name, needs in rules.items(): missing = [n for n in needs if n not in known] if missing: raise ValueError(f"{name} needs {missing}") return list(TopologicalSorter(rules).static_order())result = order(AFTER)print(result)at = {name: i for i, name in enumerate(result)}assert all(at[n] < at[name] for name, needs in AFTER.items() for n in needs)try: order({**AFTER, "redact": ["errors", "roles"]})except CycleError as e: print("refuse to start:", e.args[1])Live changes
Why set_next at run time is a race
The textbook advantage says that handlers can be added, removed and reordered at run time. With linked objects this takes two writes, and a request can pass between them.
Removing B while a request walks
Python
import threadingclass Chain: def __init__(self, handlers): self._lock = threading.Lock() self._handlers = tuple(handlers) def handle(self, request): snapshot = self._handlers # one read, then never again for h in snapshot: answer = h(request) if answer is not None: return answer raise LookupError(request) def edit(self, change): with self._lock: # writers wait for each other self._handlers = tuple(change(list(self._handlers)))def only(n, name): return lambda r: name if r == n else Nonechain = Chain([only(1, "a"), only(2, "b"), only(3, "c")])errors = []def traffic(): for _ in range(20000): try: chain.handle(3) except LookupError as e: errors.append(e)t = threading.Thread(target=traffic)t.start()for i in range(500): chain.edit(lambda hs: [hs[0], hs[-1]] if len(hs) == 3 else [hs[0], only(2, "b"), hs[-1]])t.join()print("failed requests:", len(errors))Ways to change a chain
| Way | Readers | Cost |
|---|---|---|
| Relink objects | may see half a change | cheap and unsafe |
| Lock around every request | wait for each other | one request at a time |
| Read and write lock | wait only for writers | a slow request delays the change |
| Swap an unchangeable list | never wait | old requests finish on the old chain |