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

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

Every link works. All unit tests are green. The bug is the order, and only a test of the order can find it.

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

5!=1208!=40,3205! = 120 \qquad 8! = 40{,}320
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])
Run it. Each link names the links that must run before it. The last call shows a contradiction found at start, not in production.
Edit and run it in your browser

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

The request was valid before and is valid after the change. It fails because it saw half of each.
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))
Run it. One reference is replaced, and a running request keeps the list with which it began.
Edit and run it in your browser

Ways to change a chain

WayReadersCost
Relink objectsmay see half a changecheap and unsafe
Lock around every requestwait for each otherone request at a time
Read and write lockwait only for writersa slow request delays the change
Swap an unchangeable listnever waitold requests finish on the old chain